-
-
Notifications
You must be signed in to change notification settings - Fork 4
Support basic refactoring from static to sealed
#234
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
5 commits
Select commit
Hold shift + click to select a range
f1db6ea
Support basic refactoring from `static` to `sealed`
viceroypenguin 1816198
Update src/Immediate.Handlers.CodeFixes/RefactoringExtensions.cs
viceroypenguin a6170d7
Update src/Immediate.Handlers.CodeFixes/RefactoringExtensions.cs
viceroypenguin bf80726
Address CR
viceroypenguin a6ec4a8
Address CR
viceroypenguin 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
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,12 @@ | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
|
||
| namespace Immediate.Handlers; | ||
|
|
||
| internal static class SyntaxExtensions | ||
| { | ||
| public static bool IsCancellationToken(this SemanticModel model, TypeSyntax? typeSyntax, CancellationToken token) => | ||
| typeSyntax is { } syntax | ||
| && model.GetSymbolInfo(syntax, token).Symbol is INamedTypeSymbol namedType | ||
| && namedType.IsCancellationToken(); | ||
| } |
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,35 @@ | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeRefactorings; | ||
| using Microsoft.CodeAnalysis.Text; | ||
|
|
||
| namespace Immediate.Handlers.CodeFixes; | ||
|
|
||
| [ExcludeFromCodeCoverage] | ||
| internal static class RefactoringExtensions | ||
| { | ||
| internal static void Deconstruct(this CodeRefactoringContext context, out Document document, out TextSpan span, out CancellationToken cancellationToken) | ||
| { | ||
| document = context.Document; | ||
| span = context.Span; | ||
| cancellationToken = context.CancellationToken; | ||
| } | ||
|
|
||
| public static async ValueTask<SyntaxNode> GetRequiredSyntaxRootAsync(this Document document, CancellationToken cancellationToken) | ||
| { | ||
| if (document.TryGetSyntaxRoot(out var root)) | ||
| return root; | ||
|
|
||
| return await document.GetSyntaxRootAsync(cancellationToken) | ||
| ?? throw new InvalidOperationException($"Failed to retrieve the syntax root for document '{document.Name ?? document.FilePath ?? "unknown"}'."); | ||
| } | ||
|
|
||
| public static async ValueTask<SemanticModel> GetRequiredSemanticModelAsync(this Document document, CancellationToken cancellationToken) | ||
| { | ||
| if (document.TryGetSemanticModel(out var semanticModel)) | ||
| return semanticModel; | ||
|
|
||
| return await document.GetSemanticModelAsync(cancellationToken) | ||
| ?? throw new InvalidOperationException("Could not retrieve semantic model for the document."); | ||
| } | ||
| } |
178 changes: 178 additions & 0 deletions
178
src/Immediate.Handlers.CodeFixes/StaticToSealedHandlerRefactoringProvider.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,178 @@ | ||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeRefactorings; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; | ||
|
|
||
| namespace Immediate.Handlers.CodeFixes; | ||
|
|
||
| [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Convert to instance handler")] | ||
| public sealed class StaticToSealedHandlerRefactoringProvider : CodeRefactoringProvider | ||
| { | ||
| public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) | ||
| { | ||
| var (document, span, token) = context; | ||
| token.ThrowIfCancellationRequested(); | ||
|
|
||
| if (await document.GetRequiredSyntaxRootAsync(token) is not CompilationUnitSyntax root) | ||
| return; | ||
|
|
||
| var model = await document.GetRequiredSemanticModelAsync(token); | ||
|
|
||
| switch (root.FindNode(span)) | ||
| { | ||
| case ClassDeclarationSyntax cds: | ||
| { | ||
| if (model.GetDeclaredSymbol(cds, token) is not INamedTypeSymbol { IsStatic: true } container) | ||
| return; | ||
|
|
||
| if (!container.GetAttributes().Any(a => a.AttributeClass.IsHandlerAttribute())) | ||
| return; | ||
|
|
||
| var method = container.GetMembers() | ||
| .OfType<IMethodSymbol>() | ||
| .FirstOrDefault(m => m is { IsStatic: true, Name: "Handle" or "HandleAsync" }); | ||
|
|
||
| if (method is null) | ||
| return; | ||
|
|
||
| var mds = (MethodDeclarationSyntax)await method | ||
| .DeclaringSyntaxReferences[0] | ||
| .GetSyntaxAsync(token); | ||
|
|
||
| var service = new RefactoringService( | ||
| document, | ||
| model, | ||
| root, | ||
| cds, | ||
| mds | ||
| ); | ||
|
|
||
| context.RegisterRefactoring( | ||
| CodeAction.Create( | ||
| title: "Convert to instance handler", | ||
| createChangedDocument: service.ConvertToInstanceHandler, | ||
| equivalenceKey: nameof(StaticToSealedHandlerRefactoringProvider) | ||
| ) | ||
| ); | ||
|
|
||
| break; | ||
| } | ||
|
|
||
| case MethodDeclarationSyntax mds: | ||
| { | ||
| if (model.GetDeclaredSymbol(mds, token) is not IMethodSymbol | ||
| { | ||
| IsStatic: true, | ||
| Name: "Handle" or "HandleAsync", | ||
| ContainingType: INamedTypeSymbol { IsStatic: true } container, | ||
| } method) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (!container.GetAttributes().Any(a => a.AttributeClass.IsHandlerAttribute())) | ||
| return; | ||
|
|
||
| var service = new RefactoringService( | ||
| document, | ||
| model, | ||
| root, | ||
| (ClassDeclarationSyntax)mds.Parent!, | ||
| mds | ||
| ); | ||
|
|
||
| context.RegisterRefactoring( | ||
| CodeAction.Create( | ||
| title: "Convert to instance handler", | ||
| createChangedDocument: service.ConvertToInstanceHandler, | ||
| equivalenceKey: nameof(StaticToSealedHandlerRefactoringProvider) | ||
| ) | ||
| ); | ||
|
|
||
| break; | ||
| } | ||
|
|
||
| default: | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| } | ||
|
|
||
| file sealed class RefactoringService( | ||
| Document document, | ||
| SemanticModel model, | ||
| CompilationUnitSyntax documentRoot, | ||
| ClassDeclarationSyntax classDeclarationSyntax, | ||
| MethodDeclarationSyntax methodDeclarationSyntax | ||
| ) | ||
| { | ||
| public Task<Document> ConvertToInstanceHandler( | ||
| CancellationToken token | ||
| ) | ||
| { | ||
| var methodParameters = methodDeclarationSyntax.ParameterList.Parameters; | ||
|
|
||
| var isLastParamCancellationToken = model.IsCancellationToken(methodParameters[^1].Type, token); | ||
|
|
||
| var classParameters = methodParameters | ||
| .Skip(1) | ||
| .Take(methodParameters.Count - (isLastParamCancellationToken ? 2 : 1)) | ||
| .Select(p => p.WithTrailingTrivia(ElasticSpace)) | ||
| .ToList(); | ||
|
|
||
| var newMethodParameters = methodParameters.RemoveParametersUntilCount(isLastParamCancellationToken ? 2 : 1); | ||
|
|
||
| var newMethodDeclarationSyntax = methodDeclarationSyntax | ||
| .WithParameterList( | ||
| methodDeclarationSyntax.ParameterList | ||
| .WithParameters(newMethodParameters) | ||
| ) | ||
| .WithModifiers( | ||
| methodDeclarationSyntax.Modifiers | ||
| .RemoveStaticModifier() | ||
| ); | ||
|
|
||
| var newClassDeclarationSyntax = classDeclarationSyntax | ||
| .ReplaceNode(methodDeclarationSyntax, newMethodDeclarationSyntax) | ||
| .WithModifiers( | ||
| classDeclarationSyntax.Modifiers | ||
| .RemoveStaticModifier() | ||
| .Insert( | ||
| // valid case will have `partial` as final element; insert `sealed` before `partial` | ||
| classDeclarationSyntax.Modifiers.Count - 2, | ||
| Token(SyntaxKind.SealedKeyword).WithTrailingTrivia(ElasticSpace) | ||
| ) | ||
| ); | ||
|
|
||
| if (classParameters.Count > 0) | ||
| { | ||
| newClassDeclarationSyntax = newClassDeclarationSyntax | ||
| .WithParameterList( | ||
| ParameterList(SeparatedList(classParameters)) | ||
| ) | ||
| .WithIdentifier(classDeclarationSyntax.Identifier.WithoutTrivia()); | ||
| } | ||
|
|
||
| return Task.FromResult(document.WithSyntaxRoot(documentRoot.ReplaceNode(classDeclarationSyntax, newClassDeclarationSyntax))); | ||
| } | ||
| } | ||
|
|
||
| file static class SyntaxExtensions | ||
| { | ||
| public static SeparatedSyntaxList<ParameterSyntax> RemoveParametersUntilCount( | ||
| this SeparatedSyntaxList<ParameterSyntax> nodes, | ||
| int count | ||
| ) | ||
| { | ||
| while (nodes.Count > count) | ||
| nodes = nodes.RemoveAt(1); | ||
| return nodes; | ||
| } | ||
|
|
||
| public static SyntaxTokenList RemoveStaticModifier( | ||
| this SyntaxTokenList list | ||
| ) => new(list.Where(static token => !token.IsKind(SyntaxKind.StaticKeyword))); | ||
| } | ||
52 changes: 52 additions & 0 deletions
52
tests/Immediate.Handlers.Tests/CodeFixTests/CodeRefactoringTestHelper.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,52 @@ | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using Immediate.Handlers.Tests.Helpers; | ||
| using Microsoft.CodeAnalysis.CodeRefactorings; | ||
| using Microsoft.CodeAnalysis.CSharp.Testing; | ||
| using Microsoft.CodeAnalysis.Testing; | ||
|
|
||
| namespace Immediate.Handlers.Tests.CodeFixTests; | ||
|
|
||
| public static class CodeRefactoringTestHelper | ||
| { | ||
| private const string EditorConfig = | ||
| """ | ||
| root = true | ||
|
|
||
| [*.cs] | ||
| charset = utf-8 | ||
| indent_style = tab | ||
| insert_final_newline = true | ||
| indent_size = 4 | ||
| """; | ||
|
|
||
| public static CSharpCodeRefactoringTest<TRefactoring, DefaultVerifier> CreateCodeRefactoringTest<TRefactoring>( | ||
| [StringSyntax("c#-test")] string inputSource, | ||
| [StringSyntax("c#-test")] string fixedSource, | ||
| int codeActionIndex = 0 | ||
| ) | ||
| where TRefactoring : CodeRefactoringProvider, new() | ||
| { | ||
| var csTest = new CSharpCodeRefactoringTest<TRefactoring, DefaultVerifier> | ||
| { | ||
| CodeActionIndex = codeActionIndex, | ||
| TestState = | ||
| { | ||
| Sources = { inputSource }, | ||
| AnalyzerConfigFiles = { { ("/.editorconfig", EditorConfig) } }, | ||
| ReferenceAssemblies = new ReferenceAssemblies( | ||
| "net8.0", | ||
| new PackageIdentity( | ||
| "Microsoft.NETCore.App.Ref", | ||
| "8.0.0"), | ||
| Path.Combine("ref", "net8.0") | ||
| ), | ||
| }, | ||
| FixedState = { MarkupHandling = MarkupMode.IgnoreFixable, Sources = { fixedSource } }, | ||
| }; | ||
|
|
||
| csTest.TestState.AdditionalReferences | ||
| .AddRange(DriverReferenceAssemblies.Msdi.GetAdditionalReferences()); | ||
|
|
||
| return csTest; | ||
| } | ||
| } |
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.