Skip to content
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

Merged
merged 7 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2
Expand All @@ -31,19 +32,76 @@ 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);
var key = new HostAnalyzerStateSetKey(project.Language, project.State.HasSdkCodeStyleAnalyzers, project.Solution.SolutionState.Analyzers.HostAnalyzerReferences);
// 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(
Copy link
Member

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<...

Copy link
Member Author

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 an IEnumerable<ImmutableArray<DiagnosticAnalyzer>>. The use of these IEnumerable's is also piped into StateManager.CreateStateSetMap. This might be cleanup for a follow up PR.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which is an IEnumerable<ImmutableArray>

Ick :) Can that one change?

Copy link
Member

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.

Copy link
Member Author

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.

ImmutableDictionary<object, ImmutableArray<DiagnosticAnalyzer>> analyzersPerReference,
ImmutableHashSet<object> referenceIdsToRedirectAsProjectAnalyzers)
{
if (referenceIdsToRedirectAsProjectAnalyzers.IsEmpty)
{
return (analyzersPerReference.Values, []);
}

var hostAnalyzerCollection = ArrayBuilder<ImmutableArray<DiagnosticAnalyzer>>.GetInstance();
var projectAnalyzerCollection = ArrayBuilder<ImmutableArray<DiagnosticAnalyzer>>.GetInstance();

foreach (var (referenceId, analyzers) in analyzersPerReference)
{
if (referenceIdsToRedirectAsProjectAnalyzers.Contains(referenceId))
{
projectAnalyzerCollection.Add(analyzers);
}
else
{
hostAnalyzerCollection.Add(analyzers);
}
}

return (hostAnalyzerCollection.ToImmutableAndFree(), projectAnalyzerCollection.ToImmutableAndFree());
}
}

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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,23 +187,28 @@ private static ImmutableDictionary<DiagnosticAnalyzer, StateSet> CreateStateSetM

private readonly struct HostAnalyzerStateSetKey : IEquatable<HostAnalyzerStateSetKey>
{
public HostAnalyzerStateSetKey(string language, IReadOnlyList<AnalyzerReference> analyzerReferences)
public HostAnalyzerStateSetKey(string language, bool hasSdkCodeStyleAnalyzers, IReadOnlyList<AnalyzerReference> analyzerReferences)
{
Language = language;
HasSdkCodeStyleAnalyzers = hasSdkCodeStyleAnalyzers;
AnalyzerReferences = analyzerReferences;
}

public string Language { get; }
public bool HasSdkCodeStyleAnalyzers { get; }
public IReadOnlyList<AnalyzerReference> AnalyzerReferences { get; }

public bool Equals(HostAnalyzerStateSetKey other)
=> Language == other.Language && AnalyzerReferences == other.AnalyzerReferences;
=> Language == other.Language &&
HasSdkCodeStyleAnalyzers == other.HasSdkCodeStyleAnalyzers &&
AnalyzerReferences == other.AnalyzerReferences;

public override bool Equals(object? obj)
=> obj is HostAnalyzerStateSetKey key && Equals(key);

public override int GetHashCode()
=> Hash.Combine(Language.GetHashCode(), AnalyzerReferences.GetHashCode());
=> Hash.Combine(Language.GetHashCode(),
Hash.Combine(HasSdkCodeStyleAnalyzers.GetHashCode(), AnalyzerReferences.GetHashCode()));
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,12 +211,18 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim
Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync(
"Project", LanguageNames.CSharp, CancellationToken.None)

' Ensure HasSdkCodeStyleAnalyzers is proper.
Assert.False(project.HasSdkCodeStyleAnalyzers)

' These are the in-box C# codestyle analyzers that ship with the SDK
project.AddAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "cs", "Microsoft.CodeAnalysis.CodeStyle.dll"))
project.AddAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "cs", "Microsoft.CodeAnalysis.CodeStyle.Fixes.dll"))
project.AddAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "cs", "Microsoft.CodeAnalysis.CSharp.CodeStyle.dll"))
project.AddAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "cs", "Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes.dll"))

' Ensure HasSdkCodeStyleAnalyzers is being properly updated.
Assert.True(project.HasSdkCodeStyleAnalyzers)

' Ensure they are not returned when getting AnalyzerReferences
Assert.Empty(environment.Workspace.CurrentSolution.Projects.Single().AnalyzerReferences)

Expand All @@ -228,6 +234,15 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim
{
Path.Combine(TempRoot.Root, "Dir", "File.dll")
}, environment.Workspace.CurrentSolution.Projects.Single().AnalyzerReferences.Select(Function(r) r.FullPath))

' Remove codestyle analyzers
project.RemoveAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "cs", "Microsoft.CodeAnalysis.CodeStyle.dll"))
project.RemoveAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "cs", "Microsoft.CodeAnalysis.CodeStyle.Fixes.dll"))
project.RemoveAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "cs", "Microsoft.CodeAnalysis.CSharp.CodeStyle.dll"))
project.RemoveAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "cs", "Microsoft.CodeAnalysis.CSharp.CodeStyle.Fixes.dll"))

' Ensure HasSdkCodeStyleAnalyzers is being properly updated.
Assert.False(project.HasSdkCodeStyleAnalyzers)
End Using
End Function

Expand All @@ -237,12 +252,18 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim
Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync(
"Project", LanguageNames.VisualBasic, CancellationToken.None)

' Ensure HasSdkCodeStyleAnalyzers is proper.
Assert.False(project.HasSdkCodeStyleAnalyzers)

' These are the in-box VB codestyle analyzers that ship with the SDK
project.AddAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "vb", "Microsoft.CodeAnalysis.CodeStyle.dll"))
project.AddAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "vb", "Microsoft.CodeAnalysis.CodeStyle.Fixes.dll"))
project.AddAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "vb", "Microsoft.CodeAnalysis.VisualBasic.CodeStyle.dll"))
project.AddAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "vb", "Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.dll"))

' Ensure HasSdkCodeStyleAnalyzers is being properly updated.
Assert.True(project.HasSdkCodeStyleAnalyzers)

' Ensure they are not returned when getting AnalyzerReferences
Assert.Empty(environment.Workspace.CurrentSolution.Projects.Single().AnalyzerReferences)

Expand All @@ -254,6 +275,14 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim
{
Path.Combine(TempRoot.Root, "Dir", "File.dll")
}, environment.Workspace.CurrentSolution.Projects.Single().AnalyzerReferences.Select(Function(r) r.FullPath))

project.RemoveAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "vb", "Microsoft.CodeAnalysis.CodeStyle.dll"))
project.RemoveAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "vb", "Microsoft.CodeAnalysis.CodeStyle.Fixes.dll"))
project.RemoveAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "vb", "Microsoft.CodeAnalysis.VisualBasic.CodeStyle.dll"))
project.RemoveAnalyzerReference(Path.Combine(TempRoot.Root, "Sdks", "Microsoft.NET.Sdk", "codestyle", "vb", "Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.dll"))

' Ensure HasSdkCodeStyleAnalyzers is being properly updated.
Assert.False(project.HasSdkCodeStyleAnalyzers)
End Using
End Function
End Class
Expand Down
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);
}
}
Loading
Loading