unitype-codegen 0.2.0

TypeScript, Python, Rust, and Haskell code generation backends for unitype
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Writing the symbolic types out in a real language.
//!
//! A backend takes a checked workspace and produces files: type declarations
//! you can import, function skeletons to fill in, and a harness that makes a
//! filled-in file reachable as a proof without anyone writing glue.
//!
//! # What the backends share and what they do not
//!
//! How a type is *spelled* is data — it lives in that language's profile, along
//! with its reserved words and its caveats. What differs between backends is
//! how a *declaration* is written, because a TypeScript interface, a Python
//! dataclass, and a Rust struct genuinely are three different things. So the
//! spelling is shared and the declaring is not, which is roughly where the real
//! difference between languages sits.
//!
//! # Generated code has to be boring
//!
//! Output is deterministic: sorted, stably ordered, no timestamps, no host
//! names, no counters. Generating twice from an unchanged workspace produces
//! byte-identical files. Generated code gets committed and diffed, and a file
//! that appears to change when nothing did makes every diff worthless.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

pub mod haskell;
pub mod literal;
pub mod python;
pub mod rust;
pub mod typescript;
pub mod writer;

use std::path::PathBuf;

use unitype_core::check::CheckedWorkspace;
use unitype_core::ir::{Expr, Type, TypeDef, TypeParamDecl, TypeRef, Universe};
use unitype_core::lang::ProfileError;
use unitype_core::{Ident, QualifiedName};

pub use writer::CodeWriter;

/// A file a backend produced.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GeneratedFile {
    /// Where it goes, relative to wherever generation was pointed.
    pub path: PathBuf,
    /// What is in it.
    pub contents: String,
}

/// What to generate.
#[derive(Clone, Debug)]
pub struct GenOptions {
    /// Only these universes, or all of them.
    pub universes: Option<Vec<Ident>>,
    /// Emit skeletons for signatures nothing proves yet.
    pub stubs: bool,
    /// Emit the harness that makes a filled-in file reachable as a proof.
    pub harness: bool,
    /// Put a header on each file saying where it came from.
    pub header: bool,
}

impl Default for GenOptions {
    fn default() -> Self {
        Self {
            universes: None,
            stubs: true,
            harness: true,
            header: true,
        }
    }
}

/// Why generation failed.
#[derive(thiserror::Error, Debug)]
pub enum GenError {
    /// No profile ships for that language.
    #[error(transparent)]
    Profile(#[from] ProfileError),
    /// The workspace asked for something this backend cannot write.
    #[error("{language} cannot express {what}: {detail}")]
    Unsupported {
        /// The target language.
        language: String,
        /// What could not be written.
        what: String,
        /// Why not.
        detail: String,
    },
}

/// A target language this can generate for.
pub trait Backend {
    /// What this backend is called on a command line.
    fn id(&self) -> &'static str;

    /// The file extension it produces.
    fn extension(&self) -> &'static str;

    /// Writes out a whole workspace.
    fn generate(
        &self,
        ws: &CheckedWorkspace,
        options: &GenOptions,
    ) -> Result<Vec<GeneratedFile>, GenError>;
}

/// The backend for a language, if this build has one.
pub fn backend(language: &str) -> Option<Box<dyn Backend>> {
    match language {
        "typescript" | "ts" => Some(Box::new(typescript::TypeScript)),
        "python" | "py" => Some(Box::new(python::Python)),
        "rust" | "rs" => Some(Box::new(rust::Rust)),
        "haskell" | "hs" => Some(Box::new(haskell::Haskell)),
        _ => None,
    }
}

/// How a language builds the things a typed literal needs.
///
/// Kept beside the backends because it is the same knowledge: what a struct
/// looks like when you make one, and what a variant is called.
pub fn constructors(language: &str) -> Option<literal::Constructors> {
    match language {
        "typescript" | "ts" => Some(literal::Constructors {
            record: |_name, fields| {
                // TypeScript has no constructor to call: an interface is
                // satisfied by an object literal.
                let parts: Vec<String> = fields
                    .iter()
                    .map(|(name, value)| format!("{name}: {value}"))
                    .collect();
                format!("{{ {} }}", parts.join(", "))
            },
            variant: |_name, tag, payload| match payload {
                Some(value) => format!("{{ $tag: {tag:?}, value: {value} }}"),
                None => format!("{{ $tag: {tag:?} }}"),
            },
            plain: typescript::literal,
            tuple: |parts| format!("[{}]", parts.join(", ")),
            typed: None,
        }),
        "python" | "py" => Some(literal::Constructors {
            record: |name, fields| {
                let parts: Vec<String> = fields
                    .iter()
                    .map(|(field, value)| format!("{field}={value}"))
                    .collect();
                format!("{name}({})", parts.join(", "))
            },
            // An enum is a TypedDict here, so a variant is written the way it
            // arrives rather than constructed.
            variant: |_name, tag, payload| match payload {
                Some(value) => format!("{{\"$tag\": {tag:?}, \"value\": {value}}}"),
                None => format!("{{\"$tag\": {tag:?}}}"),
            },
            plain: python::literal,
            tuple: literal::parenthesised,
            typed: None,
        }),
        "rust" | "rs" => Some(literal::Constructors {
            record: |name, fields| {
                let parts: Vec<String> = fields
                    .iter()
                    .map(|(field, value)| format!("{field}: {value}"))
                    .collect();
                format!("{name} {{ {} }}", parts.join(", "))
            },
            variant: |name, tag, payload| match payload {
                Some(value) => format!("{name}::{tag}({value})"),
                None => format!("{name}::{tag}"),
            },
            plain: rust::literal,
            tuple: literal::parenthesised,
            typed: None,
        }),
        "haskell" | "hs" => Some(literal::Constructors {
            record: haskell::record,
            variant: haskell::variant,
            plain: haskell::literal,
            // Haskell has no one-element tuple, so there is no `(a,)` to write.
            // Unreached in practice: `typed` below writes tuples itself.
            tuple: |parts| format!("({})", parts.join(", ")),
            // Fields are named after the type that declares them, and a value
            // that is there has to be said to be, so the walk is its own.
            typed: Some(haskell::typed_literal),
        }),
        _ => None,
    }
}

/// Every backend this build ships.
pub fn backends() -> Vec<Box<dyn Backend>> {
    ["typescript", "python", "rust", "haskell"]
        .into_iter()
        .filter_map(backend)
        .collect()
}

/// The universes to write out, in a settled order.
pub(crate) fn selected<'a>(ws: &'a CheckedWorkspace, options: &GenOptions) -> Vec<&'a Universe> {
    let mut chosen: Vec<&Universe> = ws
        .workspace()
        .universes
        .iter()
        .filter(|u| {
            options
                .universes
                .as_ref()
                .is_none_or(|wanted| wanted.contains(&u.name))
        })
        .collect();
    chosen.sort_by(|a, b| a.name.cmp(&b.name));
    chosen
}

/// Refuses a workspace that is generic over a type constructor.
///
/// A parameter standing for a constructor, and every application of one, has
/// no spelling in the languages generated here, so writing one would mean
/// guessing what it is. Each backend asks this before it writes a line, so a
/// declaration of that kind fails by name rather than producing code that
/// reads the wrong way.
pub(crate) fn refuse_higher_order(
    ws: &CheckedWorkspace,
    options: &GenOptions,
    language: &str,
) -> Result<(), GenError> {
    let refuse = |what: String| GenError::Unsupported {
        language: language.into(),
        what,
        detail: "it applies or passes a type constructor, which this backend does not write yet"
            .into(),
    };
    for universe in selected(ws, options) {
        for def in &universe.types {
            let generic = def.params().iter().any(TypeParamDecl::is_higher_order);
            if generic || def_types(def).into_iter().any(is_higher_order) {
                return Err(refuse(format!("`{}::{}`", universe.name, def.name())));
            }
        }
        for sig in &universe.functions {
            let mut uses = sig.params_decl.iter().any(TypeParamDecl::is_higher_order)
                || sig.params.iter().any(|p| is_higher_order(&p.ty))
                || is_higher_order(&sig.ret);
            if let Some(body) = &sig.body {
                body.walk(&mut |e| {
                    if let Expr::Fold { ty: Some(ty), .. } = e {
                        uses |= is_higher_order(ty);
                    }
                });
            }
            if uses {
                return Err(refuse(format!("`{}::{}`", universe.name, sig.name)));
            }
        }
    }
    Ok(())
}

/// Whether a type applies or passes a type constructor anywhere inside it.
fn is_higher_order(ty: &Type) -> bool {
    matches!(ty, Type::Apply { .. } | Type::Constructor { .. })
        || ty.children().into_iter().any(is_higher_order)
}

/// The types a declaration is built from, for checking what they mention.
fn def_types(def: &TypeDef) -> Vec<&Type> {
    match def {
        TypeDef::Struct(d) => d.fields.iter().map(|f| &f.ty).collect(),
        TypeDef::Enum(d) => d.variants.iter().map(|v| &v.payload).collect(),
        TypeDef::Alias(d) => vec![&d.target],
        TypeDef::Interface(d) => d.fields.iter().map(|f| &f.ty).collect(),
    }
}

/// Whether any body in a universe contains an expression `wanted` picks out.
///
/// A backend that needs a helper or an import for some form asks this, so a
/// module that never uses the form does not carry what it would have needed.
pub(crate) fn bodies_use(universe: &Universe, wanted: impl Fn(&Expr) -> bool) -> bool {
    universe.functions.iter().any(|sig| {
        let mut found = false;
        if let Some(body) = &sig.body {
            body.walk(&mut |e| found |= wanted(e));
        }
        found
    })
}

/// Declarations ordered so that nothing is mentioned before it exists.
///
/// Python needs this — a class cannot inherit from one defined later in the
/// file — and it costs the other targets nothing. Ties are broken by name so
/// that two runs agree.
pub(crate) fn ordered_defs(universe: &Universe) -> Vec<&TypeDef> {
    let mut pending: Vec<&TypeDef> = universe.types.iter().collect();
    pending.sort_by(|a, b| a.name().cmp(b.name()));

    let mut placed: Vec<Ident> = Vec::new();
    let mut out: Vec<&TypeDef> = Vec::with_capacity(pending.len());

    while !pending.is_empty() {
        let (ready, waiting): (Vec<&TypeDef>, Vec<&TypeDef>) =
            pending.into_iter().partition(|def| {
                requires(universe, def)
                    .iter()
                    .all(|needed| placed.contains(needed))
            });

        // The checker has already refused inheritance cycles, so this cannot
        // happen for a workspace that came through the front door. If something
        // gets here anyway, emitting it is better than looping.
        if ready.is_empty() {
            out.extend(waiting);
            break;
        }

        placed.extend(ready.iter().map(|d| d.name().clone()));
        out.extend(ready);
        pending = waiting;
    }
    out
}

/// What a declaration is built out of, within its own universe.
///
/// Only what it *extends* or, for an alias, what it stands for. A field merely
/// mentioning another type does not constrain the order in any target here.
fn requires(universe: &Universe, def: &TypeDef) -> Vec<Ident> {
    let mut out = Vec::new();
    let mut take = |r: &TypeRef| {
        if r.universe.as_ref() == Some(&universe.name) {
            out.push(r.name.clone());
        }
    };
    match def {
        TypeDef::Struct(d) => {
            d.extends.iter().for_each(&mut take);
            d.implements.iter().for_each(&mut take);
        }
        TypeDef::Interface(d) => d.extends.iter().for_each(&mut take),
        TypeDef::Alias(d) => refs_in(&d.target, &mut take),
        TypeDef::Enum(_) => {}
    }
    out
}

/// Every reference a type makes, at any depth.
fn refs_in(ty: &Type, f: &mut impl FnMut(&TypeRef)) {
    if let Type::Ref(r) = ty {
        f(r);
    }
    for child in ty.children() {
        refs_in(child, f);
    }
}

/// The header put at the top of a generated file.
///
/// Names the universe and its structural address, so that a file can be traced
/// back to what it was generated from — and so that regenerating an unchanged
/// universe produces an unchanged header.
pub(crate) fn header(comment: &str, universe: &Universe, ws: &CheckedWorkspace) -> Vec<String> {
    let mut addresses: Vec<String> = universe
        .types
        .iter()
        .filter_map(|d| {
            let name = QualifiedName::new(universe.name.clone(), d.name().clone());
            Some(format!("{}: {}", d.name(), ws.shape_hash(&name)?.short()))
        })
        .collect();
    addresses.sort();

    let mut out = vec![
        format!(
            "{comment} Generated by unitype from universe `{}`.",
            universe.name
        ),
        format!("{comment} Do not edit; edit the universe and generate again."),
    ];
    if !addresses.is_empty() {
        out.push(comment.trim_end().to_string());
        out.push(format!("{comment} Structural addresses:"));
        out.extend(addresses.iter().map(|a| format!("{comment}   {a}")));
    }
    out
}

/// A universe with something generic of every kind, for the backends' tests:
/// a bounded parameter, a generic parent, a generic interface implemented, an
/// enum and an alias over two parameters, a parameter nothing uses, and
/// signatures with and without a body.
#[cfg(test)]
pub(crate) const GENERIC: &str = r#"{"universes":[{"name":"demo","types":[
    {"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
    {"k":"interface","name":"Holder","params":[{"name":"T"}],
     "fields":[{"name":"held","ty":{"k":"param","name":"T"}}]},
    {"k":"struct","name":"Box","params":[{"name":"T"}],
     "fields":[{"name":"value","ty":{"k":"param","name":"T"}}]},
    {"k":"struct","name":"Labelled","params":[{"name":"T"},{"name":"N","bounds":["Named"]}],
     "extends":{"name":"Box","args":[{"k":"param","name":"T"}]},
     "fields":[{"name":"label","ty":{"k":"param","name":"N"}}]},
    {"k":"struct","name":"Tagged","params":[{"name":"T"}],
     "implements":[{"name":"Holder","args":[{"k":"param","name":"T"}]}],
     "fields":[{"name":"held","ty":{"k":"param","name":"T"}},{"name":"tag","ty":"str"}]},
    {"k":"enum","name":"Outcome","params":[{"name":"T"},{"name":"E"}],"variants":[
        {"name":"Ok","payload":{"k":"param","name":"T"}},
        {"name":"Err","payload":{"k":"param","name":"E"}},
        {"name":"Pending"}]},
    {"k":"alias","name":"Swap","params":[{"name":"A"},{"name":"B"}],
     "target":{"k":"tuple","items":[{"k":"param","name":"B"},{"k":"param","name":"A"}]}},
    {"k":"struct","name":"Ghost","params":[{"name":"T"}],"fields":[{"name":"id","ty":"str"}]},
    {"k":"struct","name":"Uses","fields":[
        {"name":"ghost","ty":{"k":"ref","name":"Ghost","args":["i64"]}},
        {"name":"outcome","ty":{"k":"ref","name":"Outcome","args":["i64","str"]}},
        {"name":"swapped","ty":{"k":"ref","name":"Swap","args":["i64","str"]}}]}],
  "functions":[
    {"name":"pick","params_decl":[{"name":"T","bounds":["Named"]}],
     "params":[{"name":"xs","ty":{"k":"list","of":{"k":"param","name":"T"}}}],
     "ret":{"k":"optional","of":{"k":"param","name":"T"}}},
    {"name":"konst","params_decl":[{"name":"A"},{"name":"B"}],
     "params":[{"name":"x","ty":{"k":"param","name":"A"}},{"name":"y","ty":{"k":"param","name":"B"}}],
     "ret":{"k":"param","name":"A"},"body":{"k":"var","name":"x"}}]}]}"#;