Skip to content

Commit 7697b29

Browse files
authored
Rollup merge of rust-lang#62476 - petrochenkov:expref, r=matthewjasper
Continue refactoring macro expansion and resolution This PR continues the work started in rust-lang#62042. It contains a set of more or less related refactorings with the general goal of making things simpler and more orthogonal. Along the way most of the issues uncovered in rust-lang#62086 are fixed. The PR is better read in per-commit fashion with whitespace changes ignored. I tried to leave some more detailed commit messages describing the motivation behind the individual changes. Fixes rust-lang#44692 Fixes rust-lang#52363 Unblocks rust-lang#62086 r? @matthewjasper
2 parents e07df9c + e86e5cb commit 7697b29

File tree

82 files changed

+1116
-1034
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

82 files changed

+1116
-1034
lines changed

src/doc/unstable-book/src/language-features/on-unimplemented.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,8 @@ application of these fields based on a variety of attributes when using
9898
`crate_local`) or matching against a particular method. Currently used
9999
for `try`.
100100
- `from_desugaring`: usable both as boolean (whether the flag is present)
101-
or matching against a particular desugaring.
101+
or matching against a particular desugaring. The desugaring is identified
102+
with its variant name in the `DesugaringKind` enum.
102103

103104
For example, the `Iterator` trait can be annotated in the following way:
104105

src/libcore/macros.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1244,19 +1244,22 @@ mod builtin {
12441244

12451245
/// Attribute macro applied to a function to turn it into a unit test.
12461246
#[stable(feature = "rust1", since = "1.0.0")]
1247+
#[allow_internal_unstable(test, rustc_attrs)]
12471248
#[rustc_builtin_macro]
12481249
#[rustc_macro_transparency = "semitransparent"]
12491250
pub macro test($item:item) { /* compiler built-in */ }
12501251

12511252
/// Attribute macro applied to a function to turn it into a benchmark test.
12521253
#[stable(feature = "rust1", since = "1.0.0")]
1254+
#[allow_internal_unstable(test, rustc_attrs)]
12531255
#[rustc_builtin_macro]
12541256
#[rustc_macro_transparency = "semitransparent"]
12551257
pub macro bench($item:item) { /* compiler built-in */ }
12561258

12571259
/// An implementation detail of the `#[test]` and `#[bench]` macros.
12581260
#[unstable(feature = "custom_test_frameworks", issue = "50297",
12591261
reason = "custom test frameworks are an unstable feature")]
1262+
#[allow_internal_unstable(test, rustc_attrs)]
12601263
#[rustc_builtin_macro]
12611264
#[rustc_macro_transparency = "semitransparent"]
12621265
pub macro test_case($item:item) { /* compiler built-in */ }

src/libcore/ops/try.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@
88
#[rustc_on_unimplemented(
99
on(all(
1010
any(from_method="from_error", from_method="from_ok"),
11-
from_desugaring="?"),
11+
from_desugaring="QuestionMark"),
1212
message="the `?` operator can only be used in a \
1313
function that returns `Result` or `Option` \
1414
(or another type that implements `{Try}`)",
1515
label="cannot use the `?` operator in a function that returns `{Self}`"),
16-
on(all(from_method="into_result", from_desugaring="?"),
16+
on(all(from_method="into_result", from_desugaring="QuestionMark"),
1717
message="the `?` operator can only be applied to values \
1818
that implement `{Try}`",
1919
label="the `?` operator cannot be applied to type `{Self}`")

src/librustc/hir/lowering.rs

+23-22
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,9 @@ use syntax::attr;
6060
use syntax::ast;
6161
use syntax::ast::*;
6262
use syntax::errors;
63-
use syntax::ext::hygiene::{Mark, SyntaxContext};
63+
use syntax::ext::hygiene::Mark;
6464
use syntax::print::pprust;
65-
use syntax::source_map::{self, respan, ExpnInfo, CompilerDesugaringKind, Spanned};
66-
use syntax::source_map::CompilerDesugaringKind::CondTemporary;
65+
use syntax::source_map::{respan, ExpnInfo, ExpnKind, DesugaringKind, Spanned};
6766
use syntax::std_inject;
6867
use syntax::symbol::{kw, sym, Symbol};
6968
use syntax::tokenstream::{TokenStream, TokenTree};
@@ -872,17 +871,15 @@ impl<'a> LoweringContext<'a> {
872871
/// allowed inside this span.
873872
fn mark_span_with_reason(
874873
&self,
875-
reason: CompilerDesugaringKind,
874+
reason: DesugaringKind,
876875
span: Span,
877876
allow_internal_unstable: Option<Lrc<[Symbol]>>,
878877
) -> Span {
879-
let mark = Mark::fresh(Mark::root());
880-
mark.set_expn_info(ExpnInfo {
881-
def_site: Some(span),
878+
span.fresh_expansion(Mark::root(), ExpnInfo {
879+
def_site: span,
882880
allow_internal_unstable,
883-
..ExpnInfo::default(source_map::CompilerDesugaring(reason), span, self.sess.edition())
884-
});
885-
span.with_ctxt(SyntaxContext::empty().apply_mark(mark))
881+
..ExpnInfo::default(ExpnKind::Desugaring(reason), span, self.sess.edition())
882+
})
886883
}
887884

888885
fn with_anonymous_lifetime_mode<R>(
@@ -1188,7 +1185,7 @@ impl<'a> LoweringContext<'a> {
11881185
};
11891186

11901187
let unstable_span = self.mark_span_with_reason(
1191-
CompilerDesugaringKind::Async,
1188+
DesugaringKind::Async,
11921189
span,
11931190
self.allow_gen_future.clone(),
11941191
);
@@ -1733,7 +1730,7 @@ impl<'a> LoweringContext<'a> {
17331730
// Not tracking it makes lints in rustc and clippy very fragile, as
17341731
// frequently opened issues show.
17351732
let exist_ty_span = self.mark_span_with_reason(
1736-
CompilerDesugaringKind::ExistentialType,
1733+
DesugaringKind::ExistentialType,
17371734
span,
17381735
None,
17391736
);
@@ -2603,7 +2600,7 @@ impl<'a> LoweringContext<'a> {
26032600
let span = output.span();
26042601

26052602
let exist_ty_span = self.mark_span_with_reason(
2606-
CompilerDesugaringKind::Async,
2603+
DesugaringKind::Async,
26072604
span,
26082605
None,
26092606
);
@@ -3275,7 +3272,7 @@ impl<'a> LoweringContext<'a> {
32753272
};
32763273

32773274
let desugared_span =
3278-
this.mark_span_with_reason(CompilerDesugaringKind::Async, span, None);
3275+
this.mark_span_with_reason(DesugaringKind::Async, span, None);
32793276

32803277
// Construct an argument representing `__argN: <ty>` to replace the argument of the
32813278
// async function.
@@ -4410,7 +4407,9 @@ impl<'a> LoweringContext<'a> {
44104407
_ => {
44114408
// Lower condition:
44124409
let cond = self.lower_expr(cond);
4413-
let span_block = self.mark_span_with_reason(CondTemporary, cond.span, None);
4410+
let span_block = self.mark_span_with_reason(
4411+
DesugaringKind::CondTemporary, cond.span, None
4412+
);
44144413
// Wrap in a construct equivalent to `{ let _t = $cond; _t }`
44154414
// to preserve drop semantics since `if cond { ... }` does not
44164415
// let temporaries live outside of `cond`.
@@ -4469,7 +4468,9 @@ impl<'a> LoweringContext<'a> {
44694468

44704469
// Lower condition:
44714470
let cond = this.with_loop_condition_scope(|this| this.lower_expr(cond));
4472-
let span_block = this.mark_span_with_reason(CondTemporary, cond.span, None);
4471+
let span_block = this.mark_span_with_reason(
4472+
DesugaringKind::CondTemporary, cond.span, None
4473+
);
44734474
// Wrap in a construct equivalent to `{ let _t = $cond; _t }`
44744475
// to preserve drop semantics since `while cond { ... }` does not
44754476
// let temporaries live outside of `cond`.
@@ -4508,7 +4509,7 @@ impl<'a> LoweringContext<'a> {
45084509
ExprKind::TryBlock(ref body) => {
45094510
self.with_catch_scope(body.id, |this| {
45104511
let unstable_span = this.mark_span_with_reason(
4511-
CompilerDesugaringKind::TryBlock,
4512+
DesugaringKind::TryBlock,
45124513
body.span,
45134514
this.allow_try_trait.clone(),
45144515
);
@@ -4836,7 +4837,7 @@ impl<'a> LoweringContext<'a> {
48364837
let mut head = self.lower_expr(head);
48374838
let head_sp = head.span;
48384839
let desugared_span = self.mark_span_with_reason(
4839-
CompilerDesugaringKind::ForLoop,
4840+
DesugaringKind::ForLoop,
48404841
head_sp,
48414842
None,
48424843
);
@@ -4990,13 +4991,13 @@ impl<'a> LoweringContext<'a> {
49904991
// }
49914992

49924993
let unstable_span = self.mark_span_with_reason(
4993-
CompilerDesugaringKind::QuestionMark,
4994+
DesugaringKind::QuestionMark,
49944995
e.span,
49954996
self.allow_try_trait.clone(),
49964997
);
49974998
let try_span = self.sess.source_map().end_point(e.span);
49984999
let try_span = self.mark_span_with_reason(
4999-
CompilerDesugaringKind::QuestionMark,
5000+
DesugaringKind::QuestionMark,
50005001
try_span,
50015002
self.allow_try_trait.clone(),
50025003
);
@@ -5811,12 +5812,12 @@ impl<'a> LoweringContext<'a> {
58115812
}
58125813
}
58135814
let span = self.mark_span_with_reason(
5814-
CompilerDesugaringKind::Await,
5815+
DesugaringKind::Await,
58155816
await_span,
58165817
None,
58175818
);
58185819
let gen_future_span = self.mark_span_with_reason(
5819-
CompilerDesugaringKind::Await,
5820+
DesugaringKind::Await,
58205821
await_span,
58215822
self.allow_gen_future.clone(),
58225823
);

src/librustc/hir/map/def_collector.rs

+19-58
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use crate::hir::map::definitions::*;
2-
use crate::hir::def_id::{CRATE_DEF_INDEX, DefIndex};
3-
use crate::session::CrateDisambiguator;
2+
use crate::hir::def_id::DefIndex;
43

54
use syntax::ast::*;
65
use syntax::ext::hygiene::Mark;
@@ -12,51 +11,30 @@ use syntax_pos::Span;
1211
/// Creates `DefId`s for nodes in the AST.
1312
pub struct DefCollector<'a> {
1413
definitions: &'a mut Definitions,
15-
parent_def: Option<DefIndex>,
14+
parent_def: DefIndex,
1615
expansion: Mark,
17-
pub visit_macro_invoc: Option<&'a mut dyn FnMut(MacroInvocationData)>,
18-
}
19-
20-
pub struct MacroInvocationData {
21-
pub mark: Mark,
22-
pub def_index: DefIndex,
2316
}
2417

2518
impl<'a> DefCollector<'a> {
2619
pub fn new(definitions: &'a mut Definitions, expansion: Mark) -> Self {
27-
DefCollector {
28-
definitions,
29-
expansion,
30-
parent_def: None,
31-
visit_macro_invoc: None,
32-
}
33-
}
34-
35-
pub fn collect_root(&mut self,
36-
crate_name: &str,
37-
crate_disambiguator: CrateDisambiguator) {
38-
let root = self.definitions.create_root_def(crate_name,
39-
crate_disambiguator);
40-
assert_eq!(root, CRATE_DEF_INDEX);
41-
self.parent_def = Some(root);
20+
let parent_def = definitions.invocation_parent(expansion);
21+
DefCollector { definitions, parent_def, expansion }
4222
}
4323

4424
fn create_def(&mut self,
4525
node_id: NodeId,
4626
data: DefPathData,
4727
span: Span)
4828
-> DefIndex {
49-
let parent_def = self.parent_def.unwrap();
29+
let parent_def = self.parent_def;
5030
debug!("create_def(node_id={:?}, data={:?}, parent_def={:?})", node_id, data, parent_def);
51-
self.definitions
52-
.create_def_with_parent(parent_def, node_id, data, self.expansion, span)
31+
self.definitions.create_def_with_parent(parent_def, node_id, data, self.expansion, span)
5332
}
5433

5534
pub fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: DefIndex, f: F) {
56-
let parent = self.parent_def;
57-
self.parent_def = Some(parent_def);
35+
let orig_parent_def = std::mem::replace(&mut self.parent_def, parent_def);
5836
f(self);
59-
self.parent_def = parent;
37+
self.parent_def = orig_parent_def;
6038
}
6139

6240
fn visit_async_fn(
@@ -97,12 +75,7 @@ impl<'a> DefCollector<'a> {
9775
}
9876

9977
fn visit_macro_invoc(&mut self, id: NodeId) {
100-
if let Some(ref mut visit) = self.visit_macro_invoc {
101-
visit(MacroInvocationData {
102-
mark: id.placeholder_to_mark(),
103-
def_index: self.parent_def.unwrap(),
104-
})
105-
}
78+
self.definitions.set_invocation_parent(id.placeholder_to_mark(), self.parent_def);
10679
}
10780
}
10881

@@ -275,36 +248,24 @@ impl<'a> visit::Visitor<'a> for DefCollector<'a> {
275248
}
276249

277250
fn visit_expr(&mut self, expr: &'a Expr) {
278-
let parent_def = self.parent_def;
279-
280-
match expr.node {
251+
let parent_def = match expr.node {
281252
ExprKind::Mac(..) => return self.visit_macro_invoc(expr.id),
282253
ExprKind::Closure(_, asyncness, ..) => {
283-
let closure_def = self.create_def(expr.id,
284-
DefPathData::ClosureExpr,
285-
expr.span);
286-
self.parent_def = Some(closure_def);
287-
288254
// Async closures desugar to closures inside of closures, so
289255
// we must create two defs.
290-
if let IsAsync::Async { closure_id, .. } = asyncness {
291-
let async_def = self.create_def(closure_id,
292-
DefPathData::ClosureExpr,
293-
expr.span);
294-
self.parent_def = Some(async_def);
256+
let closure_def = self.create_def(expr.id, DefPathData::ClosureExpr, expr.span);
257+
match asyncness {
258+
IsAsync::Async { closure_id, .. } =>
259+
self.create_def(closure_id, DefPathData::ClosureExpr, expr.span),
260+
IsAsync::NotAsync => closure_def,
295261
}
296262
}
297-
ExprKind::Async(_, async_id, _) => {
298-
let async_def = self.create_def(async_id,
299-
DefPathData::ClosureExpr,
300-
expr.span);
301-
self.parent_def = Some(async_def);
302-
}
303-
_ => {}
263+
ExprKind::Async(_, async_id, _) =>
264+
self.create_def(async_id, DefPathData::ClosureExpr, expr.span),
265+
_ => self.parent_def,
304266
};
305267

306-
visit::walk_expr(self, expr);
307-
self.parent_def = parent_def;
268+
self.with_parent(parent_def, |this| visit::walk_expr(this, expr));
308269
}
309270

310271
fn visit_ty(&mut self, ty: &'a Ty) {

src/librustc/hir/map/definitions.rs

+13
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,9 @@ pub struct Definitions {
100100
expansions_that_defined: FxHashMap<DefIndex, Mark>,
101101
next_disambiguator: FxHashMap<(DefIndex, DefPathData), u32>,
102102
def_index_to_span: FxHashMap<DefIndex, Span>,
103+
/// When collecting definitions from an AST fragment produced by a macro invocation `Mark`
104+
/// we know what parent node that fragment should be attached to thanks to this table.
105+
invocation_parents: FxHashMap<Mark, DefIndex>,
103106
}
104107

105108
/// A unique identifier that we can use to lookup a definition
@@ -434,6 +437,7 @@ impl Definitions {
434437
assert!(self.def_index_to_node.is_empty());
435438
self.def_index_to_node.push(ast::CRATE_NODE_ID);
436439
self.node_to_def_index.insert(ast::CRATE_NODE_ID, root_index);
440+
self.set_invocation_parent(Mark::root(), root_index);
437441

438442
// Allocate some other DefIndices that always must exist.
439443
GlobalMetaDataKind::allocate_def_indices(self);
@@ -526,6 +530,15 @@ impl Definitions {
526530
pub fn add_parent_module_of_macro_def(&mut self, mark: Mark, module: DefId) {
527531
self.parent_modules_of_macro_defs.insert(mark, module);
528532
}
533+
534+
pub fn invocation_parent(&self, invoc_id: Mark) -> DefIndex {
535+
self.invocation_parents[&invoc_id]
536+
}
537+
538+
pub fn set_invocation_parent(&mut self, invoc_id: Mark, parent: DefIndex) {
539+
let old_parent = self.invocation_parents.insert(invoc_id, parent);
540+
assert!(old_parent.is_none(), "parent def-index is reset for an invocation");
541+
}
529542
}
530543

531544
impl DefPathData {

src/librustc/hir/map/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use self::collector::NodeCollector;
2-
pub use self::def_collector::{DefCollector, MacroInvocationData};
2+
pub use self::def_collector::DefCollector;
33
pub use self::definitions::{
44
Definitions, DefKey, DefPath, DefPathData, DisambiguatedDefPathData, DefPathHash
55
};

src/librustc/ich/impls_syntax.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,6 @@ impl_stable_hash_for!(enum ::syntax::ext::base::MacroKind {
8989
Bang,
9090
Attr,
9191
Derive,
92-
ProcMacroStub,
9392
});
9493

9594

@@ -399,7 +398,7 @@ impl_stable_hash_for!(enum ::syntax_pos::hygiene::Transparency {
399398

400399
impl_stable_hash_for!(struct ::syntax_pos::hygiene::ExpnInfo {
401400
call_site,
402-
format,
401+
kind,
403402
def_site,
404403
default_transparency,
405404
allow_internal_unstable,
@@ -408,13 +407,13 @@ impl_stable_hash_for!(struct ::syntax_pos::hygiene::ExpnInfo {
408407
edition
409408
});
410409

411-
impl_stable_hash_for!(enum ::syntax_pos::hygiene::ExpnFormat {
412-
MacroAttribute(sym),
413-
MacroBang(sym),
414-
CompilerDesugaring(kind)
410+
impl_stable_hash_for!(enum ::syntax_pos::hygiene::ExpnKind {
411+
Root,
412+
Macro(kind, descr),
413+
Desugaring(kind)
415414
});
416415

417-
impl_stable_hash_for!(enum ::syntax_pos::hygiene::CompilerDesugaringKind {
416+
impl_stable_hash_for!(enum ::syntax_pos::hygiene::DesugaringKind {
418417
CondTemporary,
419418
Async,
420419
Await,

0 commit comments

Comments
 (0)