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