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