Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code fix for CS8313, CS8363 (invalid default literal as case constant / pattern) to use default expression #30359

Closed
wants to merge 8 commits into from

Large diffs are not rendered by default.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/Features/CSharp/Portable/CSharpFeaturesResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -569,4 +569,7 @@
<data name="Remove_unused_variables" xml:space="preserve">
<value>Remove unused variables</value>
</data>
<data name="Use_default_0" xml:space="preserve">
<value>Use 'default({0})'</value>
</data>
</root>
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.UseDefaultExpression
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseDefaultExpression), Shared]
internal sealed class CSharpUseDefaultExpressionCodeFixProvider : CodeFixProvider
{
private const string CS8313 = nameof(CS8313); // A default literal 'default' is not valid as a case constant. Use another literal (e.g. '0' or 'null') as appropriate. If you intended to write the default label, use 'default:' without 'case'.
private const string CS8363 = nameof(CS8363); // A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern 'var _'.
private const string CS8107 = nameof(CS8107); // Feature is not available in C# 7.0. Please use language version X or greater.
Copy link
Contributor Author

@Neme12 Neme12 Oct 7, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jcouv When I get one of these errors of "Feature X is not available", is it possible to determine which feature it is? (I need to know this is specifically "feature 'default literal'"). I couldn't find anything in the diagnostic properties. Do you have an idea? Thanks.

Currently I'm just checking that the token found at the diagnostic location is a default literal, and that's probably sufficient, but it doesn't feel right. I assumed it would be possible to make a more precise check to verify that this is the right diagnostic we are looking for. Also, I don't think it would be as easy to check in case of other features (that we might want to provide code fixes for in the future), where it's not simply a matter of looking for a certain token.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, i'd love something cleaner here as well.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd be tempted to give default a dedicated error code in this case (ie. change compiler) as we did for some other "feature is not available" features.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jcouv But that wouldn't work for other features. Why not just add something to the diagnostic properties, similar to RequiredLanguageVersion? The way I imagine it, there would be a property called LanguageFeature with either a value of "default literal" (always the english string for the feature, so that it can be switched on programatically) or something like IDS_FeatureDefaultLiteral (but that would probably require making the compiler enum public).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's possible for sure, but it seems a rather big hammer (especially making enum public) and I'm not yet sure about the generalized problem (how often do we need this?).

Copy link
Contributor Author

@Neme12 Neme12 Oct 8, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be useful for code fixes similar to this, which see a language feature you cannot use in this language version and offer to convert it to something you can use. For example, a code fix to change out var into a declared variable, or a code fix from async Main into what the compiler would generate.

They would need to know the error is about the feature they're interested in.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Relates to #19871 (making the language version diagnostic more parameterized and structured)

private const string CS8059 = nameof(CS8059); // Feature is not available in C# 6. Please use language version X or greater.
private const string CS8026 = nameof(CS8026); // Feature is not available in C# 5. Please use language version X or greater.
private const string CS8025 = nameof(CS8025); // Feature is not available in C# 4. Please use language version X or greater.
private const string CS8024 = nameof(CS8024); // Feature is not available in C# 3. Please use language version X or greater.
private const string CS8023 = nameof(CS8023); // Feature is not available in C# 2. Please use language version X or greater.

public override ImmutableArray<string> FixableDiagnosticIds { get; } =
ImmutableArray.Create(CS8313, CS8363, CS8107, CS8059, CS8026, CS8025, CS8024, CS8023);

public override FixAllProvider GetFixAllProvider()
{
// This code fix addresses very specific compiler errors. It's unlikely there will be more than 1 of them at a time.
return null;
}

public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var token = syntaxRoot.FindToken(context.Span.Start);

if (token.Span == context.Span &&
token.IsKind(SyntaxKind.DefaultKeyword) &&
token.Parent.IsKind(SyntaxKind.DefaultLiteralExpression))
{
var defaultLiteral = (LiteralExpressionSyntax)token.Parent;
var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

var type = semanticModel.GetTypeInfo(defaultLiteral, context.CancellationToken).ConvertedType;
if (type == null || type.TypeKind == TypeKind.Error)
{
return;
}

if (type.IsAnonymousType)
{
type = semanticModel.Compilation.GetSpecialType(SpecialType.System_Object);
}

// If there happens to be more than 1 diagnostic (for example a default literal in a case label in C# 7.0),
// we will fix all of them, so pass in context.Diagnostics, not just the first one.
context.RegisterCodeFix(
new MyCodeAction(
c => FixAsync(context.Document, context.Span, type, c),
type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)),
context.Diagnostics);
}
}

private static async Task<Document> FixAsync(Document document, TextSpan span, ITypeSymbol type, CancellationToken cancellationToken)
{
var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

var defaultToken = syntaxRoot.FindToken(span.Start);
var defaultLiteral = (LiteralExpressionSyntax)defaultToken.Parent;

var typeSyntax = type.GenerateTypeSyntax(allowVar: false);

var defaultExpression =
SyntaxFactory.DefaultExpression(
defaultToken.WithoutTrivia(),
SyntaxFactory.Token(SyntaxKind.OpenParenToken),
typeSyntax,
SyntaxFactory.Token(SyntaxKind.CloseParenToken)).WithTriviaFrom(defaultLiteral);

var newRoot = syntaxRoot.ReplaceNode(defaultLiteral, defaultExpression);
return document.WithSyntaxRoot(newRoot);
}

private sealed class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string type)
: base(string.Format(CSharpFeaturesResources.Use_default_0, type), createChangedDocument, CSharpFeaturesResources.Use_default_0)
{
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

namespace Microsoft.CodeAnalysis.CSharp.UseDefaultLiteral
{
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseDefaultLiteral), Shared]
internal partial class CSharpUseDefaultLiteralCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">Seřadit modifikátory dostupnosti</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">Příkaz if lze zjednodušit.</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">Zugriffsmodifizierer sortieren</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">Die if-Anweisung kann vereinfacht werden.</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">Ordenar modificadores de accesibilidad</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">La instrucción "if" se puede simplificar</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">Trier les modificateurs d'accessibilité</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">L'instruction 'if' peut être simplifiée</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">Ordina i modificatori di accessibilità</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">L'istruzione 'if' può essere semplificata</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">アクセシビリティ修飾子を並べ替える</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">'if' ステートメントは簡素化できます</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">접근성 한정자 정렬</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">'if' 문을 간단하게 줄일 수 있습니다.</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">Sortuj modyfikatory dostępności</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">Instrukcja „if” może zostać uproszczona</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">Classificar modificadores de acessibilidade</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">A instrução 'if' pode ser simplificada</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">Сортировать модификаторы доступности</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">Оператор if можно упростить</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">Erişilebilirlik değiştiricilerini sırala</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">'if' deyimi basitleştirilebilir</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">对可访问性修饰符排序</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">可简化“if”语句</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@
<target state="translated">排序協助工具修飾詞</target>
<note />
</trans-unit>
<trans-unit id="Use_default_0">
<source>Use 'default({0})'</source>
<target state="new">Use 'default({0})'</target>
<note />
</trans-unit>
<trans-unit id="if_statement_can_be_simplified">
<source>'if' statement can be simplified</source>
<target state="translated">'if' 陳述式可簡化</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ internal static class PredefinedCodeFixProviderNames
public const string Suppression = nameof(Suppression);
public const string AddOverloads = nameof(AddOverloads);
public const string AddNew = nameof(AddNew);
public const string UseDefaultExpression = nameof(UseDefaultExpression);
public const string UseDefaultLiteral = nameof(UseDefaultLiteral);
public const string UseImplicitType = nameof(UseImplicitType);
public const string UseExplicitType = nameof(UseExplicitType);
public const string UseCollectionInitializer = nameof(UseCollectionInitializer);
Expand Down
1 change: 1 addition & 0 deletions src/Test/Utilities/Portable/Traits/Traits.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ public static class Features
public const string CodeActionsUseCompoundAssignment = "CodeActions.UseCompoundAssignment";
public const string CodeActionsUseConditionalExpression = "CodeActions.UseConditionalExpression";
public const string CodeActionsUseDeconstruction = "CodeActions.UseDeconstruction";
public const string CodeActionsUseDefaultExpression = "CodeActions.UseDefaultExpression";
public const string CodeActionsUseDefaultLiteral = "CodeActions.UseDefaultLiteral";
public const string CodeActionsUseInferredMemberName = "CodeActions.UseInferredMemberName";
public const string CodeActionsUseExpressionBody = "CodeActions.UseExpressionBody";
Expand Down