Skip to content

Commit 924d30a

Browse files
committed
Auto merge of rust-lang#14585 - Veykril:macro-def-err, r=Veykril
Make `ExpandDatabase::parse_macro_expansion` and `ExpandDatabase::parse_or_expand` infallible
2 parents 697b335 + 4ea5d7f commit 924d30a

39 files changed

+222
-244
lines changed

crates/hir-def/src/attr.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -498,7 +498,7 @@ impl AttrsWithOwner {
498498
AttrDefId::FieldId(id) => {
499499
let map = db.fields_attrs_source_map(id.parent);
500500
let file_id = id.parent.file_id(db);
501-
let root = db.parse_or_expand(file_id).unwrap();
501+
let root = db.parse_or_expand(file_id);
502502
let owner = match &map[id.local_id] {
503503
Either::Left(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
504504
Either::Right(it) => ast::AnyHasAttrs::new(it.to_node(&root)),
@@ -514,7 +514,7 @@ impl AttrsWithOwner {
514514
AttrDefId::EnumVariantId(id) => {
515515
let map = db.variants_attrs_source_map(id.parent);
516516
let file_id = id.parent.lookup(db).id.file_id();
517-
let root = db.parse_or_expand(file_id).unwrap();
517+
let root = db.parse_or_expand(file_id);
518518
InFile::new(file_id, ast::AnyHasAttrs::new(map[id.local_id].to_node(&root)))
519519
}
520520
AttrDefId::StaticId(id) => id.lookup(db).source(db).map(ast::AnyHasAttrs::new),

crates/hir-def/src/body.rs

+2-20
Original file line numberDiff line numberDiff line change
@@ -174,30 +174,12 @@ impl Expander {
174174
fn enter_expand_inner(
175175
db: &dyn DefDatabase,
176176
call_id: MacroCallId,
177-
mut error: Option<ExpandError>,
177+
error: Option<ExpandError>,
178178
) -> ExpandResult<Option<InFile<Parse<SyntaxNode>>>> {
179179
let file_id = call_id.as_file();
180180
let ExpandResult { value, err } = db.parse_or_expand_with_err(file_id);
181181

182-
if error.is_none() {
183-
error = err;
184-
}
185-
186-
let parse = match value {
187-
Some(it) => it,
188-
None => {
189-
// Only `None` if the macro expansion produced no usable AST.
190-
if error.is_none() {
191-
tracing::warn!("no error despite `parse_or_expand` failing");
192-
}
193-
194-
return ExpandResult::only_err(error.unwrap_or_else(|| {
195-
ExpandError::Other("failed to parse macro invocation".into())
196-
}));
197-
}
198-
};
199-
200-
ExpandResult { value: Some(InFile::new(file_id, parse)), err: error }
182+
ExpandResult { value: Some(InFile::new(file_id, value)), err: error.or(err) }
201183
}
202184

203185
pub fn exit(&mut self, db: &dyn DefDatabase, mut mark: Mark) {

crates/hir-def/src/data.rs

+14-16
Original file line numberDiff line numberDiff line change
@@ -640,22 +640,20 @@ impl<'a> AssocItemCollector<'a> {
640640
AssocItem::MacroCall(call) => {
641641
let file_id = self.expander.current_file_id();
642642
let root = self.db.parse_or_expand(file_id);
643-
if let Some(root) = root {
644-
let call = &item_tree[call];
645-
646-
let ast_id_map = self.db.ast_id_map(file_id);
647-
let macro_call = ast_id_map.get(call.ast_id).to_node(&root);
648-
let _cx = stdx::panic_context::enter(format!(
649-
"collect_items MacroCall: {macro_call}"
650-
));
651-
if let Ok(res) =
652-
self.expander.enter_expand::<ast::MacroItems>(self.db, macro_call)
653-
{
654-
self.collect_macro_items(res, &|| hir_expand::MacroCallKind::FnLike {
655-
ast_id: InFile::new(file_id, call.ast_id),
656-
expand_to: hir_expand::ExpandTo::Items,
657-
});
658-
}
643+
let call = &item_tree[call];
644+
645+
let ast_id_map = self.db.ast_id_map(file_id);
646+
let macro_call = ast_id_map.get(call.ast_id).to_node(&root);
647+
let _cx = stdx::panic_context::enter(format!(
648+
"collect_items MacroCall: {macro_call}"
649+
));
650+
if let Ok(res) =
651+
self.expander.enter_expand::<ast::MacroItems>(self.db, macro_call)
652+
{
653+
self.collect_macro_items(res, &|| hir_expand::MacroCallKind::FnLike {
654+
ast_id: InFile::new(file_id, call.ast_id),
655+
expand_to: hir_expand::ExpandTo::Items,
656+
});
659657
}
660658
}
661659
}

crates/hir-def/src/item_tree.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,7 @@ pub struct ItemTree {
108108
impl ItemTree {
109109
pub(crate) fn file_item_tree_query(db: &dyn DefDatabase, file_id: HirFileId) -> Arc<ItemTree> {
110110
let _p = profile::span("file_item_tree_query").detail(|| format!("{file_id:?}"));
111-
let syntax = match db.parse_or_expand(file_id) {
112-
Some(node) => node,
113-
None => return Default::default(),
114-
};
111+
let syntax = db.parse_or_expand(file_id);
115112
if never!(syntax.kind() == SyntaxKind::ERROR, "{:?} from {:?} {}", file_id, syntax, syntax)
116113
{
117114
// FIXME: not 100% sure why these crop up, but return an empty tree to avoid a panic

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ m!(&k");
3333
"#,
3434
expect![[r#"
3535
macro_rules! m { ($i:literal) => {}; }
36-
/* error: Failed to lower macro args to token tree */"#]],
36+
/* error: invalid token tree */"#]],
3737
);
3838
}
3939

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ macro_rules! m1 { ($x:ident) => { ($x } }
9898
macro_rules! m2 { ($x:ident) => {} }
9999
100100
/* error: invalid macro definition: expected subtree */
101-
/* error: Failed to lower macro args to token tree */
101+
/* error: invalid token tree */
102102
"#]],
103103
)
104104
}

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

+24-25
Original file line numberDiff line numberDiff line change
@@ -151,34 +151,33 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
151151
if let Some(err) = exp.err {
152152
format_to!(expn_text, "/* error: {} */", err);
153153
}
154-
if let Some((parse, token_map)) = exp.value {
155-
if expect_errors {
156-
assert!(!parse.errors().is_empty(), "no parse errors in expansion");
157-
for e in parse.errors() {
158-
format_to!(expn_text, "/* parse error: {} */\n", e);
159-
}
160-
} else {
161-
assert!(
162-
parse.errors().is_empty(),
163-
"parse errors in expansion: \n{:#?}",
164-
parse.errors()
165-
);
154+
let (parse, token_map) = exp.value;
155+
if expect_errors {
156+
assert!(!parse.errors().is_empty(), "no parse errors in expansion");
157+
for e in parse.errors() {
158+
format_to!(expn_text, "/* parse error: {} */\n", e);
166159
}
167-
let pp = pretty_print_macro_expansion(
168-
parse.syntax_node(),
169-
show_token_ids.then_some(&*token_map),
160+
} else {
161+
assert!(
162+
parse.errors().is_empty(),
163+
"parse errors in expansion: \n{:#?}",
164+
parse.errors()
170165
);
171-
let indent = IndentLevel::from_node(call.syntax());
172-
let pp = reindent(indent, pp);
173-
format_to!(expn_text, "{}", pp);
166+
}
167+
let pp = pretty_print_macro_expansion(
168+
parse.syntax_node(),
169+
show_token_ids.then_some(&*token_map),
170+
);
171+
let indent = IndentLevel::from_node(call.syntax());
172+
let pp = reindent(indent, pp);
173+
format_to!(expn_text, "{}", pp);
174174

175-
if tree {
176-
let tree = format!("{:#?}", parse.syntax_node())
177-
.split_inclusive('\n')
178-
.map(|line| format!("// {line}"))
179-
.collect::<String>();
180-
format_to!(expn_text, "\n{}", tree)
181-
}
175+
if tree {
176+
let tree = format!("{:#?}", parse.syntax_node())
177+
.split_inclusive('\n')
178+
.map(|line| format!("// {line}"))
179+
.collect::<String>();
180+
format_to!(expn_text, "\n{}", tree)
182181
}
183182
let range = call.syntax().text_range();
184183
let range: Range<usize> = range.into();

crates/hir-def/src/nameres/collector.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1371,7 +1371,7 @@ impl DefCollector<'_> {
13711371

13721372
self.def_map.diagnostics.push(diag);
13731373
}
1374-
if let Some(errors) = value {
1374+
if let errors @ [_, ..] = &*value {
13751375
let loc: MacroCallLoc = self.db.lookup_intern_macro_call(macro_call_id);
13761376
let diag = DefDiagnostic::macro_expansion_parse_error(module_id, loc.kind, &errors);
13771377
self.def_map.diagnostics.push(diag);

crates/hir-def/src/nameres/tests/incremental.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ fn typing_inside_a_macro_should_not_invalidate_def_map() {
109109
}
110110

111111
#[test]
112-
fn typing_inside_a_function_should_not_invalidate_expansions() {
112+
fn typing_inside_a_function_should_not_invalidate_item_expansions() {
113113
let (mut db, pos) = TestDB::with_position(
114114
r#"
115115
//- /lib.rs
@@ -161,7 +161,7 @@ m!(Z);
161161
let n_recalculated_item_trees = events.iter().filter(|it| it.contains("item_tree")).count();
162162
assert_eq!(n_recalculated_item_trees, 1);
163163
let n_reparsed_macros =
164-
events.iter().filter(|it| it.contains("parse_macro_expansion")).count();
164+
events.iter().filter(|it| it.contains("parse_macro_expansion(")).count();
165165
assert_eq!(n_reparsed_macros, 0);
166166
}
167167
}

crates/hir-def/src/src.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ impl<N: ItemTreeNode> HasSource for AssocItemLoc<N> {
2020
fn source(&self, db: &dyn DefDatabase) -> InFile<N::Source> {
2121
let tree = self.id.item_tree(db);
2222
let ast_id_map = db.ast_id_map(self.id.file_id());
23-
let root = db.parse_or_expand(self.id.file_id()).unwrap();
23+
let root = db.parse_or_expand(self.id.file_id());
2424
let node = &tree[self.id.value];
2525

2626
InFile::new(self.id.file_id(), ast_id_map.get(node.ast_id()).to_node(&root))
@@ -33,7 +33,7 @@ impl<N: ItemTreeNode> HasSource for ItemLoc<N> {
3333
fn source(&self, db: &dyn DefDatabase) -> InFile<N::Source> {
3434
let tree = self.id.item_tree(db);
3535
let ast_id_map = db.ast_id_map(self.id.file_id());
36-
let root = db.parse_or_expand(self.id.file_id()).unwrap();
36+
let root = db.parse_or_expand(self.id.file_id());
3737
let node = &tree[self.id.value];
3838

3939
InFile::new(self.id.file_id(), ast_id_map.get(node.ast_id()).to_node(&root))
@@ -46,7 +46,7 @@ impl HasSource for Macro2Loc {
4646
fn source(&self, db: &dyn DefDatabase) -> InFile<Self::Value> {
4747
let tree = self.id.item_tree(db);
4848
let ast_id_map = db.ast_id_map(self.id.file_id());
49-
let root = db.parse_or_expand(self.id.file_id()).unwrap();
49+
let root = db.parse_or_expand(self.id.file_id());
5050
let node = &tree[self.id.value];
5151

5252
InFile::new(self.id.file_id(), ast_id_map.get(node.ast_id()).to_node(&root))
@@ -59,7 +59,7 @@ impl HasSource for MacroRulesLoc {
5959
fn source(&self, db: &dyn DefDatabase) -> InFile<Self::Value> {
6060
let tree = self.id.item_tree(db);
6161
let ast_id_map = db.ast_id_map(self.id.file_id());
62-
let root = db.parse_or_expand(self.id.file_id()).unwrap();
62+
let root = db.parse_or_expand(self.id.file_id());
6363
let node = &tree[self.id.value];
6464

6565
InFile::new(self.id.file_id(), ast_id_map.get(node.ast_id()).to_node(&root))
@@ -72,7 +72,7 @@ impl HasSource for ProcMacroLoc {
7272
fn source(&self, db: &dyn DefDatabase) -> InFile<Self::Value> {
7373
let tree = self.id.item_tree(db);
7474
let ast_id_map = db.ast_id_map(self.id.file_id());
75-
let root = db.parse_or_expand(self.id.file_id()).unwrap();
75+
let root = db.parse_or_expand(self.id.file_id());
7676
let node = &tree[self.id.value];
7777

7878
InFile::new(self.id.file_id(), ast_id_map.get(node.ast_id()).to_node(&root))

crates/hir-expand/src/builtin_derive_macro.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ fn parse_adt(tt: &tt::Subtree) -> Result<BasicAdtInfo, ExpandError> {
198198
fn expand_simple_derive(tt: &tt::Subtree, trait_path: tt::Subtree) -> ExpandResult<tt::Subtree> {
199199
let info = match parse_adt(tt) {
200200
Ok(info) => info,
201-
Err(e) => return ExpandResult::with_err(tt::Subtree::empty(), e),
201+
Err(e) => return ExpandResult::new(tt::Subtree::empty(), e),
202202
};
203203
let mut where_block = vec![];
204204
let (params, args): (Vec<_>, Vec<_>) = info

crates/hir-expand/src/builtin_fn_macro.rs

+6-9
Original file line numberDiff line numberDiff line change
@@ -249,10 +249,7 @@ fn format_args_expand(
249249
let mut args = parse_exprs_with_sep(tt, ',');
250250

251251
if args.is_empty() {
252-
return ExpandResult::with_err(
253-
tt::Subtree::empty(),
254-
mbe::ExpandError::NoMatchingRule.into(),
255-
);
252+
return ExpandResult::new(tt::Subtree::empty(), mbe::ExpandError::NoMatchingRule.into());
256253
}
257254
for arg in &mut args {
258255
// Remove `key =`.
@@ -575,7 +572,7 @@ fn include_expand(
575572
Ok((subtree, map, file_id)) => {
576573
ExpandResult::ok(ExpandedEager { subtree, included_file: Some((file_id, map)) })
577574
}
578-
Err(e) => ExpandResult::with_err(
575+
Err(e) => ExpandResult::new(
579576
ExpandedEager { subtree: tt::Subtree::empty(), included_file: None },
580577
e,
581578
),
@@ -588,7 +585,7 @@ fn include_bytes_expand(
588585
tt: &tt::Subtree,
589586
) -> ExpandResult<ExpandedEager> {
590587
if let Err(e) = parse_string(tt) {
591-
return ExpandResult::with_err(
588+
return ExpandResult::new(
592589
ExpandedEager { subtree: tt::Subtree::empty(), included_file: None },
593590
e,
594591
);
@@ -613,7 +610,7 @@ fn include_str_expand(
613610
let path = match parse_string(tt) {
614611
Ok(it) => it,
615612
Err(e) => {
616-
return ExpandResult::with_err(
613+
return ExpandResult::new(
617614
ExpandedEager { subtree: tt::Subtree::empty(), included_file: None },
618615
e,
619616
)
@@ -650,7 +647,7 @@ fn env_expand(
650647
let key = match parse_string(tt) {
651648
Ok(it) => it,
652649
Err(e) => {
653-
return ExpandResult::with_err(
650+
return ExpandResult::new(
654651
ExpandedEager { subtree: tt::Subtree::empty(), included_file: None },
655652
e,
656653
)
@@ -686,7 +683,7 @@ fn option_env_expand(
686683
let key = match parse_string(tt) {
687684
Ok(it) => it,
688685
Err(e) => {
689-
return ExpandResult::with_err(
686+
return ExpandResult::new(
690687
ExpandedEager { subtree: tt::Subtree::empty(), included_file: None },
691688
e,
692689
)

0 commit comments

Comments
 (0)