dotnet / roslyn-analyzers

MIT License
1.59k stars 466 forks source link

RS1022 false positive when accessing a constant #5341

Open jnm2 opened 3 years ago

jnm2 commented 3 years ago

Analyzer

Diagnostic ID: RS1022 Change diagnostic analyzer type 'SomeAnalyzer' to remove all direct and/or indirect accesses to type(s) 'SomeCodeFixProvider', which access type(s) '[...]'

NuGet Package: Microsoft.CodeAnalysis.Analyzers

Version: 3.0.0

Describe the bug

I declare public constant strings for diagnostic property names consumed by the code fix in the code fix class since the code fix is the sole reason for the existence of the diagnostic properties.

It is safe to access these constants from the analyzer because the compiler does not leave any trace of a reference within the analyzer class to the code fix class in the compile output.

Steps To Reproduce

using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class SomeAnalyzer : DiagnosticAnalyzer
{
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException();

    public override void Initialize(AnalysisContext context)
    {
        _ = SomeCodeFixProvider.SomeDiagnosticPropertyName;
    }
}

[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public sealed class SomeCodeFixProvider : CodeFixProvider
{
    public const string SomeDiagnosticPropertyName = "SomeDiagnosticProperty";

    public override ImmutableArray<string> FixableDiagnosticIds => throw new NotImplementedException();

    public override Task RegisterCodeFixesAsync(CodeFixContext context)
    {
        throw new NotImplementedException();
    }
}

⚠ RS1022 Change diagnostic analyzer type 'SomeAnalyzer' to remove all direct and/or indirect accesses to type(s) 'SomeCodeFixProvider', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixContext, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.ExportCodeFixProviderAttribute'

mavasani commented 3 years ago

We can specially handle this false positive, but I believe the common pattern is to have such constants defined in the analyzer and then have the code fix type reference them.