dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19.05k stars 4.03k forks source link

CA1823 incorrectly flags const used as a fixed buffer length #37593

Open stephentoub opened 5 years ago

stephentoub commented 5 years ago

Analyzer package

Microsoft.CodeAnalysis.FxCopAnalyzers

Package Version

v2.9.4

Diagnostic ID

CA1823

Repro steps

using System.Runtime.InteropServices;

class Program
{
    static void Main() { }

    private const int SomeLength = 16;

    [StructLayout(LayoutKind.Sequential)]
    internal unsafe struct SomeStruct
    {
        internal fixed byte FixedBuffer[SomeLength];
    }
}

Expected behavior

No warnings.

Actual behavior

The CA1823 analyzer flags the SomeLength const as being unused:

Program.cs(7,23,7,33): warning CA1823: Unused field 'SomeLength'.

even though obviously it is being used.

mavasani commented 5 years ago

@jinujoseph @vatsalyaagrawal Can we port this issue to Roslyn repo? The issue does not seem specific to this analyzer. Seems like there is no IFieldReferenceOperation being generated for SomeLength usage in internal fixed byte FixedBuffer[SomeLength];.

Even Find All References also does not seem to find this reference to SomeLength, and the reference is also not colored as a normal reference would be, so it is very likely that the underlying compiler bound tree does not have a bound node representing this field reference.

stephentoub commented 5 years ago

Even Find All References also does not seem to find this reference to SomeLength

Yeah, and the Rename support doesn't fix the reference, IDE0051 flags it as unused, Go to Definition on the reference fails, etc.

CyrusNajmabadi commented 5 years ago

QuiclInfo doesn't work either. So this is likely a deeper SemanticModel issue, not just an IOp issue.

mavasani commented 5 years ago

@CyrusNajmabadi is correct - this is a deeper issue in the compiler layer. Moved to Area-Compilers.

sharwell commented 4 years ago

The underlying semantic model issue is likely #29224

gwr commented 2 months ago

FYI, there's an instance of this warning in PR https://github.com/dotnet/runtime/pull/105403 src/libraries/Common/src/Interop/SunOS/procfs/Interop.ProcFs.Definitions.cs Would be nice to remove that pragma once this is fixed. Let me know if a separate issue is wanted for that.