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;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Contract {
pub modules: Vec<Module>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Module {
pub path: Vec<String>,
pub module: ContractModule,
}
impl Contract {
#[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
}
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, ¶m.name);
type_ref(out, ¶m.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);
}
}
}
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()),
)
}
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
);
}
}