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        // Fields that are required (have no default value). Each item is the fields name and type.
36        required_fields: [$($required_field_id:ident $required_field_ty:ty),*],
37
38        // Names for the field durability methods on the builder (typically `foo_durability`)
39        field_durability_ids: [$($field_durability_id:ident),*],
40
41        // Number of fields
42        num_fields: $N:literal,
43
44        // If true, this is a singleton input.
45        is_singleton: $is_singleton:tt,
46
47        // If true, generate a debug impl.
48        generate_debug_impl: $generate_debug_impl:tt,
49
50        // Annoyingly macro-rules hygiene does not extend to items defined in the macro.
51        // We have the procedural macro generate names for those items that are
52        // not used elsewhere in the user's code.
53        unused_names: [
54            $zalsa:ident,
55            $zalsa_struct:ident,
56            $Configuration:ident,
57            $Builder:ident,
58            $CACHE:ident,
59            $Db:ident,
60        ]
61    ) => {
62        $(#[$attr])*
63        #[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
64        $vis struct $Struct(salsa::Id);
65
66        const _: () = {
67            use salsa::plumbing as $zalsa;
68            use $zalsa::input as $zalsa_struct;
69
70            type $Configuration = $Struct;
71
72            impl $zalsa_struct::Configuration for $Configuration {
73                const DEBUG_NAME: &'static str = stringify!($Struct);
74                const FIELD_DEBUG_NAMES: &'static [&'static str] = &[$(stringify!($field_id)),*];
75                type Singleton = $zalsa::macro_if! {if $is_singleton {$zalsa::input::Singleton} else {$zalsa::input::NotSingleton}};
76
77                /// The input struct (which wraps an `Id`)
78                type Struct = $Struct;
79
80                /// A (possibly empty) tuple of the fields for this struct.
81                type Fields = ($($field_ty,)*);
82
83                /// A array of [`StampedValue<()>`](`StampedValue`) tuples, one per each of the value fields.
84                type Stamps = $zalsa::Array<$zalsa::Stamp, $N>;
85            }
86
87            impl $Configuration {
88                pub fn ingredient(db: &dyn $zalsa::Database) -> &$zalsa_struct::IngredientImpl<Self> {
89                    static CACHE: $zalsa::IngredientCache<$zalsa_struct::IngredientImpl<$Configuration>> =
90                        $zalsa::IngredientCache::new();
91                    let zalsa = db.zalsa();
92                    CACHE.get_or_create(zalsa, || {
93                        zalsa.add_or_lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>()
94                    })
95                }
96
97                pub fn ingredient_mut(db: &mut dyn $zalsa::Database) -> (&mut $zalsa_struct::IngredientImpl<Self>, &mut $zalsa::Runtime) {
98                    let zalsa_mut = db.zalsa_mut();
99                    let current_revision = zalsa_mut.new_revision();
100                    let index = zalsa_mut.add_or_lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>();
101                    let (ingredient, runtime) = zalsa_mut.lookup_ingredient_mut(index);
102                    let ingredient = ingredient.assert_type_mut::<$zalsa_struct::IngredientImpl<Self>>();
103                    (ingredient, runtime)
104                }
105            }
106
107            impl $zalsa::FromId for $Struct {
108                fn from_id(id: salsa::Id) -> Self {
109                    Self(id)
110                }
111            }
112
113            impl $zalsa::AsId for $Struct {
114                fn as_id(&self) -> salsa::Id {
115                    self.0
116                }
117            }
118
119            unsafe impl $zalsa::Update for $Struct {
120                unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool {
121                    if unsafe { *old_pointer } != new_value {
122                        unsafe { *old_pointer = new_value };
123                        true
124                    } else {
125                        false
126                    }
127                }
128            }
129
130            $zalsa::macro_if! { $generate_debug_impl =>
131                impl std::fmt::Debug for $Struct {
132                    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133                        Self::default_debug_fmt(*self, f)
134                    }
135                }
136            }
137
138            impl $zalsa::SalsaStructInDb for $Struct {
139                type MemoIngredientMap = $zalsa::MemoIngredientSingletonIndex;
140
141                fn lookup_or_create_ingredient_index(aux: &$zalsa::Zalsa) -> $zalsa::IngredientIndices {
142                    aux.add_or_lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>().into()
143                }
144
145                #[inline]
146                fn cast(id: $zalsa::Id, type_id: $zalsa::TypeId) -> $zalsa::Option<Self> {
147                    if type_id == $zalsa::TypeId::of::<$Struct>() {
148                        $zalsa::Some($Struct(id))
149                    } else {
150                        $zalsa::None
151                    }
152                }
153            }
154
155            impl $Struct {
156                #[inline]
157                pub fn $new_fn<$Db>(db: &$Db, $($required_field_id: $required_field_ty),*) -> Self
158                where
159                    // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
160                    $Db: ?Sized + salsa::Database,
161                {
162                    Self::builder($($required_field_id,)*).new(db)
163                }
164
165                pub fn builder($($required_field_id: $required_field_ty),*) -> <Self as $zalsa_struct::HasBuilder>::Builder
166                {
167                    builder::new_builder($($zalsa::maybe_default!($field_option, $field_ty, $field_id,)),*)
168                }
169
170                $(
171                    $field_getter_vis fn $field_getter_id<'db, $Db>(self, db: &'db $Db) -> $zalsa::maybe_cloned_ty!($field_option, 'db, $field_ty)
172                    where
173                        // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
174                        $Db: ?Sized + $zalsa::Database,
175                    {
176                        let fields = $Configuration::ingredient(db.as_dyn_database()).field(
177                            db.as_dyn_database(),
178                            self,
179                            $field_index,
180                        );
181                        $zalsa::maybe_clone!(
182                            $field_option,
183                            $field_ty,
184                            &fields.$field_index,
185                        )
186                    }
187                )*
188
189                $(
190                    #[must_use]
191                    $field_setter_vis fn $field_setter_id<'db, $Db>(self, db: &'db mut $Db) -> impl salsa::Setter<FieldTy = $field_ty> + 'db
192                    where
193                        // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
194                        $Db: ?Sized + $zalsa::Database,
195                    {
196                        let (ingredient, revision) = $Configuration::ingredient_mut(db.as_dyn_database_mut());
197                        $zalsa::input::SetterImpl::new(
198                            revision,
199                            self,
200                            $field_index,
201                            ingredient,
202                            |fields, f| std::mem::replace(&mut fields.$field_index, f),
203                        )
204                    }
205                )*
206
207                $zalsa::macro_if! { $is_singleton =>
208                    pub fn try_get<$Db>(db: &$Db) -> Option<Self>
209                    where
210                        // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
211                        $Db: ?Sized + salsa::Database,
212                    {
213                        $Configuration::ingredient(db.as_dyn_database()).get_singleton_input(db)
214                    }
215
216                    #[track_caller]
217                    pub fn get<$Db>(db: &$Db) -> Self
218                    where
219                        // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
220                        $Db: ?Sized + salsa::Database,
221                    {
222                        Self::try_get(db).unwrap()
223                    }
224                }
225
226                /// Default debug formatting for this struct (may be useful if you define your own `Debug` impl)
227                pub fn default_debug_fmt(this: Self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
228                where
229                    // rustc rejects trivial bounds, but it cannot see through higher-ranked bounds
230                    // with its check :^)
231                    $(for<'__trivial_bounds> $field_ty: std::fmt::Debug),*
232                {
233                    $zalsa::with_attached_database(|db| {
234                        let fields = $Configuration::ingredient(db).leak_fields(db, this);
235                        let mut f = f.debug_struct(stringify!($Struct));
236                        let f = f.field("[salsa id]", &$zalsa::AsId::as_id(&this));
237                        $(
238                            let f = f.field(stringify!($field_id), &fields.$field_index);
239                        )*
240                        f.finish()
241                    }).unwrap_or_else(|| {
242                        f.debug_struct(stringify!($Struct))
243                            .field("[salsa id]", &this.0)
244                            .finish()
245                    })
246                }
247            }
248
249            impl $zalsa_struct::HasBuilder for $Struct {
250                type Builder = builder::$Builder;
251            }
252
253            // Implement `new` here instead of inside the builder module
254            // because $Configuration can't be named in `builder`.
255            impl builder::$Builder {
256                /// Creates the new input with the set values.
257                #[must_use]
258                pub fn new<$Db>(self, db: &$Db) -> $Struct
259                where
260                    // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
261                    $Db: ?Sized + salsa::Database
262                {
263                    let current_revision = $zalsa::current_revision(db);
264                    let ingredient = $Configuration::ingredient(db.as_dyn_database());
265                    let (fields, stamps) = builder::builder_into_inner(self, current_revision);
266                    ingredient.new_input(db.as_dyn_database(), fields, stamps)
267                }
268            }
269
270            mod builder {
271                use super::*;
272
273                use salsa::plumbing as $zalsa;
274                use $zalsa::input as $zalsa_struct;
275
276                // These are standalone functions instead of methods on `Builder` to prevent
277                // that the enclosing module can call them.
278                pub(super) fn new_builder($($field_id: $field_ty),*) -> $Builder {
279                    $Builder {
280                        fields: ($($field_id,)*),
281                        durabilities: [salsa::Durability::default(); $N],
282                    }
283                }
284
285                pub(super) fn builder_into_inner(builder: $Builder, revision: $zalsa::Revision) -> (($($field_ty,)*), $zalsa::Array<$zalsa::Stamp, $N>) {
286                    let stamps = $zalsa::Array::new([
287                        $($zalsa::stamp(revision, builder.durabilities[$field_index])),*
288                    ]);
289
290                    (builder.fields, stamps)
291                }
292
293                #[must_use]
294                pub struct $Builder {
295                    /// The field values.
296                    fields: ($($field_ty,)*),
297
298                    /// The durabilities per field.
299                    durabilities: [salsa::Durability; $N],
300                }
301
302                impl $Builder {
303                    /// Sets the durability of all fields.
304                    ///
305                    /// Overrides any previously set durabilities.
306                    pub fn durability(mut self, durability: salsa::Durability) -> Self {
307                        self.durabilities = [durability; $N];
308                        self
309                    }
310
311                    $($zalsa::maybe_default_tt! { $field_option =>
312                        /// Sets the value of the field `$field_id`.
313                        #[must_use]
314                        pub fn $field_id(mut self, value: $field_ty) -> Self
315                        {
316                            self.fields.$field_index = value;
317                            self
318                        }
319                    })*
320
321                    $(
322                        /// Sets the durability for the field `$field_id`.
323                        #[must_use]
324                        pub fn $field_durability_id(mut self, durability: salsa::Durability) -> Self
325                        {
326                            self.durabilities[$field_index] = durability;
327                            self
328                        }
329                    )*
330                }
331            }
332        };
333    };
334}