Skip to main content

ra_ap_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//! Also see <https://rustc-dev-guide.rust-lang.org/macro-expansion.html#hygiene-and-hierarchies>
8//!
9//! # The Expansion Order Hierarchy
10//!
11//! `ExpnData` in rustc, rust-analyzer's version is `MacroCallLoc`. Traversing the hierarchy
12//! upwards can be achieved by walking up `MacroCallLoc::kind`'s contained file id, as
13//! `MacroFile`s are interned `MacroCallLoc`s.
14//!
15//! # The Macro Definition Hierarchy
16//!
17//! `SyntaxContextData` in rustc and rust-analyzer. Basically the same in both.
18//!
19//! # The Call-site Hierarchy
20//!
21//! `ExpnData::call_site` in rustc, `MacroCallLoc::call_site` in rust-analyzer.
22#[cfg(feature = "salsa")]
23use crate::Edition;
24
25use std::fmt;
26
27/// A syntax context describes a hierarchy tracking order of macro definitions.
28#[cfg(feature = "salsa")]
29#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
30pub struct SyntaxContext(
31    /// # Invariant
32    ///
33    /// This is either a valid `salsa::Id` or a root `SyntaxContext`.
34    u32,
35    std::marker::PhantomData<&'static salsa::plumbing::interned::Value<SyntaxContext>>,
36);
37
38#[cfg(feature = "salsa")]
39const _: () = {
40    use crate::MacroCallId;
41    use salsa::plumbing as zalsa_;
42    use salsa::plumbing::interned as zalsa_struct_;
43
44    #[derive(Clone, Eq, Debug)]
45    pub struct SyntaxContextData {
46        outer_expn: Option<MacroCallId>,
47        outer_transparency: Transparency,
48        edition: Edition,
49        parent: SyntaxContext,
50        opaque: SyntaxContext,
51        opaque_and_semiopaque: SyntaxContext,
52    }
53
54    impl PartialEq for SyntaxContextData {
55        fn eq(&self, other: &Self) -> bool {
56            self.outer_expn == other.outer_expn
57                && self.outer_transparency == other.outer_transparency
58                && self.edition == other.edition
59                && self.parent == other.parent
60        }
61    }
62
63    impl std::hash::Hash for SyntaxContextData {
64        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
65            self.outer_expn.hash(state);
66            self.outer_transparency.hash(state);
67            self.edition.hash(state);
68            self.parent.hash(state);
69        }
70    }
71
72    impl zalsa_::HasJar for SyntaxContext {
73        type Jar = zalsa_struct_::JarImpl<SyntaxContext>;
74        const KIND: zalsa_::JarKind = zalsa_::JarKind::Struct;
75    }
76
77    zalsa_::register_jar! {
78        zalsa_::ErasedJar::erase::<SyntaxContext>()
79    }
80
81    /// Key to use during hash lookups. Each field is some type that implements `Lookup<T>`
82    /// for the owned type. This permits interning with an `&str` when a `String` is required and so forth.
83    #[derive(Hash)]
84    struct StructKey<'db, T0, T1, T2, T3>(T0, T1, T2, T3, std::marker::PhantomData<&'db ()>);
85
86    impl<'db, T0, T1, T2, T3> zalsa_::HashEqLike<StructKey<'db, T0, T1, T2, T3>> for SyntaxContextData
87    where
88        Option<MacroCallId>: zalsa_::HashEqLike<T0>,
89        Transparency: zalsa_::HashEqLike<T1>,
90        Edition: zalsa_::HashEqLike<T2>,
91        SyntaxContext: zalsa_::HashEqLike<T3>,
92    {
93        fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
94            zalsa_::HashEqLike::<T0>::hash(&self.outer_expn, &mut *h);
95            zalsa_::HashEqLike::<T1>::hash(&self.outer_transparency, &mut *h);
96            zalsa_::HashEqLike::<T2>::hash(&self.edition, &mut *h);
97            zalsa_::HashEqLike::<T3>::hash(&self.parent, &mut *h);
98        }
99        fn eq(&self, data: &StructKey<'db, T0, T1, T2, T3>) -> bool {
100            zalsa_::HashEqLike::<T0>::eq(&self.outer_expn, &data.0)
101                && zalsa_::HashEqLike::<T1>::eq(&self.outer_transparency, &data.1)
102                && zalsa_::HashEqLike::<T2>::eq(&self.edition, &data.2)
103                && zalsa_::HashEqLike::<T3>::eq(&self.parent, &data.3)
104        }
105    }
106    impl zalsa_struct_::Configuration for SyntaxContext {
107        const LOCATION: salsa::plumbing::Location =
108            salsa::plumbing::Location { file: file!(), line: line!() };
109        const DEBUG_NAME: &'static str = "SyntaxContextData";
110        const REVISIONS: std::num::NonZeroUsize = std::num::NonZeroUsize::MAX;
111        const PERSIST: bool = false;
112
113        type Fields<'a> = SyntaxContextData;
114        type Struct<'a> = SyntaxContext;
115
116        fn serialize<S>(_: &Self::Fields<'_>, _: S) -> Result<S::Ok, S::Error>
117        where
118            S: zalsa_::serde::Serializer,
119        {
120            unimplemented!("attempted to serialize value that set `PERSIST` to false")
121        }
122
123        fn deserialize<'de, D>(_: D) -> Result<Self::Fields<'static>, D::Error>
124        where
125            D: zalsa_::serde::Deserializer<'de>,
126        {
127            unimplemented!("attempted to deserialize value that cannot set `PERSIST` to false");
128        }
129    }
130
131    impl SyntaxContext {
132        pub fn ingredient(zalsa: &zalsa_::Zalsa) -> &zalsa_struct_::IngredientImpl<Self> {
133            static CACHE: zalsa_::IngredientCache<zalsa_struct_::IngredientImpl<SyntaxContext>> =
134                zalsa_::IngredientCache::new();
135
136            // SAFETY: `lookup_jar_by_type` returns a valid ingredient index, and the only
137            // ingredient created by our jar is the struct ingredient.
138            unsafe {
139                CACHE.get_or_create(zalsa, || {
140                    zalsa.lookup_jar_by_type::<zalsa_struct_::JarImpl<SyntaxContext>>()
141                })
142            }
143        }
144    }
145    impl zalsa_::AsId for SyntaxContext {
146        fn as_id(&self) -> salsa::Id {
147            self.as_salsa_id().expect("`SyntaxContext::as_id()` called on a root `SyntaxContext`")
148        }
149    }
150    impl zalsa_::FromId for SyntaxContext {
151        fn from_id(id: salsa::Id) -> Self {
152            Self::from_salsa_id(id)
153        }
154    }
155    unsafe impl Send for SyntaxContext {}
156
157    unsafe impl Sync for SyntaxContext {}
158
159    impl zalsa_::SalsaStructInDb for SyntaxContext {
160        type MemoIngredientMap = salsa::plumbing::MemoIngredientSingletonIndex;
161        const LEAF_TYPE_IDS: &[salsa::plumbing::ConstTypeId] =
162            &[salsa::plumbing::ConstTypeId::of::<SyntaxContext>()];
163
164        fn lookup_ingredient_index(aux: &zalsa_::Zalsa) -> salsa::plumbing::IngredientIndices {
165            aux.lookup_jar_by_type::<zalsa_struct_::JarImpl<SyntaxContext>>().into()
166        }
167
168        fn entries(zalsa: &zalsa_::Zalsa) -> impl Iterator<Item = zalsa_::DatabaseKeyIndex> + '_ {
169            let _ingredient_index =
170                zalsa.lookup_jar_by_type::<zalsa_struct_::JarImpl<SyntaxContext>>();
171            <SyntaxContext>::ingredient(zalsa).entries(zalsa).map(|entry| entry.key())
172        }
173
174        #[inline]
175        fn cast(id: salsa::Id, type_id: std::any::TypeId) -> Option<Self> {
176            if type_id == std::any::TypeId::of::<SyntaxContext>() {
177                Some(<Self as salsa::plumbing::FromId>::from_id(id))
178            } else {
179                None
180            }
181        }
182
183        #[inline]
184        unsafe fn memo_table(
185            zalsa: &zalsa_::Zalsa,
186            id: zalsa_::Id,
187            current_revision: zalsa_::Revision,
188        ) -> zalsa_::MemoTableWithTypes<'_> {
189            // SAFETY: Guaranteed by caller.
190            unsafe {
191                zalsa.table().memos::<zalsa_struct_::Value<SyntaxContext>>(id, current_revision)
192            }
193        }
194    }
195
196    unsafe impl salsa::plumbing::Update for SyntaxContext {
197        unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool {
198            if unsafe { *old_pointer } != new_value {
199                unsafe { *old_pointer = new_value };
200                true
201            } else {
202                false
203            }
204        }
205    }
206    impl<'db> SyntaxContext {
207        pub fn new<
208            Db,
209            T0: zalsa_::Lookup<Option<MacroCallId>> + std::hash::Hash,
210            T1: zalsa_::Lookup<Transparency> + std::hash::Hash,
211            T2: zalsa_::Lookup<Edition> + std::hash::Hash,
212            T3: zalsa_::Lookup<SyntaxContext> + std::hash::Hash,
213        >(
214            db: &'db Db,
215            outer_expn: T0,
216            outer_transparency: T1,
217            edition: T2,
218            parent: T3,
219            opaque: impl FnOnce(SyntaxContext) -> SyntaxContext,
220            opaque_and_semiopaque: impl FnOnce(SyntaxContext) -> SyntaxContext,
221        ) -> Self
222        where
223            Db: ?Sized + salsa::Database,
224            Option<MacroCallId>: zalsa_::HashEqLike<T0>,
225            Transparency: zalsa_::HashEqLike<T1>,
226            Edition: zalsa_::HashEqLike<T2>,
227            SyntaxContext: zalsa_::HashEqLike<T3>,
228        {
229            let (zalsa, zalsa_local) = db.zalsas();
230
231            SyntaxContext::ingredient(zalsa).intern(
232                zalsa,
233                zalsa_local,
234                StructKey::<'db>(
235                    outer_expn,
236                    outer_transparency,
237                    edition,
238                    parent,
239                    std::marker::PhantomData,
240                ),
241                |id, data| SyntaxContextData {
242                    outer_expn: zalsa_::Lookup::into_owned(data.0),
243                    outer_transparency: zalsa_::Lookup::into_owned(data.1),
244                    edition: zalsa_::Lookup::into_owned(data.2),
245                    parent: zalsa_::Lookup::into_owned(data.3),
246                    opaque: opaque(zalsa_::FromId::from_id(id)),
247                    opaque_and_semiopaque: opaque_and_semiopaque(zalsa_::FromId::from_id(id)),
248                },
249            )
250        }
251
252        /// Invariant: Only the root [`SyntaxContext`] has a [`None`] outer expansion.
253        // FIXME: The None case needs to encode the context crate id. We can encode that as the MSB of
254        // MacroCallId is reserved anyways so we can do bit tagging here just fine.
255        // The bigger issue is that this will cause interning to now create completely separate chains
256        // per crate. Though that is likely not a problem as `MacroCallId`s are already crate calling dependent.
257        pub fn outer_expn<Db>(self, db: &'db Db) -> Option<MacroCallId>
258        where
259            Db: ?Sized + zalsa_::Database,
260        {
261            let id = self.as_salsa_id()?;
262            let zalsa = db.zalsa();
263            let fields = SyntaxContext::ingredient(zalsa).data(zalsa, id);
264            fields.outer_expn
265        }
266
267        pub fn outer_transparency<Db>(self, db: &'db Db) -> Transparency
268        where
269            Db: ?Sized + zalsa_::Database,
270        {
271            let Some(id) = self.as_salsa_id() else { return Transparency::Opaque };
272            let zalsa = db.zalsa();
273            let fields = SyntaxContext::ingredient(zalsa).data(zalsa, id);
274            fields.outer_transparency
275        }
276
277        pub fn edition<Db>(self, db: &'db Db) -> Edition
278        where
279            Db: ?Sized + zalsa_::Database,
280        {
281            match self.as_salsa_id() {
282                Some(id) => {
283                    let zalsa = db.zalsa();
284                    let fields = SyntaxContext::ingredient(zalsa).data(zalsa, id);
285                    fields.edition
286                }
287                None => Edition::from_u32(SyntaxContext::MAX_ROOT_ID - self.into_u32()),
288            }
289        }
290
291        pub fn parent<Db>(self, db: &'db Db) -> SyntaxContext
292        where
293            Db: ?Sized + zalsa_::Database,
294        {
295            match self.as_salsa_id() {
296                Some(id) => {
297                    let zalsa = db.zalsa();
298                    let fields = SyntaxContext::ingredient(zalsa).data(zalsa, id);
299                    fields.parent
300                }
301                None => self,
302            }
303        }
304
305        /// This context, but with all transparent and semi-opaque expansions filtered away.
306        pub fn opaque<Db>(self, db: &'db Db) -> SyntaxContext
307        where
308            Db: ?Sized + zalsa_::Database,
309        {
310            match self.as_salsa_id() {
311                Some(id) => {
312                    let zalsa = db.zalsa();
313                    let fields = SyntaxContext::ingredient(zalsa).data(zalsa, id);
314                    fields.opaque
315                }
316                None => self,
317            }
318        }
319
320        /// This context, but with all transparent expansions filtered away.
321        pub fn opaque_and_semiopaque<Db>(self, db: &'db Db) -> SyntaxContext
322        where
323            Db: ?Sized + zalsa_::Database,
324        {
325            match self.as_salsa_id() {
326                Some(id) => {
327                    let zalsa = db.zalsa();
328                    let fields = SyntaxContext::ingredient(zalsa).data(zalsa, id);
329                    fields.opaque_and_semiopaque
330                }
331                None => self,
332            }
333        }
334    }
335};
336
337#[cfg(feature = "salsa")]
338impl<'db> SyntaxContext {
339    const MAX_ROOT_ID: u32 = salsa::Id::MAX_U32 + Edition::LATEST as u32;
340
341    #[inline]
342    pub const fn into_u32(self) -> u32 {
343        self.0
344    }
345
346    /// # Safety
347    ///
348    /// The ID must be a valid `SyntaxContext`.
349    #[inline]
350    pub const unsafe fn from_u32(u32: u32) -> Self {
351        // INVARIANT: Our precondition.
352        Self(u32, std::marker::PhantomData)
353    }
354
355    #[inline]
356    fn as_salsa_id(self) -> Option<salsa::Id> {
357        if self.is_root() {
358            None
359        } else {
360            // SAFETY: By our invariant, this is either a root (which we verified it's not) or a
361            // valid `salsa::Id` index.
362            unsafe { Some(salsa::Id::from_index(self.0)) }
363        }
364    }
365
366    #[inline]
367    fn from_salsa_id(id: salsa::Id) -> Self {
368        // SAFETY: This comes from a Salsa ID.
369        unsafe { Self::from_u32(id.index()) }
370    }
371
372    #[inline]
373    pub fn is_root(self) -> bool {
374        (SyntaxContext::MAX_ROOT_ID - Edition::LATEST as u32) <= self.into_u32()
375            && self.into_u32() <= (SyntaxContext::MAX_ROOT_ID - Edition::Edition2015 as u32)
376    }
377
378    #[inline]
379    pub fn remove_root_edition(&mut self) {
380        if self.is_root() {
381            *self = Self::root(Edition::Edition2015);
382        }
383    }
384
385    /// The root context, which is the parent of all other contexts. All `FileId`s have this context.
386    #[inline]
387    pub const fn root(edition: Edition) -> Self {
388        let edition = edition as u32;
389        // SAFETY: Roots are valid `SyntaxContext`s
390        unsafe { SyntaxContext::from_u32(SyntaxContext::MAX_ROOT_ID - edition) }
391    }
392
393    #[inline]
394    pub fn outer_mark(
395        self,
396        db: &'db dyn salsa::Database,
397    ) -> (Option<crate::MacroCallId>, Transparency) {
398        (self.outer_expn(db), self.outer_transparency(db))
399    }
400
401    #[inline]
402    pub fn normalize_to_macros_2_0(self, db: &'db dyn salsa::Database) -> SyntaxContext {
403        self.opaque(db)
404    }
405
406    #[inline]
407    pub fn normalize_to_macro_rules(self, db: &'db dyn salsa::Database) -> SyntaxContext {
408        self.opaque_and_semiopaque(db)
409    }
410
411    pub fn is_opaque(self, db: &'db dyn salsa::Database) -> bool {
412        !self.is_root() && self.outer_transparency(db).is_opaque()
413    }
414
415    pub fn remove_mark(
416        &mut self,
417        db: &'db dyn salsa::Database,
418    ) -> (Option<crate::MacroCallId>, Transparency) {
419        let data = *self;
420        *self = data.parent(db);
421        (data.outer_expn(db), data.outer_transparency(db))
422    }
423
424    pub fn marks(
425        self,
426        db: &'db dyn salsa::Database,
427    ) -> impl Iterator<Item = (crate::MacroCallId, Transparency)> {
428        let mut marks = self.marks_rev(db).collect::<Vec<_>>();
429        marks.reverse();
430        marks.into_iter()
431    }
432
433    pub fn marks_rev(
434        self,
435        db: &'db dyn salsa::Database,
436    ) -> impl Iterator<Item = (crate::MacroCallId, Transparency)> {
437        std::iter::successors(Some(self), move |&mark| Some(mark.parent(db)))
438            .take_while(|&it| !it.is_root())
439            .map(|ctx| {
440                let mark = ctx.outer_mark(db);
441                // We stop before taking the root expansion, as such we cannot encounter a `None` outer
442                // expansion, as only the ROOT has it.
443                (mark.0.unwrap(), mark.1)
444            })
445    }
446}
447#[cfg(not(feature = "salsa"))]
448#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
449pub struct SyntaxContext(u32);
450
451#[cfg(not(feature = "salsa"))]
452impl SyntaxContext {
453    pub const fn into_u32(self) -> u32 {
454        self.0
455    }
456
457    /// # Safety
458    ///
459    /// None. This is always safe to call without the `salsa` feature.
460    pub const unsafe fn from_u32(u32: u32) -> Self {
461        Self(u32)
462    }
463}
464
465/// A property of a macro expansion that determines how identifiers
466/// produced by that expansion are resolved.
467#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug)]
468pub enum Transparency {
469    /// Identifier produced by a transparent expansion is always resolved at call-site.
470    /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this.
471    Transparent,
472    /// Identifier produced by a semi-opaque expansion may be resolved
473    /// either at call-site or at definition-site.
474    /// If it's a local variable, label or `$crate` then it's resolved at def-site.
475    /// Otherwise it's resolved at call-site.
476    /// `macro_rules` macros behave like this, built-in macros currently behave like this too,
477    /// but that's an implementation detail.
478    SemiOpaque,
479    /// Identifier produced by an opaque expansion is always resolved at definition-site.
480    /// Def-site spans in procedural macros, identifiers from `macro` by default use this.
481    Opaque,
482}
483
484impl Transparency {
485    /// Returns `true` if the transparency is [`Opaque`].
486    ///
487    /// [`Opaque`]: Transparency::Opaque
488    pub fn is_opaque(&self) -> bool {
489        matches!(self, Self::Opaque)
490    }
491}
492
493#[cfg(feature = "salsa")]
494impl fmt::Display for SyntaxContext {
495    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496        if self.is_root() {
497            write!(
498                f,
499                "ROOT{}",
500                Edition::from_u32(SyntaxContext::MAX_ROOT_ID - self.into_u32()).number()
501            )
502        } else {
503            write!(f, "{}", self.into_u32())
504        }
505    }
506}
507
508#[cfg(not(feature = "salsa"))]
509impl fmt::Display for SyntaxContext {
510    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511        write!(f, "{}", self.into_u32())
512    }
513}
514
515impl std::fmt::Debug for SyntaxContext {
516    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
517        if f.alternate() {
518            fmt::Display::fmt(self, f)
519        } else {
520            f.debug_tuple("SyntaxContext").field(&self.0).finish()
521        }
522    }
523}
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    #[test]
530    fn test_root_edition_is_root() {
531        for edition in Edition::iter() {
532            let ctx = SyntaxContext::root(edition);
533            assert!(ctx.is_root(), "{edition} root should be identified as root");
534        }
535    }
536
537    #[test]
538    fn test_root_edition_editions() {
539        let db = salsa::DatabaseImpl::new();
540        for edition in Edition::iter() {
541            let ctx = SyntaxContext::root(edition);
542            assert_eq!(edition, ctx.edition(&db), "{edition} root should have edition {edition}");
543        }
544    }
545
546    #[test]
547    fn test_roots_do_not_overlap_with_salsa_ids() {
548        for edition in Edition::iter() {
549            let root = SyntaxContext::root(edition);
550            let root_u32 = root.into_u32();
551            assert!(
552                root_u32 >= salsa::Id::MAX_U32,
553                "Root context for {:?} (value {}) must be >= salsa::Id::MAX_U32 ({}) to avoid collision",
554                edition,
555                root_u32,
556                salsa::Id::MAX_U32
557            );
558        }
559    }
560
561    #[test]
562    fn test_non_root_value_is_not_root() {
563        for edition in Edition::iter() {
564            // SAFETY: This is just for testing purposes
565            let ctx = unsafe { SyntaxContext::from_u32(edition as u32 + 1) };
566            assert!(!ctx.is_root(), "{edition} root should be identified as root");
567        }
568    }
569
570    #[test]
571    fn test_interned_context_round_trips_through_u32() {
572        let db = salsa::DatabaseImpl::new();
573        let root = SyntaxContext::root(Edition::Edition2015);
574        let ctx = SyntaxContext::new(
575            &db,
576            None,
577            Transparency::Opaque,
578            Edition::Edition2021,
579            root,
580            |_| root,
581            |_| root,
582        );
583
584        // SAFETY: The value was produced by `SyntaxContext::into_u32` above.
585        let round_tripped = unsafe { SyntaxContext::from_u32(ctx.into_u32()) };
586        assert_eq!(round_tripped.edition(&db), Edition::Edition2021);
587        assert_eq!(round_tripped.parent(&db), root);
588    }
589}