public EmitResult Emit() { var diagnostics = ImmutableArray.CreateBuilder <Diagnostic>(); var validateOk = ValidateCompilation(diagnostics); if (!validateOk) { return(new EmitResult(false, diagnostics.ToImmutable())); } if (_bootstrapper is null) { throw new ArgumentNullException(nameof(_bootstrapper)); } var bootstrapper = _bootstrapper.GetBootstrapper(); var configuration = ParseConfiguration(); var syntaxTrees = TransformSyntaxTrees(diagnostics, configuration) .Append(bootstrapper); if (_csharpSyntaxTrees?.Length > 0) { syntaxTrees = syntaxTrees.Concat(_csharpSyntaxTrees); } if (diagnostics.Where(d => d.DiagnosticType == DiagnosticType.Error).Any()) { return(new EmitResult(false, diagnostics.ToImmutable())); } var dllFileName = $"{_projectName}.dll"; var compilation = CSharpCompilation .Create(_projectName) .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication) .WithOptimizationLevel(configuration) .WithPlatform(Platform.AnyCpu)) .WithReferences(BuildReferences()) .AddSyntaxTrees(syntaxTrees); var result = EmitAssembly(compilation, dllFileName, configuration); foreach (var diagnostic in result.Diagnostics) { diagnostics.Add(Diagnostic.FromCSharpDiagnostic(diagnostic)); } return(new EmitResult(result.Success, diagnostics.ToImmutable(), _outputFolder, dllFileName, syntaxTrees.ToImmutableArray())); }
private bool ValidateCompilation(ImmutableArray <Diagnostic> .Builder diagnostics) { var error = false; if (!Directory.Exists(_outputFolder)) { diagnostics.Add(Diagnostic.Error(new TextLocation(), "Invalid output directory.")); error = true; } if (string.IsNullOrEmpty(_projectName)) { diagnostics.Add(Diagnostic.Error(new TextLocation(), "Invalid assembly name.")); error = true; } if (_syntaxTrees is null || _syntaxTrees.Length == 0) { diagnostics.Add(Diagnostic.Error(new TextLocation(), "At least one syntax tree is required.")); error = true; } if (_targetFrameworks is null || _targetFrameworks.Length == 0) { diagnostics.Add(Diagnostic.Error(new TextLocation(), "At least one target framework is required.")); error = true; } if (_bootstrapper is null) { diagnostics.Add(Diagnostic.Error(new TextLocation(), "Bootstrapper not set.")); error = true; } return(!error); }