CodeCompilerResult CompileFileInternal(
            CodeCompilerArguments arguments,
            TextWriter log,
            CancellationToken token)
        {
            CSharpCommandLineArguments args = null;

            if (arguments.AdditionalArguments != null)
            {
                var splitArgs = CommandLineParser.SplitCommandLineIntoArguments(arguments.AdditionalArguments, false);
                if (splitArgs.Any())
                {
                    args = CSharpCommandLineParser.Default.Parse(splitArgs, arguments.TempDirectory, null, null);
                }
            }

            var references = new List <MetadataReference> ();

            foreach (var assemblyReference in AssemblyResolver.GetResolvedReferences(runtime, arguments.AssemblyReferences))
            {
                references.Add(MetadataReference.CreateFromFile(assemblyReference));
            }

            var parseOptions = args?.ParseOptions ?? new CSharpParseOptions();

            if (arguments.LangVersion != null)
            {
                if (LanguageVersionFacts.TryParse(arguments.LangVersion, out var langVersion))
                {
                    parseOptions = parseOptions.WithLanguageVersion(langVersion);
                }
                else
                {
                    throw new System.Exception($"Unknown value '{arguments.LangVersion}' for langversion");
                }
            }
            else
            {
                // need to update this when updating referenced roslyn binaries
                CSharpLangVersionHelper.GetBestSupportedLangVersion(runtime, CSharpLangVersion.v9_0);
            }

            var syntaxTrees = new List <SyntaxTree> ();

            foreach (var sourceFile in arguments.SourceFiles)
            {
                using var stream = File.OpenRead(sourceFile);
                var        sourceText = SourceText.From(stream, Encoding.UTF8, canBeEmbedded: true);
                SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceText, parseOptions, cancellationToken: token, path: sourceFile);
                syntaxTrees.Add(syntaxTree);
            }

            var compilationOptions = (args?.CompilationOptions ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                                     .WithOutputKind(OutputKind.DynamicallyLinkedLibrary);

            var compilation = CSharpCompilation.Create(
                "GeneratedTextTransformation",
                syntaxTrees,
                references,
                compilationOptions
                );


            EmitOptions emitOptions = args?.EmitOptions ?? new EmitOptions();

            if (arguments.Debug)
            {
                var embeddedTexts = syntaxTrees.Select(st => EmbeddedText.FromSource(st.FilePath, st.GetText())).ToList();
                emitOptions = emitOptions.WithDebugInformationFormat(DebugInformationFormat.Embedded);
            }

            using var fs = File.OpenWrite(arguments.OutputPath);
            EmitResult result = compilation.Emit(fs, options: emitOptions, cancellationToken: token);

            if (result.Success)
            {
                return(new CodeCompilerResult {
                    Output = new List <string> (),
                    Success = true,
                    Errors = new List <CodeCompilerError> ()
                });
            }

            var failures = result.Diagnostics.Where(x => x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error);
            var errors   = failures.Select(x => {
                var location          = x.Location.GetMappedLineSpan();
                var startLinePosition = location.StartLinePosition;
                var endLinePosition   = location.EndLinePosition;
                return(new CodeCompilerError {
                    Message = x.GetMessage(),
                    Column = startLinePosition.Character,
                    Line = startLinePosition.Line,
                    EndLine = endLinePosition.Line,
                    EndColumn = endLinePosition.Character,
                    IsError = x.Severity == DiagnosticSeverity.Error,
                    Origin = location.Path
                });
            }).ToList();

            return(new CodeCompilerResult {
                Success = false,
                Output = new List <string> (),
                Errors = errors
            });
        }
 public override Task <CodeCompilerResult> CompileFile(
     CodeCompilerArguments arguments,
     TextWriter log,
     CancellationToken token)
 => Task.FromResult(CompileFileInternal(arguments, log, token));
Exemple #3
0
        public override async Task <CodeCompilerResult> CompileFile(
            CodeCompilerArguments arguments,
            TextWriter log,
            CancellationToken token)
        {
            var references = new List <MetadataReference> ();

            foreach (var assemblyReference in arguments.AssemblyReferences)
            {
                var argumentsAssemblyReference = assemblyReference;
                var path = AssemblyResolver.Resolve(_runtime, argumentsAssemblyReference);
                references.Add(MetadataReference.CreateFromFile(path));
            }

            references.Add(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(typeof(string).Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(typeof(Console).Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(typeof(IntPtr).Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(typeof(AssemblyTargetedPatchBandAttribute).Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location));

            var source     = File.ReadAllText(arguments.SourceFiles.Single());
            var syntaxTree = CSharpSyntaxTree.ParseText(source);

            var compilation = CSharpCompilation.Create(
                "GeneratedTextTransformation",
                new List <SyntaxTree> {
                syntaxTree
            },
                references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                );

            var pdbFilePath = Path.ChangeExtension(arguments.OutputPath, "pdb");

            EmitResult result;

            using (var fs = File.OpenWrite(arguments.OutputPath)) {
                using (var symbolsStream = File.OpenWrite(pdbFilePath)) {
                    var emitOptions = new EmitOptions(
                        debugInformationFormat: DebugInformationFormat.PortablePdb,
                        pdbFilePath: pdbFilePath);


                    var embeddedTexts = new List <EmbeddedText> {
                        EmbeddedText.FromSource(
                            arguments.SourceFiles.Single(),
                            SourceText.From(source, Encoding.UTF8)),
                    };

                    result = compilation.Emit(
                        fs,
                        symbolsStream,
                        embeddedTexts: embeddedTexts,
                        options: emitOptions);
                }
            }

            if (result.Success)
            {
                return(new CodeCompilerResult {
                    Output = new List <string> (),
                    Success = true,
                    Errors = new List <CodeCompilerError> ()
                });
            }

            var failures = result.Diagnostics.Where(x => x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error);

            return(new CodeCompilerResult {
                Success = false,
                Output = new List <string> (),
                Errors = failures.Select(
                    x => new CodeCompilerError {
                    Message = x.GetMessage(),
                    Column = x.Location.GetMappedLineSpan().StartLinePosition.Character,
                    Line = x.Location.GetMappedLineSpan().StartLinePosition.Line,
                    EndLine = x.Location.GetMappedLineSpan().EndLinePosition.Line,
                    EndColumn = x.Location.GetMappedLineSpan().EndLinePosition.Character,
                    IsError = x.IsWarningAsError,
                    Origin = x.Location.GetMappedLineSpan().Path
                }).ToList(),
            });
        }
Exemple #4
0
        public override async Task <CodeCompilerResult> CompileFile(
            CodeCompilerArguments arguments,
            TextWriter log,
            CancellationToken token)
        {
            var references = new List <MetadataReference> ();

            foreach (var assemblyReference in AssemblyResolver.GetResolvedReferences(runtime, arguments.AssemblyReferences))
            {
                references.Add(MetadataReference.CreateFromFile(assemblyReference));
            }

            var syntaxTrees = new List <SyntaxTree> ();

            foreach (var sourceFile in arguments.SourceFiles)
            {
                using var stream = File.OpenRead(sourceFile);
                var sourceText = SourceText.From(stream, Encoding.UTF8);
                syntaxTrees.Add(CSharpSyntaxTree.ParseText(sourceText));
            }

            var compilation = CSharpCompilation.Create(
                "GeneratedTextTransformation",
                syntaxTrees,
                references,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                );

            EmitOptions emitOptions = null;

            if (arguments.Debug)
            {
                var embeddedTexts = syntaxTrees.Select(st => EmbeddedText.FromSource(st.FilePath, st.GetText())).ToList();
                emitOptions = new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded);
            }

            using var fs = File.OpenWrite(arguments.OutputPath);
            EmitResult result = compilation.Emit(fs, options: emitOptions);

            if (result.Success)
            {
                return(new CodeCompilerResult {
                    Output = new List <string> (),
                    Success = true,
                    Errors = new List <CodeCompilerError> ()
                });
            }

            var failures = result.Diagnostics.Where(x => x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error);
            var errors   = failures.Select(x => {
                var location          = x.Location.GetMappedLineSpan();
                var startLinePosition = location.StartLinePosition;
                var endLinePosition   = location.EndLinePosition;
                return(new CodeCompilerError {
                    Message = x.GetMessage(),
                    Column = startLinePosition.Character,
                    Line = startLinePosition.Line,
                    EndLine = endLinePosition.Line,
                    EndColumn = endLinePosition.Character,
                    IsError = x.Severity == DiagnosticSeverity.Error,
                    Origin = location.Path
                });
            }).ToList();

            return(new CodeCompilerResult {
                Success = false,
                Output = new List <string> (),
                Errors = errors
            });
        }
        public override async Task <CodeCompilerResult> CompileFile(
            CodeCompilerArguments arguments,
            TextWriter log,
            CancellationToken token)
        {
            var references = new List <MetadataReference> ();

            foreach (var assemblyReference in AssemblyResolver.GetResolvedReferences(runtime, arguments.AssemblyReferences))
            {
                references.Add(MetadataReference.CreateFromFile(assemblyReference));
                try {
                    Assembly.LoadFrom(assemblyReference);
                } catch (Exception) { }
            }

            var syntaxTrees = new List <SyntaxTree> ();

            foreach (var sourceFile in arguments.SourceFiles)
            {
                using var stream = File.OpenRead(sourceFile);
                var sourceText = SourceText.From(stream, Encoding.UTF8, canBeEmbedded: true);
                syntaxTrees.Add(CSharpSyntaxTree.ParseText(sourceText, path: sourceFile));
            }

            var compilationoptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            if (arguments.Debug)
            {
                compilationoptions = compilationoptions.WithOptimizationLevel(OptimizationLevel.Debug);
            }

            var compilation = CSharpCompilation.Create(
                "GeneratedTextTransformation",
                syntaxTrees,
                references,
                compilationoptions
                );

            EmitOptions         emitOptions   = null;
            List <EmbeddedText> embeddedTexts = null;
            string pdbPath = null;

            if (arguments.Debug)
            {
                pdbPath       = Path.ChangeExtension(arguments.OutputPath, "pdb");
                embeddedTexts = syntaxTrees.Where(st => !string.IsNullOrEmpty(st.FilePath)).Select(st => EmbeddedText.FromSource(st.FilePath, st.GetText())).ToList();
                emitOptions   = new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb, pdbFilePath: pdbPath);
            }

            EmitResult result;

            using var fs = File.OpenWrite(arguments.OutputPath);
            {
                if (pdbPath != null)
                {
                    using var pdb = File.OpenWrite(pdbPath);
                    result        = compilation.Emit(fs, pdbStream: pdb, options: emitOptions, embeddedTexts: embeddedTexts);
                }
                else
                {
                    result = compilation.Emit(fs, options: emitOptions, embeddedTexts: embeddedTexts);
                }
            }

            if (result.Success)
            {
                return(new CodeCompilerResult {
                    Output = new List <string> (),
                    Success = true,
                    Errors = new List <CodeCompilerError> ()
                });
            }

            var failures = result.Diagnostics.Where(x => x.IsWarningAsError || x.Severity == DiagnosticSeverity.Error);
            var errors   = failures.Select(x => {
                var location          = x.Location.GetMappedLineSpan();
                var startLinePosition = location.StartLinePosition;
                var endLinePosition   = location.EndLinePosition;
                return(new CodeCompilerError {
                    Message = x.GetMessage(),
                    Column = startLinePosition.Character,
                    Line = startLinePosition.Line,
                    EndLine = endLinePosition.Line,
                    EndColumn = endLinePosition.Character,
                    IsError = x.Severity == DiagnosticSeverity.Error,
                    Origin = location.Path
                });
            }).ToList();

            return(new CodeCompilerResult {
                Success = false,
                Output = new List <string> (),
                Errors = errors
            });
        }