use std::fmt::Write as _;
use std::ops::Range;
use flow_value::{Decimal, Int};
mod encoding;
pub use encoding::{Contract, Module};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContractModule {
pub generated_from: String,
pub imports: Vec<Import>,
pub items: Vec<Item>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Import {
pub path: String,
pub binding: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Item<M = String> {
pub docs: String,
pub origin: Option<Origin>,
pub declaration: Declaration<M>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Origin {
pub path: String,
pub item: String,
}
const FROM: &str = "// from ";
impl Origin {
#[must_use]
pub fn line(&self) -> String {
format!("{FROM}{}: {}", self.path, self.item)
}
#[must_use]
pub fn read(line: &str) -> Option<(Origin, Range<usize>)> {
let indent = line.len() - line.trim_start().len();
let spelled = line.trim().strip_prefix(FROM)?;
let skipped = spelled.len() - spelled.trim_start().len();
let start = indent + FROM.len() + skipped;
let range = start..indent + FROM.len() + spelled.len();
let (path, item) = spelled.trim().rsplit_once(": ")?;
let (path, item) = (path.trim(), item.trim());
if path.is_empty() || item.is_empty() {
return None;
}
Some((
Origin {
path: path.to_owned(),
item: item.to_owned(),
},
range,
))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Declaration<M = String> {
Type(TypeDeclaration<M>),
Flow(FlowDeclaration<M>),
}
impl<M> Declaration<M> {
#[must_use]
pub fn name(&self) -> &str {
match self {
Declaration::Type(ty) => &ty.name,
Declaration::Flow(flow) => &flow.name,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TypeDeclaration<M = String> {
pub name: String,
pub params: Vec<String>,
pub body: TypeBody<M>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TypeBody<M = String> {
Host,
Newtype {
visibility: Visibility,
base: TypeRef<M>,
},
Record(Vec<Field<M>>),
Enum(Vec<Constructor<M>>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Field<M = String> {
pub docs: String,
pub visibility: Visibility,
pub name: String,
pub ty: TypeRef<M>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Visibility {
Public,
Private,
}
impl Visibility {
fn keyword(self) -> &'static str {
match self {
Visibility::Public => "pub ",
Visibility::Private => "",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Constructor<M = String> {
pub docs: String,
pub name: String,
pub payload: Payload<M>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Payload<M = String> {
Empty,
Positional(Vec<TypeRef<M>>),
Named(Vec<Field<M>>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FlowDeclaration<M = String> {
pub name: String,
pub generics: Vec<String>,
pub params: Vec<Param<M>>,
pub result: TypeRef<M>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Param<M = String> {
pub name: String,
pub ty: TypeRef<M>,
pub default: Option<Constant<M>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TypeRef<M = String> {
Named {
module: Option<M>,
name: String,
args: Vec<TypeRef<M>>,
},
Tuple(Vec<TypeRef<M>>),
}
impl<M> TypeRef<M> {
#[must_use]
pub fn named(name: &str) -> TypeRef<M> {
TypeRef::applied(name, Vec::new())
}
#[must_use]
pub fn applied(name: &str, args: Vec<TypeRef<M>>) -> TypeRef<M> {
TypeRef::Named {
module: None,
name: name.to_owned(),
args,
}
}
#[must_use]
pub fn qualified(module: impl Into<M>, name: &str) -> TypeRef<M> {
TypeRef::Named {
module: Some(module.into()),
name: name.to_owned(),
args: Vec::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Constant<M = String> {
None,
Some(Box<Constant<M>>),
Bool(bool),
Int(Int),
Decimal(Decimal),
Text(String),
Tuple(Vec<Constant<M>>),
Constructor(String),
Applied {
newtype: TypeRef<M>,
value: Box<Constant<M>>,
},
}
impl<M> Item<M> {
pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Item<N> {
Item {
docs: self.docs.clone(),
origin: self.origin.clone(),
declaration: self.declaration.qualify(module),
}
}
}
impl<M> Declaration<M> {
pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Declaration<N> {
match self {
Declaration::Type(ty) => Declaration::Type(TypeDeclaration {
name: ty.name.clone(),
params: ty.params.clone(),
body: ty.body.qualify(module),
}),
Declaration::Flow(flow) => Declaration::Flow(FlowDeclaration {
name: flow.name.clone(),
generics: flow.generics.clone(),
params: flow
.params
.iter()
.map(|param| Param {
name: param.name.clone(),
ty: param.ty.qualify(module),
default: param
.default
.as_ref()
.map(|default| default.qualify(module)),
})
.collect(),
result: flow.result.qualify(module),
}),
}
}
}
impl<M> TypeBody<M> {
fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> TypeBody<N> {
match self {
TypeBody::Host => TypeBody::Host,
TypeBody::Newtype { visibility, base } => TypeBody::Newtype {
visibility: *visibility,
base: base.qualify(module),
},
TypeBody::Record(fields) => {
TypeBody::Record(fields.iter().map(|field| field.qualify(module)).collect())
}
TypeBody::Enum(constructors) => TypeBody::Enum(
constructors
.iter()
.map(|constructor| Constructor {
docs: constructor.docs.clone(),
name: constructor.name.clone(),
payload: match &constructor.payload {
Payload::Empty => Payload::Empty,
Payload::Positional(parts) => Payload::Positional(
parts.iter().map(|part| part.qualify(module)).collect(),
),
Payload::Named(fields) => Payload::Named(
fields.iter().map(|field| field.qualify(module)).collect(),
),
},
})
.collect(),
),
}
}
}
impl<M> Field<M> {
fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Field<N> {
Field {
docs: self.docs.clone(),
visibility: self.visibility,
name: self.name.clone(),
ty: self.ty.qualify(module),
}
}
}
impl<M> TypeRef<M> {
pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> TypeRef<N> {
match self {
TypeRef::Named {
module: qualifier,
name,
args,
} => TypeRef::Named {
module: qualifier.as_ref().and_then(&mut *module),
name: name.clone(),
args: args.iter().map(|arg| arg.qualify(module)).collect(),
},
TypeRef::Tuple(parts) => {
TypeRef::Tuple(parts.iter().map(|part| part.qualify(module)).collect())
}
}
}
}
impl<M> Constant<M> {
pub fn qualify<N>(&self, module: &mut impl FnMut(&M) -> Option<N>) -> Constant<N> {
match self {
Constant::None => Constant::None,
Constant::Some(inner) => Constant::Some(Box::new(inner.qualify(module))),
Constant::Bool(value) => Constant::Bool(*value),
Constant::Int(literal) => Constant::Int(literal.clone()),
Constant::Decimal(literal) => Constant::Decimal(literal.clone()),
Constant::Text(text) => Constant::Text(text.clone()),
Constant::Tuple(parts) => {
Constant::Tuple(parts.iter().map(|part| part.qualify(module)).collect())
}
Constant::Constructor(name) => Constant::Constructor(name.clone()),
Constant::Applied { newtype, value } => Constant::Applied {
newtype: newtype.qualify(module),
value: Box::new(value.qualify(module)),
},
}
}
}
#[must_use]
pub fn print(module: &ContractModule) -> String {
let mut out = format!(
"// Generated by flow build from {}. Do not edit.\n",
visible(&module.generated_from)
);
for import in &module.imports {
let _ = write!(out, "use \"{}\"", import.path);
if let Some(binding) = &import.binding {
let _ = write!(out, " as {binding}");
}
out.push('\n');
}
for item in &module.items {
out.push('\n');
out.push_str(&print_item(item));
}
out
}
#[must_use]
pub fn print_item(item: &Item) -> String {
let mut out = String::new();
docs(&mut out, &item.docs, "");
if let Some(origin) = &item.origin {
out.push_str(&origin.line());
out.push('\n');
}
match &item.declaration {
Declaration::Type(ty) => type_declaration(&mut out, ty),
Declaration::Flow(flow) => flow_declaration(&mut out, flow),
}
out.push('\n');
out
}
fn type_declaration(out: &mut String, ty: &TypeDeclaration) {
let _ = write!(out, "pub type {}", ty.name);
names(out, &ty.params);
match &ty.body {
TypeBody::Host => {}
TypeBody::Newtype { visibility, base } => {
let _ = write!(out, "({}{})", visibility.keyword(), type_ref(base));
}
TypeBody::Record(fields) => {
out.push_str(" {\n");
for field in fields {
self::field(out, field, " ");
}
out.push('}');
}
TypeBody::Enum(constructors) => {
out.push_str(" {\n");
for constructor in constructors {
docs(out, &constructor.docs, " ");
let _ = write!(out, " {}", constructor.name);
match &constructor.payload {
Payload::Empty => {}
Payload::Positional(parts) => {
let parts: Vec<String> = parts.iter().map(type_ref).collect();
let _ = write!(out, "({})", parts.join(", "));
}
Payload::Named(fields) => {
out.push_str(" {\n");
for field in fields {
self::field(out, field, " ");
}
out.push_str(" }");
}
}
out.push_str(",\n");
}
out.push('}');
}
}
}
fn field(out: &mut String, field: &Field, indent: &str) {
docs(out, &field.docs, indent);
let _ = writeln!(
out,
"{indent}{}{}: {},",
field.visibility.keyword(),
field.name,
type_ref(&field.ty)
);
}
fn flow_declaration(out: &mut String, flow: &FlowDeclaration) {
let _ = write!(out, "pub flow {}", flow.name);
names(out, &flow.generics);
let params: Vec<String> = flow
.params
.iter()
.map(|param| match ¶m.default {
Some(default) => format!(
"{}: {} = {}",
param.name,
type_ref(¶m.ty),
constant(default)
),
None => format!("{}: {}", param.name, type_ref(¶m.ty)),
})
.collect();
let _ = write!(out, "({}) -> {}", params.join(", "), type_ref(&flow.result));
}
fn names(out: &mut String, names: &[String]) {
if !names.is_empty() {
let _ = write!(out, "<{}>", names.join(", "));
}
}
#[must_use]
pub fn type_ref(ty: &TypeRef) -> String {
match ty {
TypeRef::Named { module, name, args } => {
let mut out = String::new();
if let Some(module) = module {
let _ = write!(out, "{module}.");
}
out.push_str(name);
if !args.is_empty() {
let args: Vec<String> = args.iter().map(type_ref).collect();
let _ = write!(out, "<{}>", args.join(", "));
}
out
}
TypeRef::Tuple(parts) => {
let parts: Vec<String> = parts.iter().map(type_ref).collect();
format!("({})", parts.join(", "))
}
}
}
#[must_use]
pub fn constant(constant: &Constant) -> String {
match constant {
Constant::None => "None".to_owned(),
Constant::Some(inner) => format!("Some({})", self::constant(inner)),
Constant::Bool(value) => value.to_string(),
Constant::Int(value) => value.to_string(),
Constant::Decimal(value) => decimal_literal(value),
Constant::Constructor(name) => name.clone(),
Constant::Text(text) => text_literal(text),
Constant::Tuple(parts) => {
let parts: Vec<String> = parts.iter().map(self::constant).collect();
format!("({})", parts.join(", "))
}
Constant::Applied { newtype, value } => {
format!("{}({})", type_ref(newtype), self::constant(value))
}
}
}
fn decimal_literal(value: &Decimal) -> String {
let text = value.to_string();
if text.contains('.') {
text
} else {
format!("{text}.0")
}
}
fn text_literal(text: &str) -> String {
let mut out = String::from("\"");
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'$' if chars.peek() == Some(&'{') => out.push_str("\\$"),
ch if not_in_a_comment(ch) => {
let _ = write!(out, "\\u{{{:x}}}", u32::from(ch));
}
ch => out.push(ch),
}
}
out.push('"');
out
}
fn docs(out: &mut String, text: &str, indent: &str) {
if text.is_empty() {
return;
}
let text = text.replace("\r\n", "\n");
let ends = ['\n', '\r', '\u{85}', '\u{2028}', '\u{2029}'];
for line in text.strip_suffix(ends).unwrap_or(&text).split(ends) {
let line = visible(line.trim_end());
if line.is_empty() {
let _ = writeln!(out, "{indent}///");
} else {
let _ = writeln!(out, "{indent}/// {line}");
}
}
}
#[must_use]
pub fn not_in_a_comment(ch: char) -> bool {
ch.is_control()
|| matches!(
ch,
'\u{2028}'
| '\u{2029}'
| '\u{061C}'
| '\u{200E}'
| '\u{200F}'
| '\u{202A}'..='\u{202E}'
| '\u{2066}'..='\u{2069}'
)
}
#[must_use]
pub fn visible(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for ch in text.chars() {
if ch != '\t' && not_in_a_comment(ch) {
let _ = write!(out, "\\u{{{:04X}}}", u32::from(ch));
} else {
out.push(ch);
}
}
out
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::{Constant, constant};
fn text(text: &str) -> String {
constant(&Constant::<String>::Text(text.to_owned()))
}
#[test]
fn a_text_constant_escapes_what_source_text_would_not_show_as_itself() {
assert_eq!(text(""), r#""""#);
assert_eq!(text(r#"a "q" \ b"#), r#""a \"q\" \\ b""#);
assert_eq!(text("line\nnext\r\ttab"), r#""line\nnext\r\ttab""#);
assert_eq!(
text("cost ${x} and $y"),
r#""cost \${x} and $y""#,
"`${{` would begin an interpolation; a lone `$` is ordinary text"
);
assert_eq!(text("bell\u{7}"), r#""bell\u{7}""#);
assert_eq!(text("a\u{202E}b"), r#""a\u{202e}b""#);
assert_eq!(
text("naïve ☃"),
r#""naïve ☃""#,
"Unicode is welcome in text"
);
}
}