Skip to main content

flow_abi/
contract.rs

1//! A generated contract module as data, and the one printer that writes it
2//! (`abi.md`, *Generated contracts*).
3//!
4//! Every generator builds a [`ContractModule`]: the host from an MCP
5//! server's tool list, a toolkit from its native declarations, which it
6//! hands the host as a [`Contract`] in the value encoding (`abi.md`,
7//! *Extracting a contract*). [`print()`] writes a module in the one layout
8//! every contract has, which `flow fmt` leaves as it is; the host is the one
9//! writer of contract text. The `// from` line above each generated item is
10//! an [`Origin`], which writes it and reads it back.
11
12use 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/// A contract module: what generated it, what it imports, and its items in
22/// order.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct ContractModule {
25    /// What it was generated from, as its first line names it, such as
26    /// `rust module tools::models` or `mcp command ./server`.
27    pub generated_from: String,
28    /// Its imports, in order.
29    pub imports: Vec<Import>,
30    /// Its items, in order.
31    pub items: Vec<Item>,
32}
33
34/// One `use` of a contract module.
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct Import {
37    /// The module path, such as `std@v1/duration` or `./models`.
38    pub path: String,
39    /// The name it is bound to, when that is not its natural one.
40    pub binding: Option<String>,
41}
42
43/// One item of a contract module.
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct Item<M = String> {
46    /// Its doc comment, a line each.
47    pub docs: String,
48    /// What it was generated from, when the generator names it.
49    pub origin: Option<Origin>,
50    /// The item itself.
51    pub declaration: Declaration<M>,
52}
53
54/// What a generated item comes from, as the comment line above it says:
55/// `// from <path>: <item>`, the definition `item` in `path`, relative to
56/// the library's root.
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct Origin {
59    /// Where the item is defined, such as `src/lib.rs`.
60    pub path: String,
61    /// The definition there, such as `Command`.
62    pub item: String,
63}
64
65/// What starts an origin line.
66const FROM: &str = "// from ";
67
68impl Origin {
69    /// The comment line that says it, without its line end.
70    #[must_use]
71    pub fn line(&self) -> String {
72        format!("{FROM}{}: {}", self.path, self.item)
73    }
74
75    /// The origin `line` says, with the byte range in `line` of what
76    /// follows `// from `, or `None` when it is no origin line. The path is
77    /// what comes before the last `: `.
78    #[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/// A contract item's declaration.
101#[derive(Clone, Debug, PartialEq, Eq)]
102pub enum Declaration<M = String> {
103    /// A type.
104    Type(TypeDeclaration<M>),
105    /// A Tool.
106    Flow(FlowDeclaration<M>),
107}
108
109impl<M> Declaration<M> {
110    /// The name it declares.
111    #[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/// A type declaration.
121#[derive(Clone, Debug, PartialEq, Eq)]
122pub struct TypeDeclaration<M = String> {
123    /// Its name.
124    pub name: String,
125    /// Its type parameters.
126    pub params: Vec<String>,
127    /// What it is.
128    pub body: TypeBody<M>,
129}
130
131/// What a declared type is.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub enum TypeBody<M = String> {
134    /// A host type, which a contract declares by name alone.
135    Host,
136    /// A newtype over `base`.
137    Newtype {
138        /// Its field's visibility.
139        visibility: Visibility,
140        /// The type it holds.
141        base: TypeRef<M>,
142    },
143    /// A record of fields.
144    Record(Vec<Field<M>>),
145    /// An enum of constructors.
146    Enum(Vec<Constructor<M>>),
147}
148
149/// A field of a record or of a constructor's named payload.
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub struct Field<M = String> {
152    /// Its doc comment.
153    pub docs: String,
154    /// Its visibility; a constructor's fields are private.
155    pub visibility: Visibility,
156    /// Its name.
157    pub name: String,
158    /// Its type.
159    pub ty: TypeRef<M>,
160}
161
162/// Whether a field can be read outside its module.
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub enum Visibility {
165    /// Written `pub`: it can.
166    Public,
167    /// It cannot.
168    Private,
169}
170
171impl Visibility {
172    /// What is written before the field.
173    fn keyword(self) -> &'static str {
174        match self {
175            Visibility::Public => "pub ",
176            Visibility::Private => "",
177        }
178    }
179}
180
181/// A constructor of an enum.
182#[derive(Clone, Debug, PartialEq, Eq)]
183pub struct Constructor<M = String> {
184    /// Its doc comment.
185    pub docs: String,
186    /// Its name.
187    pub name: String,
188    /// What it holds.
189    pub payload: Payload<M>,
190}
191
192/// What a constructor holds.
193#[derive(Clone, Debug, PartialEq, Eq)]
194pub enum Payload<M = String> {
195    /// Nothing.
196    Empty,
197    /// Values of these types, in order.
198    Positional(Vec<TypeRef<M>>),
199    /// These fields.
200    Named(Vec<Field<M>>),
201}
202
203/// A Tool's declaration.
204#[derive(Clone, Debug, PartialEq, Eq)]
205pub struct FlowDeclaration<M = String> {
206    /// Its name.
207    pub name: String,
208    /// Its type parameters.
209    pub generics: Vec<String>,
210    /// Its parameters, in order.
211    pub params: Vec<Param<M>>,
212    /// Its result type.
213    pub result: TypeRef<M>,
214}
215
216/// A Tool's parameter.
217#[derive(Clone, Debug, PartialEq, Eq)]
218pub struct Param<M = String> {
219    /// Its name.
220    pub name: String,
221    /// Its type.
222    pub ty: TypeRef<M>,
223    /// Its default, which makes it optional.
224    pub default: Option<Constant<M>>,
225}
226
227/// A type as a contract writes it.
228#[derive(Clone, Debug, PartialEq, Eq)]
229pub enum TypeRef<M = String> {
230    /// A named type, through the import bound to `module` when another
231    /// module declares it, applied to `args`.
232    Named {
233        /// The import binding that qualifies it.
234        module: Option<M>,
235        /// Its name.
236        name: String,
237        /// Its type arguments.
238        args: Vec<TypeRef<M>>,
239    },
240    /// A tuple of these types.
241    Tuple(Vec<TypeRef<M>>),
242}
243
244impl<M> TypeRef<M> {
245    /// The type `name`, unqualified and applied to nothing.
246    #[must_use]
247    pub fn named(name: &str) -> TypeRef<M> {
248        TypeRef::applied(name, Vec::new())
249    }
250
251    /// The type `name`, unqualified, applied to `args`.
252    #[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    /// The type `name` declared by the module bound to `module`.
262    #[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/// A parameter's default: a constant of the parameter's type.
273#[derive(Clone, Debug, PartialEq, Eq)]
274pub enum Constant<M = String> {
275    /// `None`.
276    None,
277    /// `Some` of a constant.
278    Some(Box<Constant<M>>),
279    /// `true` or `false`.
280    Bool(bool),
281    /// An integer, such as `-5`.
282    Int(Int),
283    /// A decimal number, written with a point, such as `1.5` or `2.0`.
284    Decimal(Decimal),
285    /// A text, written as a literal with the escapes it needs.
286    Text(String),
287    /// A tuple of constants.
288    Tuple(Vec<Constant<M>>),
289    /// A payload-free constructor, such as `Ready`.
290    Constructor(String),
291    /// A newtype's constructor applied to a constant of its base.
292    Applied {
293        /// The newtype.
294        newtype: TypeRef<M>,
295        /// The constant it holds.
296        value: Box<Constant<M>>,
297    },
298}
299
300impl<M> Item<M> {
301    /// The item with each type's module, as [`TypeRef::qualify`] says.
302    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    /// The declaration with each type's module, as [`TypeRef::qualify`]
313    /// says.
314    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    /// The type with each module that qualifies a name in it replaced by
388    /// what `module` gives for it: the import binding it is written
389    /// through, or `None` to write the name bare.
390    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    /// The constant with each type in it qualified as [`TypeRef::qualify`]
410    /// says.
411    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/// The text of `module`, in the one layout every contract has.
432#[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/// The text of `item`: its doc comment, its origin line and its
453/// declaration, ending its last line.
454#[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 &param.default {
529            Some(default) => format!(
530                "{}: {} = {}",
531                param.name,
532                type_ref(&param.ty),
533                constant(default)
534            ),
535            None => format!("{}: {}", param.name, type_ref(&param.ty)),
536        })
537        .collect();
538    let _ = write!(out, "({}) -> {}", params.join(", "), type_ref(&flow.result));
539}
540
541/// `<A, B>` after a declared name, when it has parameters.
542fn names(out: &mut String, names: &[String]) {
543    if !names.is_empty() {
544        let _ = write!(out, "<{}>", names.join(", "));
545    }
546}
547
548/// The text of `ty`.
549#[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/// The text of `constant`.
572#[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
592/// `value` as a decimal literal, which has digits on both sides of its
593/// point: `2.0` for two, `0.05` for a twentieth.
594fn 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
603/// `text` as a Flow text literal, with the escapes it needs.
604fn 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
625/// Writes `text` as doc comment lines, each indented by `indent`. It is
626/// split at every line end it holds, a carriage return, line or paragraph
627/// separator, or next-line control included, each line's trailing space
628/// dropped, and any other character [`not_in_a_comment`] refuses escaped,
629/// so no part of it leaves its doc comment.
630fn 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    // A line end closing the text ends its last line; it starts no other.
637    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/// Whether `ch` may not stand as it is in a comment line of generated
648/// source: a control character, which may end the line or rewrite the
649/// terminal that shows it, a line or paragraph separator, which an editor
650/// shows as a line end, or a bidirectional control, which `grammar.md`
651/// refuses anywhere.
652#[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/// `text` with every character [`not_in_a_comment`] refuses written as its
668/// `\u{...}` escape, so it stays on one comment line and shows what it
669/// holds. A tab is kept: it is whitespace in a comment.
670#[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}