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

Fix VSTHRD110 to not misfire due to parentheses in invocation expressions #1245

Merged
merged 1 commit into from
Oct 24, 2023
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 @@ -57,14 +57,33 @@ private void AnalyzeInvocation(OperationAnalysisContext context, CommonInterest.
return;
}

// Only consider invocations that are direct statements. Otherwise, we assume their
// result is awaited, assigned, or otherwise consumed.
if (operation.Parent is IExpressionStatementOperation || operation.Parent is IConditionalAccessOperation)
// Only consider invocations that are direct statements (or are statements through limited steps).
// Otherwise, we assume their result is awaited, assigned, or otherwise consumed.
IOperation? parentOperation = operation.Parent;
while (parentOperation is not null)
{
if (awaitableTypes.IsAwaitableType(operation.Type))
if (parentOperation is IExpressionStatementOperation)
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, operation.Syntax.GetLocation()));
// This expression is directly used in a statement.
break;
}

// This check is where we allow for specific operation types that may appear between the invocation
// and the statement that don't disqualify the invocation search for an invalid pattern.
if (parentOperation is IConditionalAccessOperation)
{
parentOperation = parentOperation.Parent;
}
else
{
// This expression is not directly used in a statement.
return;
}
}

if (awaitableTypes.IsAwaitableType(operation.Type))
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, operation.Syntax.GetLocation()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,24 @@ public async ValueTask DisposeAsync()
await CSVerify.VerifyAnalyzerAsync(test);
}

[Fact]
public async Task ParentheticalUseOfTaskResult_ProducesNoDiagnostic()
{
string test = """
using System;
using System.Threading.Tasks;

class Class1
{
public Func<Task<int>>? VCLoadMethod;

public int? VirtualCurrencyBalances => (VCLoadMethod?.Invoke()).GetAwaiter().GetResult();
}
""";

await CSVerify.VerifyAnalyzerAsync(test);
}

private DiagnosticResult CreateDiagnostic(int line, int column, int length)
=> CSVerify.Diagnostic().WithSpan(line, column, line, column + length);
}