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;
        }
Example #2
0
        public override void OutAStructDecl(AStructDecl node)
        {
            //Insert init in each constructor
            AThisLvalue    thisLvalue    = new AThisLvalue(new TThis("this"));
            ALvalueExp     thisExp       = new ALvalueExp(thisLvalue);
            APointerLvalue pointerLvalue = new APointerLvalue(new TStar("*"), thisExp);

            ANamedType namedType = new ANamedType(new TIdentifier(node.GetName().Text), null);

            data.StructTypeLinks[namedType] = node;
            data.LvalueTypes[thisLvalue]    =
                data.ExpTypes[thisExp]      = new APointerType(new TStar("*"), namedType);
            data.LvalueTypes[pointerLvalue] = namedType;


            foreach (AConstructorDecl constructor in node.GetLocals().OfType <ADeclLocalDecl>().Select(decl => decl.GetDecl()).OfType <AConstructorDecl>())
            {
                AABlock block = new AABlock(new ArrayList(), new TRBrace("}"));
                MakeAssignments(block, namedType, pointerLvalue, false);

                ((AABlock)constructor.GetBlock()).GetStatements().Insert(0, new ABlockStm(new TLBrace("{"), block));
            }

            base.OutAStructDecl(node);
        }
Example #3
0
 public override void CaseANamedType(ANamedType node)
 {
     if (SharedData.LastCreated.GenericLinks.ContainsKey(node))
     {
         ContainsGenericVar = true;
     }
 }
Example #4
0
        private AStructDecl Lookup(ANamedType type)
        {
            //Look for structs
            List <AStructDecl> structs = new List <AStructDecl>();
            bool matchingPrimitive;

            LinkNamedTypes.GetMatchingTypes(type, new List <ATypedefDecl>(), structs, new List <AMethodDecl>(), new List <TIdentifier>(), out matchingPrimitive);

            if (structs.Count == 0)
            {
                errors.Add(new ErrorCollection.Error(type.GetToken(), "No type found named " + ((AAName)type.GetName()).AsString()), true);
                throw new ParserException(null, null);
            }
            else if (structs.Count > 1)
            {
                List <ErrorCollection.Error> subError = new List <ErrorCollection.Error>();
                foreach (AStructDecl structDecl in structs)
                {
                    subError.Add(new ErrorCollection.Error(structDecl.GetName(), "Matching " + Util.GetTypeName(structDecl)));
                }
                errors.Add(
                    new ErrorCollection.Error(type.GetToken(),
                                              "Found multiple structs/classes matching " + ((AAName)type.GetName()).AsString(),
                                              false, subError.ToArray()), true);
            }

            return(structs[0]);
        }
Example #5
0
        private PLvalue DetypeArray(PType type)
        {
            if (type is AArrayTempType)
            {
                AArrayTempType atype = (AArrayTempType)type;
                return(new AArrayLvalue(atype.GetToken(), new ALvalueExp(DetypeArray(atype.GetType())),
                                        atype.GetDimention()));
            }
            if (type is ANamedType)
            {
                ANamedType atype = (ANamedType)type;
                return(new AAmbiguousNameLvalue(atype.GetName()));
            }
            if (type is AVoidType)
            {
                AVoidType atype = (AVoidType)type;
                throw new Exception(Util.TokenToStringPos(atype.GetToken()) + " (Weeder)Unexpected type: void. It should not be possible for this error to occur");
            }

            /*if (type is AArrayType)
             * {
             *  AArrayType atype = (AArrayType)type;
             *  throw new Exception(Util.TokenToStringPos(atype.GetToken()) + " (Weeder)Unexpected type: ArrayType. It should not be possible for this error to occur");
             * }*/
            throw new Exception("(Weeder)Unexpected type: none. It should not be possible for this error to occur");
        }
Example #6
0
 public override void InANamedType(ANamedType node)
 {
     if (!node.IsPrimitive())// !GalaxyKeywords.Primitives.words.Any(word => word == node.GetName().Text))
     {
         AStructDecl decl = finalTrans.data.StructTypeLinks[node];
         AddDepency(Util.GetAncestor <AASourceFile>(node), Util.GetAncestor <AASourceFile>(decl));
     }
 }
Example #7
0
        public static void SetPrimitive(this ANamedType node, string primitive)
        {
            AAName      name           = (AAName)node.GetName();
            TIdentifier lastIdentifier = (TIdentifier)name.GetIdentifier()[name.GetIdentifier().Count - 1];

            name.GetIdentifier().Clear();
            lastIdentifier.Text = primitive;
            name.GetIdentifier().Add(lastIdentifier);
        }
Example #8
0
        public static bool IsPrimitive(this ANamedType node, string[] primitives)
        {
            AAName name = (AAName)node.GetName();

            if (name.GetIdentifier().Count != 1)
            {
                return(false);
            }
            return(primitives.Contains(((TIdentifier)name.GetIdentifier()[0]).Text));
        }
Example #9
0
        public static bool IsPrimitive(this ANamedType node)
        {
            AAName name = (AAName)node.GetName();

            if (name.GetIdentifier().Count != 1)
            {
                return(false);
            }
            return(GalaxyKeywords.Primitives.words.Contains(((TIdentifier)name.GetIdentifier()[0]).Text));
        }
Example #10
0
 public override void OutANamedType(ANamedType node)
 {
     if (!node.IsPrimitive())//!GalaxyKeywords.Primitives.words.Contains(node.GetName().Text))
     {
         node.SetName(
             new AAName(new List <TIdentifier>()
         {
             new TIdentifier(finalTrans.data.StructTypeLinks[node].GetName().Text)
         }));
     }
 }
Example #11
0
        public static void GetMatchingTypes(ANamedType node, List <ATypedefDecl> typeDefs, List <AStructDecl> structs, List <AMethodDecl> delegates, List <TIdentifier> generics, out bool matchPrimitive)
        {
            List <string> names = new List <string>();

            foreach (TIdentifier identifier in ((AAName)node.GetName()).GetIdentifier())
            {
                names.Add(identifier.Text);
            }
            matchPrimitive = names.Count == 1 && GalaxyKeywords.Primitives.words.Contains(names[0]);
            GetMatchingTypes(node, names, typeDefs, structs, delegates, new List <ANamespaceDecl>(), generics);
        }
Example #12
0
        public static string TypeToIdentifierString(PType type)
        {
            if (type is AVoidType)
            {
                return("void");
            }

            /*if (type is AArrayType)
             * {
             *  AArrayType aType = (AArrayType)type;
             *  return TypeToString(aType.GetType()) + "[" + aType.GetDimention().Text + "]";
             * }*/
            if (type is AArrayTempType)
            {
                AArrayTempType aType = (AArrayTempType)type;
                return(TypeToIdentifierString(aType.GetType()) + "Ar" + (aType.GetIntDim() == null ? "" : aType.GetIntDim().Text));
            }
            if (type is ANamedType)
            {
                ANamedType aType = (ANamedType)type;
                return(((AAName)aType.GetName()).AsString().Replace('.', '_'));
            }
            if (type is APointerType)
            {
                APointerType aType = (APointerType)type;
                return("p" + TypeToIdentifierString(aType.GetType()));
            }
            if (type is ADynamicArrayType)
            {
                ADynamicArrayType aType = (ADynamicArrayType)type;
                return(TypeToIdentifierString(aType.GetType()) + "DAr");
            }
            if (type is AGenericType)
            {
                AGenericType aType = (AGenericType)type;
                string       ret   = TypeToIdentifierString(aType.GetBase()) + "G_";
                bool         first = true;
                foreach (PType t in aType.GetGenericTypes())
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        ret += "_";
                    }
                    ret += TypeToIdentifierString(t);
                }
                return(ret + "_G");
            }
            throw new Exception("Unknown type");
        }
 public override void CaseANamedType(ANamedType node)
 {
     if (processStructs)
     {
         AStructDecl structDecl = finalTrans.data.StructTypeLinks.ContainsKey(node)
                                      ? finalTrans.data.StructTypeLinks[node]
                                      : null;
         if (structDecl != null && !usedStructs.Contains(structDecl))
         {
             usedStructs.Add(structDecl);
         }
     }
     base.CaseANamedType(node);
 }
Example #14
0
        public override void OutAGenericType(AGenericType node)
        {
            if (!(node.GetBase() is ANamedType))
            {
                errors.Add(new ErrorCollection.Error(node.GetToken(), LocRM.GetString("ErrorText44")));
                return;
            }
            ANamedType Base = (ANamedType)node.GetBase();

            if (!data.StructTypeLinks.ContainsKey(Base))
            {
                errors.Add(new ErrorCollection.Error(node.GetToken(), LocRM.GetString("ErrorText44")));
                return;
            }
            AStructDecl str = data.StructTypeLinks[Base];

            if (str.GetGenericVars().Count != node.GetGenericTypes().Count)
            {
                errors.Add(new ErrorCollection.Error(node.GetToken(), LocRM.GetString("ErrorText45"),
                                                     false, new ErrorCollection.Error(str.GetName(), LocRM.GetString("ErrorText46") + Util.GetTypeName(str))));
                return;
            }
            LookForGenericVar finder = new LookForGenericVar();

            foreach (PType genericType in node.GetGenericTypes())
            {
                genericType.Apply(finder);
                if (finder.ContainsGenericVar || finder.ContainsNestedGenerics)
                {
                    //if (finder.ContainsGenericVar)
                    structsWithGenerics.Add(Util.GetAncestor <AStructDecl>(node));
                    if (finder.ContainsNestedGenerics)
                    {
                        if (!Util.HasAncestor <AStructDecl>(node) || Util.GetAncestor <AStructDecl>(node).GetGenericVars().Count == 0)
                        {
                            needAnotherPass = true;
                        }
                    }
                    return;
                }
            }
            if (!Refferences.ContainsKey(str))
            {
                Refferences[str] = new List <AGenericType>();
            }
            Refferences[str].Add(node);
            base.OutAGenericType(node);
        }
Example #15
0
 public override void CaseAFieldDecl(AFieldDecl node)
 {
     if (node.GetType() is ANamedType)
     {
         ANamedType type = (ANamedType)node.GetType();
         if (finalTrans.data.StructTypeLinks.ContainsKey(type))
         {
             AStructDecl strDecl = finalTrans.data.StructTypeLinks[type];
             if (strDecl.GetLocals().Cast <PLocalDecl>().Select(decl => decl is AALocalDecl).Count() == 0)
             {
                 node.Parent().RemoveChild(node);
                 return;
             }
         }
     }
     base.CaseAFieldDecl(node);
 }
Example #16
0
            public override void CaseANamedType(ANamedType node)
            {
                AAName name = (AAName)node.GetName();

                if (name.GetIdentifier().Count > 2)
                {
                    return;
                }
                if (name.GetIdentifier().Count == 2 && ((TIdentifier)name.GetIdentifier()[0]).Text != "Dialogs")
                {
                    return;
                }
                if (name.GetIdentifier().Count == 1)
                {
                    bool         foundDialogs = false;
                    AASourceFile file         = Util.GetAncestor <AASourceFile>(node);
                    foreach (AUsingDecl usingDecl in file.GetUsings())
                    {
                        if (usingDecl.GetNamespace().Count == 1)
                        {
                            TIdentifier identifer = (TIdentifier)usingDecl.GetNamespace()[0];
                            if (identifer.Text == "Dialogs")
                            {
                                foundDialogs = true;
                                break;
                            }
                        }
                    }
                    if (!foundDialogs)
                    {
                        ANamespaceDecl ns = Util.GetAncestor <ANamespaceDecl>(node);
                        if (!Util.HasAncestor <ANamespaceDecl>(ns.Parent()) && ns.GetName().Text == "Dialogs")
                        {
                            foundDialogs = true;
                        }
                    }
                    if (!foundDialogs)
                    {
                        return;
                    }
                }
                if (((TIdentifier)name.GetIdentifier()[name.GetIdentifier().Count - 1]).Text == oldName)
                {
                    types.Add((TIdentifier)name.GetIdentifier()[name.GetIdentifier().Count - 1]);
                }
            }
Example #17
0
        public override void DefaultIn(Node node)
        {
            if (node is PExp)
            {
                PExp exp = (PExp)node;
                if (finalTrans.data.ExpTypes[exp] is ANamedType)
                {
                    ANamedType type = (ANamedType)finalTrans.data.ExpTypes[exp];
                    if (finalTrans.data.StructTypeLinks.ContainsKey(type))
                    {
                        AStructDecl strDecl = finalTrans.data.StructTypeLinks[type];
                        if (strDecl.GetLocals().Cast <PLocalDecl>().Select(decl => decl is AALocalDecl).Count() == 0)
                        {
                            if (node.Parent() is AAssignmentExp)
                            {
                                node = node.Parent().Parent();
                            }
                            MoveMethodDeclsOut mover = new MoveMethodDeclsOut("removedStructVar", finalTrans.data);
                            node.Apply(mover);
                            foreach (PStm pStm in mover.NewStatements)
                            {
                                pStm.Apply(this);
                            }
                            node.Parent().RemoveChild(node);

                            if (node.Parent() is ABinopExp)
                            {
                                ABinopExp        parent = (ABinopExp)node.Parent();
                                ABooleanConstExp replacer;
                                if (parent.GetBinop() is ANeBinop || parent.GetBinop() is AGtBinop || parent.GetBinop() is ALtBinop)
                                {
                                    replacer = new ABooleanConstExp(new AFalseBool());
                                }
                                else
                                {
                                    replacer = new ABooleanConstExp(new ATrueBool());
                                }
                                finalTrans.data.ExpTypes[replacer] = new ANamedType(new TIdentifier("bool"), null);
                                parent.ReplaceBy(replacer);
                            }
                        }
                    }
                }
            }
        }
Example #18
0
 public override void OutANamedType(ANamedType node)
 {
     //If using a generic type, you must us it as a generic
     if (data.StructTypeLinks.ContainsKey(node))
     {
         AStructDecl str = data.StructTypeLinks[node];
         if (str.GetGenericVars().Count > 0)
         {
             if (!(node.Parent() is AGenericType))
             {
                 errors.Add(new ErrorCollection.Error(node.GetToken(),
                                                      LocRM.GetString("ErrorText46"),
                                                      false,
                                                      new ErrorCollection.Error(str.GetName(),
                                                                                LocRM.GetString("ErrorText48") +
                                                                                Util.GetTypeName(str))));
             }
         }
     }
     base.OutANamedType(node);
 }
Example #19
0
 public override void OutANamedType(ANamedType node)
 {
     //If using a generic type, you must us it as a generic
     if (data.StructTypeLinks.ContainsKey(node))
     {
         AStructDecl str = data.StructTypeLinks[node];
         if (str.GetGenericVars().Count > 0)
         {
             if (!(node.Parent() is AGenericType))
             {
                 errors.Add(new ErrorCollection.Error(node.GetToken(),
                                                      "Target struct is a generic type. You must specify types for the generics.",
                                                      false,
                                                      new ErrorCollection.Error(str.GetName(),
                                                                                "Matching " +
                                                                                Util.GetTypeName(str))));
             }
         }
     }
     base.OutANamedType(node);
 }
Example #20
0
        public override void CaseAALocalDecl(AALocalDecl node)
        {
            if (node.GetType() is ANamedType)
            {
                ANamedType type = (ANamedType)node.GetType();
                if (finalTrans.data.StructTypeLinks.ContainsKey(type))
                {
                    AStructDecl strDecl = finalTrans.data.StructTypeLinks[type];
                    if (strDecl.GetLocals().Cast <PLocalDecl>().Select(decl => decl is AALocalDecl).Count() == 0)
                    {
                        MoveMethodDeclsOut mover = new MoveMethodDeclsOut("removedStructVar", finalTrans.data);
                        node.Apply(mover);
                        foreach (PStm stm in mover.NewStatements)
                        {
                            stm.Apply(this);
                        }
                        PStm pStm = Util.GetAncestor <PStm>(node);
                        if (pStm == null)
                        {
                            strDecl = Util.GetAncestor <AStructDecl>(node);


                            node.Parent().RemoveChild(node);

                            if (strDecl != null && strDecl.GetLocals().Cast <PLocalDecl>().Select(decl => decl is AALocalDecl).Count() == 0)
                            {
                                reqRerun = true;
                            }
                        }
                        else
                        {
                            pStm.Parent().RemoveChild(pStm);
                        }
                        return;
                    }
                }
            }
            base.CaseAALocalDecl(node);
        }
Example #21
0
        public StructDescription(AStructDecl structDecl)
        {
            Parser parser = new Parser(structDecl);

            Name   = parser.Name;
            IsEnum = Name.StartsWith("enum ");
            if (IsEnum)
            {
                Name = Name.Substring(5);
                foreach (VariableDescription field in parser.Fields)
                {
                    field.PlacementPrefix = "Enum Field";
                }
            }
            Fields = parser.Fields;

            Methods        = parser.Methods;
            Constructors   = parser.Constructors;
            Deconstructors = parser.Deconstructors;
            LineFrom       = structDecl.GetName().Line;
            LineTo         = structDecl.GetEndToken().Line;
            if (structDecl.GetBase() is AGenericType)
            {
                BaseRef = (ANamedType)((AGenericType)structDecl.GetBase()).GetBase();
            }
            else
            {
                BaseRef = (ANamedType)structDecl.GetBase();
            }
            structDecl.RemoveChild(BaseRef);
            foreach (TIdentifier identifier in structDecl.GetGenericVars())
            {
                GenericVars.Add(identifier.Text);
            }
            IsClass    = structDecl.GetClassToken() != null;
            Visibility = (PVisibilityModifier)structDecl.GetVisibilityModifier().Clone();
            Position   = TextPoint.FromCompilerCoords(structDecl.GetName());
        }
Example #22
0
        public static bool IsSame(this ANamedType node1, ANamedType node2, bool primitiveOnly)
        {
            AAName name1 = (AAName)node1.GetName();
            AAName name2 = (AAName)node2.GetName();

            if (primitiveOnly && (name1.GetIdentifier().Count > 1 || name2.GetIdentifier().Count > 1))
            {
                return(false);
            }
            if (name1.GetIdentifier().Count != name2.GetIdentifier().Count)
            {
                return(false);
            }
            for (int i = 0; i < name2.GetIdentifier().Count; i++)
            {
                TIdentifier identifier1 = (TIdentifier)name1.GetIdentifier()[i];
                TIdentifier identifier2 = (TIdentifier)name2.GetIdentifier()[i];
                if (identifier1.Text != identifier2.Text)
                {
                    return(false);
                }
            }
            return(true);
        }
Example #23
0
        private static void GetMatchingTypes(ANamedType node, List <string> names, List <ATypedefDecl> typeDefs, List <AStructDecl> structs, List <AMethodDecl> delegates, List <ANamespaceDecl> namespaces, List <TIdentifier> generics)
        {
            List <IList>  decls             = new List <IList>();
            List <string> currentNamespace  = Util.GetFullNamespace(node);
            AASourceFile  currentSourceFile = Util.GetAncestor <AASourceFile>(node);

            if (names.Count == 1)
            {
                string name = names[0];
                //Check generic vars
                AStructDecl currentStruct = Util.GetAncestor <AStructDecl>(node);
                if (currentStruct != null)
                {
                    foreach (TIdentifier genericVar in currentStruct.GetGenericVars())
                    {
                        if (genericVar.Text == name)
                        {
                            generics.Add(genericVar);
                        }
                    }
                }
                //Get all type decls and namespaces matching this name, visible from this location
                List <IList> visibleDecls = Util.GetVisibleDecls(node, ((AAName)node.GetName()).GetIdentifier().Count == 1);
                foreach (IList declList in visibleDecls)
                {
                    bool sameFile = false;
                    if (declList.Count > 0)
                    {
                        sameFile = currentSourceFile == Util.GetAncestor <AASourceFile>((PDecl)declList[0]);
                    }
                    foreach (PDecl decl in declList)
                    {
                        bool sameNS = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl));
                        if (decl is ANamespaceDecl)
                        {
                            ANamespaceDecl aDecl = (ANamespaceDecl)decl;
                            if (aDecl.GetName().Text == name)
                            {
                                namespaces.Add(aDecl);
                            }
                            continue;
                        }
                        if (decl is ATypedefDecl)
                        {
                            if (Util.IsAncestor(node, decl))
                            {
                                continue;
                            }
                            ATypedefDecl aDecl = (ATypedefDecl)decl;
                            if (aDecl.GetStatic() != null && !sameFile ||
                                aDecl.GetVisibilityModifier() is APrivateVisibilityModifier && !sameNS)
                            {
                                continue;
                            }
                            ANamedType namedType = (ANamedType)aDecl.GetName();
                            AAName     aName     = (AAName)namedType.GetName();
                            string     n         = ((TIdentifier)aName.GetIdentifier()[0]).Text;
                            if (n == name)
                            {
                                typeDefs.Add(aDecl);
                            }
                            continue;
                        }
                        if (decl is AStructDecl)
                        {
                            AStructDecl aDecl = (AStructDecl)decl;
                            if (!sameNS && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier)
                            {
                                continue;
                            }
                            if (aDecl.GetName().Text == name)
                            {
                                structs.Add(aDecl);
                            }
                            continue;
                        }
                        if (decl is AMethodDecl)
                        {
                            AMethodDecl aDecl = (AMethodDecl)decl;
                            if (!sameNS && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier ||
                                !sameFile && aDecl.GetStatic() != null)
                            {
                                continue;
                            }
                            if (aDecl.GetDelegate() != null && aDecl.GetName().Text == name)
                            {
                                delegates.Add(aDecl);
                            }
                            continue;
                        }
                    }
                }
            }
            else
            {
                string name = names[names.Count - 1];
                List <ANamespaceDecl> baseNamespaces = new List <ANamespaceDecl>();
                List <string>         baseNames      = new List <string>();
                baseNames.AddRange(names);
                baseNames.RemoveAt(baseNames.Count - 1);
                GetMatchingTypes(node, baseNames, new List <ATypedefDecl>(), new List <AStructDecl>(), new List <AMethodDecl>(), baseNamespaces, generics);
                foreach (ANamespaceDecl ns in baseNamespaces)
                {
                    bool sameFile = currentSourceFile == Util.GetAncestor <AASourceFile>(ns);
                    foreach (PDecl decl in ns.GetDecl())
                    {
                        bool sameNS = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace(decl));
                        if (decl is ANamespaceDecl)
                        {
                            ANamespaceDecl aDecl = (ANamespaceDecl)decl;
                            if (aDecl.GetName().Text == name)
                            {
                                namespaces.Add(aDecl);
                            }
                            continue;
                        }
                        if (decl is ATypedefDecl)
                        {
                            ATypedefDecl aDecl     = (ATypedefDecl)decl;
                            ANamedType   namedType = (ANamedType)aDecl.GetName();
                            AAName       aName     = (AAName)namedType.GetName();
                            string       n         = ((TIdentifier)aName.GetIdentifier()[0]).Text;
                            if (n == name)
                            {
                                typeDefs.Add(aDecl);
                            }
                            continue;
                        }
                        if (decl is AStructDecl)
                        {
                            AStructDecl aDecl = (AStructDecl)decl;
                            if (!sameNS && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier)
                            {
                                continue;
                            }
                            if (aDecl.GetName().Text == name)
                            {
                                structs.Add(aDecl);
                            }
                            continue;
                        }
                        if (decl is AMethodDecl)
                        {
                            AMethodDecl aDecl = (AMethodDecl)decl;
                            if (!sameNS && aDecl.GetVisibilityModifier() is APrivateVisibilityModifier ||
                                !sameFile && aDecl.GetStatic() != null)
                            {
                                continue;
                            }
                            if (aDecl.GetDelegate() != null && aDecl.GetName().Text == name)
                            {
                                delegates.Add(aDecl);
                            }
                            continue;
                        }
                    }
                }
            }
        }
Example #24
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);
        }
Example #25
0
        private void Apply(AAProgram ast)
        {
            int stage       = 1;
            int totalStages = 31;

            List <ANamedType> deleteUs = new List <ANamedType>();

            foreach (KeyValuePair <ANamedType, AStructDecl> pair in data.StructTypeLinks)
            {
                ANamedType  type = pair.Key;
                AStructDecl str  = pair.Value;
                if (data.Enums.ContainsKey(str))
                {
                    type.SetName(new AAName(new ArrayList()
                    {
                        new TIdentifier(data.Enums[str] ? "int" : "byte")
                    }));
                    deleteUs.Add(type);
                }
            }
            foreach (ANamedType type in deleteUs)
            {
                data.StructTypeLinks.Remove(type);
            }



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing namespaces");
            }
            stage++;

            ast.Apply(new RemoveNamespaces());

            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Moving static members out");
            }
            stage++;

            ast.Apply(new StaticStructMembers(data));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing constant variables");
            }
            stage++;

            ast.Apply(new RemoveConstants(data));



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Locating main entry");
            }
            stage++;

            ast.Apply(new MainEntryFinder(this));



            if (mainEntry == null)
            {
                //errors.Add(new ErrorCollection.Error("No entry point found (void InitMap(){...})", true));

                //Generate main entry
                AASourceFile file =
                    ast.GetSourceFiles().Cast <AASourceFile>().FirstOrDefault(
                        sourceFile => !Util.GetAncestor <AASourceFile>(sourceFile).GetName().Text.Contains("\\"));
                if (file == null)
                {
                    //Make default sourcefile
                    file = new AASourceFile();
                    file.SetName(new TIdentifier("MapScript"));
                    ast.GetSourceFiles().Add(file);
                    data.LineCounts[file] = 1;
                }
                mainEntry = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new AVoidType(new TVoid("void")), new TIdentifier("InitMap"), new ArrayList(), new AABlock());
                file.GetDecl().Add(mainEntry);
                data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, mainEntry));
            }
            else if (Util.GetAncestor <AASourceFile>(mainEntry).GetName().Text.Contains("\\"))
            {
                errors.Add(new ErrorCollection.Error(mainEntry.GetName(), Util.GetAncestor <AASourceFile>(mainEntry), "The source file containing the main entry function should be placed in root folder to be able to overwrite MapScript.galaxy", true));
            }

            ((AABlock)mainEntry.GetBlock()).GetStatements().Insert(0, mainEntryFieldInitBlock);



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Setting default values for struct variables");
            }
            stage++;

            ast.Apply(new StructInitializer(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming expression ifs");
            }
            stage++;

            ast.Apply(new TransformExpressionIfs(data));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Renaming unicode identifiers and strings");
            }
            stage++;

            ast.Apply(new RenameUnicode(data));



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming properties to methods (Phase 1)");
            }
            stage++;

            TransformProperties.Phase1.Parse(this);


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing dead code");
            }
            stage++;

            ast.Apply(new RemoveDeadCode());


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Moving methods members out of structs");
            }
            stage++;

            ast.Apply(new TransformMethodDecls(this));


            if (errors.HasErrors)
            {
                return;
            }


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Invoking initializers");
            }
            stage++;



            MakeInitializerInvokes();


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Moving assignments out to their own statement");
            }
            stage++;

            ast.Apply(new AssignFixup(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming properties to methods (Phase 2)");
            }
            stage++;

            TransformProperties.Phase2.Parse(this);



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Fixing invokes (sync/assync)");
            }
            stage++;

            if (data.Invokes.Count > 0)
            {
                Invokes.Parse(this);
            }



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing empty structs");
            }
            stage++;

            ast.Apply(new RemoveEmptyStructs(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Making delegates");
            }
            stage++;



            ast.Apply(new Delegates(this));



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming inline methods (Run 1)");
            }
            stage++;

            //ast.Apply(new AddUnneededRef(data));
            ast.Apply(new FixInlineMethods(this, false));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removing unneeded ref parameters");
            }
            stage++;



            ast.Apply(new RemoveUnnededRef(data));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Expanding struct equality tests");
            }
            stage++;

            ast.Apply(new SplitStructTests(data));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming pointers");
            }
            stage++;

            new Pointers(data).Parse(ast);



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Transforming inline methods (Run 2)");
            }
            stage++;

            ast.Apply(new FixInlineMethods(this, true));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Splitting local structs into primitives");
            }
            stage++;

            //Split local struct into primitives, to make optimizations easier
            ast.Apply(new StructSplitter(data));
            //ast.Apply(new BulkCopyFixup(this));
            //BulkCopyFixup.Parse(ast, this);


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Removnig redundant assignments");
            }
            stage++;

            //Remove stupid assignments (assignments to a variable where that variable is not used before its next assignment
            ast.Apply(new RemoveUnusedVariables(this));



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Folding constants");
            }
            stage++;



            ast.Apply(new ConstantFolding(data));

            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Optimizing");
            }
            stage++;



            //Assign fixup was here //Dahm grafiti painters
            //ast.Apply(new LivenessAnalysis(this));
            ast.Apply(new Optimizations.OptimizePhase(this, "Transforming code (" + (stage - 1) + " / " + totalStages + "): Optimizing"));


            ast.Apply(new FixByteArrayIndexes(data));


            if (Options.Compiler.MakeShortNames)
            {
                if (data.AllowPrintouts)
                {
                    Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Making short names");
                }
                stage++;

                ast.Apply(new MakeShortNames(this));
            }
            else
            {
                if (data.AllowPrintouts)
                {
                    Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Making unique names");
                }
                stage++;

                //MakeUniqueNames.Parse(ast, this);
                ast.Apply(new MakeUniqueNamesV2());
            }



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Renaming references to variables whose names have changed");
            }
            stage++;
            //Remove uneeded blocks and check that names fit the decls
            ast.Apply(new RenameRefferences(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Obfuscating strings");
            }
            stage++;
            //Obfuscate strings
            ast.Apply(new ObfuscateStrings(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Mergeing methods if they are the same");
            }
            stage++;
            MergeSameMethods.Parse(this);


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText("Transforming code (" + stage + " / " + totalStages + "): Generating includes (merging to one file if selected)");
            }
            stage++;
            //Insert includes, and move methods, structs and fields around so they are visible
            FixIncludes.Apply(ast, this);
            if (Options.Compiler.OneOutputFile)
            {
                ((AASourceFile)mainEntry.Parent()).SetName(new TIdentifier("MapScript"));
            }
        }
Example #26
0
        public override void OutAAProgram(AAProgram node)
        {
            foreach (var pair in Refferences)
            {
                if (structsWithGenerics.Contains(pair.Key) && pair.Value.Count > 0)
                {
                    needAnotherPass = true;
                }
            }
            foreach (var pair in Refferences)
            {
                AStructDecl str = pair.Key;
                if (!copies.ContainsKey(str))
                {
                    copies[str] = new List <List <PType> >();
                }
                IList declList;
                Node  parent = str.Parent();
                if (parent is AASourceFile)
                {
                    declList = ((AASourceFile)parent).GetDecl();
                }
                else
                {
                    declList = ((ANamespaceDecl)parent).GetDecl();
                }
                //AASourceFile pFile = (AASourceFile) str.Parent();
                foreach (AGenericType refference in pair.Value)
                {
                    AStructDecl clone   = null;
                    bool        addList = true;
                    foreach (List <PType> list in copies[str])
                    {
                        bool listEqual = true;
                        for (int i = 0; i < list.Count; i++)
                        {
                            if (!Util.TypesEqual(list[i], (PType)refference.GetGenericTypes()[i], data))
                            {
                                listEqual = false;
                                break;
                            }
                        }
                        if (listEqual)
                        {
                            addList = false;
                            clone   = clones[list];
                            break;
                        }
                    }
                    if (addList)
                    {
                        List <PType> list = new List <PType>();
                        foreach (PType type in refference.GetGenericTypes())
                        {
                            list.Add(type);
                        }
                        copies[str].Add(list);

                        clone = (AStructDecl)str.Clone();
                        declList.Insert(declList.IndexOf(str), clone);


                        clone.Apply(new EnviromentBuilding(errors, data));
                        clone.Apply(new EnviromentChecking(errors, data, false));
                        clone.Apply(new LinkNamedTypes(errors, data));

                        /*
                         * data.Structs.Add(new SharedData.DeclItem<AStructDecl>(pFile, clone));
                         * data.StructFields[clone] = new List<AALocalDecl>();
                         * data.StructMethods[clone] = new List<AMethodDecl>();
                         * data.StructProperties[clone] = new List<APropertyDecl>();
                         * data.StructConstructors[clone] = new List<AConstructorDecl>();
                         * foreach (PLocalDecl localDecl in clone.GetLocals())
                         * {
                         *  if (localDecl is AALocalDecl)
                         *  {
                         *      data.StructFields[clone].Add((AALocalDecl)localDecl);
                         *  }
                         *  else
                         *  {
                         *      PDecl decl = ((ADeclLocalDecl) localDecl).GetDecl();
                         *      if (decl is AMethodDecl)
                         *      {
                         *          data.StructMethods[clone].Add((AMethodDecl) decl);
                         *      }
                         *      else if (decl is APropertyDecl)
                         *      {
                         *          data.StructProperties[clone].Add((APropertyDecl)decl);
                         *      }
                         *      else
                         *      {
                         *          data.StructConstructors[clone].Add((AConstructorDecl) decl);
                         *      }
                         *  }
                         * }*/

                        clones[list] = clone;


                        clone.setGenericVars(new ArrayList());

                        FixGenericLinks.Parse(str, clone, list, data);
                        clone.GetName().Text = Util.TypeToIdentifierString(refference);
                    }
                    //Change refference to clone
                    ANamedType    baseRef = (ANamedType)refference.GetBase();
                    List <string> cloneNs = Util.GetFullNamespace(clone);
                    cloneNs.Add(clone.GetName().Text);
                    AAName aName = (AAName)baseRef.GetName();
                    aName.GetIdentifier().Clear();
                    foreach (var n in cloneNs)
                    {
                        aName.GetIdentifier().Add(new TIdentifier(n));
                    }
                    data.StructTypeLinks[baseRef] = clone;
                    refference.ReplaceBy(baseRef);
                }

                if (!needAnotherPass)
                {
                    parent.RemoveChild(str);
                }
            }
            if (needAnotherPass)
            {
                Refferences.Clear();
                structsWithGenerics.Clear();
                needAnotherPass = false;
                CaseAAProgram(node);
            }
        }
Example #27
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;
            }
        }
Example #28
0
        public override void OutANamedType(ANamedType node)
        {
            if (node.Parent() is ATypedefDecl && ((ATypedefDecl)node.Parent()).GetName() == node)
            {
                return;
            }

            //Link named type to their definition (structs)
            List <ATypedefDecl> typeDefs  = new List <ATypedefDecl>();
            List <AStructDecl>  structs   = new List <AStructDecl>();
            List <AMethodDecl>  delegates = new List <AMethodDecl>();
            List <TIdentifier>  generics  = new List <TIdentifier>();
            bool matchPrimitive;

            GetMatchingTypes(node, typeDefs, structs, delegates, generics, out matchPrimitive);

            int matches = typeDefs.Count + structs.Count + delegates.Count + (matchPrimitive ? 1 : 0) + generics.Count;

            if (matches == 0)
            {
                errors.Add(new ErrorCollection.Error(node.GetToken(), "Could not find any types matching " + ((AAName)node.GetName()).AsString()), true);
            }
            else if (generics.Count != 1 && matches > 1)
            {
                List <ErrorCollection.Error> subError = new List <ErrorCollection.Error>();
                if (matchPrimitive)
                {
                    subError.Add(new ErrorCollection.Error(node.GetToken(), "Matches primitive " + ((AAName)node.GetName()).AsString()));
                }
                foreach (ATypedefDecl typeDef in typeDefs)
                {
                    subError.Add(new ErrorCollection.Error(typeDef.GetToken(), "Matching typedef"));
                }
                foreach (AStructDecl structDecl in structs)
                {
                    subError.Add(new ErrorCollection.Error(structDecl.GetName(), "Matching " + Util.GetTypeName(structDecl)));
                }
                foreach (AMethodDecl methodDecl in delegates)
                {
                    subError.Add(new ErrorCollection.Error(methodDecl.GetName(), "Matching delegate"));
                }
                foreach (TIdentifier identifier in generics)
                {
                    subError.Add(new ErrorCollection.Error(identifier, "Matching generic"));
                }
                errors.Add(
                    new ErrorCollection.Error(node.GetToken(),
                                              "Found multiple types matching " + ((AAName)node.GetName()).AsString(),
                                              false, subError.ToArray()), true);
            }
            else
            {
                if (generics.Count == 1)
                {
                    data.GenericLinks[node] = generics[0];
                    return;
                }
                if (typeDefs.Count == 1)
                {
                    ATypedefDecl typeDef = typeDefs[0];
                    //data.TypeDefLinks[node] = typeDef;
                    PType type = (PType)typeDef.GetType().Clone();
                    node.ReplaceBy(type);
                    type.Apply(this);
                    return;
                }
                if (structs.Count == 1)
                {
                    data.StructTypeLinks[node] = structs[0];
                }
                else if (delegates.Count == 1)
                {
                    data.DelegateTypeLinks[node] = delegates[0];
                }
                if (!matchPrimitive && !(structs.Count == 1 && data.Enums.ContainsKey(structs[0])) && node.Parent() is AEnrichmentDecl) //Not allowed to enrich a struct, class or delegate
                {
                    errors.Add(new ErrorCollection.Error(node.GetToken(), "You can not enrich this type."));
                }
            }
        }
        private void Apply(AAProgram ast)
        {
            int stage       = 1;
            int totalStages = 31;

            List <ANamedType> deleteUs = new List <ANamedType>();

            foreach (KeyValuePair <ANamedType, AStructDecl> pair in data.StructTypeLinks)
            {
                ANamedType  type = pair.Key;
                AStructDecl str  = pair.Value;
                if (data.Enums.ContainsKey(str))
                {
                    type.SetName(new AAName(new ArrayList()
                    {
                        new TIdentifier(data.Enums[str] ? "int" : "byte")
                    }));
                    deleteUs.Add(type);
                }
            }
            foreach (ANamedType type in deleteUs)
            {
                data.StructTypeLinks.Remove(type);
            }



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text2"));
            }
            stage++;

            ast.Apply(new RemoveNamespaces());

            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text3"));
            }
            stage++;

            ast.Apply(new StaticStructMembers(data));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text4"));
            }
            stage++;

            ast.Apply(new RemoveConstants(data));



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text5"));
            }
            stage++;

            ast.Apply(new MainEntryFinder(this));



            if (mainEntry == null)
            {
                //errors.Add(new ErrorCollection.Error("No entry point found (void InitMap(){...})", true));

                //Generate main entry
                AASourceFile file =
                    ast.GetSourceFiles().Cast <AASourceFile>().FirstOrDefault(
                        sourceFile => !Util.GetAncestor <AASourceFile>(sourceFile).GetName().Text.Contains("\\"));
                if (file == null)
                {
                    //Make default sourcefile
                    file = new AASourceFile();
                    file.SetName(new TIdentifier("MapScript"));
                    ast.GetSourceFiles().Add(file);
                    data.LineCounts[file] = 1;
                }
                mainEntry = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null, new AVoidType(new TVoid("void")), new TIdentifier("InitMap"), new ArrayList(), new AABlock());
                file.GetDecl().Add(mainEntry);
                data.Methods.Add(new SharedData.DeclItem <AMethodDecl>(file, mainEntry));
            }
            else if (Util.GetAncestor <AASourceFile>(mainEntry).GetName().Text.Contains("\\"))
            {
                errors.Add(new ErrorCollection.Error(mainEntry.GetName(), Util.GetAncestor <AASourceFile>(mainEntry), LocRM.GetString("FT_Text6"), true));
            }

            ((AABlock)mainEntry.GetBlock()).GetStatements().Insert(0, mainEntryFieldInitBlock);



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text7"));
            }
            stage++;

            ast.Apply(new StructInitializer(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text8"));
            }
            stage++;

            ast.Apply(new TransformExpressionIfs(data));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text9"));
            }
            stage++;

            ast.Apply(new RenameUnicode(data));



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text10"));
            }
            stage++;

            TransformProperties.Phase1.Parse(this);


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text11"));
            }
            stage++;

            ast.Apply(new RemoveDeadCode());


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text12"));
            }
            stage++;

            ast.Apply(new TransformMethodDecls(this));


            if (errors.HasErrors)
            {
                return;
            }


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text13"));
            }
            stage++;



            MakeInitializerInvokes();


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text14"));
            }
            stage++;

            ast.Apply(new AssignFixup(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text15"));
            }
            stage++;

            TransformProperties.Phase2.Parse(this);



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text16"));
            }
            stage++;

            if (data.Invokes.Count > 0)
            {
                Invokes.Parse(this);
            }



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text17"));
            }
            stage++;

            ast.Apply(new RemoveEmptyStructs(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text18"));
            }
            stage++;



            ast.Apply(new Delegates(this));



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text19"));
            }
            stage++;

            //ast.Apply(new AddUnneededRef(data));
            ast.Apply(new FixInlineMethods(this, false));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text20"));
            }
            stage++;



            ast.Apply(new RemoveUnnededRef(data));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text21"));
            }
            stage++;

            ast.Apply(new SplitStructTests(data));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text22"));
            }
            stage++;

            new Pointers(data).Parse(ast);



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text23"));
            }
            stage++;

            ast.Apply(new FixInlineMethods(this, true));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text24"));
            }
            stage++;

            //Split local struct into primitives, to make optimizations easier
            ast.Apply(new StructSplitter(data));
            //ast.Apply(new BulkCopyFixup(this));
            //BulkCopyFixup.Parse(ast, this);


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text25"));
            }
            stage++;

            //Remove stupid assignments (assignments to a variable where that variable is not used before its next assignment
            ast.Apply(new RemoveUnusedVariables(this));



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text26"));
            }
            stage++;



            ast.Apply(new ConstantFolding(data));

            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text27"));
            }
            stage++;



            //Assign fixup was here //Dahm grafiti painters
            //ast.Apply(new LivenessAnalysis(this));
            ast.Apply(new Optimizations.OptimizePhase(this, LocRM.GetString("FT_Text1") + (stage - 1) + " / " + totalStages + LocRM.GetString("FT_Text27")));


            ast.Apply(new FixByteArrayIndexes(data));


            if (Options.Compiler.MakeShortNames)
            {
                if (data.AllowPrintouts)
                {
                    Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text28"));
                }
                stage++;

                ast.Apply(new MakeShortNames(this));
            }
            else
            {
                if (data.AllowPrintouts)
                {
                    Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text29"));
                }
                stage++;

                //MakeUniqueNames.Parse(ast, this);
                ast.Apply(new MakeUniqueNamesV2());
            }



            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text30"));
            }
            stage++;
            //Remove uneeded blocks and check that names fit the decls
            ast.Apply(new RenameRefferences(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text31"));
            }
            stage++;
            //Obfuscate strings
            ast.Apply(new ObfuscateStrings(this));


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text32"));
            }
            stage++;
            MergeSameMethods.Parse(this);


            if (data.AllowPrintouts)
            {
                Form1.Form.SetStatusText(LocRM.GetString("FT_Text1") + stage + " / " + totalStages + LocRM.GetString("FT_Text33"));
            }
            stage++;
            //Insert includes, and move methods, structs and fields around so they are visible
            FixIncludes.Apply(ast, this);
            if (Options.Compiler.OneOutputFile)
            {
                ((AASourceFile)mainEntry.Parent()).SetName(new TIdentifier("MapScript"));
            }
        }
Example #30
0
        private List <PStm> AssignDefault(PLvalue lvalue)
        {
            List <PStm> returner  = new List <PStm>();
            PType       type      = data.LvalueTypes[lvalue];
            PExp        rightSide = null;

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

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

            throw new Exception("Unexpected type. (LivenessAnalasys.AssignDefault), got " + type);
        }