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