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