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
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
//! Decoding a value of a declared type (`abi.md`, *Decoding*).
//!
//! Decoding is directed by the type and never coerces, guesses a
//! constructor, fills a default or repairs a value. Every failure names where
//! it happened and why.

use std::sync::Arc;

use flow_value::{Bytes, Decimal, Dict, Int, Payload, Record, Set, Text, Tuple, Value, Variant};
use num_bigint::BigInt;

use crate::error::{DecodeError, Path};
use crate::json::{Json, parse, quote};
use crate::limits::Limits;
use crate::time;
use crate::types::{Body, Catalog, Type};

/// What is being decoded, which decides what a field the type does not
/// declare means.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
    /// A Tool reply or `json.decode`: an undeclared field is ignored.
    Reply,
    /// A run's input: an undeclared field is refused, and so is a host value,
    /// since input is data.
    Input,
    /// A value the program made, read back from its canonical text, such as
    /// a checkpoint's arguments on resume. This is not decoding (`abi.md`,
    /// *Decoding*): every type is rebuilt, opaque types and host tokens
    /// included, and a type with a part that has no encoding, such as a
    /// list of functions, whose text holds no value there. An undeclared
    /// field is refused, since the text is canonical.
    Rebuild,
}

/// Decodes `text` as a value of `ty`.
pub fn decode_text(
    catalog: &Catalog,
    ty: &Type,
    text: &str,
    mode: Mode,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    decodable(catalog, ty, mode)?;
    let json = parse(text, limits)?;
    run(catalog, ty, &json, mode, limits)
}

/// Decodes `json` as a value of `ty`.
pub fn decode(
    catalog: &Catalog,
    ty: &Type,
    json: &Json,
    mode: Mode,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    decodable(catalog, ty, mode)?;
    run(catalog, ty, json, mode, limits)
}

/// Rebuilds a checkpoint's argument of type `ty` from `json` (`trace.md`,
/// *Checkpoints*), as [`decode`] does in [`Mode::Rebuild`], except that a
/// task is the id of the call it is parked on, which `tasks` turns into the
/// task given that id and the type of the task's result. An id `tasks`
/// knows no task for is a [`DecodeError`].
pub fn rebuild(
    catalog: &Catalog,
    ty: &Type,
    json: &Json,
    limits: &Limits,
    tasks: &mut dyn FnMut(&str, &Type) -> Option<Value>,
) -> Result<Value, DecodeError> {
    decodable(catalog, ty, Mode::Rebuild)?;
    Decoder {
        catalog,
        mode: Mode::Rebuild,
        limits,
        path: Path::default(),
        tasks: Some(tasks),
    }
    .value(ty, json, 0)
}

fn run(
    catalog: &Catalog,
    ty: &Type,
    json: &Json,
    mode: Mode,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    Decoder {
        catalog,
        mode,
        limits,
        path: Path::default(),
        tasks: None,
    }
    .value(ty, json, 0)
}

/// Whether decoding may build a value of `ty` at all: no part of it has no
/// encoding and no part is `opaque`, and in [`Mode::Input`] none is a host
/// type (`tools.md`, *Decoding*). This is judged of the type, before any
/// text is read, so an absent part refuses as surely as a present one.
/// Rebuilding refuses no type but an unbound type parameter.
pub fn decodable(catalog: &Catalog, ty: &Type, mode: Mode) -> Result<(), DecodeError> {
    match catalog.judge(ty, mode) {
        Some(problem) => Err(DecodeError::new(&Path::default(), problem)),
        None => Ok(()),
    }
}

/// How a checkpoint's task is rebuilt: from its call id and the type of its
/// result.
type Tasks<'c> = &'c mut dyn FnMut(&str, &Type) -> Option<Value>;

struct Decoder<'c> {
    catalog: &'c Catalog,
    mode: Mode,
    limits: &'c Limits,
    path: Path,
    /// How a checkpoint's task is rebuilt from its call id; `None` outside
    /// one.
    tasks: Option<Tasks<'c>>,
}

impl Decoder<'_> {
    fn fail(&self, problem: impl Into<String>) -> DecodeError {
        DecodeError::new(&self.path, problem.into())
    }

    fn limited(&self, problem: impl Into<String>) -> DecodeError {
        DecodeError::limited(&self.path, problem.into())
    }

    fn expected(&self, what: &str, json: &Json) -> DecodeError {
        self.fail(format!("should be {what}, not {}", json.kind()))
    }

    fn at<T>(
        &mut self,
        step: impl FnOnce(&mut Path),
        go: impl FnOnce(&mut Self) -> Result<T, DecodeError>,
    ) -> Result<T, DecodeError> {
        step(&mut self.path);
        let result = go(self)?;
        self.path.pop();
        Ok(result)
    }

    /// Enters an aggregate `level` deep, which [`Limits::depth`] bounds.
    fn enter(&self, level: usize) -> Result<usize, DecodeError> {
        let level = level + 1;
        if level > self.limits.depth {
            return Err(self.limited(format!("nests deeper than {} levels", self.limits.depth)));
        }
        Ok(level)
    }

    fn text(&self, text: &str) -> Result<Text, DecodeError> {
        if text.len() > self.limits.text_bytes {
            return Err(self.limited(format!("is longer than {} bytes", self.limits.text_bytes)));
        }
        Ok(Text::new(text))
    }

    fn value(&mut self, ty: &Type, json: &Json, level: usize) -> Result<Value, DecodeError> {
        let value = match (ty, json) {
            (Type::Int, Json::Number(number)) => Value::Int(self.int(number)?),
            (Type::Int, _) => return Err(self.expected("an integer", json)),
            (Type::Decimal, Json::Number(number)) => self.decimal(number)?,
            (Type::Decimal, _) => return Err(self.expected("a number", json)),
            (Type::Bool, Json::Bool(flag)) => Value::Bool(*flag),
            (Type::Bool, _) => return Err(self.expected("a boolean", json)),
            (Type::Text, Json::String(text)) => Value::Text(self.text(text)?),
            (Type::Text, _) => return Err(self.expected("a string", json)),
            (Type::Bytes, Json::String(text)) => Value::Bytes(self.bytes(text)?),
            (Type::Bytes, _) => return Err(self.expected("a base64 string", json)),
            (Type::Duration, Json::String(text)) => Value::Duration(
                time::duration(text).ok_or_else(|| self.fail("should be an ISO 8601 duration"))?,
            ),
            (Type::Duration, _) => return Err(self.expected("an ISO 8601 duration", json)),
            (Type::Instant, Json::String(text)) => Value::Instant(
                time::instant(text)
                    .ok_or_else(|| self.fail("should be an ISO 8601 date and time"))?,
            ),
            (Type::Instant, _) => return Err(self.expected("an ISO 8601 date and time", json)),
            (Type::Unit, Json::Array(items)) if items.is_empty() => Value::Unit,
            (Type::Unit, _) => return Err(self.expected("`[]`", json)),
            (Type::Task(result), Json::String(call)) if self.tasks.is_some() => {
                let tasks = self.tasks.as_mut().expect("checked by the guard");
                match tasks(call, result) {
                    Some(task) => task,
                    None => {
                        return Err(
                            self.fail(format!("names {}, which no task is parked on", quote(call)))
                        );
                    }
                }
            }
            (Type::Task(_), _) if self.tasks.is_some() => {
                return Err(self.expected("the id of the call a task is parked on", json));
            }
            // Only rebuilding reaches a type with no encoding, and a value
            // the program made holds nothing of one: had it held one, no
            // checkpoint would have been taken.
            (Type::NotData | Type::Function { .. }, _) => {
                return Err(self.fail("has a type with no encoding, so it holds no value"));
            }
            // Only `Never`, and a task outside a checkpoint, reach here of
            // these: the others were refused before any text was read.
            (Type::Never | Type::Param(_) | Type::Task(_), _) => {
                return Err(self.fail("has a type with no values to decode"));
            }
            (Type::Json, _) => self.raw(json, level)?,
            (Type::List(item), Json::Array(items)) => {
                let level = self.enter(level)?;
                Value::List(self.items(item, items, level)?.into_iter().collect())
            }
            (Type::Set(item), Json::Array(items)) => {
                let level = self.enter(level)?;
                let items = self.items(item, items, level)?;
                Value::Set(Set::from_items(items).expect("decoded values are data"))
            }
            (Type::List(_) | Type::Set(_), _) => return Err(self.expected("an array", json)),
            (Type::Dict(key, item), _) => self.dict(key, item, json, level)?,
            (Type::Option(item), _) => self.option(item, json, level)?,
            (Type::Tuple(parts), Json::Array(items)) if parts.len() == items.len() => {
                let level = self.enter(level)?;
                let parts = parts
                    .iter()
                    .zip(items)
                    .enumerate()
                    .map(|(index, (part, item))| {
                        self.at(|path| path.index(index), |me| me.value(part, item, level))
                    })
                    .collect::<Result<Vec<_>, _>>()?;
                Value::Tuple(Tuple::new(parts))
            }
            (Type::Tuple(parts), _) => {
                return Err(self.expected(&format!("an array of {} elements", parts.len()), json));
            }
            (Type::Named(decl, args), _) => self.named(ty, *decl, args, json, level)?,
        };
        Ok(value)
    }

    fn decimal(&self, number: &Decimal) -> Result<Value, DecodeError> {
        if number.coefficient().bits() > self.limits.int_bits {
            return Err(self.limited(format!(
                "has a coefficient larger than {} bits",
                self.limits.int_bits
            )));
        }
        Ok(Value::Decimal(number.clone()))
    }

    fn int(&self, number: &Decimal) -> Result<Int, DecodeError> {
        if number.exponent() < 0 {
            return Err(self.fail("should be a whole number"));
        }
        // The number is coefficient × 10^exponent with a nonzero coefficient
        // or a zero exponent, and 10^p has more than p bits, so an exponent
        // past the limit is refused without building a power of ten as long
        // as it; one within it is built and measured exactly.
        let too_large = || {
            self.limited(format!(
                "is an integer larger than {} bits",
                self.limits.int_bits
            ))
        };
        let places = number.exponent().unsigned_abs();
        if places > self.limits.int_bits {
            return Err(too_large());
        }
        let places = u32::try_from(places).expect("an exponent the limit bounds");
        let value = number.coefficient() * BigInt::from(10).pow(places);
        if value.magnitude().bits() > self.limits.int_bits {
            return Err(too_large());
        }
        Ok(Int::from(value))
    }

    fn bytes(&self, text: &str) -> Result<Bytes, DecodeError> {
        let bytes =
            base64(text).ok_or_else(|| self.fail("should be standard base64 with padding"))?;
        if bytes.len() > self.limits.text_bytes {
            return Err(self.limited(format!("is longer than {} bytes", self.limits.text_bytes)));
        }
        Ok(Bytes::from(bytes))
    }

    fn items(
        &mut self,
        ty: &Type,
        items: &[Json],
        level: usize,
    ) -> Result<Vec<Value>, DecodeError> {
        items
            .iter()
            .enumerate()
            .map(|(index, item)| self.at(|path| path.index(index), |me| me.value(ty, item, level)))
            .collect()
    }

    fn dict(
        &mut self,
        key: &Type,
        item: &Type,
        json: &Json,
        level: usize,
    ) -> Result<Value, DecodeError> {
        let entries = match (key, json) {
            (Type::Text, Json::Object(members)) => {
                let level = self.enter(level)?;
                members
                    .iter()
                    .map(|(name, member)| {
                        self.at(
                            |path| path.key(name),
                            |me| Ok((Value::Text(me.text(name)?), me.value(item, member, level)?)),
                        )
                    })
                    .collect::<Result<Vec<_>, DecodeError>>()?
            }
            (Type::Text, _) => return Err(self.expected("an object", json)),
            (_, Json::Array(pairs)) => {
                let level = self.enter(level)?;
                pairs
                    .iter()
                    .enumerate()
                    .map(|(index, pair)| {
                        self.at(
                            |path| path.index(index),
                            |me| match pair {
                                Json::Array(parts) if parts.len() == 2 => {
                                    let name = me.at(
                                        |path| path.index(0),
                                        |me| me.value(key, &parts[0], level),
                                    )?;
                                    let value = me.at(
                                        |path| path.index(1),
                                        |me| me.value(item, &parts[1], level),
                                    )?;
                                    Ok((name, value))
                                }
                                _ => Err(me.expected("a `[key, value]` pair", pair)),
                            },
                        )
                    })
                    .collect::<Result<Vec<_>, DecodeError>>()?
            }
            _ => return Err(self.expected("an array of `[key, value]` pairs", json)),
        };
        let count = entries.len();
        let dict = Dict::from_entries(entries).expect("decoded keys are data");
        if dict.len() != count {
            return Err(self.fail("has two equal keys"));
        }
        Ok(Value::Dict(dict))
    }

    fn option(&mut self, item: &Type, json: &Json, level: usize) -> Result<Value, DecodeError> {
        let option = self.catalog.option();
        let level = self.enter(level)?;
        let (index, payload) = match json {
            Json::String(name) if name == "None" => (option.at[0], Vec::new()),
            Json::Object(members) if members.len() == 1 && members[0].0 == "Some" => {
                let inner = self.at(
                    |path| path.name("Some"),
                    |me| me.value(item, &members[0].1, level),
                )?;
                (option.at[1], vec![inner])
            }
            Json::Null => return Err(self.fail("is null, which only an Option field may be")),
            _ => return Err(self.expected("`\"None\"` or `{\"Some\": ...}`", json)),
        };
        Ok(Value::Variant(
            Variant::new(Arc::clone(&option.shape), index, payload).expect("std's Option"),
        ))
    }

    /// The value of an `Option` field: absent or `null` is `None`, and
    /// anything else is the payload of `Some`.
    fn option_field(
        &mut self,
        item: &Type,
        json: Option<&Json>,
        level: usize,
    ) -> Result<Value, DecodeError> {
        let option = self.catalog.option();
        let level = self.enter(level)?;
        let (index, payload) = match json {
            None | Some(Json::Null) => (option.at[0], Vec::new()),
            Some(json) => (option.at[1], vec![self.value(item, json, level)?]),
        };
        Ok(Value::Variant(
            Variant::new(Arc::clone(&option.shape), index, payload).expect("std's Option"),
        ))
    }

    fn named(
        &mut self,
        ty: &Type,
        decl: crate::DeclId,
        args: &[Type],
        json: &Json,
        level: usize,
    ) -> Result<Value, DecodeError> {
        let named = self.catalog.decl(decl);
        match &named.body {
            Body::Record(shape, fields) => {
                let Json::Object(members) = json else {
                    return Err(self.expected("an object", json));
                };
                let level = self.enter(level)?;
                let names: Vec<&str> = shape.fields().collect();
                let fields: Vec<Type> = fields.iter().map(|field| field.subst(args)).collect();
                let values = self.fields(ty, &names, &fields, members, level)?;
                Ok(Value::Record(
                    Record::new(Arc::clone(shape), values).expect("one value per field"),
                ))
            }
            Body::Enum(shape, ctors) => {
                let (name, payload) = match json {
                    Json::String(name) => (name, None),
                    Json::Object(members) if members.len() == 1 => {
                        (&members[0].0, Some(&members[0].1))
                    }
                    _ => {
                        return Err(self
                            .expected("a constructor's name or an object with one member", json));
                    }
                };
                let Some(index) = (0..)
                    .map_while(|index| shape.constructor(index))
                    .position(|ctor| ctor.name() == name)
                else {
                    return Err(self.fail(format!(
                        "names {}, which is not a constructor of {}",
                        quote(name),
                        self.catalog.name(ty)
                    )));
                };
                let ctor = shape.constructor(index).expect("found above");
                let parts: Vec<Type> = ctors[index].iter().map(|part| part.subst(args)).collect();
                let level = self.enter(level)?;
                let values = self.at(
                    |path| path.name(name),
                    |me| me.payload(ty, ctor.payload(), &parts, payload, level),
                )?;
                Ok(Value::Variant(
                    Variant::new(Arc::clone(shape), index, values).expect("one value per part"),
                ))
            }
            Body::NonData => Err(self.fail("has a type with no encoding, so it holds no value")),
            Body::Host => match json {
                Json::String(token) => Ok(Value::Host(flow_value::HostToken::new(token))),
                _ => Err(self.expected("a host token string", json)),
            },
        }
    }

    fn payload(
        &mut self,
        ty: &Type,
        payload: &Payload,
        parts: &[Type],
        json: Option<&Json>,
        level: usize,
    ) -> Result<Vec<Value>, DecodeError> {
        match (payload, json) {
            (Payload::None, None) => Ok(Vec::new()),
            (Payload::None, Some(_)) => Err(self.fail("carries no payload")),
            (_, None) => Err(self.fail("carries a payload, so it is written as an object")),
            (Payload::Positional(1), Some(json)) => Ok(vec![self.value(&parts[0], json, level)?]),
            (Payload::Positional(count), Some(Json::Array(items))) if items.len() == *count => {
                parts
                    .iter()
                    .zip(items)
                    .enumerate()
                    .map(|(index, (part, item))| {
                        self.at(|path| path.index(index), |me| me.value(part, item, level))
                    })
                    .collect()
            }
            (Payload::Positional(count), Some(json)) => {
                Err(self.expected(&format!("an array of {count} elements"), json))
            }
            (Payload::Named(names), Some(Json::Object(members))) => {
                let names: Vec<&str> = names.iter().map(|name| &**name).collect();
                self.fields(ty, &names, parts, members, level)
            }
            (Payload::Named(_), Some(json)) => Err(self.expected("an object", json)),
        }
    }

    /// The values of named fields read from `members`, in declaration order.
    fn fields(
        &mut self,
        ty: &Type,
        names: &[&str],
        types: &[Type],
        members: &[(String, Json)],
        level: usize,
    ) -> Result<Vec<Value>, DecodeError> {
        if self.mode != Mode::Reply
            && let Some((extra, _)) = members
                .iter()
                .find(|(key, _)| !names.contains(&key.as_str()))
        {
            return self.at(
                |path| path.name(extra),
                |me| Err(me.fail(format!("is not a field of {}", me.catalog.name(ty)))),
            );
        }
        names
            .iter()
            .zip(types)
            .map(|(name, field)| {
                let member = members
                    .iter()
                    .find(|(key, _)| key == name)
                    .map(|(_, json)| json);
                self.at(
                    |path| path.name(name),
                    |me| match (field, member) {
                        (Type::Option(item), member) => me.option_field(item, member, level),
                        (_, Some(Json::Null)) => {
                            Err(me.fail("is null, which only an Option field may be"))
                        }
                        (_, Some(json)) => me.value(field, json, level),
                        (_, None) => Err(me.fail("is missing")),
                    },
                )
            })
            .collect()
    }

    /// A `json.Value` standing for `json`.
    fn raw(&mut self, json: &Json, level: usize) -> Result<Value, DecodeError> {
        let raw = self.catalog.json();
        let [null, flag, number, text, list, object] = raw.at;
        let level = self.enter(level)?;
        let (index, payload) = match json {
            Json::Null => (null, Vec::new()),
            Json::Bool(value) => (flag, vec![Value::Bool(*value)]),
            Json::Number(value) => (number, vec![self.decimal(value)?]),
            Json::String(value) => (text, vec![Value::Text(self.text(value)?)]),
            Json::Array(items) => {
                let inner = self.enter(level)?;
                let items = self.items(&Type::Json, items, inner)?;
                (list, vec![Value::List(items.into_iter().collect())])
            }
            Json::Object(_) => (
                object,
                vec![self.dict(&Type::Text, &Type::Json, json, level)?],
            ),
        };
        Ok(Value::Variant(
            Variant::new(Arc::clone(&raw.shape), index, payload).expect("std's json.Value"),
        ))
    }
}

/// The bytes standard base64 with padding spells, or `None` for any other
/// text: a character outside the alphabet, missing or misplaced padding, or
/// bits set past the last byte.
fn base64(text: &str) -> Option<Vec<u8>> {
    let sextet = |byte: u8| -> Option<u32> {
        Some(u32::from(match byte {
            b'A'..=b'Z' => byte - b'A',
            b'a'..=b'z' => byte - b'a' + 26,
            b'0'..=b'9' => byte - b'0' + 52,
            b'+' => 62,
            b'/' => 63,
            _ => return None,
        }))
    };
    let bytes = text.as_bytes();
    if !bytes.len().is_multiple_of(4) {
        return None;
    }
    let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
    let groups = bytes.len() / 4;
    for (at, group) in bytes.chunks(4).enumerate() {
        let padding = group.iter().rev().take_while(|byte| **byte == b'=').count();
        if padding > 2 || (padding > 0 && at + 1 != groups) {
            return None;
        }
        let mut bits = 0u32;
        for byte in &group[..4 - padding] {
            // The low six bits are clear, so adding places the sextet.
            bits = (bits << 6) + sextet(*byte)?;
        }
        bits <<= 6 * padding;
        let [_, first, second, third] = bits.to_be_bytes();
        let kept = 3 - padding;
        let unused = [first, second, third];
        if unused[kept..].iter().any(|byte| *byte != 0) {
            return None;
        }
        out.extend_from_slice(&unused[..kept]);
    }
    Some(out)
}