]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/hygiene.rs
Auto merge of #69474 - Dylan-DPC:rollup-ciotplu, r=Dylan-DPC
[rust.git] / src / librustc_span / hygiene.rs
1 //! Machinery for hygienic macros, inspired by the `MTWT[1]` paper.
2 //!
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>
7
8 // Hygiene data is stored in a global variable and accessed via TLS, which
9 // means that accesses are somewhat expensive. (`HygieneData::with`
10 // encapsulates a single access.) Therefore, on hot code paths it is worth
11 // ensuring that multiple HygieneData accesses are combined into a single
12 // `HygieneData::with`.
13 //
14 // This explains why `HygieneData`, `SyntaxContext` and `ExpnId` have interfaces
15 // with a certain amount of redundancy in them. For example,
16 // `SyntaxContext::outer_expn_data` combines `SyntaxContext::outer` and
17 // `ExpnId::expn_data` so that two `HygieneData` accesses can be performed within
18 // a single `HygieneData::with` call.
19 //
20 // It also explains why many functions appear in `HygieneData` and again in
21 // `SyntaxContext` or `ExpnId`. For example, `HygieneData::outer` and
22 // `SyntaxContext::outer` do the same thing, but the former is for use within a
23 // `HygieneData::with` call while the latter is for use outside such a call.
24 // When modifying this file it is important to understand this distinction,
25 // because getting it wrong can lead to nested `HygieneData::with` calls that
26 // trigger runtime aborts. (Fortunately these are obvious and easy to fix.)
27
28 use crate::edition::Edition;
29 use crate::symbol::{kw, sym, Symbol};
30 use crate::GLOBALS;
31 use crate::{Span, DUMMY_SP};
32
33 use rustc_data_structures::fx::FxHashMap;
34 use rustc_data_structures::sync::Lrc;
35 use rustc_macros::HashStable_Generic;
36 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
37 use std::fmt;
38
39 /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
40 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
41 pub struct SyntaxContext(u32);
42
43 #[derive(Debug)]
44 struct SyntaxContextData {
45     outer_expn: ExpnId,
46     outer_transparency: Transparency,
47     parent: SyntaxContext,
48     /// This context, but with all transparent and semi-transparent expansions filtered away.
49     opaque: SyntaxContext,
50     /// This context, but with all transparent expansions filtered away.
51     opaque_and_semitransparent: SyntaxContext,
52     /// Name of the crate to which `$crate` with this context would resolve.
53     dollar_crate_name: Symbol,
54 }
55
56 /// A unique ID associated with a macro invocation and expansion.
57 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
58 pub struct ExpnId(u32);
59
60 /// A property of a macro expansion that determines how identifiers
61 /// produced by that expansion are resolved.
62 #[derive(
63     Copy,
64     Clone,
65     PartialEq,
66     Eq,
67     PartialOrd,
68     Hash,
69     Debug,
70     RustcEncodable,
71     RustcDecodable,
72     HashStable_Generic
73 )]
74 pub enum Transparency {
75     /// Identifier produced by a transparent expansion is always resolved at call-site.
76     /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
77     Transparent,
78     /// Identifier produced by a semi-transparent expansion may be resolved
79     /// either at call-site or at definition-site.
80     /// If it's a local variable, label or `$crate` then it's resolved at def-site.
81     /// Otherwise it's resolved at call-site.
82     /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
83     /// but that's an implementation detail.
84     SemiTransparent,
85     /// Identifier produced by an opaque expansion is always resolved at definition-site.
86     /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
87     Opaque,
88 }
89
90 impl ExpnId {
91     pub fn fresh(expn_data: Option<ExpnData>) -> Self {
92         HygieneData::with(|data| data.fresh_expn(expn_data))
93     }
94
95     /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
96     #[inline]
97     pub fn root() -> Self {
98         ExpnId(0)
99     }
100
101     #[inline]
102     pub fn as_u32(self) -> u32 {
103         self.0
104     }
105
106     #[inline]
107     pub fn from_u32(raw: u32) -> ExpnId {
108         ExpnId(raw)
109     }
110
111     #[inline]
112     pub fn expn_data(self) -> ExpnData {
113         HygieneData::with(|data| data.expn_data(self).clone())
114     }
115
116     #[inline]
117     pub fn set_expn_data(self, expn_data: ExpnData) {
118         HygieneData::with(|data| {
119             let old_expn_data = &mut data.expn_data[self.0 as usize];
120             assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
121             *old_expn_data = Some(expn_data);
122         })
123     }
124
125     pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
126         HygieneData::with(|data| data.is_descendant_of(self, ancestor))
127     }
128
129     /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
130     /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
131     pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
132         HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
133     }
134
135     /// Returns span for the macro which originally caused this expansion to happen.
136     ///
137     /// Stops backtracing at include! boundary.
138     pub fn expansion_cause(mut self) -> Option<Span> {
139         let mut last_macro = None;
140         loop {
141             let expn_data = self.expn_data();
142             // Stop going up the backtrace once include! is encountered
143             if expn_data.is_root()
144                 || expn_data.kind == ExpnKind::Macro(MacroKind::Bang, sym::include)
145             {
146                 break;
147             }
148             self = expn_data.call_site.ctxt().outer_expn();
149             last_macro = Some(expn_data.call_site);
150         }
151         last_macro
152     }
153 }
154
155 #[derive(Debug)]
156 crate struct HygieneData {
157     /// Each expansion should have an associated expansion data, but sometimes there's a delay
158     /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
159     /// first and then resolved later), so we use an `Option` here.
160     expn_data: Vec<Option<ExpnData>>,
161     syntax_context_data: Vec<SyntaxContextData>,
162     syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
163 }
164
165 impl HygieneData {
166     crate fn new(edition: Edition) -> Self {
167         HygieneData {
168             expn_data: vec![Some(ExpnData::default(ExpnKind::Root, DUMMY_SP, edition))],
169             syntax_context_data: vec![SyntaxContextData {
170                 outer_expn: ExpnId::root(),
171                 outer_transparency: Transparency::Opaque,
172                 parent: SyntaxContext(0),
173                 opaque: SyntaxContext(0),
174                 opaque_and_semitransparent: SyntaxContext(0),
175                 dollar_crate_name: kw::DollarCrate,
176             }],
177             syntax_context_map: FxHashMap::default(),
178         }
179     }
180
181     fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
182         GLOBALS.with(|globals| f(&mut *globals.hygiene_data.borrow_mut()))
183     }
184
185     fn fresh_expn(&mut self, expn_data: Option<ExpnData>) -> ExpnId {
186         self.expn_data.push(expn_data);
187         ExpnId(self.expn_data.len() as u32 - 1)
188     }
189
190     fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
191         self.expn_data[expn_id.0 as usize].as_ref().expect("no expansion data for an expansion ID")
192     }
193
194     fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
195         while expn_id != ancestor {
196             if expn_id == ExpnId::root() {
197                 return false;
198             }
199             expn_id = self.expn_data(expn_id).parent;
200         }
201         true
202     }
203
204     fn modern(&self, ctxt: SyntaxContext) -> SyntaxContext {
205         self.syntax_context_data[ctxt.0 as usize].opaque
206     }
207
208     fn modern_and_legacy(&self, ctxt: SyntaxContext) -> SyntaxContext {
209         self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
210     }
211
212     fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
213         self.syntax_context_data[ctxt.0 as usize].outer_expn
214     }
215
216     fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
217         let data = &self.syntax_context_data[ctxt.0 as usize];
218         (data.outer_expn, data.outer_transparency)
219     }
220
221     fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
222         self.syntax_context_data[ctxt.0 as usize].parent
223     }
224
225     fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
226         let outer_mark = self.outer_mark(*ctxt);
227         *ctxt = self.parent_ctxt(*ctxt);
228         outer_mark
229     }
230
231     fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
232         let mut marks = Vec::new();
233         while ctxt != SyntaxContext::root() {
234             marks.push(self.outer_mark(ctxt));
235             ctxt = self.parent_ctxt(ctxt);
236         }
237         marks.reverse();
238         marks
239     }
240
241     fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
242         while span.from_expansion() && span.ctxt() != to {
243             span = self.expn_data(self.outer_expn(span.ctxt())).call_site;
244         }
245         span
246     }
247
248     fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
249         let mut scope = None;
250         while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
251             scope = Some(self.remove_mark(ctxt).0);
252         }
253         scope
254     }
255
256     fn apply_mark(
257         &mut self,
258         ctxt: SyntaxContext,
259         expn_id: ExpnId,
260         transparency: Transparency,
261     ) -> SyntaxContext {
262         assert_ne!(expn_id, ExpnId::root());
263         if transparency == Transparency::Opaque {
264             return self.apply_mark_internal(ctxt, expn_id, transparency);
265         }
266
267         let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
268         let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
269             self.modern(call_site_ctxt)
270         } else {
271             self.modern_and_legacy(call_site_ctxt)
272         };
273
274         if call_site_ctxt == SyntaxContext::root() {
275             return self.apply_mark_internal(ctxt, expn_id, transparency);
276         }
277
278         // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
279         // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
280         //
281         // In this case, the tokens from the macros 1.0 definition inherit the hygiene
282         // at their invocation. That is, we pretend that the macros 1.0 definition
283         // was defined at its invocation (i.e., inside the macros 2.0 definition)
284         // so that the macros 2.0 definition remains hygienic.
285         //
286         // See the example at `test/ui/hygiene/legacy_interaction.rs`.
287         for (expn_id, transparency) in self.marks(ctxt) {
288             call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency);
289         }
290         self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
291     }
292
293     fn apply_mark_internal(
294         &mut self,
295         ctxt: SyntaxContext,
296         expn_id: ExpnId,
297         transparency: Transparency,
298     ) -> SyntaxContext {
299         let syntax_context_data = &mut self.syntax_context_data;
300         let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
301         let mut opaque_and_semitransparent =
302             syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
303
304         if transparency >= Transparency::Opaque {
305             let parent = opaque;
306             opaque = *self
307                 .syntax_context_map
308                 .entry((parent, expn_id, transparency))
309                 .or_insert_with(|| {
310                     let new_opaque = SyntaxContext(syntax_context_data.len() as u32);
311                     syntax_context_data.push(SyntaxContextData {
312                         outer_expn: expn_id,
313                         outer_transparency: transparency,
314                         parent,
315                         opaque: new_opaque,
316                         opaque_and_semitransparent: new_opaque,
317                         dollar_crate_name: kw::DollarCrate,
318                     });
319                     new_opaque
320                 });
321         }
322
323         if transparency >= Transparency::SemiTransparent {
324             let parent = opaque_and_semitransparent;
325             opaque_and_semitransparent = *self
326                 .syntax_context_map
327                 .entry((parent, expn_id, transparency))
328                 .or_insert_with(|| {
329                     let new_opaque_and_semitransparent =
330                         SyntaxContext(syntax_context_data.len() as u32);
331                     syntax_context_data.push(SyntaxContextData {
332                         outer_expn: expn_id,
333                         outer_transparency: transparency,
334                         parent,
335                         opaque,
336                         opaque_and_semitransparent: new_opaque_and_semitransparent,
337                         dollar_crate_name: kw::DollarCrate,
338                     });
339                     new_opaque_and_semitransparent
340                 });
341         }
342
343         let parent = ctxt;
344         *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
345             let new_opaque_and_semitransparent_and_transparent =
346                 SyntaxContext(syntax_context_data.len() as u32);
347             syntax_context_data.push(SyntaxContextData {
348                 outer_expn: expn_id,
349                 outer_transparency: transparency,
350                 parent,
351                 opaque,
352                 opaque_and_semitransparent,
353                 dollar_crate_name: kw::DollarCrate,
354             });
355             new_opaque_and_semitransparent_and_transparent
356         })
357     }
358 }
359
360 pub fn clear_syntax_context_map() {
361     HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
362 }
363
364 pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
365     HygieneData::with(|data| data.walk_chain(span, to))
366 }
367
368 pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
369     // The new contexts that need updating are at the end of the list and have `$crate` as a name.
370     let (len, to_update) = HygieneData::with(|data| {
371         (
372             data.syntax_context_data.len(),
373             data.syntax_context_data
374                 .iter()
375                 .rev()
376                 .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate)
377                 .count(),
378         )
379     });
380     // The callback must be called from outside of the `HygieneData` lock,
381     // since it will try to acquire it too.
382     let range_to_update = len - to_update..len;
383     let names: Vec<_> =
384         range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
385     HygieneData::with(|data| {
386         range_to_update.zip(names.into_iter()).for_each(|(idx, name)| {
387             data.syntax_context_data[idx].dollar_crate_name = name;
388         })
389     })
390 }
391
392 pub fn debug_hygiene_data(verbose: bool) -> String {
393     HygieneData::with(|data| {
394         if verbose {
395             format!("{:#?}", data)
396         } else {
397             let mut s = String::from("");
398             s.push_str("Expansions:");
399             data.expn_data.iter().enumerate().for_each(|(id, expn_info)| {
400                 let expn_info = expn_info.as_ref().expect("no expansion data for an expansion ID");
401                 s.push_str(&format!(
402                     "\n{}: parent: {:?}, call_site_ctxt: {:?}, kind: {:?}",
403                     id,
404                     expn_info.parent,
405                     expn_info.call_site.ctxt(),
406                     expn_info.kind,
407                 ));
408             });
409             s.push_str("\n\nSyntaxContexts:");
410             data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
411                 s.push_str(&format!(
412                     "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
413                     id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
414                 ));
415             });
416             s
417         }
418     })
419 }
420
421 impl SyntaxContext {
422     #[inline]
423     pub const fn root() -> Self {
424         SyntaxContext(0)
425     }
426
427     #[inline]
428     crate fn as_u32(self) -> u32 {
429         self.0
430     }
431
432     #[inline]
433     crate fn from_u32(raw: u32) -> SyntaxContext {
434         SyntaxContext(raw)
435     }
436
437     /// Extend a syntax context with a given expansion and transparency.
438     crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
439         HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
440     }
441
442     /// Pulls a single mark off of the syntax context. This effectively moves the
443     /// context up one macro definition level. That is, if we have a nested macro
444     /// definition as follows:
445     ///
446     /// ```rust
447     /// macro_rules! f {
448     ///    macro_rules! g {
449     ///        ...
450     ///    }
451     /// }
452     /// ```
453     ///
454     /// and we have a SyntaxContext that is referring to something declared by an invocation
455     /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
456     /// invocation of f that created g1.
457     /// Returns the mark that was removed.
458     pub fn remove_mark(&mut self) -> ExpnId {
459         HygieneData::with(|data| data.remove_mark(self).0)
460     }
461
462     pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
463         HygieneData::with(|data| data.marks(self))
464     }
465
466     /// Adjust this context for resolution in a scope created by the given expansion.
467     /// For example, consider the following three resolutions of `f`:
468     ///
469     /// ```rust
470     /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
471     /// m!(f);
472     /// macro m($f:ident) {
473     ///     mod bar {
474     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
475     ///         pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
476     ///     }
477     ///     foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
478     ///     //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
479     ///     //| and it resolves to `::foo::f`.
480     ///     bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
481     ///     //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
482     ///     //| and it resolves to `::bar::f`.
483     ///     bar::$f(); // `f`'s `SyntaxContext` is empty.
484     ///     //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
485     ///     //| and it resolves to `::bar::$f`.
486     /// }
487     /// ```
488     /// This returns the expansion whose definition scope we use to privacy check the resolution,
489     /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
490     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
491         HygieneData::with(|data| data.adjust(self, expn_id))
492     }
493
494     /// Like `SyntaxContext::adjust`, but also modernizes `self`.
495     pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
496         HygieneData::with(|data| {
497             *self = data.modern(*self);
498             data.adjust(self, expn_id)
499         })
500     }
501
502     /// Adjust this context for resolution in a scope created by the given expansion
503     /// via a glob import with the given `SyntaxContext`.
504     /// For example:
505     ///
506     /// ```rust
507     /// m!(f);
508     /// macro m($i:ident) {
509     ///     mod foo {
510     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
511     ///         pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
512     ///     }
513     ///     n(f);
514     ///     macro n($j:ident) {
515     ///         use foo::*;
516     ///         f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
517     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
518     ///         $i(); // `$i`'s `SyntaxContext` has a mark from `n`
519     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
520     ///         $j(); // `$j`'s `SyntaxContext` has a mark from `m`
521     ///         //^ This cannot be glob-adjusted, so this is a resolution error.
522     ///     }
523     /// }
524     /// ```
525     /// This returns `None` if the context cannot be glob-adjusted.
526     /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
527     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
528         HygieneData::with(|data| {
529             let mut scope = None;
530             let mut glob_ctxt = data.modern(glob_span.ctxt());
531             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
532                 scope = Some(data.remove_mark(&mut glob_ctxt).0);
533                 if data.remove_mark(self).0 != scope.unwrap() {
534                     return None;
535                 }
536             }
537             if data.adjust(self, expn_id).is_some() {
538                 return None;
539             }
540             Some(scope)
541         })
542     }
543
544     /// Undo `glob_adjust` if possible:
545     ///
546     /// ```rust
547     /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
548     ///     assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
549     /// }
550     /// ```
551     pub fn reverse_glob_adjust(
552         &mut self,
553         expn_id: ExpnId,
554         glob_span: Span,
555     ) -> Option<Option<ExpnId>> {
556         HygieneData::with(|data| {
557             if data.adjust(self, expn_id).is_some() {
558                 return None;
559             }
560
561             let mut glob_ctxt = data.modern(glob_span.ctxt());
562             let mut marks = Vec::new();
563             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
564                 marks.push(data.remove_mark(&mut glob_ctxt));
565             }
566
567             let scope = marks.last().map(|mark| mark.0);
568             while let Some((expn_id, transparency)) = marks.pop() {
569                 *self = data.apply_mark(*self, expn_id, transparency);
570             }
571             Some(scope)
572         })
573     }
574
575     pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
576         HygieneData::with(|data| {
577             let mut self_modern = data.modern(self);
578             data.adjust(&mut self_modern, expn_id);
579             self_modern == data.modern(other)
580         })
581     }
582
583     #[inline]
584     pub fn modern(self) -> SyntaxContext {
585         HygieneData::with(|data| data.modern(self))
586     }
587
588     #[inline]
589     pub fn modern_and_legacy(self) -> SyntaxContext {
590         HygieneData::with(|data| data.modern_and_legacy(self))
591     }
592
593     #[inline]
594     pub fn outer_expn(self) -> ExpnId {
595         HygieneData::with(|data| data.outer_expn(self))
596     }
597
598     /// `ctxt.outer_expn_data()` is equivalent to but faster than
599     /// `ctxt.outer_expn().expn_data()`.
600     #[inline]
601     pub fn outer_expn_data(self) -> ExpnData {
602         HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
603     }
604
605     #[inline]
606     pub fn outer_mark_with_data(self) -> (ExpnId, Transparency, ExpnData) {
607         HygieneData::with(|data| {
608             let (expn_id, transparency) = data.outer_mark(self);
609             (expn_id, transparency, data.expn_data(expn_id).clone())
610         })
611     }
612
613     pub fn dollar_crate_name(self) -> Symbol {
614         HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
615     }
616 }
617
618 impl fmt::Debug for SyntaxContext {
619     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620         write!(f, "#{}", self.0)
621     }
622 }
623
624 impl Span {
625     /// Creates a fresh expansion with given properties.
626     /// Expansions are normally created by macros, but in some cases expansions are created for
627     /// other compiler-generated code to set per-span properties like allowed unstable features.
628     /// The returned span belongs to the created expansion and has the new properties,
629     /// but its location is inherited from the current span.
630     pub fn fresh_expansion(self, expn_data: ExpnData) -> Span {
631         self.fresh_expansion_with_transparency(expn_data, Transparency::Transparent)
632     }
633
634     pub fn fresh_expansion_with_transparency(
635         self,
636         expn_data: ExpnData,
637         transparency: Transparency,
638     ) -> Span {
639         HygieneData::with(|data| {
640             let expn_id = data.fresh_expn(Some(expn_data));
641             self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency))
642         })
643     }
644 }
645
646 /// A subset of properties from both macro definition and macro call available through global data.
647 /// Avoid using this if you have access to the original definition or call structures.
648 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
649 pub struct ExpnData {
650     // --- The part unique to each expansion.
651     /// The kind of this expansion - macro or compiler desugaring.
652     pub kind: ExpnKind,
653     /// The expansion that produced this expansion.
654     #[stable_hasher(ignore)]
655     pub parent: ExpnId,
656     /// The location of the actual macro invocation or syntax sugar , e.g.
657     /// `let x = foo!();` or `if let Some(y) = x {}`
658     ///
659     /// This may recursively refer to other macro invocations, e.g., if
660     /// `foo!()` invoked `bar!()` internally, and there was an
661     /// expression inside `bar!`; the call_site of the expression in
662     /// the expansion would point to the `bar!` invocation; that
663     /// call_site span would have its own ExpnData, with the call_site
664     /// pointing to the `foo!` invocation.
665     pub call_site: Span,
666
667     // --- The part specific to the macro/desugaring definition.
668     // --- It may be reasonable to share this part between expansions with the same definition,
669     // --- but such sharing is known to bring some minor inconveniences without also bringing
670     // --- noticeable perf improvements (PR #62898).
671     /// The span of the macro definition (possibly dummy).
672     /// This span serves only informational purpose and is not used for resolution.
673     pub def_site: Span,
674     /// List of #[unstable]/feature-gated features that the macro is allowed to use
675     /// internally without forcing the whole crate to opt-in
676     /// to them.
677     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
678     /// Whether the macro is allowed to use `unsafe` internally
679     /// even if the user crate has `#![forbid(unsafe_code)]`.
680     pub allow_internal_unsafe: bool,
681     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
682     /// for a given macro.
683     pub local_inner_macros: bool,
684     /// Edition of the crate in which the macro is defined.
685     pub edition: Edition,
686 }
687
688 impl ExpnData {
689     /// Constructs expansion data with default properties.
690     pub fn default(kind: ExpnKind, call_site: Span, edition: Edition) -> ExpnData {
691         ExpnData {
692             kind,
693             parent: ExpnId::root(),
694             call_site,
695             def_site: DUMMY_SP,
696             allow_internal_unstable: None,
697             allow_internal_unsafe: false,
698             local_inner_macros: false,
699             edition,
700         }
701     }
702
703     pub fn allow_unstable(
704         kind: ExpnKind,
705         call_site: Span,
706         edition: Edition,
707         allow_internal_unstable: Lrc<[Symbol]>,
708     ) -> ExpnData {
709         ExpnData {
710             allow_internal_unstable: Some(allow_internal_unstable),
711             ..ExpnData::default(kind, call_site, edition)
712         }
713     }
714
715     #[inline]
716     pub fn is_root(&self) -> bool {
717         if let ExpnKind::Root = self.kind { true } else { false }
718     }
719 }
720
721 /// Expansion kind.
722 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
723 pub enum ExpnKind {
724     /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
725     Root,
726     /// Expansion produced by a macro.
727     Macro(MacroKind, Symbol),
728     /// Transform done by the compiler on the AST.
729     AstPass(AstPass),
730     /// Desugaring done by the compiler during HIR lowering.
731     Desugaring(DesugaringKind),
732 }
733
734 impl ExpnKind {
735     pub fn descr(&self) -> String {
736         match *self {
737             ExpnKind::Root => kw::PathRoot.to_string(),
738             ExpnKind::Macro(macro_kind, name) => match macro_kind {
739                 MacroKind::Bang => format!("{}!", name),
740                 MacroKind::Attr => format!("#[{}]", name),
741                 MacroKind::Derive => format!("#[derive({})]", name),
742             },
743             ExpnKind::AstPass(kind) => kind.descr().to_string(),
744             ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()),
745         }
746     }
747 }
748
749 /// The kind of macro invocation or definition.
750 #[derive(
751     Clone,
752     Copy,
753     PartialEq,
754     Eq,
755     RustcEncodable,
756     RustcDecodable,
757     Hash,
758     Debug,
759     HashStable_Generic
760 )]
761 pub enum MacroKind {
762     /// A bang macro `foo!()`.
763     Bang,
764     /// An attribute macro `#[foo]`.
765     Attr,
766     /// A derive macro `#[derive(Foo)]`
767     Derive,
768 }
769
770 impl MacroKind {
771     pub fn descr(self) -> &'static str {
772         match self {
773             MacroKind::Bang => "macro",
774             MacroKind::Attr => "attribute macro",
775             MacroKind::Derive => "derive macro",
776         }
777     }
778
779     pub fn descr_expected(self) -> &'static str {
780         match self {
781             MacroKind::Attr => "attribute",
782             _ => self.descr(),
783         }
784     }
785
786     pub fn article(self) -> &'static str {
787         match self {
788             MacroKind::Attr => "an",
789             _ => "a",
790         }
791     }
792 }
793
794 /// The kind of AST transform.
795 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
796 pub enum AstPass {
797     StdImports,
798     TestHarness,
799     ProcMacroHarness,
800 }
801
802 impl AstPass {
803     fn descr(self) -> &'static str {
804         match self {
805             AstPass::StdImports => "standard library imports",
806             AstPass::TestHarness => "test harness",
807             AstPass::ProcMacroHarness => "proc macro harness",
808         }
809     }
810 }
811
812 /// The kind of compiler desugaring.
813 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
814 pub enum DesugaringKind {
815     /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
816     /// However, we do not want to blame `c` for unreachability but rather say that `i`
817     /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
818     /// This also applies to `while` loops.
819     CondTemporary,
820     QuestionMark,
821     TryBlock,
822     /// Desugaring of an `impl Trait` in return type position
823     /// to an `type Foo = impl Trait;` and replacing the
824     /// `impl Trait` with `Foo`.
825     OpaqueTy,
826     Async,
827     Await,
828     ForLoop,
829 }
830
831 impl DesugaringKind {
832     /// The description wording should combine well with "desugaring of {}".
833     fn descr(self) -> &'static str {
834         match self {
835             DesugaringKind::CondTemporary => "`if` or `while` condition",
836             DesugaringKind::Async => "`async` block or function",
837             DesugaringKind::Await => "`await` expression",
838             DesugaringKind::QuestionMark => "operator `?`",
839             DesugaringKind::TryBlock => "`try` block",
840             DesugaringKind::OpaqueTy => "`impl Trait`",
841             DesugaringKind::ForLoop => "`for` loop",
842         }
843     }
844 }
845
846 impl Encodable for ExpnId {
847     fn encode<E: Encoder>(&self, _: &mut E) -> Result<(), E::Error> {
848         Ok(()) // FIXME(jseyfried) intercrate hygiene
849     }
850 }
851
852 impl Decodable for ExpnId {
853     fn decode<D: Decoder>(_: &mut D) -> Result<Self, D::Error> {
854         Ok(ExpnId::root()) // FIXME(jseyfried) intercrate hygiene
855     }
856 }