Skip to main content

meta_language/transform/
json_recovery.rs

1//! Conservative JSON recovery over the native grammar's concrete syntax tree.
2
3use std::sync::OnceLock;
4
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7
8use crate::decorators::{DecoratorLevel, DecoratorRecord, DecoratorSet};
9use crate::{
10    FeatureGrammarParser, FeatureParseOptions, SyntaxTree, compile_feature_grammar,
11    parse_grammar_links,
12};
13
14/// An operation a caller may enable for JSON recovery.
15#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
16#[serde(rename_all = "camelCase")]
17pub enum JsonRepairKind {
18    /// Keep a partial value by closing literals and containers at the input boundary.
19    CloseOpenContainers,
20    /// Remove commas immediately before a closing delimiter or the end of an open container.
21    DropTrailingCommas,
22    /// Remove JSON Markdown fence lines.
23    StripCodeFence,
24    /// Keep the first value and remove surrounding prose or subsequent values.
25    ExtractFirstValue,
26    /// Remove a non-value suffix.
27    StripTrailingGarbage,
28    /// Preserve malformed escape spellings and raw control characters as string data.
29    RepairEscapes,
30}
31
32/// The actions and optional schema used to recover a JSON value.
33#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
34#[serde(default)]
35pub struct JsonRecoveryOptions {
36    /// Allowed repairs. Defaults to all six operations.
37    pub allow: Vec<JsonRepairKind>,
38    /// Schema used to report missing required properties.
39    pub schema: Option<Value>,
40}
41
42impl Default for JsonRecoveryOptions {
43    fn default() -> Self {
44        Self {
45            allow: vec![
46                JsonRepairKind::CloseOpenContainers,
47                JsonRepairKind::DropTrailingCommas,
48                JsonRepairKind::StripCodeFence,
49                JsonRepairKind::ExtractFirstValue,
50                JsonRepairKind::StripTrailingGarbage,
51                JsonRepairKind::RepairEscapes,
52            ],
53            schema: None,
54        }
55    }
56}
57
58/// A half-open range of original UTF-8 bytes.
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
60pub struct JsonRecoverySpan {
61    /// First byte of the range.
62    pub start: usize,
63    /// Byte immediately after the range.
64    pub end: usize,
65}
66
67impl JsonRecoverySpan {
68    const fn new(start: usize, end: usize) -> Self {
69        Self { start, end }
70    }
71}
72
73/// An edit witnessed by recovery nodes in the original concrete syntax tree.
74#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
75pub struct JsonRecoveryEdit {
76    /// Operation that admitted the edit.
77    pub kind: JsonRepairKind,
78    /// Original bytes replaced, empty for insertion.
79    pub span: JsonRecoverySpan,
80    /// Replacement text.
81    pub inserted: String,
82    /// Exact original text removed.
83    pub removed: String,
84}
85
86/// A diagnostic that accompanies the repair report.
87#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
88#[serde(tag = "kind", rename_all = "camelCase")]
89pub enum JsonRecoveryIssue {
90    /// No permitted plan produced one valid JSON value.
91    UnrecoveredSyntax {
92        /// Original bytes at which recovery stopped.
93        span: JsonRecoverySpan,
94    },
95    /// A long, short-period repetition in the original source.
96    DegenerateRepetition {
97        /// Original bytes occupied by the selected run.
98        span: JsonRecoverySpan,
99    },
100    /// The schema calls for a property absent from the parsed object.
101    MissingRequiredProperty {
102        /// JSON Pointer of the absent property.
103        pointer: String,
104        /// Its original property name from the schema.
105        property: String,
106    },
107}
108
109/// Recovered source and its parsed value, with a replayable edit report.
110#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
111pub struct JsonRecoveryResult {
112    /// Source after applying every reported edit, or the original on refusal.
113    pub text: String,
114    /// Parsed value, including `Some(Value::Null)` for a valid JSON null.
115    pub value: Option<Value>,
116    /// Edits in original source order. Insertions at one offset appear in application order.
117    pub edits: Vec<JsonRecoveryEdit>,
118    /// Whether a value was recovered without a truncation or missing required properties.
119    pub complete: bool,
120    /// Unrecovered syntax, missing required properties or possible degenerate repetition.
121    pub issues: Vec<JsonRecoveryIssue>,
122}
123
124fn parse_recovery_tree(
125    text: &str,
126    start_rule: &str,
127    offset: usize,
128) -> Result<SyntaxTree, JsonRecoverySpan> {
129    static PARSER: OnceLock<FeatureGrammarParser> = OnceLock::new();
130    let parser = PARSER.get_or_init(|| {
131        let grammar = parse_grammar_links(include_str!("../data/json-recovery-grammar.lino"))
132            .expect("shipped JSON recovery grammar");
133        compile_feature_grammar(&grammar, None, FeatureParseOptions::default())
134            .expect("compiled JSON recovery grammar")
135    });
136    let outcome = parser
137        .parse_tree(
138            text.as_bytes(),
139            &FeatureParseOptions {
140                start_rule: Some(start_rule.to_owned()),
141                accept_recovery: Some(true),
142                // Match the rule nesting bound used by the JavaScript recovery executor.
143                max_depth: Some(192),
144                ..FeatureParseOptions::default()
145            },
146        )
147        .expect("registered JSON recovery start rule");
148    if let Some(rejection) = outcome.rejection {
149        let position = offset + rejection.offset.unwrap_or(0);
150        let end = if rejection.reason == "syntax" {
151            position
152        } else {
153            offset + text.len()
154        };
155        return Err(JsonRecoverySpan::new(position, end));
156    }
157    Ok(outcome.tree.expect("successful JSON recovery tree"))
158}
159
160const fn is_json_space(character: char) -> bool {
161    matches!(character, ' ' | '\t' | '\n' | '\r')
162}
163
164fn starts_value(text: &str) -> bool {
165    let text = text.trim_start_matches(is_json_space);
166    matches!(
167        text.as_bytes().first().copied(),
168        Some(b'[' | b'{' | b'"' | b'-' | b'0'..=b'9')
169    ) || ["true", "false", "null"].iter().any(|prefix| {
170        text.strip_prefix(prefix).is_some_and(|rest| {
171            rest.as_bytes()
172                .first()
173                .is_none_or(|byte| !byte.is_ascii_alphanumeric() && *byte != b'_')
174        })
175    })
176}
177
178fn fence_marker(text: &str) -> Option<(u8, usize)> {
179    let marker = *text.as_bytes().first()?;
180    if !matches!(marker, b'`' | b'~') {
181        return None;
182    }
183    let count = text.bytes().take_while(|&byte| byte == marker).count();
184    (count >= 3).then_some((marker, count))
185}
186
187fn repetition_issue(text: &str) -> Option<JsonRecoveryIssue> {
188    const MINIMUM_LENGTH: usize = 256;
189    let bytes = text.as_bytes();
190    if bytes.len() < MINIMUM_LENGTH {
191        return None;
192    }
193    let mut best: Option<JsonRecoverySpan> = None;
194    for period in 1..=32 {
195        let minimum = MINIMUM_LENGTH.max(period * 8);
196        let mut start = 0;
197        for end in period..=bytes.len() {
198            if end < bytes.len() && bytes[end] == bytes[end - period] {
199                continue;
200            }
201            if end - start >= minimum {
202                let mut from = start;
203                let mut to = end;
204                while !text.is_char_boundary(from) {
205                    from += 1;
206                }
207                while !text.is_char_boundary(to) {
208                    to -= 1;
209                }
210                let length = to - from;
211                if length >= minimum
212                    && best.is_none_or(|span| {
213                        length > span.end - span.start
214                            || (length == span.end - span.start && from < span.start)
215                    })
216                    && bytes[from..from + period]
217                        .iter()
218                        .any(|&byte| !is_json_space(char::from(byte)))
219                {
220                    best = Some(JsonRecoverySpan::new(from, to));
221                }
222            }
223            start = end - period + 1;
224        }
225    }
226    best.map(|span| JsonRecoveryIssue::DegenerateRepetition { span })
227}
228
229fn pointer_part(key: &str) -> String {
230    key.replace('~', "~0").replace('/', "~1")
231}
232
233fn missing_required_properties(value: &Value, schema: &Value, issues: &mut Vec<JsonRecoveryIssue>) {
234    let mut pending = vec![(value, schema, String::new())];
235    while let Some((item, rule, pointer)) = pending.pop() {
236        match item {
237            Value::Array(items) => {
238                let prefixes = rule["prefixItems"].as_array();
239                for (index, item) in items.iter().enumerate().rev() {
240                    let child = prefixes
241                        .and_then(|prefix| prefix.get(index))
242                        .unwrap_or_else(|| &rule["items"]);
243                    if child.is_object() {
244                        pending.push((item, child, format!("{pointer}/{index}")));
245                    }
246                }
247            }
248            Value::Object(object) => {
249                if let Some(required) = rule["required"].as_array() {
250                    let mut reported = std::collections::BTreeSet::new();
251                    for key in required.iter().filter_map(Value::as_str) {
252                        if !object.contains_key(key) && reported.insert(key) {
253                            issues.push(JsonRecoveryIssue::MissingRequiredProperty {
254                                pointer: format!("{pointer}/{}", pointer_part(key)),
255                                property: key.to_owned(),
256                            });
257                        }
258                    }
259                }
260                if let Some(properties) = rule["properties"].as_object() {
261                    let mut applicable: Vec<_> = properties
262                        .iter()
263                        .filter_map(|(key, child)| object.get(key).map(|item| (key, item, child)))
264                        .collect();
265                    applicable.sort_unstable_by_key(|(key, _, _)| std::cmp::Reverse(*key));
266                    for (key, item, child) in applicable {
267                        pending.push((item, child, format!("{pointer}/{}", pointer_part(key))));
268                    }
269                }
270            }
271            _ => {}
272        }
273    }
274}
275
276fn kind_for_name(name: &str) -> Option<JsonRepairKind> {
277    Some(match name {
278        "closeOpenContainers" => JsonRepairKind::CloseOpenContainers,
279        "dropTrailingCommas" => JsonRepairKind::DropTrailingCommas,
280        "stripCodeFence" => JsonRepairKind::StripCodeFence,
281        "extractFirstValue" => JsonRepairKind::ExtractFirstValue,
282        "stripTrailingGarbage" => JsonRepairKind::StripTrailingGarbage,
283        "repairEscapes" => JsonRepairKind::RepairEscapes,
284        _ => return None,
285    })
286}
287
288fn collect_edits(
289    tree: &SyntaxTree,
290    text: &str,
291    offset: usize,
292    allow: &[JsonRepairKind],
293    edits: &mut Vec<JsonRecoveryEdit>,
294    from_prose: bool,
295) -> Result<(), JsonRecoverySpan> {
296    static DECORATORS: OnceLock<DecoratorSet> = OnceLock::new();
297    let decorators = DECORATORS.get_or_init(|| {
298        DecoratorSet::from_lino(include_str!("../data/json-recovery-decorators.lino"))
299            .expect("shipped JSON recovery decorators")
300    });
301    let mut pending = vec![(tree, "")];
302    while let Some((node, region)) = pending.pop() {
303        let node_type = match node {
304            SyntaxTree::Node { kind, children, .. } => {
305                let mut region = kind.as_str();
306                if region == "trailing_region"
307                    && (from_prose
308                        || !allow.contains(&JsonRepairKind::StripTrailingGarbage)
309                        || starts_value(&text[offset + node.start()..offset + node.end()]))
310                {
311                    region = "following_value";
312                }
313                pending.extend(children.iter().rev().map(|child| (child, region)));
314                continue;
315            }
316            SyntaxTree::Error { .. } => "error",
317            SyntaxTree::Missing { .. } => "missing",
318            _ => continue,
319        };
320        let span = JsonRecoverySpan::new(offset + node.start(), offset + node.end());
321        let record = DecoratorRecord::from([
322            ("type".to_owned(), node_type.to_owned()),
323            ("region".to_owned(), region.to_owned()),
324        ]);
325        let decorated = decorators
326            .decorate(DecoratorLevel::Transformation, &record)
327            .ok_or(span)?;
328        let kind = decorated
329            .get("kind")
330            .and_then(|name| kind_for_name(name))
331            .ok_or(span)?;
332        if !allow.contains(&kind) {
333            return Err(span);
334        }
335        let removed = &text[span.start..span.end];
336        let inserted = match decorated.get("action").map(String::as_str) {
337            Some("insert") => match node {
338                SyntaxTree::Missing {
339                    kind: Some(kind), ..
340                } => kind.clone(),
341                _ => return Err(span),
342            },
343            Some("escapeBackslash") => r"\\".to_owned(),
344            Some("escapeControl") => format!(r"\u00{:02x}", text.as_bytes()[span.start]),
345            Some("remove") => String::new(),
346            _ => return Err(span),
347        };
348        if matches!(
349            kind,
350            JsonRepairKind::StripCodeFence | JsonRepairKind::ExtractFirstValue
351        ) && let Some(previous) = edits.last_mut()
352            && previous.kind == kind
353            && previous.span.end == span.start
354        {
355            previous.span.end = span.end;
356            previous.removed.push_str(removed);
357        } else {
358            edits.push(JsonRecoveryEdit {
359                kind,
360                span,
361                inserted,
362                removed: removed.to_owned(),
363            });
364        }
365    }
366    Ok(())
367}
368
369fn children(tree: &SyntaxTree) -> impl Iterator<Item = &SyntaxTree> {
370    let children = match tree {
371        SyntaxTree::Node { children, .. } => children.as_slice(),
372        _ => &[],
373    };
374    children.iter()
375}
376
377fn node_named(tree: &SyntaxTree, name: &str) -> bool {
378    matches!(tree, SyntaxTree::Node { kind, .. } if kind == name)
379}
380
381fn plan_fenced_recovery(
382    text: &str,
383    frame: &SyntaxTree,
384    allow: &[JsonRepairKind],
385    edits: &mut Vec<JsonRecoveryEdit>,
386    from_prose: bool,
387) -> Result<(), JsonRecoverySpan> {
388    let fenced = children(frame)
389        .find(|node| node_named(node, "fenced_region"))
390        .expect("fence frame has a content region");
391    let mut parts = children(fenced).filter(|node| matches!(node, SyntaxTree::Node { .. }));
392    let opening = parts.next().expect("opening fence");
393    let body = parts.next().expect("fenced body");
394    let closing = parts.next();
395    let tail = parts.next();
396    if let Some(closing) = closing {
397        let (opener, opening_count) =
398            fence_marker(&text[opening.start()..opening.end()]).expect("validated opening marker");
399        let (closer, closing_count) =
400            fence_marker(text[closing.start()..closing.end()].trim_start_matches(is_json_space))
401                .expect("validated closing marker");
402        if opener != closer || closing_count < opening_count {
403            return Err(JsonRecoverySpan::new(closing.start(), closing.end()));
404        }
405    }
406    for prefix in children(frame)
407        .take_while(|node| !node_named(node, "fenced_region"))
408        .chain(std::iter::once(opening))
409    {
410        collect_edits(prefix, text, 0, allow, edits, false)?;
411    }
412    let parsed = parse_recovery_tree(&text[body.start()..body.end()], "document", body.start())?;
413    collect_edits(&parsed, text, body.start(), allow, edits, false)?;
414    if let Some(closing) = closing {
415        collect_edits(closing, text, 0, allow, edits, false)?;
416    }
417    if let Some(tail) = tail {
418        collect_edits(tail, text, 0, allow, edits, from_prose)?;
419    }
420    Ok(())
421}
422
423fn plan_recovery(
424    text: &str,
425    allow: &[JsonRepairKind],
426    edits: &mut Vec<JsonRecoveryEdit>,
427) -> Result<(), JsonRecoverySpan> {
428    if fence_marker(text.trim_start_matches(is_json_space)).is_some() {
429        let frame = parse_recovery_tree(text, "fenced_document", 0)?;
430        return plan_fenced_recovery(text, &frame, allow, edits, false);
431    }
432    let parsed = parse_recovery_tree(text, "document", 0);
433    if parsed.is_ok() || !allow.contains(&JsonRepairKind::ExtractFirstValue) || starts_value(text) {
434        return collect_edits(&parsed?, text, 0, allow, edits, false);
435    }
436
437    let parsed = parse_recovery_tree(text, "prose_document", 0);
438    if text
439        .split('\n')
440        .skip(1)
441        .any(|line| fence_marker(line.trim_start_matches([' ', '\t'])).is_some())
442        && let Ok(frame) = parse_recovery_tree(text, "prose_fenced_document", 0)
443    {
444        let opening = children(&frame)
445            .find(|node| node_named(node, "fenced_region"))
446            .expect("fence frame has a content region");
447        let prefix_end = parsed.as_ref().ok().and_then(|tree| {
448            children(tree)
449                .find(|node| node_named(node, "leading_region"))
450                .map(SyntaxTree::end)
451        });
452        if prefix_end.is_none_or(|end| opening.start() < end) {
453            return plan_fenced_recovery(text, &frame, allow, edits, true);
454        }
455    }
456    collect_edits(&parsed?, text, 0, allow, edits, true)
457}
458
459fn apply_edits(text: &str, edits: &[JsonRecoveryEdit]) -> String {
460    let mut output = String::with_capacity(text.len());
461    let mut offset = 0;
462    for edit in edits {
463        output.push_str(&text[offset..edit.span.start]);
464        output.push_str(&edit.inserted);
465        offset = edit.span.end;
466    }
467    output.push_str(&text[offset..]);
468    output
469}
470
471fn parse_value(text: &str) -> Option<Value> {
472    let mut value: Value = serde_json::from_str(text).ok()?;
473    let mut pending = vec![&mut value];
474    while let Some(item) = pending.pop() {
475        match item {
476            Value::Object(properties) => pending.extend(properties.values_mut()),
477            Value::Array(items) => pending.extend(items.iter_mut()),
478            Value::Number(number)
479                if number
480                    .as_i64()
481                    .is_some_and(|value| value.unsigned_abs() > 9_007_199_254_740_991)
482                    || number
483                        .as_u64()
484                        .is_some_and(|value| value > 9_007_199_254_740_991) =>
485            {
486                *number = serde_json::Number::from_f64(number.as_f64()?)?;
487            }
488            _ => {}
489        }
490    }
491    Some(value)
492}
493
494/// Recover one JSON value and report every edit in original UTF-8 byte coordinates.
495#[must_use]
496pub fn recover_json(text: &str, options: &JsonRecoveryOptions) -> JsonRecoveryResult {
497    let mut report = JsonRecoveryResult {
498        text: text.to_owned(),
499        value: parse_value(text),
500        edits: Vec::new(),
501        complete: false,
502        issues: repetition_issue(text).into_iter().collect(),
503    };
504    if report.value.is_none() {
505        let recovered = plan_recovery(text, &options.allow, &mut report.edits).and_then(|()| {
506            let source = apply_edits(text, &report.edits);
507            let value = parse_value(&source).ok_or_else(|| JsonRecoverySpan::new(0, text.len()))?;
508            Ok((source, value))
509        });
510        match recovered {
511            Ok((source, value)) => {
512                report.text = source;
513                report.value = Some(value);
514            }
515            Err(span) => {
516                report.edits.clear();
517                report
518                    .issues
519                    .push(JsonRecoveryIssue::UnrecoveredSyntax { span });
520                return report;
521            }
522        }
523    }
524
525    let issue_count = report.issues.len();
526    if let Some((value, schema)) = report.value.as_ref().zip(options.schema.as_ref()) {
527        missing_required_properties(value, schema, &mut report.issues);
528    }
529    report.complete = report.issues.len() == issue_count
530        && !report
531            .edits
532            .iter()
533            .any(|edit| edit.kind == JsonRepairKind::CloseOpenContainers);
534    report
535}