Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/instructions/rust-extractor.instructions.md
Original file line number Diff line number Diff line change
@@ -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.
44 changes: 32 additions & 12 deletions rust/extractor/src/translate/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ast::Item> for Translator<'_> {
Expand Down Expand Up @@ -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<ExpansionSpanMap>,
/// 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<SyntaxNode>,
}

const UNKNOWN_LOCATION: (LineCol, LineCol) =
Expand Down Expand Up @@ -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)> {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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<T>(&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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand All @@ -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();
Expand Down Expand Up @@ -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<generated::Item>) {
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);
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod m {
#![proc_macro::add_marker]

pub fn f() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# custom inner attributes are nightly-only in rustc, but rust-analyzer expands them anyway
qltest_cargo_check: false
Original file line number Diff line number Diff line change
@@ -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()
}
Original file line number Diff line number Diff line change
@@ -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 |
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import rust

query predicate attribute_macros(Item i, int index, Item expanded) {
i.fromSource() and expanded = i.getAttributeMacroExpansion().getItem(index)
}
Loading