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 using git reset --hard command.
Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later.
Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to 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 first understand the issue. The issue is about macro path completion - when inside a macro call's arguments, trying to complete the macro name (which is at the path position). Let me look at the completion code
Assistant
Now let me look at the analysis module:
Assistant
Let me look at the classify_name_ref function specifically:
Assistant
Now let me look at how the issue manifests. First, let me reproduce the issue:
Assistant
Let me look at the existing tests to understand how completion tests work:
Assistant
Let me look at the expand_to_test test which might have a similar pattern:
Assistant
Now I have an idea of what the test infrastructure looks like. Let me look for existing tests that cover the specific scenario in the issue:
Assistant
Now let me create a simple script to reproduce the issue:
Assistant
Now let me write a small test that reproduces the issue:
Assistant
Let me look at the special.rs test file to find any tests related to this:
Assistant
Let me now look at how the completion code identifies the position when we have foo!(bar$0). The issue is that when we type bar$0 inside foo!(...), the macro foo expands to use $i, and then $i!() is called.
Let's understand what happens when we type bar$0 inside foo!(bar$0);:
We are inside the macro foo's token tree, in the position where $i:ident would be substituted.
When we type bar$0, we want this to be completed with valid identifier names like bar.
Let me see if there is a test that exercises this:
Assistant
OK, so the test expand_to_test!(v$0) does work. It expands v$0 (which is a $i:ident parameter) and substitutes it as an expression $i;. So the identifier v becomes an expression, and we complete things that work in expression context.
So foo!(bar$0) calls the macro foo with bar as the ident $i. Then $i!() becomes bar!(). So at position bar$0, we are completing in a position that will become the macro call path.
This is more complex. When we type bar$0, we want to complete it as a path/macro call. We expect to see macros that could be called.
Let me write a test to see what happens currently:
Assistant
Now let me create a simple test for the issue in the existing test file to confirm the behavior:
Assistant
So in this case, i!($0) (with empty) and i!(module$0) does correctly expand module and complete. Let me see if there's a more specific test:
Assistant
OK, now let me write a quick test for the issue. First, let me run the existing tests to make sure things work:
Assistant
Now let me try to build:
Assistant
Good. Now let me write a quick test to see the current behavior:
Assistant
Now let me write a temporary test in the existing test file to see what we get:
Assistant
Let me look at an actual existing test to understand:
Assistant
OK. Let me now add a temporary test inline to see what currently happens:
Assistant
OK, the test passes with empty completions. Let me update the test to see what's actually returned:
Assistant
Interesting! So the actual output is completely empty - no completions at all. Let me see what happens with the existing tests that pass:
Assistant
Now let me look at what other tests work to understand the proper layout:
Assistant
Let me look at what other completion tests look like with bar$0:
Assistant
Let me look at the actual test that's relevant - tests that handle macro_rules:
Assistant
Let me see the test expand_to_test!(v$0) works to understand. Let me look at the result with cargo test:
Assistant
OK, so the existing test passes. The completion gives 56 items or so. Now let me check what happens in the issue case - the issue is that there are zero completions.
Let me also look at where the analysis would have gone wrong:
Assistant
Now let me look at how the expansion works for our case. Let me trace what happens. The issue snippet:
The body of foo! is $i!() where $i is the ident we're completing.
The expansion of foo!(bar$0) should be bar$0!().
The completion system would:
Identify that we're inside the foo! macro call.
Speculatively expand foo! to see what we get.
After expansion, the position $i!() becomes bar!() (with $i replaced by bar).
The completion system should then identify the cursor position in the expanded code as being right after bar (in the macro path).
Let me look at how the macro_segment analysis works:
Assistant
OK, so this is for macro segment definitions. Now let me look more carefully at the issue. Let me check the analysis to see what's happening with the position bar$0. Let me trace this more carefully by looking at the speculative expansion.
Assistant
Now let me understand the expansion flow. When the speculative expansion occurs for foo!(bar$0):
The original macro call is foo!(bar) (without $0)
The speculative args is bar <fake_ident_token> (with the fake ident)
The expansion should be bar<fake_ident_token>!()
We then look for the cursor in the expansion
So in this case, the cursor lands in the middle of a macro call path (bar$0!()). The completion system should recognize this as a path completion.
Let me trace what happens in analyze function:
Assistant
So when we are inside a macro foo!(bar$0):
We speculatively expand foo! to bar!() (since $i is replaced by bar and the !() is appended).
The cursor in the speculative file is right after bar (where the $0 was inserted).
We look at the cursor position to identify what kind of completion to perform.
In the speculative file, after expansion, the cursor is in the middle of bar!() which is the macro call path. We need to identify this position as a path completion.
Now let me see what find_node_at_offset returns:
Assistant
Let me look at the actual expansion. I need to understand if the speculative expansion succeeds. Let me trace this with some debug prints:
Assistant
Let me write a quick debug program that uses rust-analyzer's API:
Assistant
Let me modify the existing test for the issue instead:
Assistant
Confirmed: actual output is empty. Let me now look at what analysis is happening. I'll add some debug prints to understand:
Assistant
Let me trace this more carefully. Let me add some debug output to understand the issue:
Assistant
OK, so when find_node_at_offset returns None, we go into the analysis branch where we either return String, UnexpandedAttrTT, MacroSegment, CfgPredicate, or None.
Let me add some debug prints to see what's happening:
Assistant
Let me check what's happening. The expansion should turn foo!(bar<ident>) into bar<ident>!(). Let me add some tracing to investigate:
Assistant
Let me put some debug prints in the analysis to see what's happening:
Assistant
Let me add a debug print and then run the test:
Assistant
Let me modify the analyze function temporarily to add some debug output:
Assistant
Let me add an eprintln to see what's going on:
Assistant
Let me revert this:
Assistant
Let me edit it properly:
Assistant
No debug output? Let me check if analyze is even called:
Assistant
Now we can see what's happening. The expansion is just foo!(barraCompletionMarker) - the macro foo is NOT being expanded! The speculative_file is showing that foo has not been expanded.
This means expand_maybe_stop is returning the same file as input without expanding foo. Let me check the expansion code more carefully:
Assistant
Let me add more debug prints to track what's happening:
Assistant
Excellent! Now we have a clearer picture:
The expand function returns false (None) for both attempts
The actual_macro_call is correctly identified as foo!(bar)
The macro_call_with_fake_ident is correctly identified as foo!(barraCompletionMarker)
Both actual_expansion_check and spec_expansion_check are true (Some)
So the expansion succeeds, but for some reason the function returns None. Let me look at the relevant code path:
Assistant
Now let me look at why this returns None. The expansion should work. Let me add more debug:
Assistant
Now I can see clearly:
actual_expansion is "bar!()" ✓
fake_expansion is "barraCompletionMarker!()" ✓
fake_mapped_tokens[0] is "barraCompletionMarker" ✓
new_offset = 0, relative_offset = 3, sum = 3, actual_range = 6 (the expansion is fine)
But expand_maybe_stop returns !
Assistant
Looking at this, the expand_maybe_stop function:
Tries expand(...). If that succeeds, returns the result.
Otherwise, checks if the original token is NOT inside a macro call. If true, returns the original file (recursion base case). If false, returns None.
So the recursion base case checks: is the original token NOT inside a macro call? If false (i.e., we're inside a macro call), return None.
In our case, after the first expansion, bar!() is the actual expansion. The original token (at offset 0 in bar!()) is bar, which IS inside a macro call (bar!()). So the base case fails and returns None.
But wait - in this case, we actually DON'T want to expand further. The cursor is at the path of the macro call, not inside its arguments. We should stop recursion here.
The check is_inside_macro_call would return true for bar!() because bar is inside the macro call bar!(). But the cursor is in the macro path, not the arguments!
So we need a better check. Let me see how is_inside_macro_call works:
Assistant
So is_inside_macro_call checks if the token is inside a MacroCall. The bar token at the start of bar!() IS inside the macro call bar!().
Now the recursion logic is: when expand fails, we check is_inside_macro_call to decide if we should stop. If is_inside_macro_call is true, we return None because we don't want to proceed with the original file (since we're inside a macro).
But this is wrong! When we're at the path of a macro call, we should treat it as if we're NOT inside the macro - we're at the position where the macro name is being completed. We want to stop expanding at this point.
Let me check what happens in the other test case:
Assistant
In this test, foo!(f$0):
foo! is a macro call that takes $expr:expr and expands to const BAR: u8 = $expr.
After expansion, f$0 becomes const BAR: u8 = f$0 (substituting $expr with f).
So f is in an expression context, and we get expression completions.
The test passes because:
After expanding foo!, the result is const BAR: u8 = f.
f is not inside any macro call (it's just at the start of an expression).
So is_inside_macro_call returns false, and we return the original (expanded) file.
In our issue case:
After expanding foo!, the result is bar!().
bar is at the start of a macro call bar!().
bar IS inside a macro call (its own).
So is_inside_macro_call returns true, and we return None (no completion).
The issue is that when the cursor is at the path of a macro call (not inside the arguments), we should treat this as if we're not inside the macro call. We should stop the recursion here.
Assistant
Assistant
Let me think about this. The simplest fix might be to change the recursion base case check. Instead of just checking is_inside_macro_call, we should also check if we're at the path of the macro call. If we're at the path (not in the arguments), we should still allow the recursion base case.
Actually, wait. Let me look at the original file more carefully. When the recursion base case triggers:
It uses original_file which is the actual expansion (or the original file in case no expansion happened).
It checks if the original_token is inside a macro call.
But the issue is that bar!() IS a macro call (with bar as the path and () as the args).
Let me check what the AST looks like for bar!():
Assistant
Actually let me check this with a simpler approach. Let me look at the relevant code:
Assistant
The base case is when the original token is NOT inside a macro call. So if the token IS inside a macro call, we return None (don't proceed).
In our case, bar (in bar!()) IS inside the macro call bar!(). So we return None.
But the cursor is in the path, not the arguments. Let me think about whether we can distinguish these cases.
Looking at is_inside_macro_call:
value.parent_ancestors().any(|ancestor| {
if ast::MacroCall::can_cast(ancestor.kind()) {
return true;
}
...
})
So is_inside_macro_call returns true if the token is inside any MacroCall ancestor. The bar token has bar!() as a MacroCall ancestor.
To distinguish "in path" from "in arguments", we can check if the token is inside the token_tree of the macro call. If the token is inside the token_tree, then it's in the arguments. If it's not, it's in the path (or somewhere outside).
Actually, looking at this more carefully, I think we need a better check. Let me look at what makes the case special:
Assistant
Now let me look at where to put the fix. The recursion base case in expand_maybe_stop is where the problem manifests. Let me modify the recursion to handle this case better.
The cleanest approach would be to:
Add a check in expand_maybe_stop (or expand) to recognize when the cursor is at the path of a macro call and avoid expanding that macro.
Let me look at this more carefully. Actually, I think the issue is more fundamental. Let me see:
When we have foo!(bar$0) where foo expands to $i!():
We expand foo -> result is bar!() with cursor at start of bar.
We recursively try to expand. The recursion sees that we're inside a macro call bar!() and tries to expand it.
But we don't want to expand bar!() because the cursor is at the macro path!
So we need to detect this case and stop the recursion. Let me modify the recursion base case check to be more precise.
Let me look at the actual change I want to make:
Assistant
Looking at this, I need to check if the cursor is INSIDE the macro call's arguments (token tree), not just inside any ancestor that's a macro call.
Let me look at how the macro call is structured:
Assistant
So MacroCall has:
path
!
token_tree
Let me think about the right check. We want to check if the token is in the token_tree part of the macro call. If yes, then it's in the arguments. If no (but it's still inside a MacroCall ancestor), then it's in the path or somewhere else.
Actually, looking at the recursion base case more carefully:
if token_at_offset_ignore_whitespace(&original_file.value, original_offset + relative_offset)
.is_some_and(|original_token| {
!sema.is_inside_macro_call(original_file.with_value(&original_token))
})
This is the recursion base case. It triggers when the original (non-speculative) file's token at the position is NOT inside a macro call. If this is true, we can return the current files as the base.
Assistant
Let me think about this. The check is in expand_maybe_stop. Let me modify it to check if we're at the path of a macro call:
Actually, let me look at the original token more carefully. When we have bar!() (with cursor at bar), the token bar has these ancestors:
bar (NameRef token)
bar (PathSegment)
bar (Path)
bar!() (MacroCall)
The check should be: if the token's nearest MacroCall ancestor's path contains this token (i.e., we're in the path), then we're NOT inside the macro call's arguments.
Let me make the fix:
Assistant
Now let me think about the right approach. Looking at the issue:
The expansion bar!() has bar as the path. We want to treat bar as if it's a regular identifier (in path position). The cursor is at the path.
The fix should be: when we check is_inside_macro_call, we should also check if the token is in the path of the macro call. If yes, we should consider it NOT inside the macro call.
Actually, I realize the issue might be simpler. Let me re-look:
When expand_maybe_stop is called with:
original_file = bar!() (the actual expansion)
speculative_file = barraCompletionMarker!() (the speculative expansion)
original_offset = 0
The expand function tries to expand the cursor position. The cursor is at offset 0 in bar!(), which is the start of bar. So expand finds a TokenTree ancestor at offset 0+3 (after the relative offset). Wait, the offset passed is ?
Assistant
So the is the offset between the cursor position and the start of the fake_ident_token. In our case:
Assistant
Now let me think about the right approach. Let me look at the AST structure of bar!():
Assistant
Now let me think about the implementation. I'll modify the recursion base case to handle the case where the cursor is at the path of a macro call.
Let me look at the code:
Assistant
Let me think. The check should be more nuanced. We want to allow the recursion base case when:
The token is NOT inside any macro call (original case), OR
The token is at the path of a macro call (new case).
For the second case, we need to check if the token's nearest macro call ancestor has this token in its path (not in its token_tree).
Let me write the fix:
Assistant
Now let me check the AST for MacroCall:
Assistant
Good. So MacroCall has path() and token_tree(). The structure is:
MacroCall
Path (path)
! (excl_token)
TokenTree (token_tree)
So we can check if a token is inside the token_tree or path of a macro call by checking ancestors.
Let me write the fix:
Assistant
Let me look at this. I think the cleanest fix is to modify the recursion base case. Let me check is_inside_macro_call again:
This checks if any ancestor is a MacroCall. For our case, bar has bar!() MacroCall as an ancestor. So it returns true.
I want to add a check: if the cursor is at the macro call's path (not the token tree), don't consider it inside.
Let me think about the cleanest approach. Let me modify the recursion base case check:
Assistant
parent_ancestors is a method on SyntaxNode. Now let me think about the right place to fix this.
Looking at the recursion base case logic:
if token_at_offset_ignore_whitespace(&original_file.value, original_offset + relative_offset)
.is_some_and(|original_token| {
!sema.is_inside_macro_call(original_file.with_value(&original_token))
})
The intent of is_inside_macro_call is to check if the token is inside a macro call's argument list (token tree). But it's checking if the token is inside any MacroCall ancestor, which is too broad.
Let me write a helper function to check if a token is inside the token tree of a macro call (specifically the argument part):
Actually, looking at this more carefully, I think the fix should be in itself. Or we can add a separate check.
Assistant
Let me think about the best approach. I think the cleanest fix is to:
Add a check in expand_maybe_stop that handles the case where the cursor lands at the path of a macro call.
The idea is: when expand fails AND we're in the path of a macro call (not in its arguments), we can use this as the base.
Let me look at how is_inside_macro_call checks the ancestors. Maybe I can add a more precise check.
Actually, looking again at the code, I realize there's a different approach. We can modify the check to also accept the case where the cursor is at the path of the macro call. Let me write the fix:
Assistant
Let me now think about the approach. The check !sema.is_inside_macro_call(...) is too strict. The fix should be to also allow the case where we're inside the path of a macro call.
Let me look at what helpers are available:
Assistant
Now let me write the fix. I'll add a helper function and modify the recursion base case:
Assistant
OK, so when the cursor is on the path of a macro call, it gets handled via kind_macro_call(it). Let me look at that:
Assistant
OK, so when the path completion is on the path of a macro call, we get the kind_macro_call branch. This handles our case, IF the cursor lands at the path of the macro call.
Now back to the recursion base case. The fix is to allow the recursion base case to trigger when the cursor is at the path of a macro call.
Let me write the fix. I'll modify the recursion base case check:
Assistant
Now let me write the fix. The idea is:
If the token is NOT inside any macro call, allow it (original behavior).
If the token is inside a macro call but the cursor is at the macro call's PATH (not token_tree), allow it (new behavior for the issue).
Let me look at how to identify "token is at the path of a macro call":
The token's ancestors include a MacroCall. If we walk up from the token and find a MacroCall, we need to check whether the MacroCall's path() ancestor is an ancestor of the token. If yes, the token is in the path. Otherwise, it's in the token_tree.
Let me write this:
Assistant
Let me now write the actual fix:
Assistant
Now let me think about this more carefully. Looking at the issue from a different angle:
The recursion base case is trying to determine when to stop expanding. The current logic:
If expand succeeds, return that result.
Otherwise, if the token is NOT inside a macro call, accept the current file as the base.
Otherwise, return None (don't use this file as the base).
The problem is that after expansion, we may end up at a position that is technically inside a NEW macro call (e.g., bar!() after expanding foo!). The current logic doesn't handle this.
What I want: if the cursor lands at the path of a macro call (regardless of whether it's the original or a new one), treat it as a "stable" position for completion.
Let me write the fix. I'll modify the recursion base case:
Assistant
Wait, I think I'm overcomplicating this. Let me revisit. Looking at the original check more carefully:
The check is_inside_macro_call was returning true. I want to instead check if we're inside the token_tree (arguments) of the macro call. Let me check the actual function semantics.
Actually, I realize there's an issue with my approach. When the cursor is at bar (start of bar!()), the bar token is inside the macro call. But its parent is PathSegment, not TokenTree. So my check correctly returns false (not inside the arguments).
Let me build and test:
Assistant
Now we have completions! Let me see the full output:
Assistant
We have completions now. We see:
fn main()
ma bar macro_rules! bar
ma foo macro_rules! foo
bt u32
various keywords
Hmm, but the issue is that we're getting some keyword completions like if, for, etc. that are not relevant for the macro path completion. Let me see what's happening.
Looking at the output, this looks like we're completing an expression, not a path. Let me check more carefully.
The result if, for, match, etc. suggests this is treated as an expression context, not a path context. But we want a path completion.
Let me think. In the expansion bar!(), the cursor is at bar (in the path of the macro call). But the result treats it as an expression.
Let me debug what kind of completion this is. Let me look at the classify_name_ref function:
Assistant
OK so kind_macro_call is called when the parent of the NameRef is a MacroCall. Let me check what kind_macro_call does:
Assistant
OK so kind_macro_call handles the case where the parent of NameRef is a MacroCall. It checks what the parent of the macro call is (MacroExpr, MacroPat, MacroType, etc.) and creates the appropriate kind.
In our case, bar!() is the macro call. Its parent is MacroExpr. So make_path_kind_expr is called.
This means it's being treated as an expression. But we want it to be a path completion for the macro name.
Hmm, looking at the existing test complete_module_exists_colons:
Let me check if the difference is that we use check_no_kw here. Let me try with that:
Assistant
With check_no_kw, the result is:
fn main() fn()
ma bar macro_rules! bar
ma foo macro_rules! foo
bt u32 u32
This is similar to the completes_qualified_macros test! Both bar and foo macros are suggested, plus main function and u32 builtin type.
This looks correct! Let me update the test:
Assistant
Let me update the expected value:
Assistant
The test passes. Now let me check that my fix doesn't break other tests:
Assistant
Two tests failed. Let me see them:
Assistant
OK so this test is for the where keyword in stmt list. It's broken because of my fix. Let me investigate.
The test is:
struct Struct $0
So we have struct Struct and the cursor is at the end (after Struct). Expected: kw where only.
With my fix, the actual is empty. Let me investigate. This is interesting - the test expects the where keyword. So this means the cursor is being placed inside a macro-like context?
Wait, let me look at the test setup. The test wraps it in:
const _: () = {struct Struct $0};
So this is a const _: () = {struct Struct;} (with ; added). Inside, we have struct Struct and the cursor is at the end.
The expected behavior is that we get kw where as a keyword completion. But with my fix, we get nothing.
Assistant
Assistant
Let me look at line 100-110 of item.rs to understand the test structure:
Assistant
OK so the test is checking that when we have struct Struct $0 wrapped in const _: () = {...};, we get kw where. Let me investigate why my fix breaks this.
The fixture is const _: () = {struct Struct $0};. So the cursor is at end of "Struct" inside the struct declaration.
Let me trace this with my fix. When we have const _: () = {struct Struct $0};, there's no macro call, so the recursion base case should trigger normally.
Actually, wait. Let me re-check my fix. The is_inside_macro_call_args function might have issues:
Assistant
Hmm, my function should work correctly for the struct Struct $0 case (no macro call ancestors, returns false). So the recursion base case should trigger.
Wait, let me think. The original is_inside_macro_call checks:
Any ancestor is a MacroCall → true
Any ancestor is an Item that's a macro call (like #[attr] item) → true
Otherwise → false
My fix is_inside_macro_call_args checks:
Any ancestor is a MacroCall, AND the token is inside its token_tree → true
Any ancestor is a MacroCall, AND the token is NOT inside its token_tree → false (stops at first MacroCall ancestor)
Otherwise (no MacroCall ancestor) → false
The key difference is the last case. In the original, if there's an Item ancestor that's a macro call, it returns true. In my fix, it doesn't check that.
Wait, but that's the same as returning false (not inside args). So my fix should be a SUPERSET of the original (more permissive).
Assistant
Confirmed that my fix breaks this test. Let me revert the test and investigate:
Assistant
Let me check what the test expects. kw where is a keyword completion. Let me check what the actual logic is:
Assistant
So where is completed when we're inside an Item. Let me check where it's called from:
Assistant
So complete_for_and_where is called for PathKind::Item or NameRefKind::Keyword. Let me check the NameRefKind::Keyword branch:
Assistant
OK, so inbetween_body_and_decl_check checks if the previous sibling is an Item without a body. This is used to determine if we're between the declaration and the body of an item.
Looking at this, this function is checking if the previous sibling is an Item (like struct Struct without {...}). If yes, return Some(item) so we can complete where keyword.
Now, let me look at the path that triggers this:
let parent = path.syntax().parent()?;
let kind = 'find_kind: {
if parent.kind() == SyntaxKind::ERROR {
if let Some(kind) = inbetween_body_and_decl_check(parent.clone()) {
return Some(make_res(NameRefKind::Keyword(kind)));
}
This is checking if the path's parent is an ERROR node. If yes, check if we're between body and decl.
Assistant
So the name_like is a NameRef with parent kind PATH_SEGMENT. Now let me check what classify_name_ref returns:
Assistant
So classify_name_ref returned None (kind is missing). This means it's failing. Let me look at what's happening. The NameRef is Struct. Let me see what the path is.
Let me look at the path:
Assistant
Assistant
OK so the test is using check_no_kw which expects kw where. The actual result is empty. Let me trace what classify_name_ref returns.
Let me check what's happening with my fix. Actually, the test is failing because classify_name_ref returns None. Let me look at why.
Actually, wait. The speculative file is const _: () = {struct Struct raCompletionMarker};. The NameRef is raCompletionMarker. The parent of NameRef is PATH_SEGMENT. The parent of PATH_SEGMENT is PATH.
So the path is Struct raCompletionMarker. This is a 2-segment path.
In classify_name_ref, this would go to PathKind::Item { kind: ItemListKind::SourceFile } initially. Let me look at the analysis code:
Assistant
Let me see where classify_name_ref returns None. Let me add debug prints in classify_name_ref:
Assistant
So classify_name_ref is being called with parent kind = PATH_SEGMENT. Let me look at the logic for this case:
Assistant
OK so kind_item checks various item lists. Now let me look at where classify_name_ref actually decides what to do for PATH_SEGMENT:
Assistant
So for PATH_SEGMENT, we get the segment and continue. Let me trace more.
Assistant
So if parent.kind() == SyntaxKind::ERROR, it tries inbetween_body_and_decl_check. If that succeeds, it returns NameRefKind::Keyword(kind).
For our test case struct Struct $0, the path is Struct raCompletionMarker. Let me check the parent of this path.
Actually, with the parser error, the path might be inside an ERROR node. Let me debug:
Assistant
Interesting! So the path is raCompletionMarker (not Struct raCompletionMarker as I thought). The parent is PATH_EXPR (path expression). The grandparent is STMT_LIST.
So this is parsed as a path expression (a statement). But originally, without my fix, the parser probably parsed Struct differently.
Let me revert my fix and see what the original behavior is:
Assistant
Now let me revert my fix temporarily to see the original behavior:
Assistant
Hmm, the test was removed. Let me re-add it:
Assistant
Interesting! Without my fix, the test is also failing! So this test was already broken before my fix. Let me check:
Assistant
Wait, the original test passes. Let me check why my test isn't passing. The test name is the same. Let me look at the difference:
The difference is check_no_kw filters out keywords! So my test is wrong because kw where IS a keyword, and check_no_kw removes all keywords. So the actual output is empty.
Let me fix the test:
Assistant
OK, with check (not check_no_kw), the test passes! The output is just kw where with a trailing newline. The expected value needs that trailing newline.
Actually, the test failed because of whitespace. Let me look at the expected format:
Looking at the diff:
[4m[31mkw where[0m
[4m[32m
[0m
So the expected is kw where and actual is kw where\n (with trailing newline). Let me check the format:
Assistant
The expected has trailing whitespace before the closing "#]]. So I need to use the format kw where\n ` with trailing spaces or newlines. Let me update:
Assistant
The test passes (this is the original test before my fix, just with a different name). Now let me restore my fix:
Assistant
Hmm, this is messy. Let me start fresh:
Assistant
Now let me re-apply my fix to the analysis.rs:
Assistant
All 732 tests pass. Now let me add the test for the issue:
Assistant
Test passes. Now let me run all tests to make sure nothing is broken:
Assistant
All 733 tests pass. Let me also run more tests to ensure nothing else is broken:
Assistant
All tests pass. Now let me also verify the fix is correct and clean by reviewing the changes:
Assistant
Assistant
All tests pass. Let me also think about another edge case. What about attribute macros?
For example, #[derive($0)] struct S {}. The cursor is inside #[derive(...)] which is an attribute macro.
With the original code, would return true (the token is inside the attribute, which is treated as a macro call by ).
Assistant
OK so derive tests use check and they work. Let me make sure my fix doesn't break them:
Assistant
Good, all derive tests pass.
Now let me also think about another potential issue. The is_inside_macro_call function in semantics.rs also checks for items that have been transformed to macro calls (like attributes). My fix doesn't check this case. Let me think if this is a problem.
Looking at the flow:
expand is called first.
expand tries to expand attributes and macros.
If succeeds, we use its result.
Assistant
All 733 tests pass. Let me also run ide tests:
Assistant
All 1304 tests pass.
Let me also think about whether there are other places where the fix should be applied. Let me look at is_inside_macro_call in semantics.rs:
Assistant
is_inside_macro_call is also used in ide-db/src/search.rs. We should NOT change this since it's a different use case (searching for references). Let me leave it as is.
Now let me also make sure my fix is well documented. Let me review the changes:
Assistant
Let me think about this once more. There's one thing I'm unsure about. Let me also test with the "naked macro call path" case:
fn main() { foo!$0 } where foo is a regular macro. Let me check if this works:
Assistant
Good, so when we type foo$0!() where foo is undefined, we get fn main() and u32 as completions. That's because the parser sees foo$0!() as a macro call (with foo as the path) and tries to complete the path. Since foo doesn't exist, we get the available items.
Let me remove this debug test:
Assistant
Now let me think about another edge case: what if the user types $0!() (just the bang and parens)?
Assistant
OK, so when we have $0!(), the parser still allows it and we get completions. Good.
Let me remove this test:
Assistant
Now let me think about another case. What about completing in a path like crate::foo$0 where foo is a sub-module?
Assistant
Let me remove this test too:
Assistant
Now let me also test a case where the macro expansion has a :::
Assistant
Now let me verify the final state of my fix:
Assistant
Let me clean up the extra newlines:
Assistant
Now let me also run the test again to make sure everything is working:
Assistant
All 733 tests pass.
Let me also run the related tests for hir-def and hir to ensure nothing is broken:
Assistant
All tests pass. Let me also run the ide-completion integration tests once more:
Assistant
Now let me think about the test. The test uses check_no_kw, but looking at it more carefully, I wonder if we should test more scenarios. Let me think about what behavior the user expects.
In the issue, the user wants to complete bar to a macro name. The expected behavior is to get macro completions.
Looking at the result:
fn main() fn()
ma bar macro_rules! bar
ma foo macro_rules! foo
bt u32 u32
This includes:
fn main() - the function (this is actually noise from process_all_names)
ma bar macro_rules! bar - the bar macro
ma foo macro_rules! foo - the foo macro
bt u32 - the u32 builtin type
These are appropriate completions for a path expression context. The macros are the most important ones.
Now let me also check if there's a similar issue with attributes. Let me try a similar pattern with attributes:
Assistant
When we have foo!(bar$0) where foo is ($m:ident) => { #[$m] struct S; }, after expansion we get #[bar] struct S; with the cursor at bar. We get attribute completions. This works correctly!
Let me remove this test:
Assistant
Now let me also test the case where the macro expansion has the path not at the start:
Assistant
Excellent! This test demonstrates that the fix works for qualified paths too. We get:
fn main()
ma baz - the baz macro
md foo:: - the foo module
bt u32 - the u32 builtin type
These are all appropriate path expression completions. We can see that the completion system is finding foo::bar as a possible completion.
Let me remove this test:
Assistant
Now let me verify the final state:
Assistant
Let me clean up the trailing whitespace:
Assistant
Let me run the test again:
Assistant
Let me also run all the tests one more time to make sure everything passes:
Assistant
All tests pass. Let me also run the hir tests:
Assistant
Assistant
Good, this test still passes.
Let me also check the empty_derive test:
Assistant
All tests pass.
Let me also verify my fix using the issue's exact test case one more time:
Assistant
Test passes. Let me also verify the final state of the diff:
Assistant
The diff is clean. Now let me think once more about the fix.
The issue is in the recursion base case of expand_maybe_stop. The function uses is_inside_macro_call to determine when to stop expanding. The original check is too strict - it considers the cursor "inside a macro call" even when the cursor is at the macro call's path.
Assistant
All 733 tests pass.
Let me also check the fix once more. The change to is_inside_macro_call in semantics.rs - I didn't change it. Let me verify:
Assistant
Assistant
The doc comment is good. Let me also double-check that the implementation is correct.
Looking at the function:
It iterates through parent ancestors.
For each MacroCall ancestor, it checks if the token is inside the token_tree.
If the token is inside the token_tree, return true (we're inside the macro args).
If the token is not inside the token_tree (but the macro_call exists), return false (we're at the path).
Assistant
All tests pass.
Now let me think about the checklist items from the issue:
Checklist Analysis
1. If an error was reported in the issue description, I have successfully reproduced it.
YES: I successfully reproduced the issue. The test case foo!(bar$0) was returning no completions before my fix. I added a test issue_macro_path_completion that demonstrates this.
2. If an error was reported in the issue description, I have confirmed that my fix resolves the error.
YES: After my fix, the test passes with the expected completions (fn main(), ma bar macro_rules! bar, ma foo macro_rules! foo, bt u32).
3. I have thought about edge cases and made sure my fix handles them as well.
YES: I considered several edge cases:
Tokens inside #[derive(...)] attributes (these are handled by first, and my fix doesn't affect them).
Assistant
No failures.
Let me also check that the test for the issue is properly named and follows the conventions:
Assistant
The test looks good. It uses check_no_kw (without keywords) and tests the exact scenario from the issue.
Let me also check the final state once more:
Assistant
The fix is minimal:
25 line additions/changes in analysis.rs (the fix + helper function + comments).
21 line additions in tests/item.rs (the test + import for check_no_kw).
Let me also verify by running the complete test suite one more time:
Assistant
All 733 tests pass.
Now let me think about whether my fix might have any unintended consequences. Let me look at the expand_maybe_stop function once more:
Assistant
The fix looks good. The comment in the code explains the rationale clearly.
Now let me also consider: should I run the broader tests in the workspace?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is the recursion. Let me see why expand_maybe_stop is returning None now:
The new_offset is 0 in bar!(), so the cursor is at the start of bar. But after expansion, bar becomes a NameRef in a path. Let me trace what happens in expand_maybe_stop with these inputs:
original_file = bar!() (the expansion result)
speculative_file = barraCompletionMarker!() (the speculative expansion result)
original_offset = 0 (start of bar in actual expansion)
fake_ident_token = barraCompletionMarker
Now, looking at expand_maybe_stop:
It calls expand(...).
expand looks for ancestor items and tries to expand their attributes.
Then it looks for token trees and tries to expand them.
The issue: After the expansion of foo, the result is bar!(). Now bar is the path of a macro call. So when we look at this position, we're inside bar!() macro call. So expand would try to expand bar!() recursively.
Now the issue is that bar!() might fail to expand speculatively, because the speculative version contains the marker. Let me see:
Looking at the macro rules:
macro_rules! bar { () => (); }
bar!() expands to (). So if we speculatively expand bar!(), we get () for the real one and something else for the fake one. But wait - the fake ident is barraCompletionMarker which is already inside bar!(). So the speculative expansion would produce barraCompletionMarker ! () -> barraCompletionMarker!() -> The macro bar only accepts (), not barraCompletionMarker!(), so the expansion fails.
This is the issue! When the cursor is in the middle of a macro path, the recursion tries to expand the macro it's currently in, but the path itself contains the fake ident token, so the expansion fails.
Let me look at the recursion:
Let me look at what other code paths handle this. Let me look at the other test that's similar:
In this test:
i!(module) where i is ($i:ident) => { $i::bar }.
After expansion: module::bar.
module is in path expression context, not inside a macro call.
So is_inside_macro_call returns false.
OK, the issue is clear. Now let me understand what the right fix is. We need to handle the case where the cursor lands at the path of a macro call.
Let me think about this. When bar$0!() is the expansion, the cursor is at bar which is the path of the macro call. In this case:
The position is at the start of a path/macro call.
We should treat this as if the position is NOT inside the macro call's arguments.
Let me look at the existing is_inside_macro_call to understand what should be the correct semantic. Looking at the original file (before expansion):
The original token is bar inside foo!(bar). The token's parent is the macro call foo!(bar). So is_inside_macro_call(original bar) returns true.
But after expansion, the token bar (in bar!()) is the path of a NEW macro call. We want to be able to complete this path.
I think the issue is that we should not be looking at the expanded file's macro call, but rather check if the cursor is INSIDE a macro call's arguments. Let me look at how to detect this:
Actually, looking more carefully at the recursion base case:
if token_at_offset_ignore_whitespace(&original_file.value, original_offset + relative_offset)
.is_some_and(|original_token| {
!sema.is_inside_macro_call(original_file.with_value(&original_token))
})
This uses original_file which is the file we're checking. The recursion tries expand first, then if that fails, checks if the original (non-expanded) token is inside a macro call. If not, we use this file as the base.
In our case:
First call: original_file = original Rust file, speculative_file = speculative Rust file.
expand succeeds and produces expansion bar!() for actual and barraCompletionMarker!() for speculative.
Now we recurse with original_file = bar!() actual expansion, speculative_file = barraCompletionMarker!() speculative expansion.
expand is called recursively:
It looks at the cursor position (offset 0 + relative_offset 3 = 3 in bar!()).
At offset 3, we have bar which is in the path of bar!().
It tries to expand bar!() which fails because of the fake ident in the path.
Returns None.
Then we check is_inside_macro_call for the actual expansion bar!(). Since bar is inside bar!() macro call, it returns true.
So we return None.
The fix should be: even if the cursor is technically inside a macro call, if the cursor is at the macro call's path (not its arguments), we should treat it as if we're not inside the macro call.
Actually wait - looking again at the recursion logic. The check is_inside_macro_call(original_file.with_value(&original_token)) checks if the original (non-speculative) file's token at the position is inside a macro call. The intent is: "if this is a top-level position (not inside a macro), we can stop."
But there's a subtle issue. When bar is the path of bar!(), the token bar IS inside the macro call bar!(). So is_inside_macro_call returns true.
The intent of the check was to avoid suggesting completions inside the macro call's arguments. But if the cursor is at the path of a macro call, that's OK - we want to complete the macro name.
Let me think about the fix differently. The issue is that after the first expansion, bar!() is a new macro call that we're now inside. The recursion tries to expand this, but it shouldn't because the cursor is in the path of this macro call, not its arguments.
Maybe we need to check if the cursor is inside the macro call's arguments (specifically the token_tree) vs the macro call's path.
Let me check the difference. When the cursor is at the path of a macro call, what does the syntax tree look like?
In bar!():
The bar is the path part of ast::MacroCall.
The () is the token tree part of ast::MacroCall.
So if we check whether the cursor is inside the token tree of a macro call, we can distinguish "inside the arguments" from "in the path".
Let me look at what kind of ancestor the cursor's token has:
bar!()
The token bar (path of bar!()) is a NameRef directly inside MacroCall -> Path. The token tree () is inside MacroCall -> TokenTree.
So we want: if the token is in a Path of a MacroCall (i.e., at the macro path), don't consider it "inside" the macro call.
Let me revert my debug patches and write a cleaner fix:
The intent is: if the current state is "stable" (not inside a macro call), use it as the base for completion.
The issue is that when we expand foo! and get bar!(), the token bar is technically inside a macro call (its own bar!() macro call). So is_inside_macro_call returns true, and we don't use this as the base.
But this is wrong! We should still use this as the base because:
The cursor is at the path of bar!(), not in its arguments.
The expansion already succeeded.
The path is just a regular identifier - we want to complete it as if it were a regular identifier.
Let me think about a different approach. What if we modify is_inside_macro_call to not consider the macro call's path as "inside"? Or, what if we modify the recursion check to be more lenient?
Actually, the simplest fix might be: when the recursive expand fails AND the cursor is at the path of a macro call, we should still use this as the base.
So token_at_offset_ignore_whitespace(&original_file.value, original_offset + relative_offset) gets the token at 0 + 3 = 3 in bar!(). Position 3 is the ! token (since bar is 3 chars).
Hmm wait, let me check the relative_offset calculation:
relative_offset
Original file: cursor at position X (after bar)
Speculative file: barraCompletionMarker, so fake_ident_token = barraCompletionMarker, starts at X
relative_offset = X - X = 0
So when we expand foo!, the relative_offset is 0 (the cursor is right after bar, which is the start of barraCompletionMarker).
After expansion, the new_offset is 0 in bar!() (the actual expansion). The relative_offset is 0. So new_offset + relative_offset = 0. The token at offset 0 in bar!() is bar. Now we call expand_maybe_stop again.
In the recursive expand_maybe_stop:
original_offset = 0
relative_offset = 0
token_at_offset_ignore_whitespace(&bar!(), 0 + 0) = bar token
sema.is_inside_macro_call(bar) = true (because bar is inside bar!())
So the base case fails.
Now let me think about the right fix. I think we should check if the cursor is at the macro call's path, not just inside the macro call.
Let me think about another approach. The expansion result is bar!() and we have bar as a name ref. We want to complete bar as a path.
What if we modify the base case check to also accept being inside a macro call's path? Let me think...
Actually, let me think about what is_inside_macro_call checks. It checks if the token is inside any MacroCall ancestor. In our case, bar IS inside bar!() MacroCall.
But the actual macro call (the original one that we're expanding) is foo!(bar). After expansion, we have bar!() which is a NEW macro call (not the original).
The intent of is_inside_macro_call was to check if the cursor is inside the arguments of the original macro. But after expansion, we're now in a position that's inside a new macro call.
Actually, I think the right fix is more subtle. Let me look at what happens with other types of macros:
Case 1: foo!(f$0) where foo is ($expr:expr) => { ... }.
Original: foo!(f). The cursor is inside the macro call foo!(f).
After expansion: ... (whatever the macro expands to).
In the expansion, the cursor is NOT inside any macro call.
Case 2: foo!(bar$0) where foo is ($i:ident) => { $i!() }.
Original: foo!(bar). The cursor is inside the macro call foo!(bar).
After expansion: bar!(). The cursor is at the path of a new macro call bar!().
In the expansion, the cursor IS inside a new macro call (the bar!()).
The difference: in case 2, the cursor is at the macro path (not the arguments). We want to treat this differently.
Let me write a helper function to check if the cursor is at the path of a macro call:
is_inside_macro_call
Let me approach this differently. Let me look at what the analysis code does with the result:
After expand_maybe_stop, we get an ExpansionResult. The original_file is the base file (either original or after expansion). The original_offset is the cursor position.
The analyze function then processes this. It calls find_node_at_offset to find what we're completing.
If we look at the issue case after a successful expansion:
original_file = bar!() (the actual expansion)
original_offset = 0
The cursor is at position 0 in bar!(), which is bar.
Now in analyze:
find_node_at_offset(&bar!(), 0) should find the NameRefbar.
Let me trace what would happen if we returned Some(ExpansionResult) in the recursion base case. The cursor position would be at bar in bar!(), and find_node_at_offset should find it.
So the fix is to make the recursion base case accept this case. Let me modify the check:
Here $i is replaced by module, and the result is module::bar. This is module as a path. But module::bar is a path expression context.
So when the expansion results in a path expression, it's handled by make_path_kind_expr. That's the path completion logic for expressions.
But in our case, the expansion is bar!() which is a macro call expression. The cursor is at the path of this macro call. We want to complete the path.
Let me look at what the test output shows. We have ma bar macro_rules! bar and ma foo macro_rules! foo, which is correct! So the path is being completed.
But we also have keywords like if, for, etc. which are inappropriate. These are keyword completions for expressions. Let me check what part of the code is adding these.
Actually wait, looking at this more carefully:
fn main() - the fn keyword
ma bar, ma foo - macros (correct!)
bt u32 - builtin type
kw const, kw crate::, kw false, kw for, kw if, kw if let, kw loop, kw match, kw return, kw self::, kw true, kw unsafe, kw while, kw while let
These look like the standard expression completions. The keywords like if, for, loop, match, etc. are typically valid in expression context.
But wait - some keywords like if, match, loop, for, while shouldn't be in a path context. We want to complete the path, not suggest keywords.
Hmm, let me check the expected output of similar tests:
Now let me look at the expected output. Looking at the existing test completes_qualified_macros:
fn main() { let _ = crate::$0 }
This expects:
fn main() fn()
ma foo!(…) macro_rules! foo
Just the function and the macro. No keywords like if, for, etc.
But in our case, we got:
fn main() fn()
ma bar macro_rules! bar
ma foo macro_rules! foo
bt u32 u32
kw const
kw crate::
kw false
kw for
kw if
kw if let
kw loop
kw match
...
The reason for the extra keywords is that the cursor position is being treated as an expression, not a path. Let me see what context the cursor is in.
Actually wait - looking at the result:
kw for - this is a keyword
kw if - this is a keyword
These are keywords for expr_ctx. So our cursor is being treated as an expression context, not a path context.
Let me check why. The path bar!() is a MacroExpr (since !() is the macro call syntax). The cursor is at bar which is the path of the macro call.
When kind_macro_call is called with the MacroExpr parent, it calls make_path_kind_expr. This makes the path context an expression.
But we want to complete the path of the macro call. Let me check what's happening.
Actually, looking at this more carefully, this is the EXPECTED behavior. In Rust, bar!() is a macro call expression. The bar part is the macro name. When we type bar, we're completing a path expression.
Let me look at the existing test to understand:
fn main() { let _ = crate::$0 }:
Cursor is at $0 after :: in crate::.
This is a path expression: crate::something.
Expected: just fn main() and ma foo!(…).
Wait, that's strange. The expected output has fn main() even though we're completing a path expression. Let me check what crate:: is.
Actually, crate:: is an absolute path. Let me look at the test output format. The fn main() is the function main itself. Let me re-read:
fn main() fn()
ma foo!(…) macro_rules! foo
So fn main() fn() means "function main() returning fn() (unit)" - that's the main function. And ma foo!(…) macro_rules! foo is the macro foo with the ! after it.
OK so for the crate::$0 case, the result is just the fn main() and the macro foo. This is a clean path completion.
For our case bar$0!():
Result has fn main(), macros bar, foo, builtin u32, and lots of keywords.
The keywords suggest that we're being treated as an expression context. Let me check what's happening.
Actually wait. Let me check the position again. In our case:
Original: foo!(bar$0)
Speculative: foo!(barraCompletionMarker)
Expansion of foo: bar!() for actual, barraCompletionMarker!() for speculative
The cursor is at the start of barraCompletionMarker in the speculative file.
So in the speculative file, the cursor is at the start of barraCompletionMarker in barraCompletionMarker!(). This is the path of the macro call. So it should be a path completion.
But our result shows lots of keyword completions. Let me see why.
Actually, I think the keyword completions are part of the expression context. When we're completing a path expression, we get keyword suggestions like if, for, etc. that could be used as expressions.
Wait, but the existing test for crate::$0 doesn't have these keywords. Why is that different?
Let me look more carefully. The crate::$0 test uses crate:: (with ::), while our case is just bar (no ::). Let me see if there's a difference.
Let me check what happens with my fix. The original token after cursor is... well, the cursor is at end of "Struct". Let me trace.
Actually, this is the where keyword completion for type bounds. Let me look at this more carefully.
Wait - the test is check_in_stmt_list(r"struct Struct $0", ...). This is struct Struct (with trailing space) + $0. So the cursor is right after Struct. The expected is just kw where.
The completion is for adding a where clause after a struct definition. Let me look at where this is handled.
Actually, I think this might be related to my fix. The struct definition ends, and the cursor is in a position where we expect to be able to add where clause.
Let me investigate the change I made:
Wait, my fix is in expand_maybe_stop. Let me check if it's also affecting struct Struct $0.
The test case:
const _: () = {struct Struct $0};
This isn't related to macros at all! So my fix should not affect it. Let me investigate.
Actually, looking at the test setup, check_in_stmt_list(r"struct Struct $0", ...). So ra_fixture is struct Struct $0. Then it's wrapped in const _: () = {{struct Struct $0};. The cursor is at the end of "Struct".
The expected output is kw where. But with my fix, we get empty.
Let me check what's happening. Hmm, my fix replaces is_inside_macro_call with is_inside_macro_call_args. Let me see if my fix has any side effects on non-macro cases.
Wait, my fix only changes the check inside expand_maybe_stop. The check is:
For non-macro cases (no MacroCall ancestor), both return false, so the ! makes them both return true. So the recursion base case should trigger in both cases for non-macro cases.
Hmm but there's a difference. is_inside_macro_call returns true if there's an ast::Item::cast(ancestor) ancestor that has a macro call attached. My function only checks MacroCall ancestors.
Wait, let me re-read the original is_inside_macro_call:
So it checks if any ancestor is a MacroCall OR if any ancestor is an Item that's been converted to a macro call (via attribute).
My fix only checks if the token is inside the token_tree of a MacroCall. So if the token is at the path of a MacroCall, my fix says "not inside args" (returns false). But the original is_inside_macro_call says "inside macro call" (returns true).
For the struct Struct $0 case, there's no macro call involved. Let me check if is_inside_macro_call returns true for this case.
Actually wait, the test fixture is:
const _: () = {{struct Struct $0};
Hmm, the wrap is const _: () = {<fixture>}; where fixture is struct Struct $0. So:
const _: () = {struct Struct $0};
So the cursor is at end of "Struct". The token is "Struct" (the name).
Let me check if this token is "inside a macro call" in any sense. Since there's no macro call, is_inside_macro_call should return false.
But wait - this test is checking the where keyword completion. The expected behavior is kw where only. Let me check what the test is doing.
Looking at the test more carefully, it's checking that where keyword is suggested. This is likely handled by some other logic. Let me look at where the where keyword is added.
Let me re-check. For the recursion base case:
Original: triggers if NOT inside macro call
My fix: triggers if NOT inside macro call args (which is more permissive)
So my fix is more permissive. It should not break the original tests because the only change is that some cases that previously failed now succeed.
But wait, the test completes_where_in_stmt_list is now failing because we're returning empty. Let me investigate more.
Maybe my fix causes a different code path to be taken. Let me add debug prints to understand what's happening for this test.
Let me look at the test fixture: const _: () = {struct Struct $0};. The cursor is at the end of "Struct". The "Struct" is the name of the struct.
Looking at the syntax tree, after struct Struct, there's no body yet. The parser might be in an ERROR state. Let me look at how this case is handled.
The cursor is at end of Struct. We need to identify what kind of completion to perform. The path is Struct (the struct name).
When the parser encounters struct Struct without a body, the AST has an ERROR node containing the incomplete struct definition. The NameRef Struct has its parent as a Path, which has its parent as the ERROR node (or Struct without body).
Now, looking at this test, the expected output is kw where. This is handled by the NameRefKind::Keyword branch.
So the analysis should return NameRefKind::Keyword(item) where item is the struct.
Let me trace why my fix breaks this.
Let me add debug prints:
OK so the speculative file is const _: () = {struct Struct raCompletionMarker};. The cursor is at position 29+something (the end of Struct). The raCompletionMarker is at position 29..47.
Wait, the test fixture is const _: () = {struct Struct $0};. The raCompletionMarker is inserted at position 29. Let me check the syntax tree:
The text is const _: () = {struct Struct raCompletionMarker};. Length is around 47. The raCompletionMarker is at 29..47. That's 18 characters for raCompletionMarker (correct: r-a-C-o-m-p-l-e-t-i-o-n-M-a-r-k-e-r = 18 chars).
Now Struct ends at position 28 (before the space). The cursor $0 is at position 29.
Wait, the raCompletionMarker is at 29..47 but Struct is at... let me count: const _: () = {struct Struct - that's const_:=()={struct_Struct_ which has spaces. Let me count:
c = 0
o = 1
n = 2
s = 3
t = 4
= 5
_ = 6
: = 7
= 8
( = 9
) = 10
= 11
= = 12
= 13
{ = 14
s = 15
t = 16
r = 17
u = 18
c = 19
t = 20
= 21
S = 22
t = 23
r = 24
u = 25
c = 26
t = 27
= 28
r = 29 (start of raCompletionMarker)
So position 29 is right after the space following Struct. So the cursor is between the space and the start of Struct... wait no. Let me re-count.
Actually, the test fixture is const _: () = {struct Struct $0};. After expansion with the completion marker, we get const _: () = {struct Struct raCompletionMarker};. The raCompletionMarker is inserted where $0 was.
So Struct is at positions 22-28 (inclusive). The space is at position 28. Then raCompletionMarker starts at position 29.
But wait, the syntax tree says name_ref.text = "raCompletionMarker" and its text_range is 29..47. That seems wrong. The NameRef should be on Struct if we want to complete the struct name.
Oh, I see. The cursor is at position 29 (after Struct + space). When we insert the raCompletionMarker, it goes at position 29. So raCompletionMarker is treated as the NameRef, and Struct is just text before it.
So the path/segment is Struct raCompletionMarker? That's a 2-segment path?
Hmm, that's strange. Let me check what the parser does. Maybe the parser interprets Struct raCompletionMarker as a path with two segments.
Wait, let me check the actual parsing. With cursor $0 after Struct, the parser might be expecting something else. Let me see.
Actually, looking at this more carefully, the struct Struct $0 fixture has the cursor after Struct. When we add the completion marker, the parser sees struct Struct raCompletionMarker. This is parsed as a struct with name Struct followed by some identifier... which is a syntax error in Rust.
So the NameRef raCompletionMarker is found by find_node_at_offset. This is because the cursor is at the position of the new NameRef.
But the analysis is supposed to identify the position context. When we have struct Struct and then something else, the parser is in a partial state.
Let me check what's happening with the original is_inside_macro_call. The original token is Struct (at position 22-28).
In the original code, is_inside_macro_call(original_token) would check if Struct is inside a macro call. It's not. So the recursion base case triggers.
In my fix, is_inside_macro_call_args(&original_token) would also return false (since Struct has no MacroCall ancestor). So the recursion base case should also trigger.
Wait, but the test is failing. Let me check more carefully.
Let me think about edge cases.
The fix I made:
Original check: !sema.is_inside_macro_call(original_file.with_value(&original_token))
New check: !is_inside_macro_call_args(&original_token)
The new function is_inside_macro_call_args:
Returns true if the token is inside the token_tree (arguments) of a macro call.
Returns false if no macro call ancestor, or if the token is at the path of the macro call.
Edge cases:
Token not in any macro call: returns false (same as before).
Token in the path of a macro call: returns false (NEW behavior, allows the recursion base case).
Token in the arguments (token_tree) of a macro call: returns true (same as before).
Now let me think about other edge cases. What about:
Token in a nested macro call's path?
Token in a nested macro call's arguments?
Token at the macro call path with :: (qualified path)?
For nested macro calls like foo!(bar!($0)):
The original code: is_inside_macro_call(bar) returns true (bar is inside foo!).
My code: is_inside_macro_call_args(bar) returns false (bar is in the path of foo!, not the token_tree).
Wait, is this the right behavior? Let me think. If we have foo!(bar!($0)):
We're inside foo! AND inside bar!.
The cursor is at $0 which is inside bar!'s arguments.
The expected behavior is... hmm, we want to expand bar! and complete $0 based on its expansion.
Let me check this case manually. With the original code:
is_inside_macro_call returns true, so recursion doesn't stop.
We keep trying to expand.
With my code:
is_inside_macro_call_args checks each ancestor MacroCall. The closest one is bar!. The token is inside bar!'s token_tree (since $0 is inside ()). So returns true. Recursion doesn't stop.
OK, that's fine.
Now for the issue case foo!(bar$0):
After expanding foo!, we have bar!() with cursor at bar.
The closest MacroCall ancestor is bar!(). The token bar is in the path of bar!, not the token_tree.
So is_inside_macro_call_args returns false.
The recursion base case triggers.
Now let me also think about what happens with crate::$0 (the existing test). The cursor is at the end of crate::. There's no macro call, so is_inside_macro_call_args returns false (same as before).
Let me also think about a case like foo!($0) where foo is ($i:ident) => { $i } (returns the ident):
After expanding foo!, we have just the identifier (let's say bar).
The cursor is at bar. No macro call ancestor.
is_inside_macro_call_args returns false.
Recursion base case triggers.
Now let me think about edge cases where my fix might have unintended consequences.
What if we have foo!(bar::baz$0) where the macro expands to bar::baz? Let me think:
After expanding foo!, we have bar::baz with cursor at baz.
No macro call ancestor.
is_inside_macro_call_args returns false.
Recursion base case triggers.
OK that's fine.
What about foo!(bar::baz$0) where foo is ($i:ident) => { $i::baz() }?
After expanding foo!, we have bar::baz() with cursor at baz in bar::baz.
No macro call ancestor (the () is a function call, not a macro call).
is_inside_macro_call_args returns false.
Recursion base case triggers.
OK that's fine too.
What about foo!(bar!$0) where foo is ($i:ident) => { $i!() }?
After expanding foo!, we have bar!() with cursor at the path of bar!().
The closest MacroCall ancestor is bar!(). The token is in the path.
is_inside_macro_call_args returns false.
Recursion base case triggers.
What about foo!(bar!(baz$0)) where foo is ($i:ident) => { $i!() }?
After expanding foo!, we have bar!(baz) with cursor at baz inside bar!'s arguments.
The closest MacroCall ancestor is bar!. The token is inside bar!'s token_tree.
is_inside_macro_call_args returns true.
Recursion doesn't stop.
What about foo!(bar!($0)) where foo is ($i:ident) => { $i!() }?
After expanding foo!, we have bar!() with cursor inside bar!'s arguments.
The closest MacroCall ancestor is bar!. The token is inside bar!'s token_tree.
is_inside_macro_call_args returns true.
Recursion doesn't stop.
What about foo!(bar!$0) where the cursor is in the middle of the path of a nested macro call?
Same as the issue case.
OK my fix seems correct. Let me also think about other tests that might be affected.
Let me also think about cases where the macro args include paths. For example:
foo!(bar!($0))
where foo is ($i:ident) => { $i!() }. After expanding foo!, we get bar!($0). So the cursor is at $0 inside bar!'s args.
With my fix:
is_inside_macro_call_args($0 token) checks ancestors. The closest MacroCall ancestor is bar!($0). The token is inside bar!'s token_tree. So returns true.
Recursion doesn't stop.
Good, this is the expected behavior.
Now let me also think about what happens if the user is at the path of the OUTERMOST macro call. For example:
foo!(bar$0)
But foo! itself doesn't expand further. So we have foo!(bar$0) directly.
In this case, the speculative file is foo!(barraCompletionMarker). The cursor is at barraCompletionMarker. The path is bar (since aCompletionMarker is part of the fake ident).
Wait, actually, let me re-trace. The original file is foo!(bar). The speculative file is foo!(barraCompletionMarker). The cursor is at position after bar. The fake_ident_token is barraCompletionMarker. The name_like is barraCompletionMarker (a NameRef).
The parent of NameRef is PATH_SEGMENT. The path is barraCompletionMarker. The parent of path is... let me think. In foo!(barraCompletionMarker), the path barraCompletionMarker is the macro call's path. So parent is MacroCall.
Then kind_macro_call is called, which calls make_path_kind_expr (assuming parent is MacroExpr).
So this works without expansion. The original file's token is bar (the original token, not the fake one). The original token's parent is PathSegment in bar. The path is bar. The parent is MacroCall.
Now in expand_maybe_stop:
original_offset = position of 'bar' in original file
relative_offset = 0 (cursor is at start of barraCompletionMarker after bar)
expand(...) is called.
It checks for ancestor items and tries to expand attributes.
For foo!, it tries to speculatively expand.
The speculative expansion foo!(barraCompletionMarker) should produce barraCompletionMarker!().
The result is barraCompletionMarker!().
Wait, but foo! is the macro ($i:ident) => { $i!() }. So foo!(barraCompletionMarker) should expand to barraCompletionMarker!().
In expand_maybe_stop, after a successful expansion, we recurse:
original_file = barraCompletionMarker!() (the actual expansion)
speculative_file = barraCompletionMarker!() (the speculative expansion)
Wait, but barraCompletionMarker is the marker for completion. The speculative expansion would be different.
Hmm, let me re-read the code:
fake_mapped_tokens
.into_iter()
.filter_map(|(fake_mapped_token, rank)| {
...
let result = expand_maybe_stop(
sema,
actual_expansion.clone(),
fake_expansion.clone(),
new_offset,
fake_mapped_token,
relative_offset,
)?;
Some((result, rank))
})
So it recursively calls expand_maybe_stop with actual_expansion (the actual expansion, no marker) and fake_expansion (the speculative expansion, with marker).
In our case:
actual_expansion = bar!()
fake_expansion = barraCompletionMarker!()
new_offset = 0 (start of barraCompletionMarker in the expansion)
fake_mapped_token = barraCompletionMarker
relative_offset = 0
Then expand_maybe_stop is called:
original_file = bar!()
speculative_file = barraCompletionMarker!()
original_offset = 0
fake_ident_token = barraCompletionMarker
relative_offset = 0
It calls expand(...):
Tries to expand bar!() (since cursor is at start of bar).
But bar!() is at the path, and the speculative expansion includes the marker in the path.
The speculative expansion fails (or produces garbage).
Returns None.
Then checks is_inside_macro_call_args(bar):
bar's ancestor is bar!() macro call.
bar is in the path of bar!(), not the token_tree.
Returns false.
So the recursion base case triggers. The result is the file bar!() and the offset is 0.
This is what we want! Now analyze is called with this result. find_node_at_offset(&bar!(), 0) finds the NameRef bar. Then classify_name_ref is called.
In classify_name_ref, the path is bar. The parent of path is... let me check. bar!() is a macro call, so the path bar is the macro call's path.
kind_macro_call is called with the macro call. The parent of macro call is MacroExpr. So make_path_kind_expr is called.
This makes the path an expression path. We get path expression completions.
OK so the fix is correct.
Now let me also think about other edge cases. What if there's a situation where we want to NOT trigger the recursion base case, but my fix incorrectly does?
Case: User types something at the path of a macro call, but the macro call is malformed.
For example, foo!(bar!$0) where bar is not a valid macro. The speculative expansion would fail. With my fix, the recursion base case triggers, returning the file as-is. This should be fine.
Let me also think about the case where the macro call is empty. For example, foo!($0):
Original file: foo!()
Speculative file: foo!(raCompletionMarker)
Cursor is inside foo!'s token_tree.
In this case:
expand(...) is called. It tries to expand foo! (succeeds or fails based on the macro definition).
If expand succeeds, we recursively process.
If expand fails, we check is_inside_macro_call_args($0 token).
The token $0 is inside foo!'s token_tree, so is_inside_macro_call_args returns true.
Recursion doesn't stop, returns None.
This is the same behavior as before.
OK my fix looks correct. Let me run more tests to ensure nothing is broken:
For #[derive($0)] struct S {}, the token $0 has these ancestors:
TokenTreeMeta (the derive($0))
Meta
Attr (the #[...])
Item::Struct (the struct S)
When checking ancestors:
MacroCall: none, skip.
Item::Struct: cast to Item. Then ctx.item_to_macro_call(Struct) checks if this item has been turned into a macro call. If derive(...) is processed, this returns Some. So is_inside_macro_call returns true.
With my fix, is_inside_macro_call_args only checks MacroCall ancestors. The token $0 has no MacroCall ancestor (the attribute is not a MacroCall). So my function returns false.
This means the recursion base case triggers for #[derive($0)]. But this is the original behavior for this case (since is_inside_macro_call returns true here, and the original code says "don't trigger recursion base case").
Wait, with my fix, is_inside_macro_call_args returns false, which means "trigger recursion base case". This is different from the original behavior for attribute macros.
Let me think if this is a problem. For #[derive($0)], the attribute expansion would have happened earlier (in the attribute expansion path). So we wouldn't be calling expand_maybe_stop for this case.
Actually, looking at the expand function, it tries to expand attributes first. If successful, it returns. So expand_maybe_stop would only be called for non-attribute expansion cases.
OK I think my fix is safe. Let me also test with derive:
expand
If expand fails, we fall back to expand_maybe_stop base case.
If expand failed because the attribute expansion didn't work, then the item-to-macro-call case wouldn't apply. The token wouldn't be inside an attribute macro at this point.
But wait, the original code's is_inside_macro_call also checks for items. This was used as a fallback check. With my fix, this check is gone. Is this a problem?
Let me look at the original behavior for #[derive($0)]:
expand is called first. It tries to expand attributes. For derive, it uses sema.expand_attr_macro. If this succeeds (which it should for valid derive), we get the expansion result.
If expand fails (e.g., for invalid derive), we fall back to expand_maybe_stop base case.
In the base case, is_inside_macro_call($0 token) returns true (because the struct has been transformed to a derive macro call).
So recursion doesn't stop.
With my fix:
Same as above, but is_inside_macro_call_args($0 token) returns false (no MacroCall ancestor).
Recursion base case triggers.
This is a behavioral difference. Let me check if this causes any test failures.
Actually wait, looking at the test no_completion_for_incorrect_derive:
#[derive{$0)] struct Test;
The expected output is empty. So this test passes with my fix because we either:
Get empty from somewhere (maybe the parser fails).
The recursion base case triggers and returns the file as-is.
Let me check the empty_derive test:
#[derive($0)] struct Test;
The expected output has derive helpers. So this works through the attribute expansion path.
OK I think my fix is correct. But let me verify by running more tests:
All tests pass. Let me also check that my fix correctly addresses the issue. Let me trace through the original issue scenario once more:
The completion system speculatively expands foo! to bar!() (with $i substituted by bar).
In the recursive expand_maybe_stop, the original token bar is inside the new macro call bar!().
The original code would check is_inside_macro_call which returns true (because bar is inside bar!()), and return None.
With my fix, the check is is_inside_macro_call_args, which checks if bar is inside the token_tree (arguments) of bar!(). Since bar is in the path, not the token_tree, returns false.
The recursion base case triggers, returning the file as-is.
The analysis continues, finds the NameRef bar at the path of bar!(), and treats it as a path expression completion.
This produces the expected macro completions.
Now let me think about the change to is_inside_macro_call to is_inside_macro_call_args. The original is_inside_macro_call returns true in more cases (e.g., when the token is inside an attribute macro). My fix is more permissive, only checking MacroCall ancestors.
Let me think about whether this could cause regressions in cases where the original code correctly didn't trigger the recursion base case.
Case 1: Token is in attribute macro #[derive(...)]
Original: is_inside_macro_call returns true (because the item is transformed to a macro call).
My fix: is_inside_macro_call_args returns false (no MacroCall ancestor).
Difference: my fix triggers recursion base case, original doesn't.
But wait, for attribute macros, the expand function should handle them first. Let me re-check.
Actually, looking at expand:
'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
match (
sema.expand_attr_macro(&actual_item),
...
) {
// maybe parent items have attributes, so continue walking the ancestors
(None, None) => continue 'ancestors,
// successful expansions
(Some(...), Some(...)) => { ... }
// exactly one expansion failed, inconsistent state so stop expanding completely
_ => break 'ancestors,
}
}
So expand first tries to expand attributes. If successful, returns the expansion. If expand returns None for both, it continues. If one succeeds and the other doesn't, it stops.
So the case where expand returns None is when neither attribute expansion nor macro expansion works. In this case, the original code's is_inside_macro_call check would still treat items inside attributes as "inside macro call", but my fix wouldn't.
Let me think about when this matters. If the cursor is in a position where expand failed but we're inside an attribute macro, then:
Original: returns None (no completion).
My fix: triggers recursion base case, tries to analyze the file as-is.
This could be a difference. But for the issue we're solving, this seems acceptable.
Actually, let me trace this more carefully. When is expand called with an attribute context?
If we have #[derive($0)] struct S, then:
expand is called.
It iterates over ancestor items. The first item ancestor is the Struct.
It tries to expand the attribute #[derive($0)].
sema.expand_attr_macro(Struct) and sema.speculative_expand_attr_macro(...).
If both succeed, we use the expansion.
If both fail, we continue to the next ancestor.
If one succeeds and the other fails, we break.
So if the attribute expansion works, expand returns the result. If not, we continue.
If we continue, we look at token trees and try macro expansion. The token tree derive($0) is found. The parent is Meta. We try sema.expand_derive_as_pseudo_attr_macro. If that works, we use it.
If that doesn't work either, we return None from expand. Then expand_maybe_stop falls back to the recursion base case.
In this fallback, the original code checks is_inside_macro_call, which returns true for the token inside the derive attribute. So recursion doesn't trigger.
With my fix, is_inside_macro_call_args returns false (no MacroCall ancestor). So recursion triggers.
This is a behavior change. Let me think if this matters.
Actually, looking at this more carefully, if expand couldn't expand the attribute, that means the expansion failed. Falling back to recursion base case means we use the original file as-is. This is probably fine - if the expansion failed, we can still try to complete the file as it is.
Let me think about whether this could cause regressions. Let me check the no_completion_for_incorrect_derive test:
#[derive{$0)] struct Test;
The expected output is empty. With my fix:
expand would try to expand the attribute #[derive{$0]. This might fail (due to the syntax error).
If expand fails, we fall back to recursion base case.
With my fix, is_inside_macro_call_args returns false, recursion base case triggers.
We try to analyze the file as-is.
But the parser likely failed to parse this correctly, so we might not get any NameRef to complete. The expected output is empty, which matches.
Let me run this test to verify:
My fix uses a new function is_inside_macro_call_args that only returns true if the cursor is inside the macro call's arguments (token_tree), not just at the path. This allows the recursion to stop when the cursor is at the macro call's path, enabling completion of the macro name itself.
The fix is minimal and focused:
Add a new helper function is_inside_macro_call_args that has more precise semantics.
Replace the original check is_inside_macro_call with the new check in expand_maybe_stop.
The fix doesn't change the behavior for:
Tokens not inside any macro call (returns false in both cases).
Tokens inside the arguments of a macro call (returns true in both cases).
The fix only changes behavior for:
Tokens at the path of a macro call: original returns true (incorrect), new returns false (correct).
Now let me verify my reasoning. Let me look at the test case once more:
Hmm but the cursor is at qux, which is a regular identifier, not a macro call. We want to complete qux. With the original behavior, the recursion wouldn't stop, returning None. With my fix, same behavior - returns None.
But actually, in this case, the user might expect to complete qux as a regular identifier (in expression context). So we want the recursion to trigger and use bar!(qux) as the base.
Wait, but the original is_inside_macro_call returns true here too (because qux is inside bar!). So the original behavior is also None.
OK so my fix doesn't change this case.
Let me also think about whether my fix is the best approach. Are there alternative approaches?
Alternative 1: Modify is_inside_macro_call in semantics.rs
Could add a flag or parameter to indicate "include path or not".
But this is more invasive and might break other callers.
Alternative 2: Add a check before the recursion
Could check if the cursor is at a macro path before doing the recursion.
More complex logic, harder to maintain.
Alternative 3: My current approach - new helper function
Localized change, minimal risk.
Clear semantic: only stops recursion when the cursor is at a stable position.
I think my approach is the best because it's localized and the semantics are clear.
Let me also verify the function is_inside_macro_call_args is correctly named and well-documented. Let me look at the docs:
If no MacroCall ancestor, return false (we're not in any macro call).
This is correct.
Let me also think about edge cases. What if the token is the ! token? Is the ! considered inside the path or in the token_tree?
Looking at the AST:
MacroCall
Path (path)
! (excl_token)
TokenTree (token_tree)
The ! token is a direct child of MacroCall. It's not inside Path or TokenTree. So my check would:
Find MacroCall ancestor.
Check if ! is inside Path (no) or TokenTree (no).
Return false.
Wait, the ! is between Path and TokenTree. Let me check:
Path: contains the path part (e.g., bar)
!: the exclamation mark
TokenTree: the arguments (e.g., ())
The ! is not inside Path or TokenTree. So if the cursor is at !, my check returns false.
But actually, looking at contains_range, the ! token's range might overlap with neither Path nor TokenTree. So tt_range.contains_range(!_range) would be false.
So my check would correctly return false for the ! token. The recursion base case would trigger, which is correct (we want to complete the macro name, not the !).
OK my fix is correct.
Let me also check what happens with Path itself. The Path contains multiple segments. Each segment has a NameRef. The Path's range is the union of all segments.
If the cursor is at a NameRef inside a Path inside a MacroCall:
Find MacroCall ancestor.
Check if the NameRef's range is inside the Path (it is, since Path contains the NameRef).
But we check TokenTree, not Path. The NameRef is NOT inside the TokenTree.
Return false.
Correct.
What if the cursor is at a token in the Path that's also in the TokenTree? That can't happen since Path and TokenTree are separate AST nodes.
OK my fix is correct.
Let me run all the tests once more to confirm:
expand
Tokens at the path of nested macro calls (handled correctly).
Tokens at the ! token of a macro call (handled correctly).
Tokens inside the arguments of nested macro calls (returns true correctly).
Multiple macro calls with various nesting levels (handled correctly).
4. I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
YES: I ran all the tests in ide-completion (733 tests), ide (1304 tests), hir-def (481 tests), and hir-expand (33 tests). All pass.
Let me also do one more check to make sure I haven't introduced any issues: