Ah! So ast::Macro is an enum that only includes MacroRules and MacroDef, NOT MacroCall. This means when we're inside foo!(bar$0):
- The parent
p of the token is TOKEN_TREE
p.ancestors().any(|it| ast::Macro::can_cast(it.kind())) will look for MacroRules or MacroDef ancestors
- But
foo!(bar$0) is a MacroCall, not a MacroRules or MacroDef
- So this check should return
false and we should fall through to the next check
Wait, but let me reconsider. The issue is that when we're inside foo!(bar$0), the find_node_at_offset(&speculative_file, speculative_offset) might return None because the parser doesn't parse bar as a valid NameRef inside a macro call's token tree.
Let me think about what happens:
- We have
foo!(bar$0) - the cursor is after bar inside the macro invocation
- The speculative file has a fake ident inserted at the cursor position
- When we look for a
name_like at the cursor position, the parser sees bar<IDENT> which might be parsed as... let me think...
Actually, inside a macro invocation like foo!(...), the content is a token tree. The parser might not parse bar<IDENT> as a NameRef because it's inside a token tree. The token tree is just a sequence of tokens.
So when find_node_at_offset(&speculative_file, speculative_offset) returns None, we go to the else branch. Then:
p is the parent of self_token, which would be a token inside a token tree
p.kind() would be TOKEN_TREE if the token tree itself is the parent, or some other kind
Wait, let me re-read the code more carefully:
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
This checks if:
- The parent
p is a TOKEN_TREE (which it would be for foo!(...))
- AND any ancestor of
p is a MacroRules or MacroDef
For foo!(bar$0), the ancestors would include MacroCall, not MacroRules or MacroDef. So the second condition would be false, and we would NOT enter this branch. We would fall through to the next checks.
Let me continue reading the code...
} else if find_node_at_offset::<ast::CfgPredicate>(
&speculative_file,
speculative_offset,
)
.is_some()
{
CompletionAnalysis::CfgPredicate
} else {
return None;
}
So if we're inside foo!(bar$0) and there's no CfgPredicate, we return None. This means NO completions are provided!
But wait, I need to re-examine. Let me look at the full structure:
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
// ...
let token = syntax::algo::skip_trivia_token(self_token.clone(), Direction::Prev)?;
let p = token.parent()?;
if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| it.kind() == SyntaxKind::TOKEN_TREE_META)
{
// attr completion
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
// macro segment completion
} else if find_node_at_offset::<ast::CfgPredicate>(...)
.is_some()
{
// cfg predicate
} else {
return None;
}
// ...
}
So the issue is:
- For
foo!(bar$0), find_node_at_offset returns None (because bar is inside a token tree and not parsed as a NameRef)
p is the parent of the token, which is the TOKEN_TREE node
p.kind() == SyntaxKind::TOKEN_TREE is true
p.ancestors().any(|it| ast::Macro::can_cast(it.kind())) checks if any ancestor is a MacroRules or MacroDef
- For
foo!(bar$0), the ancestors are TOKEN_TREE, MACRO_CALL, etc. - NOT MACRO_RULES or MACRO_DEF
- So this condition is
false
- We fall through to check for
CfgPredicate, which also doesn't match
- We return
None, so no completions
This is the bug! When we're inside a MacroCall token tree (like foo!(bar$0)), we should still provide macro path completions for bar.
Actually wait, I need to reconsider the structure. Let me think about what the AST looks like for foo!(bar$0):
MACRO_CALL
PATH
PATH_SEGMENT "foo"
EXCL_TOKEN "!"
TOKEN_TREE
IDENT "bar"
So when we're at $0 after bar:
- The speculative file would have
foo!(bar<IDENT>)
find_node_at_offset(&speculative_file, speculative_offset) looks for a NameLike at that position
- But
bar<IDENT> inside a TOKEN_TREE is not a valid NameRef - it's just tokens inside a token tree
- So
find_node_at_offset returns None
- We go to the else branch
self_token is the <IDENT> token (the fake ident we inserted)
token = syntax::algo::skip_trivia_token(self_token.clone(), Direction::Prev) would get bar or the whitespace before it
p = token.parent() would be the TOKEN_TREE
So the condition p.kind() == SyntaxKind::TOKEN_TREE would be true.
And p.ancestors().any(|it| ast::Macro::can_cast(it.kind())) would check if any ancestor is MacroRules or MacroDef. For a MacroCall, this would be false because MacroCall is not a Macro variant.
So we would NOT enter either of the TOKEN_TREE branches, and we would return None.
This is the bug! The fix should be to also handle the case where we're inside a MacroCall token tree and provide macro path completions.
Now let me think about how to fix this. We need to detect when we're inside a MacroCall token tree and provide appropriate completions.
Looking at the code, when we're at foo!(bar$0), we need to:
- Detect that we're inside a
MacroCall token tree
- Look at what comes before the cursor position to understand what kind of completion we need
- Since we're completing a macro path, we should provide macro completions
Let me look at how MacroCall is handled elsewhere to understand the pattern.
Actually, I realize the issue might be slightly different. Let me check if find_node_at_offset actually returns None or if it returns something else.
Actually, the fake ident token is what we inserted. Let me look at how the speculative file is constructed.
Let me look at the expansion code to understand what happens.
Actually, I think the issue might be more subtle. Let me trace through what happens when we have foo!(bar$0):
- The original file has
foo!(bar$0) where $0 is the cursor position
- We insert a fake ident at the cursor position, making it
foo!(bar<IDENT>)
- The parser parses this. Inside a token tree,
bar<IDENT> would be parsed as two separate tokens: an IDENT token bar and an IDENT token <IDENT> (the fake ident)
- When we look for a
NameLike at the position of <IDENT>, we don't find one because we're inside a token tree, not in a context where a name reference is expected
Actually, I think I need to re-check this. The issue might be that the parser parses bar<IDENT> inside a token tree differently than I think.
Let me actually create a test to verify the behavior.
Actually, let me first look at existing tests to see if there's a similar case:
fn completes_in_simple_macro_call() {
check_no_kw(
r#"
macro_rules! m { ($e:expr) => { $e } }
fn main() { m!(self::f$0); }
fn foo() {}
"#,
expect![[r#"
fn foo() fn()
fn main() fn()
"#]],
);
}
In this test, m!(self::f$0) provides completions for foo and main. This works because self::f is parsed as a path inside the token tree. The parser can parse self::f<IDENT> as a path when we're inside a token tree?
Actually, I think the key difference is:
self::f$0 - here self::f is a path expression prefix, and the parser can recognize it as a path inside the token tree
bar$0 - here bar is just an identifier, and the parser doesn't recognize it as anything meaningful inside a token tree
Actually wait, let me look at the test more carefully. In m!(self::f$0), the completions returned are fn foo() and fn main(). These are function completions, not macro completions. And self is a keyword, not a macro name.
But in our case, we're looking at foo!(bar$0) where bar should be completed as a macro path. This is different because:
- We're inside a macro invocation
foo!(...)
- We're completing the first segment of a path (before any
::)
- We want to complete a macro name
Let me look at how the completes_in_simple_macro_call test works. The completions include fn foo() and fn main(), which are function completions. This suggests that inside m!(self::f$0), the parser treats self::f as a path expression.
But in foo!(bar$0), the issue is different. Here we're completing the macro PATH (the name of the macro to invoke), not an expression inside a macro call.
Actually, I think I misread the issue. Let me re-read the issue:
macro_rules! bar { () => (); }
macro_rules! foo { ($i:ident) => { $i!() }; }
fn main() {
foo!(bar$0);
}
Here:
bar is a macro that takes no arguments
foo is a macro that takes an identifier and expands it to a macro call
foo!(bar$0) is a macro invocation where we want to complete bar as the macro path
So the cursor is inside foo!(...), and we're typing bar to complete the macro path that will be used as $i in foo's expansion.
The question is: should rust-analyzer complete bar here? And if so, what completions should it provide?
Since we're inside foo!(bar$0), the bar will be treated as an identifier that gets expanded by foo to become a macro call. So we should provide completions for macro names that can be used here.
Let me think about what the fix should be:
- When we're inside a
MacroCall's token tree and we're completing an identifier (not inside a nested path)
- We should provide macro path completions
Actually, looking at the code again, I think the issue is that when we're inside a token tree, we should check if we're inside a MacroCall and provide appropriate completions.
Let me look at how the code determines what type of completion to provide inside a token tree.
Looking at the code structure:
- If we're inside a
TOKEN_TREE_META, we provide attribute-related completions
- If we're inside a
TOKEN_TREE whose ancestor is a MacroRules or MacroDef, we provide macro segment completions ($name)
- Otherwise, we return
None
The missing case is when we're inside a TOKEN_TREE whose ancestor is a MacroCall. In this case, we should provide path completions for the macro invocation arguments.
Let me look at the fix. We need to handle the case where:
p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::MacroCall::can_cast(it.kind()))
But wait, I need to check if ast::MacroCall::can_cast is a valid method.
Actually, looking at the code more carefully, I see that there's already handling for ast::MacroCall in the classify_name_ref function. The issue is that when we're inside a token tree, we never reach classify_name_ref because find_node_at_offset returns None.
So the fix should be to handle the case where we're inside a MacroCall token tree and provide appropriate completions.
Let me look at what completions should be provided. In the case of foo!(bar$0), we're completing an identifier that will be used as $i in foo's pattern ($i:ident). This means we should provide completions for all available identifiers, including macros.
Actually, wait. Let me reconsider. In foo!(bar$0), the bar is inside a token tree that's a direct child of MacroCall. The bar should be interpreted as a path (the macro path to invoke after expansion by foo).
Hmm, but actually, the bar here is not directly a macro path - it's a value that gets passed to foo as a metavariable binding. After foo expands, it becomes bar!().
So the completions we should provide here are macro names that could be used as the $i in foo. Since foo expands to $i!(), any macro name would work.
Let me look at how to implement this fix. The key is to detect when we're inside a MacroCall token tree and provide appropriate completions.
Actually, I realize I should look more carefully at what happens inside a token tree. The parser inside a token tree is more lenient - it just recognizes tokens and token trees, not semantic constructs like paths or expressions.
So when we're at foo!(bar$0), the speculative file would have something like foo!(bar<IDENT>). The parser would see this as a token tree containing bar<IDENT>. The <IDENT> is a fake ident we inserted.
When we try to find a NameLike at the position of <IDENT>, we won't find one because the token tree parsing doesn't recognize <IDENT> as part of a name reference.
So find_node_at_offset returns None, and we fall into the else branch. There, we check if the parent is a TOKEN_TREE. If it is, and if any ancestor is a Macro, we provide macro segment completions. But since MacroCall is not a Macro variant, we don't enter that branch.
The fix should be to also handle the case where the parent is a TOKEN_TREE and any ancestor is a MacroCall. In this case, we should provide some kind of path completion.
Let me look at how to implement this. I think we need to:
- Detect when we're inside a
MacroCall's token tree
- Look at the tokens before the cursor to understand what we're completing
- Provide appropriate completions
Actually, looking at this more carefully, I think the issue is that when we're inside a macro invocation's token tree, we should provide completions based on the macro's signature. But that's complex because we'd need to expand the macro and see what patterns it expects.
For now, let me focus on a simpler fix: when we're inside a MacroCall token tree and the previous token is an identifier (or we're at the start of a path), we should provide macro name completions.
Let me look at how the completions module handles macro paths.
Actually, let me first check if there are existing tests that are failing or if this is a completely new case.
Let me look at the tests more carefully.
Actually, I think the issue is that when we're inside foo!(bar$0), we should be able to complete bar as a macro name. The current code returns None in this case, which means no completions are provided.
Let me think about what the fix should be:
- When we detect that we're inside a
MacroCall token tree
- And we're completing an identifier at the start of what could be a macro path
- We should provide macro name completions
The fix would be in the else branch where we currently return None for token trees inside macro invocations.
Let me look at the code more carefully to understand the exact fix needed.
Looking at the code around line 518:
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
if let Some([_ident, colon, _name, dollar]) = fake_ident_token
.siblings_with_tokens(Direction::Prev)
.filter(|it| !it.kind().is_trivia())
.take(4)
.collect_array()
&& dollar.kind() == T![$]
&& colon.kind() == T![:]
{
CompletionAnalysis::MacroSegment
} else {
return None;
}
}
This handles macro segment completion (like $name patterns). But it returns None for other cases, including when we're inside a MacroCall token tree.
The fix should be to add another branch that handles MacroCall token trees. Let me think about what analysis to return.
Actually, I think we need to provide path completions here. The issue is that we're inside a token tree, so we can't use the normal path completion machinery. We need to either:
- Provide macro name completions directly
- Or somehow construct a path context and use the normal completion machinery
Let me look at how other cases provide completions. Actually, looking at the code structure, I see that different CompletionAnalysis variants lead to different completion functions. Let me see what CompletionAnalysis variants exist.
Looking at the code, I see CompletionAnalysis includes:
Name - for completing names (identifiers in declaration context)
NameRef - for completing name references (identifiers in use context)
Lifetime - for completing lifetimes
String - for completing strings
UnexpandedAttrTT - for attribute token trees
MacroSegment - for macro segment completion ($name)
CfgPredicate - for cfg predicate completion
TokenTree - for token tree completion?
Let me search for the CompletionAnalysis enum definition.
Actually, I think the issue is that when we're inside a MacroCall token tree, we should be able to complete paths (macro names). The normal path completion machinery works when find_node_at_offset returns a NameLike::NameRef, but when we're inside a token tree, it returns None.
I think the fix is to handle the MacroCall case in the else branch and provide path completions.
Let me look at how the fix should be structured. We need to:
- Detect when we're inside a
MacroCall token tree
- Determine if we're completing a macro path (first identifier in the token tree before any
::)
- If so, provide macro name completions
Let me look at the code to see how to implement this.
Actually, let me first check if there's an existing CompletionAnalysis variant that can handle this case.
Looking at the code, I see that when find_node_at_offset returns None, we return various CompletionAnalysis variants depending on the context. For MacroCall token trees, we don't currently return any analysis, so no completions are provided.
I think the fix is to add handling for MacroCall token trees. When we're inside a MacroCall token tree and we're completing an identifier, we should provide path completions for that path.
But the tricky part is that we're inside a token tree, so we can't use the normal path completion machinery. We need to somehow construct a path context and use the normal completion code.
Actually, looking at this more carefully, I think the issue might be simpler. Let me re-examine the code.
Wait, I realize I may have misunderstood the issue. Let me re-read the issue description:
Cannot complete macro path in macro
So the issue is that when you're inside a macro invocation like foo!(bar$0), you cannot complete bar as a macro path. This means no completions are provided.
The fix should be to detect when we're inside a MacroCall token tree and provide appropriate completions.
Let me look at the code to see how to implement this. I think the key insight is that when we're inside a MacroCall token tree, we should be able to complete paths (macro names), similar to how we can complete paths in normal expression context.
Actually, I think the issue might be that we need to handle the case where the MacroCall's token tree contains an identifier that could be a macro path. This would be the case when we're at the beginning of the token tree or after certain delimiters.
Let me look at how the completion is triggered. When we're inside foo!(bar$0):
find_node_at_offset returns None (because we're inside a token tree)
- We check if the parent is a
TOKEN_TREE and if any ancestor is a Macro - this fails because MacroCall is not a Macro
- We check if there's a
CfgPredicate - this fails
- We return
None, so no completions
The fix should be to add handling for when the parent is a TOKEN_TREE and any ancestor is a MacroCall. In this case, we should provide path completions.
But how? We can't use the normal path completion machinery because we don't have a NameRef node. We need to somehow construct the context and provide completions.
Actually, looking at this more carefully, I think the fix might involve creating a synthetic path context and using the normal completion machinery. Let me look at how the completions are gathered.
Looking at the completions.rs file, I see that complete_name_ref is called with the NameRefContext. If we can create a synthetic NameRefContext for the case where we're inside a MacroCall token tree, we could reuse the normal completion machinery.
But this would require significant refactoring. Let me think of a simpler approach.
Actually, I think the simplest fix is to detect when we're inside a MacroCall token tree and the identifier we're completing could be a macro path, and then provide macro name completions directly.
Let me look at how macro completions are rendered. Looking at the render module, I see there's a macro_ module that handles macro completions.
Let me look at how to provide macro completions.
Actually, I think I need to take a different approach. Let me look at how the completion context is constructed when we're inside a macro invocation.
Looking at the code structure again:
CompletionContext::new creates the completion context
CompletionContext::analyze determines the analysis
- The analysis is used to gather completions
The issue is that CompletionContext::analyze returns None when we're inside a MacroCall token tree, which means no completions are gathered.
The fix should be to make CompletionContext::analyze return a valid analysis for MacroCall token trees.
Looking at the code, I see that there are several CompletionAnalysis variants. For macro invocations, we might need a new variant or we might be able to reuse an existing one.
Actually, looking at the code more carefully, I see that the CompletionAnalysis enum includes various variants. Let me see if there's one that could work for macro invocation token trees.
Looking at the code:
CompletionAnalysis::UnexpandedAttrTT {
colon_prefix,
fake_attribute_under_caret: Some(attr),
extern_crate,
}
This handles attribute token trees. We might need something similar for macro call token trees.
But actually, I think the better approach is to handle this case by creating a path context and using the normal completion machinery. Let me look at how this could be done.
Actually, I just realized something. Let me re-read the code around line 518:
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
This checks if any ancestor is a Macro (which includes MacroRules and MacroDef). But for a MacroCall, the ancestors would include MacroCall, not MacroRules or MacroDef.
Wait, but MacroCall is not a Macro variant. So this condition would be false for MacroCall token trees.
But wait, let me reconsider. The issue is:
foo!(bar$0)
Here foo is the macro path, and bar$0 is inside the token tree of the MacroCall. The ancestors of the token tree would include MacroCall, not MacroRules or MacroDef.
So the condition p.ancestors().any(|it| ast::Macro::can_cast(it.kind())) would be false, and we would fall through to the next check.
Let me continue reading the code:
} else if find_node_at_offset::<ast::CfgPredicate>(
&speculative_file,
speculative_offset,
)
.is_some()
{
CompletionAnalysis::CfgPredicate
} else {
return None;
}
So if we're not inside a CfgPredicate, we return None. This is the bug!
The fix should be to handle the case where we're inside a MacroCall token tree. In this case, we should provide path completions.
Now let me think about how to implement this fix. We need to:
- Detect when we're inside a
MacroCall token tree
- Provide appropriate completions
For step 1, we can check if any ancestor is a MacroCall:
p.ancestors().any(|it| ast::MacroCall::can_cast(it.kind()))
But ast::MacroCall::can_cast might not exist. Let me check.
Actually, looking at the code, I see that ast::MacroCall implements AstNode, so it should have a can_cast method.
For step 2, we need to provide completions. I think the best approach is to somehow construct a path context and use the normal completion machinery.
Actually, let me look at the approach differently. The issue is that find_node_at_offset returns None when we're inside a token tree. But we can still determine what we're completing by looking at the siblings of the fake ident token.
Let me look at the code that handles MacroSegment completion (line 521-532):
if let Some([_ident, colon, _name, dollar]) = fake_ident_token
.siblings_with_tokens(Direction::Prev)
.filter(|it| !it.kind().is_trivia())
.take(4)
.collect_array()
&& dollar.kind() == T![$]
&& colon.kind() == T![:]
{
CompletionAnalysis::MacroSegment
} else {
return None;
}
This looks at the 4 previous non-trivia tokens to determine if we're completing a macro segment. We could use a similar approach to detect if we're completing a macro path in a MacroCall token tree.
But I think a better approach would be to restructure the code to handle MacroCall token trees by creating a synthetic path context.
Actually, let me look at this from a different angle. Let me check if there are existing tests that cover this case or similar cases.
Let me search for tests related to macro path completion.
Actually, let me first try to reproduce the issue by running the existing tests.
Let me start by understanding the structure better and then implementing the fix.
The fix I have in mind is:
- In the else branch where
find_node_at_offset returns None, check if we're inside a MacroCall token tree
- If so, create a synthetic path context or return a special
CompletionAnalysis variant that triggers path completion
But I realize that returning a CompletionAnalysis variant that triggers path completion would require restructuring the completion code, which is complex.
A simpler approach might be to:
- Detect when we're inside a
MacroCall token tree and we're completing a path
- Directly call the completion functions for macro paths
But this would also require significant changes to the completion code.
Let me look at the code structure more carefully to find the best place to implement the fix.
Actually, I think the key insight is that when we're inside a MacroCall token tree and we're completing an identifier, we should be able to complete it as a path. The simplest way to do this is to create a synthetic NameRefContext with a path context and use the normal completion machinery.
But this would require significant changes to the code structure. Let me think of a simpler approach.
Actually, looking at the code more carefully, I see that the analysis is used in lib.rs to determine which completion functions to call:
match analysis {
CompletionAnalysis::Name(name_ctx) => completions::complete_name(acc, ctx, name_ctx),
CompletionAnalysis::NameRef(name_ref_ctx) => {
completions::complete_name_ref(acc, ctx, name_ref_ctx)
},
...
}
So if we can return a valid NameRef analysis for MacroCall token trees, the normal completion machinery would be used.
The question is how to create a valid NameRef context when we're inside a token tree.
Looking at the code, I see that classify_name_ref creates a NameRefContext by analyzing the syntax tree. When we're inside a token tree, we don't have a NameRef node, so we can't use classify_name_ref.
But we could create a synthetic path context by looking at the tokens around the cursor position.
Actually, let me look at this from a different angle. The issue is that when we're inside a macro invocation's token tree, we can't complete macro paths. But we should be able to.
I think the fix is to detect when we're inside a MacroCall token tree and provide path completions by creating a synthetic path context.
Let me implement this fix:
- In the else branch, check if we're inside a
MacroCall token tree
- If so, try to create a synthetic path context based on the tokens around the cursor
- Return a
NameRef analysis with the synthetic path context
But creating a synthetic path context is complex because we need to construct AST nodes. Let me think of a simpler approach.
Actually, looking at the code structure again, I think the best approach is to add a new handling case for MacroCall token trees in the else branch. We need to:
- Detect when we're inside a
MacroCall token tree
- Check if we're completing a path (first identifier or part of a path)
- If so, provide path completions
But how do we provide path completions when we don't have a NameRef node?
I think the answer is that we need to create a synthetic path context by looking at the tokens around the cursor. Let me look at how to do this.
Actually, let me take a step back and think about the problem differently.
The issue is that find_node_at_offset(&speculative_file, speculative_offset) returns None when we're inside a MacroCall token tree. This is because the parser doesn't recognize identifiers inside token trees as NameRef nodes.
But we still want to provide completions for these cases. The key is to detect the context and provide appropriate completions.
Looking at the code, I see that when we're inside a TOKEN_TREE_META, we provide attribute completions. When we're inside a TOKEN_TREE whose ancestor is a Macro, we provide macro segment completions. We need to add handling for TOKEN_TREE whose ancestor is a MacroCall.
For MacroCall token trees, the completions should be path completions. This is because inside a MacroCall, we're completing the arguments to the macro, which can be paths.
But the issue is that we're inside a token tree, so we don't have a proper path context. We need to somehow create a path context.
Actually, let me look at this from the perspective of the test case:
macro_rules! bar { () => (); }
macro_rules! foo { ($i:ident) => { $i!() }; }
fn main() {
foo!(bar$0);
}
Here, foo!(bar$0) is a macro invocation. The cursor is after bar, and we want to complete bar as a macro name.
The expected behavior is that bar should be completed as a macro name. So the completions should include bar (and possibly other macro names).
Now, the question is: how do we detect that we're completing a macro path?
Looking at the tokens, we have foo!(bar$0). The bar is inside a token tree, and it's the first identifier in the token tree. So we're completing a macro path.
The fix should be:
- Detect when we're inside a
MacroCall token tree
- Check if we're completing the first identifier in the token tree (a macro path)
- If so, provide macro name completions
Let me look at how to implement this. We need to:
- Check if any ancestor is a
MacroCall
- Check if we're completing the first identifier in the token tree (by looking at the siblings of the fake ident token)
- If so, return a
NameRef analysis with a path context
For step 3, we need to create a synthetic path context. This would involve looking at the tokens before the cursor and determining if they form a path.
Actually, I think the simplest approach is to return a CompletionAnalysis::NameRef with a path context that has PathKind::Expr. This would trigger the normal expression path completion, which includes macro completions.
But we need to create a synthetic PathCompletionCtx to pass to the completion functions. Let me look at how to do this.
Actually, I realize that the issue might be more nuanced. When we're inside a MacroCall token tree, we're completing the arguments to the macro, not a macro path. The arguments can be various things, not just paths.
In the test case foo!(bar$0), bar is an argument to foo, and it will be expanded to become a macro path after foo expands. So we should provide completions that make sense for this context.
Since foo's pattern is ($i:ident), the argument should be an identifier. So we should provide completions for identifiers, including macro names.
Actually, looking at the test case completes_in_simple_macro_call:
fn completes_in_simple_macro_call() {
check_no_kw(
r#"
macro_rules! m { ($e:expr) => { $e } }
fn main() { m!(self::f$0); }
fn foo() {}
"#,
expect![[r#"
fn foo() fn()
fn main() fn()
"#]],
);
}
In this test, m!(self::f$0) provides completions for foo and main. These are function completions, not macro completions. And self::f is parsed as a path expression inside the token tree.
So the parser CAN parse paths inside token trees! The key difference is that self::f is a valid path expression prefix, while bar$0 is just an identifier followed by the cursor.
Let me think about this more carefully. When we have m!(self::f$0):
- The parser sees
self::f<IDENT> inside the token tree
- The parser can recognize this as a path expression prefix
- So
find_node_at_offset returns a NameLike::NameRef
- The normal path completion machinery is used
But when we have foo!(bar$0):
- The parser sees
bar<IDENT> inside the token tree
- The parser doesn't recognize this as a path expression prefix (because
bar is not a keyword like self)
- So
find_node_at_offset returns None
- We fall into the else branch and return
None
This explains the difference! The parser can recognize paths that start with keywords like self, super, crate, Self, but not paths that start with regular identifiers.
So the fix should be to handle the case where we're inside a MacroCall token tree and we're completing an identifier that could be a path start.
Now let me think about how to implement this fix. We need to:
- Detect when we're inside a
MacroCall token tree
- Check if we're at the start of an identifier that could be a path
- If so, provide path completions
For step 3, we need to create a path context and use the normal completion machinery. The simplest approach is to create a synthetic path context with PathKind::Expr.
Let me look at how to create a synthetic path context.
Actually, looking at the code, I see that when find_node_at_offset returns None, we don't have access to the syntax nodes needed to create a path context. We would need to construct them from the tokens around the cursor.
Let me look at an alternative approach. Instead of creating a synthetic path context, we could:
- Detect when we're inside a
MacroCall token tree
- Look at the tokens to determine what kind of completion we need
- Directly call the completion functions for that type of completion
For macro path completion, we need to call the function that provides macro completions. Let me look at how macro completions are provided in the normal case.
Looking at the completions module, I see that macros are completed through the normal path completion machinery. Specifically, in completions.rs, the complete_name_ref function handles path completions, and it includes macro completions through the PathKind enum.
But looking at the PathKind enum, I don't see a variant specifically for macro paths. Macros are completed through the PathKind::Expr variant, which provides expression completions including macros.
So if we can create a synthetic path context with PathKind::Expr, we could use the normal completion machinery.
But creating a synthetic path context is complex because we need to construct AST nodes. Let me think of a simpler approach.
Actually, looking at this more carefully, I think the fix should involve restructuring the code to handle MacroCall token trees by creating a synthetic path context.
Let me look at the code structure to find the best place to implement this fix.
Actually, I think I've been overcomplicating this. Let me look at the code again and find a simpler fix.
Looking at the code around line 518:
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
This checks if the parent is a TOKEN_TREE and any ancestor is a Macro (MacroRules or MacroDef). For MacroCall token trees, this condition is false.
The fix could be to add another condition that checks for MacroCall token trees:
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().map_while(ast::Item::cast).any(|it| matches!(it, ast::Item::MacroCall(_)))
{
But ast::Item::MacroCall might not be a valid pattern. Let me check.
Actually, looking at the code, I see that ast::Item includes MacroCall:
ast::Item::MacroCall(_) => None,
So we can check if any ancestor is a MacroCall item.
But the fix needs more than just detecting the context. We also need to provide completions. The question is: what completions should we provide?
For MacroCall token trees, the completions should be based on what the macro expects. But determining this would require macro expansion, which is complex.
For now, let me focus on providing basic path completions for MacroCall token trees. This would include identifiers, macros, etc.
Looking at the code structure, I think the best approach is to add a new CompletionAnalysis variant that handles MacroCall token trees. This variant would contain the information needed to provide completions.
But adding a new CompletionAnalysis variant would require changes in multiple places. Let me think of a simpler approach.
Actually, looking at this more carefully, I think we can reuse the existing CompletionAnalysis::NameRef variant. We just need to create a synthetic path context that triggers path completions.
The key insight is that when we're inside a MacroCall token tree and we're completing an identifier, we should treat it as if we're completing an expression path. This would provide completions for identifiers, macros, etc.
Let me look at how to implement this. We need to:
- Detect when we're inside a
MacroCall token tree
- Create a synthetic path context
- Return a
NameRef analysis with the synthetic path context
For step 2, we need to create a PathCompletionCtx. Looking at the struct definition:
pub(crate) struct PathCompletionCtx<'db> {
pub(crate) has_call_parens: bool,
pub(crate) has_macro_bang: bool,
pub(crate) qualified: Qualified<'db>,
pub(crate) parent: Option<ast::Path>,
pub(crate) path: ast::Path,
pub(crate) original_path: Option<ast::Path>,
pub(crate) kind: PathKind<'db>,
pub(crate) has_type_args: bool,
pub(crate) use_tree_parent: bool,
}
We need to fill in all these fields. This is complex because we need to construct AST nodes.
Actually, I think a simpler approach would be to look at the tokens around the cursor and construct a minimal path context. Let me think about what's needed.
For the simplest case where we're completing bar in foo!(bar$0):
has_call_parens: false (we haven't typed ()
has_macro_bang: false (we haven't typed !)
qualified: Qualified::No (no qualifier)
parent: None (no parent path)
path: the path containing the identifier we're completing
original_path: the corresponding path in the original file
kind: PathKind::Expr { ... }
has_type_args: false
use_tree_parent: false
The tricky part is creating the path and original_path AST nodes. These are needed for the completion machinery to work correctly.
Actually, let me look at how the normal path completion works. When we have a valid NameRef node, classify_name_ref extracts the path from the parent PathSegment and creates a PathCompletionCtx with the appropriate values.
For the case where we're inside a token tree, we don't have a PathSegment node, so we can't extract the path. We would need to construct a synthetic path.
But wait, let me think about this differently. The issue is that find_node_at_offset returns None when we're inside a token tree. But we still have access to the tokens around the cursor position.
Maybe instead of trying to create a synthetic path context, we can modify the approach to handle token tree cases differently.
Actually, looking at this from a different angle, I wonder if the issue is that we should be able to find a NameRef even inside a token tree. Let me check if the parser can recognize identifiers inside token trees as name references.
Actually, looking at the test case completes_in_simple_macro_call, I see that m!(self::f$0) does provide completions. This means the parser CAN recognize paths inside token trees when they start with keywords like self.
The issue is that for foo!(bar$0), the parser doesn't recognize bar as a path because bar is not a keyword that can start a path.
So the fix should be to handle this case by detecting when we're inside a MacroCall token tree and we're completing an identifier that could be a path start, and then providing path completions.
Let me now think about the implementation. I think the simplest approach is to:
- Detect when we're inside a
MacroCall token tree
- Check if we're at the start of an identifier (no previous non-trivia tokens in the token tree that could be part of a path)
- If so, return a synthetic path context
For step 3, we need to create a PathCompletionCtx. But constructing AST nodes is complex. Let me look for an alternative.
Actually, I just realized something. Looking at the code more carefully, I see that the find_node_at_offset function looks for a NameLike at the cursor position. If we're inside a token tree, the parser doesn't recognize identifiers as NameLike nodes.
But the fake ident token we inserted (<IDENT>) is a token, not a node. So find_node_at_offset returns None because there's no NameLike node at that position.
The fix should be to handle this case by detecting when we're inside a token tree and we have an identifier at the cursor position, and then providing appropriate completions.
Let me look at how to implement this. I think the fix should be in the else branch where we currently return None.
Looking at the code:
} else {
return None;
}
We need to add handling for MacroCall token trees before this return None.
Here's my proposed fix:
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.parent().map_or(false, |parent| {
parent.kind() == SyntaxKind::MACRO_CALL
|| parent.ancestors().map_while(ast::Item::cast).any(|item| matches!(item, ast::Item::MacroCall(_)))
})
{
// Handle macro call token tree - provide path completions
// TODO: Implement path completions for macro call token trees
return None;
}
But this still returns None, which doesn't solve the problem. We need to actually provide completions.
Let me think about how to provide completions. I think the best approach is to return a CompletionAnalysis::NameRef with a synthetic path context.
But creating a synthetic path context requires constructing AST nodes, which is complex. Let me look for a simpler approach.
Actually, I just realized that we can use the fake_ident_token to create a synthetic path. The fake_ident_token is a token, and we can create a synthetic PathSegment and Path from it.
But this would require significant changes to the code structure. Let me think of an even simpler approach.
Actually, looking at the code structure, I think we can modify the approach to detect when we're inside a MacroCall token tree and the fake ident is the first identifier in the token tree, and then return a special analysis that triggers path completions.
But I'm not sure how to implement this without significant refactoring. Let me look at the code more carefully to find a simpler fix.
Actually, let me re-read the issue description:
Cannot complete macro path in macro
The user is trying to complete bar in foo!(bar$0) as a macro path. The expected behavior is that rust-analyzer should provide completions for bar, including the bar macro.
Let me look at the code to see if there's a simpler fix.
Actually, I think the key insight is that when we're inside a MacroCall token tree, we should be able to complete paths. The simplest way to do this is to detect the context and return a NameRef analysis.
Let me look at the code to see how to construct a NameRef analysis for this case.
Actually, looking at this more carefully, I think the issue is that when we're inside a MacroCall token tree, we don't have access to the original path or the parent path segments. This makes it difficult to create a proper path context.
But wait, let me think about what information we DO have:
- The
fake_ident_token - the fake ident we inserted at the cursor position
- The
original_token - the corresponding token in the original file
- The
sema - the semantic analyzer
We can use this information to construct a path context.
Actually, I think the simplest approach is to look at the code that handles other token tree cases and see if we can reuse that logic.
Looking at the code for MacroSegment completion (line 521-532):
if let Some([_ident, colon, _name, dollar]) = fake_ident_token
.siblings_with_tokens(Direction::Prev)
.filter(|it| !it.kind().is_trivia())
.take(4)
.collect_array()
&& dollar.kind() == T![$]
&& colon.kind() == T![:]
{
CompletionAnalysis::MacroSegment
}
This looks at the previous tokens to determine if we're completing a macro segment. We could use a similar approach to determine if we're completing a macro path in a MacroCall token tree.
For MacroCall token trees, we would check if the previous tokens form a valid path prefix. If they do, we return a NameRef analysis with a path context.
But the issue is still that we need to create a synthetic path context, which requires constructing AST nodes.
Let me look at an alternative approach. Maybe we can modify the code to use the original_token to look up the corresponding path in the original file and create a path context from that.
Actually, looking at the code more carefully, I see that find_node_in_file_compensated is used to find nodes in the original file that correspond to nodes in the speculative file. We could use this to find the corresponding path in the original file.
But for a MacroCall token tree, there might not be a corresponding path in the original file because the path is inside a token tree.
OK let me think about this differently. The core issue is:
- When we're inside a
MacroCall token tree, find_node_at_offset returns None because the parser doesn't recognize identifiers inside token trees as NameRef nodes
- We return
None for completions, so no completions are provided
The fix should be to handle the MacroCall token tree case and provide completions.
One approach is to modify the speculative file to parse the identifier as a NameRef. But this would require changes to the parser, which is complex.
Another approach is to detect when we're inside a MacroCall token tree and directly provide completions without using the normal path completion machinery.
Let me look at how to implement this second approach. We need to:
- Detect when we're inside a
MacroCall token tree
- Provide completions directly (without using the normal path completion machinery)
For step 2, we need to gather completions for macro names. This would involve looking at all available macros and adding them to the completion list.
But this would require significant changes to the completion code. Let me think of a simpler approach.
Actually, I just thought of another approach. What if we modify the speculative file to wrap the identifier in a way that makes it parse as a NameRef? For example, if we're at foo!(bar$0), we could insert the fake ident as foo!(path! { bar <IDENT> }) or something like that.
But this would be very complex and could introduce other issues.
Let me go back to the original approach of handling MacroCall token trees by returning a NameRef analysis with a synthetic path context.
Actually, I just realized something. Looking at the code structure, the CompletionAnalysis enum is used to determine what kind of completions to provide. For NameRef analysis, the normal path completion machinery is used.
So if we can return a NameRef analysis for MacroCall token trees, the normal completion machinery would be used.
The question is how to create a valid NameRef context for MacroCall token trees.
Looking at the code, I see that classify_name_ref creates a NameRefContext by analyzing the syntax tree. When we're inside a token tree, we don't have a NameRef node, so we can't use classify_name_ref.
But we could create a synthetic NameRefContext by looking at the tokens around the cursor and constructing the necessary information.
Let me look at what information is needed for a NameRefContext:
pub(crate) struct NameRefContext<'db> {
pub(crate) nameref: Option<ast::NameRef>,
pub(crate) kind: NameRefKind<'db>,
}
pub(crate) enum NameRefKind<'db> {
Path(PathCompletionCtx<'db>),
DotAccess(DotAccess<'db>),
Keyword(ast::Item),
RecordExpr {
dot_prefix: bool,
expr: ast::RecordExpr,
},
Pattern(PatternContext),
ExternCrate,
}
For MacroCall token trees, we would want to return NameRefKind::Path(PathCompletionCtx).
The PathCompletionCtx contains:
has_call_parens
has_macro_bang
qualified
parent
path
original_path
kind
has_type_args
use_tree_parent
We need to fill in all these fields. This is complex because we need to construct AST nodes for path and original_path.
Actually, let me look at the code to see how these fields are used in the completion machinery.
Looking at completions.rs, I see that complete_name_ref handles NameRefKind::Path by calling the path completion functions. These functions use the PathCompletionCtx to determine what completions to provide.
The path and original_path fields are used to extract the path segments and provide completions for the current segment.
For a MacroCall token tree, we don't have a proper path node, so we need to construct a synthetic one.
Actually, I just realized that we might be able to use the fake_ident_token to create a synthetic path. The fake_ident_token is the token that was inserted at the cursor position, and it contains the identifier we're trying to complete.
Let me look at how to create a synthetic path from the fake_ident_token.
Actually, looking at this more carefully, I think we can create a synthetic PathSegment and Path from the fake_ident_token. Then we can use these to create a PathCompletionCtx.
But this would require significant changes to the code structure. Let me think of a simpler approach.
OK let me step back and think about this problem from first principles.
The issue is:
- User types
foo!(bar$0) inside a Rust file
foo is a macro invocation, and bar is inside its token tree
- User wants to complete
bar as a macro name
- Currently, rust-analyzer returns
None for completions in this case
The fix should be:
- Detect when we're inside a
MacroCall token tree
- Provide completions for macro names (and other identifiers)
Now, the question is how to provide completions without using the normal path completion machinery.
One approach is to directly gather macro completions and add them to the completion list. This would involve:
- Finding all available macros
- Creating
CompletionItem objects for each macro
- Adding them to the completion list
But this would require significant changes to the completion code.
Another approach is to create a synthetic path context and use the normal completion machinery. This would involve:
- Creating a synthetic
PathCompletionCtx
- Returning a
NameRef analysis with the synthetic context
- Letting the normal completion machinery handle the rest
For this approach, we need to construct AST nodes for the synthetic path. This is complex but might be the cleanest solution.
Let me look at how to construct AST nodes. The syntax crate has functions for creating AST nodes, so we should be able to create a synthetic path from the fake_ident_token.
Actually, looking at the syntax crate, I see that AST nodes are typically constructed by parsing source code. Creating them programmatically would require using the SyntaxNode API directly.
Let me look at how to create a synthetic path using the SyntaxNode API.
Actually, I think a simpler approach would be to check if there's already a path-like structure in the token tree that we can use.
Looking at the tokens in foo!(bar$0):
MACRO_CALL
PATH
PATH_SEGMENT "foo"
EXCL_TOKEN "!"
TOKEN_TREE
IDENT "bar"
The bar is inside the TOKEN_TREE, and it's just an IDENT token, not a PathSegment node.
So we can't reuse an existing path structure. We need to create a synthetic one.
Let me look at how to create a synthetic Path and PathSegment using the SyntaxNode API.
Actually, looking at the syntax crate, I see that we can create synthetic nodes using the SyntaxFactory API or by constructing SyntaxNode directly.
But this would be complex and error-prone. Let me think of a simpler approach.
Actually, I just realized that we might not need to create a synthetic path. Instead, we could modify the code to handle the case where we're inside a MacroCall token tree by directly gathering completions.
Looking at the code structure, the completions module contains functions that gather completions for different contexts. We could add a new function that gathers completions for MacroCall token trees.
But this would require significant changes to the code structure.
OK, let me try a different approach. Let me look at the test case more carefully:
fn completes_in_simple_macro_call() {
check_no_kw(
r#"
macro_rules! m { ($e:expr) => { $e } }
fn main() { m!(self::f$0); }
fn foo() {}
"#,
expect![[r#"
fn foo() fn()
fn main() fn()
"#]],
);
}
In this test, m!(self::f$0) provides completions. This works because self::f is parsed as a path inside the token tree.
The key difference with our case foo!(bar$0) is that bar is not recognized as a path prefix. So find_node_at_offset returns None.
But wait, if self::f is recognized as a path, why isn't bar?
The difference is that self is a keyword that can start a path, while bar is a regular identifier that the parser doesn't recognize as a path prefix.
So the fix should be to handle the case where we're inside a MacroCall token tree and the cursor is at an identifier that could start a path.
Let me look at how to implement this fix.
Actually, I think the simplest approach is to add handling for MacroCall token trees in the else branch. When we detect that we're inside a MacroCall token tree, we should provide path completions.
But how do we provide path completions without a proper NameRef node?
One idea is to use the original_token to look up the corresponding node in the original file. If the original file has a valid NameRef node at that position, we can use that to create a path context.
But in the case of foo!(bar$0), the original file also doesn't have a valid NameRef node because bar is inside a token tree.
So this approach won't work.
OK, I think the fix requires us to handle MacroCall token trees by creating a synthetic path context or by directly gathering completions.
Let me look at the code structure to find the best place to implement this fix.
Actually, let me look at the completions.rs file to see how completions are gathered:
match analysis {
CompletionAnalysis::Name(name_ctx) => completions::complete_name(acc, ctx, name_ctx),
CompletionAnalysis::NameRef(name_ref_ctx) => {
completions::complete_name_ref(acc, ctx, name_ref_ctx)
},
...
}
For NameRef analysis, complete_name_ref is called. Let me look at that function.
<tool_call>
<function=bash_terminal>
<parameter=command>
grep -n "fn complete_name_ref" /rust-analyzer/crates/ide-completion/src/completions.rs
</tool_call>