]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_span/src/hygiene.rs
Encode ExpnId using ExpnHash for incr. comp.
[rust.git] / compiler / rustc_span / src / 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::with_session_globals;
30 use crate::{HashStableContext, Span, DUMMY_SP};
31
32 use crate::def_id::{CrateNum, DefId, StableCrateId, CRATE_DEF_ID, LOCAL_CRATE};
33 use rustc_data_structures::fingerprint::Fingerprint;
34 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
35 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
36 use rustc_data_structures::sync::{Lock, Lrc};
37 use rustc_data_structures::unhash::UnhashMap;
38 use rustc_index::vec::IndexVec;
39 use rustc_macros::HashStable_Generic;
40 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
41 use std::fmt;
42 use std::hash::Hash;
43 use tracing::*;
44
45 /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
46 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
47 pub struct SyntaxContext(u32);
48
49 #[derive(Debug, Encodable, Decodable, Clone)]
50 pub struct SyntaxContextData {
51     outer_expn: ExpnId,
52     outer_transparency: Transparency,
53     parent: SyntaxContext,
54     /// This context, but with all transparent and semi-transparent expansions filtered away.
55     opaque: SyntaxContext,
56     /// This context, but with all transparent expansions filtered away.
57     opaque_and_semitransparent: SyntaxContext,
58     /// Name of the crate to which `$crate` with this context would resolve.
59     dollar_crate_name: Symbol,
60 }
61
62 rustc_index::newtype_index! {
63     /// A unique ID associated with a macro invocation and expansion.
64     pub struct ExpnIndex {
65         ENCODABLE = custom
66     }
67 }
68
69 /// A unique ID associated with a macro invocation and expansion.
70 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
71 pub struct ExpnId {
72     pub krate: CrateNum,
73     pub local_id: ExpnIndex,
74 }
75
76 impl fmt::Debug for ExpnId {
77     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78         // Generate crate_::{{expn_}}.
79         write!(f, "{:?}::{{{{expn{}}}}}", self.krate, self.local_id.private)
80     }
81 }
82
83 rustc_index::newtype_index! {
84     /// A unique ID associated with a macro invocation and expansion.
85     pub struct LocalExpnId {
86         ENCODABLE = custom
87         DEBUG_FORMAT = "expn{}"
88     }
89 }
90
91 /// A unique hash value associated to an expansion.
92 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
93 pub struct ExpnHash(Fingerprint);
94
95 impl ExpnHash {
96     /// Returns the [StableCrateId] identifying the crate this [ExpnHash]
97     /// originates from.
98     #[inline]
99     pub fn stable_crate_id(self) -> StableCrateId {
100         StableCrateId(self.0.as_value().0)
101     }
102
103     /// Returns the crate-local part of the [ExpnHash].
104     ///
105     /// Used for tests.
106     #[inline]
107     pub fn local_hash(self) -> u64 {
108         self.0.as_value().1
109     }
110
111     #[inline]
112     pub fn is_root(self) -> bool {
113         self.0 == Fingerprint::ZERO
114     }
115
116     /// Builds a new [ExpnHash] with the given [StableCrateId] and
117     /// `local_hash`, where `local_hash` must be unique within its crate.
118     fn new(stable_crate_id: StableCrateId, local_hash: u64) -> ExpnHash {
119         ExpnHash(Fingerprint::new(stable_crate_id.0, local_hash))
120     }
121 }
122
123 /// A property of a macro expansion that determines how identifiers
124 /// produced by that expansion are resolved.
125 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Encodable, Decodable)]
126 #[derive(HashStable_Generic)]
127 pub enum Transparency {
128     /// Identifier produced by a transparent expansion is always resolved at call-site.
129     /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
130     Transparent,
131     /// Identifier produced by a semi-transparent expansion may be resolved
132     /// either at call-site or at definition-site.
133     /// If it's a local variable, label or `$crate` then it's resolved at def-site.
134     /// Otherwise it's resolved at call-site.
135     /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
136     /// but that's an implementation detail.
137     SemiTransparent,
138     /// Identifier produced by an opaque expansion is always resolved at definition-site.
139     /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
140     Opaque,
141 }
142
143 impl LocalExpnId {
144     /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
145     pub const ROOT: LocalExpnId = LocalExpnId::from_u32(0);
146
147     pub fn from_raw(idx: ExpnIndex) -> LocalExpnId {
148         LocalExpnId::from_u32(idx.as_u32())
149     }
150
151     pub fn as_raw(self) -> ExpnIndex {
152         ExpnIndex::from_u32(self.as_u32())
153     }
154
155     pub fn fresh_empty() -> LocalExpnId {
156         HygieneData::with(|data| data.fresh_expn(None))
157     }
158
159     pub fn fresh(expn_data: ExpnData, ctx: impl HashStableContext) -> LocalExpnId {
160         debug_assert_eq!(expn_data.parent.krate, LOCAL_CRATE);
161         let expn_id = HygieneData::with(|data| data.fresh_expn(Some(expn_data)));
162         update_disambiguator(expn_id, ctx);
163         expn_id
164     }
165
166     #[inline]
167     pub fn expn_hash(self) -> ExpnHash {
168         HygieneData::with(|data| data.local_expn_hash(self))
169     }
170
171     #[inline]
172     pub fn expn_data(self) -> ExpnData {
173         HygieneData::with(|data| data.local_expn_data(self).clone())
174     }
175
176     #[inline]
177     pub fn to_expn_id(self) -> ExpnId {
178         ExpnId { krate: LOCAL_CRATE, local_id: self.as_raw() }
179     }
180
181     #[inline]
182     pub fn set_expn_data(self, mut expn_data: ExpnData, ctx: impl HashStableContext) {
183         debug_assert_eq!(expn_data.parent.krate, LOCAL_CRATE);
184         HygieneData::with(|data| {
185             let old_expn_data = &mut data.local_expn_data[self];
186             assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
187             assert_eq!(expn_data.orig_id, None);
188             debug_assert_eq!(expn_data.krate, LOCAL_CRATE);
189             expn_data.orig_id = Some(self.as_u32());
190             *old_expn_data = Some(expn_data);
191         });
192         update_disambiguator(self, ctx)
193     }
194
195     #[inline]
196     pub fn is_descendant_of(self, ancestor: LocalExpnId) -> bool {
197         self.to_expn_id().is_descendant_of(ancestor.to_expn_id())
198     }
199
200     /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
201     /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
202     #[inline]
203     pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
204         self.to_expn_id().outer_expn_is_descendant_of(ctxt)
205     }
206
207     /// Returns span for the macro which originally caused this expansion to happen.
208     ///
209     /// Stops backtracing at include! boundary.
210     #[inline]
211     pub fn expansion_cause(self) -> Option<Span> {
212         self.to_expn_id().expansion_cause()
213     }
214
215     #[inline]
216     #[track_caller]
217     pub fn parent(self) -> LocalExpnId {
218         self.expn_data().parent.as_local().unwrap()
219     }
220 }
221
222 impl ExpnId {
223     /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
224     /// Invariant: we do not create any ExpnId with local_id == 0 and krate != 0.
225     pub const fn root() -> ExpnId {
226         ExpnId { krate: LOCAL_CRATE, local_id: ExpnIndex::from_u32(0) }
227     }
228
229     #[inline]
230     pub fn expn_hash(self) -> ExpnHash {
231         HygieneData::with(|data| data.expn_hash(self))
232     }
233
234     #[inline]
235     pub fn from_hash(hash: ExpnHash) -> Option<ExpnId> {
236         HygieneData::with(|data| data.expn_hash_to_expn_id.get(&hash).copied())
237     }
238
239     #[inline]
240     pub fn as_local(self) -> Option<LocalExpnId> {
241         if self.krate == LOCAL_CRATE { Some(LocalExpnId::from_raw(self.local_id)) } else { None }
242     }
243
244     #[inline]
245     #[track_caller]
246     pub fn expect_local(self) -> LocalExpnId {
247         self.as_local().unwrap()
248     }
249
250     #[inline]
251     pub fn expn_data(self) -> ExpnData {
252         HygieneData::with(|data| data.expn_data(self).clone())
253     }
254
255     pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
256         HygieneData::with(|data| data.is_descendant_of(self, ancestor))
257     }
258
259     /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than
260     /// `expn_id.is_descendant_of(ctxt.outer_expn())`.
261     pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool {
262         HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt)))
263     }
264
265     /// Returns span for the macro which originally caused this expansion to happen.
266     ///
267     /// Stops backtracing at include! boundary.
268     pub fn expansion_cause(mut self) -> Option<Span> {
269         let mut last_macro = None;
270         loop {
271             let expn_data = self.expn_data();
272             // Stop going up the backtrace once include! is encountered
273             if expn_data.is_root()
274                 || expn_data.kind == ExpnKind::Macro(MacroKind::Bang, sym::include)
275             {
276                 break;
277             }
278             self = expn_data.call_site.ctxt().outer_expn();
279             last_macro = Some(expn_data.call_site);
280         }
281         last_macro
282     }
283 }
284
285 #[derive(Debug)]
286 pub struct HygieneData {
287     /// Each expansion should have an associated expansion data, but sometimes there's a delay
288     /// between creation of an expansion ID and obtaining its data (e.g. macros are collected
289     /// first and then resolved later), so we use an `Option` here.
290     local_expn_data: IndexVec<LocalExpnId, Option<ExpnData>>,
291     local_expn_hashes: IndexVec<LocalExpnId, ExpnHash>,
292     /// Data and hash information from external crates.  We may eventually want to remove these
293     /// maps, and fetch the information directly from the other crate's metadata like DefIds do.
294     foreign_expn_data: FxHashMap<ExpnId, ExpnData>,
295     foreign_expn_hashes: FxHashMap<ExpnId, ExpnHash>,
296     expn_hash_to_expn_id: UnhashMap<ExpnHash, ExpnId>,
297     syntax_context_data: Vec<SyntaxContextData>,
298     syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
299     /// Maps the `local_hash` of an `ExpnData` to the next disambiguator value.
300     /// This is used by `update_disambiguator` to keep track of which `ExpnData`s
301     /// would have collisions without a disambiguator.
302     /// The keys of this map are always computed with `ExpnData.disambiguator`
303     /// set to 0.
304     expn_data_disambiguators: FxHashMap<u64, u32>,
305 }
306
307 impl HygieneData {
308     crate fn new(edition: Edition) -> Self {
309         let mut root_data = ExpnData::default(
310             ExpnKind::Root,
311             DUMMY_SP,
312             edition,
313             Some(CRATE_DEF_ID.to_def_id()),
314             None,
315         );
316         root_data.orig_id = Some(0);
317
318         HygieneData {
319             local_expn_data: IndexVec::from_elem_n(Some(root_data), 1),
320             local_expn_hashes: IndexVec::from_elem_n(ExpnHash(Fingerprint::ZERO), 1),
321             foreign_expn_data: FxHashMap::default(),
322             foreign_expn_hashes: FxHashMap::default(),
323             expn_hash_to_expn_id: std::iter::once((ExpnHash(Fingerprint::ZERO), ExpnId::root()))
324                 .collect(),
325             syntax_context_data: vec![SyntaxContextData {
326                 outer_expn: ExpnId::root(),
327                 outer_transparency: Transparency::Opaque,
328                 parent: SyntaxContext(0),
329                 opaque: SyntaxContext(0),
330                 opaque_and_semitransparent: SyntaxContext(0),
331                 dollar_crate_name: kw::DollarCrate,
332             }],
333             syntax_context_map: FxHashMap::default(),
334             expn_data_disambiguators: FxHashMap::default(),
335         }
336     }
337
338     pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
339         with_session_globals(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
340     }
341
342     fn fresh_expn(&mut self, mut expn_data: Option<ExpnData>) -> LocalExpnId {
343         let expn_id = self.local_expn_data.next_index();
344         if let Some(data) = expn_data.as_mut() {
345             debug_assert_eq!(data.krate, LOCAL_CRATE);
346             assert_eq!(data.orig_id, None);
347             data.orig_id = Some(expn_id.as_u32());
348         }
349         self.local_expn_data.push(expn_data);
350         let _eid = self.local_expn_hashes.push(ExpnHash(Fingerprint::ZERO));
351         debug_assert_eq!(expn_id, _eid);
352         expn_id
353     }
354
355     #[inline]
356     fn local_expn_hash(&self, expn_id: LocalExpnId) -> ExpnHash {
357         self.local_expn_hashes[expn_id]
358     }
359
360     #[inline]
361     fn expn_hash(&self, expn_id: ExpnId) -> ExpnHash {
362         match expn_id.as_local() {
363             Some(expn_id) => self.local_expn_hashes[expn_id],
364             None => self.foreign_expn_hashes[&expn_id],
365         }
366     }
367
368     fn local_expn_data(&self, expn_id: LocalExpnId) -> &ExpnData {
369         self.local_expn_data[expn_id].as_ref().expect("no expansion data for an expansion ID")
370     }
371
372     fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
373         if let Some(expn_id) = expn_id.as_local() {
374             self.local_expn_data[expn_id].as_ref().expect("no expansion data for an expansion ID")
375         } else {
376             &self.foreign_expn_data[&expn_id]
377         }
378     }
379
380     fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
381         while expn_id != ancestor {
382             if expn_id == ExpnId::root() {
383                 return false;
384             }
385             expn_id = self.expn_data(expn_id).parent;
386         }
387         true
388     }
389
390     fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
391         self.syntax_context_data[ctxt.0 as usize].opaque
392     }
393
394     fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
395         self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
396     }
397
398     fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
399         self.syntax_context_data[ctxt.0 as usize].outer_expn
400     }
401
402     fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
403         let data = &self.syntax_context_data[ctxt.0 as usize];
404         (data.outer_expn, data.outer_transparency)
405     }
406
407     fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
408         self.syntax_context_data[ctxt.0 as usize].parent
409     }
410
411     fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
412         let outer_mark = self.outer_mark(*ctxt);
413         *ctxt = self.parent_ctxt(*ctxt);
414         outer_mark
415     }
416
417     fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
418         let mut marks = Vec::new();
419         while ctxt != SyntaxContext::root() {
420             debug!("marks: getting parent of {:?}", ctxt);
421             marks.push(self.outer_mark(ctxt));
422             ctxt = self.parent_ctxt(ctxt);
423         }
424         marks.reverse();
425         marks
426     }
427
428     fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
429         debug!("walk_chain({:?}, {:?})", span, to);
430         debug!("walk_chain: span ctxt = {:?}", span.ctxt());
431         while span.from_expansion() && span.ctxt() != to {
432             let outer_expn = self.outer_expn(span.ctxt());
433             debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn);
434             let expn_data = self.expn_data(outer_expn);
435             debug!("walk_chain({:?}): expn_data={:?}", span, expn_data);
436             span = expn_data.call_site;
437         }
438         span
439     }
440
441     fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
442         let mut scope = None;
443         while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
444             scope = Some(self.remove_mark(ctxt).0);
445         }
446         scope
447     }
448
449     fn apply_mark(
450         &mut self,
451         ctxt: SyntaxContext,
452         expn_id: ExpnId,
453         transparency: Transparency,
454     ) -> SyntaxContext {
455         assert_ne!(expn_id, ExpnId::root());
456         if transparency == Transparency::Opaque {
457             return self.apply_mark_internal(ctxt, expn_id, transparency);
458         }
459
460         let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
461         let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
462             self.normalize_to_macros_2_0(call_site_ctxt)
463         } else {
464             self.normalize_to_macro_rules(call_site_ctxt)
465         };
466
467         if call_site_ctxt == SyntaxContext::root() {
468             return self.apply_mark_internal(ctxt, expn_id, transparency);
469         }
470
471         // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
472         // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition.
473         //
474         // In this case, the tokens from the macros 1.0 definition inherit the hygiene
475         // at their invocation. That is, we pretend that the macros 1.0 definition
476         // was defined at its invocation (i.e., inside the macros 2.0 definition)
477         // so that the macros 2.0 definition remains hygienic.
478         //
479         // See the example at `test/ui/hygiene/legacy_interaction.rs`.
480         for (expn_id, transparency) in self.marks(ctxt) {
481             call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency);
482         }
483         self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
484     }
485
486     fn apply_mark_internal(
487         &mut self,
488         ctxt: SyntaxContext,
489         expn_id: ExpnId,
490         transparency: Transparency,
491     ) -> SyntaxContext {
492         let syntax_context_data = &mut self.syntax_context_data;
493         let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
494         let mut opaque_and_semitransparent =
495             syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
496
497         if transparency >= Transparency::Opaque {
498             let parent = opaque;
499             opaque = *self
500                 .syntax_context_map
501                 .entry((parent, expn_id, transparency))
502                 .or_insert_with(|| {
503                     let new_opaque = SyntaxContext(syntax_context_data.len() as u32);
504                     syntax_context_data.push(SyntaxContextData {
505                         outer_expn: expn_id,
506                         outer_transparency: transparency,
507                         parent,
508                         opaque: new_opaque,
509                         opaque_and_semitransparent: new_opaque,
510                         dollar_crate_name: kw::DollarCrate,
511                     });
512                     new_opaque
513                 });
514         }
515
516         if transparency >= Transparency::SemiTransparent {
517             let parent = opaque_and_semitransparent;
518             opaque_and_semitransparent = *self
519                 .syntax_context_map
520                 .entry((parent, expn_id, transparency))
521                 .or_insert_with(|| {
522                     let new_opaque_and_semitransparent =
523                         SyntaxContext(syntax_context_data.len() as u32);
524                     syntax_context_data.push(SyntaxContextData {
525                         outer_expn: expn_id,
526                         outer_transparency: transparency,
527                         parent,
528                         opaque,
529                         opaque_and_semitransparent: new_opaque_and_semitransparent,
530                         dollar_crate_name: kw::DollarCrate,
531                     });
532                     new_opaque_and_semitransparent
533                 });
534         }
535
536         let parent = ctxt;
537         *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
538             let new_opaque_and_semitransparent_and_transparent =
539                 SyntaxContext(syntax_context_data.len() as u32);
540             syntax_context_data.push(SyntaxContextData {
541                 outer_expn: expn_id,
542                 outer_transparency: transparency,
543                 parent,
544                 opaque,
545                 opaque_and_semitransparent,
546                 dollar_crate_name: kw::DollarCrate,
547             });
548             new_opaque_and_semitransparent_and_transparent
549         })
550     }
551 }
552
553 pub fn clear_syntax_context_map() {
554     HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
555 }
556
557 pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
558     HygieneData::with(|data| data.walk_chain(span, to))
559 }
560
561 pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {
562     // The new contexts that need updating are at the end of the list and have `$crate` as a name.
563     let (len, to_update) = HygieneData::with(|data| {
564         (
565             data.syntax_context_data.len(),
566             data.syntax_context_data
567                 .iter()
568                 .rev()
569                 .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate)
570                 .count(),
571         )
572     });
573     // The callback must be called from outside of the `HygieneData` lock,
574     // since it will try to acquire it too.
575     let range_to_update = len - to_update..len;
576     let names: Vec<_> =
577         range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
578     HygieneData::with(|data| {
579         range_to_update.zip(names).for_each(|(idx, name)| {
580             data.syntax_context_data[idx].dollar_crate_name = name;
581         })
582     })
583 }
584
585 pub fn debug_hygiene_data(verbose: bool) -> String {
586     HygieneData::with(|data| {
587         if verbose {
588             format!("{:#?}", data)
589         } else {
590             let mut s = String::from("");
591             s.push_str("Expansions:");
592             let mut debug_expn_data = |(id, expn_info): (&ExpnId, &ExpnData)| {
593                 s.push_str(&format!(
594                     "\n{:?}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
595                     id,
596                     expn_info.parent,
597                     expn_info.call_site.ctxt(),
598                     expn_info.def_site.ctxt(),
599                     expn_info.kind,
600                 ))
601             };
602             data.local_expn_data.iter_enumerated().for_each(|(id, expn_info)| {
603                 let expn_info = expn_info.as_ref().expect("no expansion data for an expansion ID");
604                 debug_expn_data((&id.to_expn_id(), expn_info))
605             });
606             data.foreign_expn_data.iter().for_each(debug_expn_data);
607             s.push_str("\n\nSyntaxContexts:");
608             data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
609                 s.push_str(&format!(
610                     "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
611                     id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
612                 ));
613             });
614             s
615         }
616     })
617 }
618
619 impl SyntaxContext {
620     #[inline]
621     pub const fn root() -> Self {
622         SyntaxContext(0)
623     }
624
625     #[inline]
626     crate fn as_u32(self) -> u32 {
627         self.0
628     }
629
630     #[inline]
631     crate fn from_u32(raw: u32) -> SyntaxContext {
632         SyntaxContext(raw)
633     }
634
635     /// Extend a syntax context with a given expansion and transparency.
636     crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
637         HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
638     }
639
640     /// Pulls a single mark off of the syntax context. This effectively moves the
641     /// context up one macro definition level. That is, if we have a nested macro
642     /// definition as follows:
643     ///
644     /// ```rust
645     /// macro_rules! f {
646     ///    macro_rules! g {
647     ///        ...
648     ///    }
649     /// }
650     /// ```
651     ///
652     /// and we have a SyntaxContext that is referring to something declared by an invocation
653     /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
654     /// invocation of f that created g1.
655     /// Returns the mark that was removed.
656     pub fn remove_mark(&mut self) -> ExpnId {
657         HygieneData::with(|data| data.remove_mark(self).0)
658     }
659
660     pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
661         HygieneData::with(|data| data.marks(self))
662     }
663
664     /// Adjust this context for resolution in a scope created by the given expansion.
665     /// For example, consider the following three resolutions of `f`:
666     ///
667     /// ```rust
668     /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
669     /// m!(f);
670     /// macro m($f:ident) {
671     ///     mod bar {
672     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
673     ///         pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
674     ///     }
675     ///     foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
676     ///     //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
677     ///     //| and it resolves to `::foo::f`.
678     ///     bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
679     ///     //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
680     ///     //| and it resolves to `::bar::f`.
681     ///     bar::$f(); // `f`'s `SyntaxContext` is empty.
682     ///     //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
683     ///     //| and it resolves to `::bar::$f`.
684     /// }
685     /// ```
686     /// This returns the expansion whose definition scope we use to privacy check the resolution,
687     /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
688     pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
689         HygieneData::with(|data| data.adjust(self, expn_id))
690     }
691
692     /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
693     pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
694         HygieneData::with(|data| {
695             *self = data.normalize_to_macros_2_0(*self);
696             data.adjust(self, expn_id)
697         })
698     }
699
700     /// Adjust this context for resolution in a scope created by the given expansion
701     /// via a glob import with the given `SyntaxContext`.
702     /// For example:
703     ///
704     /// ```rust
705     /// m!(f);
706     /// macro m($i:ident) {
707     ///     mod foo {
708     ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
709     ///         pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
710     ///     }
711     ///     n(f);
712     ///     macro n($j:ident) {
713     ///         use foo::*;
714     ///         f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
715     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
716     ///         $i(); // `$i`'s `SyntaxContext` has a mark from `n`
717     ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
718     ///         $j(); // `$j`'s `SyntaxContext` has a mark from `m`
719     ///         //^ This cannot be glob-adjusted, so this is a resolution error.
720     ///     }
721     /// }
722     /// ```
723     /// This returns `None` if the context cannot be glob-adjusted.
724     /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
725     pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
726         HygieneData::with(|data| {
727             let mut scope = None;
728             let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
729             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
730                 scope = Some(data.remove_mark(&mut glob_ctxt).0);
731                 if data.remove_mark(self).0 != scope.unwrap() {
732                     return None;
733                 }
734             }
735             if data.adjust(self, expn_id).is_some() {
736                 return None;
737             }
738             Some(scope)
739         })
740     }
741
742     /// Undo `glob_adjust` if possible:
743     ///
744     /// ```rust
745     /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
746     ///     assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
747     /// }
748     /// ```
749     pub fn reverse_glob_adjust(
750         &mut self,
751         expn_id: ExpnId,
752         glob_span: Span,
753     ) -> Option<Option<ExpnId>> {
754         HygieneData::with(|data| {
755             if data.adjust(self, expn_id).is_some() {
756                 return None;
757             }
758
759             let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
760             let mut marks = Vec::new();
761             while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
762                 marks.push(data.remove_mark(&mut glob_ctxt));
763             }
764
765             let scope = marks.last().map(|mark| mark.0);
766             while let Some((expn_id, transparency)) = marks.pop() {
767                 *self = data.apply_mark(*self, expn_id, transparency);
768             }
769             Some(scope)
770         })
771     }
772
773     pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
774         HygieneData::with(|data| {
775             let mut self_normalized = data.normalize_to_macros_2_0(self);
776             data.adjust(&mut self_normalized, expn_id);
777             self_normalized == data.normalize_to_macros_2_0(other)
778         })
779     }
780
781     #[inline]
782     pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
783         HygieneData::with(|data| data.normalize_to_macros_2_0(self))
784     }
785
786     #[inline]
787     pub fn normalize_to_macro_rules(self) -> SyntaxContext {
788         HygieneData::with(|data| data.normalize_to_macro_rules(self))
789     }
790
791     #[inline]
792     pub fn outer_expn(self) -> ExpnId {
793         HygieneData::with(|data| data.outer_expn(self))
794     }
795
796     /// `ctxt.outer_expn_data()` is equivalent to but faster than
797     /// `ctxt.outer_expn().expn_data()`.
798     #[inline]
799     pub fn outer_expn_data(self) -> ExpnData {
800         HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
801     }
802
803     #[inline]
804     pub fn outer_mark(self) -> (ExpnId, Transparency) {
805         HygieneData::with(|data| data.outer_mark(self))
806     }
807
808     pub fn dollar_crate_name(self) -> Symbol {
809         HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
810     }
811
812     pub fn edition(self) -> Edition {
813         HygieneData::with(|data| data.expn_data(data.outer_expn(self)).edition)
814     }
815 }
816
817 impl fmt::Debug for SyntaxContext {
818     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
819         write!(f, "#{}", self.0)
820     }
821 }
822
823 impl Span {
824     /// Creates a fresh expansion with given properties.
825     /// Expansions are normally created by macros, but in some cases expansions are created for
826     /// other compiler-generated code to set per-span properties like allowed unstable features.
827     /// The returned span belongs to the created expansion and has the new properties,
828     /// but its location is inherited from the current span.
829     pub fn fresh_expansion(self, expn_data: ExpnData, ctx: impl HashStableContext) -> Span {
830         self.fresh_expansion_with_transparency(expn_data, Transparency::Transparent, ctx)
831     }
832
833     pub fn fresh_expansion_with_transparency(
834         self,
835         expn_data: ExpnData,
836         transparency: Transparency,
837         ctx: impl HashStableContext,
838     ) -> Span {
839         let expn_id = LocalExpnId::fresh(expn_data, ctx).to_expn_id();
840         HygieneData::with(|data| {
841             self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency))
842         })
843     }
844
845     /// Reuses the span but adds information like the kind of the desugaring and features that are
846     /// allowed inside this span.
847     pub fn mark_with_reason(
848         self,
849         allow_internal_unstable: Option<Lrc<[Symbol]>>,
850         reason: DesugaringKind,
851         edition: Edition,
852         ctx: impl HashStableContext,
853     ) -> Span {
854         let expn_data = ExpnData {
855             allow_internal_unstable,
856             ..ExpnData::default(ExpnKind::Desugaring(reason), self, edition, None, None)
857         };
858         self.fresh_expansion(expn_data, ctx)
859     }
860 }
861
862 /// A subset of properties from both macro definition and macro call available through global data.
863 /// Avoid using this if you have access to the original definition or call structures.
864 #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
865 pub struct ExpnData {
866     // --- The part unique to each expansion.
867     /// The kind of this expansion - macro or compiler desugaring.
868     pub kind: ExpnKind,
869     /// The expansion that produced this expansion.
870     pub parent: ExpnId,
871     /// The location of the actual macro invocation or syntax sugar , e.g.
872     /// `let x = foo!();` or `if let Some(y) = x {}`
873     ///
874     /// This may recursively refer to other macro invocations, e.g., if
875     /// `foo!()` invoked `bar!()` internally, and there was an
876     /// expression inside `bar!`; the call_site of the expression in
877     /// the expansion would point to the `bar!` invocation; that
878     /// call_site span would have its own ExpnData, with the call_site
879     /// pointing to the `foo!` invocation.
880     pub call_site: Span,
881     /// The crate that originally created this `ExpnData`. During
882     /// metadata serialization, we only encode `ExpnData`s that were
883     /// created locally - when our serialized metadata is decoded,
884     /// foreign `ExpnId`s will have their `ExpnData` looked up
885     /// from the crate specified by `Crate
886     krate: CrateNum,
887     /// The raw that this `ExpnData` had in its original crate.
888     /// An `ExpnData` can be created before being assigned an `ExpnId`,
889     /// so this might be `None` until `set_expn_data` is called
890     // This is used only for serialization/deserialization purposes:
891     // two `ExpnData`s that differ only in their `orig_id` should
892     // be considered equivalent.
893     #[stable_hasher(ignore)]
894     orig_id: Option<u32>,
895     /// Used to force two `ExpnData`s to have different `Fingerprint`s.
896     /// Due to macro expansion, it's possible to end up with two `ExpnId`s
897     /// that have identical `ExpnData`s. This violates the contract of `HashStable`
898     /// - the two `ExpnId`s are not equal, but their `Fingerprint`s are equal
899     /// (since the numerical `ExpnId` value is not considered by the `HashStable`
900     /// implementation).
901     ///
902     /// The `disambiguator` field is set by `update_disambiguator` when two distinct
903     /// `ExpnId`s would end up with the same `Fingerprint`. Since `ExpnData` includes
904     /// a `krate` field, this value only needs to be unique within a single crate.
905     disambiguator: u32,
906
907     // --- The part specific to the macro/desugaring definition.
908     // --- It may be reasonable to share this part between expansions with the same definition,
909     // --- but such sharing is known to bring some minor inconveniences without also bringing
910     // --- noticeable perf improvements (PR #62898).
911     /// The span of the macro definition (possibly dummy).
912     /// This span serves only informational purpose and is not used for resolution.
913     pub def_site: Span,
914     /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
915     /// internally without forcing the whole crate to opt-in
916     /// to them.
917     pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
918     /// Whether the macro is allowed to use `unsafe` internally
919     /// even if the user crate has `#![forbid(unsafe_code)]`.
920     pub allow_internal_unsafe: bool,
921     /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
922     /// for a given macro.
923     pub local_inner_macros: bool,
924     /// Edition of the crate in which the macro is defined.
925     pub edition: Edition,
926     /// The `DefId` of the macro being invoked,
927     /// if this `ExpnData` corresponds to a macro invocation
928     pub macro_def_id: Option<DefId>,
929     /// The normal module (`mod`) in which the expanded macro was defined.
930     pub parent_module: Option<DefId>,
931 }
932
933 // These would require special handling of `orig_id`.
934 impl !PartialEq for ExpnData {}
935 impl !Hash for ExpnData {}
936
937 impl ExpnData {
938     pub fn new(
939         kind: ExpnKind,
940         parent: ExpnId,
941         call_site: Span,
942         def_site: Span,
943         allow_internal_unstable: Option<Lrc<[Symbol]>>,
944         allow_internal_unsafe: bool,
945         local_inner_macros: bool,
946         edition: Edition,
947         macro_def_id: Option<DefId>,
948         parent_module: Option<DefId>,
949     ) -> ExpnData {
950         ExpnData {
951             kind,
952             parent,
953             call_site,
954             def_site,
955             allow_internal_unstable,
956             allow_internal_unsafe,
957             local_inner_macros,
958             edition,
959             macro_def_id,
960             parent_module,
961             krate: LOCAL_CRATE,
962             orig_id: None,
963             disambiguator: 0,
964         }
965     }
966
967     /// Constructs expansion data with default properties.
968     pub fn default(
969         kind: ExpnKind,
970         call_site: Span,
971         edition: Edition,
972         macro_def_id: Option<DefId>,
973         parent_module: Option<DefId>,
974     ) -> ExpnData {
975         ExpnData {
976             kind,
977             parent: ExpnId::root(),
978             call_site,
979             def_site: DUMMY_SP,
980             allow_internal_unstable: None,
981             allow_internal_unsafe: false,
982             local_inner_macros: false,
983             edition,
984             macro_def_id,
985             parent_module,
986             krate: LOCAL_CRATE,
987             orig_id: None,
988             disambiguator: 0,
989         }
990     }
991
992     pub fn allow_unstable(
993         kind: ExpnKind,
994         call_site: Span,
995         edition: Edition,
996         allow_internal_unstable: Lrc<[Symbol]>,
997         macro_def_id: Option<DefId>,
998         parent_module: Option<DefId>,
999     ) -> ExpnData {
1000         ExpnData {
1001             allow_internal_unstable: Some(allow_internal_unstable),
1002             ..ExpnData::default(kind, call_site, edition, macro_def_id, parent_module)
1003         }
1004     }
1005
1006     #[inline]
1007     pub fn is_root(&self) -> bool {
1008         matches!(self.kind, ExpnKind::Root)
1009     }
1010
1011     #[inline]
1012     fn hash_expn(&self, ctx: &mut impl HashStableContext) -> u64 {
1013         let mut hasher = StableHasher::new();
1014         self.hash_stable(ctx, &mut hasher);
1015         hasher.finish()
1016     }
1017 }
1018
1019 /// Expansion kind.
1020 #[derive(Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
1021 pub enum ExpnKind {
1022     /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
1023     Root,
1024     /// Expansion produced by a macro.
1025     Macro(MacroKind, Symbol),
1026     /// Transform done by the compiler on the AST.
1027     AstPass(AstPass),
1028     /// Desugaring done by the compiler during HIR lowering.
1029     Desugaring(DesugaringKind),
1030     /// MIR inlining
1031     Inlined,
1032 }
1033
1034 impl ExpnKind {
1035     pub fn descr(&self) -> String {
1036         match *self {
1037             ExpnKind::Root => kw::PathRoot.to_string(),
1038             ExpnKind::Macro(macro_kind, name) => match macro_kind {
1039                 MacroKind::Bang => format!("{}!", name),
1040                 MacroKind::Attr => format!("#[{}]", name),
1041                 MacroKind::Derive => format!("#[derive({})]", name),
1042             },
1043             ExpnKind::AstPass(kind) => kind.descr().to_string(),
1044             ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()),
1045             ExpnKind::Inlined => "inlined source".to_string(),
1046         }
1047     }
1048 }
1049
1050 /// The kind of macro invocation or definition.
1051 #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
1052 #[derive(HashStable_Generic)]
1053 pub enum MacroKind {
1054     /// A bang macro `foo!()`.
1055     Bang,
1056     /// An attribute macro `#[foo]`.
1057     Attr,
1058     /// A derive macro `#[derive(Foo)]`
1059     Derive,
1060 }
1061
1062 impl MacroKind {
1063     pub fn descr(self) -> &'static str {
1064         match self {
1065             MacroKind::Bang => "macro",
1066             MacroKind::Attr => "attribute macro",
1067             MacroKind::Derive => "derive macro",
1068         }
1069     }
1070
1071     pub fn descr_expected(self) -> &'static str {
1072         match self {
1073             MacroKind::Attr => "attribute",
1074             _ => self.descr(),
1075         }
1076     }
1077
1078     pub fn article(self) -> &'static str {
1079         match self {
1080             MacroKind::Attr => "an",
1081             _ => "a",
1082         }
1083     }
1084 }
1085
1086 /// The kind of AST transform.
1087 #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
1088 pub enum AstPass {
1089     StdImports,
1090     TestHarness,
1091     ProcMacroHarness,
1092 }
1093
1094 impl AstPass {
1095     fn descr(self) -> &'static str {
1096         match self {
1097             AstPass::StdImports => "standard library imports",
1098             AstPass::TestHarness => "test harness",
1099             AstPass::ProcMacroHarness => "proc macro harness",
1100         }
1101     }
1102 }
1103
1104 /// The kind of compiler desugaring.
1105 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
1106 pub enum DesugaringKind {
1107     /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
1108     /// However, we do not want to blame `c` for unreachability but rather say that `i`
1109     /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
1110     /// This also applies to `while` loops.
1111     CondTemporary,
1112     QuestionMark,
1113     TryBlock,
1114     /// Desugaring of an `impl Trait` in return type position
1115     /// to an `type Foo = impl Trait;` and replacing the
1116     /// `impl Trait` with `Foo`.
1117     OpaqueTy,
1118     Async,
1119     Await,
1120     ForLoop(ForLoopLoc),
1121 }
1122
1123 /// A location in the desugaring of a `for` loop
1124 #[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
1125 pub enum ForLoopLoc {
1126     Head,
1127     IntoIter,
1128 }
1129
1130 impl DesugaringKind {
1131     /// The description wording should combine well with "desugaring of {}".
1132     fn descr(self) -> &'static str {
1133         match self {
1134             DesugaringKind::CondTemporary => "`if` or `while` condition",
1135             DesugaringKind::Async => "`async` block or function",
1136             DesugaringKind::Await => "`await` expression",
1137             DesugaringKind::QuestionMark => "operator `?`",
1138             DesugaringKind::TryBlock => "`try` block",
1139             DesugaringKind::OpaqueTy => "`impl Trait`",
1140             DesugaringKind::ForLoop(_) => "`for` loop",
1141         }
1142     }
1143 }
1144
1145 #[derive(Default)]
1146 pub struct HygieneEncodeContext {
1147     /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
1148     /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
1149     /// that we don't accidentally try to encode any more `SyntaxContexts`
1150     serialized_ctxts: Lock<FxHashSet<SyntaxContext>>,
1151     /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
1152     /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData`
1153     /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
1154     /// until we reach a fixed point.
1155     latest_ctxts: Lock<FxHashSet<SyntaxContext>>,
1156
1157     serialized_expns: Lock<FxHashSet<ExpnId>>,
1158
1159     latest_expns: Lock<FxHashSet<ExpnId>>,
1160 }
1161
1162 impl HygieneEncodeContext {
1163     /// Record the fact that we need to serialize the corresponding `ExpnData`.
1164     pub fn schedule_expn_data_for_encoding(&self, expn: ExpnId) {
1165         if !self.serialized_expns.lock().contains(&expn) {
1166             self.latest_expns.lock().insert(expn);
1167         }
1168     }
1169
1170     pub fn encode<T, R>(
1171         &self,
1172         encoder: &mut T,
1173         mut encode_ctxt: impl FnMut(&mut T, u32, &SyntaxContextData) -> Result<(), R>,
1174         mut encode_expn: impl FnMut(&mut T, ExpnId, ExpnData, ExpnHash) -> Result<(), R>,
1175     ) -> Result<(), R> {
1176         // When we serialize a `SyntaxContextData`, we may end up serializing
1177         // a `SyntaxContext` that we haven't seen before
1178         while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() {
1179             debug!(
1180                 "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}",
1181                 self.latest_ctxts.lock().len(),
1182                 self.latest_ctxts
1183             );
1184
1185             // Consume the current round of SyntaxContexts.
1186             // Drop the lock() temporary early
1187             let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) };
1188
1189             // It's fine to iterate over a HashMap, because the serialization
1190             // of the table that we insert data into doesn't depend on insertion
1191             // order
1192             for_all_ctxts_in(latest_ctxts.into_iter(), |index, ctxt, data| {
1193                 if self.serialized_ctxts.lock().insert(ctxt) {
1194                     encode_ctxt(encoder, index, data)?;
1195                 }
1196                 Ok(())
1197             })?;
1198
1199             let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) };
1200
1201             for_all_expns_in(latest_expns.into_iter(), |expn, data, hash| {
1202                 if self.serialized_expns.lock().insert(expn) {
1203                     encode_expn(encoder, expn, data, hash)?;
1204                 }
1205                 Ok(())
1206             })?;
1207         }
1208         debug!("encode_hygiene: Done serializing SyntaxContextData");
1209         Ok(())
1210     }
1211 }
1212
1213 #[derive(Default)]
1214 /// Additional information used to assist in decoding hygiene data
1215 pub struct HygieneDecodeContext {
1216     // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
1217     // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
1218     // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
1219     // so that multiple occurrences of the same serialized id are decoded to the same
1220     // `SyntaxContext`
1221     remapped_ctxts: Lock<Vec<Option<SyntaxContext>>>,
1222 }
1223
1224 /// Register an expansion which has been decoded from the on-disk-cache for the local crate.
1225 pub fn register_local_expn_id(mut data: ExpnData, hash: ExpnHash) -> ExpnId {
1226     HygieneData::with(|hygiene_data| {
1227         // If we just deserialized an `ExpnData` owned by
1228         // the local crate, its `orig_id` will be stale,
1229         // so we need to update it to its own value.
1230         // This only happens when we deserialize the incremental cache,
1231         // since a crate will never decode its own metadata.
1232         let expn_id = hygiene_data.local_expn_data.next_index();
1233         data.orig_id = Some(expn_id.as_u32());
1234         hygiene_data.local_expn_data.push(Some(data));
1235         let _eid = hygiene_data.local_expn_hashes.push(hash);
1236         debug_assert_eq!(expn_id, _eid);
1237
1238         let expn_id = expn_id.to_expn_id();
1239
1240         let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id);
1241         debug_assert!(_old_id.is_none());
1242         expn_id
1243     })
1244 }
1245
1246 /// Register an expansion which has been decoded from the metadata of a foreign crate.
1247 pub fn register_expn_id(data: ExpnData, hash: ExpnHash) -> ExpnId {
1248     let expn_id =
1249         ExpnId { krate: data.krate, local_id: ExpnIndex::from_u32(data.orig_id.unwrap()) };
1250     HygieneData::with(|hygiene_data| {
1251         let _old_data = hygiene_data.foreign_expn_data.insert(expn_id, data);
1252         debug_assert!(_old_data.is_none());
1253         let _old_hash = hygiene_data.foreign_expn_hashes.insert(expn_id, hash);
1254         debug_assert!(_old_hash.is_none());
1255         let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id);
1256         debug_assert!(_old_id.is_none());
1257     });
1258     expn_id
1259 }
1260
1261 /// Decode an expansion from the metadata of a foreign crate.
1262 pub fn decode_expn_id(
1263     krate: CrateNum,
1264     index: u32,
1265     decode_data: impl FnOnce(ExpnId) -> (ExpnData, ExpnHash),
1266 ) -> ExpnId {
1267     if index == 0 {
1268         debug!("decode_expn_id: deserialized root");
1269         return ExpnId::root();
1270     }
1271
1272     let index = ExpnIndex::from_u32(index);
1273
1274     // This function is used to decode metadata, so it cannot decode information about LOCAL_CRATE.
1275     debug_assert_ne!(krate, LOCAL_CRATE);
1276     let expn_id = ExpnId { krate, local_id: index };
1277
1278     // Fast path if the expansion has already been decoded.
1279     if HygieneData::with(|hygiene_data| hygiene_data.foreign_expn_data.contains_key(&expn_id)) {
1280         return expn_id;
1281     }
1282
1283     // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1284     // other ExpnIds
1285     let (expn_data, hash) = decode_data(expn_id);
1286     debug_assert_eq!(krate, expn_data.krate);
1287     debug_assert_eq!(Some(index.as_u32()), expn_data.orig_id);
1288
1289     register_expn_id(expn_data, hash)
1290 }
1291
1292 // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1293 // to track which `SyntaxContext`s we have already decoded.
1294 // The provided closure will be invoked to deserialize a `SyntaxContextData`
1295 // if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1296 pub fn decode_syntax_context<
1297     D: Decoder,
1298     F: FnOnce(&mut D, u32) -> Result<SyntaxContextData, D::Error>,
1299 >(
1300     d: &mut D,
1301     context: &HygieneDecodeContext,
1302     decode_data: F,
1303 ) -> Result<SyntaxContext, D::Error> {
1304     let raw_id: u32 = Decodable::decode(d)?;
1305     if raw_id == 0 {
1306         debug!("decode_syntax_context: deserialized root");
1307         // The root is special
1308         return Ok(SyntaxContext::root());
1309     }
1310
1311     let outer_ctxts = &context.remapped_ctxts;
1312
1313     // Ensure that the lock() temporary is dropped early
1314     {
1315         if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1316             return Ok(ctxt);
1317         }
1318     }
1319
1320     // Allocate and store SyntaxContext id *before* calling the decoder function,
1321     // as the SyntaxContextData may reference itself.
1322     let new_ctxt = HygieneData::with(|hygiene_data| {
1323         let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
1324         // Push a dummy SyntaxContextData to ensure that nobody else can get the
1325         // same ID as us. This will be overwritten after call `decode_Data`
1326         hygiene_data.syntax_context_data.push(SyntaxContextData {
1327             outer_expn: ExpnId::root(),
1328             outer_transparency: Transparency::Transparent,
1329             parent: SyntaxContext::root(),
1330             opaque: SyntaxContext::root(),
1331             opaque_and_semitransparent: SyntaxContext::root(),
1332             dollar_crate_name: kw::Empty,
1333         });
1334         let mut ctxts = outer_ctxts.lock();
1335         let new_len = raw_id as usize + 1;
1336         if ctxts.len() < new_len {
1337             ctxts.resize(new_len, None);
1338         }
1339         ctxts[raw_id as usize] = Some(new_ctxt);
1340         drop(ctxts);
1341         new_ctxt
1342     });
1343
1344     // Don't try to decode data while holding the lock, since we need to
1345     // be able to recursively decode a SyntaxContext
1346     let mut ctxt_data = decode_data(d, raw_id)?;
1347     // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1348     // We don't care what the encoding crate set this to - we want to resolve it
1349     // from the perspective of the current compilation session
1350     ctxt_data.dollar_crate_name = kw::DollarCrate;
1351
1352     // Overwrite the dummy data with our decoded SyntaxContextData
1353     HygieneData::with(|hygiene_data| {
1354         let dummy = std::mem::replace(
1355             &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize],
1356             ctxt_data,
1357         );
1358         // Make sure nothing weird happening while `decode_data` was running
1359         assert_eq!(dummy.dollar_crate_name, kw::Empty);
1360     });
1361
1362     Ok(new_ctxt)
1363 }
1364
1365 fn for_all_ctxts_in<E, F: FnMut(u32, SyntaxContext, &SyntaxContextData) -> Result<(), E>>(
1366     ctxts: impl Iterator<Item = SyntaxContext>,
1367     mut f: F,
1368 ) -> Result<(), E> {
1369     let all_data: Vec<_> = HygieneData::with(|data| {
1370         ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect()
1371     });
1372     for (ctxt, data) in all_data.into_iter() {
1373         f(ctxt.0, ctxt, &data)?;
1374     }
1375     Ok(())
1376 }
1377
1378 fn for_all_expns_in<E>(
1379     expns: impl Iterator<Item = ExpnId>,
1380     mut f: impl FnMut(ExpnId, ExpnData, ExpnHash) -> Result<(), E>,
1381 ) -> Result<(), E> {
1382     let all_data: Vec<_> = HygieneData::with(|data| {
1383         expns
1384             .map(|expn| (expn, data.expn_data(expn).clone(), data.expn_hash(expn).clone()))
1385             .collect()
1386     });
1387     for (expn, data, hash) in all_data.into_iter() {
1388         f(expn, data, hash)?;
1389     }
1390     Ok(())
1391 }
1392
1393 impl<E: Encoder> Encodable<E> for LocalExpnId {
1394     fn encode(&self, e: &mut E) -> Result<(), E::Error> {
1395         self.to_expn_id().encode(e)
1396     }
1397 }
1398
1399 impl<E: Encoder> Encodable<E> for ExpnId {
1400     default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1401         panic!("cannot encode `ExpnId` with `{}`", std::any::type_name::<E>());
1402     }
1403 }
1404
1405 impl<D: Decoder> Decodable<D> for LocalExpnId {
1406     fn decode(d: &mut D) -> Result<Self, D::Error> {
1407         ExpnId::decode(d).map(ExpnId::expect_local)
1408     }
1409 }
1410
1411 impl<D: Decoder> Decodable<D> for ExpnId {
1412     default fn decode(_: &mut D) -> Result<Self, D::Error> {
1413         panic!("cannot decode `ExpnId` with `{}`", std::any::type_name::<D>());
1414     }
1415 }
1416
1417 pub fn raw_encode_syntax_context<E: Encoder>(
1418     ctxt: SyntaxContext,
1419     context: &HygieneEncodeContext,
1420     e: &mut E,
1421 ) -> Result<(), E::Error> {
1422     if !context.serialized_ctxts.lock().contains(&ctxt) {
1423         context.latest_ctxts.lock().insert(ctxt);
1424     }
1425     ctxt.0.encode(e)
1426 }
1427
1428 impl<E: Encoder> Encodable<E> for SyntaxContext {
1429     default fn encode(&self, _: &mut E) -> Result<(), E::Error> {
1430         panic!("cannot encode `SyntaxContext` with `{}`", std::any::type_name::<E>());
1431     }
1432 }
1433
1434 impl<D: Decoder> Decodable<D> for SyntaxContext {
1435     default fn decode(_: &mut D) -> Result<Self, D::Error> {
1436         panic!("cannot decode `SyntaxContext` with `{}`", std::any::type_name::<D>());
1437     }
1438 }
1439
1440 /// Updates the `disambiguator` field of the corresponding `ExpnData`
1441 /// such that the `Fingerprint` of the `ExpnData` does not collide with
1442 /// any other `ExpnIds`.
1443 ///
1444 /// This method is called only when an `ExpnData` is first associated
1445 /// with an `ExpnId` (when the `ExpnId` is initially constructed, or via
1446 /// `set_expn_data`). It is *not* called for foreign `ExpnId`s deserialized
1447 /// from another crate's metadata - since `ExpnData` includes a `krate` field,
1448 /// collisions are only possible between `ExpnId`s within the same crate.
1449 fn update_disambiguator(expn_id: LocalExpnId, mut ctx: impl HashStableContext) {
1450     let mut expn_data = expn_id.expn_data();
1451     // This disambiguator should not have been set yet.
1452     assert_eq!(
1453         expn_data.disambiguator, 0,
1454         "Already set disambiguator for ExpnData: {:?}",
1455         expn_data
1456     );
1457     let mut expn_hash = expn_data.hash_expn(&mut ctx);
1458
1459     let disambiguator = HygieneData::with(|data| {
1460         // If this is the first ExpnData with a given hash, then keep our
1461         // disambiguator at 0 (the default u32 value)
1462         let disambig = data.expn_data_disambiguators.entry(expn_hash).or_default();
1463         let disambiguator = *disambig;
1464         *disambig += 1;
1465         disambiguator
1466     });
1467
1468     if disambiguator != 0 {
1469         debug!("Set disambiguator for {:?} (hash {:?})", expn_id, expn_hash);
1470         debug!("expn_data = {:?}", expn_data);
1471
1472         expn_data.disambiguator = disambiguator;
1473         expn_hash = expn_data.hash_expn(&mut ctx);
1474
1475         // Verify that the new disambiguator makes the hash unique
1476         #[cfg(debug_assertions)]
1477         HygieneData::with(|data| {
1478             assert_eq!(
1479                 data.expn_data_disambiguators.get(&expn_hash),
1480                 None,
1481                 "Hash collision after disambiguator update!",
1482             );
1483         });
1484     }
1485
1486     let expn_hash =
1487         ExpnHash::new(ctx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), expn_hash);
1488     HygieneData::with(|data| {
1489         data.local_expn_data[expn_id].as_mut().unwrap().disambiguator = disambiguator;
1490         debug_assert_eq!(data.local_expn_hashes[expn_id].0, Fingerprint::ZERO);
1491         data.local_expn_hashes[expn_id] = expn_hash;
1492         let _old_id = data.expn_hash_to_expn_id.insert(expn_hash, expn_id.to_expn_id());
1493         debug_assert!(_old_id.is_none());
1494     });
1495 }
1496
1497 impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1498     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1499         const TAG_EXPANSION: u8 = 0;
1500         const TAG_NO_EXPANSION: u8 = 1;
1501
1502         if *self == SyntaxContext::root() {
1503             TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1504         } else {
1505             TAG_EXPANSION.hash_stable(ctx, hasher);
1506             let (expn_id, transparency) = self.outer_mark();
1507             expn_id.hash_stable(ctx, hasher);
1508             transparency.hash_stable(ctx, hasher);
1509         }
1510     }
1511 }
1512
1513 impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1514     fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1515         let hash = if *self == ExpnId::root() {
1516             // Avoid fetching TLS storage for a trivial often-used value.
1517             Fingerprint::ZERO
1518         } else {
1519             self.expn_hash().0
1520         };
1521
1522         hash.hash_stable(ctx, hasher);
1523     }
1524 }