A Roslyn based C# source generation framework
Перейти к файлу
Jérôme Laban 1accbe1b47 Use nuget reference for addins 2018-02-27 09:42:37 -05:00
build Use nuget reference for addins 2018-02-27 09:42:37 -05:00
doc Initial commit 2018-01-12 09:27:48 -05:00
samples/Basic Initial commit 2018-01-12 09:27:48 -05:00
src Fix clean target is not cleaning intermediate folders 2018-02-21 10:09:54 -05:00
.appveyor.yml Adjust build definition 2018-02-01 11:41:13 -05:00
.gitattributes Initial commit 2018-01-12 09:27:48 -05:00
.gitignore Added new SourceGeneratorDependencyAttribute 2018-01-25 14:46:26 -05:00
License.md Initial commit 2018-01-12 09:27:48 -05:00
gitversion.yml Bump Version after Release S2 2018-02-26 11:58:15 -05:00
readme.md Changed the naming for generator depencies. 2018-02-07 12:58:46 -05:00

readme.md

Uno SourceGenerator

The Uno source generator is an API compatible source generator inspired by Roslyn v2.0 source generation feature, and an msbuild task which executes the SourceGenerators.

It provides a way to generate C# source code based on a project being built, using all of its syntactic and semantic model information.

Using this generator allows for a set of generators to share the same Roslyn compilation context, which is particularly expensive to create, and run all the generators in parallel.

The Uno.SourceGeneratorTasks support updating generators on the fly, making iterative development easier as visual studio or MSBuild will not lock the generator's assemblies.

The Uno.SourceGeneratorTasks support any target framework for code generation, though there are limitations when using a mixed targetframeworks graph, such as generating code in a net47 project that references a netstandard2.0 project. In such cases, prefer adding a net47 target instead of targeting netstandard2.0.

Visual Studio 2017 15.3+ for Windows and macOS are supported.

Build status

Target Branch Status Recommended Nuget packages version
development master Build status NuGet NuGet

Creating a Source Generator

  1. In Visual Studio 2017, create a .NET Standard Class Library project named MyGenerator

  2. In the csproj file

    1. Change the TargetFramework to net46
    2. Add a package reference to Uno.SourceGeneration (take the latest version)
    <ItemGroup>
    	<PackageReference Include="Uno.SourceGeneration" Version="1.5.0" />
    </ItemGroup>
    
  3. Add a new source file containing this code :

    using System;
    using Uno.SourceGeneration;
    
    namespace MyGenerator
    {
    	public class MyCustomSourceGenerator : SourceGenerator
    	{
    		public override void Execute(SourceGeneratorContext context)
    		{
    			var project = context.GetProjectInstance();
    
    			context.AddCompilationUnit("Test", "namespace MyGeneratedCode { class TestGeneration { } }");
    		}
    	}
    }
    

    Note that the GetProjectInstance is a helper method that provides access to the msbuild project currently being built. It provides access to the msbuild properties and item groups of the project, allowing for fine configuration of the source generator.

  4. Create a file named MyGenerator.props (should be the name of your project + .props) in a folder named build and set its Build Action to Content. Put the following content:

    <Project>
    	<ItemGroup>
    		<SourceGenerator Include="$(MSBuildThisFileDirectory)..\bin\$(Configuration)\net46\MyGenerator.dll" 
    				 Condition="Exists('$(MSBuildThisFileDirectory)..\bin')" />
    		<SourceGenerator Include="$(MSBuildThisFileDirectory)..\tools\MyGenerator.dll" 
    				 Condition="Exists('$(MSBuildThisFileDirectory)..\tools')" />
    	</ItemGroup>
    </Project>
    

Using the generator inside the same solution (another project)

  1. In Visual Studio 2017, create a .NET Standard Class Library project named MyLibrary. This is the project where your generator will do its generation.
  2. In the .csproj file:
    1. Change the TargetFramework to net46 (.Net Framework v4.6)
    2. Add a package reference to Uno.SourceGenerationTasks
      <ItemGroup>
         <PackageReference Include="Uno.SourceGenerationTasks" Version="1.5.0" />
      </ItemGroup>
      

      *You can also use the Nuget Package Manager to add this package reference. The version can differ, please use the same than the generator project.

    3. Import the source generator by placing the following line at the end :
      <Import Project="..\MyGenerator\build\MyGenerator.props" />
      
  3. Add some C# code that uses the MyGeneratedCode.TestGeneration class that the generator creates.
  4. Compile... it should works.
  5. You can sneak at the generated code by clicking the Show All Files button in the Solution Explorer. The code will be in the folder obj\<config>\<platform>\g\<generator name>\.

Packaging the source generator in NuGet

Packaging the generator in nuget requires to :

  1. In the csproj file containing your generator:
    1. Add this group to your csproj:

      <ItemGroup>
        <Content Include="build/**/*.*">
          <Pack>true</Pack>
          <PackagePath>build</PackagePath>
        </Content>
      </ItemGroup>
      
      

      Note that the name of this file must match the package name to be taken into account by nuget.

    2. Update the package references as follows

      <ItemGroup>
        <PackageReference Include="Uno.SourceGeneration" Version="1.19.0-dev.316" PrivateAssets="All" />
        <PackageReference Include="Uno.SourceGenerationTasks" Version="1.19.0-dev.316" PrivateAssets="None" />
      </ItemGroup>
      

      This ensure that the source generator tasks will be included in any project referencing your new generator, and that the source generation interfaces are not included.

      *You can also use the Nuget Package Manager to add this package reference. The version can differ, please take the latest stable one.

    3. Add the following property:

      <PropertyGroup>
        <IsTool>true</IsTool>
      </PropertyGroup>
      

      This will allow for the generator package to be installed on any target framework.

Debugging a generator

In your generator, add the following in the SourceGenerator.Execute override :

Debugger.Launch();

This will open another visual studio instance, and allow for stepping through the generator's code.

General guidelines for creating generators

  • Generators should have the least possible external dependencies. Generators are loaded in a separate AppDomain but multiple assemblies versions can be troublesome when loaded side by side.

  • You can add a dependency on your generator by adding the Uno.SourceGeneration.SourceGeneratorDependency attribute on your class:

    [GenerateAfter("Uno.ImmutableGenerator")] // Generate ImmutableGenerator before EqualityGenerator
    public class EqualityGenerator : SourceGenerator
    

    For instance here, it will ensure that the ImmutableGenerator is executed before your EqualityGenerator. If you don't declare those dependencies, when a project is loaded to be analyzed, all generated files from a generator are excluded from the roslyn Compilation object of other generators, meaning that if two generators use the same conditions to generate the same code, there will be a compilation error in the resulting code.

  • You can also define a generator which must be executed after yours. To do this, you need to declare a dependent generator:

    [GenerateBefore("Uno.EqualityGenerator")] // Generate ImmutableGenerator before EqualityGenerator
    public class ImmutableGenerator : SourceGenerator
    
  • Sometimes you may need to kill all instances of MsBuild. On Windows, the fatest way to to that is to open a shell in admin mode and type this line:

    taskkill /fi "imagename eq msbuild.exe" /f /t
    

Troubleshooting

The source generator provides additional details when building, when running the _UnoSourceGenerator msbuild target.

To view this information either place visual studio in details verbosity (Options, Projects and Solutions, Build and Run then MSBuild project build output verbosity) or by using the excellent MSBuild Binary and Structured Log Viewer from Kirill Osenkov.