├── img ├── logo.png ├── banner.png └── logo.svg ├── src ├── TestProjects │ ├── global.json │ ├── TestLibrary1 │ │ ├── TestClass1.cs │ │ └── TestLibrary1.csproj │ ├── TestLibrary2 │ │ ├── TestClass2.cs │ │ └── TestLibrary2.csproj │ ├── TestLibraryRoot │ │ ├── TestClassRoot.cs │ │ └── TestLibraryRoot.csproj │ └── TestLibraryRoot.sln ├── global.json ├── dotnet-releaser.toml ├── Broslyn.Tests │ ├── Broslyn.Tests.csproj │ └── CSharpCompilationCaptureTests.cs ├── Broslyn │ ├── Broslyn.csproj │ ├── CSharpCompilationCaptureResult.cs │ └── CSharpCompilationCapture.cs └── Broslyn.sln ├── .github ├── workflows │ ├── nuget_org_only.config │ └── ci.yml └── FUNDING.yml ├── changelog.md ├── license.txt ├── readme.md └── .gitignore /img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xoofx/Broslyn/HEAD/img/logo.png -------------------------------------------------------------------------------- /img/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xoofx/Broslyn/HEAD/img/banner.png -------------------------------------------------------------------------------- /src/TestProjects/global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "5.0", 4 | "rollForward": "latestMinor" 5 | } 6 | } -------------------------------------------------------------------------------- /src/global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "7.0.100", 4 | "rollForward": "latestMinor", 5 | "allowPrerelease": false 6 | } 7 | } -------------------------------------------------------------------------------- /src/dotnet-releaser.toml: -------------------------------------------------------------------------------- 1 | # configuration file for dotnet-releaser 2 | [msbuild] 3 | project = "./Broslyn.sln" 4 | [github] 5 | user = "xoofx" 6 | repo = "Broslyn" 7 | -------------------------------------------------------------------------------- /src/TestProjects/TestLibrary1/TestClass1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TestLibrary1 4 | { 5 | public class TestClass1 6 | { 7 | public static int Calculate() => 1; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/TestProjects/TestLibrary2/TestClass2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TestLibrary2 4 | { 5 | public class TestClass2 6 | { 7 | public static int Calculate() => 2; 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/TestProjects/TestLibrary1/TestLibrary1.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | false 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/TestProjects/TestLibrary2/TestLibrary2.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | false 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.github/workflows/nuget_org_only.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/TestProjects/TestLibraryRoot/TestClassRoot.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TestLibraryRoot 4 | { 5 | public class TestClassRoot 6 | { 7 | public static int Calculate() => TestLibrary1.TestClass1.Calculate() + TestLibrary2.TestClass2.Calculate(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /changelog.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | > This changelog is no longer used. Please visit https://github.com/xoofx/Broslyn/releases 4 | 5 | ## 1.1.0 (6 Jan 2022) 6 | - Use net6.0 to avoid .NET Framework dependency to `Microsoft.Build` (PR #3) 7 | 8 | ## 1.0.1 (12 Nov 2020) 9 | - Fix package description 10 | 11 | ## 1.0.0 (12 Nov 2020) 12 | - Initial release 13 | -------------------------------------------------------------------------------- /src/TestProjects/TestLibraryRoot/TestLibraryRoot.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;netcoreapp3.1 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Broslyn.Tests/Broslyn.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [xoofx] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: 4 | push: 5 | paths-ignore: 6 | - 'doc/**' 7 | - 'img/**' 8 | - 'changelog.md' 9 | - 'readme.md' 10 | pull_request: 11 | 12 | jobs: 13 | build: 14 | runs-on: windows-latest 15 | 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v3 19 | with: 20 | fetch-depth: 0 21 | 22 | - name: Install .NET 7.0 23 | uses: actions/setup-dotnet@v3 24 | with: 25 | dotnet-version: '7.0.x' 26 | 27 | - name: Build, Test, Pack, Publish 28 | shell: bash 29 | run: | 30 | dotnet tool install -g dotnet-releaser --configfile .github/workflows/nuget_org_only.config 31 | dotnet-releaser run --nuget-token ${{secrets.NUGET_TOKEN}} --github-token ${{secrets.GITHUB_TOKEN}} src/dotnet-releaser.toml -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016-2022, Alexandre Mutel 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification 5 | , are permitted provided that the following conditions are met: 6 | 7 | 1. Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | 2. Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 15 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 16 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 17 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 18 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 20 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 21 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 22 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 23 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /src/Broslyn/Broslyn.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0;netstandard2.0 5 | A lightweight utility library to create a Roslyn AdhocWorkspace from an existing solution`/`csproj. 6 | Alexandre Mutel 7 | en-US 8 | Alexandre Mutel 9 | roslyn 10 | logo.png 11 | readme.md 12 | https://github.com/xoofx/Broslyn 13 | BSD-2-Clause 14 | $(NoWarn);CS1591 15 | true 16 | 17 | true 18 | true 19 | snupkg 20 | 21 | 22 | 23 | 24 | 25 | 26 | all 27 | runtime; build; native; contentfiles; analyzers; buildtransitive 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/Broslyn.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.32014.148 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Broslyn", "Broslyn\Broslyn.csproj", "{50D6A2DC-FE21-4355-9E10-66F071807DA6}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Broslyn.Tests", "Broslyn.Tests\Broslyn.Tests.csproj", "{A3A36DD6-9593-4F94-8E27-54B2E238C976}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{F490171D-C09B-41DB-AA42-64BFFAB82D2A}" 11 | ProjectSection(SolutionItems) = preProject 12 | ..\.gitignore = ..\.gitignore 13 | ..\changelog.md = ..\changelog.md 14 | ..\.github\workflows\ci.yml = ..\.github\workflows\ci.yml 15 | dotnet-releaser.toml = dotnet-releaser.toml 16 | global.json = global.json 17 | ..\license.txt = ..\license.txt 18 | ..\readme.md = ..\readme.md 19 | EndProjectSection 20 | EndProject 21 | Global 22 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 23 | Debug|Any CPU = Debug|Any CPU 24 | Release|Any CPU = Release|Any CPU 25 | EndGlobalSection 26 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 27 | {50D6A2DC-FE21-4355-9E10-66F071807DA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {50D6A2DC-FE21-4355-9E10-66F071807DA6}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {50D6A2DC-FE21-4355-9E10-66F071807DA6}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {50D6A2DC-FE21-4355-9E10-66F071807DA6}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {A3A36DD6-9593-4F94-8E27-54B2E238C976}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {A3A36DD6-9593-4F94-8E27-54B2E238C976}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {A3A36DD6-9593-4F94-8E27-54B2E238C976}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {A3A36DD6-9593-4F94-8E27-54B2E238C976}.Release|Any CPU.Build.0 = Release|Any CPU 35 | EndGlobalSection 36 | GlobalSection(SolutionProperties) = preSolution 37 | HideSolutionNode = FALSE 38 | EndGlobalSection 39 | GlobalSection(ExtensibilityGlobals) = postSolution 40 | SolutionGuid = {061D4464-093C-4A7C-A2CB-C996A8344ABA} 41 | EndGlobalSection 42 | EndGlobal 43 | -------------------------------------------------------------------------------- /src/TestProjects/TestLibraryRoot.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30709.132 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestLibraryRoot", "TestLibraryRoot\TestLibraryRoot.csproj", "{1A294704-C751-43DE-8A1F-181187AD525F}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestLibrary1", "TestLibrary1\TestLibrary1.csproj", "{09404F1A-13E6-45D2-A1D3-33AFE6789367}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestLibrary2", "TestLibrary2\TestLibrary2.csproj", "{FD348352-04FD-4A20-98FF-DD4B0EC1F210}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {1A294704-C751-43DE-8A1F-181187AD525F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {1A294704-C751-43DE-8A1F-181187AD525F}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {1A294704-C751-43DE-8A1F-181187AD525F}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {1A294704-C751-43DE-8A1F-181187AD525F}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {09404F1A-13E6-45D2-A1D3-33AFE6789367}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {09404F1A-13E6-45D2-A1D3-33AFE6789367}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {09404F1A-13E6-45D2-A1D3-33AFE6789367}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {09404F1A-13E6-45D2-A1D3-33AFE6789367}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {FD348352-04FD-4A20-98FF-DD4B0EC1F210}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {FD348352-04FD-4A20-98FF-DD4B0EC1F210}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {FD348352-04FD-4A20-98FF-DD4B0EC1F210}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {FD348352-04FD-4A20-98FF-DD4B0EC1F210}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {937323B4-6D8B-4685-9C37-5EA233E50121} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /src/Broslyn/CSharpCompilationCaptureResult.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Microsoft.CodeAnalysis; 3 | using Microsoft.CodeAnalysis.CSharp; 4 | 5 | namespace Broslyn 6 | { 7 | /// 8 | /// Result of a CSharp compilation capture that provides access to a Roslyn Workspace to allow in memory inspection. 9 | /// 10 | public sealed class CSharpCompilationCaptureResult 11 | { 12 | private readonly Dictionary _commandLineArguments; 13 | 14 | internal CSharpCompilationCaptureResult(AdhocWorkspace workspace, Dictionary commandLineArguments) 15 | { 16 | _commandLineArguments = commandLineArguments; 17 | Workspace = workspace; 18 | } 19 | 20 | /// 21 | /// Gets the associated workspace. 22 | /// 23 | public AdhocWorkspace Workspace { get; } 24 | 25 | /// 26 | /// Tries to get the associated to the specified project id. 27 | /// 28 | /// The project id. 29 | /// The output arguments if it was found. 30 | /// true if the project id has associated command line arguments. 31 | public bool TryGetCommandLineArguments(ProjectId projectId, out CSharpCommandLineArguments commandLineArguments) 32 | { 33 | return _commandLineArguments.TryGetValue(projectId, out commandLineArguments); 34 | } 35 | 36 | /// 37 | /// Tries to get the associated to the specified project. 38 | /// 39 | /// The project 40 | /// The output arguments if it was found. 41 | /// true if the project id has associated command line arguments. 42 | public bool TryGetCommandLineArguments(Project project, out CSharpCommandLineArguments commandLineArguments) 43 | { 44 | return TryGetCommandLineArguments(project.Id, out commandLineArguments); 45 | } 46 | } 47 | } -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Broslyn [![Build Status](https://github.com/xoofx/Broslyn/workflows/ci/badge.svg?branch=master)](https://github.com/xoofx/Broslyn/actions) [![NuGet](https://img.shields.io/nuget/v/Broslyn.svg)](https://www.nuget.org/packages/Broslyn/) 2 | 3 | 4 | 5 | A lightweight utility library to create a Roslyn `AdhocWorkspace` from an existing `solution`/`csproj`, by capturing the CSharp compiler emited command while rebuilding the project. 6 | This can be used primarily for syntax tree inspection/code generation. 7 | 8 | > This library requires a `dotnet` SDK to be installed 9 | 10 | ## Usage 11 | 12 | ```csharp 13 | // Rebuild the specified project in Release and capture 14 | var result = CSharpCompilationCapture.Build(@"C:\Path\To\A\Sln\Or\project.csproj", "Release"); 15 | var workspace = result.Workspace; 16 | var project = workspace.CurrentSolution.Projects.FirstOrDefault(); 17 | var compilation = await project.GetCompilationAsync(); 18 | // ... 19 | ``` 20 | 21 | ## Why? 22 | 23 | If you have been using `MSBuildWorkdspace` to get an access to CSharp projects, you will find sometimes that it is actually impossible to work with if you are expecting your Roslyn application to run on a different runtime than the one currently installed through the `dotnet` SDK. 24 | 25 | This is a known issue [Use more permissive load context for MSBuildWorkspace by default](https://github.com/dotnet/roslyn/issues/49248) and I hope that it will be fix in the future. 26 | 27 | To workaround this problem and allow to load a CSharp Project with Roslyn no matter which SDK is installed, Broslyn is working like this: 28 | 29 | - It runs a `dotnet msbuild /t:rebuild` on the project or solution passed to it with an output to a binlog file. 30 | - By running the re-build, we are able to capture the exact `csc` command issued by the build system and we can extract them with by [reading compiler invocations](https://github.com/KirillOsenkov/MSBuildStructuredLog/wiki/Reading-Compiler-invocations) using the fantastic [MSBuildStruturedLog](https://github.com/KirillOsenkov/MSBuildStructuredLog) library. 31 | - We then extract the csc arguments and transform them back to `CSharpCompilationArguments`. 32 | - From this we can create for each `csc` invocation and equivalent Roslyn `Project` that will guarantee the exact same compilation settings. 33 | 34 | This was a nice suggestion from [Kirill Osenkov](https://twitter.com/KirillOsenkov) (the author of MSBuildStruturedLog) and it turns out that it was very easy to implement. 35 | 36 | ## License 37 | 38 | This software is released under the [BSD-Clause 2 license](https://opensource.org/licenses/BSD-2-Clause). 39 | 40 | ## Related projects 41 | 42 | * [Buildalizer](https://github.com/daveaglick/Buildalyzer): A more featured library if you are looking for a better introspection on project references and dependencies 43 | - In Broslyn, a Project will only contain assembly references in order to compile to CSharp but will not provide full introspection on the original project references. 44 | 45 | ## Author 46 | 47 | Alexandre Mutel aka [xoofx](https://xoofx.github.io). 48 | 49 | -------------------------------------------------------------------------------- /src/Broslyn.Tests/CSharpCompilationCaptureTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Microsoft.CodeAnalysis; 8 | using NUnit.Framework; 9 | 10 | namespace Broslyn.Tests 11 | { 12 | /// 13 | /// Testing 14 | /// 15 | public class CSharpCompilationCaptureTests 16 | { 17 | [Test] 18 | public async Task TestLibraryRoot() 19 | { 20 | var projectPath = Path.Combine(Environment.CurrentDirectory, "..", "..", "..", "..", "TestProjects", "TestLibraryRoot.sln"); 21 | 22 | var clock = Stopwatch.StartNew(); 23 | var result = CSharpCompilationCapture.Build(projectPath); 24 | Console.WriteLine($"Project {projectPath} built in {clock.Elapsed.TotalMilliseconds}ms"); 25 | 26 | var workspace = result.Workspace; 27 | 28 | // TestLibrary1 29 | // TestLibrary2 30 | // TestLibraryRoot (netcoreapp3.1) + TestLibraryRoot (netstandard2.0) 31 | Assert.AreEqual(1 + 1 + 2, workspace.CurrentSolution.Projects.Count()); 32 | 33 | Assert.True(workspace.CurrentSolution.Projects.Any(p => p.Name == "TestLibrary1"), "Expecting TestLibrary1 in the projects"); 34 | Assert.True(workspace.CurrentSolution.Projects.Any(p => p.Name == "TestLibrary2"), "Expecting TestLibrary1 in the projects"); 35 | Assert.AreEqual(2, workspace.CurrentSolution.Projects.Count(p => p.Name == "TestLibraryRoot"), "Expecting 2 TestLibraryRoot projects"); 36 | 37 | foreach (var project in workspace.CurrentSolution.Projects) 38 | { 39 | clock.Restart(); 40 | Assert.AreEqual(OptimizationLevel.Debug, project.CompilationOptions.OptimizationLevel); 41 | 42 | var hasArguments = result.TryGetCommandLineArguments(project, out var arguments); 43 | Assert.True(hasArguments, "Unable to retrieve CSharp Arguments by Project"); 44 | hasArguments = result.TryGetCommandLineArguments(project.Id, out arguments); 45 | Assert.True(hasArguments, "Unable to retrieve CSharp Arguments by ProjectId"); 46 | 47 | // Compile the project 48 | var compilation = await project.GetCompilationAsync(); 49 | Assert.NotNull(compilation, "Compilation must not be null"); 50 | var diagnostics = compilation.GetDiagnostics(); 51 | 52 | var errors = diagnostics.Where(x => x.Severity == DiagnosticSeverity.Error).ToList(); 53 | if (errors.Count > 0) 54 | { 55 | var builder = new StringBuilder(); 56 | builder.AppendLine($"Project {project.Name} has errors:"); 57 | foreach (var diag in errors) 58 | { 59 | builder.AppendLine($"{diag}"); 60 | } 61 | Assert.AreEqual(0, errors.Count, $"Invalid compilation errors: {builder}"); 62 | } 63 | else 64 | { 65 | Console.WriteLine($"Project {project.Name} ({project.CompilationOptions.OptimizationLevel}) in-memory compiled in {clock.Elapsed.TotalMilliseconds}ms"); 66 | 67 | // We should have at least 1 syntax tree 68 | var trees = compilation.SyntaxTrees.ToList(); 69 | Assert.AreNotEqual(0, trees.Count, "Expecting SyntaxTrees"); 70 | } 71 | } 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /img/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | image/svg+xml 79 | 89 | C# 110 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.vspscc 94 | *.vssscc 95 | .builds 96 | *.pidb 97 | *.svclog 98 | *.scc 99 | 100 | # Chutzpah Test files 101 | _Chutzpah* 102 | 103 | # Visual C++ cache files 104 | ipch/ 105 | *.aps 106 | *.ncb 107 | *.opendb 108 | *.opensdf 109 | *.sdf 110 | *.cachefile 111 | *.VC.db 112 | *.VC.VC.opendb 113 | 114 | # Visual Studio profiler 115 | *.psess 116 | *.vsp 117 | *.vspx 118 | *.sap 119 | 120 | # Visual Studio Trace Files 121 | *.e2e 122 | 123 | # TFS 2012 Local Workspace 124 | $tf/ 125 | 126 | # Guidance Automation Toolkit 127 | *.gpState 128 | 129 | # ReSharper is a .NET coding add-in 130 | _ReSharper*/ 131 | *.[Rr]e[Ss]harper 132 | *.DotSettings.user 133 | 134 | # TeamCity is a build add-in 135 | _TeamCity* 136 | 137 | # DotCover is a Code Coverage Tool 138 | *.dotCover 139 | 140 | # AxoCover is a Code Coverage Tool 141 | .axoCover/* 142 | !.axoCover/settings.json 143 | 144 | # Coverlet is a free, cross platform Code Coverage Tool 145 | coverage*.json 146 | coverage*.xml 147 | coverage*.info 148 | 149 | # Visual Studio code coverage results 150 | *.coverage 151 | *.coveragexml 152 | 153 | # NCrunch 154 | _NCrunch_* 155 | .*crunch*.local.xml 156 | nCrunchTemp_* 157 | 158 | # MightyMoose 159 | *.mm.* 160 | AutoTest.Net/ 161 | 162 | # Web workbench (sass) 163 | .sass-cache/ 164 | 165 | # Installshield output folder 166 | [Ee]xpress/ 167 | 168 | # DocProject is a documentation generator add-in 169 | DocProject/buildhelp/ 170 | DocProject/Help/*.HxT 171 | DocProject/Help/*.HxC 172 | DocProject/Help/*.hhc 173 | DocProject/Help/*.hhk 174 | DocProject/Help/*.hhp 175 | DocProject/Help/Html2 176 | DocProject/Help/html 177 | 178 | # Click-Once directory 179 | publish/ 180 | 181 | # Publish Web Output 182 | *.[Pp]ublish.xml 183 | *.azurePubxml 184 | # Note: Comment the next line if you want to checkin your web deploy settings, 185 | # but database connection strings (with potential passwords) will be unencrypted 186 | *.pubxml 187 | *.publishproj 188 | 189 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 190 | # checkin your Azure Web App publish settings, but sensitive information contained 191 | # in these scripts will be unencrypted 192 | PublishScripts/ 193 | 194 | # NuGet Packages 195 | *.nupkg 196 | # NuGet Symbol Packages 197 | *.snupkg 198 | # The packages folder can be ignored because of Package Restore 199 | **/[Pp]ackages/* 200 | # except build/, which is used as an MSBuild target. 201 | !**/[Pp]ackages/build/ 202 | # Uncomment if necessary however generally it will be regenerated when needed 203 | #!**/[Pp]ackages/repositories.config 204 | # NuGet v3's project.json files produces more ignorable files 205 | *.nuget.props 206 | *.nuget.targets 207 | 208 | # Microsoft Azure Build Output 209 | csx/ 210 | *.build.csdef 211 | 212 | # Microsoft Azure Emulator 213 | ecf/ 214 | rcf/ 215 | 216 | # Windows Store app package directories and files 217 | AppPackages/ 218 | BundleArtifacts/ 219 | Package.StoreAssociation.xml 220 | _pkginfo.txt 221 | *.appx 222 | *.appxbundle 223 | *.appxupload 224 | 225 | # Visual Studio cache files 226 | # files ending in .cache can be ignored 227 | *.[Cc]ache 228 | # but keep track of directories ending in .cache 229 | !?*.[Cc]ache/ 230 | 231 | # Others 232 | ClientBin/ 233 | ~$* 234 | *~ 235 | *.dbmdl 236 | *.dbproj.schemaview 237 | *.jfm 238 | *.pfx 239 | *.publishsettings 240 | orleans.codegen.cs 241 | 242 | # Including strong name files can present a security risk 243 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 244 | #*.snk 245 | 246 | # Since there are multiple workflows, uncomment next line to ignore bower_components 247 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 248 | #bower_components/ 249 | 250 | # RIA/Silverlight projects 251 | Generated_Code/ 252 | 253 | # Backup & report files from converting an old project file 254 | # to a newer Visual Studio version. Backup files are not needed, 255 | # because we have git ;-) 256 | _UpgradeReport_Files/ 257 | Backup*/ 258 | UpgradeLog*.XML 259 | UpgradeLog*.htm 260 | ServiceFabricBackup/ 261 | *.rptproj.bak 262 | 263 | # SQL Server files 264 | *.mdf 265 | *.ldf 266 | *.ndf 267 | 268 | # Business Intelligence projects 269 | *.rdl.data 270 | *.bim.layout 271 | *.bim_*.settings 272 | *.rptproj.rsuser 273 | *- [Bb]ackup.rdl 274 | *- [Bb]ackup ([0-9]).rdl 275 | *- [Bb]ackup ([0-9][0-9]).rdl 276 | 277 | # Microsoft Fakes 278 | FakesAssemblies/ 279 | 280 | # GhostDoc plugin setting file 281 | *.GhostDoc.xml 282 | 283 | # Node.js Tools for Visual Studio 284 | .ntvs_analysis.dat 285 | node_modules/ 286 | 287 | # Visual Studio 6 build log 288 | *.plg 289 | 290 | # Visual Studio 6 workspace options file 291 | *.opt 292 | 293 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 294 | *.vbw 295 | 296 | # Visual Studio LightSwitch build output 297 | **/*.HTMLClient/GeneratedArtifacts 298 | **/*.DesktopClient/GeneratedArtifacts 299 | **/*.DesktopClient/ModelManifest.xml 300 | **/*.Server/GeneratedArtifacts 301 | **/*.Server/ModelManifest.xml 302 | _Pvt_Extensions 303 | 304 | # Paket dependency manager 305 | .paket/paket.exe 306 | paket-files/ 307 | 308 | # FAKE - F# Make 309 | .fake/ 310 | 311 | # CodeRush personal settings 312 | .cr/personal 313 | 314 | # Python Tools for Visual Studio (PTVS) 315 | __pycache__/ 316 | *.pyc 317 | 318 | # Cake - Uncomment if you are using it 319 | # tools/** 320 | # !tools/packages.config 321 | 322 | # Tabs Studio 323 | *.tss 324 | 325 | # Telerik's JustMock configuration file 326 | *.jmconfig 327 | 328 | # BizTalk build output 329 | *.btp.cs 330 | *.btm.cs 331 | *.odx.cs 332 | *.xsd.cs 333 | 334 | # OpenCover UI analysis results 335 | OpenCover/ 336 | 337 | # Azure Stream Analytics local run output 338 | ASALocalRun/ 339 | 340 | # MSBuild Binary and Structured Log 341 | *.binlog 342 | 343 | # NVidia Nsight GPU debugger configuration file 344 | *.nvuser 345 | 346 | # MFractors (Xamarin productivity tool) working folder 347 | .mfractor/ 348 | 349 | # Local History for Visual Studio 350 | .localhistory/ 351 | 352 | # BeatPulse healthcheck temp database 353 | healthchecksdb 354 | 355 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 356 | MigrationBackup/ 357 | 358 | # Ionide (cross platform F# VS Code tools) working folder 359 | .ionide/ 360 | 361 | # Fody - auto-generated XML schema 362 | FodyWeavers.xsd 363 | 364 | # Common IntelliJ Platform excludes 365 | 366 | # User specific 367 | **/.idea/**/workspace.xml 368 | **/.idea/**/tasks.xml 369 | **/.idea/shelf/* 370 | **/.idea/dictionaries 371 | **/.idea/httpRequests/ 372 | 373 | # Sensitive or high-churn files 374 | **/.idea/**/dataSources/ 375 | **/.idea/**/dataSources.ids 376 | **/.idea/**/dataSources.xml 377 | **/.idea/**/dataSources.local.xml 378 | **/.idea/**/sqlDataSources.xml 379 | **/.idea/**/dynamic.xml 380 | 381 | # Rider 382 | # Rider auto-generates .iml files, and contentModel.xml 383 | **/.idea/**/*.iml 384 | **/.idea/**/contentModel.xml 385 | **/.idea/**/modules.xml 386 | 387 | *.suo 388 | *.user 389 | .vs/ 390 | [Bb]in/ 391 | [Oo]bj/ 392 | _UpgradeReport_Files/ 393 | [Pp]ackages/ 394 | 395 | Thumbs.db 396 | Desktop.ini 397 | .DS_Store 398 | 399 | # Tmp folders 400 | tmp/ 401 | [Tt]emp/ 402 | 403 | # Remove artifacts produced by dotnet-releaser 404 | artifacts-dotnet-releaser/ 405 | -------------------------------------------------------------------------------- /src/Broslyn/CSharpCompilationCapture.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Text.RegularExpressions; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CSharp; 10 | using Microsoft.CodeAnalysis.Text; 11 | 12 | namespace Broslyn 13 | { 14 | /// 15 | /// Frontend class to capture the build of a project/solution that contains CSharp projects. 16 | /// 17 | public sealed class CSharpCompilationCapture 18 | { 19 | private readonly Dictionary _references; 20 | 21 | private CSharpCompilationCapture() 22 | { 23 | _references = new Dictionary(); 24 | } 25 | 26 | /// 27 | /// Build the specified project or solution to collect the CSharp compilations and allow to reconstruct in memory an inspect-able Roslyn workspace. 28 | /// 29 | /// The path to a project or solution. 30 | /// The default configuration to build. Default: Debug. 31 | /// The default configuration to build. Default: Any CPU. 32 | /// Optional additional properties to pass to the build. 33 | /// The result of the compilation capture. Use to get an access to a Roslyn Workspace. 34 | public static CSharpCompilationCaptureResult Build(string projectFileOrSolution, string configuration = "Debug", string platform = "Any CPU", Dictionary properties = null) 35 | { 36 | if (projectFileOrSolution == null) throw new ArgumentNullException(nameof(projectFileOrSolution)); 37 | if (!File.Exists(projectFileOrSolution)) throw new ArgumentException($"Invalid file path argument `{projectFileOrSolution}`. The file path does not exists", nameof(projectFileOrSolution)); 38 | 39 | // Create our merged properties used later by msbuild 40 | var mergedProperties = new Dictionary {{"Configuration", configuration}, {"Platform", platform}}; 41 | // Allow passed properties to override configuration/platform 42 | if (properties != null) 43 | { 44 | foreach (var property in properties) 45 | { 46 | mergedProperties[property.Key] = property.Value; 47 | } 48 | } 49 | 50 | var inspector = new CSharpCompilationCapture(); 51 | return inspector.Build(projectFileOrSolution, mergedProperties); 52 | } 53 | 54 | private CSharpCompilationCaptureResult Build(string projectFileOrSolution, Dictionary properties) 55 | { 56 | // Create a bin log 57 | var tempBinLog = BuildBinLog(projectFileOrSolution, properties); 58 | 59 | // Read compiler invocations from the log 60 | var invocations = Microsoft.Build.Logging.StructuredLogger.CompilerInvocationsReader.ReadInvocations(tempBinLog); 61 | File.Delete(tempBinLog); 62 | 63 | // Create the workspace for all the projects 64 | var workspace = new AdhocWorkspace(); 65 | var projectToArgs = new Dictionary(); 66 | 67 | foreach (var compilerInvocation in invocations) 68 | { 69 | // We support only CSharp projects 70 | if (compilerInvocation.Language != Microsoft.Build.Logging.StructuredLogger.CompilerInvocation.CSharp) 71 | { 72 | continue; 73 | } 74 | 75 | // Rebuild command line arguments 76 | // Try to discard the exec name by going straight to the first csc parameter (assuming that we are using / instead of -) 77 | // TODO: very brittle, issue opened on StructuredLogger https://github.com/KirillOsenkov/MSBuildStructuredLog/issues/413 78 | var commandLineArgs = compilerInvocation.CommandLineArguments; 79 | var indexOfFirstOption = commandLineArgs.IndexOf(" /", StringComparison.Ordinal); 80 | if (indexOfFirstOption >= 0) 81 | { 82 | commandLineArgs = commandLineArgs.Substring(indexOfFirstOption + 1); 83 | } 84 | var args = ParseArguments(commandLineArgs); 85 | 86 | var projectName = Path.GetFileNameWithoutExtension(compilerInvocation.ProjectFilePath); 87 | var project = workspace.AddProject(projectName, LanguageNames.CSharp); 88 | 89 | project = GetCompilationOptionsAndFiles(project, compilerInvocation, args, out var csharpArguments); 90 | 91 | projectToArgs[project.Id] = csharpArguments; 92 | 93 | workspace.TryApplyChanges(project.Solution); 94 | } 95 | 96 | return new CSharpCompilationCaptureResult(workspace, projectToArgs); 97 | } 98 | 99 | /// 100 | /// Launch a dotnet msbuild /t:rebuild with the specified project and options 101 | /// 102 | /// The path to the binary log of msbuild. 103 | private static string BuildBinLog(string projectFileOrSolution, Dictionary properties) 104 | { 105 | var tempBinlogFilePath = Path.GetTempFileName() + ".binlog"; 106 | 107 | bool success = false; 108 | string errorMessage = null; 109 | 110 | Exception innerException = null; 111 | try 112 | { 113 | var argsBuilder = new StringBuilder($"msbuild /t:restore /t:rebuild /binaryLogger:{EscapeValue(tempBinlogFilePath)} /verbosity:minimal /nologo {EscapeValue(projectFileOrSolution)}"); 114 | // Pass all our user properties to msbuild 115 | foreach (var property in properties) 116 | { 117 | argsBuilder.Append($" /p:{property.Key}={EscapeValue(property.Value)}"); 118 | } 119 | 120 | var startInfo = new ProcessStartInfo("dotnet", argsBuilder.ToString()) 121 | { 122 | WorkingDirectory = Path.GetDirectoryName(projectFileOrSolution), 123 | CreateNoWindow = true, 124 | UseShellExecute = false, 125 | RedirectStandardOutput = true, 126 | RedirectStandardError = true 127 | }; 128 | var process = new Process() {StartInfo = startInfo}; 129 | //Console.WriteLine($"dotnet {startInfo.Arguments}"); 130 | 131 | var output = new StringBuilder(); 132 | process.OutputDataReceived += (_, e) => 133 | { 134 | if (!string.IsNullOrWhiteSpace(e.Data)) 135 | { 136 | output.AppendLine(e.Data); 137 | } 138 | }; 139 | 140 | process.ErrorDataReceived += (_, e) => 141 | { 142 | if (!string.IsNullOrWhiteSpace(e.Data)) 143 | { 144 | output.AppendLine(e.Data); 145 | } 146 | }; 147 | 148 | process.Start(); 149 | process.BeginOutputReadLine(); 150 | process.BeginErrorReadLine(); 151 | 152 | process.WaitForExit(); 153 | 154 | if (process.ExitCode != 0) 155 | { 156 | errorMessage = $"Unable to build {projectFileOrSolution}. Reason:\n{output}"; 157 | } 158 | else 159 | { 160 | success = true; 161 | } 162 | } 163 | catch (Exception ex) 164 | { 165 | errorMessage = $"Unexpected exceptions when trying to build {projectFileOrSolution}. Reason:\n{ex}"; 166 | innerException = ex; 167 | } 168 | 169 | if (!success) 170 | { 171 | File.Delete(tempBinlogFilePath); 172 | if (innerException != null) 173 | throw new InvalidOperationException(errorMessage, innerException); 174 | throw new InvalidOperationException(errorMessage); 175 | } 176 | 177 | return tempBinlogFilePath; 178 | } 179 | 180 | /// 181 | /// Creates a Project and collect CSharp arguments from a compiler invocation. 182 | /// 183 | private Project GetCompilationOptionsAndFiles(Project project, Microsoft.Build.Logging.StructuredLogger.CompilerInvocation invocation, List args, out CSharpCommandLineArguments arguments) 184 | { 185 | arguments = CSharpCommandLineParser.Default.Parse(args, invocation.ProjectDirectory, sdkDirectory: null); 186 | 187 | project = project.WithCompilationOptions(arguments.CompilationOptions); 188 | project = project.WithParseOptions(arguments.ParseOptions); 189 | project = project.WithMetadataReferences(arguments.MetadataReferences.Select(x => x.Reference).Select(GetOrCreateMetaDataReference)); 190 | 191 | foreach (var sourceFile in arguments.SourceFiles) 192 | { 193 | var filePath = sourceFile.Path; 194 | var name = filePath; 195 | if (name.StartsWith(invocation.ProjectDirectory)) 196 | { 197 | name = name.Substring(invocation.ProjectDirectory.Length); 198 | } 199 | // Set encoding to avoid running into CS8055 later (https://github.com/dotnet/roslyn/issues/43840) 200 | var document = project.AddDocument(name, SourceText.From(File.ReadAllText(filePath), Encoding.UTF8), filePath: filePath); 201 | project = document.Project; 202 | } 203 | 204 | return project; 205 | } 206 | 207 | /// 208 | /// Cache metadata references to avoid loading them between projects 209 | /// 210 | private MetadataReference GetOrCreateMetaDataReference(string file) 211 | { 212 | if (!_references.TryGetValue(file, out var meta)) 213 | { 214 | meta = AssemblyMetadata.CreateFromFile(file); 215 | _references.Add(file, meta); 216 | } 217 | return meta.GetReference(filePath: file); 218 | } 219 | 220 | /// 221 | /// Collect compiler arguments in a list from the specified string. 222 | /// 223 | private static List ParseArguments(string commandLineArguments) 224 | { 225 | var args = new List(); 226 | var arg = new StringBuilder(); 227 | for (var i = 0; i < commandLineArguments.Length; i++) 228 | { 229 | var c = commandLineArguments[i]; 230 | if (char.IsWhiteSpace(c)) continue; 231 | arg.Length = 0; 232 | for(; i < commandLineArguments.Length; i++) 233 | { 234 | c = commandLineArguments[i]; 235 | if (c == '"') 236 | { 237 | bool previousIsEscape = false; 238 | bool argFlush = false; 239 | arg.Append('"'); 240 | for (i++; i < commandLineArguments.Length; i++) 241 | { 242 | c = commandLineArguments[i]; 243 | arg.Append(c); 244 | if (!previousIsEscape && c == '"') 245 | { 246 | argFlush = true; 247 | break; 248 | } 249 | 250 | if (!previousIsEscape && c == '\\') 251 | { 252 | previousIsEscape = true; 253 | } 254 | else 255 | { 256 | previousIsEscape = false; 257 | } 258 | } 259 | 260 | if (argFlush) break; 261 | throw new InvalidOperationException($"Invalid string `{arg}` non terminated by a closing `\"`"); 262 | } 263 | else if (char.IsWhiteSpace(c)) 264 | { 265 | break; 266 | } 267 | else 268 | { 269 | arg.Append(c); 270 | } 271 | } 272 | 273 | args.Add(arg.ToString()); 274 | } 275 | return args; 276 | } 277 | 278 | private static readonly Regex MatchWhitespace = new Regex(@"[\s\:]"); 279 | 280 | private static string EscapeValue(string path) 281 | { 282 | path = path.Replace("\"", "\\\""); 283 | return MatchWhitespace.IsMatch(path) ? $"\"{path}\"" : path; 284 | } 285 | } 286 | } --------------------------------------------------------------------------------