Skip to main content

salsa_macro_rules/
setup_interned_struct.rs

1/// Macro for setting up a function that must intern its arguments.
2#[macro_export]
3macro_rules! setup_interned_struct {
4    (
5        // Attributes on the struct
6        attrs: [$(#[$attr:meta]),*],
7
8        // Visibility of the struct
9        vis: $vis:vis,
10
11        // Name of the struct
12        Struct: $Struct:ident,
13
14        // Name of the struct data. This is a parameter because `std::concat_idents`
15        // is unstable and taking an additional dependency is unnecessary.
16        StructData: $StructDataIdent:ident,
17
18        // Name of the struct type with a `'static` argument (unless this type has no db lifetime,
19        // in which case this is the same as `$Struct`)
20        StructWithStatic: $StructWithStatic:ty,
21
22        // Name of the `'db` lifetime that the user gave
23        db_lt: $db_lt:lifetime,
24
25        // optional db lifetime argument.
26        db_lt_arg: $($db_lt_arg:lifetime)?,
27
28        // the salsa ID
29        id: $Id:path,
30
31        // The minimum number of revisions to keep the value interned.
32        revisions: $($revisions:expr)?,
33
34        // the lifetime used in the desugared interned struct.
35        // if the `db_lt_arg`, is present, this is `db_lt_arg`, but otherwise,
36        // it is `'static`.
37        interior_lt: $interior_lt:lifetime,
38
39        // Name user gave for `new`
40        new_fn: $new_fn:ident,
41
42        // A series of option tuples; see `setup_tracked_struct` macro
43        field_options: [$($field_option:tt),*],
44
45        // Field names
46        field_ids: [$($field_id:ident),*],
47
48        // Names for field setter methods (typically `set_foo`)
49        field_getters: [$($field_getter_vis:vis $field_getter_id:ident),*],
50
51        // Field types
52        field_tys: [$($field_ty:ty),*],
53
54        // Indices for each field from 0..N -- must be unsuffixed (e.g., `0`, `1`).
55        field_indices: [$($field_index:tt),*],
56
57        // Indexed types for each field (T0, T1, ...)
58        field_indexed_tys: [$($indexed_ty:ident),*],
59
60        // Attrs for each field.
61        field_attrs: [$([$(#[$field_attr:meta]),*]),*],
62
63        // Number of fields
64        num_fields: $N:literal,
65
66        // If true, generate a debug impl.
67        generate_debug_impl: $generate_debug_impl:tt,
68
69        // The function used to implement `C::heap_size`.
70        heap_size_fn: $($heap_size_fn:path)?,
71
72        // If `true`, `serialize_fn` and `deserialize_fn` have been provided.
73        persist: $persist:tt,
74
75        // The path to the `serialize` function for the value's fields.
76        serialize_fn: $($serialize_fn:path)?,
77
78        // The path to the `serialize` function for the value's fields.
79        deserialize_fn: $($deserialize_fn:path)?,
80
81        // Ensures that every field can be rebound to the database lifetime.
82        assert_fields_are_salsa_values: {$($assert_fields_are_salsa_values:tt)*},
83
84        // Annoyingly macro-rules hygiene does not extend to items defined in the macro.
85        // We have the procedural macro generate names for those items that are
86        // not used elsewhere in the user's code.
87        unused_names: [
88            $zalsa:ident,
89            $zalsa_struct:ident,
90            $Configuration:ident,
91            $CACHE:ident,
92            $Db:ident,
93        ]
94    ) => {
95        $(#[$attr])*
96        #[derive(Copy, Clone, PartialEq, Eq, Hash)]
97        $vis struct $Struct< $($db_lt_arg)? >(
98            $Id,
99            std::marker::PhantomData<fn() -> &$interior_lt ()>
100        );
101
102        #[allow(clippy::all)]
103        #[allow(dead_code)]
104        const _: () = {
105            use ::salsa::plumbing as $zalsa;
106            use $zalsa::interned as $zalsa_struct;
107
108            type $Configuration = $StructWithStatic;
109
110            impl<$($db_lt_arg)?> $zalsa::HasJar for $Struct<$($db_lt_arg)?> {
111                type Jar = $zalsa_struct::JarImpl<$Configuration>;
112                const KIND: $zalsa::JarKind = $zalsa::JarKind::Struct;
113            }
114
115            $zalsa::register_jar! {
116                $zalsa::ErasedJar::erase::<$StructWithStatic>()
117            }
118
119            #[allow(unused_lifetimes)]
120            fn _assert_fields_are_salsa_values<$db_lt>() {
121                use $zalsa::{SalsaValueDispatch, SalsaValueFallback as _};
122                $($assert_fields_are_salsa_values)*
123            }
124            let _ = _assert_fields_are_salsa_values;
125
126            type $StructDataIdent<$db_lt> = ($($field_ty,)*);
127
128            /// Key to use during hash lookups. Each field is some type that implements `Lookup<T>`
129            /// for the owned type. This permits interning with an `&str` when a `String` is required and so forth.
130            #[derive(Hash)]
131            struct StructKey<$db_lt, $($indexed_ty),*>(
132                $($indexed_ty,)*
133                ::std::marker::PhantomData<&$db_lt ()>,
134            );
135
136            impl<$db_lt, $($indexed_ty,)*> $zalsa::HashEqLike<StructKey<$db_lt, $($indexed_ty),*>>
137                for $StructDataIdent<$db_lt>
138                where
139                $($field_ty: $zalsa::HashEqLike<$indexed_ty>),*
140                {
141
142
143
144                fn eq(&self, data: &StructKey<$db_lt, $($indexed_ty),*>) -> bool {
145                    ($($zalsa::HashEqLike::<$indexed_ty>::eq(&self.$field_index, &data.$field_index) && )* true)
146                }
147            }
148
149            impl<$db_lt, $($indexed_ty: $zalsa::Lookup<$field_ty>),*> $zalsa::Lookup<$StructDataIdent<$db_lt>>
150                for StructKey<$db_lt, $($indexed_ty),*> {
151
152                #[allow(unused_unit)]
153                fn into_owned(self) -> $StructDataIdent<$db_lt> {
154                    ($($zalsa::Lookup::into_owned(self.$field_index),)*)
155                }
156            }
157
158            // SAFETY: The generated assertions above prove every field can be
159            // retained after erasing the database lifetime.
160            unsafe impl $zalsa::interned::Configuration for $StructWithStatic {
161                const LOCATION: $zalsa::Location = $zalsa::Location {
162                    file: file!(),
163                    line: line!(),
164                };
165                const DEBUG_NAME: &'static str = stringify!($Struct);
166                const PERSIST: bool = $persist;
167
168                $(
169                    const REVISIONS: ::core::num::NonZeroUsize = ::core::num::NonZeroUsize::new($revisions).unwrap();
170                )?
171
172                type Fields<'a> = $StructDataIdent<'a>;
173                type Struct<'db> = $Struct< $($db_lt_arg)? >;
174
175                $(
176                    fn heap_size(value: &Self::Fields<'_>) -> Option<usize> {
177                        Some($heap_size_fn(value))
178                    }
179                )?
180
181                fn serialize<S: $zalsa::serde::Serializer>(
182                    fields: &Self::Fields<'_>,
183                    serializer: S,
184                ) -> ::std::result::Result<S::Ok, S::Error> {
185                    $zalsa::macro_if! {
186                        if $persist {
187                            $($serialize_fn(fields, serializer))?
188                        } else {
189                            panic!("attempted to serialize value not marked with `persist` attribute")
190                        }
191                    }
192                }
193
194                fn deserialize<'de, D: $zalsa::serde::Deserializer<'de>>(
195                    deserializer: D,
196                ) -> ::std::result::Result<Self::Fields<'static>, D::Error> {
197                    $zalsa::macro_if! {
198                        if $persist {
199                            $($deserialize_fn(deserializer))?
200                        } else {
201                            panic!("attempted to deserialize value not marked with `persist` attribute")
202                        }
203                    }
204                }
205            }
206
207            impl $Configuration {
208                pub fn ingredient(zalsa: &$zalsa::Zalsa) -> &$zalsa_struct::IngredientImpl<Self> {
209                    static CACHE: $zalsa::IngredientCache<$zalsa_struct::IngredientImpl<$Configuration>> =
210                        $zalsa::IngredientCache::new();
211
212                    // SAFETY: The ingredient at offset 0 in `JarImpl<$Configuration>` has type
213                    // `IngredientImpl<$Configuration>`.
214                    unsafe {
215                        CACHE.get_or_create::<$zalsa_struct::JarImpl<$Configuration>, 0>(zalsa)
216                    }
217                }
218            }
219
220            impl< $($db_lt_arg)? > $zalsa::AsId for $Struct< $($db_lt_arg)? > {
221                fn as_id(&self) -> ::salsa::Id {
222                    self.0.as_id()
223                }
224            }
225
226            impl< $($db_lt_arg)? > $zalsa::FromId for $Struct< $($db_lt_arg)? > {
227                fn from_id(id: ::salsa::Id) -> Self {
228                    Self(<$Id>::from_id(id), ::std::marker::PhantomData)
229                }
230            }
231
232            unsafe impl< $($db_lt_arg)? > Send for $Struct< $($db_lt_arg)? > {}
233
234            unsafe impl< $($db_lt_arg)? > Sync for $Struct< $($db_lt_arg)? > {}
235
236            $zalsa::macro_if! { $generate_debug_impl =>
237                impl< $($db_lt_arg)? > ::std::fmt::Debug for $Struct< $($db_lt_arg)? > {
238                    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
239                        Self::default_debug_fmt(*self, f)
240                    }
241                }
242            }
243
244            impl< $($db_lt_arg)? > $zalsa::SalsaStructInDb for $Struct< $($db_lt_arg)? > {
245                type MemoIngredientMap = $zalsa::MemoIngredientSingletonIndex;
246                const LEAF_TYPE_IDS: &'static [$zalsa::TypeId] = &[$zalsa::TypeId::of::<$Struct>()];
247
248                fn lookup_ingredient_index(aux: &$zalsa::Zalsa) -> $zalsa::IngredientIndices {
249                    aux.lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>().into()
250                }
251
252                fn entries(
253                    zalsa: &$zalsa::Zalsa
254                ) -> impl Iterator<Item = $zalsa::DatabaseKeyIndex> + '_ {
255                    let ingredient_index = zalsa.lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>();
256                    <$Configuration>::ingredient(zalsa).entries(zalsa).map(|entry| entry.key())
257                }
258
259                #[inline]
260                fn cast(id: $zalsa::Id, type_id: $zalsa::TypeId) -> $zalsa::Option<Self> {
261                    if type_id == $zalsa::TypeId::of::<$Struct>() {
262                        $zalsa::Some(<$Struct as $zalsa::FromId>::from_id(id))
263                    } else {
264                        $zalsa::None
265                    }
266                }
267
268                #[inline]
269                unsafe fn memo_table(
270                    zalsa: &$zalsa::Zalsa,
271                    id: $zalsa::Id,
272                    current_revision: $zalsa::Revision,
273                ) -> $zalsa::MemoTableWithTypes<'_> {
274                    // SAFETY: Guaranteed by caller.
275                    unsafe { zalsa.table().memos::<$zalsa_struct::Value<$Configuration>>(id, current_revision) }
276                }
277            }
278
279            $zalsa::macro_if! { $persist =>
280                impl<$($db_lt_arg)?> $zalsa::serde::Serialize for $Struct<$($db_lt_arg)?> {
281                    fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
282                    where
283                        S: $zalsa::serde::Serializer,
284                    {
285                        $zalsa::serde::Serialize::serialize(&$zalsa::AsId::as_id(self), serializer)
286                    }
287                }
288
289                impl<'de, $($db_lt_arg)?> $zalsa::serde::Deserialize<'de> for $Struct<$($db_lt_arg)?> {
290                    fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
291                    where
292                        D: $zalsa::serde::Deserializer<'de>,
293                    {
294                        let id = $zalsa::Id::deserialize(deserializer)?;
295                        Ok($zalsa::FromId::from_id(id))
296                    }
297                }
298            }
299
300
301            unsafe impl< $($db_lt_arg)? > $zalsa::SalsaValue for $Struct< $($db_lt_arg)? > {}
302
303            impl<$db_lt> $Struct< $($db_lt_arg)? >  {
304                pub fn $new_fn<$Db, $($indexed_ty: $zalsa::Lookup<$field_ty> + ::std::hash::Hash,)*>(db: &$db_lt $Db,  $($field_id: $indexed_ty),*) -> Self
305                where
306                    // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
307                    $Db: ?Sized + ::salsa::Database,
308                    $(
309                        $field_ty: $zalsa::HashEqLike<$indexed_ty>,
310                    )*
311                {
312                    let (zalsa, zalsa_local) = db.zalsas();
313                    $Configuration::ingredient(zalsa).intern(zalsa, zalsa_local,
314                        StructKey::<$db_lt>($($field_id,)* ::std::marker::PhantomData::default()))
315                }
316
317                $(
318                    $(#[$field_attr])*
319                    $field_getter_vis fn $field_getter_id<$Db>(self, db: &'db $Db) -> $zalsa::return_mode_ty!($field_option, 'db, $field_ty)
320                    where
321                        // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
322                        $Db: ?Sized + $zalsa::Database,
323                    {
324                        let zalsa = db.zalsa();
325                        let fields = $Configuration::ingredient(zalsa).fields(zalsa, self);
326                        $zalsa::return_mode_expression!(
327                            $field_option,
328                            $field_ty,
329                            &fields.$field_index,
330                        )
331                    }
332                )*
333            }
334
335            // Duplication can be dropped here once we no longer allow the `no_lifetime` hack
336            $zalsa::macro_if! {
337                iftt ($($db_lt_arg)?) {
338                    impl $Struct<'_> {
339                        /// Default debug formatting for this struct (may be useful if you define your own `Debug` impl)
340                        pub fn default_debug_fmt(this: Self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
341                        where
342                            // rustc rejects trivial bounds, but it cannot see through higher-ranked bounds
343                            // with its check :^)
344                            $(for<$db_lt> $field_ty: ::std::fmt::Debug),*
345                        {
346                            $zalsa::with_attached_database(|db| {
347                                let zalsa = db.zalsa();
348                                let fields = $Configuration::ingredient(zalsa).fields(zalsa, this);
349                                let mut f = f.debug_struct(stringify!($Struct));
350                                $(
351                                    let f = f.field(stringify!($field_id), &fields.$field_index);
352                                )*
353                                f.finish()
354                            }).unwrap_or_else(|| {
355                                f.debug_tuple(stringify!($Struct))
356                                    .field(&$zalsa::AsId::as_id(&this))
357                                    .finish()
358                            })
359                        }
360                    }
361                } else {
362                    impl $Struct {
363                        /// Default debug formatting for this struct (may be useful if you define your own `Debug` impl)
364                        pub fn default_debug_fmt(this: Self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
365                        where
366                            // rustc rejects trivial bounds, but it cannot see through higher-ranked bounds
367                            // with its check :^)
368                            $(for<$db_lt> $field_ty: ::std::fmt::Debug),*
369                        {
370                            $zalsa::with_attached_database(|db| {
371                                let zalsa = db.zalsa();
372                                let fields = $Configuration::ingredient(zalsa).fields(zalsa, this);
373                                let mut f = f.debug_struct(stringify!($Struct));
374                                $(
375                                    let f = f.field(stringify!($field_id), &fields.$field_index);
376                                )*
377                                f.finish()
378                            }).unwrap_or_else(|| {
379                                f.debug_tuple(stringify!($Struct))
380                                    .field(&$zalsa::AsId::as_id(&this))
381                                    .finish()
382                            })
383                        }
384                    }
385                }
386            }
387        };
388    };
389}