Skip to content

Commit 7cefa27

Browse files
authored
Remove unaccessible local symbols (#797)
1 parent 391f64f commit 7cefa27

File tree

3 files changed

+33
-3
lines changed

3 files changed

+33
-3
lines changed

src/Meziantou.Analyzer/Internals/OperationExtensions.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System.Collections.Generic;
1+
using System.Collections.Generic;
22
using System.Linq;
33
using System.Threading;
44
using Meziantou.Analyzer.Internals;
@@ -270,6 +270,12 @@ static bool IsValid(Location location, int operationLocation, int? staticContext
270270

271271
if (isInInitializer)
272272
continue;
273+
274+
// Cannot use variables declared in top-level statements when not in this context
275+
if (symbol.ContainingSymbol?.IsTopLevelStatement(cancellationToken) is true && operation.GetContainingMethod(cancellationToken)?.IsTopLevelStatement(cancellationToken) is not true)
276+
{
277+
continue;
278+
}
273279
}
274280

275281
yield return symbol;

src/Meziantou.Analyzer/Rules/UseAnOverloadThatHasCancellationTokenAnalyzer.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,6 @@ public void AnalyzeLoop(OperationAnalysisContext context)
309309

310310
private string[] FindCancellationTokens(IOperation operation, CancellationToken cancellationToken)
311311
{
312-
313312
var availableSymbols = new List<NameAndType>();
314313

315314
foreach (var symbol in operation.LookupAvailableSymbols(cancellationToken))

tests/Meziantou.Analyzer.Test/Rules/UseAnOverloadThatHasCancellationTokenAnalyzerTests.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System.Threading.Tasks;
1+
using System.Threading.Tasks;
22
using Meziantou.Analyzer.Rules;
33
using Meziantou.Analyzer.Test.Helpers;
44
using TestHelper;
@@ -1271,4 +1271,29 @@ class Sample
12711271
.ShouldReportDiagnosticWithMessage("Use an overload with a CancellationToken, available tokens: Xunit.TestContext.Current.CancellationToken")
12721272
.ValidateAsync();
12731273
}
1274+
1275+
[Fact]
1276+
public async Task TopLevelStatements()
1277+
{
1278+
await CreateProjectBuilder()
1279+
.WithSourceCode("""
1280+
using System.Threading;
1281+
using System.Threading.Tasks;
1282+
1283+
var cancellationToken = CancellationToken.None;
1284+
1285+
class Sample
1286+
{
1287+
void Foo()
1288+
{
1289+
{|MA0032:Repro()|};
1290+
}
1291+
1292+
public static void Repro() => throw null;
1293+
public static void Repro(CancellationToken cancellationToken) => throw null;
1294+
}
1295+
""")
1296+
.WithOutputKind(Microsoft.CodeAnalysis.OutputKind.ConsoleApplication)
1297+
.ValidateAsync();
1298+
}
12741299
}

0 commit comments

Comments
 (0)