Skip to content

Commit 9b20c0b

Browse files
committed
Fix ContainsGlobalUsingAlias when the file starts with a global using directive
1 parent 57bc0cc commit 9b20c0b

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp11/ReadabilityRules/SA1121CSharp11UnitTests.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,28 @@ class TestClass
4141
FixedSources = { source1, newSource2 },
4242
}.RunAsync(CancellationToken.None).ConfigureAwait(false);
4343
}
44+
45+
[Fact]
46+
[WorkItem(3594, "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3594")]
47+
public async Task TestUsingNameChangeInGlobalUsingInSameFileAsync()
48+
{
49+
var source = @"global using MyDouble = System.Double;
50+
class TestClass
51+
{
52+
private [|MyDouble|] x;
53+
}";
54+
55+
var newSource = @"global using MyDouble = System.Double;
56+
class TestClass
57+
{
58+
private double x;
59+
}";
60+
61+
await new CSharpTest()
62+
{
63+
TestSources = { source },
64+
FixedSources = { newSource },
65+
}.RunAsync(CancellationToken.None).ConfigureAwait(false);
66+
}
4467
}
4568
}

StyleCop.Analyzers/StyleCop.Analyzers/Helpers/UsingAliasCache.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,10 @@ private bool ContainsGlobalUsingAlias(SemanticModel semanticModel, CancellationT
7171
{
7272
if (this.perCompilationCache == -1)
7373
{
74-
// Check for global using aliases
75-
var scopes = semanticModel.GetImportScopes(0, cancellationToken);
74+
// Check for global using aliases. We check at the end of the file since GetImportScopes is observed to
75+
// omit global using directives in the current file at position 0 for the specific case where there is
76+
// no whitespace preceding the global using directives.
77+
var scopes = semanticModel.GetImportScopes(semanticModel.SyntaxTree.Length, cancellationToken);
7678
Interlocked.CompareExchange(ref this.perCompilationCache, scopes.Any(x => x.Aliases.Length > 0) ? 1 : 0, -1);
7779
}
7880

0 commit comments

Comments
 (0)