Skip to content

Commit

Permalink
Make source generated JsonTypeInfo properties nullable-oblivious (#95341
Browse files Browse the repository at this point in the history
)
  • Loading branch information
eiriktsarpalis authored Nov 28, 2023
1 parent 8435c96 commit ed6323f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@

using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.Json.Serialization;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using SourceGenerators;

Expand Down Expand Up @@ -1009,7 +1007,9 @@ private static void GenerateTypeInfoFactoryHeader(SourceWriter writer, TypeGener
/// <summary>
/// Defines the source generated JSON serialization contract metadata for a given type.
/// </summary>
#nullable disable annotations // Marking the property type as nullable-oblivious.
public {{typeInfoFQN}} {{typeInfoPropertyName}}
#nullable enable annotations
{
get => _{{typeInfoPropertyName}} ??= ({{typeInfoFQN}}){{OptionsInstanceVariableName}}.GetTypeInfo(typeof({{typeFQN}}));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -737,5 +737,36 @@ public class MyClass
Compilation compilation = CompilationHelper.CreateCompilation(source, parseOptions: CompilationHelper.CreateParseOptions(languageVersion));
CompilationHelper.RunJsonSourceGenerator(compilation);
}

[Fact]
public void DoesNotWarnOnNullabilityMismatch()
{
string source = $$"""
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
#nullable enable

namespace HelloWorld
{
public static class MyClass
{
public static string Test()
{
Dictionary<int, string?> values = new();
return JsonSerializer.Serialize(values, JsonContext.Default.DictionaryInt32String);
}
}

[JsonSerializable(typeof(Dictionary<int, string>))]
internal partial class JsonContext : JsonSerializerContext
{
}
}
""";

Compilation compilation = CompilationHelper.CreateCompilation(source);
CompilationHelper.RunJsonSourceGenerator(compilation);
}
}
}

0 comments on commit ed6323f

Please sign in to comment.