Debian Codegraph @

src/setup_tracked_fn.rs

raw symbols SCIP
1 /// Macro for setting up a function that must intern its arguments.
2 #[macro_export]
3 macro_rules! setup_tracked_fn {
4 (
5 // Attributes on the function
6 attrs: [$(#[$attr:meta]),*],
7
8 // Visibility of the function
9 vis: $vis:vis,
10
11 // Name of the function
12 fn_name: $fn_name:ident,
13
14 // Name of the `'db` lifetime that the user gave; if they didn't, then defaults to `'db`
15 db_lt: $db_lt:lifetime,
16
17 // Path to the database trait that the user's database parameter used
18 Db: $Db:path,
19
20 // Name of the database parameter given by the user.
21 db: $db:ident,
22
23 // An identifier for each function argument EXCEPT the database.
24 // We prefer to use the identifier the user gave, but if the user gave a pattern
25 // (e.g., `(a, b): (u32, u32)`) we will synthesize an identifier.
26 input_ids: [$($input_id:ident),*],
27
28 // Types of the function arguments (may reference `$generics`).
29 input_tys: [$($input_ty:ty),*],
30
31 // Types of the function arguments as should be put in interned struct.
32 interned_input_tys: [$($interned_input_ty:ty),*],
33
34 // Return type of the function (may reference `$generics`).
35 output_ty: $output_ty:ty,
36
37 // Function body, may reference identifiers defined in `$input_pats` and the generics from `$generics`
38 inner_fn: {$($inner_fn:tt)*},
39
40 // Path to the cycle recovery function to use.
41 cycle_recovery_fn: ($($cycle_recovery_fn:tt)*),
42
43 // Path to function to get the initial value to use for cycle recovery.
44 cycle_recovery_initial: ($($cycle_recovery_initial:tt)*),
45
46 // Name of cycle recovery strategy variant to use.
47 cycle_recovery_strategy: $cycle_recovery_strategy:ident,
48
49 // If true, this is specifiable.
50 is_specifiable: $is_specifiable:tt,
51
52 // Equality check strategy function
53 values_equal: {$($values_equal:tt)+},
54
55 // If true, the input needs an interner (because it has >1 argument).
56 needs_interner: $needs_interner:tt,
57
58 // The function used to implement `C::heap_size`.
59 heap_size_fn: $($heap_size_fn:path)?,
60
61 // The eviction policy type for this function
62 eviction: $Eviction:ty,
63
64 // LRU capacity (a literal, maybe 0)
65 lru: $lru:tt,
66
67 // The return mode for the function, see `salsa_macros::options::Option::returns`
68 return_mode: $return_mode:tt,
69
70 // If true, the input and output values implement `serde::{Serialize, Deserialize}`.
71 persist: $persist:tt,
72
73 assert_interned_inputs_are_salsa_values: {$($assert_interned_inputs_are_salsa_values:tt)*},
74
75 assert_output_is_salsa_value_or_static: {$($assert_output_is_salsa_value_or_static:tt)*},
76
77 $(self_ty: $self_ty:ty,)?
78
79 // Annoyingly macro-rules hygiene does not extend to items defined in the macro.
80 // We have the procedural macro generate names for those items that are
81 // not used elsewhere in the user's code.
82 unused_names: [
83 $zalsa:ident,
84 $Configuration:ident,
85 $InternedData:ident,
86 $FN_CACHE:ident,
87 $INTERN_CACHE:ident,
88 $inner:ident,
89 ]
90 ) => {
91 // Suppress this clippy lint because we sometimes require `'db` where the ordinary Rust rules would not.
92 #[allow(clippy::needless_lifetimes)]
93 $(#[$attr])*
94 $vis fn $fn_name<$db_lt>(
95 $db: &$db_lt dyn $Db,
96 $($input_id: $input_ty,)*
97 ) -> ::salsa::plumbing::return_mode_ty!(($return_mode, __), $db_lt, $output_ty) {
98 use ::salsa::plumbing as $zalsa;
99
100 $zalsa::attach($db, || {
101 let (zalsa, zalsa_local) = $db.zalsas();
102 let result = $zalsa::macro_if! {
103 if $needs_interner {
104 {
105 let key = $fn_name::intern_ingredient_(zalsa).intern_id(zalsa, zalsa_local, ($($input_id),*), |_, data| data);
106 $fn_name::fn_ingredient_($db, zalsa).fetch($db, zalsa, zalsa_local, key)
107 }
108 } else {
109 {
110 $fn_name::fn_ingredient_($db, zalsa).fetch($db, zalsa, zalsa_local, $zalsa::AsId::as_id(&($($input_id),*)))
111 }
112 }
113 };
114
115 $zalsa::return_mode_expression!(($return_mode, __), $output_ty, result,)
116 })
117 }
118
119 // The module needs be last in the macro expansion in order to make the tracked
120 // function's ident be identified as a function, not a struct, during semantic highlighting.
121 // for more details, see https://github.com/salsa-rs/salsa/pull/612.
122 #[doc(hidden)]
123 #[allow(non_camel_case_types)]
124 $vis struct $fn_name {
125 _priv: ::std::convert::Infallible,
126 }
127
128 const _: () = {
129 use ::salsa::plumbing as $zalsa;
130
131 struct $Configuration;
132
133 $zalsa::register_jar! {
134 $zalsa::ErasedJar::erase::<$fn_name>()
135 }
136
137 impl $zalsa::HasJar for $fn_name {
138 type Jar = $fn_name;
139 const KIND: $zalsa::JarKind = $zalsa::JarKind::TrackedFn;
140 }
141
142 static $FN_CACHE: $zalsa::IngredientCache<$zalsa::function::IngredientImpl<$Configuration>> =
143 $zalsa::IngredientCache::new();
144
145 $zalsa::macro_if! {
146 if $needs_interner {
147 #[allow(unused_lifetimes)]
148 fn _assert_interned_inputs_are_salsa_values<$db_lt>() {
149 use $zalsa::{SalsaValueDispatch, SalsaValueFallback as _};
150 $($assert_interned_inputs_are_salsa_values)*
151 }
152 let _ = _assert_interned_inputs_are_salsa_values;
153
154 #[derive(Copy, Clone)]
155 struct $InternedData<$db_lt>(
156 ::salsa::Id,
157 ::std::marker::PhantomData<fn() -> &$db_lt ()>,
158 );
159
160 static $INTERN_CACHE: $zalsa::IngredientCache<$zalsa::interned::IngredientImpl<$Configuration>> =
161 $zalsa::IngredientCache::new();
162
163 impl $zalsa::SalsaStructInDb for $InternedData<'_> {
164 type MemoIngredientMap = $zalsa::MemoIngredientSingletonIndex;
165 const LEAF_TYPE_IDS: &'static [$zalsa::ConstTypeId] = &[$zalsa::ConstTypeId::of::<$InternedData>()];
166
167 fn lookup_ingredient_index(aux: &$zalsa::Zalsa) -> $zalsa::IngredientIndices {
168 $zalsa::IngredientIndices::empty()
169 }
170
171 fn entries(
172 zalsa: &$zalsa::Zalsa
173 ) -> impl Iterator<Item = $zalsa::DatabaseKeyIndex> + '_ {
174 let ingredient_index = zalsa.lookup_jar_by_type::<$fn_name>().successor(0);
175 <$Configuration>::intern_ingredient(zalsa).entries(zalsa).map(|entry| entry.key())
176 }
177
178 #[inline]
179 fn cast(id: $zalsa::Id, type_id: ::core::any::TypeId) -> Option<Self> {
180 if type_id == ::core::any::TypeId::of::<$InternedData>() {
181 Some($InternedData(id, ::core::marker::PhantomData))
182 } else {
183 None
184 }
185 }
186
187 #[inline]
188 unsafe fn memo_table(
189 zalsa: &$zalsa::Zalsa,
190 id: $zalsa::Id,
191 current_revision: $zalsa::Revision,
192 ) -> $zalsa::MemoTableWithTypes<'_> {
193 // SAFETY: Guaranteed by caller.
194 unsafe { zalsa.table().memos::<$zalsa::interned::Value<$Configuration>>(id, current_revision) }
195 }
196 }
197
198 impl $zalsa::AsId for $InternedData<'_> {
199 #[inline]
200 fn as_id(&self) -> ::salsa::Id {
201 self.0
202 }
203 }
204
205 impl $zalsa::FromId for $InternedData<'_> {
206 #[inline]
207 fn from_id(id: ::salsa::Id) -> Self {
208 Self(id, ::core::marker::PhantomData)
209 }
210 }
211
212 // SAFETY: The generated assertions above prove every field
213 // can be retained after erasing the database lifetime.
214 unsafe impl $zalsa::interned::Configuration for $Configuration {
215 const LOCATION: $zalsa::Location = $zalsa::Location {
216 file: file!(),
217 line: line!(),
218 };
219 const DEBUG_NAME: &'static str = concat!($(stringify!($self_ty), "::",)? stringify!($fn_name), "::interned_arguments");
220 const PERSIST: bool = $persist;
221
222 type Fields<$db_lt> = ($($interned_input_ty),*);
223
224 type Struct<$db_lt> = $InternedData<$db_lt>;
225
226 fn serialize<S: $zalsa::serde::Serializer>(
227 fields: &Self::Fields<'_>,
228 serializer: S,
229 ) -> ::std::result::Result<S::Ok, S::Error> {
230 $zalsa::macro_if! {
231 if $persist {
232 $zalsa::serde::Serialize::serialize(fields, serializer)
233 } else {
234 panic!("attempted to serialize value not marked with `persist` attribute")
235 }
236 }
237 }
238
239 fn deserialize<'de, D: $zalsa::serde::Deserializer<'de>>(
240 deserializer: D,
241 ) -> ::std::result::Result<Self::Fields<'static>, D::Error> {
242 $zalsa::macro_if! {
243 if $persist {
244 $zalsa::serde::Deserialize::deserialize(deserializer)
245 } else {
246 panic!("attempted to deserialize value not marked with `persist` attribute")
247 }
248 }
249 }
250 }
251 } else {
252 type $InternedData<$db_lt> = ($($interned_input_ty),*);
253
254 $zalsa::macro_if! { $persist =>
255 const fn query_input_is_persistable<T>()
256 where
257 T: $zalsa::serde::Serialize + for<'de> $zalsa::serde::Deserialize<'de>,
258 {
259 }
260
261 fn assert_query_input_is_persistable<$db_lt>() {
262 query_input_is_persistable::<$($interned_input_ty),*>();
263 }
264 }
265 }
266 }
267
268 impl $Configuration {
269 fn fn_ingredient(db: &dyn $Db) -> &$zalsa::function::IngredientImpl<$Configuration> {
270 let zalsa = db.zalsa();
271 Self::fn_ingredient_(db, zalsa)
272 }
273
274 #[inline]
275 fn fn_ingredient_<'z>(db: &dyn $Db, zalsa: &'z $zalsa::Zalsa) -> &'z $zalsa::function::IngredientImpl<$Configuration> {
276 // SAFETY: `lookup_jar_by_type` returns a valid ingredient index, and the first
277 // ingredient created by our jar is the function ingredient.
278 unsafe {
279 $FN_CACHE.get_or_create::<$fn_name, 0>(zalsa)
280 }
281 .get_or_init(|| *<dyn $Db as $Db>::zalsa_register_downcaster(db))
282 }
283
284 pub fn fn_ingredient_mut(db: &mut dyn $Db) -> &mut $zalsa::function::IngredientImpl<Self> {
285 let view = *<dyn $Db as $Db>::zalsa_register_downcaster(db);
286 let zalsa_mut = db.zalsa_mut();
287 let index = zalsa_mut.lookup_jar_by_type::<$fn_name>();
288 let (ingredient, _) = zalsa_mut.lookup_ingredient_mut(index);
289 let ingredient = ingredient.assert_type_mut::<$zalsa::function::IngredientImpl<Self>>();
290 ingredient.get_or_init(|| view);
291 ingredient
292 }
293
294 $zalsa::macro_if! { $needs_interner =>
295 fn intern_ingredient(
296 zalsa: &$zalsa::Zalsa,
297 ) -> &$zalsa::interned::IngredientImpl<$Configuration> {
298 Self::intern_ingredient_(zalsa)
299 }
300
301 #[inline]
302 fn intern_ingredient_<'z>(
303 zalsa: &'z $zalsa::Zalsa
304 ) -> &'z $zalsa::interned::IngredientImpl<$Configuration> {
305 // SAFETY: `lookup_jar_by_type` returns a valid ingredient index, and the second
306 // ingredient created by our jar is the interned ingredient (given `needs_interner`).
307 unsafe {
308 $INTERN_CACHE.get_or_create::<$fn_name, 1>(zalsa)
309 }
310 }
311 }
312 }
313
314 $($assert_output_is_salsa_value_or_static)*
315
316 // SAFETY: The generated assertion above proves the output is either
317 // a `SalsaValue` or the same `'static` type for every database lifetime.
318 // `unsafe(non_salsa_values)` makes this guarantee the caller's responsibility.
319 unsafe impl $zalsa::function::Configuration for $Configuration {
320 const LOCATION: $zalsa::Location = $zalsa::Location {
321 file: file!(),
322 line: line!(),
323 };
324 const DEBUG_NAME: &'static str = concat!($(stringify!($self_ty), "::", )? stringify!($fn_name));
325 const PERSIST: bool = $persist;
326
327 type DbView = dyn $Db;
328
329 type SalsaStruct<$db_lt> = $InternedData<$db_lt>;
330
331 type Input<$db_lt> = ($($interned_input_ty),*);
332
333 type Output<$db_lt> = $output_ty;
334
335 type Eviction = $Eviction;
336
337 const CYCLE_STRATEGY: $zalsa::CycleRecoveryStrategy = $zalsa::CycleRecoveryStrategy::$cycle_recovery_strategy;
338
339 $($values_equal)+
340
341 $(
342 fn heap_size(value: &Self::Output<'_>) -> Option<usize> {
343 Some($heap_size_fn(value))
344 }
345 )?
346
347 fn execute<$db_lt>($db: &$db_lt Self::DbView, ($($input_id),*): ($($interned_input_ty),*)) -> Self::Output<$db_lt> {
348 $($inner_fn)*
349
350 $inner($db, $($input_id),*)
351 }
352
353 fn cycle_initial<$db_lt>(db: &$db_lt Self::DbView, id: ::salsa::Id, ($($input_id),*): ($($interned_input_ty),*)) -> Self::Output<$db_lt> {
354 $($cycle_recovery_initial)*(db, id, $($input_id),*)
355 }
356
357 fn recover_from_cycle<$db_lt>(
358 db: &$db_lt dyn $Db,
359 cycle: &::salsa::Cycle,
360 last_provisional_value: &Self::Output<$db_lt>,
361 value: Self::Output<$db_lt>,
362 ($($input_id),*): ($($interned_input_ty),*)
363 ) -> Self::Output<$db_lt> {
364 $($cycle_recovery_fn)*(db, cycle, last_provisional_value, value, $($input_id),*)
365 }
366
367 fn id_to_input<$db_lt>(zalsa: &$db_lt $zalsa::Zalsa, key: ::salsa::Id) -> Self::Input<$db_lt> {
368 $zalsa::macro_if! {
369 if $needs_interner {
370 $Configuration::intern_ingredient_(zalsa).data(zalsa, key).clone()
371 } else {
372 $zalsa::FromIdWithDb::from_id(key, zalsa)
373 }
374 }
375 }
376
377 fn serialize<S: $zalsa::serde::Serializer>(
378 value: &Self::Output<'_>,
379 serializer: S,
380 ) -> ::std::result::Result<S::Ok, S::Error> {
381 $zalsa::macro_if! {
382 if $persist {
383 $zalsa::serde::Serialize::serialize(value, serializer)
384 } else {
385 panic!("attempted to serialize value not marked with `persist` attribute")
386 }
387 }
388 }
389
390 fn deserialize<'de, D: $zalsa::serde::Deserializer<'de>>(
391 deserializer: D,
392 ) -> ::std::result::Result<Self::Output<'static>, D::Error> {
393 $zalsa::macro_if! {
394 if $persist {
395 $zalsa::serde::Deserialize::deserialize(deserializer)
396 } else {
397 panic!("attempted to deserialize value not marked with `persist` attribute")
398 }
399 }
400 }
401 }
402
403 impl $zalsa::Jar for $fn_name {
404 fn create_ingredients(
405 zalsa: &mut $zalsa::Zalsa,
406 first_index: $zalsa::IngredientIndex,
407 ) -> Vec<Box<dyn $zalsa::Ingredient>> {
408 let struct_index: $zalsa::IngredientIndices = $zalsa::macro_if! {
409 if $needs_interner {
410 first_index.successor(0).into()
411 } else {
412 // Note that struct ingredients are created before tracked functions,
413 // so this cannot panic.
414 <$InternedData as $zalsa::SalsaStructInDb>::lookup_ingredient_index(zalsa)
415 }
416 };
417
418 $zalsa::macro_if! { $needs_interner =>
419 let mut intern_ingredient = <$zalsa::interned::IngredientImpl<$Configuration>>::new(
420 first_index.successor(0)
421 );
422 }
423
424 let intern_ingredient_memo_types = $zalsa::macro_if! {
425 if $needs_interner {
426 Some($zalsa::Ingredient::memo_table_types_mut(&mut intern_ingredient))
427 } else {
428 None
429 }
430 };
431 // SAFETY: We call with the correct memo types.
432 let memo_ingredient_indices = unsafe {
433 $zalsa::NewMemoIngredientIndices::create(
434 zalsa,
435 struct_index,
436 first_index,
437 $zalsa::function::MemoEntryType::of::<$zalsa::function::Memo<$Configuration>>(),
438 intern_ingredient_memo_types,
439 )
440 };
441
442 let fn_ingredient = <$zalsa::function::IngredientImpl<$Configuration>>::new(
443 first_index,
444 memo_ingredient_indices,
445 $lru,
446 );
447 $zalsa::macro_if! {
448 if $needs_interner {
449 vec![
450 Box::new(fn_ingredient),
451 Box::new(intern_ingredient),
452 ]
453 } else {
454 vec![
455 Box::new(fn_ingredient),
456 ]
457 }
458 }
459 }
460
461 fn id_struct_type_id() -> $zalsa::TypeId {
462 $zalsa::TypeId::of::<$InternedData<'static>>()
463 }
464 }
465
466 impl $fn_name {
467 $zalsa::gate_accumulated! {
468 pub fn accumulated<$db_lt, A: ::salsa::Accumulator>(
469 $db: &$db_lt dyn $Db,
470 $($input_id: $interned_input_ty,)*
471 ) -> Vec<&$db_lt A> {
472 use ::salsa::plumbing as $zalsa;
473 let key = $zalsa::macro_if! {
474 if $needs_interner {{
475 let (zalsa, zalsa_local) = $db.zalsas();
476 $Configuration::intern_ingredient(zalsa).intern_id(zalsa, zalsa_local, ($($input_id),*), |_, data| data)
477 }} else {
478 $zalsa::AsId::as_id(&($($input_id),*))
479 }
480 };
481
482 $Configuration::fn_ingredient($db).accumulated_by::<A>($db, key)
483 }
484 }
485
486 $zalsa::macro_if! { $is_specifiable =>
487 pub fn specify<$db_lt>(
488 $db: &$db_lt dyn $Db,
489 $($input_id: $interned_input_ty,)*
490 value: $output_ty,
491 ) {
492 let key = $zalsa::AsId::as_id(&($($input_id),*));
493 $Configuration::fn_ingredient($db).specify_and_record(
494 $db,
495 key,
496 value,
497 )
498 }
499 }
500
501 /// Sets the lru capacity
502 ///
503 /// **WARNING:** Just like an ordinary write, this method triggers
504 /// cancellation. If you invoke it while a snapshot exists, it
505 /// will block until that snapshot is dropped -- if that snapshot
506 /// is owned by the current thread, this could trigger deadlock.
507 fn set_lru_capacity(db: &mut dyn $Db, value: usize) where for<'trivial_bounds> $Eviction: $zalsa::function::HasCapacity {
508 $Configuration::fn_ingredient_mut(db).set_capacity(value);
509 }
510
511 $zalsa::macro_if! { $needs_interner =>
512 #[inline]
513 fn intern_ingredient_(
514 zalsa: &$zalsa::Zalsa,
515 ) -> &$zalsa::interned::IngredientImpl<$Configuration> {
516 $Configuration::intern_ingredient_(zalsa)
517 }
518 }
519
520 #[inline]
521 fn fn_ingredient_<'z>(db: &dyn $Db, zalsa: &'z $zalsa::Zalsa) -> &'z $zalsa::function::IngredientImpl<$Configuration> {
522 $Configuration::fn_ingredient_(db, zalsa)
523 }
524 }
525 };
526 };
527 }