Skip to main content

unitype_codegen/
lib.rs

1//! Writing the symbolic types out in a real language.
2//!
3//! A backend takes a checked workspace and produces files: type declarations
4//! you can import, function skeletons to fill in, and a harness that makes a
5//! filled-in file reachable as a proof without anyone writing glue.
6//!
7//! # What the backends share and what they do not
8//!
9//! How a type is *spelled* is data — it lives in that language's profile, along
10//! with its reserved words and its caveats. What differs between backends is
11//! how a *declaration* is written, because a TypeScript interface, a Python
12//! dataclass, and a Rust struct genuinely are three different things. So the
13//! spelling is shared and the declaring is not, which is roughly where the real
14//! difference between languages sits.
15//!
16//! # Generated code has to be boring
17//!
18//! Output is deterministic: sorted, stably ordered, no timestamps, no host
19//! names, no counters. Generating twice from an unchanged workspace produces
20//! byte-identical files. Generated code gets committed and diffed, and a file
21//! that appears to change when nothing did makes every diff worthless.
22
23#![forbid(unsafe_code)]
24#![warn(missing_docs)]
25
26pub mod haskell;
27pub mod literal;
28pub mod python;
29pub mod rust;
30pub mod typescript;
31pub mod writer;
32
33use std::path::PathBuf;
34
35use unitype_core::check::CheckedWorkspace;
36use unitype_core::ir::{Expr, Type, TypeDef, TypeParamDecl, TypeRef, Universe};
37use unitype_core::lang::ProfileError;
38use unitype_core::{Ident, QualifiedName};
39
40pub use writer::CodeWriter;
41
42/// A file a backend produced.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct GeneratedFile {
45    /// Where it goes, relative to wherever generation was pointed.
46    pub path: PathBuf,
47    /// What is in it.
48    pub contents: String,
49}
50
51/// What to generate.
52#[derive(Clone, Debug)]
53pub struct GenOptions {
54    /// Only these universes, or all of them.
55    pub universes: Option<Vec<Ident>>,
56    /// Emit skeletons for signatures nothing proves yet.
57    pub stubs: bool,
58    /// Emit the harness that makes a filled-in file reachable as a proof.
59    pub harness: bool,
60    /// Put a header on each file saying where it came from.
61    pub header: bool,
62}
63
64impl Default for GenOptions {
65    fn default() -> Self {
66        Self {
67            universes: None,
68            stubs: true,
69            harness: true,
70            header: true,
71        }
72    }
73}
74
75/// Why generation failed.
76#[derive(thiserror::Error, Debug)]
77pub enum GenError {
78    /// No profile ships for that language.
79    #[error(transparent)]
80    Profile(#[from] ProfileError),
81    /// The workspace asked for something this backend cannot write.
82    #[error("{language} cannot express {what}: {detail}")]
83    Unsupported {
84        /// The target language.
85        language: String,
86        /// What could not be written.
87        what: String,
88        /// Why not.
89        detail: String,
90    },
91}
92
93/// A target language this can generate for.
94pub trait Backend {
95    /// What this backend is called on a command line.
96    fn id(&self) -> &'static str;
97
98    /// The file extension it produces.
99    fn extension(&self) -> &'static str;
100
101    /// Writes out a whole workspace.
102    fn generate(
103        &self,
104        ws: &CheckedWorkspace,
105        options: &GenOptions,
106    ) -> Result<Vec<GeneratedFile>, GenError>;
107}
108
109/// The backend for a language, if this build has one.
110pub fn backend(language: &str) -> Option<Box<dyn Backend>> {
111    match language {
112        "typescript" | "ts" => Some(Box::new(typescript::TypeScript)),
113        "python" | "py" => Some(Box::new(python::Python)),
114        "rust" | "rs" => Some(Box::new(rust::Rust)),
115        "haskell" | "hs" => Some(Box::new(haskell::Haskell)),
116        _ => None,
117    }
118}
119
120/// How a language builds the things a typed literal needs.
121///
122/// Kept beside the backends because it is the same knowledge: what a struct
123/// looks like when you make one, and what a variant is called.
124pub fn constructors(language: &str) -> Option<literal::Constructors> {
125    match language {
126        "typescript" | "ts" => Some(literal::Constructors {
127            record: |_name, fields| {
128                // TypeScript has no constructor to call: an interface is
129                // satisfied by an object literal.
130                let parts: Vec<String> = fields
131                    .iter()
132                    .map(|(name, value)| format!("{name}: {value}"))
133                    .collect();
134                format!("{{ {} }}", parts.join(", "))
135            },
136            variant: |_name, tag, payload| match payload {
137                Some(value) => format!("{{ $tag: {tag:?}, value: {value} }}"),
138                None => format!("{{ $tag: {tag:?} }}"),
139            },
140            plain: typescript::literal,
141            tuple: |parts| format!("[{}]", parts.join(", ")),
142            typed: None,
143        }),
144        "python" | "py" => Some(literal::Constructors {
145            record: |name, fields| {
146                let parts: Vec<String> = fields
147                    .iter()
148                    .map(|(field, value)| format!("{field}={value}"))
149                    .collect();
150                format!("{name}({})", parts.join(", "))
151            },
152            // An enum is a TypedDict here, so a variant is written the way it
153            // arrives rather than constructed.
154            variant: |_name, tag, payload| match payload {
155                Some(value) => format!("{{\"$tag\": {tag:?}, \"value\": {value}}}"),
156                None => format!("{{\"$tag\": {tag:?}}}"),
157            },
158            plain: python::literal,
159            tuple: literal::parenthesised,
160            typed: None,
161        }),
162        "rust" | "rs" => Some(literal::Constructors {
163            record: |name, fields| {
164                let parts: Vec<String> = fields
165                    .iter()
166                    .map(|(field, value)| format!("{field}: {value}"))
167                    .collect();
168                format!("{name} {{ {} }}", parts.join(", "))
169            },
170            variant: |name, tag, payload| match payload {
171                Some(value) => format!("{name}::{tag}({value})"),
172                None => format!("{name}::{tag}"),
173            },
174            plain: rust::literal,
175            tuple: literal::parenthesised,
176            typed: None,
177        }),
178        "haskell" | "hs" => Some(literal::Constructors {
179            record: haskell::record,
180            variant: haskell::variant,
181            plain: haskell::literal,
182            // Haskell has no one-element tuple, so there is no `(a,)` to write.
183            // Unreached in practice: `typed` below writes tuples itself.
184            tuple: |parts| format!("({})", parts.join(", ")),
185            // Fields are named after the type that declares them, and a value
186            // that is there has to be said to be, so the walk is its own.
187            typed: Some(haskell::typed_literal),
188        }),
189        _ => None,
190    }
191}
192
193/// Every backend this build ships.
194pub fn backends() -> Vec<Box<dyn Backend>> {
195    ["typescript", "python", "rust", "haskell"]
196        .into_iter()
197        .filter_map(backend)
198        .collect()
199}
200
201/// The universes to write out, in a settled order.
202pub(crate) fn selected<'a>(ws: &'a CheckedWorkspace, options: &GenOptions) -> Vec<&'a Universe> {
203    let mut chosen: Vec<&Universe> = ws
204        .workspace()
205        .universes
206        .iter()
207        .filter(|u| {
208            options
209                .universes
210                .as_ref()
211                .is_none_or(|wanted| wanted.contains(&u.name))
212        })
213        .collect();
214    chosen.sort_by(|a, b| a.name.cmp(&b.name));
215    chosen
216}
217
218/// Refuses a workspace that is generic over a type constructor.
219///
220/// A parameter standing for a constructor, and every application of one, has
221/// no spelling in the languages generated here, so writing one would mean
222/// guessing what it is. Each backend asks this before it writes a line, so a
223/// declaration of that kind fails by name rather than producing code that
224/// reads the wrong way.
225pub(crate) fn refuse_higher_order(
226    ws: &CheckedWorkspace,
227    options: &GenOptions,
228    language: &str,
229) -> Result<(), GenError> {
230    let refuse = |what: String| GenError::Unsupported {
231        language: language.into(),
232        what,
233        detail: "it applies or passes a type constructor, which this backend does not write yet"
234            .into(),
235    };
236    for universe in selected(ws, options) {
237        for def in &universe.types {
238            let generic = def.params().iter().any(TypeParamDecl::is_higher_order);
239            if generic || def_types(def).into_iter().any(is_higher_order) {
240                return Err(refuse(format!("`{}::{}`", universe.name, def.name())));
241            }
242        }
243        for sig in &universe.functions {
244            let mut uses = sig.params_decl.iter().any(TypeParamDecl::is_higher_order)
245                || sig.params.iter().any(|p| is_higher_order(&p.ty))
246                || is_higher_order(&sig.ret);
247            if let Some(body) = &sig.body {
248                body.walk(&mut |e| {
249                    if let Expr::Fold { ty: Some(ty), .. } = e {
250                        uses |= is_higher_order(ty);
251                    }
252                });
253            }
254            if uses {
255                return Err(refuse(format!("`{}::{}`", universe.name, sig.name)));
256            }
257        }
258    }
259    Ok(())
260}
261
262/// Whether a type applies or passes a type constructor anywhere inside it.
263fn is_higher_order(ty: &Type) -> bool {
264    matches!(ty, Type::Apply { .. } | Type::Constructor { .. })
265        || ty.children().into_iter().any(is_higher_order)
266}
267
268/// The types a declaration is built from, for checking what they mention.
269fn def_types(def: &TypeDef) -> Vec<&Type> {
270    match def {
271        TypeDef::Struct(d) => d.fields.iter().map(|f| &f.ty).collect(),
272        TypeDef::Enum(d) => d.variants.iter().map(|v| &v.payload).collect(),
273        TypeDef::Alias(d) => vec![&d.target],
274        TypeDef::Interface(d) => d.fields.iter().map(|f| &f.ty).collect(),
275    }
276}
277
278/// Whether any body in a universe contains an expression `wanted` picks out.
279///
280/// A backend that needs a helper or an import for some form asks this, so a
281/// module that never uses the form does not carry what it would have needed.
282pub(crate) fn bodies_use(universe: &Universe, wanted: impl Fn(&Expr) -> bool) -> bool {
283    universe.functions.iter().any(|sig| {
284        let mut found = false;
285        if let Some(body) = &sig.body {
286            body.walk(&mut |e| found |= wanted(e));
287        }
288        found
289    })
290}
291
292/// Declarations ordered so that nothing is mentioned before it exists.
293///
294/// Python needs this — a class cannot inherit from one defined later in the
295/// file — and it costs the other targets nothing. Ties are broken by name so
296/// that two runs agree.
297pub(crate) fn ordered_defs(universe: &Universe) -> Vec<&TypeDef> {
298    let mut pending: Vec<&TypeDef> = universe.types.iter().collect();
299    pending.sort_by(|a, b| a.name().cmp(b.name()));
300
301    let mut placed: Vec<Ident> = Vec::new();
302    let mut out: Vec<&TypeDef> = Vec::with_capacity(pending.len());
303
304    while !pending.is_empty() {
305        let (ready, waiting): (Vec<&TypeDef>, Vec<&TypeDef>) =
306            pending.into_iter().partition(|def| {
307                requires(universe, def)
308                    .iter()
309                    .all(|needed| placed.contains(needed))
310            });
311
312        // The checker has already refused inheritance cycles, so this cannot
313        // happen for a workspace that came through the front door. If something
314        // gets here anyway, emitting it is better than looping.
315        if ready.is_empty() {
316            out.extend(waiting);
317            break;
318        }
319
320        placed.extend(ready.iter().map(|d| d.name().clone()));
321        out.extend(ready);
322        pending = waiting;
323    }
324    out
325}
326
327/// What a declaration is built out of, within its own universe.
328///
329/// Only what it *extends* or, for an alias, what it stands for. A field merely
330/// mentioning another type does not constrain the order in any target here.
331fn requires(universe: &Universe, def: &TypeDef) -> Vec<Ident> {
332    let mut out = Vec::new();
333    let mut take = |r: &TypeRef| {
334        if r.universe.as_ref() == Some(&universe.name) {
335            out.push(r.name.clone());
336        }
337    };
338    match def {
339        TypeDef::Struct(d) => {
340            d.extends.iter().for_each(&mut take);
341            d.implements.iter().for_each(&mut take);
342        }
343        TypeDef::Interface(d) => d.extends.iter().for_each(&mut take),
344        TypeDef::Alias(d) => refs_in(&d.target, &mut take),
345        TypeDef::Enum(_) => {}
346    }
347    out
348}
349
350/// Every reference a type makes, at any depth.
351fn refs_in(ty: &Type, f: &mut impl FnMut(&TypeRef)) {
352    if let Type::Ref(r) = ty {
353        f(r);
354    }
355    for child in ty.children() {
356        refs_in(child, f);
357    }
358}
359
360/// The header put at the top of a generated file.
361///
362/// Names the universe and its structural address, so that a file can be traced
363/// back to what it was generated from — and so that regenerating an unchanged
364/// universe produces an unchanged header.
365pub(crate) fn header(comment: &str, universe: &Universe, ws: &CheckedWorkspace) -> Vec<String> {
366    let mut addresses: Vec<String> = universe
367        .types
368        .iter()
369        .filter_map(|d| {
370            let name = QualifiedName::new(universe.name.clone(), d.name().clone());
371            Some(format!("{}: {}", d.name(), ws.shape_hash(&name)?.short()))
372        })
373        .collect();
374    addresses.sort();
375
376    let mut out = vec![
377        format!(
378            "{comment} Generated by unitype from universe `{}`.",
379            universe.name
380        ),
381        format!("{comment} Do not edit; edit the universe and generate again."),
382    ];
383    if !addresses.is_empty() {
384        out.push(comment.trim_end().to_string());
385        out.push(format!("{comment} Structural addresses:"));
386        out.extend(addresses.iter().map(|a| format!("{comment}   {a}")));
387    }
388    out
389}
390
391/// A universe with something generic of every kind, for the backends' tests:
392/// a bounded parameter, a generic parent, a generic interface implemented, an
393/// enum and an alias over two parameters, a parameter nothing uses, and
394/// signatures with and without a body.
395#[cfg(test)]
396pub(crate) const GENERIC: &str = r#"{"universes":[{"name":"demo","types":[
397    {"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
398    {"k":"interface","name":"Holder","params":[{"name":"T"}],
399     "fields":[{"name":"held","ty":{"k":"param","name":"T"}}]},
400    {"k":"struct","name":"Box","params":[{"name":"T"}],
401     "fields":[{"name":"value","ty":{"k":"param","name":"T"}}]},
402    {"k":"struct","name":"Labelled","params":[{"name":"T"},{"name":"N","bounds":["Named"]}],
403     "extends":{"name":"Box","args":[{"k":"param","name":"T"}]},
404     "fields":[{"name":"label","ty":{"k":"param","name":"N"}}]},
405    {"k":"struct","name":"Tagged","params":[{"name":"T"}],
406     "implements":[{"name":"Holder","args":[{"k":"param","name":"T"}]}],
407     "fields":[{"name":"held","ty":{"k":"param","name":"T"}},{"name":"tag","ty":"str"}]},
408    {"k":"enum","name":"Outcome","params":[{"name":"T"},{"name":"E"}],"variants":[
409        {"name":"Ok","payload":{"k":"param","name":"T"}},
410        {"name":"Err","payload":{"k":"param","name":"E"}},
411        {"name":"Pending"}]},
412    {"k":"alias","name":"Swap","params":[{"name":"A"},{"name":"B"}],
413     "target":{"k":"tuple","items":[{"k":"param","name":"B"},{"k":"param","name":"A"}]}},
414    {"k":"struct","name":"Ghost","params":[{"name":"T"}],"fields":[{"name":"id","ty":"str"}]},
415    {"k":"struct","name":"Uses","fields":[
416        {"name":"ghost","ty":{"k":"ref","name":"Ghost","args":["i64"]}},
417        {"name":"outcome","ty":{"k":"ref","name":"Outcome","args":["i64","str"]}},
418        {"name":"swapped","ty":{"k":"ref","name":"Swap","args":["i64","str"]}}]}],
419  "functions":[
420    {"name":"pick","params_decl":[{"name":"T","bounds":["Named"]}],
421     "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
422     "ret":{"k":"optional","of":{"k":"param","name":"T"}}},
423    {"name":"konst","params_decl":[{"name":"A"},{"name":"B"}],
424     "params":[{"name":"x","ty":{"k":"param","name":"A"}},{"name":"y","ty":{"k":"param","name":"B"}}],
425     "ret":{"k":"param","name":"A"},"body":{"k":"var","name":"x"}}]}]}"#;