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

Don't offer to simplify lambdas if it would change semantics #69101

Merged
merged 3 commits into from
Jul 19, 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 @@ -176,6 +176,26 @@ private void AnalyzeSyntax(SyntaxNodeAnalysisContext context, INamedTypeSymbol?
if (invokedMethod.GetAttributes().Any(a => Equals(a.AttributeClass, conditionalAttributeType)))
return;

// In the case where we have `() => expr.m()`, check if `expr` is overwritten anywhere. If so then we do not
// want to remove the lambda, as that will bind eagerly to the original `expr` and will not see the write
// that later happens
if (invokedExpression is MemberAccessExpressionSyntax { Expression: var accessedExpression })
{
// Limit the search space to the outermost code block that could contain references to this expr (or
// fall back to compilation unit for top level statements).
var outermostBody = invokedExpression.AncestorsAndSelf().Last(
n => n is BlockSyntax or ArrowExpressionClauseSyntax or AnonymousFunctionExpressionSyntax or CompilationUnitSyntax);
foreach (var candidate in outermostBody.DescendantNodes().OfType<ExpressionSyntax>())
{
if (candidate != accessedExpression &&
SemanticEquivalence.AreEquivalent(semanticModel, candidate, accessedExpression) &&
candidate.IsWrittenTo(semanticModel, cancellationToken))
{
return;
}
}
}

// Semantically, this looks good to go. Now, do an actual speculative replacement to ensure that the
// non-invoked method reference refers to the same method symbol, and that it converts to the same type that
// the lambda was.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,29 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryLambda
[Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryLambdaExpression)]
public class RemoveUnnecessaryLambdaExpressionTests
{
private static async Task TestInRegularAndScriptAsync(string testCode, string fixedCode, LanguageVersion version = LanguageVersion.Preview)
private static async Task TestInRegularAndScriptAsync(
string testCode,
string fixedCode,
LanguageVersion version = LanguageVersion.Preview,
OutputKind? outputKind = null)
{
await new VerifyCS.Test
{
TestCode = testCode,
FixedCode = fixedCode,
LanguageVersion = version,
TestState =
{
OutputKind = outputKind,
}
}.RunAsync();
}

private static Task TestMissingInRegularAndScriptAsync(string testCode, LanguageVersion version = LanguageVersion.Preview)
=> TestInRegularAndScriptAsync(testCode, testCode, version);
private static Task TestMissingInRegularAndScriptAsync(
string testCode,
LanguageVersion version = LanguageVersion.Preview,
OutputKind? outputKind = null)
=> TestInRegularAndScriptAsync(testCode, testCode, version, outputKind);

[Fact]
public async Task TestMissingInCSharp10()
Expand Down Expand Up @@ -1722,5 +1733,242 @@ private static void M2(Action<string> a) { }
}
""");
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")]
public async Task TestNotWithAssignmentOfInvokedExpression1()
{
await TestMissingInRegularAndScriptAsync("""
using System;
using System.Threading.Tasks;

TaskCompletionSource<bool> valueSet = new();
Helper helper = new(v => valueSet.SetResult(v));
helper.Set(true);
valueSet = new();
helper.Set(false);

class Helper
{
private readonly Action<bool> action;
internal Helper(Action<bool> action)
{
this.action = action;
}

internal void Set(bool value) => action(value);
}

""", outputKind: OutputKind.ConsoleApplication);
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")]
public async Task TestWithoutAssignmentOfInvokedExpression1()
{
await TestInRegularAndScriptAsync("""
using System;
using System.Threading.Tasks;

TaskCompletionSource<bool> valueSet = new();
Helper helper = new([|v => |]valueSet.SetResult(v));
helper.Set(true);
helper.Set(false);

class Helper
{
private readonly Action<bool> action;
internal Helper(Action<bool> action)
{
this.action = action;
}

internal void Set(bool value) => action(value);
}

""", """
using System;
using System.Threading.Tasks;

TaskCompletionSource<bool> valueSet = new();
Helper helper = new(valueSet.SetResult);
helper.Set(true);
helper.Set(false);

class Helper
{
private readonly Action<bool> action;
internal Helper(Action<bool> action)
{
this.action = action;
}

internal void Set(bool value) => action(value);
}

""",
outputKind: OutputKind.ConsoleApplication);
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")]
public async Task TestNotWithAssignmentOfInvokedExpression2()
{
await TestMissingInRegularAndScriptAsync("""
using System;
using System.Threading.Tasks;

class C
{
void M()
{
TaskCompletionSource<bool> valueSet = new();
Helper helper = new(v => valueSet.SetResult(v));
helper.Set(true);
valueSet = new();
helper.Set(false);
}
}

class Helper
{
private readonly Action<bool> action;
internal Helper(Action<bool> action)
{
this.action = action;
}

internal void Set(bool value) => action(value);
}

""");
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")]
public async Task TestWithoutAssignmentOfInvokedExpression2()
{
await TestInRegularAndScriptAsync("""
using System;
using System.Threading.Tasks;

class C
{
void M()
{
TaskCompletionSource<bool> valueSet = new();
Helper helper = new([|v => |]valueSet.SetResult(v));
helper.Set(true);
helper.Set(false);
}
}

class Helper
{
private readonly Action<bool> action;
internal Helper(Action<bool> action)
{
this.action = action;
}

internal void Set(bool value) => action(value);
}

""", """
using System;
using System.Threading.Tasks;

class C
{
void M()
{
TaskCompletionSource<bool> valueSet = new();
Helper helper = new(valueSet.SetResult);
helper.Set(true);
helper.Set(false);
}
}

class Helper
{
private readonly Action<bool> action;
internal Helper(Action<bool> action)
{
this.action = action;
}

internal void Set(bool value) => action(value);
}

""");
}

[Fact, WorkItem("https://github.com/dotnet/roslyn/issues/69094")]
public async Task TestWithoutAssignmentOfInvokedExpression3()
{
await TestInRegularAndScriptAsync("""
using System;
using System.Threading.Tasks;

class C
{
void M()
{
TaskCompletionSource<bool> valueSet = new();
Helper helper = new([|v => |]valueSet.SetResult(v));
helper.Set(true);
helper.Set(false);

var v = () =>
{
// this is a different local. it should not impact the outer simplification
TaskCompletionSource<bool> valueSet = new();
valueSet = new();
};
}
}

class Helper
{
private readonly Action<bool> action;
internal Helper(Action<bool> action)
{
this.action = action;
}

internal void Set(bool value) => action(value);
}

""", """
using System;
using System.Threading.Tasks;

class C
{
void M()
{
TaskCompletionSource<bool> valueSet = new();
Helper helper = new(valueSet.SetResult);
helper.Set(true);
helper.Set(false);

var v = () =>
{
// this is a different local. it should not impact the outer simplification
TaskCompletionSource<bool> valueSet = new();
valueSet = new();
};
}
}

class Helper
{
private readonly Action<bool> action;
internal Helper(Action<bool> action)
{
this.action = action;
}

internal void Set(bool value) => action(value);
}

""");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\ReferenceCountedDisposableCache.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\RestrictedInternalsVisibleToAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\SemanticEquivalence.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SemaphoreSlimFactory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SerializableBytes.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utilities\SoftCrashException.cs" />
Expand Down