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 1 commit
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? valueName = null;
Poker-sang marked this conversation as resolved.
Show resolved Hide resolved
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;
valueName = local.Declaration.Variables[0].Identifier.ValueText;
additionalNodes++;
typeNode ??= local.Declaration.Type;
break;
case VariableDeclaratorSyntax
{
Parent: VariableDeclarationSyntax
{
Parent: LocalDeclarationStatementSyntax local
}
} declarator:
variableDeclarator = declarator;
localDeclarationStatement = local;
valueName = 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 @@ -122,13 +148,13 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
var outArgument = generator.Argument(RefKind.Out,
DeclarationExpression(
typeSyntax,
SingleVariableDesignation(Identifier(Value))
SingleVariableDesignation(Identifier(valueName ?? Value))
)
);
var tryGetValueInvocation = generator.InvocationExpression(tryGetValueAccess, keyArgument, outArgument);
editor.ReplaceNode(containsKeyInvocation, tryGetValueInvocation);

var identifierName = (IdentifierNameSyntax)generator.IdentifierName(Value);
var identifierName = (IdentifierNameSyntax)generator.IdentifierName(valueName ?? 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,20 @@ private static bool FindUsages(IOperation operation, ref DictionaryUsageContext
case IIncrementOrDecrementOperation inc when inc.Target == indexer &&
inc.Parent is not IExpressionStatementOperation:
return false;
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;
}

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
@@ -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.Generic;
using System.Globalization;
Expand Down 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 @@ -1225,6 +1260,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