Skip to content

No reliable way to tell if a reference type is nullable from a source generator #49555

@trampster

Description

@trampster

Version Used:
5.0.100

Roslyn doesn't seem to provide a reliable way of determining if NRT is enabled for a ITypeSymbol

Steps to Reproduce:

  1. Create a project with NRT turned off
  2. Add an assembly level attribute like the following: [assembly: JsonArray(typeof(string))]
  3. In a different file turn on NRT with: #nullable enable and then off again with #nullable restore
  4. In a Source Generator get a ITypeSymbol to the string from the attribute
  5. Notice that ITypeSymbol.NullableAnnotation returns 'NotAnnotated' when it should be 'None'
  6. Remove the #nullable enable and #nullable restore from the other file
  7. Notice ITypeSymbol.NullableAnnotation now is 'None'

Expected Behavior:

  • ITypeSymbol.NullableAnnotation should return 'None' if NRT is off for that section of code

Actual Behavior:

  • ITypeSymbol.NullableAnnotation returns 'NotAnnotated'

The help on NullableAnnotation is kind of vague about what 'None' means:

        //
        // Summary:
        //     The expression has not been analyzed, or the syntax is not an expression (such
        //     as a statement).
        //
        // Remarks:
        //     There are a few different reasons the expression could have not been analyzed:
        //     1) The symbol producing the expression comes from a method that has not been
        //     annotated, such as invoking a C# 7.3 or earlier method, or a method in this compilation
        //     that is in a disabled context. 2) Nullable is completely disabled in this compilation.
        None = 0,

If None cannot be used to determine that NRT is off or on, then Roslyn needs to provide a way to determine this.

I run into this problem writing JsonSrcGen which is a Json Source Generator.

  • If I don't' annotate my code the user will get warnings.
  • If I annotate my generated Json code to make everything nullable and the user makes there property non nullable then my generated code will produce a warning about possible null assignment.
  • If I suppress this warning then the users property could end up being set to null which may be surprising to the user.
  • I can't assume non nullable because then I won't support null in the json ever.

Ideally I would want to detect the the property type is non nullable and then throw an exception if the Json is null for that property. By making the property type non nullable the user is telling me that they don't expect null in the Json and therefore if there is this is an error (so an exception is the correct thing)

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions