use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::sync::Arc;
use flow_types::{Constructor, EnumShape, Payload, RecordShape};
use crate::build::{Begun, Frame, Walk, build};
use crate::bytes::Reader;
use crate::description::{self as described, Identity, Owner, Program, Template, Term};
use crate::version::{DATA_VERSION, DataVersion, Versioned};
use crate::wire::{AnyWire, Opened, Rest, Shaped, ValueReader, ValueWriter, Wire, WireForm};
use crate::{
BINDING, Catalog, DecodeError, EncodeError, EncodeErrorKind, Place, REPLY, Signature, ToolDecl,
crossable, decodable, schema,
};
use flow_types::Versions;
use flow_types::{Body, Decl, DeclId, Fold, MemberDoc, Nested, Type};
use flow_value::Int;
pub(crate) fn fail(problem: impl Into<String>) -> DecodeError {
DecodeError {
path: crate::Place::default(),
problem: problem.into(),
kind: crate::DecodeErrorKind::Mismatch,
}
}
fn unwritable(problem: &str) -> EncodeError {
EncodeError::new(&crate::Place::default(), EncodeErrorKind::Invalid, problem)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Form {
Full,
Comparable,
}
impl Form {
fn identity(self, identity: Identity) -> Identity {
match self {
Form::Full => identity,
Form::Comparable => Identity {
library: identity.library.map(|library| described::Library {
version: None,
..library
}),
..identity
},
}
}
fn doc(self, doc: Option<&String>) -> Option<String> {
match self {
Form::Full => doc.cloned(),
Form::Comparable => None,
}
}
}
struct Typing<'r> {
reading: &'r Reading,
scope: Scope,
path: Place,
}
type Terms<'t> = std::vec::IntoIter<&'t Term>;
enum Join {
List,
Set,
Option,
Task,
Dict,
Tuple,
Function,
Named(DeclId),
}
impl Typing<'_> {
fn begin<'t>(&self, term: &'t Term) -> Result<Begun<Terms<'t>, Join, Type>, DecodeError> {
let open = |join, parts: Vec<&'t Term>| {
let room = parts.len();
Frame::open(join, parts.into_iter(), room, 0)
};
Ok(match term {
Term::Int => Begun::Done(Type::Int),
Term::Decimal => Begun::Done(Type::Decimal),
Term::Bool => Begun::Done(Type::Bool),
Term::Text => Begun::Done(Type::Text),
Term::Bytes => Begun::Done(Type::Bytes),
Term::Duration => Begun::Done(Type::Duration),
Term::Instant => Begun::Done(Type::Instant),
Term::Unit => Begun::Done(Type::Unit),
Term::Never => Begun::Done(Type::Never),
Term::JsonValue => Begun::Done(Type::Json),
Term::Param { owner, index } => {
Begun::Done(self.reading.param(owner, index, self.scope)?)
}
Term::List(item) => open(Join::List, vec![&**item]),
Term::Set(item) => open(Join::Set, vec![&**item]),
Term::Option(item) => open(Join::Option, vec![&**item]),
Term::Task(item) => open(Join::Task, vec![&**item]),
Term::Dict(key, value) => open(Join::Dict, vec![&**key, &**value]),
Term::Tuple(parts) => {
if parts.len() < 2 {
return Err(fail("a tuple term holds fewer than two terms"));
}
open(Join::Tuple, parts.iter().collect())
}
Term::Function { params, result } => {
open(Join::Function, params.iter().chain([&**result]).collect())
}
Term::Named { declaration, args } => {
let at = read_place(declaration, "a declaration's place")?;
open(Join::Named(DeclId(at)), args.iter().collect())
}
})
}
}
impl<'t> Walk<Terms<'t>, Join, Type> for Typing<'_> {
type Error = DecodeError;
fn path(&mut self) -> &mut Place {
&mut self.path
}
fn next(
&mut self,
frame: &mut Frame<Terms<'t>, Join, Type>,
) -> Result<Option<Begun<Terms<'t>, Join, Type>>, DecodeError> {
frame.parts.next().map(|term| self.begin(term)).transpose()
}
fn steps(_: &Frame<Terms<'t>, Join, Type>) -> usize {
0
}
fn finish(&mut self, frame: Frame<Terms<'t>, Join, Type>) -> Result<Type, DecodeError> {
let mut parts = frame.values;
let mut last = || parts.pop().expect("a term's parts, each a type");
Ok(match frame.make {
Join::List => Type::list(last()),
Join::Set => Type::set(last()),
Join::Option => Type::option(last()),
Join::Task => Type::Task(Box::new(last())),
Join::Dict => {
let value = last();
Type::dict(last(), value)
}
Join::Tuple => Type::Tuple(parts),
Join::Function => {
let result = Box::new(last());
Type::Function {
params: parts,
result,
}
}
Join::Named(id) => Type::Named(id, parts),
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Scope {
Tool(usize),
Concrete,
Template(usize, usize),
}
fn members(decl: &Decl) -> Vec<&Type> {
match &decl.body {
Body::Record(_, fields) => fields.iter().collect(),
Body::Enum(_, constructors) => constructors.iter().flatten().collect(),
Body::Newtype(base) => vec![base],
Body::Host | Body::NonData => Vec::new(),
}
}
fn push_parts<'a>(stack: &mut Vec<&'a Type>, ty: &'a Type) {
match ty {
Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
stack.push(item);
}
Type::Dict(key, value) => {
stack.push(value);
stack.push(key);
}
Type::Tuple(parts) => stack.extend(parts.iter().rev()),
Type::Function { params, result } => {
stack.push(result);
stack.extend(params.iter().rev());
}
Type::Named(_, args) => stack.extend(args.iter().rev()),
Type::Int
| Type::Decimal
| Type::Bool
| Type::Text
| Type::Bytes
| Type::Duration
| Type::Instant
| Type::Unit
| Type::Never
| Type::Json
| Type::Param(_)
| Type::NotData => {}
}
}
fn first_reach<'a>(
catalog: &'a Catalog,
roots: impl IntoIterator<Item = &'a Type>,
) -> Result<Vec<DeclId>, EncodeError> {
let count = catalog.decls().len();
let mut stack: Vec<&Type> = roots.into_iter().collect();
stack.reverse();
let mut reached = HashSet::new();
let mut order = Vec::new();
while let Some(ty) = stack.pop() {
push_parts(&mut stack, ty);
if let Type::Named(id, args) = ty {
if crate::bytes::index(id.0) >= count {
return Err(unwritable("a type names a declaration the catalog lacks"));
}
let decl = catalog.decl(*id);
if args.len() != decl.params.len() {
return Err(unwritable("a declaration's argument count differs"));
}
if reached.insert(*id) {
order.push(*id);
stack.extend(members(decl).into_iter().rev());
}
}
}
Ok(order)
}
struct Writer<'c> {
catalog: &'c Catalog,
form: Form,
index: HashMap<DeclId, usize>,
}
fn place(at: usize) -> Int {
Int::from(i64::try_from(at).expect("a place fits 63 bits"))
}
impl<'c> Writer<'c> {
fn new(catalog: &'c Catalog, form: Form, order: &[DeclId]) -> Self {
Writer {
catalog,
form,
index: order.iter().enumerate().map(|(at, id)| (*id, at)).collect(),
}
}
fn entries(
&self,
entries: &[(String, Type)],
scope: Scope,
) -> Result<Vec<(String, Term)>, EncodeError> {
entries
.iter()
.map(|(name, ty)| Ok((name.clone(), self.term(ty, scope)?)))
.collect()
}
fn terms(&self, parts: &[Type], scope: Scope) -> Result<Vec<Term>, EncodeError> {
parts.iter().map(|part| self.term(part, scope)).collect()
}
fn term(&self, ty: &Type, scope: Scope) -> Result<Term, EncodeError> {
ty.fold(&mut Terming {
writer: self,
scope,
})
}
fn templates(&self, order: &[DeclId]) -> Result<Vec<Template>, EncodeError> {
order
.iter()
.enumerate()
.map(|(at, id)| self.template(at, *id))
.collect()
}
fn template(&self, at: usize, id: DeclId) -> Result<Template, EncodeError> {
let decl = self.catalog.decl(id);
let scope = Scope::Template(at, decl.params.len());
let member = |at: usize| decl.members.get(at);
let field = |name: &str, ty: &Type, doc: Option<&String>| {
Ok(described::Field {
name: name.to_owned(),
ty: self.term(ty, scope)?,
doc: self.form.doc(doc),
})
};
let body = match &decl.body {
Body::Record(shape, fields) => described::Body::Record(
shape
.fields()
.zip(fields)
.enumerate()
.map(|(at, (name, ty))| {
field(name, ty, member(at).and_then(|m| m.doc.as_ref()))
})
.collect::<Result<_, EncodeError>>()?,
),
Body::Enum(shape, constructors) => described::Body::Enum(
constructors
.iter()
.enumerate()
.map(|(at, parts)| {
let ctor = shape.constructor(at).expect(
"a catalog's enum has one payload per constructor of its shape",
);
let payload = match ctor.payload() {
Payload::None => described::Payload::Empty,
Payload::Positional(_) => {
described::Payload::Positional(self.terms(parts, scope)?)
}
Payload::Named(names) => described::Payload::Named(
names
.iter()
.zip(parts)
.enumerate()
.map(|(at_field, (name, ty))| {
let doc = member(at)
.and_then(|m| m.fields.get(at_field))
.and_then(Option::as_ref);
field(name, ty, doc)
})
.collect::<Result<_, EncodeError>>()?,
),
};
Ok(described::Constructor {
name: ctor.name().to_owned(),
doc: self.form.doc(member(at).and_then(|m| m.doc.as_ref())),
payload,
})
})
.collect::<Result<_, EncodeError>>()?,
),
Body::Newtype(base) => described::Body::Newtype(self.term(base, scope)?),
Body::Host => described::Body::Host,
Body::NonData => described::Body::Nondata,
};
Ok(Template {
name: decl.identity.name.clone(),
identity: self.form.identity(Identity::of(&decl.identity)),
lexical_ordinal: Int::from(i64::from(decl.lexical_ordinal)),
generic: decl.params.clone(),
opaque: decl.opaque,
doc: self.form.doc(decl.doc.as_ref()),
body,
})
}
}
struct Terming<'w, 'c> {
writer: &'w Writer<'c>,
scope: Scope,
}
impl Fold<Type> for Terming<'_, '_> {
type Made = Result<Term, EncodeError>;
fn open(&mut self, _: &Type) -> Option<Self::Made> {
None
}
fn join(
&mut self,
ty: &Type,
mut part: impl FnMut(&mut Self, &Type) -> Self::Made,
) -> Self::Made {
let (writer, scope) = (self.writer, self.scope);
let mut term = |ty: &Type| part(self, ty);
let mut terms = |parts: &[Type]| parts.iter().map(&mut term).collect::<Result<Vec<_>, _>>();
Ok(match ty {
Type::Int => Term::Int,
Type::Decimal => Term::Decimal,
Type::Bool => Term::Bool,
Type::Text => Term::Text,
Type::Bytes => Term::Bytes,
Type::Duration => Term::Duration,
Type::Instant => Term::Instant,
Type::Unit => Term::Unit,
Type::Never => Term::Never,
Type::Json => Term::JsonValue,
Type::List(item) => Term::List(Box::new(term(item)?)),
Type::Set(item) => Term::Set(Box::new(term(item)?)),
Type::Option(item) => Term::Option(Box::new(term(item)?)),
Type::Task(item) => Term::Task(Box::new(term(item)?)),
Type::Dict(key, value) => {
let key = Box::new(term(key)?);
Term::Dict(key, Box::new(term(value)?))
}
Type::Tuple(parts) if parts.len() >= 2 => Term::Tuple(terms(parts)?),
Type::Function { params, result } => {
let params = terms(params)?;
Term::Function {
params,
result: Box::new(term(result)?),
}
}
Type::Named(id, args) => Term::Named {
declaration: place(
*writer
.index
.get(id)
.expect("the walk indexes every declaration a type it writes names"),
),
args: terms(args)?,
},
Type::Param(index) => {
let at = crate::bytes::index(*index);
let owner = match scope {
Scope::Tool(arity) if at < arity => Owner::Tool,
Scope::Template(owner, arity) if at < arity => Owner::Declaration(place(owner)),
Scope::Tool(_) | Scope::Template(..) => {
return Err(unwritable("a type parameter's index exceeds its owner's"));
}
Scope::Concrete => return Err(unwritable("a concrete type names a parameter")),
};
Term::Param {
owner,
index: Int::from(i64::from(*index)),
}
}
Type::Tuple(_) | Type::NotData => {
return Err(unwritable("a type that has no description"));
}
})
}
}
fn write_spec(
catalog: &Catalog,
signature: &Signature,
form: Form,
) -> Result<Vec<u8>, EncodeError> {
let order = first_reach(catalog, signature_types(signature))?;
let writer = Writer::new(catalog, form, &order);
let scope = Scope::Tool(signature.generic.len());
Ok(described::TypeSpec {
generic: signature.generic.clone(),
params: writer.entries(&signature.params, scope)?,
result: writer.term(&signature.result, scope)?,
declarations: writer.templates(&order)?,
}
.bytes())
}
fn signature_types(signature: &Signature) -> impl Iterator<Item = &Type> + Clone {
signature
.params
.iter()
.map(|(_, ty)| ty)
.chain([&signature.result])
}
struct Read {
generic: Vec<String>,
bindings: Vec<(String, Type)>,
params: Vec<(String, Type)>,
result: Type,
decls: Vec<Decl>,
}
impl Read {
fn signature(&self) -> Signature {
Signature {
generic: self.generic.clone(),
params: self.params.clone(),
result: self.result.clone(),
}
}
fn spec(spec: described::TypeSpec) -> Result<Read, DecodeError> {
unique(spec.generic.iter().map(String::as_str))?;
let scope = Scope::Tool(spec.generic.len());
let mut reading = Reading::default();
let params = reading.entries(spec.params, scope)?;
let result = reading.ty(&spec.result, scope)?;
Ok(Read {
generic: spec.generic,
bindings: Vec::new(),
params,
result,
decls: reading.decls(spec.declarations)?,
})
}
fn listed(spec: described::TypeSpec) -> Result<Read, DecodeError> {
let read = Read::spec(spec)?;
if read.decls.is_empty() {
Ok(read)
} else {
Err(fail(
"a Tool in the contract file holds templates of its own",
))
}
}
fn call(types: described::CallTypes) -> Result<Read, DecodeError> {
let mut reading = Reading::default();
let bindings = reading.entries(types.bindings, Scope::Concrete)?;
let params = reading.entries(types.params, Scope::Concrete)?;
let result = reading.ty(&types.result, Scope::Concrete)?;
Ok(Read {
generic: Vec::new(),
bindings,
params,
result,
decls: reading.decls(types.declarations)?,
})
}
}
fn unique<'a>(names: impl Iterator<Item = &'a str>) -> Result<(), DecodeError> {
let mut seen = HashSet::new();
let mut names = names;
match names.find(|name| !seen.insert(*name)) {
Some(name) => Err(fail(format!(
"the name {name:?} appears twice in one scope"
))),
None => Ok(()),
}
}
fn read_place(value: &Int, what: &str) -> Result<u32, DecodeError> {
u32::try_from(value.as_bigint())
.map_err(|_| fail(format!("{what} is {value}, which is no place")))
}
type Fields = (Vec<String>, Vec<Type>, Vec<Option<String>>);
#[derive(Default)]
struct Reading {
templates: Option<usize>,
}
impl Reading {
fn entries(
&self,
entries: Vec<(String, Term)>,
scope: Scope,
) -> Result<Vec<(String, Type)>, DecodeError> {
let entries = entries
.into_iter()
.map(|(name, term)| Ok((name, self.ty(&term, scope)?)))
.collect::<Result<Vec<_>, DecodeError>>()?;
unique(entries.iter().map(|(name, _)| name.as_str()))?;
Ok(entries)
}
fn types(&self, terms: &[Term], scope: Scope) -> Result<Vec<Type>, DecodeError> {
terms.iter().map(|term| self.ty(term, scope)).collect()
}
fn ty(&self, term: &Term, scope: Scope) -> Result<Type, DecodeError> {
let mut typing = Typing {
reading: self,
scope,
path: Place::default(),
};
let root = typing.begin(term)?;
build(&mut typing, root)
}
fn param(&self, owner: &Owner, index: &Int, scope: Scope) -> Result<Type, DecodeError> {
let owner = match owner {
Owner::Tool => None,
Owner::Declaration(owner) => Some(crate::bytes::index(read_place(
owner,
"a declaration owner",
)?)),
};
let index = read_place(index, "a type parameter's index")?;
let arity = match (scope, owner) {
(Scope::Tool(arity), None) => arity,
(Scope::Template(own, arity), Some(owner)) if owner == own => arity,
(_, Some(owner)) if self.templates.is_some_and(|count| owner >= count) => {
return Err(fail("a type parameter's owner is an unresolved reference"));
}
(Scope::Concrete, _) => return Err(fail("a concrete root names a type parameter")),
(Scope::Tool(_) | Scope::Template(..), _) => {
return Err(fail("a type parameter has the wrong owner"));
}
};
if crate::bytes::index(index) >= arity {
return Err(fail("a type parameter's index exceeds its owner's"));
}
Ok(Type::Param(index))
}
fn fields(&self, fields: Vec<described::Field>, scope: Scope) -> Result<Fields, DecodeError> {
let (mut names, mut types, mut docs) = (Vec::new(), Vec::new(), Vec::new());
for field in fields {
types.push(self.ty(&field.ty, scope)?);
names.push(field.name);
docs.push(field.doc);
}
unique(names.iter().map(String::as_str))?;
Ok((names, types, docs))
}
fn decls(&mut self, templates: Vec<Template>) -> Result<Vec<Decl>, DecodeError> {
self.templates = Some(templates.len());
templates
.into_iter()
.enumerate()
.map(|(at, template)| self.decl(at, template))
.collect()
}
fn decl(&self, at: usize, template: Template) -> Result<Decl, DecodeError> {
let Template {
name,
identity,
lexical_ordinal,
generic: params,
opaque,
doc,
body,
} = template;
if identity.name != name {
return Err(fail("a template's name differs from its identity's"));
}
let lexical_ordinal = read_place(&lexical_ordinal, "a lexical ordinal")?;
if lexical_ordinal == 0 {
return Err(fail("a lexical ordinal must be positive"));
}
unique(params.iter().map(String::as_str))?;
let scope = Scope::Template(at, params.len());
let mut members = Vec::new();
let body = match body {
described::Body::Record(fields) => {
let (names, types, docs) = self.fields(fields, scope)?;
members = docs
.into_iter()
.map(|doc| MemberDoc {
doc,
fields: Vec::new(),
})
.collect();
Body::Record(
RecordShape::new(&name, names.iter().map(String::as_str)),
types,
)
}
described::Body::Enum(ctors) => {
let mut constructors = Vec::new();
let mut payloads = Vec::new();
for ctor in ctors {
let (payload, parts, fields) = match ctor.payload {
described::Payload::Empty => (Payload::None, Vec::new(), Vec::new()),
described::Payload::Positional(terms) => {
let parts = self.types(&terms, scope)?;
(Payload::Positional(parts.len()), parts, Vec::new())
}
described::Payload::Named(fields) => {
let (names, types, docs) = self.fields(fields, scope)?;
(
Payload::Named(names.into_iter().map(Arc::from).collect()),
types,
docs,
)
}
};
constructors.push(Constructor::new(&ctor.name, payload));
payloads.push(parts);
members.push(MemberDoc {
doc: ctor.doc,
fields,
});
}
unique(constructors.iter().map(Constructor::name))?;
Body::Enum(EnumShape::new(&name, constructors), payloads)
}
described::Body::Newtype(base) => Body::Newtype(self.ty(&base, scope)?),
described::Body::Host => Body::Host,
described::Body::Nondata => Body::NonData,
};
Ok(Decl {
identity: identity
.identity()
.map_err(|error| fail(error.to_string()))?,
lexical_ordinal,
params,
opaque,
doc,
members,
body,
})
}
}
fn admit<'a>(
decls: Vec<Decl>,
roots: impl Iterator<Item = &'a Type> + Clone,
) -> Result<Catalog, DecodeError> {
for ty in roots.clone() {
resolves(ty, &decls)?;
}
for ty in decls.iter().flat_map(members) {
resolves(ty, &decls)?;
}
in_first_reach_order(&decls, roots)?;
let mut identities = HashSet::new();
for decl in &decls {
if !identities.insert((decl.identity.clone(), decl.lexical_ordinal)) {
return Err(fail("two templates have one identity and lexical ordinal"));
}
}
newtypes_end(&decls)?;
Catalog::std(decls)
}
fn resolves(ty: &Type, decls: &[Decl]) -> Result<(), DecodeError> {
let mut stack = vec![ty];
while let Some(ty) = stack.pop() {
if let Type::Named(id, args) = ty {
let decl = decls
.get(crate::bytes::index(id.0))
.ok_or_else(|| fail("a Named term is an unresolved reference"))?;
if args.len() != decl.params.len() {
return Err(fail(
"a Named term's argument count differs from its template's",
));
}
}
push_parts(&mut stack, ty);
}
Ok(())
}
fn in_first_reach_order<'a, 'r: 'a>(
decls: &'a [Decl],
roots: impl Iterator<Item = &'r Type>,
) -> Result<(), DecodeError> {
let mut stack: Vec<&'a Type> = roots.map(|ty: &'r Type| -> &'a Type { ty }).collect();
stack.reverse();
let mut next = 0usize;
while let Some(ty) = stack.pop() {
push_parts(&mut stack, ty);
if let Type::Named(id, _) = ty {
let at = crate::bytes::index(id.0);
if at == next {
next += 1;
stack.extend(members(&decls[at]).into_iter().rev());
} else if at > next {
return Err(fail(format!(
"the templates are not in first-reach order: template {at} is reached before template {next}"
)));
}
}
}
if next == decls.len() {
Ok(())
} else {
Err(fail(format!(
"template {next} is one nothing in the description reaches"
)))
}
}
fn references<'a>(ty: &'a Type, visit: &mut impl FnMut(DeclId, &'a [Type])) {
let mut stack = vec![ty];
while let Some(ty) = stack.pop() {
if let Type::Named(id, args) = ty {
visit(*id, args);
}
push_parts(&mut stack, ty);
}
}
fn newtypes_end(decls: &[Decl]) -> Result<(), DecodeError> {
for start in 0..decls.len() {
let mut at = start;
for _ in 0..decls.len() {
let Body::Newtype(Type::Named(next, _)) = &decls[at].body else {
break;
};
at = crate::bytes::index(next.0);
if at == start {
return Err(fail("a newtype template is its own base"));
}
}
}
Ok(())
}
pub(crate) fn regular(decls: &[Decl]) -> Result<(), DecodeError> {
let mut edges = vec![Vec::new(); decls.len()];
for (at, decl) in decls.iter().enumerate() {
for ty in members(decl) {
references(ty, &mut |id, args| {
edges[at].push((crate::bytes::index(id.0), args.to_vec()));
});
}
}
let component = components(&edges);
let mut done = vec![false; decls.len()];
for root in 0..decls.len() {
if std::mem::replace(&mut done[component[root]], true) {
continue;
}
let mut assignments: HashMap<usize, Vec<u32>> = HashMap::new();
assignments.insert(
root,
(0..u32::try_from(decls[root].params.len())
.expect("a declaration read within its bytes has fewer than 2^32 parameters"))
.collect(),
);
let mut pending = vec![root];
while let Some(source) = pending.pop() {
for (target, args) in &edges[source] {
if component[*target] != component[root] {
continue;
}
let arity = decls[source].params.len();
if decls[*target].params.len() != arity || args.len() != arity {
return Err(fail("recursive declaration arities differ"));
}
let permutation = args
.iter()
.map(|arg| match arg {
Type::Param(index) => Ok(*index),
_ => Err(fail("recursive arguments must be bare owner parameters")),
})
.collect::<Result<Vec<_>, _>>()?;
if permutation.iter().copied().collect::<HashSet<_>>().len() != arity {
return Err(fail("recursive argument substitution is not bijective"));
}
let next: Vec<_> = permutation
.iter()
.map(|index| assignments[&source][crate::bytes::index(*index)])
.collect();
if let Some(previous) = assignments.get(target) {
if *previous != next {
return Err(fail("recursive substitutions do not compose to identity"));
}
} else {
assignments.insert(*target, next);
pending.push(*target);
}
}
}
}
Ok(())
}
fn components(edges: &[Vec<(usize, Vec<Type>)>]) -> Vec<usize> {
const UNSEEN: usize = usize::MAX;
let mut order = vec![UNSEEN; edges.len()];
let mut low = vec![0; edges.len()];
let mut on_stack = vec![false; edges.len()];
let mut component = vec![UNSEEN; edges.len()];
let mut stack = Vec::new();
let mut visited = 0;
let mut components = 0;
for start in 0..edges.len() {
if order[start] != UNSEEN {
continue;
}
let mut walk = vec![(start, 0)];
order[start] = visited;
low[start] = visited;
visited += 1;
stack.push(start);
on_stack[start] = true;
while let Some(&(node, edge)) = walk.last() {
if let Some((target, _)) = edges[node].get(edge) {
let target = *target;
let top = walk.len() - 1;
walk[top].1 += 1;
if order[target] == UNSEEN {
order[target] = visited;
low[target] = visited;
visited += 1;
stack.push(target);
on_stack[target] = true;
walk.push((target, 0));
} else if on_stack[target] {
low[node] = low[node].min(order[target]);
}
continue;
}
walk.pop();
if let Some(&(parent, _)) = walk.last() {
low[parent] = low[parent].min(low[node]);
}
if low[node] == order[node] {
while let Some(member) = stack.pop() {
on_stack[member] = false;
component[member] = components;
if member == node {
break;
}
}
components += 1;
}
}
}
component
}
#[derive(Clone, Debug)]
pub struct TypeSpec {
catalog: Catalog,
signature: Signature,
bytes: Arc<[u8]>,
}
impl PartialEq for TypeSpec {
fn eq(&self, other: &Self) -> bool {
self.bytes == other.bytes
}
}
impl Eq for TypeSpec {}
impl TypeSpec {
pub fn from_catalog(catalog: &Catalog, signature: &Signature) -> Result<Self, EncodeError> {
let bytes = write_spec(catalog, signature, Form::Full)?;
Ok(Self::read(&bytes)?)
}
pub fn read(bytes: &[u8]) -> Result<Self, DecodeError> {
let mut reader = Reader::new(bytes);
let spec = Self::read_from(&mut reader)?;
if reader.is_empty() {
Ok(spec)
} else {
Err(fail(format!(
"a type description has {} bytes left over",
reader.remaining()
)))
}
}
pub fn read_from(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
let start = reader.position();
let spec = described::TypeSpec::read(reader)?;
let bytes = reader.since(start).into();
let read = Read::spec(spec)?;
let signature = read.signature();
let catalog = admit(read.decls, signature_types(&signature))?;
Ok(TypeSpec {
catalog,
signature,
bytes,
})
}
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
pub fn catalog(&self) -> &Catalog {
&self.catalog
}
pub fn signature(&self) -> &Signature {
&self.signature
}
pub fn comparable(&self) -> Vec<u8> {
write_spec(&self.catalog, &self.signature, Form::Comparable)
.expect("a description read is written again")
}
pub fn outline(&self) -> String {
let name = |ty: &Type| self.catalog.written(ty, Versions::Hidden);
let mut out = String::new();
if !self.signature.generic.is_empty() {
write!(out, "<{}>", self.signature.generic.join(", ")).expect("a string");
}
let params: Vec<String> = self
.signature
.params
.iter()
.map(|(key, ty)| format!("{key}: {}", name(ty)))
.collect();
write!(
out,
"({}) -> {}",
params.join(", "),
name(&self.signature.result)
)
.expect("a string");
for (id, decl) in self.catalog.decls() {
let shown = name(&Type::Named(
id,
(0..u32::try_from(decl.params.len()).expect("an arity"))
.map(Type::Param)
.collect(),
));
let opaque = if decl.opaque { "opaque " } else { "" };
let body = match &decl.body {
Body::Record(shape, fields) => {
let fields: Vec<String> = shape
.fields()
.zip(fields)
.map(|(field, ty)| format!("{field}: {}", name(ty)))
.collect();
format!("{{ {} }}", fields.join(", "))
}
Body::Enum(shape, constructors) => {
let constructors: Vec<String> = constructors
.iter()
.enumerate()
.map(|(at, parts)| {
let ctor = shape.constructor(at).expect("a validated shape");
let parts: Vec<String> = match ctor.payload() {
Payload::None => return ctor.name().to_owned(),
Payload::Positional(_) => parts.iter().map(name).collect(),
Payload::Named(names) => names
.iter()
.zip(parts)
.map(|(field, ty)| format!("{field}: {}", name(ty)))
.collect(),
};
format!("{}({})", ctor.name(), parts.join(", "))
})
.collect();
format!("{{ {} }}", constructors.join(" | "))
}
Body::Newtype(base) => format!("({})", name(base)),
Body::Host => "host".to_owned(),
Body::NonData => "nondata".to_owned(),
};
write!(out, "; {opaque}type {shown} {body}").expect("a string");
}
out
}
pub fn validate_call(
&self,
generic: Option<&described::CallTypes>,
) -> Result<Option<ValidatedTypes>, DecodeError> {
let Some(generic) = generic else {
return if self.signature.generic.is_empty() {
Ok(None)
} else {
Err(fail("a generic Tool's call carries no types"))
};
};
if self.signature.generic.is_empty() {
return Err(fail("a call to a Tool that is not generic carries types"));
}
let read = Read::call(generic.clone())?;
if read
.bindings
.iter()
.map(|(name, _)| name)
.ne(self.signature.generic.iter())
{
return Err(fail(
"the call's bindings differ from the Tool's type parameters in name, count or order",
));
}
let bindings = read.bindings.clone();
let signature = read.signature();
let catalog = admit(read.decls, call_roots(&bindings, &signature))?;
let arguments: Vec<_> = bindings.iter().map(|(_, ty)| ty.clone()).collect();
Equality::new(&self.catalog, &catalog).signature(
&self.signature,
&signature,
&arguments,
)?;
for (_, ty) in &bindings {
decodable(&catalog, ty, BINDING)?;
}
for (_, ty) in &signature.params {
crossable(&catalog, ty)?;
}
crossable(&catalog, &signature.result)?;
decodable(&catalog, &signature.result, REPLY)?;
let schema = bound_schema(&catalog, &bindings)?;
Ok(Some(ValidatedTypes {
catalog,
bindings,
signature,
schema,
types: generic.bytes().into(),
}))
}
}
fn call_roots<'a>(
bindings: &'a [(String, Type)],
signature: &'a Signature,
) -> impl Iterator<Item = &'a Type> + Clone {
bindings
.iter()
.map(|(_, ty)| ty)
.chain(signature_types(signature))
}
pub fn comparable(identity: &Identity, spec: &TypeSpec) -> Vec<u8> {
let mut out = Form::Comparable.identity(identity.clone()).bytes();
out.extend(spec.comparable());
out
}
#[derive(Clone, Debug)]
pub struct ValidatedTypes {
catalog: Catalog,
bindings: Vec<(String, Type)>,
signature: Signature,
schema: Option<String>,
types: Arc<[u8]>,
}
impl ValidatedTypes {
pub fn catalog(&self) -> &Catalog {
&self.catalog
}
pub fn binding(&self, name: &str) -> Option<&Type> {
self.bindings
.iter()
.find(|(key, _)| key == name)
.map(|(_, ty)| ty)
}
pub fn bindings(&self) -> &[(String, Type)] {
&self.bindings
}
pub fn argument(&self, name: &str) -> Option<&Type> {
self.signature
.params
.iter()
.find(|(key, _)| key == name)
.map(|(_, ty)| ty)
}
pub fn params(&self) -> &[(String, Type)] {
&self.signature.params
}
pub fn result(&self) -> &Type {
&self.signature.result
}
pub fn schema(&self) -> Option<&str> {
self.schema.as_deref()
}
pub fn types(&self) -> &[u8] {
&self.types
}
}
#[derive(Clone, Debug)]
pub struct ResultType {
catalog: Catalog,
result: Type,
bytes: Arc<[u8]>,
}
impl PartialEq for ResultType {
fn eq(&self, other: &Self) -> bool {
self.bytes == other.bytes
}
}
impl Eq for ResultType {}
impl ResultType {
pub fn from_catalog(catalog: &Catalog, result: &Type) -> Result<Self, EncodeError> {
let order = first_reach(catalog, [result])?;
let writer = Writer::new(catalog, Form::Full, &order);
let bytes = described::ResultType {
result: writer.term(result, Scope::Concrete)?,
declarations: writer.templates(&order)?,
}
.bytes();
Self::read(&bytes).map_err(|error| unwritable(&error.problem))
}
pub fn read(bytes: &[u8]) -> Result<Self, DecodeError> {
let mut reader = Reader::new(bytes);
let result = Self::read_from(&mut reader)?;
if reader.is_empty() {
Ok(result)
} else {
Err(fail(format!(
"a result type has {} bytes left over",
reader.remaining()
)))
}
}
pub fn read_from(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
let start = reader.position();
let described = described::ResultType::read(reader)?;
let bytes = reader.since(start).into();
let mut reading = Reading::default();
let result = reading.ty(&described.result, Scope::Concrete)?;
let decls = reading.decls(described.declarations)?;
let catalog = admit(decls, std::iter::once(&result))?;
Ok(ResultType {
catalog,
result,
bytes,
})
}
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
pub fn catalog(&self) -> &Catalog {
&self.catalog
}
pub fn result(&self) -> &Type {
&self.result
}
}
fn bound_schema(
catalog: &Catalog,
bindings: &[(String, Type)],
) -> Result<Option<String>, DecodeError> {
match bindings {
[(_, bound)] => schema(catalog, bound)
.map(|schema| Some(schema.canonical()))
.map_err(|error| fail(error.problem)),
_ => Ok(None),
}
}
pub fn call_views(
catalog: &Catalog,
signature: &Signature,
arguments: &[Type],
) -> Result<described::CallTypes, EncodeError> {
if arguments.len() != signature.generic.len() {
return Err(unwritable("a generic call's argument count differs"));
}
let bindings: Vec<_> = signature
.generic
.iter()
.cloned()
.zip(arguments.iter().cloned())
.collect();
let concrete = Signature {
generic: Vec::new(),
params: signature
.params
.iter()
.map(|(name, ty)| (name.clone(), ty.subst(arguments)))
.collect(),
result: signature.result.subst(arguments),
};
let order = first_reach(catalog, call_roots(&bindings, &concrete))?;
let writer = Writer::new(catalog, Form::Full, &order);
Ok(described::CallTypes {
bindings: writer.entries(&bindings, Scope::Concrete)?,
params: writer.entries(&concrete.params, Scope::Concrete)?,
result: writer.term(&concrete.result, Scope::Concrete)?,
declarations: writer.templates(&order)?,
})
}
pub fn call_bindings(
types: &described::CallTypes,
) -> Result<(Catalog, Vec<(String, Type)>), DecodeError> {
let read = Read::call(types.clone())?;
let bindings = read.bindings.clone();
let signature = read.signature();
let catalog = admit(read.decls, call_roots(&bindings, &signature))?;
Ok((catalog, bindings))
}
#[derive(Clone, Debug)]
pub struct ListedProgram {
pub root: String,
pub tools: Vec<(Identity, TypeSpec)>,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ListingError {
Version(DataVersion),
Invalid(String),
}
impl std::fmt::Display for ListingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ListingError::Version(version) => write!(
f,
"the contract file is written in data version {version}, not {DATA_VERSION}"
),
ListingError::Invalid(problem) => write!(f, "the contract file is invalid: {problem}"),
}
}
}
impl std::error::Error for ListingError {}
pub fn write_listing(
root: &str,
catalog: &Catalog,
tools: &[&ToolDecl],
) -> Result<Vec<u8>, EncodeError> {
let order = first_reach(
catalog,
tools
.iter()
.flat_map(|tool| signature_types(&tool.signature)),
)?;
let writer = Writer::new(catalog, Form::Full, &order);
let tools = tools
.iter()
.map(|tool| {
let signature = &tool.signature;
let scope = Scope::Tool(signature.generic.len());
let spec = described::TypeSpec {
generic: signature.generic.clone(),
params: writer.entries(&signature.params, scope)?,
result: writer.term(&signature.result, scope)?,
declarations: Vec::new(),
};
Ok((Identity::of(&tool.identity), spec))
})
.collect::<Result<_, EncodeError>>()?;
let program = Program {
root: root.to_owned(),
tools,
types: writer.templates(&order)?,
};
Ok(Versioned {
version: DATA_VERSION,
rest: Rest(vec![program].bytes()),
}
.bytes())
}
pub fn read_listing(bytes: &[u8]) -> Result<Vec<ListedProgram>, ListingError> {
let invalid = |error: DecodeError| ListingError::Invalid(error.problem);
let Versioned { version, rest } = Versioned::decode(bytes).map_err(invalid)?;
if !DATA_VERSION.reads(&version) {
return Err(ListingError::Version(version));
}
let programs = Vec::<Program>::decode(&rest.0).map_err(invalid)?;
programs
.into_iter()
.map(|program| {
let listed = program
.tools
.into_iter()
.map(|(identity, spec)| Ok((identity, Read::listed(spec)?.signature())))
.collect::<Result<Vec<_>, DecodeError>>()?;
let decls = Reading::default().decls(program.types)?;
let catalog = admit(
decls,
listed
.iter()
.flat_map(|(_, signature)| signature_types(signature)),
)?;
let tools = listed
.into_iter()
.map(|(identity, signature)| {
let spec = TypeSpec::from_catalog(&catalog, &signature)
.expect("a Tool whose types the catalog admitted has a description");
(identity, spec)
})
.collect();
Ok(ListedProgram {
root: program.root,
tools,
})
})
.collect::<Result<_, DecodeError>>()
.map_err(invalid)
}
struct Equality<'a> {
served: &'a Catalog,
caller: &'a Catalog,
compared: HashSet<(DeclId, DeclId)>,
mapping: HashMap<DeclId, DeclId>,
}
impl<'a> Equality<'a> {
fn new(served: &'a Catalog, caller: &'a Catalog) -> Self {
Self {
served,
caller,
compared: HashSet::new(),
mapping: HashMap::new(),
}
}
fn signature(
&mut self,
served: &Signature,
caller: &Signature,
bindings: &[Type],
) -> Result<(), DecodeError> {
if served
.params
.iter()
.map(|(name, _)| name)
.ne(caller.params.iter().map(|(name, _)| name))
{
return Err(fail("concrete parameters differ in name, count or order"));
}
for ((_, expected), (_, actual)) in served.params.iter().zip(&caller.params) {
self.term(expected, actual, Some(bindings))?;
}
self.term(&served.result, &caller.result, Some(bindings))
}
fn parts(
&mut self,
expected: &[Type],
actual: &[Type],
bindings: Option<&[Type]>,
) -> Result<(), DecodeError> {
if expected.len() != actual.len() {
return Err(fail("concrete type arity differs"));
}
for (expected, actual) in expected.iter().zip(actual) {
self.term(expected, actual, bindings)?;
}
Ok(())
}
fn term(
&mut self,
expected: &Type,
actual: &Type,
bindings: Option<&[Type]>,
) -> Result<(), DecodeError> {
if let (Type::Param(index), Some(bindings)) = (expected, bindings) {
return if bindings.get(crate::bytes::index(*index)) == Some(actual) {
Ok(())
} else {
Err(fail("concrete root differs from its generic binding"))
};
}
match (expected, actual) {
(Type::Named(left, left_args), Type::Named(right, right_args)) => {
self.parts(left_args, right_args, bindings)?;
self.declaration(*left, *right)
}
(Type::List(left), Type::List(right))
| (Type::Set(left), Type::Set(right))
| (Type::Option(left), Type::Option(right))
| (Type::Task(left), Type::Task(right)) => self.term(left, right, bindings),
(Type::Dict(lk, lv), Type::Dict(rk, rv)) => {
self.term(lk, rk, bindings)?;
self.term(lv, rv, bindings)
}
(Type::Tuple(left), Type::Tuple(right)) => self.parts(left, right, bindings),
(
Type::Function {
params: lp,
result: lr,
},
Type::Function {
params: rp,
result: rr,
},
) => {
self.parts(lp, rp, bindings)?;
self.term(lr, rr, bindings)
}
_ if expected == actual => Ok(()),
_ => Err(fail("concrete type differs from served template")),
}
}
fn declaration(&mut self, left: DeclId, right: DeclId) -> Result<(), DecodeError> {
if self
.mapping
.insert(left, right)
.is_some_and(|previous| previous != right)
{
return Err(fail(
"known declaration maps to conflicting caller templates",
));
}
if !self.compared.insert((left, right)) {
return Ok(());
}
let left = self.served.decl(left);
let right = self.caller.decl(right);
if left.identity != right.identity
|| left.lexical_ordinal != right.lexical_ordinal
|| left.params.len() != right.params.len()
|| left.opaque != right.opaque
{
return Err(fail(
"known declaration template identity or generic facts differ",
));
}
match (&left.body, &right.body) {
(Body::Record(ls, lt), Body::Record(rs, rt)) if ls.fields().eq(rs.fields()) => {
self.parts(lt, rt, None)
}
(Body::Enum(ls, lt), Body::Enum(rs, rt)) if lt.len() == rt.len() => {
for (at, (left, right)) in lt.iter().zip(rt).enumerate() {
let lc = ls.constructor(at).expect("validated constructor");
let rc = rs.constructor(at).expect("validated constructor");
if lc.name() != rc.name() || lc.payload() != rc.payload() {
return Err(fail("known constructor order or payload differs"));
}
self.parts(left, right, None)?;
}
Ok(())
}
(Body::Newtype(left), Body::Newtype(right)) => self.term(left, right, None),
(Body::Host, Body::Host) | (Body::NonData, Body::NonData) => Ok(()),
_ => Err(fail("known declaration members or kind differ")),
}
}
}
impl Shaped for TypeSpec {
const FORM: WireForm = <described::TypeSpec as Shaped>::FORM;
fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
described::TypeSpec::decode(self.bytes())
.map_err(|_| out.refuse(ty))?
.write_at(out, ty)
}
fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
let described = described::TypeSpec::read_at(input, ty)?;
Self::decode(&described.bytes()).map_err(|_| input.mismatch(ty))
}
}
impl Wire for TypeSpec {
fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
out.extend_from_slice(self.bytes());
}
fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
TypeSpec::read_from(reader).map(Opened::built)
}
}
impl Shaped for ResultType {
const FORM: WireForm = <described::ResultType as Shaped>::FORM;
fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
described::ResultType::decode(self.bytes())
.map_err(|_| out.refuse(ty))?
.write_at(out, ty)
}
fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
let described = described::ResultType::read_at(input, ty)?;
Self::decode(&described.bytes()).map_err(|_| input.mismatch(ty))
}
}
impl Wire for ResultType {
fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
out.extend_from_slice(self.bytes());
}
fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
ResultType::read_from(reader).map(Opened::built)
}
}