-
Notifications
You must be signed in to change notification settings - Fork 4.1k
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
Closed
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
2bd49a3
Adding CSharpUseDefaultExpressionCodeFixProvider
Neme12 f57cd7a
Adding missing ExportCodeFixProvider.Name for UseDefaultLiteral
Neme12 20d7519
Adding a defensive null check
Neme12 cf01567
Fixing resource string
Neme12 a2a735e
Not offering the code fix for an error type, adding tests for cases w…
Neme12 4cce95c
Using default(T) in the code fix title
Neme12 2fba4f0
Adding 1 more test
Neme12 17dd3a5
Merge remote-tracking branch 'upstream/master' into useDefaultExpression
Neme12 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
830 changes: 830 additions & 0 deletions
830
src/EditorFeatures/CSharpTest/UseDefaultExpression/UseDefaultExpressionTests.cs
Large diffs are not rendered by default.
Oops, something went wrong.
9 changes: 9 additions & 0 deletions
9
src/Features/CSharp/Portable/CSharpFeaturesResources.Designer.cs
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
...eatures/CSharp/Portable/UseDefaultExpression/CSharpUseDefaultExpressionCodeFixProvider.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | ||
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) | ||
{ | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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?).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)