Skip to content

Commit 3643c37

Browse files
committed
Auto merge of #16183 - Veykril:expander, r=Veykril
internal: Cleanup Expander a bit
2 parents d2dacc0 + 9d24764 commit 3643c37

File tree

7 files changed

+68
-91
lines changed

7 files changed

+68
-91
lines changed

crates/hir-def/src/body/lower.rs

Lines changed: 19 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use either::Either;
88
use hir_expand::{
99
ast_id_map::AstIdMap,
1010
name::{name, AsName, Name},
11-
AstId, ExpandError, InFile,
11+
ExpandError, InFile,
1212
};
1313
use intern::Interned;
1414
use profile::Count;
@@ -66,7 +66,7 @@ pub(super) fn lower(
6666
krate,
6767
def_map: expander.module.def_map(db),
6868
source_map: BodySourceMap::default(),
69-
ast_id_map: db.ast_id_map(expander.current_file_id),
69+
ast_id_map: db.ast_id_map(expander.current_file_id()),
7070
body: Body {
7171
exprs: Default::default(),
7272
pats: Default::default(),
@@ -408,7 +408,7 @@ impl ExprCollector<'_> {
408408
ast::Expr::ParenExpr(e) => {
409409
let inner = self.collect_expr_opt(e.expr());
410410
// make the paren expr point to the inner expression as well
411-
let src = self.expander.to_source(syntax_ptr);
411+
let src = self.expander.in_file(syntax_ptr);
412412
self.source_map.expr_map.insert(src, inner);
413413
inner
414414
}
@@ -441,7 +441,7 @@ impl ExprCollector<'_> {
441441
Some(e) => self.collect_expr(e),
442442
None => self.missing_expr(),
443443
};
444-
let src = self.expander.to_source(AstPtr::new(&field));
444+
let src = self.expander.in_file(AstPtr::new(&field));
445445
self.source_map.field_map_back.insert(expr, src);
446446
Some(RecordLitField { name, expr })
447447
})
@@ -644,7 +644,7 @@ impl ExprCollector<'_> {
644644
Some(id) => {
645645
// Make the macro-call point to its expanded expression so we can query
646646
// semantics on syntax pointers to the macro
647-
let src = self.expander.to_source(syntax_ptr);
647+
let src = self.expander.in_file(syntax_ptr);
648648
self.source_map.expr_map.insert(src, id);
649649
id
650650
}
@@ -957,9 +957,9 @@ impl ExprCollector<'_> {
957957
T: ast::AstNode,
958958
{
959959
// File containing the macro call. Expansion errors will be attached here.
960-
let outer_file = self.expander.current_file_id;
960+
let outer_file = self.expander.current_file_id();
961961

962-
let macro_call_ptr = self.expander.to_source(syntax_ptr);
962+
let macro_call_ptr = self.expander.in_file(syntax_ptr);
963963
let module = self.expander.module.local_id;
964964

965965
let res = match self.def_map.modules[module]
@@ -1021,10 +1021,10 @@ impl ExprCollector<'_> {
10211021
Some((mark, expansion)) => {
10221022
// Keep collecting even with expansion errors so we can provide completions and
10231023
// other services in incomplete macro expressions.
1024-
self.source_map.expansions.insert(macro_call_ptr, self.expander.current_file_id);
1024+
self.source_map.expansions.insert(macro_call_ptr, self.expander.current_file_id());
10251025
let prev_ast_id_map = mem::replace(
10261026
&mut self.ast_id_map,
1027-
self.db.ast_id_map(self.expander.current_file_id),
1027+
self.db.ast_id_map(self.expander.current_file_id()),
10281028
);
10291029

10301030
if record_diagnostics {
@@ -1074,7 +1074,7 @@ impl ExprCollector<'_> {
10741074
Some(tail) => {
10751075
// Make the macro-call point to its expanded expression so we can query
10761076
// semantics on syntax pointers to the macro
1077-
let src = self.expander.to_source(syntax_ptr);
1077+
let src = self.expander.in_file(syntax_ptr);
10781078
self.source_map.expr_map.insert(src, tail);
10791079
Some(tail)
10801080
}
@@ -1148,7 +1148,7 @@ impl ExprCollector<'_> {
11481148

11491149
let block_id = if block_has_items {
11501150
let file_local_id = self.ast_id_map.ast_id(&block);
1151-
let ast_id = AstId::new(self.expander.current_file_id, file_local_id);
1151+
let ast_id = self.expander.in_file(file_local_id);
11521152
Some(self.db.intern_block(BlockLoc { ast_id, module: self.expander.module }))
11531153
} else {
11541154
None
@@ -1341,7 +1341,7 @@ impl ExprCollector<'_> {
13411341
let ast_pat = f.pat()?;
13421342
let pat = self.collect_pat(ast_pat, binding_list);
13431343
let name = f.field_name()?.as_name();
1344-
let src = self.expander.to_source(AstPtr::new(&f));
1344+
let src = self.expander.in_file(AstPtr::new(&f));
13451345
self.source_map.pat_field_map_back.insert(pat, src);
13461346
Some(RecordFieldPat { name, pat })
13471347
})
@@ -1399,7 +1399,7 @@ impl ExprCollector<'_> {
13991399
ast::Pat::MacroPat(mac) => match mac.macro_call() {
14001400
Some(call) => {
14011401
let macro_ptr = AstPtr::new(&call);
1402-
let src = self.expander.to_source(AstPtr::new(&Either::Left(pat)));
1402+
let src = self.expander.in_file(AstPtr::new(&Either::Left(pat)));
14031403
let pat =
14041404
self.collect_macro_call(call, macro_ptr, true, |this, expanded_pat| {
14051405
this.collect_pat_opt(expanded_pat, binding_list)
@@ -1480,10 +1480,7 @@ impl ExprCollector<'_> {
14801480
}
14811481

14821482
self.source_map.diagnostics.push(BodyDiagnostic::InactiveCode {
1483-
node: InFile::new(
1484-
self.expander.current_file_id,
1485-
SyntaxNodePtr::new(owner.syntax()),
1486-
),
1483+
node: self.expander.in_file(SyntaxNodePtr::new(owner.syntax())),
14871484
cfg,
14881485
opts: self.expander.cfg_options().clone(),
14891486
});
@@ -1522,10 +1519,7 @@ impl ExprCollector<'_> {
15221519
} else {
15231520
Err(BodyDiagnostic::UnreachableLabel {
15241521
name,
1525-
node: InFile::new(
1526-
self.expander.current_file_id,
1527-
AstPtr::new(&lifetime),
1528-
),
1522+
node: self.expander.in_file(AstPtr::new(&lifetime)),
15291523
})
15301524
};
15311525
}
@@ -1534,7 +1528,7 @@ impl ExprCollector<'_> {
15341528

15351529
Err(BodyDiagnostic::UndeclaredLabel {
15361530
name,
1537-
node: InFile::new(self.expander.current_file_id, AstPtr::new(&lifetime)),
1531+
node: self.expander.in_file(AstPtr::new(&lifetime)),
15381532
})
15391533
}
15401534

@@ -1998,7 +1992,7 @@ fn pat_literal_to_hir(lit: &ast::LiteralPat) -> Option<(Literal, ast::Literal)>
19981992

19991993
impl ExprCollector<'_> {
20001994
fn alloc_expr(&mut self, expr: Expr, ptr: ExprPtr) -> ExprId {
2001-
let src = self.expander.to_source(ptr);
1995+
let src = self.expander.in_file(ptr);
20021996
let id = self.body.exprs.alloc(expr);
20031997
self.source_map.expr_map_back.insert(id, src.clone());
20041998
self.source_map.expr_map.insert(src, id);
@@ -2026,7 +2020,7 @@ impl ExprCollector<'_> {
20262020
}
20272021

20282022
fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
2029-
let src = self.expander.to_source(ptr);
2023+
let src = self.expander.in_file(ptr);
20302024
let id = self.body.pats.alloc(pat);
20312025
self.source_map.pat_map_back.insert(id, src.clone());
20322026
self.source_map.pat_map.insert(src, id);
@@ -2041,7 +2035,7 @@ impl ExprCollector<'_> {
20412035
}
20422036

20432037
fn alloc_label(&mut self, label: Label, ptr: LabelPtr) -> LabelId {
2044-
let src = self.expander.to_source(ptr);
2038+
let src = self.expander.in_file(ptr);
20452039
let id = self.body.labels.alloc(label);
20462040
self.source_map.label_map_back.insert(id, src.clone());
20472041
self.source_map.label_map.insert(src, id);

crates/hir-def/src/db.rs

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -242,12 +242,6 @@ pub trait DefDatabase: InternDatabase + ExpandDatabase + Upcast<dyn ExpandDataba
242242
#[salsa::invoke(LangItems::crate_lang_items_query)]
243243
fn crate_lang_items(&self, krate: CrateId) -> Arc<LangItems>;
244244

245-
#[salsa::transparent]
246-
fn crate_limits(&self, crate_id: CrateId) -> CrateLimits;
247-
248-
#[salsa::transparent]
249-
fn recursion_limit(&self, crate_id: CrateId) -> u32;
250-
251245
fn crate_supports_no_std(&self, crate_id: CrateId) -> bool;
252246
}
253247

@@ -256,24 +250,6 @@ fn crate_def_map_wait(db: &dyn DefDatabase, krate: CrateId) -> Arc<DefMap> {
256250
db.crate_def_map_query(krate)
257251
}
258252

259-
pub struct CrateLimits {
260-
/// The maximum depth for potentially infinitely-recursive compile-time operations like macro expansion or auto-dereference.
261-
pub recursion_limit: u32,
262-
}
263-
264-
fn crate_limits(db: &dyn DefDatabase, crate_id: CrateId) -> CrateLimits {
265-
let def_map = db.crate_def_map(crate_id);
266-
267-
CrateLimits {
268-
// 128 is the default in rustc.
269-
recursion_limit: def_map.recursion_limit().unwrap_or(128),
270-
}
271-
}
272-
273-
fn recursion_limit(db: &dyn DefDatabase, crate_id: CrateId) -> u32 {
274-
db.crate_limits(crate_id).recursion_limit
275-
}
276-
277253
fn crate_supports_no_std(db: &dyn DefDatabase, crate_id: CrateId) -> bool {
278254
let file = db.crate_graph()[crate_id].root_file_id;
279255
let item_tree = db.file_item_tree(file.into());

crates/hir-def/src/expander.rs

Lines changed: 31 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use hir_expand::{
88
InFile, MacroCallId,
99
};
1010
use limit::Limit;
11-
use syntax::{ast, Parse, SyntaxNode};
11+
use syntax::{ast, Parse};
1212

1313
use crate::{
1414
attr::Attrs, db::DefDatabase, lower::LowerCtx, path::Path, AsMacroCall, MacroId, ModuleId,
@@ -20,7 +20,7 @@ pub struct Expander {
2020
cfg_options: CfgOptions,
2121
span_map: SpanMap,
2222
krate: CrateId,
23-
pub(crate) current_file_id: HirFileId,
23+
current_file_id: HirFileId,
2424
pub(crate) module: ModuleId,
2525
/// `recursion_depth == usize::MAX` indicates that the recursion limit has been reached.
2626
recursion_depth: u32,
@@ -29,12 +29,13 @@ pub struct Expander {
2929

3030
impl Expander {
3131
pub fn new(db: &dyn DefDatabase, current_file_id: HirFileId, module: ModuleId) -> Expander {
32-
let recursion_limit = db.recursion_limit(module.krate);
33-
#[cfg(not(test))]
34-
let recursion_limit = Limit::new(recursion_limit as usize);
35-
// Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
36-
#[cfg(test)]
37-
let recursion_limit = Limit::new(std::cmp::min(32, recursion_limit as usize));
32+
let recursion_limit = module.def_map(db).recursion_limit() as usize;
33+
let recursion_limit = Limit::new(if cfg!(test) {
34+
// Without this, `body::tests::your_stack_belongs_to_me` stack-overflows in debug
35+
std::cmp::min(32, recursion_limit)
36+
} else {
37+
recursion_limit
38+
});
3839
Expander {
3940
current_file_id,
4041
module,
@@ -56,7 +57,7 @@ impl Expander {
5657
let mut unresolved_macro_err = None;
5758

5859
let result = self.within_limit(db, |this| {
59-
let macro_call = InFile::new(this.current_file_id, &macro_call);
60+
let macro_call = this.in_file(&macro_call);
6061
match macro_call.as_call_id_with_errors(db.upcast(), this.module.krate(), |path| {
6162
resolver(path).map(|it| db.macro_def(it))
6263
}) {
@@ -83,17 +84,6 @@ impl Expander {
8384
self.within_limit(db, |_this| ExpandResult::ok(Some(call_id)))
8485
}
8586

86-
fn enter_expand_inner(
87-
db: &dyn DefDatabase,
88-
call_id: MacroCallId,
89-
error: Option<ExpandError>,
90-
) -> ExpandResult<Option<InFile<Parse<SyntaxNode>>>> {
91-
let macro_file = call_id.as_macro_file();
92-
let ExpandResult { value, err } = db.parse_macro_expansion(macro_file);
93-
94-
ExpandResult { value: Some(InFile::new(macro_file.into(), value.0)), err: error.or(err) }
95-
}
96-
9787
pub fn exit(&mut self, mut mark: Mark) {
9888
self.span_map = mark.span_map;
9989
self.current_file_id = mark.file_id;
@@ -113,7 +103,7 @@ impl Expander {
113103
LowerCtx::new(db, self.span_map.clone(), self.current_file_id)
114104
}
115105

116-
pub(crate) fn to_source<T>(&self, value: T) -> InFile<T> {
106+
pub(crate) fn in_file<T>(&self, value: T) -> InFile<T> {
117107
InFile { file_id: self.current_file_id, value }
118108
}
119109

@@ -164,26 +154,34 @@ impl Expander {
164154
return ExpandResult { value: None, err };
165155
};
166156

167-
let res = Self::enter_expand_inner(db, call_id, err);
168-
match res.err {
169-
// If proc-macro is disabled or unresolved, we want to expand to a missing expression
170-
// instead of an empty tree which might end up in an empty block.
171-
Some(ExpandError::UnresolvedProcMacro(_)) => res.map(|_| None),
172-
_ => res.map(|value| {
173-
value.and_then(|InFile { file_id, value }| {
174-
let parse = value.cast::<T>()?;
157+
let macro_file = call_id.as_macro_file();
158+
let res = db.parse_macro_expansion(macro_file);
159+
160+
let err = err.or(res.err);
161+
ExpandResult {
162+
value: match err {
163+
// If proc-macro is disabled or unresolved, we want to expand to a missing expression
164+
// instead of an empty tree which might end up in an empty block.
165+
Some(ExpandError::UnresolvedProcMacro(_)) => None,
166+
_ => (|| {
167+
let parse = res.value.0.cast::<T>()?;
175168

176169
self.recursion_depth += 1;
177-
let old_span_map = std::mem::replace(&mut self.span_map, db.span_map(file_id));
178-
let old_file_id = std::mem::replace(&mut self.current_file_id, file_id);
170+
let old_span_map = std::mem::replace(
171+
&mut self.span_map,
172+
SpanMap::ExpansionSpanMap(res.value.1),
173+
);
174+
let old_file_id =
175+
std::mem::replace(&mut self.current_file_id, macro_file.into());
179176
let mark = Mark {
180177
file_id: old_file_id,
181178
span_map: old_span_map,
182179
bomb: DropBomb::new("expansion mark dropped"),
183180
};
184181
Some((mark, parse))
185-
})
186-
}),
182+
})(),
183+
},
184+
err,
187185
}
188186
}
189187
}

crates/hir-def/src/nameres.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -626,8 +626,9 @@ impl DefMap {
626626
self.diagnostics.as_slice()
627627
}
628628

629-
pub fn recursion_limit(&self) -> Option<u32> {
630-
self.data.recursion_limit
629+
pub fn recursion_limit(&self) -> u32 {
630+
// 128 is the default in rustc
631+
self.data.recursion_limit.unwrap_or(128)
631632
}
632633
}
633634

crates/hir-def/src/resolver.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
use std::{fmt, hash::BuildHasherDefault};
33

44
use base_db::CrateId;
5-
use hir_expand::name::{name, Name};
5+
use hir_expand::{
6+
name::{name, Name},
7+
MacroDefId,
8+
};
69
use indexmap::IndexMap;
710
use intern::Interned;
811
use rustc_hash::FxHashSet;
@@ -406,6 +409,15 @@ impl Resolver {
406409
.take_macros_import()
407410
}
408411

412+
pub fn resolve_path_as_macro_def(
413+
&self,
414+
db: &dyn DefDatabase,
415+
path: &ModPath,
416+
expected_macro_kind: Option<MacroSubNs>,
417+
) -> Option<MacroDefId> {
418+
self.resolve_path_as_macro(db, path, expected_macro_kind).map(|(it, _)| db.macro_def(it))
419+
}
420+
409421
/// Returns a set of names available in the current scope.
410422
///
411423
/// Note that this is a somewhat fuzzy concept -- internally, the compiler

crates/hir/src/semantics.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -340,9 +340,7 @@ impl<'db> SemanticsImpl<'db> {
340340
let macro_call = InFile::new(file_id, actual_macro_call);
341341
let krate = resolver.krate();
342342
let macro_call_id = macro_call.as_call_id(self.db.upcast(), krate, |path| {
343-
resolver
344-
.resolve_path_as_macro(self.db.upcast(), &path, Some(MacroSubNs::Bang))
345-
.map(|(it, _)| self.db.macro_def(it))
343+
resolver.resolve_path_as_macro_def(self.db.upcast(), &path, Some(MacroSubNs::Bang))
346344
})?;
347345
hir_expand::db::expand_speculative(
348346
self.db.upcast(),

crates/hir/src/source_analyzer.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -770,9 +770,7 @@ impl SourceAnalyzer {
770770
) -> Option<MacroFileId> {
771771
let krate = self.resolver.krate();
772772
let macro_call_id = macro_call.as_call_id(db.upcast(), krate, |path| {
773-
self.resolver
774-
.resolve_path_as_macro(db.upcast(), &path, Some(MacroSubNs::Bang))
775-
.map(|(it, _)| db.macro_def(it))
773+
self.resolver.resolve_path_as_macro_def(db.upcast(), &path, Some(MacroSubNs::Bang))
776774
})?;
777775
// why the 64?
778776
Some(macro_call_id.as_macro_file()).filter(|it| it.expansion_level(db.upcast()) < 64)

0 commit comments

Comments
 (0)