Example #1
0
        public override void CaseAMethodDecl(AMethodDecl node)
        {
            Write("\n");
            if (node.GetStatic() != null)
            {
                Write("static ");
            }
            if (node.GetNative() != null)
            {
                Write("native ");
            }
            node.GetReturnType().Apply(this);
            Write(" " + node.GetName().Text + "(");
            bool first = true;

            foreach (AALocalDecl formal in node.GetFormals())
            {
                if (!first)
                {
                    Write(", ");
                }
                formal.Apply(this);
                first = false;
            }
            if (node.GetBlock() != null)
            {
                Write(")\n");
                node.GetBlock().Apply(this);
            }
            else
            {
                Write(");\n\n");
            }
        }
Example #2
0
 public override void OutAMethodDecl(AMethodDecl node)
 {
     //If void return is missing, insert it.
     if (node.GetReturnType() is AVoidType && node.GetBlock() != null)
     {
         AABlock block        = (AABlock)node.GetBlock();
         bool    insertReturn = false;
         while (true)
         {
             if (block.GetStatements().Count == 0)
             {
                 insertReturn = true;
                 break;
             }
             PStm lastStm = (PStm)block.GetStatements()[block.GetStatements().Count - 1];
             if (lastStm is AVoidReturnStm)
             {
                 break;
             }
             if (lastStm is ABlockStm)
             {
                 block = (AABlock)((ABlockStm)block.GetStatements()[block.GetStatements().Count - 1]).GetBlock();
                 continue;
             }
             insertReturn = true;
             break;
         }
         if (insertReturn)
         {
             block.GetStatements().Add(new AVoidReturnStm(new TReturn("return", block.GetToken().Line, block.GetToken().Pos)));
         }
     }
     base.OutAMethodDecl(node);
 }
Example #3
0
        /*public override void InAMethodDecl(AMethodDecl node)
         * {
         *  AABlock block = (AABlock) node.GetBlock();
         *  if (block != null)
         *  {
         *      if (!data.Locals.ContainsKey(block))
         *          data.Locals.Add(block, new List<AALocalDecl>());
         *      foreach (AALocalDecl formal in node.GetFormals())
         *      {
         *          data.Locals[block].Add(formal);
         *      }
         *  }
         * }
         *
         * public override void InAConstructorDecl(AConstructorDecl node)
         * {
         *  AABlock block = (AABlock)node.GetBlock();
         *  if (block != null)
         *  {
         *      if (!data.Locals.ContainsKey(block))
         *          data.Locals.Add(block, new List<AALocalDecl>());
         *      foreach (AALocalDecl formal in node.GetFormals())
         *      {
         *          data.Locals[block].Add(formal);
         *      }
         *  }
         * }*/

        public override void OutAMethodDecl(AMethodDecl node)
        {
            AStructDecl     parentStruct     = Util.GetAncestor <AStructDecl>(node);
            AEnrichmentDecl parentEnrichment = Util.GetAncestor <AEnrichmentDecl>(node);

            if (parentStruct != null)
            {
                //Struct method
                data.StructMethods[parentStruct].Add(node);
            }
            else if (parentEnrichment == null)
            {//Global method
                //Dont care about abstract methods - will add them later
                if (node.GetBlock() != null || node.GetNative() != null)
                {
                    data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(currentSourceFile, node));
                    data.UserMethods.Add(node);
                }
                else if (node.GetDelegate() != null)
                {
                    data.Delegates.Add(new SharedData.DeclItem <AMethodDecl>(currentSourceFile, node));
                }
                else
                {
                    node.Parent().RemoveChild(node);
                    return;
                }
            }
            base.OutAMethodDecl(node);
        }
Example #4
0
        public override void CaseALocalDeclStm(ALocalDeclStm node)
        {
            AMethodDecl pMethod = Util.GetAncestor <AMethodDecl>(node);
            AALocalDecl decl    = (AALocalDecl)node.GetLocalDecl();

            if (decl.GetInit() == null)
            {
                ALocalLvalue lvalue = new ALocalLvalue(new TIdentifier(decl.GetName().Text));
                data.LocalLinks[lvalue]  = decl;
                data.LvalueTypes[lvalue] = decl.GetType();
                List <PStm> statements = AssignDefault(lvalue);
                AABlock     pBlock     = (AABlock)node.Parent();
                foreach (PStm statement in statements)
                {
                    pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(node), statement);
                }
                pBlock.RemoveChild(node);
            }
            else
            {
                //Make an assignment expression before moving
                ALocalLvalue lvalue = new ALocalLvalue(new TIdentifier(decl.GetName().Text));
                data.LvalueTypes[lvalue] = decl.GetType();
                AAssignmentExp exp    = new AAssignmentExp(new TAssign("="), lvalue, decl.GetInit());
                AExpStm        expStm = new AExpStm(new TSemicolon(";"), exp);
                node.ReplaceBy(expStm);
                data.LvalueTypes[lvalue] = decl.GetType();
                data.ExpTypes[exp]       = decl.GetType();
                data.LocalLinks[lvalue]  = decl;
            }

            AABlock block = (AABlock)pMethod.GetBlock();

            block.GetStatements().Insert(0, node);
        }
        public static bool Parse(AMethodDecl method, SharedData data)
        {
            RemoveSelfAssignments remover = new RemoveSelfAssignments(data);

            method.GetBlock().Apply(remover);
            return(remover.changedSomething);
        }
Example #6
0
        public static ControlFlowGraph Create(AMethodDecl method)
        {
            ControlFlowGraph graph     = new ControlFlowGraph(method);
            CFGGenerator     generator = new CFGGenerator();

            method.GetBlock().Apply(generator);
            graph.Nodes = new List <Node>(generator.Nodes.Count);
            graph.Nodes.AddRange(generator.Nodes);
            return(graph);
        }
Example #7
0
            private void Analyze(AMethodDecl method)
            {
                MethodAnalyzer analyzer = new MethodAnalyzer(method, Methods, data);

                method.GetBlock().Apply(this);
                Methods[method] = analyzer.SafeData;



                /*  List of safe variables after each statement
                 *      While statements need a list for first statement in the while, and a list for first statement after the while
                 *          Also need to account for break and continue statments
                 *      If statements need a list for then then branch, and one for the else branch.
                 *
                 *  CFG:
                 *  Join(v):
                 *      First, set safeList = intersection(pred(stm))
                 *      Parse through expression, do the folloing in the order you get out of nodes
                 *          pointerLvalue: If unsafe, make a test, and restart check ///NO, its an iterative build. do this after
                 *          delete: clear safeList, safeIfTrue and safeIfFalse
                 *          p == null: if p is a pointer, add p to a safeIfTrue list
                 *          p != null: if p is a pointer, add p to a safeIfFalse list
                 *          !<exp>: swap safeIfTrue and safeIfFalse lists
                 *          <exp> || <exp>: intersection between left and right safeIfTrue list
                 *          <exp> && <exp>: intersection between left and right safeIfFalse list
                 *
                 *          if stm:         thenList = safeList U safeIfTrue
                 *                          afterList = safeList U safeIfFalse
                 *          if-else stm:    thenList = safeList U safeIfTrue
                 *                          elseList = safeList U safeIfFalse
                 *          while stm:      thenList = safeList U safeIfTrue
                 *
                 *
                 * Problem: if something is safe before a while, it currently can't become safe in the while, since it will not initially be safe at the end of the while.
                 *
                 *
                 *
                 * -------------------------------
                 *
                 * List of unsafe variables after each CFG node.
                 *
                 * Preprocess step: List of all used variables (Base: Field/Local, Others:Pointer/StructField)
                 *
                 * All those variables are unsafe before first statment
                 *
                 *
                 * Join(v):
                 *
                 *
                 */
            }
Example #8
0
        public override void CaseAMethodDecl(AMethodDecl node)
        {
            if (node.GetNative() == null && node.GetBlock() == null)
            {
                return;
            }
            if (node.GetStatic() != null)
            {
                return;
            }

            string inputStr = "native " + TypeToString(node.GetReturnType()) + " " + node.GetName().Text +
                              "(";
            bool first = true;

            foreach (AALocalDecl formal in node.GetFormals())
            {
                if (!first)
                {
                    inputStr += ", ";
                }
                inputStr += TypeToString(formal.GetType()) + " " + formal.GetName().Text;
                first     = false;
            }
            inputStr += ");";

            writer.WriteLine(inputStr);

            AStructDecl        str = Util.GetAncestor <AStructDecl>(node);
            List <AMethodDecl> methodList;

            if (str != null)
            {
                methodList = StructMethods[str];
            }
            else
            {
                methodList = Methods;
            }
            string sig = Util.GetMethodSignature(node);

            if (methodList.Any(otherMethod => Util.GetMethodSignature(otherMethod) == sig))
            {
                return;
            }

            methodList.Add(node);
            node.SetBlock(null);
            node.Parent().RemoveChild(node);
        }
Example #9
0
        public override void OutAALocalDecl(AALocalDecl node)
        {
            //Can have a local as a struct member, a parameter or a local variable
            AABlock          pBlock       = Util.GetAncestor <AABlock>(node);
            AMethodDecl      pMethod      = Util.GetAncestor <AMethodDecl>(node);
            AConstructorDecl pConstructor = Util.GetAncestor <AConstructorDecl>(node);
            AStructDecl      pStruct      = Util.GetAncestor <AStructDecl>(node);

            if (pBlock != null)
            {//We got a local variable
                data.Locals[pBlock].Add(node);
                data.UserLocals.Add(node);
            }
            else if (pMethod != null || pConstructor != null)
            {//We got a parameter
                if (pMethod != null)
                {
                    pBlock = (AABlock)pMethod.GetBlock();
                }
                else
                {
                    pBlock = (AABlock)pConstructor.GetBlock();
                }
                if (pBlock != null)
                {
                    if (!data.Locals.ContainsKey(pBlock))
                    {
                        data.Locals.Add(pBlock, new List <AALocalDecl>());
                    }
                    data.Locals[pBlock].Add(node);
                    data.UserLocals.Add(node);
                }
            }
            else
            {//We got a struct variable
                data.StructFields[pStruct].Add(node);
            }
            base.OutAALocalDecl(node);
        }
        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
            });
        }
Example #11
0
        private void MakeInitializerInvokes()
        {
            AABlock      block = (AABlock)mainEntry.GetBlock();
            AASourceFile file  = Util.GetAncestor <AASourceFile>(mainEntry);
            AMethodDecl  invokeMethod;

            /* Add
             * void Invoke(string methodName)
             * {
             *     trigger initTrigger = TriggerCreate(methodName);
             *     TriggerExecute(initTrigger, false, true);
             *     TriggerDestroy(initTrigger);
             * }
             */

            {
                //void Invoke(string methodName)
                AALocalDecl parameter = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                        new ANamedType(new TIdentifier("string"), null),
                                                        new TIdentifier("methodName"), null);
                AABlock methodBody = new AABlock();
                invokeMethod = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                               new AVoidType(new TVoid("void")), new TIdentifier("Invoke"),
                                               new ArrayList()
                {
                    parameter
                }, methodBody);

                //trigger initTrigger = TriggerCreate(methodName);
                ALocalLvalue parameterLvalue = new ALocalLvalue(new TIdentifier("methodName"));
                data.LocalLinks[parameterLvalue] = parameter;
                ALvalueExp parameterLvalueExp = new ALvalueExp(parameterLvalue);
                data.LvalueTypes[parameterLvalue]     =
                    data.ExpTypes[parameterLvalueExp] = parameter.GetType();
                ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("TriggerCreate"), new ArrayList()
                {
                    parameterLvalueExp
                });
                data.ExpTypes[invoke] = new ANamedType(new TIdentifier("trigger"), null);
                foreach (AMethodDecl methodDecl in data.Libraries.Methods)
                {
                    if (methodDecl.GetName().Text == "TriggerCreate")
                    {
                        data.SimpleMethodLinks[invoke] = methodDecl;
                        break;
                    }
                }
                AALocalDecl initTriggerDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                              new ANamedType(new TIdentifier("trigger"), null),
                                                              new TIdentifier("initTrigger"), invoke);
                methodBody.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), initTriggerDecl));

                //TriggerExecute(initTrigger, false, true);
                ALocalLvalue initTriggerLvalue = new ALocalLvalue(new TIdentifier("initTrigger"));
                data.LocalLinks[initTriggerLvalue] = initTriggerDecl;
                ALvalueExp initTriggerLvalueExp = new ALvalueExp(initTriggerLvalue);
                data.LvalueTypes[initTriggerLvalue]     =
                    data.ExpTypes[initTriggerLvalueExp] = initTriggerDecl.GetType();
                ABooleanConstExp falseBool = new ABooleanConstExp(new AFalseBool());
                ABooleanConstExp trueBool  = new ABooleanConstExp(new ATrueBool());
                data.ExpTypes[falseBool]    =
                    data.ExpTypes[trueBool] = new ANamedType(new TIdentifier("bool"), null);
                invoke = new ASimpleInvokeExp(new TIdentifier("TriggerExecute"), new ArrayList()
                {
                    initTriggerLvalueExp, falseBool, trueBool
                });
                data.ExpTypes[invoke] = new AVoidType(new TVoid("void"));
                foreach (AMethodDecl methodDecl in data.Libraries.Methods)
                {
                    if (methodDecl.GetName().Text == "TriggerExecute")
                    {
                        data.SimpleMethodLinks[invoke] = methodDecl;
                        break;
                    }
                }
                methodBody.GetStatements().Add(new AExpStm(new TSemicolon(";"), invoke));

                //TriggerDestroy(initTrigger);
                initTriggerLvalue = new ALocalLvalue(new TIdentifier("initTrigger"));
                data.LocalLinks[initTriggerLvalue] = initTriggerDecl;
                initTriggerLvalueExp = new ALvalueExp(initTriggerLvalue);
                data.LvalueTypes[initTriggerLvalue]     =
                    data.ExpTypes[initTriggerLvalueExp] = initTriggerDecl.GetType();
                invoke = new ASimpleInvokeExp(new TIdentifier("TriggerDestroy"), new ArrayList()
                {
                    initTriggerLvalueExp
                });
                data.ExpTypes[invoke] = new AVoidType(new TVoid("void"));
                foreach (AMethodDecl methodDecl in data.Libraries.Methods)
                {
                    if (methodDecl.GetName().Text == "TriggerDestroy")
                    {
                        data.SimpleMethodLinks[invoke] = methodDecl;
                        break;
                    }
                }
                methodBody.GetStatements().Add(new AExpStm(new TSemicolon(";"), invoke));

                file.GetDecl().Add(invokeMethod);
            }

            for (int i = data.InitializerMethods.Count - 1; i >= 0; i--)
            {
                AMethodDecl method = data.InitializerMethods[i];
                //Turn method into a trigger
                method.SetReturnType(new ANamedType(new TIdentifier("bool"), null));
                method.GetFormals().Add(new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                        new ANamedType(new TIdentifier("bool"), null),
                                                        new TIdentifier("testConds"), null));
                method.GetFormals().Add(new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                        new ANamedType(new TIdentifier("bool"), null),
                                                        new TIdentifier("runActions"), null));
                method.SetTrigger(new TTrigger("trigger"));
                ((AABlock)method.GetBlock()).GetStatements().Add(new AVoidReturnStm(new TReturn("return")));
                TriggerConvertReturn returnConverter = new TriggerConvertReturn(data);
                method.Apply(returnConverter);
                data.TriggerDeclarations[method] = new List <TStringLiteral>();


                //Add Invoke(<name>); to main entry
                TStringLiteral literal = new TStringLiteral(method.GetName().Text);
                data.TriggerDeclarations[method].Add(literal);
                AStringConstExp stringConst = new AStringConstExp(literal);
                data.ExpTypes[stringConst] = new ANamedType(new TIdentifier("string"), null);
                ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("Invoke"), new ArrayList()
                {
                    stringConst
                });
                data.SimpleMethodLinks[invoke] = invokeMethod;
                data.ExpTypes[invoke]          = invokeMethod.GetReturnType();
                block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), invoke));



                //ASyncInvokeExp syncInvokeExp = new ASyncInvokeExp(new TSyncInvoke("Invoke"), new AAmbiguousNameLvalue(new ASimpleName(new TIdentifier(method.GetName().Text))), new ArrayList());
                //data.Invokes.Add(method, new List<InvokeStm>(){new InvokeStm(syncInvokeExp)});
                //data.ExpTypes[syncInvokeExp] = new AVoidType(new TVoid("void"));

                //block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), syncInvokeExp));
            }
            for (int i = data.InvokeOnIniti.Count - 1; i >= 0; i--)
            {
                AMethodDecl method = data.InvokeOnIniti[i];

                //Turn method into a trigger
                method.SetReturnType(new ANamedType(new TIdentifier("bool"), null));
                method.GetFormals().Add(new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                        new ANamedType(new TIdentifier("bool"), null),
                                                        new TIdentifier("testConds"), null));
                method.GetFormals().Add(new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                        new ANamedType(new TIdentifier("bool"), null),
                                                        new TIdentifier("runActions"), null));
                method.SetTrigger(new TTrigger("trigger"));
                ((AABlock)method.GetBlock()).GetStatements().Add(new AVoidReturnStm(new TReturn("return")));
                TriggerConvertReturn returnConverter = new TriggerConvertReturn(data);
                method.Apply(returnConverter);
                data.TriggerDeclarations[method] = new List <TStringLiteral>();


                //Add Invoke(<name>); to main entry
                TStringLiteral literal = new TStringLiteral(method.GetName().Text);
                data.TriggerDeclarations[method].Add(literal);
                AStringConstExp stringConst = new AStringConstExp(literal);
                data.ExpTypes[stringConst] = new ANamedType(new TIdentifier("string"), null);
                ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("Invoke"), new ArrayList()
                {
                    stringConst
                });
                data.SimpleMethodLinks[invoke] = invokeMethod;
                data.ExpTypes[invoke]          = invokeMethod.GetReturnType();
                block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), invoke));


                /*
                 * ASyncInvokeExp syncInvokeExp = new ASyncInvokeExp(new TSyncInvoke("Invoke"),  new AAmbiguousNameLvalue(new ASimpleName(new TIdentifier(method.GetName().Text))), new ArrayList());
                 * data.Invokes.Add(method, new List<InvokeStm>() { new InvokeStm(syncInvokeExp) });
                 * data.ExpTypes[syncInvokeExp] = new AVoidType(new TVoid("void"));
                 *
                 * block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), syncInvokeExp));*/
            }
            for (int i = data.FieldsToInitInMapInit.Count - 1; i >= 0; i--)
            {
                AFieldDecl field = data.FieldsToInitInMapInit[i];
                if (field.GetInit() == null)
                {
                    continue;
                }

                AFieldLvalue   lvalue     = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), lvalue, field.GetInit());

                data.ExpTypes[assignment]    =
                    data.LvalueTypes[lvalue] = field.GetType();
                data.FieldLinks[lvalue]      = field;

                block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), assignment));
            }
            block.RemoveChild(mainEntryFieldInitBlock);
            block.GetStatements().Insert(0, mainEntryFieldInitBlock);
        }
Example #12
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);
                    }
                }
            }
        //private List<ErrorCollection.Error> multipleEntryCandidates = new List<ErrorCollection.Error>();
        public override void CaseAMethodDecl(AMethodDecl node)
        {
            //Done in a previous iteration

            /*if (node.GetName().Text == "InitMap" && node.GetFormals().Count == 0)
             * {
             *  if (finalTrans.multipleMainEntries)
             *  {
             *      multipleEntryCandidates.Add(new ErrorCollection.Error(node.GetName(), Util.GetAncestor<AASourceFile>(node.GetName()), "Candidate"));
             *  }
             *  else if (finalTrans.mainEntry != null)
             *  {
             *      multipleEntryCandidates.Add(new ErrorCollection.Error(finalTrans.mainEntry.GetName(), Util.GetAncestor<AASourceFile>(finalTrans.mainEntry.GetName()), "Candidate"));
             *      multipleEntryCandidates.Add(new ErrorCollection.Error(node.GetName(), Util.GetAncestor<AASourceFile>(node.GetName()), "Candidate"));
             *      //finalTrans.errors.Add(new ErrorCollection.Error(node.GetName(), Util.GetAncestor<AASourceFile>(node), "Found multiple candidates for a main entry", true));
             *      finalTrans.multipleMainEntries = true;
             *      finalTrans.mainEntry = null;
             *  }
             *  else
             *      finalTrans.mainEntry = node;
             * }*/

            AStructDecl str = Util.GetAncestor <AStructDecl>(node);

            if (str != null)
            {
                if (node.GetStatic() == null)
                {
                    structMethods.Add(node);
                }
                //Move the method outside the struct
                str.RemoveChild(node.Parent());
                AASourceFile file = (AASourceFile)str.Parent();
                int          i    = file.GetDecl().IndexOf(str);
                file.GetDecl().Insert(i /* + 1*/, node);
                node.GetName().Text = GetUniqueStructMethodName(str.GetName().Text + "_" + node.GetName().Text);

                if (node.GetStatic() == null)
                {
                    //Add the struct as a parameter
                    PType structType = new ANamedType(new TIdentifier(str.GetName().Text), null);
                    finalTrans.data.StructTypeLinks[(ANamedType)structType] = str;
                    if (str.GetClassToken() != null)
                    {
                        structType = new APointerType(new TStar("*"), structType);
                    }
                    structFormal = new AALocalDecl(new APublicVisibilityModifier(), null,
                                                   str.GetClassToken() == null ? new TRef("ref") : null, null, null,
                                                   structType,
                                                   new TIdentifier("currentStruct", node.GetName().Line,
                                                                   node.GetName().Pos), null);
                    node.GetFormals().Add(structFormal);
                    data.Locals[(AABlock)node.GetBlock()].Add(structFormal);
                }
                else
                {
                    node.SetStatic(null);
                }
                finalTrans.data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, node));
                if (node.GetStatic() == null)
                {
                    OldParentStruct[node] = str;
                }
                //Fix refferences to other struct stuff);
                base.CaseAMethodDecl(node);
                //Will visit later, since it's added after the struct
                //base.CaseAMethodDecl(node);
                //if (str.GetLocals().Count == 0)
                //    str.Parent().RemoveChild(str);
                return;
            }
            AEnrichmentDecl enrichment = Util.GetAncestor <AEnrichmentDecl>(node);

            if (enrichment != null)
            {
                if (node.GetStatic() == null)
                {
                    structMethods.Add(node);
                }
                //Move the method outside the struct
                enrichment.RemoveChild(node);
                AASourceFile file = (AASourceFile)enrichment.Parent();
                int          i    = file.GetDecl().IndexOf(enrichment);
                file.GetDecl().Insert(i /* + 1*/, node);
                node.GetName().Text = GetUniqueStructMethodName(Util.TypeToIdentifierString(enrichment.GetType()) + "_" + node.GetName().Text);

                if (node.GetStatic() == null)
                {
                    //Add the struct as a parameter
                    PType structType = Util.MakeClone(enrichment.GetType(), finalTrans.data);
                    structFormal = new AALocalDecl(new APublicVisibilityModifier(), null, new TRef("ref"), null, null,
                                                   structType,
                                                   new TIdentifier("currentEnrichment", node.GetName().Line,
                                                                   node.GetName().Pos), null);
                    node.GetFormals().Add(structFormal);
                }
                finalTrans.data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, node));
                //Fix refferences to other struct stuff);
                base.CaseAMethodDecl(node);
                //Will visit later, since it's added after the struct
                //base.CaseAMethodDecl(node);
                //if (str.GetLocals().Count == 0)
                //    str.Parent().RemoveChild(str);
                return;
            }
            //Build a list of overloads
            List <AMethodDecl> overloads     = new List <AMethodDecl>();
            List <string>      prefixMatches = new List <string>();

            foreach (SharedData.DeclItem <AMethodDecl> declItem in finalTrans.data.Methods)
            {
                if (!Util.IsSameNamespace(declItem.Decl, node))
                {
                    continue;
                }
                if (declItem.Decl.GetName().Text == node.GetName().Text)
                {
                    overloads.Add(declItem.Decl);
                }
                if (declItem.Decl.GetName().Text.StartsWith(node.GetName().Text + "O"))
                {
                    prefixMatches.Add(declItem.Decl.GetName().Text);
                }
            }



            foreach (AMethodDecl method in finalTrans.data.Libraries.Methods)
            {
                if (method.GetBlock() != null || method.GetNative() != null)
                {
                    if (method.GetName().Text == node.GetName().Text)
                    {
                        overloads.Add(method);
                    }
                    if (method.GetName().Text.StartsWith(node.GetName().Text + "O"))
                    {
                        prefixMatches.Add(method.GetName().Text);
                    }
                }
            }

            //Add fields
            foreach (SharedData.DeclItem <AFieldDecl> declItem in finalTrans.data.Fields)
            {
                if (declItem.Decl.GetName().Text.StartsWith(node.GetName().Text + "O"))
                {
                    prefixMatches.Add(declItem.Decl.GetName().Text);
                }
            }

            foreach (AFieldDecl field in finalTrans.data.Libraries.Fields)
            {
                if (field.GetName().Text.StartsWith(node.GetName().Text + "O"))
                {
                    prefixMatches.Add(field.GetName().Text);
                }
            }

            //Dont want to hit another method by appending O#
            string postfix = "";

            while (true)
            {
                postfix += "O";
                if (prefixMatches.Any(text => text.StartsWith(node.GetName().Text + postfix)))
                {
                    continue;
                }
                break;
            }

            if (overloads.Count > 1)
            {
                int i = 0;
                foreach (AMethodDecl method in overloads)
                {
                    if (node == finalTrans.mainEntry || (node.GetTrigger() != null && finalTrans.data.HasUnknownTrigger))
                    {
                        continue;
                    }
                    i++;
                    method.GetName().Text += postfix + i;
                }
            }

            if (node != finalTrans.mainEntry && (node.GetTrigger() == null || !finalTrans.data.HasUnknownTrigger))
            {
                node.GetName().Text = namespacePrefix + node.GetName().Text;
            }


            base.CaseAMethodDecl(node);
        }
        public override void CaseAConstructorDecl(AConstructorDecl node)
        {
            AStructDecl     str        = Util.GetAncestor <AStructDecl>(node);
            AEnrichmentDecl enrichment = Util.GetAncestor <AEnrichmentDecl>(node);
            AMethodDecl     replacer   = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new AVoidType(new TVoid("void")),
                                                         node.GetName(), new ArrayList(), node.GetBlock());

            replacer.GetName().Text += "_Constructor";
            while (node.GetFormals().Count > 0)
            {
                replacer.GetFormals().Add(node.GetFormals()[0]);
            }

            //Move the method outside the struct
            AASourceFile file = Util.GetAncestor <AASourceFile>(node);

            if (str != null)
            {
                str.RemoveChild(node.Parent());
            }
            else
            {
                enrichment.RemoveChild(node);
            }
            int i = file.GetDecl().IndexOf(str ?? (PDecl)enrichment);

            file.GetDecl().Insert(i /* + 1*/, replacer);
            //Add the struct as a parameter
            PType type;

            if (str != null)
            {
                ANamedType structType = new ANamedType(new TIdentifier(str.GetName().Text), null);
                finalTrans.data.StructTypeLinks[structType] = str;
                type = structType;
            }
            else
            {
                type = Util.MakeClone(enrichment.GetType(), finalTrans.data);
            }
            finalTrans.data.ConstructorMap[node] = replacer;
            structFormal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new APointerType(new TStar("*"), type), new TIdentifier("currentStruct", replacer.GetName().Line, replacer.GetName().Pos), null);
            replacer.GetFormals().Add(structFormal);
            finalTrans.data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, replacer));

            //Add return stm
            replacer.SetReturnType(new APointerType(new TStar("*"), Util.MakeClone(type, data)));
            replacer.Apply(new TransformConstructorReturns(structFormal, data));

            //Insert call to base constructor););
            if (finalTrans.data.ConstructorBaseLinks.ContainsKey(node))
            {
                AMethodDecl      baseConstructor = finalTrans.data.ConstructorMap[finalTrans.data.ConstructorBaseLinks[node]];
                ASimpleInvokeExp invoke          = new ASimpleInvokeExp(new TIdentifier(baseConstructor.GetName().Text), new ArrayList());
                while (node.GetBaseArgs().Count > 0)
                {
                    invoke.GetArgs().Add(node.GetBaseArgs()[0]);
                }
                AThisLvalue thisLvalue1 = new AThisLvalue(new TThis("this"));
                ALvalueExp  thisExp1    = new ALvalueExp(thisLvalue1);
                invoke.GetArgs().Add(thisExp1);

                AThisLvalue thisLvalue2 = new AThisLvalue(new TThis("this"));

                AAssignmentExp assignExp = new AAssignmentExp(new TAssign("="), thisLvalue2, invoke);

                ANamedType structType = new ANamedType(new TIdentifier(str.GetName().Text), null);
                finalTrans.data.StructTypeLinks[structType] = str;

                finalTrans.data.LvalueTypes[thisLvalue1]         =
                    finalTrans.data.LvalueTypes[thisLvalue2]     =
                        finalTrans.data.ExpTypes[thisExp1]       =
                            finalTrans.data.ExpTypes[assignExp]  =
                                finalTrans.data.ExpTypes[invoke] = new APointerType(new TStar("*"), structType);

                //finalTrans.data.ExpTypes[invoke] = new AVoidType(new TVoid("void"));
                finalTrans.data.SimpleMethodLinks[invoke] = baseConstructor;

                ((AABlock)replacer.GetBlock()).GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), assignExp));

                //Inline if base and current are two different kinds of pointer types (int/string)
                AStructDecl      baseStruct = null;
                AConstructorDecl baseC      = finalTrans.data.ConstructorBaseLinks[node];
                foreach (KeyValuePair <AStructDecl, List <AConstructorDecl> > pair in finalTrans.data.StructConstructors)
                {
                    bool found = false;
                    foreach (AConstructorDecl decl in pair.Value)
                    {
                        if (baseC == decl)
                        {
                            found = true;
                            break;
                        }
                    }
                    if (found)
                    {
                        baseStruct = pair.Key;
                        break;
                    }
                }
                if ((str.GetIntDim() == null) != (baseStruct.GetIntDim() == null))
                {
                    //For the inilining, change the type to the type of the caller
                    AALocalDecl lastFormal = baseConstructor.GetFormals().OfType <AALocalDecl>().Last();
                    lastFormal.SetRef(new TRef("ref"));
                    APointerType oldType = (APointerType)lastFormal.GetType();

                    structType = new ANamedType(new TIdentifier(str.GetName().Text), null);
                    finalTrans.data.StructTypeLinks[structType] = str;

                    APointerType newType = new APointerType(new TStar("*"), structType);
                    lastFormal.SetType(newType);

                    foreach (
                        ALocalLvalue lvalue in
                        data.LocalLinks.Where(pair => pair.Value == lastFormal).Select(pair => pair.Key))
                    {
                        data.LvalueTypes[lvalue] = newType;
                        if (lvalue.Parent() is ALvalueExp)
                        {
                            data.ExpTypes[(PExp)lvalue.Parent()] = newType;
                            if (lvalue.Parent().Parent() is APointerLvalue)
                            {
                                data.LvalueTypes[(PLvalue)lvalue.Parent().Parent()] = newType.GetType();
                            }
                        }
                    }

                    FixInlineMethods.Inline(invoke, finalTrans);
                    lastFormal.SetRef(null);
                    foreach (
                        ALocalLvalue lvalue in
                        data.LocalLinks.Where(pair => pair.Value == lastFormal).Select(pair => pair.Key))
                    {
                        data.LvalueTypes[lvalue] = oldType;
                        if (lvalue.Parent() is ALvalueExp)
                        {
                            data.ExpTypes[(PExp)lvalue.Parent()] = oldType;
                            if (lvalue.Parent().Parent() is APointerLvalue)
                            {
                                data.LvalueTypes[(PLvalue)lvalue.Parent().Parent()] = oldType.GetType();
                            }
                        }
                    }

                    lastFormal.SetType(oldType);
                }

                //Inline it instead, Since the pointer implementations might not be the same (int vs string)

                /*AMethodDecl baseConstructor = finalTrans.data.ConstructorMap[finalTrans.data.ConstructorBaseLinks[node]];
                 *
                 * AABlock localsBlock = new AABlock(new ArrayList(), new TRBrace("}"));
                 * ABlockStm cloneBlock = new ABlockStm(new TLBrace("{"), (PBlock) baseConstructor.GetBlock().Clone());
                 * Dictionary<AALocalDecl, PLvalue> localMap = new Dictionary<AALocalDecl, PLvalue>();
                 * for (int argNr = 0; argNr < baseConstructor.GetFormals().Count; argNr++)
                 * {
                 *  AALocalDecl formal = (AALocalDecl) baseConstructor.GetFormals()[i];
                 *  PExp arg;
                 *  if (i < baseConstructor.GetFormals().Count - 1)
                 *      arg = (PExp)node.GetBaseArgs()[i];
                 *  else
                 *  {
                 *      AThisLvalue thisLvalue = new AThisLvalue(new TThis("this"));
                 *      ALvalueExp thisExp = new ALvalueExp(thisLvalue);
                 *
                 *      ANamedType structType = new ANamedType(new TIdentifier(str.GetName().Text), null);
                 *      finalTrans.data.StructTypeLinks[structType] = str;
                 *
                 *      finalTrans.data.LvalueTypes[thisLvalue] =
                 *          finalTrans.data.ExpTypes[thisExp] = new APointerType(new TStar("*"), structType);
                 *
                 *      arg = thisExp;
                 *  }
                 *
                 *  if (formal.GetRef() != null || formal.GetOut() != null)
                 *  {
                 *      //Use same variable
                 *      localMap[formal] = ((ALvalueExp) arg).GetLvalue();
                 *  }
                 *  else
                 *  {
                 *      //Make a new variable
                 *      AALocalDecl newLocal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                 *                                             Util.MakeClone(formal.GetType(), finalTrans.data),
                 *                                             new TIdentifier(formal.GetName().Text),
                 *                                             Util.MakeClone(arg, data));
                 *
                 *      ALocalLvalue newLocalRef = new ALocalLvalue(new TIdentifier(newLocal.GetName().Text));
                 *
                 *      localMap[formal] = newLocalRef;
                 *      data.LvalueTypes[newLocalRef] = newLocal.GetType();
                 *      data.LocalLinks[newLocalRef] = newLocal;
                 *
                 *      localsBlock.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), newLocal));
                 *  }
                 *
                 * }
                 *
                 * CloneMethod cloner = new CloneMethod(finalTrans.data, localMap, cloneBlock);
                 * baseConstructor.GetBlock().Apply(cloner);
                 *
                 * ((AABlock)cloneBlock.GetBlock()).GetStatements().Insert(0, new ABlockStm(new TLBrace("{"), localsBlock));
                 * ((AABlock)node.GetBlock()).GetStatements().Insert(0, cloneBlock);*/
            }

            //Fix refferences to other struct stuff);
            base.CaseAMethodDecl(replacer);

            //Add functionality to refference the current struct in a constructor
            //Want to do it as a pointer type, since the constructer can only be called for pointer types
        }