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

Enhance: Inline variable in CA1854 (IDictionary.TryGetValue) #7071

Merged
merged 4 commits into from
Feb 23, 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
Original file line number Diff line number Diff line change
Expand Up @@ -58,19 +58,26 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
var dictionaryAccessors = new List<SyntaxNode>();
ExpressionStatementSyntax? addStatementNode = null;
SyntaxNode? changedValueNode = null;
string? variableName = null;
LocalDeclarationStatementSyntax? localDeclarationStatement = null;
VariableDeclaratorSyntax? variableDeclarator = null;
var additionalNodes = 0;
SyntaxNode? typeNode = null;
foreach (var location in diagnostic.AdditionalLocations)
{
var node = root.FindNode(location.SourceSpan, getInnermostNodeForTie: true);
switch (node)
{
case ElementAccessExpressionSyntax:
dictionaryAccessors.Add(node);
typeNode ??= node;
break;
case ExpressionStatementSyntax exp:
if (addStatementNode != null)
return null;

addStatementNode = exp;
additionalNodes++;
switch (addStatementNode.Expression)
{
case AssignmentExpressionSyntax assign:
Expand All @@ -83,15 +90,34 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
return null;
}

break;
case LocalDeclarationStatementSyntax local:
localDeclarationStatement = local;
variableName = local.Declaration.Variables[0].Identifier.ValueText;
additionalNodes++;
typeNode ??= local.Declaration.Type;
break;
case VariableDeclaratorSyntax
{
Parent: VariableDeclarationSyntax
{
Parent: LocalDeclarationStatementSyntax local
}
} declarator:
variableDeclarator = declarator;
localDeclarationStatement = local;
variableName = declarator.Identifier.ValueText;
additionalNodes++;
typeNode ??= local.Declaration.Type;
break;
}
}

if (diagnostic.AdditionalLocations.Count != dictionaryAccessors.Count + (addStatementNode != null ? 1 : 0))
if (diagnostic.AdditionalLocations.Count != dictionaryAccessors.Count + additionalNodes)
return null;

var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var type = model.GetTypeInfo(dictionaryAccessors[0], cancellationToken).Type;
var type = model.GetTypeInfo(typeNode!, cancellationToken).Type;

return CodeAction.Create(PreferDictionaryTryGetValueCodeFixTitle, async ct =>
{
Expand Down Expand Up @@ -119,7 +145,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
var outArgument = (ArgumentSyntax)generator.Argument(RefKind.Out,
DeclarationExpression(
typeSyntax,
SingleVariableDesignation(Identifier(Value))
SingleVariableDesignation(Identifier(variableName ?? Value))
)
);

Expand All @@ -128,7 +154,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
.AddArgumentListArguments(outArgument);
editor.ReplaceNode(containsKeyInvocation, tryGetValueInvocation);

var identifierName = (IdentifierNameSyntax)generator.IdentifierName(Value);
var identifierName = (IdentifierNameSyntax)generator.IdentifierName(variableName ?? Value);
if (addStatementNode != null)
{
editor.InsertBefore(addStatementNode,
Expand Down Expand Up @@ -160,6 +186,18 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
}
}

if (localDeclarationStatement is not null)
{
if (variableDeclarator is null)
{
editor.RemoveNode(localDeclarationStatement);
}
else
{
editor.RemoveNode(variableDeclarator);
}
}

return editor.GetChangedDocument();
}, PreferDictionaryTryGetValueCodeFixTitle);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,33 @@ private static bool FindUsages(IOperation operation, ref DictionaryUsageContext
case IIncrementOrDecrementOperation inc when inc.Target == indexer &&
inc.Parent is not IExpressionStatementOperation:
return false;
// C#
case IVariableInitializerOperation
{
Parent: IVariableDeclaratorOperation
{
Parent: IVariableDeclarationOperation
{
Parent: IVariableDeclarationGroupOperation declarationGroup
} declaration
} declarator
} init when init.Value == indexer:
usageContext.UsageLocations.Add(declaration.Children.Count() is 1
? declarationGroup.Syntax.GetLocation()
: declarator.Syntax.GetLocation());
continue;
// VB
case IVariableInitializerOperation
{
Parent: IVariableDeclarationOperation
{
Parent: IVariableDeclarationGroupOperation declarationGroup
} declaration
} init when init.Value == indexer:
usageContext.UsageLocations.Add(declarationGroup.Declarations.Length is 1
? declarationGroup.Syntax.GetLocation()
: declaration.Syntax.GetLocation());
continue;
}

usageContext.UsageLocations.Add(indexer.Syntax.GetLocation());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.

using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeFixes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,41 @@ bool GetDict(out IDictionary<string, int> dict)

return 0;";

private const string GuardedInlineVariable = @"
string key = ""key"";
var data = new Dictionary<string, string>();
if ({|#0:data.ContainsKey(key)|})
{
{|#1:var a = data[key];|}
}
return 0;";

private const string GuardedInlineVariableFixed = @"
string key = ""key"";
var data = new Dictionary<string, string>();
if (data.TryGetValue(key, out string a))
{
}
return 0;";

private const string GuardedInlineVariable2 = @"
string key = ""key"";
var data = new Dictionary<string, string>();
if ({|#0:data.ContainsKey(key)|})
{
string {|#1:a = data[key]|}, b = """";
}
return 0;";

private const string GuardedInlineVariable2Fixed = @"
string key = ""key"";
var data = new Dictionary<string, string>();
if (data.TryGetValue(key, out string a))
{
string b = """";
}
return 0;";

#region NoDiagnostic

private const string InvalidModifiedBeforeUse = @"
Expand Down Expand Up @@ -1064,6 +1099,43 @@ End If
End If
Return 0";

private const string VbGuardedInlineVariable = @"
Dim key = ""key""
Dim data = New Dictionary(Of String, String)()
If {|#0:data.ContainsKey(key)|} Then
{|#1:Dim x As String = data(key)|}
End If
Return 0";

private const string VbGuardedInlineVariableFixed = @"
Dim key = ""key""
Dim data = New Dictionary(Of String, String)()

Dim x As String = Nothing

If data.TryGetValue(key, x) Then
End If
Return 0";

private const string VbGuardedInlineVariable2 = @"
Dim key = ""key""
Dim data = New Dictionary(Of String, String)()
If {|#0:data.ContainsKey(key)|} Then
Dim {|#1:x As String = data(key)|}, y
End If
Return 0";

private const string VbGuardedInlineVariable2Fixed = @"
Dim key = ""key""
Dim data = New Dictionary(Of String, String)()

Dim x As String = Nothing

If data.TryGetValue(key, x) Then
Dim y
End If
Return 0";

#region NoDiagnostic

private const string VbInvalidModifiedBeforeUse = @"
Expand Down Expand Up @@ -1225,6 +1297,8 @@ End If
[InlineData(GuardedIndexerInSimpleAssignment, GuardedIndexerInSimpleAssignmentFixed)]
[InlineData(GuardedIndexerInCompoundAssignment, GuardedIndexerInCompoundAssignmentFixed)]
[InlineData(GuardedKeyInSimpleAssignment, GuardedKeyInSimpleAssignmentFixed)]
[InlineData(GuardedInlineVariable, GuardedInlineVariableFixed)]
[InlineData(GuardedInlineVariable2, GuardedInlineVariable2Fixed)]
public Task ShouldReportDiagnostic(string codeSnippet, string fixedCodeSnippet, int additionalLocations = 1)
{
string testCode = CreateCSharpCode(codeSnippet);
Expand Down Expand Up @@ -1296,6 +1370,8 @@ public Task ShouldNotReportDiagnostic(string codeSnippet, LanguageVersion versio
[InlineData(VbGuardedIndexerInSimpleAssignment, VbGuardedIndexerInSimpleAssignmentFixed)]
[InlineData(VbGuardedIndexerInCompoundAssignment, VbGuardedIndexerInCompoundAssignmentFixed)]
[InlineData(VbGuardedKeyInSimpleAssignment, VbGuardedKeyInSimpleAssignmentFixed)]
[InlineData(VbGuardedInlineVariable, VbGuardedInlineVariableFixed)]
[InlineData(VbGuardedInlineVariable2, VbGuardedInlineVariable2Fixed)]
public Task VbShouldReportDiagnostic(string codeSnippet, string fixedCodeSnippet, int additionalLocations = 1)
{
string testCode = CreateVbCode(codeSnippet);
Expand Down
Loading