public override void InAAProgram(AAProgram node)
        {
            return;
            //Check that there are not two diffrent definitions with same name, in same namespace

            for (int i = 0; i < node.GetSourceFiles().Count; i++)
            {
                for (int j = i; j < node.GetSourceFiles().Count; j++)
                {
                    AASourceFile file1 = (AASourceFile) node.GetSourceFiles()[i];
                    AASourceFile file2 = (AASourceFile) node.GetSourceFiles()[j];

                    Check(new List<IList>() {file1.GetDecl()}, new List<IList>() {file2.GetDecl()});
                }
            }
        }
 public override void CaseAAProgram(AAProgram node)
 {
     InAAProgram(node);
     {
         Object[] temp = new Object[node.GetSourceFiles().Count];
         node.GetSourceFiles().CopyTo(temp, 0);
         for (int i = temp.Length - 1; i >= 0; i--)
         {
             ((PSourceFile)temp[i]).Apply(this);
         }
     }
     OutAAProgram(node);
 }
        private void CompileThread()
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo(Form1.Language);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(Form1.Language);
            try
            {
                if (!compilingFromCommandLine)
                    form.SetStatusText(LocRM.GetString("GC_Text3"));

                if (!compilingFromCommandLine)
                    ClearErrorWindow();
                //Build a tree with all sourcefiles
                AAProgram root = new AAProgram();
                ErrorCollection errors = new ErrorCollection();
                currentErrorCollection = errors;
                if (!compilingFromCommandLine)
                    errors.ErrorAdded += errors_ErrorAdded;
                bool addedDeobfuscator = false;
                SharedData sharedData = new SharedData();
                sharedData.AllowPrintouts = !compilingFromCommandLine;
                //Parse project files
                List<string> fileNames = new List<string>();
                List<string> sources = new List<string>();
                foreach (
                    FileItem sourceFile in Form1.GetSourceFiles(ProjectProperties.CurrentProjectPropperties.SrcFolder))
                {
                    if (sourceFile.Deactivated)
                        continue;
                    StreamReader reader = sourceFile.File.OpenText();

                    string filename = sourceFile.File.FullName;
                    //Remove c:/.../projectDir/src
                    filename = filename.Remove(0, (ProjectDir.FullName + "/src/").Length);
                    //Remove .galaxy++
                    filename = filename.Remove(filename.Length - ".galaxy++".Length);
                    fileNames.Add(filename);
                    sources.Add(reader.ReadToEnd());
                    reader.Close();
                    continue;

                    Parser parser = new Parser(new Lexer(reader));
                    try
                    {
                        Start start = parser.Parse();
                        AASourceFile sourceNode = (AASourceFile) start.GetPSourceFile();
                        reader.Close();
                        reader = sourceFile.File.OpenText();
                        int lineCount = 0;
                        while (reader.ReadLine() != null)
                        {
                            lineCount++;
                        }
                        reader.Close();
                        sharedData.LineCounts[sourceNode] = lineCount;

                        //Extract encryption function
                       /* {
                            AASourceFile file = (AASourceFile) start.GetPSourceFile();
                            if (file.GetDecl().Count > 0 && file.GetDecl()[0] is AMethodDecl)
                            {
                                AMethodDecl method = (AMethodDecl) file.GetDecl()[0];
                                if (method.GetName().Text == "Galaxy_pp_Deobfuscate")
                                {
                                    FileInfo dobfuscateFile = new FileInfo("Deobfuscator.LibraryData");
                                    IFormatter formatter = new BinaryFormatter();
                                    Stream stream = dobfuscateFile.Open(FileMode.Create);
                                    formatter.Serialize(stream, method);
                                    stream.Close();
                                }
                            }
                        }*/

                        if (Options.Compiler.ObfuscateStrings)
                        {
                            HasStringConstExp checker = new HasStringConstExp();
                            start.Apply(checker);

                            if (!addedDeobfuscator /* && checker.HasStringConst*/)
                            {
                                FileInfo dobfuscateFile = new FileInfo("Deobfuscator.LibraryData");
                                IFormatter formatter = new BinaryFormatter();
                                Stream stream = dobfuscateFile.Open(FileMode.Open);
                                AASourceFile file = (AASourceFile) start.GetPSourceFile();

                                AMethodDecl method = (AMethodDecl) formatter.Deserialize(stream);
                                sharedData.DeobfuscateMethod = method;
                                method.GetName().Line = 0;

                                HasStringConstExp checker2 = new HasStringConstExp();
                                method.Apply(checker2);
                                file.GetDecl().Insert(0, method);
                                stream.Close();

                                addedDeobfuscator = true;

                                foreach (AStringConstExp stringConstExp in checker2.List)
                                {
                                    int line = -sharedData.UnobfuscatedStrings.Count - 1;
                                    AFieldDecl field = new AFieldDecl(new APublicVisibilityModifier(), null, new TConst("const", line, 0),
                                                                      new ANamedType(new TIdentifier("string", line, 1),
                                                                                     null),
                                                                      new TIdentifier("Galaxy_pp_stringU" +
                                                                                      sharedData.UnobfuscatedStrings.
                                                                                          Count),
                                                                      null);
                                    //If the strings are the same - point them to same field
                                    bool newField = true;
                                    foreach (AStringConstExp oldStringConstExp in sharedData.UnobfuscatedStrings.Keys)
                                    {
                                        if (stringConstExp.GetStringLiteral().Text ==
                                            oldStringConstExp.GetStringLiteral().Text)
                                        {
                                            field = sharedData.UnobfuscatedStrings[oldStringConstExp];
                                            newField = false;
                                            break;
                                        }
                                    }
                                    if (newField)
                                    {
                                        file.GetDecl().Insert(0, field);
                                        sharedData.ObfuscationFields.Add(field);
                                    }
                                    sharedData.UnobfuscatedStrings.Add(stringConstExp, field);

                                }

                            }
                            foreach (AStringConstExp stringConstExp in checker.List)
                            {
                                int line = -sharedData.ObfuscatedStrings.Count - 1;
                                AFieldDecl field = new AFieldDecl(new APublicVisibilityModifier(), null, new TConst("const", line, 0),
                                                                  new ANamedType(new TIdentifier("string", line, 1),
                                                                                 null),
                                                                  new TIdentifier("Galaxy_pp_stringO" +
                                                                                  sharedData.ObfuscatedStrings.Count),
                                                                  null);
                                //If the strings are the same - point them to same field
                                bool newField = true;
                                foreach (AStringConstExp oldStringConstExp in sharedData.ObfuscatedStrings.Keys)
                                {
                                    if (stringConstExp.GetStringLiteral().Text ==
                                        oldStringConstExp.GetStringLiteral().Text)
                                    {
                                        field = sharedData.ObfuscatedStrings[oldStringConstExp];
                                        newField = false;
                                        break;
                                    }
                                }
                                if (newField)
                                {
                                    AASourceFile file = (AASourceFile) sharedData.DeobfuscateMethod.Parent();
                                    file.GetDecl().Insert(file.GetDecl().IndexOf(sharedData.DeobfuscateMethod) + 1,
                                                          field);
                                    sharedData.ObfuscationFields.Add(field);
                                }
                                sharedData.ObfuscatedStrings.Add(stringConstExp, field);
                            }
                        }

                        sourceNode.SetName(new TIdentifier(filename));
                        root.GetSourceFiles().Add(start.GetPSourceFile());

                    }
                    catch (ParserException err)
                    {
                        String errMsg = err.Message;
                        //Remove [...]
                        errMsg = errMsg.Substring(errMsg.IndexOf(']') + 1).TrimStart();
                        errors.Add(new ErrorCollection.Error(err.Token, filename, errMsg));
                    }
                    reader.Close();
                }
                //Parse project dialogs
                foreach (
                    DialogItem dialogItem in Form1.GetDialogsFiles(ProjectProperties.CurrentProjectPropperties.SrcFolder))
                {
                    if (dialogItem.Deactivated)
                        continue;
                   // List<string> fileNames = new List<string>();
                   // List<string> sources = new List<string>();

                    DialogData data;
                    if (dialogItem.OpenFileData != null)
                    {
                        data = dialogItem.OpenFileData;
                        data.Save(dialogItem.FullName);
                    }
                    else
                    {
                        data = DialogData.Load(dialogItem.FullName);
                        data.DialogItem = dialogItem;
                    }

                    string filename = dialogItem.FullName;
                    filename = filename.Remove(0, (ProjectDir.FullName + "/src/").Length);
                    filename = filename.Remove(filename.Length - ".Dialog".Length);

                    fileNames.Add(filename);
                    sources.Add(data.Code ?? "");

                    fileNames.Add(filename + ".Designer");
                    sources.Add(data.DesignerCode ?? "");

                    continue;

                    for (int i = 0; i < fileNames.Count; i++)
                    {
                        filename = fileNames[i];
                        StringReader reader = new StringReader(sources[i] ?? "");
                        Parser parser = new Parser(new Lexer(reader));
                        try
                        {
                            Start start = parser.Parse();
                            AASourceFile sourceNode = (AASourceFile) start.GetPSourceFile();
                            reader.Close();
                            reader.Dispose();
                            reader = new StringReader(sources[i] ?? "");
                            int lineCount = 0;
                            while (reader.ReadLine() != null)
                            {
                                lineCount++;
                            }
                            reader.Close();

                            sharedData.LineCounts[sourceNode] = lineCount;

                            if (Options.Compiler.ObfuscateStrings)
                            {
                                HasStringConstExp checker = new HasStringConstExp();
                                start.Apply(checker);

                                if (!addedDeobfuscator /* && checker.HasStringConst*/)
                                {
                                    FileInfo dobfuscateFile = new FileInfo("Deobfuscator.LibraryData");
                                    IFormatter formatter = new BinaryFormatter();
                                    Stream stream = dobfuscateFile.Open(FileMode.Open);
                                    AASourceFile file = (AASourceFile) start.GetPSourceFile();

                                    AMethodDecl method = (AMethodDecl) formatter.Deserialize(stream);
                                    sharedData.DeobfuscateMethod = method;
                                    method.GetName().Line = 0;

                                    HasStringConstExp checker2 = new HasStringConstExp();
                                    method.Apply(checker2);
                                    file.GetDecl().Insert(0, method);
                                    stream.Close();

                                    addedDeobfuscator = true;

                                    foreach (AStringConstExp stringConstExp in checker2.List)
                                    {
                                        int line = -sharedData.UnobfuscatedStrings.Count - 1;
                                        AFieldDecl field = new AFieldDecl(new APublicVisibilityModifier(), null,
                                                                          new TConst("const", line, 0),
                                                                          new ANamedType(
                                                                              new TIdentifier("string", line, 1),
                                                                              null),
                                                                          new TIdentifier("Galaxy_pp_stringU" +
                                                                                          sharedData.UnobfuscatedStrings
                                                                                              .
                                                                                              Count),
                                                                          null);
                                        //If the strings are the same - point them to same field
                                        bool newField = true;
                                        foreach (
                                            AStringConstExp oldStringConstExp in sharedData.UnobfuscatedStrings.Keys)
                                        {
                                            if (stringConstExp.GetStringLiteral().Text ==
                                                oldStringConstExp.GetStringLiteral().Text)
                                            {
                                                field = sharedData.UnobfuscatedStrings[oldStringConstExp];
                                                newField = false;
                                                break;
                                            }
                                        }
                                        if (newField)
                                        {
                                            file.GetDecl().Insert(0, field);
                                            sharedData.ObfuscationFields.Add(field);
                                        }
                                        sharedData.UnobfuscatedStrings.Add(stringConstExp, field);

                                    }

                                }
                                foreach (AStringConstExp stringConstExp in checker.List)
                                {
                                    int line = -sharedData.ObfuscatedStrings.Count - 1;
                                    AFieldDecl field = new AFieldDecl(new APublicVisibilityModifier(), null,
                                                                      new TConst("const", line, 0),
                                                                      new ANamedType(new TIdentifier("string", line, 1),
                                                                                     null),
                                                                      new TIdentifier("Galaxy_pp_stringO" +
                                                                                      sharedData.ObfuscatedStrings.Count),
                                                                      null);
                                    //If the strings are the same - point them to same field
                                    bool newField = true;
                                    foreach (AStringConstExp oldStringConstExp in sharedData.ObfuscatedStrings.Keys)
                                    {
                                        if (stringConstExp.GetStringLiteral().Text ==
                                            oldStringConstExp.GetStringLiteral().Text)
                                        {
                                            field = sharedData.ObfuscatedStrings[oldStringConstExp];
                                            newField = false;
                                            break;
                                        }
                                    }
                                    if (newField)
                                    {
                                        AASourceFile file = (AASourceFile) sharedData.DeobfuscateMethod.Parent();
                                        file.GetDecl().Insert(file.GetDecl().IndexOf(sharedData.DeobfuscateMethod) + 1,
                                                              field);
                                        sharedData.ObfuscationFields.Add(field);
                                    }
                                    sharedData.ObfuscatedStrings.Add(stringConstExp, field);
                                }
                            }

                            sourceNode.SetName(new TIdentifier(filename));
                            root.GetSourceFiles().Add(start.GetPSourceFile());

                        }
                        catch (ParserException err)
                        {
                            String errMsg = err.Message;
                            //Remove [...]
                            errMsg = errMsg.Substring(errMsg.IndexOf(']') + 1).TrimStart();
                            errors.Add(new ErrorCollection.Error(err.Token, filename, errMsg));
                        }
                        reader.Close();
                    }
                }
               // Preprocessor.Parse(sources, errors);
                for (int i = 0; i < fileNames.Count; i++)
                {
                    string filename = fileNames[i];
                    StringReader reader = new StringReader(sources[i] ?? "");
                    Parser parser = new Parser(new Lexer(reader));
                    try
                    {
                        Start start = parser.Parse();
                        AASourceFile sourceNode = (AASourceFile)start.GetPSourceFile();
                        reader.Close();
                        reader.Dispose();
                        reader = new StringReader(sources[i] ?? "");
                        int lineCount = 0;
                        while (reader.ReadLine() != null)
                        {
                            lineCount++;
                        }
                        reader.Close();

                        sharedData.LineCounts[sourceNode] = lineCount;

                        //Extract encryption function
                         /*{
                             AASourceFile file = (AASourceFile) start.GetPSourceFile();
                             if (file.GetDecl().Count > 0 && file.GetDecl()[0] is AMethodDecl)
                             {
                                 AMethodDecl method = (AMethodDecl) file.GetDecl()[0];
                                 if (method.GetName().Text == "Galaxy_pp_Deobfuscate")
                                 {
                                     FileInfo dobfuscateFile = new FileInfo("Deobfuscator.LibraryData");
                                     IFormatter formatter = new BinaryFormatter();
                                     Stream stream = dobfuscateFile.Open(FileMode.Create);
                                     formatter.Serialize(stream, method);
                                     stream.Close();
                                 }
                             }
                         }*/

                        if (Options.Compiler.ObfuscateStrings)
                        {
                            HasStringConstExp checker = new HasStringConstExp();
                            start.Apply(checker);

                            if (!addedDeobfuscator /* && checker.HasStringConst*/)
                            {
                                FileInfo dobfuscateFile = new FileInfo("Deobfuscator.LibraryData");
                                IFormatter formatter = new BinaryFormatter();
                                Stream stream = dobfuscateFile.Open(FileMode.Open);
                                AASourceFile file = (AASourceFile)start.GetPSourceFile();

                                AMethodDecl method = (AMethodDecl)formatter.Deserialize(stream);
                                sharedData.DeobfuscateMethod = method;
                                method.GetName().Line = 0;

                                HasStringConstExp checker2 = new HasStringConstExp();
                                method.Apply(checker2);
                                file.GetDecl().Insert(0, method);
                                stream.Close();

                                addedDeobfuscator = true;

                                foreach (AStringConstExp stringConstExp in checker2.List)
                                {
                                    int line = -sharedData.UnobfuscatedStrings.Count - 1;
                                    AFieldDecl field = new AFieldDecl(new APublicVisibilityModifier(), null,
                                                                      new TConst("const", line, 0),
                                                                      new ANamedType(
                                                                          new TIdentifier("string", line, 1),
                                                                          null),
                                                                      new TIdentifier("Galaxy_pp_stringU" +
                                                                                      sharedData.UnobfuscatedStrings
                                                                                          .
                                                                                          Count),
                                                                      null);
                                    //If the strings are the same - point them to same field
                                    bool newField = true;
                                    foreach (
                                        AStringConstExp oldStringConstExp in sharedData.UnobfuscatedStrings.Keys)
                                    {
                                        if (stringConstExp.GetStringLiteral().Text ==
                                            oldStringConstExp.GetStringLiteral().Text)
                                        {
                                            field = sharedData.UnobfuscatedStrings[oldStringConstExp];
                                            newField = false;
                                            break;
                                        }
                                    }
                                    if (newField)
                                    {
                                        file.GetDecl().Insert(0, field);
                                        sharedData.ObfuscationFields.Add(field);
                                    }
                                    sharedData.UnobfuscatedStrings.Add(stringConstExp, field);

                                }

                            }
                            foreach (AStringConstExp stringConstExp in checker.List)
                            {
                                int line = -sharedData.ObfuscatedStrings.Count - 1;
                                AFieldDecl field = new AFieldDecl(new APublicVisibilityModifier(), null,
                                                                  new TConst("const", line, 0),
                                                                  new ANamedType(new TIdentifier("string", line, 1),
                                                                                 null),
                                                                  new TIdentifier("Galaxy_pp_stringO" +
                                                                                  sharedData.ObfuscatedStrings.Count),
                                                                  null);
                                //If the strings are the same - point them to same field
                                bool newField = true;
                                foreach (AStringConstExp oldStringConstExp in sharedData.ObfuscatedStrings.Keys)
                                {
                                    if (stringConstExp.GetStringLiteral().Text ==
                                        oldStringConstExp.GetStringLiteral().Text)
                                    {
                                        field = sharedData.ObfuscatedStrings[oldStringConstExp];
                                        newField = false;
                                        break;
                                    }
                                }
                                if (newField)
                                {
                                    AASourceFile file = (AASourceFile)sharedData.DeobfuscateMethod.Parent();
                                    file.GetDecl().Insert(file.GetDecl().IndexOf(sharedData.DeobfuscateMethod) + 1,
                                                          field);
                                    sharedData.ObfuscationFields.Add(field);
                                }
                                sharedData.ObfuscatedStrings.Add(stringConstExp, field);
                            }
                        }

                        sourceNode.SetName(new TIdentifier(filename));
                        root.GetSourceFiles().Add(start.GetPSourceFile());

                    }
                    catch (ParserException err)
                    {
                        String errMsg = err.Message;
                        //Remove [...]
                        errMsg = errMsg.Substring(errMsg.IndexOf(']') + 1).TrimStart();
                        errors.Add(new ErrorCollection.Error(err.Token, filename, errMsg));
                    }
                    reader.Close();
                }

                //Load libraries
                foreach (Library lib in ProjectProperties.CurrentProjectPropperties.Libraries)
                {
                    foreach (KeyValuePair<Library.File, string> sourceFile in lib.GetFiles())
                    {
                        StringReader sReader = new StringReader(sourceFile.Key.Text);
                        {
                            Parser parser = new Parser(new Lexer(sReader));

                            try
                            {
                                Start start = parser.Parse();
                                AASourceFile sourceNode = (AASourceFile) start.GetPSourceFile();
                                sReader.Close();
                                sReader.Dispose();
                                sReader = new StringReader(sourceFile.Key.Text);
                                int lineCount = 0;
                                while (sReader.ReadLine() != null)
                                {
                                    lineCount++;
                                }
                                sReader.Close();
                                sReader.Dispose();
                                sharedData.LineCounts[sourceNode] = lineCount;

                                if (Options.Compiler.ObfuscateStrings)
                                {
                                    HasStringConstExp checker = new HasStringConstExp();
                                    start.Apply(checker);

                                    if (!addedDeobfuscator /* && checker.HasStringConst*/)
                                    {
                                        FileInfo dobfuscateFile = new FileInfo("Deobfuscator.LibraryData");
                                        IFormatter formatter = new BinaryFormatter();
                                        Stream stream = dobfuscateFile.Open(FileMode.Open);
                                        AASourceFile file = (AASourceFile) start.GetPSourceFile();

                                        AMethodDecl method = (AMethodDecl) formatter.Deserialize(stream);
                                        sharedData.DeobfuscateMethod = method;
                                        method.GetName().Line = 0;

                                        HasStringConstExp checker2 = new HasStringConstExp();
                                        method.Apply(checker2);
                                        file.GetDecl().Insert(0, method);
                                        stream.Close();

                                        addedDeobfuscator = true;

                                        foreach (AStringConstExp stringConstExp in checker2.List)
                                        {
                                            int line = -sharedData.UnobfuscatedStrings.Count - 1;
                                            AFieldDecl field = new AFieldDecl(new APublicVisibilityModifier(), null,
                                                                              new TConst("const", line, 0),
                                                                              new ANamedType(
                                                                                  new TIdentifier("string", line, 1),
                                                                                  null),
                                                                              new TIdentifier("Galaxy_pp_stringU" +
                                                                                              sharedData.
                                                                                                  UnobfuscatedStrings
                                                                                                  .
                                                                                                  Count),
                                                                              null);
                                            //If the strings are the same - point them to same field
                                            bool newField = true;
                                            foreach (
                                                AStringConstExp oldStringConstExp in sharedData.UnobfuscatedStrings.Keys
                                                )
                                            {
                                                if (stringConstExp.GetStringLiteral().Text ==
                                                    oldStringConstExp.GetStringLiteral().Text)
                                                {
                                                    field = sharedData.UnobfuscatedStrings[oldStringConstExp];
                                                    newField = false;
                                                    break;
                                                }
                                            }
                                            if (newField)
                                            {
                                                file.GetDecl().Insert(0, field);
                                                sharedData.ObfuscationFields.Add(field);
                                            }
                                            sharedData.UnobfuscatedStrings.Add(stringConstExp, field);

                                        }

                                    }
                                    foreach (AStringConstExp stringConstExp in checker.List)
                                    {
                                        int line = -sharedData.ObfuscatedStrings.Count - 1;
                                        AFieldDecl field = new AFieldDecl(new APublicVisibilityModifier(), null,
                                                                          new TConst("const", line, 0),
                                                                          new ANamedType(
                                                                              new TIdentifier("string", line, 1),
                                                                              null),
                                                                          new TIdentifier("Galaxy_pp_stringO" +
                                                                                          sharedData.ObfuscatedStrings.
                                                                                              Count),
                                                                          null);
                                        //If the strings are the same - point them to same field
                                        bool newField = true;
                                        foreach (AStringConstExp oldStringConstExp in sharedData.ObfuscatedStrings.Keys)
                                        {
                                            if (stringConstExp.GetStringLiteral().Text ==
                                                oldStringConstExp.GetStringLiteral().Text)
                                            {
                                                field = sharedData.ObfuscatedStrings[oldStringConstExp];
                                                newField = false;
                                                break;
                                            }
                                        }
                                        if (newField)
                                        {
                                            AASourceFile file = (AASourceFile) sharedData.DeobfuscateMethod.Parent();
                                            file.GetDecl().Insert(
                                                file.GetDecl().IndexOf(sharedData.DeobfuscateMethod) + 1,
                                                field);
                                            sharedData.ObfuscationFields.Add(field);
                                        }
                                        sharedData.ObfuscatedStrings.Add(stringConstExp, field);
                                    }
                                }

                                sourceNode.SetName(new TIdentifier(sourceFile.Value));
                                root.GetSourceFiles().Add(start.GetPSourceFile());

                            }
                            catch (ParserException err)
                            {
                                String errMsg = err.Message;
                                //Remove [...]
                                errMsg = errMsg.Substring(errMsg.IndexOf(']') + 1).TrimStart();
                                errors.Add(new ErrorCollection.Error(err.Token, sourceFile.Value, errMsg));
                            }
                        }
                    }
                }

                string rootFileName = "";
                DirectoryInfo outputDir = ProjectDir.CreateSubdirectory("output");
                try
                {
                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text4"));
                    sharedData.Libraries = libraryData;
                    Weeder.Parse(root, errors, sharedData);

                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text5"));
                    if (!errors.HasErrors) EnviromentBuilding.Parse(root, errors, sharedData);

                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text6"));
                    if (!errors.HasErrors) EnviromentChecking.Parse(root, errors, sharedData);

                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text7"));
                    if (!errors.HasErrors) root.Apply(new LinkNamedTypes(errors, sharedData));

                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text8"));
                    if (!errors.HasErrors) root.Apply(new FixGenerics(errors, sharedData));

                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text9"));
                    if (!errors.HasErrors) root.Apply(new Enheritance(sharedData, errors));

                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text10"));
                    if (!errors.HasErrors) TypeLinking.Parse(root, errors, sharedData);

                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text11"));
                    if (!errors.HasErrors) TypeChecking.Parse(root, errors, sharedData);
                    if (!errors.HasErrors) root.Apply(new MakeEnrichmentLinks(sharedData, errors));
                    if (!errors.HasErrors) root.Apply(new SetArrayIndexes(sharedData, errors));
                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text12"));
                    if (!errors.HasErrors) FinalTransformations.Parse(root, errors, sharedData, out rootFileName);
                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text13"));
                    if (!errors.HasErrors) CodeGeneration.Parse(root, errors, sharedData, outputDir);
                    if (!errors.HasErrors) GenerateBankPreloadFile.Generate(sharedData, outputDir);
                }
                catch (ParserException err)
                {

                }

                Compiling = false;

                if (!errors.HasErrors)
                {
                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text14"));
                    ProjectProperties.CurrentProjectPropperties.RootFileName = rootFileName;
                    ProjectProperties.CurrentProjectPropperties.CompileStatus =
                        ProjectProperties.ECompileStatus.SuccessfullyCompiled;
                    if (CompilationSuccessfull != null)
                        CompilationSuccessfull();
                }
                else
                {
                    if (!compilingFromCommandLine)
                        form.SetStatusText(LocRM.GetString("GC_Text15"));
                    if (CompilationFailed != null)
                        CompilationFailed();
                }

            }
            #if DEBUG
            finally
            {

            }
            #else
            catch (Exception error)
            {
                Compiling = false;
                //Program.ErrorHandeler(this, new ThreadExceptionEventArgs(error));
                new ExceptionForm(error, true).ShowDialog();
                form.SetStatusText("Critical compile error");
                if (CompilationFailed != null)
                    CompilationFailed();
            }
            #endif
        }
        public void CompileLibrary(DirectoryInfo libraryDir, StreamWriter writer)
        {
            AAProgram root = new AAProgram();
            ErrorCollection errors = new ErrorCollection();

            foreach (FileInfo file in GetSourceFiles(libraryDir))
            {
                //Replace keywords
                StreamReader reader = file.OpenText();
                StringBuilder text = new StringBuilder("");
                string[] keywords = new[] {"ref", "out", "InvokeSync", "InvokeAsync",
                                                  "switch", "case", "default", "new", "delete", "this","delegate", "value", "base",
                "inline", "namespace", "using",
                                                                           "Trigger", "Initializer",
                                                                           "events", "conditions", "actions", "class",
                                                                           "typedef", "get", "set", "enrich",
                                                                           "public", "private", "protected",
                "LibraryName", "LibraryVersion", "SupportedVersions", "RequiredLibraries", "global"};

                int i;
                StringBuilder currentIdentifier = new StringBuilder("");
                while ((i = reader.Read()) != -1)
                {
                    if (Util.IsIdentifierLetter((char)i))
                    {
                        currentIdentifier.Append((char)i);
                    }
                    else
                    {
                        if (currentIdentifier.Length > 0)
                        {
                            string identifier = currentIdentifier.ToString();
                            currentIdentifier.Clear();
                            if (keywords.Contains(identifier))
                            {
                                identifier = "_" + identifier;
                            }
                            text.Append(identifier);
                        }
                        text.Append((char) i);
                    }
                }

                Parser parser = new Parser(new Lexer(new StringReader(text.ToString())));
                try
                {
                    Start start = parser.Parse();
                    AASourceFile srcFile = (AASourceFile) start.GetPSourceFile();
                    srcFile.SetName(new TIdentifier(file.FullName.Substring(libraryDir.FullName.Length + 1)));
                    root.GetSourceFiles().Add(srcFile);
                }
                catch (ParserException err)
                {
                    errors.Add(new ErrorCollection.Error(err.Token, file.Name, err.Message, false));
                }
                reader.Close();
            }

            try
            {
                Weeder.Parse(root, errors, new SharedData());
                LibraryData lib = new LibraryData(root, writer);
                FileInfo precompFile = new FileInfo(libraryDir.FullName + "\\Precompiled.LibraryData");
                IFormatter formatter = new BinaryFormatter();
                Stream stream = precompFile.Open(FileMode.Create);
                formatter.Serialize(stream, lib);
                stream.Close();
            }
            catch (Exception err)
            {

            }
            if (errors.HasErrors)
                MessageBox.Show("Errors in libray " + libraryDir.Name);
        }
 public override void CaseAAProgram(AAProgram node)
 {
     GetOldParameterTypes getOldParameterTypes = new GetOldParameterTypes();
     node.Apply(getOldParameterTypes);
     oldParameterTypes = getOldParameterTypes.OldParameterTypes;
     oldReturnTypes = getOldParameterTypes.OldReturnTypes;
     foreach (AASourceFile sourceFile in node.GetSourceFiles())
     {
         foreach (PDecl decl in sourceFile.GetDecl())
         {
             if (decl is AMethodDecl)
             {
                 GetUsedParameters getUses = new GetUsedParameters(data);
                 decl.Apply(getUses);
                 UsedParameters[(AMethodDecl) decl] = getUses.UsedParameters;
             }
         }
     }
      	            base.CaseAAProgram(node);
     while (mover.NewStatements.Count > 0)
     {
         List<PStm> stms = mover.NewStatements;
         mover = new MoveMethodDeclsOut("bulkCopyVar", data);
         foreach (PStm stm in stms)
         {
             stm.Apply(this);
         }
     }
 }
            public override void CaseAAProgram(AAProgram node)
            {
                //Add all fields to exposed
                foreach (AASourceFile sourceFile in node.GetSourceFiles())
                {
                    foreach (PDecl decl in sourceFile.GetDecl())
                    {
                        if (decl is AFieldDecl)
                        {
                            AFieldDecl aDecl = (AFieldDecl) decl;
                            //foreach (List<PointerType> variable in GetAllPointerTypes(aDecl, aDecl.GetType()))
                            {

                            }
                        }
                    }
                }
                base.CaseAAProgram(node);
            }
        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"));
        }