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