Skip to main content

salsa_macro_rules/
setup_input_struct.rs

1/// Macro for setting up a function that must intern its arguments.
2#[macro_export]
3macro_rules! setup_input_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 user gave for `new`
15        new_fn: $new_fn:ident,
16
17        // A series of option tuples; see `setup_tracked_struct` macro
18        field_options: [$($field_option:tt),*],
19
20        // Field names
21        field_ids: [$($field_id:ident),*],
22
23        // Names for field getter methods (typically `foo`)
24        field_getters: [$($field_getter_vis:vis $field_getter_id:ident),*],
25
26        // Names for field setter methods (typically `set_foo`)
27        field_setters: [$($field_setter_vis:vis $field_setter_id:ident),*],
28
29        // Field types
30        field_tys: [$($field_ty:ty),*],
31
32        // Indices for each field from 0..N -- must be unsuffixed (e.g., `0`, `1`).
33        field_indices: [$($field_index:tt),*],
34
35        // Attributes for each field
36        field_attrs: [$([$(#[$field_attr:meta]),*]),*],
37
38        // Fields that are required (have no default value). Each item is the fields name and type.
39        required_fields: [$($required_field_id:ident $required_field_ty:ty),*],
40
41        // Names for the field durability methods on the builder (typically `foo_durability`)
42        field_durability_ids: [$($field_durability_id:ident),*],
43
44        // Number of fields
45        num_fields: $N:literal,
46
47        // If true, this is a singleton input.
48        is_singleton: $is_singleton:tt,
49
50        // If true, generate a debug impl.
51        generate_debug_impl: $generate_debug_impl:tt,
52
53        // The function used to implement `C::heap_size`.
54        heap_size_fn: $($heap_size_fn:path)?,
55
56        // If `true`, `serialize_fn` and `deserialize_fn` have been provided.
57        persist: $persist:tt,
58
59        // The path to the `serialize` function for the value's fields.
60        serialize_fn: $($serialize_fn:path)?,
61
62        // The path to the `serialize` function for the value's fields.
63        deserialize_fn: $($deserialize_fn:path)?,
64
65        // Annoyingly macro-rules hygiene does not extend to items defined in the macro.
66        // We have the procedural macro generate names for those items that are
67        // not used elsewhere in the user's code.
68        unused_names: [
69            $zalsa:ident,
70            $zalsa_struct:ident,
71            $Configuration:ident,
72            $Builder:ident,
73            $CACHE:ident,
74            $Db:ident,
75        ]
76    ) => {
77        $(#[$attr])*
78        #[derive(Copy, Clone, PartialEq, Eq, Hash)]
79        $vis struct $Struct(salsa::Id);
80
81        #[allow(clippy::all)]
82        #[allow(dead_code)]
83        const _: () = {
84            use ::salsa::plumbing as $zalsa;
85            use $zalsa::input as $zalsa_struct;
86
87            type $Configuration = $Struct;
88
89            impl $zalsa::HasJar for $Struct {
90                type Jar = $zalsa_struct::JarImpl<$Configuration>;
91                const KIND: $zalsa::JarKind = $zalsa::JarKind::Struct;
92            }
93
94            $zalsa::register_jar! {
95                $zalsa::ErasedJar::erase::<$Struct>()
96            }
97
98            impl $zalsa_struct::Configuration for $Configuration {
99                const LOCATION: $zalsa::Location = $zalsa::Location {
100                    file: file!(),
101                    line: line!(),
102                };
103                const DEBUG_NAME: &'static str = stringify!($Struct);
104                const FIELD_DEBUG_NAMES: &'static [&'static str] = &[$(stringify!($field_id)),*];
105
106                const PERSIST: bool = $persist;
107
108                type Singleton = $zalsa::macro_if! {if $is_singleton {$zalsa::input::Singleton} else {$zalsa::input::NotSingleton}};
109
110                type Struct = $Struct;
111
112                type Fields = ($($field_ty,)*);
113
114                type Revisions = [$zalsa::Revision; $N];
115                type Durabilities = [$zalsa::Durability; $N];
116
117                $(
118                    fn heap_size(value: &Self::Fields) -> Option<usize> {
119                        Some($heap_size_fn(value))
120                    }
121                )?
122
123                fn serialize<S: $zalsa::serde::Serializer>(
124                    fields: &Self::Fields,
125                    serializer: S,
126                ) -> ::std::result::Result<S::Ok, S::Error> {
127                    $zalsa::macro_if! {
128                        if $persist {
129                            $($serialize_fn(fields, serializer))?
130                        } else {
131                            panic!("attempted to serialize value not marked with `persist` attribute")
132                        }
133                    }
134                }
135
136                fn deserialize<'de, D: $zalsa::serde::Deserializer<'de>>(
137                    deserializer: D,
138                ) -> ::std::result::Result<Self::Fields, D::Error> {
139                    $zalsa::macro_if! {
140                        if $persist {
141                            $($deserialize_fn(deserializer))?
142                        } else {
143                            panic!("attempted to deserialize value not marked with `persist` attribute")
144                        }
145                    }
146                }
147
148            }
149
150            impl $Configuration {
151                pub fn ingredient(db: &dyn $zalsa::Database) -> &$zalsa_struct::IngredientImpl<Self> {
152                    Self::ingredient_(db.zalsa())
153                }
154
155                fn ingredient_(zalsa: &$zalsa::Zalsa) -> &$zalsa_struct::IngredientImpl<Self> {
156                    static CACHE: $zalsa::IngredientCache<$zalsa_struct::IngredientImpl<$Configuration>> =
157                        $zalsa::IngredientCache::new();
158
159                    // SAFETY: The ingredient at offset 0 in `JarImpl<$Configuration>` has type
160                    // `IngredientImpl<$Configuration>`.
161                    unsafe {
162                        CACHE.get_or_create::<$zalsa_struct::JarImpl<$Configuration>, 0>(zalsa)
163                    }
164                }
165
166                pub fn ingredient_mut(zalsa_mut: &mut $zalsa::Zalsa) -> (&mut $zalsa_struct::IngredientImpl<Self>, &mut $zalsa::Runtime) {
167                    zalsa_mut.new_revision();
168                    let index = zalsa_mut.lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>();
169                    let (ingredient, runtime) = zalsa_mut.lookup_ingredient_mut(index);
170                    let ingredient = ingredient.assert_type_mut::<$zalsa_struct::IngredientImpl<Self>>();
171                    (ingredient, runtime)
172                }
173            }
174
175            impl $zalsa::FromId for $Struct {
176                fn from_id(id: salsa::Id) -> Self {
177                    Self(id)
178                }
179            }
180
181            impl $zalsa::AsId for $Struct {
182                fn as_id(&self) -> salsa::Id {
183                    self.0
184                }
185            }
186
187            unsafe impl $zalsa::SalsaValue for $Struct {}
188
189            $zalsa::macro_if! { $generate_debug_impl =>
190                impl ::std::fmt::Debug for $Struct {
191                    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
192                        Self::default_debug_fmt(*self, f)
193                    }
194                }
195            }
196
197            impl $zalsa::SalsaStructInDb for $Struct {
198                type MemoIngredientMap = $zalsa::MemoIngredientSingletonIndex;
199                const LEAF_TYPE_IDS: &'static [$zalsa::TypeId] = &[$zalsa::TypeId::of::<$Struct>()];
200
201                fn lookup_ingredient_index(aux: &$zalsa::Zalsa) -> $zalsa::IngredientIndices {
202                    aux.lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>().into()
203                }
204
205                fn entries(
206                    zalsa: &$zalsa::Zalsa
207                ) -> impl Iterator<Item = $zalsa::DatabaseKeyIndex> + '_ {
208                    let ingredient_index = zalsa.lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>();
209                    <$Configuration>::ingredient_(zalsa).entries(zalsa).map(|entry| entry.key())
210                }
211
212                #[inline]
213                fn cast(id: $zalsa::Id, type_id: $zalsa::TypeId) -> $zalsa::Option<Self> {
214                    if type_id == $zalsa::TypeId::of::<$Struct>() {
215                        $zalsa::Some($Struct(id))
216                    } else {
217                        $zalsa::None
218                    }
219                }
220
221                #[inline]
222                unsafe fn memo_table(
223                    zalsa: &$zalsa::Zalsa,
224                    id: $zalsa::Id,
225                    current_revision: $zalsa::Revision,
226                ) -> $zalsa::MemoTableWithTypes<'_> {
227                    // SAFETY: Guaranteed by caller.
228                    unsafe { zalsa.table().memos::<$zalsa_struct::Value<$Configuration>>(id, current_revision) }
229                }
230            }
231
232            $zalsa::macro_if! { $persist =>
233                impl $zalsa::serde::Serialize for $Struct {
234                    fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
235                    where
236                        S: $zalsa::serde::Serializer,
237                    {
238                        $zalsa::serde::Serialize::serialize(&$zalsa::AsId::as_id(self), serializer)
239                    }
240                }
241
242                impl<'de> $zalsa::serde::Deserialize<'de> for $Struct {
243                    fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
244                    where
245                        D: $zalsa::serde::Deserializer<'de>,
246                    {
247                        let id = $zalsa::Id::deserialize(deserializer)?;
248                        Ok($zalsa::FromId::from_id(id))
249                    }
250                }
251            }
252            impl $Struct {
253                #[inline]
254                pub fn $new_fn<$Db>(db: &$Db, $($required_field_id: $required_field_ty),*) -> Self
255                where
256                    // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
257                    $Db: ?Sized + salsa::Database,
258                {
259                    Self::builder($($required_field_id,)*).new(db)
260                }
261
262                pub fn builder($($required_field_id: $required_field_ty),*) -> <Self as $zalsa_struct::HasBuilder>::Builder
263                {
264                    builder::new_builder($($zalsa::maybe_default!($field_option, $field_ty, $field_id,)),*)
265                }
266
267                $(
268                    $(#[$field_attr])*
269                    $field_getter_vis fn $field_getter_id<'db, $Db>(self, db: &'db $Db) -> $zalsa::return_mode_ty!($field_option, 'db, $field_ty)
270                    where
271                        // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
272                        $Db: ?Sized + $zalsa::Database,
273                    {
274                        let (zalsa, zalsa_local) = db.zalsas();
275                        let fields = $Configuration::ingredient_(zalsa).field(
276                            zalsa,
277                            zalsa_local,
278                            self,
279                            $field_index,
280                        );
281                        $zalsa::return_mode_expression!(
282                            $field_option,
283                            $field_ty,
284                            &fields.$field_index,
285                        )
286                    }
287                )*
288
289                $(
290                    #[must_use]
291                    $field_setter_vis fn $field_setter_id<'db, $Db>(self, db: &'db mut $Db) -> impl salsa::Setter<FieldTy = $field_ty>
292                    where
293                        // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
294                        $Db: ?Sized + $zalsa::Database,
295                    {
296                        let zalsa = db.zalsa_mut();
297                        let (ingredient, revision) = $Configuration::ingredient_mut(zalsa);
298                        $zalsa::input::SetterImpl::new(
299                            revision,
300                            self,
301                            $field_index,
302                            ingredient,
303                            |fields, f| ::std::mem::replace(&mut fields.$field_index, f),
304                        )
305                    }
306                )*
307
308                $zalsa::macro_if! { $is_singleton =>
309                    pub fn try_get<$Db>(db: &$Db) -> Option<Self>
310                    where
311                        // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
312                        $Db: ?Sized + salsa::Database,
313                    {
314                        let zalsa = db.zalsa();
315                        $Configuration::ingredient_(zalsa).get_singleton_input(zalsa)
316                    }
317
318                    #[track_caller]
319                    pub fn get<$Db>(db: &$Db) -> Self
320                    where
321                        // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
322                        $Db: ?Sized + salsa::Database,
323                    {
324                        Self::try_get(db).unwrap()
325                    }
326                }
327
328                /// Default debug formatting for this struct (may be useful if you define your own `Debug` impl)
329                pub fn default_debug_fmt(this: Self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
330                where
331                    // rustc rejects trivial bounds, but it cannot see through higher-ranked bounds
332                    // with its check :^)
333                    $(for<'__trivial_bounds> $field_ty: ::std::fmt::Debug),*
334                {
335                    $zalsa::with_attached_database(|db| {
336                        let zalsa = db.zalsa();
337                        let fields = $Configuration::ingredient_(zalsa).leak_fields(zalsa, this);
338                        let mut f = f.debug_struct(stringify!($Struct));
339                        let f = f.field("[salsa id]", &$zalsa::AsId::as_id(&this));
340                        $(
341                            let f = f.field(stringify!($field_id), &fields.$field_index);
342                        )*
343                        f.finish()
344                    }).unwrap_or_else(|| {
345                        f.debug_struct(stringify!($Struct))
346                            .field("[salsa id]", &this.0)
347                            .finish()
348                    })
349                }
350            }
351
352            impl $zalsa_struct::HasBuilder for $Struct {
353                type Builder = builder::$Builder;
354            }
355
356            // Implement `new` here instead of inside the builder module
357            // because $Configuration can't be named in `builder`.
358            impl builder::$Builder {
359                /// Creates the new input with the set values.
360                #[must_use]
361                pub fn new<$Db>(self, db: &$Db) -> $Struct
362                where
363                    // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
364                    $Db: ?Sized + ::salsa::Database
365                {
366                    let (zalsa, zalsa_local) = db.zalsas();
367                    let current_revision = zalsa.current_revision();
368                    let ingredient = $Configuration::ingredient_(zalsa);
369                    let (fields, revision, durabilities) = builder::builder_into_inner(self, current_revision);
370                    ingredient.new_input(zalsa, zalsa_local, fields, revision, durabilities)
371                }
372            }
373
374            mod builder {
375                use super::*;
376
377                use ::salsa::plumbing as $zalsa;
378                use $zalsa::input as $zalsa_struct;
379
380                // These are standalone functions instead of methods on `Builder` to prevent
381                // that the enclosing module can call them.
382                pub(super) fn new_builder($($field_id: $field_ty),*) -> $Builder {
383                    $Builder {
384                        fields: ($($field_id,)*),
385                        durabilities: [::salsa::Durability::default(); $N],
386                    }
387                }
388
389                pub(super) fn builder_into_inner(builder: $Builder, revision: $zalsa::Revision) -> (($($field_ty,)*), [$zalsa::Revision; $N], [$zalsa::Durability; $N]) {
390                    (builder.fields, [revision; $N], [$(builder.durabilities[$field_index]),*])
391                }
392
393                #[must_use]
394                pub struct $Builder {
395                    /// The field values.
396                    fields: ($($field_ty,)*),
397
398                    /// The durabilities per field.
399                    durabilities: [::salsa::Durability; $N],
400                }
401
402                impl $Builder {
403                    /// Sets the durability of all fields.
404                    ///
405                    /// Overrides any previously set durabilities.
406                    pub fn durability(mut self, durability: ::salsa::Durability) -> Self {
407                        self.durabilities = [durability; $N];
408                        self
409                    }
410
411                    $($zalsa::maybe_default_tt! { $field_option =>
412                        /// Sets the value of the field `$field_id`.
413                        #[must_use]
414                        pub fn $field_id(mut self, value: $field_ty) -> Self
415                        {
416                            self.fields.$field_index = value;
417                            self
418                        }
419                    })*
420
421                    $(
422                        /// Sets the durability for the field `$field_id`.
423                        #[must_use]
424                        pub fn $field_durability_id(mut self, durability: ::salsa::Durability) -> Self
425                        {
426                            self.durabilities[$field_index] = durability;
427                            self
428                        }
429                    )*
430                }
431            }
432        };
433    };
434}