public override void CaseALocalDeclStm(ALocalDeclStm node)
        {
            AMethodDecl pMethod = Util.GetAncestor<AMethodDecl>(node);
            AALocalDecl decl = (AALocalDecl) node.GetLocalDecl();

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

            AABlock block = (AABlock) pMethod.GetBlock();
            block.GetStatements().Insert(0, node);
        }
        public override void CaseASimpleInvokeExp(ASimpleInvokeExp node)
        {
            PExp expNode = (PExp)node;
            PType type = data.ExpTypes[expNode];
            if (type is APointerType) type = new ANamedType(new TIdentifier("string"), null);
            ALocalLvalue local = new ALocalLvalue(new TIdentifier("tempName", 0, 0));
            ALvalueExp exp = new ALvalueExp(local);
            PStm stm = Util.GetAncestor<PStm>(node);
            AABlock block = (AABlock)stm.Parent();
            node.ReplaceBy(exp);
            AALocalDecl localDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                    Util.MakeClone(type, data),
                                                    new TIdentifier(varName, 0, 0), expNode);
            ALocalDeclStm newStm = new ALocalDeclStm(new TSemicolon(";"), localDecl);
            block.GetStatements().Insert(block.GetStatements().IndexOf(stm), newStm);
            NewStatements.Add(newStm);

            data.LvalueTypes[local] = type;
            data.ExpTypes[exp] = type;
            data.LocalLinks[local] = localDecl;
            //localDecl.Apply(this);
            exp.Apply(this);
            return;
        }
 public override void CaseALocalDeclStm(ALocalDeclStm node)
 {
     //Create node
     GetNode(node);
 }
 public virtual void CaseALocalDeclStm(ALocalDeclStm node)
 {
     DefaultCase(node);
 }
 public virtual void OutALocalDeclStm(ALocalDeclStm node)
 {
     DefaultOut(node);
 }
 public virtual void InALocalDeclStm(ALocalDeclStm node)
 {
     DefaultIn(node);
 }
 public override void CaseALocalDeclStm(ALocalDeclStm node)
 {
     InALocalDeclStm(node);
     if (node.GetLocalDecl() != null)
     {
         node.GetLocalDecl().Apply(this);
     }
     if (node.GetToken() != null)
     {
         node.GetToken().Apply(this);
     }
     OutALocalDeclStm(node);
 }
Esempio n. 8
0
        public override void OutAShadySAssignmentExp(AShadySAssignmentExp node)
        {
            if (node.GetLocalDeclRight().Count == 1 &&
                ((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetName() == null)
            {
                //Assignment expression
                //Cant have any [] or * after first lvalue
                if (node.GetPostPointers().Count > 0)
                {
                    Token token;
                    PShadyDynamicOps op = (PShadyDynamicOps)node.GetPostPointers()[0];
                    if (op is APointerShadyDynamicOps)
                        token = ((APointerShadyDynamicOps) op).GetToken();
                    else
                        token = ((AArrayShadyDynamicOps)op).GetToken();
                    errors.Add(new ErrorCollection.Error(token, currentSourceFile, "Didn't expect " + token.Text + " there. Im very confused."));
                }
                if (node.GetGenericToken() != null)
                    errors.Add(new ErrorCollection.Error(node.GetGenericToken(),
                                                         "What the hell is this? I didn't see that coming. Or maybe I did.. But I don't like it!"));

                //an assignment can't be const);
                if (node.GetConst() != null)
                    errors.Add(new ErrorCollection.Error(node.GetConst(), currentSourceFile, "Unexpected const", false));
                //An assignment must have a right side
                if (((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetInit() == null ||
                    ((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetAssignop() == null)
                {
                    Token token = GetToken(node.GetLvalue());
                    errors.Add(new ErrorCollection.Error(token, currentSourceFile, "Expected assignment", false));
                    node.Parent().RemoveChild(node);
                    return;
                }
                ASAssignmentExp exp = new ASAssignmentExp(
                    ((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetAssignop(), node.GetLvalue(),
                    ((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetInit());
                node.ReplaceBy(exp);
                exp.Apply(this);
            }
            else
            {
                //Local decl
                AMultiLocalDecl localDecl = new AMultiLocalDecl(node.GetConst(), LvalueToType(node.GetLvalue(), node.GetPostPointers(), node.GetGenericToken(), node.GetGenericTypes()),
                                                                new ArrayList());
                while (node.GetLocalDeclRight().Count > 0)
                {
                    localDecl.GetLocalDeclRight().Add(node.GetLocalDeclRight()[0]);
                }

                AExpStm expStm = Util.GetAncestor<AExpStm>(node);
                ALocalDeclStm localDeclStm = new ALocalDeclStm(expStm.GetToken(), localDecl);
                expStm.ReplaceBy(localDeclStm);
                localDeclStm.Apply(this);
            }
        }
        public override void OutAIncDecExp(AIncDecExp node)
        {
            PIncDecOp op = node.GetIncDecOp();
            if (!Util.HasAncestor<AABlock>(node))
            {
                Token token = null;
                if (op is APostDecIncDecOp)
                    token = ((APostDecIncDecOp) op).GetToken();
                else if (op is APreDecIncDecOp)
                    token = ((APreDecIncDecOp)op).GetToken();
                else if (op is APostIncIncDecOp)
                    token = ((APostIncIncDecOp)op).GetToken();
                else if (op is APreIncIncDecOp)
                    token = ((APreIncIncDecOp)op).GetToken();
                errors.Add(new ErrorCollection.Error(token, LocRM.GetString("ErrorText114")));
                throw new ParserException(token, "TypeChecking.OutAIncDecExp");
            }

            bool plus = op is APreIncIncDecOp || op is APostIncIncDecOp;
            if (op is APreIncIncDecOp || op is APreDecIncDecOp || node.Parent() is AExpStm)
            {//++i, --i, i++; or i--;
                //Replace with assignment
                //<exp>++ => <exp> + 1
                //(... foo = <exp> ...)++ => (... foo = <exp> ...) = (... foo ...) + 1
                //(... foo++ ...)++ => (... foo++ ...) = (... foo ...) + 1

                PLvalue clone = Util.MakeClone(node.GetLvalue(), data);
                clone.Apply(new AssignFixup(data));
                PBinop binop;
                if (plus)
                {
                    binop = new APlusBinop(new TPlus("+"));
                }
                else
                {
                    binop = new AMinusBinop(new TMinus("-"));
                }
                ABinopExp addExp = new ABinopExp(new ALvalueExp(clone), binop, new AIntConstExp(new TIntegerLiteral("1")));
                AAssignmentExp exp = new AAssignmentExp(new TAssign("="), node.GetLvalue(), addExp);
                node.ReplaceBy(exp);
                exp.Apply(this);
                return;
            }
            {//i++ or i--
                //Make a new local so
                //int newLocal = i;
                //++i;
                //...newLocal...;
                PLvalue lvalueClone = Util.MakeClone(node.GetLvalue(), data);
                PExp exp = new ALvalueExp(Util.MakeClone(node.GetLvalue(), data));
                data.ExpTypes[exp] = data.LvalueTypes[node.GetLvalue()];
                AALocalDecl localDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(data.LvalueTypes[node.GetLvalue()], data), new TIdentifier("incDecVar"), exp);
                ALocalDeclStm localDeclStm = new ALocalDeclStm(new TSemicolon(";"), localDecl);

                node.SetIncDecOp(plus
                                     ? (PIncDecOp) new APreIncIncDecOp(new TPlusPlus("++"))
                                     : new APreDecIncDecOp(new TMinusMinus("--")));

                ALocalLvalue lvalue = new ALocalLvalue(new TIdentifier(localDecl.GetName().Text));
                exp = new ALvalueExp(lvalue);
                data.ExpTypes[exp] = data.LvalueTypes[lvalue] = data.LvalueTypes[node.GetLvalue()];
                data.LocalLinks[lvalue] = localDecl;

                PStm pStm = Util.GetAncestor<PStm>(node);
                node.ReplaceBy(exp);
                PStm nodeStm = new AExpStm(new TSemicolon(";"), node);

                AABlock block = (AABlock) pStm.Parent();

                block.GetStatements().Insert(block.GetStatements().IndexOf(pStm), localDeclStm);
                block.GetStatements().Insert(block.GetStatements().IndexOf(pStm), nodeStm);
                localDeclStm.Apply(this);
                nodeStm.Apply(this);
                exp.Apply(this);

                if (pStm is AWhileStm && Util.IsAncestor(exp, ((AWhileStm)pStm).GetCondition()))
                {
                    AWhileStm aStm = (AWhileStm)pStm;
                    //Insert
                    // newLocal = i
                    // ++i
                    //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)
                    {
                        PLvalue nodeLvalue1 = Util.MakeClone(lvalueClone, data);
                        PExp nodeLvalue1Exp = new ALvalueExp(nodeLvalue1);
                        PLvalue nodeLvalue2 = Util.MakeClone(lvalueClone, data);
                        ALocalLvalue newLocalLvalue = new ALocalLvalue(new TIdentifier("newLocal"));
                        data.LocalLinks[newLocalLvalue] = localDecl;
                        AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), newLocalLvalue, nodeLvalue1Exp);
                        PStm assignmentStm = new AExpStm(new TSemicolon(";"), assignment);

                        AIncDecExp newIncDecExp = new AIncDecExp(nodeLvalue2, plus
                                                                                  ? (PIncDecOp)
                                                                                    new APreIncIncDecOp(
                                                                                        new TPlusPlus("++"))
                                                                                  : new APreDecIncDecOp(
                                                                                        new TMinusMinus("--")));
                        PStm newIncDecExpStm = new AExpStm(new TSemicolon(";"), newIncDecExp);

                        block = (AABlock)continueStm.Parent();
                        block.GetStatements().Insert(block.GetStatements().IndexOf(continueStm), assignmentStm);
                        block.GetStatements().Insert(block.GetStatements().IndexOf(continueStm), newIncDecExpStm);

                        assignment.Apply(this);
                        newIncDecExp.Apply(this);
                    }
                }
                return;
            }
        }
 public override void CaseALocalDeclStm(ALocalDeclStm node)
 {
     node.GetLocalDecl().Apply(this);
     Write(";\n");
 }
        public override void CaseAMethodDecl(AMethodDecl node)
        {
            if (firstMethodCall)
                StatementRemover.Parse(node);
            firstMethodCall = false;

            before.Clear();
            after.Clear();
            uses.Clear();
            intersectingLocals.Clear();
            definedLocals.Clear();
            renamedLocals.Clear();
            assigns.Clear();
            changes = false;

            //Make uses
            setUses = true;
            base.CaseAMethodDecl(node);
            setUses = false;

            //Build a list of what's visible
            do
            {
                changes = false;
                base.CaseAMethodDecl(node);
            } while (changes);

            setSpans = true;
            base.CaseAMethodDecl(node);
            setSpans = false;

            //Join locals of same type, unless they are both parameters or they are listed as intersecting
            for (int i = 0; i < definedLocals.Count; i++)
            {
                for (int j = i + 1; j < definedLocals.Count; j++)
                {
                    AALocalDecl decl1 = definedLocals[i];
                    AALocalDecl decl2 = definedLocals[j];

                    if (Util.TypeToString(decl1.GetType()) == Util.TypeToString(decl2.GetType()) &&
                        !intersectingLocals.Contains(new Pair(decl1, decl2)))
                    {
                        if (Util.GetAncestor<AABlock>(decl1) == null &&
                            Util.GetAncestor<AABlock>(decl2) == null)
                            continue;

                        AALocalDecl replacement = decl1;
                        AALocalDecl replaced = decl2;

                        //Dont replace the parameter
                        if (Util.GetAncestor<AABlock>(replaced) == null)
                        {
                            replacement = decl2;
                            replaced = decl1;
                            i--;
                        }
                        j--;

                        renamedLocals.Add(replaced, replacement);
                        definedLocals.Remove(replaced);
                        foreach (Pair pair in intersectingLocals)
                        {
                            if (pair.Local1 == replaced)
                                pair.Local1 = replacement;
                            if (pair.Local2 == replaced)
                                pair.Local2 = replacement;
                        }

                        //Assign defaults
                        if (replaced.GetInit() == null)
                        {
                            ALocalLvalue lvalue = new ALocalLvalue(new TIdentifier(replaced.GetName().Text));
                            finalTrans.data.LocalLinks[lvalue] = replaced;
                            finalTrans.data.LvalueTypes[lvalue] = replaced.GetType();
                            List<PStm> statements = AssignDefault(lvalue);
                            PStm pStm = Util.GetAncestor<PStm>(replaced);
                            AABlock pBlock = (AABlock) pStm.Parent();
                            foreach (PStm statement in statements)
                            {
                                pBlock.GetStatements().Insert(pBlock.GetStatements().IndexOf(pStm), statement);
                            }
                            pBlock.RemoveChild(pStm);
                        }
                        else
                        {
                            //Make an assignment expression instead
                            ALocalDeclStm declStm = (ALocalDeclStm)replaced.Parent();
                            ALocalLvalue lvalue = new ALocalLvalue((TIdentifier)replaced.GetName().Clone());
                            finalTrans.data.LvalueTypes[lvalue] = replaced.GetType();
                            AAssignmentExp exp = new AAssignmentExp(new TAssign("=", lvalue.GetName().Line, lvalue.GetName().Pos), lvalue, replaced.GetInit());
                            AExpStm expStm = new AExpStm(declStm.GetToken(), exp);
                            declStm.ReplaceBy(expStm);
                            finalTrans.data.LvalueTypes[lvalue] = replacement.GetType();
                            finalTrans.data.ExpTypes[exp] = replacement.GetType();
                            finalTrans.data.LocalLinks[lvalue] = replacement;
                        }
                    }
                }
            }

            //Unique names
            List<string> names = new List<string>();
            //Avoid clash with methods/fields/structs
            names.AddRange(finalTrans.data.Methods.Select(declItem => declItem.Decl.GetName().Text));
            names.AddRange(finalTrans.data.Fields.Select(declItem => declItem.Decl.GetName().Text));
            names.AddRange(finalTrans.data.Structs.Select(declItem => declItem.Decl.GetName().Text));
            foreach (AALocalDecl local in definedLocals)
            {
                string name = local.GetName().Text;
                int version = 1;
                while (names.Contains(name))
                {
                    version++;
                    name = local.GetName().Text + version;
                }
                local.GetName().Text = name;
                names.Add(name);
            }

            //Move defined locals to the start of the method
            foreach (AALocalDecl formal in node.GetFormals())
            {
                definedLocals.Remove(formal);
            }
            AABlock block = (AABlock)node.GetBlock();
            for (int i = 0; i < block.GetStatements().Count; i++)
            {
                ALocalDeclStm stm;
                if (block.GetStatements()[i] is ALocalDeclStm)
                {
                    stm = (ALocalDeclStm)block.GetStatements()[i];
                    definedLocals.Remove((AALocalDecl)stm.GetLocalDecl());
                    continue;
                }
                //Add the rest at i
                if (definedLocals.Count == 0)
                    break;
                AALocalDecl decl = definedLocals[0];
                definedLocals.RemoveAt(0);

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

                stm = new ALocalDeclStm(new TSemicolon(";"), decl);
                block.GetStatements().Insert(i, stm);
            }

            fixRefferences = true;
            base.CaseAMethodDecl(node);
            fixRefferences = false;

            //If we have an assignment to a local where the stored result is never used, remove the assignment

            //Since we changed some statements, rebuild stuff
            before.Clear();
            after.Clear();
            uses.Clear();
            intersectingLocals.Clear();
            definedLocals.Clear();
            renamedLocals.Clear();
            assigns.Clear();
            changes = false;

            //Make uses
            setUses = true;
            base.CaseAMethodDecl(node);
            setUses = false;

            //Build a list of what's visible
            do
            {
                changes = false;
                base.CaseAMethodDecl(node);
            } while (changes);

            PStm[] stms = new PStm[before.Keys.Count];
            before.Keys.CopyTo(stms, 0);
            foreach (PStm stm in stms)
            {
                if (assigns[stm] != null && //Assignment exp
                    !after[stm].Contains(assigns[stm]) && //Assignment unused
                    Util.GetAncestor<AMethodDecl>(assigns[stm]) != null &&
                    !(stm is ALocalDeclStm))//It is to a local
                {
                    stm.Apply(new MoveMethodDeclsOut(finalTrans.data));
                    stm.Parent().RemoveChild(stm);
                }
            }

            //Remove foo = foo;
            RemoveStupidAssignments assignmentRemover = new RemoveStupidAssignments(finalTrans.data);
            node.Apply(assignmentRemover);

            //Remove unused local variables
            foreach (AALocalDecl local in definedLocals)
            {
                if (Util.GetAncestor<AAProgram>(local) != null && Util.GetAncestor<AABlock>(local) != null &&
                    !finalTrans.data.LocalLinks.Where(p => p.Value == local).Any(p => Util.GetAncestor<AAProgram>(p.Key) != null))
                    local.Parent().Parent().RemoveChild(local.Parent());
            }

            if (assignmentRemover.RemovedOne)
            {
                CaseAMethodDecl(node);
                return;
            }

            //If an assignment to a variable is completely local, and that assignment is only used once, put the assignment where it is used
            //Since we changed some statements, rebuild stuff
            before.Clear();
            after.Clear();
            uses.Clear();
            intersectingLocals.Clear();
            definedLocals.Clear();
            renamedLocals.Clear();
            assigns.Clear();
            changes = false;

            //Make uses
            setUses = true;
            base.CaseAMethodDecl(node);
            setUses = false;

            //Build a list of what's visible
            do
            {
                changes = false;
                base.CaseAMethodDecl(node);
            } while (changes);
            foreach (KeyValuePair<PStm, AALocalDecl> pair in assigns)
            {
                PStm assignStm = pair.Key;
                AALocalDecl assignVar = pair.Value;
                bool isLocal = Util.IsLocal(assignStm, finalTrans.data);
                bool containsInvokeInPrevStm = false;
                if (assignVar != null && after[assignStm].Contains(assignVar))
                {
                    bool dontMove = false;
                    //First, if there are any conditional parrent statement, where the variable is in live before the stm, then we can't move it
                    PStm condParent = (PStm) Util.GetNearestAncestor(assignStm, typeof (AIfThenStm), typeof (AIfThenElseStm),
                                                                     typeof (AWhileStm));
                    while (condParent != null)
                    {
                        if (before[condParent].Contains(assignVar))
                        {
                            dontMove = true;
                            break;
                        }
                        condParent = (PStm)Util.GetNearestAncestor(condParent.Parent(), typeof(AIfThenStm), typeof(AIfThenElseStm),
                                                                     typeof(AWhileStm));
                    }

                    PStm useStm = null;
                    List<PStm> successors = GetSuccessor(assignStm);
                    bool containsConditionalAssignments = false;
                    while (successors.Count > 0)
                    {
                        if (successors.Count > 500)
                            useStm = useStm;
                        PStm successor = successors[0];
                        successors.RemoveAt(0);
                        if (uses[successor].Contains(assignVar))
                        {
                            if (useStm == null && !containsConditionalAssignments && !(successor is AWhileStm))
                                useStm = successor;
                            else
                            {
                                dontMove = true;
                                break;
                            }
                        }
                        if (after[successor].Contains(assignVar) && !(assigns.ContainsKey(successor) && assigns[successor] == assignVar))
                        {
                            List<PStm> newSuccessors = GetSuccessor(successor);
                            foreach (PStm stm in newSuccessors)
                            {
                                if (!successors.Contains(stm))
                                    successors.Add(stm);
                            }
                        }
                        if (assigns.ContainsKey(successor) && uses[assignStm].Contains(assigns[successor]))
                        {
                            dontMove = true;
                            break;
                        }

                        if (assigns.ContainsKey(successor) && assigns[successor] == assignVar)
                        {
                            condParent = (PStm)Util.GetNearestAncestor(successor, typeof(AIfThenStm), typeof(AIfThenElseStm),
                                                                       typeof(AWhileStm));
                            while (condParent != null)
                            {
                                if (!Util.IsAncestor(assignStm, condParent))
                                {
                                    containsConditionalAssignments = true;
                                    break;
                                }
                                condParent = (PStm)Util.GetNearestAncestor(condParent.Parent(), typeof(AIfThenStm), typeof(AIfThenElseStm),
                                                                             typeof(AWhileStm));
                            }

                            //If we found a usage, and it is inside a while that the assignStm is not inside, but we are inside, don't move
                            if (useStm != null)
                            {
                                AWhileStm whileParant = Util.GetAncestor<AWhileStm>(successor);
                                while (whileParant != null)
                                {
                                    if (Util.IsAncestor(useStm, whileParant) && !Util.IsAncestor(assignStm, whileParant))
                                    {
                                        dontMove = true;
                                        break;
                                    }
                                    whileParant = Util.GetAncestor<AWhileStm>(whileParant.Parent());
                                }
                            }
                        }

                        FindInvoke finder  = new FindInvoke();
                        successor.Apply(finder);
                        if (finder.ContainsInvoke && useStm == null)
                            containsInvokeInPrevStm = true;
                    }

                    if (useStm != null && !dontMove)
                    {
                        //If assignStm is inside an if, and the use stm is not, and there is another assignment
                        //to the same variable in an else block, then don't join
                        AIfThenElseStm ifThenElse = Util.GetAncestor<AIfThenElseStm>(assignStm);
                        while (ifThenElse != null)
                        {
                            if (!Util.IsAncestor(useStm, ifThenElse))
                            {
                                ABlockStm otherBlock;
                                if (Util.IsAncestor(assignStm, ifThenElse.GetThenBody()))
                                    otherBlock = (ABlockStm) ifThenElse.GetElseBody();
                                else
                                    otherBlock = (ABlockStm)ifThenElse.GetThenBody();
                                StmEnum enumerator = new StmEnum(otherBlock);
                                while (enumerator.MoveNext())
                                {
                                    PStm stm = (PStm) enumerator.Current;
                                    if (assigns.ContainsKey(stm) && assigns[stm] == assignVar)
                                    {
                                        dontMove = true;
                                        break;
                                    }
                                }
                                if (dontMove)
                                    break;
                            }
                            ifThenElse = Util.GetAncestor<AIfThenElseStm>(ifThenElse.Parent());
                        }

                        //If the assignStm or useStm is inside a while, it could get complicated
                        //if (Util.HasAncestor<AWhileStm>(assignStm) || Util.HasAncestor<AWhileStm>(useStm))
                        //    dontMove = true;
                    }

                    if (useStm != null && dontMove == false && (isLocal || !containsInvokeInPrevStm))
                    {

                        //Ensure that it is not used twice in this stm
                        FindLvalue finder = new FindLvalue(assignVar, finalTrans.data);
                        useStm.Apply(finder);
                        if (!finder.IsUsedTwice && (isLocal || !finder.HasPrevInvoke))
                        {
                            PExp rightside;
                            if (assignStm is ALocalDeclStm)
                            {
                                rightside = ((AALocalDecl)((ALocalDeclStm)assignStm).GetLocalDecl()).GetInit();
                            }
                            else
                            {
                                rightside = ((AAssignmentExp)((AExpStm)assignStm).GetExp()).GetExp();
                                assignStm.Parent().RemoveChild(assignStm);
                            }
                            if (rightside != null)
                            {
                                finder.Lvalue.Parent().ReplaceBy(rightside);
                                CaseAMethodDecl(node);
                                return;
                            }
                        }
                    }
                }
            }

            if (StatementRemover.Parse(node))
            {
                CaseAMethodDecl(node);
                return;
            }
            firstMethodCall = true;
        }
        public override void OutAShadySAssignmentExp(AShadySAssignmentExp node)
        {
            if (node.GetLocalDeclRight().Count == 1 &&
                ((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetName() == null)
            {
                //Assignment expression

                //an assignment can't be const);
                //An assignment must have a right side
                if (((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetInit() == null ||
                    ((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetAssignop() == null)
                {
                    node.Parent().RemoveChild(node);
                    return;
                }
                ASAssignmentExp exp = new ASAssignmentExp(
                    ((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetAssignop(), node.GetLvalue(),
                    ((AALocalDeclRight) node.GetLocalDeclRight()[0]).GetInit());
                node.ReplaceBy(exp);
                exp.Apply(this);
            }
            else
            {

                //Local decl
                AMultiLocalDecl localDecl = new AMultiLocalDecl(node.GetConst(), LvalueToType(node.GetLvalue(), node.GetPostPointers(), node.GetGenericToken(), node.GetGenericTypes()),
                                                                new ArrayList());
                while (node.GetLocalDeclRight().Count > 0)
                {
                    localDecl.GetLocalDeclRight().Add(node.GetLocalDeclRight()[0]);
                }

                AExpStm expStm = Util.GetAncestor<AExpStm>(node);
                ALocalDeclStm localDeclStm = new ALocalDeclStm(expStm.GetToken(), localDecl);
                expStm.ReplaceBy(localDeclStm);
                localDeclStm.Apply(this);
            }
        }
Esempio n. 13
0
            public override void CaseANewExp(ANewExp node)
            {
                //Call new object or new array
                ASimpleInvokeExp invoke = new ASimpleInvokeExp(new TIdentifier("invoke"), new ArrayList());
                ANamedType pointerType = new ANamedType(new TIdentifier("string"), null);
                if (node.GetType() is AArrayTempType)
                {
                    if (newArrayMethod == null) CreateNewArrayMethod(node, data);

                    node.GetType().Apply(this);
                    AArrayTempType type = (AArrayTempType) node.GetType();
                    invoke.GetArgs().Add(Util.MakeClone(type.GetDimention(), data));
                    data.SimpleMethodLinks[invoke] = newArrayMethod;
                }
                else if (Util.IsIntPointer(node, node.GetType(), data))
                {
                    if (node.GetType() is ANamedType && data.StructTypeLinks.ContainsKey((ANamedType) node.GetType()))
                        data.SimpleMethodLinks[invoke] = CreateNewObjectMethod(node, data.StructTypeLinks[(ANamedType) node.GetType()],
                                                                               data);
                    else
                    {
                        data.SimpleMethodLinks[invoke] = CreateNewObjectMethod(node,
                                                                                data.EnrichmentTypeLinks[node.GetType()],
                                                                                data);
                    }
                    pointerType = new ANamedType(new TIdentifier("int"), null);
                }
                else
                {
                    if (newObjectMethod == null) CreateNewObjectMethod(node, data);

                    data.SimpleMethodLinks[invoke] = newObjectMethod;
                }
                node.ReplaceBy(invoke);
                data.ExpTypes[invoke] = pointerType;

                //Call initializer
                if (data.ConstructorLinks.ContainsKey(node))
                {
                    PStm pStm = Util.GetAncestor<PStm>(invoke);
                    AABlock pblock = (AABlock) pStm.Parent();

                    PLvalue lvalue;
                    ALvalueExp lvalueExp;
                    PStm stm;
                    AAssignmentExp assignment = null;
                    AALocalDecl localDecl = null;
                    if (invoke.Parent() is AAssignmentExp)
                    {
                        AAssignmentExp parent = (AAssignmentExp) invoke.Parent();
                        assignment = parent;
                        /*lvalue = parent.GetLvalue();
                        lvalue.Apply(new MoveMethodDeclsOut("pointerVar", data));
                        lvalue = Util.MakeClone(lvalue, data);*/
                    }
                    else if (invoke.Parent() is AALocalDecl)
                    {
                        AALocalDecl parent = (AALocalDecl) invoke.Parent();
                        localDecl = parent;
                        /*lvalue = new ALocalLvalue(new TIdentifier(parent.GetName().Text));

                        data.LocalLinks[(ALocalLvalue) lvalue] = parent;
                        data.LvalueTypes[lvalue] = parent.GetType();*/
                    }
                    else
                    {
                        //Move the new invocation out into a local decl, and use that
                        localDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                                Util.MakeClone(pointerType, data),
                                                                new TIdentifier("newVar"), null);
                        ALocalLvalue localLvalue = new ALocalLvalue(new TIdentifier("newVar"));
                        lvalueExp = new ALvalueExp(localLvalue);
                        invoke.ReplaceBy(lvalueExp);
                        localDecl.SetInit(invoke);
                        stm = new ALocalDeclStm(new TSemicolon(";"), localDecl);
                        pblock.GetStatements().Insert(pblock.GetStatements().IndexOf(pStm), stm);
                        pStm = stm;
                        //lvalue = new ALocalLvalue(new TIdentifier("newVar"));

                        //data.LocalLinks[(ALocalLvalue) lvalue] =
                            data.LocalLinks[localLvalue] = localDecl;
                        //data.LvalueTypes[lvalue] =
                            data.LvalueTypes[localLvalue] =
                            data.ExpTypes[lvalueExp] = localDecl.GetType();
                    }

                    ASimpleInvokeExp oldInvoke = invoke;
                    invoke = new ASimpleInvokeExp(new TIdentifier("renameMe"), new ArrayList());
                    while (node.GetArgs().Count > 0)
                    {
                        invoke.GetArgs().Add(node.GetArgs()[0]);
                    }
                    if (assignment != null)
                    {
                        assignment.SetExp(invoke);
                        invoke.GetArgs().Add(oldInvoke);
                    }
                    else
                    {
                        localDecl.SetInit(invoke);
                        invoke.GetArgs().Add(oldInvoke);
                    }
                    //lvalueExp = new ALvalueExp(lvalue);
                    //invoke.GetArgs().Add(lvalueExp);
                    //stm = new AExpStm(new TSemicolon(";"), invoke);
                    //pblock.GetStatements().Insert(pblock.GetStatements().IndexOf(pStm) + 1, stm);

                    //data.ExpTypes[lvalueExp] = data.LvalueTypes[lvalue];
                    data.SimpleMethodLinks[invoke] = data.ConstructorMap[data.ConstructorLinks[node]];
                    data.ExpTypes[invoke] = data.ConstructorMap[data.ConstructorLinks[node]].GetReturnType();
                    invoke.Apply(this);
                }
            }
        public static List<AABlock> Inline(ASimpleInvokeExp node, FinalTransformations finalTrans)
        {
            /*if (Util.GetAncestor<AMethodDecl>(node) != null && Util.GetAncestor<AMethodDecl>(node).GetName().Text == "UIChatFrame_LeaveChannel")
                node = node;*/

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

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

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

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

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

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

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

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

            AABlock afterBlock = new AABlock();

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

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

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

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

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

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

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

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

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

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

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

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

            pBlock = (AABlock)pStm.Parent();

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

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

                node.ReplaceBy(exp);
            }
            return new List<AABlock>() { outerBlock };
        }
 public override void InALocalDeclStm(ALocalDeclStm node)
 {
     if (node.GetLocalDecl() == null)
         node = node;
 }