-
-
Notifications
You must be signed in to change notification settings - Fork 806
Add analyzer "Lookup Must Return Nullable Type" #9552
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
135 changes: 135 additions & 0 deletions
135
src/HotChocolate/Core/src/Types.Analyzers/LookupReturnsNonNullableTypeAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| using System.Collections.Immutable; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
|
|
||
| namespace HotChocolate.Types.Analyzers; | ||
|
|
||
| [DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
| public sealed class LookupReturnsNonNullableTypeAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = | ||
| [Errors.LookupReturnsNonNullableType]; | ||
|
|
||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
| context.RegisterSyntaxNodeAction(AnalyzeMethodDeclaration, SyntaxKind.MethodDeclaration); | ||
| context.RegisterSyntaxNodeAction(AnalyzePropertyDeclaration, SyntaxKind.PropertyDeclaration); | ||
| } | ||
|
|
||
| private static void AnalyzeMethodDeclaration(SyntaxNodeAnalysisContext context) | ||
| { | ||
| var methodDeclaration = (MethodDeclarationSyntax)context.Node; | ||
|
|
||
| if (!HasLookupAttribute(context, methodDeclaration.AttributeLists)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var methodSymbol = context.SemanticModel.GetDeclaredSymbol(methodDeclaration); | ||
| if (methodSymbol is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var returnType = UnwrapTaskType(methodSymbol.ReturnType); | ||
|
|
||
| if (IsNullableType(returnType)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var diagnostic = Diagnostic.Create( | ||
| Errors.LookupReturnsNonNullableType, | ||
| methodDeclaration.ReturnType.GetLocation()); | ||
|
|
||
| context.ReportDiagnostic(diagnostic); | ||
| } | ||
|
|
||
| private static void AnalyzePropertyDeclaration(SyntaxNodeAnalysisContext context) | ||
| { | ||
| var propertyDeclaration = (PropertyDeclarationSyntax)context.Node; | ||
|
|
||
| if (!HasLookupAttribute(context, propertyDeclaration.AttributeLists)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var propertySymbol = context.SemanticModel.GetDeclaredSymbol(propertyDeclaration); | ||
| if (propertySymbol is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var propertyType = UnwrapTaskType(propertySymbol.Type); | ||
|
|
||
| if (IsNullableType(propertyType)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var diagnostic = Diagnostic.Create( | ||
| Errors.LookupReturnsNonNullableType, | ||
| propertyDeclaration.Type.GetLocation()); | ||
|
|
||
| context.ReportDiagnostic(diagnostic); | ||
| } | ||
|
|
||
| private static bool HasLookupAttribute( | ||
| SyntaxNodeAnalysisContext context, | ||
| SyntaxList<AttributeListSyntax> attributeLists) | ||
| { | ||
| var semanticModel = context.SemanticModel; | ||
|
|
||
| foreach (var attributeList in attributeLists) | ||
| { | ||
| foreach (var attribute in attributeList.Attributes) | ||
| { | ||
| var symbolInfo = semanticModel.GetSymbolInfo(attribute); | ||
| if (symbolInfo.Symbol is not IMethodSymbol attributeSymbol) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| var attributeType = attributeSymbol.ContainingType; | ||
| if (attributeType.ToDisplayString() == WellKnownAttributes.LookupAttribute) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private static ITypeSymbol UnwrapTaskType(ITypeSymbol typeSymbol) | ||
| { | ||
| if (typeSymbol is INamedTypeSymbol namedType | ||
| && namedType.TypeArguments.Length == 1 | ||
| && namedType.Name is nameof(Task) or nameof(ValueTask)) | ||
| { | ||
| return namedType.TypeArguments[0]; | ||
| } | ||
|
|
||
| return typeSymbol; | ||
| } | ||
|
|
||
| private static bool IsNullableType(ITypeSymbol typeSymbol) | ||
| { | ||
| if (typeSymbol.NullableAnnotation == NullableAnnotation.Annotated) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| if (typeSymbol is INamedTypeSymbol namedType | ||
| && namedType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } | ||
114 changes: 114 additions & 0 deletions
114
src/HotChocolate/Core/src/Types.Analyzers/LookupReturnsNonNullableTypeCodeFixProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace HotChocolate.Types.Analyzers; | ||
|
|
||
| [Shared] | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(LookupReturnsNonNullableTypeCodeFixProvider))] | ||
| public sealed class LookupReturnsNonNullableTypeCodeFixProvider : CodeFixProvider | ||
| { | ||
| public override ImmutableArray<string> FixableDiagnosticIds { get; } = ["HC0113"]; | ||
|
|
||
| public override FixAllProvider GetFixAllProvider() | ||
| => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
| if (root is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var diagnostic = context.Diagnostics[0]; | ||
| var diagnosticSpan = diagnostic.Location.SourceSpan; | ||
|
|
||
| var node = root.FindNode(diagnosticSpan); | ||
|
|
||
| // Determine the type syntax to make nullable. | ||
| TypeSyntax? typeSyntax = null; | ||
|
|
||
| var methodDeclaration = node.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault(); | ||
| if (methodDeclaration is not null) | ||
| { | ||
| typeSyntax = methodDeclaration.ReturnType; | ||
| } | ||
| else | ||
| { | ||
| var propertyDeclaration = node.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().FirstOrDefault(); | ||
| if (propertyDeclaration is not null) | ||
| { | ||
| typeSyntax = propertyDeclaration.Type; | ||
| } | ||
| } | ||
|
|
||
| if (typeSyntax is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| const string title = "Make return type nullable"; | ||
|
|
||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: title, | ||
| createChangedDocument: c => MakeReturnTypeNullableAsync( | ||
| context.Document, | ||
| typeSyntax, | ||
| c), | ||
| equivalenceKey: title), | ||
| diagnostic); | ||
| } | ||
|
|
||
| private static async Task<Document> MakeReturnTypeNullableAsync( | ||
| Document document, | ||
| TypeSyntax typeSyntax, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
| if (root is null) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| TypeSyntax newTypeSyntax; | ||
|
|
||
| // If the type is Task<T> or ValueTask<T>, wrap the inner type argument. | ||
| if (typeSyntax is GenericNameSyntax genericName | ||
| && genericName.TypeArgumentList.Arguments.Count == 1 | ||
| && genericName.Identifier.Text is nameof(Task) or nameof(ValueTask)) | ||
| { | ||
| var innerType = genericName.TypeArgumentList.Arguments[0]; | ||
|
|
||
| // Guard against double-wrapping. | ||
| if (innerType is NullableTypeSyntax) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| var nullableInnerType = SyntaxFactory.NullableType(innerType); | ||
| var newTypeArgumentList = genericName.TypeArgumentList.WithArguments( | ||
| SyntaxFactory.SingletonSeparatedList<TypeSyntax>(nullableInnerType)); | ||
| newTypeSyntax = genericName.WithTypeArgumentList(newTypeArgumentList); | ||
| } | ||
|
glen-84 marked this conversation as resolved.
Outdated
|
||
| else | ||
| { | ||
| // Guard against double-wrapping. | ||
| if (typeSyntax is NullableTypeSyntax) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| newTypeSyntax = SyntaxFactory.NullableType(typeSyntax); | ||
| } | ||
|
glen-84 marked this conversation as resolved.
|
||
|
|
||
| newTypeSyntax = newTypeSyntax.WithTriviaFrom(typeSyntax); | ||
| var newRoot = root.ReplaceNode(typeSyntax, newTypeSyntax); | ||
| return document.WithSyntaxRoot(newRoot); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.