Skip to main content

agent_first_data/document/
coerce.rs

1//! CLI-facing value construction for `set`/`add`: a bare VALUE/FIELD=VALUE is
2//! always [`Value::String`] with zero coercion — no shape-guessing, no type
3//! prefixes. An exact type is requested explicitly via [`ValueType`] (`set`'s
4//! `--value-type` flag); [`guard_bare_overwrite`] is the heterogeneous-overwrite
5//! guard that turns a bare VALUE silently rewriting what is already at the path
6//! — a scalar of another type, or a whole container — into an argument error
7//! instead.
8
9use crate::document::{DocumentError, DocumentResult, Value};
10
11/// The exact type an explicit `--value-type` requests for a `set` VALUE.
12///
13/// `String` is also the *implicit* type of a bare VALUE (zero coercion) —
14/// see [`guard_bare_overwrite`] for the rule that keeps that implicit choice
15/// from silently overwriting a differently-typed existing scalar.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum ValueType {
18    String,
19    Number,
20    Bool,
21    Null,
22    Json,
23}
24
25impl ValueType {
26    /// Parse a `--value-type` flag value. `None` for anything else.
27    pub fn parse(name: &str) -> Option<Self> {
28        match name {
29            "string" => Some(Self::String),
30            "number" => Some(Self::Number),
31            "bool" => Some(Self::Bool),
32            "null" => Some(Self::Null),
33            "json" => Some(Self::Json),
34            _ => None,
35        }
36    }
37
38    /// The flag spelling this variant was parsed from (used in error
39    /// messages and the heterogeneous-overwrite guard's escape hatches).
40    pub fn name(self) -> &'static str {
41        match self {
42            Self::String => "string",
43            Self::Number => "number",
44            Self::Bool => "bool",
45            Self::Null => "null",
46            Self::Json => "json",
47        }
48    }
49}
50
51/// Construct a `Value` from a CLI string per an explicit [`ValueType`].
52///
53/// `raw` is the VALUE positional; it must be `None` for [`ValueType::Null`]
54/// (null takes no payload) and `Some` for every other type. `number`/`bool`
55/// parse strictly (an invalid literal is a [`DocumentError::InvalidArgument`],
56/// not a silent fallback to string); `json` is the only entry point for
57/// arrays, objects, and an "exact-type scalar" (`--value-type json` value
58/// `"8080"` writes the *string* `"8080"`, not the number). `number` is
59/// literal-faithful: an oversized integer or high-precision float is
60/// preserved digit for digit via [`Value::Number`].
61pub fn value_from_type(value_type: ValueType, raw: Option<&str>) -> DocumentResult<Value> {
62    match value_type {
63        ValueType::Null => match raw {
64            None => Ok(Value::Null),
65            Some(_) => Err(DocumentError::InvalidArgument {
66                detail: "--value-type null takes no VALUE".to_string(),
67            }),
68        },
69        ValueType::String => Ok(Value::String(require_value(raw, value_type)?.to_string())),
70        ValueType::Bool => {
71            let raw = require_value(raw, value_type)?;
72            parse_bool(raw)
73                .map(Value::Bool)
74                .ok_or_else(|| DocumentError::InvalidArgument {
75                    detail: "VALUE is not a boolean for --value-type bool; expected true or false"
76                        .to_string(),
77                })
78        }
79        ValueType::Number => parse_number_literal(require_value(raw, value_type)?),
80        ValueType::Json => {
81            let raw = require_value(raw, value_type)?;
82            serde_json::from_str::<serde_json::Value>(raw)
83                .map(Value::from)
84                .map_err(|error| DocumentError::InvalidArgument {
85                    detail: format!("VALUE is not valid JSON for --value-type json: {error}"),
86                })
87        }
88    }
89}
90
91fn require_value(raw: Option<&str>, value_type: ValueType) -> DocumentResult<&str> {
92    raw.ok_or_else(|| DocumentError::InvalidArgument {
93        detail: format!("--value-type {} requires a VALUE", value_type.name()),
94    })
95}
96
97/// Parse a `--value-type number` literal strictly as a JSON number (no
98/// leading zeros, no `+` sign, no `Infinity`/`NaN` — the same grammar the
99/// document layer's JSON reader accepts), preserving its exact digits via
100/// [`Value::Number`] when it does not fit `Integer`/`Unsigned`/`Float`
101/// exactly. Reuses `serde_json`'s `arbitrary_precision` parsing so the
102/// validation and the literal-fidelity capture are the same code path as
103/// the JSON document reader (`format::json::load`).
104fn parse_number_literal(text: &str) -> DocumentResult<Value> {
105    serde_json::from_str::<serde_json::Value>(text)
106        .ok()
107        .filter(serde_json::Value::is_number)
108        .map(Value::from)
109        .ok_or_else(|| DocumentError::InvalidArgument {
110            detail: "VALUE is not a number literal for --value-type number".to_string(),
111        })
112}
113
114fn parse_bool(value: &str) -> Option<bool> {
115    match value {
116        "true" => Some(true),
117        "false" => Some(false),
118        _ => None,
119    }
120}
121
122/// The four AFDATA scalar "kinds" the heterogeneous-overwrite guard
123/// distinguishes. `Number` covers `Integer`/`Unsigned`/`Float`/
124/// [`Value::Number`] — the guard cares whether VALUE would change a scalar
125/// *from* one of these kinds *to* a bare string, not which numeric
126/// representation was in play.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum ScalarKind {
129    Null,
130    Bool,
131    Number,
132    String,
133}
134
135impl ScalarKind {
136    /// The `--value-type` spelling that keeps a value of this kind.
137    pub fn value_type_name(self) -> &'static str {
138        match self {
139            Self::Null => "null",
140            Self::Bool => "bool",
141            Self::Number => "number",
142            Self::String => "string",
143        }
144    }
145}
146
147/// Whether `value` satisfies `expected` for a typed read — the GET-side
148/// counterpart to [`value_from_type`]. `Json` matches any value; `Number`
149/// matches every numeric representation; the rest match their one kind. A
150/// consumer that asks for a type gets a value back only when it actually is
151/// that type, so a wrong-typed leaf is a caught error rather than a surprise.
152pub fn value_matches_type(value: &Value, expected: ValueType) -> bool {
153    match expected {
154        ValueType::Json => true,
155        ValueType::String => matches!(value, Value::String(_)),
156        ValueType::Bool => matches!(value, Value::Bool(_)),
157        ValueType::Null => matches!(value, Value::Null),
158        ValueType::Number => matches!(
159            value,
160            Value::Integer(_) | Value::Unsigned(_) | Value::Float(_) | Value::Number(_)
161        ),
162    }
163}
164
165/// The scalar kind of `value`, or `None` for an array/object.
166///
167/// Containers have no scalar kind; [`guard_bare_overwrite`] reports them
168/// separately as [`BareOverwrite::Container`] rather than exempting them.
169pub fn scalar_kind(value: &Value) -> Option<ScalarKind> {
170    match value {
171        Value::Null => Some(ScalarKind::Null),
172        Value::Bool(_) => Some(ScalarKind::Bool),
173        Value::Integer(_) | Value::Unsigned(_) | Value::Float(_) | Value::Number(_) => {
174            Some(ScalarKind::Number)
175        }
176        Value::String(_) => Some(ScalarKind::String),
177        Value::Array(_) | Value::Object(_) => None,
178    }
179}
180
181/// What a bare VALUE would overwrite, and the `--value-type` that would keep
182/// it — see [`guard_bare_overwrite`].
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub enum BareOverwrite {
185    /// A scalar of a different kind: the type changes.
186    Scalar(ScalarKind),
187    /// A whole array or object: the container is discarded.
188    Container(&'static str),
189}
190
191impl BareOverwrite {
192    /// The kind name to show the caller.
193    pub fn found(self) -> &'static str {
194        match self {
195            Self::Scalar(kind) => kind.value_type_name(),
196            Self::Container(name) => name,
197        }
198    }
199
200    /// The `--value-type` spelling that preserves what is already there.
201    ///
202    /// A container has no scalar type to keep, so preserving it means writing
203    /// it back as a JSON literal.
204    pub fn keeps(self) -> &'static str {
205        match self {
206            Self::Scalar(kind) => kind.value_type_name(),
207            Self::Container(_) => "json",
208        }
209    }
210}
211
212/// The heterogeneous-overwrite guard, which closes the "no silent type
213/// rewrites" rule: a bare VALUE (implicit `--value-type
214/// string`) is always a string, so writing one over anything that is not
215/// already a string rewrites what is there. That is an argument error, not a
216/// coercion decision. Returns what would be overwritten so the caller can name
217/// both escape hatches (`--value-type <kind>` to keep it, `--value-type
218/// string` to convert deliberately).
219///
220/// Containers are guarded too, and are the reason this returns more than a
221/// [`ScalarKind`]: `set config.json deps hello` over a three-element array
222/// used to exit 0 and leave `"deps": "hello"` behind. A type change at least
223/// keeps one value; discarding a container loses everything under it, with no
224/// signal at all.
225///
226/// `Ok(())` only when there is nothing to guard: the target is absent (a new
227/// key) or already a string. Never called when `--value-type` was passed
228/// explicitly — an explicit type is a deliberate declaration, not a silent
229/// rewrite.
230pub fn guard_bare_overwrite(existing: Option<&Value>) -> Result<(), BareOverwrite> {
231    match existing {
232        None | Some(Value::String(_)) => Ok(()),
233        Some(Value::Array(_)) => Err(BareOverwrite::Container("array")),
234        Some(Value::Object(_)) => Err(BareOverwrite::Container("object")),
235        Some(other) => match scalar_kind(other) {
236            Some(kind) => Err(BareOverwrite::Scalar(kind)),
237            None => Ok(()),
238        },
239    }
240}
241
242/// Coerce a CLI string toward the type already present at `existing`, for a
243/// consumer that *knows* the target type from the value it is replacing (a
244/// config setter reading typed leaves out of a serialized document).
245///
246/// This is the library counterpart to the CLI's explicit `--value-type`: the
247/// generic `afdata` CLI must ask the user for the type because it cannot know
248/// it, but a consumer that does — because it holds the existing typed leaf, or
249/// its own schema — should neither add a flag nor re-parse. It is **type
250/// directed, not shape guessing**: the existing leaf's [`scalar_kind`] selects
251/// the parse; a `bool`/`number` literal that does not match falls back to a
252/// string; a string, `null`, or absent leaf yields a string; a container leaf
253/// is replaced with a JSON literal.
254pub fn coerce_toward(raw: &str, existing: Option<&Value>) -> DocumentResult<Value> {
255    match existing.and_then(scalar_kind) {
256        Some(ScalarKind::Bool) => Ok(value_from_type(ValueType::Bool, Some(raw))
257            .unwrap_or_else(|_| Value::String(raw.to_string()))),
258        Some(ScalarKind::Number) => Ok(value_from_type(ValueType::Number, Some(raw))
259            .unwrap_or_else(|_| Value::String(raw.to_string()))),
260        Some(ScalarKind::String | ScalarKind::Null) => Ok(Value::String(raw.to_string())),
261        // A container leaf (array/object) or a brand-new key with no type to
262        // aim at: a structured literal (`[`/`{`) is parsed as JSON so the value
263        // round-trips, while a bare scalar stays a string — no scalar
264        // shape-guessing (`007` never becomes `7`).
265        None => coerce_structured_or_string(raw),
266    }
267}
268
269/// A structured literal (`[`/`{`) parses as a JSON array/object; anything else
270/// is taken verbatim as a string. Used where no scalar type is known, so a
271/// bare value is never shape-guessed into a number/bool.
272fn coerce_structured_or_string(raw: &str) -> DocumentResult<Value> {
273    let trimmed = raw.trim_start();
274    if trimmed.starts_with('[') || trimmed.starts_with('{') {
275        value_from_type(ValueType::Json, Some(raw))
276    } else {
277        Ok(Value::String(raw.to_string()))
278    }
279}
280
281/// Coerce a CLI value slice toward the type at `existing` via [`coerce_toward`]:
282/// one value becomes a scalar, several become an array whose elements are each
283/// coerced toward the existing array's element type. An empty slice is an error.
284pub fn coerce_values_toward(values: &[String], existing: Option<&Value>) -> DocumentResult<Value> {
285    match values {
286        [] => Err(DocumentError::EmptyValues),
287        [one] => coerce_toward(one, existing),
288        many => {
289            let element = existing
290                .and_then(Value::as_array)
291                .and_then(|array| array.first());
292            Ok(Value::Array(
293                many.iter()
294                    .map(|value| coerce_toward(value, element))
295                    .collect::<DocumentResult<Vec<_>>>()?,
296            ))
297        }
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    #![allow(clippy::unwrap_used, clippy::panic)]
304    use super::*;
305
306    #[test]
307    fn bare_string_is_zero_coercion() {
308        for raw in ["007", "1.0", "true", "null", "3e10"] {
309            assert_eq!(
310                value_from_type(ValueType::String, Some(raw)).unwrap(),
311                Value::String(raw.to_string())
312            );
313        }
314    }
315
316    #[test]
317    fn value_type_number_is_literal_faithful() {
318        assert_eq!(
319            value_from_type(ValueType::Number, Some("18446744073709551615")).unwrap(),
320            Value::Unsigned(u64::MAX)
321        );
322        let huge = "123456789012345678901234567890";
323        assert_eq!(
324            value_from_type(ValueType::Number, Some(huge)).unwrap(),
325            Value::Number(huge.to_string())
326        );
327        let precise = "0.1000000000000000055511151231257827";
328        assert_eq!(
329            value_from_type(ValueType::Number, Some(precise)).unwrap(),
330            Value::Number(precise.to_string())
331        );
332    }
333
334    #[test]
335    fn value_type_number_rejects_leading_zero_and_non_numeric() {
336        assert!(value_from_type(ValueType::Number, Some("007")).is_err());
337        assert!(value_from_type(ValueType::Number, Some("abc")).is_err());
338        assert!(value_from_type(ValueType::Number, Some("+5")).is_err());
339    }
340
341    #[test]
342    fn value_type_bool_accepts_only_json_boolean_literals() {
343        for (raw, expected) in [("true", true), ("false", false)] {
344            assert_eq!(
345                value_from_type(ValueType::Bool, Some(raw)).unwrap(),
346                Value::Bool(expected)
347            );
348        }
349        for raw in ["yes", "no", "on", "off", "1", "0", "TRUE", "nope"] {
350            assert!(value_from_type(ValueType::Bool, Some(raw)).is_err());
351        }
352    }
353
354    #[test]
355    fn value_type_null_takes_no_value() {
356        assert_eq!(value_from_type(ValueType::Null, None).unwrap(), Value::Null);
357        assert!(value_from_type(ValueType::String, None).is_err());
358        assert!(value_from_type(ValueType::Null, Some("x")).is_err());
359    }
360
361    #[test]
362    fn value_type_json_is_the_only_container_entry_point() {
363        let value = value_from_type(ValueType::Json, Some(r#"["a","b"]"#)).unwrap();
364        assert_eq!(
365            value,
366            Value::Array(vec![
367                Value::String("a".to_string()),
368                Value::String("b".to_string())
369            ])
370        );
371        // An exact-type scalar via --value-type json: the string "8080", not
372        // the number 8080.
373        assert_eq!(
374            value_from_type(ValueType::Json, Some("\"8080\"")).unwrap(),
375            Value::String("8080".to_string())
376        );
377    }
378
379    #[test]
380    fn guard_fires_for_any_bare_overwrite_that_is_not_string_to_string() {
381        assert_eq!(guard_bare_overwrite(None), Ok(()));
382        assert_eq!(
383            guard_bare_overwrite(Some(&Value::String("x".to_string()))),
384            Ok(())
385        );
386        // A container is no longer exempt: it used to pass here, which is how
387        // `set config.json deps hello` discarded a whole array at exit 0.
388        assert_eq!(
389            guard_bare_overwrite(Some(&Value::Array(vec![]))),
390            Err(BareOverwrite::Container("array"))
391        );
392        assert_eq!(
393            guard_bare_overwrite(Some(&Value::Integer(8080))),
394            Err(BareOverwrite::Scalar(ScalarKind::Number))
395        );
396        assert_eq!(
397            guard_bare_overwrite(Some(&Value::Bool(true))),
398            Err(BareOverwrite::Scalar(ScalarKind::Bool))
399        );
400        assert_eq!(
401            guard_bare_overwrite(Some(&Value::Null)),
402            Err(BareOverwrite::Scalar(ScalarKind::Null))
403        );
404    }
405
406    #[test]
407    fn coerce_toward_is_type_directed_not_shape_guessing() {
408        // Toward an existing scalar's kind: bool/number parse toward it, a
409        // non-matching literal falls back to a string, a string leaf stays a
410        // string.
411        assert_eq!(
412            coerce_toward("false", Some(&Value::Bool(true))).unwrap(),
413            Value::Bool(false)
414        );
415        assert_eq!(
416            coerce_toward("5432", Some(&Value::Integer(1))).unwrap(),
417            Value::from(serde_json::json!(5432))
418        );
419        assert_eq!(
420            coerce_toward("not-a-number", Some(&Value::Integer(1))).unwrap(),
421            Value::String("not-a-number".to_string())
422        );
423        assert_eq!(
424            coerce_toward("007", Some(&Value::String("x".to_string()))).unwrap(),
425            Value::String("007".to_string())
426        );
427        // No existing type: a bare scalar is a string (no `007` -> `7`), but a
428        // structured literal parses as JSON.
429        assert_eq!(
430            coerce_toward("007", None).unwrap(),
431            Value::String("007".to_string())
432        );
433        assert!(matches!(
434            coerce_toward("[]", None).unwrap(),
435            Value::Array(_)
436        ));
437        assert!(matches!(
438            coerce_toward("{\"a\":1}", Some(&Value::Object(Default::default()))).unwrap(),
439            Value::Object(_)
440        ));
441    }
442
443    #[test]
444    fn coerce_values_toward_scalar_vs_array() {
445        assert!(matches!(
446            coerce_values_toward(&[], None),
447            Err(DocumentError::EmptyValues)
448        ));
449        assert_eq!(
450            coerce_values_toward(&["x".to_string()], None).unwrap(),
451            Value::String("x".to_string())
452        );
453        // Several values become an array, each coerced toward the existing
454        // array's element type.
455        let existing = Value::Array(vec![Value::Bool(true)]);
456        assert_eq!(
457            coerce_values_toward(&["false".to_string(), "true".to_string()], Some(&existing))
458                .unwrap(),
459            Value::Array(vec![Value::Bool(false), Value::Bool(true)])
460        );
461    }
462}
463
464#[cfg(test)]
465mod bare_overwrite_tests {
466    use super::*;
467    use std::collections::BTreeMap;
468
469    #[test]
470    fn containers_are_guarded_and_ask_for_json() {
471        let array = Value::Array(vec![Value::String("a".to_string())]);
472        let object = Value::Object(BTreeMap::new());
473        for (value, name) in [(&array, "array"), (&object, "object")] {
474            let overwrite = guard_bare_overwrite(Some(value)).unwrap_err();
475            assert_eq!(overwrite.found(), name);
476            // A container has no scalar type to keep; JSON is how it survives.
477            assert_eq!(overwrite.keeps(), "json");
478        }
479    }
480
481    #[test]
482    fn scalars_keep_naming_their_own_type() {
483        let overwrite = guard_bare_overwrite(Some(&Value::Integer(8080))).unwrap_err();
484        assert_eq!(overwrite, BareOverwrite::Scalar(ScalarKind::Number));
485        assert_eq!(overwrite.keeps(), "number");
486    }
487
488    #[test]
489    fn a_new_key_or_an_existing_string_is_not_a_rewrite() {
490        assert!(guard_bare_overwrite(None).is_ok());
491        assert!(guard_bare_overwrite(Some(&Value::String("old".to_string()))).is_ok());
492    }
493}