Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid capturing diagnostic objects in SG incremental values #86605

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/libraries/System.Text.Json/gen/Helpers/DiagnosticInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;
using System.Numerics.Hashing;
using Microsoft.CodeAnalysis;

namespace System.Text.Json.SourceGeneration
{
/// <summary>
/// Descriptor for diagnostic instances using structural equality comparison.
/// Provides a work-around for https://github.com/dotnet/roslyn/issues/68291.
/// </summary>
public readonly struct DiagnosticInfo : IEquatable<DiagnosticInfo>
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
{
public required DiagnosticDescriptor Descriptor { get; init; }
public required object?[] MessageArgs { get; init; }
public required Location? Location { get; init; }

public Diagnostic CreateDiagnostic()
=> Diagnostic.Create(Descriptor, Location, MessageArgs);

public override readonly bool Equals(object? obj) => obj is DiagnosticInfo info && Equals(info);
public readonly bool Equals(DiagnosticInfo other)
{
return Descriptor.Equals(other.Descriptor) &&
MessageArgs.SequenceEqual(other.MessageArgs) &&
eiriktsarpalis marked this conversation as resolved.
Show resolved Hide resolved
Location == other.Location;
}

public override readonly int GetHashCode()
{
int hashCode = Descriptor.GetHashCode();
foreach (object? messageArg in MessageArgs)
{
hashCode = HashHelpers.Combine(hashCode, messageArg?.GetHashCode() ?? 0);
}

hashCode = HashHelpers.Combine(hashCode, Location?.GetHashCode() ?? 0);
return hashCode;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ public Emitter(in JsonSourceGenerationContext sourceGenerationContext, SourceGen

public void Emit()
{
foreach (Diagnostic diagnostic in _generationSpec.Diagnostics)
foreach (DiagnosticInfo diagnostic in _generationSpec.Diagnostics)
{
// Report any diagnostics produced by the parser ahead of formatting source code.
_sourceGenerationContext.ReportDiagnostic(diagnostic);
_sourceGenerationContext.ReportDiagnostic(diagnostic.CreateDiagnostic());
}

foreach (ContextGenerationSpec contextGenerationSpec in _generationSpec.ContextGenerationSpecs)
Expand Down
11 changes: 7 additions & 4 deletions src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,16 @@ private sealed class Parser
#pragma warning restore
private JsonKnownNamingPolicy _currentContextNamingPolicy;

private readonly List<Diagnostic> _diagnostics = new();
private readonly List<DiagnosticInfo> _diagnostics = new();

public void ReportDiagnostic(DiagnosticDescriptor descriptor, Location? location, params object?[]? messageArgs)
{
location = location.GetTrimmedLocation();
Diagnostic diag = Diagnostic.Create(descriptor, location, messageArgs);
_diagnostics.Add(diag);
_diagnostics.Add(new DiagnosticInfo
{
Descriptor = descriptor,
Location = location.GetTrimmedLocation(),
MessageArgs = messageArgs ?? Array.Empty<object?>(),
});
}

private static DiagnosticDescriptor TypeNotSupported { get; } = new DiagnosticDescriptor(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.CodeAnalysis;

namespace System.Text.Json.SourceGeneration
{
/// <summary>
Expand All @@ -26,6 +24,6 @@ public sealed record SourceGenerationSpec
{
public required ImmutableEquatableArray<ContextGenerationSpec> ContextGenerationSpecs { get; init; }

public required ImmutableEquatableArray<Diagnostic> Diagnostics { get; init; }
public required ImmutableEquatableArray<DiagnosticInfo> Diagnostics { get; init; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
<Compile Include="..\Common\JsonUnmappedMemberHandling.cs" Link="Common\System\Text\Json\Serialization\JsonUnmappedMemberHandling.cs" />
<Compile Include="..\Common\ThrowHelper.cs" Link="Common\System\Text\Json\ThrowHelper.cs" />
<Compile Include="$(CommonPath)\Roslyn\GetBestTypeByMetadataName.cs" Link="Common\Roslyn\GetBestTypeByMetadataName.cs" />
<Compile Include="Helpers\DiagnosticInfo.cs" />
<Compile Include="Helpers\ImmutableEquatableArray.cs" />
<Compile Include="Helpers\KnownTypeSymbols.cs" />
<Compile Include="Helpers\RoslynExtensions.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,32 @@ public class Model
return CreateCompilation(source);
}

public static Compilation CreatePolymorphicClassOnFastPathContext()
{
string source = """
using System.Text.Json.Serialization;

namespace HelloWorld
{
[JsonSerializable(typeof(MyBaseClass), GenerationMode = JsonSourceGenerationMode.Serialization)]
internal partial class JsonContext : JsonSerializerContext
{
}

[JsonDerivedType(typeof(MyDerivedClass), "derived")]
public class MyBaseClass
{
}

public class MyDerivedClass : MyBaseClass
{
}
}
""";

return CreateCompilation(source);
}

internal static void CheckDiagnosticMessages(
DiagnosticSeverity level,
ImmutableArray<Diagnostic> diagnostics,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -356,5 +356,23 @@ public void WarnOnClassesWithInaccessibleJsonIncludeProperties()
CompilationHelper.CheckDiagnosticMessages(DiagnosticSeverity.Warning, result.Diagnostics, expectedWarningDiagnostics, sort: false);
CompilationHelper.CheckDiagnosticMessages(DiagnosticSeverity.Error, result.Diagnostics, Array.Empty<(Location, string)>());
}

[Fact]
public void PolymorphicClassWarnsOnFastPath()
{
Compilation compilation = CompilationHelper.CreatePolymorphicClassOnFastPathContext();
JsonSourceGeneratorResult result = CompilationHelper.RunJsonSourceGenerator(compilation);

Location myBaseClassLocation = compilation.GetSymbolsWithName("MyBaseClass").First().Locations[0];

(Location, string)[] expectedWarningDiagnostics = new (Location, string)[]
{
(myBaseClassLocation, "Type 'HelloWorld.MyBaseClass' is annotated with 'JsonDerivedTypeAttribute' which is not supported in 'JsonSourceGenerationMode.Serialization'."),
};

CompilationHelper.CheckDiagnosticMessages(DiagnosticSeverity.Info, result.Diagnostics, Array.Empty<(Location, string)>());
CompilationHelper.CheckDiagnosticMessages(DiagnosticSeverity.Warning, result.Diagnostics, expectedWarningDiagnostics, sort: false);
CompilationHelper.CheckDiagnosticMessages(DiagnosticSeverity.Error, result.Diagnostics, Array.Empty<(Location, string)>());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Xunit;

Expand Down