Пример #1
0
 public CloneMethod(FinalTransformations finalTrans, Dictionary <AALocalDecl, PLvalue> localMap, Dictionary <AALocalDecl, PExp> localExpMap, Node currentCloneNode)
 {
     this.finalTrans       = finalTrans;
     this.localMap         = localMap;
     this.localExpMap      = localExpMap;
     this.currentCloneNode = currentCloneNode;
 }
 public RemoveUnusedVariables(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
     unusedMethods.AddRange(finalTrans.data.Methods.Select((declItem) => declItem.Decl));
     foreach (SharedData.DeclItem <AFieldDecl> declItem in finalTrans.data.Fields)
     {
         assignedToFields[declItem.Decl] = new List <AAssignmentExp>();
     }
 }
 public RemoveUnusedVariables(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
     unusedMethods.AddRange(finalTrans.data.Methods.Select((declItem) => declItem.Decl));
     foreach (SharedData.DeclItem<AFieldDecl> declItem in finalTrans.data.Fields)
     {
         assignedToFields[declItem.Decl] = new List<AAssignmentExp>();
     }
 }
 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";
 }
Пример #5
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";
            }
        }
Пример #6
0
        public static void Parse(FinalTransformations finalTrans)
        {
            SharedData data = finalTrans.data;

            for (int i = 0; i < data.Methods.Count; i++)
            {
                for (int j = i + 1; j < data.Methods.Count; j++)
                {
                    AMethodDecl m1       = data.Methods[i].Decl;
                    AMethodDecl m2       = data.Methods[j].Decl;
                    bool        switched = false;
                    if (finalTrans.mainEntry == m1 || m1.GetTrigger() != null)
                    {
                        if (finalTrans.mainEntry == m2 || m2.GetTrigger() != null)
                        {
                            continue;
                        }
                    }
                    else if (finalTrans.mainEntry == m2 || m2.GetTrigger() != null)
                    {
                        AMethodDecl temp = m1;
                        m1       = m2;
                        m2       = temp;
                        switched = true;
                    }

                    MergeSameMethods merger = new MergeSameMethods(m2, data);
                    m1.Apply(merger);
                    if (merger.canMerge)
                    {
                        merger.otherNode = m1;
                        m2.Apply(merger);
                        if (merger.canMerge)
                        {
                            var arr = data.SimpleMethodLinks.ToArray();
                            foreach (KeyValuePair <ASimpleInvokeExp, AMethodDecl> link in arr)
                            {
                                if (link.Value == m2)
                                {
                                    data.SimpleMethodLinks[link.Key] = m1;
                                    link.Key.SetName(new TIdentifier(m1.GetName().Text));
                                }
                            }


                            m2.Parent().RemoveChild(m2);
                            if (switched)
                            {
                                data.Methods.RemoveAt(i);
                                i--;
                                break;
                            }
                            else
                            {
                                data.Methods.RemoveAt(j);
                                j--;
                                continue;
                            }
                        }
                    }
                }
            }
        }
Пример #7
0
 public AssignFixup(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #8
0
 public Delegates(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
 public Phase1(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #10
0
 public Phase1(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #11
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);
                    }
                }
            }
        }
 public MarkShortMethodsAsInline(FinalTransformations finalTrans, bool inlineConstructors)
 {
     this.finalTrans = finalTrans;
     this.inlineConstructors = inlineConstructors;
 }
 public CloneMethod(FinalTransformations finalTrans, Dictionary<AALocalDecl, PLvalue> localMap, Dictionary<AALocalDecl, PExp> localExpMap, Node currentCloneNode)
 {
     this.finalTrans = finalTrans;
     this.localMap = localMap;
     this.localExpMap = localExpMap;
     this.currentCloneNode = currentCloneNode;
 }
        public static List<AABlock> Inline(ASimpleInvokeExp node, FinalTransformations finalTrans)
        {
            /*if (Util.GetAncestor<AMethodDecl>(node) != null && Util.GetAncestor<AMethodDecl>(node).GetName().Text == "UIChatFrame_LeaveChannel")
                node = node;*/

            SharedData data = finalTrans.data;
            //If this node is inside the condition of a while, replace it with a new local var,
            //make a clone before the while, one before each continue in the while, and one at the end of the while
            //(unless the end is a return or break)
            AABlock pBlock;
            if (Util.HasAncestor<AWhileStm>(node))
            {
                AWhileStm whileStm = Util.GetAncestor<AWhileStm>(node);
                if (Util.IsAncestor(node, whileStm.GetCondition()))
                {
                    List<ASimpleInvokeExp> toInline = new List<ASimpleInvokeExp>();
                    //Above while
                    AALocalDecl replaceVarDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                                 Util.MakeClone(data.ExpTypes[node], data),
                                                                 new TIdentifier("whileVar"), null);
                    ALocalLvalue replaceVarRef = new ALocalLvalue(new TIdentifier("whileVar"));
                    ALvalueExp replaceVarRefExp = new ALvalueExp(replaceVarRef);
                    data.LocalLinks[replaceVarRef] = replaceVarDecl;
                    data.ExpTypes[replaceVarRefExp] = data.LvalueTypes[replaceVarRef] = replaceVarDecl.GetType();
                    node.ReplaceBy(replaceVarRefExp);
                    replaceVarDecl.SetInit(node);
                    pBlock = (AABlock) whileStm.Parent();
                    pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(whileStm), new ALocalDeclStm(new TSemicolon(";"), replaceVarDecl));
                    toInline.Add(node);

                    //In the end of the while
                    PStm lastStm = whileStm.GetBody();
                    while (lastStm is ABlockStm)
                    {
                        AABlock block = (AABlock) ((ABlockStm) lastStm).GetBlock();
                        if (block.GetStatements().Count == 0)
                        {
                            lastStm = null;
                            break;
                        }
                        lastStm = (PStm) block.GetStatements()[block.GetStatements().Count - 1];
                    }
                    if (lastStm == null || !(lastStm is AValueReturnStm || lastStm is AVoidReturnStm || lastStm is ABreakStm))
                    {
                        lastStm = whileStm.GetBody();
                        AABlock block;
                        if (lastStm is ABlockStm)
                        {
                            block = (AABlock)((ABlockStm)lastStm).GetBlock();
                        }
                        else
                        {
                            block = new AABlock(new ArrayList(), new TRBrace("}"));
                            block.GetStatements().Add(lastStm);
                            whileStm.SetBody(new ABlockStm(new TLBrace("{"), block));
                        }

                        replaceVarRef = new ALocalLvalue(new TIdentifier("whileVar"));
                        ASimpleInvokeExp clone = (ASimpleInvokeExp)Util.MakeClone(node, data);
                        toInline.Add(clone);
                        AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), replaceVarRef, clone);
                        data.LocalLinks[replaceVarRef] = replaceVarDecl;
                        data.ExpTypes[assignment] = data.LvalueTypes[replaceVarRef] = replaceVarDecl.GetType();
                        block.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment));
                    }

                    //After each continue
                    CloneBeforeContinue cloner = new CloneBeforeContinue(node, replaceVarDecl, data);
                    whileStm.GetBody().Apply(cloner);
                    toInline.AddRange(cloner.replacementExpressions);
                    List<AABlock> visitBlocks = new List<AABlock>();
                    foreach (ASimpleInvokeExp invoke in toInline)
                    {
                        visitBlocks.AddRange(Inline(invoke, finalTrans));
                    }
                    return visitBlocks;
                }
            }

            AMethodDecl decl = finalTrans.data.SimpleMethodLinks[node];
            FindAssignedToFormals assignedToFormalsFinder = new FindAssignedToFormals(finalTrans.data);
            decl.Apply(assignedToFormalsFinder);
            List<AALocalDecl> assignedToFormals = assignedToFormalsFinder.AssignedFormals;

            /*
                 * inline int foo(int a)
                 * {
                 *      int b = 2;
                 *      int c;
                 *      ...
                 *      while(...)
                 *      {
                 *          ...
                 *          break;
                 *          ...
                 *          return c;
                 *      }
                 *      ...
                 *      return 2;
                 * }
                 *
                 * bar(foo(<arg for a>));
                 * ->
                 *
                 * {
                 *      bool inlineMethodReturned = false;
                 *      int inlineReturner;
                 *      int a = <arg for a>;
                 *      while (!inlineMethodReturned)
                 *      {
                 *          int b = 2;
                 *          int c;
                 *          ...
                 *          while(...)
                 *          {
                 *              ...
                 *              break
                 *              ...
                 *              inlineReturner = c;
                 *              inlineMethodReturned = true;
                 *              break;
                 *          }
                 *          if (inlineMethodReturned)
                 *          {
                 *              break;
                 *          }
                 *          ...
                 *          inlineReturner = 2;
                 *          inlineMethodReturned = true;
                 *          break;
                 *          break;
                 *      }
                 *      bar(inlineReturner);
                 * }
                 *
                 *
                 */

            AABlock outerBlock = new AABlock();
            PExp exp = new ABooleanConstExp(new AFalseBool());
            finalTrans.data.ExpTypes[exp] = new ANamedType(new TIdentifier("bool"), null);
            AALocalDecl hasMethodReturnedVar = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("bool"), null),
                                                               new TIdentifier("hasInlineReturned"), exp);
            finalTrans.data.GeneratedVariables.Add(hasMethodReturnedVar);
            PStm stm = new ALocalDeclStm(new TSemicolon(";"), hasMethodReturnedVar);
            outerBlock.GetStatements().Add(stm);

            AALocalDecl methodReturnerVar = null;
            if (!(decl.GetReturnType() is AVoidType))
            {
                methodReturnerVar = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(decl.GetReturnType(), finalTrans.data),
                                                       new TIdentifier("inlineReturner"), null);
                stm = new ALocalDeclStm(new TSemicolon(";"), methodReturnerVar);
                outerBlock.GetStatements().Add(stm);
            }

            AABlock afterBlock = new AABlock();

            //A dictionary from the formals of the inline method to a cloneable replacement lvalue
            Dictionary<AALocalDecl, PLvalue> Parameters = new Dictionary<AALocalDecl, PLvalue>();
            Dictionary<AALocalDecl, PExp> ParameterExps = new Dictionary<AALocalDecl, PExp>();
            for (int i = 0; i < decl.GetFormals().Count; i++)
            {
                AALocalDecl formal = (AALocalDecl)decl.GetFormals()[i];
                PExp arg = (PExp)node.GetArgs()[0];
                PLvalue lvalue;
                //if ref, dont make a new var
                if (formal.GetRef() != null && arg is ALvalueExp)
                {
                    arg.Apply(new MoveMethodDeclsOut("inlineVar", finalTrans.data));
                    arg.Parent().RemoveChild(arg);
                    lvalue = ((ALvalueExp) arg).GetLvalue();

                }
                else if (!assignedToFormals.Contains(formal) && Util.IsLocal(arg, finalTrans.data))
                {
                    lvalue = new ALocalLvalue(new TIdentifier("I hope I dont make it"));
                    finalTrans.data.LvalueTypes[lvalue] = formal.GetType();
                    finalTrans.data.LocalLinks[(ALocalLvalue) lvalue] = formal;
                    ParameterExps[formal] = arg;
                    arg.Parent().RemoveChild(arg);
                }
                else
                {
                    AAssignmentExp assExp = null;
                    if (formal.GetOut() != null)
                    {
                        //Dont initialize with arg, but assign arg after
                        arg.Apply(new MoveMethodDeclsOut("inlineVar", finalTrans.data));
                        lvalue = ((ALvalueExp)arg).GetLvalue();
                        assExp = new AAssignmentExp(new TAssign("="), lvalue, null);
                        finalTrans.data.ExpTypes[assExp] = finalTrans.data.LvalueTypes[lvalue];
                        arg.Parent().RemoveChild(arg);
                        arg = null;
                    }
                    AALocalDecl parameter = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data),
                                                            new TIdentifier(formal.GetName().Text),
                                                            arg);
                    stm = new ALocalDeclStm(new TSemicolon(";"), parameter);
                    outerBlock.GetStatements().Add(stm);

                    lvalue = new ALocalLvalue(new TIdentifier(parameter.GetName().Text));
                    finalTrans.data.LvalueTypes[lvalue] = parameter.GetType();
                    finalTrans.data.LocalLinks[(ALocalLvalue)lvalue] = parameter;

                    if (formal.GetOut() != null)
                    {
                        //Dont initialize with arg, but assign arg after
                        ALvalueExp lvalueExp = new ALvalueExp(Util.MakeClone(lvalue, finalTrans.data));
                        finalTrans.data.ExpTypes[lvalueExp] = finalTrans.data.LvalueTypes[lvalue];
                        assExp.SetExp(lvalueExp);
                        afterBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assExp));
                    }
                }
                Parameters.Add(formal, lvalue);
            }

            AABlock innerBlock = (AABlock)decl.GetBlock().Clone();
            exp = new ABooleanConstExp(new ATrueBool());
            finalTrans.data.ExpTypes[exp] = new ANamedType(new TIdentifier("bool"), null);
            ABlockStm innerBlockStm = new ABlockStm(new TLBrace("{"), innerBlock);

            bool needWhile = CheckIfWhilesIsNeeded.IsWhileNeeded(decl.GetBlock());
            if (needWhile)
                stm = new AWhileStm(new TLParen("("), exp, innerBlockStm);
            else
                stm = innerBlockStm;
            outerBlock.GetStatements().Add(stm);

            outerBlock.GetStatements().Add(new ABlockStm(new TLBrace("{"), afterBlock));

            //Clone method contents to inner block.
            CloneMethod cloneFixer = new CloneMethod(finalTrans, Parameters, ParameterExps, innerBlockStm);
            decl.GetBlock().Apply(cloneFixer);
            foreach (KeyValuePair<PLvalue, PExp> pair in cloneFixer.ReplaceUsAfter)
            {
                PLvalue lvalue = pair.Key;
                PExp replacement =  Util.MakeClone(pair.Value, finalTrans.data);
                ALvalueExp lvalueParent = (ALvalueExp) lvalue.Parent();
                lvalueParent.ReplaceBy(replacement);
            }
            innerBlockStm.Apply(new FixTypes(finalTrans.data));

            innerBlock.Apply(new FixReturnsAndWhiles(hasMethodReturnedVar, methodReturnerVar, finalTrans.data, needWhile));

            GetNonBlockStm stmFinder = new GetNonBlockStm(false);
            innerBlock.Apply(stmFinder);
            if (needWhile && (stmFinder.Stm == null || !(stmFinder.Stm is ABreakStm)))
                innerBlock.GetStatements().Add(new ABreakStm(new TBreak("break")));

            //Insert before current statement
            ABlockStm outerBlockStm = new ABlockStm(new TLBrace("{"), outerBlock);

            PStm pStm = Util.GetAncestor<PStm>(node);

            pBlock = (AABlock)pStm.Parent();

            pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm), outerBlockStm);

            if (node.Parent() == pStm && pStm is AExpStm)
            {
                pBlock.RemoveChild(pStm);
            }
            else
            {
                PLvalue lvalue = new ALocalLvalue(new TIdentifier(methodReturnerVar.GetName().Text));
                finalTrans.data.LvalueTypes[lvalue] = methodReturnerVar.GetType();
                finalTrans.data.LocalLinks[(ALocalLvalue)lvalue] = methodReturnerVar;
                exp = new ALvalueExp(lvalue);
                finalTrans.data.ExpTypes[exp] = methodReturnerVar.GetType();

                node.ReplaceBy(exp);
            }
            return new List<AABlock>() { outerBlock };
        }
 public FixInlineMethods(FinalTransformations finalTrans, bool inlineConstructors)
 {
     this.finalTrans = finalTrans;
     this.inlineConstructors = inlineConstructors;
 }
Пример #16
0
        public static List <AABlock> Inline(ASimpleInvokeExp node, FinalTransformations finalTrans)
        {
            /*if (Util.GetAncestor<AMethodDecl>(node) != null && Util.GetAncestor<AMethodDecl>(node).GetName().Text == "UIChatFrame_LeaveChannel")
             *  node = node;*/

            SharedData data = finalTrans.data;
            //If this node is inside the condition of a while, replace it with a new local var,
            //make a clone before the while, one before each continue in the while, and one at the end of the while
            //(unless the end is a return or break)
            AABlock pBlock;

            if (Util.HasAncestor <AWhileStm>(node))
            {
                AWhileStm whileStm = Util.GetAncestor <AWhileStm>(node);
                if (Util.IsAncestor(node, whileStm.GetCondition()))
                {
                    List <ASimpleInvokeExp> toInline = new List <ASimpleInvokeExp>();
                    //Above while
                    AALocalDecl replaceVarDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                                 Util.MakeClone(data.ExpTypes[node], data),
                                                                 new TIdentifier("whileVar"), null);
                    ALocalLvalue replaceVarRef    = new ALocalLvalue(new TIdentifier("whileVar"));
                    ALvalueExp   replaceVarRefExp = new ALvalueExp(replaceVarRef);
                    data.LocalLinks[replaceVarRef]  = replaceVarDecl;
                    data.ExpTypes[replaceVarRefExp] = data.LvalueTypes[replaceVarRef] = replaceVarDecl.GetType();
                    node.ReplaceBy(replaceVarRefExp);
                    replaceVarDecl.SetInit(node);
                    pBlock = (AABlock)whileStm.Parent();
                    pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(whileStm), new ALocalDeclStm(new TSemicolon(";"), replaceVarDecl));
                    toInline.Add(node);


                    //In the end of the while
                    PStm lastStm = whileStm.GetBody();
                    while (lastStm is ABlockStm)
                    {
                        AABlock block = (AABlock)((ABlockStm)lastStm).GetBlock();
                        if (block.GetStatements().Count == 0)
                        {
                            lastStm = null;
                            break;
                        }
                        lastStm = (PStm)block.GetStatements()[block.GetStatements().Count - 1];
                    }
                    if (lastStm == null || !(lastStm is AValueReturnStm || lastStm is AVoidReturnStm || lastStm is ABreakStm))
                    {
                        lastStm = whileStm.GetBody();
                        AABlock block;
                        if (lastStm is ABlockStm)
                        {
                            block = (AABlock)((ABlockStm)lastStm).GetBlock();
                        }
                        else
                        {
                            block = new AABlock(new ArrayList(), new TRBrace("}"));
                            block.GetStatements().Add(lastStm);
                            whileStm.SetBody(new ABlockStm(new TLBrace("{"), block));
                        }

                        replaceVarRef = new ALocalLvalue(new TIdentifier("whileVar"));
                        ASimpleInvokeExp clone = (ASimpleInvokeExp)Util.MakeClone(node, data);
                        toInline.Add(clone);
                        AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), replaceVarRef, clone);
                        data.LocalLinks[replaceVarRef] = replaceVarDecl;
                        data.ExpTypes[assignment]      = data.LvalueTypes[replaceVarRef] = replaceVarDecl.GetType();
                        block.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment));
                    }

                    //After each continue
                    CloneBeforeContinue cloner = new CloneBeforeContinue(node, replaceVarDecl, data);
                    whileStm.GetBody().Apply(cloner);
                    toInline.AddRange(cloner.replacementExpressions);
                    List <AABlock> visitBlocks = new List <AABlock>();
                    foreach (ASimpleInvokeExp invoke in toInline)
                    {
                        visitBlocks.AddRange(Inline(invoke, finalTrans));
                    }
                    return(visitBlocks);
                }
            }



            AMethodDecl           decl = finalTrans.data.SimpleMethodLinks[node];
            FindAssignedToFormals assignedToFormalsFinder = new FindAssignedToFormals(finalTrans.data);

            decl.Apply(assignedToFormalsFinder);
            List <AALocalDecl> assignedToFormals = assignedToFormalsFinder.AssignedFormals;


            /*
             * inline int foo(int a)
             * {
             *      int b = 2;
             *      int c;
             *      ...
             *      while(...)
             *      {
             *          ...
             *          break;
             *          ...
             *          return c;
             *      }
             *      ...
             *      return 2;
             * }
             *
             * bar(foo(<arg for a>));
             * ->
             *
             * {
             *      bool inlineMethodReturned = false;
             *      int inlineReturner;
             *      int a = <arg for a>;
             *      while (!inlineMethodReturned)
             *      {
             *          int b = 2;
             *          int c;
             *          ...
             *          while(...)
             *          {
             *              ...
             *              break
             *              ...
             *              inlineReturner = c;
             *              inlineMethodReturned = true;
             *              break;
             *          }
             *          if (inlineMethodReturned)
             *          {
             *              break;
             *          }
             *          ...
             *          inlineReturner = 2;
             *          inlineMethodReturned = true;
             *          break;
             *          break;
             *      }
             *      bar(inlineReturner);
             * }
             *
             *
             */


            AABlock outerBlock = new AABlock();
            PExp    exp        = new ABooleanConstExp(new AFalseBool());

            finalTrans.data.ExpTypes[exp] = new ANamedType(new TIdentifier("bool"), null);
            AALocalDecl hasMethodReturnedVar = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("bool"), null),
                                                               new TIdentifier("hasInlineReturned"), exp);

            finalTrans.data.GeneratedVariables.Add(hasMethodReturnedVar);
            PStm stm = new ALocalDeclStm(new TSemicolon(";"), hasMethodReturnedVar);

            outerBlock.GetStatements().Add(stm);

            AALocalDecl methodReturnerVar = null;

            if (!(decl.GetReturnType() is AVoidType))
            {
                methodReturnerVar = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(decl.GetReturnType(), finalTrans.data),
                                                    new TIdentifier("inlineReturner"), null);
                stm = new ALocalDeclStm(new TSemicolon(";"), methodReturnerVar);
                outerBlock.GetStatements().Add(stm);
            }

            AABlock afterBlock = new AABlock();

            //A dictionary from the formals of the inline method to a cloneable replacement lvalue
            Dictionary <AALocalDecl, PLvalue> Parameters    = new Dictionary <AALocalDecl, PLvalue>();
            Dictionary <AALocalDecl, PExp>    ParameterExps = new Dictionary <AALocalDecl, PExp>();

            for (int i = 0; i < decl.GetFormals().Count; i++)
            {
                AALocalDecl formal = (AALocalDecl)decl.GetFormals()[i];
                PExp        arg    = (PExp)node.GetArgs()[0];
                PLvalue     lvalue;
                //if ref, dont make a new var
                if (formal.GetRef() != null && arg is ALvalueExp)
                {
                    arg.Apply(new MoveMethodDeclsOut("inlineVar", finalTrans.data));
                    arg.Parent().RemoveChild(arg);
                    lvalue = ((ALvalueExp)arg).GetLvalue();
                }
                else if (!assignedToFormals.Contains(formal) && Util.IsLocal(arg, finalTrans.data))
                {
                    lvalue = new ALocalLvalue(new TIdentifier("I hope I dont make it"));
                    finalTrans.data.LvalueTypes[lvalue] = formal.GetType();
                    finalTrans.data.LocalLinks[(ALocalLvalue)lvalue] = formal;
                    ParameterExps[formal] = arg;
                    arg.Parent().RemoveChild(arg);
                }
                else
                {
                    AAssignmentExp assExp = null;
                    if (formal.GetOut() != null)
                    {
                        //Dont initialize with arg, but assign arg after
                        arg.Apply(new MoveMethodDeclsOut("inlineVar", finalTrans.data));
                        lvalue = ((ALvalueExp)arg).GetLvalue();
                        assExp = new AAssignmentExp(new TAssign("="), lvalue, null);
                        finalTrans.data.ExpTypes[assExp] = finalTrans.data.LvalueTypes[lvalue];
                        arg.Parent().RemoveChild(arg);
                        arg = null;
                    }
                    AALocalDecl parameter = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data),
                                                            new TIdentifier(formal.GetName().Text),
                                                            arg);
                    stm = new ALocalDeclStm(new TSemicolon(";"), parameter);
                    outerBlock.GetStatements().Add(stm);

                    lvalue = new ALocalLvalue(new TIdentifier(parameter.GetName().Text));
                    finalTrans.data.LvalueTypes[lvalue] = parameter.GetType();
                    finalTrans.data.LocalLinks[(ALocalLvalue)lvalue] = parameter;


                    if (formal.GetOut() != null)
                    {
                        //Dont initialize with arg, but assign arg after
                        ALvalueExp lvalueExp = new ALvalueExp(Util.MakeClone(lvalue, finalTrans.data));
                        finalTrans.data.ExpTypes[lvalueExp] = finalTrans.data.LvalueTypes[lvalue];
                        assExp.SetExp(lvalueExp);
                        afterBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assExp));
                    }
                }
                Parameters.Add(formal, lvalue);
            }

            AABlock innerBlock = (AABlock)decl.GetBlock().Clone();

            exp = new ABooleanConstExp(new ATrueBool());
            finalTrans.data.ExpTypes[exp] = new ANamedType(new TIdentifier("bool"), null);
            ABlockStm innerBlockStm = new ABlockStm(new TLBrace("{"), innerBlock);

            bool needWhile = CheckIfWhilesIsNeeded.IsWhileNeeded(decl.GetBlock());

            if (needWhile)
            {
                stm = new AWhileStm(new TLParen("("), exp, innerBlockStm);
            }
            else
            {
                stm = innerBlockStm;
            }
            outerBlock.GetStatements().Add(stm);

            outerBlock.GetStatements().Add(new ABlockStm(new TLBrace("{"), afterBlock));

            //Clone method contents to inner block.
            CloneMethod cloneFixer = new CloneMethod(finalTrans, Parameters, ParameterExps, innerBlockStm);

            decl.GetBlock().Apply(cloneFixer);
            foreach (KeyValuePair <PLvalue, PExp> pair in cloneFixer.ReplaceUsAfter)
            {
                PLvalue    lvalue       = pair.Key;
                PExp       replacement  = Util.MakeClone(pair.Value, finalTrans.data);
                ALvalueExp lvalueParent = (ALvalueExp)lvalue.Parent();
                lvalueParent.ReplaceBy(replacement);
            }
            innerBlockStm.Apply(new FixTypes(finalTrans.data));

            innerBlock.Apply(new FixReturnsAndWhiles(hasMethodReturnedVar, methodReturnerVar, finalTrans.data, needWhile));

            GetNonBlockStm stmFinder = new GetNonBlockStm(false);

            innerBlock.Apply(stmFinder);
            if (needWhile && (stmFinder.Stm == null || !(stmFinder.Stm is ABreakStm)))
            {
                innerBlock.GetStatements().Add(new ABreakStm(new TBreak("break")));
            }

            //Insert before current statement
            ABlockStm outerBlockStm = new ABlockStm(new TLBrace("{"), outerBlock);

            PStm pStm = Util.GetAncestor <PStm>(node);

            pBlock = (AABlock)pStm.Parent();

            pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm), outerBlockStm);

            if (node.Parent() == pStm && pStm is AExpStm)
            {
                pBlock.RemoveChild(pStm);
            }
            else
            {
                PLvalue lvalue = new ALocalLvalue(new TIdentifier(methodReturnerVar.GetName().Text));
                finalTrans.data.LvalueTypes[lvalue] = methodReturnerVar.GetType();
                finalTrans.data.LocalLinks[(ALocalLvalue)lvalue] = methodReturnerVar;
                exp = new ALvalueExp(lvalue);
                finalTrans.data.ExpTypes[exp] = methodReturnerVar.GetType();

                node.ReplaceBy(exp);
            }
            return(new List <AABlock>()
            {
                outerBlock
            });
        }
Пример #17
0
 public MarkShortMethodsAsInline(FinalTransformations finalTrans, bool inlineConstructors)
 {
     this.finalTrans         = finalTrans;
     this.inlineConstructors = inlineConstructors;
 }
Пример #18
0
 public Phase2(FinalTransformations finalTrans, List <Item> allItems)
 {
     this.finalTrans = finalTrans;
     this.allItems   = allItems;
 }
 public MainEntryFinder(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
 public StructInitializer(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
 public ObfuscateStrings(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
 public TransformMethodDecls(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #23
0
 public MainEntryFinder(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
 public TransformMethodDecls(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #25
0
 public RemoveEmptyStructs(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
            /*
             * Apply after assignement fixup
             * Assume no i++
             *
             * Convert usages to method invocations.
             */
            public static void Parse(FinalTransformations finalTrans)
            {
                SharedData data = finalTrans.data;

                foreach (KeyValuePair<APropertyLvalue, APropertyDecl> pair in data.PropertyLinks)
                {
                    APropertyLvalue lvalue = pair.Key;
                    APropertyDecl property = pair.Value;

                    if (Util.GetAncestor<AAProgram>(lvalue) == null)
                        continue;

                    if (lvalue.Parent() is AAssignmentExp)
                    {
                        AAssignmentExp assignment = (AAssignmentExp) lvalue.Parent();
                        ASimpleInvokeExp invoke =
                            new ASimpleInvokeExp(
                                new TIdentifier("Set" + property.GetName().Text, lvalue.GetName().Line,
                                                lvalue.GetName().Pos), new ArrayList(){assignment.GetExp()});
                        assignment.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Setters[property];
                        data.ExpTypes[invoke] = new AVoidType(new TVoid("void"));
                    }
                    else
                    {
                        ALvalueExp exp = (ALvalueExp) lvalue.Parent();
                        ASimpleInvokeExp invoke =
                            new ASimpleInvokeExp(
                                new TIdentifier("Get" + property.GetName().Text, lvalue.GetName().Line,
                                                lvalue.GetName().Pos), new ArrayList() {});
                        exp.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Getters[property];
                        data.ExpTypes[invoke] = property.GetType();
                    }
                }
                foreach (KeyValuePair<AStructLvalue, APropertyDecl> pair in data.StructPropertyLinks)
                {
                    AStructLvalue lvalue = pair.Key;
                    APropertyDecl property = pair.Value;
                    AEnrichmentDecl enrichmentDecl = null;
                    AStructDecl structDecl = null;
                    if (data.EnrichmentTypeLinks.ContainsKey(data.ExpTypes[lvalue.GetReceiver()]))
                        enrichmentDecl = data.EnrichmentTypeLinks[data.ExpTypes[lvalue.GetReceiver()]];
                    if (enrichmentDecl == null)
                        structDecl = data.StructTypeLinks[(ANamedType)data.ExpTypes[lvalue.GetReceiver()]];

                    if (Util.GetAncestor<AAProgram>(lvalue) == null)
                        continue;

                    PExp structArg;
                    if (structDecl == null || structDecl.GetClassToken() == null)
                    {
                        structArg = lvalue.GetReceiver();
                    }
                    else
                    {
                        //Send pointer
                        ALvalueExp lvalueExp = (ALvalueExp) lvalue.GetReceiver();
                        APointerLvalue pointerValue = (APointerLvalue) lvalueExp.GetLvalue();
                        structArg = pointerValue.GetBase();
                    }

                    if (lvalue.Parent() is AAssignmentExp)
                    {
                        AAssignmentExp assignment = (AAssignmentExp)lvalue.Parent();
                        ASimpleInvokeExp invoke =
                            new ASimpleInvokeExp(
                                new TIdentifier("Set" + property.GetName().Text, lvalue.GetName().Line,
                                                lvalue.GetName().Pos), new ArrayList() { assignment.GetExp(), structArg });
                        assignment.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Setters[property];
                        data.ExpTypes[invoke] = new AVoidType(new TVoid("void"));
                    }
                    else
                    {
                        ALvalueExp exp = (ALvalueExp)lvalue.Parent();
                        ASimpleInvokeExp invoke =
                            new ASimpleInvokeExp(
                                new TIdentifier("Get" + property.GetName().Text, lvalue.GetName().Line,
                                                lvalue.GetName().Pos), new ArrayList() { structArg });
                        exp.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Getters[property];
                        data.ExpTypes[invoke] = property.GetType();
                    }
                }
                foreach (KeyValuePair<AArrayLvalue, Util.Pair<APropertyDecl, bool>> pair in data.ArrayPropertyLinks)
                {
                    AArrayLvalue lvalue = pair.Key;
                    APropertyDecl property = pair.Value.First;
                    bool implicitMatch = pair.Value.Second;
                    AEnrichmentDecl enrichmentDecl = null;
                    AStructDecl structDecl = null;

                    if (OldEnrichmentParents.ContainsKey(property))
                        enrichmentDecl = OldEnrichmentParents[property];
                    else
                        structDecl = OldStructParents[property];
                    if (Util.GetAncestor<AAProgram>(lvalue) == null)
                        continue;

                    PExp structArg;
                    if (structDecl == null || structDecl.GetClassToken() == null)
                    {
                        structArg = lvalue.GetBase();
                    }
                    else
                    {
                        //Send pointer
                        if (implicitMatch)
                            structArg = lvalue.GetBase();
                        else
                        {
                            ALvalueExp lvalueExp = (ALvalueExp) lvalue.GetBase();
                            APointerLvalue pointerValue = (APointerLvalue) lvalueExp.GetLvalue();
                            structArg = pointerValue.GetBase();
                        }
                    }

                  /*  if (!(structArg is ALvalueExp &&
                        (((ALvalueExp)structArg).GetLvalue() is ALocalLvalue || ((ALvalueExp)structArg).GetLvalue() is AFieldLvalue ||
                        ((ALvalueExp)structArg).GetLvalue() is AStructLvalue || ((ALvalueExp)structArg).GetLvalue() is AStructFieldLvalue))
                    {
                        //Make new local
                        AALocalDecl decl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                           Util.MakeClone(data.ExpTypes[structArg], data),
                                                           new TIdentifier("propertyVar"), structArg);
                        ALocalLvalue declRef = new ALocalLvalue(new TIdentifier("propertyVar"));
                        structArg = new ALvalueExp(declRef);
                        PStm stm = Util.GetAncestor<PStm>(lvalue);
                    }*/

                    if (lvalue.Parent() is AAssignmentExp)
                    {
                        AAssignmentExp assignment = (AAssignmentExp)lvalue.Parent();
                        ASimpleInvokeExp invoke =
                            new ASimpleInvokeExp(
                                new TIdentifier("SetThis", lvalue.GetToken().Line,
                                                lvalue.GetToken().Pos), new ArrayList() { lvalue.GetIndex() ,assignment.GetExp(), structArg });
                        assignment.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Setters[property];
                        data.ExpTypes[invoke] = new AVoidType(new TVoid("void"));
                    }
                    else
                    {
                        ALvalueExp exp = (ALvalueExp)lvalue.Parent();
                        ASimpleInvokeExp invoke =
                            new ASimpleInvokeExp(
                                new TIdentifier("GetThis", lvalue.GetToken().Line,
                                                lvalue.GetToken().Pos), new ArrayList() {  lvalue.GetIndex(), structArg });
                        exp.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Getters[property];
                        data.ExpTypes[invoke] = property.GetType();
                    }
                }
            }
 public RemoveEmptyStructs(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
            /*
             * 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);
                    }
                }
            }
Пример #29
0
 public MakeShortNames(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #30
0
 public AssignFixup(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #31
0
 public FixInlineMethods(FinalTransformations finalTrans, bool inlineConstructors)
 {
     this.finalTrans         = finalTrans;
     this.inlineConstructors = inlineConstructors;
 }
 public LivenessAnalysis(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #33
0
 public Delegates(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #34
0
            /*
             * Apply after assignement fixup
             * Assume no i++
             *
             * Convert usages to method invocations.
             */

            public static void Parse(FinalTransformations finalTrans)
            {
                SharedData data = finalTrans.data;

                foreach (KeyValuePair <APropertyLvalue, APropertyDecl> pair in data.PropertyLinks)
                {
                    APropertyLvalue lvalue   = pair.Key;
                    APropertyDecl   property = pair.Value;

                    if (Util.GetAncestor <AAProgram>(lvalue) == null)
                    {
                        continue;
                    }

                    if (lvalue.Parent() is AAssignmentExp)
                    {
                        AAssignmentExp   assignment = (AAssignmentExp)lvalue.Parent();
                        ASimpleInvokeExp invoke     =
                            new ASimpleInvokeExp(
                                new TIdentifier("Set" + property.GetName().Text, lvalue.GetName().Line,
                                                lvalue.GetName().Pos), new ArrayList()
                        {
                            assignment.GetExp()
                        });
                        assignment.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Setters[property];
                        data.ExpTypes[invoke]          = new AVoidType(new TVoid("void"));
                    }
                    else
                    {
                        ALvalueExp       exp    = (ALvalueExp)lvalue.Parent();
                        ASimpleInvokeExp invoke =
                            new ASimpleInvokeExp(
                                new TIdentifier("Get" + property.GetName().Text, lvalue.GetName().Line,
                                                lvalue.GetName().Pos), new ArrayList()
                        {
                        });
                        exp.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Getters[property];
                        data.ExpTypes[invoke]          = property.GetType();
                    }
                }
                foreach (KeyValuePair <AStructLvalue, APropertyDecl> pair in data.StructPropertyLinks)
                {
                    AStructLvalue   lvalue         = pair.Key;
                    APropertyDecl   property       = pair.Value;
                    AEnrichmentDecl enrichmentDecl = null;
                    AStructDecl     structDecl     = null;
                    if (data.EnrichmentTypeLinks.ContainsKey(data.ExpTypes[lvalue.GetReceiver()]))
                    {
                        enrichmentDecl = data.EnrichmentTypeLinks[data.ExpTypes[lvalue.GetReceiver()]];
                    }
                    if (enrichmentDecl == null)
                    {
                        structDecl = data.StructTypeLinks[(ANamedType)data.ExpTypes[lvalue.GetReceiver()]];
                    }

                    if (Util.GetAncestor <AAProgram>(lvalue) == null)
                    {
                        continue;
                    }

                    PExp structArg;
                    if (structDecl == null || structDecl.GetClassToken() == null)
                    {
                        structArg = lvalue.GetReceiver();
                    }
                    else
                    {
                        //Send pointer
                        ALvalueExp     lvalueExp    = (ALvalueExp)lvalue.GetReceiver();
                        APointerLvalue pointerValue = (APointerLvalue)lvalueExp.GetLvalue();
                        structArg = pointerValue.GetBase();
                    }

                    if (lvalue.Parent() is AAssignmentExp)
                    {
                        AAssignmentExp   assignment = (AAssignmentExp)lvalue.Parent();
                        ASimpleInvokeExp invoke     =
                            new ASimpleInvokeExp(
                                new TIdentifier("Set" + property.GetName().Text, lvalue.GetName().Line,
                                                lvalue.GetName().Pos), new ArrayList()
                        {
                            assignment.GetExp(), structArg
                        });
                        assignment.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Setters[property];
                        data.ExpTypes[invoke]          = new AVoidType(new TVoid("void"));
                    }
                    else
                    {
                        ALvalueExp       exp    = (ALvalueExp)lvalue.Parent();
                        ASimpleInvokeExp invoke =
                            new ASimpleInvokeExp(
                                new TIdentifier("Get" + property.GetName().Text, lvalue.GetName().Line,
                                                lvalue.GetName().Pos), new ArrayList()
                        {
                            structArg
                        });
                        exp.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Getters[property];
                        data.ExpTypes[invoke]          = property.GetType();
                    }
                }
                foreach (KeyValuePair <AArrayLvalue, Util.Pair <APropertyDecl, bool> > pair in data.ArrayPropertyLinks)
                {
                    AArrayLvalue    lvalue         = pair.Key;
                    APropertyDecl   property       = pair.Value.First;
                    bool            implicitMatch  = pair.Value.Second;
                    AEnrichmentDecl enrichmentDecl = null;
                    AStructDecl     structDecl     = null;

                    if (OldEnrichmentParents.ContainsKey(property))
                    {
                        enrichmentDecl = OldEnrichmentParents[property];
                    }
                    else
                    {
                        structDecl = OldStructParents[property];
                    }
                    if (Util.GetAncestor <AAProgram>(lvalue) == null)
                    {
                        continue;
                    }

                    PExp structArg;
                    if (structDecl == null || structDecl.GetClassToken() == null)
                    {
                        structArg = lvalue.GetBase();
                    }
                    else
                    {
                        //Send pointer
                        if (implicitMatch)
                        {
                            structArg = lvalue.GetBase();
                        }
                        else
                        {
                            ALvalueExp     lvalueExp    = (ALvalueExp)lvalue.GetBase();
                            APointerLvalue pointerValue = (APointerLvalue)lvalueExp.GetLvalue();
                            structArg = pointerValue.GetBase();
                        }
                    }

                    /*  if (!(structArg is ALvalueExp &&
                     *    (((ALvalueExp)structArg).GetLvalue() is ALocalLvalue || ((ALvalueExp)structArg).GetLvalue() is AFieldLvalue ||
                     *    ((ALvalueExp)structArg).GetLvalue() is AStructLvalue || ((ALvalueExp)structArg).GetLvalue() is AStructFieldLvalue))
                     * {
                     *    //Make new local
                     *    AALocalDecl decl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                     *                                       Util.MakeClone(data.ExpTypes[structArg], data),
                     *                                       new TIdentifier("propertyVar"), structArg);
                     *    ALocalLvalue declRef = new ALocalLvalue(new TIdentifier("propertyVar"));
                     *    structArg = new ALvalueExp(declRef);
                     *    PStm stm = Util.GetAncestor<PStm>(lvalue);
                     * }*/

                    if (lvalue.Parent() is AAssignmentExp)
                    {
                        AAssignmentExp   assignment = (AAssignmentExp)lvalue.Parent();
                        ASimpleInvokeExp invoke     =
                            new ASimpleInvokeExp(
                                new TIdentifier("SetThis", lvalue.GetToken().Line,
                                                lvalue.GetToken().Pos), new ArrayList()
                        {
                            lvalue.GetIndex(), assignment.GetExp(), structArg
                        });
                        assignment.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Setters[property];
                        data.ExpTypes[invoke]          = new AVoidType(new TVoid("void"));
                    }
                    else
                    {
                        ALvalueExp       exp    = (ALvalueExp)lvalue.Parent();
                        ASimpleInvokeExp invoke =
                            new ASimpleInvokeExp(
                                new TIdentifier("GetThis", lvalue.GetToken().Line,
                                                lvalue.GetToken().Pos), new ArrayList()
                        {
                            lvalue.GetIndex(), structArg
                        });
                        exp.ReplaceBy(invoke);
                        data.SimpleMethodLinks[invoke] = data.Getters[property];
                        data.ExpTypes[invoke]          = property.GetType();
                    }
                }
            }
Пример #35
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);
                    }
                }
        }
Пример #36
0
            /*
             * 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);
                    }
                }
            }
Пример #37
0
 public Phase2(FinalTransformations finalTrans, List<Item> allItems)
 {
     this.finalTrans = finalTrans;
     this.allItems = allItems;
 }
Пример #38
0
 private MakeUniqueNames(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
 public RenameRefferences(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #40
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;
                }
            }
        }
Пример #41
0
 public StructInitializer(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
 public MakeShortNames(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
Пример #43
0
 public RenameRefferences(FinalTransformations finalTrans)
 {
     this.finalTrans = finalTrans;
 }
        public static void Parse(FinalTransformations finalTrans)
        {
            SharedData data = finalTrans.data;
            for (int i = 0; i< data.Methods.Count; i++)
            {
                for (int j = i + 1; j < data.Methods.Count; j++)
                {
                    AMethodDecl m1 = data.Methods[i].Decl;
                    AMethodDecl m2 = data.Methods[j].Decl;
                    bool switched = false;
                    if (finalTrans.mainEntry == m1 || m1.GetTrigger() != null)
                    {
                        if (finalTrans.mainEntry == m2 || m2.GetTrigger() != null)
                        {
                            continue;
                        }
                    }
                    else if (finalTrans.mainEntry == m2 || m2.GetTrigger() != null)
                    {
                        AMethodDecl temp = m1;
                        m1 = m2;
                        m2 = temp;
                        switched = true;
                    }

                    MergeSameMethods merger = new MergeSameMethods(m2, data);
                    m1.Apply(merger);
                    if (merger.canMerge)
                    {
                        merger.otherNode = m1;
                        m2.Apply(merger);
                        if (merger.canMerge)
                        {
                            var arr = data.SimpleMethodLinks.ToArray();
                            foreach (KeyValuePair<ASimpleInvokeExp, AMethodDecl> link in arr)
                            {
                                if (link.Value == m2)
                                {
                                    data.SimpleMethodLinks[link.Key] = m1;
                                    link.Key.SetName(new TIdentifier(m1.GetName().Text));
                                }
                            }

                            m2.Parent().RemoveChild(m2);
                            if (switched)
                            {
                                data.Methods.RemoveAt(i);
                                i--;
                                break;
                            }
                            else
                            {
                                data.Methods.RemoveAt(j);
                                j--;
                                continue;
                            }
                        }
                    }
                }
            }
        }