rustc_span/
hygiene.rs

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