Skip to main content

alpha2_diagnose/
tree.rs

1//! A document as a tree of values, read from text or built by a program.
2
3use std::fmt;
4
5use serde::de::{self, Deserializer, MapAccess, SeqAccess, Visitor};
6use serde::ser::{SerializeMap, SerializeSeq, Serializer};
7use serde::{Deserialize, Serialize};
8
9use crate::path::{Path, Segment};
10
11/// A place in the text a node was read from.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
13#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
14pub struct Span {
15    /// Byte offset of the first byte, in UTF-8.
16    pub offset: usize,
17    /// Length in bytes.
18    pub length: usize,
19    /// Line of the first byte, from 1.
20    pub line: u32,
21    /// Column of the first byte, from 1, counted in characters (Unicode scalar values).
22    pub column: u32,
23}
24
25impl Span {
26    /// The byte offset just past the span.
27    #[must_use]
28    pub const fn end(&self) -> usize {
29        self.offset + self.length
30    }
31
32    /// Whether `offset` lies inside the span (its end excluded, an empty span holding its start).
33    #[must_use]
34    pub const fn holds(&self, offset: usize) -> bool {
35        offset >= self.offset && (offset < self.end() || offset == self.offset)
36    }
37}
38
39/// One value of a document and where it was read from.
40#[derive(Clone, Debug, PartialEq)]
41pub struct Node {
42    /// The value.
43    pub value: Value,
44    /// Where it was read from; `None` for a node built by a program or changed by a fix.
45    pub span: Option<Span>,
46}
47
48/// The kinds of value a document holds.
49#[derive(Clone, Debug, PartialEq)]
50pub enum Value {
51    /// `null`.
52    Null,
53    /// `true` or `false`.
54    Bool(bool),
55    /// A number, kept as it was spelt.
56    Number(Number),
57    /// A string.
58    Text(String),
59    /// An array.
60    List(Vec<Node>),
61    /// An object, its entries in document order; a repeated key is kept.
62    Map(Vec<Entry>),
63}
64
65/// One key and value of a map.
66#[derive(Clone, Debug, PartialEq)]
67pub struct Entry {
68    /// The key.
69    pub key: String,
70    /// Where the key was read from, its quotes included.
71    pub key_span: Option<Span>,
72    /// The value.
73    pub value: Node,
74}
75
76/// What a number's spelling says about it.
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum NumberKind {
79    /// Digits only, with an optional minus, and not `-0`.
80    Integer,
81    /// A fraction, an exponent or `-0`.
82    Decimal,
83    /// `NaN` or an infinity, which JSON cannot spell; only a recovering reader makes one.
84    NotFinite,
85}
86
87/// A number as it was spelt, so `1920.0` and `1920` stay apart.
88#[derive(Clone, Debug, PartialEq, Eq)]
89pub struct Number {
90    text: String,
91    kind: NumberKind,
92}
93
94impl Number {
95    /// A number from a JSON spelling, or `None` when `text` is not one.
96    #[must_use]
97    pub fn parse(text: &str) -> Option<Self> {
98        let kind = json_number_kind(text)?;
99        Some(Self {
100            text: text.to_owned(),
101            kind,
102        })
103    }
104
105    /// An integer.
106    #[must_use]
107    pub fn integer(value: i64) -> Self {
108        Self {
109            text: value.to_string(),
110            kind: NumberKind::Integer,
111        }
112    }
113
114    /// An unsigned integer.
115    #[must_use]
116    pub fn unsigned(value: u64) -> Self {
117        Self {
118            text: value.to_string(),
119            kind: NumberKind::Integer,
120        }
121    }
122
123    /// A float in its shortest spelling that reads back to it; `NaN` and infinities are kept
124    /// as [`NumberKind::NotFinite`].
125    #[must_use]
126    pub fn float(value: f64) -> Self {
127        if !value.is_finite() {
128            return Self::not_finite(if value.is_nan() {
129                "NaN"
130            } else if value > 0.0 {
131                "Infinity"
132            } else {
133                "-Infinity"
134            });
135        }
136        let text = format!("{value:?}");
137        let kind = json_number_kind(&text).unwrap_or(NumberKind::Decimal);
138        Self { text, kind }
139    }
140
141    pub(crate) fn not_finite(text: &str) -> Self {
142        Self {
143            text: text.to_owned(),
144            kind: NumberKind::NotFinite,
145        }
146    }
147
148    /// The spelling.
149    #[must_use]
150    pub fn text(&self) -> &str {
151        &self.text
152    }
153
154    /// What the spelling says.
155    #[must_use]
156    pub const fn kind(&self) -> NumberKind {
157        self.kind
158    }
159
160    /// The value as a double (an infinity past its range, `NaN` for `NaN`).
161    #[must_use]
162    pub fn as_f64(&self) -> f64 {
163        match self.text.as_str() {
164            "NaN" => f64::NAN,
165            "Infinity" => f64::INFINITY,
166            "-Infinity" => f64::NEG_INFINITY,
167            text => text.parse().unwrap_or(f64::NAN),
168        }
169    }
170
171    /// The value when the spelling is an integer that fits in 128 bits.
172    #[must_use]
173    pub fn as_i128(&self) -> Option<i128> {
174        (self.kind == NumberKind::Integer)
175            .then(|| self.text.parse().ok())
176            .flatten()
177    }
178
179    /// The value when it is a whole number, whatever the spelling (`1920.0` gives 1920).
180    #[must_use]
181    pub fn whole(&self) -> Option<i128> {
182        if let Some(value) = self.as_i128() {
183            return Some(value);
184        }
185        let value = self.as_f64();
186        #[expect(
187            clippy::cast_possible_truncation,
188            reason = "checked against the range below"
189        )]
190        (value.is_finite() && value.fract() == 0.0 && value.abs() < 1e36).then_some(value as i128)
191    }
192}
193
194impl fmt::Display for Number {
195    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
196        formatter.write_str(&self.text)
197    }
198}
199
200fn json_number_kind(text: &str) -> Option<NumberKind> {
201    let bytes = text.as_bytes();
202    let mut at = usize::from(bytes.first() == Some(&b'-'));
203    let digits = |at: &mut usize| {
204        let start = *at;
205        while bytes.get(*at).is_some_and(u8::is_ascii_digit) {
206            *at += 1;
207        }
208        *at - start
209    };
210    let integer_start = at;
211    let integer_digits = digits(&mut at);
212    if integer_digits == 0 || (integer_digits > 1 && bytes[integer_start] == b'0') {
213        return None;
214    }
215    let mut decimal = false;
216    if bytes.get(at) == Some(&b'.') {
217        at += 1;
218        if digits(&mut at) == 0 {
219            return None;
220        }
221        decimal = true;
222    }
223    if matches!(bytes.get(at), Some(b'e' | b'E')) {
224        at += 1;
225        if matches!(bytes.get(at), Some(b'+' | b'-')) {
226            at += 1;
227        }
228        if digits(&mut at) == 0 {
229            return None;
230        }
231        decimal = true;
232    }
233    if at != bytes.len() {
234        return None;
235    }
236    Some(if decimal || text == "-0" {
237        NumberKind::Decimal
238    } else {
239        NumberKind::Integer
240    })
241}
242
243impl Node {
244    /// A node without a place in a text.
245    #[must_use]
246    pub const fn new(value: Value) -> Self {
247        Self { value, span: None }
248    }
249
250    /// `null`.
251    #[must_use]
252    pub const fn null() -> Self {
253        Self::new(Value::Null)
254    }
255
256    /// A boolean.
257    #[must_use]
258    pub const fn bool(value: bool) -> Self {
259        Self::new(Value::Bool(value))
260    }
261
262    /// An integer.
263    #[must_use]
264    pub fn integer(value: i64) -> Self {
265        Self::new(Value::Number(Number::integer(value)))
266    }
267
268    /// A float.
269    #[must_use]
270    pub fn float(value: f64) -> Self {
271        Self::new(Value::Number(Number::float(value)))
272    }
273
274    /// A number.
275    #[must_use]
276    pub const fn number(value: Number) -> Self {
277        Self::new(Value::Number(value))
278    }
279
280    /// A string.
281    #[must_use]
282    pub fn text(value: impl Into<String>) -> Self {
283        Self::new(Value::Text(value.into()))
284    }
285
286    /// An array.
287    #[must_use]
288    pub const fn list(items: Vec<Self>) -> Self {
289        Self::new(Value::List(items))
290    }
291
292    /// An object from keys and values, in order.
293    #[must_use]
294    pub fn map<K: Into<String>>(entries: impl IntoIterator<Item = (K, Self)>) -> Self {
295        Self::new(Value::Map(
296            entries
297                .into_iter()
298                .map(|(key, value)| Entry {
299                    key: key.into(),
300                    key_span: None,
301                    value,
302                })
303                .collect(),
304        ))
305    }
306
307    /// The JSON name of the value's kind: `null`, `boolean`, `number`, `string`, `array` or
308    /// `object`.
309    #[must_use]
310    pub const fn kind_name(&self) -> &'static str {
311        match self.value {
312            Value::Null => "null",
313            Value::Bool(_) => "boolean",
314            Value::Number(_) => "number",
315            Value::Text(_) => "string",
316            Value::List(_) => "array",
317            Value::Map(_) => "object",
318        }
319    }
320
321    /// The string, when the node is one.
322    #[must_use]
323    pub fn as_str(&self) -> Option<&str> {
324        match &self.value {
325            Value::Text(text) => Some(text),
326            _ => None,
327        }
328    }
329
330    /// The number, when the node is one.
331    #[must_use]
332    pub const fn as_number(&self) -> Option<&Number> {
333        match &self.value {
334            Value::Number(number) => Some(number),
335            _ => None,
336        }
337    }
338
339    /// The boolean, when the node is one.
340    #[must_use]
341    pub const fn as_bool(&self) -> Option<bool> {
342        match self.value {
343            Value::Bool(value) => Some(value),
344            _ => None,
345        }
346    }
347
348    /// The items, when the node is an array.
349    #[must_use]
350    pub fn as_list(&self) -> Option<&[Self]> {
351        match &self.value {
352            Value::List(items) => Some(items),
353            _ => None,
354        }
355    }
356
357    /// The entries, when the node is an object.
358    #[must_use]
359    pub fn as_map(&self) -> Option<&[Entry]> {
360        match &self.value {
361            Value::Map(entries) => Some(entries),
362            _ => None,
363        }
364    }
365
366    /// The value under `key` in an object; of a repeated key, the last, as JSON readers keep.
367    #[must_use]
368    pub fn get(&self, key: &str) -> Option<&Self> {
369        self.as_map()?
370            .iter()
371            .rev()
372            .find(|entry| entry.key == key)
373            .map(|entry| &entry.value)
374    }
375
376    /// The entry under `key` in an object (the last of a repeated key).
377    #[must_use]
378    pub fn entry(&self, key: &str) -> Option<&Entry> {
379        self.as_map()?.iter().rev().find(|entry| entry.key == key)
380    }
381
382    /// The node a path names, its root name ignored.
383    #[must_use]
384    pub fn at(&self, path: &Path) -> Option<&Self> {
385        path.segments()
386            .iter()
387            .try_fold(self, |node, segment| node.child(segment))
388    }
389
390    /// The node a path names, for change.
391    pub fn at_mut(&mut self, path: &Path) -> Option<&mut Self> {
392        path.segments()
393            .iter()
394            .try_fold(self, |node, segment| node.child_mut(segment))
395    }
396
397    /// The child a segment names.
398    #[must_use]
399    pub fn child(&self, segment: &Segment) -> Option<&Self> {
400        match (segment, &self.value) {
401            (Segment::Key(key), Value::Map(_)) => self.get(key),
402            (Segment::Index(index), Value::List(items)) => items.get(*index),
403            _ => None,
404        }
405    }
406
407    /// The child a segment names, for change.
408    pub fn child_mut(&mut self, segment: &Segment) -> Option<&mut Self> {
409        match (segment, &mut self.value) {
410            (Segment::Key(key), Value::Map(entries)) => entries
411                .iter_mut()
412                .rev()
413                .find(|entry| entry.key == *key)
414                .map(|entry| &mut entry.value),
415            (Segment::Index(index), Value::List(items)) => items.get_mut(*index),
416            _ => None,
417        }
418    }
419
420    /// The number of nodes in the tree, this one included.
421    #[must_use]
422    pub fn count(&self) -> usize {
423        1 + match &self.value {
424            Value::List(items) => items.iter().map(Self::count).sum(),
425            Value::Map(entries) => entries.iter().map(|entry| entry.value.count()).sum(),
426            _ => 0,
427        }
428    }
429
430    /// Whether two trees hold the same document, places ignored: keys in order, repeated keys
431    /// kept, numbers by their spelling.
432    #[must_use]
433    pub fn same_document(&self, other: &Self) -> bool {
434        match (&self.value, &other.value) {
435            (Value::List(left), Value::List(right)) => {
436                left.len() == right.len()
437                    && left
438                        .iter()
439                        .zip(right)
440                        .all(|(left, right)| left.same_document(right))
441            }
442            (Value::Map(left), Value::Map(right)) => {
443                left.len() == right.len()
444                    && left.iter().zip(right).all(|(left, right)| {
445                        left.key == right.key && left.value.same_document(&right.value)
446                    })
447            }
448            (left, right) => left == right,
449        }
450    }
451
452    /// Whether two values are equal as JSON values: numbers by value, objects by their last
453    /// value per key whatever the order.
454    #[must_use]
455    pub fn same_value(&self, other: &Self) -> bool {
456        match (&self.value, &other.value) {
457            (Value::Number(left), Value::Number(right)) => {
458                match (left.as_i128(), right.as_i128()) {
459                    (Some(left), Some(right)) => left == right,
460                    _ => left.as_f64().total_cmp(&right.as_f64()).is_eq(),
461                }
462            }
463            (Value::List(left), Value::List(right)) => {
464                left.len() == right.len()
465                    && left
466                        .iter()
467                        .zip(right)
468                        .all(|(left, right)| left.same_value(right))
469            }
470            (Value::Map(left), Value::Map(_)) => {
471                map_keys(self) == map_keys(other)
472                    && left.iter().all(|entry| {
473                        self.get(&entry.key)
474                            .zip(other.get(&entry.key))
475                            .is_some_and(|(left, right)| left.same_value(right))
476                    })
477            }
478            (left, right) => left == right,
479        }
480    }
481
482    /// The tree with every place removed, as a program would build it.
483    #[must_use]
484    pub fn without_spans(mut self) -> Self {
485        self.clear_spans();
486        self
487    }
488
489    fn clear_spans(&mut self) {
490        self.span = None;
491        match &mut self.value {
492            Value::List(items) => items.iter_mut().for_each(Self::clear_spans),
493            Value::Map(entries) => {
494                for entry in entries {
495                    entry.key_span = None;
496                    entry.value.clear_spans();
497                }
498            }
499            _ => {}
500        }
501    }
502}
503
504fn map_keys(node: &Node) -> Vec<&str> {
505    let mut keys: Vec<&str> = node
506        .as_map()
507        .unwrap_or_default()
508        .iter()
509        .map(|entry| entry.key.as_str())
510        .collect();
511    keys.sort_unstable();
512    keys.dedup();
513    keys
514}
515
516impl From<bool> for Node {
517    fn from(value: bool) -> Self {
518        Self::bool(value)
519    }
520}
521
522impl From<i64> for Node {
523    fn from(value: i64) -> Self {
524        Self::integer(value)
525    }
526}
527
528impl From<u64> for Node {
529    fn from(value: u64) -> Self {
530        Self::number(Number::unsigned(value))
531    }
532}
533
534impl From<usize> for Node {
535    fn from(value: usize) -> Self {
536        Self::number(Number::unsigned(value as u64))
537    }
538}
539
540impl From<f64> for Node {
541    fn from(value: f64) -> Self {
542        Self::float(value)
543    }
544}
545
546impl From<&str> for Node {
547    fn from(value: &str) -> Self {
548        Self::text(value)
549    }
550}
551
552impl From<String> for Node {
553    fn from(value: String) -> Self {
554        Self::text(value)
555    }
556}
557
558impl<T: Into<Self>> From<Vec<T>> for Node {
559    fn from(items: Vec<T>) -> Self {
560        Self::list(items.into_iter().map(Into::into).collect())
561    }
562}
563
564impl Serialize for Node {
565    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
566        match &self.value {
567            Value::Null => serializer.serialize_unit(),
568            Value::Bool(value) => serializer.serialize_bool(*value),
569            Value::Number(number) => {
570                if let Some(value) = number.as_i128() {
571                    if let Ok(value) = i64::try_from(value) {
572                        return serializer.serialize_i64(value);
573                    }
574                    if let Ok(value) = u64::try_from(value) {
575                        return serializer.serialize_u64(value);
576                    }
577                    return serializer.serialize_i128(value);
578                }
579                let value = number.as_f64();
580                if value.is_finite() {
581                    serializer.serialize_f64(value)
582                } else {
583                    serializer.serialize_unit()
584                }
585            }
586            Value::Text(text) => serializer.serialize_str(text),
587            Value::List(items) => {
588                let mut seq = serializer.serialize_seq(Some(items.len()))?;
589                for item in items {
590                    seq.serialize_element(item)?;
591                }
592                seq.end()
593            }
594            Value::Map(entries) => {
595                let mut map = serializer.serialize_map(Some(entries.len()))?;
596                for entry in entries {
597                    map.serialize_entry(&entry.key, &entry.value)?;
598                }
599                map.end()
600            }
601        }
602    }
603}
604
605impl<'de> Deserialize<'de> for Node {
606    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
607        deserializer.deserialize_any(NodeVisitor)
608    }
609}
610
611struct NodeVisitor;
612
613impl<'de> Visitor<'de> for NodeVisitor {
614    type Value = Node;
615
616    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
617        formatter.write_str("any JSON value")
618    }
619
620    fn visit_unit<E: de::Error>(self) -> Result<Node, E> {
621        Ok(Node::null())
622    }
623
624    fn visit_none<E: de::Error>(self) -> Result<Node, E> {
625        Ok(Node::null())
626    }
627
628    fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Node, D::Error> {
629        Node::deserialize(deserializer)
630    }
631
632    fn visit_bool<E: de::Error>(self, value: bool) -> Result<Node, E> {
633        Ok(Node::bool(value))
634    }
635
636    fn visit_i64<E: de::Error>(self, value: i64) -> Result<Node, E> {
637        Ok(Node::integer(value))
638    }
639
640    fn visit_u64<E: de::Error>(self, value: u64) -> Result<Node, E> {
641        Ok(Node::from(value))
642    }
643
644    fn visit_i128<E: de::Error>(self, value: i128) -> Result<Node, E> {
645        Ok(Node::number(Number {
646            text: value.to_string(),
647            kind: NumberKind::Integer,
648        }))
649    }
650
651    fn visit_u128<E: de::Error>(self, value: u128) -> Result<Node, E> {
652        Ok(Node::number(Number {
653            text: value.to_string(),
654            kind: NumberKind::Integer,
655        }))
656    }
657
658    fn visit_f64<E: de::Error>(self, value: f64) -> Result<Node, E> {
659        Ok(Node::float(value))
660    }
661
662    fn visit_str<E: de::Error>(self, value: &str) -> Result<Node, E> {
663        Ok(Node::text(value))
664    }
665
666    fn visit_string<E: de::Error>(self, value: String) -> Result<Node, E> {
667        Ok(Node::text(value))
668    }
669
670    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Node, A::Error> {
671        let mut items = Vec::new();
672        while let Some(item) = seq.next_element()? {
673            items.push(item);
674        }
675        Ok(Node::list(items))
676    }
677
678    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Node, A::Error> {
679        let mut entries = Vec::new();
680        while let Some((key, value)) = map.next_entry::<String, Node>()? {
681            entries.push((key, value));
682        }
683        Ok(Node::map(entries))
684    }
685}
686
687#[cfg(feature = "schema")]
688impl schemars::JsonSchema for Node {
689    fn schema_name() -> std::borrow::Cow<'static, str> {
690        "Value".into()
691    }
692
693    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
694        schemars::json_schema!({ "description": "Any JSON value." })
695    }
696}
697
698#[cfg(test)]
699mod tests {
700    use super::*;
701
702    #[test]
703    fn number_spelling_sets_its_kind() {
704        assert_eq!(Number::parse("1920").unwrap().kind(), NumberKind::Integer);
705        assert_eq!(Number::parse("1920.0").unwrap().kind(), NumberKind::Decimal);
706        assert_eq!(Number::parse("1e3").unwrap().kind(), NumberKind::Decimal);
707        assert_eq!(Number::parse("-0").unwrap().kind(), NumberKind::Decimal);
708        assert_eq!(Number::parse("-12").unwrap().kind(), NumberKind::Integer);
709        for bad in ["", "-", "01", "1.", ".5", "+1", "1e", "1e+", "0x10", "NaN"] {
710            assert!(Number::parse(bad).is_none(), "{bad}");
711        }
712    }
713
714    #[test]
715    fn number_values() {
716        assert_eq!(Number::parse("1920.0").unwrap().whole(), Some(1920));
717        assert_eq!(Number::parse("1920.5").unwrap().whole(), None);
718        assert_eq!(Number::parse("1920.0").unwrap().as_i128(), None);
719        assert_eq!(
720            Number::parse("18446744073709551616").unwrap().as_i128(),
721            Some(1 << 64)
722        );
723        assert_eq!(Number::float(0.5).text(), "0.5");
724        assert_eq!(Number::float(1.0).kind(), NumberKind::Decimal);
725        assert_eq!(Number::float(f64::NAN).kind(), NumberKind::NotFinite);
726    }
727
728    #[test]
729    fn get_takes_the_last_repeated_key() {
730        let node = Node::map([("a", Node::integer(1)), ("a", Node::integer(2))]);
731        assert_eq!(node.get("a"), Some(&Node::integer(2)));
732        assert_eq!(node.count(), 3);
733    }
734
735    #[test]
736    fn same_value_ignores_spelling_and_order() {
737        let left = Node::map([("a", Node::integer(1)), ("b", Node::float(2.0))]);
738        let right = Node::map([("b", Node::integer(2)), ("a", Node::float(1.0))]);
739        assert!(left.same_value(&right));
740        assert!(!left.same_document(&right));
741    }
742
743    #[test]
744    fn at_follows_keys_and_indexes() {
745        let node = Node::map([("a", Node::list(vec![Node::null(), Node::text("x")]))]);
746        let path = Path::root("doc").key("a").index(1);
747        assert_eq!(node.at(&path), Some(&Node::text("x")));
748        assert_eq!(node.at(&Path::root("doc").key("b")), None);
749    }
750}