-
Notifications
You must be signed in to change notification settings - Fork 16
feat: Add code fix for INTL0301/INTL0302 (FavorDirectoryEnumerationCalls) #400
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
Open
BenjaminMichaelis
wants to merge
1
commit into
main
Choose a base branch
from
bmichaelis/codefixFavorDirectoryEnumerationCalls
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
207 changes: 207 additions & 0 deletions
207
IntelliTect.Analyzer/IntelliTect.Analyzer.CodeFixes/FavorDirectoryEnumerationCalls.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,207 @@ | ||
| using System.Collections.Immutable; | ||
| using System.Composition; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Formatting; | ||
| using Microsoft.CodeAnalysis.Text; | ||
|
|
||
| namespace IntelliTect.Analyzer.CodeFixes | ||
| { | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(FavorDirectoryEnumerationCalls))] | ||
| [Shared] | ||
| public class FavorDirectoryEnumerationCalls : CodeFixProvider | ||
| { | ||
| private const string TitleGetFiles = "Use Directory.EnumerateFiles"; | ||
| private const string TitleGetDirectories = "Use Directory.EnumerateDirectories"; | ||
|
|
||
| public sealed override ImmutableArray<string> FixableDiagnosticIds => | ||
| ImmutableArray.Create( | ||
| Analyzers.FavorDirectoryEnumerationCalls.DiagnosticId301, | ||
| Analyzers.FavorDirectoryEnumerationCalls.DiagnosticId302); | ||
|
|
||
| public sealed override FixAllProvider GetFixAllProvider() => | ||
| WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
|
|
||
| Diagnostic diagnostic = context.Diagnostics.First(); | ||
| TextSpan diagnosticSpan = diagnostic.Location.SourceSpan; | ||
|
|
||
| // The diagnostic span covers the full invocation expression (Directory.GetFiles(...)) | ||
| InvocationExpressionSyntax invocation = root.FindToken(diagnosticSpan.Start) | ||
| .Parent.AncestorsAndSelf() | ||
| .OfType<InvocationExpressionSyntax>() | ||
| .First(); | ||
|
|
||
| bool isGetFiles = diagnostic.Id == Analyzers.FavorDirectoryEnumerationCalls.DiagnosticId301; | ||
| string title = isGetFiles ? TitleGetFiles : TitleGetDirectories; | ||
| string newMethodName = isGetFiles ? "EnumerateFiles" : "EnumerateDirectories"; | ||
|
|
||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: title, | ||
| createChangedDocument: c => UseEnumerationMethodAsync(context.Document, invocation, newMethodName, c), | ||
| equivalenceKey: title), | ||
| diagnostic); | ||
| } | ||
|
|
||
| private static async Task<Document> UseEnumerationMethodAsync( | ||
| Document document, | ||
| InvocationExpressionSyntax invocation, | ||
| string newMethodName, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; | ||
|
|
||
| SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); | ||
|
|
||
| // Rename: Directory.GetFiles(...) → Directory.EnumerateFiles(...) | ||
| InvocationExpressionSyntax renamedInvocation = invocation.WithExpression( | ||
| memberAccess.WithName(SyntaxFactory.IdentifierName(newMethodName))); | ||
|
|
||
| ExpressionSyntax replacement = NeedsToArrayWrapper(invocation, semanticModel, cancellationToken) | ||
| // Wrap as Directory.EnumerateFiles(...).ToArray() | ||
| ? SyntaxFactory.InvocationExpression( | ||
| SyntaxFactory.MemberAccessExpression( | ||
| SyntaxKind.SimpleMemberAccessExpression, | ||
| renamedInvocation, | ||
| SyntaxFactory.IdentifierName("ToArray"))) | ||
| : renamedInvocation; | ||
|
|
||
| SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
| SyntaxNode newRoot = oldRoot.ReplaceNode(invocation, replacement.WithAdditionalAnnotations(Formatter.Annotation)); | ||
|
|
||
| if (replacement != renamedInvocation && newRoot is CompilationUnitSyntax compilationUnit) | ||
| { | ||
| newRoot = AddUsingIfMissing(compilationUnit, "System.Linq"); | ||
| } | ||
|
|
||
| return document.WithSyntaxRoot(newRoot); | ||
| } | ||
|
|
||
| private static bool NeedsToArrayWrapper( | ||
| InvocationExpressionSyntax invocation, | ||
| SemanticModel semanticModel, | ||
| CancellationToken ct) | ||
| { | ||
| SyntaxNode parent = invocation.Parent; | ||
|
|
||
| // string[] files = Directory.GetFiles(...) or field/property initializer | ||
| if (parent is EqualsValueClauseSyntax equalsValue) | ||
| { | ||
| // Local variable or field: string[] files = ... / private string[] _files = ... | ||
| if (equalsValue.Parent is VariableDeclaratorSyntax | ||
| && equalsValue.Parent.Parent is VariableDeclarationSyntax declaration | ||
| && semanticModel.GetTypeInfo(declaration.Type, ct).Type is IArrayTypeSymbol) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| // Property initializer: public string[] Files { get; } = Directory.GetFiles(...) | ||
| if (equalsValue.Parent is PropertyDeclarationSyntax property | ||
| && semanticModel.GetTypeInfo(property.Type, ct).Type is IArrayTypeSymbol) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| // files = Directory.GetFiles(...) | ||
| if (parent is AssignmentExpressionSyntax assignment | ||
| && semanticModel.GetTypeInfo(assignment.Left, ct).Type is IArrayTypeSymbol) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| // return Directory.GetFiles(...) in a method or local function returning string[] | ||
| if (parent is ReturnStatementSyntax) | ||
| { | ||
| TypeSyntax returnType = invocation.Ancestors() | ||
| .Select(a => a switch | ||
| { | ||
| MethodDeclarationSyntax m => m.ReturnType, | ||
| LocalFunctionStatementSyntax lf => lf.ReturnType, | ||
| _ => null | ||
| }) | ||
| .FirstOrDefault(t => t != null); | ||
| if (returnType != null | ||
| && semanticModel.GetTypeInfo(returnType, ct).Type is IArrayTypeSymbol) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
BenjaminMichaelis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // Expression-bodied members: string[] GetFiles() => Directory.GetFiles(...) | ||
| if (parent is ArrowExpressionClauseSyntax arrow) | ||
| { | ||
| TypeSyntax returnType = arrow.Parent switch | ||
| { | ||
| MethodDeclarationSyntax m => m.ReturnType, | ||
| LocalFunctionStatementSyntax lf => lf.ReturnType, | ||
| PropertyDeclarationSyntax p => p.Type, | ||
| _ => null | ||
| }; | ||
| if (returnType != null && semanticModel.GetTypeInfo(returnType, ct).Type is IArrayTypeSymbol) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| // SomeMethod(Directory.GetFiles(...)) where the parameter type is string[] | ||
| if (parent is ArgumentSyntax argument | ||
| && argument.Parent is ArgumentListSyntax argumentList | ||
| && argumentList.Parent is InvocationExpressionSyntax outerInvocation | ||
| && semanticModel.GetSymbolInfo(outerInvocation, ct).Symbol is IMethodSymbol outerMethod) | ||
| { | ||
| IParameterSymbol targetParam; | ||
|
|
||
| // Named argument: SomeMethod(param: Directory.GetFiles(...)) | ||
| if (argument.NameColon != null) | ||
| { | ||
| string paramName = argument.NameColon.Name.Identifier.Text; | ||
| targetParam = outerMethod.Parameters.FirstOrDefault(p => p.Name == paramName); | ||
| } | ||
| else | ||
| { | ||
| int argIndex = argumentList.Arguments.IndexOf(argument); | ||
| int paramCount = outerMethod.Parameters.Length; | ||
| targetParam = argIndex >= 0 && argIndex < paramCount | ||
| ? outerMethod.Parameters[argIndex] | ||
| : argIndex >= 0 && paramCount > 0 && outerMethod.Parameters[paramCount - 1].IsParams | ||
| ? outerMethod.Parameters[paramCount - 1] | ||
| : null; | ||
| } | ||
|
|
||
| if (targetParam?.Type is IArrayTypeSymbol) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private static SyntaxNode AddUsingIfMissing(CompilationUnitSyntax root, string namespaceName) | ||
| { | ||
| bool alreadyPresent = root.Usings.Any(u => u.Name?.ToString() == namespaceName); | ||
| if (alreadyPresent) | ||
| { | ||
| return root; | ||
| } | ||
|
|
||
| UsingDirectiveSyntax newUsing = SyntaxFactory.UsingDirective( | ||
| SyntaxFactory.ParseName(namespaceName)) | ||
| .NormalizeWhitespace() | ||
| .WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed); | ||
|
|
||
| return root.AddUsings(newUsing); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
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.
Does this mean this analyzer fails to detect this case?
IEnumerable<string> files = Directory.GetFiles(...);