Skip to main content

flow_abi/
json.rs

1//! JSON text: a tree, a strict reader, and the canonical writer.
2//!
3//! The reader is `abi.md`'s *Decoding* table at the level of text: numbers
4//! are read exactly, a string escape naming a lone surrogate is refused, an
5//! object naming one key twice is refused, and nothing nests deeper than the
6//! caller allows. The writer is *The canonical form*: no whitespace, object
7//! keys in ascending code-point order, the fewest escapes, and numbers in
8//! plain decimal notation.
9//!
10//! The reader is written here rather than borrowed so that every one of those
11//! rules is this crate's: a general-purpose reader rounds numbers, keeps the
12//! last of two equal keys, or bounds nesting at a depth of its own choosing.
13
14use std::collections::BTreeSet;
15use std::fmt::Write as _;
16
17use flow_types::Nested;
18use flow_value::Decimal;
19use num_bigint::BigInt;
20
21use crate::bytes::wide;
22use crate::error::{DecodeError, DecodeErrorKind, Place};
23use crate::limits::Limits;
24
25/// A JSON value.
26///
27/// An object keeps its members in the order they were read or built; the
28/// canonical writer sorts them. A tree built here never holds two members
29/// with one key.
30#[derive(Clone, PartialEq, Eq, Debug)]
31pub enum Json {
32    /// `null`.
33    Null,
34    /// `true` or `false`.
35    Bool(bool),
36    /// A number, exactly.
37    Number(Decimal),
38    /// A string.
39    String(String),
40    /// An array.
41    Array(Vec<Json>),
42    /// An object.
43    Object(Vec<(String, Json)>),
44}
45
46impl Json {
47    /// What kind of JSON value this is, for a message: `"a string"`.
48    pub fn kind(&self) -> &'static str {
49        match self {
50            Json::Null => "null",
51            Json::Bool(_) => "a boolean",
52            Json::Number(_) => "a number",
53            Json::String(_) => "a string",
54            Json::Array(_) => "an array",
55            Json::Object(_) => "an object",
56        }
57    }
58
59    /// The canonical text of this value (`abi.md`, *The canonical form*).
60    pub fn canonical(&self) -> String {
61        let mut out = String::new();
62        write_canonical(self, &mut out);
63        out
64    }
65
66    /// The member `key` of an object, if this is an object that has one.
67    pub fn get(&self, key: &str) -> Option<&Json> {
68        match self {
69            Json::Object(members) => members
70                .iter()
71                .find(|(name, _)| name == key)
72                .map(|(_, value)| value),
73            _ => None,
74        }
75    }
76}
77
78/// A value nests as deeply as the type its schema is written for, so it is
79/// a [`Nested`] tree, which drops on a native stack of bounded size.
80impl Nested for Json {
81    const LEAF: Json = Json::Null;
82
83    /// An array's items, or an object's members' values.
84    fn parts(&self) -> impl DoubleEndedIterator<Item = &Json> {
85        let (items, members): (&[Json], &[(String, Json)]) = match self {
86            Json::Array(items) => (items, &[]),
87            Json::Object(members) => (&[], members),
88            Json::Null | Json::Bool(_) | Json::Number(_) | Json::String(_) => (&[], &[]),
89        };
90        items.iter().chain(members.iter().map(|(_, value)| value))
91    }
92
93    fn parts_mut(&mut self) -> impl Iterator<Item = &mut Json> {
94        let (items, members): (&mut [Json], &mut [(String, Json)]) = match self {
95            Json::Array(items) => (items, &mut []),
96            Json::Object(members) => (&mut [], members),
97            Json::Null | Json::Bool(_) | Json::Number(_) | Json::String(_) => (&mut [], &mut []),
98        };
99        items
100            .iter_mut()
101            .chain(members.iter_mut().map(|(_, value)| value))
102    }
103}
104
105impl Drop for Json {
106    fn drop(&mut self) {
107        self.free_parts();
108    }
109}
110
111/// Reads one JSON value from `text`, refusing anything after it but
112/// whitespace.
113///
114/// Arrays and objects may nest `limits.json_depth()` deep. A number is held
115/// to the limits by its value, not its spelling, and is measured before
116/// anything as large as its value is built: its significant digits must
117/// make an integer within `limits.int_bits`, and it may take no more than
118/// `limits.text_bytes` characters in plain notation. Written out, the
119/// numbers of one text together may grow it by no more than
120/// `limits.text_bytes` characters, so the canonical text of what is read is
121/// never longer than `text` and that limit together, however its numbers
122/// were spelled.
123///
124/// # Errors
125///
126/// A [`DecodeError`] when `text` is not one JSON value, or passes any of
127/// the bounds above.
128pub fn parse(text: &str, limits: &Limits) -> Result<Json, DecodeError> {
129    let mut reader = Reader {
130        bytes: text.as_bytes(),
131        text,
132        at: 0,
133        path: Place::default(),
134        max_depth: limits.json_depth(),
135        max_digits: limits.text_bytes,
136        int_bits: limits.int_bits,
137        growth: limits.text_bytes,
138    };
139    reader.whitespace();
140    let value = reader.value()?;
141    reader.whitespace();
142    if reader.at < reader.bytes.len() {
143        return Err(reader.fail("has text after the JSON value"));
144    }
145    Ok(value)
146}
147
148/// An array or an object being read, with what it holds so far.
149enum Open {
150    Array(Vec<Json>),
151    /// The members read so far, every key seen, and the key of the member
152    /// being read.
153    Object(Vec<(String, Json)>, BTreeSet<String>, String),
154}
155
156struct Reader<'t> {
157    bytes: &'t [u8],
158    text: &'t str,
159    at: usize,
160    path: Place,
161    max_depth: usize,
162    max_digits: usize,
163    int_bits: u64,
164    /// How many more characters the numbers still to be read may take in
165    /// plain notation than they were written in.
166    growth: usize,
167}
168
169impl<'t> Reader<'t> {
170    fn fail(&self, problem: &str) -> DecodeError {
171        self.refuse(DecodeErrorKind::Syntax { at: self.at }, problem)
172    }
173
174    fn refuse(&self, kind: DecodeErrorKind, problem: &str) -> DecodeError {
175        DecodeError::of(&self.path, kind, format!("{problem} (at byte {})", self.at))
176    }
177
178    fn limited(&self, problem: &str) -> DecodeError {
179        DecodeError::of(
180            &self.path,
181            DecodeErrorKind::TooLarge,
182            format!("{problem} (at byte {})", self.at),
183        )
184    }
185
186    fn peek(&self) -> Option<u8> {
187        self.bytes.get(self.at).copied()
188    }
189
190    // Every loop here is bounded by the text's length, so that no change to
191    // how a step advances can make reading run forever.
192
193    fn whitespace(&mut self) {
194        self.at += self.bytes[self.at..]
195            .iter()
196            .take_while(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))
197            .count();
198    }
199
200    fn literal(&mut self, word: &str, value: Json) -> Result<Json, DecodeError> {
201        if self.bytes[self.at..].starts_with(word.as_bytes()) {
202            self.at += word.len();
203            Ok(value)
204        } else {
205            Err(self.fail("is not valid JSON"))
206        }
207    }
208
209    /// Reads one JSON value. The arrays and objects it is inside wait on a
210    /// stack on the heap, so the native stack does not grow with the text's
211    /// nesting.
212    fn value(&mut self) -> Result<Json, DecodeError> {
213        let mut open = Vec::new();
214        // Each round reads at least one byte.
215        for _ in 0..self.bytes.len() {
216            let Some(value) = self.begin(&mut open)? else {
217                continue;
218            };
219            if let Some(whole) = self.close(&mut open, value)? {
220                return Ok(whole);
221            }
222        }
223        Err(self.fail("ends before a JSON value"))
224    }
225
226    /// Reads a value that holds no other, or an empty array or object, or
227    /// opens an array or object and steps onto its first element.
228    fn begin(&mut self, open: &mut Vec<Open>) -> Result<Option<Json>, DecodeError> {
229        let value = match self.peek() {
230            Some(b'n') => self.literal("null", Json::Null)?,
231            Some(b't') => self.literal("true", Json::Bool(true))?,
232            Some(b'f') => self.literal("false", Json::Bool(false))?,
233            Some(b'"') => Json::String(self.string()?),
234            Some(b'[') => {
235                self.enter(open.len() + 1)?;
236                self.at += 1;
237                self.whitespace();
238                if self.peek() == Some(b']') {
239                    self.at += 1;
240                    return Ok(Some(Json::Array(Vec::new())));
241                }
242                self.path.index(0);
243                open.push(Open::Array(Vec::new()));
244                return Ok(None);
245            }
246            Some(b'{') => {
247                self.enter(open.len() + 1)?;
248                self.at += 1;
249                self.whitespace();
250                if self.peek() == Some(b'}') {
251                    self.at += 1;
252                    return Ok(Some(Json::Object(Vec::new())));
253                }
254                let mut seen = BTreeSet::new();
255                let key = self.key(&mut seen)?;
256                self.path.key(&key);
257                open.push(Open::Object(Vec::new(), seen, key));
258                return Ok(None);
259            }
260            Some(b'-' | b'0'..=b'9') => self.number()?,
261            Some(_) => return Err(self.fail("is not valid JSON")),
262            None => return Err(self.fail("ends before a JSON value")),
263        };
264        Ok(Some(value))
265    }
266
267    /// Puts `value` in the innermost open array or object, closing each one
268    /// that ends after it. Returns the whole value once nothing is open, or
269    /// `None` once it steps onto the next element of one that is.
270    fn close(&mut self, open: &mut Vec<Open>, value: Json) -> Result<Option<Json>, DecodeError> {
271        let mut value = value;
272        while let Some(innermost) = open.last_mut() {
273            self.path.pop();
274            self.whitespace();
275            match innermost {
276                Open::Array(items) => {
277                    items.push(value);
278                    match self.peek() {
279                        Some(b',') => {
280                            self.at += 1;
281                            self.path.index(items.len());
282                            self.whitespace();
283                            return Ok(None);
284                        }
285                        Some(b']') => {
286                            self.at += 1;
287                            value = Json::Array(std::mem::take(items));
288                        }
289                        _ => return Err(self.fail("is not valid JSON: expected `,` or `]`")),
290                    }
291                }
292                Open::Object(members, seen, key) => {
293                    members.push((std::mem::take(key), value));
294                    match self.peek() {
295                        Some(b',') => {
296                            self.at += 1;
297                            *key = self.key(seen)?;
298                            self.path.key(key);
299                            return Ok(None);
300                        }
301                        Some(b'}') => {
302                            self.at += 1;
303                            value = Json::Object(std::mem::take(members));
304                        }
305                        _ => return Err(self.fail("is not valid JSON: expected `,` or `}`")),
306                    }
307                }
308            }
309            open.pop();
310        }
311        Ok(Some(value))
312    }
313
314    fn enter(&self, depth: usize) -> Result<(), DecodeError> {
315        if depth > self.max_depth {
316            return Err(self.limited(&format!("nests deeper than {} levels", self.max_depth)));
317        }
318        Ok(())
319    }
320
321    /// Reads an object's key and the `:` after it, refusing a key `seen`
322    /// already holds.
323    fn key(&mut self, seen: &mut BTreeSet<String>) -> Result<String, DecodeError> {
324        self.whitespace();
325        if self.peek() != Some(b'"') {
326            return Err(self.fail("is not valid JSON: expected a key"));
327        }
328        let key = self.string()?;
329        if !seen.insert(key.clone()) {
330            self.path.key(&key);
331            return Err(self.refuse(
332                DecodeErrorKind::Duplicate,
333                "is a key its object already has",
334            ));
335        }
336        self.whitespace();
337        if self.peek() != Some(b':') {
338            return Err(self.fail("is not valid JSON: expected `:`"));
339        }
340        self.at += 1;
341        self.whitespace();
342        Ok(key)
343    }
344
345    fn digits(&mut self) -> &'t str {
346        let text = self.text;
347        let start = self.at;
348        self.at += text[start..].bytes().take_while(u8::is_ascii_digit).count();
349        &text[start..self.at]
350    }
351
352    fn number(&mut self) -> Result<Json, DecodeError> {
353        let start = self.at;
354        let negative = self.peek() == Some(b'-');
355        if negative {
356            self.at += 1;
357        }
358        let whole = self.digits();
359        if whole.is_empty() || (whole.len() > 1 && whole.starts_with('0')) {
360            return Err(self.fail("is not a valid JSON number"));
361        }
362        let mut fraction = "";
363        if self.peek() == Some(b'.') {
364            self.at += 1;
365            fraction = self.digits();
366            if fraction.is_empty() {
367                return Err(self.fail("is not a valid JSON number"));
368            }
369        }
370        let mut power = "0";
371        let mut lowers = false;
372        if matches!(self.peek(), Some(b'e' | b'E')) {
373            self.at += 1;
374            lowers = self.peek() == Some(b'-');
375            if matches!(self.peek(), Some(b'-' | b'+')) {
376                self.at += 1;
377            }
378            power = self.digits();
379            if power.is_empty() {
380                return Err(self.fail("is not a valid JSON number"));
381            }
382        }
383        let spelling = self.at - start - usize::from(negative);
384        // The number is measured from its spelling before anything as large
385        // as its value is built: building a coefficient takes time in the
386        // square of its digits, and writing a number out takes as many
387        // characters as its plain notation has. The coefficient is the
388        // digits from the first nonzero one, the point skipped, with the
389        // trailing zeros left to the exponent.
390        let (head, tail) = if whole == "0" {
391            (fraction.trim_start_matches('0'), "")
392        } else {
393            (whole, fraction)
394        };
395        if head.is_empty() {
396            // Zero, under any exponent.
397            return Ok(Json::Number(
398                Decimal::new(BigInt::default(), 0).expect("zero"),
399            ));
400        }
401        let (kept_head, kept_tail) = match tail.trim_end_matches('0') {
402            "" => (head.trim_end_matches('0'), ""),
403            kept => (head, kept),
404        };
405        let kept = kept_head.len() + kept_tail.len();
406        let zeros = head.len() + tail.len() - kept;
407        // 2^b has fewer than b/3 + 1 digits, since 2^3 < 10: a coefficient
408        // with more is past the limit, and one with no more is short enough
409        // to build and measure exactly.
410        let past_bits = || {
411            self.limited(&format!(
412                "is a number whose digits make an integer larger than {} bits",
413                self.int_bits
414            ))
415        };
416        if u64::try_from(kept).unwrap_or(u64::MAX) > self.int_bits / 3 + 1 {
417            return Err(past_bits());
418        }
419        crate::work::built(kept);
420        let coefficient: BigInt = format!("{kept_head}{kept_tail}")
421            .parse()
422            .expect("ASCII digits");
423        if coefficient.bits() > self.int_bits {
424            return Err(past_bits());
425        }
426        let too_large = || self.limited("is a number too large for this host");
427        // An exponent past 64 bits is past every limit, whatever the
428        // coefficient and the point make of it.
429        let power: i64 = power.parse().map_err(|_| too_large())?;
430        let power = i128::from(power);
431        let length = |n: usize| i128::try_from(n).expect("a length fits 128 bits");
432        let exponent = if lowers { -power } else { power } - length(fraction.len()) + length(zeros);
433        let exponent = i64::try_from(exponent).map_err(|_| too_large())?;
434        let plain = plain_length(u128::from(wide(kept)), exponent);
435        if plain > u128::from(wide(self.max_digits)) {
436            return Err(too_large());
437        }
438        let plain = usize::try_from(plain).expect("within the text limit");
439        self.growth = self
440            .growth
441            .checked_sub(plain.saturating_sub(spelling))
442            .ok_or_else(|| {
443                self.limited(&format!(
444                    "has numbers that, written out, would lengthen it by more than {} characters",
445                    self.max_digits
446                ))
447            })?;
448        let coefficient = if negative { -coefficient } else { coefficient };
449        let number = Decimal::new(coefficient, exponent).expect("no trailing zero to strip");
450        Ok(Json::Number(number))
451    }
452
453    fn hex4(&mut self) -> Result<u32, DecodeError> {
454        let digits = self
455            .text
456            .get(self.at..self.at + 4)
457            .filter(|digits| digits.bytes().all(|byte| byte.is_ascii_hexdigit()))
458            .ok_or_else(|| self.fail("has an invalid `\\u` escape"))?;
459        self.at += 4;
460        Ok(u32::from_str_radix(digits, 16).expect("four hexadecimal digits"))
461    }
462
463    fn string(&mut self) -> Result<String, DecodeError> {
464        self.at += 1;
465        let mut out = String::new();
466        for _ in 0..self.bytes.len() {
467            let start = self.at;
468            self.at += self.bytes[start..]
469                .iter()
470                .take_while(|byte| !matches!(byte, b'"' | b'\\' | 0x00..=0x1f))
471                .count();
472            out.push_str(&self.text[start..self.at]);
473            match self.peek() {
474                Some(b'"') => {
475                    self.at += 1;
476                    return Ok(out);
477                }
478                Some(b'\\') => {
479                    self.at += 1;
480                    let escaped = self.peek();
481                    self.at += 1;
482                    match escaped {
483                        Some(b'"') => out.push('"'),
484                        Some(b'\\') => out.push('\\'),
485                        Some(b'/') => out.push('/'),
486                        Some(b'b') => out.push('\u{8}'),
487                        Some(b'f') => out.push('\u{c}'),
488                        Some(b'n') => out.push('\n'),
489                        Some(b'r') => out.push('\r'),
490                        Some(b't') => out.push('\t'),
491                        Some(b'u') => out.push(self.unicode_escape()?),
492                        _ => {
493                            self.at -= 1;
494                            return Err(self.fail("has an invalid escape"));
495                        }
496                    }
497                }
498                Some(_) => return Err(self.fail("has an unescaped control character")),
499                None => break,
500            }
501        }
502        Err(self.fail("ends inside a string"))
503    }
504
505    fn unicode_escape(&mut self) -> Result<char, DecodeError> {
506        let first = self.hex4()?;
507        if !(0xd800..=0xdfff).contains(&first) {
508            return Ok(char::from_u32(first).expect("a scalar value outside the surrogates"));
509        }
510        // A high surrogate must be followed by an escape naming a low one;
511        // anything else, a low one first included, is a lone surrogate.
512        let second = if first < 0xdc00 && self.bytes[self.at..].starts_with(b"\\u") {
513            self.at += 2;
514            self.hex4()?
515        } else {
516            first
517        };
518        if !(0xdc00..=0xdfff).contains(&second) || first >= 0xdc00 {
519            return Err(self.fail("has an escape naming a lone surrogate"));
520        }
521        let code = 0x10000 + ((first - 0xd800) << 10) + (second - 0xdc00);
522        Ok(char::from_u32(code).expect("a surrogate pair names a scalar value"))
523    }
524}
525
526/// How many characters a number of `digits` significant digits times
527/// `10^exponent` takes in plain decimal notation, sign excluded.
528fn plain_length(digits: u128, exponent: i64) -> u128 {
529    let places = u128::from(exponent.unsigned_abs());
530    if exponent >= 0 {
531        digits + places
532    } else if digits > places {
533        // The digits with a point among them.
534        digits + 1
535    } else {
536        // `0.`, zeros, and the digits.
537        places + 2
538    }
539}
540
541/// `text` as a canonical JSON string, quotes included.
542pub(crate) fn quote(text: &str) -> String {
543    let mut out = String::with_capacity(text.len() + 2);
544    write_string(text, &mut out);
545    out
546}
547
548fn write_string(text: &str, out: &mut String) {
549    out.push('"');
550    for code_point in text.chars() {
551        match code_point {
552            '"' => out.push_str("\\\""),
553            '\\' => out.push_str("\\\\"),
554            '\u{8}' => out.push_str("\\b"),
555            '\u{c}' => out.push_str("\\f"),
556            '\n' => out.push_str("\\n"),
557            '\r' => out.push_str("\\r"),
558            '\t' => out.push_str("\\t"),
559            '\u{0}'..='\u{1f}' => {
560                write!(out, "\\u{:04x}", u32::from(code_point)).expect("writing to a string");
561            }
562            _ => out.push(code_point),
563        }
564    }
565    out.push('"');
566}
567
568/// Writes the canonical text of `value` to `out`, from a stack on the heap of
569/// what is left to write, so a value nested however deep is written on a
570/// native stack of fixed size.
571fn write_canonical(value: &Json, out: &mut String) {
572    enum Piece<'j> {
573        Value(&'j Json),
574        Key(&'j str),
575        Text(&'static str),
576    }
577    let mut pending = vec![Piece::Value(value)];
578    while let Some(piece) = pending.pop() {
579        let value = match piece {
580            Piece::Value(value) => value,
581            Piece::Key(key) => {
582                write_string(key, out);
583                out.push(':');
584                continue;
585            }
586            Piece::Text(text) => {
587                out.push_str(text);
588                continue;
589            }
590        };
591        match value {
592            Json::Null => out.push_str("null"),
593            Json::Bool(true) => out.push_str("true"),
594            Json::Bool(false) => out.push_str("false"),
595            Json::Number(number) => write!(out, "{number}").expect("writing to a string"),
596            Json::String(text) => write_string(text, out),
597            Json::Array(items) => {
598                out.push('[');
599                pending.push(Piece::Text("]"));
600                for (index, item) in items.iter().enumerate().rev() {
601                    pending.push(Piece::Value(item));
602                    if index > 0 {
603                        pending.push(Piece::Text(","));
604                    }
605                }
606            }
607            Json::Object(members) => {
608                // UTF-8 byte order is code-point order.
609                let mut sorted: Vec<&(String, Json)> = members.iter().collect();
610                sorted.sort_by(|a, b| a.0.cmp(&b.0));
611                out.push('{');
612                pending.push(Piece::Text("}"));
613                for (index, (key, item)) in sorted.into_iter().enumerate().rev() {
614                    pending.push(Piece::Value(item));
615                    pending.push(Piece::Key(key));
616                    if index > 0 {
617                        pending.push(Piece::Text(","));
618                    }
619                }
620            }
621        }
622    }
623}