Skip to content

Commit

Permalink
LookupSymbols excludes symbols from parent variable declarator (#589)
Browse files Browse the repository at this point in the history
  • Loading branch information
meziantou authored Aug 2, 2023
1 parent d3744b9 commit e4fcf73
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/Meziantou.Analyzer/Internals/OperationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,28 @@ static bool IsValid(Location location, int operationLocation, int? staticContext
}
}

if (symbol.Kind is SymbolKind.Local)
{
// var a = Sample(a); // cannot use "a"
var ancestors = operation.Ancestors();
var isInInitializer = false;
foreach (var ancestor in ancestors)
{
if (ancestor is IVariableDeclaratorOperation declaratorOperation)
{
if (declaratorOperation.Symbol.IsEqualTo(symbol))
{
isInInitializer = true;
break;
}
}
}

if (isInInitializer)
continue;
}


yield return symbol;
}
}
Expand Down
6 changes: 6 additions & 0 deletions tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,12 @@ public ProjectBuilder WithNoFixCompilation()
return this;
}

public ProjectBuilder WithDefaultAnalyzerId(string id)
{
DefaultAnalyzerId = id;
return this;
}

public ProjectBuilder WithAnalyzer(DiagnosticAnalyzer diagnosticAnalyzer, string id = null, string message = null)
{
DiagnosticAnalyzer.Add(diagnosticAnalyzer);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1019,4 +1019,23 @@ await CreateProjectBuilder()
.ValidateAsync();
}

[Fact]
public async Task CancellationTokenNotAvailableAsVariableDeclarator()
{
const string SourceCode = @"
using System.Threading;
class Test
{
public static void A()
{
CancellationToken Foo(CancellationToken cancellationToken = default) => cancellationToken;
var token = [||]Foo();
}
}";
await CreateProjectBuilder()
.WithDefaultAnalyzerId("MA0032")
.WithSourceCode(SourceCode)
.ValidateAsync();
}
}

0 comments on commit e4fcf73

Please sign in to comment.