Skip to content

Commit a20b41e

Browse files
committed
Auto merge of #15367 - Veykril:eager-macro-inputs, r=Veykril
fix: Strip unused token ids from eager macro input token maps
2 parents 62dcf39 + d999d34 commit a20b41e

File tree

7 files changed

+82
-24
lines changed

7 files changed

+82
-24
lines changed

crates/hir-def/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1160,7 +1160,7 @@ fn macro_call_as_call_id_(
11601160
let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db));
11611161
expand_eager_macro_input(db, krate, macro_call, def, &|path| {
11621162
resolver(path).filter(MacroDefId::is_fn_like)
1163-
})?
1163+
})
11641164
}
11651165
_ if def.is_fn_like() => ExpandResult {
11661166
value: Some(def.as_lazy_macro(

crates/hir-def/src/macro_expansion_tests/mbe.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,30 @@ fn#19 main#20(#21)#21 {#22
9999
);
100100
}
101101

102+
#[test]
103+
fn eager_expands_with_unresolved_within() {
104+
check(
105+
r#"
106+
#[rustc_builtin_macro]
107+
#[macro_export]
108+
macro_rules! format_args {}
109+
110+
fn main(foo: ()) {
111+
format_args!("{} {} {}", format_args!("{}", 0), foo, identity!(10), "bar")
112+
}
113+
"#,
114+
expect![[r##"
115+
#[rustc_builtin_macro]
116+
#[macro_export]
117+
macro_rules! format_args {}
118+
119+
fn main(foo: ()) {
120+
/* error: unresolved macro identity */::core::fmt::Arguments::new_v1(&["", " ", " ", ], &[::core::fmt::ArgumentV1::new(&(::core::fmt::Arguments::new_v1(&["", ], &[::core::fmt::ArgumentV1::new(&(0), ::core::fmt::Display::fmt), ])), ::core::fmt::Display::fmt), ::core::fmt::ArgumentV1::new(&(foo), ::core::fmt::Display::fmt), ::core::fmt::ArgumentV1::new(&(identity!(10)), ::core::fmt::Display::fmt), ])
121+
}
122+
"##]],
123+
);
124+
}
125+
102126
#[test]
103127
fn token_mapping_eager() {
104128
check(

crates/hir-expand/src/eager.rs

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
//!
2020
//! See the full discussion : <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Eager.20expansion.20of.20built-in.20macros>
2121
use base_db::CrateId;
22-
use rustc_hash::FxHashMap;
22+
use rustc_hash::{FxHashMap, FxHashSet};
2323
use syntax::{ted, Parse, SyntaxNode, TextRange, TextSize, WalkEvent};
2424
use triomphe::Arc;
2525

@@ -29,7 +29,7 @@ use crate::{
2929
hygiene::Hygiene,
3030
mod_path::ModPath,
3131
EagerCallInfo, ExpandError, ExpandResult, ExpandTo, InFile, MacroCallId, MacroCallKind,
32-
MacroCallLoc, MacroDefId, MacroDefKind, UnresolvedMacro,
32+
MacroCallLoc, MacroDefId, MacroDefKind,
3333
};
3434

3535
pub fn expand_eager_macro_input(
@@ -38,7 +38,7 @@ pub fn expand_eager_macro_input(
3838
macro_call: InFile<ast::MacroCall>,
3939
def: MacroDefId,
4040
resolver: &dyn Fn(ModPath) -> Option<MacroDefId>,
41-
) -> Result<ExpandResult<Option<MacroCallId>>, UnresolvedMacro> {
41+
) -> ExpandResult<Option<MacroCallId>> {
4242
let ast_map = db.ast_id_map(macro_call.file_id);
4343
// the expansion which the ast id map is built upon has no whitespace, so the offsets are wrong as macro_call is from the token tree that has whitespace!
4444
let call_id = InFile::new(macro_call.file_id, ast_map.ast_id(&macro_call.value));
@@ -71,22 +71,23 @@ pub fn expand_eager_macro_input(
7171
InFile::new(arg_id.as_file(), arg_exp.syntax_node()),
7272
krate,
7373
resolver,
74-
)?
74+
)
7575
};
7676
let err = parse_err.or(err);
7777

7878
let Some((expanded_eager_input, mapping)) = expanded_eager_input else {
79-
return Ok(ExpandResult { value: None, err });
79+
return ExpandResult { value: None, err };
8080
};
8181

8282
let (mut subtree, expanded_eager_input_token_map) =
8383
mbe::syntax_node_to_token_tree(&expanded_eager_input);
8484

8585
let og_tmap = if let Some(tt) = macro_call.value.token_tree() {
86-
let og_tmap = mbe::syntax_node_to_token_map(tt.syntax());
86+
let mut ids_used = FxHashSet::default();
87+
let mut og_tmap = mbe::syntax_node_to_token_map(tt.syntax());
8788
// The tokenmap and ids of subtree point into the expanded syntax node, but that is inaccessible from the outside
8889
// so we need to remap them to the original input of the eager macro.
89-
subtree.visit_ids(&|id| {
90+
subtree.visit_ids(&mut |id| {
9091
// Note: we discard all token ids of braces and the like here, but that's not too bad and only a temporary fix
9192

9293
if let Some(range) = expanded_eager_input_token_map
@@ -97,13 +98,15 @@ pub fn expand_eager_macro_input(
9798
// remap from eager input expansion to original eager input
9899
if let Some(&og_range) = ws_mapping.get(og_range) {
99100
if let Some(og_token) = og_tmap.token_by_range(og_range) {
101+
ids_used.insert(og_token);
100102
return og_token;
101103
}
102104
}
103105
}
104106
}
105107
tt::TokenId::UNSPECIFIED
106108
});
109+
og_tmap.filter(|id| ids_used.contains(&id));
107110
og_tmap
108111
} else {
109112
Default::default()
@@ -121,7 +124,7 @@ pub fn expand_eager_macro_input(
121124
kind: MacroCallKind::FnLike { ast_id: call_id, expand_to },
122125
};
123126

124-
Ok(ExpandResult { value: Some(db.intern_macro_call(loc)), err })
127+
ExpandResult { value: Some(db.intern_macro_call(loc)), err }
125128
}
126129

127130
fn lazy_expand(
@@ -147,13 +150,13 @@ fn eager_macro_recur(
147150
curr: InFile<SyntaxNode>,
148151
krate: CrateId,
149152
macro_resolver: &dyn Fn(ModPath) -> Option<MacroDefId>,
150-
) -> Result<ExpandResult<Option<(SyntaxNode, FxHashMap<TextRange, TextRange>)>>, UnresolvedMacro> {
153+
) -> ExpandResult<Option<(SyntaxNode, FxHashMap<TextRange, TextRange>)>> {
151154
let original = curr.value.clone_for_update();
152155
let mut mapping = FxHashMap::default();
153156

154157
let mut replacements = Vec::new();
155158

156-
// Note: We only report a single error inside of eager expansions
159+
// FIXME: We only report a single error inside of eager expansions
157160
let mut error = None;
158161
let mut offset = 0i32;
159162
let apply_offset = |it: TextSize, offset: i32| {
@@ -184,24 +187,28 @@ fn eager_macro_recur(
184187
}
185188
};
186189
let def = match call.path().and_then(|path| ModPath::from_src(db, path, hygiene)) {
187-
Some(path) => macro_resolver(path.clone()).ok_or(UnresolvedMacro { path })?,
190+
Some(path) => match macro_resolver(path.clone()) {
191+
Some(def) => def,
192+
None => {
193+
error =
194+
Some(ExpandError::other(format!("unresolved macro {}", path.display(db))));
195+
continue;
196+
}
197+
},
188198
None => {
189199
error = Some(ExpandError::other("malformed macro invocation"));
190200
continue;
191201
}
192202
};
193203
let ExpandResult { value, err } = match def.kind {
194204
MacroDefKind::BuiltInEager(..) => {
195-
let ExpandResult { value, err } = match expand_eager_macro_input(
205+
let ExpandResult { value, err } = expand_eager_macro_input(
196206
db,
197207
krate,
198208
curr.with_value(call.clone()),
199209
def,
200210
macro_resolver,
201-
) {
202-
Ok(it) => it,
203-
Err(err) => return Err(err),
204-
};
211+
);
205212
match value {
206213
Some(call_id) => {
207214
let ExpandResult { value, err: err2 } =
@@ -251,7 +258,7 @@ fn eager_macro_recur(
251258
parse.as_ref().map(|it| it.syntax_node()),
252259
krate,
253260
macro_resolver,
254-
)?;
261+
);
255262
let err = err.or(error);
256263

257264
if let Some(tt) = call.token_tree() {
@@ -281,7 +288,7 @@ fn eager_macro_recur(
281288
}
282289
// check if the whole original syntax is replaced
283290
if call.syntax() == &original {
284-
return Ok(ExpandResult { value: value.zip(Some(mapping)), err: error });
291+
return ExpandResult { value: value.zip(Some(mapping)), err: error };
285292
}
286293

287294
if let Some(insert) = value {
@@ -292,5 +299,5 @@ fn eager_macro_recur(
292299
}
293300

294301
replacements.into_iter().rev().for_each(|(old, new)| ted::replace(old.syntax(), new));
295-
Ok(ExpandResult { value: Some((original, mapping)), err: error })
302+
ExpandResult { value: Some((original, mapping)), err: error }
296303
}

crates/ide/src/syntax_highlighting/test_data/highlight_macros.html

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,18 @@
9090
<span class="brace">}</span>
9191
<span class="brace">}</span>
9292

93+
<span class="attribute_bracket attribute">#</span><span class="attribute_bracket attribute">[</span><span class="builtin_attr attribute library">rustc_builtin_macro</span><span class="attribute_bracket attribute">]</span>
94+
<span class="keyword">macro_rules</span><span class="macro_bang">!</span> <span class="macro declaration">concat</span> <span class="brace">{</span><span class="brace">}</span>
95+
<span class="attribute_bracket attribute">#</span><span class="attribute_bracket attribute">[</span><span class="builtin_attr attribute library">rustc_builtin_macro</span><span class="attribute_bracket attribute">]</span>
96+
<span class="keyword">macro_rules</span><span class="macro_bang">!</span> <span class="macro declaration">include</span> <span class="brace">{</span><span class="brace">}</span>
97+
<span class="attribute_bracket attribute">#</span><span class="attribute_bracket attribute">[</span><span class="builtin_attr attribute library">rustc_builtin_macro</span><span class="attribute_bracket attribute">]</span>
98+
<span class="keyword">macro_rules</span><span class="macro_bang">!</span> <span class="macro declaration">format_args</span> <span class="brace">{</span><span class="brace">}</span>
99+
100+
<span class="macro">include</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="none macro">concat</span><span class="punctuation macro">!</span><span class="parenthesis macro">(</span><span class="string_literal macro">"foo/"</span><span class="comma macro">,</span> <span class="string_literal macro">"foo.rs"</span><span class="parenthesis macro">)</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
101+
93102
<span class="keyword">fn</span> <span class="function declaration">main</span><span class="parenthesis">(</span><span class="parenthesis">)</span> <span class="brace">{</span>
94-
<span class="unresolved_reference">println</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="string_literal macro">"Hello, {}!"</span><span class="comma macro">,</span> <span class="numeric_literal macro">92</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
103+
<span class="macro">format_args</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="string_literal macro">"Hello, </span><span class="format_specifier">{</span><span class="format_specifier">}</span><span class="string_literal macro">!"</span><span class="comma macro">,</span> <span class="numeric_literal macro">92</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
95104
<span class="macro">dont_color_me_braces</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
96105
<span class="macro">noop</span><span class="macro_bang">!</span><span class="parenthesis macro">(</span><span class="macro macro">noop</span><span class="macro_bang macro">!</span><span class="parenthesis macro">(</span><span class="numeric_literal macro">1</span><span class="parenthesis macro">)</span><span class="parenthesis macro">)</span><span class="semicolon">;</span>
97-
<span class="brace">}</span></code></pre>
106+
<span class="brace">}</span>
107+
</code></pre>

crates/ide/src/syntax_highlighting/tests.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ fn macros() {
4848
check_highlighting(
4949
r#"
5050
//- proc_macros: mirror
51+
//- /lib.rs crate:lib
5152
proc_macros::mirror! {
5253
{
5354
,i32 :x pub
@@ -95,11 +96,23 @@ macro without_args {
9596
}
9697
}
9798
99+
#[rustc_builtin_macro]
100+
macro_rules! concat {}
101+
#[rustc_builtin_macro]
102+
macro_rules! include {}
103+
#[rustc_builtin_macro]
104+
macro_rules! format_args {}
105+
106+
include!(concat!("foo/", "foo.rs"));
107+
98108
fn main() {
99-
println!("Hello, {}!", 92);
109+
format_args!("Hello, {}!", 92);
100110
dont_color_me_braces!();
101111
noop!(noop!(1));
102112
}
113+
//- /foo/foo.rs crate:foo
114+
mod foo {}
115+
use self::foo as bar;
103116
"#,
104117
expect_file!["./test_data/highlight_macros.html"],
105118
false,

crates/mbe/src/token_map.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,4 +117,8 @@ impl TokenMap {
117117
TokenTextRange::Delimiter(_) => None,
118118
})
119119
}
120+
121+
pub fn filter(&mut self, id: impl Fn(tt::TokenId) -> bool) {
122+
self.entries.retain(|&(tid, _)| id(tid));
123+
}
120124
}

crates/tt/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ pub mod token_id {
7070
}
7171

7272
impl Subtree {
73-
pub fn visit_ids(&mut self, f: &impl Fn(TokenId) -> TokenId) {
73+
pub fn visit_ids(&mut self, f: &mut impl FnMut(TokenId) -> TokenId) {
7474
self.delimiter.open = f(self.delimiter.open);
7575
self.delimiter.close = f(self.delimiter.close);
7676
self.token_trees.iter_mut().for_each(|tt| match tt {

0 commit comments

Comments
 (0)