1use flow_value::{Decimal, Int};
11use num_bigint::BigInt;
12
13use super::{
14 Constant, Constructor, ContractModule, Declaration, Field, FlowDeclaration, Import, Item,
15 Origin, Param, Payload, TypeBody, TypeDeclaration, TypeRef, Visibility,
16};
17use crate::bytes::{NONE, Reader, SOME, wide, write_int, write_signed, write_text, write_uint};
18use crate::error::{DecodeError, DecodeErrorKind, Place};
19use crate::limits::Limits;
20
21#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct Contract {
24 pub modules: Vec<Module>,
26}
27
28#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct Module {
31 pub path: Vec<String>,
34 pub module: ContractModule,
36}
37
38impl Contract {
39 #[must_use]
41 pub fn bytes(&self) -> Vec<u8> {
42 let mut out = Vec::new();
43 list(&mut out, &self.modules, |out, module| {
44 list(out, &module.path, |out, segment| write_text(out, segment));
45 write_text(out, &module.module.generated_from);
46 list(out, &module.module.imports, |out, import| {
47 write_text(out, &import.path);
48 option(out, import.binding.as_ref(), |out, binding| {
49 write_text(out, binding);
50 });
51 });
52 list(out, &module.module.items, item);
53 });
54 out
55 }
56
57 pub fn decode(bytes: &[u8]) -> Result<Contract, DecodeError> {
64 let mut read = Read {
65 reader: Reader::new(bytes),
66 depth: 0,
67 };
68 let modules = read.list(|read| {
69 Ok(Module {
70 path: read.list(Read::text)?,
71 module: ContractModule {
72 generated_from: read.text()?,
73 imports: read.list(|read| {
74 Ok(Import {
75 path: read.text()?,
76 binding: read.option(Read::text)?,
77 })
78 })?,
79 items: read.list(Read::item)?,
80 },
81 })
82 })?;
83 if !read.reader.is_empty() {
84 return Err(read.invalid("holds bytes after its contract"));
85 }
86 Ok(Contract { modules })
87 }
88}
89
90fn list<T>(out: &mut Vec<u8>, items: &[T], mut each: impl FnMut(&mut Vec<u8>, &T)) {
91 write_uint(out, wide(items.len()));
92 for one in items {
93 each(out, one);
94 }
95}
96
97fn option<T>(out: &mut Vec<u8>, value: Option<&T>, each: impl FnOnce(&mut Vec<u8>, &T)) {
98 match value {
99 None => write_uint(out, NONE),
100 Some(value) => {
101 write_uint(out, SOME);
102 each(out, value);
103 }
104 }
105}
106
107fn item(out: &mut Vec<u8>, item: &Item) {
108 write_text(out, &item.docs);
109 option(out, item.origin.as_ref(), |out, origin| {
110 write_text(out, &origin.path);
111 write_text(out, &origin.item);
112 });
113 match &item.declaration {
114 Declaration::Type(ty) => {
115 write_uint(out, 0);
116 write_text(out, &ty.name);
117 list(out, &ty.params, |out, param| write_text(out, param));
118 match &ty.body {
119 TypeBody::Host => write_uint(out, 0),
120 TypeBody::Newtype { visibility, base } => {
121 write_uint(out, 1);
122 public(out, *visibility);
123 type_ref(out, base);
124 }
125 TypeBody::Record(fields) => {
126 write_uint(out, 2);
127 list(out, fields, field);
128 }
129 TypeBody::Enum(constructors) => {
130 write_uint(out, 3);
131 list(out, constructors, constructor);
132 }
133 }
134 }
135 Declaration::Flow(flow) => {
136 write_uint(out, 1);
137 write_text(out, &flow.name);
138 list(out, &flow.generics, |out, name| write_text(out, name));
139 list(out, &flow.params, |out, param| {
140 write_text(out, ¶m.name);
141 type_ref(out, ¶m.ty);
142 option(out, param.default.as_ref(), constant);
143 });
144 type_ref(out, &flow.result);
145 }
146 }
147}
148
149fn public(out: &mut Vec<u8>, visibility: Visibility) {
150 out.push(u8::from(visibility == Visibility::Public));
151}
152
153fn field(out: &mut Vec<u8>, field: &Field) {
154 write_text(out, &field.docs);
155 public(out, field.visibility);
156 write_text(out, &field.name);
157 type_ref(out, &field.ty);
158}
159
160fn constructor(out: &mut Vec<u8>, constructor: &Constructor) {
161 write_text(out, &constructor.docs);
162 write_text(out, &constructor.name);
163 match &constructor.payload {
164 Payload::Empty => write_uint(out, 0),
165 Payload::Positional(parts) => {
166 write_uint(out, 1);
167 list(out, parts, type_ref);
168 }
169 Payload::Named(fields) => {
170 write_uint(out, 2);
171 list(out, fields, self::field);
172 }
173 }
174}
175
176fn type_ref(out: &mut Vec<u8>, ty: &TypeRef) {
177 match ty {
178 TypeRef::Named { module, name, args } => {
179 write_uint(out, 0);
180 option(out, module.as_ref(), |out, module| write_text(out, module));
181 write_text(out, name);
182 list(out, args, type_ref);
183 }
184 TypeRef::Tuple(parts) => {
185 write_uint(out, 1);
186 list(out, parts, type_ref);
187 }
188 }
189}
190
191fn constant(out: &mut Vec<u8>, constant: &Constant) {
192 match constant {
193 Constant::None => write_uint(out, 0),
194 Constant::Some(inner) => {
195 write_uint(out, 1);
196 self::constant(out, inner);
197 }
198 Constant::Bool(value) => {
199 write_uint(out, 2);
200 out.push(u8::from(*value));
201 }
202 Constant::Int(value) => {
203 write_uint(out, 3);
204 write_int(out, value.as_bigint());
205 }
206 Constant::Decimal(value) => {
207 write_uint(out, 4);
208 write_int(out, value.coefficient());
209 write_signed(out, value.exponent());
210 }
211 Constant::Text(text) => {
212 write_uint(out, 5);
213 write_text(out, text);
214 }
215 Constant::Tuple(parts) => {
216 write_uint(out, 6);
217 list(out, parts, self::constant);
218 }
219 Constant::Constructor(name) => {
220 write_uint(out, 7);
221 write_text(out, name);
222 }
223 Constant::Applied { newtype, value } => {
224 write_uint(out, 8);
225 type_ref(out, newtype);
226 self::constant(out, value);
227 }
228 }
229}
230
231struct Read<'a> {
234 reader: Reader<'a>,
235 depth: usize,
236}
237
238impl Read<'_> {
239 fn invalid(&self, problem: &str) -> DecodeError {
240 DecodeError::of(
241 &Place::default(),
242 DecodeErrorKind::Mismatch,
243 format!("{problem} at byte {}", self.reader.position()),
244 )
245 }
246
247 fn nested<T>(
250 &mut self,
251 part: impl FnOnce(&mut Self) -> Result<T, DecodeError>,
252 ) -> Result<T, DecodeError> {
253 if self.depth >= Limits::LANGUAGE.depth {
254 return Err(DecodeError::of(
255 &Place::default(),
256 DecodeErrorKind::TooLarge,
257 format!(
258 "nests deeper than {} at byte {}",
259 Limits::LANGUAGE.depth,
260 self.reader.position()
261 ),
262 ));
263 }
264 self.depth += 1;
265 let read = part(self);
266 self.depth -= 1;
267 read
268 }
269
270 fn text(&mut self) -> Result<String, DecodeError> {
271 Ok(self.reader.text(&Limits::LANGUAGE)?.to_owned())
272 }
273
274 fn bool(&mut self) -> Result<bool, DecodeError> {
275 self.reader.bool()
276 }
277
278 fn tag(&mut self, count: u64) -> Result<u64, DecodeError> {
279 let tag = self.reader.uint()?;
280 if tag < count {
281 Ok(tag)
282 } else {
283 Err(self.invalid(&format!("has constructor {tag} of {count}")))
284 }
285 }
286
287 fn list<T>(
288 &mut self,
289 mut each: impl FnMut(&mut Self) -> Result<T, DecodeError>,
290 ) -> Result<Vec<T>, DecodeError> {
291 let count = self.reader.count()?;
292 self.nested(|read| {
293 let mut items = Vec::with_capacity(count.min(read.reader.remaining()));
294 for _ in 0..count {
295 items.push(each(read)?);
296 }
297 Ok(items)
298 })
299 }
300
301 fn option<T>(
302 &mut self,
303 each: impl FnOnce(&mut Self) -> Result<T, DecodeError>,
304 ) -> Result<Option<T>, DecodeError> {
305 match self.tag(2)? {
306 NONE => Ok(None),
307 _ => self.nested(each).map(Some),
308 }
309 }
310
311 fn visibility(&mut self) -> Result<Visibility, DecodeError> {
312 Ok(if self.bool()? {
313 Visibility::Public
314 } else {
315 Visibility::Private
316 })
317 }
318
319 fn item(&mut self) -> Result<Item, DecodeError> {
320 let docs = self.text()?;
321 let origin = self.option(|read| {
322 Ok(Origin {
323 path: read.text()?,
324 item: read.text()?,
325 })
326 })?;
327 let declaration = match self.tag(2)? {
328 0 => Declaration::Type(TypeDeclaration {
329 name: self.text()?,
330 params: self.list(Read::text)?,
331 body: match self.tag(4)? {
332 0 => TypeBody::Host,
333 1 => TypeBody::Newtype {
334 visibility: self.visibility()?,
335 base: self.nested(Read::type_ref)?,
336 },
337 2 => TypeBody::Record(self.list(Read::field)?),
338 _ => TypeBody::Enum(self.list(Read::constructor)?),
339 },
340 }),
341 _ => Declaration::Flow(FlowDeclaration {
342 name: self.text()?,
343 generics: self.list(Read::text)?,
344 params: self.list(|read| {
345 Ok(Param {
346 name: read.text()?,
347 ty: read.type_ref()?,
348 default: read.option(Read::constant)?,
349 })
350 })?,
351 result: self.type_ref()?,
352 }),
353 };
354 Ok(Item {
355 docs,
356 origin,
357 declaration,
358 })
359 }
360
361 fn field(&mut self) -> Result<Field, DecodeError> {
362 Ok(Field {
363 docs: self.text()?,
364 visibility: self.visibility()?,
365 name: self.text()?,
366 ty: self.type_ref()?,
367 })
368 }
369
370 fn constructor(&mut self) -> Result<Constructor, DecodeError> {
371 Ok(Constructor {
372 docs: self.text()?,
373 name: self.text()?,
374 payload: match self.tag(3)? {
375 0 => Payload::Empty,
376 1 => Payload::Positional(self.list(Read::type_ref)?),
377 _ => Payload::Named(self.list(Read::field)?),
378 },
379 })
380 }
381
382 fn type_ref(&mut self) -> Result<TypeRef, DecodeError> {
383 match self.tag(2)? {
384 0 => Ok(TypeRef::Named {
385 module: self.option(Read::text)?,
386 name: self.text()?,
387 args: self.list(Read::type_ref)?,
388 }),
389 _ => Ok(TypeRef::Tuple(self.list(Read::type_ref)?)),
390 }
391 }
392
393 fn constant(&mut self) -> Result<Constant, DecodeError> {
394 Ok(match self.tag(9)? {
395 0 => Constant::None,
396 1 => Constant::Some(Box::new(self.nested(Read::constant)?)),
397 2 => Constant::Bool(self.bool()?),
398 3 => Constant::Int(Int::from(self.reader.int(&Limits::LANGUAGE)?)),
399 4 => {
400 let coefficient: BigInt = self.reader.int(&Limits::LANGUAGE)?;
401 let exponent = self.reader.signed()?;
402 let decimal = Decimal::new(coefficient, exponent)
403 .map_err(|_| self.invalid("has a decimal whose scale passes the host's"))?;
404 if decimal.text_len() > u128::from(wide(Limits::LANGUAGE.text_bytes)) {
405 return Err(self.invalid(&format!(
406 "has a decimal longer than {} digits written out",
407 Limits::LANGUAGE.text_bytes
408 )));
409 }
410 Constant::Decimal(decimal)
411 }
412 5 => Constant::Text(self.text()?),
413 6 => Constant::Tuple(self.list(Read::constant)?),
414 7 => Constant::Constructor(self.text()?),
415 _ => Constant::Applied {
416 newtype: self.nested(Read::type_ref)?,
417 value: Box::new(self.nested(Read::constant)?),
418 },
419 })
420 }
421}
422
423#[cfg(test)]
424#[cfg_attr(coverage, coverage(off))]
425mod tests {
426 use super::*;
427
428 fn deep(depth: usize) -> Constant {
429 (0..depth).fold(Constant::None, |inner, _| Constant::Some(Box::new(inner)))
430 }
431
432 fn with_default(default: Constant) -> Contract {
433 Contract {
434 modules: vec![Module {
435 path: Vec::new(),
436 module: ContractModule {
437 generated_from: "test".to_owned(),
438 imports: Vec::new(),
439 items: vec![Item {
440 docs: String::new(),
441 origin: Some(Origin {
442 path: "tools.go".to_owned(),
443 item: "Find".to_owned(),
444 }),
445 declaration: Declaration::Flow(FlowDeclaration {
446 name: "find".to_owned(),
447 generics: Vec::new(),
448 params: vec![Param {
449 name: "limit".to_owned(),
450 ty: TypeRef::Named {
451 module: None,
452 name: "Int".to_owned(),
453 args: Vec::new(),
454 },
455 default: Some(default),
456 }],
457 result: TypeRef::Tuple(Vec::new()),
458 }),
459 }],
460 },
461 }],
462 }
463 }
464
465 #[test]
466 fn a_contract_comes_back_from_its_encoding() {
467 for default in [
468 Constant::Int(Int::parse("-12345678901234567890123").unwrap()),
469 Constant::Decimal(Decimal::parse("-1.25").unwrap()),
470 Constant::Tuple(vec![Constant::Bool(true), Constant::Text("é".to_owned())]),
471 deep(Limits::LANGUAGE.depth - 8),
472 ] {
473 let contract = with_default(default);
474 assert_eq!(Contract::decode(&contract.bytes()), Ok(contract));
475 }
476 }
477
478 #[test]
479 fn bytes_that_are_not_one_contract_are_refused() {
480 let mut trailing = with_default(Constant::None).bytes();
481 trailing.push(0);
482 assert!(Contract::decode(&trailing).is_err());
483 let bytes = with_default(Constant::None).bytes();
484 assert!(Contract::decode(&bytes[..bytes.len() - 1]).is_err());
485 let mut tag = bytes;
486 *tag.last_mut().unwrap() = 9;
487 assert!(Contract::decode(&tag).is_err());
488 let vast = with_default(Constant::Decimal(
489 Decimal::new(BigInt::from(1), 1_000_000_000).unwrap(),
490 ))
491 .bytes();
492 assert!(
493 Contract::decode(&vast)
494 .unwrap_err()
495 .problem
496 .contains("longer than")
497 );
498 let too_deep = with_default(deep(Limits::LANGUAGE.depth + 1)).bytes();
499 assert_eq!(
500 Contract::decode(&too_deep).unwrap_err().kind,
501 DecodeErrorKind::TooLarge
502 );
503 }
504}