-
Notifications
You must be signed in to change notification settings - Fork 4.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
When replacing CodeStyle analyzers do not provide Features analyzers fallback options #75534
Changes from 5 commits
0a838b9
180455c
03eccdd
e9f7c04
1198405
7344695
dff04fe
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -32,18 +32,75 @@ public IEnumerable<StateSet> GetAllHostStateSets() | |
private HostAnalyzerStateSets GetOrCreateHostStateSets(Project project, ProjectAnalyzerStateSets projectStateSets) | ||
{ | ||
var key = new HostAnalyzerStateSetKey(project.Language, project.Solution.SolutionState.Analyzers.HostAnalyzerReferences); | ||
var hostStateSets = ImmutableInterlocked.GetOrAdd(ref _hostAnalyzerStateMap, key, CreateLanguageSpecificAnalyzerMap, project.Solution.SolutionState.Analyzers); | ||
// Some Host Analyzers may need to be treated as Project Analyzers so that they do not have access to the | ||
// Host fallback options. These ids will be used when building up the Host and Project analyzer collections. | ||
var referenceIdsToRedirect = GetReferenceIdsToRedirectAsProjectAnalyzers(project); | ||
var hostStateSets = ImmutableInterlocked.GetOrAdd(ref _hostAnalyzerStateMap, key, CreateLanguageSpecificAnalyzerMap, (project.Solution.SolutionState.Analyzers, referenceIdsToRedirect)); | ||
return hostStateSets.WithExcludedAnalyzers(projectStateSets.SkippedAnalyzersInfo.SkippedAnalyzers); | ||
|
||
static HostAnalyzerStateSets CreateLanguageSpecificAnalyzerMap(HostAnalyzerStateSetKey arg, HostDiagnosticAnalyzers hostAnalyzers) | ||
static HostAnalyzerStateSets CreateLanguageSpecificAnalyzerMap(HostAnalyzerStateSetKey arg, (HostDiagnosticAnalyzers HostAnalyzers, ImmutableHashSet<object> ReferenceIdsToRedirect) state) | ||
{ | ||
var language = arg.Language; | ||
var analyzersPerReference = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(language); | ||
var analyzersPerReference = state.HostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(language); | ||
|
||
var analyzerMap = CreateStateSetMap(language, [], analyzersPerReference.Values, includeWorkspacePlaceholderAnalyzers: true); | ||
var (hostAnalyzerCollection, projectAnalyzerCollection) = GetAnalyzerCollections(analyzersPerReference, state.ReferenceIdsToRedirect); | ||
var analyzerMap = CreateStateSetMap(language, projectAnalyzerCollection, hostAnalyzerCollection, includeWorkspacePlaceholderAnalyzers: true); | ||
|
||
return new HostAnalyzerStateSets(analyzerMap); | ||
} | ||
|
||
static (IEnumerable<ImmutableArray<DiagnosticAnalyzer>> HostAnalyzerCollection, IEnumerable<ImmutableArray<DiagnosticAnalyzer>> ProjectAnalyzerCollection) GetAnalyzerCollections( | ||
ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> analyzersPerReference, | ||
ImmutableHashSet<object> referenceIdsToRedirectAsProjectAnalyzers) | ||
{ | ||
if (referenceIdsToRedirectAsProjectAnalyzers.IsEmpty) | ||
{ | ||
return (analyzersPerReference.Values, []); | ||
} | ||
|
||
var hostAnalyzerCollection = new List<ImmutableArray<DiagnosticAnalyzer>>(); | ||
var projectAnalyzerCollection = new List<ImmutableArray<DiagnosticAnalyzer>>(); | ||
|
||
foreach (var kvp in analyzersPerReference) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Deconstruct: |
||
{ | ||
if (referenceIdsToRedirectAsProjectAnalyzers.Contains(kvp.Key)) | ||
{ | ||
projectAnalyzerCollection.Add(kvp.Value); | ||
} | ||
else | ||
{ | ||
hostAnalyzerCollection.Add(kvp.Value); | ||
} | ||
} | ||
|
||
return (hostAnalyzerCollection, projectAnalyzerCollection); | ||
} | ||
} | ||
|
||
private static ImmutableHashSet<object> GetReferenceIdsToRedirectAsProjectAnalyzers(Project project) | ||
{ | ||
if (project.State.HasSdkCodeStyleAnalyzers) | ||
{ | ||
// When a project uses CodeStyle analyzers added by the SDK, we remove them in favor of the | ||
// Features analyzers. We need to then treat the Features analyzers as Project analyzers so | ||
// they do not get access to the Host fallback options. | ||
return GetFeaturesAnalyzerReferenceIds(project.Solution.SolutionState.Analyzers); | ||
} | ||
|
||
return []; | ||
|
||
static ImmutableHashSet<object> GetFeaturesAnalyzerReferenceIds(HostDiagnosticAnalyzers hostAnalyzers) | ||
{ | ||
var builder = ImmutableHashSet.CreateBuilder<object>(); | ||
|
||
foreach (var analyzerReference in hostAnalyzers.HostAnalyzerReferences) | ||
{ | ||
if (analyzerReference.IsFeaturesAnalyzer()) | ||
builder.Add(analyzerReference.Id); | ||
} | ||
|
||
return builder.ToImmutable(); | ||
} | ||
} | ||
|
||
private sealed class HostAnalyzerStateSets | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using System.Collections.Immutable; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.Formatting; | ||
using Microsoft.CodeAnalysis.Options; | ||
using Microsoft.CodeAnalysis.Shared.TestHooks; | ||
using Roslyn.Test.Utilities; | ||
using Roslyn.VisualStudio.IntegrationTests; | ||
using Roslyn.VisualStudio.NewIntegrationTests.InProcess; | ||
using Xunit; | ||
|
||
namespace Roslyn.VisualStudio.NewIntegrationTests.CSharp; | ||
|
||
public class CSharpRedirectFeaturesAnalyzers : AbstractEditorTest | ||
{ | ||
protected override string LanguageName => LanguageNames.CSharp; | ||
|
||
private const int GlobalIndentationSize = 6; | ||
private const int DefaultIndentationSize = 4; | ||
|
||
[IdeFact] | ||
public async Task DoesNotUseHostOptions_WhenEnforceCodeStyleInBuildIsTrue() | ||
{ | ||
await SetupSolutionAsync( | ||
enforceCodeStyleInBuild: true, | ||
GlobalIndentationSize, | ||
HangMitigatingCancellationToken); | ||
|
||
var code = GenerateTestCode(GlobalIndentationSize); | ||
|
||
await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "C.cs", code, open: true, cancellationToken: HangMitigatingCancellationToken); | ||
|
||
var errors = await GetErrorsFromErrorListAsync(HangMitigatingCancellationToken); | ||
AssertEx.Equal( | ||
[ | ||
"C.cs(3, 5): error IDE0055: Fix formatting", | ||
"C.cs(4, 5): error IDE0055: Fix formatting", | ||
"C.cs(6, 5): error IDE0055: Fix formatting", | ||
], | ||
errors); | ||
} | ||
|
||
[IdeFact] | ||
public async Task UsesHostOptions_WhenEnforceCodeStyleInBuildIsFalse() | ||
{ | ||
await SetupSolutionAsync( | ||
enforceCodeStyleInBuild: false, | ||
GlobalIndentationSize, | ||
HangMitigatingCancellationToken); | ||
|
||
var code = GenerateTestCode(DefaultIndentationSize); | ||
|
||
await TestServices.SolutionExplorer.AddFileAsync(ProjectName, "C.cs", code, open: true, cancellationToken: HangMitigatingCancellationToken); | ||
|
||
var errors = await GetErrorsFromErrorListAsync(HangMitigatingCancellationToken); | ||
AssertEx.Equal( | ||
[ | ||
"C.cs(3, 5): error IDE0055: Fix formatting", | ||
"C.cs(4, 5): error IDE0055: Fix formatting", | ||
"C.cs(6, 5): error IDE0055: Fix formatting", | ||
], | ||
errors); | ||
} | ||
|
||
private async Task SetupSolutionAsync(bool enforceCodeStyleInBuild, int globalIndentationSize, CancellationToken cancellationToken) | ||
{ | ||
await TestServices.SolutionExplorer.CreateSolutionAsync(SolutionName, cancellationToken); | ||
|
||
await TestServices.SolutionExplorer.AddCustomProjectAsync( | ||
ProjectName, | ||
".csproj", | ||
$""" | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net8.0</TargetFramework> | ||
<Nullable>enable</Nullable> | ||
<EnforceCodeStyleInBuild>{enforceCodeStyleInBuild}</EnforceCodeStyleInBuild> | ||
</PropertyGroup> | ||
|
||
</Project> | ||
""", | ||
cancellationToken); | ||
await TestServices.SolutionExplorer.RestoreNuGetPackagesAsync(ProjectName, cancellationToken); | ||
|
||
// Configure the global indentation size which would be part of the Host fallback options. | ||
var globalOptions = await TestServices.Shell.GetComponentModelServiceAsync<IGlobalOptionService>(cancellationToken); | ||
globalOptions.SetGlobalOption(FormattingOptions2.UseTabs, LanguageNames.CSharp, false); | ||
globalOptions.SetGlobalOption(FormattingOptions2.IndentationSize, LanguageNames.CSharp, globalIndentationSize); | ||
|
||
// Add .editorconfig to configure so that formatting diagnostics are errors | ||
await TestServices.SolutionExplorer.AddFileAsync(ProjectName, | ||
".editorconfig", | ||
""" | ||
root = true | ||
|
||
[*.cs] | ||
dotnet_diagnostic.IDE0055.severity = error | ||
""", | ||
open: false, | ||
cancellationToken); | ||
|
||
await TestServices.Workspace.WaitForAllAsyncOperationsAsync( | ||
[ | ||
FeatureAttribute.Workspace, | ||
FeatureAttribute.SolutionCrawlerLegacy, | ||
FeatureAttribute.DiagnosticService, | ||
FeatureAttribute.ErrorSquiggles | ||
], | ||
cancellationToken); | ||
} | ||
|
||
private static string GenerateTestCode(int indentationSize) | ||
{ | ||
var indentation = new string(' ', indentationSize); | ||
return $$""" | ||
class C | ||
{ | ||
{{indentation}}void M() | ||
{{indentation}}{ | ||
|
||
{{indentation}}} | ||
} | ||
"""; | ||
} | ||
|
||
private async Task<ImmutableArray<string>> GetErrorsFromErrorListAsync(CancellationToken cancellationToken) | ||
{ | ||
await WaitForCodeActionListToPopulateAsync(cancellationToken); | ||
|
||
await TestServices.ErrorList.ShowErrorListAsync(cancellationToken); | ||
await TestServices.Workspace.WaitForAllAsyncOperationsAsync( | ||
[ | ||
FeatureAttribute.Workspace, | ||
FeatureAttribute.SolutionCrawlerLegacy, | ||
FeatureAttribute.DiagnosticService, | ||
FeatureAttribute.ErrorSquiggles, | ||
FeatureAttribute.ErrorList | ||
], | ||
cancellationToken); | ||
return await TestServices.ErrorList.GetErrorsAsync(cancellationToken); | ||
} | ||
|
||
private async Task WaitForCodeActionListToPopulateAsync(CancellationToken cancellationToken) | ||
{ | ||
await TestServices.Editor.ActivateAsync(cancellationToken); | ||
await TestServices.Editor.PlaceCaretAsync("void M()", charsOffset: -1, cancellationToken); | ||
|
||
await TestServices.Editor.InvokeCodeActionListAsync(cancellationToken); | ||
|
||
await TestServices.Workspace.WaitForAllAsyncOperationsAsync( | ||
[ | ||
FeatureAttribute.Workspace, | ||
FeatureAttribute.SolutionCrawlerLegacy, | ||
FeatureAttribute.DiagnosticService, | ||
FeatureAttribute.ErrorSquiggles | ||
], | ||
cancellationToken); | ||
|
||
await TestServices.Editor.DismissLightBulbSessionAsync(cancellationToken); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,7 @@ | |
using System.Collections.Generic; | ||
using System.Collections.Immutable; | ||
using System.Diagnostics; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
@@ -81,14 +82,33 @@ public static string GetAnalyzerId(this DiagnosticAnalyzer analyzer) | |
|
||
private static string GetAssemblyQualifiedName(Type type) | ||
{ | ||
// AnalyzerFileReference now includes things like versions, public key as part of its identity. | ||
// AnalyzerFileReference now includes things like versions, public key as part of its identity. | ||
// so we need to consider them. | ||
return RoslynImmutableInterlocked.GetOrAdd( | ||
ref s_typeToAssemblyQualifiedName, | ||
type, | ||
static type => type.AssemblyQualifiedName ?? throw ExceptionUtilities.UnexpectedValue(type)); | ||
} | ||
|
||
private static readonly ImmutableHashSet<string> s_featuresAnalyzerFileNames = new[] { | ||
"Microsoft.CodeAnalysis.Features.dll", | ||
"Microsoft.CodeAnalysis.CSharp.Features.dll", | ||
"Microsoft.CodeAnalysis.VisualBasic.Features.dll", | ||
}.ToImmutableHashSet(StringComparer.OrdinalIgnoreCase); | ||
|
||
private static ImmutableSegmentedDictionary<string, bool> s_analyzerFullPathToIsFeatureAnalyzer = ImmutableSegmentedDictionary<string, bool>.Empty; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we need to cache this? It's just simple comparison of 3 strings. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You can simplify to:
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. agreed. dictionaries fo rthis seem unnecessary. |
||
|
||
public static bool IsFeaturesAnalyzer(this AnalyzerReference reference) | ||
{ | ||
if (reference.FullPath is null) | ||
return false; | ||
|
||
return RoslynImmutableInterlocked.GetOrAdd( | ||
ref s_analyzerFullPathToIsFeatureAnalyzer, | ||
reference.FullPath, | ||
static fullPath => s_featuresAnalyzerFileNames.Contains(Path.GetFileName(fullPath))); | ||
} | ||
|
||
public static async Task<ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResultBuilder>> ToResultBuilderMapAsync( | ||
this AnalysisResult analysisResult, | ||
ImmutableArray<Diagnostic> additionalPragmaSuppressionDiagnostics, | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
def don't like returning these as lazy enumerbles. can you make both an
ImmutableArray<ImmutableArray<...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I could but then we have to do something about the common case where we aren't redirecting and are returning
analyzersPerReference.Values
which is anIEnumerable<ImmutableArray<DiagnosticAnalyzer>>
. The use of these IEnumerable's is also piped intoStateManager.CreateStateSetMap
. This might be cleanup for a follow up PR.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ick :) Can that one change?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
at the very least, don't return mutable lists. return an immutable array here. that way we don't have to worry about it changing.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Updated to use ArrayBuilder instead of List.