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
18.92k stars 4.01k forks source link

Roslyn doesn't update pure null check openrands if pattern matching includes tuple expressions #50158

Open TessenR opened 3 years ago

TessenR commented 3 years ago

Version Used:

Branch master (19 Dec 2020)
Latest commit 80e9227 by msftbot[bot]:
Merge pull request #50073 from dotnet/merges/release/dev16.9-to-master

Merge release/dev16.9 to master

Steps to Reproduce:

Compile the following code

#nullable enable
class E
{
  public string F = "";
}

class Test
{
  void M1(E e)
  {
    switch (e, 1)
    {
      case ({ F: { } }, _): return;
    }
    e.F.ToString();
  }

  void M2(E e)
  {
    switch (e)
    {
      case { F: { } }: return;
    }
    e.F.ToString();
  }
}

Expected Behavior: Warnings for e.F dereference in both methods

Actual Behavior: Warning in M2 but not M1

Notes Roslyn updates pure null check pattern operands to nullable in NullableWalker.LearnFromAnyNullPatterns but it ignores pattern matching over tuple expressions

jcouv commented 3 years ago

Very broadly, a switch on a tuple literal currently loses the nullability states of the tuple elements.

Example:


#nullable enable
public class C 
{
    public void M(string? x) 
    {
        _ = ((x == null), 1) switch
        {
            (false, _) => x.ToString(), // warning CS8602: Dereference of a possibly null reference. (incorrect)
            _ => throw null!
        };
    }
}