Пример #1
0
 public override void OutAAProgram(AAProgram node)
 {
     if (multipleEntryCandidates.Count > 0)
     {
         finalTrans.errors.Add(new ErrorCollection.Error(multipleEntryCandidates[0], LocRM.GetString("ErrorText1"), multipleEntryCandidates.ToArray()));
     }
 }
Пример #2
0
 public override void OutAAProgram(AAProgram node)
 {
     if (multipleEntryCandidates.Count > 0)
     {
         finalTrans.errors.Add(new ErrorCollection.Error(multipleEntryCandidates[0], "Found multiple candidates for the main entry", multipleEntryCandidates.ToArray()));
     }
 }
Пример #3
0
 public override void InAAProgram(AAProgram node)
 {
     if (Options.Compiler.AutomaticallyInlineShortMethods)
     {
         node.Apply(new MarkShortMethodsAsInline(finalTrans, inlineConstructors));
     }
     base.InAAProgram(node);
 }
Пример #4
0
 public override void OutAAProgram(AAProgram node)
 {
     foreach (ANamedType type in finalTrans.data.DelegateTypeLinks.Keys)
     {
         type.SetPrimitive("string");
     }
     base.OutAAProgram(node);
 }
Пример #5
0
        public override void OutAAProgram(AAProgram node)
        {
            foreach (KeyValuePair <AArrayLengthLvalue, AArrayTempType> pair in data.ArrayLengthTypes)
            {
                AIntConstExp intConst = new AIntConstExp(new TIntegerLiteral(pair.Value.GetIntDim().Text));
                data.ExpTypes[intConst] = new ANamedType(new TIdentifier("int"), null);
                ALvalueExp exp = Util.GetAncestor <ALvalueExp>(pair.Key);
                exp.ReplaceBy(intConst);
            }

            base.OutAAProgram(node);
        }
Пример #6
0
 public override void OutAAProgram(AAProgram node)
 {
     //Remove all inits of struct fields
     foreach (AStructDecl str in data.Structs.Select(declItem => declItem.Decl))
     {
         foreach (AALocalDecl localDecl in str.GetLocals().OfType <AALocalDecl>())
         {
             localDecl.SetInit(null);
         }
     }
     base.OutAAProgram(node);
 }
Пример #7
0
        public override void OutAAProgram(AAProgram node)
        {
            List <ALocalLvalue> deleteUs = new List <ALocalLvalue>();

            foreach (KeyValuePair <ALocalLvalue, AALocalDecl> pair in finalTrans.data.LocalLinks)
            {
                if (!Util.HasAncestor <AAProgram>(pair.Key))
                {
                    deleteUs.Add(pair.Key);
                }
            }
            foreach (ALocalLvalue lvalue in deleteUs)
            {
                finalTrans.data.LocalLinks.Remove(lvalue);
            }
        }
Пример #8
0
        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";
            }
        }
Пример #9
0
        public override void CaseAAProgram(AAProgram node)
        {
            /*decls.AddRange(finalTrans.data.Structs.Select(str => str.Decl));
             * decls.AddRange(finalTrans.data.Methods.Select(str => str.Decl));
             * decls.AddRange(finalTrans.data.Fields.Select(str => str.Decl));
             * if (finalTrans.data.Locals.Count > 0)
             *  decls.AddRange(finalTrans.data.Locals.Select(str => str.Value).Aggregate(Aggregate));
             * if (finalTrans.data.Structs.Count > 0)
             *  decls.AddRange(finalTrans.data.StructFields.Values.Aggregate(Aggregate));*/
            base.CaseAAProgram(node);
            Random rand = new Random();

            while (decls.Count > 0)
            {
                int  i = rand.Next(decls.Count);
                Node n = decls[i];
                decls.RemoveAt(i);

                if (n is AFieldDecl)
                {
                    AFieldDecl an     = (AFieldDecl)n;
                    an.GetName().Text = nextName;
                }
                else if (n is AMethodDecl)
                {
                    AMethodDecl an = (AMethodDecl)n;
                    if (finalTrans.mainEntry == an || (an.GetTrigger() != null && finalTrans.data.HasUnknownTrigger))
                    {
                        continue;
                    }
                    an.GetName().Text = nextName;
                }
                else if (n is AALocalDecl)
                {
                    AALocalDecl an    = (AALocalDecl)n;
                    an.GetName().Text = nextName;
                }
                else if (n is AStructDecl)
                {
                    AStructDecl an    = (AStructDecl)n;
                    an.GetName().Text = nextName;
                }
                NextName();
            }
        }
Пример #10
0
        public override void OutAAProgram(AAProgram node)
        {
            //Link stuff in delegates

            /* foreach (SharedData.DeclItem<AMethodDecl> declItem in data.Delegates)
             * {
             *   //declItem.File.GetDecl().Add(declItem.Decl);
             *   declItem.Decl.Apply(this);
             *   //declItem.File.GetDecl().Remove(declItem.Decl);
             * }*/
            //Remove typedefs
            foreach (ATypedefDecl decl in data.Typedefs)
            {
                decl.Parent().RemoveChild(decl);
            }
            data.Typedefs.Clear();
            base.OutAAProgram(node);
        }
Пример #11
0
            public override void OutAAProgram(AAProgram node)
            {
                //First, analyze methods with no dependancies
                List <AMethodDecl> analyzedMethods = new List <AMethodDecl>();

                while (true)
                {
                    bool processedSomething = false;
                    foreach (KeyValuePair <AMethodDecl, List <AMethodDecl> > pair in dependancies)
                    {
                        AMethodDecl method = pair.Key;
                        if (analyzedMethods.Contains(method))
                        {
                            continue;
                        }

                        bool hasDependancies = false;
                        foreach (AMethodDecl dependancy in pair.Value)
                        {
                            if (!analyzedMethods.Contains(dependancy))
                            {
                                hasDependancies = true;
                                break;
                            }
                        }
                        if (hasDependancies)
                        {
                            continue;
                        }
                        processedSomething = true;
                        Analyze(method);
                        analyzedMethods.Add(method);
                    }
                    if (analyzedMethods.Count == dependancies.Count)
                    {
                        break;
                    }
                    if (processedSomething)
                    {
                        continue;
                    }
                    //There is a cycle left.
                }
            }
Пример #12
0
        public override void OutAAProgram(AAProgram node)
        {
            //Fix types
            foreach (var pair in data.LocalLinks.Where(pair => Util.HasAncestor <AAProgram>(pair.Key) &&
                                                       !Util.TypesEqual(data.ExpTypes[(PExp)pair.Key.Parent()], pair.Value.GetType(), data)))
            {
                ALocalLvalue lvalue = pair.Key;
                AALocalDecl  decl   = pair.Value;


                data.LvalueTypes[lvalue] = decl.GetType();
                if (lvalue.Parent() is ALvalueExp)
                {
                    data.ExpTypes[(PExp)lvalue.Parent()] = decl.GetType();
                    if (lvalue.Parent().Parent() is APointerLvalue)
                    {
                        data.LvalueTypes[(PLvalue)lvalue.Parent().Parent()] = ((APointerType)decl.GetType()).GetType();
                    }
                }
            }

            base.OutAAProgram(node);
        }
Пример #13
0
 public static void Parse(AAProgram ast, FinalTransformations finalTrans)
 {
     /*
      * Should be done in Pointers phase
      * foo == null > foo == "" || !DataTableExists(foo);
      *             | foo == -1 || !inUse[foo] || GetIdentifier(foo) != foo->identifier
      *
      *
      * delete foo > delete foo;
      *              foo = null;
      *
      * foo = null > foo = ""
      *            | foo = -1
      *
      *
      * This phase:
      * Add identifier to all structs and classes that are ever dynamically created
      * At any (*foo), analyze if foo can be null, and if so, create null check.
      *
      * Phase 1: Generate SafeVariablesData for all methods.
      *
      */
 }
Пример #14
0
        public static void CalculateMethodModify(AAProgram ast, SharedData data, out int methodCount)
        {
            //Calculate what global variables all methods might modify.
            methodData.Clear();


            GetDependancies dependancies = new GetDependancies(data);

            ast.Apply(dependancies);
            methodCount = dependancies.UsedMethods.Count;

            while (dependancies.UsedMethods.Count > 0)
            {
                LinkedList <AMethodDecl> modified = new LinkedList <AMethodDecl>();
                foreach (var pair in dependancies.UsedMethods)
                {
                    AMethodDecl        method      = pair.Key;
                    List <AMethodDecl> usedMethods = pair.Value;


                    ModifyData modifyData = new ModifyData();
                    foreach (AFieldDecl fieldDecl in dependancies.ReadFields[method])
                    {
                        modifyData.Add(fieldDecl, true, false);
                    }
                    foreach (AFieldDecl fieldDecl in dependancies.WrittenFields[method])
                    {
                        modifyData.Add(fieldDecl, false, true);
                    }
                    bool skip = false;
                    foreach (AMethodDecl usedMethod in usedMethods)
                    {
                        ModifyData usedData = GetModifyData(usedMethod);
                        if (usedData == null)
                        {
                            skip = true;
                            break;
                        }
                        modifyData.Union(usedData);
                    }
                    if (skip)
                    {
                        continue;
                    }
                    methodData[method] = modifyData;
                    modified.AddLast(method);
                }
                foreach (AMethodDecl decl in modified)
                {
                    dependancies.UsedMethods.Remove(decl);
                    dependancies.ReadFields.Remove(decl);
                    dependancies.WrittenFields.Remove(decl);
                }
                if (modified.Count == 0)
                {//The rest is in a circular dependancy
                    foreach (var pair in dependancies.UsedMethods)
                    {
                        AMethodDecl method = pair.Key;

                        ModifyData modifyData = new ModifyData();

                        Update(method, new List <AMethodDecl>(), modifyData, dependancies.UsedMethods, dependancies.ReadFields, dependancies.WrittenFields);

                        methodData[method] = modifyData;
                        modified.AddLast(method);
                    }
                    dependancies.UsedMethods.Clear();
                }
            }
        }
Пример #15
0
        public static void Apply(AAProgram ast, FinalTransformations finalTrans)
        {
            //Build list of file dependacies
            Phase1 phase1 = new Phase1(finalTrans);

            ast.Apply(phase1);
            var dependancies = phase1.dependancies;

            if (dependancies.Keys.Count == 0)
            {
                return;
            }
            AASourceFile root = Util.GetAncestor <AASourceFile>(finalTrans.mainEntry) ??
                                dependancies.Keys.FirstOrDefault(file => !file.GetName().Text.Contains("\\")) ??
                                dependancies.Keys.First(file => true);

            //Remove files unreachable from root
            //On second thought, dont. there might be static refferences the other way which needs to be included

            /*{
             *  List<AASourceFile> reachable = GetReachable(root, dependancies);
             *  AASourceFile[] keys = new AASourceFile[dependancies.Count];
             *  dependancies.Keys.CopyTo(keys, 0);
             *  foreach (AASourceFile key in keys)
             *  {
             *      if (!reachable.Contains(key))
             *          dependancies.Remove(key);
             *  }
             * }*/


            //Push common depancies up

            /*
             * root -> (item1 -> (item3), item2 -> (item4 -> (item3)))
             *
             * root -> (item3, item1, item2 -> (item4))
             */

            //Add unreachable to the root
            while (true)
            {
                List <AASourceFile> reachable = new List <AASourceFile>();
                GetReachable(root, dependancies, ref reachable);
                if (reachable.Count == dependancies.Count + (reachable.Contains(null) ? 1 : 0))
                {
                    break;
                }
                AASourceFile[] keys = new AASourceFile[dependancies.Count];
                dependancies.Keys.CopyTo(keys, 0);
                foreach (AASourceFile key in keys)
                {
                    if (!reachable.Contains(key))
                    {
                        AASourceFile k = key;
                        //See if you can find another unreachable file which need this file
                        Dictionary <AASourceFile, int> decendantCounts = new Dictionary <AASourceFile, int>();
                        decendantCounts.Add(k, CountDecendants(k, dependancies, new List <AASourceFile>()));
                        while (true)
                        {
                            AASourceFile file = null;
                            foreach (KeyValuePair <AASourceFile, List <AASourceFile> > dependancy in dependancies)
                            {
                                if (decendantCounts.ContainsKey(dependancy.Key))
                                {
                                    continue;
                                }
                                if (!dependancy.Value.Contains(k))
                                {
                                    continue;
                                }
                                file = dependancy.Key;
                                break;
                            }

                            //AASourceFile file = dependancies.FirstOrDefault(item => item.Value.Contains(k)).Key;
                            if (file == null)
                            {
                                break;
                            }
                            decendantCounts.Add(file, CountDecendants(file, dependancies, new List <AASourceFile>()));
                            k = file;
                        }
                        foreach (KeyValuePair <AASourceFile, int> decendantItem in decendantCounts)
                        {
                            if (decendantItem.Value > decendantCounts[k])
                            {
                                k = decendantItem.Key;
                            }
                        }

                        dependancies[root].Add(k);
                        break;
                    }
                }
            }
            //It is moved down here because cycles are not removed in unreachable
            RemoveCycles(root, dependancies, new List <AASourceFile> {
                root
            });


            //Convert to tree to make it easier
            List <Item> allItems        = new List <Item>();
            IncludeItem rootIncludeItem = MakeTree(root, dependancies, allItems, null);

            bool[] removed = new bool[allItems.Count];
            for (int i = 0; i < removed.Length; i++)
            {
                removed[i] = false;
            }
            int removedCount = 0;

            //Ensure that each include is only included one place
            for (int i = 0; i < allItems.Count; i++)
            {
                if (removed[i])
                {
                    continue;
                }

                IncludeItem item1 = (IncludeItem)allItems[i];
                for (int j = i + 1; j < allItems.Count; j++)
                {
                    if (removed[j])
                    {
                        continue;
                    }
                    IncludeItem item2 = (IncludeItem)allItems[j];

                    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 = Math.Min(path1[k - 1].Children.IndexOf(path1[k]),
                                                        path2[k - 1].Children.IndexOf(path2[k]));


                                item1.Parent.Children.Remove(item1);
                                LinkedList <IncludeItem> toRemove = new LinkedList <IncludeItem>();
                                toRemove.AddLast(item2);
                                while (toRemove.Count > 0)
                                {
                                    IncludeItem item = toRemove.First.Value;
                                    toRemove.RemoveFirst();
                                    item.Parent.Children.Remove(item);
                                    //allItems.Remove(item);
                                    removedCount++;
                                    removed[item.ListIndex] = true;
                                    foreach (IncludeItem child in item.Children)
                                    {
                                        toRemove.AddLast(child);
                                    }
                                }
                                //j--;



                                path1[k - 1].Children.Insert(insertAt, item1);
                                item1.Parent = path1[k - 1];



                                break;
                            }
                        }
                    }
                }
            }

            List <Item> newAllItems = new List <Item>(allItems.Count - removedCount);

            for (int i = 0; i < allItems.Count; i++)
            {
                if (!removed[i])
                {
                    newAllItems.Add(allItems[i]);
                }
            }
            allItems = newAllItems;

            //Move the null node to nr [0]
            foreach (IncludeItem item in allItems)
            {
                if (item.Current == null)
                {
                    int  itemIndex = item.Parent.Children.IndexOf(item);
                    Item item0     = item.Parent.Children[0];
                    item.Parent.Children[0]         = item;
                    item.Parent.Children[itemIndex] = item0;
                    break;
                }
            }

            //Insert method decls and move structs & fields up as needed
            ast.Apply(new Phase2(finalTrans, allItems));

            //Insert the headers in the files

            if (Options.Compiler.OneOutputFile)
            {
                //for (int i = 0; i < allItems.Count; i++)
                int i = 0;
                while (allItems.Count > 0)
                {
                    if (allItems[i] is IncludeItem)
                    {
                        IncludeItem includeItem = (IncludeItem)allItems[i];
                        //Dont want the standard lib
                        if (includeItem.Current == null)
                        {
                            i++;
                            continue;
                        }
                        //If it has children with children, then pick another first
                        if (includeItem.Children.Any(child => child.Children.Count > 0))
                        {
                            i++;
                            continue;
                        }
                        if (includeItem.Children.Count == 0)
                        {
                            if (includeItem.Parent == null)
                            {
                                break;
                            }
                            i++;
                            continue;
                        }
                        i = 0;
                        //Put all children into this
                        while (includeItem.Children.Count > 0)
                        {
                            int childNr = includeItem.Children.Count - 1;
                            allItems.Remove(includeItem.Children[childNr]);
                            if (includeItem.Children[childNr] is FieldItem)
                            {
                                FieldItem aItem = (FieldItem)includeItem.Children[childNr];
                                Node      node  = aItem.FieldDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is StructItem)
                            {
                                StructItem aItem = (StructItem)includeItem.Children[childNr];
                                Node       node  = aItem.StructDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is MethodDeclItem)
                            {
                                MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[childNr];
                                AMethodDecl    aNode = new AMethodDecl();
                                if (aItem.RealDecl.GetStatic() != null)
                                {
                                    aNode.SetStatic(new TStatic("static"));
                                }
                                aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                                aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                                foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                                {
                                    AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                    aNode.GetFormals().Add(clone);
                                }
                                includeItem.Current.GetDecl().Insert(0, aNode);
                            }
                            else if (includeItem.Children[childNr] is IncludeItem)
                            {
                                IncludeItem aChild = (IncludeItem)includeItem.Children[childNr];
                                if (aChild.Current == null)
                                {
                                    AIncludeDecl node = new AIncludeDecl(new TInclude("include"),
                                                                         new TStringLiteral("\"TriggerLibs/NativeLib\""));
                                    includeItem.Current.GetDecl().Insert(0, node);
                                }
                                else
                                {
                                    PDecl[] decls = new PDecl[aChild.Current.GetDecl().Count];
                                    aChild.Current.GetDecl().CopyTo(decls, 0);
                                    for (int k = decls.Length - 1; k >= 0; k--)
                                    {
                                        includeItem.Current.GetDecl().Insert(0, decls[k]);
                                    }
                                    aChild.Current.Parent().RemoveChild(aChild.Current);
                                    //i = -1;
                                }
                            }
                            includeItem.Children.RemoveAt(childNr);
                        }
                    }
                }
            }
            else
            {
                foreach (IncludeItem includeItem in allItems.OfType <IncludeItem>())
                {
                    for (int i = includeItem.Children.Count - 1; i >= 0; i--)
                    {
                        Node node;
                        if (includeItem.Children[i] is IncludeItem)
                        {
                            IncludeItem aItem = (IncludeItem)includeItem.Children[i];
                            node = new AIncludeDecl(new TInclude("include"),
                                                    new TStringLiteral("\"" + (aItem.Current == null ? "TriggerLibs/NativeLib" : aItem.Current.GetName().Text.Replace("\\", "/")) + "\""));
                            if (aItem.Current == null && finalTrans.mainEntry != null)
                            {
                                //Search for user defined initlib
                                bool foundInvoke = false;
                                foreach (ASimpleInvokeExp invokeExp in finalTrans.data.SimpleMethodLinks.Keys)
                                {
                                    if (invokeExp.GetName().Text == "libNtve_InitLib" && invokeExp.GetArgs().Count == 0)
                                    {
                                        /*finalTrans.errors.Add(new ErrorCollection.Error(invokeExp.GetName(),
                                         *                                              Util.GetAncestor<AASourceFile>(
                                         *                                                  invokeExp),
                                         *                                              "You are invoking libNtve_InitLib() yourself somewhere. It will not be auto inserted.",
                                         *                                              true));*/
                                        foundInvoke = true;
                                        break;
                                    }
                                }

                                if (!foundInvoke)
                                {
                                    //Init the lib
                                    ASimpleInvokeExp initExp = new ASimpleInvokeExp();
                                    initExp.SetName(new TIdentifier("libNtve_InitLib"));
                                    finalTrans.data.ExpTypes[initExp] = new AVoidType(new TVoid("void"));
                                    foreach (AMethodDecl method in finalTrans.data.Libraries.Methods)
                                    {
                                        if (method.GetName().Text == "libNtve_InitLib" && method.GetFormals().Count == 0)
                                        {
                                            finalTrans.data.SimpleMethodLinks[initExp] = method;
                                        }
                                    }
                                    AABlock block = (AABlock)finalTrans.mainEntry.GetBlock();
                                    block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), initExp));
                                }
                            }
                        }
                        else if (includeItem.Children[i] is FieldItem)
                        {
                            FieldItem aItem = (FieldItem)includeItem.Children[i];
                            node = aItem.FieldDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is StructItem)
                        {
                            StructItem aItem = (StructItem)includeItem.Children[i];
                            node = aItem.StructDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is MethodDeclItem)
                        {
                            MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[i];
                            AMethodDecl    aNode = new AMethodDecl();
                            if (aItem.RealDecl.GetStatic() != null)
                            {
                                aNode.SetStatic(new TStatic("static"));
                            }
                            aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                            aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                            foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                            {
                                AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                aNode.GetFormals().Add(clone);
                            }
                            node = aNode;
                        }
                        else
                        {
                            throw new Exception("FixIncludes.Apply: Unexpected item type");
                        }

                        includeItem.Current.GetDecl().Insert(0, node);
                    }
                }
            }
        }
Пример #16
0
 public static void Parse(AAProgram ast, ErrorCollection errors, SharedData data, DirectoryInfo outputDir)
 {
     ast.Apply(new CodeGeneration(errors, data, outputDir));
 }
Пример #17
0
        public static List <IList> GetVisibleDecls(Node node, bool includeUsings)
        {
            List <IList>          returner          = new List <IList>();
            AASourceFile          currentSourceFile = GetAncestor <AASourceFile>(node);
            List <List <string> > usedNamespaces    = new List <List <string> >();

            if (includeUsings)
            {
                foreach (AUsingDecl usingDecl in currentSourceFile.GetUsings())
                {
                    List <string> ns = new List <string>();
                    foreach (TIdentifier identifier in usingDecl.GetNamespace())
                    {
                        ns.Add(identifier.Text);
                    }
                    // ns.Reverse();
                    usedNamespaces.Add(ns);
                }
            }
            {
                List <string> currentNS = GetFullNamespace(node);
                if (currentNS.Count > 0)
                {
                    usedNamespaces.Add(currentNS);
                }
            }
            List <IList> currentList = new List <IList>();
            List <IList> nextList    = new List <IList>();
            AAProgram    program     = GetAncestor <AAProgram>(currentSourceFile);

            foreach (AASourceFile sourceFile in program.GetSourceFiles())
            {
                currentList.Add(sourceFile.GetDecl());
                returner.Add(sourceFile.GetDecl());
            }
            while (currentList.Count > 0)
            {
                foreach (IList declList in currentList)
                {
                    foreach (PDecl decl in declList)
                    {
                        if (decl is ANamespaceDecl)
                        {
                            ANamespaceDecl aDecl  = (ANamespaceDecl)decl;
                            List <string>  ns     = GetFullNamespace(decl);
                            bool           prefix = false;
                            bool           match  = false;
                            foreach (List <string> usedNamespace in usedNamespaces)
                            {
                                if (NamespacePrefix(ns, usedNamespace))
                                {
                                    prefix = true;
                                    if (NamespacesEquals(ns, usedNamespace))
                                    {
                                        match = true;
                                        break;
                                    }
                                }
                            }
                            if (prefix)
                            {
                                nextList.Add(aDecl.GetDecl());
                            }
                            if (match)
                            {
                                returner.Add(aDecl.GetDecl());
                            }
                        }
                    }
                }
                currentList = nextList;
                nextList    = new List <IList>();
            }
            return(returner);
        }
Пример #18
0
 public override void InAAProgram(AAProgram node)
 {
     LocalChecker.CalculateMethodModify(node, data, out methodCount);
 }
        public override void OutAAProgram(AAProgram node)
        {
            if (!processStructs)
            {
                if (!processFieldsOnly)
                {
                    unusedMethods.RemoveAll(method => method.GetTrigger() != null);

                    if (finalTrans.mainEntry != null)
                    {
                        unusedMethods.Remove(finalTrans.mainEntry);
                    }
                    if (finalTrans.data.DeobfuscateMethod != null)
                    {
                        unusedMethods.Remove(finalTrans.data.DeobfuscateMethod);
                    }
                    foreach (AMethodDecl unusedMethod in unusedMethods)
                    {
                        if (firstMethodRun && finalTrans.data.UserMethods.Contains(unusedMethod))
                        {
                            children.Add(new ErrorCollection.Error(unusedMethod.GetName(),
                                                                   Util.GetAncestor <AASourceFile>(unusedMethod),
                                                                   LocRM.GetString("ErrorText219") + unusedMethod.GetName().Text, true));
                        }
                        if (Options.Compiler.RemoveUnusedMethods)
                        {
                            unusedMethod.Parent().RemoveChild(unusedMethod);
                        }
                    }
                    firstMethodRun = false;
                    if (Options.Compiler.RemoveUnusedMethods)
                    {
                        finalTrans.data.Methods.RemoveAll(declItem => unusedMethods.Contains(declItem.Decl));
                        if (unusedMethods.Count > 0)
                        {
                            //We removed a method. this may cause other methods to be unused
                            processMethodsOnly = true;
                            unusedMethods.Clear();
                            unusedMethods.AddRange(finalTrans.data.Methods.Select((declItem) => declItem.Decl));
                            base.CaseAAProgram(node);
                            return;
                        }
                    }
                    unusedMethods.Clear();
                    processMethodsOnly = false;
                }
                if (!processFieldsOnly)
                {
                    fieldsWithMethodCalls.Clear();
                    usedFields.Clear();
                    processFieldsOnly = true;
                    base.CaseAAProgram(node);
                    return;
                }

                usedFields.AddRange(finalTrans.data.ObfuscationFields);
                List <SharedData.DeclItem <AFieldDecl> > removedFields = new List <SharedData.DeclItem <AFieldDecl> >();
                foreach (SharedData.DeclItem <AFieldDecl> declItem in finalTrans.data.Fields)
                {
                    AFieldDecl fieldDecl = declItem.Decl;
                    if (fieldDecl.GetConst() == null && !usedFields.Contains(fieldDecl))
                    {
                        if (!reportedFields.Contains(declItem.Decl))
                        {
                            if (firstFieldRun && finalTrans.data.UserFields.Contains(fieldDecl))
                            {
                                children.Add(new ErrorCollection.Error(fieldDecl.GetName(),
                                                                       Util.GetAncestor <AASourceFile>(fieldDecl),
                                                                       LocRM.GetString("ErrorText65") + fieldDecl.GetName().Text, true));
                            }
                            reportedFields.Add(declItem.Decl);
                        }
                        if (Options.Compiler.RemoveUnusedFields || (fieldDecl.GetType() is AArrayTempType && ((AArrayTempType)fieldDecl.GetType()).GetIntDim().Text == "0"))
                        {
                            //We cannot remove it if there is a method call in it
                            if (fieldsWithMethodCalls.Contains(fieldDecl))
                            {
                                continue;
                            }

                            //Remove assignments to the field
                            foreach (AAssignmentExp assignmentExp in assignedToFields[fieldDecl])
                            {
                                if (assignmentExp.Parent() is AExpStm)
                                {
                                    AExpStm stm = (AExpStm)assignmentExp.Parent();
                                    RemoveVariableStatement(stm, assignmentExp.GetExp(), stm.GetToken().Line,
                                                            stm.GetToken().Pos);

                                    continue;
                                }
                                PExp exp = assignmentExp.GetExp();
                                assignmentExp.ReplaceBy(exp);
                            }
                            removedFields.Add(declItem);
                            fieldDecl.Parent().RemoveChild(fieldDecl);
                        }
                    }
                }
                firstFieldRun = false;
                foreach (var removedField in removedFields)
                {
                    finalTrans.data.Fields.Remove(removedField);
                }

                /* if (Options.Compiler.RemoveUnusedFields)
                 *   finalTrans.data.Fields.RemoveAll(
                 *       declItem =>
                 *       (!usedFields.Contains(declItem.Decl)) && (!fieldsWithMethodCalls.Contains(declItem.Decl)));*/
                if (removedFields.Count > 0)
                {
                    //Other fields may have become unused
                    fieldsWithMethodCalls.Clear();
                    usedFields.Clear();
                    processFieldsOnly = true;
                    base.CaseAAProgram(node);
                    return;
                }
                //Remove empty arrays from struct fields
                foreach (var pair in finalTrans.data.StructFields)
                {
                    for (int i = 0; i < pair.Value.Count; i++)
                    {
                        AALocalDecl field = pair.Value[i];
                        if (field.GetType() is AArrayTempType && ((AArrayTempType)field.GetType()).GetIntDim().Text == "0")
                        {
                            field.Parent().RemoveChild(field);
                            pair.Value.RemoveAt(i);
                            --i;
                        }
                    }
                }
            }
            //Remove unused structs
            processFieldsOnly = false;
            if (!processStructs)
            {
                processStructs = true;
                base.CaseAAProgram(node);
                return;
            }
            foreach (SharedData.DeclItem <AStructDecl> declItem in finalTrans.data.Structs)
            {
                if (!usedStructs.Contains(declItem.Decl))
                {
                    if (firstStructRun)
                    {
                        children.Add(new ErrorCollection.Error(declItem.Decl.GetName(),
                                                               Util.GetAncestor <AASourceFile>(declItem.Decl),
                                                               LocRM.GetString("ErrorText64") + declItem.Decl.GetName().Text, true));
                    }

                    if (Options.Compiler.RemoveUnusedStructs)
                    {
                        if (declItem.Decl != null && declItem.Decl.Parent() != null)
                        {
                            declItem.Decl.Parent().RemoveChild(declItem.Decl);
                        }
                    }
                }
            }
            if (Options.Compiler.RemoveUnusedStructs)
            {
                finalTrans.data.Structs.RemoveAll(declItem => !usedStructs.Contains(declItem.Decl));
            }


            if (children.Count > 0)
            {
                finalTrans.errors.Add(new ErrorCollection.Error(children[0], LocRM.GetString("ErrorText66"), children.ToArray()));
            }
        }
        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"));
            }
        }
Пример #21
0
        public static void Parse(AAProgram ast, FinalTransformations finalTrans)
        {
            bool restart = true;

            while (restart)
            {
                restart = false;
                //Fix locals
                ast.Apply(new MakeUniqueNames(finalTrans));

                //Fix methods
                foreach (SharedData.DeclItem <AMethodDecl> declItem1 in finalTrans.data.Methods)
                {
                    AMethodDecl decl1 = declItem1.Decl;
                    if (decl1.GetName().Text.StartsWith("_"))
                    {
                        decl1.GetName().Text = "u" + decl1.GetName().Text;
                        restart = true;
                        break;
                    }
                    //Other methods
                    foreach (SharedData.DeclItem <AMethodDecl> declItem2 in finalTrans.data.Methods)
                    {
                        AMethodDecl decl2 = declItem2.Decl;
                        if (decl1 != decl2 && decl1.GetName().Text == decl2.GetName().Text)
                        {
                            decl1.GetName().Text += "1";
                            decl2.GetName().Text += "2";
                            restart = true;
                            break;
                        }
                    }
                    if (restart)
                    {
                        break;
                    }

                    //Fields
                    foreach (SharedData.DeclItem <AFieldDecl> declItem2 in finalTrans.data.Fields)
                    {
                        AFieldDecl decl2 = declItem2.Decl;
                        if (decl1.GetName().Text == decl2.GetName().Text)
                        {
                            decl1.GetName().Text += "M";
                            decl2.GetName().Text += "F";
                            restart = true;
                            break;
                        }
                    }
                    if (restart)
                    {
                        break;
                    }


                    //structs
                    foreach (SharedData.DeclItem <AStructDecl> declItem2 in finalTrans.data.Structs)
                    {
                        AStructDecl decl2 = declItem2.Decl;
                        if (decl1.GetName().Text == decl2.GetName().Text)
                        {
                            decl1.GetName().Text += "M";
                            decl2.GetName().Text += "S";
                            restart = true;
                            break;
                        }
                    }
                    if (restart)
                    {
                        break;
                    }
                }
                if (restart)
                {
                    continue;
                }


                //Fix fields
                foreach (SharedData.DeclItem <AFieldDecl> declItem1 in finalTrans.data.Fields)
                {
                    AFieldDecl decl1 = declItem1.Decl;
                    if (decl1.GetName().Text.StartsWith("_"))
                    {
                        decl1.GetName().Text = "u" + decl1.GetName().Text;
                        restart = true;
                        break;
                    }
                    //Other fields
                    foreach (SharedData.DeclItem <AFieldDecl> declItem2 in finalTrans.data.Fields)
                    {
                        AFieldDecl decl2 = declItem2.Decl;
                        if (decl1 != decl2 && decl1.GetName().Text == decl2.GetName().Text)
                        {
                            decl1.GetName().Text += "1";
                            decl2.GetName().Text += "2";
                            restart = true;
                            break;
                        }
                    }
                    if (restart)
                    {
                        break;
                    }


                    //structs
                    foreach (SharedData.DeclItem <AStructDecl> declItem2 in finalTrans.data.Structs)
                    {
                        AStructDecl decl2 = declItem2.Decl;
                        if (decl1.GetName().Text == decl2.GetName().Text)
                        {
                            decl1.GetName().Text += "F";
                            decl2.GetName().Text += "S";
                            restart = true;
                            break;
                        }
                    }
                    if (restart)
                    {
                        break;
                    }
                }
                if (restart)
                {
                    continue;
                }


                //Fix structs
                foreach (SharedData.DeclItem <AStructDecl> declItem1 in finalTrans.data.Structs)
                {
                    AStructDecl decl1 = declItem1.Decl;
                    if (decl1.GetName().Text.StartsWith("_"))
                    {
                        decl1.GetName().Text = "u" + decl1.GetName().Text;
                        restart = true;
                        break;
                    }
                    //Other fields
                    foreach (SharedData.DeclItem <AStructDecl> declItem2 in finalTrans.data.Structs)
                    {
                        AStructDecl decl2 = declItem2.Decl;
                        if (decl1 != decl2 && decl1.GetName().Text == decl2.GetName().Text)
                        {
                            decl1.GetName().Text += "1";
                            decl2.GetName().Text += "2";
                            restart = true;
                            break;
                        }
                    }
                    if (restart)
                    {
                        break;
                    }
                }
                if (restart)
                {
                    continue;
                }
            }
        }
Пример #22
0
        public override void OutAAProgram(AAProgram node)
        {
            foreach (var pair in Refferences)
            {
                if (structsWithGenerics.Contains(pair.Key) && pair.Value.Count > 0)
                {
                    needAnotherPass = true;
                }
            }
            foreach (var pair in Refferences)
            {
                AStructDecl str = pair.Key;
                if (!copies.ContainsKey(str))
                {
                    copies[str] = new List <List <PType> >();
                }
                IList declList;
                Node  parent = str.Parent();
                if (parent is AASourceFile)
                {
                    declList = ((AASourceFile)parent).GetDecl();
                }
                else
                {
                    declList = ((ANamespaceDecl)parent).GetDecl();
                }
                //AASourceFile pFile = (AASourceFile) str.Parent();
                foreach (AGenericType refference in pair.Value)
                {
                    AStructDecl clone   = null;
                    bool        addList = true;
                    foreach (List <PType> list in copies[str])
                    {
                        bool listEqual = true;
                        for (int i = 0; i < list.Count; i++)
                        {
                            if (!Util.TypesEqual(list[i], (PType)refference.GetGenericTypes()[i], data))
                            {
                                listEqual = false;
                                break;
                            }
                        }
                        if (listEqual)
                        {
                            addList = false;
                            clone   = clones[list];
                            break;
                        }
                    }
                    if (addList)
                    {
                        List <PType> list = new List <PType>();
                        foreach (PType type in refference.GetGenericTypes())
                        {
                            list.Add(type);
                        }
                        copies[str].Add(list);

                        clone = (AStructDecl)str.Clone();
                        declList.Insert(declList.IndexOf(str), clone);


                        clone.Apply(new EnviromentBuilding(errors, data));
                        clone.Apply(new EnviromentChecking(errors, data, false));
                        clone.Apply(new LinkNamedTypes(errors, data));

                        /*
                         * data.Structs.Add(new SharedData.DeclItem<AStructDecl>(pFile, clone));
                         * data.StructFields[clone] = new List<AALocalDecl>();
                         * data.StructMethods[clone] = new List<AMethodDecl>();
                         * data.StructProperties[clone] = new List<APropertyDecl>();
                         * data.StructConstructors[clone] = new List<AConstructorDecl>();
                         * foreach (PLocalDecl localDecl in clone.GetLocals())
                         * {
                         *  if (localDecl is AALocalDecl)
                         *  {
                         *      data.StructFields[clone].Add((AALocalDecl)localDecl);
                         *  }
                         *  else
                         *  {
                         *      PDecl decl = ((ADeclLocalDecl) localDecl).GetDecl();
                         *      if (decl is AMethodDecl)
                         *      {
                         *          data.StructMethods[clone].Add((AMethodDecl) decl);
                         *      }
                         *      else if (decl is APropertyDecl)
                         *      {
                         *          data.StructProperties[clone].Add((APropertyDecl)decl);
                         *      }
                         *      else
                         *      {
                         *          data.StructConstructors[clone].Add((AConstructorDecl) decl);
                         *      }
                         *  }
                         * }*/

                        clones[list] = clone;


                        clone.setGenericVars(new ArrayList());

                        FixGenericLinks.Parse(str, clone, list, data);
                        clone.GetName().Text = Util.TypeToIdentifierString(refference);
                    }
                    //Change refference to clone
                    ANamedType    baseRef = (ANamedType)refference.GetBase();
                    List <string> cloneNs = Util.GetFullNamespace(clone);
                    cloneNs.Add(clone.GetName().Text);
                    AAName aName = (AAName)baseRef.GetName();
                    aName.GetIdentifier().Clear();
                    foreach (var n in cloneNs)
                    {
                        aName.GetIdentifier().Add(new TIdentifier(n));
                    }
                    data.StructTypeLinks[baseRef] = clone;
                    refference.ReplaceBy(baseRef);
                }

                if (!needAnotherPass)
                {
                    parent.RemoveChild(str);
                }
            }
            if (needAnotherPass)
            {
                Refferences.Clear();
                structsWithGenerics.Clear();
                needAnotherPass = false;
                CaseAAProgram(node);
            }
        }
Пример #23
0
 public static void Parse(AAProgram ast, ErrorCollection errors, SharedData data)
 {
     ast.Apply(new EnviromentBuilding(errors, data));
 }
Пример #24
0
        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"));
            }
        }
Пример #25
0
        public override void OutAAProgram(AAProgram node)
        {
            List <IDecl> decls = new List <IDecl>(this.decls.Count);

            decls.AddRange(this.decls);
            bool changes;

            do
            {
                decls.Sort(Compare);
                changes = false;


                for (int i = 0; i < decls.Count; i++)
                {
                    int j = i + 1;
                    for (; j < decls.Count; j++)
                    {
                        if (Compare(decls[i], decls[j]) != 0)
                        {
                            break;
                        }
                    }
                    if (j - i > 1)
                    {//The same from i to j-1
                        bool sameType = true;
                        for (int k = i + 1; k < j; k++)
                        {
                            if (decls[i].GetType() != decls[k].GetType())
                            {
                                //We have diffrent types. Add letter
                                sameType = false;
                                for (k = i; k < j; k++)
                                {
                                    decls[k].AddStandardLetter();
                                }
                                break;
                            }
                        }
                        //Now, add numbers if they are still the same
                        if (sameType)
                        {
                            for (int k = i; k < j; k++)
                            {
                                decls[k].Name += k - i + 1;
                            }
                        }
                        i       = j - 1;
                        changes = true;
                    }
                }
            } while (changes);


            List <IDecl> localDecls = new List <IDecl>(this.localDecls.Count);

            localDecls.AddRange(this.localDecls);
            do
            {
                localDecls.Sort(Compare);
                changes = false;


                for (int i = 0; i < localDecls.Count; i++)
                {
                    int j = i + 1;
                    for (; j < localDecls.Count; j++)
                    {
                        if (Compare(localDecls[i], localDecls[j]) != 0)
                        {
                            break;
                        }
                    }
                    if (j - i > 1)
                    {//The same from i to j-1
                        bool sameType = true;
                        for (int k = i + 1; k < j; k++)
                        {
                            if (localDecls[i].GetType() != localDecls[k].GetType())
                            {
                                //We have diffrent types. Add letter
                                sameType = false;
                                for (k = i; k < j; k++)
                                {
                                    localDecls[k].AddStandardLetter();
                                }
                                break;
                            }
                        }
                        //Now, add numbers if they are still the same
                        if (sameType)
                        {
                            for (int k = i; k < j; k++)
                            {
                                localDecls[k].Name += k - i + 1;
                            }
                        }
                        i       = j - 1;
                        changes = true;
                    }
                }
            } while (changes);
        }
Пример #26
0
 public LibraryData(AAProgram program, StreamWriter writer)
 {
     this.writer = writer;
     program.Apply(this);
 }