AArnott / CodeGeneration.Roslyn

Assists in performing Roslyn-based code generation during a build.
Microsoft Public License
408 stars 60 forks source link

Add example for a generator respecting nullability #190

Closed manne closed 3 years ago

manne commented 4 years ago

This PR adds a generator respecting the nullability context of the class.

For the class NullableEnabled where #nullable enable it generates a method string? DoSomething(string?). In the generated code nullable is enabled and restored properly.

For the class NullableDisabled where #nullable disable it generates a method string DoSomething(string).

can solve issue #183 . I did not read the whole conversation properly 🤨

amis92 commented 4 years ago

So, this example is fine and a good addition. It doesn't fix #183, however.

That would require passing around both LangVersion and Nullable msbuild properties, starting in .targets, through dotnet-codegen up to the creation of Compilation.

manne commented 4 years ago

The following code/file is generated

// ------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------

namespace CodeGeneration.Roslyn.Tests.OtherFolder
{
    using System;
    using System.Diagnostics;
    using CodeGeneration.Roslyn.Tests.Generators;
    using Xunit;

    public partial class NullableEnabled
    {
#nullable enable
        public string? DoSomething(string? value)
        {
            return value;
        }
#nullable restore

#nullable enable
        public string? DoSomethingStrict(string value)
        {
            return value;
        }
#nullable restore
    }
}

namespace CodeGeneration.Roslyn.Tests.OtherFolder
{
    using System;
    using System.Diagnostics;
    using CodeGeneration.Roslyn.Tests.Generators;
    using Xunit;

    public partial class NullableDisabled
    {
        public string DoSomething(string value)
        {
            return value;
        }

        public string DoSomethingStrict(string value)
        {
            return value;
        }
    }
}
amis92 commented 4 years ago

I think that since we need to check that the warning is generated (if we don't specify #pragma warning disable), we should write tests more like DocumentTransformTests are, with the use of CompilationTestsBase.

So, inputs and outputs are just strings that contain source code, and we could validate that the resulting compilation has no errors/warnings by checking diagnostics.

It may be probably done in another PR, though.

AArnott commented 3 years ago

This project is getting archived in favor of Source Generators. See #229