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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Contains Traits, Types and utilities used by the derive macros
use std::{
any::{Any, TypeId},
borrow::Cow,
collections::VecDeque,
ffi::{OsStr, OsString},
mem::MaybeUninit,
};
use thiserror::Error;
#[expect(unused)] // used in doc
use crate::Configuration;
#[cfg(feature = "clap")]
pub use crate::clap::value_enum::ValueEnumChange;
pub use crate::lists::{HashMapChange, HashMapKey, VecChange};
pub use crate::option::OptionChange;
/// Denotes that the operation is not supported by a [crate::Configuration]
#[derive(Debug, Error)]
#[error(
"operation not supported by this configuration type. Incorrect implementation of the Configuration trait"
)]
pub struct NotSupported;
#[derive(Debug, Error)]
#[error("failed to parse value: {0}")]
pub struct ParseError(pub String);
/// internal parts of [crate::Configuration]
///
/// This trait is used to clean up the user interface
pub trait CongenInternal: Sized {
/// The [CongenChange] type associated with this [Configuration]
type CongenChange: CongenChange<Configuration = Self>;
/// apply change to `self`
///
/// providing a `default` value in case `Self = Option<Configuration>` and
/// `self == None`. In this case if `default` is provided it must return `Some(default)`.
fn apply_change_with_inner_default(
&mut self,
change: Self::CongenChange,
inner_default: Option<fn() -> Box<dyn Any>>,
);
/// Get a [Description] of this [Configuration]
fn description(field_name: &'static str) -> Description;
/// Returns `Ok(default_value)` if this type has a default
fn default() -> Result<Self, crate::internal::NotSupported> {
Err(crate::internal::NotSupported)
}
/// The typename of this [Configuration].
///
/// This is used in a user-facing system and does not need to exactly match the rust type.
fn type_name() -> Cow<'static, str> {
std::any::type_name::<Self>().into()
}
}
pub trait CongenChange: Sized {
type Configuration: crate::Configuration;
/// An empty change.
///
/// applying the result of this function should have no effect
fn empty() -> Self;
fn default() -> Result<Self, NotSupported> {
Err(NotSupported)
}
/// Parses a simple field value.
///
/// Returns `Err(NotSupported)` for complex structs that can't be directly parsed from a
/// string.
/// Otherwise it should either return `Ok(Ok(parsed_value))` or `Ok(Err(parse_error))`
fn parse(_input: &OsStr) -> Result<Result<Self, ParseError>, NotSupported> {
Err(NotSupported)
}
fn unwrap_field(self) -> Result<Self::Configuration, Self> {
Err(self)
}
/// combine 2 changes.
///
/// # Implementation
///
/// given a `configuration: Self::Configuration` applying the result of
/// `change_a.apply_change(change_b)` should be the same as applying `change_a` and
/// then `change_b`, e.g.
/// ```compile_fail
/// let combined = change_a.apply_change(change_b);
/// configuration.apply_change(combined)
/// ```
/// should be the same as
/// ```compile_fail
/// configuration.apply_change(change_a);
/// configuration.apply_change(change_b);
/// ```
fn apply_change(&mut self, change: Self);
/// Create a change that fills the `path` based on the verb
///
/// # Example
///
/// A path `[a, b, c]` and a verb `ChangeVerb::UseDefault` means that the result
/// should be something like `empty().a.b.c = default()`.
///
/// # Implementation
///
/// an empty path always refers to `Self` while any path entry refers to a subfield
/// relative to `self`.
/// The result should be initialized to `Self::empty` with just the final field in the path
/// changed based on the verb.
fn from_path_and_verb<'a, P>(path: P, verb: ChangeVerb) -> Result<Self, VerbError>
where
P: Iterator<Item = &'a str>;
}
/// Marks that [CongenInternal::default] is immplemented to return `Ok(default)`
pub trait CongenDefault: CongenInternal {}
/// A comp-time check that `C` implements [CongenDefault]
pub const fn assert_impl_default<C: CongenDefault>() -> bool {
true
}
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum VerbError {
#[error("invalid path: the specified configuration path does not exist")]
InvalidPath,
#[error("unsupported verb '{0:?}' for this configuration field")]
UnsupportedVerb(ChangeVerb),
#[error("unknown verb: {0}")]
UnknownVerb(String),
#[error(transparent)]
NotSupported(#[from] NotSupported),
#[error(transparent)]
ParseError(#[from] ParseError),
#[error("failed to downcast value to the expected type")]
DowncastFailed,
#[error("the description is in an invalid state")]
InvalidDescription,
#[error("wrong key type. Expected either String or Int but got the opposite")]
WrongKeyType,
#[error("wrong list value type. Expected either Field or Composit but got the opposite")]
WrongListValueType,
#[error("list verbs are forbidden for operation. Found {0:?}")]
ListVerbIllegal(ChangeVerb),
}
/// A [ChangeVerb] is used to create a [CongenChange] based on a path.
///
/// See [CongenChange::from_path_and_verb].
#[derive(Debug)]
pub enum ChangeVerb {
/// Set the change to [CongenChange::parse] of the value
Set(OsString),
/// Enable the flag in the change
SetFlag,
/// Unset the change
Unset,
/// Use the default value for the change.
UseDefault,
/// Similar to [ChangeVerb::Set] but already contains the parsed value
///
/// The value must be of the same type as defined by the [crate::Configuration] path.
SetAny(Box<dyn Any + 'static>),
List(ListVerb),
}
#[derive(Debug)]
pub enum ListVerb {
Append {
key: Option<ListKey>,
new_value: ListValue,
},
Update {
key: ListKey,
updated_value: ListValue,
},
Remove {
key: ListKey,
},
Empty,
}
#[derive(Debug)]
pub enum ListValue {
Value(OsString),
WithPath(Vec<String>, Box<ChangeVerb>),
}
impl From<OsString> for ListValue {
fn from(value: OsString) -> Self {
ListValue::Value(value)
}
}
#[derive(Debug)]
pub enum ListKey {
Stringy(String),
Unsigned(u64),
Signed(i64),
}
impl From<ListVerb> for ChangeVerb {
fn from(value: ListVerb) -> Self {
ChangeVerb::List(value)
}
}
/// Descibes a [crate::Configuration]
#[derive(Debug, Clone)]
pub enum Description {
/// A composite type, e.g. structs or enums with values
Composit(CompositDescription),
/// A simple parsable field, e.g. String, int, anything parsable from the command line
Field(FieldDescription),
/// A lsit type, e.g. `Vec<T>`, `HashMap<String, T>`
List(ListDescription),
}
impl Description {
/// creates a [Description] that claims to have a default value.
///
/// When calling this the caller must ensure that the coresponding [crate::Configuration]
/// can provide a default value.
pub fn with_default(self) -> Self {
match self {
Description::Composit(composit) => Self::Composit(composit.with_default()),
Description::Field(field) => Self::Field(field.with_default()),
Description::List(list) => Self::List(list.with_default()),
}
}
/// The name of the Field/Struct/Enum
pub fn name(&self) -> &'static str {
match self {
Description::Field(f) => f.field_name,
Description::Composit(c) => c.field_name,
Description::List(l) => l.field_name,
}
}
/// Whether or not the [crate::Configuration] provides a default value
pub fn has_default(&self) -> bool {
match self {
Description::Field(f) => f.has_default,
Description::Composit(c) => c.has_default,
Description::List(l) => l.has_default,
}
}
/// Whether or not the [crate::Configuration] can be unset
pub fn allow_unset(&self) -> bool {
match self {
Description::Field(f) => f.allow_unset,
Description::Composit(c) => c.allow_unset,
Description::List(_) => false,
}
}
/// Returns true if a path is valid for the [crate::Configuration]
pub fn actionable_field<'a, 's, P>(&'s self, mut path: P) -> Option<Description>
where
P: Iterator<Item = &'a str>,
{
match self {
Description::Composit(composit_description) => {
let Some(next_field_name) = path.next() else {
return if composit_description.is_actionable() {
Some(self.clone())
} else {
None
};
};
let next_field = composit_description.field(next_field_name)?;
next_field.actionable_field(path)
}
Description::Field(_) | Description::List(_) if path.next().is_none() => {
Some(self.clone())
}
_ => None,
}
}
pub fn actionable_fields(&self) -> Vec<ActionableField> {
let composite = match self {
Description::Field(_) | Description::List(_) => {
return vec![ActionableField {
description: self.clone(),
path: VecDeque::new(),
}];
}
Description::Composit(comp) => comp,
};
let mut actionable = Vec::new();
for field in composite.fields.iter() {
match field {
Description::Field(_) | Description::List(_) => {
actionable.push(ActionableField {
description: field.clone(),
path: VecDeque::from([field.name()]),
});
}
Description::Composit(composite) => {
let fields = field.actionable_fields().into_iter().map(|mut field| {
field.path.push_front(composite.field_name);
field
});
actionable.extend(fields);
if composite.is_actionable() {
actionable.push(ActionableField {
description: field.clone(),
path: VecDeque::from([composite.field_name]),
});
}
}
}
}
actionable
}
}
#[derive(Debug)]
pub struct ActionableField {
pub description: Description,
pub path: VecDeque<&'static str>,
}
impl From<CompositDescription> for Description {
fn from(value: CompositDescription) -> Self {
Description::Composit(value)
}
}
impl From<FieldDescription> for Description {
fn from(value: FieldDescription) -> Self {
Description::Field(value)
}
}
impl From<ListDescription> for Description {
fn from(value: ListDescription) -> Self {
Description::List(value)
}
}
/// A description for a composite type, e.g. structs or enums with values
#[derive(Debug, Clone)]
pub struct CompositDescription {
pub field_name: &'static str,
pub type_name: Cow<'static, str>,
pub fields: Vec<Description>,
pub has_default: bool,
pub allow_unset: bool,
}
impl CompositDescription {
pub fn with_default(self) -> Self {
Self {
has_default: true,
..self
}
}
/// returns `true` if the description describes a field that is actionable
pub fn is_actionable(&self) -> bool {
self.has_default || self.allow_unset
}
/// returns a reference to the fields [Description] if the field exists
pub fn field<'d>(&'d self, name: &str) -> Option<&'d Description> {
self.fields.iter().find(|f| f.name() == name)
}
}
/// A description for a simple parsable field, e.g. String, int, anything parsable from the command line
#[derive(Debug, Clone)]
pub struct FieldDescription {
pub field_name: &'static str,
pub type_name: Cow<'static, str>,
pub is_flag: bool,
pub allow_unset: bool,
pub has_default: bool,
#[cfg(feature = "clap")]
pub clap_data: Option<FieldClapDescription>,
}
#[cfg(feature = "clap")]
#[derive(Debug, Clone, Default)]
pub struct FieldClapDescription {
pub value_hint: clap::ValueHint,
pub value_parser: Option<clap::builder::Resettable<clap::builder::ValueParser>>,
pub allow_hyphen_values: bool,
pub allow_negative_numbers: bool,
}
impl FieldDescription {
pub fn with_default(self) -> Self {
Self {
has_default: true,
..self
}
}
}
#[derive(Debug, Clone)]
pub struct ListDescription {
pub field_name: &'static str,
pub type_name: Cow<'static, str>,
pub inner_desc: Box<Description>,
pub has_default: bool,
pub key_type: ListKeyType,
pub append_requires_key: bool,
}
#[derive(Debug, Clone)]
pub enum ListKeyType {
String,
Signed,
Unsigned,
}
impl ListDescription {
pub fn with_default(self) -> Self {
Self {
has_default: true,
..self
}
}
}
/// A helper to safely cast between 2 identical generic types
///
/// this will panic if `T` and `F` are not of the same type.
/// Used to handle generics, where we know `T` and `F` should be of the same type,
/// but can't express this in the type system, e.g. circular type between `crate::Configuration` and
/// `CongenChange`:
/// `<C as Configuration>::CongenChange::Configuration == C`
pub(crate) fn self_cast<F: 'static, T: 'static>(value: F) -> T {
assert_eq!(TypeId::of::<F>(), TypeId::of::<T>());
let mut maybe = MaybeUninit::new(value);
unsafe {
// Safety: created through MaybeUninit::new
let value: &mut F = maybe.assume_init_mut();
let value: &mut dyn Any = value;
let value: &mut T = value.downcast_mut().unwrap_or_else(|| {
panic!(
"called downcast on incompatible types: {} => {}",
core::any::type_name::<F>(),
core::any::type_name::<T>()
)
});
// Safety: value is properly initialized as it is a reference to "maybe"
// this is a valid "move" because "maybe" is of type MaybeUninit and never accessed
// again, not even dropped.
core::ptr::read(value)
}
}