Skip to main content

agent_first_data/document/
value.rs

1//! Custom Value type — zero external format dependencies.
2
3use std::collections::BTreeMap;
4
5use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
6
7use super::error::DocumentError;
8
9/// Custom Value IR independent of any format crate.
10/// Supports all formats: JSON, TOML, YAML, dotenv, and INI.
11#[derive(Debug, Clone, PartialEq)]
12pub enum Value {
13    Null,
14    Bool(bool),
15    Integer(i64),
16    Unsigned(u64),
17    Float(f64),
18    /// A numeric literal that would lose digits if forced through
19    /// [`Value::Integer`]/[`Value::Unsigned`]/[`Value::Float`]: an integer
20    /// outside `u64::MAX`, or any literal written with a fractional part or
21    /// exponent (`3.14`, `1e-10`, `-0.0`, …). Holds the exact source text
22    /// verbatim — never parsed and reserialized through `f64` — so a 30-digit
23    /// integer or a high-precision decimal round-trips digit for digit.
24    ///
25    /// Produced by the JSON backend's reader (`format::json::load`), which is
26    /// the format whose number grammar is genuinely arbitrary-precision;
27    /// TOML integers are grammar-limited to `i64` and TOML/YAML floats are
28    /// canonically `f64` at the format level, so those backends keep using
29    /// `Integer`/`Unsigned`/`Float` for values in range. `set --value-type
30    /// number` also produces this variant, preserving the CLI argument's
31    /// literal spelling the same way.
32    Number(String),
33    String(String),
34    Array(Vec<Value>),
35    /// Object map. Keys are stored sorted (BTreeMap), not in insertion order.
36    Object(BTreeMap<String, Value>),
37}
38
39pub(crate) fn non_finite_spelling(value: f64) -> &'static str {
40    if value.is_nan() {
41        ".nan"
42    } else if value.is_sign_negative() {
43        "-.inf"
44    } else {
45        ".inf"
46    }
47}
48
49impl Value {
50    /// Stable value-kind label for diagnostics and machine-readable metadata.
51    ///
52    /// Signed and unsigned fixed-width integers both report `integer`; exact
53    /// numeric literals stored in [`Value::Number`] report `number`.
54    #[must_use]
55    pub const fn kind_name(&self) -> &'static str {
56        match self {
57            Self::Null => "null",
58            Self::Bool(_) => "boolean",
59            Self::Integer(_) | Self::Unsigned(_) => "integer",
60            Self::Float(_) => "float",
61            Self::Number(_) => "number",
62            Self::String(_) => "string",
63            Self::Array(_) => "array",
64            Self::Object(_) => "object",
65        }
66    }
67
68    pub fn is_null(&self) -> bool {
69        matches!(self, Value::Null)
70    }
71
72    pub fn is_bool(&self) -> bool {
73        matches!(self, Value::Bool(_))
74    }
75
76    pub fn as_bool(&self) -> Option<bool> {
77        match self {
78            Value::Bool(b) => Some(*b),
79            _ => None,
80        }
81    }
82
83    /// True for `Integer`/`Unsigned`, and for a [`Value::Number`] literal
84    /// with no fractional part or exponent — a big integer that only missed
85    /// `Integer`/`Unsigned` because it overflows `i64`/`u64`, not because it
86    /// is actually fractional.
87    pub fn is_integer(&self) -> bool {
88        match self {
89            Value::Integer(_) | Value::Unsigned(_) => true,
90            Value::Number(text) => is_integer_literal(text),
91            _ => false,
92        }
93    }
94
95    /// Exact `i64` value, when this holds one. `None` for a [`Value::Number`]
96    /// literal even when it is integral — by construction that variant only
97    /// exists because the literal does *not* fit `i64`/`u64`; read the exact
98    /// digits via [`Value::as_number_literal`] instead.
99    pub fn as_integer(&self) -> Option<i64> {
100        match self {
101            Value::Integer(i) => Some(*i),
102            _ => None,
103        }
104    }
105
106    pub fn as_unsigned(&self) -> Option<u64> {
107        match self {
108            Value::Unsigned(value) => Some(*value),
109            _ => None,
110        }
111    }
112
113    /// True for `Float`, and for a [`Value::Number`] literal with a
114    /// fractional part or exponent.
115    pub fn is_float(&self) -> bool {
116        match self {
117            Value::Float(_) => true,
118            Value::Number(text) => !is_integer_literal(text),
119            _ => false,
120        }
121    }
122
123    /// Best-effort numeric magnitude as `f64` — lossy for a
124    /// [`Value::Number`] literal outside `f64`'s exact range, but never
125    /// fails for a well-formed literal. Callers that need the exact digits
126    /// (not just the magnitude) must read [`Value::as_number_literal`]
127    /// instead; this accessor exists for magnitude-only consumers (numeric
128    /// comparisons, lint checks) that cannot use arbitrary precision anyway.
129    pub fn as_float(&self) -> Option<f64> {
130        match self {
131            Value::Float(f) => Some(*f),
132            Value::Number(text) => text.parse::<f64>().ok(),
133            _ => None,
134        }
135    }
136
137    /// True for a [`Value::Number`] literal (a number outside
138    /// `Integer`/`Unsigned`/`Float`'s exact range, preserved verbatim).
139    pub fn is_number_literal(&self) -> bool {
140        matches!(self, Value::Number(_))
141    }
142
143    /// The exact source text of a [`Value::Number`] literal, digit for
144    /// digit. `None` for every other variant, including `Integer`/
145    /// `Unsigned`/`Float` — those already round-trip exactly through their
146    /// own `Display`, so this accessor is specifically for the literal-only
147    /// case where that would corrupt the value.
148    pub fn as_number_literal(&self) -> Option<&str> {
149        match self {
150            Value::Number(text) => Some(text),
151            _ => None,
152        }
153    }
154
155    pub fn is_string(&self) -> bool {
156        matches!(self, Value::String(_))
157    }
158
159    pub fn as_str(&self) -> Option<&str> {
160        match self {
161            Value::String(s) => Some(s),
162            _ => None,
163        }
164    }
165
166    pub fn is_array(&self) -> bool {
167        matches!(self, Value::Array(_))
168    }
169
170    pub fn as_array(&self) -> Option<&Vec<Value>> {
171        match self {
172            Value::Array(a) => Some(a),
173            _ => None,
174        }
175    }
176
177    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
178        match self {
179            Value::Array(a) => Some(a),
180            _ => None,
181        }
182    }
183
184    pub fn is_object(&self) -> bool {
185        matches!(self, Value::Object(_))
186    }
187
188    pub fn as_object(&self) -> Option<&BTreeMap<String, Value>> {
189        match self {
190            Value::Object(o) => Some(o),
191            _ => None,
192        }
193    }
194
195    pub fn as_object_mut(&mut self) -> Option<&mut BTreeMap<String, Value>> {
196        match self {
197            Value::Object(o) => Some(o),
198            _ => None,
199        }
200    }
201
202    pub fn get(&self, key: &str) -> Option<&Value> {
203        self.as_object().and_then(|o| o.get(key))
204    }
205
206    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
207        self.as_object_mut().and_then(|o| o.get_mut(key))
208    }
209}
210
211/// True when a numeric literal's text has no fractional part or exponent —
212/// a plain (optionally negative) run of decimal digits.
213fn is_integer_literal(text: &str) -> bool {
214    !text.contains(['.', 'e', 'E'])
215}
216
217impl std::fmt::Display for Value {
218    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
219        match self {
220            Value::Null => write!(f, "null"),
221            Value::Bool(b) => write!(f, "{b}"),
222            Value::Integer(i) => write!(f, "{i}"),
223            Value::Unsigned(i) => write!(f, "{i}"),
224            Value::Float(fl) => write!(f, "{fl}"),
225            Value::Number(text) => write!(f, "{text}"),
226            Value::String(s) => write!(f, "\"{}\"", s.escape_default()),
227            Value::Array(_) => write!(f, "[...]"),
228            Value::Object(_) => write!(f, "{{...}}"),
229        }
230    }
231}
232
233impl Serialize for Value {
234    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
235        match self {
236            Value::Null => serializer.serialize_none(),
237            Value::Bool(value) => serializer.serialize_bool(*value),
238            Value::Integer(value) => serializer.serialize_i64(*value),
239            Value::Unsigned(value) => serializer.serialize_u64(*value),
240            Value::Float(value) if value.is_finite() => serializer.serialize_f64(*value),
241            Value::Float(_) => Err(serde::ser::Error::custom(
242                "non-finite float is not representable as structured data",
243            )),
244            Value::Number(text) => {
245                let number = serde_json::from_str::<serde_json::Value>(text)
246                    .ok()
247                    .filter(serde_json::Value::is_number)
248                    .ok_or_else(|| serde::ser::Error::custom("invalid preserved number literal"))?;
249                number.serialize(serializer)
250            }
251            Value::String(value) => serializer.serialize_str(value),
252            Value::Array(values) => values.serialize(serializer),
253            Value::Object(values) => values.serialize(serializer),
254        }
255    }
256}
257
258impl<'de> Deserialize<'de> for Value {
259    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
260        struct ValueVisitor;
261
262        impl<'de> de::Visitor<'de> for ValueVisitor {
263            type Value = Value;
264
265            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266                formatter.write_str("a document value")
267            }
268
269            fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
270                Ok(Value::Null)
271            }
272
273            fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
274                Ok(Value::Null)
275            }
276
277            fn visit_bool<E: de::Error>(self, value: bool) -> Result<Self::Value, E> {
278                Ok(Value::Bool(value))
279            }
280
281            fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
282                Ok(Value::Integer(value))
283            }
284
285            fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
286                Ok(Value::Unsigned(value))
287            }
288
289            fn visit_f64<E: de::Error>(self, value: f64) -> Result<Self::Value, E> {
290                Ok(Value::Float(value))
291            }
292
293            fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
294                Ok(Value::String(value.to_string()))
295            }
296
297            fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
298                Ok(Value::String(value))
299            }
300
301            fn visit_seq<A: de::SeqAccess<'de>>(
302                self,
303                mut access: A,
304            ) -> Result<Self::Value, A::Error> {
305                let mut values = Vec::new();
306                while let Some(value) = access.next_element()? {
307                    values.push(value);
308                }
309                Ok(Value::Array(values))
310            }
311
312            fn visit_map<A: de::MapAccess<'de>>(
313                self,
314                mut access: A,
315            ) -> Result<Self::Value, A::Error> {
316                let mut values = BTreeMap::new();
317                while let Some((key, value)) = access.next_entry()? {
318                    values.insert(key, value);
319                }
320                Ok(Value::Object(values))
321            }
322        }
323
324        deserializer.deserialize_any(ValueVisitor)
325    }
326}
327
328mod json_convert {
329    use super::*;
330
331    impl From<serde_json::Value> for Value {
332        fn from(v: serde_json::Value) -> Self {
333            match v {
334                serde_json::Value::Null => Value::Null,
335                serde_json::Value::Bool(b) => Value::Bool(b),
336                serde_json::Value::Number(n) => {
337                    // With the crate's `arbitrary_precision` feature enabled,
338                    // `n.as_str()` is the exact source literal — `as_i64`/
339                    // `as_u64` only succeed for a literal with no fractional
340                    // part or exponent that also fits the target width, so a
341                    // plain in-range integer still takes the exact
342                    // `Integer`/`Unsigned` path (unchanged from before);
343                    // everything else (every float literal, and integers
344                    // beyond `u64::MAX`) is preserved digit for digit as
345                    // `Value::Number` instead of being forced through `f64`.
346                    // `-0` fits `i64` but would lose its sign there; JSON
347                    // keeps a literal as written.
348                    if n.as_str() == "-0" {
349                        Value::Number(n.as_str().to_string())
350                    } else if let Some(i) = n.as_i64() {
351                        Value::Integer(i)
352                    } else if let Some(u) = n.as_u64() {
353                        Value::Unsigned(u)
354                    } else {
355                        Value::Number(n.as_str().to_string())
356                    }
357                }
358                serde_json::Value::String(s) => Value::String(s),
359                serde_json::Value::Array(a) => {
360                    Value::Array(a.into_iter().map(Value::from).collect())
361                }
362                serde_json::Value::Object(o) => {
363                    let map = o.into_iter().map(|(k, v)| (k, Value::from(v))).collect();
364                    Value::Object(map)
365                }
366            }
367        }
368    }
369
370    use super::super::PathStep;
371
372    impl Value {
373        /// Redact a selected document node in context while retaining native
374        /// numeric values that survive redaction.
375        pub fn redacted_at(
376            &self,
377            path: &[PathStep],
378            redactor: &crate::Redactor,
379        ) -> Result<Self, DocumentError> {
380            let projection = self.project_output(true, &mut Vec::new())?;
381            Ok(restore_non_finite(
382                self,
383                redactor.value_at(path, &projection),
384            ))
385        }
386    }
387
388    fn restore_non_finite(original: &Value, shown: serde_json::Value) -> Value {
389        match (original, shown) {
390            (Value::Float(value), serde_json::Value::String(text))
391                if !value.is_finite() && text == non_finite_spelling(*value) =>
392            {
393                Value::Float(*value)
394            }
395            (Value::Array(original), serde_json::Value::Array(shown)) => Value::Array(
396                original
397                    .iter()
398                    .zip(shown)
399                    .map(|(original, shown)| restore_non_finite(original, shown))
400                    .collect(),
401            ),
402            (Value::Object(original), serde_json::Value::Object(shown)) => Value::Object(
403                shown
404                    .into_iter()
405                    .map(|(key, shown)| {
406                        let value = if let Some(original) = original.get(&key) {
407                            restore_non_finite(original, shown)
408                        } else {
409                            Value::from(shown)
410                        };
411                        (key, value)
412                    })
413                    .collect(),
414            ),
415            (_, shown) => Value::from(shown),
416        }
417    }
418
419    impl TryFrom<&Value> for serde_json::Value {
420        type Error = DocumentError;
421
422        fn try_from(value: &Value) -> Result<Self, Self::Error> {
423            value.project_output(false, &mut Vec::new())
424        }
425    }
426
427    impl Value {
428        pub(crate) fn project_output(
429            &self,
430            allow_non_finite: bool,
431            path: &mut Vec<String>,
432        ) -> Result<serde_json::Value, DocumentError> {
433            use serde_json::Value as Json;
434
435            match self {
436                Self::Null => Ok(Json::Null),
437                Self::Bool(value) => Ok(Json::Bool(*value)),
438                Self::Integer(value) => Ok(Json::Number((*value).into())),
439                Self::Unsigned(value) => Ok(Json::Number((*value).into())),
440                Self::Float(value) => match serde_json::Number::from_f64(*value) {
441                    Some(value) => Ok(Json::Number(value)),
442                    None if allow_non_finite => {
443                        Ok(Json::String(super::non_finite_spelling(*value).to_owned()))
444                    }
445                    None => Err(DocumentError::NonFiniteNumber {
446                        path: crate::document::join_path(path),
447                    }),
448                },
449                Self::Number(text) => serde_json::from_str::<Json>(text)
450                    .ok()
451                    .filter(Json::is_number)
452                    .ok_or_else(|| DocumentError::UnsupportedOperation {
453                        format: "JSON".to_string(),
454                        operation: "serialize".to_string(),
455                        detail: "invalid number literal".to_string(),
456                    }),
457                Self::String(value) => Ok(Json::String(value.clone())),
458                Self::Array(values) => {
459                    let mut output = Vec::with_capacity(values.len());
460                    for (index, value) in values.iter().enumerate() {
461                        path.push(index.to_string());
462                        output.push(value.project_output(allow_non_finite, path)?);
463                        path.pop();
464                    }
465                    Ok(Json::Array(output))
466                }
467                Self::Object(values) => {
468                    let mut output = serde_json::Map::new();
469                    for (key, value) in values {
470                        path.push(key.clone());
471                        output.insert(key.clone(), value.project_output(allow_non_finite, path)?);
472                        path.pop();
473                    }
474                    Ok(Json::Object(output))
475                }
476            }
477        }
478    }
479
480    impl TryFrom<Value> for serde_json::Value {
481        type Error = DocumentError;
482
483        fn try_from(value: Value) -> Result<Self, Self::Error> {
484            Self::try_from(&value)
485        }
486    }
487}
488
489#[cfg(test)]
490mod tests {
491    use super::Value;
492    use std::collections::BTreeMap;
493
494    #[test]
495    fn value_kind_names_are_stable() {
496        let cases = [
497            (Value::Null, "null"),
498            (Value::Bool(true), "boolean"),
499            (Value::Integer(-1), "integer"),
500            (Value::Unsigned(1), "integer"),
501            (Value::Float(1.5), "float"),
502            (Value::Number("1e1000".to_string()), "number"),
503            (Value::String("value".to_string()), "string"),
504            (Value::Array(Vec::new()), "array"),
505            (Value::Object(BTreeMap::new()), "object"),
506        ];
507
508        for (value, expected) in cases {
509            assert_eq!(value.kind_name(), expected);
510        }
511    }
512
513    #[test]
514    fn json_conversion_rejects_non_finite_float() {
515        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
516            let error = serde_json::Value::try_from(Value::Float(value))
517                .expect_err("non-finite float must fail");
518            assert_eq!(error.code(), "document_non_finite_number");
519            assert!(error.to_string().contains("non-finite"));
520        }
521    }
522
523    #[test]
524    fn serde_rejects_non_finite_float_instead_of_emitting_null() {
525        let error =
526            serde_json::to_string(&Value::Float(f64::NAN)).expect_err("non-finite float must fail");
527        assert!(error.to_string().contains("non-finite"));
528    }
529}