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