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
//! Rebuilding a value one program made as a value of another program's type
//! (`history.md`, *A run may continue on edited code*).
//!
//! The value is walked by structure, directed by the type it is rebuilt at:
//! a record's fields and a named payload are matched by name, a constructor
//! is found by its name, and a host value stays the same token. It is
//! rebuilt as [`crate::decode`] in [`crate::Mode::Rebuild`] rebuilds the value's
//! JSON form, without writing that form: a field the type does not declare is
//! refused, a missing field is `None` when it is an `Option` and refused
//! otherwise, two elements of a set or two keys of a dictionary that rebuild
//! equal are refused, and a std type with a form holds its text to that form.
//!
//! The parts of a value are its own, so this module only says where each
//! comes from and at which type; [`crate::build`] keeps the aggregates being
//! rebuilt on the heap and makes each from its parts, so a value nested as
//! deep as the limits allow is rebuilt in constant native stack.

use std::borrow::Cow;
use std::sync::Arc;

use flow_types::{DeclId, JsonValueCtor, OptionCtor, Payload};
use flow_value::{Dict, Set, Text, Value};

use crate::build::{Begun, Frame, Make, Source, build, distinct_dict, distinct_set, normal};
use crate::catalog::{Catalog, StdForm};
use crate::error::{DecodeError, DecodeErrorKind, Place};
use crate::form::{json_parts, part_types};
use crate::json::quote;
use crate::limits::Limits;
use flow_types::{Body, Type};

/// Rebuilds `value`, which another program made, as a value of `ty` in
/// `catalog`, matching each record field, named payload part and
/// constructor by its declared name.
///
/// # Errors
///
/// A [`DecodeError`] naming where `value` is not a value of `ty`: a
/// constructor `ty` does not declare, a field it does not declare or one it
/// requires that `value` lacks, a part of another form, two elements or
/// keys that rebuild equal, a type with no values, or a nesting deeper than
/// `limits` allow.
pub fn rebuild_by_name(
    catalog: &Catalog,
    ty: &Type,
    value: &Value,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    let mut rebuilder = Rebuilder {
        catalog,
        limits,
        path: Place::default(),
    };
    let root = rebuilder.begin(&Cow::Borrowed(ty), value, 0)?;
    build(&mut rebuilder, root)
}

struct Rebuilder<'a> {
    catalog: &'a Catalog,
    limits: &'a Limits,
    path: Place,
}

/// The parts of an aggregate being rebuilt: the types they are rebuilt at
/// and where each is given. The types repeat in turn, so a list or set has
/// its element type, a dictionary its key and value types, and a tuple, a
/// payload or a record one type per part.
///
/// A type is borrowed from the one the rebuild was asked for while it can
/// be, and owned only where a declaration's arguments were put in place.
struct Parts<'a> {
    types: Vec<Cow<'a, Type>>,
    given: Given<'a>,
}

/// Where an aggregate's parts are given.
enum Given<'a> {
    /// The value's parts in order, each at its index.
    Indexed(flow_value::Parts<'a>),
    /// One part, read where the aggregate is: an `Option`'s `Some` or a
    /// newtype's base.
    One(&'a Value),
    /// The declared fields in order, each with the part given by its name,
    /// or none when it is not given.
    Fields(Vec<(&'a str, Option<&'a Value>)>),
}

impl<'a> Parts<'a> {
    fn new(types: Vec<Cow<'a, Type>>, given: Given<'a>) -> Self {
        Parts { types, given }
    }
}

impl<'a> Rebuilder<'a> {
    fn refuse(&self, kind: DecodeErrorKind, problem: impl Into<String>) -> DecodeError {
        DecodeError::of(&self.path, kind, problem.into())
    }

    /// 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.refuse(
                DecodeErrorKind::TooLarge,
                format!("nests deeper than {} levels", self.limits.depth),
            ));
        }
        Ok(level)
    }

    /// Begins rebuilding `value` as a value of `ty`, `level` deep: one that
    /// holds no other value is done at once, and an aggregate is opened.
    fn begin(
        &mut self,
        ty: &Cow<'a, Type>,
        value: &'a Value,
        level: usize,
    ) -> Result<Begun<Parts<'a>>, DecodeError> {
        let indexed = |make: Make, ty: &Cow<'a, Type>, level: usize| {
            Frame::open(
                make,
                Parts::new(part_types(ty), Given::Indexed(value.parts())),
                0,
                level,
            )
        };
        match (&**ty, value) {
            (Type::Int, Value::Int(_))
            | (Type::Decimal, Value::Decimal(_))
            | (Type::Bool, Value::Bool(_))
            | (Type::Text, Value::Text(_))
            | (Type::Bytes, Value::Bytes(_))
            | (Type::Duration, Value::Duration(_))
            | (Type::Instant, Value::Instant(_))
            | (Type::Unit, Value::Unit) => Ok(Begun::Done(value.clone())),
            (Type::NotData | Type::Function { .. }, _) => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                "has a type with no encoding, so it holds no value",
            )),
            (Type::Never | Type::Param(_) | Type::Task(_), _) => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                "has a type with no values to decode",
            )),
            (Type::Json, Value::Variant(_)) => self.json(value, level),
            (Type::List(_), Value::List(_)) => Ok(indexed(Make::List, ty, self.enter(level)?)),
            (Type::Set(_), Value::Set(_)) => Ok(indexed(Make::Set, ty, self.enter(level)?)),
            (Type::Dict(..), Value::Dict(_)) => Ok(indexed(Make::Dict, ty, self.enter(level)?)),
            (Type::Tuple(parts), Value::Tuple(tuple)) if parts.len() == tuple.parts().len() => {
                Ok(indexed(Make::Tuple, ty, self.enter(level)?))
            }
            (Type::Option(_), Value::Variant(_)) => self.option(ty, value, level),
            (Type::Named(decl, args), _) => self.named(ty, *decl, args, value, level),
            _ => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                format!("is not a value of {}", self.catalog.name(ty)),
            )),
        }
    }

    /// The value of a field that was not given at `ty`: `None` for an
    /// `Option`, and refused for any other.
    fn missing(&self, ty: &Type) -> Result<Value, DecodeError> {
        if matches!(&*self.catalog.erase(ty), Type::Option(_)) {
            Ok(self.catalog.none())
        } else {
            Err(self.refuse(DecodeErrorKind::Missing, "is missing"))
        }
    }

    /// An `Option` of `ty`.
    fn option(
        &mut self,
        ty: &Cow<'a, Type>,
        value: &'a Value,
        level: usize,
    ) -> Result<Begun<Parts<'a>>, DecodeError> {
        let level = self.enter(level)?;
        let option = self.catalog.option();
        let Value::Variant(variant) = value else {
            return Err(self.refuse(DecodeErrorKind::Mismatch, "is not an Option"));
        };
        match (
            OptionCtor::named(variant.constructor().name()),
            variant.payload(),
        ) {
            (Some(OptionCtor::None), []) => Ok(Begun::Done(self.catalog.none())),
            (Some(OptionCtor::Some), [item]) => {
                self.path.constructor(OptionCtor::Some.name());
                Ok(Frame::open(
                    Make::Variant(
                        Arc::clone(&option.shape),
                        option.ctors.index(OptionCtor::Some),
                    ),
                    Parts::new(part_types(ty), Given::One(item)),
                    1,
                    level,
                ))
            }
            _ => Err(self.refuse(DecodeErrorKind::Mismatch, "is not an Option")),
        }
    }

    /// A `json.Value`, constructor by constructor.
    fn json(&mut self, value: &'a Value, level: usize) -> Result<Begun<Parts<'a>>, DecodeError> {
        let level = self.enter(level)?;
        let Value::Variant(variant) = value else {
            return Err(self.refuse(DecodeErrorKind::Mismatch, "is not a value of json.Value"));
        };
        let raw = self.catalog.json();
        let name = variant.constructor().name();
        let Some(ctor) = JsonValueCtor::named(name) else {
            return Err(self.refuse(
                DecodeErrorKind::Mismatch,
                format!(
                    "names {}, which is not a constructor of json.Value",
                    quote(name)
                ),
            ));
        };
        let parts = json_parts(ctor);
        if parts.len() != variant.payload().len() {
            return Err(self.refuse(DecodeErrorKind::Mismatch, "has a payload of another form"));
        }
        self.path.constructor(name);
        let types = parts.into_iter().map(Cow::Owned).collect();
        Ok(Frame::open(
            Make::Variant(Arc::clone(&raw.shape), raw.ctors.index(ctor)),
            Parts::new(types, Given::Indexed(value.parts())),
            0,
            level,
        ))
    }

    /// A value of the declared type `ty`, `decl` with `args`.
    fn named(
        &mut self,
        ty: &Type,
        decl: DeclId,
        args: &[Type],
        value: &'a Value,
        level: usize,
    ) -> Result<Begun<Parts<'a>>, DecodeError> {
        let catalog = self.catalog;
        let declared = catalog.decl(decl);
        let owned = |types: &[Type]| -> Vec<Cow<'a, Type>> {
            types
                .iter()
                .map(|part| Cow::Owned(part.subst(args)))
                .collect()
        };
        match (&declared.body, value) {
            (Body::Record(shape, types), Value::Record(record)) => {
                let level = self.enter(level)?;
                let names: Vec<&str> = record.shape().fields().collect();
                let given = self.by_name(ty, shape.fields().collect(), &names, record.fields())?;
                Ok(Frame::open(
                    Make::Record(Arc::clone(shape)),
                    Parts::new(owned(types), given),
                    0,
                    level,
                ))
            }
            (Body::Enum(shape, ctors), Value::Variant(variant)) => {
                let name = variant.constructor().name();
                let Some(index) = shape
                    .constructors()
                    .iter()
                    .position(|ctor| ctor.name() == name)
                else {
                    return Err(self.refuse(
                        DecodeErrorKind::Mismatch,
                        format!(
                            "names {}, which is not a constructor of {}",
                            quote(name),
                            catalog.name(ty)
                        ),
                    ));
                };
                let level = self.enter(level)?;
                self.path.constructor(name);
                let given = match (
                    shape.constructors()[index].payload(),
                    variant.constructor().payload(),
                ) {
                    (Payload::None, Payload::None) => Given::Indexed(value.parts()),
                    (Payload::Positional(count), Payload::Positional(given)) if count == given => {
                        Given::Indexed(value.parts())
                    }
                    (Payload::Named(names), Payload::Named(given)) => {
                        let names = names.iter().map(|name| &**name).collect();
                        let given: Vec<&str> = given.iter().map(|name| &**name).collect();
                        self.by_name(ty, names, &given, variant.payload())?
                    }
                    (Payload::None | Payload::Positional(_) | Payload::Named(_), _) => {
                        return Err(
                            self.refuse(DecodeErrorKind::Mismatch, "has a payload of another form")
                        );
                    }
                };
                Ok(Frame::open(
                    Make::Variant(Arc::clone(shape), index),
                    Parts::new(owned(&ctors[index]), given),
                    0,
                    level,
                ))
            }
            (Body::Newtype(base), _) => Ok(Frame::open(
                Make::Newtype(StdForm::of(declared)),
                Parts::new(vec![Cow::Owned(base.subst(args))], Given::One(value)),
                1,
                level,
            )),
            (Body::Host, Value::Host(_)) => Ok(Begun::Done(value.clone())),
            (Body::NonData, _) => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                "has a type with no encoding, so it holds no value",
            )),
            (Body::Record(..) | Body::Enum(..) | Body::Host, _) => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                format!("is not a value of {}", catalog.name(ty)),
            )),
        }
    }

    /// The fields `names`, each with the part of its name in `given`'s
    /// `values`, or none where `given` lacks it; a name `given` holds that
    /// `names` lacks is refused. Both sides are sorted once and matched by
    /// binary search, so a record of f fields costs O(f log f).
    fn by_name(
        &mut self,
        ty: &Type,
        names: Vec<&'a str>,
        given: &[&'a str],
        values: &'a [Value],
    ) -> Result<Given<'a>, DecodeError> {
        let sorted = |names: &[&'a str]| {
            let mut order: Vec<usize> = (0..names.len()).collect();
            order.sort_unstable_by_key(|&at| names[at]);
            order
        };
        let declared = sorted(&names);
        if let Some(extra) = given.iter().find(|name| {
            declared
                .binary_search_by(|&at| names[at].cmp(name))
                .is_err()
        }) {
            self.path.field(extra);
            return Err(self.refuse(
                DecodeErrorKind::Unknown,
                format!("is not a field of {}", self.catalog.name(ty)),
            ));
        }
        let present = sorted(given);
        let fields = names
            .into_iter()
            .map(|name| {
                let at = present.binary_search_by(|&at| given[at].cmp(name)).ok();
                (name, at.map(|at| &values[present[at]]))
            })
            .collect();
        Ok(Given::Fields(fields))
    }
}

impl<'a> Source<Parts<'a>> for Rebuilder<'a> {
    fn path(&mut self) -> &mut Place {
        &mut self.path
    }

    fn next(
        &mut self,
        frame: &mut Frame<Parts<'a>>,
    ) -> Result<Option<Begun<Parts<'a>>>, DecodeError> {
        let at = frame.values.len();
        let parts = &mut frame.parts;
        let part = match &mut parts.given {
            Given::Indexed(values) => {
                let Some(part) = values.next() else {
                    return Ok(None);
                };
                self.path.index(at);
                Some(part)
            }
            Given::One(part) => {
                if at > 0 {
                    return Ok(None);
                }
                Some(*part)
            }
            Given::Fields(fields) => {
                let Some(&(name, part)) = fields.get(at) else {
                    return Ok(None);
                };
                self.path.field(name);
                part
            }
        };
        let ty = &parts.types[at % parts.types.len()];
        let begun = match part {
            Some(part) => self.begin(ty, part, frame.level)?,
            None => Begun::Done(self.missing(ty)?),
        };
        Ok(Some(begun))
    }

    fn steps(frame: &Frame<Parts<'a>>) -> usize {
        match frame.parts.given {
            Given::One(_) => 0,
            Given::Indexed(_) | Given::Fields(_) => 1,
        }
    }

    fn set(&self, items: Vec<Value>) -> Result<Set, DecodeError> {
        distinct_set(items, &self.path)
    }

    fn dict(&self, entries: Vec<(Value, Value)>) -> Result<Dict, DecodeError> {
        distinct_dict(entries, &self.path)
    }

    fn form(&self, form: StdForm, text: Text) -> Result<Value, DecodeError> {
        normal(form, &text, self.limits, &self.path)
    }
}