Skip to content

Commit

Permalink
Fix false-positive for MA0106 when capturing a parameter inside the l…
Browse files Browse the repository at this point in the history
…ambda
  • Loading branch information
meziantou committed Dec 18, 2023
1 parent 186ea1c commit 241bedc
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,9 @@ private static void DetectClosure(OperationAnalysisContext context, IOperation a
var dataFlow = semanticModel.AnalyzeDataFlow(syntax);
if (dataFlow.CapturedInside.Length > 0)
{
// A parameter can be captured inside (by another lambda)
var parameters = GetParameters(argumentOperation);
if (dataFlow.Captured.Any(s => !parameters.Contains(s, SymbolEqualityComparer.Default)))
if (dataFlow.CapturedInside.Any(s => !parameters.Contains(s, SymbolEqualityComparer.Default)))
{
context.ReportDiagnostic(RuleFactoryArg, argumentOperation, string.Join(", ", dataFlow.Captured.Select(symbol => symbol.Name)));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis;

namespace Meziantou.Analyzer.Rules;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,28 @@ await CreateProjectBuilder()
.WithSourceCode(SourceCode)
.ValidateAsync();
}

[Fact]
public async Task GetOrAdd_NoClosure()
{
const string SourceCode = """
using System;
using System.Collections.Concurrent;
using System.Linq;
var dict = new ConcurrentDictionary<string, Type>();
dict.GetOrAdd("", static layout2 =>
{
var types = System.Array.Empty<string>().Where(t => t == layout2);
throw null!;
});
var dummy = new object();
var f = new System.Func<bool>(() => dummy != null);
""";
await CreateProjectBuilder()
.WithOutputKind(Microsoft.CodeAnalysis.OutputKind.ConsoleApplication)
.WithSourceCode(SourceCode)
.ValidateAsync();
}
}

0 comments on commit 241bedc

Please sign in to comment.