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
The issue is about not being able to complete macro paths in macro invocations. Let me understand the problem:
The $0 represents the cursor position. So the user is inside a macro invocation foo!() and trying to type bar to complete the macro path. The issue is that rust-analyzer doesn't provide completion for bar (which is a macro) inside the foo!() invocation.
Let me first explore the repository structure to understand how it's organized and find the relevant code for completions.
Assistant
This is the rust-analyzer repository. Let me look for the completion-related code, since the issue is about completing macro paths.
Assistant
Let me look for macro-related completions. The issue is about completing a macro name inside another macro invocation.
Assistant
Let me search for existing tests related to macro completion and understand how completions work:
Assistant
Let me look at the expression tests and specifically how path completions work inside macro invocations:
Assistant
Let me escape the exclamation mark properly.
Assistant
Let me look at the test around line 807 for in_macro_expr_frag:
Assistant
Now let me look at the test around line 1185 which seems related to ident fragment specifiers:
Assistant
I need to understand how the completion context is determined for macro invocations. Let me look at the context module and specifically how macro call arguments are handled.
Assistant
Let me look at the analysis module to understand how macro invocations are analyzed:
Assistant
I need to understand how the completion context is determined. Let me search for how macro calls are handled in the analysis.
Assistant
Let me look at the kind_macro_call function and surrounding context:
Assistant
Let me understand how the macro call path is expanded and how completions are determined. The issue is that when we're inside a macro call like foo!(bar$0), the completion for bar should be available. Let me search for where completions are collected.
Assistant
I need to understand the flow of how completions work for macro invocations. When the user types foo!(bar$0), the cursor is inside a token tree of a macro call. The completion system needs to recognize that:
We're inside a macro call argument
The macro foo expects an ident fragment
The completion should include macro names like bar
Let me look at how token trees and macro calls are handled.
Assistant
I need to look at how the completion context handles being inside a token tree without being able to expand. Let me look at the part where it determines what to do when the expansion fails:
Assistant
Now I see how the analysis works. When the cursor is inside a token tree (macro call arguments), if the macro expands successfully, it uses the expansion. But when the macro cannot expand (like when the macro expects an ident and we're trying to complete a macro path), the analysis falls through.
Let me look at the expand_and_analyze function more carefully:
Assistant
I'm continuing my analysis of how the macro expansion and completion analysis works. Let me look at how the expand function handles the case when we're inside a token tree of a macro call that expects an ident fragment. The key issue is that when the macro expansion fails, the completion context isn't properly set up to provide path completions (which would include macro names).
Assistant
Now I understand the issue better. When the macro expansion fails (returns None), the code falls back to checking if we're inside a macro call. If we're not inside a macro call, it returns the base expansion result. But if we ARE inside a macro call and the expansion fails, it returns None, which means no completions at all.
The problem is: when we have foo!(bar$0) and foo expects an $i:ident, the speculative expansion might fail or succeed, but when it succeeds, the expanded result contains a path like bar, which should allow completing macros. However, the path completion should include macro items in scope.
Let me look at how path completions are collected:
Assistant
Let me look at the expr.rs file to understand how expression path completions work:
Assistant
Now I see the core completion logic. The scope_def_applicable closure correctly filters macros to only include fn-like ones in expression position. Let me understand the issue better by looking at how the expansion and analysis handles the case when we're inside foo!(bar$0).
Assistant
I see MacroSegment is an analysis result type. Let me understand when it's triggered. Looking at the analysis code (lines 516-531):
rust
Assistant
Let me search for tests related to macro path completion inside macro calls.
Assistant
Let me fix the regex to search for tests related to ident fragment specifiers in macro calls.
Assistant
Let me look at the tests around line 1185 to see how completions work in macro invocations with ident fragments.
Assistant
Let me look at how macro completions work and search for related test cases:
Assistant
Let me look at how path resolution rendering handles macros:
Assistant
Let me now try to understand the issue better by looking at how the macro expansion and path completion interact. Let me search for tests that involve completing a macro name inside another macro call:
Assistant
Let me search for how the macro expansion handles the case where the cursor is inside a macro call argument that expects an ident.
Assistant
Let me look at the main completion entry point and understand the flow better:
Assistant
Let me trace through what happens when the cursor is inside foo!(bar$0). First, let me look at how macro expansion handles the token tree arguments:
Assistant
Assistant
Let me try to run a test to understand the issue better.
Assistant
I need to configure the Rust toolchain first before running tests.
Assistant
Now let me run the tests to understand the current behavior:
Assistant
Let me write a test to reproduce the issue and see what completions are currently offered:
Assistant
Let me write a proper test using the test utilities from the crate:
Assistant
Let me write a temporary test script to see what completions are offered in the issue scenario:
Assistant
Let me run the test to see if it reproduces the issue.
Assistant
The test module isn't being picked up. Let me add it properly:
Assistant
Let me look at how the tests module is organized and add my test to an existing file:
Assistant
Let me add a test to the expression tests file to reproduce the issue:
Assistant
Assistant
The bash command failed because there was some issue with the special characters. Let me try a different approach.
Assistant
Let me look at the existing test that works for macro completion in macro invocations and understand why:
Assistant
Assistant
Let me search for how the CompletionContext is built and how the fallback works when expand_and_analyze returns None.
Assistant
The user is asking me to continue investigating. Let me look at the CompletionContext construction and how it handles the case when expand_and_analyze returns None.
Assistant
Let me look at how expand_and_analyze is called in context.rs to understand the flow better.
Assistant
Let me look at how is_inside_macro_call is implemented to understand why the working case works:
Assistant
Let me look at the is_inside_macro_call function to understand what it checks.
Assistant
Let me look at the CompletionContext::new function to understand the fallback behavior when expand_and_analyze returns None:
Assistant
Let me look at the key function expand_maybe_stop more carefully to understand the fix needed.
Assistant
Now I understand the issue. The problem is in expand_maybe_stop function. When we're inside a macro call and the expansion fails (one succeeds but the other fails), the function returns None instead of providing completions. This causes the completion system to fall back to the original source file where the cursor is inside a token tree with no meaningful completions.
The fix is to return the base case even when inside a macro call. Let me implement this:
Assistant
The user wants me to open a file using the open command. Let me use the correct format.
Assistant
Looking at the code, I now understand the issue. In expand_maybe_stop, when expansion fails and we're inside a macro call, we return None instead of the base case. This causes the completion system to fall back to the original source file where the cursor is in a token tree with no meaningful completions.
The fix is to always return the base case in expand_maybe_stop, regardless of whether we're inside a macro call. Let me implement this fix:
Assistant
Now I understand the issue. The expand_maybe_stop function returns None when we're inside a macro call and the expansion fails. This causes the completion system to fall back to the original source file, where the cursor is inside a token tree without any meaningful completions.
The fix is to always return the base case, even when we're inside a macro call. The analysis will then use the expansion files to determine what completions to provide. Let me implement this fix:
Assistant
The user wants me to fix the issue where macro paths cannot be completed inside macro invocations. I've been analyzing the code and identified that the issue is in the expand_maybe_stop function in /rust-analyzer/crates/ide-completion/src/context/analysis.rs.
The problem is that when we're inside a macro call and the speculative expansion diverges from the real expansion (e.g., bar!() vs barraCompletionMarker!()), the function returns None instead of providing a base case for completions.
I tried to delete lines 150-169 but that approach might have been too aggressive. Let me check what the file looks like now and then make the proper fix.
Assistant
I made a mistake and removed too much. Let me fix the expand_maybe_stop function by adding back the base case without the is_inside_macro_call check.
Assistant
I made a mistake and removed too much code. Let me restore the file and make the correct change.
Assistant
I understand the issue now. Looking at expand_maybe_stop, when the expansion fails and we're inside a macro call, we return None, which causes the completion system to fall back to the source file where the cursor is in a token tree without meaningful completions.
The fix is to always return the base case, even when we're inside a macro call. This way, the analysis can use the expansion files to determine what completions to provide.
Assistant
Now I can see the issue clearly. The expand_maybe_stop function has a condition that returns None when we're inside a macro call, which prevents completions from being provided. The fix is to always return the base case, removing this condition.
Let me make the fix:
Assistant
Let me use the edit command to replace the specific lines in the file:
Assistant
I'll replace lines 150-169 with the simplified code that always returns the base case:
Assistant
Let me verify the change was applied correctly:
Assistant
The change looks good. Now let me verify the fix compiles and run the existing tests to make sure I didn't break anything:
Assistant
I see the test macro_that_ignores_completion_marker is failing. Let me get more details about what's different:
Assistant
Assistant
The previous command didn't execute properly. Let me try again to search for the ExpandResult struct definition.
Assistant
Let me look for the ExpandResult in the hir crate or related crates.
Assistant
Let me revert my previous change and implement a more targeted fix:
Assistant
Let me investigate how scope_at_offset works to understand why my fix broke the test:
Assistant
The user is continuing to work on the issue. I need to investigate the scope_at_offset function to understand why my fix broke the test, and then find a better solution.
Assistant
Assistant
The previous command didn't work because I forgot to properly format it. Let me try again to search for the function definition.
Assistant
The user wants me to continue working on the issue. Let me look at the analyze_with_offset_no_infer function to understand how it works with expansion files.
Assistant
Now I see how scope_at_offset works. It uses find_file to locate the file and then analyze_impl to get the scope. Let me understand the key insight better.
The issue is:
When we're at foo!(bar$0) and the macro expands to bar!(), we need to provide completions for the path bar
The current code returns None when inside a macro call because is_inside_macro_call returns true
But bar in bar!() is the PATH of the macro call, not inside its INPUT (token tree)
The fix should be to only return None if we're inside a macro call's INPUT (token tree), not just any part of a macro call. If we're at the path of a macro call, we should return the base case and provide path completions.
Let me implement this fix:
Assistant
Looking at the code, I can see the issue clearly now. The is_inside_macro_call check returns true for ANY token that has a MacroCall ancestor, including the PATH of the macro call. But we should only return None (continue recursion) if we're inside a macro call's INPUT (token tree), not if we're at the path.
Let me implement the fix:
Assistant
The fix was applied. Let me verify the changes look correct and then run the tests to see if they pass.
Assistant
The code has a small formatting issue with the doc comment. Let me also check if I need to add any imports. Let me verify and run the tests:
Assistant
The three key tests pass. Let me now run the full test suite for ide-completion to make sure I haven't broken anything:
Assistant
All 732 tests pass. Now let me verify that the issue is actually fixed by creating a test case that specifically tests the scenario from the issue:
Assistant
Let me run the test I added to verify that it passes with the fix.
Assistant
The test is almost passing. The actual output is slightly different from what I expected - the macro names don't have the !(…) suffix. Let me update the expected output to match the actual output:
Assistant
The test is failing because my expected output doesn't match the actual output. The actual output shows ma bar and ma foo without the !(…) suffix, while I expected ma bar!(…) and ma foo!(…). Let me update the test with the correct expected output using UPDATE_EXPECT.
Assistant
Let me see what the updated expected output looks like:
Assistant
I need to remove the test I added before submitting, as the instructions explicitly state I should not add new tests. Let me revert that change and keep only the fix.
Assistant
Let me verify that my fix is still in place and run the tests again to confirm everything works:
Assistant
Let me verify the fix is complete and run the full test suite one more time to confirm everything works.
Assistant
Let me check if there's a formatting issue with the doc comment in my fix:
Assistant
I see there's a formatting issue where my new function's doc comment got merged with the previous comment block. Let me fix that:
Assistant
Let me fix the doc comment formatting properly by viewing the current state and making a clean edit:
Assistant
I see the formatting got messed up. Let me revert the file and apply a cleaner fix:
Assistant
Let me re-apply the fix more carefully.
Assistant
Let me verify the current state of the file:
Assistant
I see the doc comment got merged with the previous one. Let me fix the formatting and then update the condition in expand_maybe_stop:
Assistant
I need to fix the formatting issue in the Rust file. The doc comment for the new function got merged with the previous comment block. Let me use a Python script to properly fix this.
Assistant
The user is continuing the task. Looking at the conversation history, I was in the middle of fixing a formatting issue in the Rust file. The doc comment for the new function is_in_token_tree_of_macro_call got merged with the previous comment block. I need to:
Fix the doc comment formatting
Update the condition in expand_maybe_stop to use the new helper function instead of sema.is_inside_macro_call
Run tests to verify the fix works
Let me check the current state of the file and apply the necessary fixes.
Assistant
I need to fix the doc comment formatting and update the condition to use the new helper function. Let me do both:
Assistant
Let me verify the fix was applied correctly and run the tests.
Assistant
The fix looks good. Let me now run all the tests to confirm everything works:
Assistant
Let me verify the fix resolves the issue by checking the diff and running a quick manual verification:
Assistant
All 732 tests pass. Let me now submit the fix.
Summary
The issue was that macro paths could not be completed inside macro invocations. For example, in:
The user couldn't complete bar inside foo!(bar$0).
Root cause
In expand_maybe_stop, when macro expansion failed (e.g., because bar is a real macro but barraCompletionMarker is not), the code checked is_inside_macro_call to decide whether to return the base case or None. The problem was that is_inside_macro_call returns true for ANY token that has a MacroCall ancestor, including tokens that are part of a macro call's PATH (like bar in bar!()). This caused the function to return instead of providing completions.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This handles the case when we're inside a token tree of a macro definition (like macro_rules! foo { ($i:ident) => { $i!() } }), specifically when looking at something like $i:.
But the issue is about completing inside a macro call like foo!(bar$0), not inside a macro definition. Let me think about this more carefully.
When we're in foo!(bar$0):
The macro foo is invoked with bar as an argument
The macro definition expects $i:ident
When expanded, it becomes $i!() which means bar!() - so bar is treated as a macro name
The problem is: when trying to complete bar, we're inside the token tree of the foo!() macro call. The completion system tries to expand the macro, but since the macro is using the ident as a macro call path, we should be able to complete macro names here.
Let me trace through what happens when we try to expand foo!(bar$0). The speculative expansion inserts the fake ident into the token tree, then tries to expand the macro. If the expansion succeeds, the cursor position should be in the expanded code where bar appears as a macro path.
The key is that when the macro expands to something like bar!(), the expanded code has a MacroCall where bar is the path. At this point, the completion system should recognize it's in a macro call position and offer macro completions. Looking at kind_macro_call, it checks if the macro call's parent is in item position, and if so, it tries to determine what kind of path we're completing based on the context around the macro call. The macro expands bar into a MacroExpr when the cursor is positioned right after it. I need to trace through the actual test cases to see what's really happening here.
Let me understand the issue better. When we're in foo!(bar$0):
The cursor is inside a token tree of the macro call foo!()
The macro foo is defined as ($i:ident) => { $i!() } - it takes an ident and uses it as a macro call
When the completion system tries to expand foo!(bar) with the fake ident, it should succeed because bar is a valid ident
After expansion, we get bar!() which is a macro call
The cursor should map to the position of bar in bar!()
At that position, we should be able to complete path elements including macros
Let me trace through what happens when the expansion fails. Looking at the code:
rust
match (
sema.expand_macro_call(&actual_macro_call),
sema.speculative_expand_macro_call(&actual_macro_call, &speculative_args, fake_ident_token),
) {
// successful expansions
(Some(actual_expansion), Some((fake_expansion, fake_mapped_tokens))) => {
// ...
}
// at least one expansion failed, we won't have anything to expand from this point
// onwards so break out
_ => None,
}
So if either expansion fails, it returns None, which then falls back to expand_maybe_stop. In expand_maybe_stop:
rust
fn expand_maybe_stop(...) -> Option<ExpansionResult> {
if let result @ Some(_) = expand(...) {
return result;
}
// We can't check whether the fake expansion is inside macro call, because that requires semantic info.
// But hopefully checking just the real one should be enough.
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))
})
{
// Recursion base case.
Some(ExpansionResult { ... })
} else {
None
}
}
If the macro expansion fails and we're still inside a macro call, it returns None instead of falling back to a base case. This means when foo!(bar$0) can't be expanded, the completion system has no result to work with. I should create a test to verify this behavior.
The problem is likely that when the real macro expansion fails, the completion system doesn't handle this gracefully. In foo!(bar), if bar isn't recognized as a macro, expansion fails, but completions should still be offered at that position. I need to check if there's logic that provides completions when expansion fails, particularly around how the fake identifier token is processed.
When the speculative expansion inserts bar as a fake ident, it should succeed, but the real expansion might fail if bar isn't actually defined as a macro. The matching logic checks both expansions - if one fails, the whole thing returns None instead of attempting to provide completions. This is where the issue likely originates.
The code comment suggests that when expansion fails, there's nothing left to work with, but that's not quite right. When we're positioned inside a token tree of a macro call, we should still offer completions for valid identifiers that could be passed as arguments. I need to examine how expand_maybe_stop handles these failure cases to understand what completions should be available. Looking at the base case, if we're still inside a macro call, it returns None instead of providing completions. This seems like the core issue—when we're nested within a macro call like foo!(bar$0), we should still be able to offer completions rather than giving up entirely. The question is whether we can extract enough context to determine what completions would be appropriate at that position.
The problem gets more specific when the macro expansion itself fails. If foo!(bar) can't expand because bar isn't a recognized macro, then sema.expand_macro_call(&actual_macro_call) returns None. Meanwhile, the speculative expansion with a fake identifier might succeed, creating a mismatch where one branch has a result and the other doesn't.
When we're inside a macro call's token tree, I need to handle expansion failures differently—perhaps by analyzing what the macro expects and offering completions based on its fragment specifiers. Looking at how in_macro_expr_frag handles expression fragments, it seems the approach is to provide context-appropriate suggestions even when the macro itself can't fully expand.
The issue appears specific to ident fragments used as macro paths. I should write a test case to confirm the exact behavior and scope of the problem.
<tool_call>
<function=bash_terminal>
<parameter=command>
cd /rust-analyzer && cargo test -p ide-completion -- regression_10042 2>&1 | tail -30
</tool_call>
Let me analyze this issue more carefully. The issue is about completing macro paths inside macro invocations.
Looking at the test macro_that_ignores_completion_marker, it shows that when we have:
The user is trying to complete bar inside foo!(bar$0). This is different because:
In the working test, the macro m expands to both use $v as a macro call AND as an expression
In the issue, the macro foo expands to use $i as a macro call only: $i!()
When the cursor is at foo!(bar$0):
The completion system creates a fake file with foo!(barraCompletionMarker)
It tries to expand both the real file and fake file
The real file has foo!(bar) - which tries to expand bar!() but bar is indeed a macro
The fake file has foo!(barraCompletionMarker) - which also tries to expand
Wait, but in the issue, the user is trying to complete bar. At the point of completion:
The original file is foo!(bar) (or just foo!() if they haven't typed anything)
They want to complete bar which is a macro
When the cursor is at foo!(bar$0), the original file contains foo!(bar) and the speculative file becomes foo!(barraCompletionMarker). The completion system needs to expand the real file to determine what context bar is in—in this case, it's a macro being invoked as $i!().
The tricky part is that the macro expansion only happens if bar is actually defined as a macro. If it isn't, or if it's just an identifier in expression position, the expansion fails. Looking at the issue, the user is inside foo!(bar$0) trying to get completion for the bar identifier. The real file has foo!(bar), and the speculative version has foo!(barraCompletionMarker). When foo expands with bar, it becomes bar!(), which succeeds. When it expands with barraCompletionMarker, it becomes barraCompletionMarker!(), and this is where the issue surfaces—the completion marker ends up in the wrong position.
The fake_mapped_tokens should map the marker token from the speculative file back to the real file, so if bar becomes the macro path in the expansion, the marker should point there. The expansion succeeds and the token maps correctly, but then I need to analyze what node exists at the speculative offset to understand what's being completed.
If the marker ends up inside a MacroCall node during analysis, the kind should resolve to a path kind like PathKind::Expr, which would enable completions for macros in scope. Looking at the in_macro_expr_frag test, I can see what completions are actually available in that context.
The issue seems specific to when the ident fragment expands into a macro call position rather than an expression position. In the failing case, the macro $i expands to $i!(), placing it directly as a macro invocation, whereas the test cases show $i::bar or $v in expression contexts. This distinction in where the expanded token appears matters for what completions get offered. I should create a temporary test to verify this specific scenario works as expected.
<tool_call>
<function=bash_terminal>
<parameter=command>
cat > /tmp/test_completion.rs << 'TESTEOF'
// Add this test to expression.rs to verify the issue
#[test]
fn test_macro_path_in_ident_frag() {
// When the ident fragment expands to a macro call path,
// we should be able to complete macro names
check(
r#"
macro_rules! bar { () => (); }
macro_rules! foo { (i:ident) => { i!() }; }
fn main() {
foo!(bar$0);
}
"#,
expect![[r#"
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
kw return
kw self::
kw true
kw unsafe
kw while
kw while let
"#]],
);
}
TESTEOF
echo "Test written"
</tool_call>
I see that the test macro_that_ignores_completion_marker does show that macro completions work in some cases. The key difference is:
In the working test: m!(v$0) where m expands to helper!($v); $v - the $v is used both as a macro call AND as an expression (the block expression is $v)
In the failing case: foo!(bar$0) where foo expands to $i!() - the $i is ONLY used as a macro call path
Let me think about this more carefully. The difference is:
Working case: The expansion is { helper!($v); $v } - a block with the ident as an expression
Failing case: The expansion is $i!() - just a macro call
When the cursor is at v$0 in m!(v$0):
The macro expands to { helper!(v); v }
The cursor maps to v as an expression (PathExpr)
This gives us expression completions including macros
When the cursor is at bar$0 in foo!(bar$0):
The macro expands to bar!()
The cursor maps to bar as a path in a MacroCall
The parent of this path is the MacroCall itself
Looking at kind_macro_call, when the parent of the path is a MacroCall, it checks if the MacroCall's parent is a MacroExpr, MacroPat, or MacroType
Let me trace through what happens more carefully:
In the analysis, when we're at position bar in the expanded bar!():
We find a Path node (bar)
We call classify_name_ref which looks at the parent
If the parent is MacroExpr, it returns a PathKind::Expr
If the parent is not one of MacroExpr/MacroPat/MacroType, it returns None
Wait, but bar!() should be parsed as a MacroExpr containing a MacroCall. Let me verify this.
Actually, looking at the code more carefully:
rust
let mut kind_macro_call = |it: ast::MacroCall| {
path_ctx.has_macro_bang = it.excl_token().is_some();
let parent = it.syntax().parent()?; // <-- This is the parent of the MacroCall
if let Some(kind) = kind_item(it.syntax()) {
return Some(kind);
}
let kind = match_ast! {
match parent {
ast::MacroExpr(expr) => make_path_kind_expr(expr.into()),
ast::MacroPat(it) => PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into())},
ast::MacroType(ty) => make_path_kind_type(ty.into()),
_ => return None,
}
};
Some(kind)
};
So if bar!() expands to a MacroExpr, the parent of the MacroCall should be MacroExpr, and we should get PathKind::Expr.
Wait, the issue might be that when the expansion happens, we're looking at the speculative file where the cursor is. Let me trace through more carefully.
Actually, I think I need to understand the issue better. The problem might be:
When we're inside foo!(bar$0) and trying to complete bar
The speculative expansion creates barraCompletionMarker!() in the expanded code
At this point, the barraCompletionMarker is part of a Path inside a MacroCall
But the analysis needs to find this Path and classify it correctly
The issue might be in how the cursor position is mapped from the original file to the speculative expansion.
Let me look at the fake_mapped_tokens logic. When the macro is expanded:
Original: foo!(bar) -> expands to bar!()
Speculative: foo!(barraCompletionMarker) -> expands to barraCompletionMarker!()
The fake_mapped_tokens maps tokens from the speculative expansion to their positions in the original expansion. So barraCompletionMarker in the speculative expansion maps to bar in the original expansion.
But the cursor position in the original file is after bar (at position of $0). So the original_offset should be the position of bar in the original file foo!(bar).
Hmm, let me think about this differently. The issue might be simpler than I thought.
Actually, wait. I think I need to check what happens when the cursor is at bar$0 and the expansion succeeds.
In the original file: foo!(bar) - the macro call
In the speculative file: foo!(barraCompletionMarker) - with fake ident
Both expand:
Original expansion: bar!() - this is bar called as a macro, but bar is a macro, so it expands further to ()
Speculative expansion: barraCompletionMarker!() - this is barraCompletionMarker called as a macro, but it's not a macro, so expansion fails
Hmm, that's interesting. The speculative expansion might fail because barraCompletionMarker is not a known macro.
Let me look at the code again:
rust
match (
sema.expand_macro_call(&actual_macro_call),
sema.speculative_expand_macro_call(&actual_macro_call, &speculative_args, fake_ident_token),
) {
// successful expansions
(Some(actual_expansion), Some((fake_expansion, fake_mapped_tokens))) => {
// ... handle both expansions
}
// at least one expansion failed, we won't have anything to expand from this point
// onwards so break out
_ => None,
}
So if the actual expansion succeeds but the speculative expansion fails (or vice versa), we return None. This is the issue!
Wait, but in the case of foo!(bar$0):
The real macro call is foo!(bar) - foo takes an ident bar and expands to bar!(). This should expand successfully.
The speculative macro call is foo!(barraCompletionMarker) - foo takes an ident barraCompletionMarker and expands to barraCompletionMarker!(). This should also expand successfully because the macro foo just substitutes the ident.
The macro foo expands to $i!() which is syntactically valid regardless of what $i is. The expansion of the result (bar!() or barraCompletionMarker!()) is a separate step.
So both expansions should succeed at the foo! level. The question is whether the subsequent expansion of bar!() vs barraCompletionMarker!() affects the completion.
Looking at the code flow:
Both foo!(bar) and foo!(barraCompletionMarker) expand successfully
We get bar!() and barraCompletionMarker!() as the expansions
We then call expand_maybe_stop recursively on these expansions
In expand_maybe_stop, we try to expand bar!() and barraCompletionMarker!()
bar!() expands to () (empty)
barraCompletionMarker!() fails because it's not a known macro
At this point, the expansions are inconsistent, and we might hit the issue.
Actually, let me re-read the code more carefully:
rust
fn expand_maybe_stop(...) -> Option<ExpansionResult> {
if let result @ Some(_) = expand(...) {
return result;
}
// We can't check whether the fake expansion is inside macro call, because that requires semantic info.
// But hopefully checking just the real one should be enough.
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))
})
{
// Recursion base case.
Some(ExpansionResult { ... })
} else {
None
}
}
So if expand returns None (expansion failed), we check if we're inside a macro call:
If we're NOT inside a macro call, we return the base case
If we ARE inside a macro call, we return None
This is the bug! When we're inside a macro call and the expansion fails, we return None instead of providing completions.
In our case:
foo!(bar) expands to bar!() - we're still inside a macro call (bar!())
bar!() expands to () - we're no longer inside a macro call (the expansion is empty)
But wait, bar!() in the real file does expand...
Hmm, let me think about this more carefully. The expand function tries to expand both the real and speculative files. If one succeeds and the other fails, it returns None.
In our case:
Real: bar!() expands to () (bar is a macro)
Speculative: barraCompletionMarker!() doesn't expand (not a macro)
So the match would be:
rust
match (
sema.expand_macro_call(&bar!()), // Some(())
sema.speculative_expand_macro_call(&bar!(), ..., barrarCompletionMarker), // None
) {
(Some, Some) => // handle both
_ => None, // This case!
}
So the expand function returns None because the speculative expansion failed.
Then in expand_maybe_stop:
expand returns None
We check if we're inside a macro call in the original file
The token at the original offset is... let me think. The original offset points to somewhere in bar!(). The token there is part of the bar ident or the macro call syntax.
is_inside_macro_call returns true because we're inside bar!()
So we return None
This is the bug! When the speculative expansion fails but the real expansion succeeds, we should still provide completions based on the real expansion's context.
Wait, but that's not quite right either. The issue is more subtle. Let me trace through again.
The original file has:
rust
fn main() {
foo!(bar);
}
After expanding foo!(bar):
rust
fn main() {
bar!();
}
After expanding bar!():
rust
fn main() {
();
}
So after full expansion, the result is (). The cursor position was inside bar in the original file, which maps to... somewhere in the expanded code.
But bar!() expands to (), which doesn't contain any identifier. So the fake_mapped_tokens for bar!() expansion might not have any tokens with the completion marker.
So if none of the mapped tokens contain the completion marker, the result is None, and expand returns None.
Then in expand_maybe_stop, we check if we're inside a macro call. At this point, we're in the bar!() level, which IS a macro call. So we return None.
But wait, the actual cursor position in the original file is inside foo!(bar), not inside bar!(). The original_file at this point is the expansion of foo, which is bar!(). So is_inside_macro_call is called with a token in bar!().
Hmm, I'm getting confused with the nesting. Let me re-read the code.
Actually, I think the issue is that the completion system relies on speculative expansion to work, but when the speculative expansion diverges from the real expansion (because bar is a macro but barraCompletionMarker is not), it fails to provide completions.
Let me look at a similar case that works: in_macro_expr_frag. In this test:
Real: m!() - this expands to... nothing? Actually m!() doesn't have an expression, so it's an incomplete input
Speculative: m!(raCompletionMarker) - this expands to raCompletionMarker
Wait, but the test shows that m!($0) provides expression completions. So the real file doesn't have m!(bar), it has m!(). The cursor is right after m!(.
So the difference is:
Working case: m!($0) - cursor is at the start, no text before cursor
Failing case: foo!(bar$0) - cursor is after bar, there's text before cursor
In the working case:
Real: m!() - might fail to expand because no expression
Speculative: m!(raCompletionMarker) - expands to raCompletionMarker
Since both might fail or succeed at the macro level, the completion system handles it differently.
In the failing case:
Real: foo!(bar) - expands to bar!() which expands to ()
Speculative: foo!(barraCompletionMarker) - expands to barraCompletionMarker!() which fails to expand
The issue is that after the first level of expansion, we have different situations:
Real: bar!() - this is a macro call that expands
Speculative: barraCompletionMarker!() - this is a macro call that doesn't expand
The recursive expansion tries to expand both, but they diverge.
OK so I think I understand the issue now. The fix needs to handle the case where:
The real expansion succeeds and provides a valid context (e.g., macro path position)
The speculative expansion fails or provides a different context
In this case, we should still provide completions based on the real context.
Let me look at how the code handles this. The key is in expand_maybe_stop:
rust
fn expand_maybe_stop(...) -> Option<ExpansionResult> {
if let result @ Some(_) = expand(...) {
return result;
}
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))
})
{
// Recursion base case.
Some(ExpansionResult { ... })
} else {
None
}
}
When expand returns None and we're inside a macro call, we return None. This is where completions are lost.
But the issue is more nuanced. In the case of foo!(bar$0):
expand is called for foo!(bar) and foo!(barraCompletionMarker)
Both expand successfully to bar!() and barraCompletionMarker!()
expand_maybe_stop is called recursively on these expansions
expand is called for bar!() and barraCompletionMarker!()
bar!() expands to (), barraCompletionMarker!() doesn't expand (not a macro)
Since one succeeds and one fails, expand returns None
Back in expand_maybe_stop, we check if we're inside a macro call
We ARE inside bar!(), so we return None
The completion system has no result
The fix should be to handle the case where one expansion succeeds and the other fails. Instead of returning None, we should try to provide completions based on the expansion that succeeded.
Actually wait, let me re-read the code more carefully. In the expand function:
rust
match (
sema.expand_macro_call(&actual_macro_call),
sema.speculative_expand_macro_call(&actual_macro_call, &speculative_args, fake_ident_token),
) {
(Some(actual_expansion), Some((fake_expansion, fake_mapped_tokens))) => {
// Both succeed
// ...
fake_mapped_tokens
.into_iter()
.filter_map(|(fake_mapped_token, rank)| {
// Only consider tokens with completion marker
if !fake_mapped_token.text().contains(COMPLETION_MARKER) {
return None;
}
// ...
expand_maybe_stop(...)
})
.min_by_key(|(_, rank)| *rank)
.map(|(result, _)| result)
}
_ => None, // At least one failed
}
So the issue is in step 6: when one expansion succeeds and the other fails, expand returns None.
But actually, I think the issue might be even earlier. Let me trace through the first level of expansion:
Original file: foo!(bar)
Speculative file: foo!(barraCompletionMarker)
Both call expand_macro_call and speculative_expand_macro_call:
Then we iterate over fake_mapped_tokens and call expand_maybe_stop for each.
The fake_mapped_tokens maps barraCompletionMarker in the speculative expansion to bar in the actual expansion.
Now in expand_maybe_stop:
original_file is the actual expansion: bar!()
speculative_file is the speculative expansion: barraCompletionMarker!()
original_offset is the position of bar in the actual expansion
fake_ident_token is the barraCompletionMarker token
Then expand is called again:
sema.expand_macro_call(&bar!()) -> Some(()) (bar expands to empty)
sema.speculative_expand_macro_call(&bar!(), barraCompletionMarker!(), fake_token) -> None (barraCompletionMarker is not a macro)
One succeeds, one fails. So expand returns None.
Back in expand_maybe_stop:
expand returned None
Check if we're inside a macro call: is_inside_macro_call with the token at original_offset in original_file
The token at original_offset is bar in bar!(), which IS inside a macro call
Return None
So the completions are lost because we're inside bar!() in the expansion.
Now, what SHOULD happen? We should recognize that:
The cursor is at bar in the macro call bar!()
bar is the path of the macro call
We should complete paths (including macros) at this position
The fix should be in expand_maybe_stop. When expand fails and we're inside a macro call, instead of returning None, we should provide a result that allows completions at the current position.
But wait, there's a subtlety. The original_file is bar!() (the expansion of foo!(bar)), and the cursor is at the position of bar in this expansion. This is a generated file, not the original source file.
Actually, let me look at what happens after expand_maybe_stop returns None.
If expand returns None, the caller (expand_maybe_stop) checks if we're inside a macro call. If we're not, it returns a base case. If we are, it returns None.
So the flow is:
expand_and_analyze calls expand_maybe_stop
expand_maybe_stop calls expand
expand returns None (expansion failed)
expand_maybe_stop checks if inside macro call
If inside macro call, returns None
Back in expand_and_analyze, we get None from expand_maybe_stop
We use the fallback: ExpansionResult { original_file, speculative_file, ... }
So if expand_maybe_stop returns None, we use a fallback ExpansionResult. This fallback uses the original file (the source file) as the basis for analysis.
But the original file at this point might be the expansion of foo!, not the original source file. Let me check.
Actually, looking at the recursive call in expand_maybe_stop:
rust
let result = expand_maybe_stop(
sema,
actual_expansion.clone(), // <-- This is the expansion of foo!, which is bar!()
fake_expansion.clone(), // <-- This is the speculative expansion, barraCompletionMarker!()
new_offset,
fake_mapped_token,
relative_offset,
)?;
When expand_maybe_stop returns None, the ? propagates it up.
Then in the outer expand:
rust
fake_mapped_tokens
.into_iter()
.filter_map(|(fake_mapped_token, rank)| {
// ...
let result = expand_maybe_stop(...)?;
Some((result, rank))
})
.min_by_key(|(_, rank)| *rank)
.map(|(result, _)| result)
If all mapped tokens result in None, then the iterator produces no elements, and min_by_key returns None.
So expand returns None, and the outer expand_maybe_stop also returns None (because we're inside a macro call).
Back in expand_and_analyze:
rust
let expansion = expand_maybe_stop(...).unwrap_or(ExpansionResult { ... });
This uses the fallback with original_file.value and speculative_file from the TOP LEVEL call, not the recursive one. So it's the original source file.
So the analysis is done on the original source file! The cursor position is in foo!(bar) in the source file, and we analyze that position.
In the source file, bar is part of a token tree of a macro call. Let me look at how this is analyzed.
In analyze:
rust
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
// Handle cases where no name-like is found
let analysis = if let Some(original) = ast::String::cast(original_token.clone()) {
CompletionAnalysis::String { ... }
} else {
// Fix up trailing whitespace problem
let token = syntax::algo::skip_trivia_token(self_token.clone(), Direction::Prev)?;
let p = token.parent()?;
if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| it.kind() == SyntaxKind::TOKEN_TREE_META)
{
CompletionAnalysis::UnexpandedAttrTT { ... }
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
// Macro segment case
// ...
} else if find_node_at_offset::<ast::CfgPredicate>(...)
{
CompletionAnalysis::CfgPredicate
} else {
return None;
}
};
return Some((analysis, (None, None), QualifierCtx::default()));
};
So if no name_like is found at the speculative offset, we check if we're in a token tree. The speculative file is the source file with the fake ident inserted.
In our case, the speculative file is:
rust
fn main() {
foo!(barraCompletionMarker);
}
At the speculative offset (start of barraCompletionMarker), we should find a Name or NameRef node. Let me think about what the parser produces.
Actually, inside a token tree, identifiers are just plain IDENT tokens, not Name or NameRef nodes. So find_node_at_offset::<ast::NameLike> might return None.
If that's the case, we enter the else branch and check if we're in a token tree:
rust
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
// Check for macro segment pattern like $ident:
if let Some([_ident, colon, _name, dollar]) = fake_ident_token
.siblings_with_tokens(Direction::Prev)
.filter(|it| !it.kind().is_trivia())
.take(4)
.collect_array()
&& dollar.kind() == T![$]
&& colon.kind() == T![:]
{
CompletionAnalysis::MacroSegment
} else {
return None;
}
}
This checks if we're in a macro definition (like macro_rules! foo { ($i:ident) => { ... } }), specifically for completing fragment specifiers like $i:ident. This is not our case - we're in a macro call, not a macro definition.
So we return None and no completions are provided.
I think I understand the issue now. The fix should be to provide completions when we're in a token tree of a macro call. Specifically, we should treat this as an expression position and provide path completions.
Let me look at how we can detect that we're in a macro call's token tree and provide appropriate completions.
Actually, wait. Let me reconsider. The issue says "Cannot complete macro path in macro". The user wants to complete bar which is a macro. But bar is already typed - they're trying to get completions that include bar.
So the completions should show bar as a macro that can be used here. The problem is that no completions are shown at all.
Let me think about what completions SHOULD be shown:
bar is a macro in scope
The position foo!(bar$0) is inside a macro call argument
The argument is matched by $i:ident in the macro definition
The macro expands to $i!() - using bar as a macro call
So bar should be completable as a macro
The fix should be to recognize that we're in a position where a macro path is expected and provide macro completions.
But how do we know that a macro path is expected? We'd need to know the macro definition and how it uses the ident fragment. This is complex because we'd need to analyze the macro body.
Alternatively, we could provide more general completions when we're in a macro call's token tree. For example, we could provide all identifiers in scope that could be valid in the argument position.
Looking at the working test case in_macro_expr_frag:
The fragment specifier is $i:ident. An ident can be many things - a variable, a type, a macro, etc. We should provide all of these as completions.
But the current code doesn't handle this case because:
The expansion succeeds for the first level (foo!(bar) -> bar!())
The expansion fails for the second level (bar!() vs barraCompletionMarker!())
We return None and lose the context
I think the fix should be in expand_maybe_stop. When the expansion fails and we're inside a macro call, instead of returning None, we should:
Check if we can determine the fragment type
Provide completions appropriate for that fragment type
If we can't determine the fragment type, provide general identifier completions
Actually, let me look at a simpler fix. The issue might be that when expand returns None because one expansion fails, we should still provide completions based on the context we have.
Let me look at how the in_macro_expr_frag test works. In that case:
The cursor is at m!($0) - no text before the cursor
The expansion of m!() might fail (no expression)
But the completion system still provides expression completions
This works because the fallback ExpansionResult uses the original source file, and the cursor is at a position where an expression is expected.
In our failing case:
The cursor is at foo!(bar$0) - text before the cursor
The expansion of foo!(bar) succeeds
The recursive expansion of bar!() vs barraCompletionMarker!() fails
We return None and the fallback uses the original source file
In the original source file, the cursor is inside a token tree
No name_like is found, and we return None
The key difference is that in the working case, the first-level expansion fails, so the fallback works. In the failing case, the first-level expansion succeeds, leading to a deeper recursion that eventually fails.
I think the fix should be: when the recursive expansion fails and we're inside a macro call, we should not return None unconditionally. Instead, we should provide a result that allows the completion system to analyze the current position.
Let me look at the code in expand_maybe_stop:
rust
fn expand_maybe_stop(...) -> Option<ExpansionResult> {
if let result @ Some(_) = expand(...) {
return result;
}
// We can't check whether the fake expansion is inside macro call, because that requires semantic info.
// But hopefully checking just the real one should be enough.
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))
})
{
// Recursion base case.
Some(ExpansionResult { ... })
} else {
None
}
}
The condition is: if we're NOT inside a macro call, return the base case. Otherwise, return None.
The issue is that when we ARE inside a macro call, we still need to provide completions. The fix should be to also return the base case when we're inside a macro call.
Wait, but the comment says "We can't check whether the fake expansion is inside macro call, because that requires semantic info." This suggests that the check is there to ensure the original and speculative states are in sync. If we're inside a macro call, the speculative expansion might be different from the original, leading to incorrect completions.
But in our case, both expansions are inside a macro call - they're just at different levels. The original is inside bar!() and the speculative is inside barraCompletionMarker!(). Both are macro calls with a single-segment path.
I think the fix should be to return the base case even when inside a macro call, but make sure the analysis handles this case correctly.
Actually, let me think about this differently. The issue is that after expansion, the cursor is at a position inside a macro call path. The completion system should recognize this and provide path completions.
The current flow is:
Expand foo!(bar) -> bar!() (original) and barraCompletionMarker!() (speculative)
Try to expand bar!() and barraCompletionMarker!() again
bar!() expands to (), barraCompletionMarker!() doesn't expand
expand returns None because one expansion failed
expand_maybe_stop returns None because we're inside a macro call
Fallback uses original source file, but cursor is in a token tree where no completions are provided
The fix should be to return the base case in step 5, so that the analysis can provide completions for the position inside the macro call path.
But wait, the base case returns the ORIGINAL_FILE, which is bar!() (the expansion), not the original source file. And the cursor is at bar in bar!(), which IS a macro call path.
original_file: original_file.value - which is bar!() (the expansion at this level)
speculative_file - which is barraCompletionMarker!()
Then in analyze, we try to find a name_like at the speculative offset in the speculative file. At that position, we should find barraCompletionMarker which is part of a Path in a MacroCall.
Wait, but inside a token tree, the tokens are just raw tokens, not AST nodes. So barraCompletionMarker!() is inside a token tree, not parsed as a MacroCall with a Path.
Hmm, but the speculative file is the result of speculative_expand_macro_call, which should be a parsed syntax tree. Let me check.
Actually, looking at the signature:
rust
fn expand_maybe_stop(
sema: &Semantics<'_, RootDatabase>,
original_file: InFile<SyntaxNode>, // <-- This has file ID
speculative_file: SyntaxNode, // <-- This is just a SyntaxNode
...
) -> Option<ExpansionResult>
The original_file is InFile<SyntaxNode> (has a file ID), and speculative_file is just a SyntaxNode (no file ID).
When we return the base case:
rust
Some(ExpansionResult {
original_file: original_file.value, // <-- The SyntaxNode, stripped of InFile wrapper
speculative_file,
...
})
We strip the InFile wrapper from original_file. So original_file.value is just the SyntaxNode.
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
// ...
};
So we look for a name_like in the SPECULATIVE file at the speculative offset.
In our case, the speculative file is barraCompletionMarker!(). But this is the result of speculative expansion, which should be a parsed tree.
Wait, barraCompletionMarker!() is parsed as a MacroExpr containing a MacroCall with a Path containing barraCompletionMarker. So find_node_at_offset should find a NameRef at the position of barraCompletionMarker.
If that's the case, then analyze would classify this as a path completion context.
Let me check if speculative_expand_macro_call returns a parsed tree.
Looking at the code, sema.speculative_expand_macro_call returns Option<(SyntaxNode, Vec<(SyntaxToken, u32)>)>. The SyntaxNode is the expansion result, which should be a parsed tree.
So if we return the base case, the analysis should find the NameRef at barraCompletionMarker and classify it as a path completion.
The problem is that we DON'T return the base case - we return None because we're inside a macro call.
I think the fix is to change expand_maybe_stop to return the base case even when inside a macro call. The check is overly conservative.
Let me look at what the check is trying to prevent:
The check says: if the original token is NOT inside a macro call, return the base case. If it IS inside a macro call, return None.
The idea is: if we're inside a macro call, the expansion failed but there might be more nesting. So we return None to signal that we can't provide completions at this level.
But this is wrong for our case. We're inside bar!(), but the expansion of bar!() succeeded (it's ()). The speculative expansion of barraCompletionMarker!() failed (not a macro). The issue is that these two expansions are inconsistent, but we should still be able to provide completions for the path bar in bar!().
I think the fix should be to always return the base case when expand returns None, regardless of whether we're inside a macro call. The base case will use the current files (the expansions), and the analysis will determine what completions to provide.
Let me also check if there are any side effects of removing this check. The comment says "We can't check whether the fake expansion is inside macro call, because that requires semantic info." This suggests that the original and speculative states might diverge if we're inside a macro call. But in practice, if the expansion failed, we should use whatever context we have.
Actually, I think I need to understand this better. Let me look at the code more carefully.
The expand_maybe_stop function is called recursively. At each level:
Try to expand (expand function)
If expansion succeeds, recurse on the result
If expansion fails:
a. If NOT inside a macro call, return base case
b. If inside a macro call, return None
The reason for step 3b is: if we're inside a macro call and the expansion failed, we might be in a situation where:
The original expansion is inside a macro that needs further expansion
The speculative expansion is different
Returning a base case would give incorrect completions
But in our case, the expansion DID succeed at the foo!() level. The failure is at the bar!() level. And bar!() expands to () (empty), so there's nothing more to expand.
The issue is that the speculative expansion barraCompletionMarker!() doesn't expand. So when expand tries to expand both, one succeeds and one fails, leading to None.
Hmm, I think the fix should be in the expand function, not expand_maybe_stop. When one expansion succeeds and the other fails, we should still use the successful expansion to provide context.
Actually, let me re-read the expand function's handling of macro calls:
rust
match (
sema.expand_macro_call(&actual_macro_call),
sema.speculative_expand_macro_call(&actual_macro_call, &speculative_args, fake_ident_token),
) {
// successful expansions
(Some(actual_expansion), Some((fake_expansion, fake_mapped_tokens))) => {
// Both succeed - recurse
fake_mapped_tokens
.into_iter()
.filter_map(|(fake_mapped_token, rank)| {
// Only consider tokens with completion marker
if !fake_mapped_token.text().contains(COMPLETION_MARKER) {
return None;
}
// ...
expand_maybe_stop(
sema,
actual_expansion.clone(),
fake_expansion.clone(),
new_offset,
fake_mapped_token,
relative_offset,
)?;
Some((result, rank))
})
.min_by_key(|(_, rank)| *rank)
.map(|(result, _)| result)
}
// at least one expansion failed, we won't have anything to expand from this point
// onwards so break out
_ => None,
}
The issue is the _ => None case. When one expansion fails, we return None. But we should still try to provide completions based on the partial information we have.
I think the fix should be to handle the cases where only one expansion fails:
rust
match (
sema.expand_macro_call(&actual_macro_call),
sema.speculative_expand_macro_call(&actual_macro_call, &speculative_args, fake_ident_token),
) {
(Some(actual_expansion), Some((fake_expansion, fake_mapped_tokens))) => {
// Both succeed
// ...
}
(Some(_), None) => {
// Real expansion succeeded but speculative failed
// This happens when the real code uses a known macro but the speculative code doesn't
// We should still provide completions based on the position in the token tree
// ...
}
(None, Some(_)) => {
// Real expansion failed but speculative succeeded
// ...
}
(None, None) => {
// Both failed
None
}
}
But this is complex. Let me think of a simpler fix.
Actually, I think the simplest fix is in expand_maybe_stop. Instead of returning None when inside a macro call, we should return the base case. The base case will use the current expansion files, and the analysis will determine the appropriate completions.
The concern about original/speculative divergence is valid, but if the expansion has already failed, we're in a situation where we need to provide the best completions we can.
Let me check if this change would break any existing tests.
Actually, looking at the code again, I think the issue is specifically in this condition:
rust
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 checks if the token at the original offset is inside a macro call. In our case, the original_file is bar!() (the expansion), and the token at the offset is bar (the macro name). This IS inside a macro call (bar!()).
But the issue is: even though we're inside a macro call, the macro call's expansion has already been computed (bar!() -> ()). The speculative expansion failed because barraCompletionMarker is not a macro. So we should provide completions for the macro path.
I think the fix is to change the condition to:
If NOT inside a macro call OR if we can determine that the macro call is terminal (nothing more to expand), return the base case
Otherwise, return None
But determining if a macro call is "terminal" is complex. A simpler approach:
Always return the base case, but let the analysis handle the case where we're inside a macro call
Let me look at what happens if we return the base case. The ExpansionResult will have:
original_file: bar!() (the SyntaxNode of the expansion)
speculative_file: barraCompletionMarker!() (the SyntaxNode of the speculative expansion)
original_offset: position of bar in the original
speculative_offset: position of barraCompletionMarker in the speculative
Then analyze is called:
rust
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
// ...
};
In the speculative file barraCompletionMarker!(), at the speculative offset (start of barraCompletionMarker), we should find a NameRef node. This NameRef is part of a Path in a MacroCall.
Then classify_name_ref is called, which checks the parent of the NameRef:
And expr::complete_expr_path provides path completions including macros.
So the fix should work! Let me verify by modifying expand_maybe_stop to always return the base case.
Wait, but there might be a subtle issue. The original_file in the base case is bar!(), which is a macro expansion. The InFile wrapper has been stripped. When we call analyze, it uses original_file for some operations, like is_in_macro_matcher.
Let me check if there are any issues with using an expansion as the original_file.
Actually, looking at the code more carefully, the original_file is used in analyze for:
classify_name_ref(sema, &original_file, ...) - uses original file for context
In step 2, the original_file is used to find the corresponding node in the original file. But if the original_file is an expansion, the node might not correspond to anything in the source file.
Hmm, this is getting complicated. Let me think about this differently.
The real issue is that when expand fails because the real and speculative expansions diverge, we should still provide completions. The current code returns None and falls back to the original source file, where the cursor is in a token tree with no meaningful completions.
A better approach: instead of falling back to the original source file, we should use the last successful expansion to provide completions.
In our case:
foo!(bar) -> bar!() succeeds for both real and speculative
bar!() -> () succeeds only for real, fails for speculative
At step 2, we should recognize that the expansions have diverged and use the context from step 1's expansion.
But the current code structure doesn't support this. The expand function is recursive and doesn't preserve the context from previous levels.
Let me think of another approach. Instead of trying to fix the expansion logic, we can fix the fallback logic. When we fall back to the original source file and the cursor is in a token tree, we should provide more general completions.
Looking at the fallback handling in analyze:
rust
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
// Handle cases where no name-like is found
// ...
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
// Macro segment case
if let Some([_ident, colon, _name, dollar]) = fake_ident_token
.siblings_with_tokens(Direction::Prev)
.filter(|it| !it.kind().is_trivia())
.take(4)
.collect_array()
&& dollar.kind() == T![$]
&& colon.kind() == T![:]
{
CompletionAnalysis::MacroSegment
} else {
return None; // <-- This is the issue!
}
}
// ...
};
When we're in a token tree of a macro call (not a macro definition), we return None. This is the bug!
The fix should be: when we're in a token tree of a macro call, provide a completion context that allows path completions.
Let me look at how to create such a context. The issue is that inside a token tree, we don't have a NameLike node, so we can't classify it as a path.
One approach: when we detect we're in a token tree of a macro call (not a macro definition), create a synthetic NameRef and classify it as a path.
Actually, looking at the code more carefully, the find_node_at_offset function should find a NameLike if there's an identifier at the cursor position. Let me check what happens.
In the speculative file foo!(barraCompletionMarker), the token tree contains barraCompletionMarker. The parser might treat this as an identifier token, not a NameLike node.
Let me verify: inside a token tree, identifiers are just IDENT tokens, not wrapped in Name or NameRef AST nodes. So find_node_at_offset::<ast::NameLike> would return None.
This is the root cause of the issue. When we're inside a token tree, we can't find a NameLike node, so we can't classify the completion context.
The fix should be to handle the case where we're in a token tree of a macro call and provide path completions.
Let me look at how to do this. I think we need to add a new CompletionAnalysis variant for "token tree of a macro call" and handle it appropriately in the completion logic.
But wait, there's already CompletionAnalysis::UnexpandedAttrTT for unexpanded attributes. We could add a similar variant for unexpanded macro calls.
Actually, let me look at what completions are expected. In the issue, the user wants to complete bar which is a macro. The macro foo uses bar as a macro call path. So the completions should include macros.
I think the fix should be:
When we're in a token tree of a macro call (not a macro definition)
And we can't find a NameLike node
Provide path completions (which include macros)
Let me implement this fix.
Actually, wait. I need to reconsider. The issue might be in a different place. Let me re-trace the flow:
User has code: foo!(bar$0)
The completion system creates a speculative file: foo!(barraCompletionMarker)
expand_and_analyze is called
expand_maybe_stop is called with the original file (source) and speculative file
expand is called to expand foo!(bar) and foo!(barraCompletionMarker)
Both expand successfully to bar!() and barraCompletionMarker!()
expand_maybe_stop is called recursively on these expansions
expand is called to expand bar!() and barraCompletionMarker!()
bar!() expands to (), barraCompletionMarker!() doesn't expand (not a macro)
Since one succeeds and one fails, expand returns None
expand_maybe_stop checks if we're inside a macro call: YES
Returns None
Back in step 7's expand function: all expand_maybe_stop calls returned None
The iterator produces no elements, min_by_key returns None
Step 5's expand returns None
Back in step 4's expand_maybe_stop: checks if inside macro call
The original file at this point is the SOURCE file
The token at the offset is bar in foo!(bar) in the source file
Is bar inside a macro call? YES, it's inside foo!(...)
Returns None
Back in expand_and_analyze: uses the fallback ExpansionResult
The fallback uses original_file.value (source file) and speculative_file (source with fake ident)
analyze is called
find_node_at_offset looks for NameLike at the speculative offset
In the speculative file foo!(barraCompletionMarker), inside the token tree, there's no NameLike node
Falls into the else branch
Checks if in a token tree of a macro definition: NO (we're in a macro call, not a macro definition)
Returns
So the issue is in step 27-28. When we're in a token tree of a macro call (not a macro definition), we should provide completions, not return None.
Let me look at the code again:
rust
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
// This is for macro definitions, like macro_rules! foo { ($i:ident) => { ... } }
// Check for $ident: pattern
if let Some([_ident, colon, _name, dollar]) = fake_ident_token
.siblings_with_tokens(Direction::Prev)
.filter(|it| !it.kind().is_trivia())
.take(4)
.collect_array()
&& dollar.kind() == T![$]
&& colon.kind() == T![:]
{
CompletionAnalysis::MacroSegment
} else {
return None; // <-- This is the bug
}
}
The condition p.ancestors().any(|it| ast::Macro::can_cast(it.kind())) checks if we're inside a macro DEFINITION, not a macro call. But what if we're inside a macro call's token tree?
Actually, ast::Macro is for macro definitions (like macro_rules! or macro), not macro calls (foo!()). So the condition correctly identifies macro definitions.
But when we're in a macro call's token tree, we fall through to the next condition:
We're not in a cfg predicate either, so we return None.
The fix should be to add a case for "token tree of a macro call" and provide path completions.
But how do we detect if we're in a token tree of a macro call? We can check if the token tree's parent (or ancestor) is a MacroCall:
rust
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::MacroCall::can_cast(it.kind()))
{
// Token tree of a macro call
// Provide path completions
// ...
}
But what kind of completions should we provide? We don't know what fragment type the macro expects. We could provide all identifiers in scope, or we could try to determine the fragment type from the macro definition.
I think a reasonable approach is to provide path completions (which include macros, functions, variables, etc.). This is what the user expects.
Let me implement this fix. I'll add a new completion analysis variant for "token tree of a macro call" and handle it in the completion logic.
Wait, actually I realize there might be a simpler approach. Instead of adding a new variant, I can modify the fallback logic to create a synthetic path completion context when we're in a token tree of a macro call.
Actually, let me look at how UnexpandedAttrTT is handled:
It calls a specific completion function. For macro call token trees, I could add a similar handler.
Let me think about what completions should be provided. In the issue, the user wants to complete a macro name. But in general, the macro could expect any kind of input (ident, expr, path, etc.). Without knowing the fragment type, we should provide the most general completions.
For an ident fragment, we should provide:
Variables
Types
Functions
Macros
Other identifiers in scope
For a path fragment, we should provide path completions.
For an expr fragment, we should provide expression completions (which include macros).
I think providing expression-like completions (path completions with macros) is a reasonable default.
OK let me now implement the fix. I'll add a check in expand_maybe_stop to return the base case even when inside a macro call.
Actually wait, I just realized something. Let me re-read the code in step 18-20:
rust
// We can't check whether the fake expansion is inside macro call, because that requires semantic info.
// But hopefully checking just the real one should be enough.
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))
})
{
// Recursion base case.
Some(ExpansionResult { ... })
} else {
None
}
At step 18, original_file is the SOURCE file (from the top-level call), not the expansion. The token at the offset is bar in foo!(bar).
sema.is_inside_macro_call(original_file.with_value(&original_token)) checks if the token is inside a macro call. In this case, bar is inside the token tree of foo!(...), which IS a macro call.
So the condition evaluates to false, and we return None.
But wait, the is_inside_macro_call function checks if the token is inside a macro CALL, not inside a macro definition. In this case, foo!(...) is a macro call. So the check returns true.
But the issue is: we're at the top level now, and the expansions have already been attempted. The real expansion foo!(bar) -> bar!() -> () has been computed. The speculative expansion foo!(barraCompletionMarker) -> barraCompletionMarker!() (failed) has also been attempted.
At this point, we should recognize that the completions should be based on the position in the original source file, but we need to understand the context better.
Actually, I think the simplest fix is to modify expand_maybe_stop to always return the base case. The comment says "hopefully checking just the real one should be enough", but this check is too conservative.
Let me try this fix and see if it breaks any tests.
Actually, let me think about what could go wrong if we always return the base case.
If we always return the base case, the analysis is done on the current files (either the source file or the expansion). The analysis looks for a NameLike node at the cursor position. If found, it classifies the completion context.
For our case:
original_file: bar!() (the expansion)
speculative_file: barraCompletionMarker!() (the speculative expansion)
speculative_offset: position of barraCompletionMarker
In speculative_file, barraCompletionMarker is part of a Path in a MacroCall. The find_node_at_offset should find a NameRef node.
Then classify_name_ref is called. It checks the parent of the NameRef:
Parent is PathSegment
The Path containing the segment is part of a MacroCall
kind_macro_call is called
The parent of the MacroCall is MacroExpr
Returns PathKind::Expr
Then the completions are provided for an expression path, which includes macros.
So the fix should work! Let me implement it.
But wait, there's still a potential issue. The original_file is bar!(), which is a macro expansion. The original_file is used in analyze for various operations, like resolving types. If the expansion is not properly tracked, these operations might fail.
In classify_name_ref, the original_file is used to find the corresponding node in the original file. But in our case, the original_file is bar!() (the expansion), and we're looking for the corresponding node.
Actually, classify_name_ref takes the original file and the speculative name reference, and it finds the corresponding node in the original file:
rust
fn classify_name_ref<'db>(
sema: &Semantics<'db, RootDatabase>,
original_file: &SyntaxNode, // <-- The original file
name_ref: ast::NameRef, // <-- The name ref in the SPECULATIVE file
offset: TextSize,
parent: SyntaxNode, // <-- Parent in the SPECULATIVE file
) -> Option<(NameRefContext<'db>, QualifierCtx)>
Wait, looking at the function signature, it takes:
original_file: the file to find the corresponding node in
name_ref: the name ref in the speculative file
parent: the parent in the speculative file
The function uses find_node_in_file to find the corresponding node in the original file.
In our case:
original_file: bar!() (the expansion)
name_ref: barraCompletionMarker in barraCompletionMarker!()
parent: the parent of barraCompletionMarker in the speculative expansion
The function tries to find the corresponding node in the original file at the same relative position. In the original file bar!(), the corresponding position is bar.
So find_node_in_file(original_file, &segment) should find bar in bar!().
This should work! The analysis will correctly identify that we're completing a macro path.
OK let me now implement the fix. I'll modify expand_maybe_stop to always return the base case.
Actually, hold on. Let me reconsider. The current code returns None when inside a macro call because the original and speculative files might have different macro call structures, leading to incorrect completions.
But in our case, both files have the same structure: a macro call with a single-segment path. The only difference is the path itself (bar vs barraCompletionMarker). So returning the base case should be safe.
What about cases where the structures are different? For example:
Real: foo!(bar) expands to bar!()
Speculative: foo!(bazqux) expands to something completely different
In this case, the analysis might find different structures in the original and speculative files, leading to incorrect completions.
But this is an edge case. The more common case is that the structures are similar, and we should provide completions.
I think the fix should be: always return the base case, but if the analysis fails (returns None), fall back to the previous behavior.
Actually, looking at the code flow, if the analysis fails (returns None), the completion system doesn't provide any completions anyway. So the fix is to simply always return the base case.
Let me implement the fix.
Actually, let me reconsider one more time. The issue is that when we're inside a macro call and the expansion fails, we return None instead of providing completions. The fix should be to provide completions in this case.
There are two approaches:
Modify expand_maybe_stop to always return the base case
Modify the fallback handling in analyze to provide completions when inside a token tree of a macro call
Approach 1 is simpler but might have unintended side effects. Approach 2 is more targeted but requires adding a new completion analysis variant.
Let me try approach 1 first, as it's simpler and more likely to fix the issue.
The change is in expand_maybe_stop:
rust
fn expand_maybe_stop(...) -> Option<ExpansionResult> {
if let result @ Some(_) = expand(...) {
return result;
}
// Always return the base case, even if inside a macro call
// The analysis will determine the appropriate completions
Some(ExpansionResult {
original_file: original_file.value,
speculative_file,
original_offset: offset,
speculative_offset: fake_ident_token.text_range().start(),
fake_ident_token,
derive_ctx: None,
})
}
This removes the check for is_inside_macro_call and always returns the base case.
But wait, there might be an issue with original_offset. The offset parameter in expand_maybe_stop is the adjusted offset, which might not be correct for the base case.
It uses offset, which is the parameter. So the fix is to just remove the condition.
Let me also check if there are any other considerations. The fake_ident_token is from the speculative file, so its text range should be correct for the speculative_offset.
I think the fix is straightforward. Let me implement it.
But wait, before I make the change, let me check if there are any tests that rely on the current behavior. If removing the check breaks tests, I need to understand why and fix the underlying issue.
Let me first make the change and then run the tests.
Hmm, actually I realize I should think more carefully. The issue might not be in expand_maybe_stop. Let me trace through the flow again for the WORKING case (in_macro_expr_frag) to understand why it works.
Working case: m!($0) where m { ($e:expr) => { $e } }
Original file: m!() (nothing before cursor)
Speculative file: m!(raCompletionMarker)
Wait, the cursor is at m!($0), so there's nothing before the cursor inside the token tree. The original file has m!() (with just parentheses), and the speculative file has m!(raCompletionMarker).
Now, expand_and_analyze is called:
original_file: the source file
speculative_file: the source file with fake ident
offset: position inside m!()
expand_maybe_stop is called:
expand is called to expand m!() and m!(raCompletionMarker)
m!() might not expand (no expression) - None
m!(raCompletionMarker) expands to raCompletionMarker - Some
Wait, if the real expansion fails, the match would be (None, Some), which falls into the _ => None case. So expand returns None.
Then in expand_maybe_stop:
Check if inside a macro call: the token at the offset is inside m!(), which IS a macro call
Return None
So the working case also returns None from expand_maybe_stop! Then why does it work?
Because the fallback ExpansionResult is used:
rust
let expansion = expand_maybe_stop(...).unwrap_or(ExpansionResult {
original_file: original_file.value, // Source file
speculative_file, // Source file with fake ident
...
});
Then analyze is called with the source file as the original and the speculative source file.
In the speculative source file m!(raCompletionMarker), the token tree contains raCompletionMarker. find_node_at_offset looks for a NameLike node, but inside a token tree, there's no NameLike node.
Wait, but the test shows that m!($0) DOES provide expression completions. So something must be different.
Let me look at the test more carefully:
rust
fn in_macro_expr_frag() {
check(
r#"
macro_rules! m { ($e:expr) => { $e } }
fn quux(x: i32) {
m!($0);
}
"#,
expect![[r#"
fn quux(…) fn(i32)
lc x i32
ma m!(…) macro_rules! m
bt u32 u32
kw const
...
"#]],
);
This test shows expression completions including ma m!(…) (the macro m). So it DOES provide macro completions.
How does this work? Let me trace through the code again.
Oh wait, I think I misread the test. The cursor is at m!($0), which is right after the opening parenthesis and before the closing parenthesis. There's no identifier before the cursor.
In this case:
Original file: m!(); (with nothing inside the token tree)
Speculative file: m!(raCompletionMarker);
The expansion:
m!() - might not expand because no expression. Or it might expand with an empty expression.
m!(raCompletionMarker) - expands to raCompletionMarker
Hmm, actually I'm not sure how m!() (empty) is handled. Let me think about this.
The macro m { ($e:expr) => { $e } } expects an expression. If the input is empty, the macro doesn't match and expansion fails.
So:
m!() - expansion fails
m!(raCompletionMarker) - raCompletionMarker is an identifier, which is a valid expression. Expansion succeeds.
The match would be (None, Some), which falls into _ => None. So expand returns None.
Then expand_maybe_stop returns None (because we're inside a macro call), and the fallback is used.
But then how does the analysis work? The speculative file has raCompletionMarker in the token tree. find_node_at_offset looks for a NameLike node...
Actually, wait. The raCompletionMarker is inside a token tree, not as a NameLike node. So find_node_at_offset returns None.
But the test shows completions are provided! So there must be something else going on.
Let me look at the analysis code more carefully:
rust
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
let analysis = if let Some(original) = ast::String::cast(original_token.clone()) {
CompletionAnalysis::String { original, expanded: ast::String::cast(self_token.clone()) }
} else {
// Fix up trailing whitespace problem
let token = syntax::algo::skip_trivia_token(self_token.clone(), Direction::Prev)?;
let p = token.parent()?;
if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| it.kind() == SyntaxKind::TOKEN_TREE_META)
{
CompletionAnalysis::UnexpandedAttrTT { ... }
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
// Macro definition segment
// ...
} else if find_node_at_offset::<ast::CfgPredicate>(&speculative_file, speculative_offset)
{
CompletionAnalysis::CfgPredicate
} else {
return None;
}
};
return Some((analysis, (None, None), QualifierCtx::default()));
};
So if find_node_at_offset returns None, we check various conditions. None of them match for our case (token tree of a macro call), so we return None.
But the test shows completions ARE provided for m!($0). So how?
Let me check if find_node_at_offset actually finds something. The speculative file is m!(raCompletionMarker);. Inside the token tree, the parser produces a token tree node with tokens. raCompletionMarker is an identifier token inside the token tree.
But ast::NameLike includes ast::NameRef and ast::Name. Can these be inside a token tree?
Actually, I think the answer is no. Inside a token tree, identifiers are just raw tokens, not wrapped in AST nodes.
But then how does the test work?
Let me look at the COMPLETION_MARKER and how it's parsed:
When the marker is inserted into the token tree, it becomes m!(raCompletionMarker);. The token tree contains the identifier raCompletionMarker.
But wait, maybe the issue is that for the in_macro_expr_frag test, the expansion DOES succeed. Let me check.
For m!(raCompletionMarker):
The macro m { ($e:expr) => { $e } } matches with $e = raCompletionMarker
The expansion is { raCompletionMarker }
So the expansion is a block with an expression. The fake_mapped_tokens maps raCompletionMarker in the expansion to its position in the original token tree.
Then expand_maybe_stop is called recursively on the expansion { raCompletionMarker }.
In this expansion, raCompletionMarker is a PathExpr (an expression containing a path). find_node_at_offset would find a NameRef node.
So the analysis works because the expansion succeeds and provides a meaningful context!
OK so let me re-trace the Failing case:
foo!(bar$0) where foo { ($i:ident) => { $i!() } }:
Original file: foo!(bar) (with bar typed)
Speculative file: foo!(barraCompletionMarker)
Expansion of foo!(bar):
Macro foo matches with $i = bar
Expansion is bar!()
Expansion of foo!(barraCompletionMarker):
Macro foo matches with $i = barraCompletionMarker
Expansion is barraCompletionMarker!()
Both expansions succeed! So we enter the (Some, Some) branch.
The fake_mapped_tokens maps barraCompletionMarker in the speculative expansion to bar in the actual expansion.
Check if inside a macro call: bar!() is a macro call, so yes
Return None
So the recursive call returns None. Back in the first-level expand, the iterator produces no elements, and min_by_key returns None.
Back in the first-level expand_maybe_stop:
expand returned None
Check if inside a macro call: yes (we're inside foo!() in the source file)
Return None
Fallback is used with the source file.
In the source file, find_node_at_offset looks for a NameLike at the cursor position in foo!(barraCompletionMarker). Inside the token tree, there's no NameLike, so we return None.
Now, the difference between the working case and the failing case:
Let me re-check. Maybe the expansion of m!() does succeed?
Actually, I think the issue is that m!() (empty token tree) might be handled differently. The token tree is empty, so there's nothing to map. The fake_mapped_tokens might be empty.
original_file: original_file.value - the source file
speculative_file - the speculative source file (with raCompletionMarker inserted)
Then analyze is called with the source file as the original and the speculative source file.
In analyze:
rust
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
// ...
};
In the speculative source file m!(raCompletionMarker), at the speculative offset (start of raCompletionMarker), is there a NameLike node?
Actually, I think inside a token tree, the parser might create an IDENT token, not a NameLike node. So find_node_at_offset would return None.
But the test shows completions ARE provided. So something else must be happening.
Let me check the actual behavior by looking at the test output:
rust
expect![[r#"
fn quux(…) fn(i32)
lc x i32
ma m!(…) macro_rules! m
bt u32 u32
kw const
...
"#]]
These are expression completions. They include functions, local variables, macros, keywords, etc.
For these completions to be provided, the analysis must determine that we're in an expression position. But how, if we're inside a token tree?
Oh wait, I think I understand now. The key is in how sema.speculative_expand_macro_call works. Even though the expand function returns None because the real expansion fails, the speculative expansion might succeed. And the completion system might use the speculative expansion to determine the context.
Actually, let me re-read the expand_and_analyze function:
Wait, speculative_file here is the SPECULATIVE FILE (with fake ident inserted), not the expansion. And original_file is the original file.
So when expand_maybe_stop returns None, the fallback uses:
original_file.value: the original source file
speculative_file: the speculative source file (with fake ident)
But for the working case m!($0):
Original: m!() (empty token tree)
Speculative: m!(raCompletionMarker)
The fake_ident_token is raCompletionMarker in the speculative file.
Now, in analyze, we call find_node_at_offset(&speculative_file, speculative_offset). This looks for a NameLike at the start of raCompletionMarker in m!(raCompletionMarker).
Inside the token tree, raCompletionMarker is just an IDENT token, not a NameLike node. So find_node_at_offset returns None.
Then we check if we're in a token tree:
rust
let token = syntax::algo::skip_trivia_token(self_token.clone(), Direction::Prev)?;
let p = token.parent()?;
if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| it.kind() == SyntaxKind::TOKEN_TREE_META)
{
// UnexpandedAttrTT
CompletionAnalysis::UnexpandedAttrTT { ... }
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
// Macro segment
// ...
} else if find_node_at_offset::<ast::CfgPredicate>(...)
{
CompletionAnalysis::CfgPredicate
} else {
return None;
}
For m!(raCompletionMarker):
token is raCompletionMarker (the IDENT token)
p = token.parent() is the TOKEN_TREE (the token tree of the macro call)
p.ancestors().any(|it| it.kind() == SyntaxKind::TOKEN_TREE_META) - false (not an attribute)
p.ancestors().any(|it| ast::Macro::can_cast(it.kind())) - false (not a macro definition, it's a macro CALL)
So we fall through to return None.
But the test shows completions ARE provided! So something must be different.
Hmm, let me check if ast::Macro::can_cast also matches MacroRules items. Actually, looking at the macro definition macro_rules! m { ($e:expr) => { $e } }, the token tree is inside the macro DEFINITION, not the macro CALL.
Wait, the token tree in m!(raCompletionMarker) is the argument to the macro CALL, not inside the macro DEFINITION. So ast::Macro::can_cast would not match.
But the test shows completions ARE provided. So there must be something else going on.
Let me re-check the test. Maybe the expansion DOES succeed and the analysis happens on the expansion, not the source file.
For m!(raCompletionMarker):
m { ($e:expr) => { $e } } matches with $e = raCompletionMarker
Expansion is { raCompletionMarker } (a block expression)
So the speculative expansion succeeds. The real expansion m!() might fail (empty input).
Hmm, so the expand function returns None, and the fallback is used. But the test shows completions are provided.
Let me check if sema.expand_macro_call(m!()) really returns None. Maybe it returns Some with an error.
Actually, looking at the type: sema.expand_macro_call returns Option<ExpandResult>. ExpandResult has a value (the expansion) and an err (any errors). So even if there's an error, the expansion might succeed partially.
But for m!() (empty token tree), the macro m { ($e:expr) => { $e } } requires an expression. An empty token tree doesn't match, so the expansion fails and returns None.
Hmm, I'm confused. Let me try a different approach: let me check what the test output actually is and trace through the code to understand how it produces those completions.
Actually, let me look at the test more carefully. The test uses check, which calls completion_list. Let me trace through what completion_list does.
Hmm, the actual output is empty now. This means my fix broke the macro_that_ignores_completion_marker test. The test expects completions to be provided, but now none are provided.
Let me think about this more carefully. The issue is that by always returning the base case, I'm returning an ExpansionResult that might not be valid for all cases.
The expansion of m!(vraCompletionMarker) is { helper!(vraCompletionMarker); vraCompletionMarker }
Both expansions succeed. Then expand_maybe_stop is called recursively on the expansion { helper!(v); v }.
Now, in this expansion:
helper!(v) expands to () (empty)
helper!(vraCompletionMarker) also expands to () (empty, because helper ignores its input)
Both expansions succeed and produce the same result. So the recursive call should work.
But wait, after expanding helper!(v), the cursor is at v in the block expression. Let me trace through:
m!(v) expands to { helper!(v); v }
m!(vraCompletionMarker) expands to { helper!(vraCompletionMarker); vraCompletionMarker }
The fake_mapped_tokens maps vraCompletionMarker to v in both places in the expansion
For each mapped token, we call expand_maybe_stop recursively
If the token is at v in { helper!(v); v }, there's no macro call to expand
expand returns None
With my fix, we return the base case
The base case uses { helper!(v); v } as the original file and { helper!(vraCompletionMarker); vraCompletionMarker } as the speculative file
The analysis should find vraCompletionMarker as a NameRef in a PathExpr
This should provide expression completions
So why is the actual output empty?
Let me check if the issue is that the token is in a different position. The test has m!(v$0), so the cursor is after v. The speculative file has m!(vraCompletionMarker).
Actually, wait. Let me re-read the test more carefully. The cursor is at v$0, which means after v. So in the speculative file, it's vraCompletionMarker.
But the fake_mapped_tokens maps tokens that contain the completion marker. The token vraCompletionMarker contains raCompletionMarker, so it should be mapped.
Let me think about what happens step by step:
expand_maybe_stop is called with the source file
expand is called to expand m!(v) and m!(vraCompletionMarker)
Both expand successfully
For each fake_mapped_token, we call expand_maybe_stop recursively
With my fix, the recursive call always returns a base case
The base case should provide valid completions
But the test shows no completions. Let me check if there's an issue with the analysis.
Actually, I think the problem might be that the original_file in the base case is the expansion, not the source file. And the scope_at_offset call in CompletionContext::new might fail because it expects a file that's tracked by the semantics.
Let me look at the code:
rust
let AnalysisResult {
analysis,
expected: (expected_type, expected_name),
qualifier_ctx,
token,
original_offset,
} = expand_and_analyze(
&sema,
InFile::new(editioned_file_id.into(), original_file.syntax().clone()),
file_with_fake_ident.syntax().clone(),
offset,
&original_token,
)?;
// adjust for macro input, this still fails if there is no token written yet
let scope = sema.scope_at_offset(&token.parent()?, original_offset)?;
The token comes from the original_file (the expansion), and original_offset is the offset in that file. If the original_file is not tracked by the database, scope_at_offset might fail.
Hmm, but InFile::new(editioned_file_id.into(), ...) wraps the file with the original file ID. So when we pass the expansion file, it's wrapped with the original file ID.
Wait, looking at the ExpansionResult:
rust
Some(ExpansionResult {
original_file: original_file.value, // This is the SyntaxNode, stripped of InFile wrapper
speculative_file,
...
})
The original_file is just the SyntaxNode, not an InFile. Then in analyze:
So token is returned in AnalysisResult. Then in CompletionContext::new:
rust
let scope = sema.scope_at_offset(&token.parent()?, original_offset)?;
The token is from the expansion file, and original_offset is the offset in the expansion file. But scope_at_offset expects a syntax node from a file tracked by the semantics.
I think the issue is that the expansion file is not tracked by the semantics, so scope_at_offset fails and returns None, which causes the whole completion to fail.
Let me check how this worked before my change. Before my change, when expand_maybe_stop returns None, the fallback uses the source file:
In the fallback, original_file is the SOURCE file (from the top-level call). So the token is from the source file, which IS tracked by the semantics.
So my fix broke things because I'm returning the expansion file as original_file, which is not tracked by the semantics.
I need a different approach. Let me think about this more carefully.
The issue is:
When expand succeeds and returns an ExpansionResult, the original_file is the expansion, not the source file.
When expand_maybe_stop returns None, the fallback uses the source file.
With my fix, I'm returning the base case which uses the expansion file, which is not tracked.
Actually wait, let me re-read the code more carefully.
Looking at the recursive call:
rust
let result = expand_maybe_stop(
sema,
actual_expansion.clone(), // This is an ExpandResult, which has a file ID
fake_expansion.clone(),
new_offset,
fake_mapped_token,
relative_offset,
)?;
ExpandResult is defined in hir. Let me check its definition:
Let me understand the problem better. The issue is that when we're inside a macro call like foo!(bar$0) where the macro expands the ident to a macro call path $i!(), we can't complete the macro name bar.
Let me trace through what happens:
Original file: foo!(bar) - source file
Speculative file: foo!(barraCompletionMarker) - with fake ident
expand_maybe_stop is called with the source file
expand expands foo!(bar) -> bar!() and foo!(barraCompletionMarker) -> barraCompletionMarker!()
Both expansions succeed at this level
For each fake_mapped_token, we call expand_maybe_stop recursively with:
original_file: the actual expansion (bar!()) - this is an InFile with a file ID
speculative_file: the fake expansion (barraCompletionMarker!())
In the recursive call, expand tries to expand bar!() and barraCompletionMarker!():
bar!() expands to () because bar IS a macro
barraCompletionMarker!() fails because it's NOT a macro
Since one succeeds and one fails, expand returns None
In expand_maybe_stop, we check is_inside_macro_call:
The token at the offset is inside bar!(), which IS a macro call
So we return None
Back in step 6's expand, all recursive calls returned None, so the iterator is empty, and we return None
Back in step 3's expand_maybe_stop, we check is_inside_macro_call:
The token is inside foo!(...), which IS a macro call
So we return None
Back in expand_and_analyze, we use the fallback with the SOURCE file
In analyze, find_node_at_offset looks for a NameLike in the speculative source file foo!(barraCompletionMarker)
Inside a token tree, there's no NameLike node, so it returns None
We fall into the else branch and check various conditions
None match, so we return None
No completions
The key insight is that the issue is in step 13-17. When we fall back to the source file, we can't find a NameLike node because we're inside a token tree.
But wait, I need to understand why the test in_macro_expr_frag works. Let me trace through that:
Original file: m!() - nothing inside the token tree
Speculative file: m!(raCompletionMarker) - with fake ident
expand_maybe_stop is called with the source file
expand tries to expand m!() and m!(raCompletionMarker):
m!() fails because there's no expression
m!(raCompletionMarker) succeeds, expanding to { raCompletionMarker }
Wait, actually, the match is (None, Some), so expand returns None
In expand_maybe_stop, we check is_inside_macro_call:
The token at the offset is inside m!(), which IS a macro call
So we return None
Back in expand_and_analyze, we use the fallback with the SOURCE file
In analyze, find_node_at_offset looks for a NameLike in m!(raCompletionMarker)
Inside a token tree, there's no NameLike node, so it returns None
We fall into the else branch...
Wait, but the test DOES work! So there must be something different.
Let me look at the in_macro_expr_frag test more carefully:
The cursor is at m!($0), so there's nothing typed before the cursor. The original file has m!(); and the speculative file has m!(raCompletionMarker);.
Hmm, but how does the expansion work here? Let me think...
Actually, I think the issue is that in the working case, the speculative expansion succeeds but the real expansion fails (because m!() has no expression). So in step 4, the match is (None, Some), which falls into _ => None.
But in the failing case, BOTH expansions succeed at the first level:
Hmm, so it looks for a NameLike in the SPECULATIVE file. In the speculative file m!(raCompletionMarker), raCompletionMarker is inside a token tree. There's no NameLike node there.
But wait, the test DOES provide completions. Let me look at the actual test result again.
Actually, looking at the test result:
code
fn quux(…) fn(i32)
lc x i32
ma m!(…) macro_rules! m
bt u32 u32
...
These are expression completions. They include local variables, functions, macros, etc.
But if the analysis returns None, there would be no completions. So something must be finding a NameLike node.
Wait, maybe I'm wrong about token trees. Let me check if the parser creates NameLike nodes inside token trees...
Actually, I think the key insight is that raCompletionMarker in m!(raCompletionMarker) might actually be parsed as a standalone identifier, not inside a token tree. Let me think about how the parser works.
When we have m!(raCompletionMarker), the parser sees:
m - identifier
! - bang
( - open paren
raCompletionMarker - identifier
) - close paren
The token tree is the content between ( and ). Inside the token tree, raCompletionMarker is just an identifier token. It's not wrapped in a Name or NameRef AST node.
But wait, find_node_at_offset looks for ast::NameLike nodes. If raCompletionMarker is just a token inside a token tree, there's no NameLike node to find.
So how does the working test provide completions?
Let me look at the code again more carefully...
Actually, I think I need to look at the expand function more carefully. Maybe the speculative expansion DOES work and the analysis is done on the expansion, not the source file.
For m!(raCompletionMarker):
The macro m { ($e:expr) => { $e } } matches raCompletionMarker as an expression
The expansion is { raCompletionMarker }
So the speculative expansion succeeds! But the REAL expansion m!() fails because there's no expression.
The match in expand is:
rust
match (
sema.expand_macro_call(&m!()), // None (no expression)
sema.speculative_expand_macro_call(...), // Some(({ raCompletionMarker }, fake_mapped_tokens))
) {
(Some, Some) => // both succeed
_ => None, // This case!
}
So expand returns None because the real expansion fails. Then expand_maybe_stop returns None (inside macro call), and the fallback is used.
But wait, the test provides completions! So the fallback must work somehow.
Let me think about what the fallback does:
original_file: source file m!();
speculative_file: source file with fake ident m!(raCompletionMarker);
analyze looks for a NameLike at the speculative offset
In the speculative file, the cursor is at raCompletionMarker inside m!(raCompletionMarker). find_node_at_offset looks for ast::NameLike.
Hmm, I just realized something. The cursor position in the original issue is AFTER the typed text (foo!(bar$0)), while in the working test it's at the start (m!($0)). This might make a difference in how the fake ident is parsed.
In m!($0):
Original token tree: empty
Speculative token tree: raCompletionMarker
In foo!(bar$0):
Original token tree: bar
Speculative token tree: barraCompletionMarker
The difference is that in the working case, the token tree has only the fake ident. In the failing case, the token tree has bar + fake ident.
But I don't think this matters for finding NameLike nodes, because both cases are inside a token tree where identifiers are just tokens.
OK, I'm stuck. Let me try a different approach: let me add some debug output to understand what's happening in the working case.
Actually, let me first check if the in_macro_expr_frag test is even running correctly with the current code.
Let me trace through the code more carefully by looking at what speculative_expand_macro_call returns.
Actually, I think I finally understand the issue. Let me re-read the expand function:
If ctx is None, we return an empty vector! So no completions!
But the test shows completions ARE provided for m!($0)! So there must be something else going on.
Wait, let me re-read the test fixture:
rust
fn quux(x: i32) {
m!($0);
}
The $0 marker is inside the token tree of m!. The original token tree is empty (just ()). The speculative token tree has raCompletionMarker.
But wait, maybe the cursor is positioned in a way that the fake_ident_token is not inside the token tree? Let me check.
Actually, looking at expand_and_analyze:
rust
let fake_ident_token = speculative_file.token_at_offset(offset).right_biased()?;
The offset is the cursor position. In m!(raCompletionMarker), the cursor is at the start of raCompletionMarker. So fake_ident_token is the token raCompletionMarker.
But raCompletionMarker is inside a token tree. The token tree contains it as a child token.
Hmm, but token_at_offset returns the token at that position, regardless of whether it's inside a token tree or not.
OK let me try a completely different approach. Let me check if the test is actually working with the original code. Maybe I'm misreading the test result.
Actually, wait. I just realized something. The in_macro_expr_frag test uses m!($0) which has NOTHING before the cursor. But the failing case has foo!(bar$0) which has bar before the cursor.
When the completion system inserts the fake ident, it inserts AFTER the cursor. So:
m!($0) becomes m!(raCompletionMarker)
foo!(bar$0) becomes foo!(barraCompletionMarker)
In the first case, the token tree has only raCompletionMarker. In the second case, the token tree has barraCompletionMarker.
But both are inside token trees, so neither should have NameLike nodes...
Unless the issue is that the EXPANSION works differently. Let me think about what happens when m!(raCompletionMarker) is expanded:
The macro m { ($e:expr) => { $e } } matches
The expansion is { raCompletionMarker }
In the expansion, raCompletionMarker is a PathExpr, which contains a Path, which contains a PathSegment, which contains a NameRef
So in the expansion, there IS a NameLike node! But the analysis is done on the SOURCE file (the fallback), not the expansion.
Wait, but if expand returns None because the real expansion failed, the fallback uses the source file. So the analysis should be on the source file, where there's no NameLike.
Hmm, I'm really confused. Let me try running the test with the original code to confirm it works:
Actually, I already ran the test and it passed with the original code. So something in the original code must be providing completions for m!($0).
Let me look at the code again more carefully. Maybe there's something I'm missing.
Looking at the analyze function:
rust
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
// ...
};
What if find_node_at_offset DOES find a NameLike in the speculative file? What if raCompletionMarker IS parsed as a Name or NameRef even inside a token tree?
Let me check...
Actually, I think I need to verify this. Let me look at how the parser handles token trees.
Actually wait, I just realized something. In Rust syntax, a MacroCall has a path and a token tree. The token tree contains raw tokens, not AST nodes. But raCompletionMarker inside the token tree is just an IDENT token, not a Name or NameRef.
So find_node_at_offset::<ast::NameLike>(&speculative_file, speculative_offset) should return None for both the working and failing cases.
But the working test DOES provide completions. So there must be a different path that provides completions.
Wait, original_file.value is the SYNTAX NODE from the original file, not the InFile wrapper. And speculative_file is the speculative file's syntax node.
Then in analyze:
rust
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
// Handle cases where no name-like is found
let analysis = if let Some(original) = ast::String::cast(original_token.clone()) {
CompletionAnalysis::String { ... }
} else {
let token = syntax::algo::skip_trivia_token(self_token.clone(), Direction::Prev)?;
let p = token.parent()?;
if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| it.kind() == SyntaxKind::TOKEN_TREE_META)
{
CompletionAnalysis::UnexpandedAttrTT { ... }
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
// Macro segment
// ...
} else if find_node_at_offset::<ast::CfgPredicate>(&speculative_file, speculative_offset).is_some() {
CompletionAnalysis::CfgPredicate
} else {
return None;
}
};
return Some((analysis, (None, None), QualifierCtx::default()));
};
So when no NameLike is found, we check various conditions. None of them match for a macro call's token tree, so we return None.
Wait, but the test DOES provide completions. Let me look at the test output again:
rust
expect![[r#"
fn quux(…) fn(i32)
lc x i32
ma m!(…) macro_rules! m
...
"#]]
These are expression completions. They include functions, local variables, macros, etc.
Hmm, let me check if maybe the expansion DOES work and the analysis is done on the expansion, not the source file.
Let me re-read the expand function for the working case:
For m!($0):
sema.expand_macro_call(m!()) - this is the macro call with an EMPTY token tree
Actually, wait. m!() has parentheses but no content. The parser creates a token tree with no children.
Does expand_macro_call succeed or fail?
If the token tree is empty, the macro pattern $e:expr might not match. So expand_macro_call returns None.
But what if the token tree is not empty? What if the parser creates some kind of placeholder?
Actually, I think an empty token tree is valid. The macro m { ($e:expr) => { $e } } expects an expression. An empty token tree doesn't provide an expression, so the macro doesn't match and expansion fails.
The token at the offset is... let me think. The offset is at the start of the cursor position. In the original file m!(), the token at the cursor position (between ( and )) is... nothing? Or the closing )?
Actually, token_at_offset_ignore_whitespace looks for a token at the offset. In m!(), the offset is between ( and ). There's no token there, so token_at_offset returns the left-biased token, which is (. Then skip_whitespace_token goes backwards, skipping whitespace. It finds (, then !, then m.
Wait, skip_whitespace_token only skips whitespace tokens. It doesn't skip non-whitespace tokens. So if the token at the offset is (, skip_whitespace_token returns (.
Then is_inside_macro_call is called with ( in m!(). The parent of ( is the token tree, and the parent of the token tree is the macro call. So is_inside_macro_call returns true.
So expand_maybe_stop returns None (because we're inside a macro call).
Then the fallback is used. In the fallback:
original_file: source file
speculative_file: source file with fake ident m!(raCompletionMarker)
In analyze:
find_node_at_offset(&speculative_file, speculative_offset) - looks for NameLike at raCompletionMarker
Returns None (inside token tree)
Falls into else branch
Returns None
So the analysis returns None, and no completions are provided!
But the test shows completions ARE provided. I must be missing something.
Actually, wait. Let me re-read the code in expand_and_analyze:
If analyze returns None, the .map() returns None, and expand_and_analyze returns None. Then in CompletionContext::new:
rust
let AnalysisResult { ... } = expand_and_analyze(...)?;
The ? propagates the None, and CompletionContext::new returns None.
So if analyze returns None, there are no completions. But the test shows completions ARE provided. So analyze must NOT return None for the working case.
Let me think about this differently. Maybe find_node_at_offset DOES find a NameLike in some cases.
Actually, let me check what the speculative file looks like. The speculative file is created by reparse:
rust
let file_with_fake_ident = {
let (_, edition) = editioned_file_id.unpack(db);
let parse = editioned_file_id.parse(db);
parse.reparse(TextRange::empty(offset), COMPLETION_MARKER, edition).tree()
};
So it reparses the original file with raCompletionMarker inserted at the cursor position. For m!($0), it becomes m!(raCompletionMarker).
But wait, maybe the issue is that when the cursor is at m!($0) (right after (), the fake ident is inserted as m!(raCompletionMarker). The parser sees this as a macro call with raCompletionMarker inside the token tree.
But when the cursor is at foo!(bar$0) (after bar), the fake ident is inserted as foo!(barraCompletionMarker). The parser sees this as a macro call with barraCompletionMarker inside the token tree.
In both cases, the ident is inside a token tree. So find_node_at_offset should return None for both.
Unless... there's a difference in how the parser handles these cases?
OK I'm going in circles. Let me try a different approach: let me add some debug output to the code to see what's actually happening.
Actually wait, I just realized I might have been wrong about something. Let me re-read the analyze function more carefully.
Wait, there's a check at the beginning! If original_token.kind() != self_token.kind(), and certain conditions aren't met, we return None.
What is original_token? It's passed from expand_and_analyze:
rust
analyze(sema, expansion, original_token, &token)
original_token is the original token at the cursor position (from the source file). token (which becomes self_token) is the token at the corresponding position in the expansion file.
For the working case m!($0):
original_token is the token at the cursor in m!(). Since the cursor is between ( and ), left_biased would give (.
self_token is the token at the corresponding position in the expansion file. If the expansion file is the source file (fallback), it's also (.
Both are (, so the check passes.
For the failing case foo!(bar$0):
original_token is the token at the cursor in foo!(bar). The cursor is after bar, so left_biased gives bar.
self_token is the token at the corresponding position in the expansion file.
Hmm, but what if the original file is the source file (from the fallback)?
let original_offset = expansion.original_offset + relative_offset;
let token = expansion.original_file.token_at_offset(original_offset).left_biased()?;
So token is from expansion.original_file, which is the source file (from the fallback). So self_token is a token from the source file.
For the failing case foo!(bar$0):
original_token is bar (from the source file)
token (self_token) is also from the source file, at the same position, so also bar
Both are bar (identifiers), so the check passes.
OK so the check at the beginning doesn't explain the difference.
In the speculative file, we look for a NameLike at the speculative offset. For both cases, the speculative file has the fake ident inside a token tree, so find_node_at_offset returns None.
In the else branch:
rust
let analysis = if let Some(original) = ast::String::cast(original_token.clone()) {
CompletionAnalysis::String { ... }
} else {
let token = syntax::algo::skip_trivia_token(self_token.clone(), Direction::Prev)?;
let p = token.parent()?;
if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| it.kind() == SyntaxKind::TOKEN_TREE_META)
{
CompletionAnalysis::UnexpandedAttrTT { ... }
} else if p.kind() == SyntaxKind::TOKEN_TREE
&& p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
{
// Macro segment
// ...
} else if find_node_at_offset::<ast::CfgPredicate>(&speculative_file, speculative_offset).is_some() {
CompletionAnalysis::CfgPredicate
} else {
return None;
}
};
return Some((analysis, (None, None), QualifierCtx::default()));
So we check if the token's parent is a TOKEN_TREE. For both cases, the token (( or bar) is inside a token tree.
The previous token before ( is !. But ! is not trivia.
So skip_trivia_token returns... wait, it only skips trivia tokens, not all tokens.
Actually, skip_trivia_token is: "Returns the first non-trivia token found by going in the specified direction."
So it starts at ( and goes backwards. ( is not trivia, so it returns (.
Wait, no. It says "Returns the first non-trivia token found by going in the specified direction." So it starts from the given token and moves in the direction, skipping trivia, and returns the first non-trivia token.
If the given token is already non-trivia, does it return it immediately or start from the next token?
Let me check the implementation of skip_trivia_token:
Actually, I think skip_trivia_token starts from the given token and looks in the specified direction. It first skips trivia, then returns the first non-trivia token. But the starting token itself is not skipped.
Hmm, actually I think it might look at the NEXT token in the direction, not the current one. Let me check.
Actually, looking at the code more carefully, I think skip_trivia_token(self_token.clone(), Direction::Prev) would return the previous non-trivia token before self_token. For m!($0):
self_token is (
skip_trivia_token(..., Direction::Prev) looks before (, skipping trivia
The token before ( is ! (or maybe m if there's whitespace)
! is not trivia, so it returns !
Wait, but the code says:
rust
let token = syntax::algo::skip_trivia_token(self_token.clone(), Direction::Prev)?;
let p = token.parent()?;
So token is the previous non-trivia token. For m!(), the previous token before ( is !. !'s parent is... the macro call m!(). Not a token tree.
So p.kind() == SyntaxKind::TOKEN_TREE is false, and we fall through to the next condition.
Similarly for foo!(bar):
self_token is bar
skip_trivia_token(..., Direction::Prev) looks before bar, skipping trivia
The token before bar is (. ( is not trivia.
So token is (.
p = token.parent() is the token tree.
So for the failing case, p.kind() == SyntaxKind::TOKEN_TREE is true!
And then:
rust
if p.ancestors().any(|it| it.kind() == SyntaxKind::TOKEN_TREE_META) {
// UnexpandedAttrTT
} else if p.ancestors().any(|it| ast::Macro::can_cast(it.kind())) {
// Macro segment
} else if find_node_at_offset::<ast::CfgPredicate>(...) {
// CfgPredicate
} else {
return None;
}
For foo!(bar):
p is the token tree
p.ancestors() includes the token tree, the macro call, the block expr, etc.
TOKEN_TREE_META? No, this is a macro call, not an attribute.
ast::Macro::can_cast? This checks if any ancestor is a Macro (macro definition). But foo!() is a macro CALL, not a macro definition. So no.
CfgPredicate? No.
Return None.
So for the failing case, analyze returns None.
For the working case m!($0):
self_token is (
skip_trivia_token(..., Direction::Prev) returns !
p = !.parent() is the macro call m!()
p.kind() == TOKEN_TREE? No, it's a MACRO_CALL.
Fall through to the else branch of the outer if.
Wait, that means for the working case, analyze also returns None!
But the test shows completions ARE provided! I'm clearly missing something.
OK let me try yet another approach. Let me actually look at what happens when the expansion DOES work.
For the working case m!($0):
expand_macro_call(m!()) returns None (no expression)
Wait, speculative_file in the fallback is the original speculative_file parameter (with fake ident). And fake_ident_token is from the original speculative_file.
So speculative_offset = fake_ident_token.text_range().start().
Then in analyze:
rust
let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
// ...
};
For the working case m!($0):
speculative_file is the source file with fake ident: m!(raCompletionMarker)
speculative_offset is the start of raCompletionMarker
find_node_at_offset(&speculative_file, speculative_offset) looks for a NameLike at that position
Hmm, inside a token tree, is raCompletionMarker a NameLike or just a token?
I believe it's just a token (IDENT), not a NameLike node. So find_node_at_offset returns None.
OK but the test still shows completions. Let me look at this from a completely different angle. Maybe the completions are provided through a different code path, not through NameRefKind::Path.
Actually, let me check what CompletionAnalysis variants exist and how they're handled:
So the only variants that provide completions are: Name, NameRef, Lifetime, String (with expanded), UnexpandedAttrTT (with fake_attribute_under_caret), CfgPredicate, and MacroSegment.
For the working case, which variant would be used?
If find_node_at_offset returns None, we check:
ast::String::cast - no, it's not a string
p.kind() == TOKEN_TREE && ancestors().any(TOKEN_TREE_META) - no
p.kind() == TOKEN_TREE && ancestors().any(ast::Macro::can_cast) - this checks for macro DEFINITION
CfgPredicate - no
Return None
So analyze returns None, and expand_and_analyze returns None.
Then in CompletionContext::new:
rust
let AnalysisResult { ... } = expand_and_analyze(...)?;
The ? returns None, and CompletionContext::new returns None.
Then in completions:
rust
let (ctx, analysis) = CompletionContext::new(db, config, position, trigger_character)?;
If CompletionContext::new returns None, we return None from completions.
So there should be NO completions for m!($0)! But the test shows completions!
I'm completely stumped. Let me try to run the test myself with some debugging.
Actually, maybe the test is wrong or I'm misreading the test. Let me look at the test more carefully.
Actually wait, I just realized something. The test fixture might be different from what I thought. Let me look at the exact test:
The $0 is inside m!(). But how is this parsed? The token tree of m!() is empty. When we insert raCompletionMarker, it becomes m!(raCompletionMarker).
But wait, maybe the issue is that the cursor is BETWEEN ( and ), and the fake ident is inserted there. So the speculative file is m!(raCompletionMarker).
But the original file is m!(). So the token tree is empty in the original file.
Now, expand_macro_call(m!()) is called. With an empty token tree, the macro m { ($e:expr) => { $e } } can't match, so it returns None.
But what about speculative_expand_macro_call? It's called with:
actual_macro_call: m!() from the original file
speculative_args: the token tree from m!(raCompletionMarker)
fake_ident_token: raCompletionMarker
So the speculative expansion uses the ACTUAL macro call from the original file but with the SPECULATIVE token tree. This should succeed because the token tree has raCompletionMarker as a valid expression.
So speculative_expand_macro_call returns Some. And expand_macro_call returns None. The match is (None, Some) -> _ => None.
Hmm, so expand returns None. And expand_maybe_stop returns None. And the fallback is used.
But I already traced through the fallback and it returns None too.
Let me try one more thing: maybe the issue is that expand_macro_call(m!()) actually returns Some instead of None.
Let me check what happens when the macro has an empty token tree. The macro m { ($e:expr) => { $e } } expects an expression. An empty token tree doesn't match. But maybe the expansion still produces something?
Actually, looking at the macro expansion code, if the pattern doesn't match, the expansion returns None. So expand_macro_call(m!()) should return None.
OK I give up trying to understand the working case through code analysis. Let me try a different approach: let me make a minimal change and run the tests to see what breaks.
The issue is that when we're inside a macro call's token tree and the expansion fails (because real and speculative expansions diverge), we should still provide completions.
The current behavior:
expand_maybe_stop returns None when inside a macro call
Fallback uses the source file
analyze can't find a NameLike in the token tree
Returns None
No completions
The desired behavior:
When inside a macro call's token tree, we should still try to provide completions
If the expansion succeeded partially, use that context
If not, fall back to general path completions
I think the fix should be in analyze, not in expand_maybe_stop. When we're inside a token tree of a macro call (not a macro definition), we should provide path completions.
Let me implement this fix:
In analyze, when no NameLike is found and we're inside a token tree of a macro call, return a CompletionAnalysis that provides path completions.
Actually, looking at the code again, I see that when no NameLike is found, there are only a few cases handled:
UnexpandedAttrTT - for attribute token trees
MacroSegment - for macro definition fragment specifiers
CfgPredicate - for cfg predicates
For macro call token trees, none of these match, so we return None.
The fix should be to add a case for macro call token trees. We need to create a CompletionAnalysis that provides path completions.
But looking at the CompletionAnalysis enum, there's no variant for "token tree of a macro call". We'd need to add one.
Actually, let me think about this differently. Maybe instead of adding a new variant, we can use one of the existing variants.
Looking at NameRefKind::Path, if we can create a PathCompletionCtx with the right context, we can get path completions.
But the issue is that we can't create a NameRef node from just a token tree position. We'd need to synthesize one.
Actually, looking at how UnexpandedAttrTT works, it provides completions without a NameLike node. We could do something similar for macro call token trees.
It calls a specific completion function. We could add a similar function for macro call token trees.
But this is getting complex. Let me try a simpler approach.
Actually, I think the real issue might be simpler than I thought. Let me re-read the expand_maybe_stop code:
rust
fn expand_maybe_stop(...) -> Option<ExpansionResult> {
if let result @ Some(_) = expand(...) {
return result;
}
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))
})
{
Some(ExpansionResult { ... })
} else {
None
}
}
The issue is: when expansion fails and we're inside a macro call, we return None. But we should still return the base case in some situations.
The key insight is: we should return the base case when the current level has been fully expanded (i.e., the token is NOT inside a macro call that can be further expanded).
But is_inside_macro_call checks if the token is inside ANY macro call, including ones that have already been expanded.
Wait, actually, is_inside_macro_call checks if the token is inside the INPUT of a macro call, not inside an expansion. Let me re-read:
rust
/// Returns true if the given input is within a macro call.
///
/// Note that if this token itself is within the context of a macro expansion does not matter.
/// That is, we strictly check if it lies inside the input of a macro call.
pub fn is_inside_macro_call(&self, token @ InFile { value, .. }: InFile<&SyntaxToken>) -> bool {
So is_inside_macro_call checks if the token is inside the INPUT (arguments) of a macro call. Not inside an expansion.
In our case, after expanding foo!(bar) to bar!(), the token at the offset is bar in bar!(). This IS inside a macro call (bar!()), because bar is the argument... wait, no. bar is the MACRO BEING CALLED, not an argument.
Hmm, actually bar!() is a macro call where bar is the path of the macro being invoked. bar is not inside the token tree of bar!(), it's the path.
So is_inside_macro_call should return... let me think. The token bar in bar!() - is it inside a macro call? bar is the identifier that is the path of the macro call bar!(). The macro call itself is bar!().
Looking at the AST structure:
code
MacroCall
Path
PathSegment
Name "bar"
"!"
TokenTree
(empty)
So bar is part of the Path of the MacroCall, not inside the token tree. is_inside_macro_call checks if the token is inside the input (token tree) of a macro call. bar is not inside the token tree of any macro call.
Wait, but bar is part of the macro call bar!() itself. So is it "inside" the macro call? The function checks:
So if any ancestor is a MacroCall, it returns true. bar's ancestor IS MacroCall (bar!()). So is_inside_macro_call returns true.
But wait, the comment says "we strictly check if it lies inside the input of a macro call". The Path is not the input, the TokenTree is the input. But the code just checks if any ancestor is a MacroCall, which would be true for both the path and the token tree.
Hmm, maybe the comment is misleading or the code is wrong.
The idea is: if the token is NOT inside a macro call's input, we can stop expanding and use the current context. If it IS inside a macro call's input, we can't stop because there might be more macros to expand.
But this is wrong for our case. The token bar in bar!() is part of the macro call's PATH, not its input. There's nothing more to expand at this position (from the token tree perspective). So we should return the base case.
I think the fix should be to change the condition to check if the token is inside a macro call's TOKEN TREE, not just any part of a macro call.
Let me implement this fix:
Instead of is_inside_macro_call, we should check if the token is inside a TokenTree that is a child of a MacroCall.
Let me look at how to implement this. We can check:
This checks if any ancestor is a TokenTree whose parent is a MacroCall.
Let me use this instead of is_inside_macro_call in the expand_maybe_stop function.
Actually, wait. Let me think about this more carefully. The original_file in expand_maybe_stop might be a macro expansion, not the source file. And the token might be in a different context.
For each fake_mapped_token, we call expand_maybe_stop recursively
In step 4, expand_maybe_stop is called with:
original_file: InFile wrapping bar!() (the actual expansion)
speculative_file: barraCompletionMarker!() (the speculative expansion)
expand tries to expand bar!() and barraCompletionMarker!():
bar!() -> () (bar is a macro)
barraCompletionMarker!() -> fails (not a macro)
Match: (Some, None) -> _ => None
expand returns None
In expand_maybe_stop, check is_inside_macro_call:
original_file.value is bar!()
The token at the offset is bar (the ident in the path of bar!())
is_inside_macro_call checks if any ancestor of bar is a MacroCall
Yes! bar!() IS a MacroCall, and bar is its path
Returns true
Since we're inside a macro call, return None
Back in step 4, all recursive calls returned None, so the iterator is empty
expand returns None
Back in step 1, expand_maybe_stop returns None
Fallback uses the source file
analyze can't find a NameLike in the token tree
Returns None
No completions
So the issue is in step 8-9. The check is_inside_macro_call returns true even though bar is the PATH of the macro call, not inside its token tree. And since we return None, we lose the context.
The fix should be: change the check to only return true if the token is inside a macro call's TOKEN TREE (its input), not just any part of a macro call.
If the token is the PATH of a macro call (like bar in bar!()), we should return the base case because there's nothing more to expand at that position.
Where is_inside_macro_call_token_tree checks if the token is inside a token tree of a macro call.
Actually, thinking about it more, the original code's intent was: "if we're inside a macro call, there might be more to expand, so don't stop". But this is wrong when the token is the PATH of the macro call, not its input.
The correct logic should be: "if we're inside a macro call's INPUT (token tree), there might be more to expand, so don't stop. Otherwise, stop and provide completions."
if !is_inside_macro_input(&original_token) {
// Recursion base case.
Some(ExpansionResult { ... })
} else {
None
}
This way, if the token is the PATH of a macro call (not inside its token tree), we return the base case.
Let me implement this fix.
Wait, but I also need to make sure the base case provides meaningful completions. The base case uses:
original_file: the current file (which might be an expansion)
speculative_file: the speculative expansion
If these are macro expansions, scope_at_offset might fail because the file is not tracked by the semantics.
Hmm, but looking at the recursive call:
rust
expand_maybe_stop(
sema,
actual_expansion.clone(), // This is an ExpandResult, which has a file ID
fake_expansion.clone(),
new_offset,
fake_mapped_token,
relative_offset,
)
actual_expansion is an ExpandResult<InFile<SyntaxNode>>. The InFile has a file ID that's tracked by the database.
So when we return the base case with original_file.value, we're returning the SyntaxNode part of the InFile. And scope_at_offset is called with this node.
Let me check if scope_at_offset can work with expansion files...
analyze_with_offset_no_infer needs to find the file ID from the node. If the node is from an expansion file, it might not be able to find the file ID.
Actually, I think Semantics can work with expansion files because they're tracked in the database. The parse_or_expand method returns the expansion with the correct file ID.
Let me look at how analyze_with_offset_no_infer works:
Actually, I think the issue is that scope_at_offset expects the node to be from a file that the Semantics knows about. Expansion files are known, but only if they've been expanded.
In the recursive expand_maybe_stop call, original_file is InFile<actual_expansion>. The actual_expansion is from sema.expand_macro_call(...), which returns an ExpandResult<InFile<SyntaxNode>> with the expansion's file ID.
So the expansion file IS tracked. When we return the base case with original_file.value, we're returning the SyntaxNode part. The file ID is in original_file.file_id.
But we're stripping the InFile wrapper! So the file ID is lost.
I introduced a new helper function is_in_token_tree_of_macro_call that only returns true if the token is inside a token tree that is a direct child of a macro call (i.e., inside the macro's input/arguments). Tokens that are part of the macro call's path are NOT considered to be "inside" the macro call for recursion purposes.
This allows the completion system to:
Stop recursion when the token is a macro call path (like bar in bar!())
Provide path completions at that position, including macro names