-
-
Notifications
You must be signed in to change notification settings - Fork 803
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 all commits
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
112 changes: 112 additions & 0 deletions
112
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,112 @@ | ||
| using System.Collections.Immutable; | ||
| using HotChocolate.Types.Analyzers.Helpers; | ||
| 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 = context.Compilation.IsTaskOrValueTask(methodSymbol.ReturnType, out var innerType) | ||
| ? innerType | ||
| : methodSymbol.ReturnType; | ||
|
|
||
| if (returnType.IsNullableType()) | ||
| { | ||
| 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 = context.Compilation.IsTaskOrValueTask(propertySymbol.Type, out var innerType) | ||
| ? innerType | ||
| : propertySymbol.Type; | ||
|
|
||
| if (propertyType.IsNullableType()) | ||
| { | ||
| 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; | ||
| } | ||
| } |
136 changes: 136 additions & 0 deletions
136
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,136 @@ | ||
| 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; | ||
| } | ||
|
|
||
| // Unwrap NullableTypeSyntax to handle cases like Task<User>?. | ||
| var effectiveType = typeSyntax is NullableTypeSyntax nullableType | ||
| ? nullableType.ElementType | ||
| : typeSyntax; | ||
|
|
||
| var genericName = FindTaskGenericName(effectiveType); | ||
|
|
||
| TypeSyntax newTypeSyntax; | ||
|
|
||
| if (genericName is not null) | ||
| { | ||
| 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)); | ||
| var newGenericName = genericName.WithTypeArgumentList(newTypeArgumentList); | ||
|
|
||
| // Replace the generic name within the effective type to preserve qualification. | ||
| newTypeSyntax = effectiveType == genericName | ||
| ? newGenericName | ||
| : effectiveType.ReplaceNode(genericName, newGenericName); | ||
| } | ||
| else | ||
| { | ||
| // Guard against double-wrapping. | ||
| if (typeSyntax is NullableTypeSyntax) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| newTypeSyntax = SyntaxFactory.NullableType(typeSyntax); | ||
| } | ||
|
|
||
| newTypeSyntax = newTypeSyntax.WithTriviaFrom(typeSyntax); | ||
| var newRoot = root.ReplaceNode(typeSyntax, newTypeSyntax); | ||
| return document.WithSyntaxRoot(newRoot); | ||
| } | ||
|
|
||
| private static GenericNameSyntax? FindTaskGenericName(TypeSyntax typeSyntax) | ||
| => typeSyntax switch | ||
| { | ||
| GenericNameSyntax { TypeArgumentList.Arguments.Count: 1 } genericName | ||
| when genericName.Identifier.Text is nameof(Task) or nameof(ValueTask) | ||
| => genericName, | ||
| QualifiedNameSyntax qualifiedName | ||
| => FindTaskGenericName(qualifiedName.Right), | ||
| AliasQualifiedNameSyntax aliasName | ||
| => FindTaskGenericName(aliasName.Name), | ||
| _ => null | ||
| }; | ||
| } | ||
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.