flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! 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_types::Nested;
use flow_value::Decimal;
use num_bigint::BigInt;

use crate::bytes::wide;
use crate::error::{DecodeError, DecodeErrorKind, Place};
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,
        }
    }
}

/// A value nests as deeply as the type its schema is written for, so it is
/// a [`Nested`] tree, which drops on a native stack of bounded size.
impl Nested for Json {
    const LEAF: Json = Json::Null;

    /// An array's items, or an object's members' values.
    fn parts(&self) -> impl DoubleEndedIterator<Item = &Json> {
        let (items, members): (&[Json], &[(String, Json)]) = match self {
            Json::Array(items) => (items, &[]),
            Json::Object(members) => (&[], members),
            Json::Null | Json::Bool(_) | Json::Number(_) | Json::String(_) => (&[], &[]),
        };
        items.iter().chain(members.iter().map(|(_, value)| value))
    }

    fn parts_mut(&mut self) -> impl Iterator<Item = &mut Json> {
        let (items, members): (&mut [Json], &mut [(String, Json)]) = match self {
            Json::Array(items) => (items, &mut []),
            Json::Object(members) => (&mut [], members),
            Json::Null | Json::Bool(_) | Json::Number(_) | Json::String(_) => (&mut [], &mut []),
        };
        items
            .iter_mut()
            .chain(members.iter_mut().map(|(_, value)| value))
    }
}

impl Drop for Json {
    fn drop(&mut self) {
        self.free_parts();
    }
}

/// 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.
///
/// # Errors
///
/// A [`DecodeError`] when `text` is not one JSON value, or passes any of
/// the bounds above.
pub fn parse(text: &str, limits: &Limits) -> Result<Json, DecodeError> {
    let mut reader = Reader {
        bytes: text.as_bytes(),
        text,
        at: 0,
        path: Place::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()?;
    reader.whitespace();
    if reader.at < reader.bytes.len() {
        return Err(reader.fail("has text after the JSON value"));
    }
    Ok(value)
}

/// An array or an object being read, with what it holds so far.
enum Open {
    Array(Vec<Json>),
    /// The members read so far, every key seen, and the key of the member
    /// being read.
    Object(Vec<(String, Json)>, BTreeSet<String>, String),
}

struct Reader<'t> {
    bytes: &'t [u8],
    text: &'t str,
    at: usize,
    path: Place,
    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 {
        self.refuse(DecodeErrorKind::Syntax { at: self.at }, problem)
    }

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

    fn limited(&self, problem: &str) -> DecodeError {
        DecodeError::of(
            &self.path,
            DecodeErrorKind::TooLarge,
            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"))
        }
    }

    /// Reads one JSON value. The arrays and objects it is inside wait on a
    /// stack on the heap, so the native stack does not grow with the text's
    /// nesting.
    fn value(&mut self) -> Result<Json, DecodeError> {
        let mut open = Vec::new();
        // Each round reads at least one byte.
        for _ in 0..self.bytes.len() {
            let Some(value) = self.begin(&mut open)? else {
                continue;
            };
            if let Some(whole) = self.close(&mut open, value)? {
                return Ok(whole);
            }
        }
        Err(self.fail("ends before a JSON value"))
    }

    /// Reads a value that holds no other, or an empty array or object, or
    /// opens an array or object and steps onto its first element.
    fn begin(&mut self, open: &mut Vec<Open>) -> Result<Option<Json>, DecodeError> {
        let value = 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'"') => Json::String(self.string()?),
            Some(b'[') => {
                self.enter(open.len() + 1)?;
                self.at += 1;
                self.whitespace();
                if self.peek() == Some(b']') {
                    self.at += 1;
                    return Ok(Some(Json::Array(Vec::new())));
                }
                self.path.index(0);
                open.push(Open::Array(Vec::new()));
                return Ok(None);
            }
            Some(b'{') => {
                self.enter(open.len() + 1)?;
                self.at += 1;
                self.whitespace();
                if self.peek() == Some(b'}') {
                    self.at += 1;
                    return Ok(Some(Json::Object(Vec::new())));
                }
                let mut seen = BTreeSet::new();
                let key = self.key(&mut seen)?;
                self.path.key(&key);
                open.push(Open::Object(Vec::new(), seen, key));
                return Ok(None);
            }
            Some(b'-' | b'0'..=b'9') => self.number()?,
            Some(_) => return Err(self.fail("is not valid JSON")),
            None => return Err(self.fail("ends before a JSON value")),
        };
        Ok(Some(value))
    }

    /// Puts `value` in the innermost open array or object, closing each one
    /// that ends after it. Returns the whole value once nothing is open, or
    /// `None` once it steps onto the next element of one that is.
    fn close(&mut self, open: &mut Vec<Open>, value: Json) -> Result<Option<Json>, DecodeError> {
        let mut value = value;
        while let Some(innermost) = open.last_mut() {
            self.path.pop();
            self.whitespace();
            match innermost {
                Open::Array(items) => {
                    items.push(value);
                    match self.peek() {
                        Some(b',') => {
                            self.at += 1;
                            self.path.index(items.len());
                            self.whitespace();
                            return Ok(None);
                        }
                        Some(b']') => {
                            self.at += 1;
                            value = Json::Array(std::mem::take(items));
                        }
                        _ => return Err(self.fail("is not valid JSON: expected `,` or `]`")),
                    }
                }
                Open::Object(members, seen, key) => {
                    members.push((std::mem::take(key), value));
                    match self.peek() {
                        Some(b',') => {
                            self.at += 1;
                            *key = self.key(seen)?;
                            self.path.key(key);
                            return Ok(None);
                        }
                        Some(b'}') => {
                            self.at += 1;
                            value = Json::Object(std::mem::take(members));
                        }
                        _ => return Err(self.fail("is not valid JSON: expected `,` or `}`")),
                    }
                }
            }
            open.pop();
        }
        Ok(Some(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(())
    }

    /// Reads an object's key and the `:` after it, refusing a key `seen`
    /// already holds.
    fn key(&mut self, seen: &mut BTreeSet<String>) -> Result<String, DecodeError> {
        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()) {
            self.path.key(&key);
            return Err(self.refuse(
                DecodeErrorKind::Duplicate,
                "is a key its object already has",
            ));
        }
        self.whitespace();
        if self.peek() != Some(b':') {
            return Err(self.fail("is not valid JSON: expected `:`"));
        }
        self.at += 1;
        self.whitespace();
        Ok(key)
    }

    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());
        }
        crate::work::built(kept);
        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(u128::from(wide(kept)), exponent);
        if plain > u128::from(wide(self.max_digits)) {
            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('"');
}

/// Writes the canonical text of `value` to `out`, from a stack on the heap of
/// what is left to write, so a value nested however deep is written on a
/// native stack of fixed size.
fn write_canonical(value: &Json, out: &mut String) {
    enum Piece<'j> {
        Value(&'j Json),
        Key(&'j str),
        Text(&'static str),
    }
    let mut pending = vec![Piece::Value(value)];
    while let Some(piece) = pending.pop() {
        let value = match piece {
            Piece::Value(value) => value,
            Piece::Key(key) => {
                write_string(key, out);
                out.push(':');
                continue;
            }
            Piece::Text(text) => {
                out.push_str(text);
                continue;
            }
        };
        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('[');
                pending.push(Piece::Text("]"));
                for (index, item) in items.iter().enumerate().rev() {
                    pending.push(Piece::Value(item));
                    if index > 0 {
                        pending.push(Piece::Text(","));
                    }
                }
            }
            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('{');
                pending.push(Piece::Text("}"));
                for (index, (key, item)) in sorted.into_iter().enumerate().rev() {
                    pending.push(Piece::Value(item));
                    pending.push(Piece::Key(key));
                    if index > 0 {
                        pending.push(Piece::Text(","));
                    }
                }
            }
        }
    }
}