flow-abi 0.1.0

The value encoding at the host boundary: type-directed JSON encoding and decoding, the canonical form and its hash, JSON Schemas, and Tool declaration fingerprints.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! JSON text: a tree, a strict reader, and the canonical writer.
//!
//! The reader is `abi.md`'s *Decoding* table at the level of text: numbers
//! are read exactly, a string escape naming a lone surrogate is refused, an
//! object naming one key twice is refused, and nothing nests deeper than the
//! caller allows. The writer is *The canonical form*: no whitespace, object
//! keys in ascending code-point order, the fewest escapes, and numbers in
//! plain decimal notation.
//!
//! The reader is written here rather than borrowed so that every one of those
//! rules is this crate's: a general-purpose reader rounds numbers, keeps the
//! last of two equal keys, or bounds nesting at a depth of its own choosing.

use std::collections::BTreeSet;
use std::fmt::Write as _;

use flow_value::Decimal;
use num_bigint::BigInt;

use crate::error::{DecodeError, Path};
use crate::limits::Limits;

/// A JSON value.
///
/// An object keeps its members in the order they were read or built; the
/// canonical writer sorts them. A tree built here never holds two members
/// with one key.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Json {
    /// `null`.
    Null,
    /// `true` or `false`.
    Bool(bool),
    /// A number, exactly.
    Number(Decimal),
    /// A string.
    String(String),
    /// An array.
    Array(Vec<Json>),
    /// An object.
    Object(Vec<(String, Json)>),
}

impl Json {
    /// What kind of JSON value this is, for a message: `"a string"`.
    pub fn kind(&self) -> &'static str {
        match self {
            Json::Null => "null",
            Json::Bool(_) => "a boolean",
            Json::Number(_) => "a number",
            Json::String(_) => "a string",
            Json::Array(_) => "an array",
            Json::Object(_) => "an object",
        }
    }

    /// The canonical text of this value (`abi.md`, *The canonical form*).
    pub fn canonical(&self) -> String {
        let mut out = String::new();
        write_canonical(self, &mut out);
        out
    }

    /// The member `key` of an object, if this is an object that has one.
    pub fn get(&self, key: &str) -> Option<&Json> {
        match self {
            Json::Object(members) => members
                .iter()
                .find(|(name, _)| name == key)
                .map(|(_, value)| value),
            _ => None,
        }
    }
}

/// Reads one JSON value from `text`, refusing anything after it but
/// whitespace.
///
/// Arrays and objects may nest `limits.json_depth()` deep. A number is held
/// to the limits by its value, not its spelling, and is measured before
/// anything as large as its value is built: its significant digits must
/// make an integer within `limits.int_bits`, and it may take no more than
/// `limits.text_bytes` characters in plain notation. Written out, the
/// numbers of one text together may grow it by no more than
/// `limits.text_bytes` characters, so the canonical text of what is read is
/// never longer than `text` and that limit together, however its numbers
/// were spelled.
pub fn parse(text: &str, limits: &Limits) -> Result<Json, DecodeError> {
    let mut reader = Reader {
        bytes: text.as_bytes(),
        text,
        at: 0,
        path: Path::default(),
        max_depth: limits.json_depth(),
        max_digits: limits.text_bytes,
        int_bits: limits.int_bits,
        growth: limits.text_bytes,
    };
    reader.whitespace();
    let value = reader.value(0)?;
    reader.whitespace();
    if reader.at < reader.bytes.len() {
        return Err(reader.fail("has text after the JSON value"));
    }
    Ok(value)
}

struct Reader<'t> {
    bytes: &'t [u8],
    text: &'t str,
    at: usize,
    path: Path,
    max_depth: usize,
    max_digits: usize,
    int_bits: u64,
    /// How many more characters the numbers still to be read may take in
    /// plain notation than they were written in.
    growth: usize,
}

impl<'t> Reader<'t> {
    fn fail(&self, problem: &str) -> DecodeError {
        DecodeError::new(&self.path, format!("{problem} (at byte {})", self.at))
    }

    fn limited(&self, problem: &str) -> DecodeError {
        DecodeError::limited(&self.path, format!("{problem} (at byte {})", self.at))
    }

    fn peek(&self) -> Option<u8> {
        self.bytes.get(self.at).copied()
    }

    // Every loop here is bounded by the text's length, so that no change to
    // how a step advances can make reading run forever.

    fn whitespace(&mut self) {
        self.at += self.bytes[self.at..]
            .iter()
            .take_while(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))
            .count();
    }

    fn literal(&mut self, word: &str, value: Json) -> Result<Json, DecodeError> {
        if self.bytes[self.at..].starts_with(word.as_bytes()) {
            self.at += word.len();
            Ok(value)
        } else {
            Err(self.fail("is not valid JSON"))
        }
    }

    fn value(&mut self, depth: usize) -> Result<Json, DecodeError> {
        match self.peek() {
            Some(b'n') => self.literal("null", Json::Null),
            Some(b't') => self.literal("true", Json::Bool(true)),
            Some(b'f') => self.literal("false", Json::Bool(false)),
            Some(b'"') => self.string().map(Json::String),
            Some(b'[') => self.array(depth + 1),
            Some(b'{') => self.object(depth + 1),
            Some(b'-' | b'0'..=b'9') => self.number(),
            Some(_) => Err(self.fail("is not valid JSON")),
            None => Err(self.fail("ends before a JSON value")),
        }
    }

    fn enter(&self, depth: usize) -> Result<(), DecodeError> {
        if depth > self.max_depth {
            return Err(self.limited(&format!("nests deeper than {} levels", self.max_depth)));
        }
        Ok(())
    }

    fn array(&mut self, depth: usize) -> Result<Json, DecodeError> {
        self.enter(depth)?;
        self.at += 1;
        let mut items = Vec::new();
        self.whitespace();
        if self.peek() == Some(b']') {
            self.at += 1;
            return Ok(Json::Array(items));
        }
        for _ in 0..self.bytes.len() {
            self.path.index(items.len());
            self.whitespace();
            let item = self.value(depth)?;
            self.path.pop();
            items.push(item);
            self.whitespace();
            match self.peek() {
                Some(b',') => self.at += 1,
                Some(b']') => {
                    self.at += 1;
                    return Ok(Json::Array(items));
                }
                _ => break,
            }
        }
        Err(self.fail("is not valid JSON: expected `,` or `]`"))
    }

    fn object(&mut self, depth: usize) -> Result<Json, DecodeError> {
        self.enter(depth)?;
        self.at += 1;
        let mut members = Vec::new();
        let mut seen = BTreeSet::new();
        self.whitespace();
        if self.peek() == Some(b'}') {
            self.at += 1;
            return Ok(Json::Object(members));
        }
        for _ in 0..self.bytes.len() {
            self.whitespace();
            if self.peek() != Some(b'"') {
                return Err(self.fail("is not valid JSON: expected a key"));
            }
            let key = self.string()?;
            if !seen.insert(key.clone()) {
                return Err(self.fail(&format!("has the key {} twice", quote(&key))));
            }
            self.whitespace();
            if self.peek() != Some(b':') {
                return Err(self.fail("is not valid JSON: expected `:`"));
            }
            self.at += 1;
            self.whitespace();
            self.path.key(&key);
            let value = self.value(depth)?;
            self.path.pop();
            members.push((key, value));
            self.whitespace();
            match self.peek() {
                Some(b',') => self.at += 1,
                Some(b'}') => {
                    self.at += 1;
                    return Ok(Json::Object(members));
                }
                _ => break,
            }
        }
        Err(self.fail("is not valid JSON: expected `,` or `}`"))
    }

    fn digits(&mut self) -> &'t str {
        let text = self.text;
        let start = self.at;
        self.at += text[start..].bytes().take_while(u8::is_ascii_digit).count();
        &text[start..self.at]
    }

    fn number(&mut self) -> Result<Json, DecodeError> {
        let start = self.at;
        let negative = self.peek() == Some(b'-');
        if negative {
            self.at += 1;
        }
        let whole = self.digits();
        if whole.is_empty() || (whole.len() > 1 && whole.starts_with('0')) {
            return Err(self.fail("is not a valid JSON number"));
        }
        let mut fraction = "";
        if self.peek() == Some(b'.') {
            self.at += 1;
            fraction = self.digits();
            if fraction.is_empty() {
                return Err(self.fail("is not a valid JSON number"));
            }
        }
        let mut power = "0";
        let mut lowers = false;
        if matches!(self.peek(), Some(b'e' | b'E')) {
            self.at += 1;
            lowers = self.peek() == Some(b'-');
            if matches!(self.peek(), Some(b'-' | b'+')) {
                self.at += 1;
            }
            power = self.digits();
            if power.is_empty() {
                return Err(self.fail("is not a valid JSON number"));
            }
        }
        let spelling = self.at - start - usize::from(negative);
        // The number is measured from its spelling before anything as large
        // as its value is built: building a coefficient takes time in the
        // square of its digits, and writing a number out takes as many
        // characters as its plain notation has. The coefficient is the
        // digits from the first nonzero one, the point skipped, with the
        // trailing zeros left to the exponent.
        let (head, tail) = if whole == "0" {
            (fraction.trim_start_matches('0'), "")
        } else {
            (whole, fraction)
        };
        if head.is_empty() {
            // Zero, under any exponent.
            return Ok(Json::Number(
                Decimal::new(BigInt::default(), 0).expect("zero"),
            ));
        }
        let (kept_head, kept_tail) = match tail.trim_end_matches('0') {
            "" => (head.trim_end_matches('0'), ""),
            kept => (head, kept),
        };
        let kept = kept_head.len() + kept_tail.len();
        let zeros = head.len() + tail.len() - kept;
        // 2^b has fewer than b/3 + 1 digits, since 2^3 < 10: a coefficient
        // with more is past the limit, and one with no more is short enough
        // to build and measure exactly.
        let past_bits = || {
            self.limited(&format!(
                "is a number whose digits make an integer larger than {} bits",
                self.int_bits
            ))
        };
        if u64::try_from(kept).unwrap_or(u64::MAX) > self.int_bits / 3 + 1 {
            return Err(past_bits());
        }
        let coefficient: BigInt = format!("{kept_head}{kept_tail}")
            .parse()
            .expect("ASCII digits");
        if coefficient.bits() > self.int_bits {
            return Err(past_bits());
        }
        let too_large = || self.limited("is a number too large for this host");
        // An exponent past 64 bits is past every limit, whatever the
        // coefficient and the point make of it.
        let power: i64 = power.parse().map_err(|_| too_large())?;
        let power = i128::from(power);
        let length = |n: usize| i128::try_from(n).expect("a length fits 128 bits");
        let exponent = if lowers { -power } else { power } - length(fraction.len()) + length(zeros);
        let exponent = i64::try_from(exponent).map_err(|_| too_large())?;
        let plain = plain_length(kept as u128, exponent);
        if plain > self.max_digits as u128 {
            return Err(too_large());
        }
        let plain = usize::try_from(plain).expect("within the text limit");
        self.growth = self
            .growth
            .checked_sub(plain.saturating_sub(spelling))
            .ok_or_else(|| {
                self.limited(&format!(
                    "has numbers that, written out, would lengthen it by more than {} characters",
                    self.max_digits
                ))
            })?;
        let coefficient = if negative { -coefficient } else { coefficient };
        let number = Decimal::new(coefficient, exponent).expect("no trailing zero to strip");
        Ok(Json::Number(number))
    }

    fn hex4(&mut self) -> Result<u32, DecodeError> {
        let digits = self
            .text
            .get(self.at..self.at + 4)
            .filter(|digits| digits.bytes().all(|byte| byte.is_ascii_hexdigit()))
            .ok_or_else(|| self.fail("has an invalid `\\u` escape"))?;
        self.at += 4;
        Ok(u32::from_str_radix(digits, 16).expect("four hexadecimal digits"))
    }

    fn string(&mut self) -> Result<String, DecodeError> {
        self.at += 1;
        let mut out = String::new();
        for _ in 0..self.bytes.len() {
            let start = self.at;
            self.at += self.bytes[start..]
                .iter()
                .take_while(|byte| !matches!(byte, b'"' | b'\\' | 0x00..=0x1f))
                .count();
            out.push_str(&self.text[start..self.at]);
            match self.peek() {
                Some(b'"') => {
                    self.at += 1;
                    return Ok(out);
                }
                Some(b'\\') => {
                    self.at += 1;
                    let escaped = self.peek();
                    self.at += 1;
                    match escaped {
                        Some(b'"') => out.push('"'),
                        Some(b'\\') => out.push('\\'),
                        Some(b'/') => out.push('/'),
                        Some(b'b') => out.push('\u{8}'),
                        Some(b'f') => out.push('\u{c}'),
                        Some(b'n') => out.push('\n'),
                        Some(b'r') => out.push('\r'),
                        Some(b't') => out.push('\t'),
                        Some(b'u') => out.push(self.unicode_escape()?),
                        _ => {
                            self.at -= 1;
                            return Err(self.fail("has an invalid escape"));
                        }
                    }
                }
                Some(_) => return Err(self.fail("has an unescaped control character")),
                None => break,
            }
        }
        Err(self.fail("ends inside a string"))
    }

    fn unicode_escape(&mut self) -> Result<char, DecodeError> {
        let first = self.hex4()?;
        if !(0xd800..=0xdfff).contains(&first) {
            return Ok(char::from_u32(first).expect("a scalar value outside the surrogates"));
        }
        // A high surrogate must be followed by an escape naming a low one;
        // anything else, a low one first included, is a lone surrogate.
        let second = if first < 0xdc00 && self.bytes[self.at..].starts_with(b"\\u") {
            self.at += 2;
            self.hex4()?
        } else {
            first
        };
        if !(0xdc00..=0xdfff).contains(&second) || first >= 0xdc00 {
            return Err(self.fail("has an escape naming a lone surrogate"));
        }
        let code = 0x10000 + ((first - 0xd800) << 10) + (second - 0xdc00);
        Ok(char::from_u32(code).expect("a surrogate pair names a scalar value"))
    }
}

/// How many characters a number of `digits` significant digits times
/// `10^exponent` takes in plain decimal notation, sign excluded.
fn plain_length(digits: u128, exponent: i64) -> u128 {
    let places = u128::from(exponent.unsigned_abs());
    if exponent >= 0 {
        digits + places
    } else if digits > places {
        // The digits with a point among them.
        digits + 1
    } else {
        // `0.`, zeros, and the digits.
        places + 2
    }
}

/// `text` as a canonical JSON string, quotes included.
pub(crate) fn quote(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    write_string(text, &mut out);
    out
}

fn write_string(text: &str, out: &mut String) {
    out.push('"');
    for code_point in text.chars() {
        match code_point {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\u{8}' => out.push_str("\\b"),
            '\u{c}' => out.push_str("\\f"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{0}'..='\u{1f}' => {
                write!(out, "\\u{:04x}", u32::from(code_point)).expect("writing to a string");
            }
            _ => out.push(code_point),
        }
    }
    out.push('"');
}

fn write_canonical(value: &Json, out: &mut String) {
    match value {
        Json::Null => out.push_str("null"),
        Json::Bool(true) => out.push_str("true"),
        Json::Bool(false) => out.push_str("false"),
        Json::Number(number) => write!(out, "{number}").expect("writing to a string"),
        Json::String(text) => write_string(text, out),
        Json::Array(items) => {
            out.push('[');
            for (index, item) in items.iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                write_canonical(item, out);
            }
            out.push(']');
        }
        Json::Object(members) => {
            // UTF-8 byte order is code-point order.
            let mut sorted: Vec<&(String, Json)> = members.iter().collect();
            sorted.sort_by(|a, b| a.0.cmp(&b.0));
            out.push('{');
            for (index, (key, item)) in sorted.into_iter().enumerate() {
                if index > 0 {
                    out.push(',');
                }
                write_string(key, out);
                out.push(':');
                write_canonical(item, out);
            }
            out.push('}');
        }
    }
}