Giter Site home page Giter Site logo

unoplatform / uno.sourcegeneration Goto Github PK

View Code? Open in Web Editor NEW
129.0 34.0 11.0 13.61 MB

A Roslyn based C# source generation framework

License: Other

C# 98.00% Batchfile 0.02% PowerShell 1.96% F# 0.02%
csharp roslyn generator visual-studio msbuild

uno.sourcegeneration's Introduction

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.

The Uno Source Generator also supports the Roslyn 3.8 (C# 9.0) Source Generator APIs, see below for more details. Note that as of Roslyn 3.8, generators do not support multi-pass generation where generators can depend on each others. In order to benefit from this feature, a generator must run using Uno.SourceGenerationTasks.

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, macOS and Linux builds are supported. Building for .NET Core requires .NET 3.0.100 or later.

Build status

Target Branch Status
development master Build Status

Nuget Packages

Package nuget.org usage
Uno.SourceGeneration NuGet Use this package to create a generator
Uno.SourceGenerationTasks NuGet Use this package to use a generator

Experimental packages are available through this NuGet feed: https://pkgs.dev.azure.com/uno-platform/Uno%20Platform/_packaging/unoplatformdev/nuget/v3/index.json

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.

    1. 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.

    1. 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.

    2. Add the following property:

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

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

Creating a C# 9.0 compatible generator

Based on C# 9.0 generators the bootstrapper defines a set of APIs that are compatible with Roslyn.

Here's a roslyn compatible generator:

[Generator]
public class CustomGenerator : ISourceGenerator
{
    public void Initialize(GeneratorInitializationContext context) {}

    public void Execute(GeneratorExecutionContext context)
    {
        context.AddSource("myGeneratedFile.cs", @"
namespace GeneratedNamespace
{
    public class GeneratedClass
    {
        public static void GeneratedMethod()
        {
            // generated code
        }
    }
}");
    }
}

Uno also provides a set of methods giving access to the MSBuild properties and items, compatible Uno's source generation tasks:

public void Execute(GeneratorExecutionContext context)
{
	var myProperty = context.GetMSBuildPropertyValue("MyTestProperty");

    var myItems = context.GetMSBuildPropertyValue("GetMSBuildItems").Select(i => i.Identity);
}

Note that the a generator running under Uno.SourceGenerationTasks does not need to define in MSBuild which properties need to be used, whereas C# 9.0 requires it.

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

Logging to build output

You can write to build output using the following code:

    public override void Execute(SourceGeneratorContext context)
    {
        var logger = context.GetLogger(); // this is an extension method on SourceGeneratorContext

        // Log something to build output when the mode is "detailed".
        logger.Debug($"The current count is {count}");

        // Log something to build output when the mode is "normal".
        logger.Info($"A total of {filesCount} has been generated.");

        // Log something as warning in build output.
        logger.Warn($"No code generated because the mode is {currentMode}.");

        // Log something as error in build output.
        logger.Error($"Unable to open file {filename}. No code generated.");
    }

Available Properties

The source generation task provides set of properties that can alter its behavior based on your project.

UnoSourceGeneratorAdditionalProperty

The UnoSourceGeneratorAdditionalProperty item group provides the ability for a project to enable the propagation of specific properties to the generators. This may be required if properties are injected dynamically, or provided as global variables.

A good example of this is the JavaSdkDirectory that is generally injected as a global parameter through the msbuild command line.

In such as case, add the following in your project file:

<ItemGroup>
    <UnoSourceGeneratorAdditionalProperty Include="JavaSdkDirectory" />
</ItemGroup>

In this case, the JavaSdkDirectory value will be captured in the original build environment, and provided to the generators' build environment.

Troubleshooting

Error: Failed to analyze project file ..., the targets ... failed to execute.

This is issue is caused by a open Roslyn issue for which all projects of the solution must have all the possible "head" projects configuration.

For instance, if you are building a UWP application, all the projects in the solution must have the 10.0.xxx target framework defined, even if netstandard2.0 would have been enough.

Generation output

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.

The source generation target can also optionally produces binlog file in the obj folder, used to troubleshoot issues with the msbuild instance created inside the application domain used to generate the code. The path for those files can be altered using the UnoSourceGeneratorBinLogOutputPath msbuild property. In the context of a VSTS build, setting it to $(build.artifactstagingdirectory) allows for an improved diagnostics experience. Set the UnoSourceGeneratorUnsecureBinLogEnabled property to true to enabled binary logging.

Important: The binary logger may leak secret environment variables, it is a best practice to never enable this feature as part of normal build.

My build ends with error code 3

By default, in some cases, the source generation host will run into an internal error, and will exit without providing details about the generation error.

To enable the logging of these errors, add the following property to your project:

<UnoSourceGeneratorCaptureGenerationHostOutput>true</UnoSourceGeneratorCaptureGenerationHostOutput>

The errors will the be visible when the build logging output is set to detailed, or by using the binary logger.

Have questions? Feature requests? Issues?

Make sure to visit our StackOverflow, create an issue or visit our gitter.

Upgrade notes

earlier versions to 1.29

A breaking change has been introduced to support proper UWP head projects, and when upgrading to Uno.SourceGenerationTasks 1.29 or later you will have to search for projects that contain the uap10.0 target framework and do the following:

  • Update to the MSBuild.Sdk.Extras 1.6.65 or later
  • Choose an UWP sdk version, and use the appropriate target framework (e.g. uap10.0 to uap10.0.16299)

uno.sourcegeneration's People

Contributors

agneszitte avatar arnaudrivard avatar carldebilly avatar ebariche avatar jeremiethibeault avatar jeromelaban avatar matfillion avatar nventive-devops avatar spouliot avatar xiaoy312 avatar youssef1313 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

uno.sourcegeneration's Issues

Can't use System.Text.Json or resolve types from Microsoft.Bcl.AsyncInterfaces

I'm trying to use System.Text.Json in a WASM project, but I have the following error at runtime.

Could not load signature of System.Text.Json.Serialization.JsonConverter`1[T]:Write due to: Could not load file or assembly 'Microsoft.Bcl.AsyncInterfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies.

It appears that System.Text.Json has a dependency to Microsoft.Bcl.AsyncInterfaces.

If I add an explicit reference to Microsoft.Bcl.AsyncInterfaces and try to resolve any of its types (e.g. IAsyncDisposable) , the WASM app stops working the moment I resolve the type.

Steps to reproduce the issue:

  1. Add a reference to Microsoft.Bcl.AsyncInterfaces.
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="1.0.0" />
  1. In the Main method of Program.cs of Uno.Wasm.Sample, have the following code.
static void Main(string[] args)  
{
    Console.WriteLine($"Mono Runtime Mode: " + Environment.GetEnvironmentVariable("UNO_BOOTSTRAP_MONO_RUNTIME_MODE"));

    var i = 42; 
    var now = DateTime.Now.ToString();
    Console.WriteLine($"Main! {i} {now}");

    try
    {
        Console.WriteLine("Getting type from Microsoft.Bcl.AsyncInterfaces");
        var t = typeof(IAsyncDisposable);
        Console.WriteLine("Success!");
    }
    catch (Exception e)
    {
        Console.WriteLine("Something went wrong!" + e.Message);
    }
}
  1. Run the app and observe that in the console you get "Getting type from Microsoft.Bcl.AsyncInterfaces" but not "Success!" nor the "Something went wrong" message. There is no error in the output, it simply breaks.

Add the netstandard2.0 target

I'm submitting a...

Feature request

Current behavior

It works both with .NET Framework and .NET Core but I keep getting this message:

warning NU1701: Package 'Uno.SourceGeneration 3.0.0-dev.10' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.

Expected behavior

Can you add the netstandard2.0 target?

Minimal reproduction of the problem with instructions

Environment

Nuget Package: 
Uno.SourceGeneration
Package Version(s): 
3.0.0-dev.10
Affected platform(s):
- [ ] iOS
- [ ] Android
- [ ] WebAssembly
- [x ] Windows
- [ ] Build tasks

Visual Studio
- [x ] 2019 (version: )
- [ ] 2017 (version: )
- [ ] 2017 Preview (version: )
- [ ] for Mac (version: )

Relevant plugins
- [ ] Resharper (version: )

Source Generation fails for systems having the environment variable Platform set to MCD

On some systems built using system builder, the environment variable Platform set to MCD. This is known to break some configurations, particularly android projects.

This issue is related to the override of msbuild variables that may fail the generation:

https://github.com/nventive/Uno.SourceGeneration/blob/1980377325022332615814ff0634f8997c3f493c/src/Uno.SourceGenerationHost.Shared/ProjectLoader.cs#L110

Which means that the global variable must not be set in order for the build to run properly.

See this for more info.

[FEAT] Add ViewBase generation

What would you like to be added:

I was trying to implement a SourceGenerator that automatically generates ViewBase classes for all views in a project.

As a result, I ran into a limitation where SourceGenerator from Uno is not able to find the code from my generator. It seems to me that at the moment this is an insurmountable obstacle for SourceGenerators.

1>CSC : error UXAML0001: The type {using:Dedoose.Views}NavigationViewBase could not be found
1>CSC : error UXAML0001: Processing failed for file C:\Users\haven\source\repos\DedooseV2\Dedoose.Apps\src\shared\Dedoose.Apps.Uno.Shared\Views\Navigation\NavigationView.xaml (System.InvalidOperationException: The type {using:Dedoose.Views}NavigationViewBase could not be found

But this can be done within the Uno generator.

At the moment, using my generator looks like this:

  <ViewBaseGenerator_Namespace>Dedoose.Views</ViewBaseGenerator_Namespace>

  <ItemGroup Label="ViewBase">
    <AdditionalFiles Include="..\..\shared\Dedoose.Apps.Shared\Views\**\*.xaml.cs" ViewBaseGenerator_BaseClass="ReactiveUI.Uno.ReactiveUserControl" ViewBaseGenerator_ViewModelNamespace="Dedoose.ViewModels" Visible="False" />
    <!-- Exclude ReactivePage view -->
    <AdditionalFiles Remove="..\..\shared\Dedoose.Apps.Shared\Views\Navigation\MainView.xaml.cs" />
  </ItemGroup>

It generates this code:

namespace Dedoose.Views
{

    public abstract partial class NavigationViewBase
       : ReactiveUI.Uno.ReactiveUserControl<Dedoose.ViewModels.NavigationViewModel>
    {
    }

   //...
}

Generator repository: https://github.com/HavenDV/ViewBaseGenerator/

Why is this needed:

To remove boilerplate code

For which Platform:

All

Reason behind choosing net 462

The uno.sourcegeneration.1.29.0-dev.161 is using net46 & uno.sourcegeneration.1.29.0-dev.178 is using net 462 )-:
If you need .net standard 2.0 support, then you can use net461
Could you please do something for this too?
Thanks in advance.

[NET5] dotnet build failure under macOS and Linux

I'm submitting a...

  • Bug report (I searched for similar issues and did not find one)

Current behavior

Building using SourceGenerators and .NET 5 Preview 5.0.100-preview.3.20216.6.

Expected behavior

Build succeeds.

Minimal reproduction of the problem with instructions

Build under Linux or macos.

Environment

Nuget Package: 

Package Version(s): 

Affected platform(s):
- [ ] iOS
- [ ] Android
- [ ] WebAssembly
- [ ] Windows
- [x] Build tasks

Visual Studio
- [ ] 2017 (version: )
- [ ] 2017 Preview (version: )
- [ ] for Mac (version: )

Relevant plugins
- [ ] Resharper (version: )

Support .NET Core 3.1.201 (and .NET 5)

I'm submitting a...

Feature request

Current behavior

When using .NET 5.0 Preview 1, results in the error:

/Users/antao.almada/.nuget/packages/uno.sourcegenerationtasks/2.0.0-dev.308/build/netstandard1.0/Uno.SourceGenerationTasks.targets(127,2): error : Exec format error [/Users/antao.almada/Projects/NetFabric.Hyperlinq/NetFabric.Hyperlinq/NetFabric.Hyperlinq.csproj]

Expected behavior

Minimal reproduction of the problem with instructions

Install .NET 5.0 Preview 1 and compile the generator project.

Environment

Nuget Package: 
`Uno.SourceGeneration`

Package Version(s): 
`2.0.0-dev.308`

Affected platform(s):
- [ ] iOS
- [ ] Android
- [ ] WebAssembly
- [ ] Windows
- [ x] Build tasks

Visual Studio
- [ ] 2017 (version: )
- [ ] 2017 Preview (version: )
- [ ] for Mac (version: )
- [x] .NET CLI

Relevant plugins
- [ ] Resharper (version: )

Are netstandard2.1 or netcoreapp3.1 supported for source generator projects?

I've just started to use this project for some basic source generation tasks, and after a lot of trial and error I have it set up and working. All my projects that will consume the source generators are netcoreapp3.1 projects, but the source generator project itself doesn't seem to want to play ball if I set the target framework to netstandard2.1 or netcoreapp3.1. net48 and netstandard2.0 work, and I settled on netstandard2.0 for now.

I don't technically need anything higher since the source generator project is fairly small and simple, but it would be nice to have some of the newer .NET Core 3.x features. Is this not currently possible, or am I missing something? I've searched through the issues, looked at the source code, looked at other projects, and I can't find any indication as to whether this is supported or not.

Build error when creating source generator for iOS/macOS

Current behavior

When creating a blank Uno app with a simple source generator, and referencing it under all heads, the macOS and iOS builds fail with the error message:

"C:\Users\agodfrey\source\repos\test\SourceGeneratorErrorMacOSiOS\SourceGeneratorErrorMacOSiOS.sln" (default target) (1:2) ->
"C:\Users\agodfrey\source\repos\test\SourceGeneratorErrorMacOSiOS\SourceGeneratorErrorMacOSiOS.iOS\SourceGeneratorErrorMacOSiOS.iOS.csproj" (default target) (3:6) ->
(_UnoSourceGenerator target) ->
  MSBUILD : error : Failed to read [C:\Users\agodfrey\source\repos\test\SourceGeneratorErrorMacOSiOS\SourceGenerator\bin\iPhone\Debug\netstandard2.0\SourceGenerator.dll], Could not find a part of the path 'C:\Users 
\agodfrey\source\repos\test\SourceGeneratorErrorMacOSiOS\SourceGenerator\bin\iPhone\Debug\netstandard2.0\SourceGenerator.dll'. [C:\Users\agodfrey\source\repos\test\SourceGeneratorErrorMacOSiOS\SourceGeneratorErrorM 
acOSiOS.iOS\SourceGeneratorErrorMacOSiOS.iOS.csproj]


torErrorMacOSiOS.macOS\SourceGeneratorErrorMacOSiOS.macOS.csproj" (default target) (6:6) ->                                   MSBUILD : error : Failed to read [C:\Users\agodfrey\source\repos\test\SourceGeneratorErrorMacOSiOS\SourceGentorErrorMacOSiOS.macOS\SourceGeneratorErrorMacOSiOS.macOS.csproj" (default target) (6:6) ->  MSBUILD : error : Failed to read [C:\Users\agodfrey\source\repos\test\Source  MSBUILD : error : Failed to read [C:\Users\agodfrey\source\repos\test\SourceGeneratorErrorMacOSiOS\SourceGenerator\bin\iPhoneSimulator\Debug\netstandard2.0\SourceGenerator.dll], Could not find a part of the path'C:\Users\agodfrey\source\repos\test\SourceGeneratorErrorMacOSiOS\SourceGenerator\bin\iPhoneSimulator\Debug\netstandard2.0\SourceGenerator.dll'. [C:\Users\agodfrey\source\repos\test\SourceGeneratorErrorMacOSiOS\SourceGeneratorErrorMacOSiOS.macOS\SourceGeneratorErrorMacOSiOS.macOS.csproj] 

No other project heads have this issue.

Expected behavior

All project heads should build successfully

How to reproduce it (as minimally and precisely as possible)

  1. Download and unzip this premade solution:
    SourceGeneratorErrorMacOSiOS.zip

  2. In a terminal, run msbuild -r. Observe the error message.

  3. Open "SourceGeneratorErrorMacOSiOS.iOS.csproj" and "SourceGeneratorErrorMacOSiOS.macOS.csproj" and on line 5, remove the text OutputItemType="Analyzer" ReferenceOutputAssembly="true" from the source generator's project reference.

  4. Run msbuild -r again. The build is successful.

Workaround

Unknown

Works on UWP/WinUI

Yes

Environment

No response

NuGet package version(s)

No response

Affected platforms

iOS, macOS

IDE

No response

IDE version

No response

Relevant plugins

No response

Anything else we need to know?

You may need to delete all bin/obj folders between builds if using MSBuild 17.0.

System.MissingMethodException on simple source generator

I started writing a simple NullParamaterCheck source generator, but I have the following exception when my test project builds (the project which is using the generator):

Generation failed for MyNamespace.NullParameterCheckAspect. System.MissingMethodException: Method not found: 'Microsoft.CodeAnalysis.Compilation Uno.SourceGeneration.SourceGeneratorContext.get_Compilation()'.
at MyNamespace.NullParameterCheckAspect.Execute(SourceGeneratorContext context)
at Uno.SourceGeneration.Host.SourceGeneratorHost.<>c__DisplayClass2_0.b__13(ValueTuple`2 generatorDef) in C:\projects\uno-sourcegeneration\src\Uno.SourceGenerationHost.Shared\SourceGeneratorHost.cs:line 155 MyNamespace.Tests C:\Git\MyNamespace\solution\packages\Uno.SourceGenerationTasks\build\net45\Uno.SourceGenerationTasks.targets 101

I'm using paket for package management and am currently using version 1.26 of your library, currently struggling to get a prerelease version...

Using VS2017 15.8.4 and projects which target 4.6.2

The start of the generator looks like that:

public override void Execute(SourceGeneratorContext context)
{
var logger = context.GetLogger();
var compilation = context.Compilation;

If i remove var compilation = context.Compilation; I can successfully log to the build output.

Is this known, am I doing something wrong?

Not able to build using dotnet CLI; Uno.SourceGenerationTasks.targets exception.

I'm trying to build a netstandard2.0 class library which makes use of Uno.Immutables 1.23 and Uno.CodeGen 1.23 in order to generate at build time the immutable classes.

First thing I noticed is the NU1701 warning about the Uno.SourceGenerationTasks being restored using net461 instead of netstandard2.0....

Package 'Uno.SourceGenerationTasks 1.21.0' was restored using '.NETFramework,Version=v4.6.1' instead of the project target framework '.NETStandard,Version=v2.0'. This package may not be fully compatible with your project.

At this point, I can still disable this warning and build the project within VS 2017 (v 15.7.5), however any attempt to build it using the dotnet CLI fails...

....nuget\packages\uno.sourcegenerationtasks\1.21.0\build\net45\Uno.SourceGenerationTasks.targets(94,3): error : Could not load type 'System.Runtime.Remoting.RemotingException' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. [F:\Tests\codegen\codegen\codegen.csproj]
0 Warning(s)
1 Error(s)

The very same issue, minus the warning obviously, happens if I target net461 instead of netstandard2.0.

Attached to this issue is a solution contaning two projects, one targetting netstandard2.0, the other net461 from which the issue is easy to reproduce.

codegen.zip

Uno.SourceGeneration.Host.exe stay open after Visual Studio closed

Current behavior

immagine

Expected behavior

Uno.SourceGeneration.Host.exe end after Visual Studio closed

How to reproduce it (as minimally and precisely as possible)

No response

Workaround

No response

Works on UWP/WinUI

None

Environment

Uno.SourceGenerationTasks

NuGet package version(s)

No response

Affected platforms

Build tasks

IDE

Visual Studio 2022

IDE version

17.5.3

Relevant plugins

No response

Anything else we need to know?

No response

Codegen in a solution

I'm submitting a...

Sample app request

Current behavior

I'm trying to setup code generation in one of my open-source projects. It contains a main project that is distributed as a NuGet package. I just want to generate code in the main project, using my own generator, before it's packaged.

Expected behavior

I've read the README and the source of Uno.CodeGen multiple times and I still can't figure it out. The targets and the dependencies do not make sense to me.

Sorry to be asking this but honestly, I researched as much as I could...

Minimal reproduction of the problem with instructions

Environment

Nuget Package: 

Package Version(s): 
1.32.0

Affected platform(s):
- [ ] iOS
- [ ] Android
- [ ] WebAssembly
- [x] Windows
- [x] macOS
- [x] Build tasks

Visual Studio
- [x] 2019 (version: Enterprise 16.5.0 Preview 1.0)
- [x] Code (version: 1.41.0)
- [ ] 2017 Preview (version: )
- [ ] for Mac (version: )

Relevant plugins
- [ ] Resharper (version: )

Add support for persistent Generation Host

I'm submitting a...

  • Feature request

Current behavior

The new Hosted Generation mode that uses out-of-process generation re-parses projects on each build, which can take a significant amont of build time.

It is important that a persistent process, such as "VBCSCompiler.exe" can stay in memory for as long as the msbuild processes that use it are running, so the parsed projects are kept in memory.

This feature is already implemented with the in-process model, via the reuse of AppDomains.

Project gets built using Visual Studio, but dotnet build results into an error

I'm submitting a...

  • Bug report (I searched for similar issues and did not find one)

Current behavior

There is a sample project attached to this issue. I can build that project using visual studio, but when I run dotnet build in command line, I receive following error:

uno.sourcegenerationtasks\1.28.0-dev.145\build\net45\Uno.SourceGenerationTasks.targets(100,4): error : Generation failed, error code -2147450740

image
UnoSourceGenerationIssueRepo.zip

Expected behavior

Project gets build as like as Visual Studio's build.

Minimal reproduction of the problem with instructions

Extract the repo and build that.

Environment

Nuget Package: 1.28.0-dev.145

Affected platform(s):
- [X] Build tasks

Visual Studio
- [X] 2017 (version: 15.8.5)

DotNet Core SDK 2.1.402

You can also have a look at my source code generator's codes here.

Random Uno.SourceGenerationTasks.targets: error : Error reading response

I'm submitting a...

  • Bug report

Current behavior

Source generation randomly fails with a message similar to this one:

Uno.SourceGenerationTasks.targets: error : Error reading response

Expected behavior

Generation does not fail.

Addtional details

For some unknown reason, the generation host crashes, resulting in this error. It sometimes can fail with an ExecutionEngineException.

Document which version of the package to use for each Visual Studio version

I'm submitting a...

  • Documentation request

Current behavior

It's hard to know which version to use.

Expected behavior

  • There should be a table (ideally in readme.md) mapping the major releases with their associated Visual Studio version(s).
  • It would be good for that table to be visible from nuget.org too.

Add support for uap10.0.xxx in source generation tasks

I'm submitting a...

  • Feature request

Current behavior

Creating a library using :

<Project Sdk="MSBuild.Sdk.Extras/1.6.46">
<PropertyGroup>
 <TargetFrameworks>uap10.0.16299</TargetFrameworks>

fails to build when including the source generation tasks package:

C:\...\1.28.0\build\uap\Uno.SourceGenerationTasks.targets(100,4): error : [Failure] Msbuild failed when processing the file 'E:\...\ClassLibraryUno.csproj' with message: C:\Program Files\dotnet\sdk\2.1.500\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets: (198, 5): Assets file 'E:\...\ClassLibraryUno\obj\project.assets.json' doesn't have a target for 'UAP,Version=v10.0'. Ensure that restore has run and that you have included 'uap10.0' in the TargetFrameworks for your project.

Expected behavior

A project with the above definition builds.

Workaround

Change uap10.0.16299 to uap10.0, and set those two properties instead:

<TargetPlatformVersion>10.0.16299.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.16299.0</TargetPlatformMinVersion>

Generators assembly needs at least one generator deriving directly from SourceGenerator to execute

Steps to reproduce :

  1. Create a project A with an abstract generator GenA deriving from SourceGenerator
  2. Create a project B, referencing project A and create a generator GenB deriving deriving from GenA
  3. Try to run GenB in a project, the Uno.SourceGeneratorTasks won't see any useful generators to run.
  4. Add a generator GenC diriving directly from SoureGenerator into Project B.
  5. Both GenB and GenC will execute correctly.

Generation may fail for Xamarin.Android projects on Azure Devops hosted agents

When building an Xamarin.Android project on Azure Devops, setting the JavaSdkDirectory property is required, as the environment variable has no effect.

This property is not propagated to the Uno.SourceGeneration build context, making the generation fail.

Workaround

Create or update a Directory.Build.props file with this content:

<Project>
 <PropertyGroup>
   <JavaSdkDirectory Condition="'$(JavaSdkDirectory)'=='' and '$(JAVA_HOME_8_X64)'!=''">$(JAVA_HOME_8_X64)</JavaSdkDirectory>
 </PropertyGroup>
</Project>

Remoting timeout using remotable logger

The following error sporadically happens when building on a heavily loaded build machine :

2018-07-06T14:14:58.2972521Z ##[error]Agent01\358\.nuget\uno.sourcegenerationtasks\1.22.0\build\MonoAndroid\Uno.SourceGenerationTasks.targets(98,4): Error : Generation failed for Uno.UI.SourceGenerators.XamlGenerator.XamlCodeGenerator. System.AggregateException: An error occurred while writing to logger(s). ---> System.Runtime.Remoting.RemotingException: Object '/3011ddec_8e68_49d3_95a0_e339e9cb548f/4editpvjty4l6fc76dzgfnxk_43.rem' has been disconnected or does not exist at the server.
   at Uno.SourceGeneratorTasks.Logger.RemotableLogger2.WriteLog(Int32 logLevel, String message)
   at Uno.SourceGeneratorTasks.Logger.RemoteLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) in C:\projects\uno-sourcegeneration\src\Uno.SourceGeneratorTasks.Shared\Logger\RemoteLogger.cs:line 71
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   --- End of inner exception stack trace ---
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   at Microsoft.Extensions.Logging.Logger`1.Microsoft.Extensions.Logging.ILogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
   at Uno.SourceGeneratorTasks.Helpers.LogExtensions.Debug(ILogger log, String message, Exception exception) in C:\projects\uno-sourcegeneration\src\Uno.SourceGeneratorTasks.Shared\Helpers\LogExtensions.cs:line 94
   at Uno.SourceGeneration.Host.SourceGeneratorHost.<>c__DisplayClass2_0.<Generate>b__13(ValueTuple`2 generatorDef) in C:\projects\uno-sourcegeneration\src\Uno.SourceGenerationHost.Shared\SourceGeneratorHost.cs:line 150
---> (Inner Exception #0) System.Runtime.Remoting.RemotingException: Object '/3011ddec_8e68_49d3_95a0_e339e9cb548f/4editpvjty4l6fc76dzgfnxk_43.rem' has been disconnected or does not exist at the server.
   at Uno.SourceGeneratorTasks.Logger.RemotableLogger2.WriteLog(Int32 logLevel, String message)
   at Uno.SourceGeneratorTasks.Logger.RemoteLogger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter) in C:\projects\uno-sourcegeneration\src\Uno.SourceGeneratorTasks.Shared\Logger\RemoteLogger.cs:line 71
   at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)

Add support for msbuild 16.0 / VS Mac 8.0 Preview

I'm submitting a...

  • Feature request

Forwarded from #62

Current behavior

Building for using msbuild 16.0 / VS for Mac 8.0 Preview produces the following error :

~/.nuget/packages/uno.sourcegenerationtasks/1.29.0-dev.195/build/netstandard1.0/Uno.SourceGenerationTasks.targets(99,4): error : System.TypeLoadException: Could not set up field 'Statement' due to: Could not load type of field 'Microsoft.CodeAnalysis.SQLite.Interop.SqlStatement:_rawStatement' (1) due to: Could not load file or assembly 'SQLitePCLRaw.core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1488e028ca7ab535' or one of its dependencies. assembly:~/.nuget/packages/uno.sourcegenerationtasks/1.29.0-dev.195/build/Dev15.0/Microsoft.CodeAnalysis.Workspaces.Desktop.dll type:SqlStatement member:(null) [~/SampleApp/SampleApp.csproj]

Expected behavior

A build works properly.

Minimal reproduction of the problem with instructions

Build any Uno.UI base sample using Source Generations >= 1.29.0-dev.195.

Workaround

Fixing this issue can be done by adding <UnoSourceGeneratorUseGenerationHost>true</UnoSourceGeneratorUseGenerationHost> to the iOS/macOS csproj files.

Environment

Nuget Package: 1.29.0-dev.195

Package Version(s): 

Affected platform(s):
- [x] iOS
- [x] macOS
- [ ] Android
- [ ] WebAssembly
- [ ] Windows
- [ ] Build tasks

Visual Studio
- [ ] 2017 (version: )
- [ ] 2017 Preview (version: )
- [x] for Mac (version: 8.0)

Relevant plugins
- [ ] Resharper (version: )

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.