コード例 #1
0
ファイル: MoreTests.cs プロジェクト: debreuil/CSharpParser
        static void testCode(string code)
        {
            Lexer lex = new Lexer(new StreamReader(new MemoryStream(
                                                       Encoding.UTF8.GetBytes(code))));
            TokenCollection     tc = lex.Lex();
            Parser              p  = new Parser(string.Empty);
            CompilationUnitNode n  = p.Parse(tc, lex.StringLiterals);

            StringBuilder sb = new StringBuilder();

            n.ToSource(sb);
            Console.WriteLine(sb.ToString());
        }
コード例 #2
0
ファイル: cmc.cs プロジェクト: andyhebear/Csharp-Parser
        private static void ParseFile(string fileName, List <Parser.Error> errors, WhatToDo whatToDo, bool useMono)
        {
            bool   createExe          = true;
            String compilerOptionsStr = "";
            String basePath           = Path.GetDirectoryName(fileName) + Path.DirectorySeparatorChar;

            if (basePath.Length == 1)
            {
                basePath = "";
            }
            String outAssembly = Path.GetFileNameWithoutExtension(fileName) + ".exe";

            List <String> files = new List <string>();

            files.Add(fileName);

            String[] compilerOptions, dependencies;
            if (!GetExtraOptions(fileName, out compilerOptions, out dependencies))
            {
                Console.WriteLine("GetExtraOptions failed!");
            }
            if (compilerOptions != null)
            {
                foreach (String compOpt in compilerOptions)
                {
                    if (compOpt.Length == 0)
                    {
                        continue;
                    }
                    if (compOpt[0] != '-')
                    {
                        files.Add(basePath + compOpt);
                    }
                    else if (compOpt == "-t:library")
                    {
                        createExe   = false;
                        outAssembly = Path.GetFileNameWithoutExtension(fileName) + ".dll";
                    }
                    else if (compOpt == "-t:module")
                    {
                        createExe           = false;
                        compilerOptionsStr += "/t:module ";
                        outAssembly         = Path.GetFileNameWithoutExtension(fileName) + ".netmodule";
                    }
                    else if (compOpt == "-unsafe")
                    {
                        compilerOptionsStr += "/unsafe ";
                    }
                    else if (compOpt.StartsWith("-r:"))
                    {
                        compilerOptionsStr += "/" + compOpt.Substring(1) + " ";
                    }
                    else
                    {
                        int colonPos = compOpt.IndexOf(':');
                        if (colonPos == -1)
                        {
                            continue;
                        }

                        String optionName = compOpt.Substring(1, colonPos - 1);
                        if (optionName != "res" && optionName != "linkresource" && optionName != "addmodule" &&
                            optionName != "keyfile")
                        {
                            continue;
                        }

                        String optFileName;
                        String rest     = compOpt.Substring(optionName.Length + 2);
                        int    commaPos = rest.IndexOf(',');
                        if (commaPos == -1)
                        {
                            optFileName = rest;
                            rest        = "";
                        }
                        else
                        {
                            optFileName = rest.Substring(0, commaPos);
                            rest        = rest.Substring(commaPos);
                        }
                        compilerOptionsStr += "/" + optionName + ":\"" + basePath + optFileName + "\"" + rest + " ";
                    }
                }
            }

            String[] unparsedFiles = new String[files.Count];
            for (int i = 0; i < files.Count; i++)
            {
                CompilationUnitNode cu = ParseUnit(files[i], errors);
                if (cu == null)
                {
                    return;
                }

                StringBuilder sb = new StringBuilder();
                cu.ToSource(sb);
                unparsedFiles[i] = sb.ToString();
            }

            //Console.WriteLine(toks + "\n\n");
            //Console.WriteLine(p.CurrentState + "\n\n");

            if (whatToDo == WhatToDo.PrintToScreen)
            {
                Console.WriteLine();
                foreach (String unparsedFile in unparsedFiles)
                {
                    Console.WriteLine(unparsedFile);
                }
            }
            else if (whatToDo == WhatToDo.Compile)
            {
                CSharpCodeProvider compiler   = new CSharpCodeProvider();
                CompilerParameters compParams = new CompilerParameters();
                compParams.ReferencedAssemblies.Add("System.dll");
                compParams.ReferencedAssemblies.Add("System.XML.dll");
                compParams.ReferencedAssemblies.Add("System.Data.dll");
                if (createExe)
                {
                    compParams.GenerateExecutable = true;
                }

                if (basePath.Length > 0)
                {
                    compilerOptionsStr += "/lib:\"" + basePath.Substring(0, basePath.Length - 1) + "\" ";
                }
                compParams.OutputAssembly  = basePath + outAssembly;
                compParams.CompilerOptions = compilerOptionsStr;
                CompilerResults res = null;
                try
                {
                    res = compiler.CompileAssemblyFromSource(compParams, unparsedFiles);
                }
                catch (BadImageFormatException ex)
                {
                    if (compilerOptionsStr.Contains("/t:module"))
                    {
                        AddError(errors, fileName, "\nMono tried to load a module as an assembly\n"
                                 + "(see https://bugzilla.novell.com/show_bug.cgi?id=353536)");
                    }
                    else
                    {
                        AddError(errors, fileName, ex.Message);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    AddError(errors, fileName, ex.Message);
                    return;
                }
                if (res.Errors.HasErrors)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("\nIllegal C# source code generated: ");
                    sb.Append(res.Errors.Count.ToString());
                    sb.Append(" Errors:\n");
                    foreach (CompilerError error in res.Errors)
                    {
                        sb.Append("Line: ");
                        sb.Append(error.Line.ToString());
                        sb.Append(" - ");
                        sb.Append(error.ErrorText);
                        sb.Append('\n');
                    }
                    AddError(errors, fileName, sb.ToString());
                    return;
                }
                Console.Write(". Compiled.");

                if (compParams.GenerateExecutable)
                {
                    Console.Write(" Testing");
                    ProcessStartInfo psi;
                    if (useMono)
                    {
                        psi = new ProcessStartInfo("mono", outAssembly);
                    }
                    else
                    {
                        psi = new ProcessStartInfo(basePath + outAssembly);
                    }

                    psi.CreateNoWindow   = true;
                    psi.UseShellExecute  = false;
                    psi.WorkingDirectory = basePath;
                    using (Process proc = Process.Start(psi))
                    {
                        for (int i = 0; i < 5 && !proc.HasExited; i++)
                        {
                            Console.Write('.');
                            proc.WaitForExit(1000);
                        }
                        if (!proc.HasExited)
                        {
                            proc.Kill();
                            AddError(errors, fileName, "Test seems to hang!");
                        }
                        else if (proc.ExitCode != 0)
                        {
                            AddError(errors, fileName, "Test failed! Exit code = " + proc.ExitCode);
                        }
                        else
                        {
                            Console.WriteLine(" Succeeded!");
                        }
                    }
                }
            }
            else if (whatToDo == WhatToDo.WriteToFiles)
            {
                for (int i = 0; i < files.Count; i++)
                {
                    String path = files[i].Substring(9);
                    Console.WriteLine(". Writing " + path);
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    using (StreamWriter writer = new StreamWriter(path))
                        writer.WriteLine(unparsedFiles[i]);
                }
            }

            /*            TestVisitorVisitor visitor = new TestVisitorVisitor();
             *
             *          // if you forget to override the method 'public override object AcceptVisitor(AbstractVisitor visitor, object data)'
             *          // it will throw an exception
             *          cu.AcceptVisitor(visitor, null);*/
        }