diff --git a/.github/instructions/rust-extractor.instructions.md b/.github/instructions/rust-extractor.instructions.md new file mode 100644 index 000000000000..c8f53418e410 --- /dev/null +++ b/.github/instructions/rust-extractor.instructions.md @@ -0,0 +1,4 @@ +--- +applyTo: "rust/extractor/src/translate/**/*.rs" +--- +Emit any syntax obtained from a rust-analyzer macro expansion API (`Semantics::expand_*` and similar) within `Translator::in_expansion`, otherwise its locations are silently wrong. Built-in derive expansions are the exception: they are located through `builtin_derive_span_map` instead. diff --git a/rust/extractor/src/translate/base.rs b/rust/extractor/src/translate/base.rs index f8fcb97785af..92f07e2628ac 100644 --- a/rust/extractor/src/translate/base.rs +++ b/rust/extractor/src/translate/base.rs @@ -20,7 +20,7 @@ use ra_ap_syntax::{ use ra_ap_syntax_bridge::{ DocCommentDesugarMode, syntax_node_to_token_tree, token_tree_to_syntax_node, }; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; impl Emission for Translator<'_> { @@ -139,6 +139,11 @@ pub struct Translator<'db> { /// synthesized syntax tree. Those nodes are not registered in the semantics cache, so /// locations are resolved through this map instead of `Semantics::original_range`. builtin_derive_span_map: Option, + /// Nesting depth of macro expansions being emitted. At depth 0 nodes belong to the file + /// being extracted, so their text range needs no mapping through `Semantics::original_range`. + expansion_depth: usize, + /// Attribute macro targets entered in `item_pre_emit`, to be exited in `item_post_emit`. + attribute_macro_targets: HashSet, } const UNKNOWN_LOCATION: (LineCol, LineCol) = @@ -167,6 +172,8 @@ impl<'db> Translator<'db> { parenthesized_expr_attrs: HashMap::new(), diagnostic_count: 0, builtin_derive_span_map: None, + expansion_depth: 0, + attribute_macro_targets: HashSet::new(), } } fn location(&self, range: TextRange) -> Option<(LineCol, LineCol)> { @@ -199,7 +206,9 @@ impl<'db> Translator<'db> { map_node_range_up_rooted(semantics.db, span_map, node.syntax().text_range())?; return (file_id == file_range.file_id).then_some(file_range.range); } - if let Some(semantics) = self.semantics.as_ref() { + if let Some(semantics) = self.semantics.as_ref() + && self.expansion_depth > 0 + { let file_range = semantics.original_range(node.syntax()); let file_id = self.file_id?; (file_id == file_range.file_id).then_some(file_range.range) @@ -394,6 +403,18 @@ impl<'db> Translator<'db> { } } + /// Runs `f`, which emits macro-expanded syntax. + /// + /// All emission of syntax obtained from `Semantics::expand_*` (or any other expansion API) must + /// go through this: `text_range_for_node` trusts nodes emitted outside of it to belong to the + /// extracted file, so an expansion emitted outside of it silently gets wrong locations. + fn in_expansion(&mut self, f: impl FnOnce(&mut Self) -> T) -> T { + self.expansion_depth += 1; + let ret = f(self); + self.expansion_depth -= 1; + ret + } + fn emit_expanded_as( &mut self, expand_to: ExpandTo, @@ -441,7 +462,9 @@ impl<'db> Translator<'db> { self.emit_macro_expansion_parse_errors(mcall, &expanded.value); let expand_to = ra_ap_hir_expand::ExpandTo::from_call_site(mcall); let kind = expanded.kind(); - if let Some(value) = self.emit_expanded_as(expand_to, expanded.value) { + if let Some(value) = + self.in_expansion(|this| this.emit_expanded_as(expand_to, expanded.value)) + { generated::MacroCall::emit_macro_call_expansion( label, value, @@ -661,6 +684,8 @@ impl<'db> Translator<'db> { // process that differently (in `extract_macro_call_expanded`) self.builtin_derive_span_map.is_none() && !matches!(node, ast::Item::MacroCall(_)) + // cheap syntactic pre-check: attribute macros need an attribute + && ast::attrs_including_inner(node).next().is_some() && self.semantics.is_some_and(|semantics| { let file = semantics.hir_file_for(node.syntax()); let node = InFile::new(file, node); @@ -686,7 +711,7 @@ impl<'db> Translator<'db> { ); } if let Some(items) = ast::MacroItems::cast(value) { - self.emit_macro_items(&items) + self.in_expansion(|this| this.emit_macro_items(&items)) } else { let message = "attribute or derive macro expansion cannot be cast to MacroItems".to_owned(); @@ -741,20 +766,15 @@ impl<'db> Translator<'db> { } } self.macro_context_depth += 1; + self.attribute_macro_targets.insert(node.syntax().clone()); None } pub(crate) fn item_post_emit(&mut self, node: &ast::Item, label: Label) { - if !self.is_attribute_macro_target(node) { + // `item_pre_emit` records the targets for which it incremented `macro_context_depth` + if !self.attribute_macro_targets.remove(node.syntax()) { return; } - // see `item_pre_emit`: - // if self.is_attribute_macro_target(node), then we either exited early with `Some(label)` - // and are not here, or we did self.macro_context_depth += 1 - assert!( - self.macro_context_depth > 0, - "macro_context_depth should be > 0 for an attribute macro target" - ); self.macro_context_depth -= 1; if let Some(expanded) = self.emit_attribute_macro_expansion(node) { generated::Item::emit_attribute_macro_expansion(label, expanded, &mut self.trap.writer); diff --git a/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/Cargo.lock b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/Cargo.lock new file mode 100644 index 000000000000..3ed3f289c886 --- /dev/null +++ b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/Cargo.lock @@ -0,0 +1,53 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "proc-macro2" +version = "1.0.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc_macro" +version = "0.0.1" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "syn" +version = "2.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4307e30089d6fd6aff212f2da3a1f9e32f3223b1f010fb09b7c95f90f3ca1e8" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "test" +version = "0.0.1" +dependencies = [ + "proc_macro", +] + +[[package]] +name = "unicode-ident" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" diff --git a/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/inner.rs b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/inner.rs new file mode 100644 index 000000000000..499be9af26f6 --- /dev/null +++ b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/inner.rs @@ -0,0 +1,5 @@ +mod m { + #![proc_macro::add_marker] + + pub fn f() {} +} diff --git a/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/options.yml b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/options.yml new file mode 100644 index 000000000000..63a7839453fd --- /dev/null +++ b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/options.yml @@ -0,0 +1,2 @@ +# custom inner attributes are nightly-only in rustc, but rust-analyzer expands them anyway +qltest_cargo_check: false diff --git a/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/proc_macro.rs b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/proc_macro.rs new file mode 100644 index 000000000000..5bbe58e0efd5 --- /dev/null +++ b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/proc_macro.rs @@ -0,0 +1,12 @@ +use proc_macro::TokenStream; +use quote::quote; + +#[proc_macro_attribute] +pub fn add_marker(_attr: TokenStream, item: TokenStream) -> TokenStream { + let item = syn::parse_macro_input!(item as syn::Item); + quote! { + #item + pub fn marker() {} + } + .into() +} diff --git a/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/test.expected b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/test.expected new file mode 100644 index 000000000000..6eef91a85fdc --- /dev/null +++ b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/test.expected @@ -0,0 +1,2 @@ +| inner.rs:1:1:5:1 | mod | 0 | inner.rs:1:1:5:1 | mod m | +| inner.rs:1:1:5:1 | mod | 1 | inner.rs:2:8:2:29 | fn marker | diff --git a/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/test.ql b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/test.ql new file mode 100644 index 000000000000..de9b38196dc3 --- /dev/null +++ b/rust/ql/test/extractor-tests/macro-expansion-inner-attribute/test.ql @@ -0,0 +1,5 @@ +import rust + +query predicate attribute_macros(Item i, int index, Item expanded) { + i.fromSource() and expanded = i.getAttributeMacroExpansion().getItem(index) +}