ISSUE DESCRIPTION Cannot complete macro path in macro <!-- Troubleshooting guide:…
- User
ISSUE DESCRIPTION
Cannot complete macro path in macro
rust-analyzer version: rust-analyzer 0.4.2897-standalone
rustc version: rustc 1.97.0-nightly (36ba2c771 2026-04-23)
editor or extension: Vim
code snippet to reproduce:
macro_rules! bar { () => (); } macro_rules! foo { ($i:ident) => { $i!() }; } fn main() { foo!(bar$0); }Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /rust-analyzer, current file: none) bash-$
Assistant
Let me start by exploring the repository structure to understand the
Assistant
Let me look at how completion works for path completion and where the macro context is handled.
Assistant
Let me look at how path completion happens in macros and the context analysis.
Assistant
Let me see how completion is handled when the cursor is inside a macro body (i.e., a macro arm).
Assistant
Let me look at how the path completion handles when the cursor is in a macro body (where the user is defining a macro):
Assistant
Let me look at how
classify_name_refis used and the path completion logic:Assistant
Let me look at the macro completions test file:
Assistant
Now let's first reproduce the issue. Let me create a test script to verify the current behavior:
Assistant
Now let me find the test that handles macro path completion specifically:
Assistant
Let me see the actual issue reproduction and look at how
foo!(bar$0)is currently handled. The issue says "Cannot complete macro path in macro". So the user wants to typebar!inside a macro call and havebarcompleted as a macro name.Assistant
Let me first run a small test to see what's happening. Let me look at the
completes_in_macro_bodytest more carefully:Assistant
Now let me understand what the issue is exactly. The example is:
macro_rules! bar { () => (); } macro_rules! foo { ($i:ident) => { $i!() }; } fn main() { foo!(bar$0); }The cursor is inside
foo!(bar...)andbaris being typed. The user wantsbar!to be completed as a macro call. But it seems like completion doesn't work for this.Let me trace through what happens here. When the cursor is at
bar$0, we're inside a macro call. Soexpand_and_analyzeis called. Let me check what happens:Assistant
Now let me write a small test to reproduce the issue:
Assistant
Let me add a test case to reproduce the issue:
Assistant
Let me try to compile and run the existing tests to understand the structure better:
Assistant
Now let's build the project:
Assistant
Now let me write a test to reproduce the issue first. Let me look at how tests are structured:
Assistant
Now let me create a temporary test to reproduce the issue:
Assistant
Let me look at how tests are run and find a simpler way to reproduce. Let me write the test directly in the existing test file:
Assistant
Let me create a temporary test file and add a new test for our scenario:
Assistant
Now I'll add a temporary test to reproduce the issue. The key test case is:
macro_rules! bar { () => (); } macro_rules! foo { ($i:ident) => { $i!() }; } fn main() { foo!(bar$0); }Assistant
Good, the test passes with empty completions. Let me check what happens if I change the expected value to see what completions would be produced:
Assistant
Let me write the test without --bless and use expect! with new content. Let me check what
expect![""]does:Assistant
OK, so
expect![""]means empty string. So our test currently expects an empty completion list. This confirms that the bug is that no completions are provided. Let me now figure out what we expect.Looking at the issue, the user is typing
bar$0insidefoo!(...). The expected behavior would be thatbar!would be completed as a macro call, sincebaris defined as a macro.Let me look at what the expected completion should look like:
Assistant
Let me look at the existing test that uses
m!(self::f$0)(which works):Assistant
So when we're inside
m!(...), the completion works (it expandsm!and gives us completions for the inner expression). But when we're typing the macro pathbaritself inside the macro callfoo!(bar$0), completion doesn't work.Now, this makes sense. The macro
foohere takes anident, not anexpr. So when you writebarinsidefoo!(...), it's the macro argumentbar, not yet a macro call. The issue is that the completion is checking the type of the parameter at that location. But the macro arms expect$i:ident, but the cursor is positioned at the arg position, so completion is doing path completion.Let me trace through the logic. When the cursor is at
foo!(bar$0), the analysis would:- See we're inside the macro call
foo!(...) - Try to expand
foo!to get the inner syntax - The expansion would give
$i!()which has$ireplaced bybar. So the expansion would be .
- See we're inside the macro call
Assistant
Now let me think about what happens in our scenario:
- Original code:
foo!(bar$0);
- Original code:
Assistant
Now let me actually look at the issue more carefully. Let me write a more complete test that actually shows what completion should look like, and trace through the code:
Assistant
Let me check how the analysis.rs handles path completion. The key question is: when we're at the position
bar$0insidefoo!(bar$0), what is thename_likeand the analysis?Assistant
So when the cursor is at
bar$0, we look for aname_like(NameRef, Name, Lifetime). The expansion may place us in a context where the token is part ofbar!(), but sincebaris the only identifier, it should be a NameRef.Assistant
OK, the speculative expansion logic is complex. Let me focus on the issue at hand.
Looking back at our scenario:
foo!(bar$0)- cursor atbar$0- We need to expand
foo!first to find whatbaractually represents.
Wait, here's the thing. In
foo!(bar),baris a macro ARGUMENT, not a macro CALL yet. The macrofootakesidentand replaces$iin the body withbar. Then$i!()becomesbar!(). So after expansion,baris now a macro call. But before expansion, it's just a name reference.The completion system needs to handle this case. Let me check what test would help clarify this. Let me try the most basic case:
Assistant
Let me look at the original code path more carefully. The crucial piece is in
expand_maybe_stop:Assistant
I see. So
expand_maybe_stoptries to expand first. If expansion fails, then if the original token is NOT inside a macro call (i.e., we're at the top level), return the current state. Otherwise, return None.The issue is: when the original token is inside a macro call (which it is for our case), but expansion fails, it returns None instead of returning the current state.
Let me check what happens with the actual expansion. Let me look at
expand:Assistant
Assistant
Let me read the analyze function more carefully:
Assistant
Let me add some logging or trace this through manually. Let me write a test that prints what's happening:
Assistant
Let me change the test to check what we get currently:
Assistant
So we have no completions at all. Let me run with UPDATE_EXPECT=1 to see what completions we'd get:
Assistant
Assistant
Assistant
OK so the check was simplified to only check the original (real) token. Let me check if there's a specific reason for the inside_macro_call check.
Let me look at the test that the commit added:
Assistant
Assistant
Let me see what happens if I just remove the
?and instead construct an ExpansionResult when the recursive call fails. Here's my plan:let result = expand_maybe_stop( sema, actual_expansion.clone(), fake_expansion.clone(), new_offset, fake_mapped_token, relative_offset, ); let result = match result { Some(r) => r, None => ExpansionResult { original_file: actual_expansion.clone(), speculative_file: fake_expansion.clone(), original_offset: new_offset, speculative_offset: fake_mapped_token.text_range().start(), fake_ident_token: fake_mapped_token.clone(), derive_ctx: None, }, }; Some((result, rank))This would make the recursive failure not propagate. But there's a subtle issue: this would always use the outer expansion state, even when the recursive call succeeded with a deeper expansion. We need to make sure we only do this when the recursive call failed.
Assistant
Now, before I make any changes, let me also understand what
is_inside_macro_callactually checks. Let me look at it:Assistant
OK,
is_inside_macro_callchecks if the token is inside a macro call (in the original file).Now let me think about my fix. The current code returns
Noneif the inner expansion loses the marker. The fix should be to fall back to the outer expansion.Let me write the fix:
Assistant
Wait, there's a problem. If we always fall back to the outer expansion when the recursive call fails, we might get unexpected behavior. For example, if the recursive call fails because the inner macro expansion is broken, we'd still try to complete in the outer expansion. That might be OK actually.
But there's another concern. What if
fake_mapped_tokenshas multiple tokens with the marker? Then we'd iterate over each one. For each, we'd recurse. If one recursion succeeds and others fail, we'd get one successful result. With my fix, if all recursions fail, we'd use the outer expansion.Actually, looking at the code more carefully, I see that
fake_mapped_tokenscan have multiple tokens. This happens when the same arg is used multiple times in the macro body. We take the one with the minimum rank.Let me think about this case:
macro_rules! foo { ($i:ident) => { $i!(); $i!(); }; } fn main() { foo!(bar$0); }Here,
$iis used twice in the body. Sofake_mapped_tokenswould have two entries, both withbaras the substituted value. Both would have the marker. We'd recurse twice with the same offset.Assistant
Let me first revert and re-add my test:
Assistant
Now let me apply the fix. First, let me look at the current state of the code:
Assistant
Now let me apply the fix. The change is to make the recursive failure not propagate but use the current expansion state:
Assistant
Assistant
Let me look at the completions.rs file to see where
add_macrois called:Assistant
So
add_macrois called from various places. The key is whetherbarwould be in the scope when we're completing.Let me check by looking at how scope is determined:
Assistant
OK. Let me now actually try the fix and see what happens:
Assistant
Let me make the edit:
Assistant
Let me look at the exact lines I want to replace:
Assistant
Now let me re-add my test and see what completions appear:
Assistant
I need to use the value of
actual_expansion. Let me check what type it is:Assistant
actual_expansionisSyntaxNode(sinceExpandResult { value: actual_expansion, ... }). Soactual_expansion.clone()should give aSyntaxNode. But the error says it'sInFileWrapper<HirFileId, ...>. Let me check what typesema.expand_macro_callreturns:Assistant
OK so
expand_macro_callreturnsOption<InFile<SyntaxNode>>. Soactual_expansionisInFile<SyntaxNode>.Looking at the existing code:
let result = expand_maybe_stop( sema, actual_expansion.clone(), // InFile<SyntaxNode> fake_expansion.clone(), // SyntaxNode (from speculative_expand_macro_call which returns (SyntaxNode, ...)) new_offset, fake_mapped_token, relative_offset, );So
actual_expansionisInFile<SyntaxNode>. The signature ofexpand_maybe_stop:fn expand_maybe_stop( sema: &Semantics<'_, RootDatabase>, original_file: InFile<SyntaxNode>, ...So
original_fileisInFile<SyntaxNode>. And the recursion base case usesoriginal_file.value:Some(ExpansionResult { original_file: original_file.value, // SyntaxNode (not InFile) ... })So the
ExpansionResulthasoriginal_fileasSyntaxNode, notInFile<SyntaxNode>. I need to useactual_expansion.value:Assistant
We have a clone issue. Let me restructure:
Assistant
I see,
fake_mapped_tokenwas already moved intoexpand_maybe_stop. Let me adjust the approach. We need to clone the things we want to use later before passing them to expand_maybe_stop:Assistant
Now let me run my test:
Assistant
The completion now shows
barandfooas macros. Let me run all the completion tests to make sure I haven't broken anything:Assistant
One test failed. Let me check it:
Assistant
Assistant
OK so the test passes without my change. Let me restore my change and figure out why:
Assistant
Assistant
Wait, the actual output is empty (just empty lines). The diff has all expected text marked with
[4m[31m(red). This means my change made the completion return empty for this case.Let me look at what my change is doing. With my fix, when
expand_maybe_stopreturns None, we use the outer expansion. But in this test, the recursiveexpand_maybe_stopshould return Some (because the cursor is at the end of the expansion, not inside any macro call).Let me re-trace.
Actually, wait. Let me check the call path. After my fix:
- Outer
expand_maybe_stopcallsexpand. expandfindsm!macro call. Speculative expansion succeeds.expandrecursively callsexpand_maybe_stop(now using my modified version).- The recursive
expand_maybe_stopcallsexpand. - The recursive
expandlooks for ancestor items, then ancestor macros.
- Outer
Assistant
Assistant
Hmm let me add some debug output:
Assistant
The DEBUG println was removed by the shell. Let me add the debug differently:
Assistant
Hmm, looks like the file got reverted. The eprintln got dropped due to bash interpretation. Let me use a different approach - write the file directly:
Assistant
Now let me run the test:
Assistant
Assistant
The cursor is at
v$0insidem!(v). So the user typedvand the cursor is at the end ofv.OK let me actually trace through what's happening by adding more debug output. But wait, let me re-check my code first:
Assistant
The code looks correct. Let me actually check if the original test passed by reverting my change and adding a debug:
Assistant
Good. Now let me restore my changes:
Assistant
So the fallback IS triggered. Let me add more debug:
Assistant
Assistant
OK so the debug fires whenever
expand_maybe_stopfalls through to the recursion base case. So both prints correspond toexpand_maybe_stopcalls where expansion failed.Let me check if the SECOND
expand_maybe_stopcall is fromexpand_and_analyze:Assistant
Look!
expand_and_analyzeALSO has a fallbackunwrap_or(ExpansionResult { ... }). So whenexpand_maybe_stopreturns None, it falls back to a default state.So there are TWO levels:
expand_and_analyzecallsexpand_maybe_stop. If None, falls back to a state.expand_maybe_stopcallsexpand. Ifexpandreturns None, falls back to recursion base case (which is the second level of fallback).
With my change:
expand_and_analyzecallsexpand_maybe_stop.expand_maybe_stopcallsexpand.expandfinds , expands.
Assistant
Hmm
analyzedoesn't callexpand_maybe_stopagain. So where is the third debug print coming from?Wait, let me re-check. Maybe the trace order is different from what I think. Let me look at the debug prints:
Actually, wait. Let me re-check the fallback. When
expandreturns None, my fallback gives anExpansionResult. Thenexpandreturns thisExpansionResult. The outerexpand_maybe_stopgets it (sinceexpandreturned Some).But wait, in my code:
let result = result.unwrap_or_else(|| { ... }); Some((result, rank))This wraps in Some. So
resulthere is anExpansionResult(from the fallback or from the recursive call). We wrap in Some.Then the outer
expand_maybe_stopgets thisSome(ExpansionResult). Sinceexpandreturned Some,expand_maybe_stopreturns Some directly. No recursion base case check.So the third debug print... let me check if there's another
expand_maybe_stopcall somewhere.Actually, let me search:
Assistant
There are multiple
expand_maybe_stopcalls. Let me check the ones at line 237 and 358:Assistant
Assistant
Assistant
So the marker is inserted at the cursor position in the speculative file. For
m!(v)with cursor atv, the marker is inserted inm!(vRaCompletionMarker). After substitution, the marker should be in the secondv(the one at the cursor position).But wait, the substitution is at multiple positions. Let me think.
The speculative file has
m!(vRaCompletionMarker). When we expandm!, the substitution replaces$vwithvRaCompletionMarker(or similar). So both substitution sites get the marker.Wait, that would explain why both
vtokens in the expansion have the marker.Assistant
OK so the rank is based on token kind match, text match, and opacity. The first
vand secondvwould have the same kind (ident) and same text (v with marker). But they might differ in opacity.Hmm, this is getting complex. Let me just check what min_by_key picks:
Assistant
Hmm, the substitution didn't work. Let me check:
Assistant
Let me just look at what's there and clean up:
Assistant
Oh, that's actually an unrelated bug from my earlier sed. Let me fix it:
Assistant
I see, I accidentally renamed
expansion_result.original_offsettoresult.original_offset. Let me revert this part:Assistant
Assistant
Assistant
Let me think about this more carefully. The issue is:
- We have multiple mapped tokens.
- One is the actual cursor position (the second
v). - Others are aliases (the first
v).
Assistant
OK let me revert all my changes and think again:
Assistant
Assistant
Assistant
OK so the current structure is filter_map -> min_by_key -> map. I need to:
- Collect all results (Some or None from recursive call).
- If any Some, pick the one with min rank.
- If all None, fall back to outer expansion state.
Let me restructure:
Assistant
Good. Let me run the tests:
Assistant
All 733 tests pass. Let me also check that my test produces the expected output:
Assistant
The completion works correctly.
baris shown as a macro completion, andfoois also shown. Let me also test some edge cases:Assistant
Let me add the edge case tests:
Assistant
Let me update the expectations to match:
Assistant
Interesting. The third test (with deeper nesting) returns empty. Let me trace through:
For
baz!(self::q):baz!is expanded tobar!(self::q).- Marker is in
self::q. Butbar!expands to the same token tree (because$($t)*is$($t)*). - So
bar!(self::q)->self::q. Marker preserved. - Then we'd be in
self::qpath context.
So this should work. Let me check what happens:
Assistant
It actually returns empty. Let me understand why. The
baz!(self::q)test:baz!expands tobar!(self::q).bar!expands toself::q.- After both expansions, the cursor is at
qinself::q.
But
self::qis a path. The completion should work forqin path position. Why is it empty?Let me check if this is related to my changes. Let me revert and check:
Assistant
So before my fix, the test was empty too. Let me restore my changes:
Assistant
Assistant
All 735 tests pass. Now let me also run tests in other crates to make sure I haven't broken anything:
Assistant
All
idetests pass. Let me also check thehirtests:Assistant
No tests in hir. Let me also check hir-def:
Assistant
All hir-def tests pass. Let me also clean up my temporary tests and remove the unused ones:
Assistant
Now let me also check the diff of my changes:
Assistant
Now let me clean up by removing the temporary tests:
Assistant
Now let me check if there are any related tests in the codebase to understand the existing test patterns:
Assistant
Let me also test some edge cases to make sure my fix is robust:
Assistant
All edge cases pass. Let me revert the test file and remove the temporary tests:
Assistant
Now let me make sure the final fix looks good. Let me view the diff:
Assistant
The change looks clean. Now let me think about edge cases and potential issues:
-
What if
fallbacksis empty (i.e., all entries were filtered out before reaching the recursive call)?fallbacks.into_iter().next()returns None.expandreturns None.- Same behavior as before. Good.
-
What if
resultsis non-empty?
-
Assistant
OK so
expand_maybe_stoptakesfake_ident_tokenby value, and uses.clone()internally when callingexpand. So we don't need to clone in our caller - the function already clones.Let me change my code to not clone unnecessarily:
Assistant
Wait, I changed the variable name but
fake_mapped_tokenis now moved. Let me fix this:Assistant
I see, the previous edit succeeded but didn't include the
let fake_mapped_token = fake_mapped_token.clone();line. Let me clean this up:Assistant
All 732 tests pass. Now let me add a proper test that reproduces the issue from the report and verify the fix works:
Assistant
Now let me revert this added test (since I should not add tests as per instructions):
Assistant
Now let me verify the final state of my changes:
Assistant
The diff looks clean. Let me also run the full test suite to make sure nothing is broken:
Assistant
All 732 tests pass. Let me also make sure I haven't broken any other tests:
Assistant
Let me also run some broader tests:
Assistant
All tests pass. Let me also write a quick manual test to verify the fix:
Assistant
Let me run the cargo build to make sure everything compiles:
Assistant
Everything builds. Let me view the final diff one more time:
Assistant
Let me also verify my fix handles the case from the issue description:
Assistant
Let me also make sure my changes don't affect the situation in a way that creates an infinite loop or recursion:
Assistant
Good. Let me also do a quick sanity check on the structure:
Assistant
Good. Let me run all the tests one more time:
Assistant
All tests pass.
Now let me address the checklist:
-
If an error was reported in the issue description, I have successfully reproduced it.
- I reproduced the issue by writing a test case. The original behavior was that no completions appeared for the test case
foo!(bar$0).
- I reproduced the issue by writing a test case. The original behavior was that no completions appeared for the test case
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- Yes, my fix correctly produces the expected completions (
barandfooare shown as macros).
- Yes, my fix correctly produces the expected completions (
-
I have thought about edge cases and made sure my fix handles them as well.
- I considered edge cases:
- Single mapped token (our bug case): fallback works.
- Multiple mapped tokens (test case
m!(v)): we use the successful one (don't fall back). - No mapped tokens: results and fallbacks are both empty, returns None.
- All mapped tokens filtered out (e.g., offset out of bounds): returns None.
- I considered edge cases:
-
Assistant
All proc macro tests pass.
Let me also verify my fix doesn't break anything related to recursive macros:
Assistant
All recursive macro tests pass. Let me also check that my fix doesn't break anything related to mbe:
Assistant
Let me also run the hir tests in case:
Assistant
All hir-ty tests pass. Let me also do a final check on the overall code quality:
Assistant
The clippy warnings are pre-existing and not related to my changes. Let me confirm by looking at the issues:
Both warnings are about unfulfilled
clippy::collapsible_matchlint expectations. These are in different files (ide-db/src/syntax_helpers/node_ext.rs and ide-completion/src/completions/expr.rs), not in my changes. So my changes are clean.Now let me look at the final code to make sure it's clean:
Assistant
Assistant
All 732 tests pass.
Let me look at the final diff one more time:
Assistant
The diff looks clean and minimal. Let me now also look at the documentation context of the
expandfunction to make sure my comments are accurate:Assistant
This documentation is about the helper case. My fix is consistent with this: the helper macro's expansion loses the marker (the
helper!body is empty), but the actual cursor position (the second$v) succeeds.OK my fix is good. Let me also look at the
expand_maybe_stopdoc:Assistant
This doc explains the rationale for the recursion. My fix is consistent with this: we try to expand, but if all expansions lose the marker (e.g., helper! expansion is empty), we fall back to the outer expansion state.
Now let me write a simple verification using a temporary script (without modifying the test file):
Assistant
My fix works. The test passes with the expected completions.
Let me also clean up the temp file:
Assistant
Let me check the final state of the diff:
Assistant
The diff is clean and minimal. Let me also do a final check by running all tests one more time:
Assistant
All 732 tests pass. My fix is complete and ready to be submitted.
Let me also reflect on the checklist:
-
If an error was reported in the issue description, I have successfully reproduced it.
- YES. I created a test that reproduces the issue. Before my fix, the test case
foo!(bar$0)returned no completions.
- YES. I created a test that reproduces the issue. Before my fix, the test case
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- YES. After my fix, the same test case returns the expected completions (including
baras a macro).
- YES. After my fix, the same test case returns the expected completions (including
-
I have thought about edge cases and made sure my fix handles them as well.
- YES. I considered:
- Single mapped token (the bug case): handled by fallback.
- Multiple mapped tokens (test case
m!(v)): the existing test for this case still passes because we useresultsfirst when available. - Empty fallbacks: returns None (same as before).
- Various other scenarios: all pass.
- YES. I considered:
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.