-
Notifications
You must be signed in to change notification settings - Fork 221
Add UnboundDirectiveAttributeAddUsingCodeActionProvider for directive attributes #12404
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 4 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
8404c74
Initial plan
Copilot a7d3b05
Add AddUsingsCodeActionProvider to offer @using directives for fully …
Copilot f793980
Refactor AddUsingsCodeActionProvider to avoid duplicate namespace ext…
Copilot 4f69d7f
Implement UnboundDirectiveAttributeAddUsingCodeActionProvider for dir…
Copilot 3b52a62
Remove incorrect AddUsingsCodeActionProvider and add UnboundDirective…
Copilot 98fbf03
Remove redundant namespace check and clarify .Component suffix usage
Copilot 328584c
Allow opting out of default imports in tests
davidwengier 0a5c30b
Fix provider to look for MarkupAttributeBlockSyntax instead of Markup…
Copilot 345c10d
Fix attribute name matching - use Name property directly and strip '@…
Copilot 38d9cb0
Address code review feedback - extract method, use GetTagHelpers(), k…
Copilot c9a3e72
Fix namespace extraction to handle generic types and improve heuristics
Copilot d3bf9ec
Fix test expectations for @bind tests
Copilot e057c87
Fix implementation, unskip tests, and remove failing test
davidwengier 47767f6
Ensure action is only offered on the name portion of the attribute
davidwengier e4bb3a3
Address code review feedback: fix cursor position check, add WorkItem…
Copilot e302b42
Remove incorrectly re-added Skip attribute from AddUsing_BindWithPara…
Copilot 03b62c1
Use TryGetTagHelpers instead of GetTagHelpers with null check
Copilot 97011f7
Use ReadOnlySpan<char> to avoid string allocations in attribute name …
Copilot 6d3dffa
Use extension method syntax for SequenceEqual instead of static metho…
Copilot 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
81 changes: 81 additions & 0 deletions
81
.../Microsoft.CodeAnalysis.Razor.Workspaces/CodeActions/Razor/AddUsingsCodeActionProvider.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,81 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Collections.Immutable; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.AspNetCore.Razor.Language; | ||
| using Microsoft.AspNetCore.Razor.Language.Syntax; | ||
| using Microsoft.AspNetCore.Razor.Threading; | ||
| using Microsoft.CodeAnalysis.Razor.CodeActions.Models; | ||
| using Microsoft.CodeAnalysis.Razor.CodeActions.Razor; | ||
|
|
||
| namespace Microsoft.CodeAnalysis.Razor.CodeActions; | ||
|
|
||
| internal class AddUsingsCodeActionProvider : IRazorCodeActionProvider | ||
| { | ||
| public Task<ImmutableArray<RazorVSInternalCodeAction>> ProvideAsync(RazorCodeActionContext context, CancellationToken cancellationToken) | ||
| { | ||
| if (context.HasSelection) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| // Make sure we're in a Razor or component file | ||
| if (!FileKinds.IsComponent(context.CodeDocument.FileKind) && !FileKinds.IsLegacy(context.CodeDocument.FileKind)) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| if (!context.CodeDocument.TryGetSyntaxRoot(out var syntaxRoot)) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| // Find the node at the cursor position | ||
| var owner = syntaxRoot.FindInnermostNode(context.StartAbsoluteIndex, includeWhitespace: false); | ||
| if (owner is null) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| // Check if we're in a fully qualified component tag | ||
| if (owner.FirstAncestorOrSelf<MarkupTagHelperElementSyntax>() is { } markupTagHelperElement) | ||
| { | ||
| var startTag = markupTagHelperElement.StartTag; | ||
| if (startTag is not null && | ||
| startTag.Name.Content.Contains('.') && | ||
| startTag.Name.Span.Contains(context.StartAbsoluteIndex)) | ||
| { | ||
| var fullyQualifiedName = startTag.Name.Content; | ||
|
|
||
| // Check if this matches a tag helper | ||
| var descriptors = markupTagHelperElement.TagHelperInfo.BindingResult.Descriptors; | ||
| var boundTagHelper = descriptors.FirstOrDefault(static d => d.Kind == TagHelperKind.Component); | ||
|
|
||
| if (boundTagHelper is not null && boundTagHelper.IsFullyQualifiedNameMatch) | ||
| { | ||
| // Create the add using code action | ||
| if (AddUsingsCodeActionResolver.TryCreateAddUsingResolutionParams( | ||
| fullyQualifiedName, | ||
| context.Request.TextDocument, | ||
| additionalEdit: null, | ||
| context.DelegatedDocumentUri, | ||
| out var extractedNamespace, | ||
| out var resolutionParams)) | ||
| { | ||
| // Extract component name for the title | ||
| var lastDotIndex = fullyQualifiedName.LastIndexOf('.'); | ||
| var componentName = lastDotIndex > 0 ? fullyQualifiedName[(lastDotIndex + 1)..] : null; | ||
|
|
||
| var addUsingCodeAction = RazorCodeActionFactory.CreateAddComponentUsing(extractedNamespace, componentName, resolutionParams); | ||
| return Task.FromResult<ImmutableArray<RazorVSInternalCodeAction>>([addUsingCodeAction]); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
| } | ||
166 changes: 166 additions & 0 deletions
166
...Razor.Workspaces/CodeActions/Razor/UnboundDirectiveAttributeAddUsingCodeActionProvider.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,166 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Collections.Immutable; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Linq; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.AspNetCore.Razor.Language; | ||
| using Microsoft.AspNetCore.Razor.Language.Legacy; | ||
| using Microsoft.AspNetCore.Razor.Language.Syntax; | ||
| using Microsoft.AspNetCore.Razor.Threading; | ||
| using Microsoft.CodeAnalysis.Razor.CodeActions.Models; | ||
| using Microsoft.CodeAnalysis.Razor.CodeActions.Razor; | ||
|
|
||
| namespace Microsoft.CodeAnalysis.Razor.CodeActions; | ||
|
|
||
| internal class UnboundDirectiveAttributeAddUsingCodeActionProvider : IRazorCodeActionProvider | ||
| { | ||
| public Task<ImmutableArray<RazorVSInternalCodeAction>> ProvideAsync(RazorCodeActionContext context, CancellationToken cancellationToken) | ||
| { | ||
| if (context.HasSelection) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| // Only work in component files | ||
| if (!FileKinds.IsComponent(context.CodeDocument.FileKind)) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| if (!context.CodeDocument.TryGetSyntaxRoot(out var syntaxRoot)) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| // Find the node at the cursor position | ||
| var owner = syntaxRoot.FindInnermostNode(context.StartAbsoluteIndex, includeWhitespace: false); | ||
| if (owner is null) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| // Find the directive attribute ancestor | ||
| var directiveAttribute = owner.FirstAncestorOrSelf<MarkupTagHelperDirectiveAttributeSyntax>(); | ||
| if (directiveAttribute?.TagHelperAttributeInfo is not { } attributeInfo) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| // Check if it's an unbound directive attribute | ||
| if (attributeInfo.Bound || !attributeInfo.IsDirectiveAttribute) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| // Try to find the missing namespace | ||
| if (!TryGetMissingDirectiveAttributeNamespace( | ||
| context.CodeDocument, | ||
| attributeInfo, | ||
| out var missingNamespace)) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| // Check if the namespace is already imported | ||
davidwengier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| var syntaxTree = context.CodeDocument.GetSyntaxTree(); | ||
| if (syntaxTree is not null) | ||
| { | ||
| var existingUsings = syntaxTree.EnumerateUsingDirectives() | ||
| .SelectMany(d => d.DescendantNodes()) | ||
| .Select(n => n.GetChunkGenerator()) | ||
| .OfType<AddImportChunkGenerator>() | ||
| .Where(g => !g.IsStatic) | ||
| .Select(g => g.ParsedNamespace) | ||
| .ToImmutableArray(); | ||
|
|
||
| if (existingUsings.Contains(missingNamespace)) | ||
| { | ||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
| } | ||
|
|
||
| // Create the code action | ||
| if (AddUsingsCodeActionResolver.TryCreateAddUsingResolutionParams( | ||
davidwengier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| missingNamespace + ".Dummy", // Dummy type name to extract namespace | ||
davidwengier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| context.Request.TextDocument, | ||
| additionalEdit: null, | ||
| context.DelegatedDocumentUri, | ||
| out var extractedNamespace, | ||
| out var resolutionParams)) | ||
| { | ||
| var addUsingCodeAction = RazorCodeActionFactory.CreateAddComponentUsing( | ||
| extractedNamespace, | ||
| newTagName: null, | ||
| resolutionParams); | ||
|
|
||
| // Set high priority and order to show prominently | ||
| addUsingCodeAction.Priority = VSInternalPriorityLevel.High; | ||
| addUsingCodeAction.Order = -999; | ||
|
|
||
| return Task.FromResult<ImmutableArray<RazorVSInternalCodeAction>>([addUsingCodeAction]); | ||
| } | ||
|
|
||
| return SpecializedTasks.EmptyImmutableArray<RazorVSInternalCodeAction>(); | ||
| } | ||
|
|
||
| private static bool TryGetMissingDirectiveAttributeNamespace( | ||
| RazorCodeDocument codeDocument, | ||
| TagHelperAttributeInfo attributeInfo, | ||
| [NotNullWhen(true)] out string? missingNamespace) | ||
| { | ||
| missingNamespace = null; | ||
|
|
||
| var tagHelperContext = codeDocument.GetRequiredTagHelperContext(); | ||
davidwengier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| var attributeName = attributeInfo.Name; | ||
|
|
||
| // For attributes with parameters, extract just the attribute name | ||
| if (attributeInfo.ParameterName is not null) | ||
| { | ||
| var colonIndex = attributeName.IndexOf(':'); | ||
| if (colonIndex >= 0) | ||
| { | ||
| attributeName = attributeName[..colonIndex]; | ||
| } | ||
| } | ||
|
|
||
| // Search for matching bound attribute descriptors | ||
| foreach (var tagHelper in tagHelperContext.TagHelpers) | ||
| { | ||
| foreach (var boundAttribute in tagHelper.BoundAttributes) | ||
| { | ||
| if (boundAttribute.Name == attributeName) | ||
| { | ||
| // Extract namespace from the type name | ||
| var typeName = boundAttribute.TypeName; | ||
|
|
||
| // Apply heuristics to determine the namespace | ||
| if (typeName.Contains(".Web.") || typeName.EndsWith(".Web.EventHandlers")) | ||
davidwengier marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| missingNamespace = "Microsoft.AspNetCore.Components.Web"; | ||
| return true; | ||
| } | ||
| else if (typeName.Contains(".Forms.")) | ||
| { | ||
| missingNamespace = "Microsoft.AspNetCore.Components.Forms"; | ||
| return true; | ||
| } | ||
| else | ||
| { | ||
| // Extract namespace from type name (everything before the last dot) | ||
| var lastDotIndex = typeName.LastIndexOf('.'); | ||
| if (lastDotIndex > 0) | ||
| { | ||
| missingNamespace = typeName[..lastDotIndex]; | ||
| return true; | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
| } | ||
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.