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
//! A generated contract in the value encoding: what a generator's
//! `extract` writes and the host reads (`abi.md`, *Extracting a contract*).
//!
//! Each type below is written as the value of the `text` type abi.md gives
//! it: a record as its fields in order, an enum as its constructor's number
//! and then its payload, an `Option` as `None` or `Some` and its value, a
//! list as its count and its items. The host reads it under
//! [`Limits::LANGUAGE`], so a contract nests no deeper than a value may.

use flow_value::{Decimal, Int};
use num_bigint::BigInt;

use super::{
    Constant, Constructor, ContractModule, Declaration, Field, FlowDeclaration, Import, Item,
    Origin, Param, Payload, TypeBody, TypeDeclaration, TypeRef, Visibility,
};
use crate::bytes::{NONE, Reader, SOME, wide, write_int, write_signed, write_text, write_uint};
use crate::error::{DecodeError, DecodeErrorKind, Place};
use crate::limits::Limits;

/// A generated contract: its modules.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Contract {
    /// Its modules, the root module's path empty.
    pub modules: Vec<Module>,
}

/// One module of a generated contract.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Module {
    /// Its module path under `contract/`, a segment each: empty for
    /// `lib.flow`, `["models"]` for `models.flow`.
    pub path: Vec<String>,
    /// The module.
    pub module: ContractModule,
}

impl Contract {
    /// Its bytes in the value encoding.
    #[must_use]
    pub fn bytes(&self) -> Vec<u8> {
        let mut out = Vec::new();
        list(&mut out, &self.modules, |out, module| {
            list(out, &module.path, |out, segment| write_text(out, segment));
            write_text(out, &module.module.generated_from);
            list(out, &module.module.imports, |out, import| {
                write_text(out, &import.path);
                option(out, import.binding.as_ref(), |out, binding| {
                    write_text(out, binding);
                });
            });
            list(out, &module.module.items, item);
        });
        out
    }

    /// The contract `bytes` hold, all of them.
    ///
    /// # Errors
    ///
    /// A [`DecodeError`] when the bytes are not one contract, or nest past
    /// the language's depth.
    pub fn decode(bytes: &[u8]) -> Result<Contract, DecodeError> {
        let mut read = Read {
            reader: Reader::new(bytes),
            depth: 0,
        };
        let modules = read.list(|read| {
            Ok(Module {
                path: read.list(Read::text)?,
                module: ContractModule {
                    generated_from: read.text()?,
                    imports: read.list(|read| {
                        Ok(Import {
                            path: read.text()?,
                            binding: read.option(Read::text)?,
                        })
                    })?,
                    items: read.list(Read::item)?,
                },
            })
        })?;
        if !read.reader.is_empty() {
            return Err(read.invalid("holds bytes after its contract"));
        }
        Ok(Contract { modules })
    }
}

fn list<T>(out: &mut Vec<u8>, items: &[T], mut each: impl FnMut(&mut Vec<u8>, &T)) {
    write_uint(out, wide(items.len()));
    for one in items {
        each(out, one);
    }
}

fn option<T>(out: &mut Vec<u8>, value: Option<&T>, each: impl FnOnce(&mut Vec<u8>, &T)) {
    match value {
        None => write_uint(out, NONE),
        Some(value) => {
            write_uint(out, SOME);
            each(out, value);
        }
    }
}

fn item(out: &mut Vec<u8>, item: &Item) {
    write_text(out, &item.docs);
    option(out, item.origin.as_ref(), |out, origin| {
        write_text(out, &origin.path);
        write_text(out, &origin.item);
    });
    match &item.declaration {
        Declaration::Type(ty) => {
            write_uint(out, 0);
            write_text(out, &ty.name);
            list(out, &ty.params, |out, param| write_text(out, param));
            match &ty.body {
                TypeBody::Host => write_uint(out, 0),
                TypeBody::Newtype { visibility, base } => {
                    write_uint(out, 1);
                    public(out, *visibility);
                    type_ref(out, base);
                }
                TypeBody::Record(fields) => {
                    write_uint(out, 2);
                    list(out, fields, field);
                }
                TypeBody::Enum(constructors) => {
                    write_uint(out, 3);
                    list(out, constructors, constructor);
                }
            }
        }
        Declaration::Flow(flow) => {
            write_uint(out, 1);
            write_text(out, &flow.name);
            list(out, &flow.generics, |out, name| write_text(out, name));
            list(out, &flow.params, |out, param| {
                write_text(out, &param.name);
                type_ref(out, &param.ty);
                option(out, param.default.as_ref(), constant);
            });
            type_ref(out, &flow.result);
        }
    }
}

fn public(out: &mut Vec<u8>, visibility: Visibility) {
    out.push(u8::from(visibility == Visibility::Public));
}

fn field(out: &mut Vec<u8>, field: &Field) {
    write_text(out, &field.docs);
    public(out, field.visibility);
    write_text(out, &field.name);
    type_ref(out, &field.ty);
}

fn constructor(out: &mut Vec<u8>, constructor: &Constructor) {
    write_text(out, &constructor.docs);
    write_text(out, &constructor.name);
    match &constructor.payload {
        Payload::Empty => write_uint(out, 0),
        Payload::Positional(parts) => {
            write_uint(out, 1);
            list(out, parts, type_ref);
        }
        Payload::Named(fields) => {
            write_uint(out, 2);
            list(out, fields, self::field);
        }
    }
}

fn type_ref(out: &mut Vec<u8>, ty: &TypeRef) {
    match ty {
        TypeRef::Named { module, name, args } => {
            write_uint(out, 0);
            option(out, module.as_ref(), |out, module| write_text(out, module));
            write_text(out, name);
            list(out, args, type_ref);
        }
        TypeRef::Tuple(parts) => {
            write_uint(out, 1);
            list(out, parts, type_ref);
        }
    }
}

fn constant(out: &mut Vec<u8>, constant: &Constant) {
    match constant {
        Constant::None => write_uint(out, 0),
        Constant::Some(inner) => {
            write_uint(out, 1);
            self::constant(out, inner);
        }
        Constant::Bool(value) => {
            write_uint(out, 2);
            out.push(u8::from(*value));
        }
        Constant::Int(value) => {
            write_uint(out, 3);
            write_int(out, value.as_bigint());
        }
        Constant::Decimal(value) => {
            write_uint(out, 4);
            write_int(out, value.coefficient());
            write_signed(out, value.exponent());
        }
        Constant::Text(text) => {
            write_uint(out, 5);
            write_text(out, text);
        }
        Constant::Tuple(parts) => {
            write_uint(out, 6);
            list(out, parts, self::constant);
        }
        Constant::Constructor(name) => {
            write_uint(out, 7);
            write_text(out, name);
        }
        Constant::Applied { newtype, value } => {
            write_uint(out, 8);
            type_ref(out, newtype);
            self::constant(out, value);
        }
    }
}

/// A contract being read: the reader, and how deeply the value being read
/// nests.
struct Read<'a> {
    reader: Reader<'a>,
    depth: usize,
}

impl Read<'_> {
    fn invalid(&self, problem: &str) -> DecodeError {
        DecodeError::of(
            &Place::default(),
            DecodeErrorKind::Mismatch,
            format!("{problem} at byte {}", self.reader.position()),
        )
    }

    /// Reads one nested part with `part`, refusing a part past the
    /// language's depth.
    fn nested<T>(
        &mut self,
        part: impl FnOnce(&mut Self) -> Result<T, DecodeError>,
    ) -> Result<T, DecodeError> {
        if self.depth >= Limits::LANGUAGE.depth {
            return Err(DecodeError::of(
                &Place::default(),
                DecodeErrorKind::TooLarge,
                format!(
                    "nests deeper than {} at byte {}",
                    Limits::LANGUAGE.depth,
                    self.reader.position()
                ),
            ));
        }
        self.depth += 1;
        let read = part(self);
        self.depth -= 1;
        read
    }

    fn text(&mut self) -> Result<String, DecodeError> {
        Ok(self.reader.text(&Limits::LANGUAGE)?.to_owned())
    }

    fn bool(&mut self) -> Result<bool, DecodeError> {
        self.reader.bool()
    }

    fn tag(&mut self, count: u64) -> Result<u64, DecodeError> {
        let tag = self.reader.uint()?;
        if tag < count {
            Ok(tag)
        } else {
            Err(self.invalid(&format!("has constructor {tag} of {count}")))
        }
    }

    fn list<T>(
        &mut self,
        mut each: impl FnMut(&mut Self) -> Result<T, DecodeError>,
    ) -> Result<Vec<T>, DecodeError> {
        let count = self.reader.count()?;
        self.nested(|read| {
            let mut items = Vec::with_capacity(count.min(read.reader.remaining()));
            for _ in 0..count {
                items.push(each(read)?);
            }
            Ok(items)
        })
    }

    fn option<T>(
        &mut self,
        each: impl FnOnce(&mut Self) -> Result<T, DecodeError>,
    ) -> Result<Option<T>, DecodeError> {
        match self.tag(2)? {
            NONE => Ok(None),
            _ => self.nested(each).map(Some),
        }
    }

    fn visibility(&mut self) -> Result<Visibility, DecodeError> {
        Ok(if self.bool()? {
            Visibility::Public
        } else {
            Visibility::Private
        })
    }

    fn item(&mut self) -> Result<Item, DecodeError> {
        let docs = self.text()?;
        let origin = self.option(|read| {
            Ok(Origin {
                path: read.text()?,
                item: read.text()?,
            })
        })?;
        let declaration = match self.tag(2)? {
            0 => Declaration::Type(TypeDeclaration {
                name: self.text()?,
                params: self.list(Read::text)?,
                body: match self.tag(4)? {
                    0 => TypeBody::Host,
                    1 => TypeBody::Newtype {
                        visibility: self.visibility()?,
                        base: self.nested(Read::type_ref)?,
                    },
                    2 => TypeBody::Record(self.list(Read::field)?),
                    _ => TypeBody::Enum(self.list(Read::constructor)?),
                },
            }),
            _ => Declaration::Flow(FlowDeclaration {
                name: self.text()?,
                generics: self.list(Read::text)?,
                params: self.list(|read| {
                    Ok(Param {
                        name: read.text()?,
                        ty: read.type_ref()?,
                        default: read.option(Read::constant)?,
                    })
                })?,
                result: self.type_ref()?,
            }),
        };
        Ok(Item {
            docs,
            origin,
            declaration,
        })
    }

    fn field(&mut self) -> Result<Field, DecodeError> {
        Ok(Field {
            docs: self.text()?,
            visibility: self.visibility()?,
            name: self.text()?,
            ty: self.type_ref()?,
        })
    }

    fn constructor(&mut self) -> Result<Constructor, DecodeError> {
        Ok(Constructor {
            docs: self.text()?,
            name: self.text()?,
            payload: match self.tag(3)? {
                0 => Payload::Empty,
                1 => Payload::Positional(self.list(Read::type_ref)?),
                _ => Payload::Named(self.list(Read::field)?),
            },
        })
    }

    fn type_ref(&mut self) -> Result<TypeRef, DecodeError> {
        match self.tag(2)? {
            0 => Ok(TypeRef::Named {
                module: self.option(Read::text)?,
                name: self.text()?,
                args: self.list(Read::type_ref)?,
            }),
            _ => Ok(TypeRef::Tuple(self.list(Read::type_ref)?)),
        }
    }

    fn constant(&mut self) -> Result<Constant, DecodeError> {
        Ok(match self.tag(9)? {
            0 => Constant::None,
            1 => Constant::Some(Box::new(self.nested(Read::constant)?)),
            2 => Constant::Bool(self.bool()?),
            3 => Constant::Int(Int::from(self.reader.int(&Limits::LANGUAGE)?)),
            4 => {
                let coefficient: BigInt = self.reader.int(&Limits::LANGUAGE)?;
                let exponent = self.reader.signed()?;
                let decimal = Decimal::new(coefficient, exponent)
                    .map_err(|_| self.invalid("has a decimal whose scale passes the host's"))?;
                if decimal.text_len() > u128::from(wide(Limits::LANGUAGE.text_bytes)) {
                    return Err(self.invalid(&format!(
                        "has a decimal longer than {} digits written out",
                        Limits::LANGUAGE.text_bytes
                    )));
                }
                Constant::Decimal(decimal)
            }
            5 => Constant::Text(self.text()?),
            6 => Constant::Tuple(self.list(Read::constant)?),
            7 => Constant::Constructor(self.text()?),
            _ => Constant::Applied {
                newtype: self.nested(Read::type_ref)?,
                value: Box::new(self.nested(Read::constant)?),
            },
        })
    }
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::*;

    fn deep(depth: usize) -> Constant {
        (0..depth).fold(Constant::None, |inner, _| Constant::Some(Box::new(inner)))
    }

    fn with_default(default: Constant) -> Contract {
        Contract {
            modules: vec![Module {
                path: Vec::new(),
                module: ContractModule {
                    generated_from: "test".to_owned(),
                    imports: Vec::new(),
                    items: vec![Item {
                        docs: String::new(),
                        origin: Some(Origin {
                            path: "tools.go".to_owned(),
                            item: "Find".to_owned(),
                        }),
                        declaration: Declaration::Flow(FlowDeclaration {
                            name: "find".to_owned(),
                            generics: Vec::new(),
                            params: vec![Param {
                                name: "limit".to_owned(),
                                ty: TypeRef::Named {
                                    module: None,
                                    name: "Int".to_owned(),
                                    args: Vec::new(),
                                },
                                default: Some(default),
                            }],
                            result: TypeRef::Tuple(Vec::new()),
                        }),
                    }],
                },
            }],
        }
    }

    #[test]
    fn a_contract_comes_back_from_its_encoding() {
        for default in [
            Constant::Int(Int::parse("-12345678901234567890123").unwrap()),
            Constant::Decimal(Decimal::parse("-1.25").unwrap()),
            Constant::Tuple(vec![Constant::Bool(true), Constant::Text("é".to_owned())]),
            deep(Limits::LANGUAGE.depth - 8),
        ] {
            let contract = with_default(default);
            assert_eq!(Contract::decode(&contract.bytes()), Ok(contract));
        }
    }

    #[test]
    fn bytes_that_are_not_one_contract_are_refused() {
        let mut trailing = with_default(Constant::None).bytes();
        trailing.push(0);
        assert!(Contract::decode(&trailing).is_err());
        let bytes = with_default(Constant::None).bytes();
        assert!(Contract::decode(&bytes[..bytes.len() - 1]).is_err());
        let mut tag = bytes;
        *tag.last_mut().unwrap() = 9;
        assert!(Contract::decode(&tag).is_err());
        let vast = with_default(Constant::Decimal(
            Decimal::new(BigInt::from(1), 1_000_000_000).unwrap(),
        ))
        .bytes();
        assert!(
            Contract::decode(&vast)
                .unwrap_err()
                .problem
                .contains("longer than")
        );
        let too_deep = with_default(deep(Limits::LANGUAGE.depth + 1)).bytes();
        assert_eq!(
            Contract::decode(&too_deep).unwrap_err().kind,
            DecodeErrorKind::TooLarge
        );
    }
}