]> git.lizzy.rs Git - rust.git/blob - src/librustc_span/hygiene.rs
Rework `rustc_serialize`
[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::{Decodable, Decoder, Encodable, Encoder};
38 use std::fmt;
39
40 /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
41 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42 pub struct SyntaxContext(u32);
43
44 #[derive(Debug, Encodable, Decodable, Clone)]
45 pub struct SyntaxContextData {
46     outer_expn: ExpnId,
47     outer_transparency: Transparency,
48     parent: SyntaxContext,
49     /// This context, but with all transparent and semi-transparent expansions filtered away.
50     opaque: SyntaxContext,
51     /// This context, but with all transparent expansions filtered away.
52     opaque_and_semitransparent: SyntaxContext,
53     /// Name of the crate to which `$crate` with this context would resolve.
54     dollar_crate_name: Symbol,
55 }
56
57 /// A unique ID associated with a macro invocation and expansion.
58 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
59 pub struct ExpnId(u32);
60
61 /// A property of a macro expansion that determines how identifiers
62 /// produced by that expansion are resolved.
63 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Encodable, Decodable)]
64 #[derive(HashStable_Generic)]
65 pub enum Transparency {
66     /// Identifier produced by a transparent expansion is always resolved at call-site.
67     /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
68     Transparent,
69     /// Identifier produced by a semi-transparent expansion may be resolved
70     /// either at call-site or at definition-site.
71     /// If it's a local variable, label or `$crate` then it's resolved at def-site.
72     /// Otherwise it's resolved at call-site.
73     /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
74     /// but that's an implementation detail.
75     SemiTransparent,
76     /// Identifier produced by an opaque expansion is always resolved at definition-site.
77     /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
78     Opaque,
79 }
80
81 impl ExpnId {
82     pub fn fresh(expn_data: Option<ExpnData>) -> Self {
83         HygieneData::with(|data| data.fresh_expn(expn_data))
84     }
85
86     /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
87     #[inline]
88     pub fn root() -> Self {
89         ExpnId(0)
90     }
91
92     #[inline]
93     pub fn as_u32(self) -> u32 {
94         self.0
95     }
96
97     #[inline]
98     pub fn from_u32(raw: u32) -> ExpnId {
99         ExpnId(raw)
100     }
101
102     #[inline]
103     pub fn expn_data(self) -> ExpnData {
104         HygieneData::with(|data| data.expn_data(self).clone())
105     }
106
107     #[inline]
108     pub fn set_expn_data(self, mut expn_data: ExpnData) {
109         HygieneData::with(|data| {
110             let old_expn_data = &mut data.expn_data[self.0 as usize];
111             assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
112             expn_data.orig_id.replace(self.as_u32()).expect_none("orig_id should be None");
113             *old_expn_data = Some(expn_data);
114         })
115     }
116
117     pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
118         HygieneData::with(|data| data.is_descendant_of(self, ancestor))
119     }
120
121     /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
122     /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
123     pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
124         HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
125     }
126
127     /// Returns span for the macro which originally caused this expansion to happen.
128     ///
129     /// Stops backtracing at include! boundary.
130     pub fn expansion_cause(mut self) -> Option<Span> {
131         let mut last_macro = None;
132         loop {
133             let expn_data = self.expn_data();
134             // Stop going up the backtrace once include! is encountered
135             if expn_data.is_root()
136                 || expn_data.kind == ExpnKind::Macro(MacroKind::Bang, sym::include)
137             {
138                 break;
139             }
140             self = expn_data.call_site.ctxt().outer_expn();
141             last_macro = Some(expn_data.call_site);
142         }
143         last_macro
144     }
145 }
146
147 #[derive(Debug)]
148 pub struct HygieneData {
149     /// Each expansion should have an associated expansion data, but sometimes there's a delay
150     /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
151     /// first and then resolved later), so we use an `Option` here.
152     expn_data: Vec<Option<ExpnData>>,
153     syntax_context_data: Vec<SyntaxContextData>,
154     syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
155 }
156
157 impl HygieneData {
158     crate fn new(edition: Edition) -> Self {
159         let mut root_data = ExpnData::default(
160             ExpnKind::Root,
161             DUMMY_SP,
162             edition,
163             Some(DefId::local(CRATE_DEF_INDEX)),
164         );
165         root_data.orig_id = Some(0);
166
167         HygieneData {
168             expn_data: vec![Some(root_data)],
169             syntax_context_data: vec![SyntaxContextData {
170                 outer_expn: ExpnId::root(),
171                 outer_transparency: Transparency::Opaque,
172                 parent: SyntaxContext(0),
173                 opaque: SyntaxContext(0),
174                 opaque_and_semitransparent: SyntaxContext(0),
175                 dollar_crate_name: kw::DollarCrate,
176             }],
177             syntax_context_map: FxHashMap::default(),
178         }
179     }
180
181     pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
182         SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
183     }
184
185     fn fresh_expn(&mut self, mut expn_data: Option<ExpnData>) -> ExpnId {
186         let raw_id = self.expn_data.len() as u32;
187         if let Some(data) = expn_data.as_mut() {
188             data.orig_id.replace(raw_id).expect_none("orig_id should be None");
189         }
190         self.expn_data.push(expn_data);
191         ExpnId(raw_id)
192     }
193
194     fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
195         self.expn_data[expn_id.0 as usize].as_ref().expect("no expansion data for an expansion ID")
196     }
197
198     fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
199         while expn_id != ancestor {
200             if expn_id == ExpnId::root() {
201                 return false;
202             }
203             expn_id = self.expn_data(expn_id).parent;
204         }
205         true
206     }
207
208     fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
209         self.syntax_context_data[ctxt.0 as usize].opaque
210     }
211
212     fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
213         self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
214     }
215
216     fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
217         self.syntax_context_data[ctxt.0 as usize].outer_expn
218     }
219
220     fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
221         let data = &self.syntax_context_data[ctxt.0 as usize];
222         (data.outer_expn, data.outer_transparency)
223     }
224
225     fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
226         self.syntax_context_data[ctxt.0 as usize].parent
227     }
228
229     fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
230         let outer_mark = self.outer_mark(*ctxt);
231         *ctxt = self.parent_ctxt(*ctxt);
232         outer_mark
233     }
234
235     fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
236         let mut marks = Vec::new();
237         while ctxt != SyntaxContext::root() {
238             debug!("marks: getting parent of {:?}", ctxt);
239             marks.push(self.outer_mark(ctxt));
240             ctxt = self.parent_ctxt(ctxt);
241         }
242         marks.reverse();
243         marks
244     }
245
246     fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
247         debug!("walk_chain({:?}, {:?})", span, to);
248         debug!("walk_chain: span ctxt = {:?}", span.ctxt());
249         while span.from_expansion() && span.ctxt() != to {
250             let outer_expn = self.outer_expn(span.ctxt());
251             debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn);
252             let expn_data = self.expn_data(outer_expn);
253             debug!("walk_chain({:?}): expn_data={:?}", span, expn_data);
254             span = expn_data.call_site;
255         }
256         span
257     }
258
259     fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
260         let mut scope = None;
261         while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
262             scope = Some(self.remove_mark(ctxt).0);
263         }
264         scope
265     }
266
267     fn apply_mark(
268         &mut self,
269         ctxt: SyntaxContext,
270         expn_id: ExpnId,
271         transparency: Transparency,
272     ) -> SyntaxContext {
273         assert_ne!(expn_id, ExpnId::root());
274         if transparency == Transparency::Opaque {
275             return self.apply_mark_internal(ctxt, expn_id, transparency);
276         }
277
278         let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
279         let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
280             self.normalize_to_macros_2_0(call_site_ctxt)
281         } else {
282             self.normalize_to_macro_rules(call_site_ctxt)
283         };
284
285         if call_site_ctxt == SyntaxContext::root() {
286             return self.apply_mark_internal(ctxt, expn_id, transparency);
287         }
288
289         // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
290         // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
291         //
292         // In this case, the tokens from the macros 1.0 definition inherit the hygiene
293         // at their invocation. That is, we pretend that the macros 1.0 definition
294         // was defined at its invocation (i.e., inside the macros 2.0 definition)
295         // so that the macros 2.0 definition remains hygienic.
296         //
297         // See the example at `test/ui/hygiene/legacy_interaction.rs`.
298         for (expn_id, transparency) in self.marks(ctxt) {
299             call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency);
300         }
301         self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
302     }
303
304     fn apply_mark_internal(
305         &mut self,
306         ctxt: SyntaxContext,
307         expn_id: ExpnId,
308         transparency: Transparency,
309     ) -> SyntaxContext {
310         let syntax_context_data = &mut self.syntax_context_data;
311         let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
312         let mut opaque_and_semitransparent =
313             syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
314
315         if transparency >= Transparency::Opaque {
316             let parent = opaque;
317             opaque = *self
318                 .syntax_context_map
319                 .entry((parent, expn_id, transparency))
320                 .or_insert_with(|| {
321                     let new_opaque = SyntaxContext(syntax_context_data.len() as u32);
322                     syntax_context_data.push(SyntaxContextData {
323                         outer_expn: expn_id,
324                         outer_transparency: transparency,
325                         parent,
326                         opaque: new_opaque,
327                         opaque_and_semitransparent: new_opaque,
328                         dollar_crate_name: kw::DollarCrate,
329                     });
330                     new_opaque
331                 });
332         }
333
334         if transparency >= Transparency::SemiTransparent {
335             let parent = opaque_and_semitransparent;
336             opaque_and_semitransparent = *self
337                 .syntax_context_map
338                 .entry((parent, expn_id, transparency))
339                 .or_insert_with(|| {
340                     let new_opaque_and_semitransparent =
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: new_opaque_and_semitransparent,
348                         dollar_crate_name: kw::DollarCrate,
349                     });
350                     new_opaque_and_semitransparent
351                 });
352         }
353
354         let parent = ctxt;
355         *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
356             let new_opaque_and_semitransparent_and_transparent =
357                 SyntaxContext(syntax_context_data.len() as u32);
358             syntax_context_data.push(SyntaxContextData {
359                 outer_expn: expn_id,
360                 outer_transparency: transparency,
361                 parent,
362                 opaque,
363                 opaque_and_semitransparent,
364                 dollar_crate_name: kw::DollarCrate,
365             });
366             new_opaque_and_semitransparent_and_transparent
367         })
368     }
369 }
370
371 pub fn clear_syntax_context_map() {
372     HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
373 }
374
375 pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
376     HygieneData::with(|data| data.walk_chain(span, to))
377 }
378
379 pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
380     // The new contexts that need updating are at the end of the list and have `$crate` as a name.
381     let (len, to_update) = HygieneData::with(|data| {
382         (
383             data.syntax_context_data.len(),
384             data.syntax_context_data
385                 .iter()
386                 .rev()
387                 .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate)
388                 .count(),
389         )
390     });
391     // The callback must be called from outside of the `HygieneData` lock,
392     // since it will try to acquire it too.
393     let range_to_update = len - to_update..len;
394     let names: Vec<_> =
395         range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
396     HygieneData::with(|data| {
397         range_to_update.zip(names.into_iter()).for_each(|(idx, name)| {
398             data.syntax_context_data[idx].dollar_crate_name = name;
399         })
400     })
401 }
402
403 pub fn debug_hygiene_data(verbose: bool) -> String {
404     HygieneData::with(|data| {
405         if verbose {
406             format!("{:#?}", data)
407         } else {
408             let mut s = String::from("");
409             s.push_str("Expansions:");
410             data.expn_data.iter().enumerate().for_each(|(id, expn_info)| {
411                 let expn_info = expn_info.as_ref().expect("no expansion data for an expansion ID");
412                 s.push_str(&format!(
413                     "\n{}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
414                     id,
415                     expn_info.parent,
416                     expn_info.call_site.ctxt(),
417                     expn_info.def_site.ctxt(),
418                     expn_info.kind,
419                 ));
420             });
421             s.push_str("\n\nSyntaxContexts:");
422             data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
423                 s.push_str(&format!(
424                     "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
425                     id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
426                 ));
427             });
428             s
429         }
430     })
431 }
432
433 impl SyntaxContext {
434     #[inline]
435     pub const fn root() -> Self {
436         SyntaxContext(0)
437     }
438
439     #[inline]
440     crate fn as_u32(self) -> u32 {
441         self.0
442     }
443
444     #[inline]
445     crate fn from_u32(raw: u32) -> SyntaxContext {
446         SyntaxContext(raw)
447     }
448
449     /// Extend a syntax context with a given expansion and transparency.
450     crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
451         HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
452     }
453
454     /// Pulls a single mark off of the syntax context. This effectively moves the
455     /// context up one macro definition level. That is, if we have a nested macro
456     /// definition as follows:
457     ///
458     /// ```rust
459     /// macro_rules! f {
460     ///    macro_rules! g {
461     ///        ...
462     ///    }
463     /// }
464     /// ```
465     ///
466     /// and we have a SyntaxContext that is referring to something declared by an invocation
467     /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
468     /// invocation of f that created g1.
469     /// Returns the mark that was removed.
470     pub fn remove_mark(&mut self) -> ExpnId {
471         HygieneData::with(|data| data.remove_mark(self).0)
472     }
473
474     pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
475         HygieneData::with(|data| data.marks(self))
476     }
477
478     /// Adjust this context for resolution in a scope created by the given expansion.
479     /// For example, consider the following three resolutions of `f`:
480     ///
481     /// ```rust
482     /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
483     /// m!(f);
484     /// macro m($f:ident) {
485     ///     mod bar {
486     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
487     ///         pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
488     ///     }
489     ///     foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
490     ///     //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
491     ///     //| and it resolves to `::foo::f`.
492     ///     bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
493     ///     //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
494     ///     //| and it resolves to `::bar::f`.
495     ///     bar::$f(); // `f`'s `SyntaxContext` is empty.
496     ///     //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
497     ///     //| and it resolves to `::bar::$f`.
498     /// }
499     /// ```
500     /// This returns the expansion whose definition scope we use to privacy check the resolution,
501     /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
502     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
503         HygieneData::with(|data| data.adjust(self, expn_id))
504     }
505
506     /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
507     pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
508         HygieneData::with(|data| {
509             *self = data.normalize_to_macros_2_0(*self);
510             data.adjust(self, expn_id)
511         })
512     }
513
514     /// Adjust this context for resolution in a scope created by the given expansion
515     /// via a glob import with the given `SyntaxContext`.
516     /// For example:
517     ///
518     /// ```rust
519     /// m!(f);
520     /// macro m($i:ident) {
521     ///     mod foo {
522     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
523     ///         pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
524     ///     }
525     ///     n(f);
526     ///     macro n($j:ident) {
527     ///         use foo::*;
528     ///         f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
529     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
530     ///         $i(); // `$i`'s `SyntaxContext` has a mark from `n`
531     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
532     ///         $j(); // `$j`'s `SyntaxContext` has a mark from `m`
533     ///         //^ This cannot be glob-adjusted, so this is a resolution error.
534     ///     }
535     /// }
536     /// ```
537     /// This returns `None` if the context cannot be glob-adjusted.
538     /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
539     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
540         HygieneData::with(|data| {
541             let mut scope = None;
542             let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
543             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
544                 scope = Some(data.remove_mark(&mut glob_ctxt).0);
545                 if data.remove_mark(self).0 != scope.unwrap() {
546                     return None;
547                 }
548             }
549             if data.adjust(self, expn_id).is_some() {
550                 return None;
551             }
552             Some(scope)
553         })
554     }
555
556     /// Undo `glob_adjust` if possible:
557     ///
558     /// ```rust
559     /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
560     ///     assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
561     /// }
562     /// ```
563     pub fn reverse_glob_adjust(
564         &mut self,
565         expn_id: ExpnId,
566         glob_span: Span,
567     ) -> Option<Option<ExpnId>> {
568         HygieneData::with(|data| {
569             if data.adjust(self, expn_id).is_some() {
570                 return None;
571             }
572
573             let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
574             let mut marks = Vec::new();
575             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
576                 marks.push(data.remove_mark(&mut glob_ctxt));
577             }
578
579             let scope = marks.last().map(|mark| mark.0);
580             while let Some((expn_id, transparency)) = marks.pop() {
581                 *self = data.apply_mark(*self, expn_id, transparency);
582             }
583             Some(scope)
584         })
585     }
586
587     pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
588         HygieneData::with(|data| {
589             let mut self_normalized = data.normalize_to_macros_2_0(self);
590             data.adjust(&mut self_normalized, expn_id);
591             self_normalized == data.normalize_to_macros_2_0(other)
592         })
593     }
594
595     #[inline]
596     pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
597         HygieneData::with(|data| data.normalize_to_macros_2_0(self))
598     }
599
600     #[inline]
601     pub fn normalize_to_macro_rules(self) -> SyntaxContext {
602         HygieneData::with(|data| data.normalize_to_macro_rules(self))
603     }
604
605     #[inline]
606     pub fn outer_expn(self) -> ExpnId {
607         HygieneData::with(|data| data.outer_expn(self))
608     }
609
610     /// `ctxt.outer_expn_data()` is equivalent to but faster than
611     /// `ctxt.outer_expn().expn_data()`.
612     #[inline]
613     pub fn outer_expn_data(self) -> ExpnData {
614         HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
615     }
616
617     #[inline]
618     pub fn outer_mark(self) -> (ExpnId, Transparency) {
619         HygieneData::with(|data| data.outer_mark(self))
620     }
621
622     #[inline]
623     pub fn outer_mark_with_data(self) -> (ExpnId, Transparency, ExpnData) {
624         HygieneData::with(|data| {
625             let (expn_id, transparency) = data.outer_mark(self);
626             (expn_id, transparency, data.expn_data(expn_id).clone())
627         })
628     }
629
630     pub fn dollar_crate_name(self) -> Symbol {
631         HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
632     }
633 }
634
635 impl fmt::Debug for SyntaxContext {
636     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
637         write!(f, "#{}", self.0)
638     }
639 }
640
641 impl Span {
642     /// Creates a fresh expansion with given properties.
643     /// Expansions are normally created by macros, but in some cases expansions are created for
644     /// other compiler-generated code to set per-span properties like allowed unstable features.
645     /// The returned span belongs to the created expansion and has the new properties,
646     /// but its location is inherited from the current span.
647     pub fn fresh_expansion(self, expn_data: ExpnData) -> Span {
648         self.fresh_expansion_with_transparency(expn_data, Transparency::Transparent)
649     }
650
651     pub fn fresh_expansion_with_transparency(
652         self,
653         expn_data: ExpnData,
654         transparency: Transparency,
655     ) -> Span {
656         HygieneData::with(|data| {
657             let expn_id = data.fresh_expn(Some(expn_data));
658             self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency))
659         })
660     }
661 }
662
663 /// A subset of properties from both macro definition and macro call available through global data.
664 /// Avoid using this if you have access to the original definition or call structures.
665 #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
666 pub struct ExpnData {
667     // --- The part unique to each expansion.
668     /// The kind of this expansion - macro or compiler desugaring.
669     pub kind: ExpnKind,
670     /// The expansion that produced this expansion.
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, Encodable, Decodable, 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, Encodable, Decodable, 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, Encodable, Decodable, 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, Encodable, Decodable, 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, Encodable, Decodable, 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 #[derive(Default)]
890 pub struct HygieneEncodeContext {
891     /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
892     /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
893     /// that we don't accidentally try to encode any more `SyntaxContexts`
894     serialized_ctxts: Lock<FxHashSet<SyntaxContext>>,
895     /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
896     /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData`
897     /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
898     /// until we reach a fixed point.
899     latest_ctxts: Lock<FxHashSet<SyntaxContext>>,
900
901     serialized_expns: Lock<FxHashSet<ExpnId>>,
902
903     latest_expns: Lock<FxHashSet<ExpnId>>,
904 }
905
906 impl HygieneEncodeContext {
907     pub fn encode<
908         T,
909         R,
910         F: FnMut(&mut T, u32, &SyntaxContextData) -> Result<(), R>,
911         G: FnMut(&mut T, u32, &ExpnData) -> Result<(), R>,
912     >(
913         &self,
914         encoder: &mut T,
915         mut encode_ctxt: F,
916         mut encode_expn: G,
917     ) -> Result<(), R> {
918         // When we serialize a `SyntaxContextData`, we may end up serializing
919         // a `SyntaxContext` that we haven't seen before
920         while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() {
921             debug!(
922                 "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}",
923                 self.latest_ctxts.lock().len(),
924                 self.latest_ctxts
925             );
926
927             // Consume the current round of SyntaxContexts.
928             // Drop the lock() temporary early
929             let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) };
930
931             // It's fine to iterate over a HashMap, because the serialization
932             // of the table that we insert data into doesn't depend on insertion
933             // order
934             for_all_ctxts_in(latest_ctxts.into_iter(), |(index, ctxt, data)| {
935                 if self.serialized_ctxts.lock().insert(ctxt) {
936                     encode_ctxt(encoder, index, data)?;
937                 }
938                 Ok(())
939             })?;
940
941             let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) };
942
943             for_all_expns_in(latest_expns.into_iter(), |index, expn, data| {
944                 if self.serialized_expns.lock().insert(expn) {
945                     encode_expn(encoder, index, data)?;
946                 }
947                 Ok(())
948             })?;
949         }
950         debug!("encode_hygiene: Done serializing SyntaxContextData");
951         Ok(())
952     }
953 }
954
955 #[derive(Default)]
956 /// Additional information used to assist in decoding hygiene data
957 pub struct HygieneDecodeContext {
958     // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
959     // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
960     // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
961     // so that multiple occurrences of the same serialized id are decoded to the same
962     // `SyntaxContext`
963     remapped_ctxts: Lock<Vec<Option<SyntaxContext>>>,
964     // The same as `remapepd_ctxts`, but for `ExpnId`s
965     remapped_expns: Lock<Vec<Option<ExpnId>>>,
966 }
967
968 pub fn decode_expn_id<
969     'a,
970     D: Decoder,
971     F: FnOnce(&mut D, u32) -> Result<ExpnData, D::Error>,
972     G: FnOnce(CrateNum) -> &'a HygieneDecodeContext,
973 >(
974     d: &mut D,
975     mode: ExpnDataDecodeMode<'a, G>,
976     decode_data: F,
977 ) -> Result<ExpnId, D::Error> {
978     let index = u32::decode(d)?;
979     let context = match mode {
980         ExpnDataDecodeMode::IncrComp(context) => context,
981         ExpnDataDecodeMode::Metadata(get_context) => {
982             let krate = CrateNum::decode(d)?;
983             get_context(krate)
984         }
985     };
986
987     // Do this after decoding, so that we decode a `CrateNum`
988     // if necessary
989     if index == ExpnId::root().as_u32() {
990         debug!("decode_expn_id: deserialized root");
991         return Ok(ExpnId::root());
992     }
993
994     let outer_expns = &context.remapped_expns;
995
996     // Ensure that the lock() temporary is dropped early
997     {
998         if let Some(expn_id) = outer_expns.lock().get(index as usize).copied().flatten() {
999             return Ok(expn_id);
1000         }
1001     }
1002
1003     // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1004     // other ExpnIds
1005     let mut expn_data = decode_data(d, index)?;
1006
1007     let expn_id = HygieneData::with(|hygiene_data| {
1008         let expn_id = ExpnId(hygiene_data.expn_data.len() as u32);
1009
1010         // If we just deserialized an `ExpnData` owned by
1011         // the local crate, its `orig_id` will be stale,
1012         // so we need to update it to its own value.
1013         // This only happens when we deserialize the incremental cache,
1014         // since a crate will never decode its own metadata.
1015         if expn_data.krate == LOCAL_CRATE {
1016             expn_data.orig_id = Some(expn_id.0);
1017         }
1018
1019         hygiene_data.expn_data.push(Some(expn_data));
1020
1021         let mut expns = outer_expns.lock();
1022         let new_len = index as usize + 1;
1023         if expns.len() < new_len {
1024             expns.resize(new_len, None);
1025         }
1026         expns[index as usize] = Some(expn_id);
1027         drop(expns);
1028         expn_id
1029     });
1030     Ok(expn_id)
1031 }
1032
1033 // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1034 // to track which `SyntaxContext`s we have already decoded.
1035 // The provided closure will be invoked to deserialize a `SyntaxContextData`
1036 // if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1037 pub fn decode_syntax_context<
1038     D: Decoder,
1039     F: FnOnce(&mut D, u32) -> Result<SyntaxContextData, D::Error>,
1040 >(
1041     d: &mut D,
1042     context: &HygieneDecodeContext,
1043     decode_data: F,
1044 ) -> Result<SyntaxContext, D::Error> {
1045     let raw_id: u32 = Decodable::decode(d)?;
1046     if raw_id == 0 {
1047         debug!("decode_syntax_context: deserialized root");
1048         // The root is special
1049         return Ok(SyntaxContext::root());
1050     }
1051
1052     let outer_ctxts = &context.remapped_ctxts;
1053
1054     // Ensure that the lock() temporary is dropped early
1055     {
1056         if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1057             return Ok(ctxt);
1058         }
1059     }
1060
1061     // Allocate and store SyntaxContext id *before* calling the decoder function,
1062     // as the SyntaxContextData may reference itself.
1063     let new_ctxt = HygieneData::with(|hygiene_data| {
1064         let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
1065         // Push a dummy SyntaxContextData to ensure that nobody else can get the
1066         // same ID as us. This will be overwritten after call `decode_Data`
1067         hygiene_data.syntax_context_data.push(SyntaxContextData {
1068             outer_expn: ExpnId::root(),
1069             outer_transparency: Transparency::Transparent,
1070             parent: SyntaxContext::root(),
1071             opaque: SyntaxContext::root(),
1072             opaque_and_semitransparent: SyntaxContext::root(),
1073             dollar_crate_name: kw::Invalid,
1074         });
1075         let mut ctxts = outer_ctxts.lock();
1076         let new_len = raw_id as usize + 1;
1077         if ctxts.len() < new_len {
1078             ctxts.resize(new_len, None);
1079         }
1080         ctxts[raw_id as usize] = Some(new_ctxt);
1081         drop(ctxts);
1082         new_ctxt
1083     });
1084
1085     // Don't try to decode data while holding the lock, since we need to
1086     // be able to recursively decode a SyntaxContext
1087     let mut ctxt_data = decode_data(d, raw_id)?;
1088     // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1089     // We don't care what the encoding crate set this to - we want to resolve it
1090     // from the perspective of the current compilation session
1091     ctxt_data.dollar_crate_name = kw::DollarCrate;
1092
1093     // Overwrite the dummy data with our decoded SyntaxContextData
1094     HygieneData::with(|hygiene_data| {
1095         let dummy = std::mem::replace(
1096             &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize],
1097             ctxt_data,
1098         );
1099         // Make sure nothing weird happening while `decode_data` was running
1100         assert_eq!(dummy.dollar_crate_name, kw::Invalid);
1101     });
1102
1103     Ok(new_ctxt)
1104 }
1105
1106 pub fn num_syntax_ctxts() -> usize {
1107     HygieneData::with(|data| data.syntax_context_data.len())
1108 }
1109
1110 pub fn for_all_ctxts_in<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1111     ctxts: impl Iterator<Item = SyntaxContext>,
1112     mut f: F,
1113 ) -> Result<(), E> {
1114     let all_data: Vec<_> = HygieneData::with(|data| {
1115         ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect()
1116     });
1117     for (ctxt, data) in all_data.into_iter() {
1118         f((ctxt.0, ctxt, &data))?;
1119     }
1120     Ok(())
1121 }
1122
1123 pub fn for_all_expns_in<E, F: FnMut(u32, ExpnId, &ExpnData) -> Result<(), E>>(
1124     expns: impl Iterator<Item = ExpnId>,
1125     mut f: F,
1126 ) -> Result<(), E> {
1127     let all_data: Vec<_> = HygieneData::with(|data| {
1128         expns.map(|expn| (expn, data.expn_data[expn.0 as usize].clone())).collect()
1129     });
1130     for (expn, data) in all_data.into_iter() {
1131         f(expn.0, expn, &data.unwrap_or_else(|| panic!("Missing data for {:?}", expn)))?;
1132     }
1133     Ok(())
1134 }
1135
1136 pub fn for_all_data<E, F: FnMut((u32, SyntaxContext, &SyntaxContextData)) -> Result<(), E>>(
1137     mut f: F,
1138 ) -> Result<(), E> {
1139     let all_data = HygieneData::with(|data| data.syntax_context_data.clone());
1140     for (i, data) in all_data.into_iter().enumerate() {
1141         f((i as u32, SyntaxContext(i as u32), &data))?;
1142     }
1143     Ok(())
1144 }
1145
1146 impl<E: Encoder> Encodable<E> for ExpnId {
1147     default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1148         panic!("cannot encode `ExpnId` with `{}`", std::any::type_name::<E>());
1149     }
1150 }
1151
1152 impl<D: Decoder> Decodable<D> for ExpnId {
1153     default fn decode(_: &mut D) -> Result<Self, D::Error> {
1154         panic!("cannot decode `ExpnId` with `{}`", std::any::type_name::<D>());
1155     }
1156 }
1157
1158 pub fn for_all_expn_data<E, F: FnMut(u32, &ExpnData) -> Result<(), E>>(mut f: F) -> Result<(), E> {
1159     let all_data = HygieneData::with(|data| data.expn_data.clone());
1160     for (i, data) in all_data.into_iter().enumerate() {
1161         f(i as u32, &data.unwrap_or_else(|| panic!("Missing ExpnData!")))?;
1162     }
1163     Ok(())
1164 }
1165
1166 pub fn raw_encode_syntax_context<E: Encoder>(
1167     ctxt: SyntaxContext,
1168     context: &HygieneEncodeContext,
1169     e: &mut E,
1170 ) -> Result<(), E::Error> {
1171     if !context.serialized_ctxts.lock().contains(&ctxt) {
1172         context.latest_ctxts.lock().insert(ctxt);
1173     }
1174     ctxt.0.encode(e)
1175 }
1176
1177 pub fn raw_encode_expn_id<E: Encoder>(
1178     expn: ExpnId,
1179     context: &HygieneEncodeContext,
1180     mode: ExpnDataEncodeMode,
1181     e: &mut E,
1182 ) -> Result<(), E::Error> {
1183     // Record the fact that we need to serialize the corresponding
1184     // `ExpnData`
1185     let needs_data = || {
1186         if !context.serialized_expns.lock().contains(&expn) {
1187             context.latest_expns.lock().insert(expn);
1188         }
1189     };
1190
1191     match mode {
1192         ExpnDataEncodeMode::IncrComp => {
1193             // Always serialize the `ExpnData` in incr comp mode
1194             needs_data();
1195             expn.0.encode(e)
1196         }
1197         ExpnDataEncodeMode::Metadata => {
1198             let data = expn.expn_data();
1199             // We only need to serialize the ExpnData
1200             // if it comes from this crate.
1201             // We currently don't serialize any hygiene information data for
1202             // proc-macro crates: see the `SpecializedEncoder<Span>` impl
1203             // for crate metadata.
1204             if data.krate == LOCAL_CRATE {
1205                 needs_data();
1206             }
1207             data.orig_id.expect("Missing orig_id").encode(e)?;
1208             data.krate.encode(e)
1209         }
1210     }
1211 }
1212
1213 pub enum ExpnDataEncodeMode {
1214     IncrComp,
1215     Metadata,
1216 }
1217
1218 pub enum ExpnDataDecodeMode<'a, F: FnOnce(CrateNum) -> &'a HygieneDecodeContext> {
1219     IncrComp(&'a HygieneDecodeContext),
1220     Metadata(F),
1221 }
1222
1223 impl<'a> ExpnDataDecodeMode<'a, Box<dyn FnOnce(CrateNum) -> &'a HygieneDecodeContext>> {
1224     pub fn incr_comp(ctxt: &'a HygieneDecodeContext) -> Self {
1225         ExpnDataDecodeMode::IncrComp(ctxt)
1226     }
1227 }
1228
1229 impl<E: Encoder> Encodable<E> for SyntaxContext {
1230     default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1231         panic!("cannot encode `SyntaxContext` with `{}`", std::any::type_name::<E>());
1232     }
1233 }
1234
1235 impl<D: Decoder> Decodable<D> for SyntaxContext {
1236     default fn decode(_: &mut D) -> Result<Self, D::Error> {
1237         panic!("cannot decode `SyntaxContext` with `{}`", std::any::type_name::<D>());
1238     }
1239 }