peace_params 0.0.15

Constraints and specifications for parameters for the peace automation framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use std::{
    fmt::{self, Debug},
    marker::PhantomData,
};

use peace_data::marker::{ApplyDry, Clean, Current, Goal};
use peace_resource_rt::{resources::ts::SetUp, BorrowFail, Resources};
use serde::{Deserialize, Serialize, Serializer};

use crate::{
    FromFunc, Func, MappingFn, ParamsResolveError, ValueResolutionCtx, ValueResolutionMode,
};

#[cfg(feature = "item_state_example")]
use peace_data::marker::Example;

/// Wrapper around a mapping function so that it can be serialized.
#[derive(Clone, Serialize, Deserialize)]
pub struct MappingFnImpl<T, F, Args> {
    /// This field's name within its parent struct.
    ///
    /// `None` if this is the top level value type.
    field_name: Option<String>,
    #[serde(
        default = "MappingFnImpl::<T, F, Args>::fn_map_none",
        skip_deserializing,
        serialize_with = "MappingFnImpl::<T, F, Args>::fn_map_serialize"
    )]
    fn_map: Option<F>,
    /// Marker.
    marker: PhantomData<(T, Args)>,
}

impl<T, F, Args> Debug for MappingFnImpl<T, F, Args>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MappingFnImpl")
            .field("field_name", &self.field_name)
            .field("fn_map", &Self::fn_map_stringify(&self.fn_map))
            .field("marker", &self.marker)
            .finish()
    }
}

impl<T, F, Args> MappingFnImpl<T, F, Args> {
    fn fn_map_serialize<S>(fn_map: &Option<F>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&Self::fn_map_stringify(fn_map))
    }

    fn fn_map_stringify(fn_map: &Option<F>) -> String {
        match fn_map {
            Some(_) => {
                let args = {
                    let args_type_name = tynm::type_name::<Args>();
                    let mut buffer = String::with_capacity(args_type_name.len() + 32);
                    args_type_name.chars().fold(0, |mut nesting_level, c| {
                        buffer.push(c);

                        match c {
                            '(' => {
                                nesting_level += 1;
                                if nesting_level == 1 {
                                    buffer.push('&');
                                }
                            }
                            ')' => nesting_level -= 1,
                            ' ' => {
                                if nesting_level == 1 {
                                    buffer.push('&');
                                }
                            }
                            _ => (),
                        }

                        nesting_level
                    });

                    buffer
                };

                format!(
                    "Some(Fn{args} -> Option<{t}>)",
                    t = tynm::type_name::<T>(),
                    args = args,
                )
            }
            None => String::from("None"),
        }
    }

    fn fn_map_none() -> Option<F> {
        None
    }
}

macro_rules! impl_mapping_fn_impl {
    ($($Arg:ident $var:ident),+) => {
        // impl<T, F, A0> MappingFnImpl<T, F, (A0,)>
        impl<T, F, $($Arg,)+> MappingFnImpl<T, F, ($($Arg,)+)>
        where
            T: Clone + Debug + Send + Sync + 'static,
            F: Fn($(&$Arg,)+) -> Option<T> + Clone + Send + Sync + 'static,
            $($Arg: Clone + Debug + Send + Sync + 'static,)+
        {
            pub fn new(field_name: Option<String>, fn_map: F) -> Self {
                Self {
                    fn_map: Some(fn_map),
                    field_name,
                    marker: PhantomData,
                }
            }

            pub fn map(
                &self,
                resources: &Resources<SetUp>,
                value_resolution_ctx: &mut ValueResolutionCtx,
            ) -> Result<T, ParamsResolveError> {
                let fn_map = self.fn_map.as_ref().unwrap_or_else(
                    #[cfg_attr(coverage_nightly, coverage(off))]
                    || {
                        panic!("`MappingFnImpl::map` called when `fn_map` is `None`\
                            {for_field_name}.\n\
                            This is a bug in the Peace framework.\n\
                            \n\
                            Type parameters are:\n\
                            \n\
                            * `T`: {t}\n\
                            * `Args`: ({Args})\n\
                            ",
                            for_field_name = self.field_name
                                .as_ref()
                                .map(|field_name| format!(" for field: `{field_name}`"))
                                .unwrap_or("".to_string()),
                            t = tynm::type_name::<T>(),
                            Args = tynm::type_name::<($($Arg,)+)>(),
                        );
                    });

                // We have to duplicate code because the return type from
                // `resources.try_borrow` is different per branch.
                match value_resolution_ctx.value_resolution_mode() {
                    #[cfg(feature = "item_state_example")]
                    ValueResolutionMode::Example => {
                        $(arg_resolve!(resources, value_resolution_ctx, Example, $var, $Arg);)+

                        fn_map($(&$var,)+).ok_or(ParamsResolveError::FromMap {
                            value_resolution_ctx: value_resolution_ctx.clone(),
                            from_type_name: tynm::type_name::<($($Arg,)+)>(),
                        })
                    }
                    ValueResolutionMode::Clean => {
                        $(arg_resolve!(resources, value_resolution_ctx, Clean, $var, $Arg);)+

                        fn_map($(&$var,)+).ok_or(ParamsResolveError::FromMap {
                            value_resolution_ctx: value_resolution_ctx.clone(),
                            from_type_name: tynm::type_name::<($($Arg,)+)>(),
                        })
                    }
                    ValueResolutionMode::Current => {
                        $(arg_resolve!(resources, value_resolution_ctx, Current, $var, $Arg);)+

                        fn_map($(&$var,)+).ok_or(ParamsResolveError::FromMap {
                            value_resolution_ctx: value_resolution_ctx.clone(),
                            from_type_name: tynm::type_name::<($($Arg,)+)>(),
                        })
                    }
                    ValueResolutionMode::Goal => {
                        $(arg_resolve!(resources, value_resolution_ctx, Goal, $var, $Arg);)+

                        fn_map($(&$var,)+).ok_or(ParamsResolveError::FromMap {
                            value_resolution_ctx: value_resolution_ctx.clone(),
                            from_type_name: tynm::type_name::<($($Arg,)+)>(),
                        })
                    }
                    ValueResolutionMode::ApplyDry => {
                        $(arg_resolve!(resources, value_resolution_ctx, ApplyDry, $var, $Arg);)+

                        fn_map($(&$var,)+).ok_or(ParamsResolveError::FromMap {
                            value_resolution_ctx: value_resolution_ctx.clone(),
                            from_type_name: tynm::type_name::<($($Arg,)+)>(),
                        })
                    }
                }
            }

            pub fn try_map(
                &self,
                resources: &Resources<SetUp>,
                value_resolution_ctx: &mut ValueResolutionCtx,
            ) -> Result<Option<T>, ParamsResolveError> {
                let fn_map = self.fn_map.as_ref().unwrap_or_else(
                    #[cfg_attr(coverage_nightly, coverage(off))]
                    || {
                        panic!("`MappingFnImpl::try_map` called when `fn_map` is `None`\
                            {for_field_name}.\n\
                            This is a bug in the Peace framework.\n\
                            \n\
                            Type parameters are:\n\
                            \n\
                            * `T`: {t}\n\
                            * `Args`: ({Args})\n\
                            ",
                            for_field_name = self.field_name
                                .as_ref()
                                .map(|field_name| format!(" for field: `{field_name}`"))
                                .unwrap_or("".to_string()),
                            t = tynm::type_name::<T>(),
                            Args = tynm::type_name::<($($Arg,)+)>(),
                        );
                    });

                // We have to duplicate code because the return type from
                // `resources.try_borrow` is different per branch.
                match value_resolution_ctx.value_resolution_mode() {
                    #[cfg(feature = "item_state_example")]
                    ValueResolutionMode::Example => {
                        $(try_arg_resolve!(resources, value_resolution_ctx, Example, $var, $Arg);)+

                        Ok(fn_map($(&$var,)+))
                    }
                    ValueResolutionMode::Clean => {
                        $(try_arg_resolve!(resources, value_resolution_ctx, Clean, $var, $Arg);)+

                        Ok(fn_map($(&$var,)+))
                    }
                    ValueResolutionMode::Current => {
                        $(try_arg_resolve!(resources, value_resolution_ctx, Current, $var, $Arg);)+

                        Ok(fn_map($(&$var,)+))
                    }
                    ValueResolutionMode::Goal => {
                        $(try_arg_resolve!(resources, value_resolution_ctx, Goal, $var, $Arg);)+

                        Ok(fn_map($(&$var,)+))
                    }
                    ValueResolutionMode::ApplyDry => {
                        $(try_arg_resolve!(resources, value_resolution_ctx, ApplyDry, $var, $Arg);)+

                        Ok(fn_map($(&$var,)+))
                    }
                }
            }
        }

        impl<T, F, $($Arg,)+> FromFunc<F> for MappingFnImpl<T, F, ($($Arg,)+)>
        where
            T: Clone + Debug + Send + Sync + 'static,
            // Ideally we can do:
            //
            // ```rust
            // F: Fn<($($Arg,)+), Output = Option<T>>
            // ```
            //
            // But this is pending <rust-lang/rust#29625>
            F: Func<Option<T>, ($($Arg,)+)>
                + Fn($(&$Arg,)+) -> Option<T>
                + Clone + Send + Sync + 'static,
            $($Arg: Clone + Debug + Send + Sync + 'static,)+
        {
            fn from_func(field_name: Option<String>, f: F) -> Self {
                Self::new(field_name, f)
            }
        }

        impl<T, F, $($Arg,)+> From<(Option<String>, F)> for MappingFnImpl<T, F, ($($Arg,)+)>
        where
            T: Clone + Debug + Send + Sync + 'static,
            F: Fn($(&$Arg,)+) -> Option<T> + Clone + Send + Sync + 'static,
            $($Arg: Clone + Debug + Send + Sync + 'static,)+
        {
            fn from((field_name, f): (Option<String>, F)) -> Self {
                Self::new(field_name, f)
            }
        }

        impl<T, F, $($Arg,)+> MappingFn for MappingFnImpl<T, F, ($($Arg,)+)>
        where
            T: Clone + Debug + Send + Sync + 'static,
            F: Fn($(&$Arg,)+) -> Option<T> + Clone + Send + Sync + 'static,
            $($Arg: Clone + Debug + Send + Sync + 'static,)+
        {
            type Output = T;

            fn map(
                &self,
                resources: &Resources<SetUp>,
                value_resolution_ctx: &mut ValueResolutionCtx,
            ) -> Result<<Self as MappingFn>::Output, ParamsResolveError> {
                MappingFnImpl::<T, F, ($($Arg,)+)>::map(self, resources, value_resolution_ctx)
            }

            fn try_map(
                &self,
                resources: &Resources<SetUp>,
                value_resolution_ctx: &mut ValueResolutionCtx,
            ) -> Result<Option<<Self as MappingFn>::Output>, ParamsResolveError> {
                MappingFnImpl::<T, F, ($($Arg,)+)>::try_map(self, resources, value_resolution_ctx)
            }

            fn is_valued(&self) -> bool {
                self.fn_map.is_some()
            }
        }
    };
}

#[derive(Debug)]
enum BorrowedData<Marked, T> {
    Marked(Marked),
    Direct(T),
}

macro_rules! arg_resolve {
    (
        $resources:ident,
        $value_resolution_ctx:ident,
        $value_resolution_mode:ident,
        $arg:ident,
        $Arg:ident
    ) => {
        // Prioritize data marker wrapper over direct data borrow.
        let borrow_marked_data_result = $resources.try_borrow::<$value_resolution_mode<$Arg>>();
        let borrow_direct = $resources.try_borrow::<$Arg>();

        let borrowed_data = match borrow_marked_data_result {
            Ok(borrow_marked_data) => BorrowedData::Marked(borrow_marked_data),
            Err(borrow_fail) => match borrow_fail {
                // Either:
                //
                // * `A0` in the function is incorrect, so `Current<A0>` is not registered by any
                //   item, or
                // * There is a bug in Peace.
                BorrowFail::ValueNotFound => match borrow_direct {
                    Ok(arg) => BorrowedData::Direct(arg),
                    Err(borrow_fail) => match borrow_fail {
                        // Either:
                        //
                        // * `A0` in the function is incorrect, so `Current<A0>` is not registered
                        //   by any item, or
                        // * There is a bug in Peace.
                        BorrowFail::ValueNotFound => {
                            return Err(ParamsResolveError::FromMap {
                                value_resolution_ctx: $value_resolution_ctx.clone(),
                                from_type_name: tynm::type_name::<$Arg>(),
                            });
                        }
                        BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => {
                            return Err(ParamsResolveError::FromMapBorrowConflict {
                                value_resolution_ctx: $value_resolution_ctx.clone(),
                                from_type_name: tynm::type_name::<$Arg>(),
                            });
                        }
                    },
                },
                BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => {
                    return Err(ParamsResolveError::FromMapBorrowConflict {
                        value_resolution_ctx: $value_resolution_ctx.clone(),
                        from_type_name: tynm::type_name::<$Arg>(),
                    });
                }
            },
        };
        let $arg = match &borrowed_data {
            BorrowedData::Marked(marked_data) => match marked_data.as_ref() {
                Some(data) => data,
                None => {
                    return Err(ParamsResolveError::FromMap {
                        value_resolution_ctx: $value_resolution_ctx.clone(),
                        from_type_name: tynm::type_name::<$Arg>(),
                    });
                }
            },
            BorrowedData::Direct(data) => data,
        };
    };
}

macro_rules! try_arg_resolve {
    (
        $resources:ident,
        $value_resolution_ctx:ident,
        $value_resolution_mode:ident,
        $arg:ident,
        $Arg:ident
    ) => {
        // Prioritize data marker wrapper over direct data borrow.
        let borrow_marked_data_result = $resources.try_borrow::<$value_resolution_mode<$Arg>>();
        let borrow_direct = $resources.try_borrow::<$Arg>();

        let borrowed_data = match borrow_marked_data_result {
            Ok(borrow_marked_data) => BorrowedData::Marked(borrow_marked_data),
            Err(borrow_fail) => match borrow_fail {
                // Either:
                //
                // * `A0` in the function is incorrect, so `Current<A0>` is not registered by any
                //   item, or
                // * There is a bug in Peace.
                BorrowFail::ValueNotFound => match borrow_direct {
                    Ok(arg) => BorrowedData::Direct(arg),
                    Err(borrow_fail) => match borrow_fail {
                        // Either:
                        //
                        // * `A0` in the function is incorrect, so `Current<A0>` is not registered
                        //   by any item, or
                        // * There is a bug in Peace.
                        BorrowFail::ValueNotFound => return Ok(None),
                        BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => {
                            return Err(ParamsResolveError::FromMapBorrowConflict {
                                value_resolution_ctx: $value_resolution_ctx.clone(),
                                from_type_name: tynm::type_name::<$Arg>(),
                            });
                        }
                    },
                },
                BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => {
                    return Err(ParamsResolveError::FromMapBorrowConflict {
                        value_resolution_ctx: $value_resolution_ctx.clone(),
                        from_type_name: tynm::type_name::<$Arg>(),
                    });
                }
            },
        };
        let $arg = match &borrowed_data {
            BorrowedData::Marked(marked_data) => match marked_data.as_ref() {
                Some(data) => data,
                None => return Ok(None),
            },
            BorrowedData::Direct(data) => &data,
        };
    };
}

// We can add more if we need to support more args.
//
// There is a compile time / Rust analyzer startup cost to it, so it's better to
// not generate more than we need.
impl_mapping_fn_impl!(A0 a0);
impl_mapping_fn_impl!(A0 a0, A1 a1);
impl_mapping_fn_impl!(A0 a0, A1 a1, A2 a2);
impl_mapping_fn_impl!(A0 a0, A1 a1, A2 a2, A3 a3);
impl_mapping_fn_impl!(A0 a0, A1 a1, A2 a2, A3 a3, A4 a4);