1 //! Machinery for hygienic macros, inspired by the `MTWT[1]` paper.
3 //! `[1]` Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce Findler. 2012.
4 //! *Macros that work together: Compile-time bindings, partial expansion,
5 //! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216.
6 //! DOI=10.1017/S0956796812000093 <https://doi.org/10.1017/S0956796812000093>
10 use crate::edition::{Edition, DEFAULT_EDITION};
11 use crate::symbol::{keywords, Symbol};
13 use serialize::{Encodable, Decodable, Encoder, Decoder};
14 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
15 use rustc_data_structures::sync::Lrc;
18 /// A SyntaxContext represents a chain of macro expansions (represented by marks).
19 #[derive(Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord, Hash)]
20 pub struct SyntaxContext(u32);
22 #[derive(Copy, Clone, Debug)]
23 struct SyntaxContextData {
25 transparency: Transparency,
26 prev_ctxt: SyntaxContext,
27 // This context, but with all transparent and semi-transparent marks filtered away.
28 opaque: SyntaxContext,
29 // This context, but with all transparent marks filtered away.
30 opaque_and_semitransparent: SyntaxContext,
31 // Name of the crate to which `$crate` with this context would resolve.
32 dollar_crate_name: Symbol,
35 /// A mark is a unique ID associated with a macro expansion.
36 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
39 #[derive(Clone, Debug)]
42 default_transparency: Transparency,
43 expn_info: Option<ExpnInfo>,
46 /// A property of a macro expansion that determines how identifiers
47 /// produced by that expansion are resolved.
48 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
49 pub enum Transparency {
50 /// Identifier produced by a transparent expansion is always resolved at call-site.
51 /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
53 /// Identifier produced by a semi-transparent expansion may be resolved
54 /// either at call-site or at definition-site.
55 /// If it's a local variable, label or `$crate` then it's resolved at def-site.
56 /// Otherwise it's resolved at call-site.
57 /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
58 /// but that's an implementation detail.
60 /// Identifier produced by an opaque expansion is always resolved at definition-site.
61 /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
66 pub fn fresh(parent: Mark) -> Self {
67 HygieneData::with(|data| {
68 data.marks.push(MarkData {
70 // By default expansions behave like `macro_rules`.
71 default_transparency: Transparency::SemiTransparent,
74 Mark(data.marks.len() as u32 - 1)
78 /// The mark of the theoretical expansion that generates freshly parsed, unexpanded AST.
80 pub fn root() -> Self {
85 pub fn as_u32(self) -> u32 {
90 pub fn from_u32(raw: u32) -> Mark {
95 pub fn parent(self) -> Mark {
96 HygieneData::with(|data| data.marks[self.0 as usize].parent)
100 pub fn expn_info(self) -> Option<ExpnInfo> {
101 HygieneData::with(|data| data.marks[self.0 as usize].expn_info.clone())
105 pub fn set_expn_info(self, info: ExpnInfo) {
106 HygieneData::with(|data| data.marks[self.0 as usize].expn_info = Some(info))
110 pub fn set_default_transparency(self, transparency: Transparency) {
111 assert_ne!(self, Mark::root());
112 HygieneData::with(|data| data.marks[self.0 as usize].default_transparency = transparency)
115 pub fn is_descendant_of(mut self, ancestor: Mark) -> bool {
116 HygieneData::with(|data| {
117 while self != ancestor {
118 if self == Mark::root() {
121 self = data.marks[self.0 as usize].parent;
127 /// Computes a mark such that both input marks are descendants of (or equal to) the returned
128 /// mark. That is, the following holds:
131 /// let la = least_ancestor(a, b);
132 /// assert!(a.is_descendant_of(la))
133 /// assert!(b.is_descendant_of(la))
135 pub fn least_ancestor(mut a: Mark, mut b: Mark) -> Mark {
136 HygieneData::with(|data| {
137 // Compute the path from a to the root
138 let mut a_path = FxHashSet::<Mark>::default();
139 while a != Mark::root() {
141 a = data.marks[a.0 as usize].parent;
144 // While the path from b to the root hasn't intersected, move up the tree
145 while !a_path.contains(&b) {
146 b = data.marks[b.0 as usize].parent;
153 // Used for enabling some compatibility fallback in resolve.
155 pub fn looks_like_proc_macro_derive(self) -> bool {
156 HygieneData::with(|data| {
157 let mark_data = &data.marks[self.0 as usize];
158 if mark_data.default_transparency == Transparency::Opaque {
159 if let Some(expn_info) = &mark_data.expn_info {
160 if let ExpnFormat::MacroAttribute(name) = expn_info.format {
161 if name.as_str().starts_with("derive(") {
173 crate struct HygieneData {
174 marks: Vec<MarkData>,
175 syntax_contexts: Vec<SyntaxContextData>,
176 markings: FxHashMap<(SyntaxContext, Mark, Transparency), SyntaxContext>,
177 default_edition: Edition,
181 crate fn new() -> Self {
183 marks: vec![MarkData {
184 parent: Mark::root(),
185 // If the root is opaque, then loops searching for an opaque mark
186 // will automatically stop after reaching it.
187 default_transparency: Transparency::Opaque,
190 syntax_contexts: vec![SyntaxContextData {
191 outer_mark: Mark::root(),
192 transparency: Transparency::Opaque,
193 prev_ctxt: SyntaxContext(0),
194 opaque: SyntaxContext(0),
195 opaque_and_semitransparent: SyntaxContext(0),
196 dollar_crate_name: keywords::DollarCrate.name(),
198 markings: FxHashMap::default(),
199 default_edition: DEFAULT_EDITION,
203 fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
204 GLOBALS.with(|globals| f(&mut *globals.hygiene_data.borrow_mut()))
208 pub fn default_edition() -> Edition {
209 HygieneData::with(|data| data.default_edition)
212 pub fn set_default_edition(edition: Edition) {
213 HygieneData::with(|data| data.default_edition = edition);
216 pub fn clear_markings() {
217 HygieneData::with(|data| data.markings = FxHashMap::default());
221 pub const fn empty() -> Self {
225 crate fn as_u32(self) -> u32 {
229 crate fn from_u32(raw: u32) -> SyntaxContext {
233 // Allocate a new SyntaxContext with the given ExpnInfo. This is used when
234 // deserializing Spans from the incr. comp. cache.
235 // FIXME(mw): This method does not restore MarkData::parent or
236 // SyntaxContextData::prev_ctxt or SyntaxContextData::opaque. These things
237 // don't seem to be used after HIR lowering, so everything should be fine
238 // as long as incremental compilation does not kick in before that.
239 pub fn allocate_directly(expansion_info: ExpnInfo) -> Self {
240 HygieneData::with(|data| {
241 data.marks.push(MarkData {
242 parent: Mark::root(),
243 default_transparency: Transparency::SemiTransparent,
244 expn_info: Some(expansion_info),
247 let mark = Mark(data.marks.len() as u32 - 1);
249 data.syntax_contexts.push(SyntaxContextData {
251 transparency: Transparency::SemiTransparent,
252 prev_ctxt: SyntaxContext::empty(),
253 opaque: SyntaxContext::empty(),
254 opaque_and_semitransparent: SyntaxContext::empty(),
255 dollar_crate_name: keywords::DollarCrate.name(),
257 SyntaxContext(data.syntax_contexts.len() as u32 - 1)
261 /// Extend a syntax context with a given mark and default transparency for that mark.
262 pub fn apply_mark(self, mark: Mark) -> SyntaxContext {
263 assert_ne!(mark, Mark::root());
264 self.apply_mark_with_transparency(
265 mark, HygieneData::with(|data| data.marks[mark.0 as usize].default_transparency)
269 /// Extend a syntax context with a given mark and transparency
270 pub fn apply_mark_with_transparency(self, mark: Mark, transparency: Transparency)
272 assert_ne!(mark, Mark::root());
273 if transparency == Transparency::Opaque {
274 return self.apply_mark_internal(mark, transparency);
278 mark.expn_info().map_or(SyntaxContext::empty(), |info| info.call_site.ctxt());
279 let call_site_ctxt = if transparency == Transparency::SemiTransparent {
280 call_site_ctxt.modern()
282 call_site_ctxt.modern_and_legacy()
285 if call_site_ctxt == SyntaxContext::empty() {
286 return self.apply_mark_internal(mark, transparency);
289 // Otherwise, `mark` is a macros 1.0 definition and the call site is in a
290 // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
292 // In this case, the tokens from the macros 1.0 definition inherit the hygiene
293 // at their invocation. That is, we pretend that the macros 1.0 definition
294 // was defined at its invocation (i.e., inside the macros 2.0 definition)
295 // so that the macros 2.0 definition remains hygienic.
297 // See the example at `test/run-pass/hygiene/legacy_interaction.rs`.
298 let mut ctxt = call_site_ctxt;
299 for (mark, transparency) in self.marks() {
300 ctxt = ctxt.apply_mark_internal(mark, transparency);
302 ctxt.apply_mark_internal(mark, transparency)
305 fn apply_mark_internal(self, mark: Mark, transparency: Transparency) -> SyntaxContext {
306 HygieneData::with(|data| {
307 let syntax_contexts = &mut data.syntax_contexts;
308 let mut opaque = syntax_contexts[self.0 as usize].opaque;
309 let mut opaque_and_semitransparent =
310 syntax_contexts[self.0 as usize].opaque_and_semitransparent;
312 if transparency >= Transparency::Opaque {
313 let prev_ctxt = opaque;
314 opaque = *data.markings.entry((prev_ctxt, mark, transparency)).or_insert_with(|| {
315 let new_opaque = SyntaxContext(syntax_contexts.len() as u32);
316 syntax_contexts.push(SyntaxContextData {
321 opaque_and_semitransparent: new_opaque,
322 dollar_crate_name: keywords::DollarCrate.name(),
328 if transparency >= Transparency::SemiTransparent {
329 let prev_ctxt = opaque_and_semitransparent;
330 opaque_and_semitransparent =
331 *data.markings.entry((prev_ctxt, mark, transparency)).or_insert_with(|| {
332 let new_opaque_and_semitransparent =
333 SyntaxContext(syntax_contexts.len() as u32);
334 syntax_contexts.push(SyntaxContextData {
339 opaque_and_semitransparent: new_opaque_and_semitransparent,
340 dollar_crate_name: keywords::DollarCrate.name(),
342 new_opaque_and_semitransparent
346 let prev_ctxt = self;
347 *data.markings.entry((prev_ctxt, mark, transparency)).or_insert_with(|| {
348 let new_opaque_and_semitransparent_and_transparent =
349 SyntaxContext(syntax_contexts.len() as u32);
350 syntax_contexts.push(SyntaxContextData {
355 opaque_and_semitransparent,
356 dollar_crate_name: keywords::DollarCrate.name(),
358 new_opaque_and_semitransparent_and_transparent
363 /// Pulls a single mark off of the syntax context. This effectively moves the
364 /// context up one macro definition level. That is, if we have a nested macro
365 /// definition as follows:
375 /// and we have a SyntaxContext that is referring to something declared by an invocation
376 /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
377 /// invocation of f that created g1.
378 /// Returns the mark that was removed.
379 pub fn remove_mark(&mut self) -> Mark {
380 HygieneData::with(|data| {
381 let outer_mark = data.syntax_contexts[self.0 as usize].outer_mark;
382 *self = data.syntax_contexts[self.0 as usize].prev_ctxt;
387 pub fn marks(mut self) -> Vec<(Mark, Transparency)> {
388 HygieneData::with(|data| {
389 let mut marks = Vec::new();
390 while self != SyntaxContext::empty() {
391 let ctxt_data = &data.syntax_contexts[self.0 as usize];
392 marks.push((ctxt_data.outer_mark, ctxt_data.transparency));
393 self = ctxt_data.prev_ctxt;
400 /// Adjust this context for resolution in a scope created by the given expansion.
401 /// For example, consider the following three resolutions of `f`:
404 /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
406 /// macro m($f:ident) {
408 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `Mark` from `m`.
409 /// pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
411 /// foo::f(); // `f`'s `SyntaxContext` has a single `Mark` from `m`
412 /// //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
413 /// //| and it resolves to `::foo::f`.
414 /// bar::f(); // `f`'s `SyntaxContext` has a single `Mark` from `m`
415 /// //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
416 /// //| and it resolves to `::bar::f`.
417 /// bar::$f(); // `f`'s `SyntaxContext` is empty.
418 /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
419 /// //| and it resolves to `::bar::$f`.
422 /// This returns the expansion whose definition scope we use to privacy check the resolution,
423 /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
424 pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
425 let mut scope = None;
426 while !expansion.is_descendant_of(self.outer()) {
427 scope = Some(self.remove_mark());
432 /// Adjust this context for resolution in a scope created by the given expansion
433 /// via a glob import with the given `SyntaxContext`.
438 /// macro m($i:ident) {
440 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `Mark` from `m`.
441 /// pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
444 /// macro n($j:ident) {
446 /// f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
447 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
448 /// $i(); // `$i`'s `SyntaxContext` has a mark from `n`
449 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
450 /// $j(); // `$j`'s `SyntaxContext` has a mark from `m`
451 /// //^ This cannot be glob-adjusted, so this is a resolution error.
455 /// This returns `None` if the context cannot be glob-adjusted.
456 /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
457 pub fn glob_adjust(&mut self, expansion: Mark, mut glob_ctxt: SyntaxContext)
458 -> Option<Option<Mark>> {
459 let mut scope = None;
460 while !expansion.is_descendant_of(glob_ctxt.outer()) {
461 scope = Some(glob_ctxt.remove_mark());
462 if self.remove_mark() != scope.unwrap() {
466 if self.adjust(expansion).is_some() {
472 /// Undo `glob_adjust` if possible:
475 /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
476 /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
479 pub fn reverse_glob_adjust(&mut self, expansion: Mark, mut glob_ctxt: SyntaxContext)
480 -> Option<Option<Mark>> {
481 if self.adjust(expansion).is_some() {
485 let mut marks = Vec::new();
486 while !expansion.is_descendant_of(glob_ctxt.outer()) {
487 marks.push(glob_ctxt.remove_mark());
490 let scope = marks.last().cloned();
491 while let Some(mark) = marks.pop() {
492 *self = self.apply_mark(mark);
498 pub fn modern(self) -> SyntaxContext {
499 HygieneData::with(|data| data.syntax_contexts[self.0 as usize].opaque)
503 pub fn modern_and_legacy(self) -> SyntaxContext {
504 HygieneData::with(|data| data.syntax_contexts[self.0 as usize].opaque_and_semitransparent)
508 pub fn outer(self) -> Mark {
509 HygieneData::with(|data| data.syntax_contexts[self.0 as usize].outer_mark)
512 pub fn dollar_crate_name(self) -> Symbol {
513 HygieneData::with(|data| data.syntax_contexts[self.0 as usize].dollar_crate_name)
516 pub fn set_dollar_crate_name(self, dollar_crate_name: Symbol) {
517 HygieneData::with(|data| {
518 let prev_dollar_crate_name = mem::replace(
519 &mut data.syntax_contexts[self.0 as usize].dollar_crate_name, dollar_crate_name
521 assert!(dollar_crate_name == prev_dollar_crate_name ||
522 prev_dollar_crate_name == keywords::DollarCrate.name(),
523 "$crate name is reset for a syntax context");
528 impl fmt::Debug for SyntaxContext {
529 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530 write!(f, "#{}", self.0)
534 /// Extra information for tracking spans of macro and syntax sugar expansion
535 #[derive(Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
536 pub struct ExpnInfo {
537 /// The location of the actual macro invocation or syntax sugar , e.g.
538 /// `let x = foo!();` or `if let Some(y) = x {}`
540 /// This may recursively refer to other macro invocations, e.g., if
541 /// `foo!()` invoked `bar!()` internally, and there was an
542 /// expression inside `bar!`; the call_site of the expression in
543 /// the expansion would point to the `bar!` invocation; that
544 /// call_site span would have its own ExpnInfo, with the call_site
545 /// pointing to the `foo!` invocation.
547 /// The span of the macro definition itself. The macro may not
548 /// have a sensible definition span (e.g., something defined
549 /// completely inside libsyntax) in which case this is None.
550 /// This span serves only informational purpose and is not used for resolution.
551 pub def_site: Option<Span>,
552 /// The format with which the macro was invoked.
553 pub format: ExpnFormat,
554 /// List of #[unstable]/feature-gated features that the macro is allowed to use
555 /// internally without forcing the whole crate to opt-in
557 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
558 /// Whether the macro is allowed to use `unsafe` internally
559 /// even if the user crate has `#![forbid(unsafe_code)]`.
560 pub allow_internal_unsafe: bool,
561 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
562 /// for a given macro.
563 pub local_inner_macros: bool,
564 /// Edition of the crate in which the macro is defined.
565 pub edition: Edition,
568 /// The source of expansion.
569 #[derive(Clone, Hash, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
570 pub enum ExpnFormat {
571 /// e.g., #[derive(...)] <item>
572 MacroAttribute(Symbol),
573 /// e.g., `format!()`
575 /// Desugaring done by the compiler during HIR lowering.
576 CompilerDesugaring(CompilerDesugaringKind)
580 pub fn name(&self) -> Symbol {
582 ExpnFormat::MacroBang(name) | ExpnFormat::MacroAttribute(name) => name,
583 ExpnFormat::CompilerDesugaring(kind) => kind.name(),
588 /// The kind of compiler desugaring.
589 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
590 pub enum CompilerDesugaringKind {
593 /// Desugaring of an `impl Trait` in return type position
594 /// to an `existential type Foo: Trait;` and replacing the
595 /// `impl Trait` with `Foo`.
596 ExistentialReturnType,
601 impl CompilerDesugaringKind {
602 pub fn name(self) -> Symbol {
603 Symbol::intern(match self {
604 CompilerDesugaringKind::Async => "async",
605 CompilerDesugaringKind::QuestionMark => "?",
606 CompilerDesugaringKind::TryBlock => "try block",
607 CompilerDesugaringKind::ExistentialReturnType => "existential type",
608 CompilerDesugaringKind::ForLoop => "for loop",
613 impl Encodable for SyntaxContext {
614 fn encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
615 Ok(()) // FIXME(jseyfried) intercrate hygiene
619 impl Decodable for SyntaxContext {
620 fn decode<D: Decoder>(_: &mut D) -> Result<SyntaxContext, D::Error> {
621 Ok(SyntaxContext::empty()) // FIXME(jseyfried) intercrate hygiene