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