GeezerVison is showing github.com — Add MsgPack014 analyzer and code fix by AArnott · Pull Request #1969 · MessagePack-CSharp/MessagePack-CSharp
Add MsgPack014 analyzer and code fix
#1969
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
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.cs
(5)
.md
(1)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -11,7 +11,8 @@ public class FormatterCodeFixProvider : CodeFixProvider
private static readonly ImmutableArray<string> FixableIds = ImmutableArray.Create(
MsgPack00xMessagePackAnalyzer.InaccessibleFormatterTypeId,
MsgPack00xMessagePackAnalyzer.InaccessibleFormatterInstanceId,
MsgPack00xMessagePackAnalyzer.PartialTypeRequired.Id);
MsgPack00xMessagePackAnalyzer.PartialTypeRequiredId,
MsgPack00xMessagePackAnalyzer.NullableReferenceTypeFormatterId);
public sealed override ImmutableArray<string> FixableDiagnosticIds => FixableIds;
Expand All
@@ -25,12 +26,13 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
foreach (Diagnostic diagnostic in context.Diagnostics)
{
SyntaxNode? syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken);
BaseTypeDeclarationSyntax? typeDecl = syntaxRoot?.FindNode(diagnostic.Location.SourceSpan) as BaseTypeDeclarationSyntax;
if (syntaxRoot is not null && typeDecl is not null)
CSharpSyntaxNode? diagnosticTargetNode = syntaxRoot?.FindNode(diagnostic.Location.SourceSpan) as CSharpSyntaxNode;
BaseTypeDeclarationSyntax? typeDecl = diagnosticTargetNode as BaseTypeDeclarationSyntax;
if (syntaxRoot is not null)
{
switch (diagnostic.Id)
{
case MsgPack00xMessagePackAnalyzer.PartialTypeRequiredId:
case MsgPack00xMessagePackAnalyzer.PartialTypeRequiredId when typeDecl is not null :
context.RegisterCodeFix(
CodeAction.Create(
"Add partial modifier",
Expand All
@@ -39,7 +41,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
diagnostic);
break;
case MsgPack00xMessagePackAnalyzer.InaccessibleFormatterTypeId:
case MsgPack00xMessagePackAnalyzer.InaccessibleFormatterTypeId when typeDecl is not null :
context.RegisterCodeFix(
CodeAction.Create(
"Make type internal",
Expand All
@@ -48,7 +50,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
diagnostic);
break;
case MsgPack00xMessagePackAnalyzer.InaccessibleFormatterInstanceId:
case MsgPack00xMessagePackAnalyzer.InaccessibleFormatterInstanceId when typeDecl is not null :
SemanticModel? semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken);
if (semanticModel?.GetDeclaredSymbol(typeDecl, context.CancellationToken) is INamedTypeSymbol typeSymbol)
{
Expand All
@@ -70,9 +72,58 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
}
break;
case MsgPack00xMessagePackAnalyzer.NullableReferenceTypeFormatterId:
if (diagnosticTargetNode is TypeSyntax typeArg)
{
context.RegisterCodeFix(
CodeAction.Create(
"Add nullable annotation",
ct => AddNullableAnnotationAsync(context, typeArg, ct),
"NullableRefAddition"),
diagnostic);
}
break;
}
}
}
}
private static async Task<Document> AddNullableAnnotationAsync(CodeFixContext context, TypeSyntax typeArg, CancellationToken ct)
{
SyntaxNode? root = await context.Document.GetSyntaxRootAsync(ct);
if (root is null)
{
return context.Document;
}
// Attempt to update any and all references to this type.
BaseTypeDeclarationSyntax? typeDecl = typeArg.FirstAncestorOrSelf<BaseTypeDeclarationSyntax>();
if (typeDecl is not null)
{
SemanticModel? semanticModel = await context.Document.GetSemanticModelAsync(ct);
if (semanticModel is not null)
{
ITypeSymbol? nonAnnotated = semanticModel.GetTypeInfo(typeArg, ct).Type;
if (nonAnnotated is not null)
{
BaseTypeDeclarationSyntax updatedTypeDecl = typeDecl.ReplaceNodes(
typeDecl.DescendantNodes().OfType<TypeSyntax>(),
(old, current) =>
{
ITypeSymbol? actual = semanticModel.GetTypeInfo(old, ct).Type;
return SymbolEqualityComparer.IncludeNullability.Equals(actual, nonAnnotated)
? SyntaxFactory.NullableType(current.WithoutTrailingTrivia()).WithTrailingTrivia(current.GetTrailingTrivia())
: current;
});
root = root.ReplaceNode(typeDecl, updatedTypeDecl);
}
}
}
Document document = context.Document;
document = document.WithSyntaxRoot(root);
return document;
}
private static Task<Document> AddPartialModifierAsync(Document document, SyntaxNode syntaxRoot, BaseTypeDeclarationSyntax typeDecl, Diagnostic diagnostic, CancellationToken cancellationToken)
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -17,4 +17,5 @@ MsgPack009 | Usage | Error | MsgPack00xMessagePackAnalyzer
MsgPack010 | Usage | Warning | Formatter is not accessible to the source generated resolver
MsgPack011 | Usage | Error | MsgPack00xMessagePackAnalyzer
MsgPack012 | Usage | Error | MsgPack00xMessagePackAnalyzer
MsgPack013 | Usage | Warning | Formatter has no accessible instance for the source generated resolver
MsgPack013 | Usage | Warning | Formatter has no accessible instance for the source generated resolver
MsgPack014 | Usage | Warning | Formatters of reference types should implement `IMessagePackFormatter<T?>`
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3,6 +3,7 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using AnalyzerOptions = MessagePack.SourceGenerator.CodeAnalysis.AnalyzerOptions;
Expand All
@@ -22,6 +23,7 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer
public const string PartialTypeRequiredId = "MsgPack011";
public const string InaccessibleDataTypeId = "MsgPack012";
public const string InaccessibleFormatterInstanceId = "MsgPack013";
public const string NullableReferenceTypeFormatterId = "MsgPack014";
internal const string Category = "Usage";
Expand Down
Expand Up
@@ -255,6 +257,15 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(InaccessibleDataTypeId));
public static readonly DiagnosticDescriptor NullableReferenceTypeFormatter = new(
id: NullableReferenceTypeFormatterId,
title: "Format nullable reference types",
category: Category,
messageFormat: "Implement IMessagePackFormatter<{0}?> (with nullable annotation)",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
helpLinkUri: AnalyzerUtilities.GetHelpLink(NullableReferenceTypeFormatterId));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(
TypeMustBeMessagePackObject,
MessageFormatterMustBeMessagePackFormatter,
Expand All
@@ -277,7 +288,8 @@ public class MsgPack00xMessagePackAnalyzer : DiagnosticAnalyzer
InaccessibleFormatterInstance,
InaccessibleFormatterType,
PartialTypeRequired,
InaccessibleDataType);
InaccessibleDataType,
NullableReferenceTypeFormatter);
public override void Initialize(AnalysisContext context)
{
Expand Down
Expand Up
@@ -316,6 +328,46 @@ private void AnalyzeSymbol(SymbolAnalysisContext context, ReferenceSymbols typeR
{
context.ReportDiagnostic(Diagnostic.Create(inaccessible, declaredSymbol.Locations[0]));
}
// Call out any formattable reference types that are not nullable.
foreach (INamedTypeSymbol iface in declaredSymbol.Interfaces)
{
if (iface.TypeArguments is [INamedTypeSymbol { IsReferenceType: true, NullableAnnotation: NullableAnnotation.NotAnnotated } a])
{
Location? location = null;
// Find the location of the actual generic type argument if we can.
foreach (var syntaxRef in declaredSymbol.DeclaringSyntaxReferences)
{
if (syntaxRef.GetSyntax(context.CancellationToken) is BaseTypeDeclarationSyntax { BaseList: { } baseList } typeSyntax)
{
#pragma warning disable RS1030 // Do not invoke Compilation.GetSemanticModel() method within a diagnostic analyzer
Comment thread
AArnott marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
SemanticModel semanticModel = context.Compilation.GetSemanticModel(syntaxRef.SyntaxTree);
#pragma warning restore RS1030 // Do not invoke Compilation.GetSemanticModel() method within a diagnostic analyzer
foreach (BaseTypeSyntax baseTypeSyntax in baseList.Types)
{
if (baseTypeSyntax.Type is GenericNameSyntax { TypeArgumentList: { Arguments: [TypeSyntax typeArg] } })
{
ITypeSymbol? actual = semanticModel.GetTypeInfo(typeArg, context.CancellationToken).Type;
if (SymbolEqualityComparer.Default.Equals(actual, a))
{
location = typeArg.GetLocation();
break;
}
}
}
if (location is not null)
{
break;
}
}
}
location ??= declaredSymbol.Locations[0];
context.ReportDiagnostic(Diagnostic.Create(NullableReferenceTypeFormatter, location, a.Name));
}
}
}
switch (declaredSymbol.TypeKind)
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3,22 +3,33 @@
using MessagePack.Formatters;
internal class CustomFormatterRecordFormatter : IMessagePackFormatter<CustomFormatterRecord>
internal class CustomFormatterRecordFormatter : IMessagePackFormatter<CustomFormatterRecord? >
{
// Deliberately test the singleton pattern.
public static readonly IMessagePackFormatter<CustomFormatterRecord> Instance = new CustomFormatterRecordFormatter();
public static readonly IMessagePackFormatter<CustomFormatterRecord? > Instance = new CustomFormatterRecordFormatter();
private CustomFormatterRecordFormatter()
{
}
public void Serialize(ref MessagePackWriter writer, CustomFormatterRecord value, MessagePackSerializerOptions options)
public void Serialize(ref MessagePackWriter writer, CustomFormatterRecord? value, MessagePackSerializerOptions options)
{
if (value is null)
{
writer.WriteNil();
return;
}
writer.WriteInt32(value.Value);
}
public CustomFormatterRecord Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
public CustomFormatterRecord? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.TryReadNil())
{
return null;
}
return new CustomFormatterRecord { Value = reader.ReadInt32() };
}
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3,15 +3,26 @@
using MessagePack.Formatters;
internal class UnserializableRecordFormatter : IMessagePackFormatter<UnserializableRecord>
internal class UnserializableRecordFormatter : IMessagePackFormatter<UnserializableRecord? >
{
public void Serialize(ref MessagePackWriter writer, UnserializableRecord value, MessagePackSerializerOptions options)
public void Serialize(ref MessagePackWriter writer, UnserializableRecord? value, MessagePackSerializerOptions options)
{
if (value is null)
{
writer.WriteNil();
return;
}
writer.WriteInt32(value.Value);
}
public UnserializableRecord Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
public UnserializableRecord? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.TryReadNil())
{
return null;
}
return new UnserializableRecord { Value = reader.ReadInt32() };
}
}
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,106 @@
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using VerifyCS = CSharpCodeFixVerifier<MessagePack.SourceGenerator.Analyzers.MsgPack00xMessagePackAnalyzer, MessagePack.Analyzers.CodeFixes.FormatterCodeFixProvider>;
public class MsgPack014NullableRefTypeFormatterTests
{
[Fact]
public async Task RefTypeWithoutNullableGetsFixed()
{
string testSource = /* lang=c#-test */ """
using MessagePack;
using MessagePack.Formatters;
#nullable enable
public class A { }
public class AFormatter : IMessagePackFormatter<{|MsgPack014:A|}>
{
public void Serialize(ref MessagePackWriter writer, A value, MessagePackSerializerOptions options) => throw new System.NotImplementedException();
public A Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new System.NotImplementedException();
}
""";
string fixedSource = /* lang=c#-test */ """
using MessagePack;
using MessagePack.Formatters;
#nullable enable
public class A { }
public class AFormatter : IMessagePackFormatter<A?>
{
public void Serialize(ref MessagePackWriter writer, A? value, MessagePackSerializerOptions options) => throw new System.NotImplementedException();
public A? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => throw new System.NotImplementedException();
}
""";
await VerifyCS.VerifyCodeFixAsync(testSource, fixedSource);
}
[Fact]
public async Task RefTypeWithNullableAnnotation()
{
string testSource = /* lang=c#-test */ """
using MessagePack;
using MessagePack.Formatters;
public class A { }
#nullable enable
public class AFormatter : IMessagePackFormatter<A?>
{
public void Serialize(ref MessagePackWriter writer, A? value, MessagePackSerializerOptions options) { }
public A? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => default;
}
""";
await VerifyCS.VerifyAnalyzerAsync(testSource);
}
[Fact]
public async Task ValueTypeWithoutNullableAnnotation()
{
string testSource = /* lang=c#-test */ """
using MessagePack;
using MessagePack.Formatters;
public struct A { }
#nullable enable
public class AFormatter : IMessagePackFormatter<A>
{
public void Serialize(ref MessagePackWriter writer, A value, MessagePackSerializerOptions options) { }
public A Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => default;
}
""";
await VerifyCS.VerifyAnalyzerAsync(testSource);
}
[Fact]
public async Task RefTypeWithoutNullableAnnotationsEnabled()
{
string testSource = /* lang=c#-test */ """
using MessagePack;
using MessagePack.Formatters;
public class A { }
#nullable disable
public class AFormatter : IMessagePackFormatter<A>
{
public void Serialize(ref MessagePackWriter writer, A value, MessagePackSerializerOptions options) { }
public A Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => default;
}
""";
await VerifyCS.VerifyAnalyzerAsync(testSource);
}
}
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.