Example #1
0
        public void UpdateCompilationReplacesOriginalSyntaxTree()
        {
            CSharpSyntaxTree  original    = GetExampleSyntaxTree1();
            CSharpSyntaxTree  replaced    = GetExampleSyntaxTree2();
            CSharpCompilation compilation = _compilation.AddSyntaxTrees(original);

            Data.CompilationData data = new(compilation);
            data.UpdateCompilation(original, replaced);
            Assert.True(data.Compilation is not null && data.Compilation != compilation && data.Compilation.ContainsSyntaxTree(replaced) && !data.Compilation.ContainsSyntaxTree(original));
        }
        private static CSharpCompilation BuildCompilation(CompilerArguments compilerArguments)
        {
            CSharpCompilation compilation = CSharpCompilation.Create(compilerArguments.FileName)
                                            .WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
                                            .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location));

            var netStandardAssembly = Assembly.Load(new AssemblyName("netstandard"));

            compilation = compilation.AddReferences(MetadataReference.CreateFromFile(netStandardAssembly.Location));
            AssemblyName[] netStandardAssemblies = netStandardAssembly.GetReferencedAssemblies();

            foreach (var assembly in netStandardAssemblies)
            {
                string assemblyLocation = Assembly.Load(assembly).Location;
                compilation = compilation.AddReferences(MetadataReference.CreateFromFile(assemblyLocation));
            }

            List <SyntaxTree> syntaxTrees = new List <SyntaxTree>();

            foreach (var sourceCode in compilerArguments.Sources)
            {
                syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(sourceCode));
            }

            compilation = compilation.AddSyntaxTrees(syntaxTrees);
            return(compilation);
        }
Example #3
0
        private static CSharpCompilation ApplyProjectInfo(CSharpCompilation compilation, CompilationProjectContext project,
                                                          CSharpParseOptions parseOptions)
        {
            var projectAttributes = new Dictionary <string, string>(StringComparer.Ordinal)
            {
                [typeof(AssemblyTitleAttribute).FullName]                = EscapeCharacters(project.Title),
                [typeof(AssemblyDescriptionAttribute).FullName]          = EscapeCharacters(project.Description),
                [typeof(AssemblyCopyrightAttribute).FullName]            = EscapeCharacters(project.Copyright),
                [typeof(AssemblyFileVersionAttribute).FullName]          = EscapeCharacters(project.AssemblyFileVersion.ToString()),
                [typeof(AssemblyVersionAttribute).FullName]              = EscapeCharacters(RemovePrereleaseTag(project.Version)),
                [typeof(AssemblyInformationalVersionAttribute).FullName] = EscapeCharacters(project.Version)
            };

            var assemblyAttributes = compilation.Assembly.GetAttributes()
                                     .Select(assemblyAttribute => assemblyAttribute.AttributeClass.ToString());
            var newAttributes = string.Join(Environment.NewLine, projectAttributes
                                            .Where(projectAttribute => projectAttribute.Value != null && !assemblyAttributes.Contains(projectAttribute.Key))
                                            .Select(projectAttribute => $"[assembly:{projectAttribute.Key}(\"{projectAttribute.Value}\")]"));

            if (!string.IsNullOrWhiteSpace(newAttributes))
            {
                compilation = compilation.AddSyntaxTrees(new[]
                {
                    CSharpSyntaxTree.ParseText(newAttributes, parseOptions,
                                               path: $"{nameof(ApplyProjectInfo)}.cs",
                                               encoding: Encoding.UTF8)
                });
            }

            return(compilation);
        }
Example #4
0
    public void ProjectReferenceBetweenTwoGeneratingProjects(bool internalsVisibleTo)
    {
        CSharpCompilation referencedProject = this.compilation
                                              .WithAssemblyName("refdProj");

        if (internalsVisibleTo)
        {
            referencedProject = referencedProject.AddSyntaxTrees(
                CSharpSyntaxTree.ParseText($@"[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute(""{this.compilation.AssemblyName}"")]", this.parseOptions));
        }

        using var referencedGenerator = new Generator(OpenMetadata(), new GeneratorOptions { ClassName = "P1" }, referencedProject, this.parseOptions);
        Assert.True(referencedGenerator.TryGenerate("LockWorkStation", CancellationToken.None));
        Assert.True(referencedGenerator.TryGenerate("CreateFile", CancellationToken.None));
        referencedProject = this.AddGeneratedCode(referencedProject, referencedGenerator);
        this.AssertNoDiagnostics(referencedProject);

        // Now produce more code in a referencing project that includes at least one of the same types as generated in the referenced project.
        this.compilation = this.compilation.AddReferences(referencedProject.ToMetadataReference());
        this.generator   = new Generator(this.metadataStream, new GeneratorOptions {
            ClassName = "P2"
        }, this.compilation, this.parseOptions);
        Assert.True(this.generator.TryGenerate("HidD_GetAttributes", CancellationToken.None));
        this.CollectGeneratedCode(this.generator);
        this.AssertNoDiagnostics();
    }
Example #5
0
        public Compilation Compile(string filePath)
        {
            Logger.WriteInfo("Resolving references.");


            MetadataReferenceResolver       metadataReferenceResolver = ScriptOptions.Default.MetadataResolver;
            IEnumerable <MetadataReference> references = ResolveReferences(metadataReferenceResolver);

            string     directoryPath = Path.GetDirectoryName(filePath);
            SyntaxTree syntaxTree    = CreateSyntaxTreeFromFilePath(filePath);

            ICollection <string> additionalFilePaths = GetAdditionalFilePaths(directoryPath, syntaxTree);

            CSharpCompilation compilation = CreateCompilation(syntaxTree, additionalFilePaths.Except(new[] { filePath }),
                                                              references, metadataReferenceResolver);

            ICollection <string> additionalFilePathsByAttributes =
                GetAdditionalFilePathsByAttributes(directoryPath, compilation.GetSemanticModel(syntaxTree));

            if (additionalFilePathsByAttributes.Any())
            {
                compilation = compilation.AddSyntaxTrees(additionalFilePathsByAttributes.Except(new[] { filePath })
                                                         .Select(CreateSyntaxTreeFromFilePath));
            }

            return(compilation);
        }
Example #6
0
        private static CSharpCompilation CreateCSharpCompilationFromSyntax(IEnumerable <string> syntax, string name, bool enableNullable, byte[] publicKey)
        {
            CSharpCompilation        compilation = CreateCSharpCompilation(name, enableNullable, publicKey);
            IEnumerable <SyntaxTree> syntaxTrees = syntax.Select(s => GetSyntaxTree(s));

            return(compilation.AddSyntaxTrees(syntaxTrees));
        }
Example #7
0
            public CSharpCompilation updateCompilation(CSharpCompilation compilation, CSharpParseOptions options,
                                                       string assemblyName, string generatedFilesDir)
            {
                if (javaFilesDict.Count == 0)
                {
                    return(compilation);
                }
                if (lastUsedJavaVersion != javaVersion)
                {
                    lastUsedJavaVersion = javaVersion;

                    var newTree = generateJavaTree(options, assemblyName, generatedFilesDir);
                    var path    = newTree.FilePath;
                    {
                        if (File.Exists(path))
                        {
                            File.Delete(path);
                        }
                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                        File.WriteAllText(path, newTree.GetText().ToString());
                    }
                    // this code smells a little
                    filesDict["GENERATED_JAVA"] = new List <string>(new[] { path });
                    var result =
                        prevousTree == null
              ? compilation.AddSyntaxTrees(newTree)
              : compilation.ReplaceSyntaxTree(prevousTree, newTree);

                    prevousTree = newTree;
                    return(result);
                }

                return(compilation);
            }
Example #8
0
        public void AddSource(GeneratedSourceText sourceText)
        {
            var syntax = CSharpSyntaxTree.ParseText(sourceText.Text, new CSharpParseOptions(_sourceCompilation.LanguageVersion), "", null, true, _ct);

            _currentCompilation = _currentCompilation.AddSyntaxTrees(syntax);
            OnSourceGenerated?.Invoke(this, sourceText);
        }
Example #9
0
        protected CSharpCompilation CreateCompilation(SyntaxTree syntaxTree)
        {
            CSharpCompilation compilation = CSharpCompilation.Create("ExamineSnippet");
            HashSet <string>  locations   = new HashSet <string>();

            locations.Add(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll");
            foreach (SyntaxNode syntaxNode in syntaxTree.GetRoot().DescendantNodes().Where(d => d.Kind() == SyntaxKind.UsingDirective))
            {
                string nodeContent = syntaxNode.ToString();
                if (assemblyReferenceMappings.ContainsKey(nodeContent))
                {
                    foreach (Type type in assemblyReferenceMappings[nodeContent])
                    {
                        if (!locations.Contains(type.Assembly.Location))
                        {
                            locations.Add(type.Assembly.Location);
                        }
                    }
                }
                else
                {
                    throw new Exception($"{nodeContent} not found in assembly mappings.");
                }
            }
            foreach (string location in locations)
            {
                compilation = compilation.AddReferences(MetadataReference.CreateFromFile(location));
            }
            return(compilation.AddSyntaxTrees(syntaxTree));
        }
Example #10
0
        private static CSharpCompilation CreateCSharpCompilationFromSyntax(IEnumerable <string> syntax, string name, bool enableNullable, bool includeDefaultReferences)
        {
            CSharpCompilation        compilation = CreateCSharpCompilation(name, enableNullable, includeDefaultReferences);
            IEnumerable <SyntaxTree> syntaxTrees = syntax.Select(s => CSharpSyntaxTree.ParseText(s));

            return(compilation.AddSyntaxTrees(syntaxTrees));
        }
Example #11
0
        public static CSharpCompilation AddAssemblyMetadata(
            CSharpCompiler compiler,
            CSharpCompilation compilation,
            CompilationOptions compilationOptions)
        {
            if (!string.IsNullOrEmpty(compilationOptions.KeyFile))
            {
                var updatedOptions = compilation.Options.WithStrongNameProvider(new DesktopStrongNameProvider());
                var keyFilePath    = Path.GetFullPath(compilationOptions.KeyFile);

                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || compilationOptions.PublicSign)
                {
                    updatedOptions = updatedOptions.WithCryptoPublicKey(
                        SnkUtils.ExtractPublicKey(File.ReadAllBytes(keyFilePath)));
                }
                else
                {
                    updatedOptions = updatedOptions.WithCryptoKeyFile(keyFilePath)
                                     .WithDelaySign(compilationOptions.DelaySign);
                }

                compilation = compilation.WithOptions(updatedOptions);
            }

            var applicationAssemblyName = Assembly.Load(new AssemblyName(compilationOptions.ApplicationName)).GetName();
            var assemblyVersionContent  = $"[assembly:{typeof(AssemblyVersionAttribute).FullName}(\"{applicationAssemblyName.Version}\")]";
            var syntaxTree = compiler.CreateSyntaxTree(SourceText.From(assemblyVersionContent));

            return(compilation.AddSyntaxTrees(syntaxTree));
        }
Example #12
0
        public async Task DoesNotGenerateEnableModuleAttributeForDisabledModule()
        {
            StringBuilder builder = new();

            foreach (DurianModule module in ModuleIdentity.GetAllModules().AsEnums().Where(m => m != DurianModule.DefaultParam))
            {
                builder
                .Append("[assembly: Durian.Generator.EnableModule(Durian.Info.")
                .Append(nameof(DurianModule))
                .Append('.')
                .Append(module.ToString())
                .AppendLine(")]");
            }

            CSharpSyntaxTree expected = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(builder.ToString());

            CSharpCompilation compilation = RoslynUtilities.CreateBaseCompilation();

            compilation = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText("[assembly: Durian.DisableModule(Durian.Info.DurianModule.DefaultParam)]"));
            DisabledModuleAnalyzer analyzer = new();
            await analyzer.RunAnalyzer(compilation);

            SingletonGeneratorTestResult result = GeneratorTest.RunGenerator("", analyzer);

            Assert.True(result.IsGenerated);
            Assert.NotNull(result.SyntaxTree);
            Assert.True(result.SyntaxTree !.IsEquivalentTo(expected));
        }
Example #13
0
        public async Task XmlDoc_CheckAllAssemblies_HaveExamples()
        {
            var helper     = new Opinion.Opinion();
            var allClasses = await helper.GetProjectClasses(".");

            foreach (var projectClass in allClasses)
            {
                var codeText = new StreamReader(projectClass).ReadToEnd();
                var code     = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

                // Parse the C# code...
                CSharpParseOptions parseOptions = new CSharpParseOptions()
                                                  .WithKind(SourceCodeKind.Regular)             // ...as representing a complete .cs file
                                                  .WithLanguageVersion(LanguageVersion.Latest); // ...enabling the latest language features

                // Compile the C# code...
                CSharpCompilationOptions compileOptions =
                    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) // ...to a dll
                    .WithOptimizationLevel(OptimizationLevel.Release)                 // ...in Release configuration
                    .WithAllowUnsafe(enabled: true);                                  // ...enabling unsafe code

                // Invoke the compiler...
                CSharpCompilation compilation =
                    CSharpCompilation.Create("TestInMemoryAssembly")                                    // ..with some fake dll name
                    .WithOptions(compileOptions)
                    .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location)); // ...referencing the same mscorlib we're running on

                // Parse and compile the C# code into a *.dll and *.xml file in-memory
                var tree           = CSharpSyntaxTree.ParseText(codeText, parseOptions);
                var newCompilation = compilation.AddSyntaxTrees(tree);
            }
        }
        private static CSharpCompilation CompileCode(string code)
        {
            CSharpParseOptions parseOptions = new CSharpParseOptions()
                                              .WithKind(SourceCodeKind.Regular)             // ...as representing a complete .cs file
                                              .WithLanguageVersion(LanguageVersion.Latest); // ...enabling the latest language features

            // Compile the C# code...
            CSharpCompilationOptions compileOptions =
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) // ...to a dll
                .WithOptimizationLevel(OptimizationLevel.Release)                 // ...in Release configuration
                .WithAllowUnsafe(enabled: true);                                  // ...enabling unsafe code

            // Invoke the compiler...
            CSharpCompilation compilation =
                CSharpCompilation.Create("TestInMemoryAssembly") // ..with some fake dll name
                .WithOptions(compileOptions)
                .AddReferences(
                    MetadataReference.CreateFromFile(typeof(object).Assembly
                                                     .Location)); // ...referencing the same mscorlib we're running on

            var tree = CSharpSyntaxTree.ParseText(code, parseOptions);

            compilation = compilation.AddSyntaxTrees(tree);
            // Parse and compile the C# code into a *.dll and *.xml file in-memory
            return(compilation);
        }
Example #15
0
 public static CSharpCompilation WithCustomTextBox(this CSharpCompilation compilation) =>
 compilation.AddSyntaxTrees(
     CSharpSyntaxTree.ParseText(
         "using Avalonia.Controls;" +
         "namespace Controls {" +
         "  public class CustomTextBox : TextBox { }" +
         "  public class EvilControl { }" +
         "}"));
Example #16
0
        private HashSet <CodeImportNodeBase> GetCodeImportNodes(string sourceCode)
        {
            _thisPath = Guid.NewGuid() + ".cs";
            var tree        = CSharpSyntaxTree.ParseText(sourceCode, _thisPath);
            var compilation = _compilation.AddSyntaxTrees(tree);

            return(GetChildrenNodes(tree.GetRoot(), compilation, null));
        }
        public CSharpCompilation Update(CSharpCompilation compilation)
        {
            ImmutableArray <SyntaxTree> trees;

            lock (syntaxTrees)
                trees = syntaxTrees.ToImmutableArray();
            return(compilation.AddSyntaxTrees(trees));
        }
Example #18
0
        private static CSharpCompilation ApplyVersionInfo(CSharpCompilation compilation, CompilationProjectContext project,
                                                          CSharpParseOptions parseOptions)
        {
            const string assemblyFileVersionName      = "System.Reflection.AssemblyFileVersionAttribute";
            const string assemblyVersionName          = "System.Reflection.AssemblyVersionAttribute";
            const string assemblyInformationalVersion = "System.Reflection.AssemblyInformationalVersionAttribute";

            var assemblyAttributes = compilation.Assembly.GetAttributes();

            var foundAssemblyFileVersion          = false;
            var foundAssemblyVersion              = false;
            var foundAssemblyInformationalVersion = false;

            foreach (var assembly in assemblyAttributes)
            {
                string attributeName = assembly.AttributeClass.ToString();

                if (string.Equals(attributeName, assemblyFileVersionName, StringComparison.Ordinal))
                {
                    foundAssemblyFileVersion = true;
                }
                else if (string.Equals(attributeName, assemblyVersionName, StringComparison.Ordinal))
                {
                    foundAssemblyVersion = true;
                }
                else if (string.Equals(attributeName, assemblyInformationalVersion, StringComparison.Ordinal))
                {
                    foundAssemblyInformationalVersion = true;
                }
            }

            var versionAttributes = new StringBuilder();

            if (!foundAssemblyFileVersion)
            {
                versionAttributes.AppendLine($"[assembly:{assemblyFileVersionName}(\"{project.AssemblyFileVersion}\")]");
            }

            if (!foundAssemblyVersion)
            {
                versionAttributes.AppendLine($"[assembly:{assemblyVersionName}(\"{RemovePrereleaseTag(project.Version)}\")]");
            }

            if (!foundAssemblyInformationalVersion)
            {
                versionAttributes.AppendLine($"[assembly:{assemblyInformationalVersion}(\"{project.Version}\")]");
            }

            if (versionAttributes.Length != 0)
            {
                compilation = compilation.AddSyntaxTrees(new[]
                {
                    CSharpSyntaxTree.ParseText(versionAttributes.ToString(), parseOptions)
                });
            }

            return(compilation);
        }
Example #19
0
        private ICompilationData CreateValidCompilationData(SyntaxTree tree)
        {
            CSharpCompilation       compilation = _compilation.AddSyntaxTrees(tree);
            Mock <ICompilationData> mock        = new();

            mock.Setup(c => c.Compilation).Returns(compilation);

            return(mock.Object);
        }
Example #20
0
        protected virtual CSharpCompilation AddToCompilation(CSharpCompilation compilation, DefaultViewCompilerCodeEmitter emitter, string fileName, string namespaceName, string className)
        {
            var tree = emitter.BuildTree(namespaceName, className, fileName);

            return(compilation
                   .AddSyntaxTrees(tree)
                   .AddReferences(emitter.UsedAssemblies
                                  .Select(a => assemblyCache.GetAssemblyMetadata(a))));
        }
 public ValueTask <CSharpCompilation> EnrichAsync(CSharpCompilation target,
                                                  CancellationToken cancellationToken = default) =>
 new ValueTask <CSharpCompilation>(target
                                   .AddSyntaxTrees(_generators
                                                   .AsParallel()
                                                   .AsUnordered()
                                                   .WithCancellation(cancellationToken)
                                                   .SelectMany(p => p.Generate())
                                                   .ToArray()));
Example #22
0
        protected virtual CSharpCompilation AddToCompilation(CSharpCompilation compilation, DefaultViewCompilerCodeEmitter emitter, string fileName, string namespaceName, string className)
        {
            var tree = emitter.BuildTree(namespaceName, className, fileName);

            return(compilation
                   .AddSyntaxTrees(tree)
                   .AddReferences(emitter.UsedAssemblies
                                  .Select(a => GetAssemblyCache().GetAssemblyMetadata(a.Key).WithAliases(ImmutableArray.Create(a.Value, "global")))));
        }
Example #23
0
        public SyntaxTree SingleFirstPass(Compilation sourceCompilation, SyntaxTree tree)
        {
            _sourceCompilation = sourceCompilation;
            var converted     = VisualBasicConverter.ConvertCompilationTree((VisualBasicCompilation)sourceCompilation, _convertedCompilation, (VisualBasicSyntaxTree)tree);
            var convertedTree = SyntaxFactory.SyntaxTree(converted);

            _convertedCompilation = _convertedCompilation.AddSyntaxTrees(convertedTree);
            return(convertedTree);
        }
Example #24
0
        /// <summary>
        /// Adds a reference to the ScriptNamespace attribute that can appear in tests.
        /// </summary>
        /// <param name="compilation">The <see cref="CSharpCompilation"/> compilation hosting the references.</param>
        /// <returns>A <see cref="CSharpCompilation"/> with the added reference to the ScriptNamespace attribute to be used in tests.</returns>
        public static CSharpCompilation AddScriptNamespaceReference(this CSharpCompilation compilation)
        {
            if (compilation == null)
            {
                throw new ArgumentNullException(nameof(compilation));
            }

            var tree = CSharpSyntaxTree.ParseText(Source);

            return(compilation.AddSyntaxTrees(tree));
        }
Example #25
0
        public static CSharpCompilation AddAssemblyMetadata(
            RoslynCompilationService compiler,
            CSharpCompilation compilation,
            CompilationOptions compilationOptions)
        {
            var applicationAssemblyName = Assembly.Load(new AssemblyName(compilationOptions.ApplicationName)).GetName();
            var assemblyVersionContent  = $"[assembly:{typeof(AssemblyVersionAttribute).FullName}(\"{applicationAssemblyName.Version}\")]";
            var syntaxTree = compiler.CreateSyntaxTree(SourceText.From(assemblyVersionContent));

            return(compilation.AddSyntaxTrees(syntaxTree));
        }
Example #26
0
        /// <summary>
        /// Runs the specified <paramref name="analyzer"/> and returns an <see cref="ImmutableArray{T}"/> of produced <see cref="Diagnostic"/>s.
        /// </summary>
        /// <param name="analyzer"><see cref="DiagnosticAnalyzer"/> to run.</param>
        /// <param name="tree">A <see cref="CSharpSyntaxTree"/> the analysis should be performed on.</param>
        public static Task <ImmutableArray <Diagnostic> > RunAnalyzer(this DiagnosticAnalyzer analyzer, CSharpSyntaxTree?tree)
        {
            CSharpCompilation compilation = RoslynUtilities.CreateBaseCompilation();

            if (tree is not null)
            {
                compilation = compilation.AddSyntaxTrees(tree);
            }

            return(RunAnalyzer(analyzer, compilation));
        }
Example #27
0
        public async Task DisablesModule_When_HasDisableModuleAttribute()
        {
            string            input       = "[assembly: Durian.DisableModule(Durian.Info.DurianModule.DefaultParam)]";
            CSharpCompilation compilation = RoslynUtilities.CreateBaseCompilation();

            compilation = compilation.AddSyntaxTrees(CSharpSyntaxTree.ParseText(input));
            DisabledModuleAnalyzer analyzer = new();
            await analyzer.RunAnalyzer(compilation);

            Assert.False(DisabledModuleAnalyzer.IsEnabled(DurianModule.DefaultParam));
        }
Example #28
0
        /// <summary>
        ///   Edits the given <paramref name="compilation"/>, adding a <see cref="CSharpSyntaxTree"/>
        ///   defining the 'Answers' class.
        /// </summary>
        private static CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken)
        {
            var tree = SyntaxFactory.ParseSyntaxTree(@"
                namespace Cometary.Tests {
                    public static class Answers {
                        public static int LifeTheUniverseAndEverything => 42;
                    }
                }
            ");

            return(compilation.AddSyntaxTrees(tree));
        }
Example #29
0
        // Given a syntax tree from a compilation unit, add/convert the comments
        public CSharpCompilation ConvertCompilation(CSharpCompilation compilation)
        {
            m_compilation = compilation;
            var trees = compilation.SyntaxTrees;

            // Loop over the trees
            foreach (SyntaxTree tree in trees)
            {
                SyntaxTree newTree = ConvertTree(tree);
                compilation = compilation.AddSyntaxTrees(newTree);
            }
            return(compilation);
        }
Example #30
0
    private CSharpCompilation AddGeneratedCode(CSharpCompilation compilation, Generator generator)
    {
        var compilationUnits = generator.GetCompilationUnits(CancellationToken.None);
        var syntaxTrees      = new List <SyntaxTree>(compilationUnits.Count);

        foreach (var unit in compilationUnits)
        {
            // Our syntax trees aren't quite right. And anyway the source generator API only takes text anyway so it doesn't _really_ matter.
            // So render the trees as text and have C# re-parse them so we get the same compiler warnings/errors that the user would get.
            syntaxTrees.Add(CSharpSyntaxTree.ParseText(unit.Value.ToFullString(), this.parseOptions, path: unit.Key));
        }

        return(compilation.AddSyntaxTrees(syntaxTrees));
    }