1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Machinery for hygienic macros, inspired by the `MTWT[1]` paper.
13 //! `[1]` Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce Findler. 2012.
14 //! *Macros that work together: Compile-time bindings, partial expansion,
15 //! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216.
16 //! DOI=10.1017/S0956796812000093 <https://doi.org/10.1017/S0956796812000093>
20 use edition::{Edition, DEFAULT_EDITION};
23 use serialize::{Encodable, Decodable, Encoder, Decoder};
24 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
27 /// A SyntaxContext represents a chain of macro expansions (represented by marks).
28 #[derive(Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord, Hash)]
29 pub struct SyntaxContext(u32);
31 #[derive(Copy, Clone, Debug)]
32 struct SyntaxContextData {
34 transparency: Transparency,
35 prev_ctxt: SyntaxContext,
36 // This context, but with all transparent and semi-transparent marks filtered away.
37 opaque: SyntaxContext,
38 // This context, but with all transparent marks filtered away.
39 opaque_and_semitransparent: SyntaxContext,
42 /// A mark is a unique id associated with a macro expansion.
43 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
46 #[derive(Clone, Debug)]
49 default_transparency: Transparency,
51 expn_info: Option<ExpnInfo>,
54 /// A property of a macro expansion that determines how identifiers
55 /// produced by that expansion are resolved.
56 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
57 pub enum Transparency {
58 /// Identifier produced by a transparent expansion is always resolved at call-site.
59 /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
61 /// Identifier produced by a semi-transparent expansion may be resolved
62 /// either at call-site or at definition-site.
63 /// If it's a local variable, label or `$crate` then it's resolved at def-site.
64 /// Otherwise it's resolved at call-site.
65 /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
66 /// but that's an implementation detail.
68 /// Identifier produced by an opaque expansion is always resolved at definition-site.
69 /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
74 pub fn fresh(parent: Mark) -> Self {
75 HygieneData::with(|data| {
76 data.marks.push(MarkData {
78 // By default expansions behave like `macro_rules`.
79 default_transparency: Transparency::SemiTransparent,
83 Mark(data.marks.len() as u32 - 1)
87 /// The mark of the theoretical expansion that generates freshly parsed, unexpanded AST.
89 pub fn root() -> Self {
94 pub fn as_u32(self) -> u32 {
99 pub fn from_u32(raw: u32) -> Mark {
104 pub fn parent(self) -> Mark {
105 HygieneData::with(|data| data.marks[self.0 as usize].parent)
109 pub fn expn_info(self) -> Option<ExpnInfo> {
110 HygieneData::with(|data| data.marks[self.0 as usize].expn_info.clone())
114 pub fn set_expn_info(self, info: ExpnInfo) {
115 HygieneData::with(|data| data.marks[self.0 as usize].expn_info = Some(info))
119 pub fn set_default_transparency(self, transparency: Transparency) {
120 assert_ne!(self, Mark::root());
121 HygieneData::with(|data| data.marks[self.0 as usize].default_transparency = transparency)
125 pub fn is_builtin(self) -> bool {
126 assert_ne!(self, Mark::root());
127 HygieneData::with(|data| data.marks[self.0 as usize].is_builtin)
131 pub fn set_is_builtin(self, is_builtin: bool) {
132 assert_ne!(self, Mark::root());
133 HygieneData::with(|data| data.marks[self.0 as usize].is_builtin = is_builtin)
136 pub fn is_descendant_of(mut self, ancestor: Mark) -> bool {
137 HygieneData::with(|data| {
138 while self != ancestor {
139 if self == Mark::root() {
142 self = data.marks[self.0 as usize].parent;
148 /// Computes a mark such that both input marks are descendants of (or equal to) the returned
149 /// mark. That is, the following holds:
152 /// let la = least_ancestor(a, b);
153 /// assert!(a.is_descendant_of(la))
154 /// assert!(b.is_descendant_of(la))
156 pub fn least_ancestor(mut a: Mark, mut b: Mark) -> Mark {
157 HygieneData::with(|data| {
158 // Compute the path from a to the root
159 let mut a_path = FxHashSet::<Mark>::default();
160 while a != Mark::root() {
162 a = data.marks[a.0 as usize].parent;
165 // While the path from b to the root hasn't intersected, move up the tree
166 while !a_path.contains(&b) {
167 b = data.marks[b.0 as usize].parent;
174 // Used for enabling some compatibility fallback in resolve.
176 pub fn looks_like_proc_macro_derive(self) -> bool {
177 HygieneData::with(|data| {
178 let mark_data = &data.marks[self.0 as usize];
179 if mark_data.default_transparency == Transparency::Opaque {
180 if let Some(expn_info) = &mark_data.expn_info {
181 if let ExpnFormat::MacroAttribute(name) = expn_info.format {
182 if name.as_str().starts_with("derive(") {
194 crate struct HygieneData {
195 marks: Vec<MarkData>,
196 syntax_contexts: Vec<SyntaxContextData>,
197 markings: FxHashMap<(SyntaxContext, Mark, Transparency), SyntaxContext>,
198 default_edition: Edition,
202 crate fn new() -> Self {
204 marks: vec![MarkData {
205 parent: Mark::root(),
206 // If the root is opaque, then loops searching for an opaque mark
207 // will automatically stop after reaching it.
208 default_transparency: Transparency::Opaque,
212 syntax_contexts: vec![SyntaxContextData {
213 outer_mark: Mark::root(),
214 transparency: Transparency::Opaque,
215 prev_ctxt: SyntaxContext(0),
216 opaque: SyntaxContext(0),
217 opaque_and_semitransparent: SyntaxContext(0),
219 markings: FxHashMap::default(),
220 default_edition: DEFAULT_EDITION,
224 fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
225 GLOBALS.with(|globals| f(&mut *globals.hygiene_data.borrow_mut()))
229 pub fn default_edition() -> Edition {
230 HygieneData::with(|data| data.default_edition)
233 pub fn set_default_edition(edition: Edition) {
234 HygieneData::with(|data| data.default_edition = edition);
237 pub fn clear_markings() {
238 HygieneData::with(|data| data.markings = FxHashMap::default());
242 pub const fn empty() -> Self {
246 crate fn as_u32(self) -> u32 {
250 crate fn from_u32(raw: u32) -> SyntaxContext {
254 // Allocate a new SyntaxContext with the given ExpnInfo. This is used when
255 // deserializing Spans from the incr. comp. cache.
256 // FIXME(mw): This method does not restore MarkData::parent or
257 // SyntaxContextData::prev_ctxt or SyntaxContextData::opaque. These things
258 // don't seem to be used after HIR lowering, so everything should be fine
259 // as long as incremental compilation does not kick in before that.
260 pub fn allocate_directly(expansion_info: ExpnInfo) -> Self {
261 HygieneData::with(|data| {
262 data.marks.push(MarkData {
263 parent: Mark::root(),
264 default_transparency: Transparency::SemiTransparent,
266 expn_info: Some(expansion_info),
269 let mark = Mark(data.marks.len() as u32 - 1);
271 data.syntax_contexts.push(SyntaxContextData {
273 transparency: Transparency::SemiTransparent,
274 prev_ctxt: SyntaxContext::empty(),
275 opaque: SyntaxContext::empty(),
276 opaque_and_semitransparent: SyntaxContext::empty(),
278 SyntaxContext(data.syntax_contexts.len() as u32 - 1)
282 /// Extend a syntax context with a given mark and default transparency for that mark.
283 pub fn apply_mark(self, mark: Mark) -> SyntaxContext {
284 assert_ne!(mark, Mark::root());
285 self.apply_mark_with_transparency(
286 mark, HygieneData::with(|data| data.marks[mark.0 as usize].default_transparency)
290 /// Extend a syntax context with a given mark and transparency
291 pub fn apply_mark_with_transparency(self, mark: Mark, transparency: Transparency)
293 assert_ne!(mark, Mark::root());
294 if transparency == Transparency::Opaque {
295 return self.apply_mark_internal(mark, transparency);
299 mark.expn_info().map_or(SyntaxContext::empty(), |info| info.call_site.ctxt());
300 let call_site_ctxt = if transparency == Transparency::SemiTransparent {
301 call_site_ctxt.modern()
303 call_site_ctxt.modern_and_legacy()
306 if call_site_ctxt == SyntaxContext::empty() {
307 return self.apply_mark_internal(mark, transparency);
310 // Otherwise, `mark` is a macros 1.0 definition and the call site is in a
311 // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
313 // In this case, the tokens from the macros 1.0 definition inherit the hygiene
314 // at their invocation. That is, we pretend that the macros 1.0 definition
315 // was defined at its invocation (i.e., inside the macros 2.0 definition)
316 // so that the macros 2.0 definition remains hygienic.
318 // See the example at `test/run-pass/hygiene/legacy_interaction.rs`.
319 let mut ctxt = call_site_ctxt;
320 for (mark, transparency) in self.marks() {
321 ctxt = ctxt.apply_mark_internal(mark, transparency);
323 ctxt.apply_mark_internal(mark, transparency)
326 fn apply_mark_internal(self, mark: Mark, transparency: Transparency) -> SyntaxContext {
327 HygieneData::with(|data| {
328 let syntax_contexts = &mut data.syntax_contexts;
329 let mut opaque = syntax_contexts[self.0 as usize].opaque;
330 let mut opaque_and_semitransparent =
331 syntax_contexts[self.0 as usize].opaque_and_semitransparent;
333 if transparency >= Transparency::Opaque {
334 let prev_ctxt = opaque;
335 opaque = *data.markings.entry((prev_ctxt, mark, transparency)).or_insert_with(|| {
336 let new_opaque = SyntaxContext(syntax_contexts.len() as u32);
337 syntax_contexts.push(SyntaxContextData {
342 opaque_and_semitransparent: new_opaque,
348 if transparency >= Transparency::SemiTransparent {
349 let prev_ctxt = opaque_and_semitransparent;
350 opaque_and_semitransparent =
351 *data.markings.entry((prev_ctxt, mark, transparency)).or_insert_with(|| {
352 let new_opaque_and_semitransparent =
353 SyntaxContext(syntax_contexts.len() as u32);
354 syntax_contexts.push(SyntaxContextData {
359 opaque_and_semitransparent: new_opaque_and_semitransparent,
361 new_opaque_and_semitransparent
365 let prev_ctxt = self;
366 *data.markings.entry((prev_ctxt, mark, transparency)).or_insert_with(|| {
367 let new_opaque_and_semitransparent_and_transparent =
368 SyntaxContext(syntax_contexts.len() as u32);
369 syntax_contexts.push(SyntaxContextData {
374 opaque_and_semitransparent,
376 new_opaque_and_semitransparent_and_transparent
381 /// Pulls a single mark off of the syntax context. This effectively moves the
382 /// context up one macro definition level. That is, if we have a nested macro
383 /// definition as follows:
393 /// and we have a SyntaxContext that is referring to something declared by an invocation
394 /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
395 /// invocation of f that created g1.
396 /// Returns the mark that was removed.
397 pub fn remove_mark(&mut self) -> Mark {
398 HygieneData::with(|data| {
399 let outer_mark = data.syntax_contexts[self.0 as usize].outer_mark;
400 *self = data.syntax_contexts[self.0 as usize].prev_ctxt;
405 pub fn marks(mut self) -> Vec<(Mark, Transparency)> {
406 HygieneData::with(|data| {
407 let mut marks = Vec::new();
408 while self != SyntaxContext::empty() {
409 let ctxt_data = &data.syntax_contexts[self.0 as usize];
410 marks.push((ctxt_data.outer_mark, ctxt_data.transparency));
411 self = ctxt_data.prev_ctxt;
418 /// Adjust this context for resolution in a scope created by the given expansion.
419 /// For example, consider the following three resolutions of `f`:
422 /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
424 /// macro m($f:ident) {
426 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `Mark` from `m`.
427 /// pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
429 /// foo::f(); // `f`'s `SyntaxContext` has a single `Mark` from `m`
430 /// //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
431 /// //| and it resolves to `::foo::f`.
432 /// bar::f(); // `f`'s `SyntaxContext` has a single `Mark` from `m`
433 /// //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
434 /// //| and it resolves to `::bar::f`.
435 /// bar::$f(); // `f`'s `SyntaxContext` is empty.
436 /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
437 /// //| and it resolves to `::bar::$f`.
440 /// This returns the expansion whose definition scope we use to privacy check the resolution,
441 /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
442 pub fn adjust(&mut self, expansion: Mark) -> Option<Mark> {
443 let mut scope = None;
444 while !expansion.is_descendant_of(self.outer()) {
445 scope = Some(self.remove_mark());
450 /// Adjust this context for resolution in a scope created by the given expansion
451 /// via a glob import with the given `SyntaxContext`.
456 /// macro m($i:ident) {
458 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `Mark` from `m`.
459 /// pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
462 /// macro n($j:ident) {
464 /// f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
465 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
466 /// $i(); // `$i`'s `SyntaxContext` has a mark from `n`
467 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
468 /// $j(); // `$j`'s `SyntaxContext` has a mark from `m`
469 /// //^ This cannot be glob-adjusted, so this is a resolution error.
473 /// This returns `None` if the context cannot be glob-adjusted.
474 /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
475 pub fn glob_adjust(&mut self, expansion: Mark, mut glob_ctxt: SyntaxContext)
476 -> Option<Option<Mark>> {
477 let mut scope = None;
478 while !expansion.is_descendant_of(glob_ctxt.outer()) {
479 scope = Some(glob_ctxt.remove_mark());
480 if self.remove_mark() != scope.unwrap() {
484 if self.adjust(expansion).is_some() {
490 /// Undo `glob_adjust` if possible:
493 /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
494 /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
497 pub fn reverse_glob_adjust(&mut self, expansion: Mark, mut glob_ctxt: SyntaxContext)
498 -> Option<Option<Mark>> {
499 if self.adjust(expansion).is_some() {
503 let mut marks = Vec::new();
504 while !expansion.is_descendant_of(glob_ctxt.outer()) {
505 marks.push(glob_ctxt.remove_mark());
508 let scope = marks.last().cloned();
509 while let Some(mark) = marks.pop() {
510 *self = self.apply_mark(mark);
516 pub fn modern(self) -> SyntaxContext {
517 HygieneData::with(|data| data.syntax_contexts[self.0 as usize].opaque)
521 pub fn modern_and_legacy(self) -> SyntaxContext {
522 HygieneData::with(|data| data.syntax_contexts[self.0 as usize].opaque_and_semitransparent)
526 pub fn outer(self) -> Mark {
527 HygieneData::with(|data| data.syntax_contexts[self.0 as usize].outer_mark)
531 impl fmt::Debug for SyntaxContext {
532 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
533 write!(f, "#{}", self.0)
537 /// Extra information for tracking spans of macro and syntax sugar expansion
538 #[derive(Clone, Hash, Debug, RustcEncodable, RustcDecodable)]
539 pub struct ExpnInfo {
540 /// The location of the actual macro invocation or syntax sugar , e.g.
541 /// `let x = foo!();` or `if let Some(y) = x {}`
543 /// This may recursively refer to other macro invocations, e.g., if
544 /// `foo!()` invoked `bar!()` internally, and there was an
545 /// expression inside `bar!`; the call_site of the expression in
546 /// the expansion would point to the `bar!` invocation; that
547 /// call_site span would have its own ExpnInfo, with the call_site
548 /// pointing to the `foo!` invocation.
550 /// The span of the macro definition itself. The macro may not
551 /// have a sensible definition span (e.g., something defined
552 /// completely inside libsyntax) in which case this is None.
553 /// This span serves only informational purpose and is not used for resolution.
554 pub def_site: Option<Span>,
555 /// The format with which the macro was invoked.
556 pub format: ExpnFormat,
557 /// Whether the macro is allowed to use #[unstable]/feature-gated
558 /// features internally without forcing the whole crate to opt-in
560 pub allow_internal_unstable: bool,
561 /// Whether the macro is allowed to use `unsafe` internally
562 /// even if the user crate has `#![forbid(unsafe_code)]`.
563 pub allow_internal_unsafe: bool,
564 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
565 /// for a given macro.
566 pub local_inner_macros: bool,
567 /// Edition of the crate in which the macro is defined.
568 pub edition: Edition,
571 /// The source of expansion.
572 #[derive(Clone, Hash, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
573 pub enum ExpnFormat {
574 /// e.g., #[derive(...)] <item>
575 MacroAttribute(Symbol),
576 /// e.g., `format!()`
578 /// Desugaring done by the compiler during HIR lowering.
579 CompilerDesugaring(CompilerDesugaringKind)
583 pub fn name(&self) -> Symbol {
585 ExpnFormat::MacroBang(name) | ExpnFormat::MacroAttribute(name) => name,
586 ExpnFormat::CompilerDesugaring(kind) => kind.name(),
591 /// The kind of compiler desugaring.
592 #[derive(Clone, Copy, Hash, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
593 pub enum CompilerDesugaringKind {
596 /// Desugaring of an `impl Trait` in return type position
597 /// to an `existential type Foo: Trait;` + replacing the
598 /// `impl Trait` with `Foo`.
599 ExistentialReturnType,
604 impl CompilerDesugaringKind {
605 pub fn name(self) -> Symbol {
606 Symbol::intern(match self {
607 CompilerDesugaringKind::Async => "async",
608 CompilerDesugaringKind::QuestionMark => "?",
609 CompilerDesugaringKind::TryBlock => "try block",
610 CompilerDesugaringKind::ExistentialReturnType => "existential type",
611 CompilerDesugaringKind::ForLoop => "for loop",
616 impl Encodable for SyntaxContext {
617 fn encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
618 Ok(()) // FIXME(jseyfried) intercrate hygiene
622 impl Decodable for SyntaxContext {
623 fn decode<D: Decoder>(_: &mut D) -> Result<SyntaxContext, D::Error> {
624 Ok(SyntaxContext::empty()) // FIXME(jseyfried) intercrate hygiene