dotnet / dotnet/roslyn

Diagnostic suppressor seems to work only for open files

Open
#75,291 8 comments 1 reaction 0 assignees View on GitHub
Area-Analyzers Diagnostic-Suppressors
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

Hi,

this is somewhat of a follow-up to https://github.com/dotnet/roslyn/issues/68885. I've initially reported this to https://github.com/nunit/nunit.analyzers/issues/786 as well, but it doesn't seem to be an issue with the analyzer itself.

For context: The NUnit.Analyzer package provides diagnostic suppressor to suppress nullable warnings for objects that can be null, but have previously been checked with NUnit's asserts that they are not null.

We recently changed a legacy test project that previously had NRTs disabled to enable them. We saw hundreds of "CS8602 - Dereference of a possibly null reference" warnings for objects that can be in fact null, but were checked with some variation of "Assert this is not null". Curiously, the warnings weren't reported at build time and disappeared after the file with the warning was opened.

Here's a repro, mostly based on the Roslyn issue above:
Project file:
```xml


net8.0
false
false
true
enable
enable


true
true




NU1608


all
runtime; build; native; contentfiles; analyzers; buildtransitive

```

Test:
```csharp
using NUnit.Framework;

namespace NUnitNullabilityTest
{
[TestFixture]
public class Tests
{
private class Model
{
public string? Name { get; set; }

public string? SomeMethod() => Name;
}

[Test]
public void Model_SomeMethod()
{
var target = new Model { Name = "name" };

var result = target.SomeMethod();

Assert.That(result, Is.Not.Null);
Assert.That(result.Length, Is.EqualTo(4)); // This is of course a nonsense assertion, but repros the issue
}
}
}

```

`result` can technically be null, so `result.Length` could theoretically throw an NRE. Since `Is.Not.Null` is asserted, we can be sure it's not null.

This produces the warning if the file is not opened:
![image](https://github.com/user-attachments/assets/68a9f255-5d14-4ea8-b078-d2e055b158be)

An vanishes if the file is opened:
![image](https://github.com/user-attachments/assets/3841e942-b98d-4fed-9c27-c98045242dfc)

Contributor guide

Open the contributing guide

Research direction

Start with the provided project file and the Tests.Model_SomeMethod repro, comparing build diagnostics before and after opening the file. Then investigate Roslyn's diagnostic-suppressor handling for closed documents. Done means the NUnit nullable suppression is applied consistently at build time and opening the file no longer changes CS8602.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
compilers, developer-experience
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.