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
//! The type descriptions' own types (`abi.md`, *Type descriptions*),
//! declared once: each is the bytes a description is written in, through its
//! [`Wire`](crate::wire::Wire) codec, and the Flow type history stores one
//! as, through [`Shape::project`](crate::wire::Shape::project).
//!
//! These are the bytes as they are, before they are checked against each
//! other: [`crate::TypeSpec`], [`crate::ResultType`] and a call's validated
//! types are a description read into these and then admitted.
use std::hash::{Hash, Hasher};
use flow_types::Identity as Declared;
use flow_types::{Fold, ModulePath, Nested, Segments, SegmentsError, Tree};
use flow_value::Int;
use crate::wire;
wire! {
/// A type term: a type with no name of its own, a declaration by its
/// place in the description with its arguments, or a type parameter.
#[derive(Debug)]
pub enum Term {
/// `Int`.
Int,
/// `Decimal`.
Decimal,
/// `Bool`.
Bool,
/// `Text`.
Text,
/// `Bytes`.
Bytes,
/// `Duration`.
Duration,
/// `Instant`.
Instant,
/// `Unit`.
Unit,
/// `Never`.
Never,
/// `json.Value`.
JsonValue,
/// `List` of this.
List(Box<Term>),
/// `Set` of this.
Set(Box<Term>),
/// `Option` of this.
Option(Box<Term>),
/// `task.Task` of this.
Task(Box<Term>),
/// `Dict` of these keys and values.
Dict(Box<Term>, Box<Term>),
/// A tuple of these parts, two or more.
Tuple(Vec<Term>),
/// A function.
Function {
/// Its parameters' terms.
params: Vec<Term>,
/// Its result's term.
result: Box<Term>,
},
/// A declaration.
Named {
/// Its template's place in the description.
declaration: Int,
/// Its arguments.
args: Vec<Term>,
},
/// A type parameter.
Param {
/// Whose parameter it is.
owner: Owner,
/// Its index among its owner's.
index: Int,
},
}
}
wire! {
/// Whose type parameter a `Param` term names.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Owner {
/// The Tool's.
Tool,
/// The template's at this place.
Declaration(Int),
}
}
wire! {
/// An identity as a description writes it (`abi.md`, *Identity and
/// signatures*): the library that holds the declaration, the module
/// path in it and the declaration's name.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct Identity {
/// The library, or the tree for a module outside every library;
/// `None` for the local tree or a bundle.
pub library: Option<Library>,
/// The module path in the library or tree; empty for a root module.
pub module: String,
/// The declaration's name.
pub name: String,
}
}
wire! {
/// The library an [`Identity`] names.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct Library {
/// Its address: `std`, a repository's, or its root in the local
/// tree, `.` for the tree's root.
pub address: String,
/// The tag a remote import resolved, `v1` for std; `None` for a
/// library of the local tree.
pub version: Option<String>,
}
}
wire! {
/// One declaration a description reaches.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Template {
/// Its name, which is its identity's.
pub name: String,
/// Its identity.
pub identity: Identity,
/// Which of the declarations of one identity it is, from 1.
pub lexical_ordinal: Int,
/// Its type parameters' names.
pub generic: Vec<String>,
/// Whether it is opaque.
pub opaque: bool,
/// Its doc comment.
pub doc: Option<String>,
/// What it declares.
pub body: Body,
}
}
wire! {
/// What a template declares.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Body {
/// A record of these fields.
Record(Vec<Field>),
/// An enum of these constructors.
Enum(Vec<Constructor>),
/// A newtype over this base.
Newtype(Term),
/// A host type.
Host,
/// A type that is not data.
Nondata,
}
}
wire! {
/// A field of a record or of a named payload.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Field {
/// Its name.
pub name: String,
/// Its term.
pub ty: Term,
/// Its doc comment.
pub doc: Option<String>,
}
}
wire! {
/// A constructor of an enum.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Constructor {
/// Its name.
pub name: String,
/// Its doc comment.
pub doc: Option<String>,
/// Its payload.
pub payload: Payload,
}
}
wire! {
/// A constructor's payload.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Payload {
/// None.
Empty,
/// Parts by position, of these terms.
Positional(Vec<Term>),
/// These named fields.
Named(Vec<Field>),
}
}
wire! {
/// A Tool's description.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct TypeSpec {
/// Its type parameters' names.
pub generic: Vec<String>,
/// Each parameter's key and term.
pub params: Vec<(String, Term)>,
/// Its result's term.
pub result: Term,
/// The templates they reach, in first-reach order.
pub declarations: Vec<Template>,
}
}
wire! {
/// A generic call's description.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct CallTypes {
/// The concrete type bound to each of the Tool's type parameters.
pub bindings: Vec<(String, Term)>,
/// Each parameter's key and concrete term.
pub params: Vec<(String, Term)>,
/// The concrete result's term.
pub result: Term,
/// The templates they reach, in first-reach order.
pub declarations: Vec<Template>,
}
}
wire! {
/// A call's concrete result type, for a client that answers it from
/// outside the call.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct ResultType {
/// The result's term.
pub result: Term,
/// The templates it reaches, in first-reach order.
pub declarations: Vec<Template>,
}
}
wire! {
/// One program as the `--contract` file lists it (`abi.md`, *Binding*).
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Program {
/// The path of the file it was formed from.
pub root: String,
/// Each Tool's identity and description, whose `declarations` are
/// empty: its terms index `types`.
pub tools: Vec<(Identity, TypeSpec)>,
/// The program's type map, in first-reach order over the Tools.
pub types: Vec<Template>,
}
}
impl Identity {
/// The parts of `identity`.
pub fn of(identity: &Declared) -> Self {
let origin = &identity.origin;
let library = match (origin.tree(), origin.library()) {
(Tree::Local, None) => None,
(Tree::Std | Tree::Repository(_) | Tree::Local, _) => Some(Library {
address: origin.address(),
version: identity.version.clone(),
}),
};
Identity {
library,
module: origin.module().to_string(),
name: identity.name.clone(),
}
}
/// The identity these parts write: the module whose library and module
/// path are these parts, so that writing it again gives them back. A
/// library with a version is a repository, or std; one without is a
/// library of the local tree, `.` its root; and no library is the
/// tree outside every library.
///
/// # Errors
///
/// The module path, or a library root of the local tree, that is no
/// path.
pub fn identity(&self) -> Result<Declared, SegmentsError> {
let module = self.module.parse()?;
let origin = match &self.library {
None => ModulePath::new(Tree::Local, None, module),
Some(Library {
address,
version: Some(_),
}) if address == Tree::STD => ModulePath::new(Tree::Std, None, module),
Some(Library {
address,
version: Some(_),
}) => ModulePath::new(Tree::Repository(address.clone()), None, module),
Some(Library {
address,
version: None,
}) if address == "." => ModulePath::new(Tree::Local, Some(Segments::root()), module),
Some(Library {
address,
version: None,
}) => ModulePath::new(Tree::Local, Some(address.parse()?), module),
};
Ok(Declared {
origin,
version: self
.library
.as_ref()
.and_then(|library| library.version.clone()),
name: self.name.clone(),
})
}
}
/// A term nests as deeply as its bytes do, so it is a [`Nested`] tree, which
/// clones, compares, hashes and drops on a native stack of bounded size.
impl Nested for Term {
const LEAF: Term = Term::Int;
/// An item, a key and a value, a tuple's parts, a declared type's
/// arguments, or a function's parameters and then its result.
fn parts(&self) -> impl DoubleEndedIterator<Item = &Term> {
let (list, boxed): (&[Term], [Option<&Term>; 2]) = match self {
Term::List(item) | Term::Set(item) | Term::Option(item) | Term::Task(item) => {
(&[], [Some(item), None])
}
Term::Dict(key, value) => (&[], [Some(key), Some(value)]),
Term::Tuple(parts) | Term::Named { args: parts, .. } => (parts, [None, None]),
Term::Function { params, result } => (params, [Some(result), None]),
Term::Int
| Term::Decimal
| Term::Bool
| Term::Text
| Term::Bytes
| Term::Duration
| Term::Instant
| Term::Unit
| Term::Never
| Term::JsonValue
| Term::Param { .. } => (&[], [None, None]),
};
list.iter().chain(boxed.into_iter().flatten())
}
fn parts_mut(&mut self) -> impl Iterator<Item = &mut Term> {
let (list, boxed): (&mut [Term], [Option<&mut Box<Term>>; 2]) = match self {
Term::List(item) | Term::Set(item) | Term::Option(item) | Term::Task(item) => {
(&mut [], [Some(item), None])
}
Term::Dict(key, value) => (&mut [], [Some(key), Some(value)]),
Term::Tuple(parts) | Term::Named { args: parts, .. } => (parts, [None, None]),
Term::Function { params, result } => (params, [Some(result), None]),
Term::Int
| Term::Decimal
| Term::Bool
| Term::Text
| Term::Bytes
| Term::Duration
| Term::Instant
| Term::Unit
| Term::Never
| Term::JsonValue
| Term::Param { .. } => (&mut [], [None, None]),
};
list.iter_mut()
.chain(boxed.into_iter().flatten().map(|part| &mut **part))
}
}
impl Term {
/// A node of `self`'s kind whose parts are what `part` makes of its
/// own, each once, in [`Nested::parts`] order.
fn map_parts(&self, mut part: impl FnMut(&Term) -> Term) -> Term {
match self {
Term::List(item) => Term::List(Box::new(part(item))),
Term::Set(item) => Term::Set(Box::new(part(item))),
Term::Option(item) => Term::Option(Box::new(part(item))),
Term::Task(item) => Term::Task(Box::new(part(item))),
Term::Dict(key, value) => {
let key = Box::new(part(key));
Term::Dict(key, Box::new(part(value)))
}
Term::Tuple(parts) => Term::Tuple(parts.iter().map(part).collect()),
Term::Named { declaration, args } => Term::Named {
declaration: declaration.clone(),
args: args.iter().map(part).collect(),
},
Term::Function { params, result } => {
let params = params.iter().map(&mut part).collect();
Term::Function {
params,
result: Box::new(part(result)),
}
}
Term::Int => Term::Int,
Term::Decimal => Term::Decimal,
Term::Bool => Term::Bool,
Term::Text => Term::Text,
Term::Bytes => Term::Bytes,
Term::Duration => Term::Duration,
Term::Instant => Term::Instant,
Term::Unit => Term::Unit,
Term::Never => Term::Never,
Term::JsonValue => Term::JsonValue,
Term::Param { owner, index } => Term::Param {
owner: owner.clone(),
index: index.clone(),
},
}
}
/// Whether `self` and `other` are alike as single nodes: of one kind,
/// declaration and parameter, with as many parts.
fn same_node(&self, other: &Term) -> bool {
match (self, other) {
(
Term::Named {
declaration: a,
args: xs,
},
Term::Named {
declaration: b,
args: ys,
},
) => a == b && xs.len() == ys.len(),
(Term::Tuple(xs), Term::Tuple(ys))
| (Term::Function { params: xs, .. }, Term::Function { params: ys, .. }) => {
xs.len() == ys.len()
}
(Term::Param { owner: a, index: i }, Term::Param { owner: b, index: j }) => {
a == b && i == j
}
_ => std::mem::discriminant(self) == std::mem::discriminant(other),
}
}
}
/// [`Term::clone`].
struct Cloning;
impl Fold<Term> for Cloning {
type Made = Term;
fn open(&mut self, _: &Term) -> Option<Term> {
None
}
fn join(&mut self, term: &Term, mut part: impl FnMut(&mut Self, &Term) -> Term) -> Term {
term.map_parts(|term| part(self, term))
}
}
impl Clone for Term {
fn clone(&self) -> Term {
self.fold(&mut Cloning)
}
}
/// Two terms are equal when their nodes, read in pre-order, are alike one
/// by one.
impl PartialEq for Term {
fn eq(&self, other: &Term) -> bool {
self.same_tree(other, Term::same_node)
}
}
impl Eq for Term {}
/// Hashes each node's kind, declaration and parameter in pre-order: equal
/// terms hash alike.
impl Hash for Term {
fn hash<H: Hasher>(&self, state: &mut H) {
self.fold(&mut Hashing(state));
}
}
/// [`Term::hash`]: each node hashed as it is opened.
struct Hashing<'h, H>(&'h mut H);
impl<H: Hasher> Fold<Term> for Hashing<'_, H> {
type Made = ();
fn open(&mut self, term: &Term) -> Option<()> {
std::mem::discriminant(term).hash(self.0);
match term {
Term::Named { declaration, .. } => declaration.hash(self.0),
Term::Param { owner, index } => {
owner.hash(self.0);
index.hash(self.0);
}
Term::Int
| Term::Decimal
| Term::Bool
| Term::Text
| Term::Bytes
| Term::Duration
| Term::Instant
| Term::Unit
| Term::Never
| Term::JsonValue
| Term::List(_)
| Term::Set(_)
| Term::Option(_)
| Term::Task(_)
| Term::Dict(_, _)
| Term::Tuple(_)
| Term::Function { .. } => {}
}
term.parts().next().is_none().then_some(())
}
fn join(&mut self, term: &Term, mut part: impl FnMut(&mut Self, &Term)) {
for term in term.parts() {
part(self, term);
}
}
}
impl Drop for Term {
fn drop(&mut self) {
self.free_parts();
}
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests;