public override void InAASourceFile(AASourceFile node) { namespacePrefix = ""; /*if (node.GetNamespace() != null) * namespacePrefix = node.GetNamespace().Text + "_";*/ }
private AMethodDecl GetIntPointerMethod() { if (GetIntPointerPartMethod != null) { return(GetIntPointerPartMethod); } /* * int GetIntPointerPart(string delegate) * { * return IntToString(GetPointerPart(delegate)); * } */ AASourceFile sourceFile = Util.GetAncestor <AASourceFile>(finalTrans.mainEntry); AALocalDecl delegateFormal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("string"), null), new TIdentifier("delegate"), null); ALocalLvalue delegateRef1 = new ALocalLvalue(new TIdentifier("delegate")); ALvalueExp delegateRef1Exp = new ALvalueExp(delegateRef1); ASimpleInvokeExp getPointerPartInvoke = new ASimpleInvokeExp(new TIdentifier("GetPointerPart"), new ArrayList() { delegateRef1Exp }); ASimpleInvokeExp StringToIntInvoke = new ASimpleInvokeExp(new TIdentifier("StringToInt"), new ArrayList() { getPointerPartInvoke }); GetIntPointerPartMethod = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new ANamedType(new TIdentifier("int"), null), new TIdentifier("GetPointerPart", finalTrans.data.LineCounts[sourceFile] + 1, 1), new ArrayList() { delegateFormal }, new AABlock( new ArrayList() { new AValueReturnStm(new TReturn("return"), StringToIntInvoke) }, new TRBrace("}"))); sourceFile.GetDecl().Add(GetIntPointerPartMethod); data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(sourceFile, GetIntPointerPartMethod)); finalTrans.data.LocalLinks[delegateRef1] = delegateFormal; finalTrans.data.LvalueTypes[delegateRef1] = finalTrans.data.ExpTypes[delegateRef1Exp] = finalTrans.data.ExpTypes[getPointerPartInvoke] = new ANamedType(new TIdentifier("string"), null); finalTrans.data.ExpTypes[StringToIntInvoke] = new ANamedType(new TIdentifier("int"), null); finalTrans.data.SimpleMethodLinks[getPointerPartInvoke] = GetStringPointerMethod(); finalTrans.data.SimpleMethodLinks[StringToIntInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == StringToIntInvoke.GetName().Text); return(GetIntPointerPartMethod); }
public override void OutAASourceFile(AASourceFile node) { if (reqRerun) { reqRerun = false; base.CaseAASourceFile(node); } }
public Error(Token pos, AASourceFile sourceFile, string message, bool warning = false, params TreeNode[] children) { this.pos = new TextPoint(pos.Line - 1, pos.Pos - 1); FileName = sourceFile == null || sourceFile.GetName() == null ? "Library file" : sourceFile.GetName().Text; Message = message; Warning = warning; Text = ToString(); if (children.Length > 0) { Nodes.AddRange(children); } SelectedImageIndex = ImageIndex = warning ? 1 : 0; }
private void AddDepency(AASourceFile currentFile, AASourceFile requiredFile) { //If requiredFile is null, it is a part of the standard library //If it's the same file, no includes are required if (currentFile == requiredFile) { return; } if (dependancies[currentFile].Contains(requiredFile)) { return; } dependancies[currentFile].Add(requiredFile); }
private static void GetReachable(AASourceFile node, Dictionary <AASourceFile, List <AASourceFile> > dependancies, ref List <AASourceFile> reachable) { if (reachable.Contains(node)) { return; } reachable.Add(node); if (node != null) { foreach (AASourceFile file in dependancies[node]) { GetReachable(file, dependancies, ref reachable); } } }
public static void Parse(AAProgram ast, ErrorCollection errors, SharedData data, out string rootFile) { FinalTransformations finalTrans = new FinalTransformations(errors, data); finalTrans.Apply(ast); AASourceFile rootSrcFile = Util.GetAncestor <AASourceFile>(finalTrans.mainEntry); if (rootSrcFile == null) { rootFile = ""; } else { rootFile = rootSrcFile.GetName().Text + ".galaxy"; } }
public override void CaseANamedType(ANamedType node) { AAName name = (AAName)node.GetName(); if (name.GetIdentifier().Count > 2) { return; } if (name.GetIdentifier().Count == 2 && ((TIdentifier)name.GetIdentifier()[0]).Text != "Dialogs") { return; } if (name.GetIdentifier().Count == 1) { bool foundDialogs = false; AASourceFile file = Util.GetAncestor <AASourceFile>(node); foreach (AUsingDecl usingDecl in file.GetUsings()) { if (usingDecl.GetNamespace().Count == 1) { TIdentifier identifer = (TIdentifier)usingDecl.GetNamespace()[0]; if (identifer.Text == "Dialogs") { foundDialogs = true; break; } } } if (!foundDialogs) { ANamespaceDecl ns = Util.GetAncestor <ANamespaceDecl>(node); if (!Util.HasAncestor <ANamespaceDecl>(ns.Parent()) && ns.GetName().Text == "Dialogs") { foundDialogs = true; } } if (!foundDialogs) { return; } } if (((TIdentifier)name.GetIdentifier()[name.GetIdentifier().Count - 1]).Text == oldName) { types.Add((TIdentifier)name.GetIdentifier()[name.GetIdentifier().Count - 1]); } }
private static int CountDecendants(AASourceFile file, Dictionary <AASourceFile, List <AASourceFile> > dependancies, List <AASourceFile> countedFiles) { if (file == null) { return(1); } countedFiles.Add(file); foreach (AASourceFile sourceFile in dependancies[file]) { if (!countedFiles.Contains(sourceFile)) { CountDecendants(sourceFile, dependancies, countedFiles); } } return(countedFiles.Count); }
private static void RemoveCycles(AASourceFile file, Dictionary <AASourceFile, List <AASourceFile> > dependancies, List <AASourceFile> path) { if (file == null) { return; } for (int i = 0; i < dependancies[file].Count; i++) { AASourceFile nextFile = dependancies[file][i]; if (path.Contains(nextFile)) { dependancies[file].RemoveAt(i--); } else { path.Add(nextFile); RemoveCycles(nextFile, dependancies, path); path.Remove(nextFile); } } }
public override void CaseAASourceFile(AASourceFile node) { string name = outputDir.FullName + "\\"; /* if (Options.Compiler.OneOutputFile) * name += "MapScript"; * else*/ name += node.GetName().Text; name += ".galaxy"; FileInfo file = new FileInfo(name); if (!file.Directory.Exists) { file.Directory.Create(); } stream = new StreamWriter(file.Open(FileMode.Create)); foreach (PDecl decl in node.GetDecl()) { decl.Apply(this); } Write("", true); stream.Close(); }
public override void CaseANamespaceDecl(ANamespaceDecl node) { string lastNamespace = currentNamespace; currentNamespace += node.GetName().Text + "_"; base.CaseANamespaceDecl(node); currentNamespace = lastNamespace; while (node.GetDecl().Count > 0) { PDecl decl = (PDecl)node.GetDecl()[0]; node.RemoveChild(decl); if (node.Parent() is ANamespaceDecl) { ANamespaceDecl parent = (ANamespaceDecl)node.Parent(); parent.GetDecl().Insert(parent.GetDecl().IndexOf(node), decl); } else { AASourceFile parent = (AASourceFile)node.Parent(); parent.GetDecl().Insert(parent.GetDecl().IndexOf(node), decl); } } node.Parent().RemoveChild(node); }
public override void CaseAASourceFile(AASourceFile node) { writer.WriteLine(node.GetName().Text + ":"); base.CaseAASourceFile(node); }
private void Apply(AAProgram ast) { int stage = 1; int totalStages = 31; List <ANamedType> deleteUs = new List <ANamedType>(); foreach (KeyValuePair <ANamedType, AStructDecl> pair in data.StructTypeLinks) { ANamedType type = pair.Key; AStructDecl str = pair.Value; if (data.Enums.ContainsKey(str)) { type.SetName(new AAName(new ArrayList() { new TIdentifier(data.Enums[str] ? "int" : "byte") })); deleteUs.Add(type); } } foreach (ANamedType type in deleteUs) { data.StructTypeLinks.Remove(type); } if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing namespaces"); } stage++; ast.Apply(new RemoveNamespaces()); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Moving static members out"); } stage++; ast.Apply(new StaticStructMembers(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing constant variables"); } stage++; ast.Apply(new RemoveConstants(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Locating main entry"); } stage++; ast.Apply(new MainEntryFinder(this)); if (mainEntry == null) { //errors.Add(new ErrorCollection.Error("No entry point found (void InitMap(){...})", true)); //Generate main entry AASourceFile file = ast.GetSourceFiles().Cast <AASourceFile>().FirstOrDefault( sourceFile => !Util.GetAncestor <AASourceFile>(sourceFile).GetName().Text.Contains("\\")); if (file == null) { //Make default sourcefile file = new AASourceFile(); file.SetName(new TIdentifier("MapScript")); ast.GetSourceFiles().Add(file); data.LineCounts[file] = 1; } mainEntry = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new AVoidType(new TVoid("void")), new TIdentifier("InitMap"), new ArrayList(), new AABlock()); file.GetDecl().Add(mainEntry); data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, mainEntry)); } else if (Util.GetAncestor <AASourceFile>(mainEntry).GetName().Text.Contains("\\")) { errors.Add(new ErrorCollection.Error(mainEntry.GetName(), Util.GetAncestor <AASourceFile>(mainEntry), "The source file containing the main entry function should be placed in root folder to be able to overwrite MapScript.galaxy", true)); } ((AABlock)mainEntry.GetBlock()).GetStatements().Insert(0, mainEntryFieldInitBlock); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Setting default values for struct variables"); } stage++; ast.Apply(new StructInitializer(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming expression ifs"); } stage++; ast.Apply(new TransformExpressionIfs(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Renaming unicode identifiers and strings"); } stage++; ast.Apply(new RenameUnicode(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming properties to methods (Phase 1)"); } stage++; TransformProperties.Phase1.Parse(this); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing dead code"); } stage++; ast.Apply(new RemoveDeadCode()); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Moving methods members out of structs"); } stage++; ast.Apply(new TransformMethodDecls(this)); if (errors.HasErrors) { return; } if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Invoking initializers"); } stage++; MakeInitializerInvokes(); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Moving assignments out to their own statement"); } stage++; ast.Apply(new AssignFixup(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming properties to methods (Phase 2)"); } stage++; TransformProperties.Phase2.Parse(this); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Fixing invokes (sync/assync)"); } stage++; if (data.Invokes.Count > 0) { Invokes.Parse(this); } if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing empty structs"); } stage++; ast.Apply(new RemoveEmptyStructs(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Making delegates"); } stage++; ast.Apply(new Delegates(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming inline methods (Run 1)"); } stage++; //ast.Apply(new AddUnneededRef(data)); ast.Apply(new FixInlineMethods(this, false)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing unneeded ref parameters"); } stage++; ast.Apply(new RemoveUnnededRef(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Expanding struct equality tests"); } stage++; ast.Apply(new SplitStructTests(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming pointers"); } stage++; new Pointers(data).Parse(ast); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming inline methods (Run 2)"); } stage++; ast.Apply(new FixInlineMethods(this, true)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Splitting local structs into primitives"); } stage++; //Split local struct into primitives, to make optimizations easier ast.Apply(new StructSplitter(data)); //ast.Apply(new BulkCopyFixup(this)); //BulkCopyFixup.Parse(ast, this); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removnig redundant assignments"); } stage++; //Remove stupid assignments (assignments to a variable where that variable is not used before its next assignment ast.Apply(new RemoveUnusedVariables(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Folding constants"); } stage++; ast.Apply(new ConstantFolding(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Optimizing"); } stage++; //Assign fixup was here //Dahm grafiti painters //ast.Apply(new LivenessAnalysis(this)); ast.Apply(new Optimizations.OptimizePhase(this, "Transforming code (" + (stage - 1) + " / " + totalStages + "): Optimizing")); ast.Apply(new FixByteArrayIndexes(data)); if (Options.Compiler.MakeShortNames) { if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Making short names"); } stage++; ast.Apply(new MakeShortNames(this)); } else { if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Making unique names"); } stage++; //MakeUniqueNames.Parse(ast, this); ast.Apply(new MakeUniqueNamesV2()); } if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Renaming references to variables whose names have changed"); } stage++; //Remove uneeded blocks and check that names fit the decls ast.Apply(new RenameRefferences(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Obfuscating strings"); } stage++; //Obfuscate strings ast.Apply(new ObfuscateStrings(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Mergeing methods if they are the same"); } stage++; MergeSameMethods.Parse(this); if (data.AllowPrintouts) { Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Generating includes (merging to one file if selected)"); } stage++; //Insert includes, and move methods, structs and fields around so they are visible FixIncludes.Apply(ast, this); if (Options.Compiler.OneOutputFile) { ((AASourceFile)mainEntry.Parent()).SetName(new TIdentifier("MapScript")); } }
private void MakeInitializerInvokes() { AABlock block = (AABlock)mainEntry.GetBlock(); AASourceFile file = Util.GetAncestor <AASourceFile>(mainEntry); AMethodDecl invokeMethod; /* Add * void Invoke(string methodName) * { * trigger initTrigger = TriggerCreate(methodName); * TriggerExecute(initTrigger, false, true); * TriggerDestroy(initTrigger); * } */ { //void Invoke(string methodName) AALocalDecl parameter = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("string"), null), new TIdentifier("methodName"), null); AABlock methodBody = new AABlock(); invokeMethod = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new AVoidType(new TVoid("void")), new TIdentifier("Invoke"), new ArrayList() { parameter }, methodBody); //trigger initTrigger = TriggerCreate(methodName); ALocalLvalue parameterLvalue = new ALocalLvalue(new TIdentifier("methodName")); data.LocalLinks[parameterLvalue] = parameter; ALvalueExp parameterLvalueExp = new ALvalueExp(parameterLvalue); data.LvalueTypes[parameterLvalue] = data.ExpTypes[parameterLvalueExp] = parameter.GetType(); ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("TriggerCreate"), new ArrayList() { parameterLvalueExp }); data.ExpTypes[invoke] = new ANamedType(new TIdentifier("trigger"), null); foreach (AMethodDecl methodDecl in data.Libraries.Methods) { if (methodDecl.GetName().Text == "TriggerCreate") { data.SimpleMethodLinks[invoke] = methodDecl; break; } } AALocalDecl initTriggerDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("trigger"), null), new TIdentifier("initTrigger"), invoke); methodBody.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), initTriggerDecl)); //TriggerExecute(initTrigger, false, true); ALocalLvalue initTriggerLvalue = new ALocalLvalue(new TIdentifier("initTrigger")); data.LocalLinks[initTriggerLvalue] = initTriggerDecl; ALvalueExp initTriggerLvalueExp = new ALvalueExp(initTriggerLvalue); data.LvalueTypes[initTriggerLvalue] = data.ExpTypes[initTriggerLvalueExp] = initTriggerDecl.GetType(); ABooleanConstExp falseBool = new ABooleanConstExp(new AFalseBool()); ABooleanConstExp trueBool = new ABooleanConstExp(new ATrueBool()); data.ExpTypes[falseBool] = data.ExpTypes[trueBool] = new ANamedType(new TIdentifier("bool"), null); invoke = new ASimpleInvokeExp(new TIdentifier("TriggerExecute"), new ArrayList() { initTriggerLvalueExp, falseBool, trueBool }); data.ExpTypes[invoke] = new AVoidType(new TVoid("void")); foreach (AMethodDecl methodDecl in data.Libraries.Methods) { if (methodDecl.GetName().Text == "TriggerExecute") { data.SimpleMethodLinks[invoke] = methodDecl; break; } } methodBody.GetStatements().Add(new AExpStm(new TSemicolon(";"), invoke)); //TriggerDestroy(initTrigger); initTriggerLvalue = new ALocalLvalue(new TIdentifier("initTrigger")); data.LocalLinks[initTriggerLvalue] = initTriggerDecl; initTriggerLvalueExp = new ALvalueExp(initTriggerLvalue); data.LvalueTypes[initTriggerLvalue] = data.ExpTypes[initTriggerLvalueExp] = initTriggerDecl.GetType(); invoke = new ASimpleInvokeExp(new TIdentifier("TriggerDestroy"), new ArrayList() { initTriggerLvalueExp }); data.ExpTypes[invoke] = new AVoidType(new TVoid("void")); foreach (AMethodDecl methodDecl in data.Libraries.Methods) { if (methodDecl.GetName().Text == "TriggerDestroy") { data.SimpleMethodLinks[invoke] = methodDecl; break; } } methodBody.GetStatements().Add(new AExpStm(new TSemicolon(";"), invoke)); file.GetDecl().Add(invokeMethod); } for (int i = data.InitializerMethods.Count - 1; i >= 0; i--) { AMethodDecl method = data.InitializerMethods[i]; //Turn method into a trigger method.SetReturnType(new ANamedType(new TIdentifier("bool"), null)); method.GetFormals().Add(new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("bool"), null), new TIdentifier("testConds"), null)); method.GetFormals().Add(new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("bool"), null), new TIdentifier("runActions"), null)); method.SetTrigger(new TTrigger("trigger")); ((AABlock)method.GetBlock()).GetStatements().Add(new AVoidReturnStm(new TReturn("return"))); TriggerConvertReturn returnConverter = new TriggerConvertReturn(data); method.Apply(returnConverter); data.TriggerDeclarations[method] = new List <TStringLiteral>(); //Add Invoke(<name>); to main entry TStringLiteral literal = new TStringLiteral(method.GetName().Text); data.TriggerDeclarations[method].Add(literal); AStringConstExp stringConst = new AStringConstExp(literal); data.ExpTypes[stringConst] = new ANamedType(new TIdentifier("string"), null); ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("Invoke"), new ArrayList() { stringConst }); data.SimpleMethodLinks[invoke] = invokeMethod; data.ExpTypes[invoke] = invokeMethod.GetReturnType(); block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), invoke)); //ASyncInvokeExp syncInvokeExp = new ASyncInvokeExp(new TSyncInvoke("Invoke"), new AAmbiguousNameLvalue(new ASimpleName(new TIdentifier(method.GetName().Text))), new ArrayList()); //data.Invokes.Add(method, new List<InvokeStm>(){new InvokeStm(syncInvokeExp)}); //data.ExpTypes[syncInvokeExp] = new AVoidType(new TVoid("void")); //block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), syncInvokeExp)); } for (int i = data.InvokeOnIniti.Count - 1; i >= 0; i--) { AMethodDecl method = data.InvokeOnIniti[i]; //Turn method into a trigger method.SetReturnType(new ANamedType(new TIdentifier("bool"), null)); method.GetFormals().Add(new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("bool"), null), new TIdentifier("testConds"), null)); method.GetFormals().Add(new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("bool"), null), new TIdentifier("runActions"), null)); method.SetTrigger(new TTrigger("trigger")); ((AABlock)method.GetBlock()).GetStatements().Add(new AVoidReturnStm(new TReturn("return"))); TriggerConvertReturn returnConverter = new TriggerConvertReturn(data); method.Apply(returnConverter); data.TriggerDeclarations[method] = new List <TStringLiteral>(); //Add Invoke(<name>); to main entry TStringLiteral literal = new TStringLiteral(method.GetName().Text); data.TriggerDeclarations[method].Add(literal); AStringConstExp stringConst = new AStringConstExp(literal); data.ExpTypes[stringConst] = new ANamedType(new TIdentifier("string"), null); ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("Invoke"), new ArrayList() { stringConst }); data.SimpleMethodLinks[invoke] = invokeMethod; data.ExpTypes[invoke] = invokeMethod.GetReturnType(); block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), invoke)); /* * ASyncInvokeExp syncInvokeExp = new ASyncInvokeExp(new TSyncInvoke("Invoke"), new AAmbiguousNameLvalue(new ASimpleName(new TIdentifier(method.GetName().Text))), new ArrayList()); * data.Invokes.Add(method, new List<InvokeStm>() { new InvokeStm(syncInvokeExp) }); * data.ExpTypes[syncInvokeExp] = new AVoidType(new TVoid("void")); * * block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), syncInvokeExp));*/ } for (int i = data.FieldsToInitInMapInit.Count - 1; i >= 0; i--) { AFieldDecl field = data.FieldsToInitInMapInit[i]; if (field.GetInit() == null) { continue; } AFieldLvalue lvalue = new AFieldLvalue(new TIdentifier(field.GetName().Text)); AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), lvalue, field.GetInit()); data.ExpTypes[assignment] = data.LvalueTypes[lvalue] = field.GetType(); data.FieldLinks[lvalue] = field; block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), assignment)); } block.RemoveChild(mainEntryFieldInitBlock); block.GetStatements().Insert(0, mainEntryFieldInitBlock); }
public override void InAASourceFile(AASourceFile node) { dependancies.Add(node, new List <AASourceFile>()); }
//private List<ErrorCollection.Error> multipleEntryCandidates = new List<ErrorCollection.Error>(); public override void CaseAMethodDecl(AMethodDecl node) { //Done in a previous iteration /*if (node.GetName().Text == "InitMap" && node.GetFormals().Count == 0) * { * if (finalTrans.multipleMainEntries) * { * multipleEntryCandidates.Add(new ErrorCollection.Error(node.GetName(), Util.GetAncestor<AASourceFile>(node.GetName()), "Candidate")); * } * else if (finalTrans.mainEntry != null) * { * multipleEntryCandidates.Add(new ErrorCollection.Error(finalTrans.mainEntry.GetName(), Util.GetAncestor<AASourceFile>(finalTrans.mainEntry.GetName()), "Candidate")); * multipleEntryCandidates.Add(new ErrorCollection.Error(node.GetName(), Util.GetAncestor<AASourceFile>(node.GetName()), "Candidate")); * //finalTrans.errors.Add(new ErrorCollection.Error(node.GetName(), Util.GetAncestor<AASourceFile>(node), "Found multiple candidates for a main entry", true)); * finalTrans.multipleMainEntries = true; * finalTrans.mainEntry = null; * } * else * finalTrans.mainEntry = node; * }*/ AStructDecl str = Util.GetAncestor <AStructDecl>(node); if (str != null) { if (node.GetStatic() == null) { structMethods.Add(node); } //Move the method outside the struct str.RemoveChild(node.Parent()); AASourceFile file = (AASourceFile)str.Parent(); int i = file.GetDecl().IndexOf(str); file.GetDecl().Insert(i /* + 1*/, node); node.GetName().Text = GetUniqueStructMethodName(str.GetName().Text + "_" + node.GetName().Text); if (node.GetStatic() == null) { //Add the struct as a parameter PType structType = new ANamedType(new TIdentifier(str.GetName().Text), null); finalTrans.data.StructTypeLinks[(ANamedType)structType] = str; if (str.GetClassToken() != null) { structType = new APointerType(new TStar("*"), structType); } structFormal = new AALocalDecl(new APublicVisibilityModifier(), null, str.GetClassToken() == null ? new TRef("ref") : null, null, null, structType, new TIdentifier("currentStruct", node.GetName().Line, node.GetName().Pos), null); node.GetFormals().Add(structFormal); data.Locals[(AABlock)node.GetBlock()].Add(structFormal); } else { node.SetStatic(null); } finalTrans.data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, node)); if (node.GetStatic() == null) { OldParentStruct[node] = str; } //Fix refferences to other struct stuff); base.CaseAMethodDecl(node); //Will visit later, since it's added after the struct //base.CaseAMethodDecl(node); //if (str.GetLocals().Count == 0) // str.Parent().RemoveChild(str); return; } AEnrichmentDecl enrichment = Util.GetAncestor <AEnrichmentDecl>(node); if (enrichment != null) { if (node.GetStatic() == null) { structMethods.Add(node); } //Move the method outside the struct enrichment.RemoveChild(node); AASourceFile file = (AASourceFile)enrichment.Parent(); int i = file.GetDecl().IndexOf(enrichment); file.GetDecl().Insert(i /* + 1*/, node); node.GetName().Text = GetUniqueStructMethodName(Util.TypeToIdentifierString(enrichment.GetType()) + "_" + node.GetName().Text); if (node.GetStatic() == null) { //Add the struct as a parameter PType structType = Util.MakeClone(enrichment.GetType(), finalTrans.data); structFormal = new AALocalDecl(new APublicVisibilityModifier(), null, new TRef("ref"), null, null, structType, new TIdentifier("currentEnrichment", node.GetName().Line, node.GetName().Pos), null); node.GetFormals().Add(structFormal); } finalTrans.data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, node)); //Fix refferences to other struct stuff); base.CaseAMethodDecl(node); //Will visit later, since it's added after the struct //base.CaseAMethodDecl(node); //if (str.GetLocals().Count == 0) // str.Parent().RemoveChild(str); return; } //Build a list of overloads List <AMethodDecl> overloads = new List <AMethodDecl>(); List <string> prefixMatches = new List <string>(); foreach (SharedData.DeclItem <AMethodDecl> declItem in finalTrans.data.Methods) { if (!Util.IsSameNamespace(declItem.Decl, node)) { continue; } if (declItem.Decl.GetName().Text == node.GetName().Text) { overloads.Add(declItem.Decl); } if (declItem.Decl.GetName().Text.StartsWith(node.GetName().Text + "O")) { prefixMatches.Add(declItem.Decl.GetName().Text); } } foreach (AMethodDecl method in finalTrans.data.Libraries.Methods) { if (method.GetBlock() != null || method.GetNative() != null) { if (method.GetName().Text == node.GetName().Text) { overloads.Add(method); } if (method.GetName().Text.StartsWith(node.GetName().Text + "O")) { prefixMatches.Add(method.GetName().Text); } } } //Add fields foreach (SharedData.DeclItem <AFieldDecl> declItem in finalTrans.data.Fields) { if (declItem.Decl.GetName().Text.StartsWith(node.GetName().Text + "O")) { prefixMatches.Add(declItem.Decl.GetName().Text); } } foreach (AFieldDecl field in finalTrans.data.Libraries.Fields) { if (field.GetName().Text.StartsWith(node.GetName().Text + "O")) { prefixMatches.Add(field.GetName().Text); } } //Dont want to hit another method by appending O# string postfix = ""; while (true) { postfix += "O"; if (prefixMatches.Any(text => text.StartsWith(node.GetName().Text + postfix))) { continue; } break; } if (overloads.Count > 1) { int i = 0; foreach (AMethodDecl method in overloads) { if (node == finalTrans.mainEntry || (node.GetTrigger() != null && finalTrans.data.HasUnknownTrigger)) { continue; } i++; method.GetName().Text += postfix + i; } } if (node != finalTrans.mainEntry && (node.GetTrigger() == null || !finalTrans.data.HasUnknownTrigger)) { node.GetName().Text = namespacePrefix + node.GetName().Text; } base.CaseAMethodDecl(node); }
private AMethodDecl GetMethodMethod() { if (GetMethodPartMethod != null) { return(GetMethodPartMethod); } /* * string GetMethodPart(string delegate) * { * int i = StringFind(delegate, ":", false); * if (i == -1) * { * return delegate; * } * return StringSub(delegate, 1, i - 1); * } */ AASourceFile sourceFile = Util.GetAncestor <AASourceFile>(finalTrans.mainEntry); AALocalDecl delegateFormal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("string"), null), new TIdentifier("delegate"), null); ALocalLvalue delegateRef1 = new ALocalLvalue(new TIdentifier("delegate")); ALocalLvalue delegateRef2 = new ALocalLvalue(new TIdentifier("delegate")); ALocalLvalue delegateRef3 = new ALocalLvalue(new TIdentifier("delegate")); ALvalueExp delegateRef1Exp = new ALvalueExp(delegateRef1); ALvalueExp delegateRef2Exp = new ALvalueExp(delegateRef2); ALvalueExp delegateRef3Exp = new ALvalueExp(delegateRef3); AStringConstExp stringConst = new AStringConstExp(new TStringLiteral("\":\"")); ABooleanConstExp booleanConst = new ABooleanConstExp(new AFalseBool()); AIntConstExp intConst1 = new AIntConstExp(new TIntegerLiteral("-1")); AIntConstExp intConst2 = new AIntConstExp(new TIntegerLiteral("1")); AIntConstExp intConst3 = new AIntConstExp(new TIntegerLiteral("1")); ASimpleInvokeExp stringFindInvoke = new ASimpleInvokeExp(new TIdentifier("StringFind"), new ArrayList() { delegateRef1Exp, stringConst, booleanConst }); AALocalDecl iDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("int"), null), new TIdentifier("i"), stringFindInvoke); ALocalLvalue iRef1 = new ALocalLvalue(new TIdentifier("i")); ALocalLvalue iRef2 = new ALocalLvalue(new TIdentifier("i")); ALvalueExp iRef1Exp = new ALvalueExp(iRef1); ALvalueExp iRef2Exp = new ALvalueExp(iRef2); ABinopExp binop1 = new ABinopExp(iRef1Exp, new AEqBinop(new TEq("==")), intConst1); AIfThenStm ifThen = new AIfThenStm(new TLParen("("), binop1, new ABlockStm(new TLBrace("{"), new AABlock( new ArrayList() { new AValueReturnStm(new TReturn("return"), delegateRef2Exp) }, new TRBrace("}")))); ABinopExp binop2 = new ABinopExp(iRef2Exp, new AMinusBinop(new TMinus("-")), intConst3); ASimpleInvokeExp stringSubInvoke = new ASimpleInvokeExp(new TIdentifier("StringSub"), new ArrayList() { delegateRef3Exp, intConst2, binop2 }); GetMethodPartMethod = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new ANamedType(new TIdentifier("string"), null), new TIdentifier("GetMethodPart", finalTrans.data.LineCounts[sourceFile] + 1, 1), new ArrayList() { delegateFormal }, new AABlock( new ArrayList() { new ALocalDeclStm(new TSemicolon(";"), iDecl), ifThen, new AValueReturnStm(new TReturn("return"), stringSubInvoke) }, new TRBrace("}"))); sourceFile.GetDecl().Add(GetMethodPartMethod); finalTrans.data.LocalLinks[delegateRef1] = finalTrans.data.LocalLinks[delegateRef2] = finalTrans.data.LocalLinks[delegateRef3] = delegateFormal; finalTrans.data.LocalLinks[iRef1] = finalTrans.data.LocalLinks[iRef2] = iDecl; finalTrans.data.LvalueTypes[delegateRef1] = finalTrans.data.LvalueTypes[delegateRef2] = finalTrans.data.LvalueTypes[delegateRef3] = finalTrans.data.ExpTypes[delegateRef1Exp] = finalTrans.data.ExpTypes[delegateRef2Exp] = finalTrans.data.ExpTypes[delegateRef3Exp] = finalTrans.data.ExpTypes[stringConst] = finalTrans.data.ExpTypes[stringSubInvoke] = new ANamedType(new TIdentifier("string"), null); finalTrans.data.LvalueTypes[iRef1] = finalTrans.data.LvalueTypes[iRef2] = finalTrans.data.ExpTypes[iRef1Exp] = finalTrans.data.ExpTypes[iRef2Exp] = finalTrans.data.ExpTypes[stringFindInvoke] = finalTrans.data.ExpTypes[intConst1] = finalTrans.data.ExpTypes[intConst2] = finalTrans.data.ExpTypes[intConst3] = finalTrans.data.ExpTypes[binop2] = new ANamedType(new TIdentifier("int"), null); finalTrans.data.ExpTypes[booleanConst] = finalTrans.data.ExpTypes[binop1] = new ANamedType(new TIdentifier("bool"), null); finalTrans.data.SimpleMethodLinks[stringFindInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringFindInvoke.GetName().Text); finalTrans.data.SimpleMethodLinks[stringSubInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringSubInvoke.GetName().Text); return(GetMethodPartMethod); }
private AMethodDecl GetStringPointerMethod() { if (GetStringPointerPartMethod != null) { return(GetStringPointerPartMethod); } /* * string GetPointerPart(string delegate) * { * return StringSub(delegate, StringFind(delegate, ":", false) + 1, StringLength(delegate)); * } */ AASourceFile sourceFile = Util.GetAncestor <AASourceFile>(finalTrans.mainEntry); AALocalDecl delegateFormal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("string"), null), new TIdentifier("delegate"), null); ALocalLvalue delegateRef1 = new ALocalLvalue(new TIdentifier("delegate")); ALocalLvalue delegateRef2 = new ALocalLvalue(new TIdentifier("delegate")); ALocalLvalue delegateRef3 = new ALocalLvalue(new TIdentifier("delegate")); ALvalueExp delegateRef1Exp = new ALvalueExp(delegateRef1); ALvalueExp delegateRef2Exp = new ALvalueExp(delegateRef2); ALvalueExp delegateRef3Exp = new ALvalueExp(delegateRef3); AStringConstExp stringConst = new AStringConstExp(new TStringLiteral("\":\"")); ABooleanConstExp booleanConst = new ABooleanConstExp(new AFalseBool()); ASimpleInvokeExp stringFindInvoke = new ASimpleInvokeExp(new TIdentifier("StringFind"), new ArrayList() { delegateRef2Exp, stringConst, booleanConst }); AIntConstExp intConst = new AIntConstExp(new TIntegerLiteral("1")); ABinopExp binop = new ABinopExp(stringFindInvoke, new APlusBinop(new TPlus("+")), intConst); ASimpleInvokeExp stringLengthInvoke = new ASimpleInvokeExp(new TIdentifier("StringLength"), new ArrayList() { delegateRef3Exp }); ASimpleInvokeExp stringSubInvoke = new ASimpleInvokeExp(new TIdentifier("StringSub"), new ArrayList() { delegateRef1Exp, binop, stringLengthInvoke }); GetStringPointerPartMethod = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new ANamedType(new TIdentifier("string"), null), new TIdentifier("GetPointerPart", finalTrans.data.LineCounts[sourceFile] + 1, 1), new ArrayList() { delegateFormal }, new AABlock( new ArrayList() { new AValueReturnStm(new TReturn("return"), stringSubInvoke) }, new TRBrace("}"))); sourceFile.GetDecl().Add(GetStringPointerPartMethod); data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(sourceFile, GetStringPointerPartMethod)); finalTrans.data.LocalLinks[delegateRef1] = finalTrans.data.LocalLinks[delegateRef2] = finalTrans.data.LocalLinks[delegateRef3] = delegateFormal; finalTrans.data.LvalueTypes[delegateRef1] = finalTrans.data.LvalueTypes[delegateRef2] = finalTrans.data.LvalueTypes[delegateRef3] = finalTrans.data.ExpTypes[delegateRef1Exp] = finalTrans.data.ExpTypes[delegateRef2Exp] = finalTrans.data.ExpTypes[delegateRef3Exp] = finalTrans.data.ExpTypes[stringConst] = finalTrans.data.ExpTypes[stringSubInvoke] = new ANamedType(new TIdentifier("string"), null); finalTrans.data.ExpTypes[booleanConst] = new ANamedType(new TIdentifier("bool"), null); finalTrans.data.ExpTypes[intConst] = finalTrans.data.ExpTypes[binop] = finalTrans.data.ExpTypes[stringFindInvoke] = finalTrans.data.ExpTypes[stringLengthInvoke] = new ANamedType(new TIdentifier("int"), null); finalTrans.data.SimpleMethodLinks[stringFindInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringFindInvoke.GetName().Text); finalTrans.data.SimpleMethodLinks[stringLengthInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringLengthInvoke.GetName().Text); finalTrans.data.SimpleMethodLinks[stringSubInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringSubInvoke.GetName().Text); return(GetStringPointerPartMethod); }
/* * Apply before Transform method decls, and remove dead code * * Convert properties to methods */ public static void Parse(FinalTransformations finalTrans) { OldEnrichmentParents.Clear(); OldStructParents.Clear(); SharedData data = finalTrans.data; foreach (APropertyDecl property in data.Properties.Select(p => p.Decl)) { AASourceFile parent = (AASourceFile)property.Parent(); if (property.GetGetter() != null) { AMethodDecl getter = new AMethodDecl(new APublicVisibilityModifier(), null, property.GetStatic() == null ? null : (TStatic)property.GetStatic().Clone(), null, null, null, Util.MakeClone(property.GetType(), data), new TIdentifier("Get" + property.GetName().Text, property.GetName().Line, 0), new ArrayList(), property.GetGetter()); data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(parent, getter)); parent.GetDecl().Insert(parent.GetDecl().IndexOf(property), getter); data.Getters[property] = getter; } if (property.GetSetter() != null) { AALocalDecl valueLocal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(property.GetType(), data), new TIdentifier("value"), null); AMethodDecl setter = new AMethodDecl(new APublicVisibilityModifier(), null, property.GetStatic() == null ? null : (TStatic)property.GetStatic().Clone(), null, null, null, new AVoidType(new TVoid("void")), new TIdentifier("Set" + property.GetName().Text, property.GetName().Line, 0), new ArrayList() { valueLocal }, property.GetSetter()); data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(parent, setter)); parent.GetDecl().Insert(parent.GetDecl().IndexOf(property), setter); setter.GetBlock().Apply(new FixValue(valueLocal, data)); data.Setters[property] = setter; } property.Parent().RemoveChild(property); } foreach (AStructDecl structDecl in data.Structs.Select(s => s.Decl)) { foreach (APropertyDecl property in data.StructProperties[structDecl]) { //Due to enheritance, they might not be in same struct if (structDecl != Util.GetAncestor <AStructDecl>(property)) { continue; } OldStructParents[property] = structDecl; if (property.GetGetter() != null) { AALocalDecl indexLocal = null; string methodName = "Get" + property.GetName().Text; if (property.GetName().Text == "") { methodName = "GetThis"; indexLocal = data.ArrayPropertyLocals[property][0]; } AMethodDecl getter = new AMethodDecl(new APublicVisibilityModifier(), null, property.GetStatic() == null ? null : (TStatic)property.GetStatic().Clone(), null, null, null, Util.MakeClone(property.GetType(), data), new TIdentifier(methodName, property.GetName().Line, 0), new ArrayList(), property.GetGetter()); if (indexLocal != null) { indexLocal.Parent().Parent().RemoveChild(indexLocal.Parent()); //data.Locals[(AABlock) getter.GetBlock()].Remove(indexLocal); getter.GetFormals().Insert(0, indexLocal); } data.StructMethods[structDecl].Add(getter); structDecl.GetLocals().Insert(structDecl.GetLocals().IndexOf(property.Parent()), new ADeclLocalDecl(getter)); data.Getters[property] = getter; } if (property.GetSetter() != null) { AALocalDecl indexLocal = null; string methodName = "Set" + property.GetName().Text; if (property.GetName().Text == "") { methodName = "SetThis"; indexLocal = data.ArrayPropertyLocals[property][data.ArrayPropertyLocals[property].Length - 1]; } AALocalDecl valueLocal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(property.GetType(), data), new TIdentifier("value"), null); AMethodDecl setter = new AMethodDecl(new APublicVisibilityModifier(), null, property.GetStatic() == null ? null : (TStatic)property.GetStatic().Clone(), null, null, null, new AVoidType(new TVoid("void")), new TIdentifier(methodName, property.GetName().Line, 0), new ArrayList() { valueLocal }, property.GetSetter()); if (indexLocal != null) { indexLocal.Parent().Parent().RemoveChild(indexLocal.Parent()); //data.Locals[(AABlock)setter.GetBlock()].Remove(indexLocal); setter.GetFormals().Insert(0, indexLocal); } data.StructMethods[structDecl].Add(setter); structDecl.GetLocals().Insert(structDecl.GetLocals().IndexOf(property.Parent()), new ADeclLocalDecl(setter)); setter.GetBlock().Apply(new FixValue(valueLocal, data)); data.Setters[property] = setter; } structDecl.RemoveChild(property.Parent()); } } foreach (AEnrichmentDecl enrichment in data.Enrichments) { for (int i = 0; i < enrichment.GetDecl().Count; i++) { if (!(enrichment.GetDecl()[i] is APropertyDecl)) { continue; } APropertyDecl property = (APropertyDecl)enrichment.GetDecl()[i]; OldEnrichmentParents[property] = enrichment; if (property.GetGetter() != null) { AALocalDecl indexLocal = null; string methodName = "Get" + property.GetName().Text; if (property.GetName().Text == "") { methodName = "GetThis"; indexLocal = data.ArrayPropertyLocals[property][0]; } AMethodDecl getter = new AMethodDecl(new APublicVisibilityModifier(), null, property.GetStatic() == null ? null : (TStatic)property.GetStatic().Clone(), null, null, null, Util.MakeClone(property.GetType(), data), new TIdentifier(methodName, property.GetName().Line, 0), new ArrayList(), property.GetGetter()); if (indexLocal != null) { indexLocal.Parent().Parent().RemoveChild(indexLocal.Parent()); //data.Locals[(AABlock)getter.GetBlock()].Remove(indexLocal); getter.GetFormals().Insert(0, indexLocal); } enrichment.GetDecl().Insert(enrichment.GetDecl().IndexOf(property), getter); data.Getters[property] = getter; } if (property.GetSetter() != null) { AALocalDecl indexLocal = null; string methodName = "Set" + property.GetName().Text; if (property.GetName().Text == "") { methodName = "SetThis"; indexLocal = data.ArrayPropertyLocals[property][data.ArrayPropertyLocals[property].Length - 1]; } AALocalDecl valueLocal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(property.GetType(), data), new TIdentifier("value"), null); AMethodDecl setter = new AMethodDecl(new APublicVisibilityModifier(), null, property.GetStatic() == null ? null : (TStatic)property.GetStatic().Clone(), null, null, null, new AVoidType(new TVoid("void")), new TIdentifier(methodName, property.GetName().Line, 0), new ArrayList() { valueLocal }, property.GetSetter()); if (indexLocal != null) { indexLocal.Parent().Parent().RemoveChild(indexLocal.Parent()); data.Locals[(AABlock)setter.GetBlock()].Remove(indexLocal); setter.GetFormals().Insert(0, indexLocal); } enrichment.GetDecl().Insert(enrichment.GetDecl().IndexOf(property), setter); setter.GetBlock().Apply(new FixValue(valueLocal, data)); data.Setters[property] = setter; } enrichment.RemoveChild(property); } } }
private static IncludeItem MakeTree(AASourceFile node, Dictionary <AASourceFile, List <AASourceFile> > dependancies, List <Item> allItems, IncludeItem mainFile) { IncludeItem includeItem = new IncludeItem(node, allItems.Count, null, new List <Item>()); //Ensure that each include is only included one place IncludeItem item2 = includeItem; bool removed = false; for (int i = 0; i < allItems.Count; i++) { IncludeItem item1 = (IncludeItem)allItems[i]; if (item1.Current == item2.Current) { List <Item> path1 = item1.Path; List <Item> path2 = item2.Path; for (int k = 0; k < Math.Min(path1.Count, path2.Count); k++) { if (path1[k] != path2[k]) { int insertAt; IncludeItem insertIn; if (k != 0) { int index1 = path1[k - 1].Children.IndexOf(path1[k]); int index2 = path2[k - 1].Children.IndexOf(path2[k]); if (index2 == -1) { index2 = path2[k - 1].Children.Count; } insertAt = Math.Min(index1, index2); insertIn = (IncludeItem)path1[k - 1]; } else { if (path1[0] == mainFile) { int index1 = mainFile.Children.IndexOf(path1[1]); if (path2[0] == mainFile) { int index2 = mainFile.Children.IndexOf(path2[1]); if (index2 == -1) { index2 = mainFile.Children.Count; if (path1.Count == 2) { index2--;//Since item1 will be removed } } insertAt = Math.Min(index1, index2); } else { insertAt = index1; } } else if (path2[0] == mainFile) { int index2 = mainFile.Children.IndexOf(path2[1]); if (index2 == -1) { index2 = mainFile.Children.Count; } insertAt = index2; } else { insertAt = mainFile.Children.Count; } insertIn = mainFile; } if (item1.Parent != insertIn || insertIn.Children.IndexOf(item1) != insertAt) { item1.Parent.Children.Remove(item1); insertIn.Children.Insert(insertAt, item1); item1.Parent = insertIn; } removed = true; break; } } } } if (removed) { return(null); } allItems.Add(includeItem); if (node != null) { foreach (AASourceFile file in dependancies[node]) { IncludeItem child = MakeTree(file, dependancies, allItems, mainFile ?? includeItem); if (child == null) { continue; } child.Parent = includeItem; includeItem.Children.Add(child); } } return(includeItem); }
public override bool Rename(string newName) { //Add .galaxy++ if not present if (!newName.EndsWith(".Dialog")) { newName = newName + ".Dialog"; } //Dont reneme if there is a clash foreach (FileSystemInfo dir in Parent.Dir.GetFileSystemInfos()) { if (dir.Name == newName + ".Dialog") { return(false); } } File.Move(Parent.Dir.FullName + "\\" + Name, Parent.Dir.FullName + "\\" + newName); string oldName = Name; Name = newName; InvokeRenamed(this, oldName, newName); //Change other stuff string shortName = Name.Substring(0, Name.LastIndexOf(".Dialog")); CodeGUINode.Text = shortName + (CodeGUINode.Text.EndsWith("*") ? ".galaxy++*" : ".galaxy++"); DesignerGUINode.Text = shortName + (DesignerGUINode.Text.EndsWith("*") ? ".Designer.galaxy++*" : ".Designer.galaxy++"); if (OpenFileData != null) { if (OpenFileData.TabPage != null) { OpenFileData.TabPage.Title = Name + (OpenFileData.TabPage.Title.EndsWith("*") ? "*" : ""); } if (OpenFileData.CodeTabPage != null) { OpenFileData.CodeTabPage.Title = shortName + (OpenFileData.CodeTabPage.Title.EndsWith("*") ? ".galaxy++*" : ".galaxy++"); } if (OpenFileData.DesignerTabPage != null) { OpenFileData.DesignerTabPage.Title = shortName + ".Designer.galaxy++"; } } //Fix refferences to dialog try { DialogData data; if (OpenFileData != null) { data = OpenFileData; } else { data = DialogData.Load(FullName); data.DialogItem = this; } string code = data.ActualCode; Name = oldName; string oldIdentifier = data.DialogIdentiferName; Name = newName; string newIdentifier = data.DialogIdentiferName; Parser parser = new Parser(new Lexer(new StringReader(code))); AASourceFile start = (AASourceFile)parser.Parse().GetPSourceFile(); Renamer ren = new Renamer(oldIdentifier); start.Apply(ren); ren.types.Reverse();//To avoid changeing the position of stuff we must change string[] lines = code.Split('\n'); foreach (TIdentifier identifier in ren.types) { lines[identifier.Line - 1] = lines[identifier.Line - 1].Substring(0, identifier.Pos - 1) + newIdentifier + lines[identifier.Line - 1].Substring(identifier.Pos + oldIdentifier.Length - 1); } string newCode = ""; foreach (string line in lines) { newCode += line + "\n"; } newCode = newCode.Remove(code.Length); if (code != newCode) { if (OpenFileData == null) { Form1.Form.OpenFile(this, CodeGUINode); } OpenFileData.ActualCode = newCode; } } catch (Exception err) { //Or not.. } Form1.Form.compiler.DialogItemChanged(this, null, true); return(true); }
/*private class IsThisOnLeftSide : DepthFirstAdapter * { * private PType type; * private SharedData data; * public bool IsAssignedTo; * private List<AMethodDecl> investigatedMethods = new List<AMethodDecl>(); * * public IsThisOnLeftSide(PType type, SharedData data) * { * this.type = type; * this.data = data; * } * * //Check assignments, method invocations and nonstatic method invocations. * * public override void CaseAMethodDecl(AMethodDecl node) * { * investigatedMethods.Add(node); * } * * public override void CaseAThisLvalue(AThisLvalue node) * { * if (IsAssignedTo) * return; * * Node iParent = GetClosestNodeOfType(node, typeof (AAssignmentExp), * typeof (ASimpleInvokeExp), * typeof (ANonstaticInvokeExp), * typeof (AAsyncInvokeStm), * typeof (ASyncInvokeExp), * typeof(AArrayLvalue), * typeof(APointerLvalue), * typeof(APropertyLvalue), * typeof(AStructLvalue)); * if (iParent == null) * return; * * if (iParent is AAssignmentExp) * { * AAssignmentExp aParent = (AAssignmentExp) iParent; * if (Util.IsAncestor(node, aParent.GetLvalue())) * { * IsAssignedTo = true; * } * return; * } * if (iParent is ASimpleInvokeExp) * { * ASimpleInvokeExp aParent = (ASimpleInvokeExp) iParent; * AMethodDecl method = data.SimpleMethodLinks[aParent]; * if (investigatedMethods.Contains(method)) * return; * * if (Util.IsAncestor(node, aParent.GetLvalue())) * { * IsAssignedTo = true; * } * return; * } * } * * private Node GetClosestNodeOfType(Node node, params Type[] types) * { * if (node == null) * return null; * if (types.Contains(node.GetType())) * return node; * return GetClosestNodeOfType(node.Parent(), types); * } * }*/ public override void CaseADeconstructorDecl(ADeconstructorDecl node) { AStructDecl str = Util.GetAncestor <AStructDecl>(node); AEnrichmentDecl enrichment = Util.GetAncestor <AEnrichmentDecl>(node); AMethodDecl replacer = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new AVoidType(new TVoid("void")), node.GetName(), new ArrayList(), node.GetBlock()); replacer.GetName().Text += "_Deconstructor"; //Move the method outside the struct AASourceFile file = Util.GetAncestor <AASourceFile>(node); if (str != null) { str.RemoveChild(node.Parent()); } /*else * enrichment.RemoveChild(node);*/ int i = file.GetDecl().IndexOf(str ?? (PDecl)enrichment); file.GetDecl().Insert(i /* + 1*/, replacer); //Add the struct as a parameter PType type; if (str != null) { ANamedType structType = new ANamedType(new TIdentifier(str.GetName().Text), null); finalTrans.data.StructTypeLinks[structType] = str; type = structType; } else { type = Util.MakeClone(enrichment.GetType(), finalTrans.data); } finalTrans.data.DeconstructorMap[node] = replacer; AALocalDecl structFormal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new APointerType(new TStar("*"), type), new TIdentifier("currentStruct", replacer.GetName().Line, replacer.GetName().Pos), null); replacer.GetFormals().Add(structFormal); finalTrans.data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, replacer)); //Call base deconstructor before each return if (str != null && str.GetBase() != null) { AStructDecl baseStruct = data.StructTypeLinks[(ANamedType)str.GetBase()]; if (data.StructDeconstructor.ContainsKey(baseStruct)) { baseStruct.Apply(this); replacer.Apply(new CallDeconstructors(baseStruct, structFormal, data)); /*AMethodDecl baseDeconstructor = data.DeconstructorMap[data.StructDeconstructor[baseStruct]]; * * * ALocalLvalue structFormalRef = new ALocalLvalue(new TIdentifier("currentStruct")); * ALvalueExp structFormalRefExp = new ALvalueExp(structFormalRef); * ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("baseDeconstructor"), * new ArrayList() {structFormalRefExp}); * AABlock block = (AABlock) replacer.GetBlock(); * block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), invoke)); * * data.LocalLinks[structFormalRef] = structFormal; * data.SimpleMethodLinks[invoke] = baseDeconstructor; * data.LvalueTypes[structFormalRef] = data.ExpTypes[structFormalRefExp] = structFormal.GetType(); * data.ExpTypes[invoke] = baseDeconstructor.GetReturnType();*/ } } this.structFormal = structFormal; base.CaseAMethodDecl(replacer); }
private static void GetMatchingTypes(ANamedType node, List <string> names, List <ATypedefDecl> typeDefs, List <AStructDecl> structs, List <AMethodDecl> delegates, List <ANamespaceDecl> namespaces, List <TIdentifier> generics) { List <IList> decls = new List <IList>(); List <string> currentNamespace = Util.GetFullNamespace(node); AASourceFile currentSourceFile = Util.GetAncestor <AASourceFile>(node); if (names.Count == 1) { string name = names[0]; //Check generic vars AStructDecl currentStruct = Util.GetAncestor <AStructDecl>(node); if (currentStruct != null) { foreach (TIdentifier genericVar in currentStruct.GetGenericVars()) { if (genericVar.Text == name) { generics.Add(genericVar); } } } //Get all type decls and namespaces matching this name, visible from this location List <IList> visibleDecls = Util.GetVisibleDecls(node, ((AAName)node.GetName()).GetIdentifier().Count == 1); foreach (IList declList in visibleDecls) { bool sameFile = false; if (declList.Count > 0) { sameFile = currentSourceFile == Util.GetAncestor <AASourceFile>((PDecl)declList[0]); } foreach (PDecl decl in declList) { bool sameNS = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl)); if (decl is ANamespaceDecl) { ANamespaceDecl aDecl = (ANamespaceDecl)decl; if (aDecl.GetName().Text == name) { namespaces.Add(aDecl); } continue; } if (decl is ATypedefDecl) { if (Util.IsAncestor(node, decl)) { continue; } ATypedefDecl aDecl = (ATypedefDecl)decl; if (aDecl.GetStatic() != null && !sameFile || aDecl.GetVisibilityModifier() is APrivateVisibilityModifier && !sameNS) { continue; } ANamedType namedType = (ANamedType)aDecl.GetName(); AAName aName = (AAName)namedType.GetName(); string n = ((TIdentifier)aName.GetIdentifier()[0]).Text; if (n == name) { typeDefs.Add(aDecl); } continue; } if (decl is AStructDecl) { AStructDecl aDecl = (AStructDecl)decl; if (!sameNS && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier) { continue; } if (aDecl.GetName().Text == name) { structs.Add(aDecl); } continue; } if (decl is AMethodDecl) { AMethodDecl aDecl = (AMethodDecl)decl; if (!sameNS && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier || !sameFile && aDecl.GetStatic() != null) { continue; } if (aDecl.GetDelegate() != null && aDecl.GetName().Text == name) { delegates.Add(aDecl); } continue; } } } } else { string name = names[names.Count - 1]; List <ANamespaceDecl> baseNamespaces = new List <ANamespaceDecl>(); List <string> baseNames = new List <string>(); baseNames.AddRange(names); baseNames.RemoveAt(baseNames.Count - 1); GetMatchingTypes(node, baseNames, new List <ATypedefDecl>(), new List <AStructDecl>(), new List <AMethodDecl>(), baseNamespaces, generics); foreach (ANamespaceDecl ns in baseNamespaces) { bool sameFile = currentSourceFile == Util.GetAncestor <AASourceFile>(ns); foreach (PDecl decl in ns.GetDecl()) { bool sameNS = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl)); if (decl is ANamespaceDecl) { ANamespaceDecl aDecl = (ANamespaceDecl)decl; if (aDecl.GetName().Text == name) { namespaces.Add(aDecl); } continue; } if (decl is ATypedefDecl) { ATypedefDecl aDecl = (ATypedefDecl)decl; ANamedType namedType = (ANamedType)aDecl.GetName(); AAName aName = (AAName)namedType.GetName(); string n = ((TIdentifier)aName.GetIdentifier()[0]).Text; if (n == name) { typeDefs.Add(aDecl); } continue; } if (decl is AStructDecl) { AStructDecl aDecl = (AStructDecl)decl; if (!sameNS && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier) { continue; } if (aDecl.GetName().Text == name) { structs.Add(aDecl); } continue; } if (decl is AMethodDecl) { AMethodDecl aDecl = (AMethodDecl)decl; if (!sameNS && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier || !sameFile && aDecl.GetStatic() != null) { continue; } if (aDecl.GetDelegate() != null && aDecl.GetName().Text == name) { delegates.Add(aDecl); } continue; } } } } }
public override void CaseAASourceFile(AASourceFile node) { currentSourceFile = node; base.CaseAASourceFile(node); }
public override void CaseAALocalDecl(AALocalDecl node) { //Convert a static struct field into a global variable. All refferences to it are structFieldLvalues. if (node.GetStatic() == null) { return; } AStructDecl str = (AStructDecl)node.Parent(); if (data.StructFields[str].Contains(node)) { data.StructFields[str].Remove(node); } AFieldDecl replacementField; //Don't enhrit static fields. if (data.EnheritanceLocalMap.ContainsKey(node)) { str.RemoveChild(node); AALocalDecl realVar = data.EnheritanceLocalMap[node]; if (convertionMap.ContainsKey(realVar)) { //Already converted to a field replacementField = convertionMap[realVar]; foreach (AStructFieldLvalue lvalue in data.StructMethodFieldLinks.Where(link => link.Value == node).Select(link => link.Key)) { AFieldLvalue newLvalue = new AFieldLvalue(new TIdentifier(replacementField.GetName().Text)); data.FieldLinks[newLvalue] = replacementField; data.LvalueTypes[newLvalue] = replacementField.GetType(); lvalue.ReplaceBy(newLvalue); } } else { List <AStructFieldLvalue> refferences = new List <AStructFieldLvalue>(); refferences.AddRange(data.StructMethodFieldLinks.Where(link => link.Value == node).Select(link => link.Key)); foreach (AStructFieldLvalue lvalue in refferences) { data.StructMethodFieldLinks[lvalue] = realVar; } } return; } replacementField = new AFieldDecl(new APublicVisibilityModifier(), null, node.GetConst(), node.GetType(), node.GetName(), node.GetInit()); replacementField.GetName().Text = str.GetName().Text + "_" + replacementField.GetName().Text; AASourceFile file = Util.GetAncestor <AASourceFile>(node); file.GetDecl().Insert(file.GetDecl().IndexOf(node.Parent()), replacementField); data.Fields.Add(new SharedData.DeclItem <AFieldDecl>(file, replacementField)); if (ContainsNewExp(replacementField.GetInit())) { data.FieldsToInitInMapInit.Add(replacementField); } foreach (AStructFieldLvalue lvalue in data.StructMethodFieldLinks.Where(link => link.Value == node).Select(link => link.Key)) { AFieldLvalue newLvalue = new AFieldLvalue(new TIdentifier(replacementField.GetName().Text)); data.FieldLinks[newLvalue] = replacementField; data.LvalueTypes[newLvalue] = replacementField.GetType(); lvalue.ReplaceBy(newLvalue); } convertionMap.Add(node, replacementField); node.Parent().RemoveChild(node); }
private void Apply(AAProgram ast) { int stage = 1; int totalStages = 31; List <ANamedType> deleteUs = new List <ANamedType>(); foreach (KeyValuePair <ANamedType, AStructDecl> pair in data.StructTypeLinks) { ANamedType type = pair.Key; AStructDecl str = pair.Value; if (data.Enums.ContainsKey(str)) { type.SetName(new AAName(new ArrayList() { new TIdentifier(data.Enums[str] ? "int" : "byte") })); deleteUs.Add(type); } } foreach (ANamedType type in deleteUs) { data.StructTypeLinks.Remove(type); } if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text2")); } stage++; ast.Apply(new RemoveNamespaces()); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text3")); } stage++; ast.Apply(new StaticStructMembers(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text4")); } stage++; ast.Apply(new RemoveConstants(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text5")); } stage++; ast.Apply(new MainEntryFinder(this)); if (mainEntry == null) { //errors.Add(new ErrorCollection.Error("No entry point found (void InitMap(){...})", true)); //Generate main entry AASourceFile file = ast.GetSourceFiles().Cast <AASourceFile>().FirstOrDefault( sourceFile => !Util.GetAncestor <AASourceFile>(sourceFile).GetName().Text.Contains("\\")); if (file == null) { //Make default sourcefile file = new AASourceFile(); file.SetName(new TIdentifier("MapScript")); ast.GetSourceFiles().Add(file); data.LineCounts[file] = 1; } mainEntry = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new AVoidType(new TVoid("void")), new TIdentifier("InitMap"), new ArrayList(), new AABlock()); file.GetDecl().Add(mainEntry); data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, mainEntry)); } else if (Util.GetAncestor <AASourceFile>(mainEntry).GetName().Text.Contains("\\")) { errors.Add(new ErrorCollection.Error(mainEntry.GetName(), Util.GetAncestor <AASourceFile>(mainEntry), LocRM.GetString("FT_Text6"), true)); } ((AABlock)mainEntry.GetBlock()).GetStatements().Insert(0, mainEntryFieldInitBlock); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text7")); } stage++; ast.Apply(new StructInitializer(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text8")); } stage++; ast.Apply(new TransformExpressionIfs(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text9")); } stage++; ast.Apply(new RenameUnicode(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text10")); } stage++; TransformProperties.Phase1.Parse(this); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text11")); } stage++; ast.Apply(new RemoveDeadCode()); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text12")); } stage++; ast.Apply(new TransformMethodDecls(this)); if (errors.HasErrors) { return; } if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text13")); } stage++; MakeInitializerInvokes(); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text14")); } stage++; ast.Apply(new AssignFixup(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text15")); } stage++; TransformProperties.Phase2.Parse(this); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text16")); } stage++; if (data.Invokes.Count > 0) { Invokes.Parse(this); } if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text17")); } stage++; ast.Apply(new RemoveEmptyStructs(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text18")); } stage++; ast.Apply(new Delegates(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text19")); } stage++; //ast.Apply(new AddUnneededRef(data)); ast.Apply(new FixInlineMethods(this, false)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text20")); } stage++; ast.Apply(new RemoveUnnededRef(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text21")); } stage++; ast.Apply(new SplitStructTests(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text22")); } stage++; new Pointers(data).Parse(ast); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text23")); } stage++; ast.Apply(new FixInlineMethods(this, true)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text24")); } stage++; //Split local struct into primitives, to make optimizations easier ast.Apply(new StructSplitter(data)); //ast.Apply(new BulkCopyFixup(this)); //BulkCopyFixup.Parse(ast, this); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text25")); } stage++; //Remove stupid assignments (assignments to a variable where that variable is not used before its next assignment ast.Apply(new RemoveUnusedVariables(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text26")); } stage++; ast.Apply(new ConstantFolding(data)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text27")); } stage++; //Assign fixup was here //Dahm grafiti painters //ast.Apply(new LivenessAnalysis(this)); ast.Apply(new Optimizations.OptimizePhase(this, LocRM.GetString("FT_Text1") + (stage - 1) + " / " + totalStages + LocRM.GetString("FT_Text27"))); ast.Apply(new FixByteArrayIndexes(data)); if (Options.Compiler.MakeShortNames) { if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text28")); } stage++; ast.Apply(new MakeShortNames(this)); } else { if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text29")); } stage++; //MakeUniqueNames.Parse(ast, this); ast.Apply(new MakeUniqueNamesV2()); } if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text30")); } stage++; //Remove uneeded blocks and check that names fit the decls ast.Apply(new RenameRefferences(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text31")); } stage++; //Obfuscate strings ast.Apply(new ObfuscateStrings(this)); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text32")); } stage++; MergeSameMethods.Parse(this); if (data.AllowPrintouts) { Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text33")); } stage++; //Insert includes, and move methods, structs and fields around so they are visible FixIncludes.Apply(ast, this); if (Options.Compiler.OneOutputFile) { ((AASourceFile)mainEntry.Parent()).SetName(new TIdentifier("MapScript")); } }
private IncludeItem GetIncludeItem(Node node) { AASourceFile file = Util.GetAncestor <AASourceFile>(node); return(allItems.OfType <IncludeItem>().FirstOrDefault(inclItem => inclItem.Current == file)); }
public override void CaseADelegateInvokeExp(ADelegateInvokeExp node) { //Build a list of the possible methods AASourceFile currentFile = Util.GetAncestor <AASourceFile>(node); List <AMethodDecl> methods = new List <AMethodDecl>(); ANamedType type = (ANamedType)finalTrans.data.ExpTypes[node.GetReceiver()]; AMethodDecl delegateMethod = finalTrans.data.DelegateTypeLinks[type]; foreach (KeyValuePair <ADelegateExp, AMethodDecl> delegateCreationPair in finalTrans.data.DelegateCreationMethod) { if (TypeChecking.Assignable(delegateCreationPair.Key.GetType(), type)) { if (!methods.Contains(delegateCreationPair.Value)) { methods.Add(delegateCreationPair.Value); } } } MoveMethodDeclsOut mover; if (methods.Count == 0) { //Can only remove it if the return value is unused if (!(node.Parent() is AExpStm)) { finalTrans.errors.Add(new ErrorCollection.Error(node.GetToken(), currentFile, "No possible methods found for delegate invoke.")); throw new ParserException(node.GetToken(), "Delegates.OutADelegateInvokeExp"); } mover = new MoveMethodDeclsOut("delegateVar", finalTrans.data); foreach (Node arg in node.GetArgs()) { arg.Apply(mover); } node.Parent().Parent().RemoveChild(node.Parent()); foreach (PStm stm in mover.NewStatements) { stm.Apply(this); } return; } if (methods.Count == 1) { ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("renameMe"), new ArrayList()); while (node.GetArgs().Count > 0) { invoke.GetArgs().Add(node.GetArgs()[0]); } //If we have a struct method, add the pointer from the delegate if (finalTrans.data.StructMethods.Any(str => str.Value.Contains(methods[0]))) { AStructDecl targetStr = finalTrans.data.StructMethods.First(str => str.Value.Contains(methods[0])).Key; AMethodDecl getPointerDecl = GetPointerMethod(targetStr.GetDimention() != null); ASimpleInvokeExp getPointerInvoke = new ASimpleInvokeExp(new TIdentifier("renameMe"), new ArrayList() { node.GetReceiver() }); invoke.GetArgs().Add(getPointerInvoke); finalTrans.data.SimpleMethodLinks[getPointerInvoke] = getPointerDecl; finalTrans.data.ExpTypes[getPointerInvoke] = getPointerDecl.GetReturnType(); } finalTrans.data.SimpleMethodLinks[invoke] = methods[0]; finalTrans.data.ExpTypes[invoke] = methods[0].GetReturnType(); node.ReplaceBy(invoke); return; } //Multiple methods. Make /* * <Methods moved out from reciever> * string delegate = GetMethodPart(<reciever>); * if (delegate == "...") * { * Foo(...); * } * else if (delegate == "...") * { * Bar(..., GetPointerPart(<reciever>); * } * else if(...) * ... * else * { * UIDisplayMessage(PlayerGroupAll(), c_messageAreaDebug, StringToText("[<file>:<line>]: No methods matched delegate.")); * int i = 1/0; * return; * } * */ AABlock block = new AABlock(new ArrayList(), new TRBrace("}")); mover = new MoveMethodDeclsOut("delegateVar", finalTrans.data); node.GetReceiver().Apply(mover); AMethodDecl methodPartMethod = GetMethodMethod(); ASimpleInvokeExp methodPartInvoke = new ASimpleInvokeExp(new TIdentifier("GetMethodPart"), new ArrayList() { Util.MakeClone(node.GetReceiver(), finalTrans.data) }); finalTrans.data.SimpleMethodLinks[methodPartInvoke] = methodPartMethod; finalTrans.data.ExpTypes[methodPartInvoke] = methodPartMethod.GetReturnType(); AALocalDecl methodPartDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("string"), null), new TIdentifier("methodPart"), methodPartInvoke); block.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), methodPartDecl)); //If the invoke's return value is used, get the lvalue PLvalue leftSide; if (node.Parent() is AALocalDecl) { leftSide = new ALocalLvalue(new TIdentifier("renameMe")); finalTrans.data.LocalLinks[(ALocalLvalue)leftSide] = (AALocalDecl)node.Parent(); finalTrans.data.LvalueTypes[leftSide] = new ANamedType(new TIdentifier("string"), null); PStm pStm = Util.GetAncestor <PStm>(node); AABlock pBlock = (AABlock)pStm.Parent(); pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm) + 1, new ABlockStm(new TLBrace("{"), block)); node.Parent().RemoveChild(node); } else if (node.Parent() is AAssignmentExp) { AAssignmentExp assignExp = (AAssignmentExp)node.Parent(); leftSide = assignExp.GetLvalue(); leftSide.Apply(mover); PStm pStm = Util.GetAncestor <PStm>(node); pStm.ReplaceBy(new ABlockStm(new TLBrace("{"), block)); } else if (node.Parent() is AExpStm) { //No assignments needed leftSide = null; node.Parent().ReplaceBy(new ABlockStm(new TLBrace("{"), block)); } else { //Create a new local AALocalDecl leftSideDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(delegateMethod.GetReturnType(), finalTrans.data), new TIdentifier("delegateVar"), null); ALocalLvalue leftSideLink = new ALocalLvalue(new TIdentifier("delegateVar")); ALvalueExp leftSideLinkExp = new ALvalueExp(leftSideLink); PStm pStm = Util.GetAncestor <PStm>(node); AABlock pBlock = (AABlock)pStm.Parent(); pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm), new ABlockStm(new TLBrace("{"), block)); node.ReplaceBy(leftSideLinkExp); finalTrans.data.LocalLinks[leftSideLink] = leftSideDecl; finalTrans.data.LvalueTypes[leftSideLink] = finalTrans.data.ExpTypes[leftSideLinkExp] = leftSideDecl.GetType(); leftSide = leftSideLink; block.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), leftSideDecl)); } ABlockStm elseBranch; //Make final else branch /* { * UIDisplayMessage(PlayerGroupAll(), c_messageAreaDebug, StringToText("<file>[<line>, <pos>]: No methods matched delegate.")); * IntToString(1/0); * return; * } */ { AABlock innerBlock = new AABlock(new ArrayList(), new TRBrace("}")); ASimpleInvokeExp playerGroupInvoke = new ASimpleInvokeExp(new TIdentifier("PlayerGroupAll"), new ArrayList()); AFieldLvalue messageAreaLink = new AFieldLvalue(new TIdentifier("c_messageAreaDebug")); ALvalueExp messageAreaLinkExp = new ALvalueExp(messageAreaLink); AStringConstExp stringConst = new AStringConstExp( new TStringLiteral("\"" + currentFile.GetName().Text.Replace('\\', '/') + "[" + node.GetToken().Line + ", " + node.GetToken().Pos + "]: Got a null delegate.\"")); ASimpleInvokeExp stringToTextInvoke = new ASimpleInvokeExp(new TIdentifier("StringToText"), new ArrayList() { stringConst }); ASimpleInvokeExp displayMessageInvoke = new ASimpleInvokeExp(new TIdentifier("UIDisplayMessage"), new ArrayList() { playerGroupInvoke, messageAreaLinkExp, stringToTextInvoke }); AIntConstExp intConst1 = new AIntConstExp(new TIntegerLiteral("1")); AIntConstExp intConst2 = new AIntConstExp(new TIntegerLiteral("0")); ABinopExp binop = new ABinopExp(intConst1, new ADivideBinop(new TDiv("/")), intConst2); ASimpleInvokeExp intToStringInvoke = new ASimpleInvokeExp(new TIdentifier("IntToString"), new ArrayList() { binop }); innerBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), displayMessageInvoke)); innerBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), intToStringInvoke)); //innerBlock.GetStatements().Add(new AVoidReturnStm(new TReturn("return"))); elseBranch = new ABlockStm(new TLBrace("{"), innerBlock); finalTrans.data.SimpleMethodLinks[playerGroupInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == playerGroupInvoke.GetName().Text); finalTrans.data.SimpleMethodLinks[stringToTextInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringToTextInvoke.GetName().Text); finalTrans.data.SimpleMethodLinks[displayMessageInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == displayMessageInvoke.GetName().Text); finalTrans.data.SimpleMethodLinks[intToStringInvoke] = finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == intToStringInvoke.GetName().Text); finalTrans.data.FieldLinks[messageAreaLink] = finalTrans.data.Libraries.Fields.First(m => m.GetName().Text == messageAreaLink.GetName().Text); finalTrans.data.ExpTypes[playerGroupInvoke] = finalTrans.data.SimpleMethodLinks[playerGroupInvoke].GetReturnType(); finalTrans.data.LvalueTypes[messageAreaLink] = finalTrans.data.ExpTypes[messageAreaLinkExp] = finalTrans.data.FieldLinks[messageAreaLink].GetType(); finalTrans.data.ExpTypes[stringToTextInvoke] = finalTrans.data.SimpleMethodLinks[stringToTextInvoke].GetReturnType(); finalTrans.data.ExpTypes[stringConst] = finalTrans.data.ExpTypes[intToStringInvoke] = new ANamedType(new TIdentifier("string"), null); finalTrans.data.ExpTypes[displayMessageInvoke] = new AVoidType(); finalTrans.data.ExpTypes[intConst1] = finalTrans.data.ExpTypes[intConst2] = finalTrans.data.ExpTypes[binop] = new ANamedType(new TIdentifier("int"), null); } foreach (AMethodDecl method in methods) { /* * if (delegate == "...") * { * Foo(...); * } * else if (delegate == "...") * { * Bar(..., GetPointerPart(<reciever>); * } * else if(...) * ... */ AABlock innerBlock = new AABlock(new ArrayList(), new TRBrace("}")); ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier(method.GetName().Text), new ArrayList()); for (int i = 0; i < node.GetArgs().Count; i++) { PExp arg = (PExp)node.GetArgs()[i]; invoke.GetArgs().Add(Util.MakeClone(arg, finalTrans.data)); } //If we have a struct method, add the pointer from the delegate if (finalTrans.data.StructMethods.Any(str => str.Value.Contains(method))) { AStructDecl targetStr = finalTrans.data.StructMethods.First(str => str.Value.Contains(method)).Key; AMethodDecl getPointerDecl = GetPointerMethod(targetStr.GetDimention() != null); ASimpleInvokeExp getPointerInvoke = new ASimpleInvokeExp(new TIdentifier("renameMe"), new ArrayList() { Util.MakeClone(node.GetReceiver(), data) }); invoke.GetArgs().Add(getPointerInvoke); finalTrans.data.SimpleMethodLinks[getPointerInvoke] = getPointerDecl; finalTrans.data.ExpTypes[getPointerInvoke] = getPointerDecl.GetReturnType(); } finalTrans.data.SimpleMethodLinks[invoke] = method; finalTrans.data.ExpTypes[invoke] = method.GetReturnType(); if (leftSide == null) { innerBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), invoke)); } else { AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), Util.MakeClone(leftSide, finalTrans.data), invoke); finalTrans.data.ExpTypes[assignment] = finalTrans.data.ExpTypes[invoke]; innerBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment)); } ALocalLvalue methodPartLink = new ALocalLvalue(new TIdentifier("methodPart")); ALvalueExp methodPartLinkExp = new ALvalueExp(methodPartLink); AStringConstExp stringConst = new AStringConstExp(new TStringLiteral("\"" + GetName(method) + "\"")); finalTrans.data.LocalLinks[methodPartLink] = methodPartDecl; finalTrans.data.LvalueTypes[methodPartLink] = finalTrans.data.ExpTypes[methodPartLinkExp] = finalTrans.data.ExpTypes[stringConst] = new ANamedType(new TIdentifier("string"), null); ABinopExp binop = new ABinopExp(methodPartLinkExp, new AEqBinop(new TEq("==")), stringConst); finalTrans.data.ExpTypes[binop] = new ANamedType(new TIdentifier("bool"), null); AIfThenElseStm ifThenElse = new AIfThenElseStm(new TLParen("("), binop, new ABlockStm(new TLBrace("{"), innerBlock), elseBranch); elseBranch = new ABlockStm(new TLBrace("{"), new AABlock(new ArrayList() { ifThenElse }, new TRBrace("}"))); } block.GetStatements().Add(elseBranch); }
public override void CaseAConstructorDecl(AConstructorDecl node) { AStructDecl str = Util.GetAncestor <AStructDecl>(node); AEnrichmentDecl enrichment = Util.GetAncestor <AEnrichmentDecl>(node); AMethodDecl replacer = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new AVoidType(new TVoid("void")), node.GetName(), new ArrayList(), node.GetBlock()); replacer.GetName().Text += "_Constructor"; while (node.GetFormals().Count > 0) { replacer.GetFormals().Add(node.GetFormals()[0]); } //Move the method outside the struct AASourceFile file = Util.GetAncestor <AASourceFile>(node); if (str != null) { str.RemoveChild(node.Parent()); } else { enrichment.RemoveChild(node); } int i = file.GetDecl().IndexOf(str ?? (PDecl)enrichment); file.GetDecl().Insert(i /* + 1*/, replacer); //Add the struct as a parameter PType type; if (str != null) { ANamedType structType = new ANamedType(new TIdentifier(str.GetName().Text), null); finalTrans.data.StructTypeLinks[structType] = str; type = structType; } else { type = Util.MakeClone(enrichment.GetType(), finalTrans.data); } finalTrans.data.ConstructorMap[node] = replacer; structFormal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new APointerType(new TStar("*"), type), new TIdentifier("currentStruct", replacer.GetName().Line, replacer.GetName().Pos), null); replacer.GetFormals().Add(structFormal); finalTrans.data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, replacer)); //Add return stm replacer.SetReturnType(new APointerType(new TStar("*"), Util.MakeClone(type, data))); replacer.Apply(new TransformConstructorReturns(structFormal, data)); //Insert call to base constructor);); if (finalTrans.data.ConstructorBaseLinks.ContainsKey(node)) { AMethodDecl baseConstructor = finalTrans.data.ConstructorMap[finalTrans.data.ConstructorBaseLinks[node]]; ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier(baseConstructor.GetName().Text), new ArrayList()); while (node.GetBaseArgs().Count > 0) { invoke.GetArgs().Add(node.GetBaseArgs()[0]); } AThisLvalue thisLvalue1 = new AThisLvalue(new TThis("this")); ALvalueExp thisExp1 = new ALvalueExp(thisLvalue1); invoke.GetArgs().Add(thisExp1); AThisLvalue thisLvalue2 = new AThisLvalue(new TThis("this")); AAssignmentExp assignExp = new AAssignmentExp(new TAssign("="), thisLvalue2, invoke); ANamedType structType = new ANamedType(new TIdentifier(str.GetName().Text), null); finalTrans.data.StructTypeLinks[structType] = str; finalTrans.data.LvalueTypes[thisLvalue1] = finalTrans.data.LvalueTypes[thisLvalue2] = finalTrans.data.ExpTypes[thisExp1] = finalTrans.data.ExpTypes[assignExp] = finalTrans.data.ExpTypes[invoke] = new APointerType(new TStar("*"), structType); //finalTrans.data.ExpTypes[invoke] = new AVoidType(new TVoid("void")); finalTrans.data.SimpleMethodLinks[invoke] = baseConstructor; ((AABlock)replacer.GetBlock()).GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), assignExp)); //Inline if base and current are two different kinds of pointer types (int/string) AStructDecl baseStruct = null; AConstructorDecl baseC = finalTrans.data.ConstructorBaseLinks[node]; foreach (KeyValuePair <AStructDecl, List <AConstructorDecl> > pair in finalTrans.data.StructConstructors) { bool found = false; foreach (AConstructorDecl decl in pair.Value) { if (baseC == decl) { found = true; break; } } if (found) { baseStruct = pair.Key; break; } } if ((str.GetIntDim() == null) != (baseStruct.GetIntDim() == null)) { //For the inilining, change the type to the type of the caller AALocalDecl lastFormal = baseConstructor.GetFormals().OfType <AALocalDecl>().Last(); lastFormal.SetRef(new TRef("ref")); APointerType oldType = (APointerType)lastFormal.GetType(); structType = new ANamedType(new TIdentifier(str.GetName().Text), null); finalTrans.data.StructTypeLinks[structType] = str; APointerType newType = new APointerType(new TStar("*"), structType); lastFormal.SetType(newType); foreach ( ALocalLvalue lvalue in data.LocalLinks.Where(pair => pair.Value == lastFormal).Select(pair => pair.Key)) { data.LvalueTypes[lvalue] = newType; if (lvalue.Parent() is ALvalueExp) { data.ExpTypes[(PExp)lvalue.Parent()] = newType; if (lvalue.Parent().Parent() is APointerLvalue) { data.LvalueTypes[(PLvalue)lvalue.Parent().Parent()] = newType.GetType(); } } } FixInlineMethods.Inline(invoke, finalTrans); lastFormal.SetRef(null); foreach ( ALocalLvalue lvalue in data.LocalLinks.Where(pair => pair.Value == lastFormal).Select(pair => pair.Key)) { data.LvalueTypes[lvalue] = oldType; if (lvalue.Parent() is ALvalueExp) { data.ExpTypes[(PExp)lvalue.Parent()] = oldType; if (lvalue.Parent().Parent() is APointerLvalue) { data.LvalueTypes[(PLvalue)lvalue.Parent().Parent()] = oldType.GetType(); } } } lastFormal.SetType(oldType); } //Inline it instead, Since the pointer implementations might not be the same (int vs string) /*AMethodDecl baseConstructor = finalTrans.data.ConstructorMap[finalTrans.data.ConstructorBaseLinks[node]]; * * AABlock localsBlock = new AABlock(new ArrayList(), new TRBrace("}")); * ABlockStm cloneBlock = new ABlockStm(new TLBrace("{"), (PBlock) baseConstructor.GetBlock().Clone()); * Dictionary<AALocalDecl, PLvalue> localMap = new Dictionary<AALocalDecl, PLvalue>(); * for (int argNr = 0; argNr < baseConstructor.GetFormals().Count; argNr++) * { * AALocalDecl formal = (AALocalDecl) baseConstructor.GetFormals()[i]; * PExp arg; * if (i < baseConstructor.GetFormals().Count - 1) * arg = (PExp)node.GetBaseArgs()[i]; * else * { * AThisLvalue thisLvalue = new AThisLvalue(new TThis("this")); * ALvalueExp thisExp = new ALvalueExp(thisLvalue); * * ANamedType structType = new ANamedType(new TIdentifier(str.GetName().Text), null); * finalTrans.data.StructTypeLinks[structType] = str; * * finalTrans.data.LvalueTypes[thisLvalue] = * finalTrans.data.ExpTypes[thisExp] = new APointerType(new TStar("*"), structType); * * arg = thisExp; * } * * if (formal.GetRef() != null || formal.GetOut() != null) * { * //Use same variable * localMap[formal] = ((ALvalueExp) arg).GetLvalue(); * } * else * { * //Make a new variable * AALocalDecl newLocal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, * Util.MakeClone(formal.GetType(), finalTrans.data), * new TIdentifier(formal.GetName().Text), * Util.MakeClone(arg, data)); * * ALocalLvalue newLocalRef = new ALocalLvalue(new TIdentifier(newLocal.GetName().Text)); * * localMap[formal] = newLocalRef; * data.LvalueTypes[newLocalRef] = newLocal.GetType(); * data.LocalLinks[newLocalRef] = newLocal; * * localsBlock.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), newLocal)); * } * * } * * CloneMethod cloner = new CloneMethod(finalTrans.data, localMap, cloneBlock); * baseConstructor.GetBlock().Apply(cloner); * * ((AABlock)cloneBlock.GetBlock()).GetStatements().Insert(0, new ABlockStm(new TLBrace("{"), localsBlock)); * ((AABlock)node.GetBlock()).GetStatements().Insert(0, cloneBlock);*/ } //Fix refferences to other struct stuff); base.CaseAMethodDecl(replacer); //Add functionality to refference the current struct in a constructor //Want to do it as a pointer type, since the constructer can only be called for pointer types }