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);
 }
Beispiel #2
0
 public override void CaseAFieldLvalue(AFieldLvalue node)
 {
     if (data.FieldLinks[node].GetConst() == null)
     {
         IsLocal = false;
     }
 }
        private int FoldInt(PLvalue lvalue, ref bool valid)
        {
            if (!valid)
            {
                return(-1);
            }

            if (lvalue is ALocalLvalue)
            {
                ALocalLvalue aLvalue = (ALocalLvalue)lvalue;
                AALocalDecl  decl    = data.LocalLinks[aLvalue];
                if (decl.GetConst() == null)
                {
                    valid = false;
                    return(-1);
                }
                return(FoldInt(decl.GetInit(), ref valid));
            }
            if (lvalue is AFieldLvalue)
            {
                AFieldLvalue aLvalue = (AFieldLvalue)lvalue;
                AFieldDecl   decl    = data.FieldLinks[aLvalue];
                if (decl.GetConst() == null)
                {
                    valid = false;
                    return(-1);
                }
                return(FoldInt(decl.GetInit(), ref valid));
            }
            if (lvalue is AStructFieldLvalue)
            {
                AStructFieldLvalue aLvalue = (AStructFieldLvalue)lvalue;
                AALocalDecl        decl    = data.StructMethodFieldLinks[aLvalue];
                if (decl.GetConst() == null)
                {
                    valid = false;
                    return(-1);
                }
                return(FoldInt(decl.GetInit(), ref valid));
            }
            if (lvalue is AStructLvalue)
            {
                AStructLvalue aLvalue = (AStructLvalue)lvalue;
                AALocalDecl   decl    = data.StructFieldLinks[aLvalue];
                if (decl.GetConst() == null)
                {
                    valid = false;
                    return(-1);
                }
                return(FoldInt(decl.GetInit(), ref valid));
            }

            valid = false;
            return(-1);
        }
        public override void CaseAFieldLvalue(AFieldLvalue node)
        {
            if (processStructs)
            {
                return;
            }

            AFieldDecl decl = finalTrans.data.FieldLinks[node];

            if (!usedFields.Contains(decl))
            {
                usedFields.Add(decl);
            }
            base.CaseAFieldLvalue(node);
        }
            public override void OutAFieldLvalue(AFieldLvalue node)
            {
                if (currentMethod == null)
                {
                    return;
                }

                AFieldDecl field = data.FieldLinks[node];

                Node n = node;

                while (true)
                {
                    n = Util.GetNearestAncestor(n.Parent(), typeof(AMethodDecl), typeof(AAssignmentExp), typeof(AArrayLvalue));
                    if (n is AMethodDecl)
                    {
                        break;
                    }
                    if (n is AAssignmentExp)
                    {
                        if (Util.IsAncestor(node, ((AAssignmentExp)n).GetLvalue()))
                        {
                            if (!WrittenFields[currentMethod].Contains(field))
                            {
                                WrittenFields[currentMethod].Add(field);
                            }
                            return;
                        }
                        break;
                    }
                    if (n is AArrayLvalue)
                    {
                        if (Util.IsAncestor(node, ((AArrayLvalue)n).GetBase()))
                        {
                            continue;
                        }
                        break;
                    }
                    break;
                }

                if (!ReadFields[currentMethod].Contains(field))
                {
                    ReadFields[currentMethod].Add(field);
                }
            }
Beispiel #6
0
        public override void OutAFieldDecl(AFieldDecl node)
        {
            if (node.GetInit() != null)
            {
                return;
            }

            //Field - init in main entry
            AABlock      pBlock      = (AABlock)finalTrans.mainEntryFieldInitBlock.GetBlock();
            int          insertIndex = 0;
            AFieldLvalue lvalue      = new AFieldLvalue(new TIdentifier(node.GetName().Text));

            data.FieldLinks[lvalue]  = node;
            data.LvalueTypes[lvalue] = node.GetType();
            AABlock block = new AABlock(new ArrayList(), new TRBrace("}"));

            MakeAssignments(block, node.GetType(), lvalue, true);

            if (block.GetStatements().Count != 0)
            {
                pBlock.GetStatements().Insert(insertIndex, new ABlockStm(new TLBrace("{"), block));
            }
        }
Beispiel #7
0
        public override void OutAFieldLvalue(AFieldLvalue node)
        {
            if (folding)
            {
                AFieldDecl field = data.FieldLinks[node];
                //Must be int and must be const
                if (!(field.GetType() is ANamedType && ((ANamedType)field.GetType()).IsPrimitive("int")))
                {
                    errors.Add(
                        new ErrorCollection.Error(node.GetName(),
                                                  LocRM.GetString("ErrorText59"),
                                                  false, new ErrorCollection.Error(field.GetName(), LocRM.GetString("ErrorText60"))), true);
                    throw new ParserException(node.GetName(), "TypeLinking.OutAFieldLvalue");
                }

                if (field.GetConst() == null)
                {
                    if (!isANewExp)
                    {
                        errors.Add(
                            new ErrorCollection.Error(node.GetName(),
                                                      LocRM.GetString("ErrorText61"),
                                                      false), true);
                        throw new ParserException(node.GetName(), "TypeLinking.OutAFieldLvalue");
                    }
                }
                if (field.GetInit() == null)//An error will be given earlier - constant fields must have an initializer
                {
                    throw new ParserException(node.GetName(), "TypeLinking.OutAFieldLvalue");
                }
                field.GetInit().Apply(this);
            }
            else
            {
                base.OutAFieldLvalue(node);
            }
        }
Beispiel #8
0
 public static bool ReturnsTheSame(PLvalue left, PLvalue right, SharedData data)
 {
     if (left.GetType() != right.GetType())
     {
         return(false);
     }
     if (left is ALocalLvalue)
     {
         ALocalLvalue aLeft  = (ALocalLvalue)left;
         ALocalLvalue aRight = (ALocalLvalue)right;
         return(data.LocalLinks[aLeft] == data.LocalLinks[aRight]);
     }
     if (left is AFieldLvalue)
     {
         AFieldLvalue aLeft  = (AFieldLvalue)left;
         AFieldLvalue aRight = (AFieldLvalue)right;
         return(data.FieldLinks[aLeft] == data.FieldLinks[aRight]);
     }
     if (left is AStructLvalue)
     {
         AStructLvalue aLeft  = (AStructLvalue)left;
         AStructLvalue aRight = (AStructLvalue)right;
         if (data.StructFieldLinks[aLeft] != data.StructFieldLinks[aRight])
         {
             return(false);
         }
         return(ReturnsTheSame(aLeft.GetReceiver(), aRight.GetReceiver(), data));
     }
     if (left is AArrayLvalue)
     {
         AArrayLvalue aLeft  = (AArrayLvalue)left;
         AArrayLvalue aRight = (AArrayLvalue)right;
         return(ReturnsTheSame(aLeft.GetIndex(), aRight.GetIndex(), data) &&
                ReturnsTheSame(aLeft.GetBase(), aRight.GetBase(), data));
     }
     throw new Exception("Util.ReturnsTheSame. Unexpected type, got " + left.GetType());
 }
Beispiel #9
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);
        }
Beispiel #10
0
        public override void DefaultIn(Node node)
        {
            if (!canMerge)
            {
                return;
            }
            if (node is AMethodDecl)
            {
                //First node - no need to fetch
                if (((AMethodDecl)node).GetFormals().Count != ((AMethodDecl)otherNode).GetFormals().Count)
                {
                    canMerge = false;
                }
                return;
            }
            //Fetch corrosponding other node
            int index = 0;
            GetChildTypeIndex getChildTypeIndex = new GetChildTypeIndex()
            {
                Parent = node.Parent(), Child = node
            };

            node.Parent().Apply(getChildTypeIndex);
            index = getChildTypeIndex.Index;
            GetChildTypeByIndex getChildTypeByIndex = new GetChildTypeByIndex()
            {
                Child = node, Index = index, Parent = otherNode
            };

            otherNode.Apply(getChildTypeByIndex);
            otherNode = getChildTypeByIndex.Child;

            if (otherNode.GetType() != node.GetType())
            {
                canMerge = false;
                return;
            }

            if (node is AALocalDecl)
            {
                locals.Add((AALocalDecl)node);
                otherLocals.Add((AALocalDecl)otherNode);
                return;
            }

            if (node is ANamedType)
            {
                ANamedType aNode  = (ANamedType)node;
                ANamedType aOther = (ANamedType)otherNode;
                if (data.StructTypeLinks.ContainsKey(aNode) != data.StructTypeLinks.ContainsKey(aOther))
                {
                    canMerge = false;
                    return;
                }
                if (data.StructTypeLinks.ContainsKey(aNode) && data.StructTypeLinks[aNode] != data.StructTypeLinks[aOther])
                {
                    canMerge = false;
                }
                if (!data.StructTypeLinks.ContainsKey(aNode) && aNode.IsSame(aOther, true))//aNode.GetName().Text != aOther.GetName().Text)
                {
                    canMerge = false;
                }
                if (aNode.IsPrimitive() && !aOther.IsPrimitive(aNode.AsIdentifierString()))
                {
                    canMerge = false;
                }
                return;
            }

            if (node is AABlock)
            {
                AABlock aNode  = (AABlock)node;
                AABlock aOther = (AABlock)otherNode;
                if (aNode.GetStatements().Count != aOther.GetStatements().Count)
                {
                    canMerge = false;
                }
                return;
            }

            if (node is AIntConstExp)
            {
                AIntConstExp aNode  = (AIntConstExp)node;
                AIntConstExp aOther = (AIntConstExp)otherNode;
                if (aNode.GetIntegerLiteral().Text != aOther.GetIntegerLiteral().Text)
                {
                    canMerge = false;
                }
                return;
            }

            if (node is AFixedConstExp)
            {
                AFixedConstExp aNode  = (AFixedConstExp)node;
                AFixedConstExp aOther = (AFixedConstExp)otherNode;
                if (aNode.GetFixedLiteral().Text != aOther.GetFixedLiteral().Text)
                {
                    canMerge = false;
                }
                return;
            }

            if (node is AStringConstExp)
            {
                AStringConstExp aNode  = (AStringConstExp)node;
                AStringConstExp aOther = (AStringConstExp)otherNode;
                if (aNode.GetStringLiteral().Text != aOther.GetStringLiteral().Text)
                {
                    canMerge = false;
                }
                return;
            }

            if (node is ACharConstExp)
            {
                ACharConstExp aNode  = (ACharConstExp)node;
                ACharConstExp aOther = (ACharConstExp)otherNode;
                if (aNode.GetCharLiteral().Text != aOther.GetCharLiteral().Text)
                {
                    canMerge = false;
                }
                return;
            }

            if (node is ASimpleInvokeExp)
            {
                ASimpleInvokeExp aNode  = (ASimpleInvokeExp)node;
                ASimpleInvokeExp aOther = (ASimpleInvokeExp)otherNode;
                if (data.SimpleMethodLinks[aNode] != data.SimpleMethodLinks[aOther] &&
                    !(data.SimpleMethodLinks[aNode] == Util.GetAncestor <AMethodDecl>(aNode) &&
                      data.SimpleMethodLinks[aOther] == Util.GetAncestor <AMethodDecl>(aOther)))
                {
                    canMerge = false;
                }
                return;
            }

            if (node is ALocalLvalue)
            {
                ALocalLvalue aNode  = (ALocalLvalue)node;
                ALocalLvalue aOther = (ALocalLvalue)otherNode;
                if (locals.IndexOf(data.LocalLinks[aNode]) != otherLocals.IndexOf(data.LocalLinks[aOther]))
                {
                    canMerge = false;
                }
                return;
            }

            if (node is AFieldLvalue)
            {
                AFieldLvalue aNode  = (AFieldLvalue)node;
                AFieldLvalue aOther = (AFieldLvalue)otherNode;
                if (data.FieldLinks[aNode] != data.FieldLinks[aOther])
                {
                    canMerge = false;
                }
                return;
            }

            if (node is AStructLvalue)
            {
                AStructLvalue aNode  = (AStructLvalue)node;
                AStructLvalue aOther = (AStructLvalue)otherNode;
                if (data.StructFieldLinks[aNode] != data.StructFieldLinks[aOther])
                {
                    canMerge = false;
                }
                return;
            }
        }
Beispiel #11
0
        private void MakeInitializerInvokes()
        {
            AABlock      block = (AABlock)mainEntry.GetBlock();
            AASourceFile file  = Util.GetAncestor <AASourceFile>(mainEntry);
            AMethodDecl  invokeMethod;

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

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

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

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

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

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

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


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



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

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

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


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


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

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

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

                block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), assignment));
            }
            block.RemoveChild(mainEntryFieldInitBlock);
            block.GetStatements().Insert(0, mainEntryFieldInitBlock);
        }
Beispiel #12
0
        public override void CaseAALocalDecl(AALocalDecl node)
        {
            //Convert a static struct field into a global variable. All refferences to it are structFieldLvalues.
            if (node.GetStatic() == null)
            {
                return;
            }



            AStructDecl str = (AStructDecl)node.Parent();

            if (data.StructFields[str].Contains(node))
            {
                data.StructFields[str].Remove(node);
            }
            AFieldDecl replacementField;

            //Don't enhrit static fields.
            if (data.EnheritanceLocalMap.ContainsKey(node))
            {
                str.RemoveChild(node);

                AALocalDecl realVar = data.EnheritanceLocalMap[node];
                if (convertionMap.ContainsKey(realVar))
                {
                    //Already converted to a field
                    replacementField = convertionMap[realVar];
                    foreach (AStructFieldLvalue lvalue in data.StructMethodFieldLinks.Where(link => link.Value == node).Select(link => link.Key))
                    {
                        AFieldLvalue newLvalue = new AFieldLvalue(new TIdentifier(replacementField.GetName().Text));
                        data.FieldLinks[newLvalue]  = replacementField;
                        data.LvalueTypes[newLvalue] = replacementField.GetType();
                        lvalue.ReplaceBy(newLvalue);
                    }
                }
                else
                {
                    List <AStructFieldLvalue> refferences = new List <AStructFieldLvalue>();
                    refferences.AddRange(data.StructMethodFieldLinks.Where(link => link.Value == node).Select(link => link.Key));
                    foreach (AStructFieldLvalue lvalue in refferences)
                    {
                        data.StructMethodFieldLinks[lvalue] = realVar;
                    }
                }
                return;
            }

            replacementField = new AFieldDecl(new APublicVisibilityModifier(), null, node.GetConst(), node.GetType(), node.GetName(), node.GetInit());

            replacementField.GetName().Text = str.GetName().Text + "_" + replacementField.GetName().Text;

            AASourceFile file = Util.GetAncestor <AASourceFile>(node);

            file.GetDecl().Insert(file.GetDecl().IndexOf(node.Parent()), replacementField);
            data.Fields.Add(new SharedData.DeclItem <AFieldDecl>(file, replacementField));

            if (ContainsNewExp(replacementField.GetInit()))
            {
                data.FieldsToInitInMapInit.Add(replacementField);
            }

            foreach (AStructFieldLvalue lvalue in data.StructMethodFieldLinks.Where(link => link.Value == node).Select(link => link.Key))
            {
                AFieldLvalue newLvalue = new AFieldLvalue(new TIdentifier(replacementField.GetName().Text));
                data.FieldLinks[newLvalue]  = replacementField;
                data.LvalueTypes[newLvalue] = replacementField.GetType();
                lvalue.ReplaceBy(newLvalue);
            }

            convertionMap.Add(node, replacementField);
            node.Parent().RemoveChild(node);
        }
Beispiel #13
0
 public override void OutAFieldLvalue(AFieldLvalue node)
 {
     currentDecl = new VariableDecl(data.FieldLinks[node], null, null);
 }
Beispiel #14
0
            public override void CaseAFieldLvalue(AFieldLvalue node)
            {
                Item currentFile = GetIncludeItem(node);

                //If the field is in a moved field, refference that field instead
                if (Util.GetAncestor <AFieldDecl>(node) != null)
                {
                    Item i = allItems.OfType <FieldItem>().FirstOrDefault(item => item.FieldDecl == Util.GetAncestor <AFieldDecl>(node));
                    if (i != null)
                    {
                        currentFile = i;
                    }
                }

                AFieldDecl decl     = finalTrans.data.FieldLinks[node];
                Item       declItem = ((Item)allItems.OfType <FieldItem>().FirstOrDefault(item => item.FieldDecl == decl)) ??
                                      allItems.OfType <IncludeItem>().First(
                    item => item.Current == Util.GetAncestor <AASourceFile>(decl));
                List <Item> cPath = currentFile.Path;
                List <Item> dPath = declItem.Path;

                bool movedIt = false;

                for (int i = 0; i < Math.Min(cPath.Count, dPath.Count); i++)
                {
                    if (cPath[i] != dPath[i])
                    {
                        //We have a fork. make sure that the field is visible
                        int cI = cPath[i - 1].Children.IndexOf(cPath[i]);
                        int dI = dPath[i - 1].Children.IndexOf(dPath[i]);

                        if (dI < cI)
                        {//The decl is okay
                            break;
                        }

                        //Move the decl up
                        if (declItem is FieldItem)
                        {
                            declItem.Parent.Children.Remove(declItem);
                            declItem.Parent = cPath[i - 1];
                        }
                        else
                        {
                            declItem = new FieldItem(decl, cPath[i - 1], new List <Item>());
                            allItems.Add(declItem);
                        }
                        cPath[i - 1].Children.Insert(cI, declItem);
                        movedIt = true;
                        break;
                    }
                    if (i == cPath.Count - 1)
                    {
                        if (i == dPath.Count - 1)
                        {
                            //The decl and use is in same file. Ensure that the decl is before
                            if (Util.TokenLessThan(decl.GetName(), node.GetName()))
                            {
                                break;
                            }
                            //Add the decl item
                            declItem = new FieldItem(decl, cPath[i], new List <Item>());
                            allItems.Add(declItem);
                            cPath[i].Children.Add(declItem);
                            movedIt = true;
                            break;
                        }
                        else
                        {
                            //The decl is included here or somewhere deeper. But above the use
                            break;
                        }
                    }
                    else if (i == dPath.Count - 1)
                    {
                        //We have reached the file where the decl is, but the use is included deeper, so it is above. Insert decl
                        int cI = cPath[i].Children.IndexOf(cPath[i + 1]);
                        declItem = new FieldItem(decl, cPath[i], new List <Item>());
                        allItems.Add(declItem);
                        cPath[i].Children.Insert(cI, declItem);
                        movedIt = true;
                        break;
                    }
                }

                //In case we have a struct type field, we must make sure the struct is still on top
                if (movedIt)
                {
                    CaseAFieldDecl(decl);
                }
                base.CaseAFieldLvalue(node);
            }
Beispiel #15
0
            public override void InAFieldLvalue(AFieldLvalue node)
            {
                AFieldDecl decl = finalTrans.data.FieldLinks[node];

                AddDepency(Util.GetAncestor <AASourceFile>(node), Util.GetAncestor <AASourceFile>(decl));
            }
Beispiel #16
0
 public override void OutAFieldLvalue(AFieldLvalue node)
 {
     node.GetName().Text = finalTrans.data.FieldLinks[node].GetName().Text;
 }
Beispiel #17
0
 bool IsConstant(PLvalue lvalue)
 {
     if (lvalue is ALocalLvalue)
     {
         ALocalLvalue aLvalue = (ALocalLvalue)lvalue;
         AALocalDecl  decl    = data.LocalLinks[aLvalue];
         if (decl == initialLocalDecl)
         {
             return(false);
         }
         return(decl.GetConst() != null && IsConstant(decl.GetInit()));
     }
     if (lvalue is AFieldLvalue)
     {
         AFieldLvalue aLvalue = (AFieldLvalue)lvalue;
         AFieldDecl   decl    = data.FieldLinks[aLvalue];
         if (decl == initialFieldDecl)
         {
             return(false);
         }
         return(decl.GetConst() != null && IsConstant(decl.GetInit()));
     }
     if (lvalue is APropertyLvalue)
     {
         return(false);
     }
     if (lvalue is ANamespaceLvalue)
     {
         return(true);
     }
     if (lvalue is AStructFieldLvalue)
     {
         AStructFieldLvalue aLvalue = (AStructFieldLvalue)lvalue;
         AALocalDecl        decl    = data.StructMethodFieldLinks[aLvalue];
         if (decl == initialLocalDecl)
         {
             return(false);
         }
         return(decl.GetConst() != null && IsConstant(decl.GetInit()));
     }
     if (lvalue is AStructLvalue)
     {
         AStructLvalue aLvalue = (AStructLvalue)lvalue;
         AALocalDecl   decl    = data.StructFieldLinks[aLvalue];
         if (decl == initialLocalDecl)
         {
             return(false);
         }
         return(decl.GetConst() != null && IsConstant(decl.GetInit()));
     }
     if (lvalue is AArrayLvalue)
     {
         AArrayLvalue aLvalue = (AArrayLvalue)lvalue;
         return(IsConstant(aLvalue.GetIndex()) && IsConstant(aLvalue.GetBase()));
     }
     if (lvalue is APointerLvalue)
     {
         APointerLvalue aLvalue = (APointerLvalue)lvalue;
         return(IsConstant(aLvalue.GetBase()));
     }
     if (lvalue is APArrayLengthLvalue)
     {
         APArrayLengthLvalue aLvalue = (APArrayLengthLvalue)lvalue;
         return(data.ExpTypes[aLvalue.GetBase()] is AArrayTempType);
     }
     if (lvalue is AThisLvalue)
     {
         return(false);
     }
     if (lvalue is AValueLvalue)
     {
         return(false);
     }
     throw new Exception("Unexpected lvalue. Got " + lvalue);
 }