Skip to content
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
8 changes: 7 additions & 1 deletion src/Meziantou.Analyzer/Internals/OperationExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Meziantou.Analyzer.Internals;
Expand Down Expand Up @@ -270,6 +270,12 @@ static bool IsValid(Location location, int operationLocation, int? staticContext

if (isInInitializer)
continue;

// Cannot use variables declared in top-level statements when not in this context
if (symbol.ContainingSymbol?.IsTopLevelStatement(cancellationToken) is true && operation.GetContainingMethod(cancellationToken)?.IsTopLevelStatement(cancellationToken) is not true)
{
continue;
}
}

yield return symbol;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,6 @@ public void AnalyzeLoop(OperationAnalysisContext context)

private string[] FindCancellationTokens(IOperation operation, CancellationToken cancellationToken)
{

var availableSymbols = new List<NameAndType>();

foreach (var symbol in operation.LookupAvailableSymbols(cancellationToken))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Threading.Tasks;
using System.Threading.Tasks;
using Meziantou.Analyzer.Rules;
using Meziantou.Analyzer.Test.Helpers;
using TestHelper;
Expand Down Expand Up @@ -1271,4 +1271,29 @@ class Sample
.ShouldReportDiagnosticWithMessage("Use an overload with a CancellationToken, available tokens: Xunit.TestContext.Current.CancellationToken")
.ValidateAsync();
}

[Fact]
public async Task TopLevelStatements()
{
await CreateProjectBuilder()
.WithSourceCode("""
using System.Threading;
using System.Threading.Tasks;

var cancellationToken = CancellationToken.None;

class Sample
{
void Foo()
{
{|MA0032:Repro()|};
}

public static void Repro() => throw null;
public static void Repro(CancellationToken cancellationToken) => throw null;
}
""")
.WithOutputKind(Microsoft.CodeAnalysis.OutputKind.ConsoleApplication)
.ValidateAsync();
}
}