Debian Codegraph @

src/setup_interned_struct.rs

raw symbols SCIP
1 /// Macro for setting up a function that must intern its arguments.
2 #[macro_export]
3 macro_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 fn hash<H: ::std::hash::Hasher>(&self, h: &mut H) {
143 $($zalsa::HashEqLike::<$indexed_ty>::hash(&self.$field_index, &mut *h);)*
144 }
145
146 fn eq(&self, data: &StructKey<$db_lt, $($indexed_ty),*>) -> bool {
147 ($($zalsa::HashEqLike::<$indexed_ty>::eq(&self.$field_index, &data.$field_index) && )* true)
148 }
149 }
150
151 impl<$db_lt, $($indexed_ty: $zalsa::Lookup<$field_ty>),*> $zalsa::Lookup<$StructDataIdent<$db_lt>>
152 for StructKey<$db_lt, $($indexed_ty),*> {
153
154 #[allow(unused_unit)]
155 fn into_owned(self) -> $StructDataIdent<$db_lt> {
156 ($($zalsa::Lookup::into_owned(self.$field_index),)*)
157 }
158 }
159
160 // SAFETY: The generated assertions above prove every field can be
161 // retained after erasing the database lifetime.
162 unsafe impl $zalsa::interned::Configuration for $StructWithStatic {
163 const LOCATION: $zalsa::Location = $zalsa::Location {
164 file: file!(),
165 line: line!(),
166 };
167 const DEBUG_NAME: &'static str = stringify!($Struct);
168 const PERSIST: bool = $persist;
169
170 $(
171 const REVISIONS: ::core::num::NonZeroUsize = ::core::num::NonZeroUsize::new($revisions).unwrap();
172 )?
173
174 type Fields<'a> = $StructDataIdent<'a>;
175 type Struct<'db> = $Struct< $($db_lt_arg)? >;
176
177 $(
178 fn heap_size(value: &Self::Fields<'_>) -> Option<usize> {
179 Some($heap_size_fn(value))
180 }
181 )?
182
183 fn serialize<S: $zalsa::serde::Serializer>(
184 fields: &Self::Fields<'_>,
185 serializer: S,
186 ) -> ::std::result::Result<S::Ok, S::Error> {
187 $zalsa::macro_if! {
188 if $persist {
189 $($serialize_fn(fields, serializer))?
190 } else {
191 panic!("attempted to serialize value not marked with `persist` attribute")
192 }
193 }
194 }
195
196 fn deserialize<'de, D: $zalsa::serde::Deserializer<'de>>(
197 deserializer: D,
198 ) -> ::std::result::Result<Self::Fields<'static>, D::Error> {
199 $zalsa::macro_if! {
200 if $persist {
201 $($deserialize_fn(deserializer))?
202 } else {
203 panic!("attempted to deserialize value not marked with `persist` attribute")
204 }
205 }
206 }
207 }
208
209 impl $Configuration {
210 pub fn ingredient(zalsa: &$zalsa::Zalsa) -> &$zalsa_struct::IngredientImpl<Self> {
211 static CACHE: $zalsa::IngredientCache<$zalsa_struct::IngredientImpl<$Configuration>> =
212 $zalsa::IngredientCache::new();
213
214 // SAFETY: `lookup_jar_by_type` returns a valid ingredient index, and the only
215 // ingredient created by our jar is the struct ingredient.
216 unsafe {
217 CACHE.get_or_create::<$zalsa_struct::JarImpl<$Configuration>, 0>(zalsa)
218 }
219 }
220 }
221
222 impl< $($db_lt_arg)? > $zalsa::AsId for $Struct< $($db_lt_arg)? > {
223 fn as_id(&self) -> ::salsa::Id {
224 self.0.as_id()
225 }
226 }
227
228 impl< $($db_lt_arg)? > $zalsa::FromId for $Struct< $($db_lt_arg)? > {
229 fn from_id(id: ::salsa::Id) -> Self {
230 Self(<$Id>::from_id(id), ::std::marker::PhantomData)
231 }
232 }
233
234 unsafe impl< $($db_lt_arg)? > Send for $Struct< $($db_lt_arg)? > {}
235
236 unsafe impl< $($db_lt_arg)? > Sync for $Struct< $($db_lt_arg)? > {}
237
238 $zalsa::macro_if! { $generate_debug_impl =>
239 impl< $($db_lt_arg)? > ::std::fmt::Debug for $Struct< $($db_lt_arg)? > {
240 fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
241 Self::default_debug_fmt(*self, f)
242 }
243 }
244 }
245
246 impl< $($db_lt_arg)? > $zalsa::SalsaStructInDb for $Struct< $($db_lt_arg)? > {
247 type MemoIngredientMap = $zalsa::MemoIngredientSingletonIndex;
248 const LEAF_TYPE_IDS: &'static [$zalsa::ConstTypeId] = &[$zalsa::ConstTypeId::of::<$Struct>()];
249
250 fn lookup_ingredient_index(aux: &$zalsa::Zalsa) -> $zalsa::IngredientIndices {
251 aux.lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>().into()
252 }
253
254 fn entries(
255 zalsa: &$zalsa::Zalsa
256 ) -> impl Iterator<Item = $zalsa::DatabaseKeyIndex> + '_ {
257 let ingredient_index = zalsa.lookup_jar_by_type::<$zalsa_struct::JarImpl<$Configuration>>();
258 <$Configuration>::ingredient(zalsa).entries(zalsa).map(|entry| entry.key())
259 }
260
261 #[inline]
262 fn cast(id: $zalsa::Id, type_id: $zalsa::TypeId) -> $zalsa::Option<Self> {
263 if type_id == $zalsa::TypeId::of::<$Struct>() {
264 $zalsa::Some(<$Struct as $zalsa::FromId>::from_id(id))
265 } else {
266 $zalsa::None
267 }
268 }
269
270 #[inline]
271 unsafe fn memo_table(
272 zalsa: &$zalsa::Zalsa,
273 id: $zalsa::Id,
274 current_revision: $zalsa::Revision,
275 ) -> $zalsa::MemoTableWithTypes<'_> {
276 // SAFETY: Guaranteed by caller.
277 unsafe { zalsa.table().memos::<$zalsa_struct::Value<$Configuration>>(id, current_revision) }
278 }
279 }
280
281 $zalsa::macro_if! { $persist =>
282 impl<$($db_lt_arg)?> $zalsa::serde::Serialize for $Struct<$($db_lt_arg)?> {
283 fn serialize<S>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
284 where
285 S: $zalsa::serde::Serializer,
286 {
287 $zalsa::serde::Serialize::serialize(&$zalsa::AsId::as_id(self), serializer)
288 }
289 }
290
291 impl<'de, $($db_lt_arg)?> $zalsa::serde::Deserialize<'de> for $Struct<$($db_lt_arg)?> {
292 fn deserialize<D>(deserializer: D) -> ::std::result::Result<Self, D::Error>
293 where
294 D: $zalsa::serde::Deserializer<'de>,
295 {
296 let id = $zalsa::Id::deserialize(deserializer)?;
297 Ok($zalsa::FromId::from_id(id))
298 }
299 }
300 }
301
302
303 unsafe impl< $($db_lt_arg)? > $zalsa::SalsaValue for $Struct< $($db_lt_arg)? > {}
304
305 impl<$db_lt> $Struct< $($db_lt_arg)? > {
306 pub fn $new_fn<$Db, $($indexed_ty: $zalsa::Lookup<$field_ty> + ::std::hash::Hash,)*>(db: &$db_lt $Db, $($field_id: $indexed_ty),*) -> Self
307 where
308 // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
309 $Db: ?Sized + ::salsa::Database,
310 $(
311 $field_ty: $zalsa::HashEqLike<$indexed_ty>,
312 )*
313 {
314 let (zalsa, zalsa_local) = db.zalsas();
315 $Configuration::ingredient(zalsa).intern(zalsa, zalsa_local,
316 StructKey::<$db_lt>($($field_id,)* ::std::marker::PhantomData::default()), |_, data| $zalsa::Lookup::into_owned(data))
317 }
318
319 $(
320 $(#[$field_attr])*
321 $field_getter_vis fn $field_getter_id<$Db>(self, db: &'db $Db) -> $zalsa::return_mode_ty!($field_option, 'db, $field_ty)
322 where
323 // FIXME(rust-lang/rust#65991): The `db` argument *should* have the type `dyn Database`
324 $Db: ?Sized + $zalsa::Database,
325 {
326 let zalsa = db.zalsa();
327 let fields = $Configuration::ingredient(zalsa).fields(zalsa, self);
328 $zalsa::return_mode_expression!(
329 $field_option,
330 $field_ty,
331 &fields.$field_index,
332 )
333 }
334 )*
335 }
336
337 // Duplication can be dropped here once we no longer allow the `no_lifetime` hack
338 $zalsa::macro_if! {
339 iftt ($($db_lt_arg)?) {
340 impl $Struct<'_> {
341 /// Default debug formatting for this struct (may be useful if you define your own `Debug` impl)
342 pub fn default_debug_fmt(this: Self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
343 where
344 // rustc rejects trivial bounds, but it cannot see through higher-ranked bounds
345 // with its check :^)
346 $(for<$db_lt> $field_ty: ::std::fmt::Debug),*
347 {
348 $zalsa::with_attached_database(|db| {
349 let zalsa = db.zalsa();
350 let fields = $Configuration::ingredient(zalsa).fields(zalsa, this);
351 let mut f = f.debug_struct(stringify!($Struct));
352 $(
353 let f = f.field(stringify!($field_id), &fields.$field_index);
354 )*
355 f.finish()
356 }).unwrap_or_else(|| {
357 f.debug_tuple(stringify!($Struct))
358 .field(&$zalsa::AsId::as_id(&this))
359 .finish()
360 })
361 }
362 }
363 } else {
364 impl $Struct {
365 /// Default debug formatting for this struct (may be useful if you define your own `Debug` impl)
366 pub fn default_debug_fmt(this: Self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
367 where
368 // rustc rejects trivial bounds, but it cannot see through higher-ranked bounds
369 // with its check :^)
370 $(for<$db_lt> $field_ty: ::std::fmt::Debug),*
371 {
372 $zalsa::with_attached_database(|db| {
373 let zalsa = db.zalsa();
374 let fields = $Configuration::ingredient(zalsa).fields(zalsa, this);
375 let mut f = f.debug_struct(stringify!($Struct));
376 $(
377 let f = f.field(stringify!($field_id), &fields.$field_index);
378 )*
379 f.finish()
380 }).unwrap_or_else(|| {
381 f.debug_tuple(stringify!($Struct))
382 .field(&$zalsa::AsId::as_id(&this))
383 .finish()
384 })
385 }
386 }
387 }
388 }
389 };
390 };
391 }