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 { pub fn f() {} } // `f`'s `SyntaxContext` is empty.
772    /// m!(f);
773    /// macro m($f:ident) {
774    ///     mod bar {
775    ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
776    ///         pub fn $f() {} // `$f`'s `SyntaxContext` is empty.
777    ///     }
778    ///     foo::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
779    ///     //^ Since `mod foo` is outside this expansion, `adjust` removes the mark from `f`,
780    ///     //| and it resolves to `::foo::f`.
781    ///     bar::f(); // `f`'s `SyntaxContext` has a single `ExpnId` from `m`
782    ///     //^ Since `mod bar` not outside this expansion, `adjust` does not change `f`,
783    ///     //| and it resolves to `::bar::f`.
784    ///     bar::$f(); // `f`'s `SyntaxContext` is empty.
785    ///     //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`,
786    ///     //| and it resolves to `::bar::$f`.
787    /// }
788    /// ```
789    /// This returns the expansion whose definition scope we use to privacy check the resolution,
790    /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope).
791    #[inline]
792    pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
793        HygieneData::with(|data| data.adjust(self, expn_id))
794    }
795
796    /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0.
797    #[inline]
798    pub(crate) fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
799        HygieneData::with(|data| {
800            *self = data.normalize_to_macros_2_0(*self);
801            data.adjust(self, expn_id)
802        })
803    }
804
805    /// Adjust this context for resolution in a scope created by the given expansion
806    /// via a glob import with the given `SyntaxContext`.
807    /// For example:
808    ///
809    /// ```compile_fail,E0425
810    /// #![feature(decl_macro)]
811    /// m!(f);
812    /// macro m($i:ident) {
813    ///     mod foo {
814    ///         pub fn f() {} // `f`'s `SyntaxContext` has a single `ExpnId` from `m`.
815    ///         pub fn $i() {} // `$i`'s `SyntaxContext` is empty.
816    ///     }
817    ///     n!(f);
818    ///     macro n($j:ident) {
819    ///         use foo::*;
820    ///         f(); // `f`'s `SyntaxContext` has a mark from `m` and a mark from `n`
821    ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::f`.
822    ///         $i(); // `$i`'s `SyntaxContext` has a mark from `n`
823    ///         //^ `glob_adjust` removes the mark from `n`, so this resolves to `foo::$i`.
824    ///         $j(); // `$j`'s `SyntaxContext` has a mark from `m`
825    ///         //^ This cannot be glob-adjusted, so this is a resolution error.
826    ///     }
827    /// }
828    /// ```
829    /// This returns `None` if the context cannot be glob-adjusted.
830    /// Otherwise, it returns the scope to use when privacy checking (see `adjust` for details).
831    pub(crate) fn glob_adjust(
832        &mut self,
833        expn_id: ExpnId,
834        glob_span: Span,
835    ) -> Option<Option<ExpnId>> {
836        HygieneData::with(|data| {
837            let mut scope = None;
838            let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
839            while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
840                scope = Some(data.remove_mark(&mut glob_ctxt).0);
841                if data.remove_mark(self).0 != scope.unwrap() {
842                    return None;
843                }
844            }
845            if data.adjust(self, expn_id).is_some() {
846                return None;
847            }
848            Some(scope)
849        })
850    }
851
852    /// Undo `glob_adjust` if possible:
853    ///
854    /// ```ignore (illustrative)
855    /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) {
856    ///     assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope));
857    /// }
858    /// ```
859    pub(crate) fn reverse_glob_adjust(
860        &mut self,
861        expn_id: ExpnId,
862        glob_span: Span,
863    ) -> Option<Option<ExpnId>> {
864        HygieneData::with(|data| {
865            if data.adjust(self, expn_id).is_some() {
866                return None;
867            }
868
869            let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt());
870            let mut marks = Vec::new();
871            while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) {
872                marks.push(data.remove_mark(&mut glob_ctxt));
873            }
874
875            let scope = marks.last().map(|mark| mark.0);
876            while let Some((expn_id, transparency)) = marks.pop() {
877                *self = data.apply_mark(*self, expn_id, transparency);
878            }
879            Some(scope)
880        })
881    }
882
883    pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool {
884        HygieneData::with(|data| {
885            let mut self_normalized = data.normalize_to_macros_2_0(self);
886            data.adjust(&mut self_normalized, expn_id);
887            self_normalized == data.normalize_to_macros_2_0(other)
888        })
889    }
890
891    #[inline]
892    pub fn normalize_to_macros_2_0(self) -> SyntaxContext {
893        HygieneData::with(|data| data.normalize_to_macros_2_0(self))
894    }
895
896    #[inline]
897    pub fn normalize_to_macro_rules(self) -> SyntaxContext {
898        HygieneData::with(|data| data.normalize_to_macro_rules(self))
899    }
900
901    #[inline]
902    pub fn outer_expn(self) -> ExpnId {
903        HygieneData::with(|data| data.outer_expn(self))
904    }
905
906    /// `ctxt.outer_expn_data()` is equivalent to but faster than
907    /// `ctxt.outer_expn().expn_data()`.
908    #[inline]
909    pub fn outer_expn_data(self) -> ExpnData {
910        HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone())
911    }
912
913    #[inline]
914    fn outer_mark(self) -> (ExpnId, Transparency) {
915        HygieneData::with(|data| data.outer_mark(self))
916    }
917
918    #[inline]
919    pub(crate) fn dollar_crate_name(self) -> Symbol {
920        HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
921    }
922
923    #[inline]
924    pub fn edition(self) -> Edition {
925        HygieneData::with(|data| data.expn_data(data.outer_expn(self)).edition)
926    }
927
928    /// Returns whether this context originates in a foreign crate's external macro.
929    ///
930    /// This is used to test whether a lint should not even begin to figure out whether it should
931    /// be reported on the current node.
932    pub fn in_external_macro(self, sm: &SourceMap) -> bool {
933        let expn_data = self.outer_expn_data();
934        match expn_data.kind {
935            ExpnKind::Root
936            | ExpnKind::Desugaring(
937                DesugaringKind::ForLoop
938                | DesugaringKind::WhileLoop
939                | DesugaringKind::OpaqueTy
940                | DesugaringKind::Async
941                | DesugaringKind::Await,
942            ) => false,
943            ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
944            ExpnKind::Macro(MacroKind::Bang, _) => {
945                // Dummy span for the `def_site` means it's an external macro.
946                expn_data.def_site.is_dummy() || sm.is_imported(expn_data.def_site)
947            }
948            ExpnKind::Macro { .. } => true, // definitely a plugin
949        }
950    }
951}
952
953impl fmt::Debug for SyntaxContext {
954    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
955        write!(f, "#{}", self.0)
956    }
957}
958
959impl Span {
960    /// Reuses the span but adds information like the kind of the desugaring and features that are
961    /// allowed inside this span.
962    pub fn mark_with_reason(
963        self,
964        allow_internal_unstable: Option<Arc<[Symbol]>>,
965        reason: DesugaringKind,
966        edition: Edition,
967        ctx: impl HashStableContext,
968    ) -> Span {
969        let expn_data = ExpnData {
970            allow_internal_unstable,
971            ..ExpnData::default(ExpnKind::Desugaring(reason), self, edition, None, None)
972        };
973        let expn_id = LocalExpnId::fresh(expn_data, ctx);
974        self.apply_mark(expn_id.to_expn_id(), Transparency::Transparent)
975    }
976}
977
978/// A subset of properties from both macro definition and macro call available through global data.
979/// Avoid using this if you have access to the original definition or call structures.
980#[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)]
981pub struct ExpnData {
982    // --- The part unique to each expansion.
983    /// The kind of this expansion - macro or compiler desugaring.
984    pub kind: ExpnKind,
985    /// The expansion that produced this expansion.
986    pub parent: ExpnId,
987    /// The location of the actual macro invocation or syntax sugar , e.g.
988    /// `let x = foo!();` or `if let Some(y) = x {}`
989    ///
990    /// This may recursively refer to other macro invocations, e.g., if
991    /// `foo!()` invoked `bar!()` internally, and there was an
992    /// expression inside `bar!`; the call_site of the expression in
993    /// the expansion would point to the `bar!` invocation; that
994    /// call_site span would have its own ExpnData, with the call_site
995    /// pointing to the `foo!` invocation.
996    pub call_site: Span,
997    /// Used to force two `ExpnData`s to have different `Fingerprint`s.
998    /// Due to macro expansion, it's possible to end up with two `ExpnId`s
999    /// that have identical `ExpnData`s. This violates the contract of `HashStable`
1000    /// - the two `ExpnId`s are not equal, but their `Fingerprint`s are equal
1001    /// (since the numerical `ExpnId` value is not considered by the `HashStable`
1002    /// implementation).
1003    ///
1004    /// The `disambiguator` field is set by `update_disambiguator` when two distinct
1005    /// `ExpnId`s would end up with the same `Fingerprint`. Since `ExpnData` includes
1006    /// a `krate` field, this value only needs to be unique within a single crate.
1007    disambiguator: u32,
1008
1009    // --- The part specific to the macro/desugaring definition.
1010    // --- It may be reasonable to share this part between expansions with the same definition,
1011    // --- but such sharing is known to bring some minor inconveniences without also bringing
1012    // --- noticeable perf improvements (PR #62898).
1013    /// The span of the macro definition (possibly dummy).
1014    /// This span serves only informational purpose and is not used for resolution.
1015    pub def_site: Span,
1016    /// List of `#[unstable]`/feature-gated features that the macro is allowed to use
1017    /// internally without forcing the whole crate to opt-in
1018    /// to them.
1019    pub allow_internal_unstable: Option<Arc<[Symbol]>>,
1020    /// Edition of the crate in which the macro is defined.
1021    pub edition: Edition,
1022    /// The `DefId` of the macro being invoked,
1023    /// if this `ExpnData` corresponds to a macro invocation
1024    pub macro_def_id: Option<DefId>,
1025    /// The normal module (`mod`) in which the expanded macro was defined.
1026    pub parent_module: Option<DefId>,
1027    /// Suppresses the `unsafe_code` lint for code produced by this macro.
1028    pub(crate) allow_internal_unsafe: bool,
1029    /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) for this macro.
1030    pub local_inner_macros: bool,
1031    /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other
1032    /// words, was the macro definition annotated with `#[collapse_debuginfo]`)?
1033    pub(crate) collapse_debuginfo: bool,
1034    /// When true, we do not display the note telling people to use the `-Zmacro-backtrace` flag.
1035    pub hide_backtrace: bool,
1036}
1037
1038impl !PartialEq for ExpnData {}
1039impl !Hash for ExpnData {}
1040
1041impl ExpnData {
1042    pub fn new(
1043        kind: ExpnKind,
1044        parent: ExpnId,
1045        call_site: Span,
1046        def_site: Span,
1047        allow_internal_unstable: Option<Arc<[Symbol]>>,
1048        edition: Edition,
1049        macro_def_id: Option<DefId>,
1050        parent_module: Option<DefId>,
1051        allow_internal_unsafe: bool,
1052        local_inner_macros: bool,
1053        collapse_debuginfo: bool,
1054        hide_backtrace: bool,
1055    ) -> ExpnData {
1056        ExpnData {
1057            kind,
1058            parent,
1059            call_site,
1060            def_site,
1061            allow_internal_unstable,
1062            edition,
1063            macro_def_id,
1064            parent_module,
1065            disambiguator: 0,
1066            allow_internal_unsafe,
1067            local_inner_macros,
1068            collapse_debuginfo,
1069            hide_backtrace,
1070        }
1071    }
1072
1073    /// Constructs expansion data with default properties.
1074    pub fn default(
1075        kind: ExpnKind,
1076        call_site: Span,
1077        edition: Edition,
1078        macro_def_id: Option<DefId>,
1079        parent_module: Option<DefId>,
1080    ) -> ExpnData {
1081        ExpnData {
1082            kind,
1083            parent: ExpnId::root(),
1084            call_site,
1085            def_site: DUMMY_SP,
1086            allow_internal_unstable: None,
1087            edition,
1088            macro_def_id,
1089            parent_module,
1090            disambiguator: 0,
1091            allow_internal_unsafe: false,
1092            local_inner_macros: false,
1093            collapse_debuginfo: false,
1094            hide_backtrace: false,
1095        }
1096    }
1097
1098    pub fn allow_unstable(
1099        kind: ExpnKind,
1100        call_site: Span,
1101        edition: Edition,
1102        allow_internal_unstable: Arc<[Symbol]>,
1103        macro_def_id: Option<DefId>,
1104        parent_module: Option<DefId>,
1105    ) -> ExpnData {
1106        ExpnData {
1107            allow_internal_unstable: Some(allow_internal_unstable),
1108            ..ExpnData::default(kind, call_site, edition, macro_def_id, parent_module)
1109        }
1110    }
1111
1112    #[inline]
1113    pub fn is_root(&self) -> bool {
1114        matches!(self.kind, ExpnKind::Root)
1115    }
1116
1117    #[inline]
1118    fn hash_expn(&self, ctx: &mut impl HashStableContext) -> Hash64 {
1119        let mut hasher = StableHasher::new();
1120        self.hash_stable(ctx, &mut hasher);
1121        hasher.finish()
1122    }
1123}
1124
1125/// Expansion kind.
1126#[derive(Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
1127pub enum ExpnKind {
1128    /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind.
1129    Root,
1130    /// Expansion produced by a macro.
1131    Macro(MacroKind, Symbol),
1132    /// Transform done by the compiler on the AST.
1133    AstPass(AstPass),
1134    /// Desugaring done by the compiler during AST lowering.
1135    Desugaring(DesugaringKind),
1136}
1137
1138impl ExpnKind {
1139    pub fn descr(&self) -> String {
1140        match *self {
1141            ExpnKind::Root => kw::PathRoot.to_string(),
1142            ExpnKind::Macro(macro_kind, name) => match macro_kind {
1143                MacroKind::Bang => format!("{name}!"),
1144                MacroKind::Attr => format!("#[{name}]"),
1145                MacroKind::Derive => format!("#[derive({name})]"),
1146            },
1147            ExpnKind::AstPass(kind) => kind.descr().to_string(),
1148            ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()),
1149        }
1150    }
1151}
1152
1153/// The kind of macro invocation or definition.
1154#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable, Hash, Debug)]
1155#[derive(HashStable_Generic)]
1156pub enum MacroKind {
1157    /// A bang macro `foo!()`.
1158    Bang,
1159    /// An attribute macro `#[foo]`.
1160    Attr,
1161    /// A derive macro `#[derive(Foo)]`
1162    Derive,
1163}
1164
1165impl MacroKind {
1166    pub fn descr(self) -> &'static str {
1167        match self {
1168            MacroKind::Bang => "macro",
1169            MacroKind::Attr => "attribute macro",
1170            MacroKind::Derive => "derive macro",
1171        }
1172    }
1173
1174    pub fn descr_expected(self) -> &'static str {
1175        match self {
1176            MacroKind::Attr => "attribute",
1177            _ => self.descr(),
1178        }
1179    }
1180
1181    pub fn article(self) -> &'static str {
1182        match self {
1183            MacroKind::Attr => "an",
1184            _ => "a",
1185        }
1186    }
1187}
1188
1189/// The kind of AST transform.
1190#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
1191pub enum AstPass {
1192    StdImports,
1193    TestHarness,
1194    ProcMacroHarness,
1195}
1196
1197impl AstPass {
1198    pub fn descr(self) -> &'static str {
1199        match self {
1200            AstPass::StdImports => "standard library imports",
1201            AstPass::TestHarness => "test harness",
1202            AstPass::ProcMacroHarness => "proc macro harness",
1203        }
1204    }
1205}
1206
1207/// The kind of compiler desugaring.
1208#[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable, HashStable_Generic)]
1209pub enum DesugaringKind {
1210    QuestionMark,
1211    TryBlock,
1212    YeetExpr,
1213    /// Desugaring of an `impl Trait` in return type position
1214    /// to an `type Foo = impl Trait;` and replacing the
1215    /// `impl Trait` with `Foo`.
1216    OpaqueTy,
1217    Async,
1218    Await,
1219    ForLoop,
1220    WhileLoop,
1221    /// `async Fn()` bound modifier
1222    BoundModifier,
1223    /// Calls to contract checks (`#[requires]` to precond, `#[ensures]` to postcond)
1224    Contract,
1225    /// A pattern type range start/end
1226    PatTyRange,
1227    /// A format literal.
1228    FormatLiteral {
1229        /// Was this format literal written in the source?
1230        /// - `format!("boo")` => Yes,
1231        /// - `format!(concat!("b", "o", "o"))` => No,
1232        /// - `format!(include_str!("boo.txt"))` => No,
1233        ///
1234        /// If it wasn't written in the source then we have to be careful with suggestions about
1235        /// rewriting it.
1236        source: bool,
1237    },
1238}
1239
1240impl DesugaringKind {
1241    /// The description wording should combine well with "desugaring of {}".
1242    pub fn descr(self) -> &'static str {
1243        match self {
1244            DesugaringKind::Async => "`async` block or function",
1245            DesugaringKind::Await => "`await` expression",
1246            DesugaringKind::QuestionMark => "operator `?`",
1247            DesugaringKind::TryBlock => "`try` block",
1248            DesugaringKind::YeetExpr => "`do yeet` expression",
1249            DesugaringKind::OpaqueTy => "`impl Trait`",
1250            DesugaringKind::ForLoop => "`for` loop",
1251            DesugaringKind::WhileLoop => "`while` loop",
1252            DesugaringKind::BoundModifier => "trait bound modifier",
1253            DesugaringKind::Contract => "contract check",
1254            DesugaringKind::PatTyRange => "pattern type",
1255            DesugaringKind::FormatLiteral { source: true } => "format string literal",
1256            DesugaringKind::FormatLiteral { source: false } => {
1257                "expression that expanded into a format string literal"
1258            }
1259        }
1260    }
1261
1262    /// For use with `rustc_unimplemented` to support conditions
1263    /// like `from_desugaring = "QuestionMark"`
1264    pub fn matches(&self, value: &str) -> bool {
1265        match self {
1266            DesugaringKind::Async => value == "Async",
1267            DesugaringKind::Await => value == "Await",
1268            DesugaringKind::QuestionMark => value == "QuestionMark",
1269            DesugaringKind::TryBlock => value == "TryBlock",
1270            DesugaringKind::YeetExpr => value == "YeetExpr",
1271            DesugaringKind::OpaqueTy => value == "OpaqueTy",
1272            DesugaringKind::ForLoop => value == "ForLoop",
1273            DesugaringKind::WhileLoop => value == "WhileLoop",
1274            DesugaringKind::BoundModifier => value == "BoundModifier",
1275            DesugaringKind::Contract => value == "Contract",
1276            DesugaringKind::PatTyRange => value == "PatTyRange",
1277            DesugaringKind::FormatLiteral { .. } => value == "FormatLiteral",
1278        }
1279    }
1280}
1281
1282#[derive(Default)]
1283pub struct HygieneEncodeContext {
1284    /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata.
1285    /// This is `None` after we finish encoding `SyntaxContexts`, to ensure
1286    /// that we don't accidentally try to encode any more `SyntaxContexts`
1287    serialized_ctxts: Lock<FxHashSet<SyntaxContext>>,
1288    /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`)
1289    /// in the most recent 'round' of serializing. Serializing `SyntaxContextData`
1290    /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop
1291    /// until we reach a fixed point.
1292    latest_ctxts: Lock<FxHashSet<SyntaxContext>>,
1293
1294    serialized_expns: Lock<FxHashSet<ExpnId>>,
1295
1296    latest_expns: Lock<FxHashSet<ExpnId>>,
1297}
1298
1299impl HygieneEncodeContext {
1300    /// Record the fact that we need to serialize the corresponding `ExpnData`.
1301    pub fn schedule_expn_data_for_encoding(&self, expn: ExpnId) {
1302        if !self.serialized_expns.lock().contains(&expn) {
1303            self.latest_expns.lock().insert(expn);
1304        }
1305    }
1306
1307    pub fn encode<T>(
1308        &self,
1309        encoder: &mut T,
1310        mut encode_ctxt: impl FnMut(&mut T, u32, &SyntaxContextKey),
1311        mut encode_expn: impl FnMut(&mut T, ExpnId, &ExpnData, ExpnHash),
1312    ) {
1313        // When we serialize a `SyntaxContextData`, we may end up serializing
1314        // a `SyntaxContext` that we haven't seen before
1315        while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() {
1316            debug!(
1317                "encode_hygiene: Serializing a round of {:?} SyntaxContextData: {:?}",
1318                self.latest_ctxts.lock().len(),
1319                self.latest_ctxts
1320            );
1321
1322            // Consume the current round of syntax contexts.
1323            // Drop the lock() temporary early.
1324            // It's fine to iterate over a HashMap, because the serialization of the table
1325            // that we insert data into doesn't depend on insertion order.
1326            #[allow(rustc::potential_query_instability)]
1327            let latest_ctxts = { mem::take(&mut *self.latest_ctxts.lock()) }.into_iter();
1328            let all_ctxt_data: Vec<_> = HygieneData::with(|data| {
1329                latest_ctxts
1330                    .map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].key()))
1331                    .collect()
1332            });
1333            for (ctxt, ctxt_key) in all_ctxt_data {
1334                if self.serialized_ctxts.lock().insert(ctxt) {
1335                    encode_ctxt(encoder, ctxt.0, &ctxt_key);
1336                }
1337            }
1338
1339            // Same as above, but for expansions instead of syntax contexts.
1340            #[allow(rustc::potential_query_instability)]
1341            let latest_expns = { mem::take(&mut *self.latest_expns.lock()) }.into_iter();
1342            let all_expn_data: Vec<_> = HygieneData::with(|data| {
1343                latest_expns
1344                    .map(|expn| (expn, data.expn_data(expn).clone(), data.expn_hash(expn)))
1345                    .collect()
1346            });
1347            for (expn, expn_data, expn_hash) in all_expn_data {
1348                if self.serialized_expns.lock().insert(expn) {
1349                    encode_expn(encoder, expn, &expn_data, expn_hash);
1350                }
1351            }
1352        }
1353        debug!("encode_hygiene: Done serializing SyntaxContextData");
1354    }
1355}
1356
1357/// Additional information used to assist in decoding hygiene data
1358#[derive(Default)]
1359pub struct HygieneDecodeContext {
1360    // A cache mapping raw serialized per-crate syntax context ids to corresponding decoded
1361    // `SyntaxContext`s in the current global `HygieneData`.
1362    remapped_ctxts: Lock<IndexVec<u32, Option<SyntaxContext>>>,
1363}
1364
1365/// Register an expansion which has been decoded from the on-disk-cache for the local crate.
1366pub fn register_local_expn_id(data: ExpnData, hash: ExpnHash) -> ExpnId {
1367    HygieneData::with(|hygiene_data| {
1368        let expn_id = hygiene_data.local_expn_data.next_index();
1369        hygiene_data.local_expn_data.push(Some(data));
1370        let _eid = hygiene_data.local_expn_hashes.push(hash);
1371        debug_assert_eq!(expn_id, _eid);
1372
1373        let expn_id = expn_id.to_expn_id();
1374
1375        let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id);
1376        debug_assert!(_old_id.is_none());
1377        expn_id
1378    })
1379}
1380
1381/// Register an expansion which has been decoded from the metadata of a foreign crate.
1382pub fn register_expn_id(
1383    krate: CrateNum,
1384    local_id: ExpnIndex,
1385    data: ExpnData,
1386    hash: ExpnHash,
1387) -> ExpnId {
1388    debug_assert!(data.parent == ExpnId::root() || krate == data.parent.krate);
1389    let expn_id = ExpnId { krate, local_id };
1390    HygieneData::with(|hygiene_data| {
1391        let _old_data = hygiene_data.foreign_expn_data.insert(expn_id, data);
1392        let _old_hash = hygiene_data.foreign_expn_hashes.insert(expn_id, hash);
1393        debug_assert!(_old_hash.is_none() || _old_hash == Some(hash));
1394        let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id);
1395        debug_assert!(_old_id.is_none() || _old_id == Some(expn_id));
1396    });
1397    expn_id
1398}
1399
1400/// Decode an expansion from the metadata of a foreign crate.
1401pub fn decode_expn_id(
1402    krate: CrateNum,
1403    index: u32,
1404    decode_data: impl FnOnce(ExpnId) -> (ExpnData, ExpnHash),
1405) -> ExpnId {
1406    if index == 0 {
1407        trace!("decode_expn_id: deserialized root");
1408        return ExpnId::root();
1409    }
1410
1411    let index = ExpnIndex::from_u32(index);
1412
1413    // This function is used to decode metadata, so it cannot decode information about LOCAL_CRATE.
1414    debug_assert_ne!(krate, LOCAL_CRATE);
1415    let expn_id = ExpnId { krate, local_id: index };
1416
1417    // Fast path if the expansion has already been decoded.
1418    if HygieneData::with(|hygiene_data| hygiene_data.foreign_expn_data.contains_key(&expn_id)) {
1419        return expn_id;
1420    }
1421
1422    // Don't decode the data inside `HygieneData::with`, since we need to recursively decode
1423    // other ExpnIds
1424    let (expn_data, hash) = decode_data(expn_id);
1425
1426    register_expn_id(krate, index, expn_data, hash)
1427}
1428
1429// Decodes `SyntaxContext`, using the provided `HygieneDecodeContext`
1430// to track which `SyntaxContext`s we have already decoded.
1431// The provided closure will be invoked to deserialize a `SyntaxContextData`
1432// if we haven't already seen the id of the `SyntaxContext` we are deserializing.
1433pub fn decode_syntax_context<D: Decoder>(
1434    d: &mut D,
1435    context: &HygieneDecodeContext,
1436    decode_data: impl FnOnce(&mut D, u32) -> SyntaxContextKey,
1437) -> SyntaxContext {
1438    let raw_id: u32 = Decodable::decode(d);
1439    if raw_id == 0 {
1440        trace!("decode_syntax_context: deserialized root");
1441        // The root is special
1442        return SyntaxContext::root();
1443    }
1444
1445    // Look into the cache first.
1446    // Reminder: `HygieneDecodeContext` is per-crate, so there are no collisions between
1447    // raw ids from different crate metadatas.
1448    if let Some(Some(ctxt)) = context.remapped_ctxts.lock().get(raw_id) {
1449        return *ctxt;
1450    }
1451
1452    // Don't try to decode data while holding the lock, since we need to
1453    // be able to recursively decode a SyntaxContext
1454    let (parent, expn_id, transparency) = decode_data(d, raw_id);
1455    let ctxt =
1456        HygieneData::with(|hygiene_data| hygiene_data.alloc_ctxt(parent, expn_id, transparency));
1457
1458    context.remapped_ctxts.lock().insert(raw_id, ctxt);
1459
1460    ctxt
1461}
1462
1463impl<E: SpanEncoder> Encodable<E> for LocalExpnId {
1464    fn encode(&self, e: &mut E) {
1465        self.to_expn_id().encode(e);
1466    }
1467}
1468
1469impl<D: SpanDecoder> Decodable<D> for LocalExpnId {
1470    fn decode(d: &mut D) -> Self {
1471        ExpnId::expect_local(ExpnId::decode(d))
1472    }
1473}
1474
1475pub fn raw_encode_syntax_context(
1476    ctxt: SyntaxContext,
1477    context: &HygieneEncodeContext,
1478    e: &mut impl Encoder,
1479) {
1480    if !context.serialized_ctxts.lock().contains(&ctxt) {
1481        context.latest_ctxts.lock().insert(ctxt);
1482    }
1483    ctxt.0.encode(e);
1484}
1485
1486/// Updates the `disambiguator` field of the corresponding `ExpnData`
1487/// such that the `Fingerprint` of the `ExpnData` does not collide with
1488/// any other `ExpnIds`.
1489///
1490/// This method is called only when an `ExpnData` is first associated
1491/// with an `ExpnId` (when the `ExpnId` is initially constructed, or via
1492/// `set_expn_data`). It is *not* called for foreign `ExpnId`s deserialized
1493/// from another crate's metadata - since `ExpnHash` includes the stable crate id,
1494/// collisions are only possible between `ExpnId`s within the same crate.
1495fn update_disambiguator(expn_data: &mut ExpnData, mut ctx: impl HashStableContext) -> ExpnHash {
1496    // This disambiguator should not have been set yet.
1497    assert_eq!(expn_data.disambiguator, 0, "Already set disambiguator for ExpnData: {expn_data:?}");
1498    assert_default_hashing_controls(&ctx, "ExpnData (disambiguator)");
1499    let mut expn_hash = expn_data.hash_expn(&mut ctx);
1500
1501    let disambiguator = HygieneData::with(|data| {
1502        // If this is the first ExpnData with a given hash, then keep our
1503        // disambiguator at 0 (the default u32 value)
1504        let disambig = data.expn_data_disambiguators.entry(expn_hash).or_default();
1505        let disambiguator = *disambig;
1506        *disambig += 1;
1507        disambiguator
1508    });
1509
1510    if disambiguator != 0 {
1511        debug!("Set disambiguator for expn_data={:?} expn_hash={:?}", expn_data, expn_hash);
1512
1513        expn_data.disambiguator = disambiguator;
1514        expn_hash = expn_data.hash_expn(&mut ctx);
1515
1516        // Verify that the new disambiguator makes the hash unique
1517        #[cfg(debug_assertions)]
1518        HygieneData::with(|data| {
1519            assert_eq!(
1520                data.expn_data_disambiguators.get(&expn_hash),
1521                None,
1522                "Hash collision after disambiguator update!",
1523            );
1524        });
1525    }
1526
1527    ExpnHash::new(ctx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), expn_hash)
1528}
1529
1530impl<CTX: HashStableContext> HashStable<CTX> for SyntaxContext {
1531    fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1532        const TAG_EXPANSION: u8 = 0;
1533        const TAG_NO_EXPANSION: u8 = 1;
1534
1535        if self.is_root() {
1536            TAG_NO_EXPANSION.hash_stable(ctx, hasher);
1537        } else {
1538            TAG_EXPANSION.hash_stable(ctx, hasher);
1539            let (expn_id, transparency) = self.outer_mark();
1540            expn_id.hash_stable(ctx, hasher);
1541            transparency.hash_stable(ctx, hasher);
1542        }
1543    }
1544}
1545
1546impl<CTX: HashStableContext> HashStable<CTX> for ExpnId {
1547    fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
1548        assert_default_hashing_controls(ctx, "ExpnId");
1549        let hash = if *self == ExpnId::root() {
1550            // Avoid fetching TLS storage for a trivial often-used value.
1551            Fingerprint::ZERO
1552        } else {
1553            self.expn_hash().0
1554        };
1555
1556        hash.hash_stable(ctx, hasher);
1557    }
1558}