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 literal;
27pub mod python;
28pub mod rust;
29pub mod typescript;
30pub mod writer;
31
32use std::path::PathBuf;
33
34use unitype_core::check::CheckedWorkspace;
35use unitype_core::ir::{Expr, Type, TypeDef, TypeRef, Universe};
36use unitype_core::lang::ProfileError;
37use unitype_core::{Ident, QualifiedName};
38
39pub use writer::CodeWriter;
40
41/// A file a backend produced.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct GeneratedFile {
44    /// Where it goes, relative to wherever generation was pointed.
45    pub path: PathBuf,
46    /// What is in it.
47    pub contents: String,
48}
49
50/// What to generate.
51#[derive(Clone, Debug)]
52pub struct GenOptions {
53    /// Only these universes, or all of them.
54    pub universes: Option<Vec<Ident>>,
55    /// Emit skeletons for signatures nothing proves yet.
56    pub stubs: bool,
57    /// Emit the harness that makes a filled-in file reachable as a proof.
58    pub harness: bool,
59    /// Put a header on each file saying where it came from.
60    pub header: bool,
61}
62
63impl Default for GenOptions {
64    fn default() -> Self {
65        Self {
66            universes: None,
67            stubs: true,
68            harness: true,
69            header: true,
70        }
71    }
72}
73
74/// Why generation failed.
75#[derive(thiserror::Error, Debug)]
76pub enum GenError {
77    /// No profile ships for that language.
78    #[error(transparent)]
79    Profile(#[from] ProfileError),
80    /// The workspace asked for something this backend cannot write.
81    #[error("{language} cannot express {what}: {detail}")]
82    Unsupported {
83        /// The target language.
84        language: String,
85        /// What could not be written.
86        what: String,
87        /// Why not.
88        detail: String,
89    },
90}
91
92/// A target language this can generate for.
93pub trait Backend {
94    /// What this backend is called on a command line.
95    fn id(&self) -> &'static str;
96
97    /// The file extension it produces.
98    fn extension(&self) -> &'static str;
99
100    /// Writes out a whole workspace.
101    fn generate(
102        &self,
103        ws: &CheckedWorkspace,
104        options: &GenOptions,
105    ) -> Result<Vec<GeneratedFile>, GenError>;
106}
107
108/// The backend for a language, if this build has one.
109pub fn backend(language: &str) -> Option<Box<dyn Backend>> {
110    match language {
111        "typescript" | "ts" => Some(Box::new(typescript::TypeScript)),
112        "python" | "py" => Some(Box::new(python::Python)),
113        "rust" | "rs" => Some(Box::new(rust::Rust)),
114        _ => None,
115    }
116}
117
118/// How a language builds the things a typed literal needs.
119///
120/// Kept beside the backends because it is the same knowledge: what a struct
121/// looks like when you make one, and what a variant is called.
122pub fn constructors(language: &str) -> Option<literal::Constructors> {
123    match language {
124        "typescript" | "ts" => Some(literal::Constructors {
125            record: |_name, fields| {
126                // TypeScript has no constructor to call: an interface is
127                // satisfied by an object literal.
128                let parts: Vec<String> = fields
129                    .iter()
130                    .map(|(name, value)| format!("{name}: {value}"))
131                    .collect();
132                format!("{{ {} }}", parts.join(", "))
133            },
134            variant: |_name, tag, payload| match payload {
135                Some(value) => format!("{{ $tag: {tag:?}, value: {value} }}"),
136                None => format!("{{ $tag: {tag:?} }}"),
137            },
138            plain: typescript::literal,
139        }),
140        "python" | "py" => Some(literal::Constructors {
141            record: |name, fields| {
142                let parts: Vec<String> = fields
143                    .iter()
144                    .map(|(field, value)| format!("{field}={value}"))
145                    .collect();
146                format!("{name}({})", parts.join(", "))
147            },
148            // An enum is a TypedDict here, so a variant is written the way it
149            // arrives rather than constructed.
150            variant: |_name, tag, payload| match payload {
151                Some(value) => format!("{{\"$tag\": {tag:?}, \"value\": {value}}}"),
152                None => format!("{{\"$tag\": {tag:?}}}"),
153            },
154            plain: python::literal,
155        }),
156        "rust" | "rs" => Some(literal::Constructors {
157            record: |name, fields| {
158                let parts: Vec<String> = fields
159                    .iter()
160                    .map(|(field, value)| format!("{field}: {value}"))
161                    .collect();
162                format!("{name} {{ {} }}", parts.join(", "))
163            },
164            variant: |name, tag, payload| match payload {
165                Some(value) => format!("{name}::{tag}({value})"),
166                None => format!("{name}::{tag}"),
167            },
168            plain: rust::literal,
169        }),
170        _ => None,
171    }
172}
173
174/// Every backend this build ships.
175pub fn backends() -> Vec<Box<dyn Backend>> {
176    ["typescript", "python", "rust"]
177        .into_iter()
178        .filter_map(backend)
179        .collect()
180}
181
182/// The universes to write out, in a settled order.
183pub(crate) fn selected<'a>(ws: &'a CheckedWorkspace, options: &GenOptions) -> Vec<&'a Universe> {
184    let mut chosen: Vec<&Universe> = ws
185        .workspace()
186        .universes
187        .iter()
188        .filter(|u| {
189            options
190                .universes
191                .as_ref()
192                .is_none_or(|wanted| wanted.contains(&u.name))
193        })
194        .collect();
195    chosen.sort_by(|a, b| a.name.cmp(&b.name));
196    chosen
197}
198
199/// Whether any body in a universe contains an expression `wanted` picks out.
200///
201/// A backend that needs a helper or an import for some form asks this, so a
202/// module that never uses the form does not carry what it would have needed.
203pub(crate) fn bodies_use(universe: &Universe, wanted: impl Fn(&Expr) -> bool) -> bool {
204    universe.functions.iter().any(|sig| {
205        let mut found = false;
206        if let Some(body) = &sig.body {
207            body.walk(&mut |e| found |= wanted(e));
208        }
209        found
210    })
211}
212
213/// Declarations ordered so that nothing is mentioned before it exists.
214///
215/// Python needs this — a class cannot inherit from one defined later in the
216/// file — and it costs the other targets nothing. Ties are broken by name so
217/// that two runs agree.
218pub(crate) fn ordered_defs(universe: &Universe) -> Vec<&TypeDef> {
219    let mut pending: Vec<&TypeDef> = universe.types.iter().collect();
220    pending.sort_by(|a, b| a.name().cmp(b.name()));
221
222    let mut placed: Vec<Ident> = Vec::new();
223    let mut out: Vec<&TypeDef> = Vec::with_capacity(pending.len());
224
225    while !pending.is_empty() {
226        let (ready, waiting): (Vec<&TypeDef>, Vec<&TypeDef>) =
227            pending.into_iter().partition(|def| {
228                requires(universe, def)
229                    .iter()
230                    .all(|needed| placed.contains(needed))
231            });
232
233        // The checker has already refused inheritance cycles, so this cannot
234        // happen for a workspace that came through the front door. If something
235        // gets here anyway, emitting it is better than looping.
236        if ready.is_empty() {
237            out.extend(waiting);
238            break;
239        }
240
241        placed.extend(ready.iter().map(|d| d.name().clone()));
242        out.extend(ready);
243        pending = waiting;
244    }
245    out
246}
247
248/// What a declaration is built out of, within its own universe.
249///
250/// Only what it *extends* or, for an alias, what it stands for. A field merely
251/// mentioning another type does not constrain the order in any target here.
252fn requires(universe: &Universe, def: &TypeDef) -> Vec<Ident> {
253    let mut out = Vec::new();
254    let mut take = |r: &TypeRef| {
255        if r.universe.as_ref() == Some(&universe.name) {
256            out.push(r.name.clone());
257        }
258    };
259    match def {
260        TypeDef::Struct(d) => {
261            d.extends.iter().for_each(&mut take);
262            d.implements.iter().for_each(&mut take);
263        }
264        TypeDef::Interface(d) => d.extends.iter().for_each(&mut take),
265        TypeDef::Alias(d) => refs_in(&d.target, &mut take),
266        TypeDef::Enum(_) => {}
267    }
268    out
269}
270
271/// Every reference a type makes, at any depth.
272fn refs_in(ty: &Type, f: &mut impl FnMut(&TypeRef)) {
273    if let Type::Ref(r) = ty {
274        f(r);
275    }
276    for child in ty.children() {
277        refs_in(child, f);
278    }
279}
280
281/// The header put at the top of a generated file.
282///
283/// Names the universe and its structural address, so that a file can be traced
284/// back to what it was generated from — and so that regenerating an unchanged
285/// universe produces an unchanged header.
286pub(crate) fn header(comment: &str, universe: &Universe, ws: &CheckedWorkspace) -> Vec<String> {
287    let mut addresses: Vec<String> = universe
288        .types
289        .iter()
290        .filter_map(|d| {
291            let name = QualifiedName::new(universe.name.clone(), d.name().clone());
292            Some(format!("{}: {}", d.name(), ws.shape_hash(&name)?.short()))
293        })
294        .collect();
295    addresses.sort();
296
297    let mut out = vec![
298        format!(
299            "{comment} Generated by unitype from universe `{}`.",
300            universe.name
301        ),
302        format!("{comment} Do not edit; edit the universe and generate again."),
303    ];
304    if !addresses.is_empty() {
305        out.push(comment.trim_end().to_string());
306        out.push(format!("{comment} Structural addresses:"));
307        out.extend(addresses.iter().map(|a| format!("{comment}   {a}")));
308    }
309    out
310}
311
312/// A universe with something generic of every kind, for the backends' tests:
313/// a bounded parameter, a generic parent, a generic interface implemented, an
314/// enum and an alias over two parameters, a parameter nothing uses, and
315/// signatures with and without a body.
316#[cfg(test)]
317pub(crate) const GENERIC: &str = r#"{"universes":[{"name":"demo","types":[
318    {"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
319    {"k":"interface","name":"Holder","params":[{"name":"T"}],
320     "fields":[{"name":"held","ty":{"k":"param","name":"T"}}]},
321    {"k":"struct","name":"Box","params":[{"name":"T"}],
322     "fields":[{"name":"value","ty":{"k":"param","name":"T"}}]},
323    {"k":"struct","name":"Labelled","params":[{"name":"T"},{"name":"N","bounds":["Named"]}],
324     "extends":{"name":"Box","args":[{"k":"param","name":"T"}]},
325     "fields":[{"name":"label","ty":{"k":"param","name":"N"}}]},
326    {"k":"struct","name":"Tagged","params":[{"name":"T"}],
327     "implements":[{"name":"Holder","args":[{"k":"param","name":"T"}]}],
328     "fields":[{"name":"held","ty":{"k":"param","name":"T"}},{"name":"tag","ty":"str"}]},
329    {"k":"enum","name":"Outcome","params":[{"name":"T"},{"name":"E"}],"variants":[
330        {"name":"Ok","payload":{"k":"param","name":"T"}},
331        {"name":"Err","payload":{"k":"param","name":"E"}},
332        {"name":"Pending"}]},
333    {"k":"alias","name":"Swap","params":[{"name":"A"},{"name":"B"}],
334     "target":{"k":"tuple","items":[{"k":"param","name":"B"},{"k":"param","name":"A"}]}},
335    {"k":"struct","name":"Ghost","params":[{"name":"T"}],"fields":[{"name":"id","ty":"str"}]},
336    {"k":"struct","name":"Uses","fields":[
337        {"name":"ghost","ty":{"k":"ref","name":"Ghost","args":["i64"]}},
338        {"name":"outcome","ty":{"k":"ref","name":"Outcome","args":["i64","str"]}},
339        {"name":"swapped","ty":{"k":"ref","name":"Swap","args":["i64","str"]}}]}],
340  "functions":[
341    {"name":"pick","params_decl":[{"name":"T","bounds":["Named"]}],
342     "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
343     "ret":{"k":"optional","of":{"k":"param","name":"T"}}},
344    {"name":"konst","params_decl":[{"name":"A"},{"name":"B"}],
345     "params":[{"name":"x","ty":{"k":"param","name":"A"}},{"name":"y","ty":{"k":"param","name":"B"}}],
346     "ret":{"k":"param","name":"A"},"body":{"k":"var","name":"x"}}]}]}"#;