예제 #1
0
파일: Emit.cs 프로젝트: obiwanjacobi/Zsharp
        public static EmitCode Create(string code, IAstModuleLoader moduleLoader = null)
        {
            var compiler = new Compiler(moduleLoader ?? new ModuleLoader());
            var errors   = compiler.ParseAst("UnitTests", AssemblyName, code);

            foreach (var err in errors)
            {
                Console.WriteLine(err);
            }
            errors.Should().BeEmpty();

            var module = compiler.Context.Modules.Modules.First();
            var emit   = new EmitCode(AssemblyName);

            emit.Visit(module);
            return(emit);
        }
예제 #2
0
        public string Compile(string filePath, string configuration, string outputAssemblyPath, string[] references)
        {
            var console = new StringBuilder();

            // parse code and build AST
            var code       = File.ReadAllText(filePath);
            var moduleName = Path.GetFileNameWithoutExtension(filePath);
            var messages   = ParseAst(filePath, moduleName, code);

            foreach (var message in messages)
            {
                console.AppendLine(message.ToString());
            }

            if (messages.HasErrors())
            {
                return(console.ToString());
            }

            var assemblyName = Path.GetFileNameWithoutExtension(outputAssemblyPath);
            var outputDir    = Path.GetDirectoryName(outputAssemblyPath) ?? ".\\";
            var module       = Context.Modules.Modules.First();
            var emit         = new EmitCode(assemblyName);

            emit.Visit(module);

            var csFile     = $"{assemblyName}.cs";
            var csFilePath = String.IsNullOrEmpty(outputDir) ? csFile : Path.Combine(outputDir, csFile);

            emit.SaveAs(csFilePath);

            var csCompiler = new CsCompiler()
            {
                Debug       = configuration == "Debug",
                ProjectPath = outputDir,
            };

            foreach (var reference in references)
            {
                csCompiler.Project.AddReference(reference);
            }

            csCompiler.Project.Executable = true;
            var buildOutput = csCompiler.Compile(assemblyName);

            if (buildOutput.Contains("Build FAILED") ||
                buildOutput.Contains("error"))
            {
                console.AppendLine();
                console.AppendLine($"Error: Generating Assembly {assemblyName} failed.");
                console.AppendLine();
                console.AppendLine(buildOutput);
            }
            else
            {
                console.AppendLine();
                console.AppendLine($"Compiled Z# assembly: {csCompiler.Project.TargetPath}");
            }

            return(console.ToString());
        }