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.03k stars 4.03k forks source link

Enforcing IDE0007 (Use implicit type) as a build warning for only one of three supported var code style options seems difficult #44250

Open mavasani opened 4 years ago

mavasani commented 4 years ago

Consider the below test snippet, with the desired IDE0007 diagnostics:

public class Class1
{
    public static void M()
    {
        Class1 x = new Class1();  // Want "use var" to be enforced as build warning here
        object o = new object();  // Want "use var" to be enforced as build warning here
        Class1 x2 = M2();  // Want "use var" to be an IDE suggestion here
        object x3 = M3();  // Want "use var" to be an IDE suggestion here
    }

    public static Class1 M2() => null;

    public static object M3() => 0;
}

Ideally, the following settings would suffice to get the above behavior:

[*.cs]
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_elsewhere = true:suggestion
csharp_style_var_when_type_is_apparent = true:warning

However, due to https://github.com/dotnet/roslyn/issues/44201, we are forced to add the below entry to editorconfig to get build time enforcement:

[*.cs]
dotnet_diagnostic.IDE0007.severity = warning

This in turn bumps up all the 3 buckets of csharp_style_var violations to warnings, so you end up warnings for all the 4 local declarations above: image

So, the only alternative to turn off csharp_style_var_elsewhere and csharp_style_var_when_type_is_apparent as follows:

[*.cs]
dotnet_diagnostic.IDE0007.severity = warning
csharp_style_var_for_built_in_types = false:none
csharp_style_var_elsewhere = false:none
csharp_style_var_when_type_is_apparent = true:warning

This gives correct enforcement for the first case, but not second. Assuming the second case is disregarded, you still lose the suggestions (three dots '...') for all but warning cases. image

We do get a refactoring "use implicit type" for these cases, but they will be bumped down the list if you have any other code fixes in the list, for example: image

I think the root cause for all these issues is that we use same diagnostic ID IDE0007 for all the csharp_style_var code style options.

mavasani commented 4 years ago

@sharwell mentioned this is a duplicate of https://github.com/dotnet/roslyn/issues/26531#issuecomment-582558152.

I am going to repurpose this issue to a pure design/code style issue to finalize the desired build enforcement for Roslyn IDE layers.

sharwell commented 4 years ago

However, due to #44201, we are forced to add the below entry to editorconfig to get build time enforcement:

This is the problem #27712 aimed to solve.

sharwell commented 1 year ago

I found a workaround for this issue: https://github.com/dotnet/winforms/commit/e8e42f7