ISSUE DESCRIPTION Cannot complete macro path in macro <!-- Troubleshooting guide:…
- User
ISSUE DESCRIPTION
Cannot complete macro path in macro
rust-analyzer version: rust-analyzer 0.4.2897-standalone
rustc version: rustc 1.97.0-nightly (36ba2c771 2026-04-23)
editor or extension: Vim
code snippet to reproduce:
macro_rules! bar { () => (); } macro_rules! foo { ($i:ident) => { $i!() }; } fn main() { foo!(bar$0); }ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /rust-analyzer, current file: none) bash-$
- Assistant
I’ll first inspect the repository layout and search for completion tests involving macro invocations and macro metavariables. Then I’ll reproduce the missing completion in the most targeted existing test harness before tracing the completion context logic.
- Assistant
The shell interpreted
!in the search expression as history expansion, so I’ll rerun using single-quoted patterns and separately list the completion crate’s structure. - Assistant
ripgrepis unavailable in this environment. I’ll use recursivegrepand inspect the test module organization and completion context source directly. - Assistant
There are already expression-completion tests for an identifier metavariable expanded into a path, which is closely related. I’ll inspect those tests plus the macro descent/context analysis code that compares the real invocation with the invocation containing the synthetic completion identifier.
- Assistant
The nearby test confirms completion works when the metavariable becomes the qualifier of
$i::bar; this issue differs because$ibecomes the callee of a macro invocation ($i!()). I’ll inspect how the original and speculative syntax trees are built and how path context records an existing macro bang, then use the server’s LSP binary with a temporary file outside the repository if feasible to capture the current completion response without changing tests. - Assistant
The likely failure is now clear: expanding
foo!producesbar!()in the real tree andbarraCompletionMarker!()in the speculative tree. Recursive expansion recognizes both as macro calls, rejects them because their paths differ, and discards the otherwise useful outer expansion; completion then falls back to the opaque token tree offoo!.I’ll verify the control flow in the full
expand/expand_maybe_stopimplementation and inspect analogous “stop at this expansion” handling, especially for failed nested expansion and attribute macros. - Assistant
The recursion base case deliberately refuses to stop while the cursor is inside a macro call, but here the cursor is in that nested call’s name, which is exactly where recursion must stop: the speculative macro name cannot resolve until completion replaces it.
I’ll implement a narrow condition at the path-mismatch check: if removing the synthetic marker from the speculative macro path yields the real macro path, return the current outer expansion as the analysis point. Other mismatches remain rejected. Before editing, I’ll check available build artifacts and the exact syntax text APIs/style used nearby.
- Assistant
No prebuilt server is available, so a direct LSP reproduction would first require a full build. I’ll make the localized source change now, with a comment explaining why macro-name completion is a valid mismatch and why expansion must stop there.
- Assistant
The edit is in place and passes
git diff --check, but Cargo cannot run because rustup has no selected default toolchain. I’ll inspect the repository’s pinned Rust version and installed toolchains, select an already installed compatible toolchain if possible, then format and compile the affected crate. - Assistant
No Rust toolchain is installed. I’ll install the exact commit pinned by
rust-version; this is necessary to format, compile, and run the completion tests reliably. - Assistant
Rustup cannot install a toolchain by compiler commit hash directly. I’ll inspect repository setup documentation and CI scripts to determine how this pinned revision is mapped or downloaded, rather than guessing a potentially incompatible stable version.
- Assistant
CI uses the pinned value separately for cache invalidation but installs
nightlywith rustfmt for normal checks. I’ll install nightly with rustfmt and then run formatting and a targeted build/test. - Assistant
Nightly and rustfmt installed successfully despite rustup’s final environment warning. I’ll format the changed file, compile
ide-completion, and run the adjacent existing macro expansion completion test as an initial regression check. - Assistant
The change compiles and the closest existing test passes. To verify the exact report without adding or modifying repository tests, I’ll build the rust-analyzer server and drive it through a short external Python LSP client against a temporary standalone Rust file. I’ll record completion labels before and after the source change by temporarily compiling the parent revision’s source into a separate worktree only if needed; the expected current response must include
bar. - Assistant
The server is built. I’ll now create only temporary files under
/tmp(leaving the repository untouched), initialize rust-analyzer over LSP, open the exact snippet, request completion immediately afterbar, and print whether the returned labels containbar. - Assistant
The first LSP probe still returned no macro labels. This may be a synchronization issue (the request was sent before workspace loading completed), or the fix may not yet reach analysis. I’ll print all returned labels and server diagnostics/logs, and retry after rust-analyzer’s
experimental/serverStatusreports quiescence (or a brief wait) to distinguish those cases. - Assistant
Even after workspace loading, the result is empty, so the condition is not sufficient. I’ll capture the raw completion response and server stderr, then instrument the relevant expansion branch with temporary tracing output (removed before submission) if the LSP protocol itself is healthy.
- Assistant
The server returned
nullrather than an empty list, suggesting completion context construction failed. I’ll sanity-check the LSP harness by requesting completion for an ordinarybaexpression in the same file. If that succeeds, I’ll trace the macro-specific context path. - Assistant
The harness is valid: ordinary expression completion returns
bar!(…). Therefore macro context construction still fails. I’ll add temporaryeprintln!diagnostics around recursive expansion, especially the path mismatch and marker-stripping condition, rebuild incrementally, and rerun the exact snippet. These diagnostics will be removed once the actual failing branch is identified. - Assistant
The temporary instrumentation script did not alter the source because rustfmt had changed the closure layout, causing its exact-match assertion to fail. I’ll inspect the current block and insert diagnostics against its formatted form.
- Assistant
I’ll insert diagnostics using the formatted block, rebuild, and rerun.
- Assistant
The mismatch branch is never reached, so the failure occurs earlier—likely while pairing token-tree ancestors or before the outer
foo!expansion. I’ll add temporary diagnostics atexpand_and_analyze,expand, token-tree pairing, and successful outer expansion. This will identify the exact early return rather than broadening the production fix speculatively. - Assistant
Diagnostics show the outer call does expand, but its mapped real offset becomes
0and no token-tree ancestor exists there, while the speculative token isbarraCompletionMarker. This suggests the real expansion may already have recursively expandedbar!()to(), whereas the unresolved speculative macro remains a call.I’ll print both expansion texts at recursive entry and the mapped-token data. The correct fix may need to stop at the outer expansion before recursing whenever the mapped marker is itself in a macro path, rather than waiting for path comparison in the next recursion.
- Assistant
The expansion texts confirm the precise cause:
bar!()is preserved, but the cursor is in the macro call’s path, outside its token tree.expand()only descends through token-tree ancestors, returnsNone, and thenexpand_maybe_stop()refuses its normal base case solely because semantic analysis says the token is inside a macro call.The right fix is therefore in that base case: allow stopping when the token is specifically inside a macro call’s path, while continuing to recurse for tokens inside macro arguments. I’ll remove all temporary diagnostics and the unreachable mismatch workaround, then implement this syntactic path exception.
- Assistant
The production change is now minimal and targets the actual failing base-case decision. I’ll rebuild and rerun the exact external LSP reproduction. The expected label is rendered as
bar!(…), and because the invocation already has!(), the resulting completion edit should insert onlybarrather than duplicate punctuation. - Assistant
The exact reproduction now succeeds: completion returns the
barmacro in the expanded$i!()path. Since the existing bang changes macro rendering, its label is correctly justbar. I’ll inspect that item’s text edit to confirm it replaces only the sourcebartoken, then run the fullide-completiontest suite to cover macro arguments, nested expansions, and ordinary contexts. - Assistant
The exact completion edit is correct: it replaces source range
barwithbarand leaves the generated/existing!()untouched. All 732ide-completiontests pass.I’ll add a concise explanatory comment for the non-obvious base-case exception, reformat, run a final package check, and inspect the final diff/status for accidental files or debug output.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.