public Declaration(PDecl decl, PType type, long address, string name)
 {
     mDecl    = decl;
     mType    = type;
     mAddress = address;
     mName    = name;
 }
示例#2
0
 public ScopeInfo(Scope scope)
 {
     mBlock    = null;
     mFunction = null;
     mType     = ScopeType.Global;
     mScope    = scope;
 }
示例#3
0
 public ScopeInfo(AFuncDecl decl, Scope scope)
 {
     mFunction = decl;
     mBlock    = null;
     mType     = ScopeType.Function;
     mScope    = scope;
 }
示例#4
0
 public ScopeInfo(ABlockStm stm, Scope scope)
 {
     mBlock    = stm;
     mFunction = null;
     mType     = ScopeType.Block;
     mScope    = scope;
 }
示例#5
0
 public void SetValueOf(PDecl decl, long value)
 {
     if (mNamedTypes.ContainsKey(decl))
     {
         mNamedTypes[decl].Value = value;
     }
     else
     {
         throw new Exception("No such declaration in direct scope");
     }
 }
示例#6
0
        /*public static bool IsDeclVisible(PDecl decl, AASourceFile viewPoint)
         * {
         *  if (!IsVisible(viewPoint, decl))
         *      return false;
         *  if (IsStatic(decl) && GetAncestor<AASourceFile>(decl) != viewPoint)
         *      return false;
         *  return true;
         * }*/

        public static bool IsStatic(PDecl decl)
        {
            if (decl is AFieldDecl)
            {
                return(((AFieldDecl)decl).GetStatic() != null);
            }
            if (decl is APropertyDecl)
            {
                return(((APropertyDecl)decl).GetStatic() != null);
            }
            if (decl is AMethodDecl)
            {
                return(((AMethodDecl)decl).GetStatic() != null);
            }
            return(false);
        }
示例#7
0
 public static Token GetName(PDecl decl)
 {
     if (decl is AFieldDecl)
     {
         return(((AFieldDecl)decl).GetName());
     }
     if (decl is AMethodDecl)
     {
         return(((AMethodDecl)decl).GetName());
     }
     if (decl is AStructDecl)
     {
         return(((AStructDecl)decl).GetName());
     }
     if (decl is AIncludeDecl)
     {
         return(((AIncludeDecl)decl).GetName());
     }
     throw new Exception("Unknown decl");
 }
        public override void CaseANamespaceDecl(ANamespaceDecl node)
        {
            string lastNamespace = currentNamespace;

            currentNamespace += node.GetName().Text + "_";
            base.CaseANamespaceDecl(node);
            currentNamespace = lastNamespace;
            while (node.GetDecl().Count > 0)
            {
                PDecl decl = (PDecl)node.GetDecl()[0];
                node.RemoveChild(decl);
                if (node.Parent() is ANamespaceDecl)
                {
                    ANamespaceDecl parent = (ANamespaceDecl)node.Parent();
                    parent.GetDecl().Insert(parent.GetDecl().IndexOf(node), decl);
                }
                else
                {
                    AASourceFile parent = (AASourceFile)node.Parent();
                    parent.GetDecl().Insert(parent.GetDecl().IndexOf(node), decl);
                }
            }
            node.Parent().RemoveChild(node);
        }
示例#9
0
 internal override void RemoveChild(Node child)
 {
     if (_decl_ == child)
     {
         _decl_ = null;
         return;
     }
 }
示例#10
0
        public void SetDecl(PDecl node)
        {
            if (_decl_ != null)
            {
                _decl_.Parent(null);
            }

            if (node != null)
            {
                if (node.Parent() != null)
                {
                    node.Parent().RemoveChild(node);
                }

                node.Parent(this);
            }

            _decl_ = node;
        }
示例#11
0
 public ADeclLocalDecl(
         PDecl _decl_
 )
 {
     SetDecl(_decl_);
 }
示例#12
0
 public Declaration(PDecl decl, PType type, string name)
 {
     mDecl = decl;
     mType = type;
     mName = name;
 }
        public static void Apply(AAProgram ast, FinalTransformations finalTrans)
        {
            //Build list of file dependacies
            Phase1 phase1 = new Phase1(finalTrans);
            ast.Apply(phase1);
            var dependancies = phase1.dependancies;
            if (dependancies.Keys.Count == 0) return;
            AASourceFile root = Util.GetAncestor<AASourceFile>(finalTrans.mainEntry) ??
                                dependancies.Keys.FirstOrDefault(file => !file.GetName().Text.Contains("\\")) ??
                                dependancies.Keys.First(file => true);

            //Remove files unreachable from root
            //On second thought, dont. there might be static refferences the other way which needs to be included
            /*{
                List<AASourceFile> reachable = GetReachable(root, dependancies);
                AASourceFile[] keys = new AASourceFile[dependancies.Count];
                dependancies.Keys.CopyTo(keys, 0);
                foreach (AASourceFile key in keys)
                {
                    if (!reachable.Contains(key))
                        dependancies.Remove(key);
                }
            }*/

            //Push common depancies up
            /*
             * root -> (item1 -> (item3), item2 -> (item4 -> (item3)))
             *
             * root -> (item3, item1, item2 -> (item4))
             */

            //Add unreachable to the root
            while (true)
            {
                List<AASourceFile> reachable = new List<AASourceFile>();
                GetReachable(root, dependancies, ref reachable);
                if (reachable.Count == dependancies.Count + (reachable.Contains(null) ? 1 : 0)) break;
                AASourceFile[] keys = new AASourceFile[dependancies.Count];
                dependancies.Keys.CopyTo(keys, 0);
                foreach (AASourceFile key in keys)
                {
                    if (!reachable.Contains(key))
                    {
                        AASourceFile k = key;
                        //See if you can find another unreachable file which need this file
                        Dictionary<AASourceFile, int> decendantCounts = new Dictionary<AASourceFile, int>();
                        decendantCounts.Add(k, CountDecendants(k, dependancies, new List<AASourceFile>()));
                        while (true)
                        {
                            AASourceFile file = null;
                            foreach (KeyValuePair<AASourceFile, List<AASourceFile>> dependancy in dependancies)
                            {
                                if (decendantCounts.ContainsKey(dependancy.Key))
                                    continue;
                                if (!dependancy.Value.Contains(k))
                                    continue;
                                file = dependancy.Key;
                                break;
                            }

                            //AASourceFile file = dependancies.FirstOrDefault(item => item.Value.Contains(k)).Key;
                            if (file == null) break;
                            decendantCounts.Add(file, CountDecendants(file, dependancies, new List<AASourceFile>()));
                            k = file;
                        }
                        foreach (KeyValuePair<AASourceFile, int> decendantItem in decendantCounts)
                        {
                            if (decendantItem.Value > decendantCounts[k])
                                k = decendantItem.Key;
                        }

                        dependancies[root].Add(k);
                        break;
                    }
                }
            }
            //It is moved down here because cycles are not removed in unreachable
            RemoveCycles(root, dependancies, new List<AASourceFile> { root });

            //Convert to tree to make it easier
            List<Item> allItems = new List<Item>();
            IncludeItem rootIncludeItem = MakeTree(root, dependancies, allItems, null);
            bool[] removed = new bool[allItems.Count];
            for (int i = 0; i < removed.Length; i++)
                removed[i] = false;
            int removedCount = 0;

            //Ensure that each include is only included one place
            for (int i = 0; i < allItems.Count; i++)
            {
                if (removed[i])
                    continue;

                IncludeItem item1 = (IncludeItem)allItems[i];
                for (int j = i + 1; j < allItems.Count; j++)
                {
                    if (removed[j])
                        continue;
                    IncludeItem item2 = (IncludeItem)allItems[j];

                    if (item1.Current == item2.Current)
                    {
                        List<Item> path1 = item1.Path;
                        List<Item> path2 = item2.Path;

                        for (int k = 0; k < Math.Min(path1.Count, path2.Count); k++)
                        {
                            if (path1[k] != path2[k])
                            {

                                int insertAt = Math.Min(path1[k - 1].Children.IndexOf(path1[k]),
                                                        path2[k - 1].Children.IndexOf(path2[k]));

                                item1.Parent.Children.Remove(item1);
                                LinkedList<IncludeItem> toRemove = new LinkedList<IncludeItem>();
                                toRemove.AddLast(item2);
                                while (toRemove.Count > 0)
                                {
                                    IncludeItem item = toRemove.First.Value;
                                    toRemove.RemoveFirst();
                                    item.Parent.Children.Remove(item);
                                    //allItems.Remove(item);
                                    removedCount++;
                                    removed[item.ListIndex] = true;
                                    foreach (IncludeItem child in item.Children)
                                    {
                                        toRemove.AddLast(child);
                                    }
                                }
                                //j--;

                                path1[k - 1].Children.Insert(insertAt, item1);
                                item1.Parent = path1[k - 1];

                                break;
                            }
                        }
                    }
                }
            }

            List<Item> newAllItems = new List<Item>(allItems.Count - removedCount);
            for (int i = 0; i < allItems.Count; i++)
                if (!removed[i])
                    newAllItems.Add(allItems[i]);
            allItems = newAllItems;

            //Move the null node to nr [0]
            foreach (IncludeItem item in allItems)
            {
                if (item.Current == null)
                {
                    int itemIndex = item.Parent.Children.IndexOf(item);
                    Item item0 = item.Parent.Children[0];
                    item.Parent.Children[0] = item;
                    item.Parent.Children[itemIndex] = item0;
                    break;
                }
            }

            //Insert method decls and move structs & fields up as needed
            ast.Apply(new Phase2(finalTrans, allItems));

            //Insert the headers in the files

            if (Options.Compiler.OneOutputFile)
            {
                //for (int i = 0; i < allItems.Count; i++)
                int i = 0;
                while (allItems.Count > 0)
                {
                    if (allItems[i] is IncludeItem)
                    {
                        IncludeItem includeItem = (IncludeItem) allItems[i];
                        //Dont want the standard lib
                        if (includeItem.Current == null)
                        {
                            i++;
                            continue;
                        }
                        //If it has children with children, then pick another first
                        if (includeItem.Children.Any(child => child.Children.Count > 0))
                        {
                            i++;
                            continue;
                        }
                        if (includeItem.Children.Count == 0)
                        {
                            if (includeItem.Parent == null)
                                break;
                            i++;
                            continue;
                        }
                        i = 0;
                        //Put all children into this
                        while (includeItem.Children.Count > 0)
                        {
                            int childNr = includeItem.Children.Count - 1;
                            allItems.Remove(includeItem.Children[childNr]);
                            if (includeItem.Children[childNr] is FieldItem)
                            {
                                FieldItem aItem = (FieldItem)includeItem.Children[childNr];
                                Node node = aItem.FieldDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is StructItem)
                            {
                                StructItem aItem = (StructItem)includeItem.Children[childNr];
                                Node node = aItem.StructDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is MethodDeclItem)
                            {
                                MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[childNr];
                                AMethodDecl aNode = new AMethodDecl();
                                if (aItem.RealDecl.GetStatic() != null) aNode.SetStatic(new TStatic("static"));
                                aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                                aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                                foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                                {
                                    AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                    aNode.GetFormals().Add(clone);
                                }
                                includeItem.Current.GetDecl().Insert(0, aNode);
                            }
                            else if (includeItem.Children[childNr] is IncludeItem)
                            {
                                IncludeItem aChild = (IncludeItem)includeItem.Children[childNr];
                                if (aChild.Current == null)
                                {
                                    AIncludeDecl node = new AIncludeDecl(new TInclude("include"),
                                                        new TStringLiteral("\"TriggerLibs/NativeLib\""));
                                    includeItem.Current.GetDecl().Insert(0, node);
                                }
                                else
                                {
                                    PDecl[] decls = new PDecl[aChild.Current.GetDecl().Count];
                                    aChild.Current.GetDecl().CopyTo(decls, 0);
                                    for (int k = decls.Length - 1; k >= 0; k--)
                                    {
                                        includeItem.Current.GetDecl().Insert(0, decls[k]);
                                    }
                                    aChild.Current.Parent().RemoveChild(aChild.Current);
                                    //i = -1;
                                }
                            }
                            includeItem.Children.RemoveAt(childNr);
                        }
                    }
                }
            }
            else
                foreach (IncludeItem includeItem in allItems.OfType<IncludeItem>())
                {
                    for (int i = includeItem.Children.Count - 1; i >= 0; i--)
                    {
                        Node node;
                        if (includeItem.Children[i] is IncludeItem)
                        {
                            IncludeItem aItem = (IncludeItem) includeItem.Children[i];
                            node = new AIncludeDecl(new TInclude("include"),
                                                    new TStringLiteral("\"" + (aItem.Current == null ? "TriggerLibs/NativeLib" : aItem.Current.GetName().Text.Replace("\\", "/")) + "\""));
                            if (aItem.Current == null && finalTrans.mainEntry != null)
                            {
                                //Search for user defined initlib
                                bool foundInvoke = false;
                                foreach (ASimpleInvokeExp invokeExp in finalTrans.data.SimpleMethodLinks.Keys)
                                {
                                    if(invokeExp.GetName().Text == "libNtve_InitLib" && invokeExp.GetArgs().Count == 0)
                                    {
                                        /*finalTrans.errors.Add(new ErrorCollection.Error(invokeExp.GetName(),
                                                                                        Util.GetAncestor<AASourceFile>(
                                                                                            invokeExp),
                                                                                        "You are invoking libNtve_InitLib() yourself somewhere. It will not be auto inserted.",
                                                                                        true));*/
                                        foundInvoke = true;
                                        break;
                                    }
                                }

                                if (!foundInvoke)
                                {
                                    //Init the lib
                                    ASimpleInvokeExp initExp = new ASimpleInvokeExp();
                                    initExp.SetName(new TIdentifier("libNtve_InitLib"));
                                    finalTrans.data.ExpTypes[initExp] = new AVoidType(new TVoid("void"));
                                    foreach (AMethodDecl method in finalTrans.data.Libraries.Methods)
                                    {
                                        if (method.GetName().Text == "libNtve_InitLib" && method.GetFormals().Count == 0)
                                        {
                                            finalTrans.data.SimpleMethodLinks[initExp] = method;
                                        }
                                    }
                                    AABlock block = (AABlock) finalTrans.mainEntry.GetBlock();
                                    block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), initExp));
                                }
                            }
                        }
                        else if (includeItem.Children[i] is FieldItem)
                        {
                            FieldItem aItem = (FieldItem)includeItem.Children[i];
                            node = aItem.FieldDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is StructItem)
                        {
                            StructItem aItem = (StructItem)includeItem.Children[i];
                            node = aItem.StructDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is MethodDeclItem)
                        {
                            MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[i];
                            AMethodDecl aNode = new AMethodDecl();
                            if (aItem.RealDecl.GetStatic() != null) aNode.SetStatic(new TStatic("static"));
                            aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                            aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                            foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                            {
                                AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                aNode.GetFormals().Add(clone);
                            }
                            node = aNode;
                        }
                        else
                            throw new Exception("FixIncludes.Apply: Unexpected item type");

                        includeItem.Current.GetDecl().Insert(0, node);
                    }
                }
        }
示例#14
0
        public override void CaseAStructDecl(AStructDecl node)
        {
            if (checkedStructs.Contains(node))
            {
                return;
            }
            checkedStructs.Add(node);

            //Set where they originate from.
            foreach (PLocalDecl localDecl in node.GetLocals())
            {
                if (localDecl is AALocalDecl)
                {
                    fieldOriginatesFrom[(AALocalDecl)localDecl] = node;
                }
                else //Is DeclLocalDecl
                {
                    ADeclLocalDecl aLocalDecl = (ADeclLocalDecl)localDecl;
                    PDecl          decl       = aLocalDecl.GetDecl();
                    if (decl is AMethodDecl)
                    {
                        methodOriginatesFrom[(AMethodDecl)decl] = node;
                    }
                    else if (decl is APropertyDecl)
                    {
                        propertyOriginatesFrom[(APropertyDecl)decl] = node;
                    }
                    else if (decl is AThisArrayPropertyDecl)
                    {
                        arrayPropertyOriginatesFrom[(AThisArrayPropertyDecl)decl] = node;
                    }
                }
            }


            if (node.GetBase() == null)
            {
                return;
            }

            AStructDecl baseStr = Lookup((ANamedType)node.GetBase());

            if (!checkedStructs.Contains(baseStr))
            {
                CaseAStructDecl(baseStr);
            }
            CheckEnheritanceList(node, new List <AStructDecl>());
            //A struct may not enhrit from a class
            if (node.GetClassToken() == null && baseStr.GetClassToken() != null)
            {
                errors.Add(new ErrorCollection.Error(node.GetName(), "A struct can not enherit from a class.", false,
                                                     new ErrorCollection.Error(baseStr.GetName(), "Enherited class")));
            }

            //Copy everything in base struct to here (Except from constructors)
            List <PLocalDecl> stuffToAdd = new List <PLocalDecl>();

            foreach (AALocalDecl baseLocalVar in data.StructFields[baseStr])
            {
                //Check that it is not overwritten
                foreach (AALocalDecl localVar in node.GetLocals().OfType <AALocalDecl>())
                {
                    if (baseLocalVar.GetName().Text == localVar.GetName().Text)
                    {
                        errors.Add(new ErrorCollection.Error(localVar.GetName(),
                                                             "It is not possible to override fields.", false,
                                                             new ErrorCollection.Error(
                                                                 fieldOriginatesFrom[baseLocalVar].GetName(),
                                                                 "Overridden " +
                                                                 Util.GetTypeName(fieldOriginatesFrom[baseLocalVar]))));
                        throw new ParserException(null, null);
                    }
                }
                foreach (APropertyDecl localProperty in data.StructProperties[node])
                {
                    if (localProperty.GetName().Text == baseLocalVar.GetName().Text)
                    {
                        errors.Add(new ErrorCollection.Error(localProperty.GetName(),
                                                             "It is not possible to override fields.", false,
                                                             new ErrorCollection.Error(
                                                                 fieldOriginatesFrom[baseLocalVar].GetName(),
                                                                 "Overridden " +
                                                                 Util.GetTypeName(fieldOriginatesFrom[baseLocalVar]))));
                        throw new ParserException(null, null);
                    }
                }
                //Insert at top
                AALocalDecl newLocalVar = (AALocalDecl)baseLocalVar.Clone();
                baseLocalVar.Apply(new FixNamedRefferences(newLocalVar, data));
                stuffToAdd.Add(newLocalVar);
                data.StructFields[node].Add(newLocalVar);
                fieldOriginatesFrom[newLocalVar] = fieldOriginatesFrom[baseLocalVar];
                if (data.EnheritanceLocalMap.ContainsKey(baseLocalVar))
                {
                    data.EnheritanceLocalMap[newLocalVar] = data.EnheritanceLocalMap[baseLocalVar];
                }
                else
                {
                    data.EnheritanceLocalMap[newLocalVar] = baseLocalVar;
                }
            }
            for (int i = stuffToAdd.Count - 1; i >= 0; i--)
            {
                node.GetLocals().Insert(0, stuffToAdd[i]);
            }
            //Methods
            foreach (AMethodDecl baseMethod in data.StructMethods[baseStr])
            {
                //Check that it is not overwritten
                foreach (AMethodDecl localMethod in node.GetLocals().OfType <ADeclLocalDecl>().Select(l => l.GetDecl()).OfType <AMethodDecl>())
                {
                    if (Util.GetMethodSignature(baseMethod) == Util.GetMethodSignature(localMethod))
                    {
                        errors.Add(new ErrorCollection.Error(localMethod.GetName(),
                                                             "It is not possible to override methods.", false,
                                                             new ErrorCollection.Error(
                                                                 methodOriginatesFrom[baseMethod].GetName(),
                                                                 "Overridden " +
                                                                 Util.GetTypeName(methodOriginatesFrom[baseMethod]))));
                        throw new ParserException(null, null);
                    }
                }
                data.StructMethods[node].Add(baseMethod);
            }
            //Properties
            foreach (APropertyDecl baseProperty in data.StructProperties[baseStr])
            {
                //Check that it is not overwritten
                foreach (APropertyDecl localProperty in data.StructProperties[node])
                {
                    if (localProperty.GetName().Text == baseProperty.GetName().Text)
                    {
                        errors.Add(new ErrorCollection.Error(localProperty.GetName(),
                                                             "It is not possible to override properties.", false,
                                                             new ErrorCollection.Error(
                                                                 propertyOriginatesFrom[baseProperty].GetName(),
                                                                 "Overridden " +
                                                                 Util.GetTypeName(propertyOriginatesFrom[baseProperty]))));
                        throw new ParserException(null, null);
                    }
                }
                foreach (AALocalDecl localVar in node.GetLocals().OfType <AALocalDecl>())
                {
                    if (baseProperty.GetName().Text == localVar.GetName().Text)
                    {
                        errors.Add(new ErrorCollection.Error(localVar.GetName(),
                                                             "It is not possible to override properties.", false,
                                                             new ErrorCollection.Error(
                                                                 propertyOriginatesFrom[baseProperty].GetName(),
                                                                 "Overridden " +
                                                                 Util.GetTypeName(propertyOriginatesFrom[baseProperty]))));
                        throw new ParserException(null, null);
                    }
                }
                data.StructProperties[node].Add(baseProperty);
            }
        }
示例#15
0
        public static void Apply(AAProgram ast, FinalTransformations finalTrans)
        {
            //Build list of file dependacies
            Phase1 phase1 = new Phase1(finalTrans);

            ast.Apply(phase1);
            var dependancies = phase1.dependancies;

            if (dependancies.Keys.Count == 0)
            {
                return;
            }
            AASourceFile root = Util.GetAncestor <AASourceFile>(finalTrans.mainEntry) ??
                                dependancies.Keys.FirstOrDefault(file => !file.GetName().Text.Contains("\\")) ??
                                dependancies.Keys.First(file => true);

            //Remove files unreachable from root
            //On second thought, dont. there might be static refferences the other way which needs to be included

            /*{
             *  List<AASourceFile> reachable = GetReachable(root, dependancies);
             *  AASourceFile[] keys = new AASourceFile[dependancies.Count];
             *  dependancies.Keys.CopyTo(keys, 0);
             *  foreach (AASourceFile key in keys)
             *  {
             *      if (!reachable.Contains(key))
             *          dependancies.Remove(key);
             *  }
             * }*/


            //Push common depancies up

            /*
             * root -> (item1 -> (item3), item2 -> (item4 -> (item3)))
             *
             * root -> (item3, item1, item2 -> (item4))
             */

            //Add unreachable to the root
            while (true)
            {
                List <AASourceFile> reachable = new List <AASourceFile>();
                GetReachable(root, dependancies, ref reachable);
                if (reachable.Count == dependancies.Count + (reachable.Contains(null) ? 1 : 0))
                {
                    break;
                }
                AASourceFile[] keys = new AASourceFile[dependancies.Count];
                dependancies.Keys.CopyTo(keys, 0);
                foreach (AASourceFile key in keys)
                {
                    if (!reachable.Contains(key))
                    {
                        AASourceFile k = key;
                        //See if you can find another unreachable file which need this file
                        Dictionary <AASourceFile, int> decendantCounts = new Dictionary <AASourceFile, int>();
                        decendantCounts.Add(k, CountDecendants(k, dependancies, new List <AASourceFile>()));
                        while (true)
                        {
                            AASourceFile file = null;
                            foreach (KeyValuePair <AASourceFile, List <AASourceFile> > dependancy in dependancies)
                            {
                                if (decendantCounts.ContainsKey(dependancy.Key))
                                {
                                    continue;
                                }
                                if (!dependancy.Value.Contains(k))
                                {
                                    continue;
                                }
                                file = dependancy.Key;
                                break;
                            }

                            //AASourceFile file = dependancies.FirstOrDefault(item => item.Value.Contains(k)).Key;
                            if (file == null)
                            {
                                break;
                            }
                            decendantCounts.Add(file, CountDecendants(file, dependancies, new List <AASourceFile>()));
                            k = file;
                        }
                        foreach (KeyValuePair <AASourceFile, int> decendantItem in decendantCounts)
                        {
                            if (decendantItem.Value > decendantCounts[k])
                            {
                                k = decendantItem.Key;
                            }
                        }

                        dependancies[root].Add(k);
                        break;
                    }
                }
            }
            //It is moved down here because cycles are not removed in unreachable
            RemoveCycles(root, dependancies, new List <AASourceFile> {
                root
            });


            //Convert to tree to make it easier
            List <Item> allItems        = new List <Item>();
            IncludeItem rootIncludeItem = MakeTree(root, dependancies, allItems, null);

            bool[] removed = new bool[allItems.Count];
            for (int i = 0; i < removed.Length; i++)
            {
                removed[i] = false;
            }
            int removedCount = 0;

            //Ensure that each include is only included one place
            for (int i = 0; i < allItems.Count; i++)
            {
                if (removed[i])
                {
                    continue;
                }

                IncludeItem item1 = (IncludeItem)allItems[i];
                for (int j = i + 1; j < allItems.Count; j++)
                {
                    if (removed[j])
                    {
                        continue;
                    }
                    IncludeItem item2 = (IncludeItem)allItems[j];

                    if (item1.Current == item2.Current)
                    {
                        List <Item> path1 = item1.Path;
                        List <Item> path2 = item2.Path;



                        for (int k = 0; k < Math.Min(path1.Count, path2.Count); k++)
                        {
                            if (path1[k] != path2[k])
                            {
                                int insertAt = Math.Min(path1[k - 1].Children.IndexOf(path1[k]),
                                                        path2[k - 1].Children.IndexOf(path2[k]));


                                item1.Parent.Children.Remove(item1);
                                LinkedList <IncludeItem> toRemove = new LinkedList <IncludeItem>();
                                toRemove.AddLast(item2);
                                while (toRemove.Count > 0)
                                {
                                    IncludeItem item = toRemove.First.Value;
                                    toRemove.RemoveFirst();
                                    item.Parent.Children.Remove(item);
                                    //allItems.Remove(item);
                                    removedCount++;
                                    removed[item.ListIndex] = true;
                                    foreach (IncludeItem child in item.Children)
                                    {
                                        toRemove.AddLast(child);
                                    }
                                }
                                //j--;



                                path1[k - 1].Children.Insert(insertAt, item1);
                                item1.Parent = path1[k - 1];



                                break;
                            }
                        }
                    }
                }
            }

            List <Item> newAllItems = new List <Item>(allItems.Count - removedCount);

            for (int i = 0; i < allItems.Count; i++)
            {
                if (!removed[i])
                {
                    newAllItems.Add(allItems[i]);
                }
            }
            allItems = newAllItems;

            //Move the null node to nr [0]
            foreach (IncludeItem item in allItems)
            {
                if (item.Current == null)
                {
                    int  itemIndex = item.Parent.Children.IndexOf(item);
                    Item item0     = item.Parent.Children[0];
                    item.Parent.Children[0]         = item;
                    item.Parent.Children[itemIndex] = item0;
                    break;
                }
            }

            //Insert method decls and move structs & fields up as needed
            ast.Apply(new Phase2(finalTrans, allItems));

            //Insert the headers in the files

            if (Options.Compiler.OneOutputFile)
            {
                //for (int i = 0; i < allItems.Count; i++)
                int i = 0;
                while (allItems.Count > 0)
                {
                    if (allItems[i] is IncludeItem)
                    {
                        IncludeItem includeItem = (IncludeItem)allItems[i];
                        //Dont want the standard lib
                        if (includeItem.Current == null)
                        {
                            i++;
                            continue;
                        }
                        //If it has children with children, then pick another first
                        if (includeItem.Children.Any(child => child.Children.Count > 0))
                        {
                            i++;
                            continue;
                        }
                        if (includeItem.Children.Count == 0)
                        {
                            if (includeItem.Parent == null)
                            {
                                break;
                            }
                            i++;
                            continue;
                        }
                        i = 0;
                        //Put all children into this
                        while (includeItem.Children.Count > 0)
                        {
                            int childNr = includeItem.Children.Count - 1;
                            allItems.Remove(includeItem.Children[childNr]);
                            if (includeItem.Children[childNr] is FieldItem)
                            {
                                FieldItem aItem = (FieldItem)includeItem.Children[childNr];
                                Node      node  = aItem.FieldDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is StructItem)
                            {
                                StructItem aItem = (StructItem)includeItem.Children[childNr];
                                Node       node  = aItem.StructDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is MethodDeclItem)
                            {
                                MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[childNr];
                                AMethodDecl    aNode = new AMethodDecl();
                                if (aItem.RealDecl.GetStatic() != null)
                                {
                                    aNode.SetStatic(new TStatic("static"));
                                }
                                aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                                aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                                foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                                {
                                    AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                    aNode.GetFormals().Add(clone);
                                }
                                includeItem.Current.GetDecl().Insert(0, aNode);
                            }
                            else if (includeItem.Children[childNr] is IncludeItem)
                            {
                                IncludeItem aChild = (IncludeItem)includeItem.Children[childNr];
                                if (aChild.Current == null)
                                {
                                    AIncludeDecl node = new AIncludeDecl(new TInclude("include"),
                                                                         new TStringLiteral("\"TriggerLibs/NativeLib\""));
                                    includeItem.Current.GetDecl().Insert(0, node);
                                }
                                else
                                {
                                    PDecl[] decls = new PDecl[aChild.Current.GetDecl().Count];
                                    aChild.Current.GetDecl().CopyTo(decls, 0);
                                    for (int k = decls.Length - 1; k >= 0; k--)
                                    {
                                        includeItem.Current.GetDecl().Insert(0, decls[k]);
                                    }
                                    aChild.Current.Parent().RemoveChild(aChild.Current);
                                    //i = -1;
                                }
                            }
                            includeItem.Children.RemoveAt(childNr);
                        }
                    }
                }
            }
            else
            {
                foreach (IncludeItem includeItem in allItems.OfType <IncludeItem>())
                {
                    for (int i = includeItem.Children.Count - 1; i >= 0; i--)
                    {
                        Node node;
                        if (includeItem.Children[i] is IncludeItem)
                        {
                            IncludeItem aItem = (IncludeItem)includeItem.Children[i];
                            node = new AIncludeDecl(new TInclude("include"),
                                                    new TStringLiteral("\"" + (aItem.Current == null ? "TriggerLibs/NativeLib" : aItem.Current.GetName().Text.Replace("\\", "/")) + "\""));
                            if (aItem.Current == null && finalTrans.mainEntry != null)
                            {
                                //Search for user defined initlib
                                bool foundInvoke = false;
                                foreach (ASimpleInvokeExp invokeExp in finalTrans.data.SimpleMethodLinks.Keys)
                                {
                                    if (invokeExp.GetName().Text == "libNtve_InitLib" && invokeExp.GetArgs().Count == 0)
                                    {
                                        /*finalTrans.errors.Add(new ErrorCollection.Error(invokeExp.GetName(),
                                         *                                              Util.GetAncestor<AASourceFile>(
                                         *                                                  invokeExp),
                                         *                                              "You are invoking libNtve_InitLib() yourself somewhere. It will not be auto inserted.",
                                         *                                              true));*/
                                        foundInvoke = true;
                                        break;
                                    }
                                }

                                if (!foundInvoke)
                                {
                                    //Init the lib
                                    ASimpleInvokeExp initExp = new ASimpleInvokeExp();
                                    initExp.SetName(new TIdentifier("libNtve_InitLib"));
                                    finalTrans.data.ExpTypes[initExp] = new AVoidType(new TVoid("void"));
                                    foreach (AMethodDecl method in finalTrans.data.Libraries.Methods)
                                    {
                                        if (method.GetName().Text == "libNtve_InitLib" && method.GetFormals().Count == 0)
                                        {
                                            finalTrans.data.SimpleMethodLinks[initExp] = method;
                                        }
                                    }
                                    AABlock block = (AABlock)finalTrans.mainEntry.GetBlock();
                                    block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), initExp));
                                }
                            }
                        }
                        else if (includeItem.Children[i] is FieldItem)
                        {
                            FieldItem aItem = (FieldItem)includeItem.Children[i];
                            node = aItem.FieldDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is StructItem)
                        {
                            StructItem aItem = (StructItem)includeItem.Children[i];
                            node = aItem.StructDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is MethodDeclItem)
                        {
                            MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[i];
                            AMethodDecl    aNode = new AMethodDecl();
                            if (aItem.RealDecl.GetStatic() != null)
                            {
                                aNode.SetStatic(new TStatic("static"));
                            }
                            aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                            aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                            foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                            {
                                AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                aNode.GetFormals().Add(clone);
                            }
                            node = aNode;
                        }
                        else
                        {
                            throw new Exception("FixIncludes.Apply: Unexpected item type");
                        }

                        includeItem.Current.GetDecl().Insert(0, node);
                    }
                }
            }
        }