public override void CaseAAssignmentExp(AAssignmentExp node)
 {
     if (!processMethodsOnly && !processStructs)
     {
         if (!processFieldsOnly)
         {
             if (node.GetLvalue() is ALocalLvalue)
             {
                 ALocalLvalue lvalue = (ALocalLvalue)node.GetLvalue();
                 assignedToLocals[finalTrans.data.LocalLinks[lvalue]].Add(node);
                 node.GetExp().Apply(this);
                 return;
             }
         }
         if (node.GetLvalue() is AFieldLvalue)
         {
             AFieldLvalue lvalue = (AFieldLvalue)node.GetLvalue();
             AFieldDecl   decl   = finalTrans.data.FieldLinks[lvalue];
             if (!assignedToFields[decl].Contains(node))
             {
                 assignedToFields[decl].Add(node);
             }
             node.GetExp().Apply(this);
             return;
         }
     }
     base.CaseAAssignmentExp(node);
 }
Exemplo n.º 2
0
            public override void CaseAValueReturnStm(AValueReturnStm node)
            {
                /*
                 * return <exp>;
                 * ->
                 * methodReturnerVar = <exp>;
                 * hasMethodReturnedVar = true;
                 * break;
                 */
                ALocalLvalue lvalue = new ALocalLvalue(new TIdentifier(methodReturnerVar.GetName().Text));

                data.LvalueTypes[lvalue] = methodReturnerVar.GetType();
                data.LocalLinks[lvalue]  = methodReturnerVar;
                AAssignmentExp exp = new AAssignmentExp(new TAssign("="), lvalue, node.GetExp());

                data.ExpTypes[exp] = methodReturnerVar.GetType();
                PStm    stm   = new AExpStm(new TSemicolon(";"), exp);
                AABlock block = new AABlock();

                block.GetStatements().Add(stm);

                block.GetStatements().Add(new AVoidReturnStm(node.GetToken()));

                node.ReplaceBy(new ABlockStm(new TLBrace("{"), block));
                block.Apply(this);
            }
Exemplo n.º 3
0
 public override void CaseAAssignmentExp(AAssignmentExp node)
 {
     node.GetLvalue().Apply(this);
     //node.GetToken().Apply(this);
     Write(" = ");
     node.GetExp().Apply(this);
 }
Exemplo n.º 4
0
            public override void CaseAVoidReturnStm(AVoidReturnStm node)
            {
                if (!neededWhile)
                {
                    node.Parent().RemoveChild(node);
                    return;
                }

                /*
                 * return;
                 * ->
                 * hasMethodReturnedVar = true;
                 * break;
                 */
                ALocalLvalue lvalue = new ALocalLvalue(new TIdentifier(hasMethodReturnedVar.GetName().Text));

                data.LvalueTypes[lvalue] = hasMethodReturnedVar.GetType();
                data.LocalLinks[lvalue]  = hasMethodReturnedVar;
                PExp exp = new ABooleanConstExp(new ATrueBool());

                data.ExpTypes[exp] = new ANamedType(new TIdentifier("bool"), null);
                exp = new AAssignmentExp(new TAssign("="), lvalue, exp);
                data.ExpTypes[exp] = hasMethodReturnedVar.GetType();
                PStm    stm   = new AExpStm(new TSemicolon(";"), exp);
                AABlock block = new AABlock();

                block.GetStatements().Add(stm);

                block.GetStatements().Add(new ABreakStm(new TBreak("break")));

                node.ReplaceBy(new ABlockStm(new TLBrace("{"), block));
            }
Exemplo n.º 5
0
        private static List <AALocalDecl> GetAssignedTo(ControlFlowGraph.Node node, SharedData data)
        {
            if (node.Statement is ALocalDeclStm)
            {
                return new List <AALocalDecl>()
                       {
                           (AALocalDecl)((ALocalDeclStm)node.Statement).GetLocalDecl()
                       }
            }
            ;
            PExp exp = node.Expression;

            if (exp != null && exp is AAssignmentExp)
            {
                AAssignmentExp aExp = (AAssignmentExp)exp;

                if (aExp.GetLvalue() is ALocalLvalue)
                {
                    return new List <AALocalDecl>()
                           {
                               data.LocalLinks[(ALocalLvalue)aExp.GetLvalue()]
                           }
                }
                ;
            }
            return(new List <AALocalDecl>());
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
 public override void OutAAssignmentExp(AAssignmentExp node)
 {
     if (Util.GetAncestor <PStm>(node) == null)
     {
         node.ReplaceBy(node.GetExp());
         return;
     }
     base.OutAAssignmentExp(node);
 }
        public static bool Parse(ControlFlowGraph cfg, SharedData data, out bool redoLivenessAnalysis)
        {
            bool changed = false;

            redoLivenessAnalysis = false;
            Dictionary <ControlFlowGraph.Node, List <ASimpleInvokeExp> > Modifications = new Dictionary <ControlFlowGraph.Node, List <ASimpleInvokeExp> >();

            foreach (ControlFlowGraph.Node node in cfg.Nodes)
            {
                if (node.Expression is AAssignmentExp)
                {
                    AAssignmentExp exp = (AAssignmentExp)node.Expression;
                    if (exp.GetLvalue() is ALocalLvalue)
                    {
                        AALocalDecl decl = data.LocalLinks[(ALocalLvalue)exp.GetLvalue()];
                        //If the variable is not live at any successors, remove this assignment
                        bool inUse = false;
                        foreach (ControlFlowGraph.Node successor in node.Successors)
                        {
                            if (successor.LiveVariables.Contains(decl))
                            {
                                inUse = true;
                                break;
                            }
                        }
                        if (!inUse)
                        {
                            //Move method invokes out
                            GetMethodInvokes getter = new GetMethodInvokes();
                            exp.GetExp().Apply(getter);
                            //Might also have to redo because we removed a reference to a variable in the right side
                            //if (getter.Invokes.Count > 0)
                            redoLivenessAnalysis = true;
                            Modifications[node]  = getter.Invokes;
                            changed = true;
                        }
                    }
                }
            }
            foreach (KeyValuePair <ControlFlowGraph.Node, List <ASimpleInvokeExp> > pair in Modifications)
            {
                ControlFlowGraph.Node node = pair.Key;
                foreach (ASimpleInvokeExp invoke in pair.Value)
                {
                    AExpStm stm    = new AExpStm(new TSemicolon(";"), invoke);
                    AABlock pBlock = (AABlock)node.Statement.Parent();
                    pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(node.Statement), stm);
                    cfg.Insert(node, stm);
                }
                cfg.Remove(node);
                node.Statement.Parent().RemoveChild(node.Statement);
            }
            return(changed);
        }
Exemplo n.º 9
0
 public override void CaseAAssignmentExp(AAssignmentExp node)
 {
     currentLocal = null;
     node.GetLvalue().Apply(this);
     if (currentLocal != null)
     {
         AALocalDecl decl = data.LocalLinks[currentLocal];
         NeededRefs[Util.GetAncestor <AMethodDecl>(node)].Add(decl);
     }
     node.GetExp().Apply(this);
 }
 public override void CaseAAssignmentExp(AAssignmentExp node)
 {
     if (node.GetExp() is ALvalueExp && Util.ReturnsTheSame(node.GetLvalue(), ((ALvalueExp)node.GetExp()).GetLvalue(), data))
     {
         RemovedOne = true;
         node.Parent().Parent().RemoveChild(node.Parent());
     }
     else
     {
         base.CaseAAssignmentExp(node);
     }
 }
Exemplo n.º 11
0
            public override void CaseAContinueStm(AContinueStm node)
            {
                AABlock          pBlock        = (AABlock)node.Parent();
                ALocalLvalue     replaceVarRef = new ALocalLvalue(new TIdentifier("whileVar"));
                ASimpleInvokeExp clone         = (ASimpleInvokeExp)Util.MakeClone(this.node, data);
                AAssignmentExp   assignment    = new AAssignmentExp(new TAssign("="), replaceVarRef, clone);

                data.LocalLinks[replaceVarRef] = replaceVarDecl;
                data.ExpTypes[assignment]      = data.LvalueTypes[replaceVarRef] = replaceVarDecl.GetType();
                pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(node), new AExpStm(new TSemicolon(";"), assignment));
                replacementExpressions.Add(clone);
            }
Exemplo n.º 12
0
            public override void CaseALocalLvalue(ALocalLvalue node)
            {
                //Only if it is not what it is assigning to
                AAssignmentExp exp = Util.GetAncestor <AAssignmentExp>(node);

                if (exp != null && node == exp.GetLvalue())
                {
                    return;
                }

                UsedLocals.Add(data.LocalLinks[node]);
            }
Exemplo n.º 13
0
        public override void CaseAAssignmentExp(AAssignmentExp node)
        {
            if (!(node.Parent() is AExpStm))
            {
                PStm parentStm = Util.GetAncestor <PStm>(node);

                MoveMethodDeclsOut mover = new MoveMethodDeclsOut("multipleAssignmentsVar", finalTrans.data);
                node.GetLvalue().Apply(mover);
                PLvalue    lvalue = Util.MakeClone(node.GetLvalue(), finalTrans.data);
                ALvalueExp exp    = new ALvalueExp(lvalue);
                finalTrans.data.ExpTypes[exp] = finalTrans.data.LvalueTypes[lvalue];
                node.ReplaceBy(exp);

                AExpStm stm = new AExpStm(new TSemicolon(";"), node);



                AABlock block = (AABlock)parentStm.Parent();
                //block.GetStatements().Insert(block.GetStatements().IndexOf(parentStm), localDeclStm);
                block.GetStatements().Insert(block.GetStatements().IndexOf(parentStm), stm);

                //localDeclStm.Apply(this);
                stm.Apply(this);

                if (parentStm is AWhileStm && Util.IsAncestor(exp, ((AWhileStm)parentStm).GetCondition()))
                {
                    AWhileStm aStm = (AWhileStm)parentStm;
                    //Copy assignment before continues
                    //Before each continue in the while, and at the end.

                    //Add continue statement, if not present
                    block = (AABlock)((ABlockStm)aStm.GetBody()).GetBlock();
                    if (block.GetStatements().Count == 0 || !(block.GetStatements()[block.GetStatements().Count - 1] is AContinueStm))
                    {
                        block.GetStatements().Add(new AContinueStm(new TContinue("continue")));
                    }

                    //Get all continue statements in the while
                    ContinueFinder finder = new ContinueFinder();
                    block.Apply(finder);
                    foreach (AContinueStm continueStm in finder.Continues)
                    {
                        stm = new AExpStm(new TSemicolon(";"), Util.MakeClone(node, finalTrans.data));
                        block.GetStatements().Insert(block.GetStatements().IndexOf(continueStm), stm);

                        stm.Apply(this);
                    }
                }
                return;
            }

            base.CaseAAssignmentExp(node);
        }
Exemplo n.º 14
0
        public override void OutASAssignmentExp(ASAssignmentExp node)
        {
            AAssignmentExp replacer = null;
            PAssignop      assignop = node.GetAssignop();
            Token          token    = null;
            PBinop         binop    = null;

            if (assignop is AAddAssignop)
            {
                token = ((AAddAssignop)assignop).GetToken();
                binop = new APlusBinop(new TPlus("+", token.Line, token.Pos));
            }
            else if (assignop is ASubAssignop)
            {
                token = ((ASubAssignop)assignop).GetToken();
                binop = new AMinusBinop(new TMinus("-", token.Line, token.Pos));
            }
            else if (assignop is AMulAssignop)
            {
                token = ((AMulAssignop)assignop).GetToken();
                binop = new ATimesBinop(new TStar("*", token.Line, token.Pos));
            }
            else if (assignop is ADivAssignop)
            {
                token = ((ADivAssignop)assignop).GetToken();
                binop = new ADivideBinop(new TDiv("/", token.Line, token.Pos));
            }
            else if (assignop is AModAssignop)
            {
                token = ((AModAssignop)assignop).GetToken();
                binop = new AModuloBinop(new TMod("%", token.Line, token.Pos));
            }
            else// if (assignop is AAssignAssignop)
            {
                token = ((AAssignAssignop)assignop).GetToken();
            }
            PExp rightSide;

            if (binop != null)
            {
                rightSide = new ABinopExp(new ALvalueExp((PLvalue)node.GetLvalue().Clone()),
                                          binop,
                                          (PExp)node.GetExp().Clone());
            }
            else
            {
                rightSide = (PExp)node.GetExp().Clone();
            }
            replacer = new AAssignmentExp(new TAssign("=", token.Line, token.Pos), (PLvalue)node.GetLvalue().Clone(), rightSide);
            node.ReplaceBy(replacer);
            replacer.Apply(this);
        }
Exemplo n.º 15
0
        private void MakeAssignments(AABlock block, PType type, PLvalue leftSide, bool onEnhritedFields)
        {
            if (type is ANamedType && data.StructTypeLinks.ContainsKey((ANamedType)type))
            {
                AStructDecl str = data.StructTypeLinks[(ANamedType)type];
                foreach (AALocalDecl field in str.GetLocals().OfType <AALocalDecl>())
                {
                    if (!onEnhritedFields && data.EnheritanceLocalMap.ContainsKey(field))
                    {
                        continue;
                    }

                    ALvalueExp lvalueExp = new ALvalueExp(Util.MakeClone(leftSide, data));
                    data.ExpTypes[lvalueExp] = data.LvalueTypes[leftSide];
                    AStructLvalue newLeftSide = new AStructLvalue(lvalueExp, new ADotDotType(new TDot(".")), new TIdentifier(field.GetName().Text));
                    data.StructFieldLinks[newLeftSide] = field;
                    data.LvalueTypes[newLeftSide]      = field.GetType();

                    if (field.GetInit() != null)
                    {
                        AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), newLeftSide,
                                                                       Util.MakeClone(field.GetInit(), data));
                        data.ExpTypes[assignment] = data.LvalueTypes[newLeftSide];

                        block.GetStatements().Add(new AExpStm(new TSemicolon(";"),
                                                              assignment));
                    }
                    else
                    {
                        MakeAssignments(block, field.GetType(), newLeftSide, onEnhritedFields);
                    }
                }
            }
            else if (type is AArrayTempType)
            {
                AArrayTempType aType = (AArrayTempType)type;
                for (int i = 0; i < int.Parse(aType.GetIntDim().Text); i++)
                {
                    AIntConstExp index = new AIntConstExp(new TIntegerLiteral(i.ToString()));
                    data.ExpTypes[index] = new ANamedType(new TIdentifier("int"), null);

                    ALvalueExp lvalueExp = new ALvalueExp(Util.MakeClone(leftSide, data));
                    data.ExpTypes[lvalueExp] = data.LvalueTypes[leftSide];
                    AArrayLvalue newLeftSide = new AArrayLvalue(new TLBracket("["), lvalueExp, index);
                    data.LvalueTypes[newLeftSide] = aType.GetType();

                    MakeAssignments(block, aType.GetType(), newLeftSide, onEnhritedFields);
                }
            }
        }
Exemplo n.º 16
0
 public override void CaseAAssignmentExp(AAssignmentExp node)
 {
     isLeftsideOfAssignment = true;
     node.GetLvalue().Apply(this);
     isLeftsideOfAssignment = false;
 }
        public static bool Parse(ControlFlowGraph cfg, SharedData data)
        {
            Dictionary <PStm, ControlFlowGraph.Node> statementNodes = new Dictionary <PStm, ControlFlowGraph.Node>();

            //Dictionary<ControlFlowGraph.Node, List<AALocalDecl>> uses = new Dictionary<ControlFlowGraph.Node, List<AALocalDecl>>();
            foreach (ControlFlowGraph.Node node in cfg.Nodes)
            {
                statementNodes[node.Statement] = node;

                /*GetUses getUses = new GetUses();
                 * node.Statement.Apply(getUses);
                 * uses[node] = getUses.Uses;*/
            }


            foreach (ControlFlowGraph.Node node in cfg.Nodes)
            {
                if (node.Expression is AAssignmentExp)
                {
                    AAssignmentExp exp = (AAssignmentExp)node.Expression;



                    if (exp.GetLvalue() is ALocalLvalue)
                    {
                        AALocalDecl decl     = data.LocalLinks[(ALocalLvalue)exp.GetLvalue()];
                        bool        dontMove = false;

                        LocalChecker.ModifyData declModData = LocalChecker.GetLocalData(node.Expression, data);

                        /*1: Search for unique use of decl
                         *  Stop if you find an assignment to decl
                         *  Stop if decl is not live
                         *  Cancel if you find two uses of decl (also within one statement)
                         */
                        ControlFlowGraph.Node useNode = null;
                        LinkedList <ControlFlowGraph.Node> nextNodes    = new LinkedList <ControlFlowGraph.Node>();
                        LinkedList <ControlFlowGraph.Node> visitedNodes = new LinkedList <ControlFlowGraph.Node>();
                        foreach (var successor in node.Successors)
                        {
                            nextNodes.AddLast(successor);
                        }
                        while (nextNodes.Count > 0)
                        {
                            ControlFlowGraph.Node successor = nextNodes.First.Value;
                            nextNodes.RemoveFirst();
                            visitedNodes.AddLast(successor);
                            LocalChecker.ModifyData succData = LocalChecker.GetLocalData(successor.Expression, data);

                            //Stop if decl is not live
                            if (!successor.LiveVariables.Contains(decl))
                            {
                                continue;
                            }


                            //Check if this node uses it)
                            if (succData.Locals.ContainsKey(decl))
                            {
                                var val = succData.Locals[decl];
                                if (val.Reads)
                                {
                                    if (useNode == null)
                                    {
                                        useNode = successor;
                                    }
                                    else
                                    {
                                        //Cancel if we found two uses
                                        dontMove = true;
                                        break;
                                    }
                                }
                                //Stop if it writes to the variable
                                if (val.Writes)
                                {
                                    continue;
                                }
                            }


                            foreach (ControlFlowGraph.Node nextSucc in successor.Successors)
                            {
                                if (visitedNodes.Contains(nextSucc))
                                {
                                    continue;
                                }
                                nextNodes.AddLast(nextSucc);
                            }
                        }

                        ALocalLvalue usedLvalue;
                        if (dontMove ||
                            useNode == null ||
                            //Cancel if there are two uses of the local within same statement
                            GetUses.HasMoreThanOneUses(useNode.Statement, decl, data, out usedLvalue))
                        {
                            continue;
                        }

                        /*2: Search back from found statement, to ensure unique assignment
                         *  Stop if assignment reached
                         *  Cancel if start of method is reached
                         *  Cancel if any statement reads/writes to a variable used in the statement (where one of them writes)
                         *  Cancel if another assignment to x is found (including local decls)
                         */
                        visitedNodes.Clear();
                        nextNodes.Clear();
                        foreach (ControlFlowGraph.Node predecessor in useNode.Predecessors)
                        {
                            nextNodes.AddLast(predecessor);
                        }
                        while (nextNodes.Count > 0)
                        {
                            ControlFlowGraph.Node predecessor = nextNodes.First.Value;
                            nextNodes.RemoveFirst();
                            visitedNodes.AddLast(predecessor);
                            LocalChecker.ModifyData predData = LocalChecker.GetLocalData(predecessor.Expression, data);

                            //Stop if assignment reached
                            if (predecessor == node)
                            {
                                continue;
                            }


                            //Cancel if this statement writes to decl
                            if (predData.Locals.ContainsKey(decl) &&
                                predData.Locals[decl].Writes ||
                                predecessor.Statement is ALocalDeclStm &&
                                ((ALocalDeclStm)predecessor.Statement).GetLocalDecl() == decl)
                            {
                                dontMove = true;
                                break;
                            }

                            //Cancel if any statement reads/writes to a variable used in the statement (where one of them writes)
                            if (declModData.Conflicts(predData))
                            {
                                dontMove = true;
                                break;
                            }

                            //Cancel if start of method is reached
                            if (predecessor.Predecessors.Count == 0)
                            {
                                dontMove = true;
                                break;
                            }

                            foreach (ControlFlowGraph.Node nextPred in predecessor.Predecessors)
                            {
                                if (visitedNodes.Contains(nextPred))
                                {
                                    continue;
                                }
                                nextNodes.AddLast(nextPred);
                            }
                        }

                        if (dontMove)
                        {
                            continue;
                        }

                        //Move it
                        cfg.Remove(node);
                        node.Statement.Parent().RemoveChild(node.Statement);
                        usedLvalue.Parent().ReplaceBy(exp.GetExp());

                        //We now need to redo liveness analysis
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 18
0
        public override void CaseADelegateInvokeExp(ADelegateInvokeExp node)
        {
            //Build a list of the possible methods
            AASourceFile       currentFile    = Util.GetAncestor <AASourceFile>(node);
            List <AMethodDecl> methods        = new List <AMethodDecl>();
            ANamedType         type           = (ANamedType)finalTrans.data.ExpTypes[node.GetReceiver()];
            AMethodDecl        delegateMethod = finalTrans.data.DelegateTypeLinks[type];

            foreach (KeyValuePair <ADelegateExp, AMethodDecl> delegateCreationPair in finalTrans.data.DelegateCreationMethod)
            {
                if (TypeChecking.Assignable(delegateCreationPair.Key.GetType(), type))
                {
                    if (!methods.Contains(delegateCreationPair.Value))
                    {
                        methods.Add(delegateCreationPair.Value);
                    }
                }
            }
            MoveMethodDeclsOut mover;

            if (methods.Count == 0)
            {
                //Can only remove it if the return value is unused
                if (!(node.Parent() is AExpStm))
                {
                    finalTrans.errors.Add(new ErrorCollection.Error(node.GetToken(),
                                                                    currentFile,
                                                                    "No possible methods found for delegate invoke."));
                    throw new ParserException(node.GetToken(), "Delegates.OutADelegateInvokeExp");
                }

                mover = new MoveMethodDeclsOut("delegateVar", finalTrans.data);
                foreach (Node arg in node.GetArgs())
                {
                    arg.Apply(mover);
                }
                node.Parent().Parent().RemoveChild(node.Parent());
                foreach (PStm stm in mover.NewStatements)
                {
                    stm.Apply(this);
                }
                return;
            }
            if (methods.Count == 1)
            {
                ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("renameMe"), new ArrayList());
                while (node.GetArgs().Count > 0)
                {
                    invoke.GetArgs().Add(node.GetArgs()[0]);
                }

                //If we have a struct method, add the pointer from the delegate
                if (finalTrans.data.StructMethods.Any(str => str.Value.Contains(methods[0])))
                {
                    AStructDecl      targetStr        = finalTrans.data.StructMethods.First(str => str.Value.Contains(methods[0])).Key;
                    AMethodDecl      getPointerDecl   = GetPointerMethod(targetStr.GetDimention() != null);
                    ASimpleInvokeExp getPointerInvoke = new ASimpleInvokeExp(new TIdentifier("renameMe"), new ArrayList()
                    {
                        node.GetReceiver()
                    });
                    invoke.GetArgs().Add(getPointerInvoke);

                    finalTrans.data.SimpleMethodLinks[getPointerInvoke] = getPointerDecl;
                    finalTrans.data.ExpTypes[getPointerInvoke]          = getPointerDecl.GetReturnType();
                }

                finalTrans.data.SimpleMethodLinks[invoke] = methods[0];
                finalTrans.data.ExpTypes[invoke]          = methods[0].GetReturnType();
                node.ReplaceBy(invoke);
                return;
            }
            //Multiple methods. Make

            /*
             * <Methods moved out from reciever>
             * string delegate = GetMethodPart(<reciever>);
             * if (delegate == "...")
             * {
             *    Foo(...);
             * }
             * else if (delegate == "...")
             * {
             *    Bar(..., GetPointerPart(<reciever>);
             * }
             * else if(...)
             * ...
             * else
             * {
             *     UIDisplayMessage(PlayerGroupAll(), c_messageAreaDebug, StringToText("[<file>:<line>]: No methods matched delegate."));
             *     int i = 1/0;
             *     return;
             * }
             *
             */
            AABlock block = new AABlock(new ArrayList(), new TRBrace("}"));

            mover = new MoveMethodDeclsOut("delegateVar", finalTrans.data);
            node.GetReceiver().Apply(mover);
            AMethodDecl      methodPartMethod = GetMethodMethod();
            ASimpleInvokeExp methodPartInvoke = new ASimpleInvokeExp(new TIdentifier("GetMethodPart"),
                                                                     new ArrayList()
            {
                Util.MakeClone(node.GetReceiver(),
                               finalTrans.data)
            });

            finalTrans.data.SimpleMethodLinks[methodPartInvoke] = methodPartMethod;
            finalTrans.data.ExpTypes[methodPartInvoke]          = methodPartMethod.GetReturnType();
            AALocalDecl methodPartDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                         new ANamedType(new TIdentifier("string"), null),
                                                         new TIdentifier("methodPart"), methodPartInvoke);

            block.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), methodPartDecl));
            //If the invoke's return value is used, get the lvalue
            PLvalue leftSide;

            if (node.Parent() is AALocalDecl)
            {
                leftSide = new ALocalLvalue(new TIdentifier("renameMe"));
                finalTrans.data.LocalLinks[(ALocalLvalue)leftSide] = (AALocalDecl)node.Parent();
                finalTrans.data.LvalueTypes[leftSide] = new ANamedType(new TIdentifier("string"), null);
                PStm    pStm   = Util.GetAncestor <PStm>(node);
                AABlock pBlock = (AABlock)pStm.Parent();
                pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm) + 1, new ABlockStm(new TLBrace("{"), block));
                node.Parent().RemoveChild(node);
            }
            else if (node.Parent() is AAssignmentExp)
            {
                AAssignmentExp assignExp = (AAssignmentExp)node.Parent();
                leftSide = assignExp.GetLvalue();
                leftSide.Apply(mover);

                PStm pStm = Util.GetAncestor <PStm>(node);
                pStm.ReplaceBy(new ABlockStm(new TLBrace("{"), block));
            }
            else if (node.Parent() is AExpStm)
            {
                //No assignments needed
                leftSide = null;
                node.Parent().ReplaceBy(new ABlockStm(new TLBrace("{"), block));
            }
            else
            {
                //Create a new local
                AALocalDecl leftSideDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                           Util.MakeClone(delegateMethod.GetReturnType(),
                                                                          finalTrans.data),
                                                           new TIdentifier("delegateVar"), null);
                ALocalLvalue leftSideLink    = new ALocalLvalue(new TIdentifier("delegateVar"));
                ALvalueExp   leftSideLinkExp = new ALvalueExp(leftSideLink);


                PStm    pStm   = Util.GetAncestor <PStm>(node);
                AABlock pBlock = (AABlock)pStm.Parent();
                pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm), new ABlockStm(new TLBrace("{"), block));

                node.ReplaceBy(leftSideLinkExp);

                finalTrans.data.LocalLinks[leftSideLink]      = leftSideDecl;
                finalTrans.data.LvalueTypes[leftSideLink]     =
                    finalTrans.data.ExpTypes[leftSideLinkExp] = leftSideDecl.GetType();

                leftSide = leftSideLink;
                block.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), leftSideDecl));
            }

            ABlockStm elseBranch;

            //Make final else branch

            /* {
             *     UIDisplayMessage(PlayerGroupAll(), c_messageAreaDebug, StringToText("<file>[<line>, <pos>]: No methods matched delegate."));
             *     IntToString(1/0);
             *     return;
             * }
             */
            {
                AABlock          innerBlock         = new AABlock(new ArrayList(), new TRBrace("}"));
                ASimpleInvokeExp playerGroupInvoke  = new ASimpleInvokeExp(new TIdentifier("PlayerGroupAll"), new ArrayList());
                AFieldLvalue     messageAreaLink    = new AFieldLvalue(new TIdentifier("c_messageAreaDebug"));
                ALvalueExp       messageAreaLinkExp = new ALvalueExp(messageAreaLink);
                AStringConstExp  stringConst        =
                    new AStringConstExp(
                        new TStringLiteral("\"" + currentFile.GetName().Text.Replace('\\', '/') + "[" +
                                           node.GetToken().Line + ", " + node.GetToken().Pos +
                                           "]: Got a null delegate.\""));
                ASimpleInvokeExp stringToTextInvoke = new ASimpleInvokeExp(new TIdentifier("StringToText"),
                                                                           new ArrayList()
                {
                    stringConst
                });
                ASimpleInvokeExp displayMessageInvoke = new ASimpleInvokeExp(new TIdentifier("UIDisplayMessage"),
                                                                             new ArrayList()
                {
                    playerGroupInvoke,
                    messageAreaLinkExp,
                    stringToTextInvoke
                });

                AIntConstExp     intConst1         = new AIntConstExp(new TIntegerLiteral("1"));
                AIntConstExp     intConst2         = new AIntConstExp(new TIntegerLiteral("0"));
                ABinopExp        binop             = new ABinopExp(intConst1, new ADivideBinop(new TDiv("/")), intConst2);
                ASimpleInvokeExp intToStringInvoke = new ASimpleInvokeExp(new TIdentifier("IntToString"),
                                                                          new ArrayList()
                {
                    binop
                });

                innerBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), displayMessageInvoke));
                innerBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), intToStringInvoke));
                //innerBlock.GetStatements().Add(new AVoidReturnStm(new TReturn("return")));

                elseBranch = new ABlockStm(new TLBrace("{"), innerBlock);


                finalTrans.data.SimpleMethodLinks[playerGroupInvoke] =
                    finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == playerGroupInvoke.GetName().Text);
                finalTrans.data.SimpleMethodLinks[stringToTextInvoke] =
                    finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringToTextInvoke.GetName().Text);
                finalTrans.data.SimpleMethodLinks[displayMessageInvoke] =
                    finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == displayMessageInvoke.GetName().Text);
                finalTrans.data.SimpleMethodLinks[intToStringInvoke] =
                    finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == intToStringInvoke.GetName().Text);
                finalTrans.data.FieldLinks[messageAreaLink] =
                    finalTrans.data.Libraries.Fields.First(m => m.GetName().Text == messageAreaLink.GetName().Text);

                finalTrans.data.ExpTypes[playerGroupInvoke] =
                    finalTrans.data.SimpleMethodLinks[playerGroupInvoke].GetReturnType();
                finalTrans.data.LvalueTypes[messageAreaLink]     =
                    finalTrans.data.ExpTypes[messageAreaLinkExp] =
                        finalTrans.data.FieldLinks[messageAreaLink].GetType();
                finalTrans.data.ExpTypes[stringToTextInvoke] =
                    finalTrans.data.SimpleMethodLinks[stringToTextInvoke].GetReturnType();
                finalTrans.data.ExpTypes[stringConst]           =
                    finalTrans.data.ExpTypes[intToStringInvoke] = new ANamedType(new TIdentifier("string"), null);
                finalTrans.data.ExpTypes[displayMessageInvoke]  = new AVoidType();

                finalTrans.data.ExpTypes[intConst1]     =
                    finalTrans.data.ExpTypes[intConst2] =
                        finalTrans.data.ExpTypes[binop] = new ANamedType(new TIdentifier("int"), null);
            }

            foreach (AMethodDecl method in methods)
            {
                /*  * if (delegate == "...")
                 * {
                 *    Foo(...);
                 * }
                 * else if (delegate == "...")
                 * {
                 *    Bar(..., GetPointerPart(<reciever>);
                 * }
                 * else if(...)
                 * ...
                 */
                AABlock          innerBlock = new AABlock(new ArrayList(), new TRBrace("}"));
                ASimpleInvokeExp invoke     = new ASimpleInvokeExp(new TIdentifier(method.GetName().Text), new ArrayList());
                for (int i = 0; i < node.GetArgs().Count; i++)
                {
                    PExp arg = (PExp)node.GetArgs()[i];
                    invoke.GetArgs().Add(Util.MakeClone(arg, finalTrans.data));
                }
                //If we have a struct method, add the pointer from the delegate
                if (finalTrans.data.StructMethods.Any(str => str.Value.Contains(method)))
                {
                    AStructDecl      targetStr        = finalTrans.data.StructMethods.First(str => str.Value.Contains(method)).Key;
                    AMethodDecl      getPointerDecl   = GetPointerMethod(targetStr.GetDimention() != null);
                    ASimpleInvokeExp getPointerInvoke = new ASimpleInvokeExp(new TIdentifier("renameMe"), new ArrayList()
                    {
                        Util.MakeClone(node.GetReceiver(), data)
                    });
                    invoke.GetArgs().Add(getPointerInvoke);

                    finalTrans.data.SimpleMethodLinks[getPointerInvoke] = getPointerDecl;
                    finalTrans.data.ExpTypes[getPointerInvoke]          = getPointerDecl.GetReturnType();
                }

                finalTrans.data.SimpleMethodLinks[invoke] = method;
                finalTrans.data.ExpTypes[invoke]          = method.GetReturnType();

                if (leftSide == null)
                {
                    innerBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), invoke));
                }
                else
                {
                    AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), Util.MakeClone(leftSide, finalTrans.data), invoke);
                    finalTrans.data.ExpTypes[assignment] = finalTrans.data.ExpTypes[invoke];
                    innerBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment));
                }
                ALocalLvalue    methodPartLink    = new ALocalLvalue(new TIdentifier("methodPart"));
                ALvalueExp      methodPartLinkExp = new ALvalueExp(methodPartLink);
                AStringConstExp stringConst       = new AStringConstExp(new TStringLiteral("\"" + GetName(method) + "\""));
                finalTrans.data.LocalLinks[methodPartLink]      = methodPartDecl;
                finalTrans.data.LvalueTypes[methodPartLink]     =
                    finalTrans.data.ExpTypes[methodPartLinkExp] =
                        finalTrans.data.ExpTypes[stringConst]   = new ANamedType(new TIdentifier("string"), null);


                ABinopExp binop = new ABinopExp(methodPartLinkExp, new AEqBinop(new TEq("==")), stringConst);
                finalTrans.data.ExpTypes[binop] = new ANamedType(new TIdentifier("bool"), null);

                AIfThenElseStm ifThenElse = new AIfThenElseStm(new TLParen("("), binop, new ABlockStm(new TLBrace("{"), innerBlock), elseBranch);

                elseBranch = new ABlockStm(new TLBrace("{"), new AABlock(new ArrayList()
                {
                    ifThenElse
                }, new TRBrace("}")));
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    lastFormal.SetType(oldType);
                }

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

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

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

            //Add functionality to refference the current struct in a constructor
            //Want to do it as a pointer type, since the constructer can only be called for pointer types
        }
Exemplo n.º 20
0
        private List <PStm> AssignDefault(PLvalue lvalue)
        {
            List <PStm> returner  = new List <PStm>();
            PType       type      = data.LvalueTypes[lvalue];
            PExp        rightSide = null;

            if (type is ANamedType)
            {
                ANamedType aType = (ANamedType)type;
                if (aType.IsPrimitive("string"))//aType.GetName().Text == "string")
                {
                    rightSide = new AStringConstExp(new TStringLiteral("\"\""));
                    data.ExpTypes[rightSide] = new ANamedType(new TIdentifier("string"), null);
                }
                else if (aType.IsPrimitive(GalaxyKeywords.NullablePrimitives.words)) //GalaxyKeywords.NullablePrimitives.words.Contains(aType.GetName().Text))
                {
                    rightSide = new ANullExp();
                    data.ExpTypes[rightSide] = new ANamedType(new TIdentifier("null"), null);
                }
                else if (aType.IsPrimitive(new [] { "int", "byte", "fixed" }))

                /*aType.GetName().Text == "int" ||
                *  aType.GetName().Text == "byte" ||
                *  aType.GetName().Text == "fixed")*/
                {
                    rightSide = new AIntConstExp(new TIntegerLiteral("0"));
                    data.ExpTypes[rightSide] = type;
                }
                else if (aType.IsPrimitive("bool"))//aType.GetName().Text == "bool")
                {
                    rightSide = new ABooleanConstExp(new AFalseBool());
                    data.ExpTypes[rightSide] = type;
                }
                else if (aType.IsPrimitive("color"))//aType.GetName().Text == "color")
                {
                    PExp             arg1   = new AIntConstExp(new TIntegerLiteral("0"));
                    PExp             arg2   = new AIntConstExp(new TIntegerLiteral("0"));
                    PExp             arg3   = new AIntConstExp(new TIntegerLiteral("0"));
                    ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("Color"), new ArrayList()
                    {
                        arg1, arg2, arg3
                    });
                    rightSide = invoke;
                    data.ExpTypes[rightSide]       = type;
                    data.ExpTypes[arg1]            =
                        data.ExpTypes[arg2]        =
                            data.ExpTypes[arg3]    = new ANamedType(new TIdentifier("int"), null);
                    data.SimpleMethodLinks[invoke] =
                        data.Libraries.Methods.First(func => func.GetName().Text == invoke.GetName().Text);
                }
                else if (aType.IsPrimitive("char"))//aType.GetName().Text == "char")
                {
                    //Dunno?!
                    rightSide = new ACharConstExp(new TCharLiteral("'\0'"));
                    data.ExpTypes[rightSide] = type;
                }
                else //Struct
                {
                    AStructDecl str = data.StructTypeLinks[aType];
                    foreach (AALocalDecl localDecl in str.GetLocals())
                    {
                        ALvalueExp    reciever  = new ALvalueExp(Util.MakeClone(lvalue, data));
                        AStructLvalue newLvalue = new AStructLvalue(reciever, new ADotDotType(new TDot(".")), new TIdentifier(localDecl.GetName().Text));
                        data.StructFieldLinks[newLvalue] = localDecl;
                        data.ExpTypes[reciever]          = type;
                        data.LvalueTypes[newLvalue]      = localDecl.GetType();
                        returner.AddRange(AssignDefault(newLvalue));
                    }
                    return(returner);
                }
                AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), Util.MakeClone(lvalue, data), rightSide);
                data.ExpTypes[assignment] = type;
                return(new List <PStm>()
                {
                    new AExpStm(new TSemicolon(";"), assignment)
                });
            }
            if (type is AArrayTempType)
            {
                AArrayTempType aType = (AArrayTempType)type;
                for (int i = 0; i < int.Parse(aType.GetIntDim().Text); i++)
                {
                    ALvalueExp   reciever  = new ALvalueExp(Util.MakeClone(lvalue, data));
                    AArrayLvalue newLvalue = new AArrayLvalue(new TLBracket("["), reciever, new AIntConstExp(new TIntegerLiteral(i.ToString())));
                    data.ExpTypes[reciever]             = type;
                    data.LvalueTypes[newLvalue]         = aType.GetType();
                    data.ExpTypes[newLvalue.GetIndex()] = new ANamedType(new TIdentifier("int"), null);
                    returner.AddRange(AssignDefault(newLvalue));
                }
                return(returner);
            }

            throw new Exception("Unexpected type. (LivenessAnalasys.AssignDefault), got " + type);
        }
Exemplo n.º 21
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();
                    }
                }
            }
Exemplo n.º 22
0
        public override void OutAIfExp(AIfExp node)
        {
            //Transform to

            /*
             * var expIfVar;
             * if (<cond>)
             * {
             *     expIfVar = <then>;
             * }
             * else
             * {
             *     expIfVar = <else>;
             * }
             * ... expIfVar ...
             */

            AALocalDecl expIfVarDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(data.ExpTypes[node], data), new TIdentifier("expIfVar"), null);

            ALocalLvalue thenExpIfVarLink  = new ALocalLvalue(new TIdentifier("expIfVar"));
            ALocalLvalue elseExpIfVarLink  = new ALocalLvalue(new TIdentifier("expIfVar"));
            ALocalLvalue usageExpIfVarLink = new ALocalLvalue(new TIdentifier("expIfVar"));

            ALvalueExp usageExpIfVarLinkExp = new ALvalueExp(usageExpIfVarLink);

            AAssignmentExp thenAssignment = new AAssignmentExp(new TAssign("="), thenExpIfVarLink, node.GetThen());
            AAssignmentExp elseAssignment = new AAssignmentExp(new TAssign("="), elseExpIfVarLink, node.GetElse());

            AIfThenElseStm ifStm = new AIfThenElseStm(new TLParen("("), node.GetCond(),
                                                      new ABlockStm(new TLBrace("{"),
                                                                    new AABlock(
                                                                        new ArrayList()
            {
                new AExpStm(new TSemicolon(";"),
                            thenAssignment)
            },
                                                                        new TRBrace("}"))),
                                                      new ABlockStm(new TLBrace("{"),
                                                                    new AABlock(
                                                                        new ArrayList()
            {
                new AExpStm(new TSemicolon(";"),
                            elseAssignment)
            },
                                                                        new TRBrace("}"))));

            data.LocalLinks[thenExpIfVarLink]          =
                data.LocalLinks[elseExpIfVarLink]      =
                    data.LocalLinks[usageExpIfVarLink] = expIfVarDecl;

            data.LvalueTypes[thenExpIfVarLink]                =
                data.LvalueTypes[elseExpIfVarLink]            =
                    data.LvalueTypes[usageExpIfVarLink]       =
                        data.ExpTypes[usageExpIfVarLinkExp]   =
                            data.ExpTypes[thenAssignment]     =
                                data.ExpTypes[elseAssignment] = expIfVarDecl.GetType();



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

            pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm), new ALocalDeclStm(new TSemicolon(";"), expIfVarDecl));
            pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm), ifStm);
            node.ReplaceBy(usageExpIfVarLinkExp);


            base.OutAIfExp(node);
        }
Exemplo n.º 23
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
            });
        }
Exemplo n.º 24
0
 private static void MakeCloneRefferences(PExp clone, PExp exp, SharedData data)
 {
     data.ExpTypes[clone] = data.ExpTypes[exp];
     if (exp is AIntConstExp || exp is AHexConstExp || exp is AOctalConstExp ||
         exp is AFixedConstExp || exp is AStringConstExp || exp is ACharConstExp ||
         exp is ABooleanConstExp || exp is ANullExp)
     {
         //No more required
     }
     else if (exp is AIncDecExp)
     {
         AIncDecExp aExp   = (AIncDecExp)exp;
         AIncDecExp aClone = (AIncDecExp)clone;
         MakeCloneRefferences(aClone.GetLvalue(), aExp.GetLvalue(), data);
     }
     else if (exp is ABinopExp)
     {
         ABinopExp aExp   = (ABinopExp)exp;
         ABinopExp aClone = (ABinopExp)clone;
         MakeCloneRefferences(aClone.GetLeft(), aExp.GetLeft(), data);
         MakeCloneRefferences(aClone.GetRight(), aExp.GetRight(), data);
     }
     else if (exp is AUnopExp)
     {
         AUnopExp aExp   = (AUnopExp)exp;
         AUnopExp aClone = (AUnopExp)clone;
         MakeCloneRefferences(aClone.GetExp(), aExp.GetExp(), data);
     }
     else if (exp is ASimpleInvokeExp)
     {
         ASimpleInvokeExp aExp   = (ASimpleInvokeExp)exp;
         ASimpleInvokeExp aClone = (ASimpleInvokeExp)clone;
         data.SimpleMethodLinks[aClone] = data.SimpleMethodLinks[aExp];
         for (int i = 0; i < aExp.GetArgs().Count; i++)
         {
             MakeCloneRefferences((PExp)aClone.GetArgs()[i], (PExp)aExp.GetArgs()[i], data);
         }
     }
     else if (exp is ANonstaticInvokeExp)
     {
         ANonstaticInvokeExp aExp   = (ANonstaticInvokeExp)exp;
         ANonstaticInvokeExp aClone = (ANonstaticInvokeExp)clone;
         data.StructMethodLinks[aClone] = data.StructMethodLinks[aExp];
         for (int i = 0; i < aExp.GetArgs().Count; i++)
         {
             MakeCloneRefferences((PExp)aClone.GetArgs()[i], (PExp)aExp.GetArgs()[i], data);
         }
         MakeCloneRefferences(aClone.GetReceiver(), aExp.GetReceiver(), data);
     }
     else if (exp is ALvalueExp)
     {
         ALvalueExp aExp   = (ALvalueExp)exp;
         ALvalueExp aClone = (ALvalueExp)clone;
         MakeCloneRefferences(aClone.GetLvalue(), aExp.GetLvalue(), data);
     }
     else if (exp is AAssignmentExp)
     {
         AAssignmentExp aExp   = (AAssignmentExp)exp;
         AAssignmentExp aClone = (AAssignmentExp)clone;
         MakeCloneRefferences(aClone.GetLvalue(), aExp.GetLvalue(), data);
         MakeCloneRefferences(aClone.GetExp(), aExp.GetExp(), data);
     }
     else if (exp is AParenExp)
     {
         AParenExp aExp   = (AParenExp)exp;
         AParenExp aClone = (AParenExp)clone;
         MakeCloneRefferences(aClone.GetExp(), aExp.GetExp(), data);
     }
     else if (exp is AStringConstExp)
     {
         AStringConstExp aExp   = (AStringConstExp)exp;
         AStringConstExp aClone = (AStringConstExp)clone;
         if (data.ObfuscatedStrings.ContainsKey(aExp))
         {
             data.ObfuscatedStrings[aClone] = data.ObfuscatedStrings[aExp];
         }
         if (data.StringsDontJoinRight.Contains(aExp))
         {
             data.StringsDontJoinRight.Add(aClone);
         }
     }
     else if (exp is ANewExp)
     {
         ANewExp aExp   = (ANewExp)exp;
         ANewExp aClone = (ANewExp)clone;
         if (data.ConstructorLinks.ContainsKey(aExp))
         {
             data.ConstructorLinks[aClone] = data.ConstructorLinks[aExp];
         }
         MakeCloneRefferences(aClone.GetType(), aExp.GetType(), data);
         for (int i = 0; i < aExp.GetArgs().Count; i++)
         {
             MakeCloneRefferences((PExp)aClone.GetArgs()[i], (PExp)aExp.GetArgs()[i], data);
         }
     }
     else if (exp is ACastExp)
     {
         ACastExp aExp   = (ACastExp)exp;
         ACastExp aClone = (ACastExp)clone;
         MakeCloneRefferences(aClone.GetType(), aExp.GetType(), data);
         MakeCloneRefferences(aClone.GetExp(), aExp.GetExp(), data);
     }
     else if (exp is ADelegateExp)
     {
         ADelegateExp aExp   = (ADelegateExp)exp;
         ADelegateExp aClone = (ADelegateExp)clone;
         if (data.DelegateCreationMethod.ContainsKey(aExp))
         {
             data.DelegateCreationMethod[aClone] = data.DelegateCreationMethod[aExp];
         }
         MakeCloneRefferences(aClone.GetType(), aExp.GetType(), data);
         MakeCloneRefferences(aClone.GetLvalue(), aExp.GetLvalue(), data);
     }
     else if (exp is ADelegateInvokeExp)
     {
         ADelegateInvokeExp aExp   = (ADelegateInvokeExp)exp;
         ADelegateInvokeExp aClone = (ADelegateInvokeExp)clone;
         MakeCloneRefferences(aClone.GetReceiver(), aExp.GetReceiver(), data);
         for (int i = 0; i < aExp.GetArgs().Count; i++)
         {
             MakeCloneRefferences((PExp)aClone.GetArgs()[i], (PExp)aExp.GetArgs()[i], data);
         }
     }
     else if (exp is AIfExp)
     {
         AIfExp aExp   = (AIfExp)exp;
         AIfExp aClone = (AIfExp)clone;
         MakeCloneRefferences(aClone.GetCond(), aExp.GetCond(), data);
         MakeCloneRefferences(aClone.GetThen(), aExp.GetThen(), data);
         MakeCloneRefferences(aClone.GetElse(), aExp.GetElse(), data);
     }
     else
     {
         throw new Exception("Unexpect exp. Got " + exp.GetType());
     }
 }
Exemplo n.º 25
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);
        }