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
use std::fmt::{self, Debug};
use peace_resource_rt::{resources::ts::SetUp, BorrowFail, Resources};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use crate::{
AnySpecDataType, AnySpecRt, FieldWiseSpecRt, MappingFn, MappingFnImpl, Params,
ParamsResolveError, ValueResolutionCtx, ValueResolutionMode, ValueSpecRt,
};
/// How to populate a field's value in an item's params.
///
/// The `MappingFn` variant's mapping function is `None` when deserialized, as
/// it is impossible to determine the underlying `F` and `U` type parameters for
/// the backing `MappingFnImpl`.
///
/// For deserialization:
///
/// 1. A `ParamsSpecsTypeReg` is constructed, and deserialization functions are
/// registered from `ItemId` to `ParamsSpecDe<T, F, U>`, where `F` and `U`
/// are derived from the `ValueSpec` provided by the user.
///
/// 2. `value_specs.yaml` is deserialized using that type registry.
///
/// 3. Each `ParamsSpecDe<T>` is mapped into a `ValueSpec<T>`, and subsequently
/// `AnySpecRtBoxed` to be passed around in a `CmdCtx`.
///
/// 4. These `AnySpecRtBoxed`s are downcasted back to `ValueSpec<T>` when
/// resolving values for item params and params partials.
#[derive(Clone, Serialize, Deserialize)]
#[serde(from = "crate::ParamsSpecDe<T>", bound = "T: Params")]
pub enum ParamsSpec<T>
where
T: Params,
{
/// Loads a stored value spec.
///
/// The value used is determined by the value spec that was
/// last stored in the `params_specs_file`. This means it
/// could be loaded as a `Value(T)` during context `build()`.
///
/// This variant may be provided when defining a command context
/// builder. However, this variant is never serialized, but
/// whichever value was *first* stored is re-loaded then
/// re-serialized.
///
/// If no value spec was previously serialized, then the command
/// context build will return an error.
Stored,
/// Uses the provided value.
///
/// The value used is whatever is passed in to the command context
/// builder.
Value {
/// The value to use.
value: T,
},
/// Uses a value loaded from `resources` at runtime.
///
/// The value may have been provided by workspace params, or
/// inserted by a predecessor at runtime.
InMemory,
/// Uses a mapped value loaded from `resources` at runtime.
///
/// The value may have been provided by workspace params, or
/// inserted by a predecessor at runtime, and is mapped by the
/// given function.
///
/// This is serialized as `MappingFn` with a string value. For
/// deserialization, there is no actual backing function, so
/// the user must provide the `MappingFn` in subsequent command
/// context builds.
MappingFn(Box<dyn MappingFn<Output = T>>),
/// Resolves this value through `ValueSpec`s for each of its fields.
///
/// This is like `T`, but with each field wrapped in
/// `ParamsSpecFieldless<T>`.
//
// Wrap each in `ValueSpec`, but for unit / external values, fail on field wise
// resolution, and also don't generate a builder method for field wise (even if is present in
// the `ValueSpec` API).
//
// Need to decide on:
//
// * Every non-recursive field is annotated with `#[params(non_recursive)]`
// * Every recursive field is annotated with `#[params(recursive)]`
//
// There shouldn't need to be automatic detection of non-recursive fields for stdlib types,
// because `peace_params` should just implement `ValueSpec` for those types.
FieldWise {
/// The field wise spec.
field_wise_spec: T::FieldWiseSpec,
},
}
impl<T> ParamsSpec<T>
where
T: Params,
{
pub fn from_map<F, Args>(field_name: Option<String>, f: F) -> Self
where
MappingFnImpl<T, F, Args>: From<(Option<String>, F)> + MappingFn<Output = T>,
{
let mapping_fn = MappingFnImpl::from((field_name, f));
Self::MappingFn(Box::new(mapping_fn))
}
}
impl<T> Debug for ParamsSpec<T>
where
T: Params,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stored => f.write_str("Stored"),
Self::Value { value } => f.debug_tuple("Value").field(value).finish(),
Self::InMemory => f.write_str("InMemory"),
Self::MappingFn(mapping_fn) => f.debug_tuple("MappingFn").field(mapping_fn).finish(),
Self::FieldWise { field_wise_spec } => {
f.debug_tuple("FieldWise").field(field_wise_spec).finish()
}
}
}
}
impl<T> From<T> for ParamsSpec<T>
where
T: Params,
{
fn from(value: T) -> Self {
Self::Value { value }
}
}
impl<T> ParamsSpec<T>
where
T: Params<Spec = ParamsSpec<T>> + Clone + Debug + Send + Sync + 'static,
T::Partial: From<T>,
{
pub fn resolve(
&self,
resources: &Resources<peace_resource_rt::resources::ts::SetUp>,
value_resolution_ctx: &mut ValueResolutionCtx,
) -> Result<T, ParamsResolveError> {
match self {
ParamsSpec::Value { value } => Ok(value.clone()),
ParamsSpec::Stored | ParamsSpec::InMemory => {
// Try resolve `T`, through the `value_resolution_ctx` first
let params_resolved = match value_resolution_ctx.value_resolution_mode() {
#[cfg(feature = "item_state_example")]
ValueResolutionMode::Example => resources
.try_borrow::<peace_data::marker::Example<T>>()
.map(|data_marker| data_marker.0.clone()),
ValueResolutionMode::Clean => resources
.try_borrow::<peace_data::marker::Clean<T>>()
.map(|data_marker| data_marker.0.clone()),
ValueResolutionMode::Current => resources
.try_borrow::<peace_data::marker::Current<T>>()
.map(|data_marker| data_marker.0.clone()),
ValueResolutionMode::Goal => resources
.try_borrow::<peace_data::marker::Goal<T>>()
.map(|data_marker| data_marker.0.clone()),
ValueResolutionMode::ApplyDry => resources
.try_borrow::<peace_data::marker::ApplyDry<T>>()
.map(|data_marker| data_marker.0.clone()),
}
.and_then(|param_opt| param_opt.ok_or(BorrowFail::ValueNotFound));
params_resolved.or_else(|_e| {
// Try resolve `T` again without the `value_resolution_ctx` wrapper.
match resources.try_borrow::<T>() {
Ok(value) => Ok((*value).clone()),
Err(borrow_fail) => match borrow_fail {
BorrowFail::ValueNotFound => Err(ParamsResolveError::InMemory {
value_resolution_ctx: value_resolution_ctx.clone(),
}),
BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => {
Err(ParamsResolveError::InMemoryBorrowConflict {
value_resolution_ctx: value_resolution_ctx.clone(),
})
}
},
}
})
}
ParamsSpec::MappingFn(mapping_fn) => mapping_fn.map(resources, value_resolution_ctx),
ParamsSpec::FieldWise { field_wise_spec } => {
field_wise_spec.resolve(resources, value_resolution_ctx)
}
}
}
pub fn resolve_partial(
&self,
resources: &Resources<SetUp>,
value_resolution_ctx: &mut ValueResolutionCtx,
) -> Result<T::Partial, ParamsResolveError> {
match self {
ParamsSpec::Value { value } => Ok(T::Partial::from((*value).clone())),
ParamsSpec::Stored | ParamsSpec::InMemory => {
// Try resolve `T`, through the `value_resolution_ctx` first
let params_partial_resolved = match value_resolution_ctx.value_resolution_mode() {
#[cfg(feature = "item_state_example")]
ValueResolutionMode::Example => resources
.try_borrow::<peace_data::marker::Example<T>>()
.map(|data_marker| data_marker.0.clone()),
ValueResolutionMode::Clean => resources
.try_borrow::<peace_data::marker::Clean<T>>()
.map(|data_marker| data_marker.0.clone()),
ValueResolutionMode::Current => resources
.try_borrow::<peace_data::marker::Current<T>>()
.map(|data_marker| data_marker.0.clone()),
ValueResolutionMode::Goal => resources
.try_borrow::<peace_data::marker::Goal<T>>()
.map(|data_marker| data_marker.0.clone()),
ValueResolutionMode::ApplyDry => resources
.try_borrow::<peace_data::marker::ApplyDry<T>>()
.map(|data_marker| data_marker.0.clone()),
}
.and_then(|param_opt| param_opt.ok_or(BorrowFail::ValueNotFound));
params_partial_resolved.map(T::Partial::from).or_else(|_e| {
// Try resolve `T` again without the `value_resolution_ctx` wrapper.
match resources.try_borrow::<T>() {
Ok(value) => Ok(T::Partial::from((*value).clone())),
Err(borrow_fail) => match borrow_fail {
BorrowFail::ValueNotFound => Ok(T::Partial::default()),
BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => {
Err(ParamsResolveError::InMemoryBorrowConflict {
value_resolution_ctx: value_resolution_ctx.clone(),
})
}
},
}
})
}
ParamsSpec::MappingFn(mapping_fn) => mapping_fn
.try_map(resources, value_resolution_ctx)
.map(|t| t.map(T::Partial::from).unwrap_or_default()),
ParamsSpec::FieldWise { field_wise_spec } => {
field_wise_spec.resolve_partial(resources, value_resolution_ctx)
}
}
}
}
impl<T> AnySpecRt for ParamsSpec<T>
where
T: Params<Spec = ParamsSpec<T>>
+ Clone
+ Debug
+ Serialize
+ DeserializeOwned
+ Send
+ Sync
+ 'static,
{
fn is_usable(&self) -> bool {
match self {
Self::Stored => false,
Self::Value { .. } | Self::InMemory => true,
Self::MappingFn(mapping_fn) => mapping_fn.is_valued(),
Self::FieldWise { field_wise_spec } => field_wise_spec.is_usable(),
}
}
fn merge(&mut self, other_boxed: &dyn AnySpecDataType)
where
Self: Sized,
{
let other: Option<&Self> = other_boxed.downcast_ref();
let other = other.unwrap_or_else(
#[cfg_attr(coverage_nightly, coverage(off))]
|| {
let self_ty_name = tynm::type_name::<Self>();
panic!(
"Failed to downcast value into `{self_ty_name}`. Value: `{other_boxed:#?}`."
);
},
);
match self {
// Use the spec that was previously stored
// (as opposed to previous value).
Self::Stored => *self = other.clone(),
// Use set value / no change on these variants
Self::Value { .. } | Self::InMemory | Self::MappingFn(_) => {}
Self::FieldWise { field_wise_spec } => {
match other {
// Don't merge stored field wise specs over provided specs.
Self::Stored | Self::Value { .. } | Self::InMemory | Self::MappingFn(_) => {}
// Merge specs fieldwise.
Self::FieldWise {
field_wise_spec: field_wise_spec_other,
} => AnySpecRt::merge(field_wise_spec, field_wise_spec_other),
}
}
}
}
}
impl<T> ValueSpecRt for ParamsSpec<T>
where
T: Params<Spec = ParamsSpec<T>>
+ Clone
+ Debug
+ Serialize
+ DeserializeOwned
+ Send
+ Sync
+ 'static,
T::Partial: From<T>,
T: TryFrom<T::Partial>,
{
type ValueType = T;
fn resolve(
&self,
resources: &Resources<SetUp>,
value_resolution_ctx: &mut ValueResolutionCtx,
) -> Result<T, ParamsResolveError> {
ParamsSpec::<T>::resolve(self, resources, value_resolution_ctx)
}
fn try_resolve(
&self,
resources: &Resources<SetUp>,
value_resolution_ctx: &mut ValueResolutionCtx,
) -> Result<Option<T>, ParamsResolveError> {
ParamsSpec::<T>::resolve_partial(self, resources, value_resolution_ctx)
.map(T::try_from)
.map(Result::ok)
}
}