Skip to content

Field symbol from symbol tree and operation tree fail Equals check in presence of nullable enable #38195

@mavasani

Description

@mavasani

Originally reported dotnet/roslyn-analyzers#2776, which seems to be a breaking change in analyzer behavior in presence of #nullable enable. I have created an isolated IOperation unit test:

        [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.NullableReferenceTypes)]
        [Fact]
        public void NullableFieldReference()
        {
            var compWithoutNullable = CreateCompilation(@"
class C<T>
{
    private C<T> _field;
    public static void M(C<T> p)
    {
        _ = p._field;
    }
}");
            var compWithNullable = CreateCompilation(@"
#nullable enable
class C<T>
{
    private C<T>? _field;
    public static void M(C<T> p)
    {
        _ = p._field;
    }
}", options: WithNonNullTypesTrue());


            testCore(compWithoutNullable); // Passes
            testCore(compWithNullable); // Fails

            static void testCore(CSharpCompilation comp)
            {
                var syntaxTree = comp.SyntaxTrees[0];
                var model = comp.GetSemanticModel(syntaxTree);
                var root = syntaxTree.GetRoot();
                var classDecl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single();
                var classSym = (INamedTypeSymbol)model.GetDeclaredSymbol(classDecl);
                var fieldSym = classSym.GetMembers("_field").Single();

                var methodDecl = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
                var methodBlockOperation = model.GetOperation(methodDecl);
                var fieldReferenceOperation = methodBlockOperation.Descendants().OfType<IFieldReferenceOperation>().Single();
                Assert.True(fieldSym.Equals(fieldReferenceOperation.Field));
            }
        }

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions