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