Skip to content

Json source generator generates uncompilable code for new .NET Framework project #83392

Closed

Description

@stephentoub

The JSON source generator purports to support working in .NET Framework and .NET Standard projects. However, such projects default to using a language version of C# 7.3, which is the last version of the language officially supported on those platform targets. And the JSON source generator emits code that requires newer features, in particular nullable, which is only usable with a C# 8+ language version. Thus, out of the box in a new .NET Framework or .NET Standard project, attempts to use the JSON source generator result in a littany of errors.

Repro:

  1. Create a new .NET Framework 4.8 console app.
  2. Add a nuget reference to the latest stable System.Text.Json nuget package.
  3. Paste this code into your Program.cs, which is based on the docs for [JsonSerializable]:
using System.Collections.Generic;
using System.Text.Json.Serialization;

internal class Program
{
    static void Main() { }
}

public class WeatherForecast
{
    public object Data { get; set; }
    public List<object> DataList { get; set; }
}

[JsonSerializable(typeof(WeatherForecast))]
[JsonSerializable(typeof(bool))]
[JsonSerializable(typeof(int))]
public partial class WeatherForecastContext : JsonSerializerContext
{
}
  1. Compile. You'll get errors like this:
1>ConsoleApp7\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\WeatherForecastContext.g.cs(32,74,32,75): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
1>ConsoleApp7\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\WeatherForecastContext.g.cs(44,76,44,77): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
1>ConsoleApp7\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\WeatherForecastContext.GetJsonTypeInfo.g.cs(41,69,41,70): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
1>ConsoleApp7\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\WeatherForecastContext.Object.g.cs(10,100,10,101): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
1>ConsoleApp7\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\WeatherForecastContext.ListObject.g.cs(10,141,10,142): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
1>ConsoleApp7\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\WeatherForecastContext.WeatherForecast.g.cs(10,102,10,103): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
1>ConsoleApp7\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\WeatherForecastContext.Boolean.g.cs(10,101,10,102): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
1>ConsoleApp7\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\WeatherForecastContext.Int32.g.cs(10,99,10,100): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
1>ConsoleApp7\System.Text.Json.SourceGeneration\System.Text.Json.SourceGeneration.JsonSourceGenerator\WeatherForecastContext.g.cs(22,54,22,55): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

To my knowledge, the only fix is to change your project's language version to something >= 8.0, which is officially an unsupported configuration.

Activity

  1. ghost added
    untriaged
    on Mar 14, 2023
  2. eiriktsarpalis commented on Mar 15, 2023

    @eiriktsarpalis
    Member

    Interesting. We do test the source generator against framework but I would guess runtime just uses the latest lang version on everything:

    <TargetFrameworks>$(NetCoreAppCurrent);$(NetFrameworkMinimum)</TargetFrameworks>

    What might be a sustainable way to address this issue? The only clean solution I can think of is removing NRT annotations altogether, but that will certainly impact readability in newer targets.

  3. removed
    untriaged
    on Mar 15, 2023
  4. added this to the 8.0.0 milestone on Mar 15, 2023
  5. added
    source-generator
    on Mar 15, 2023
  6. pinkfloydx33 commented on Mar 15, 2023

    @pinkfloydx33

    Aren't source generators "supposed" to respect the language version of the project, ie. generate compliant code? I've always wondered what most generators did in this area as it seemed very inconvenient to do so.

    It doesn't seem like it'd be too bad/difficult to generate different code for something like nullable annotations. I suppose when building source via strings that it could become quite messy w/r/t all the other newer language features one might want to leverage. Would using the roslyn APIs make that any easier?

    Nullability is one thing... but even if you fixed that there's other features to consider. For example you have things like required and init that the generator supports which you'd have to dance around. I guess the question becomes where do you draw the line?

    Not a helpful comment, I know; I'm just really curious to see where the runtime lands here.

  7. krwq commented on Mar 15, 2023

    @krwq
    Member

    I'm just curious since when this is true... If we haven't heard anyone external complaining about it is it possible people use latest language version or they don't care about netfx? Assuming we want to have this supported IMO easiest will be to remove nullability - maybe there is some simple solution like asking Roslyn to rewrite our code but without nullability annotations - I think that would be acceptable if we generated code a notch slower on netfx.

  8. stephentoub commented on Mar 15, 2023

    @stephentoub
    MemberAuthor

    What might be a sustainable way to address this issue?

    Change the source generator to look at the compilation's LanguageVersion and generate code that only uses features it supports or issue a warning diagnostic and fail to generate any code if the LangVer isn't supported, eg parameterizing the code at

    new CSharpParseOptions(kind: SourceCodeKind.Regular, documentationMode: DocumentationMode.Parse);
    such that different tests can pass a different version and/or so that a different version is set when targeting netfx. And ensure we have tests that use all relevant language versions. eg
    public async Task Diagnostic_InvalidLangVersion_LimitedSupport(LanguageVersion version)

  9. stephentoub commented on Mar 15, 2023

    @stephentoub
    MemberAuthor

    Assuming we want to have this supported

    We should be paying attention to LanguageVersion, regardless, whether to downgrade what code we emit to ensure it compiles or to issue diagnostics instead of outputting code if the version is insufficient. If Roslyn APIs can simplify that, either to flag places we've done something wrong or to rewrite the code appropriate to a version, we can certainly take advantage.

    But LanguageVersion aside, we should also seriously consider having all of our generators only officially support core moving forward. I would not lose sleep if, for example, the json generator output a warning instead of code if langver was < C# 8.
    cc: @jkotas, @davidfowl

  10. tarekgh commented on Mar 15, 2023

    @tarekgh
    Member

    I am wondering, isn't the current error telling need lang version at least 8.0? I understand the idea of checking the lang version in the source gen, but producing such warning when compiling for .NET Framework, what we'll suggest to the user? As pointed out before, lang version 8.0 is not officially supported at that time and I don't think we can suggest upgrading the lang version.

  11. jkotas commented on Mar 15, 2023

    @jkotas
    Member

    what we'll suggest to the user?

    Migrate to .NET Core. There are many new features and APIs that are available in .NET Core only.

  12. tarekgh commented on Mar 15, 2023

    @tarekgh
    Member

    Why do we allow the source generators at all when compiling for .NET Framework? should we just stop supporting it when compiling for netfx or netstandard then?

  13. NN--- commented on Mar 15, 2023

    @NN---
    Contributor

    Since Nullable attributes are simply classes and not a runtime feature, as a workaround it is possible to add them to the project and have everything compiled.

    https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs

  14. stephentoub commented on Mar 15, 2023

    @stephentoub
    MemberAuthor

    Since Nullable attributes are simply classes and not a runtime feature, as a workaround it is possible to add them to the project and have everything compiled.

    That's not the case. The source generator is emitting use of nullable-related syntax. That produces errors in versions of C# earlier than 8.0 regardless of whether such attributes are defined.

  15. NN--- commented on Mar 15, 2023

    @NN---
    Contributor

    I understand.
    Nullable syntax doesn't work with C# 7.3.

  16. Sergio0694 commented on Mar 27, 2023

    @Sergio0694
    Contributor

    FWIW if another reference point is useful, we use a similar approach in the source generators for the MVVM Toolkit (which is not part of the SDK, but still first party). We emit code targeting C# 8 for everyone (which at least allows us to produce code with nullability annotations for everyone and simplify our generator logic), and right at the start of each generator we check the current C# version and if it's lower than C# 8 we emit a warning and stop there instead. People on lower targets are then free to either just use the rest of the MVVM Toolkit without source generators on the officially supported path, or manually bump their language version in the .csproj to C# 8 or greater, and then leverage the source generators too accepting the fact that the Roslyn/SDK side of things in that configuration is technically not supported. For practical purposes, this works just fine 😄

    The only additional checks we do just to avoid compromises on more recent targets is to eg. checking whether some types are available (eg. the nullability attributes), and only emit them if they are, otherwise skip them. This adds relatively low additional complexity and in turn allows us to have generated code for recent targets be "perfect", while still not breaking downlevel targets. As a bonus, people can also choose to polyfill those attributes and then they'll get them generated as well.

  17. ghost added
    in-pr
    on Jun 23, 2023
  18. ghost removed
    in-pr
    on Jun 23, 2023
  19. ghost locked as resolved and limited conversation to collaborators on Jul 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

area-System.Text.Jsonbugsource-generator

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions