1use std::fmt::Write as _;
13use std::ops::Range;
14
15use flow_value::{Decimal, Int};
16
17mod encoding;
18
19pub use encoding::{Contract, Module};
20
21#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct ContractModule {
25 pub generated_from: String,
28 pub imports: Vec<Import>,
30 pub items: Vec<Item>,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct Import {
37 pub path: String,
39 pub binding: Option<String>,
41}
42
43#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct Item<M = String> {
46 pub docs: String,
48 pub origin: Option<Origin>,
50 pub declaration: Declaration<M>,
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct Origin {
59 pub path: String,
61 pub item: String,
63}
64
65const FROM: &str = "// from ";
67
68impl Origin {
69 #[must_use]
71 pub fn line(&self) -> String {
72 format!("{FROM}{}: {}", self.path, self.item)
73 }
74
75 #[must_use]
79 pub fn read(line: &str) -> Option<(Origin, Range<usize>)> {
80 let indent = line.len() - line.trim_start().len();
81 let spelled = line.trim().strip_prefix(FROM)?;
82 let skipped = spelled.len() - spelled.trim_start().len();
83 let start = indent + FROM.len() + skipped;
84 let range = start..indent + FROM.len() + spelled.len();
85 let (path, item) = spelled.trim().rsplit_once(": ")?;
86 let (path, item) = (path.trim(), item.trim());
87 if path.is_empty() || item.is_empty() {
88 return None;
89 }
90 Some((
91 Origin {
92 path: path.to_owned(),
93 item: item.to_owned(),
94 },
95 range,
96 ))
97 }
98}
99
100#[derive(Clone, Debug, PartialEq, Eq)]
102pub enum Declaration<M = String> {
103 Type(TypeDeclaration<M>),
105 Flow(FlowDeclaration<M>),
107}
108
109impl<M> Declaration<M> {
110 #[must_use]
112 pub fn name(&self) -> &str {
113 match self {
114 Declaration::Type(ty) => &ty.name,
115 Declaration::Flow(flow) => &flow.name,
116 }
117 }
118}
119
120#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct TypeDeclaration<M = String> {
123 pub name: String,
125 pub params: Vec<String>,
127 pub body: TypeBody<M>,
129}
130
131#[derive(Clone, Debug, PartialEq, Eq)]
133pub enum TypeBody<M = String> {
134 Host,
136 Newtype {
138 visibility: Visibility,
140 base: TypeRef<M>,
142 },
143 Record(Vec<Field<M>>),
145 Enum(Vec<Constructor<M>>),
147}
148
149#[derive(Clone, Debug, PartialEq, Eq)]
151pub struct Field<M = String> {
152 pub docs: String,
154 pub visibility: Visibility,
156 pub name: String,
158 pub ty: TypeRef<M>,
160}
161
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub enum Visibility {
165 Public,
167 Private,
169}
170
171impl Visibility {
172 fn keyword(self) -> &'static str {
174 match self {
175 Visibility::Public => "pub ",
176 Visibility::Private => "",
177 }
178 }
179}
180
181#[derive(Clone, Debug, PartialEq, Eq)]
183pub struct Constructor<M = String> {
184 pub docs: String,
186 pub name: String,
188 pub payload: Payload<M>,
190}
191
192#[derive(Clone, Debug, PartialEq, Eq)]
194pub enum Payload<M = String> {
195 Empty,
197 Positional(Vec<TypeRef<M>>),
199 Named(Vec<Field<M>>),
201}
202
203#[derive(Clone, Debug, PartialEq, Eq)]
205pub struct FlowDeclaration<M = String> {
206 pub name: String,
208 pub generics: Vec<String>,
210 pub params: Vec<Param<M>>,
212 pub result: TypeRef<M>,
214}
215
216#[derive(Clone, Debug, PartialEq, Eq)]
218pub struct Param<M = String> {
219 pub name: String,
221 pub ty: TypeRef<M>,
223 pub default: Option<Constant<M>>,
225}
226
227#[derive(Clone, Debug, PartialEq, Eq)]
229pub enum TypeRef<M = String> {
230 Named {
233 module: Option<M>,
235 name: String,
237 args: Vec<TypeRef<M>>,
239 },
240 Tuple(Vec<TypeRef<M>>),
242}
243
244impl<M> TypeRef<M> {
245 #[must_use]
247 pub fn named(name: &str) -> TypeRef<M> {
248 TypeRef::applied(name, Vec::new())
249 }
250
251 #[must_use]
253 pub fn applied(name: &str, args: Vec<TypeRef<M>>) -> TypeRef<M> {
254 TypeRef::Named {
255 module: None,
256 name: name.to_owned(),
257 args,
258 }
259 }
260
261 #[must_use]
263 pub fn qualified(module: impl Into<M>, name: &str) -> TypeRef<M> {
264 TypeRef::Named {
265 module: Some(module.into()),
266 name: name.to_owned(),
267 args: Vec::new(),
268 }
269 }
270}
271
272#[derive(Clone, Debug, PartialEq, Eq)]
274pub enum Constant<M = String> {
275 None,
277 Some(Box<Constant<M>>),
279 Bool(bool),
281 Int(Int),
283 Decimal(Decimal),
285 Text(String),
287 Tuple(Vec<Constant<M>>),
289 Constructor(String),
291 Applied {
293 newtype: TypeRef<M>,
295 value: Box<Constant<M>>,
297 },
298}
299
300impl<M> Item<M> {
301 pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Item<N> {
303 Item {
304 docs: self.docs.clone(),
305 origin: self.origin.clone(),
306 declaration: self.declaration.qualify(module),
307 }
308 }
309}
310
311impl<M> Declaration<M> {
312 pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Declaration<N> {
315 match self {
316 Declaration::Type(ty) => Declaration::Type(TypeDeclaration {
317 name: ty.name.clone(),
318 params: ty.params.clone(),
319 body: ty.body.qualify(module),
320 }),
321 Declaration::Flow(flow) => Declaration::Flow(FlowDeclaration {
322 name: flow.name.clone(),
323 generics: flow.generics.clone(),
324 params: flow
325 .params
326 .iter()
327 .map(|param| Param {
328 name: param.name.clone(),
329 ty: param.ty.qualify(module),
330 default: param
331 .default
332 .as_ref()
333 .map(|default| default.qualify(module)),
334 })
335 .collect(),
336 result: flow.result.qualify(module),
337 }),
338 }
339 }
340}
341
342impl<M> TypeBody<M> {
343 fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> TypeBody<N> {
344 match self {
345 TypeBody::Host => TypeBody::Host,
346 TypeBody::Newtype { visibility, base } => TypeBody::Newtype {
347 visibility: *visibility,
348 base: base.qualify(module),
349 },
350 TypeBody::Record(fields) => {
351 TypeBody::Record(fields.iter().map(|field| field.qualify(module)).collect())
352 }
353 TypeBody::Enum(constructors) => TypeBody::Enum(
354 constructors
355 .iter()
356 .map(|constructor| Constructor {
357 docs: constructor.docs.clone(),
358 name: constructor.name.clone(),
359 payload: match &constructor.payload {
360 Payload::Empty => Payload::Empty,
361 Payload::Positional(parts) => Payload::Positional(
362 parts.iter().map(|part| part.qualify(module)).collect(),
363 ),
364 Payload::Named(fields) => Payload::Named(
365 fields.iter().map(|field| field.qualify(module)).collect(),
366 ),
367 },
368 })
369 .collect(),
370 ),
371 }
372 }
373}
374
375impl<M> Field<M> {
376 fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Field<N> {
377 Field {
378 docs: self.docs.clone(),
379 visibility: self.visibility,
380 name: self.name.clone(),
381 ty: self.ty.qualify(module),
382 }
383 }
384}
385
386impl<M> TypeRef<M> {
387 pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> TypeRef<N> {
391 match self {
392 TypeRef::Named {
393 module: qualifier,
394 name,
395 args,
396 } => TypeRef::Named {
397 module: qualifier.as_ref().and_then(&mut *module),
398 name: name.clone(),
399 args: args.iter().map(|arg| arg.qualify(module)).collect(),
400 },
401 TypeRef::Tuple(parts) => {
402 TypeRef::Tuple(parts.iter().map(|part| part.qualify(module)).collect())
403 }
404 }
405 }
406}
407
408impl<M> Constant<M> {
409 pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Constant<N> {
412 match self {
413 Constant::None => Constant::None,
414 Constant::Some(inner) => Constant::Some(Box::new(inner.qualify(module))),
415 Constant::Bool(value) => Constant::Bool(*value),
416 Constant::Int(literal) => Constant::Int(literal.clone()),
417 Constant::Decimal(literal) => Constant::Decimal(literal.clone()),
418 Constant::Text(text) => Constant::Text(text.clone()),
419 Constant::Tuple(parts) => {
420 Constant::Tuple(parts.iter().map(|part| part.qualify(module)).collect())
421 }
422 Constant::Constructor(name) => Constant::Constructor(name.clone()),
423 Constant::Applied { newtype, value } => Constant::Applied {
424 newtype: newtype.qualify(module),
425 value: Box::new(value.qualify(module)),
426 },
427 }
428 }
429}
430
431#[must_use]
433pub fn print(module: &ContractModule) -> String {
434 let mut out = format!(
435 "// Generated by flow build from {}. Do not edit.\n",
436 visible(&module.generated_from)
437 );
438 for import in &module.imports {
439 let _ = write!(out, "use \"{}\"", import.path);
440 if let Some(binding) = &import.binding {
441 let _ = write!(out, " as {binding}");
442 }
443 out.push('\n');
444 }
445 for item in &module.items {
446 out.push('\n');
447 out.push_str(&print_item(item));
448 }
449 out
450}
451
452#[must_use]
455pub fn print_item(item: &Item) -> String {
456 let mut out = String::new();
457 docs(&mut out, &item.docs, "");
458 if let Some(origin) = &item.origin {
459 out.push_str(&origin.line());
460 out.push('\n');
461 }
462 match &item.declaration {
463 Declaration::Type(ty) => type_declaration(&mut out, ty),
464 Declaration::Flow(flow) => flow_declaration(&mut out, flow),
465 }
466 out.push('\n');
467 out
468}
469
470fn type_declaration(out: &mut String, ty: &TypeDeclaration) {
471 let _ = write!(out, "pub type {}", ty.name);
472 names(out, &ty.params);
473 match &ty.body {
474 TypeBody::Host => {}
475 TypeBody::Newtype { visibility, base } => {
476 let _ = write!(out, "({}{})", visibility.keyword(), type_ref(base));
477 }
478 TypeBody::Record(fields) => {
479 out.push_str(" {\n");
480 for field in fields {
481 self::field(out, field, " ");
482 }
483 out.push('}');
484 }
485 TypeBody::Enum(constructors) => {
486 out.push_str(" {\n");
487 for constructor in constructors {
488 docs(out, &constructor.docs, " ");
489 let _ = write!(out, " {}", constructor.name);
490 match &constructor.payload {
491 Payload::Empty => {}
492 Payload::Positional(parts) => {
493 let parts: Vec<String> = parts.iter().map(type_ref).collect();
494 let _ = write!(out, "({})", parts.join(", "));
495 }
496 Payload::Named(fields) => {
497 out.push_str(" {\n");
498 for field in fields {
499 self::field(out, field, " ");
500 }
501 out.push_str(" }");
502 }
503 }
504 out.push_str(",\n");
505 }
506 out.push('}');
507 }
508 }
509}
510
511fn field(out: &mut String, field: &Field, indent: &str) {
512 docs(out, &field.docs, indent);
513 let _ = writeln!(
514 out,
515 "{indent}{}{}: {},",
516 field.visibility.keyword(),
517 field.name,
518 type_ref(&field.ty)
519 );
520}
521
522fn flow_declaration(out: &mut String, flow: &FlowDeclaration) {
523 let _ = write!(out, "pub flow {}", flow.name);
524 names(out, &flow.generics);
525 let params: Vec<String> = flow
526 .params
527 .iter()
528 .map(|param| match ¶m.default {
529 Some(default) => format!(
530 "{}: {} = {}",
531 param.name,
532 type_ref(¶m.ty),
533 constant(default)
534 ),
535 None => format!("{}: {}", param.name, type_ref(¶m.ty)),
536 })
537 .collect();
538 let _ = write!(out, "({}) -> {}", params.join(", "), type_ref(&flow.result));
539}
540
541fn names(out: &mut String, names: &[String]) {
543 if !names.is_empty() {
544 let _ = write!(out, "<{}>", names.join(", "));
545 }
546}
547
548#[must_use]
550pub fn type_ref(ty: &TypeRef) -> String {
551 match ty {
552 TypeRef::Named { module, name, args } => {
553 let mut out = String::new();
554 if let Some(module) = module {
555 let _ = write!(out, "{module}.");
556 }
557 out.push_str(name);
558 if !args.is_empty() {
559 let args: Vec<String> = args.iter().map(type_ref).collect();
560 let _ = write!(out, "<{}>", args.join(", "));
561 }
562 out
563 }
564 TypeRef::Tuple(parts) => {
565 let parts: Vec<String> = parts.iter().map(type_ref).collect();
566 format!("({})", parts.join(", "))
567 }
568 }
569}
570
571#[must_use]
573pub fn constant(constant: &Constant) -> String {
574 match constant {
575 Constant::None => "None".to_owned(),
576 Constant::Some(inner) => format!("Some({})", self::constant(inner)),
577 Constant::Bool(value) => value.to_string(),
578 Constant::Int(value) => value.to_string(),
579 Constant::Decimal(value) => decimal_literal(value),
580 Constant::Constructor(name) => name.clone(),
581 Constant::Text(text) => text_literal(text),
582 Constant::Tuple(parts) => {
583 let parts: Vec<String> = parts.iter().map(self::constant).collect();
584 format!("({})", parts.join(", "))
585 }
586 Constant::Applied { newtype, value } => {
587 format!("{}({})", type_ref(newtype), self::constant(value))
588 }
589 }
590}
591
592fn decimal_literal(value: &Decimal) -> String {
595 let text = value.to_string();
596 if text.contains('.') {
597 text
598 } else {
599 format!("{text}.0")
600 }
601}
602
603fn text_literal(text: &str) -> String {
605 let mut out = String::from("\"");
606 let mut chars = text.chars().peekable();
607 while let Some(ch) = chars.next() {
608 match ch {
609 '\\' => out.push_str("\\\\"),
610 '"' => out.push_str("\\\""),
611 '\n' => out.push_str("\\n"),
612 '\r' => out.push_str("\\r"),
613 '\t' => out.push_str("\\t"),
614 '$' if chars.peek() == Some(&'{') => out.push_str("\\$"),
615 ch if not_in_a_comment(ch) => {
616 let _ = write!(out, "\\u{{{:x}}}", u32::from(ch));
617 }
618 ch => out.push(ch),
619 }
620 }
621 out.push('"');
622 out
623}
624
625fn docs(out: &mut String, text: &str, indent: &str) {
631 if text.is_empty() {
632 return;
633 }
634 let text = text.replace("\r\n", "\n");
635 let ends = ['\n', '\r', '\u{85}', '\u{2028}', '\u{2029}'];
636 for line in text.strip_suffix(ends).unwrap_or(&text).split(ends) {
638 let line = visible(line.trim_end());
639 if line.is_empty() {
640 let _ = writeln!(out, "{indent}///");
641 } else {
642 let _ = writeln!(out, "{indent}/// {line}");
643 }
644 }
645}
646
647#[must_use]
653pub fn not_in_a_comment(ch: char) -> bool {
654 ch.is_control()
655 || matches!(
656 ch,
657 '\u{2028}'
658 | '\u{2029}'
659 | '\u{061C}'
660 | '\u{200E}'
661 | '\u{200F}'
662 | '\u{202A}'..='\u{202E}'
663 | '\u{2066}'..='\u{2069}'
664 )
665}
666
667#[must_use]
671pub fn visible(text: &str) -> String {
672 let mut out = String::with_capacity(text.len());
673 for ch in text.chars() {
674 if ch != '\t' && not_in_a_comment(ch) {
675 let _ = write!(out, "\\u{{{:04X}}}", u32::from(ch));
676 } else {
677 out.push(ch);
678 }
679 }
680 out
681}
682
683#[cfg(test)]
684#[cfg_attr(coverage, coverage(off))]
685mod tests {
686 use super::{Constant, constant};
687
688 fn text(text: &str) -> String {
689 constant(&Constant::<String>::Text(text.to_owned()))
690 }
691
692 #[test]
693 fn a_text_constant_escapes_what_source_text_would_not_show_as_itself() {
694 assert_eq!(text(""), r#""""#);
695 assert_eq!(text(r#"a "q" \ b"#), r#""a \"q\" \\ b""#);
696 assert_eq!(text("line\nnext\r\ttab"), r#""line\nnext\r\ttab""#);
697 assert_eq!(
698 text("cost ${x} and $y"),
699 r#""cost \${x} and $y""#,
700 "`${{` would begin an interpolation; a lone `$` is ordinary text"
701 );
702 assert_eq!(text("bell\u{7}"), r#""bell\u{7}""#);
703 assert_eq!(text("a\u{202E}b"), r#""a\u{202e}b""#);
704 assert_eq!(
705 text("naïve ☃"),
706 r#""naïve ☃""#,
707 "Unicode is welcome in text"
708 );
709 }
710}