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