]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/hygiene.rs
Don't serialize ExpnData for foreign crates
[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::edition::Edition;
28 use crate::symbol::{kw, sym, Symbol};
29 use crate::SESSION_GLOBALS;
30 use crate::{Span, DUMMY_SP};
31
32 use crate::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
33 use log::*;
34 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
35 use rustc_data_structures::sync::{Lock, Lrc};
36 use rustc_macros::HashStable_Generic;
37 use rustc_serialize::{
38     Decodable, Decoder, Encodable, Encoder, UseSpecializedDecodable, UseSpecializedEncodable,
39 };
40 use std::fmt;
41
42 /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
43 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44 pub struct SyntaxContext(u32);
45
46 #[derive(Debug, RustcEncodable, RustcDecodable, Clone)]
47 pub struct SyntaxContextData {
48     outer_expn: ExpnId,
49     outer_transparency: Transparency,
50     parent: SyntaxContext,
51     /// This context, but with all transparent and semi-transparent expansions filtered away.
52     opaque: SyntaxContext,
53     /// This context, but with all transparent expansions filtered away.
54     opaque_and_semitransparent: SyntaxContext,
55     /// Name of the crate to which `$crate` with this context would resolve.
56     dollar_crate_name: Symbol,
57 }
58
59 /// A unique ID associated with a macro invocation and expansion.
60 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
61 pub struct ExpnId(u32);
62
63 /// A property of a macro expansion that determines how identifiers
64 /// produced by that expansion are resolved.
65 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, RustcEncodable, RustcDecodable)]
66 #[derive(HashStable_Generic)]
67 pub enum Transparency {
68     /// Identifier produced by a transparent expansion is always resolved at call-site.
69     /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
70     Transparent,
71     /// Identifier produced by a semi-transparent expansion may be resolved
72     /// either at call-site or at definition-site.
73     /// If it's a local variable, label or `$crate` then it's resolved at def-site.
74     /// Otherwise it's resolved at call-site.
75     /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
76     /// but that's an implementation detail.
77     SemiTransparent,
78     /// Identifier produced by an opaque expansion is always resolved at definition-site.
79     /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
80     Opaque,
81 }
82
83 pub(crate) const NUM_TRANSPARENCIES: usize = 3;
84
85 impl ExpnId {
86     pub fn fresh(expn_data: Option<ExpnData>) -> Self {
87         HygieneData::with(|data| data.fresh_expn(expn_data))
88     }
89
90     /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
91     #[inline]
92     pub fn root() -> Self {
93         ExpnId(0)
94     }
95
96     #[inline]
97     pub fn as_u32(self) -> u32 {
98         self.0
99     }
100
101     #[inline]
102     pub fn from_u32(raw: u32) -> ExpnId {
103         ExpnId(raw)
104     }
105
106     #[inline]
107     pub fn expn_data(self) -> ExpnData {
108         HygieneData::with(|data| data.expn_data(self).clone())
109     }
110
111     #[inline]
112     pub fn set_expn_data(self, mut expn_data: ExpnData) {
113         HygieneData::with(|data| {
114             let old_expn_data = &mut data.expn_data[self.0 as usize];
115             assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
116             expn_data.orig_id.replace(self.as_u32()).expect_none("orig_id should be None");
117             *old_expn_data = Some(expn_data);
118         })
119     }
120
121     pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
122         HygieneData::with(|data| data.is_descendant_of(self, ancestor))
123     }
124
125     /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
126     /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
127     pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
128         HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
129     }
130
131     /// Returns span for the macro which originally caused this expansion to happen.
132     ///
133     /// Stops backtracing at include! boundary.
134     pub fn expansion_cause(mut self) -> Option<Span> {
135         let mut last_macro = None;
136         loop {
137             let expn_data = self.expn_data();
138             // Stop going up the backtrace once include! is encountered
139             if expn_data.is_root()
140                 || expn_data.kind == ExpnKind::Macro(MacroKind::Bang, sym::include)
141             {
142                 break;
143             }
144             self = expn_data.call_site.ctxt().outer_expn();
145             last_macro = Some(expn_data.call_site);
146         }
147         last_macro
148     }
149 }
150
151 #[derive(Debug)]
152 pub struct HygieneData {
153     /// Each expansion should have an associated expansion data, but sometimes there's a delay
154     /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
155     /// first and then resolved later), so we use an `Option` here.
156     expn_data: Vec<Option<ExpnData>>,
157     syntax_context_data: Vec<SyntaxContextData>,
158     syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
159 }
160
161 impl HygieneData {
162     crate fn new(edition: Edition) -> Self {
163         let mut root_data = ExpnData::default(
164             ExpnKind::Root,
165             DUMMY_SP,
166             edition,
167             Some(DefId::local(CRATE_DEF_INDEX)),
168         );
169         root_data.orig_id = Some(0);
170
171         HygieneData {
172             expn_data: vec![Some(root_data)],
173             syntax_context_data: vec![SyntaxContextData {
174                 outer_expn: ExpnId::root(),
175                 outer_transparency: Transparency::Opaque,
176                 parent: SyntaxContext(0),
177                 opaque: SyntaxContext(0),
178                 opaque_and_semitransparent: SyntaxContext(0),
179                 dollar_crate_name: kw::DollarCrate,
180             }],
181             syntax_context_map: FxHashMap::default(),
182         }
183     }
184
185     pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
186         SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
187     }
188
189     fn fresh_expn(&mut self, mut expn_data: Option<ExpnData>) -> ExpnId {
190         let raw_id = self.expn_data.len() as u32;
191         if let Some(data) = expn_data.as_mut() {
192             data.orig_id.replace(raw_id).expect_none("orig_id should be None");
193         }
194         self.expn_data.push(expn_data);
195         ExpnId(raw_id)
196     }
197
198     fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
199         self.expn_data[expn_id.0 as usize].as_ref().expect("no expansion data for an expansion ID")
200     }
201
202     fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
203         while expn_id != ancestor {
204             if expn_id == ExpnId::root() {
205                 return false;
206             }
207             expn_id = self.expn_data(expn_id).parent;
208         }
209         true
210     }
211
212     fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
213         self.syntax_context_data[ctxt.0 as usize].opaque
214     }
215
216     fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
217         self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
218     }
219
220     fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
221         self.syntax_context_data[ctxt.0 as usize].outer_expn
222     }
223
224     fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
225         let data = &self.syntax_context_data[ctxt.0 as usize];
226         (data.outer_expn, data.outer_transparency)
227     }
228
229     fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
230         self.syntax_context_data[ctxt.0 as usize].parent
231     }
232
233     fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
234         let outer_mark = self.outer_mark(*ctxt);
235         *ctxt = self.parent_ctxt(*ctxt);
236         outer_mark
237     }
238
239     fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
240         let mut marks = Vec::new();
241         while ctxt != SyntaxContext::root() {
242             debug!("marks: getting parent of {:?}", ctxt);
243             marks.push(self.outer_mark(ctxt));
244             ctxt = self.parent_ctxt(ctxt);
245         }
246         marks.reverse();
247         marks
248     }
249
250     fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
251         debug!("walk_chain({:?}, {:?})", span, to);
252         debug!("walk_chain: span ctxt = {:?}", span.ctxt());
253         while span.from_expansion() && span.ctxt() != to {
254             let outer_expn = self.outer_expn(span.ctxt());
255             debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn);
256             let expn_data = self.expn_data(outer_expn);
257             debug!("walk_chain({:?}): expn_data={:?}", span, expn_data);
258             span = expn_data.call_site;
259         }
260         span
261     }
262
263     fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
264         let mut scope = None;
265         while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
266             scope = Some(self.remove_mark(ctxt).0);
267         }
268         scope
269     }
270
271     fn apply_mark(
272         &mut self,
273         ctxt: SyntaxContext,
274         expn_id: ExpnId,
275         transparency: Transparency,
276     ) -> SyntaxContext {
277         assert_ne!(expn_id, ExpnId::root());
278         if transparency == Transparency::Opaque {
279             return self.apply_mark_internal(ctxt, expn_id, transparency);
280         }
281
282         let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
283         let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
284             self.normalize_to_macros_2_0(call_site_ctxt)
285         } else {
286             self.normalize_to_macro_rules(call_site_ctxt)
287         };
288
289         if call_site_ctxt == SyntaxContext::root() {
290             return self.apply_mark_internal(ctxt, expn_id, transparency);
291         }
292
293         // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
294         // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
295         //
296         // In this case, the tokens from the macros 1.0 definition inherit the hygiene
297         // at their invocation. That is, we pretend that the macros 1.0 definition
298         // was defined at its invocation (i.e., inside the macros 2.0 definition)
299         // so that the macros 2.0 definition remains hygienic.
300         //
301         // See the example at `test/ui/hygiene/legacy_interaction.rs`.
302         for (expn_id, transparency) in self.marks(ctxt) {
303             call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency);
304         }
305         self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
306     }
307
308     fn apply_mark_internal(
309         &mut self,
310         ctxt: SyntaxContext,
311         expn_id: ExpnId,
312         transparency: Transparency,
313     ) -> SyntaxContext {
314         let syntax_context_data = &mut self.syntax_context_data;
315         let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
316         let mut opaque_and_semitransparent =
317             syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
318
319         if transparency >= Transparency::Opaque {
320             let parent = opaque;
321             opaque = *self
322                 .syntax_context_map
323                 .entry((parent, expn_id, transparency))
324                 .or_insert_with(|| {
325                     let new_opaque = 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: new_opaque,
331                         opaque_and_semitransparent: new_opaque,
332                         dollar_crate_name: kw::DollarCrate,
333                     });
334                     new_opaque
335                 });
336         }
337
338         if transparency >= Transparency::SemiTransparent {
339             let parent = opaque_and_semitransparent;
340             opaque_and_semitransparent = *self
341                 .syntax_context_map
342                 .entry((parent, expn_id, transparency))
343                 .or_insert_with(|| {
344                     let new_opaque_and_semitransparent =
345                         SyntaxContext(syntax_context_data.len() as u32);
346                     syntax_context_data.push(SyntaxContextData {
347                         outer_expn: expn_id,
348                         outer_transparency: transparency,
349                         parent,
350                         opaque,
351                         opaque_and_semitransparent: new_opaque_and_semitransparent,
352                         dollar_crate_name: kw::DollarCrate,
353                     });
354                     new_opaque_and_semitransparent
355                 });
356         }
357
358         let parent = ctxt;
359         *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
360             let new_opaque_and_semitransparent_and_transparent =
361                 SyntaxContext(syntax_context_data.len() as u32);
362             syntax_context_data.push(SyntaxContextData {
363                 outer_expn: expn_id,
364                 outer_transparency: transparency,
365                 parent,
366                 opaque,
367                 opaque_and_semitransparent,
368                 dollar_crate_name: kw::DollarCrate,
369             });
370             new_opaque_and_semitransparent_and_transparent
371         })
372     }
373 }
374
375 pub fn clear_syntax_context_map() {
376     HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
377 }
378
379 pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
380     HygieneData::with(|data| data.walk_chain(span, to))
381 }
382
383 pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
384     // The new contexts that need updating are at the end of the list and have `$crate` as a name.
385     let (len, to_update) = HygieneData::with(|data| {
386         (
387             data.syntax_context_data.len(),
388             data.syntax_context_data
389                 .iter()
390                 .rev()
391                 .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate)
392                 .count(),
393         )
394     });
395     // The callback must be called from outside of the `HygieneData` lock,
396     // since it will try to acquire it too.
397     let range_to_update = len - to_update..len;
398     let names: Vec<_> =
399         range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
400     HygieneData::with(|data| {
401         range_to_update.zip(names.into_iter()).for_each(|(idx, name)| {
402             data.syntax_context_data[idx].dollar_crate_name = name;
403         })
404     })
405 }
406
407 pub fn debug_hygiene_data(verbose: bool) -> String {
408     HygieneData::with(|data| {
409         if verbose {
410             format!("{:#?}", data)
411         } else {
412             let mut s = String::from("");
413             s.push_str("Expansions:");
414             data.expn_data.iter().enumerate().for_each(|(id, expn_info)| {
415                 let expn_info = expn_info.as_ref().expect("no expansion data for an expansion ID");
416                 s.push_str(&format!(
417                     "\n{}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
418                     id,
419                     expn_info.parent,
420                     expn_info.call_site.ctxt(),
421                     expn_info.def_site.ctxt(),
422                     expn_info.kind,
423                 ));
424             });
425             s.push_str("\n\nSyntaxContexts:");
426             data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
427                 s.push_str(&format!(
428                     "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
429                     id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
430                 ));
431             });
432             s
433         }
434     })
435 }
436
437 impl SyntaxContext {
438     #[inline]
439     pub const fn root() -> Self {
440         SyntaxContext(0)
441     }
442
443     #[inline]
444     crate fn as_u32(self) -> u32 {
445         self.0
446     }
447
448     #[inline]
449     crate fn from_u32(raw: u32) -> SyntaxContext {
450         SyntaxContext(raw)
451     }
452
453     /// Extend a syntax context with a given expansion and transparency.
454     crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
455         HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
456     }
457
458     /// Pulls a single mark off of the syntax context. This effectively moves the
459     /// context up one macro definition level. That is, if we have a nested macro
460     /// definition as follows:
461     ///
462     /// ```rust
463     /// macro_rules! f {
464     ///    macro_rules! g {
465     ///        ...
466     ///    }
467     /// }
468     /// ```
469     ///
470     /// and we have a SyntaxContext that is referring to something declared by an invocation
471     /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
472     /// invocation of f that created g1.
473     /// Returns the mark that was removed.
474     pub fn remove_mark(&mut self) -> ExpnId {
475         HygieneData::with(|data| data.remove_mark(self).0)
476     }
477
478     pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
479         HygieneData::with(|data| data.marks(self))
480     }
481
482     /// Adjust this context for resolution in a scope created by the given expansion.
483     /// For example, consider the following three resolutions of `f`:
484     ///
485     /// ```rust
486     /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
487     /// m!(f);
488     /// macro m($f:ident) {
489     ///     mod bar {
490     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
491     ///         pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
492     ///     }
493     ///     foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
494     ///     //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
495     ///     //| and it resolves to `::foo::f`.
496     ///     bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
497     ///     //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
498     ///     //| and it resolves to `::bar::f`.
499     ///     bar::$f(); // `f`'s `SyntaxContext` is empty.
500     ///     //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
501     ///     //| and it resolves to `::bar::$f`.
502     /// }
503     /// ```
504     /// This returns the expansion whose definition scope we use to privacy check the resolution,
505     /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
506     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
507         HygieneData::with(|data| data.adjust(self, expn_id))
508     }
509
510     /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
511     pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
512         HygieneData::with(|data| {
513             *self = data.normalize_to_macros_2_0(*self);
514             data.adjust(self, expn_id)
515         })
516     }
517
518     /// Adjust this context for resolution in a scope created by the given expansion
519     /// via a glob import with the given `SyntaxContext`.
520     /// For example:
521     ///
522     /// ```rust
523     /// m!(f);
524     /// macro m($i:ident) {
525     ///     mod foo {
526     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
527     ///         pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
528     ///     }
529     ///     n(f);
530     ///     macro n($j:ident) {
531     ///         use foo::*;
532     ///         f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
533     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
534     ///         $i(); // `$i`'s `SyntaxContext` has a mark from `n`
535     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
536     ///         $j(); // `$j`'s `SyntaxContext` has a mark from `m`
537     ///         //^ This cannot be glob-adjusted, so this is a resolution error.
538     ///     }
539     /// }
540     /// ```
541     /// This returns `None` if the context cannot be glob-adjusted.
542     /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
543     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
544         HygieneData::with(|data| {
545             let mut scope = None;
546             let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
547             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
548                 scope = Some(data.remove_mark(&mut glob_ctxt).0);
549                 if data.remove_mark(self).0 != scope.unwrap() {
550                     return None;
551                 }
552             }
553             if data.adjust(self, expn_id).is_some() {
554                 return None;
555             }
556             Some(scope)
557         })
558     }
559
560     /// Undo `glob_adjust` if possible:
561     ///
562     /// ```rust
563     /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
564     ///     assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
565     /// }
566     /// ```
567     pub fn reverse_glob_adjust(
568         &mut self,
569         expn_id: ExpnId,
570         glob_span: Span,
571     ) -> Option<Option<ExpnId>> {
572         HygieneData::with(|data| {
573             if data.adjust(self, expn_id).is_some() {
574                 return None;
575             }
576
577             let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
578             let mut marks = Vec::new();
579             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
580                 marks.push(data.remove_mark(&mut glob_ctxt));
581             }
582
583             let scope = marks.last().map(|mark| mark.0);
584             while let Some((expn_id, transparency)) = marks.pop() {
585                 *self = data.apply_mark(*self, expn_id, transparency);
586             }
587             Some(scope)
588         })
589     }
590
591     pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
592         HygieneData::with(|data| {
593             let mut self_normalized = data.normalize_to_macros_2_0(self);
594             data.adjust(&mut self_normalized, expn_id);
595             self_normalized == data.normalize_to_macros_2_0(other)
596         })
597     }
598
599     #[inline]
600     pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
601         HygieneData::with(|data| data.normalize_to_macros_2_0(self))
602     }
603
604     #[inline]
605     pub fn normalize_to_macro_rules(self) -> SyntaxContext {
606         HygieneData::with(|data| data.normalize_to_macro_rules(self))
607     }
608
609     #[inline]
610     pub fn outer_expn(self) -> ExpnId {
611         HygieneData::with(|data| data.outer_expn(self))
612     }
613
614     /// `ctxt.outer_expn_data()` is equivalent to but faster than
615     /// `ctxt.outer_expn().expn_data()`.
616     #[inline]
617     pub fn outer_expn_data(self) -> ExpnData {
618         HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
619     }
620
621     #[inline]
622     pub fn outer_mark_with_data(self) -> (ExpnId, Transparency, ExpnData) {
623         HygieneData::with(|data| {
624             let (expn_id, transparency) = data.outer_mark(self);
625             (expn_id, transparency, data.expn_data(expn_id).clone())
626         })
627     }
628
629     pub fn dollar_crate_name(self) -> Symbol {
630         HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
631     }
632 }
633
634 impl fmt::Debug for SyntaxContext {
635     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636         write!(f, "#{}", self.0)
637     }
638 }
639
640 impl Span {
641     /// Creates a fresh expansion with given properties.
642     /// Expansions are normally created by macros, but in some cases expansions are created for
643     /// other compiler-generated code to set per-span properties like allowed unstable features.
644     /// The returned span belongs to the created expansion and has the new properties,
645     /// but its location is inherited from the current span.
646     pub fn fresh_expansion(self, expn_data: ExpnData) -> Span {
647         self.fresh_expansion_with_transparency(expn_data, Transparency::Transparent)
648     }
649
650     pub fn fresh_expansion_with_transparency(
651         self,
652         expn_data: ExpnData,
653         transparency: Transparency,
654     ) -> Span {
655         HygieneData::with(|data| {
656             let expn_id = data.fresh_expn(Some(expn_data));
657             self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency))
658         })
659     }
660 }
661
662 /// A subset of properties from both macro definition and macro call available through global data.
663 /// Avoid using this if you have access to the original definition or call structures.
664 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
665 pub struct ExpnData {
666     // --- The part unique to each expansion.
667     /// The kind of this expansion - macro or compiler desugaring.
668     pub kind: ExpnKind,
669     /// The expansion that produced this expansion.
670     #[stable_hasher(ignore)]
671     pub parent: ExpnId,
672     /// The location of the actual macro invocation or syntax sugar , e.g.
673     /// `let x = foo!();` or `if let Some(y) = x {}`
674     ///
675     /// This may recursively refer to other macro invocations, e.g., if
676     /// `foo!()` invoked `bar!()` internally, and there was an
677     /// expression inside `bar!`; the call_site of the expression in
678     /// the expansion would point to the `bar!` invocation; that
679     /// call_site span would have its own ExpnData, with the call_site
680     /// pointing to the `foo!` invocation.
681     pub call_site: Span,
682
683     // --- The part specific to the macro/desugaring definition.
684     // --- It may be reasonable to share this part between expansions with the same definition,
685     // --- but such sharing is known to bring some minor inconveniences without also bringing
686     // --- noticeable perf improvements (PR #62898).
687     /// The span of the macro definition (possibly dummy).
688     /// This span serves only informational purpose and is not used for resolution.
689     pub def_site: Span,
690     /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
691     /// internally without forcing the whole crate to opt-in
692     /// to them.
693     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
694     /// Whether the macro is allowed to use `unsafe` internally
695     /// even if the user crate has `#![forbid(unsafe_code)]`.
696     pub allow_internal_unsafe: bool,
697     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
698     /// for a given macro.
699     pub local_inner_macros: bool,
700     /// Edition of the crate in which the macro is defined.
701     pub edition: Edition,
702     /// The `DefId` of the macro being invoked,
703     /// if this `ExpnData` corresponds to a macro invocation
704     pub macro_def_id: Option<DefId>,
705     /// The crate that originally created this `ExpnData. During
706     /// metadata serialization, we only encode `ExpnData`s that were
707     /// created locally - when our serialized metadata is decoded,
708     /// foreign `ExpnId`s will have their `ExpnData` looked up
709     /// from the crate specified by `Crate
710     pub krate: CrateNum,
711     /// The raw that this `ExpnData` had in its original crate.
712     /// An `ExpnData` can be created before being assigned an `ExpnId`,
713     /// so this might be `None` until `set_expn_data` is called
714     // This is used only for serialization/deserialization purposes:
715     // two `ExpnData`s that differ only in their `orig_id` should
716     // be considered equivalent.
717     #[stable_hasher(ignore)]
718     pub orig_id: Option<u32>,
719 }
720
721 // This would require special handling of `orig_id` and `parent`
722 impl !PartialEq for ExpnData {}
723
724 impl ExpnData {
725     /// Constructs expansion data with default properties.
726     pub fn default(
727         kind: ExpnKind,
728         call_site: Span,
729         edition: Edition,
730         macro_def_id: Option<DefId>,
731     ) -> ExpnData {
732         ExpnData {
733             kind,
734             parent: ExpnId::root(),
735             call_site,
736             def_site: DUMMY_SP,
737             allow_internal_unstable: None,
738             allow_internal_unsafe: false,
739             local_inner_macros: false,
740             edition,
741             macro_def_id,
742             krate: LOCAL_CRATE,
743             orig_id: None,
744         }
745     }
746
747     pub fn allow_unstable(
748         kind: ExpnKind,
749         call_site: Span,
750         edition: Edition,
751         allow_internal_unstable: Lrc<[Symbol]>,
752         macro_def_id: Option<DefId>,
753     ) -> ExpnData {
754         ExpnData {
755             allow_internal_unstable: Some(allow_internal_unstable),
756             ..ExpnData::default(kind, call_site, edition, macro_def_id)
757         }
758     }
759
760     #[inline]
761     pub fn is_root(&self) -> bool {
762         if let ExpnKind::Root = self.kind { true } else { false }
763     }
764 }
765
766 /// Expansion kind.
767 #[derive(Clone, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
768 pub enum ExpnKind {
769     /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
770     Root,
771     /// Expansion produced by a macro.
772     Macro(MacroKind, Symbol),
773     /// Transform done by the compiler on the AST.
774     AstPass(AstPass),
775     /// Desugaring done by the compiler during HIR lowering.
776     Desugaring(DesugaringKind),
777 }
778
779 impl ExpnKind {
780     pub fn descr(&self) -> String {
781         match *self {
782             ExpnKind::Root => kw::PathRoot.to_string(),
783             ExpnKind::Macro(macro_kind, name) => match macro_kind {
784                 MacroKind::Bang => format!("{}!", name),
785                 MacroKind::Attr => format!("#[{}]", name),
786                 MacroKind::Derive => format!("#[derive({})]", name),
787             },
788             ExpnKind::AstPass(kind) => kind.descr().to_string(),
789             ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()),
790         }
791     }
792 }
793
794 /// The kind of macro invocation or definition.
795 #[derive(Clone, Copy, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
796 #[derive(HashStable_Generic)]
797 pub enum MacroKind {
798     /// A bang macro `foo!()`.
799     Bang,
800     /// An attribute macro `#[foo]`.
801     Attr,
802     /// A derive macro `#[derive(Foo)]`
803     Derive,
804 }
805
806 impl MacroKind {
807     pub fn descr(self) -> &'static str {
808         match self {
809             MacroKind::Bang => "macro",
810             MacroKind::Attr => "attribute macro",
811             MacroKind::Derive => "derive macro",
812         }
813     }
814
815     pub fn descr_expected(self) -> &'static str {
816         match self {
817             MacroKind::Attr => "attribute",
818             _ => self.descr(),
819         }
820     }
821
822     pub fn article(self) -> &'static str {
823         match self {
824             MacroKind::Attr => "an",
825             _ => "a",
826         }
827     }
828 }
829
830 /// The kind of AST transform.
831 #[derive(Clone, Copy, Debug, PartialEq, RustcEncodable, RustcDecodable, HashStable_Generic)]
832 pub enum AstPass {
833     StdImports,
834     TestHarness,
835     ProcMacroHarness,
836 }
837
838 impl AstPass {
839     fn descr(self) -> &'static str {
840         match self {
841             AstPass::StdImports => "standard library imports",
842             AstPass::TestHarness => "test harness",
843             AstPass::ProcMacroHarness => "proc macro harness",
844         }
845     }
846 }
847
848 /// The kind of compiler desugaring.
849 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
850 pub enum DesugaringKind {
851     /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
852     /// However, we do not want to blame `c` for unreachability but rather say that `i`
853     /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
854     /// This also applies to `while` loops.
855     CondTemporary,
856     QuestionMark,
857     TryBlock,
858     /// Desugaring of an `impl Trait` in return type position
859     /// to an `type Foo = impl Trait;` and replacing the
860     /// `impl Trait` with `Foo`.
861     OpaqueTy,
862     Async,
863     Await,
864     ForLoop(ForLoopLoc),
865 }
866
867 /// A location in the desugaring of a `for` loop
868 #[derive(Clone, Copy, PartialEq, Debug, RustcEncodable, RustcDecodable, HashStable_Generic)]
869 pub enum ForLoopLoc {
870     Head,
871     IntoIter,
872 }
873
874 impl DesugaringKind {
875     /// The description wording should combine well with "desugaring of {}".
876     fn descr(self) -> &'static str {
877         match self {
878             DesugaringKind::CondTemporary => "`if` or `while` condition",
879             DesugaringKind::Async => "`async` block or function",
880             DesugaringKind::Await => "`await` expression",
881             DesugaringKind::QuestionMark => "operator `?`",
882             DesugaringKind::TryBlock => "`try` block",
883             DesugaringKind::OpaqueTy => "`impl Trait`",
884             DesugaringKind::ForLoop(_) => "`for` loop",
885         }
886     }
887 }
888
889 impl UseSpecializedEncodable for ExpnId {}
890 impl UseSpecializedDecodable for ExpnId {}
891
892 #[derive(Default)]
893 pub struct HygieneEncodeContext {
894     /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
895     /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
896     /// that we don't accidentally try to encode any more `SyntaxContexts`
897     serialized_ctxts: Lock<FxHashSet<SyntaxContext>>,
898     /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
899     /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData`
900     /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
901     /// until we reach a fixed point.
902     latest_ctxts: Lock<FxHashSet<SyntaxContext>>,
903
904     serialized_expns: Lock<FxHashSet<ExpnId>>,
905
906     latest_expns: Lock<FxHashSet<ExpnId>>,
907 }
908
909 impl HygieneEncodeContext {
910     pub fn encode<
911         T,
912         R,
913         F: FnMut(&mut T, u32, &SyntaxContextData) -> Result<(), R>,
914         G: FnMut(&mut T, u32, &ExpnData) -> Result<(), R>,
915     >(
916         &self,
917         encoder: &mut T,
918         mut encode_ctxt: F,
919         mut encode_expn: G,
920     ) -> Result<(), R> {
921         // When we serialize a `SyntaxContextData`, we may end up serializing
922         // a `SyntaxContext` that we haven't seen before
923         while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() {
924             debug!(
925                 "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}",
926                 self.latest_ctxts.lock().len(),
927                 self.latest_ctxts
928             );
929
930             // Consume the current round of SyntaxContexts.
931             // Drop the lock() temporary early
932             let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) };
933
934             // It's fine to iterate over a HashMap, because the serialization
935             // of the table that we insert data into doesn't depend on insertion
936             // order
937             for_all_ctxts_in(latest_ctxts.into_iter(), |(index, ctxt, data)| {
938                 if self.serialized_ctxts.lock().insert(ctxt) {
939                     encode_ctxt(encoder, index, data)?;
940                 }
941                 Ok(())
942             })?;
943
944             let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) };
945
946             for_all_expns_in(latest_expns.into_iter(), |index, expn, data| {
947                 if self.serialized_expns.lock().insert(expn) {
948                     encode_expn(encoder, index, data)?;
949                 }
950                 Ok(())
951             })?;
952         }
953         debug!("encode_hygiene: Done serializing SyntaxContextData");
954         Ok(())
955     }
956 }
957
958 #[derive(Default)]
959 /// Additional information used to assist in decoding hygiene data
960 pub struct HygieneDecodeContext {
961     // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
962     // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
963     // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
964     // so that multiple occurrences of the same serialized id are decoded to the same
965     // `SyntaxContext`
966     remapped_ctxts: Lock<Vec<Option<SyntaxContext>>>,
967     // The same as `remapepd_ctxts`, but for `ExpnId`s
968     remapped_expns: Lock<Vec<Option<ExpnId>>>,
969 }
970
971 pub fn decode_expn_id<
972     'a,
973     D: Decoder,
974     F: FnOnce(&mut D, u32) -> Result<ExpnData, D::Error>,
975     G: FnOnce(CrateNum) -> &'a HygieneDecodeContext,
976 >(
977     d: &mut D,
978     mode: ExpnDataDecodeMode<'a, G>,
979     decode_data: F,
980 ) -> Result<ExpnId, D::Error> {
981     let index = u32::decode(d)?;
982     let context = match mode {
983         ExpnDataDecodeMode::IncrComp(context) => context,
984         ExpnDataDecodeMode::Metadata(get_context) => {
985             let krate = CrateNum::decode(d)?;
986             get_context(krate)
987         }
988     };
989
990     // Do this after decoding, so that we decode a `CrateNum`
991     // if necessary
992     if index == ExpnId::root().as_u32() {
993         debug!("decode_expn_id: deserialized root");
994         return Ok(ExpnId::root());
995     }
996
997     let outer_expns = &context.remapped_expns;
998
999     // Ensure that the lock() temporary is dropped early
1000     {
1001         if let Some(expn_id) = outer_expns.lock().get(index as usize).copied().flatten() {
1002             return Ok(expn_id);
1003         }
1004     }
1005
1006     // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1007     // other ExpnIds
1008     let mut expn_data = decode_data(d, index)?;
1009
1010     let expn_id = HygieneData::with(|hygiene_data| {
1011         let expn_id = ExpnId(hygiene_data.expn_data.len() as u32);
1012
1013         // If we just deserialized an `ExpnData` owned by
1014         // the local crate, its `orig_id` will be stale,
1015         // so we need to update it to its own value.
1016         // This only happens when we deserialize the incremental cache,
1017         // since a crate will never decode its own metadata.
1018         if expn_data.krate == LOCAL_CRATE {
1019             expn_data.orig_id = Some(expn_id.0);
1020         }
1021
1022         hygiene_data.expn_data.push(Some(expn_data));
1023
1024         let mut expns = outer_expns.lock();
1025         let new_len = index as usize + 1;
1026         if expns.len() < new_len {
1027             expns.resize(new_len, None);
1028         }
1029         expns[index as usize] = Some(expn_id);
1030         drop(expns);
1031         expn_id
1032     });
1033     return Ok(expn_id);
1034 }
1035
1036 // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1037 // to track which `SyntaxContext`s we have already decoded.
1038 // The provided closure will be invoked to deserialize a `SyntaxContextData`
1039 // if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1040 pub fn decode_syntax_context<
1041     D: Decoder,
1042     F: FnOnce(&mut D, u32) -> Result<SyntaxContextData, D::Error>,
1043 >(
1044     d: &mut D,
1045     context: &HygieneDecodeContext,
1046     decode_data: F,
1047 ) -> Result<SyntaxContext, D::Error> {
1048     let raw_id: u32 = Decodable::decode(d)?;
1049     if raw_id == 0 {
1050         debug!("decode_syntax_context: deserialized root");
1051         // The root is special
1052         return Ok(SyntaxContext::root());
1053     }
1054
1055     let outer_ctxts = &context.remapped_ctxts;
1056
1057     // Ensure that the lock() temporary is dropped early
1058     {
1059         if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1060             return Ok(ctxt);
1061         }
1062     }
1063
1064     // Allocate and store SyntaxContext id *before* calling the decoder function,
1065     // as the SyntaxContextData may reference itself.
1066     let new_ctxt = HygieneData::with(|hygiene_data| {
1067         let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
1068         // Push a dummy SyntaxContextData to ensure that nobody else can get the
1069         // same ID as us. This will be overwritten after call `decode_Data`
1070         hygiene_data.syntax_context_data.push(SyntaxContextData {
1071             outer_expn: ExpnId::root(),
1072             outer_transparency: Transparency::Transparent,
1073             parent: SyntaxContext::root(),
1074             opaque: SyntaxContext::root(),
1075             opaque_and_semitransparent: SyntaxContext::root(),
1076             dollar_crate_name: kw::Invalid,
1077         });
1078         let mut ctxts = outer_ctxts.lock();
1079         let new_len = raw_id as usize + 1;
1080         if ctxts.len() < new_len {
1081             ctxts.resize(new_len, None);
1082         }
1083         ctxts[raw_id as usize] = Some(new_ctxt);
1084         drop(ctxts);
1085         new_ctxt
1086     });
1087
1088     // Don't try to decode data while holding the lock, since we need to
1089     // be able to recursively decode a SyntaxContext
1090     let mut ctxt_data = decode_data(d, raw_id)?;
1091     // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1092     // We don't care what the encoding crate set this to - we want to resolve it
1093     // from the perspective of the current compilation session
1094     ctxt_data.dollar_crate_name = kw::DollarCrate;
1095
1096     // Overwrite the dummy data with our decoded SyntaxContextData
1097     HygieneData::with(|hygiene_data| {
1098         let dummy = std::mem::replace(
1099             &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize],
1100             ctxt_data,
1101         );
1102         // Make sure nothing weird happening while `decode_data` was running
1103         assert_eq!(dummy.dollar_crate_name, kw::Invalid);
1104     });
1105
1106     return Ok(new_ctxt);
1107 }
1108
1109 pub fn num_syntax_ctxts() -> usize {
1110     HygieneData::with(|data| data.syntax_context_data.len())
1111 }
1112
1113 pub fn for_all_ctxts_in<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1114     ctxts: impl Iterator<Item = SyntaxContext>,
1115     mut f: F,
1116 ) -> Result<(), E> {
1117     let all_data: Vec<_> = HygieneData::with(|data| {
1118         ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect()
1119     });
1120     for (ctxt, data) in all_data.into_iter() {
1121         f((ctxt.0, ctxt, &data))?;
1122     }
1123     Ok(())
1124 }
1125
1126 pub fn for_all_expns_in<E, F: FnMut(u32, ExpnId, &ExpnData) -> Result<(), E>>(
1127     expns: impl Iterator<Item = ExpnId>,
1128     mut f: F,
1129 ) -> Result<(), E> {
1130     let all_data: Vec<_> = HygieneData::with(|data| {
1131         expns.map(|expn| (expn, data.expn_data[expn.0 as usize].clone())).collect()
1132     });
1133     for (expn, data) in all_data.into_iter() {
1134         f(expn.0, expn, &data.unwrap_or_else(|| panic!("Missing data for {:?}", expn)))?;
1135     }
1136     Ok(())
1137 }
1138 pub fn for_all_data<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1139     mut f: F,
1140 ) -> Result<(), E> {
1141     let all_data = HygieneData::with(|data| data.syntax_context_data.clone());
1142     for (i, data) in all_data.into_iter().enumerate() {
1143         f((i as u32, SyntaxContext(i as u32), &data))?;
1144     }
1145     Ok(())
1146 }
1147
1148 pub fn for_all_expn_data<E, F: FnMut(u32, &ExpnData) -> Result<(), E>>(mut f: F) -> Result<(), E> {
1149     let all_data = HygieneData::with(|data| data.expn_data.clone());
1150     for (i, data) in all_data.into_iter().enumerate() {
1151         f(i as u32, &data.unwrap_or_else(|| panic!("Missing ExpnData!")))?;
1152     }
1153     Ok(())
1154 }
1155
1156 pub fn raw_encode_syntax_context<E: Encoder>(
1157     ctxt: SyntaxContext,
1158     context: &HygieneEncodeContext,
1159     e: &mut E,
1160 ) -> Result<(), E::Error> {
1161     if !context.serialized_ctxts.lock().contains(&ctxt) {
1162         context.latest_ctxts.lock().insert(ctxt);
1163     }
1164     ctxt.0.encode(e)
1165 }
1166
1167 pub fn raw_encode_expn_id<E: Encoder>(
1168     expn: ExpnId,
1169     context: &HygieneEncodeContext,
1170     mode: ExpnDataEncodeMode,
1171     e: &mut E,
1172 ) -> Result<(), E::Error> {
1173     // Record the fact that we need to serialize the corresponding
1174     // `ExpnData`
1175     let needs_data = || {
1176         if !context.serialized_expns.lock().contains(&expn) {
1177             context.latest_expns.lock().insert(expn);
1178         }
1179     };
1180
1181     match mode {
1182         ExpnDataEncodeMode::IncrComp => {
1183             // Always serialize the `ExpnData` in incr comp mode
1184             needs_data();
1185             expn.0.encode(e)
1186         }
1187         ExpnDataEncodeMode::Metadata => {
1188             let data = expn.expn_data();
1189             // We only need to serialize the ExpnData
1190             // if it comes from this crate.
1191             if data.krate == LOCAL_CRATE {
1192                 needs_data();
1193             }
1194             data.orig_id.expect("Missing orig_id").encode(e)?;
1195             data.krate.encode(e)
1196         }
1197     }
1198 }
1199
1200 pub enum ExpnDataEncodeMode {
1201     IncrComp,
1202     Metadata,
1203 }
1204
1205 pub enum ExpnDataDecodeMode<'a, F: FnOnce(CrateNum) -> &'a HygieneDecodeContext> {
1206     IncrComp(&'a HygieneDecodeContext),
1207     Metadata(F),
1208 }
1209
1210 impl<'a> ExpnDataDecodeMode<'a, Box<dyn FnOnce(CrateNum) -> &'a HygieneDecodeContext>> {
1211     pub fn incr_comp(ctxt: &'a HygieneDecodeContext) -> Self {
1212         ExpnDataDecodeMode::IncrComp(ctxt)
1213     }
1214 }
1215
1216 impl UseSpecializedEncodable for SyntaxContext {}
1217 impl UseSpecializedDecodable for SyntaxContext {}