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