Skip to main content

agent_first_data/document/format/
json.rs

1//! JSON format backend (via serde_json).
2
3use crate::document::{DocumentError, DocumentResult, Value};
4
5/// Lossless JSON source document. The parsed node tree stores byte spans for
6/// every value/member, so editors can replace only the requested span while
7/// retaining untouched ordering, whitespace, escapes, and number spelling.
8#[derive(Debug)]
9pub struct JsonDocument<'a> {
10    source: &'a str,
11    root: Node,
12}
13
14impl<'a> JsonDocument<'a> {
15    pub fn parse(source: &'a str) -> DocumentResult<Self> {
16        if source.starts_with('\u{feff}') {
17            return Err(DocumentError::SourceRefused {
18                format: "JSON".to_string(),
19                detail: "line 1, column 1: unexpected UTF-8 byte-order mark (BOM)".to_string(),
20            });
21        }
22        let mut parser = Parser::new(source)?;
23        let root = parser.parse_value(0)?;
24        if parser.skip_ws(root.end) != source.len() {
25            return Err(DocumentError::ParseError {
26                format: "JSON".to_string(),
27                detail: "trailing bytes after root value".to_string(),
28            });
29        }
30        Ok(Self { source, root })
31    }
32
33    #[must_use]
34    pub fn source(&self) -> &'a str {
35        self.source
36    }
37
38    #[must_use]
39    pub(crate) fn root(&self) -> &Node {
40        &self.root
41    }
42}
43
44/// Set a JSON value at `path` while retaining every byte outside the edited
45/// region. JSON has no comments, but this still preserves key order,
46/// whitespace, line endings, escapes, and untouched number spellings.
47///
48/// Matches the in-memory [`crate::document::set_path`] capability:
49/// - an existing value (scalar *or* collection) is replaced in place;
50/// - a missing leaf, and any missing intermediate parent objects, are created
51///   under the deepest existing ancestor object.
52pub(crate) fn set_preserving(content: &str, path: &str, value: &Value) -> DocumentResult<String> {
53    let segments = crate::document::parse_path(path)?;
54    let document = JsonDocument::parse(content)?;
55    let root = document.root();
56    let mut output = content.to_string();
57    if segments.last().is_some_and(|segment| segment == "-")
58        && let Some(parent) = resolve(root, &segments[..segments.len() - 1], 0)
59        && matches!(parent.kind, NodeKind::Array(_))
60    {
61        return append_array_item_preserving(
62            content,
63            &crate::document::join_path(&segments[..segments.len() - 1]),
64            value,
65        );
66    }
67    match resolve(root, &segments, 0) {
68        Some(target) => {
69            // Replace the whole existing node span — scalar or collection. A
70            // replaced collection is re-rendered compactly; everything outside
71            // its span (and key order) is untouched.
72            let replacement = compact_json(value)?;
73            output.replace_range(target.start..target.end, &replacement);
74        }
75        None => {
76            // The full path is absent. Find the deepest existing ancestor
77            // object, then splice one new member holding the remaining path
78            // chain wrapped around the leaf value — creating every missing
79            // intermediate object along the way.
80            let (insert_at, tail) = deepest_existing_object(root, &segments).ok_or_else(|| {
81                DocumentError::UnsupportedOperation {
82                    format: "JSON".to_string(),
83                    operation: "set".to_string(),
84                    detail: "cannot insert a new key into a non-object JSON value".to_string(),
85                }
86            })?;
87            let NodeKind::Object(entries) = &insert_at.kind else {
88                unreachable!("deepest_existing_object only returns object nodes");
89            };
90            let (member_key, rest) = tail.split_first().ok_or(DocumentError::EmptyPath)?;
91            let new_key =
92                serde_json::to_string(member_key).map_err(|error| serialization_failed(&error))?;
93            let layout = Layout::of(content);
94            let (position, fragment) = match entries.last() {
95                Some((_, last_node)) => {
96                    let anchor = last_node.member_start.unwrap_or(last_node.start);
97                    let (indent, multiline) = member_indent(content.as_bytes(), anchor);
98                    let member_value =
99                        nested_member_value(rest, value, multiline, &indent, &layout)?;
100                    let fragment = if multiline {
101                        format!(",{}{indent}{new_key}: {member_value}", layout.newline)
102                    } else {
103                        let colon_layout = &content[anchor..last_node.start];
104                        let after_key = colon_layout.rfind(':').map_or(":", |colon| {
105                            let before = colon_layout[..colon].trim_end().len();
106                            &colon_layout[before..]
107                        });
108                        let separator = if let Some((_, previous)) = entries.iter().rev().nth(1) {
109                            &content[previous.end..anchor]
110                        } else if after_key.len() > 1 || anchor > insert_at.start + 1 {
111                            ", "
112                        } else {
113                            ","
114                        };
115                        format!("{separator}{new_key}{after_key}{member_value}")
116                    };
117                    (last_node.end, fragment)
118                }
119                None => {
120                    let (indent, multiline) = layout.first_member(content, insert_at);
121                    let member_value =
122                        nested_member_value(rest, value, multiline, &indent, &layout)?;
123                    let prefix = if multiline { layout.newline } else { "" };
124                    (
125                        insert_at.start + 1,
126                        format!("{prefix}{indent}{new_key}: {member_value}"),
127                    )
128                }
129            };
130            output.insert_str(position, &fragment);
131        }
132    }
133    serde_json::from_str::<serde_json::Value>(&output).map_err(|error| {
134        DocumentError::ParseError {
135            format: "JSON".to_string(),
136            detail: error.to_string(),
137        }
138    })?;
139    Ok(output)
140}
141
142/// Compact one-line JSON rendering of a document value.
143fn compact_json(value: &Value) -> DocumentResult<String> {
144    let json_value = serde_json::Value::try_from(value)?;
145    serde_json::to_string(&json_value).map_err(|error| DocumentError::UnsupportedOperation {
146        format: "JSON".to_string(),
147        operation: "set".to_string(),
148        detail: error.to_string(),
149    })
150}
151
152/// The deepest node reachable along `segments` that is an object, paired with
153/// the still-missing tail below it. Returns `None` if that deepest existing
154/// node is not an object (so a child key cannot be created under it).
155fn deepest_existing_object<'a>(
156    root: &'a Node,
157    segments: &'a [String],
158) -> Option<(&'a Node, &'a [String])> {
159    // `segments` itself does not resolve (checked by the caller), so start one
160    // level up and walk toward the root; the root (empty prefix) always exists.
161    for split in (0..segments.len()).rev() {
162        if let Some(node) = resolve(root, &segments[..split], 0) {
163            return match node.kind {
164                NodeKind::Object(_) => Some((node, &segments[split..])),
165                _ => None,
166            };
167        }
168    }
169    None
170}
171
172/// Render the value for a spliced member: the leaf `value` wrapped in an object
173/// for each remaining `tail` segment (`["a","b"] , v` → `{"a":{"b":v}}`).
174/// Multiline output is re-indented to sit at `base_indent`.
175fn nested_member_value(
176    tail: &[String],
177    value: &Value,
178    multiline: bool,
179    base_indent: &str,
180    layout: &Layout,
181) -> DocumentResult<String> {
182    use serde::Serialize as _;
183    let mut nested = serde_json::Value::try_from(value)?;
184    for segment in tail.iter().rev() {
185        let mut object = serde_json::Map::new();
186        object.insert(segment.clone(), nested);
187        nested = serde_json::Value::Object(object);
188    }
189    if multiline {
190        let mut buffer = Vec::new();
191        let formatter = serde_json::ser::PrettyFormatter::with_indent(layout.unit.as_bytes());
192        let mut serializer = serde_json::Serializer::with_formatter(&mut buffer, formatter);
193        nested
194            .serialize(&mut serializer)
195            .map_err(|error| serialization_failed(&error))?;
196        let pretty = String::from_utf8(buffer).map_err(|error| serialization_failed(&error))?;
197        Ok(pretty.replace('\n', &format!("{}{base_indent}", layout.newline)))
198    } else {
199        serde_json::to_string(&nested).map_err(|error| serialization_failed(&error))
200    }
201}
202
203/// How a JSON source lays itself out, so spliced text matches it: its line
204/// ending and the indentation of one nesting level.
205struct Layout {
206    newline: &'static str,
207    unit: String,
208}
209
210impl Layout {
211    fn of(content: &str) -> Self {
212        let newline = if content.contains("\r\n") {
213            "\r\n"
214        } else {
215            "\n"
216        };
217        // The first indented line is a child of the root container, so its
218        // indentation is one level, in whatever characters the file uses.
219        let unit = content
220            .lines()
221            .skip(1)
222            .find_map(|line| {
223                let indent = &line[..line.len() - line.trim_start_matches([' ', '\t']).len()];
224                (!indent.is_empty() && !line.trim().is_empty()).then(|| indent.to_string())
225            })
226            .unwrap_or_else(|| "  ".to_string());
227        Self { newline, unit }
228    }
229
230    /// Use the closing delimiter's indent when the empty container spans lines.
231    fn first_member(&self, content: &str, container: &Node) -> (String, bool) {
232        let close = container.end - 1;
233        let (mut indent, multiline) = member_indent(content.as_bytes(), close);
234        if multiline && content[container.start..close].contains('\n') {
235            indent.push_str(&self.unit);
236            (indent, true)
237        } else {
238            (String::new(), false)
239        }
240    }
241}
242
243/// serde_json could not render a value that is already in hand. Nothing was
244/// parsed, so this is not a parse failure.
245fn serialization_failed(error: &dyn std::fmt::Display) -> DocumentError {
246    DocumentError::UnsupportedOperation {
247        format: "JSON".to_string(),
248        operation: "set".to_string(),
249        detail: format!("value is not representable as JSON: {error}"),
250    }
251}
252
253/// Indentation of the member whose key begins at `anchor`, and whether that
254/// member sits on its own line (so a spliced sibling should too).
255fn member_indent(bytes: &[u8], anchor: usize) -> (String, bool) {
256    match bytes[..anchor].iter().rposition(|byte| *byte == b'\n') {
257        Some(newline)
258            if bytes[newline + 1..anchor]
259                .iter()
260                .all(|byte| matches!(byte, b' ' | b'\t')) =>
261        {
262            let indent = bytes[newline + 1..anchor]
263                .iter()
264                .take_while(|byte| matches!(byte, b' ' | b'\t'))
265                .map(|byte| *byte as char)
266                .collect();
267            (indent, true)
268        }
269        _ => (String::new(), false),
270    }
271}
272
273/// Remove one existing JSON member or array item while preserving the rest of
274/// the source layout. Removing the root value is intentionally unsupported.
275pub(crate) fn unset_preserving(content: &str, path: &str) -> DocumentResult<String> {
276    let segments = crate::document::parse_path(path)?;
277    let document = JsonDocument::parse(content)?;
278    let (last, parents) = segments.split_last().ok_or(DocumentError::EmptyPath)?;
279    let missing = || DocumentError::PathNotFound {
280        path: path.to_string(),
281    };
282    let parent = resolve(document.root(), parents, 0).ok_or_else(missing)?;
283    match &parent.kind {
284        NodeKind::Object(entries) => {
285            let index = entries
286                .iter()
287                .rposition(|(key, _)| key == last)
288                .ok_or_else(missing)?;
289            remove_child(
290                content,
291                parent,
292                index,
293                entries.iter().map(|(_, child)| child),
294            )
295        }
296        NodeKind::Array(items) => {
297            let index = last
298                .parse::<usize>()
299                .ok()
300                .filter(|&index| index < items.len())
301                .ok_or_else(missing)?;
302            remove_child(content, parent, index, items.iter())
303        }
304        NodeKind::Scalar => Err(missing()),
305    }
306}
307
308/// Append one JSON array item while retaining the existing array's trailing
309/// whitespace and all bytes outside the insertion point.
310pub(crate) fn append_array_item_preserving(
311    content: &str,
312    path: &str,
313    item: &Value,
314) -> DocumentResult<String> {
315    let segments = array_path_segments(path)?;
316    let mut parser = Parser::new(content)?;
317    let root = parser.parse_value(0)?;
318    let target = resolve(&root, &segments, 0).ok_or_else(|| DocumentError::PathNotFound {
319        path: path.to_string(),
320    })?;
321    let NodeKind::Array(items) = &target.kind else {
322        return Err(DocumentError::UnsupportedOperation {
323            format: "JSON".to_string(),
324            operation: "add".to_string(),
325            detail: "target is not an array".to_string(),
326        });
327    };
328    let layout = Layout::of(content);
329    let (position, indent, multiline) = if let Some(last) = items.last() {
330        let (indent, multiline) = member_indent(content.as_bytes(), last.start);
331        (last.end, indent, multiline)
332    } else {
333        let (indent, multiline) = layout.first_member(content, target);
334        (target.start + 1, indent, multiline)
335    };
336    let fragment = nested_member_value(&[], item, multiline, &indent, &layout).map_err(
337        |error| match error {
338            DocumentError::UnsupportedOperation { format, detail, .. } => {
339                DocumentError::UnsupportedOperation {
340                    format,
341                    detail,
342                    operation: "add".into(),
343                }
344            }
345            other => other,
346        },
347    )?;
348    let insertion = if items.is_empty() {
349        let prefix = if multiline { layout.newline } else { "" };
350        format!("{prefix}{indent}{fragment}")
351    } else if multiline {
352        format!(",{}{indent}{fragment}", layout.newline)
353    } else {
354        let last = &items[items.len() - 1];
355        let gap = if let Some(previous) = items.iter().rev().nth(1) {
356            let after_comma = skip_ws_bytes(content.as_bytes(), previous.end) + 1;
357            &content[after_comma..last.start]
358        } else {
359            &content[target.start + 1..last.start]
360        };
361        format!(",{gap}{fragment}")
362    };
363    let mut output = content.to_string();
364    output.insert_str(position, &insertion);
365    Ok(output)
366}
367
368/// Remove one item from a JSON array by numeric index without rebuilding the
369/// document.
370pub(crate) fn remove_array_item_preserving(
371    content: &str,
372    path: &str,
373    index: usize,
374) -> DocumentResult<String> {
375    let segments = array_path_segments(path)?;
376    let mut parser = Parser::new(content)?;
377    let root = parser.parse_value(0)?;
378    let target = resolve(&root, &segments, 0).ok_or_else(|| DocumentError::PathNotFound {
379        path: path.to_string(),
380    })?;
381    let NodeKind::Array(items) = &target.kind else {
382        return Err(DocumentError::UnsupportedOperation {
383            format: "JSON".to_string(),
384            operation: "remove".to_string(),
385            detail: "target is not an array".to_string(),
386        });
387    };
388    if index >= items.len() {
389        return Err(DocumentError::IndexOutOfBounds {
390            path: path.to_string(),
391            index,
392            len: items.len(),
393        });
394    }
395    remove_child(content, target, index, items.iter())
396}
397
398fn remove_child<'a>(
399    content: &str,
400    parent: &Node,
401    index: usize,
402    mut children: impl ExactSizeIterator<Item = &'a Node>,
403) -> DocumentResult<String> {
404    let count = children.len();
405    let start_of = |node: &Node| node.member_start.unwrap_or(node.start);
406    let range = if count == 1 {
407        parent.start + 1..parent.end - 1
408    } else if index == 0 {
409        let first = children.next().ok_or(DocumentError::EmptyPath)?;
410        let next = children.next().ok_or(DocumentError::EmptyPath)?;
411        start_of(first)..start_of(next)
412    } else {
413        let previous = children.nth(index - 1).ok_or(DocumentError::EmptyPath)?;
414        let node = children.next().ok_or(DocumentError::EmptyPath)?;
415        if let Some(next) = children.next() {
416            start_of(node)..start_of(next)
417        } else {
418            previous.end..node.end
419        }
420    };
421    let mut output = content.to_string();
422    output.replace_range(range, "");
423    Ok(output)
424}
425
426/// An empty keyed-list prefix names a root array. Other document operations
427/// continue to reject an empty dot-path because they require an addressed
428/// child.
429fn array_path_segments(path: &str) -> DocumentResult<Vec<String>> {
430    if path.is_empty() {
431        Ok(Vec::new())
432    } else {
433        crate::document::parse_path(path)
434    }
435}
436
437fn skip_ws_bytes(source: &[u8], mut position: usize) -> usize {
438    while source
439        .get(position)
440        .is_some_and(|byte| matches!(byte, b' ' | b'\n' | b'\r' | b'\t'))
441    {
442        position += 1;
443    }
444    position
445}
446
447#[derive(Debug, Clone)]
448pub(crate) struct Node {
449    start: usize,
450    end: usize,
451    member_start: Option<usize>,
452    kind: NodeKind,
453}
454
455#[derive(Debug, Clone)]
456enum NodeKind {
457    Scalar,
458    Object(Vec<(String, Node)>),
459    Array(Vec<Node>),
460}
461
462fn resolve<'a>(node: &'a Node, segments: &[String], index: usize) -> Option<&'a Node> {
463    if index == segments.len() {
464        return Some(node);
465    }
466    match &node.kind {
467        NodeKind::Object(entries) => entries
468            .iter()
469            .rev()
470            .find(|(key, _)| key == &segments[index])
471            .and_then(|(_, child)| resolve(child, segments, index + 1)),
472        NodeKind::Array(items) => segments[index]
473            .parse::<usize>()
474            .ok()
475            .and_then(|item| items.get(item))
476            .and_then(|child| resolve(child, segments, index + 1)),
477        NodeKind::Scalar => None,
478    }
479}
480
481struct Parser<'a> {
482    source: &'a [u8],
483}
484
485impl<'a> Parser<'a> {
486    fn new(source: &'a str) -> DocumentResult<Self> {
487        // Validate the complete grammar and recursion budget before scanning
488        // spans. Otherwise an edit could repair malformed input silently, or
489        // unbounded nesting could exhaust the stack before semantic loading.
490        serde_json::from_str::<serde_json::Value>(source).map_err(|error| {
491            DocumentError::ParseError {
492                format: "JSON".to_string(),
493                detail: error.to_string(),
494            }
495        })?;
496        Ok(Self {
497            source: source.as_bytes(),
498        })
499    }
500
501    fn parse_value(&mut self, mut position: usize) -> DocumentResult<Node> {
502        position = self.skip_ws(position);
503        let start = position;
504        let Some(byte) = self.source.get(position).copied() else {
505            return self.error(position, "expected JSON value");
506        };
507        let kind = match byte {
508            b'{' => self.parse_object(&mut position)?,
509            b'[' => self.parse_array(&mut position)?,
510            b'"' => {
511                position = self.parse_string(position)?;
512                NodeKind::Scalar
513            }
514            _ => {
515                position = self.parse_scalar(position)?;
516                NodeKind::Scalar
517            }
518        };
519        Ok(Node {
520            start,
521            end: position,
522            member_start: None,
523            kind,
524        })
525    }
526
527    fn parse_object(&mut self, position: &mut usize) -> DocumentResult<NodeKind> {
528        *position += 1;
529        let mut entries = Vec::new();
530        let mut keys = std::collections::HashSet::new();
531        loop {
532            *position = self.skip_ws(*position);
533            if self.source.get(*position) == Some(&b'}') {
534                *position += 1;
535                return Ok(NodeKind::Object(entries));
536            }
537            let key_start = *position;
538            let key_end = self.parse_string(*position)?;
539            let key = serde_json::from_slice::<String>(&self.source[key_start..key_end]).map_err(
540                |error| DocumentError::ParseError {
541                    format: "JSON".to_string(),
542                    detail: error.to_string(),
543                },
544            )?;
545            if !keys.insert(key.clone()) {
546                return self.error(key_start, "duplicate object key");
547            }
548            *position = self.skip_ws(key_end);
549            if self.source.get(*position) != Some(&b':') {
550                return self.error(*position, "expected `:` after object key");
551            }
552            *position += 1;
553            let child = self.parse_value(*position)?;
554            *position = child.end;
555            let mut child = child;
556            child.member_start = Some(key_start);
557            entries.push((key, child));
558            *position = self.skip_ws(*position);
559            match self.source.get(*position) {
560                Some(b',') => *position += 1,
561                Some(b'}') => {
562                    *position += 1;
563                    return Ok(NodeKind::Object(entries));
564                }
565                _ => return self.error(*position, "expected `,` or `}` in object"),
566            }
567        }
568    }
569
570    fn parse_array(&mut self, position: &mut usize) -> DocumentResult<NodeKind> {
571        *position += 1;
572        let mut items = Vec::new();
573        loop {
574            *position = self.skip_ws(*position);
575            if self.source.get(*position) == Some(&b']') {
576                *position += 1;
577                return Ok(NodeKind::Array(items));
578            }
579            let child = self.parse_value(*position)?;
580            *position = child.end;
581            items.push(child);
582            *position = self.skip_ws(*position);
583            match self.source.get(*position) {
584                Some(b',') => *position += 1,
585                Some(b']') => {
586                    *position += 1;
587                    return Ok(NodeKind::Array(items));
588                }
589                _ => return self.error(*position, "expected `,` or `]` in array"),
590            }
591        }
592    }
593
594    fn parse_string(&self, mut position: usize) -> DocumentResult<usize> {
595        if self.source.get(position) != Some(&b'"') {
596            return self.error(position, "expected JSON string");
597        }
598        position += 1;
599        let mut escaped = false;
600        while let Some(byte) = self.source.get(position).copied() {
601            position += 1;
602            if escaped {
603                escaped = false;
604            } else if byte == b'\\' {
605                escaped = true;
606            } else if byte == b'"' {
607                return Ok(position);
608            }
609        }
610        self.error(position, "unterminated JSON string")
611    }
612
613    fn parse_scalar(&self, mut position: usize) -> DocumentResult<usize> {
614        let start = position;
615        while let Some(byte) = self.source.get(position).copied() {
616            if matches!(byte, b',' | b']' | b'}' | b' ' | b'\n' | b'\r' | b'\t') {
617                break;
618            }
619            position += 1;
620        }
621        if position == start {
622            return self.error(position, "empty JSON scalar");
623        }
624        serde_json::from_slice::<serde_json::Value>(&self.source[start..position])
625            .map_err(|error| DocumentError::ParseError {
626                format: "JSON".to_string(),
627                detail: error.to_string(),
628            })
629            .map(|_| position)
630    }
631
632    fn skip_ws(&self, mut position: usize) -> usize {
633        while self
634            .source
635            .get(position)
636            .is_some_and(|byte| matches!(byte, b' ' | b'\n' | b'\r' | b'\t'))
637        {
638            position += 1;
639        }
640        position
641    }
642
643    fn error<T>(&self, position: usize, detail: &str) -> DocumentResult<T> {
644        Err(DocumentError::ParseError {
645            format: "JSON".to_string(),
646            detail: format!("at byte {position}: {detail}"),
647        })
648    }
649}
650
651pub fn load(content: &str) -> DocumentResult<Value> {
652    JsonDocument::parse(content)?;
653    serde_json::from_str::<serde_json::Value>(content)
654        .map(Value::from)
655        .map_err(|e| DocumentError::ParseError {
656            format: "JSON".to_string(),
657            detail: e.to_string(),
658        })
659}
660
661pub fn save(value: &Value) -> DocumentResult<String> {
662    let json_val = serde_json::Value::try_from(value)?;
663    serde_json::to_string_pretty(&json_val).map_err(|e| DocumentError::ParseError {
664        format: "JSON".to_string(),
665        detail: e.to_string(),
666    })
667}
668
669#[cfg(test)]
670mod tests {
671    use super::{JsonDocument, load, save};
672    use crate::document::Value;
673
674    #[test]
675    fn duplicate_keys_are_rejected_by_load_and_editor_parser() {
676        let source = r#"{"same":1,"same":2}"#;
677        assert!(load(source).is_err());
678        assert!(JsonDocument::parse(source).is_err());
679    }
680
681    #[test]
682    fn source_parser_rejects_invalid_strings_and_trailing_commas_before_editing() {
683        for source in [r#"{"key":"\q"}"#, "[1,]", r#"{"key":1,}"#] {
684            assert!(JsonDocument::parse(source).is_err(), "{source}");
685        }
686        assert!(
687            super::set_preserving(
688                r#"{"key":"\q"}"#,
689                "key",
690                &Value::String("replacement".into()),
691            )
692            .is_err()
693        );
694    }
695
696    #[test]
697    fn source_parser_bounds_nesting_before_scanning_spans() {
698        for depth in [256, 10_000] {
699            let source = format!("{}0{}", "[".repeat(depth), "]".repeat(depth));
700            assert!(JsonDocument::parse(&source).is_err());
701        }
702    }
703
704    #[test]
705    fn save_rejects_non_finite_float() {
706        let error = save(&Value::Float(f64::INFINITY)).expect_err("infinity must fail");
707        assert!(error.to_string().contains("non-finite"));
708    }
709}