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

Fixed DeclareAsNullableCodeFixProvider for casts in variable declarations #1393

Merged
merged 4 commits into from
Feb 17, 2024
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
1 change: 1 addition & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Fix analyzer [RCS0049](https://josefpihrt.github.io/docs/roslynator/analyzers/RCS0049) ([PR](https://github.com/dotnet/roslynator/pull/1386))
- Fix analyzer [RCS1159](https://josefpihrt.github.io/docs/roslynator/analyzers/RCS1159) ([PR](https://github.com/dotnet/roslynator/pull/1390))
- Fix code fix for [CS8600](https://josefpihrt.github.io/docs/roslynator/fixes/CS8600) changing the wrong type when casts or `var` are involved ([PR](https://github.com/dotnet/roslynator/pull/1393) by @jroessel)

## [4.10.0] - 2024-01-24

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
Expand Down Expand Up @@ -30,7 +31,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
if (!IsEnabled(diagnostic.Id, CodeFixIdentifiers.AddNullableAnnotation, context.Document, root.SyntaxTree))
return;

if (!TryFindFirstAncestorOrSelf(root, context.Span, out SyntaxNode node, predicate: f => f.IsKind(SyntaxKind.EqualsValueClause, SyntaxKind.DeclarationExpression, SyntaxKind.SimpleAssignmentExpression)))
if (!TryFindFirstAncestorOrSelf(root, context.Span, out SyntaxNode node, predicate: f => f.IsKind(SyntaxKind.EqualsValueClause, SyntaxKind.DeclarationExpression, SyntaxKind.SimpleAssignmentExpression, SyntaxKind.CastExpression)))
return;

if (node is EqualsValueClauseSyntax equalsValueClause)
Expand Down Expand Up @@ -67,6 +68,10 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
}
}
}
else if (node is CastExpressionSyntax castExpression)
{
TryRegisterCodeFixForCast(context, diagnostic, castExpression.Type);
}
}

private static void TryRegisterCodeFix(CodeFixContext context, Diagnostic diagnostic, TypeSyntax type)
Expand All @@ -85,4 +90,46 @@ private static void TryRegisterCodeFix(CodeFixContext context, Diagnostic diagno

context.RegisterCodeFix(codeAction, diagnostic);
}

private static void TryRegisterCodeFixForCast(CodeFixContext context, Diagnostic diagnostic, TypeSyntax type)
{
if (type.IsKind(SyntaxKind.NullableType))
return;

CodeAction codeAction = CodeAction.Create(
"Declare as nullable",
async ct =>
{
NullableTypeSyntax newType = SyntaxFactory.NullableType(type.WithoutTrivia()).WithTriviaFrom(type);

// This could be in a variable declaration whose type we also may have to change
if (type.Parent?.Parent is EqualsValueClauseSyntax
{
Parent: VariableDeclaratorSyntax
{
Parent: VariableDeclarationSyntax
{
Variables.Count: 1,
Type: { IsVar: false } declarationType
} variableDeclaration
}
}
&& !declarationType.IsKind(SyntaxKind.NullableType))
{
NullableTypeSyntax newDeclarationType = SyntaxFactory.NullableType(declarationType.WithoutTrivia()).WithTriviaFrom(declarationType);
VariableDeclarationSyntax newVariableDeclaration = variableDeclaration
.ReplaceNode(type, newType)
.WithType(newDeclarationType);

return await context.Document.ReplaceNodeAsync(variableDeclaration, newVariableDeclaration, ct).ConfigureAwait(false);
}
else
{
return await context.Document.ReplaceNodeAsync(type, newType, ct).ConfigureAwait(false);
}
},
GetEquivalenceKey(diagnostic));

context.RegisterCodeFix(codeAction, diagnostic);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,40 @@ void M()
", equivalenceKey: EquivalenceKey.Create(DiagnosticId));
}

[Fact, Trait(Traits.CodeFix, CompilerDiagnosticIdentifiers.CS8600_ConvertingNullLiteralOrPossibleNullValueToNonNullableType)]
public async Task Test_LocalDeclarationWithCast()
{
await VerifyFixAsync(@"
using System;
#nullable enable

public class C
{
private object? Get() => null;

void M()
{
var s = (string) Get();
string s2 = (string) Get();
}
}
", @"
using System;
#nullable enable

public class C
{
private object? Get() => null;

void M()
{
var s = (string?) Get();
string? s2 = (string?) Get();
}
}
", equivalenceKey: EquivalenceKey.Create(DiagnosticId));
}

[Fact, Trait(Traits.CodeFix, CompilerDiagnosticIdentifiers.CS8600_ConvertingNullLiteralOrPossibleNullValueToNonNullableType)]
public async Task Test_DeclarationExpression()
{
Expand Down