-
Notifications
You must be signed in to change notification settings - Fork 480
Add UseExceptionThrowHelpers analyzer/fixer #6293
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
This file contains hidden or 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 hidden or 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
534 changes: 534 additions & 0 deletions
534
src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpers.cs
Large diffs are not rendered by default.
Oops, something went wrong.
148 changes: 148 additions & 0 deletions
148
src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpersFixer.cs
This file contains hidden or 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,148 @@ | ||
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. | ||
|
|
||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Threading.Tasks; | ||
| using Analyzer.Utilities; | ||
| using Analyzer.Utilities.Extensions; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.Editing; | ||
|
|
||
| namespace Microsoft.NetCore.Analyzers.Runtime | ||
| { | ||
| /// <summary>Fixer for <see cref="UseExceptionThrowHelpers"/>.</summary> | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared] | ||
| public sealed class UseExceptionThrowHelpersFixer : CodeFixProvider | ||
| { | ||
| public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create( | ||
| UseExceptionThrowHelpers.UseArgumentNullExceptionThrowIfNullRuleId, | ||
| UseExceptionThrowHelpers.UseArgumentExceptionThrowIfNullOrEmptyRuleId, | ||
| UseExceptionThrowHelpers.UseArgumentOutOfRangeExceptionThrowIfRuleId, | ||
| UseExceptionThrowHelpers.UseObjectDisposedExceptionThrowIfRuleId); | ||
|
|
||
| public sealed override FixAllProvider GetFixAllProvider() => CustomFixAllProvider.Instance; | ||
|
|
||
| public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| Document doc = context.Document; | ||
| SemanticModel model = await doc.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); | ||
| SyntaxNode root = await doc.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
|
|
||
| if (TryGetFixInfo(doc, root, model, context.Diagnostics[0], out INamedTypeSymbol? typeSymbol, out string? methodName, out SyntaxNode? node, out SyntaxNode? arg, out SyntaxNode? other)) | ||
| { | ||
| string title = string.Format(MicrosoftNetCoreAnalyzersResources.UseThrowHelperFix, typeSymbol.Name, methodName); | ||
| context.RegisterCodeFix( | ||
| CodeAction.Create(title, equivalenceKey: title, createChangedDocument: async cancellationToken => | ||
| { | ||
| DocumentEditor editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false); | ||
| ApplyFix(typeSymbol, methodName, node, arg, other, editor); | ||
| return editor.GetChangedDocument(); | ||
| }), | ||
| context.Diagnostics); | ||
| } | ||
| } | ||
|
|
||
| private static bool TryGetFixInfo( | ||
| Document doc, | ||
| SyntaxNode root, | ||
| SemanticModel model, | ||
| Diagnostic diagnostic, | ||
| [NotNullWhen(true)] out INamedTypeSymbol? typeSymbol, | ||
| [NotNullWhen(true)] out string? methodName, | ||
| [NotNullWhen(true)] out SyntaxNode? node, | ||
| [NotNullWhen(true)] out SyntaxNode? arg, | ||
| [NotNullWhen(true)] out SyntaxNode? other) | ||
| { | ||
| typeSymbol = null; | ||
| methodName = null; | ||
| arg = null; | ||
| other = null; | ||
|
|
||
| node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); | ||
| if (node != null && | ||
| diagnostic.AdditionalLocations.Count != 0 && | ||
| diagnostic.AdditionalLocations[0] is Location argLocation) | ||
| { | ||
| arg = root.FindNode(argLocation.SourceSpan, getInnermostNodeForTie: true); | ||
| string id = diagnostic.Id; | ||
|
|
||
| if (diagnostic.AdditionalLocations.Count == 2) | ||
| { | ||
| Location otherLocation = diagnostic.AdditionalLocations[1]; | ||
| other = otherLocation == Location.None ? // None is special-cased by the analyzer to mean "this" | ||
| SyntaxGenerator.GetGenerator(doc).ThisExpression() : | ||
| root.FindNode(otherLocation.SourceSpan, getInnermostNodeForTie: true); | ||
| } | ||
|
|
||
| switch (id) | ||
| { | ||
| case UseExceptionThrowHelpers.UseArgumentNullExceptionThrowIfNullRuleId: | ||
| typeSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentNullException); | ||
| methodName = "ThrowIfNull"; | ||
| break; | ||
|
|
||
| case UseExceptionThrowHelpers.UseArgumentExceptionThrowIfNullOrEmptyRuleId: | ||
| typeSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentException); | ||
| methodName = "ThrowIfNullOrEmpty"; | ||
| break; | ||
|
|
||
| case UseExceptionThrowHelpers.UseArgumentOutOfRangeExceptionThrowIfRuleId: | ||
| typeSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentOutOfRangeException); | ||
| diagnostic.Properties.TryGetValue(UseExceptionThrowHelpers.MethodNamePropertyKey, out methodName); | ||
| break; | ||
|
|
||
| case UseExceptionThrowHelpers.UseObjectDisposedExceptionThrowIfRuleId when other is not null: | ||
| typeSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObjectDisposedException); | ||
| methodName = "ThrowIf"; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| return typeSymbol != null && methodName != null && arg != null; | ||
| } | ||
|
|
||
| private static void ApplyFix( | ||
| INamedTypeSymbol typeSymbol, | ||
| string methodName, | ||
| SyntaxNode node, | ||
| SyntaxNode arg, | ||
| SyntaxNode other, | ||
| SyntaxEditor editor) | ||
| { | ||
| editor.ReplaceNode( | ||
| node, | ||
| editor.Generator.ExpressionStatement( | ||
| editor.Generator.InvocationExpression( | ||
| editor.Generator.MemberAccessExpression( | ||
| editor.Generator.TypeExpressionForStaticMemberAccess(typeSymbol), methodName), | ||
| other is not null ? new SyntaxNode[] { arg, other } : new SyntaxNode[] { arg })).WithTriviaFrom(node)); | ||
| } | ||
|
|
||
| private sealed class CustomFixAllProvider : DocumentBasedFixAllProvider | ||
| { | ||
| public static readonly CustomFixAllProvider Instance = new(); | ||
|
|
||
| protected override string CodeActionTitle => MicrosoftNetCoreAnalyzersResources.UseThrowHelperFix; | ||
|
|
||
| protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics) | ||
| { | ||
| DocumentEditor editor = await DocumentEditor.CreateAsync(document, fixAllContext.CancellationToken).ConfigureAwait(false); | ||
| SyntaxNode root = editor.OriginalRoot; | ||
| SemanticModel model = editor.SemanticModel; | ||
|
|
||
| foreach (Diagnostic diagnostic in diagnostics) | ||
| { | ||
| if (TryGetFixInfo(document, root, model, diagnostic, out INamedTypeSymbol? typeSymbol, out string? methodName, out SyntaxNode? node, out SyntaxNode? arg, out SyntaxNode? other)) | ||
| { | ||
| ApplyFix(typeSymbol, methodName, node, arg, other, editor); | ||
| } | ||
| } | ||
|
|
||
| return editor.GetChangedRoot(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or 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 hidden or 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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.