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_value::Decimal;
18use num_bigint::BigInt;
19
20use crate::error::{DecodeError, Path};
21use crate::limits::Limits;
22
23/// A JSON value.
24///
25/// An object keeps its members in the order they were read or built; the
26/// canonical writer sorts them. A tree built here never holds two members
27/// with one key.
28#[derive(Clone, PartialEq, Eq, Debug)]
29pub enum Json {
30    /// `null`.
31    Null,
32    /// `true` or `false`.
33    Bool(bool),
34    /// A number, exactly.
35    Number(Decimal),
36    /// A string.
37    String(String),
38    /// An array.
39    Array(Vec<Json>),
40    /// An object.
41    Object(Vec<(String, Json)>),
42}
43
44impl Json {
45    /// What kind of JSON value this is, for a message: `"a string"`.
46    pub fn kind(&self) -> &'static str {
47        match self {
48            Json::Null => "null",
49            Json::Bool(_) => "a boolean",
50            Json::Number(_) => "a number",
51            Json::String(_) => "a string",
52            Json::Array(_) => "an array",
53            Json::Object(_) => "an object",
54        }
55    }
56
57    /// The canonical text of this value (`abi.md`, *The canonical form*).
58    pub fn canonical(&self) -> String {
59        let mut out = String::new();
60        write_canonical(self, &mut out);
61        out
62    }
63
64    /// The member `key` of an object, if this is an object that has one.
65    pub fn get(&self, key: &str) -> Option<&Json> {
66        match self {
67            Json::Object(members) => members
68                .iter()
69                .find(|(name, _)| name == key)
70                .map(|(_, value)| value),
71            _ => None,
72        }
73    }
74}
75
76/// Reads one JSON value from `text`, refusing anything after it but
77/// whitespace.
78///
79/// Arrays and objects may nest `limits.json_depth()` deep. A number is held
80/// to the limits by its value, not its spelling, and is measured before
81/// anything as large as its value is built: its significant digits must
82/// make an integer within `limits.int_bits`, and it may take no more than
83/// `limits.text_bytes` characters in plain notation. Written out, the
84/// numbers of one text together may grow it by no more than
85/// `limits.text_bytes` characters, so the canonical text of what is read is
86/// never longer than `text` and that limit together, however its numbers
87/// were spelled.
88pub fn parse(text: &str, limits: &Limits) -> Result<Json, DecodeError> {
89    let mut reader = Reader {
90        bytes: text.as_bytes(),
91        text,
92        at: 0,
93        path: Path::default(),
94        max_depth: limits.json_depth(),
95        max_digits: limits.text_bytes,
96        int_bits: limits.int_bits,
97        growth: limits.text_bytes,
98    };
99    reader.whitespace();
100    let value = reader.value(0)?;
101    reader.whitespace();
102    if reader.at < reader.bytes.len() {
103        return Err(reader.fail("has text after the JSON value"));
104    }
105    Ok(value)
106}
107
108struct Reader<'t> {
109    bytes: &'t [u8],
110    text: &'t str,
111    at: usize,
112    path: Path,
113    max_depth: usize,
114    max_digits: usize,
115    int_bits: u64,
116    /// How many more characters the numbers still to be read may take in
117    /// plain notation than they were written in.
118    growth: usize,
119}
120
121impl<'t> Reader<'t> {
122    fn fail(&self, problem: &str) -> DecodeError {
123        DecodeError::new(&self.path, format!("{problem} (at byte {})", self.at))
124    }
125
126    fn limited(&self, problem: &str) -> DecodeError {
127        DecodeError::limited(&self.path, format!("{problem} (at byte {})", self.at))
128    }
129
130    fn peek(&self) -> Option<u8> {
131        self.bytes.get(self.at).copied()
132    }
133
134    // Every loop here is bounded by the text's length, so that no change to
135    // how a step advances can make reading run forever.
136
137    fn whitespace(&mut self) {
138        self.at += self.bytes[self.at..]
139            .iter()
140            .take_while(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))
141            .count();
142    }
143
144    fn literal(&mut self, word: &str, value: Json) -> Result<Json, DecodeError> {
145        if self.bytes[self.at..].starts_with(word.as_bytes()) {
146            self.at += word.len();
147            Ok(value)
148        } else {
149            Err(self.fail("is not valid JSON"))
150        }
151    }
152
153    fn value(&mut self, depth: usize) -> Result<Json, DecodeError> {
154        match self.peek() {
155            Some(b'n') => self.literal("null", Json::Null),
156            Some(b't') => self.literal("true", Json::Bool(true)),
157            Some(b'f') => self.literal("false", Json::Bool(false)),
158            Some(b'"') => self.string().map(Json::String),
159            Some(b'[') => self.array(depth + 1),
160            Some(b'{') => self.object(depth + 1),
161            Some(b'-' | b'0'..=b'9') => self.number(),
162            Some(_) => Err(self.fail("is not valid JSON")),
163            None => Err(self.fail("ends before a JSON value")),
164        }
165    }
166
167    fn enter(&self, depth: usize) -> Result<(), DecodeError> {
168        if depth > self.max_depth {
169            return Err(self.limited(&format!("nests deeper than {} levels", self.max_depth)));
170        }
171        Ok(())
172    }
173
174    fn array(&mut self, depth: usize) -> Result<Json, DecodeError> {
175        self.enter(depth)?;
176        self.at += 1;
177        let mut items = Vec::new();
178        self.whitespace();
179        if self.peek() == Some(b']') {
180            self.at += 1;
181            return Ok(Json::Array(items));
182        }
183        for _ in 0..self.bytes.len() {
184            self.path.index(items.len());
185            self.whitespace();
186            let item = self.value(depth)?;
187            self.path.pop();
188            items.push(item);
189            self.whitespace();
190            match self.peek() {
191                Some(b',') => self.at += 1,
192                Some(b']') => {
193                    self.at += 1;
194                    return Ok(Json::Array(items));
195                }
196                _ => break,
197            }
198        }
199        Err(self.fail("is not valid JSON: expected `,` or `]`"))
200    }
201
202    fn object(&mut self, depth: usize) -> Result<Json, DecodeError> {
203        self.enter(depth)?;
204        self.at += 1;
205        let mut members = Vec::new();
206        let mut seen = BTreeSet::new();
207        self.whitespace();
208        if self.peek() == Some(b'}') {
209            self.at += 1;
210            return Ok(Json::Object(members));
211        }
212        for _ in 0..self.bytes.len() {
213            self.whitespace();
214            if self.peek() != Some(b'"') {
215                return Err(self.fail("is not valid JSON: expected a key"));
216            }
217            let key = self.string()?;
218            if !seen.insert(key.clone()) {
219                return Err(self.fail(&format!("has the key {} twice", quote(&key))));
220            }
221            self.whitespace();
222            if self.peek() != Some(b':') {
223                return Err(self.fail("is not valid JSON: expected `:`"));
224            }
225            self.at += 1;
226            self.whitespace();
227            self.path.key(&key);
228            let value = self.value(depth)?;
229            self.path.pop();
230            members.push((key, value));
231            self.whitespace();
232            match self.peek() {
233                Some(b',') => self.at += 1,
234                Some(b'}') => {
235                    self.at += 1;
236                    return Ok(Json::Object(members));
237                }
238                _ => break,
239            }
240        }
241        Err(self.fail("is not valid JSON: expected `,` or `}`"))
242    }
243
244    fn digits(&mut self) -> &'t str {
245        let text = self.text;
246        let start = self.at;
247        self.at += text[start..].bytes().take_while(u8::is_ascii_digit).count();
248        &text[start..self.at]
249    }
250
251    fn number(&mut self) -> Result<Json, DecodeError> {
252        let start = self.at;
253        let negative = self.peek() == Some(b'-');
254        if negative {
255            self.at += 1;
256        }
257        let whole = self.digits();
258        if whole.is_empty() || (whole.len() > 1 && whole.starts_with('0')) {
259            return Err(self.fail("is not a valid JSON number"));
260        }
261        let mut fraction = "";
262        if self.peek() == Some(b'.') {
263            self.at += 1;
264            fraction = self.digits();
265            if fraction.is_empty() {
266                return Err(self.fail("is not a valid JSON number"));
267            }
268        }
269        let mut power = "0";
270        let mut lowers = false;
271        if matches!(self.peek(), Some(b'e' | b'E')) {
272            self.at += 1;
273            lowers = self.peek() == Some(b'-');
274            if matches!(self.peek(), Some(b'-' | b'+')) {
275                self.at += 1;
276            }
277            power = self.digits();
278            if power.is_empty() {
279                return Err(self.fail("is not a valid JSON number"));
280            }
281        }
282        let spelling = self.at - start - usize::from(negative);
283        // The number is measured from its spelling before anything as large
284        // as its value is built: building a coefficient takes time in the
285        // square of its digits, and writing a number out takes as many
286        // characters as its plain notation has. The coefficient is the
287        // digits from the first nonzero one, the point skipped, with the
288        // trailing zeros left to the exponent.
289        let (head, tail) = if whole == "0" {
290            (fraction.trim_start_matches('0'), "")
291        } else {
292            (whole, fraction)
293        };
294        if head.is_empty() {
295            // Zero, under any exponent.
296            return Ok(Json::Number(
297                Decimal::new(BigInt::default(), 0).expect("zero"),
298            ));
299        }
300        let (kept_head, kept_tail) = match tail.trim_end_matches('0') {
301            "" => (head.trim_end_matches('0'), ""),
302            kept => (head, kept),
303        };
304        let kept = kept_head.len() + kept_tail.len();
305        let zeros = head.len() + tail.len() - kept;
306        // 2^b has fewer than b/3 + 1 digits, since 2^3 < 10: a coefficient
307        // with more is past the limit, and one with no more is short enough
308        // to build and measure exactly.
309        let past_bits = || {
310            self.limited(&format!(
311                "is a number whose digits make an integer larger than {} bits",
312                self.int_bits
313            ))
314        };
315        if u64::try_from(kept).unwrap_or(u64::MAX) > self.int_bits / 3 + 1 {
316            return Err(past_bits());
317        }
318        let coefficient: BigInt = format!("{kept_head}{kept_tail}")
319            .parse()
320            .expect("ASCII digits");
321        if coefficient.bits() > self.int_bits {
322            return Err(past_bits());
323        }
324        let too_large = || self.limited("is a number too large for this host");
325        // An exponent past 64 bits is past every limit, whatever the
326        // coefficient and the point make of it.
327        let power: i64 = power.parse().map_err(|_| too_large())?;
328        let power = i128::from(power);
329        let length = |n: usize| i128::try_from(n).expect("a length fits 128 bits");
330        let exponent = if lowers { -power } else { power } - length(fraction.len()) + length(zeros);
331        let exponent = i64::try_from(exponent).map_err(|_| too_large())?;
332        let plain = plain_length(kept as u128, exponent);
333        if plain > self.max_digits as u128 {
334            return Err(too_large());
335        }
336        let plain = usize::try_from(plain).expect("within the text limit");
337        self.growth = self
338            .growth
339            .checked_sub(plain.saturating_sub(spelling))
340            .ok_or_else(|| {
341                self.limited(&format!(
342                    "has numbers that, written out, would lengthen it by more than {} characters",
343                    self.max_digits
344                ))
345            })?;
346        let coefficient = if negative { -coefficient } else { coefficient };
347        let number = Decimal::new(coefficient, exponent).expect("no trailing zero to strip");
348        Ok(Json::Number(number))
349    }
350
351    fn hex4(&mut self) -> Result<u32, DecodeError> {
352        let digits = self
353            .text
354            .get(self.at..self.at + 4)
355            .filter(|digits| digits.bytes().all(|byte| byte.is_ascii_hexdigit()))
356            .ok_or_else(|| self.fail("has an invalid `\\u` escape"))?;
357        self.at += 4;
358        Ok(u32::from_str_radix(digits, 16).expect("four hexadecimal digits"))
359    }
360
361    fn string(&mut self) -> Result<String, DecodeError> {
362        self.at += 1;
363        let mut out = String::new();
364        for _ in 0..self.bytes.len() {
365            let start = self.at;
366            self.at += self.bytes[start..]
367                .iter()
368                .take_while(|byte| !matches!(byte, b'"' | b'\\' | 0x00..=0x1f))
369                .count();
370            out.push_str(&self.text[start..self.at]);
371            match self.peek() {
372                Some(b'"') => {
373                    self.at += 1;
374                    return Ok(out);
375                }
376                Some(b'\\') => {
377                    self.at += 1;
378                    let escaped = self.peek();
379                    self.at += 1;
380                    match escaped {
381                        Some(b'"') => out.push('"'),
382                        Some(b'\\') => out.push('\\'),
383                        Some(b'/') => out.push('/'),
384                        Some(b'b') => out.push('\u{8}'),
385                        Some(b'f') => out.push('\u{c}'),
386                        Some(b'n') => out.push('\n'),
387                        Some(b'r') => out.push('\r'),
388                        Some(b't') => out.push('\t'),
389                        Some(b'u') => out.push(self.unicode_escape()?),
390                        _ => {
391                            self.at -= 1;
392                            return Err(self.fail("has an invalid escape"));
393                        }
394                    }
395                }
396                Some(_) => return Err(self.fail("has an unescaped control character")),
397                None => break,
398            }
399        }
400        Err(self.fail("ends inside a string"))
401    }
402
403    fn unicode_escape(&mut self) -> Result<char, DecodeError> {
404        let first = self.hex4()?;
405        if !(0xd800..=0xdfff).contains(&first) {
406            return Ok(char::from_u32(first).expect("a scalar value outside the surrogates"));
407        }
408        // A high surrogate must be followed by an escape naming a low one;
409        // anything else, a low one first included, is a lone surrogate.
410        let second = if first < 0xdc00 && self.bytes[self.at..].starts_with(b"\\u") {
411            self.at += 2;
412            self.hex4()?
413        } else {
414            first
415        };
416        if !(0xdc00..=0xdfff).contains(&second) || first >= 0xdc00 {
417            return Err(self.fail("has an escape naming a lone surrogate"));
418        }
419        let code = 0x10000 + ((first - 0xd800) << 10) + (second - 0xdc00);
420        Ok(char::from_u32(code).expect("a surrogate pair names a scalar value"))
421    }
422}
423
424/// How many characters a number of `digits` significant digits times
425/// `10^exponent` takes in plain decimal notation, sign excluded.
426fn plain_length(digits: u128, exponent: i64) -> u128 {
427    let places = u128::from(exponent.unsigned_abs());
428    if exponent >= 0 {
429        digits + places
430    } else if digits > places {
431        // The digits with a point among them.
432        digits + 1
433    } else {
434        // `0.`, zeros, and the digits.
435        places + 2
436    }
437}
438
439/// `text` as a canonical JSON string, quotes included.
440pub(crate) fn quote(text: &str) -> String {
441    let mut out = String::with_capacity(text.len() + 2);
442    write_string(text, &mut out);
443    out
444}
445
446fn write_string(text: &str, out: &mut String) {
447    out.push('"');
448    for code_point in text.chars() {
449        match code_point {
450            '"' => out.push_str("\\\""),
451            '\\' => out.push_str("\\\\"),
452            '\u{8}' => out.push_str("\\b"),
453            '\u{c}' => out.push_str("\\f"),
454            '\n' => out.push_str("\\n"),
455            '\r' => out.push_str("\\r"),
456            '\t' => out.push_str("\\t"),
457            '\u{0}'..='\u{1f}' => {
458                write!(out, "\\u{:04x}", u32::from(code_point)).expect("writing to a string");
459            }
460            _ => out.push(code_point),
461        }
462    }
463    out.push('"');
464}
465
466fn write_canonical(value: &Json, out: &mut String) {
467    match value {
468        Json::Null => out.push_str("null"),
469        Json::Bool(true) => out.push_str("true"),
470        Json::Bool(false) => out.push_str("false"),
471        Json::Number(number) => write!(out, "{number}").expect("writing to a string"),
472        Json::String(text) => write_string(text, out),
473        Json::Array(items) => {
474            out.push('[');
475            for (index, item) in items.iter().enumerate() {
476                if index > 0 {
477                    out.push(',');
478                }
479                write_canonical(item, out);
480            }
481            out.push(']');
482        }
483        Json::Object(members) => {
484            // UTF-8 byte order is code-point order.
485            let mut sorted: Vec<&(String, Json)> = members.iter().collect();
486            sorted.sort_by(|a, b| a.0.cmp(&b.0));
487            out.push('{');
488            for (index, (key, item)) in sorted.into_iter().enumerate() {
489                if index > 0 {
490                    out.push(',');
491                }
492                write_string(key, out);
493                out.push(':');
494                write_canonical(item, out);
495            }
496            out.push('}');
497        }
498    }
499}