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