]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_span/src/hygiene.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / compiler / rustc_span / src / hygiene.rs
CommitLineData
f035d41b 1//! Machinery for hygienic macros.
5bcae85e 2//!
f035d41b
XL
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>.
5bcae85e 6
dc9dc135
XL
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//
416331ca 13// This explains why `HygieneData`, `SyntaxContext` and `ExpnId` have interfaces
dc9dc135 14// with a certain amount of redundancy in them. For example,
e1599b0c
XL
15// `SyntaxContext::outer_expn_data` combines `SyntaxContext::outer` and
16// `ExpnId::expn_data` so that two `HygieneData` accesses can be performed within
dc9dc135
XL
17// a single `HygieneData::with` call.
18//
19// It also explains why many functions appear in `HygieneData` and again in
416331ca 20// `SyntaxContext` or `ExpnId`. For example, `HygieneData::outer` and
dc9dc135
XL
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
dc9dc135 27use crate::edition::Edition;
60c5eb7d 28use crate::symbol::{kw, sym, Symbol};
136023e0
XL
29use crate::with_session_globals;
30use crate::{HashStableContext, Span, DUMMY_SP};
cc61c64b 31
136023e0 32use crate::def_id::{CrateNum, DefId, StableCrateId, CRATE_DEF_ID, LOCAL_CRATE};
5869c6ff 33use rustc_data_structures::fingerprint::Fingerprint;
3dfed10e 34use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5099ac24 35use rustc_data_structures::stable_hasher::HashingControls;
5869c6ff 36use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
3dfed10e 37use rustc_data_structures::sync::{Lock, Lrc};
136023e0
XL
38use rustc_data_structures::unhash::UnhashMap;
39use rustc_index::vec::IndexVec;
dfeec247
XL
40use rustc_macros::HashStable_Generic;
41use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
416331ca 42use std::fmt;
5869c6ff 43use std::hash::Hash;
3dfed10e 44use tracing::*;
5bcae85e 45
416331ca
XL
46/// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks".
47#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
8faf50e0
XL
48pub struct SyntaxContext(u32);
49
3dfed10e
XL
50#[derive(Debug, Encodable, Decodable, Clone)]
51pub struct SyntaxContextData {
416331ca
XL
52 outer_expn: ExpnId,
53 outer_transparency: Transparency,
54 parent: SyntaxContext,
55 /// This context, but with all transparent and semi-transparent expansions filtered away.
8faf50e0 56 opaque: SyntaxContext,
416331ca 57 /// This context, but with all transparent expansions filtered away.
8faf50e0 58 opaque_and_semitransparent: SyntaxContext,
48663c56 59 /// Name of the crate to which `$crate` with this context would resolve.
0731742a 60 dollar_crate_name: Symbol,
5bcae85e
SL
61}
62
136023e0
XL
63rustc_index::newtype_index! {
64 /// A unique ID associated with a macro invocation and expansion.
65 pub struct ExpnIndex {
66 ENCODABLE = custom
67 }
68}
69
416331ca 70/// A unique ID associated with a macro invocation and expansion.
136023e0
XL
71#[derive(Clone, Copy, PartialEq, Eq, Hash)]
72pub struct ExpnId {
73 pub krate: CrateNum,
74 pub local_id: ExpnIndex,
75}
76
77impl 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
84rustc_index::newtype_index! {
85 /// A unique ID associated with a macro invocation and expansion.
86 pub struct LocalExpnId {
87 ENCODABLE = custom
5e7ed085 88 ORD_IMPL = custom
136023e0
XL
89 DEBUG_FORMAT = "expn{}"
90 }
91}
92
5e7ed085
FG
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.
96impl !Ord for LocalExpnId {}
97impl !PartialOrd for LocalExpnId {}
98
5099ac24
FG
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.
104fn assert_default_hashing_controls<CTX: HashStableContext>(ctx: &CTX, msg: &str) {
105 match ctx.hashing_controls() {
5099ac24
FG
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.
5e7ed085 110 HashingControls { hash_spans }
064997fb 111 if hash_spans == !ctx.unstable_opts_incremental_ignore_spans() => {}
5099ac24
FG
112 other => panic!("Attempted hashing of {msg} with non-default HashingControls: {:?}", other),
113 }
114}
115
136023e0
XL
116/// A unique hash value associated to an expansion.
117#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)]
118pub struct ExpnHash(Fingerprint);
119
120impl 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}
5bcae85e 147
8faf50e0
XL
148/// A property of a macro expansion that determines how identifiers
149/// produced by that expansion are resolved.
3dfed10e 150#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Encodable, Decodable)]
ba9703b0 151#[derive(HashStable_Generic)]
8faf50e0
XL
152pub 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,
ff7c6d11
XL
166}
167
136023e0
XL
168impl LocalExpnId {
169 /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST.
170 pub const ROOT: LocalExpnId = LocalExpnId::from_u32(0);
171
5099ac24 172 #[inline]
136023e0
XL
173 pub fn from_raw(idx: ExpnIndex) -> LocalExpnId {
174 LocalExpnId::from_u32(idx.as_u32())
5bcae85e 175 }
9e0c209e 176
5099ac24 177 #[inline]
136023e0
XL
178 pub fn as_raw(self) -> ExpnIndex {
179 ExpnIndex::from_u32(self.as_u32())
9e0c209e
SL
180 }
181
136023e0
XL
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 })
c30ab7b3
SL
202 }
203
ff7c6d11 204 #[inline]
136023e0
XL
205 pub fn expn_hash(self) -> ExpnHash {
206 HygieneData::with(|data| data.local_expn_hash(self))
32a655c1
SL
207 }
208
b7449926 209 #[inline]
e1599b0c 210 pub fn expn_data(self) -> ExpnData {
136023e0 211 HygieneData::with(|data| data.local_expn_data(self).clone())
b7449926
XL
212 }
213
ff7c6d11 214 #[inline]
136023e0
XL
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);
416331ca 223 HygieneData::with(|data| {
136023e0 224 let old_expn_data = &mut data.local_expn_data[self];
e1599b0c
XL
225 assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID");
226 *old_expn_data = Some(expn_data);
136023e0
XL
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());
5869c6ff 231 });
136023e0
XL
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
261impl 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())
7cac9316
XL
292 }
293
a2a8927a 294 #[inline]
416331ca 295 pub fn is_descendant_of(self, ancestor: ExpnId) -> bool {
a2a8927a
XL
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 }
dc9dc135 303 HygieneData::with(|data| data.is_descendant_of(self, ancestor))
7cac9316
XL
304 }
305
416331ca
XL
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)))
83c7162d 310 }
60c5eb7d
XL
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
dfeec247 320 if expn_data.is_root()
136023e0 321 || expn_data.kind == ExpnKind::Macro(MacroKind::Bang, sym::include)
dfeec247 322 {
60c5eb7d
XL
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 }
5bcae85e
SL
330}
331
8faf50e0 332#[derive(Debug)]
3dfed10e 333pub struct HygieneData {
e1599b0c
XL
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.
136023e0
XL
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>,
416331ca
XL
344 syntax_context_data: Vec<SyntaxContextData>,
345 syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
136023e0 346 /// Maps the `local_hash` of an `ExpnData` to the next disambiguator value.
5869c6ff
XL
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.
136023e0 351 expn_data_disambiguators: FxHashMap<u64, u32>,
5bcae85e
SL
352}
353
354impl HygieneData {
923072b8 355 pub(crate) fn new(edition: Edition) -> Self {
136023e0 356 let root_data = ExpnData::default(
3dfed10e
XL
357 ExpnKind::Root,
358 DUMMY_SP,
359 edition,
136023e0
XL
360 Some(CRATE_DEF_ID.to_def_id()),
361 None,
3dfed10e 362 );
3dfed10e 363
5bcae85e 364 HygieneData {
136023e0
XL
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(),
416331ca
XL
371 syntax_context_data: vec![SyntaxContextData {
372 outer_expn: ExpnId::root(),
373 outer_transparency: Transparency::Opaque,
374 parent: SyntaxContext(0),
8faf50e0
XL
375 opaque: SyntaxContext(0),
376 opaque_and_semitransparent: SyntaxContext(0),
dc9dc135 377 dollar_crate_name: kw::DollarCrate,
ff7c6d11 378 }],
416331ca 379 syntax_context_map: FxHashMap::default(),
5869c6ff 380 expn_data_disambiguators: FxHashMap::default(),
5bcae85e
SL
381 }
382 }
383
3dfed10e 384 pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
136023e0 385 with_session_globals(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
5bcae85e 386 }
5bcae85e 387
136023e0
XL
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],
3dfed10e 398 }
136023e0
XL
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")
dc9dc135
XL
403 }
404
e1599b0c 405 fn expn_data(&self, expn_id: ExpnId) -> &ExpnData {
136023e0
XL
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 }
416331ca
XL
411 }
412
413 fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool {
a2a8927a
XL
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 }
416331ca 425 if expn_id == ExpnId::root() {
dc9dc135
XL
426 return false;
427 }
e1599b0c 428 expn_id = self.expn_data(expn_id).parent;
dc9dc135 429 }
dc9dc135
XL
430 }
431
ba9703b0 432 fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
416331ca 433 self.syntax_context_data[ctxt.0 as usize].opaque
dc9dc135
XL
434 }
435
ba9703b0 436 fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
416331ca 437 self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
dc9dc135
XL
438 }
439
416331ca
XL
440 fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
441 self.syntax_context_data[ctxt.0 as usize].outer_expn
dc9dc135
XL
442 }
443
e1599b0c
XL
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)
dc9dc135
XL
447 }
448
416331ca
XL
449 fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
450 self.syntax_context_data[ctxt.0 as usize].parent
dc9dc135
XL
451 }
452
e1599b0c
XL
453 fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) {
454 let outer_mark = self.outer_mark(*ctxt);
416331ca 455 *ctxt = self.parent_ctxt(*ctxt);
e1599b0c 456 outer_mark
dc9dc135
XL
457 }
458
416331ca 459 fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> {
dc9dc135 460 let mut marks = Vec::new();
e1599b0c 461 while ctxt != SyntaxContext::root() {
3dfed10e 462 debug!("marks: getting parent of {:?}", ctxt);
e1599b0c 463 marks.push(self.outer_mark(ctxt));
416331ca 464 ctxt = self.parent_ctxt(ctxt);
dc9dc135
XL
465 }
466 marks.reverse();
467 marks
468 }
469
470 fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span {
3dfed10e
XL
471 debug!("walk_chain({:?}, {:?})", span, to);
472 debug!("walk_chain: span ctxt = {:?}", span.ctxt());
e1599b0c 473 while span.from_expansion() && span.ctxt() != to {
3dfed10e
XL
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;
dc9dc135
XL
479 }
480 span
481 }
482
416331ca 483 fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option<ExpnId> {
dc9dc135 484 let mut scope = None;
416331ca 485 while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) {
e1599b0c 486 scope = Some(self.remove_mark(ctxt).0);
dc9dc135
XL
487 }
488 scope
489 }
490
e1599b0c 491 fn apply_mark(
dfeec247
XL
492 &mut self,
493 ctxt: SyntaxContext,
494 expn_id: ExpnId,
495 transparency: Transparency,
e1599b0c 496 ) -> SyntaxContext {
416331ca 497 assert_ne!(expn_id, ExpnId::root());
dc9dc135 498 if transparency == Transparency::Opaque {
416331ca 499 return self.apply_mark_internal(ctxt, expn_id, transparency);
dc9dc135
XL
500 }
501
e1599b0c 502 let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt();
dc9dc135 503 let mut call_site_ctxt = if transparency == Transparency::SemiTransparent {
ba9703b0 504 self.normalize_to_macros_2_0(call_site_ctxt)
dc9dc135 505 } else {
ba9703b0 506 self.normalize_to_macro_rules(call_site_ctxt)
dc9dc135
XL
507 };
508
e1599b0c 509 if call_site_ctxt == SyntaxContext::root() {
416331ca 510 return self.apply_mark_internal(ctxt, expn_id, transparency);
dc9dc135
XL
511 }
512
416331ca 513 // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a
dc9dc135
XL
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 //
416331ca
XL
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);
dc9dc135 524 }
416331ca 525 self.apply_mark_internal(call_site_ctxt, expn_id, transparency)
dc9dc135
XL
526 }
527
416331ca 528 fn apply_mark_internal(
dfeec247
XL
529 &mut self,
530 ctxt: SyntaxContext,
531 expn_id: ExpnId,
532 transparency: Transparency,
416331ca
XL
533 ) -> SyntaxContext {
534 let syntax_context_data = &mut self.syntax_context_data;
535 let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
dc9dc135 536 let mut opaque_and_semitransparent =
416331ca 537 syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
dc9dc135
XL
538
539 if transparency >= Transparency::Opaque {
416331ca 540 let parent = opaque;
dfeec247
XL
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
dc9dc135 555 });
dc9dc135
XL
556 }
557
558 if transparency >= Transparency::SemiTransparent {
416331ca 559 let parent = opaque_and_semitransparent;
dfeec247
XL
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
dc9dc135 575 });
dc9dc135
XL
576 }
577
416331ca
XL
578 let parent = ctxt;
579 *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
dc9dc135 580 let new_opaque_and_semitransparent_and_transparent =
416331ca
XL
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,
dc9dc135
XL
586 opaque,
587 opaque_and_semitransparent,
588 dollar_crate_name: kw::DollarCrate,
589 });
590 new_opaque_and_semitransparent_and_transparent
591 })
592 }
94b46f34
XL
593}
594
416331ca
XL
595pub fn clear_syntax_context_map() {
596 HygieneData::with(|data| data.syntax_context_map = FxHashMap::default());
5bcae85e
SL
597}
598
dc9dc135
XL
599pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
600 HygieneData::with(|data| data.walk_chain(span, to))
601}
602
416331ca
XL
603pub 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.
dfeec247
XL
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 });
416331ca
XL
615 // The callback must be called from outside of the `HygieneData` lock,
616 // since it will try to acquire it too.
dfeec247 617 let range_to_update = len - to_update..len;
416331ca
XL
618 let names: Vec<_> =
619 range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect();
dfeec247 620 HygieneData::with(|data| {
cdc7bbd5 621 range_to_update.zip(names).for_each(|(idx, name)| {
dfeec247
XL
622 data.syntax_context_data[idx].dollar_crate_name = name;
623 })
624 })
416331ca
XL
625}
626
e1599b0c
XL
627pub fn debug_hygiene_data(verbose: bool) -> String {
628 HygieneData::with(|data| {
629 if verbose {
630 format!("{:#?}", data)
631 } else {
064997fb 632 let mut s = String::from("Expansions:");
136023e0 633 let mut debug_expn_data = |(id, expn_data): (&ExpnId, &ExpnData)| {
e1599b0c 634 s.push_str(&format!(
136023e0 635 "\n{:?}: parent: {:?}, call_site_ctxt: {:?}, def_site_ctxt: {:?}, kind: {:?}",
e1599b0c 636 id,
136023e0
XL
637 expn_data.parent,
638 expn_data.call_site.ctxt(),
639 expn_data.def_site.ctxt(),
640 expn_data.kind,
641 ))
642 };
643 data.local_expn_data.iter_enumerated().for_each(|(id, expn_data)| {
644 let expn_data = expn_data.as_ref().expect("no expansion data for an expansion ID");
645 debug_expn_data((&id.to_expn_id(), expn_data))
e1599b0c 646 });
064997fb 647
c295e0f8 648 // Sort the hash map for more reproducible output.
064997fb
FG
649 // Because of this, it is fine to rely on the unstable iteration order of the map.
650 #[allow(rustc::potential_query_instability)]
c295e0f8
XL
651 let mut foreign_expn_data: Vec<_> = data.foreign_expn_data.iter().collect();
652 foreign_expn_data.sort_by_key(|(id, _)| (id.krate, id.local_id));
653 foreign_expn_data.into_iter().for_each(debug_expn_data);
e1599b0c
XL
654 s.push_str("\n\nSyntaxContexts:");
655 data.syntax_context_data.iter().enumerate().for_each(|(id, ctxt)| {
656 s.push_str(&format!(
657 "\n#{}: parent: {:?}, outer_mark: ({:?}, {:?})",
dfeec247 658 id, ctxt.parent, ctxt.outer_expn, ctxt.outer_transparency,
e1599b0c
XL
659 ));
660 });
661 s
662 }
663 })
664}
665
5bcae85e 666impl SyntaxContext {
48663c56 667 #[inline]
e1599b0c 668 pub const fn root() -> Self {
5bcae85e
SL
669 SyntaxContext(0)
670 }
671
48663c56 672 #[inline]
923072b8 673 pub(crate) fn as_u32(self) -> u32 {
8faf50e0
XL
674 self.0
675 }
676
48663c56 677 #[inline]
923072b8 678 pub(crate) fn from_u32(raw: u32) -> SyntaxContext {
8faf50e0
XL
679 SyntaxContext(raw)
680 }
681
416331ca 682 /// Extend a syntax context with a given expansion and transparency.
923072b8 683 pub(crate) fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
e1599b0c 684 HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
5bcae85e 685 }
cc61c64b 686
83c7162d
XL
687 /// Pulls a single mark off of the syntax context. This effectively moves the
688 /// context up one macro definition level. That is, if we have a nested macro
689 /// definition as follows:
690 ///
04454e1e 691 /// ```ignore (illustrative)
83c7162d
XL
692 /// macro_rules! f {
693 /// macro_rules! g {
694 /// ...
695 /// }
696 /// }
697 /// ```
698 ///
699 /// and we have a SyntaxContext that is referring to something declared by an invocation
700 /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the
701 /// invocation of f that created g1.
702 /// Returns the mark that was removed.
416331ca 703 pub fn remove_mark(&mut self) -> ExpnId {
e1599b0c 704 HygieneData::with(|data| data.remove_mark(self).0)
7cac9316
XL
705 }
706
416331ca 707 pub fn marks(self) -> Vec<(ExpnId, Transparency)> {
dc9dc135 708 HygieneData::with(|data| data.marks(self))
2c00a5a8
XL
709 }
710
7cac9316
XL
711 /// Adjust this context for resolution in a scope created by the given expansion.
712 /// For example, consider the following three resolutions of `f`:
ff7c6d11 713 ///
7cac9316 714 /// ```rust
04454e1e 715 /// #![feature(decl_macro)]
7cac9316
XL
716 /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
717 /// m!(f);
718 /// macro m($f:ident) {
719 /// mod bar {
416331ca 720 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
7cac9316
XL
721 /// pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
722 /// }
416331ca 723 /// foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
7cac9316
XL
724 /// //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
725 /// //| and it resolves to `::foo::f`.
416331ca 726 /// bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
7cac9316
XL
727 /// //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
728 /// //| and it resolves to `::bar::f`.
729 /// bar::$f(); // `f`'s `SyntaxContext` is empty.
730 /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
731 /// //| and it resolves to `::bar::$f`.
732 /// }
733 /// ```
734 /// This returns the expansion whose definition scope we use to privacy check the resolution,
0731742a 735 /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
416331ca
XL
736 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
737 HygieneData::with(|data| data.adjust(self, expn_id))
dc9dc135
XL
738 }
739
ba9703b0
XL
740 /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
741 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
dc9dc135 742 HygieneData::with(|data| {
ba9703b0 743 *self = data.normalize_to_macros_2_0(*self);
416331ca 744 data.adjust(self, expn_id)
dc9dc135 745 })
7cac9316
XL
746 }
747
748 /// Adjust this context for resolution in a scope created by the given expansion
749 /// via a glob import with the given `SyntaxContext`.
ff7c6d11
XL
750 /// For example:
751 ///
04454e1e
FG
752 /// ```compile_fail,E0425
753 /// #![feature(decl_macro)]
7cac9316
XL
754 /// m!(f);
755 /// macro m($i:ident) {
756 /// mod foo {
416331ca 757 /// pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
7cac9316
XL
758 /// pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
759 /// }
3c0e092e 760 /// n!(f);
7cac9316
XL
761 /// macro n($j:ident) {
762 /// use foo::*;
763 /// f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
764 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
765 /// $i(); // `$i`'s `SyntaxContext` has a mark from `n`
766 /// //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
767 /// $j(); // `$j`'s `SyntaxContext` has a mark from `m`
768 /// //^ This cannot be glob-adjusted, so this is a resolution error.
769 /// }
770 /// }
771 /// ```
772 /// This returns `None` if the context cannot be glob-adjusted.
773 /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
416331ca 774 pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
dc9dc135
XL
775 HygieneData::with(|data| {
776 let mut scope = None;
ba9703b0 777 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
416331ca 778 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
e1599b0c
XL
779 scope = Some(data.remove_mark(&mut glob_ctxt).0);
780 if data.remove_mark(self).0 != scope.unwrap() {
dc9dc135
XL
781 return None;
782 }
783 }
416331ca 784 if data.adjust(self, expn_id).is_some() {
7cac9316
XL
785 return None;
786 }
dc9dc135
XL
787 Some(scope)
788 })
7cac9316
XL
789 }
790
791 /// Undo `glob_adjust` if possible:
ff7c6d11 792 ///
04454e1e 793 /// ```ignore (illustrative)
7cac9316
XL
794 /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
795 /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
796 /// }
797 /// ```
dfeec247
XL
798 pub fn reverse_glob_adjust(
799 &mut self,
800 expn_id: ExpnId,
801 glob_span: Span,
802 ) -> Option<Option<ExpnId>> {
dc9dc135 803 HygieneData::with(|data| {
416331ca 804 if data.adjust(self, expn_id).is_some() {
dc9dc135
XL
805 return None;
806 }
7cac9316 807
ba9703b0 808 let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
dc9dc135 809 let mut marks = Vec::new();
416331ca 810 while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
dc9dc135
XL
811 marks.push(data.remove_mark(&mut glob_ctxt));
812 }
7cac9316 813
e1599b0c
XL
814 let scope = marks.last().map(|mark| mark.0);
815 while let Some((expn_id, transparency)) = marks.pop() {
816 *self = data.apply_mark(*self, expn_id, transparency);
dc9dc135
XL
817 }
818 Some(scope)
819 })
820 }
821
416331ca 822 pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
dc9dc135 823 HygieneData::with(|data| {
ba9703b0
XL
824 let mut self_normalized = data.normalize_to_macros_2_0(self);
825 data.adjust(&mut self_normalized, expn_id);
826 self_normalized == data.normalize_to_macros_2_0(other)
dc9dc135 827 })
7cac9316
XL
828 }
829
ff7c6d11 830 #[inline]
ba9703b0
XL
831 pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
832 HygieneData::with(|data| data.normalize_to_macros_2_0(self))
8faf50e0
XL
833 }
834
835 #[inline]
ba9703b0
XL
836 pub fn normalize_to_macro_rules(self) -> SyntaxContext {
837 HygieneData::with(|data| data.normalize_to_macro_rules(self))
7cac9316
XL
838 }
839
ff7c6d11 840 #[inline]
416331ca
XL
841 pub fn outer_expn(self) -> ExpnId {
842 HygieneData::with(|data| data.outer_expn(self))
dc9dc135
XL
843 }
844
e1599b0c
XL
845 /// `ctxt.outer_expn_data()` is equivalent to but faster than
846 /// `ctxt.outer_expn().expn_data()`.
dc9dc135 847 #[inline]
e1599b0c
XL
848 pub fn outer_expn_data(self) -> ExpnData {
849 HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
dc9dc135
XL
850 }
851
3dfed10e
XL
852 #[inline]
853 pub fn outer_mark(self) -> (ExpnId, Transparency) {
854 HygieneData::with(|data| data.outer_mark(self))
855 }
856
0731742a 857 pub fn dollar_crate_name(self) -> Symbol {
416331ca 858 HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
0731742a 859 }
5869c6ff
XL
860
861 pub fn edition(self) -> Edition {
136023e0 862 HygieneData::with(|data| data.expn_data(data.outer_expn(self)).edition)
5869c6ff 863 }
5bcae85e
SL
864}
865
866impl fmt::Debug for SyntaxContext {
9fa01778 867 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5bcae85e
SL
868 write!(f, "#{}", self.0)
869 }
870}
cc61c64b 871
416331ca
XL
872impl Span {
873 /// Creates a fresh expansion with given properties.
874 /// Expansions are normally created by macros, but in some cases expansions are created for
875 /// other compiler-generated code to set per-span properties like allowed unstable features.
876 /// The returned span belongs to the created expansion and has the new properties,
877 /// but its location is inherited from the current span.
5e7ed085 878 pub fn fresh_expansion(self, expn_id: LocalExpnId) -> Span {
416331ca 879 HygieneData::with(|data| {
5e7ed085
FG
880 self.with_ctxt(data.apply_mark(
881 SyntaxContext::root(),
882 expn_id.to_expn_id(),
883 Transparency::Transparent,
884 ))
416331ca
XL
885 })
886 }
5869c6ff
XL
887
888 /// Reuses the span but adds information like the kind of the desugaring and features that are
889 /// allowed inside this span.
890 pub fn mark_with_reason(
891 self,
892 allow_internal_unstable: Option<Lrc<[Symbol]>>,
893 reason: DesugaringKind,
894 edition: Edition,
136023e0 895 ctx: impl HashStableContext,
5869c6ff 896 ) -> Span {
136023e0 897 let expn_data = ExpnData {
5869c6ff 898 allow_internal_unstable,
136023e0
XL
899 ..ExpnData::default(ExpnKind::Desugaring(reason), self, edition, None, None)
900 };
5e7ed085
FG
901 let expn_id = LocalExpnId::fresh(expn_data, ctx);
902 self.fresh_expansion(expn_id)
5869c6ff 903 }
416331ca
XL
904}
905
906/// A subset of properties from both macro definition and macro call available through global data.
907/// Avoid using this if you have access to the original definition or call structures.
3dfed10e 908#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
e1599b0c 909pub struct ExpnData {
dc9dc135 910 // --- The part unique to each expansion.
e1599b0c
XL
911 /// The kind of this expansion - macro or compiler desugaring.
912 pub kind: ExpnKind,
913 /// The expansion that produced this expansion.
914 pub parent: ExpnId,
cc61c64b
XL
915 /// The location of the actual macro invocation or syntax sugar , e.g.
916 /// `let x = foo!();` or `if let Some(y) = x {}`
917 ///
0731742a 918 /// This may recursively refer to other macro invocations, e.g., if
cc61c64b
XL
919 /// `foo!()` invoked `bar!()` internally, and there was an
920 /// expression inside `bar!`; the call_site of the expression in
921 /// the expansion would point to the `bar!` invocation; that
e1599b0c 922 /// call_site span would have its own ExpnData, with the call_site
cc61c64b
XL
923 /// pointing to the `foo!` invocation.
924 pub call_site: Span,
136023e0
XL
925 /// Used to force two `ExpnData`s to have different `Fingerprint`s.
926 /// Due to macro expansion, it's possible to end up with two `ExpnId`s
927 /// that have identical `ExpnData`s. This violates the contract of `HashStable`
928 /// - the two `ExpnId`s are not equal, but their `Fingerprint`s are equal
929 /// (since the numerical `ExpnId` value is not considered by the `HashStable`
930 /// implementation).
931 ///
932 /// The `disambiguator` field is set by `update_disambiguator` when two distinct
933 /// `ExpnId`s would end up with the same `Fingerprint`. Since `ExpnData` includes
934 /// a `krate` field, this value only needs to be unique within a single crate.
935 disambiguator: u32,
dc9dc135
XL
936
937 // --- The part specific to the macro/desugaring definition.
e1599b0c
XL
938 // --- It may be reasonable to share this part between expansions with the same definition,
939 // --- but such sharing is known to bring some minor inconveniences without also bringing
940 // --- noticeable perf improvements (PR #62898).
416331ca 941 /// The span of the macro definition (possibly dummy).
8faf50e0 942 /// This span serves only informational purpose and is not used for resolution.
416331ca 943 pub def_site: Span,
f9f354fc 944 /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
9fa01778 945 /// internally without forcing the whole crate to opt-in
cc61c64b 946 /// to them.
9fa01778 947 pub allow_internal_unstable: Option<Lrc<[Symbol]>>,
3b2f2976
XL
948 /// Whether the macro is allowed to use `unsafe` internally
949 /// even if the user crate has `#![forbid(unsafe_code)]`.
950 pub allow_internal_unsafe: bool,
8faf50e0
XL
951 /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`)
952 /// for a given macro.
953 pub local_inner_macros: bool,
94b46f34
XL
954 /// Edition of the crate in which the macro is defined.
955 pub edition: Edition,
f9f354fc
XL
956 /// The `DefId` of the macro being invoked,
957 /// if this `ExpnData` corresponds to a macro invocation
958 pub macro_def_id: Option<DefId>,
136023e0
XL
959 /// The normal module (`mod`) in which the expanded macro was defined.
960 pub parent_module: Option<DefId>,
cc61c64b
XL
961}
962
3dfed10e 963impl !PartialEq for ExpnData {}
5869c6ff 964impl !Hash for ExpnData {}
3dfed10e 965
e1599b0c 966impl ExpnData {
5869c6ff
XL
967 pub fn new(
968 kind: ExpnKind,
969 parent: ExpnId,
970 call_site: Span,
971 def_site: Span,
972 allow_internal_unstable: Option<Lrc<[Symbol]>>,
973 allow_internal_unsafe: bool,
974 local_inner_macros: bool,
975 edition: Edition,
976 macro_def_id: Option<DefId>,
136023e0 977 parent_module: Option<DefId>,
5869c6ff
XL
978 ) -> ExpnData {
979 ExpnData {
980 kind,
981 parent,
982 call_site,
983 def_site,
984 allow_internal_unstable,
985 allow_internal_unsafe,
986 local_inner_macros,
987 edition,
988 macro_def_id,
136023e0 989 parent_module,
5869c6ff
XL
990 disambiguator: 0,
991 }
992 }
993
e1599b0c 994 /// Constructs expansion data with default properties.
f9f354fc
XL
995 pub fn default(
996 kind: ExpnKind,
997 call_site: Span,
998 edition: Edition,
999 macro_def_id: Option<DefId>,
136023e0 1000 parent_module: Option<DefId>,
f9f354fc 1001 ) -> ExpnData {
e1599b0c 1002 ExpnData {
416331ca 1003 kind,
e1599b0c
XL
1004 parent: ExpnId::root(),
1005 call_site,
416331ca 1006 def_site: DUMMY_SP,
dc9dc135
XL
1007 allow_internal_unstable: None,
1008 allow_internal_unsafe: false,
1009 local_inner_macros: false,
1010 edition,
f9f354fc 1011 macro_def_id,
136023e0 1012 parent_module,
5869c6ff 1013 disambiguator: 0,
dc9dc135
XL
1014 }
1015 }
1016
dfeec247
XL
1017 pub fn allow_unstable(
1018 kind: ExpnKind,
1019 call_site: Span,
1020 edition: Edition,
1021 allow_internal_unstable: Lrc<[Symbol]>,
f9f354fc 1022 macro_def_id: Option<DefId>,
136023e0 1023 parent_module: Option<DefId>,
dfeec247 1024 ) -> ExpnData {
e1599b0c 1025 ExpnData {
416331ca 1026 allow_internal_unstable: Some(allow_internal_unstable),
136023e0 1027 ..ExpnData::default(kind, call_site, edition, macro_def_id, parent_module)
dc9dc135
XL
1028 }
1029 }
e1599b0c
XL
1030
1031 #[inline]
1032 pub fn is_root(&self) -> bool {
1b1a35ee 1033 matches!(self.kind, ExpnKind::Root)
e1599b0c 1034 }
136023e0
XL
1035
1036 #[inline]
1037 fn hash_expn(&self, ctx: &mut impl HashStableContext) -> u64 {
1038 let mut hasher = StableHasher::new();
1039 self.hash_stable(ctx, &mut hasher);
1040 hasher.finish()
1041 }
dc9dc135
XL
1042}
1043
416331ca 1044/// Expansion kind.
3dfed10e 1045#[derive(Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
416331ca
XL
1046pub enum ExpnKind {
1047 /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
1048 Root,
1049 /// Expansion produced by a macro.
136023e0 1050 Macro(MacroKind, Symbol),
e1599b0c
XL
1051 /// Transform done by the compiler on the AST.
1052 AstPass(AstPass),
cc61c64b 1053 /// Desugaring done by the compiler during HIR lowering.
dfeec247 1054 Desugaring(DesugaringKind),
29967ef6
XL
1055 /// MIR inlining
1056 Inlined,
3b2f2976
XL
1057}
1058
416331ca 1059impl ExpnKind {
dfeec247 1060 pub fn descr(&self) -> String {
8faf50e0 1061 match *self {
dfeec247 1062 ExpnKind::Root => kw::PathRoot.to_string(),
136023e0 1063 ExpnKind::Macro(macro_kind, name) => match macro_kind {
dfeec247
XL
1064 MacroKind::Bang => format!("{}!", name),
1065 MacroKind::Attr => format!("#[{}]", name),
1066 MacroKind::Derive => format!("#[derive({})]", name),
1067 },
1068 ExpnKind::AstPass(kind) => kind.descr().to_string(),
1069 ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()),
29967ef6 1070 ExpnKind::Inlined => "inlined source".to_string(),
416331ca
XL
1071 }
1072 }
1073}
1074
1075/// The kind of macro invocation or definition.
3dfed10e 1076#[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)]
ba9703b0 1077#[derive(HashStable_Generic)]
416331ca
XL
1078pub enum MacroKind {
1079 /// A bang macro `foo!()`.
1080 Bang,
1081 /// An attribute macro `#[foo]`.
1082 Attr,
1083 /// A derive macro `#[derive(Foo)]`
1084 Derive,
1085}
1086
1087impl MacroKind {
1088 pub fn descr(self) -> &'static str {
1089 match self {
1090 MacroKind::Bang => "macro",
1091 MacroKind::Attr => "attribute macro",
1092 MacroKind::Derive => "derive macro",
1093 }
1094 }
1095
e1599b0c
XL
1096 pub fn descr_expected(self) -> &'static str {
1097 match self {
1098 MacroKind::Attr => "attribute",
1099 _ => self.descr(),
1100 }
1101 }
1102
416331ca
XL
1103 pub fn article(self) -> &'static str {
1104 match self {
1105 MacroKind::Attr => "an",
1106 _ => "a",
8faf50e0
XL
1107 }
1108 }
1109}
1110
e1599b0c 1111/// The kind of AST transform.
3dfed10e 1112#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
e1599b0c
XL
1113pub enum AstPass {
1114 StdImports,
1115 TestHarness,
1116 ProcMacroHarness,
e1599b0c
XL
1117}
1118
1119impl AstPass {
136023e0 1120 pub fn descr(self) -> &'static str {
e1599b0c
XL
1121 match self {
1122 AstPass::StdImports => "standard library imports",
1123 AstPass::TestHarness => "test harness",
1124 AstPass::ProcMacroHarness => "proc macro harness",
e1599b0c
XL
1125 }
1126 }
1127}
1128
3b2f2976 1129/// The kind of compiler desugaring.
3dfed10e 1130#[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
416331ca 1131pub enum DesugaringKind {
48663c56
XL
1132 /// We desugar `if c { i } else { e }` to `match $ExprKind::Use(c) { true => i, _ => e }`.
1133 /// However, we do not want to blame `c` for unreachability but rather say that `i`
1134 /// is unreachable. This desugaring kind allows us to avoid blaming `c`.
416331ca
XL
1135 /// This also applies to `while` loops.
1136 CondTemporary,
3b2f2976 1137 QuestionMark,
b7449926 1138 TryBlock,
04454e1e 1139 YeetExpr,
94b46f34 1140 /// Desugaring of an `impl Trait` in return type position
416331ca 1141 /// to an `type Foo = impl Trait;` and replacing the
94b46f34 1142 /// `impl Trait` with `Foo`.
416331ca 1143 OpaqueTy,
8faf50e0 1144 Async,
48663c56 1145 Await,
3c0e092e 1146 ForLoop,
c295e0f8 1147 WhileLoop,
f035d41b
XL
1148}
1149
416331ca
XL
1150impl DesugaringKind {
1151 /// The description wording should combine well with "desugaring of {}".
136023e0 1152 pub fn descr(self) -> &'static str {
416331ca
XL
1153 match self {
1154 DesugaringKind::CondTemporary => "`if` or `while` condition",
1155 DesugaringKind::Async => "`async` block or function",
1156 DesugaringKind::Await => "`await` expression",
1157 DesugaringKind::QuestionMark => "operator `?`",
1158 DesugaringKind::TryBlock => "`try` block",
04454e1e 1159 DesugaringKind::YeetExpr => "`do yeet` expression",
416331ca 1160 DesugaringKind::OpaqueTy => "`impl Trait`",
3c0e092e 1161 DesugaringKind::ForLoop => "`for` loop",
c295e0f8 1162 DesugaringKind::WhileLoop => "`while` loop",
416331ca 1163 }
3b2f2976 1164 }
cc61c64b
XL
1165}
1166
3dfed10e
XL
1167#[derive(Default)]
1168pub struct HygieneEncodeContext {
1169 /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
1170 /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
1171 /// that we don't accidentally try to encode any more `SyntaxContexts`
1172 serialized_ctxts: Lock<FxHashSet<SyntaxContext>>,
1173 /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
5e7ed085 1174 /// in the most recent 'round' of serializing. Serializing `SyntaxContextData`
3dfed10e
XL
1175 /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
1176 /// until we reach a fixed point.
1177 latest_ctxts: Lock<FxHashSet<SyntaxContext>>,
1178
1179 serialized_expns: Lock<FxHashSet<ExpnId>>,
1180
1181 latest_expns: Lock<FxHashSet<ExpnId>>,
1182}
1183
1184impl HygieneEncodeContext {
136023e0
XL
1185 /// Record the fact that we need to serialize the corresponding `ExpnData`.
1186 pub fn schedule_expn_data_for_encoding(&self, expn: ExpnId) {
1187 if !self.serialized_expns.lock().contains(&expn) {
1188 self.latest_expns.lock().insert(expn);
1189 }
1190 }
1191
923072b8 1192 pub fn encode<T>(
3dfed10e
XL
1193 &self,
1194 encoder: &mut T,
923072b8
FG
1195 mut encode_ctxt: impl FnMut(&mut T, u32, &SyntaxContextData),
1196 mut encode_expn: impl FnMut(&mut T, ExpnId, &ExpnData, ExpnHash),
1197 ) {
3dfed10e
XL
1198 // When we serialize a `SyntaxContextData`, we may end up serializing
1199 // a `SyntaxContext` that we haven't seen before
1200 while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() {
1201 debug!(
1202 "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}",
1203 self.latest_ctxts.lock().len(),
1204 self.latest_ctxts
1205 );
1206
1207 // Consume the current round of SyntaxContexts.
1208 // Drop the lock() temporary early
1209 let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) };
1210
1211 // It's fine to iterate over a HashMap, because the serialization
1212 // of the table that we insert data into doesn't depend on insertion
1213 // order
064997fb 1214 #[allow(rustc::potential_query_instability)]
136023e0 1215 for_all_ctxts_in(latest_ctxts.into_iter(), |index, ctxt, data| {
3dfed10e 1216 if self.serialized_ctxts.lock().insert(ctxt) {
923072b8 1217 encode_ctxt(encoder, index, data);
3dfed10e 1218 }
923072b8 1219 });
3dfed10e
XL
1220
1221 let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) };
1222
064997fb
FG
1223 // Same as above, this is fine as we are inserting into a order-independent hashset
1224 #[allow(rustc::potential_query_instability)]
136023e0 1225 for_all_expns_in(latest_expns.into_iter(), |expn, data, hash| {
3dfed10e 1226 if self.serialized_expns.lock().insert(expn) {
923072b8 1227 encode_expn(encoder, expn, data, hash);
3dfed10e 1228 }
923072b8 1229 });
3dfed10e
XL
1230 }
1231 debug!("encode_hygiene: Done serializing SyntaxContextData");
3dfed10e
XL
1232 }
1233}
1234
1235#[derive(Default)]
1236/// Additional information used to assist in decoding hygiene data
1237pub struct HygieneDecodeContext {
1238 // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current
1239 // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create
1240 // a new id in the global `HygieneData`. This map tracks the ID we end up picking,
1241 // so that multiple occurrences of the same serialized id are decoded to the same
1242 // `SyntaxContext`
1243 remapped_ctxts: Lock<Vec<Option<SyntaxContext>>>,
3dfed10e
XL
1244}
1245
136023e0
XL
1246/// Register an expansion which has been decoded from the on-disk-cache for the local crate.
1247pub fn register_local_expn_id(data: ExpnData, hash: ExpnHash) -> ExpnId {
1248 HygieneData::with(|hygiene_data| {
1249 let expn_id = hygiene_data.local_expn_data.next_index();
1250 hygiene_data.local_expn_data.push(Some(data));
1251 let _eid = hygiene_data.local_expn_hashes.push(hash);
1252 debug_assert_eq!(expn_id, _eid);
1253
1254 let expn_id = expn_id.to_expn_id();
3dfed10e 1255
136023e0
XL
1256 let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id);
1257 debug_assert!(_old_id.is_none());
1258 expn_id
1259 })
1260}
1261
1262/// Register an expansion which has been decoded from the metadata of a foreign crate.
1263pub fn register_expn_id(
1264 krate: CrateNum,
1265 local_id: ExpnIndex,
1266 data: ExpnData,
1267 hash: ExpnHash,
1268) -> ExpnId {
a2a8927a 1269 debug_assert!(data.parent == ExpnId::root() || krate == data.parent.krate);
136023e0
XL
1270 let expn_id = ExpnId { krate, local_id };
1271 HygieneData::with(|hygiene_data| {
1272 let _old_data = hygiene_data.foreign_expn_data.insert(expn_id, data);
1273 debug_assert!(_old_data.is_none());
1274 let _old_hash = hygiene_data.foreign_expn_hashes.insert(expn_id, hash);
1275 debug_assert!(_old_hash.is_none());
1276 let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id);
1277 debug_assert!(_old_id.is_none());
1278 });
1279 expn_id
1280}
1281
1282/// Decode an expansion from the metadata of a foreign crate.
1283pub fn decode_expn_id(
1284 krate: CrateNum,
1285 index: u32,
1286 decode_data: impl FnOnce(ExpnId) -> (ExpnData, ExpnHash),
1287) -> ExpnId {
1288 if index == 0 {
3dfed10e 1289 debug!("decode_expn_id: deserialized root");
136023e0 1290 return ExpnId::root();
3dfed10e
XL
1291 }
1292
136023e0 1293 let index = ExpnIndex::from_u32(index);
3dfed10e 1294
136023e0
XL
1295 // This function is used to decode metadata, so it cannot decode information about LOCAL_CRATE.
1296 debug_assert_ne!(krate, LOCAL_CRATE);
1297 let expn_id = ExpnId { krate, local_id: index };
1298
1299 // Fast path if the expansion has already been decoded.
1300 if HygieneData::with(|hygiene_data| hygiene_data.foreign_expn_data.contains_key(&expn_id)) {
1301 return expn_id;
3dfed10e
XL
1302 }
1303
1304 // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1305 // other ExpnIds
136023e0 1306 let (expn_data, hash) = decode_data(expn_id);
3dfed10e 1307
136023e0 1308 register_expn_id(krate, index, expn_data, hash)
3dfed10e
XL
1309}
1310
1311// Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1312// to track which `SyntaxContext`s we have already decoded.
1313// The provided closure will be invoked to deserialize a `SyntaxContextData`
1314// if we haven't already seen the id of the `SyntaxContext` we are deserializing.
5099ac24 1315pub fn decode_syntax_context<D: Decoder, F: FnOnce(&mut D, u32) -> SyntaxContextData>(
3dfed10e
XL
1316 d: &mut D,
1317 context: &HygieneDecodeContext,
1318 decode_data: F,
5099ac24
FG
1319) -> SyntaxContext {
1320 let raw_id: u32 = Decodable::decode(d);
3dfed10e
XL
1321 if raw_id == 0 {
1322 debug!("decode_syntax_context: deserialized root");
1323 // The root is special
5099ac24 1324 return SyntaxContext::root();
3dfed10e
XL
1325 }
1326
1327 let outer_ctxts = &context.remapped_ctxts;
1328
1329 // Ensure that the lock() temporary is dropped early
1330 {
1331 if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
5099ac24 1332 return ctxt;
3dfed10e
XL
1333 }
1334 }
1335
1336 // Allocate and store SyntaxContext id *before* calling the decoder function,
1337 // as the SyntaxContextData may reference itself.
1338 let new_ctxt = HygieneData::with(|hygiene_data| {
1339 let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
1340 // Push a dummy SyntaxContextData to ensure that nobody else can get the
1341 // same ID as us. This will be overwritten after call `decode_Data`
1342 hygiene_data.syntax_context_data.push(SyntaxContextData {
1343 outer_expn: ExpnId::root(),
1344 outer_transparency: Transparency::Transparent,
1345 parent: SyntaxContext::root(),
1346 opaque: SyntaxContext::root(),
1347 opaque_and_semitransparent: SyntaxContext::root(),
5869c6ff 1348 dollar_crate_name: kw::Empty,
3dfed10e
XL
1349 });
1350 let mut ctxts = outer_ctxts.lock();
1351 let new_len = raw_id as usize + 1;
1352 if ctxts.len() < new_len {
1353 ctxts.resize(new_len, None);
1354 }
1355 ctxts[raw_id as usize] = Some(new_ctxt);
1356 drop(ctxts);
1357 new_ctxt
1358 });
1359
1360 // Don't try to decode data while holding the lock, since we need to
1361 // be able to recursively decode a SyntaxContext
5099ac24 1362 let mut ctxt_data = decode_data(d, raw_id);
3dfed10e
XL
1363 // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1364 // We don't care what the encoding crate set this to - we want to resolve it
1365 // from the perspective of the current compilation session
1366 ctxt_data.dollar_crate_name = kw::DollarCrate;
1367
1368 // Overwrite the dummy data with our decoded SyntaxContextData
1369 HygieneData::with(|hygiene_data| {
1370 let dummy = std::mem::replace(
1371 &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize],
1372 ctxt_data,
1373 );
1374 // Make sure nothing weird happening while `decode_data` was running
5869c6ff 1375 assert_eq!(dummy.dollar_crate_name, kw::Empty);
3dfed10e
XL
1376 });
1377
5099ac24 1378 new_ctxt
3dfed10e
XL
1379}
1380
923072b8 1381fn for_all_ctxts_in<F: FnMut(u32, SyntaxContext, &SyntaxContextData)>(
3dfed10e
XL
1382 ctxts: impl Iterator<Item = SyntaxContext>,
1383 mut f: F,
923072b8 1384) {
3dfed10e
XL
1385 let all_data: Vec<_> = HygieneData::with(|data| {
1386 ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect()
1387 });
1388 for (ctxt, data) in all_data.into_iter() {
923072b8 1389 f(ctxt.0, ctxt, &data);
3dfed10e 1390 }
3dfed10e
XL
1391}
1392
923072b8 1393fn for_all_expns_in(
3dfed10e 1394 expns: impl Iterator<Item = ExpnId>,
923072b8
FG
1395 mut f: impl FnMut(ExpnId, &ExpnData, ExpnHash),
1396) {
3dfed10e 1397 let all_data: Vec<_> = HygieneData::with(|data| {
c295e0f8 1398 expns.map(|expn| (expn, data.expn_data(expn).clone(), data.expn_hash(expn))).collect()
3dfed10e 1399 });
136023e0 1400 for (expn, data, hash) in all_data.into_iter() {
923072b8 1401 f(expn, &data, hash);
3dfed10e 1402 }
3dfed10e
XL
1403}
1404
136023e0 1405impl<E: Encoder> Encodable<E> for LocalExpnId {
923072b8
FG
1406 fn encode(&self, e: &mut E) {
1407 self.to_expn_id().encode(e);
136023e0
XL
1408 }
1409}
1410
3dfed10e 1411impl<E: Encoder> Encodable<E> for ExpnId {
923072b8 1412 default fn encode(&self, _: &mut E) {
3dfed10e
XL
1413 panic!("cannot encode `ExpnId` with `{}`", std::any::type_name::<E>());
1414 }
1415}
1416
136023e0 1417impl<D: Decoder> Decodable<D> for LocalExpnId {
5099ac24
FG
1418 fn decode(d: &mut D) -> Self {
1419 ExpnId::expect_local(ExpnId::decode(d))
136023e0
XL
1420 }
1421}
1422
3dfed10e 1423impl<D: Decoder> Decodable<D> for ExpnId {
5099ac24 1424 default fn decode(_: &mut D) -> Self {
3dfed10e
XL
1425 panic!("cannot decode `ExpnId` with `{}`", std::any::type_name::<D>());
1426 }
1427}
1428
3dfed10e
XL
1429pub fn raw_encode_syntax_context<E: Encoder>(
1430 ctxt: SyntaxContext,
1431 context: &HygieneEncodeContext,
1432 e: &mut E,
923072b8 1433) {
3dfed10e
XL
1434 if !context.serialized_ctxts.lock().contains(&ctxt) {
1435 context.latest_ctxts.lock().insert(ctxt);
1436 }
923072b8 1437 ctxt.0.encode(e);
3dfed10e
XL
1438}
1439
3dfed10e 1440impl<E: Encoder> Encodable<E> for SyntaxContext {
923072b8 1441 default fn encode(&self, _: &mut E) {
3dfed10e 1442 panic!("cannot encode `SyntaxContext` with `{}`", std::any::type_name::<E>());
cc61c64b
XL
1443 }
1444}
1445
3dfed10e 1446impl<D: Decoder> Decodable<D> for SyntaxContext {
5099ac24 1447 default fn decode(_: &mut D) -> Self {
3dfed10e 1448 panic!("cannot decode `SyntaxContext` with `{}`", std::any::type_name::<D>());
cc61c64b
XL
1449 }
1450}
5869c6ff
XL
1451
1452/// Updates the `disambiguator` field of the corresponding `ExpnData`
1453/// such that the `Fingerprint` of the `ExpnData` does not collide with
1454/// any other `ExpnIds`.
1455///
1456/// This method is called only when an `ExpnData` is first associated
1457/// with an `ExpnId` (when the `ExpnId` is initially constructed, or via
1458/// `set_expn_data`). It is *not* called for foreign `ExpnId`s deserialized
136023e0 1459/// from another crate's metadata - since `ExpnHash` includes the stable crate id,
5869c6ff 1460/// collisions are only possible between `ExpnId`s within the same crate.
136023e0 1461fn update_disambiguator(expn_data: &mut ExpnData, mut ctx: impl HashStableContext) -> ExpnHash {
5869c6ff
XL
1462 // This disambiguator should not have been set yet.
1463 assert_eq!(
1464 expn_data.disambiguator, 0,
1465 "Already set disambiguator for ExpnData: {:?}",
1466 expn_data
1467 );
5099ac24 1468 assert_default_hashing_controls(&ctx, "ExpnData (disambiguator)");
136023e0 1469 let mut expn_hash = expn_data.hash_expn(&mut ctx);
5869c6ff 1470
136023e0 1471 let disambiguator = HygieneData::with(|data| {
5869c6ff
XL
1472 // If this is the first ExpnData with a given hash, then keep our
1473 // disambiguator at 0 (the default u32 value)
136023e0
XL
1474 let disambig = data.expn_data_disambiguators.entry(expn_hash).or_default();
1475 let disambiguator = *disambig;
5869c6ff 1476 *disambig += 1;
136023e0 1477 disambiguator
5869c6ff
XL
1478 });
1479
136023e0
XL
1480 if disambiguator != 0 {
1481 debug!("Set disambiguator for expn_data={:?} expn_hash={:?}", expn_data, expn_hash);
1482
1483 expn_data.disambiguator = disambiguator;
1484 expn_hash = expn_data.hash_expn(&mut ctx);
5869c6ff
XL
1485
1486 // Verify that the new disambiguator makes the hash unique
1487 #[cfg(debug_assertions)]
136023e0
XL
1488 HygieneData::with(|data| {
1489 assert_eq!(
1490 data.expn_data_disambiguators.get(&expn_hash),
1491 None,
1492 "Hash collision after disambiguator update!",
1493 );
1494 });
1495 }
1496
1497 ExpnHash::new(ctx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), expn_hash)
1498}
1499
1500impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1501 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1502 const TAG_EXPANSION: u8 = 0;
1503 const TAG_NO_EXPANSION: u8 = 1;
1504
1505 if *self == SyntaxContext::root() {
1506 TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1507 } else {
1508 TAG_EXPANSION.hash_stable(ctx, hasher);
1509 let (expn_id, transparency) = self.outer_mark();
1510 expn_id.hash_stable(ctx, hasher);
1511 transparency.hash_stable(ctx, hasher);
1512 }
1513 }
1514}
1515
1516impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1517 fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
5099ac24 1518 assert_default_hashing_controls(ctx, "ExpnId");
136023e0
XL
1519 let hash = if *self == ExpnId::root() {
1520 // Avoid fetching TLS storage for a trivial often-used value.
1521 Fingerprint::ZERO
1522 } else {
1523 self.expn_hash().0
5869c6ff 1524 };
136023e0
XL
1525
1526 hash.hash_stable(ctx, hasher);
5869c6ff
XL
1527 }
1528}