Skip to main content

unitype_codegen/
typescript.rs

1//! Writing a universe out as TypeScript.
2//!
3//! Structs become interfaces, inheritance becomes `extends`, and an enum
4//! becomes a discriminated union tagged the way the wire tags it. Nothing here
5//! invents a representation: what a generated interface describes is exactly
6//! what arrives over a pipe, which is what lets a TypeScript proof and a Rust
7//! proof of the same proposition agree without either being told about the
8//! other.
9//!
10//! Generic declarations and signatures keep their parameters, and a bound
11//! becomes `extends`: TypeScript is structural, so `T extends Named` says what
12//! the bound says, and several bounds are one intersection.
13
14use std::cell::RefCell;
15use std::collections::HashMap;
16
17use unitype_core::check::CheckedWorkspace;
18use unitype_core::ir::{
19    AliasDef, EnumDef, Expr, Field, FunctionSig, InterfaceDef, PrimOp, StructDef, Type, TypeDef,
20    TypeParamDecl, Universe,
21};
22use unitype_core::lang::{LanguageProfile, profile};
23use unitype_core::{Ident, QualifiedName};
24
25use crate::writer::CodeWriter;
26use crate::{
27    Backend, GenError, GenOptions, GeneratedFile, bodies_use, header, ordered_defs, selected,
28};
29
30/// The TypeScript backend.
31pub struct TypeScript;
32
33impl Backend for TypeScript {
34    fn id(&self) -> &'static str {
35        "typescript"
36    }
37
38    fn extension(&self) -> &'static str {
39        "ts"
40    }
41
42    fn generate(
43        &self,
44        ws: &CheckedWorkspace,
45        options: &GenOptions,
46    ) -> Result<Vec<GeneratedFile>, GenError> {
47        let profile = profile("typescript")?;
48        crate::refuse_higher_order(ws, options, "typescript")?;
49        let mut files = Vec::new();
50
51        for universe in selected(ws, options) {
52            files.push(GeneratedFile {
53                path: format!("typescript/{}.ts", universe.name).into(),
54                contents: universe_file(ws, universe, &profile, options),
55            });
56        }
57
58        if options.harness {
59            files.push(GeneratedFile {
60                path: "typescript/unitype_harness.ts".into(),
61                contents: HARNESS.to_string(),
62            });
63        }
64        Ok(files)
65    }
66}
67
68fn universe_file(
69    ws: &CheckedWorkspace,
70    universe: &Universe,
71    profile: &LanguageProfile,
72    options: &GenOptions,
73) -> String {
74    let mut w = CodeWriter::new();
75
76    if options.header {
77        for line in header("//", universe, ws) {
78            w.line(line);
79        }
80        w.blank();
81    }
82    if let Some(doc) = &universe.doc {
83        w.comment("// ", doc);
84        w.blank();
85    }
86
87    let imports = imports(ws, universe, profile);
88    for import in &imports {
89        w.write(format_args!(
90            "import type {{ {} }} from \"./{}\";",
91            import.1.join(", "),
92            import.0
93        ));
94    }
95    if !imports.is_empty() {
96        w.blank();
97    }
98
99    if options.stubs {
100        emit_helpers(&mut w, universe);
101    }
102
103    for def in ordered_defs(universe) {
104        match def {
105            TypeDef::Struct(d) => emit_struct(&mut w, ws, d, profile),
106            TypeDef::Interface(d) => emit_interface(&mut w, ws, d, profile),
107            TypeDef::Enum(d) => emit_enum(&mut w, d, profile),
108            TypeDef::Alias(d) => emit_alias(&mut w, d, profile),
109        }
110        w.blank();
111    }
112
113    if options.stubs {
114        for sig in &universe.functions {
115            emit_signature(&mut w, ws, universe, sig, profile);
116            w.blank();
117        }
118    }
119
120    w.finish()
121}
122
123/// What this universe needs from others, grouped by where it comes from.
124fn imports(
125    ws: &CheckedWorkspace,
126    universe: &Universe,
127    profile: &LanguageProfile,
128) -> Vec<(String, Vec<String>)> {
129    let mut found: std::collections::BTreeMap<String, std::collections::BTreeSet<String>> =
130        Default::default();
131    let mut note = |ty: &Type| {
132        crate::refs_in(ty, &mut |r| {
133            if let Some(from) = &r.universe {
134                if from != &universe.name {
135                    found
136                        .entry(from.to_string())
137                        .or_default()
138                        .insert(r.name.to_string());
139                }
140            }
141        });
142    };
143
144    for def in &universe.types {
145        match def {
146            TypeDef::Struct(d) => d.fields.iter().for_each(|f| note(&f.ty)),
147            TypeDef::Interface(d) => d.fields.iter().for_each(|f| note(&f.ty)),
148            TypeDef::Enum(d) => d.variants.iter().for_each(|v| note(&v.payload)),
149            TypeDef::Alias(d) => note(&d.target),
150        }
151        for bound in def.params().iter().flat_map(|p| &p.bounds) {
152            note(&Type::Ref(bound.clone()));
153        }
154    }
155    for sig in &universe.functions {
156        sig.params.iter().for_each(|p| note(&p.ty));
157        note(&sig.ret);
158        for bound in sig.params_decl.iter().flat_map(|p| &p.bounds) {
159            note(&Type::Ref(bound.clone()));
160        }
161        // A body names types of its own, in what a fold carries and what a
162        // binding holds, so it is written out here to find out which.
163        if let Some(body) = &sig.body {
164            let writer = Body::new(ws, profile);
165            writer.expression(body, &scope(sig));
166            writer.named.take().iter().for_each(&mut note);
167        }
168    }
169
170    found
171        .into_iter()
172        .map(|(from, names)| (from, names.into_iter().collect()))
173        .collect()
174}
175
176/// Writes prose as a documentation comment.
177///
178/// A block comment has to be closed, and has to stay closed: prose that
179/// happens to contain `*/` would end the comment early and leave the rest of
180/// the sentence to be read as code.
181fn jsdoc(w: &mut CodeWriter, text: &str) {
182    let safe = text.replace("*/", "*\\/");
183    let single = safe.trim();
184    if !single.contains('\n') && single.len() < 68 {
185        w.write(format_args!("/** {single} */"));
186        return;
187    }
188    w.line("/**");
189    w.comment(" * ", &safe);
190    w.line(" */");
191}
192
193fn emit_struct(
194    w: &mut CodeWriter,
195    ws: &CheckedWorkspace,
196    def: &StructDef,
197    profile: &LanguageProfile,
198) {
199    if let Some(doc) = &def.doc {
200        jsdoc(w, doc);
201    }
202    // A struct's parent and the interfaces it satisfies both become `extends`,
203    // since TypeScript interfaces are structural and an interface may extend
204    // any number of others.
205    let mut parents: Vec<String> = def
206        .extends
207        .iter()
208        .chain(&def.implements)
209        .map(|r| profile.spell(&Type::Ref(r.clone())))
210        .collect();
211    parents.dedup();
212
213    let name = format!(
214        "{}{}",
215        profile.name(&def.name),
216        generics(&def.params, profile)
217    );
218    let head = if parents.is_empty() {
219        format!("export interface {name} {{")
220    } else {
221        format!("export interface {name} extends {} {{", parents.join(", "))
222    };
223
224    // Only what this declaration adds: TypeScript inherits the rest.
225    let own: Vec<&Field> = def.fields.iter().collect();
226    if own.is_empty() {
227        w.line(head.trim_end_matches(" {").to_string() + " {}");
228        return;
229    }
230    w.block(head, "}", |w| emit_fields(w, ws, &own, profile));
231}
232
233fn emit_interface(
234    w: &mut CodeWriter,
235    ws: &CheckedWorkspace,
236    def: &InterfaceDef,
237    profile: &LanguageProfile,
238) {
239    if let Some(doc) = &def.doc {
240        jsdoc(w, doc);
241    }
242    let parents: Vec<String> = def
243        .extends
244        .iter()
245        .map(|r| profile.spell(&Type::Ref(r.clone())))
246        .collect();
247    let name = format!(
248        "{}{}",
249        profile.name(&def.name),
250        generics(&def.params, profile)
251    );
252    let head = if parents.is_empty() {
253        format!("export interface {name} {{")
254    } else {
255        format!("export interface {name} extends {} {{", parents.join(", "))
256    };
257    let own: Vec<&Field> = def.fields.iter().collect();
258    if own.is_empty() {
259        w.line(head.trim_end_matches(" {").to_string() + " {}");
260        return;
261    }
262    w.block(head, "}", |w| emit_fields(w, ws, &own, profile));
263}
264
265fn emit_fields(
266    w: &mut CodeWriter,
267    ws: &CheckedWorkspace,
268    fields: &[&Field],
269    profile: &LanguageProfile,
270) {
271    for field in fields {
272        if let Some(doc) = &field.doc {
273            jsdoc(w, doc);
274        }
275        for caveat in profile.caveats(&field.ty) {
276            w.comment("// ", &caveat);
277        }
278        // A field that may be absent is optional *and* nullable, because the
279        // wire has one way of being absent and TypeScript has two.
280        w.write(format_args!(
281            "{}{}: {};",
282            profile.name(&field.name),
283            if may_be_absent(ws, &field.ty) {
284                "?"
285            } else {
286                ""
287            },
288            profile.spell(&field.ty)
289        ));
290    }
291}
292
293/// Whether a field of this type may be left out.
294///
295/// What may be absent is what the canonical form leaves out, and so what a
296/// body may leave out: anything that expands to `T?`, `null` or `any`.
297fn may_be_absent(ws: &CheckedWorkspace, ty: &Type) -> bool {
298    matches!(
299        ws.expand_alias(ty),
300        Type::Optional { .. } | Type::Unit | Type::Any
301    )
302}
303
304fn emit_enum(w: &mut CodeWriter, def: &EnumDef, profile: &LanguageProfile) {
305    if let Some(doc) = &def.doc {
306        jsdoc(w, doc);
307    }
308    // Tagged the way the wire tags it, so what a reader destructures is what
309    // actually arrived.
310    w.line(format!(
311        "export type {}{} =",
312        profile.name(&def.name),
313        generics(&def.params, profile)
314    ));
315    w.indented(|w| {
316        for variant in &def.variants {
317            let tag = format!("$tag: {:?}", variant.name.as_str());
318            if matches!(variant.payload, Type::Unit) {
319                w.write(format_args!("| {{ {tag} }}"));
320            } else {
321                w.write(format_args!(
322                    "| {{ {tag}; value: {} }}",
323                    profile.spell(&variant.payload)
324                ));
325            }
326        }
327    });
328    w.line(";");
329}
330
331fn emit_alias(w: &mut CodeWriter, def: &AliasDef, profile: &LanguageProfile) {
332    if let Some(doc) = &def.doc {
333        jsdoc(w, doc);
334    }
335    let spelled = match &def.target {
336        // A union has no single spelling in the profile, since how it is written
337        // depends on the declaration it appears in. Here it is a union type.
338        Type::Union { members } => members
339            .iter()
340            .map(|m| profile.spell(m))
341            .collect::<Vec<_>>()
342            .join(" | "),
343        other => profile.spell(other),
344    };
345    w.write(format_args!(
346        "export type {}{} = {spelled};",
347        profile.name(&def.name),
348        generics(&def.params, profile)
349    ));
350}
351
352/// A declaration's or a signature's generic parameters as TypeScript writes
353/// them — `<T, K extends Named & Sized>` — or nothing when there are none.
354fn generics(params: &[TypeParamDecl], profile: &LanguageProfile) -> String {
355    if params.is_empty() {
356        return String::new();
357    }
358    let parts: Vec<String> = params
359        .iter()
360        .map(|p| {
361            let name = profile.name(&p.name);
362            if p.bounds.is_empty() {
363                return name;
364            }
365            let bounds: Vec<String> = p
366                .bounds
367                .iter()
368                .map(|b| profile.spell(&Type::Ref(b.clone())))
369                .collect();
370            format!("{name} extends {}", bounds.join(" & "))
371        })
372        .collect();
373    format!("<{}>", parts.join(", "))
374}
375
376fn emit_signature(
377    w: &mut CodeWriter,
378    ws: &CheckedWorkspace,
379    universe: &Universe,
380    sig: &FunctionSig,
381    profile: &LanguageProfile,
382) {
383    if let Some(doc) = &sig.doc {
384        jsdoc(w, doc);
385    }
386
387    let params: Vec<String> = sig
388        .params
389        .iter()
390        .map(|p| format!("{}: {}", profile.name(&p.name), profile.spell(&p.ty)))
391        .collect();
392    let ret = profile.spell(&sig.ret);
393    let name = format!(
394        "{}{}",
395        profile.name(&sig.name),
396        generics(&sig.params_decl, profile)
397    );
398
399    match &sig.body {
400        // A body is a proof already: transpile it rather than leaving a hole.
401        Some(body) => {
402            w.block(
403                format!("export function {name}({}): {ret} {{", params.join(", ")),
404                "}",
405                |w| {
406                    w.write(format_args!(
407                        "return {};",
408                        Body::new(ws, profile).expression(body, &scope(sig))
409                    ));
410                },
411            );
412        }
413        None => {
414            w.comment(
415                "// ",
416                &format!(
417                    "A proposition with no proof here. Implement it and register it \
418                     as `{}`.",
419                    QualifiedName::new(universe.name.clone(), sig.name.clone())
420                ),
421            );
422            w.block(
423                format!("export function {name}({}): {ret} {{", params.join(", ")),
424                "}",
425                |w| {
426                    w.write(format_args!(
427                        "throw new Error(\"{} is not implemented\");",
428                        QualifiedName::new(universe.name.clone(), sig.name.clone())
429                    ));
430                },
431            );
432        }
433    }
434}
435
436/// Comparison as every other backend does it, written out once per module that
437/// needs it.
438///
439/// `===` asks whether two arrays are the same array, and `<` orders strings by
440/// UTF-16 unit; a body means the same values, and code point order. Neither
441/// helper is exported, and both names are reserved, so a body cannot shadow
442/// them.
443const EQUAL: &str = r#"function unitypeEqual(a: unknown, b: unknown): boolean {
444  if (a === b) return true;
445  // Absent and null are one state on the wire, and so here.
446  if (a === null || a === undefined || b === null || b === undefined) {
447    return (a ?? null) === (b ?? null);
448  }
449  if (Array.isArray(a) || Array.isArray(b)) {
450    return Array.isArray(a) && Array.isArray(b) && a.length === b.length &&
451      a.every((x, i) => unitypeEqual(x, b[i]));
452  }
453  if (typeof a === "object" && typeof b === "object") {
454    const x = a as Record<string, unknown>;
455    const y = b as Record<string, unknown>;
456    return [...new Set([...Object.keys(x), ...Object.keys(y)])].every((k) => unitypeEqual(x[k], y[k]));
457  }
458  return false;
459}"#;
460
461const COMPARE: &str = r#"function unitypeCompare(a: number | string, b: number | string): number {
462  if (typeof a === "string" && typeof b === "string") {
463    const x = Array.from(a, (c) => c.codePointAt(0) as number);
464    const y = Array.from(b, (c) => c.codePointAt(0) as number);
465    for (let i = 0; i < Math.min(x.length, y.length); i++) {
466      if (x[i] !== y[i]) return x[i] - y[i];
467    }
468    return x.length - y.length;
469  }
470  return a < b ? -1 : a > b ? 1 : 0;
471}"#;
472
473fn emit_helpers(w: &mut CodeWriter, universe: &Universe) {
474    let compares = |wanted: fn(PrimOp) -> bool| {
475        bodies_use(
476            universe,
477            |e| matches!(e, Expr::Prim { op, .. } if wanted(*op)),
478        )
479    };
480    if compares(|op| matches!(op, PrimOp::Eq | PrimOp::Ne)) {
481        for line in EQUAL.lines() {
482            w.line(line);
483        }
484        w.blank();
485    }
486    if compares(PrimOp::is_ordering) {
487        for line in COMPARE.lines() {
488            w.line(line);
489        }
490        w.blank();
491    }
492}
493
494/// What each name in scope holds, at some point in a body.
495type Env = HashMap<Ident, Type>;
496
497/// What a signature's parameters hold, which is where every body starts.
498fn scope(sig: &FunctionSig) -> Env {
499    sig.params
500        .iter()
501        .map(|p| (p.name.clone(), p.ty.clone()))
502        .collect()
503}
504
505/// Writing a body as TypeScript.
506///
507/// The same body becomes Python and Rust elsewhere. A mapping written once in
508/// the symbolic language is three functions, none of which anyone wrote.
509///
510/// TypeScript works out most of what a body holds by itself, but a binding it
511/// is not told about takes on whatever it is given, widened: a pair becomes an
512/// array of either, and a variant's tag any string at all. Saying what a
513/// binding holds takes knowing what each name in scope holds, which the
514/// workspace can say once it is told, as it is for Rust. Every type the text
515/// names is kept, so that the module can import the ones declared elsewhere.
516struct Body<'a> {
517    ws: &'a CheckedWorkspace,
518    profile: &'a LanguageProfile,
519    named: RefCell<Vec<Type>>,
520}
521
522impl<'a> Body<'a> {
523    fn new(ws: &'a CheckedWorkspace, profile: &'a LanguageProfile) -> Self {
524        Body {
525            ws,
526            profile,
527            named: RefCell::new(Vec::new()),
528        }
529    }
530
531    /// Writes `expr`, where `env` says what each name holds.
532    fn expression(&self, expr: &Expr, env: &Env) -> String {
533        let profile = self.profile;
534        match expr {
535            Expr::Lit { value } => crate::typescript::literal(value),
536            Expr::Var { name } => profile.name(name),
537            Expr::Field { of, name } => {
538                let read = format!("{}.{}", self.expression(of, env), profile.name(name));
539                // A field that may be absent is declared optional, so
540                // TypeScript reads it as `undefined` as well as `null`, where
541                // the profile's `T?` is `T | null` alone. Absent and null are
542                // one state on the wire, so the read gives `null` for both.
543                let holds = self.ws.type_of_expr(expr, env);
544                if holds.is_some_and(|t| may_be_absent(self.ws, &t)) {
545                    format!("({read} ?? null)")
546                } else {
547                    read
548                }
549            }
550            Expr::MakeRecord { fields, .. } => {
551                let parts: Vec<String> = fields
552                    .iter()
553                    .map(|f| {
554                        format!(
555                            "{}: {}",
556                            profile.name(&f.name),
557                            self.expression(&f.value, env)
558                        )
559                    })
560                    .collect();
561                format!("{{ {} }}", parts.join(", "))
562            }
563            Expr::MakeList { items } | Expr::MakeTuple { items } => {
564                let parts: Vec<String> = items.iter().map(|i| self.expression(i, env)).collect();
565                format!("[{}]", parts.join(", "))
566            }
567            Expr::MakeVariant { tag, value, .. } => match value {
568                Some(v) => format!(
569                    "{{ $tag: {:?}, value: {} }}",
570                    tag.as_str(),
571                    self.expression(v, env)
572                ),
573                None => format!("{{ $tag: {:?} }}", tag.as_str()),
574            },
575            Expr::Call { sig, args } => {
576                let parts: Vec<String> = args.iter().map(|a| self.expression(a, env)).collect();
577                format!("{}({})", profile.name(&sig.name), parts.join(", "))
578            }
579            // An immediately-applied function keeps this an expression, so a
580            // body nests wherever an expression can go. Its parameter says what
581            // it holds unless TypeScript already knows.
582            Expr::Let { name, value, body } => {
583                let bound = self.ws.type_of_expr(value, env);
584                let mut inner = env.clone();
585                if let Some(bound) = &bound {
586                    inner.insert(name.clone(), bound.clone());
587                }
588                let said = bound.filter(|_| !known(value)).and_then(|t| self.spell(&t));
589                format!(
590                    "(({}{}) => {})({})",
591                    profile.name(name),
592                    said.map(|t| format!(": {t}")).unwrap_or_else(|| " ".into()),
593                    arrow(self.expression(body, &inner)),
594                    self.expression(value, env)
595                )
596            }
597            Expr::If {
598                cond,
599                then,
600                otherwise,
601            } => format!(
602                "({} ? {} : {})",
603                self.expression(cond, env),
604                self.expression(then, env),
605                self.expression(otherwise, env)
606            ),
607            Expr::MapThrough {
608                functor,
609                value,
610                var,
611                body,
612            } => {
613                use unitype_core::ir::Functor;
614                let mut inner = env.clone();
615                if let Some(subject) = self.ws.type_of_expr(value, env) {
616                    if let Some((_, inside)) = Functor::split(&self.ws.expand_alias(&subject)) {
617                        inner.insert(var.clone(), inside.clone());
618                    }
619                }
620                let subject = self.expression(value, env);
621                let bound = profile.name(var);
622                let inner = arrow(self.expression(body, &inner));
623                match functor {
624                    Functor::List => format!("{subject}.map(({bound}) => {inner})"),
625                    // Absent stays absent, which in TypeScript means checking.
626                    Functor::Optional => format!(
627                        "(({bound}) => {bound} === null || {bound} === undefined ? null : {inner})({subject})"
628                    ),
629                    Functor::Future => format!("{subject}.then(({bound}) => {inner})"),
630                }
631            }
632            Expr::Prim { op, args } => {
633                let operands: Vec<String> = args.iter().map(|a| self.expression(a, env)).collect();
634                match (op, operands.as_slice()) {
635                    (PrimOp::Eq, [x, y]) => format!("unitypeEqual({x}, {y})"),
636                    (PrimOp::Ne, [x, y]) => format!("!unitypeEqual({x}, {y})"),
637                    (op, [x, y]) if op.is_ordering() => {
638                        let sign = match op {
639                            PrimOp::Lt => "<",
640                            PrimOp::Le => "<=",
641                            PrimOp::Gt => ">",
642                            _ => ">=",
643                        };
644                        format!("(unitypeCompare({x}, {y}) {sign} 0)")
645                    }
646                    (PrimOp::Neg, [x]) => format!("(-{x})"),
647                    (PrimOp::Not, [x]) => format!("(!{x})"),
648                    (PrimOp::Len, [x]) => format!("{x}.length"),
649                    (op, [x, y]) => {
650                        let sign = match op {
651                            PrimOp::Add => "+",
652                            PrimOp::Sub => "-",
653                            PrimOp::Mul => "*",
654                            PrimOp::And => "&&",
655                            _ => "||",
656                        };
657                        format!("({x} {sign} {y})")
658                    }
659                    _ => unreachable!("the checker holds every operation to its arity"),
660                }
661            }
662            Expr::Fold {
663                list,
664                init,
665                acc,
666                item,
667                body,
668                ..
669            } => {
670                let mut inner = env.clone();
671                if let Some(carried) = self.ws.type_of_expr(expr, env) {
672                    inner.insert(acc.clone(), carried);
673                }
674                let element =
675                    self.ws
676                        .type_of_expr(list, env)
677                        .and_then(|t| match self.ws.expand_alias(&t) {
678                            Type::List { of } => Some(*of),
679                            _ => None,
680                        });
681                if let Some(element) = element {
682                    inner.insert(item.clone(), element);
683                }
684                format!(
685                    "{}.reduce{}(({}, {}) => {}, {})",
686                    self.expression(list, env),
687                    carried(expr)
688                        .and_then(|t| self.spell(&t))
689                        .map(|t| format!("<{t}>"))
690                        .unwrap_or_default(),
691                    profile.name(acc),
692                    profile.name(item),
693                    arrow(self.expression(body, &inner)),
694                    self.expression(init, env)
695                )
696            }
697            // `$c` and `$m` cannot be the name of anything a body binds, since
698            // no identifier may contain a `$`.
699            Expr::Case {
700                value,
701                var,
702                some,
703                none,
704            } => {
705                let mut present = env.clone();
706                let inside =
707                    self.ws
708                        .type_of_expr(value, env)
709                        .map(|t| match self.ws.expand_alias(&t) {
710                            Type::Optional { of } => *of,
711                            // Only `null` gets here, so the present arm binds
712                            // something that is never there.
713                            _ => Type::Never,
714                        });
715                if let Some(inside) = inside {
716                    present.insert(var.clone(), inside);
717                }
718                format!(
719                    "(($c) => $c === null || $c === undefined ? {} : (({}) => {})($c))({})",
720                    self.expression(none, env),
721                    profile.name(var),
722                    arrow(self.expression(some, &present)),
723                    self.expression(value, env)
724                )
725            }
726            Expr::Match { ty, value, arms } => {
727                let subject = self.expression(value, env);
728                let Some((last, rest)) = arms.split_last() else {
729                    return format!("(($m) => {{ throw new Error(\"no variant\"); }})({subject})");
730                };
731                let variants = self.ws.variants_of(ty).unwrap_or_default();
732                let arm = |a: &unitype_core::ir::MatchArm| {
733                    let mut inner = env.clone();
734                    let payload = variants.iter().find(|v| v.name == a.tag);
735                    if let (Some(var), Some(variant)) = (&a.var, payload) {
736                        inner.insert(var.clone(), variant.payload.clone());
737                    }
738                    let body = self.expression(&a.body, &inner);
739                    match &a.var {
740                        Some(var) => {
741                            format!("(({}) => {})($m.value)", profile.name(var), arrow(body))
742                        }
743                        None => body,
744                    }
745                };
746                // Every variant has an arm, so the last needs no test.
747                let mut chain = arm(last);
748                for a in rest.iter().rev() {
749                    chain = format!("$m.$tag === {:?} ? {} : {chain}", a.tag.as_str(), arm(a));
750                }
751                format!("(($m) => {chain})({subject})")
752            }
753        }
754    }
755
756    /// How a binding or a fold says what it holds, or `None` where TypeScript
757    /// is better left to work it out.
758    ///
759    /// The profile has no one spelling for a union or an anonymous record, and
760    /// writes `unknown` for either, which would refuse every use a body makes
761    /// of the value. A union that is the whole type is written out as one, as
762    /// an alias's is; one inside anything else leaves the type unsaid, as
763    /// does a record or a function anywhere in it.
764    fn spell(&self, ty: &Type) -> Option<String> {
765        let members = match ty {
766            Type::Union { members } => members.as_slice(),
767            other => std::slice::from_ref(other),
768        };
769        if !members.iter().all(spelled_whole) {
770            return None;
771        }
772        self.named.borrow_mut().push(ty.clone());
773        Some(
774            members
775                .iter()
776                .map(|m| self.profile.spell(m))
777                .collect::<Vec<_>>()
778                .join(" | "),
779        )
780    }
781}
782
783/// Whether TypeScript takes what `expr` produces from a declaration, so that a
784/// binding of it need not say.
785///
786/// A name, a field and a call are read off what declared or bound them, and an
787/// operation always gives a number or a boolean. Anything else TypeScript
788/// works out from its shape, which can say less. A declaration can say less
789/// than the checker as well, `unknown` where the checker has a union, and then
790/// a binding that said more would refuse what it is given.
791fn known(expr: &Expr) -> bool {
792    matches!(
793        expr,
794        Expr::Var { .. } | Expr::Field { .. } | Expr::Call { .. } | Expr::Prim { .. }
795    )
796}
797
798/// Whether the profile spells every part of a type as itself.
799fn spelled_whole(ty: &Type) -> bool {
800    match ty {
801        Type::Union { .. } | Type::Record { .. } | Type::Function { .. } => false,
802        other => other.children().into_iter().all(spelled_whole),
803    }
804}
805
806/// What a fold's `reduce` is told it carries, if anything.
807///
808/// TypeScript takes what a fold carries from its starting value, which can say
809/// less than the fold does: from `null` it would carry only `null`, from one
810/// variant only that variant, and from a record that leaves a field out a
811/// record without it. So where the fold says what it carries, or starts from a
812/// struct or an enum it builds, which is what the checker takes it to carry,
813/// the `reduce` says so too. Any other fold is left as TypeScript reads it.
814fn carried(fold: &Expr) -> Option<Type> {
815    let Expr::Fold { init, ty, .. } = fold else {
816        return None;
817    };
818    ty.clone().or_else(|| match init.as_ref() {
819        Expr::MakeRecord { ty, .. } | Expr::MakeVariant { ty, .. } => Some(Type::Ref(ty.clone())),
820        _ => None,
821    })
822}
823
824/// The body of an arrow function, bracketed if it would otherwise be read as a
825/// block.
826///
827/// `(x) => { a: 1 }` is a function whose body is a statement labelled `a`, not
828/// one returning a record, so a record has to be wrapped to be returned.
829fn arrow(body: String) -> String {
830    if body.starts_with('{') {
831        format!("({body})")
832    } else {
833        body
834    }
835}
836
837/// Writes a value as a TypeScript literal.
838pub fn literal(value: &unitype_core::value::Value) -> String {
839    use unitype_core::value::Value;
840    match value {
841        Value::Null => "null".into(),
842        Value::Bool(b) => b.to_string(),
843        Value::Int(i) => i.to_string(),
844        Value::Float(f) => format_float(*f),
845        Value::Str(s) => format!("{s:?}"),
846        // Bytes travel as base64, and so does a literal one.
847        Value::Bytes(b) => format!("{:?}", base64(b)),
848        Value::List(items) | Value::Tuple(items) => {
849            let parts: Vec<String> = items.iter().map(literal).collect();
850            format!("[{}]", parts.join(", "))
851        }
852        Value::Record(fields) => {
853            let parts: Vec<String> = fields
854                .iter()
855                .map(|(k, v)| format!("{}: {}", key(k), literal(v)))
856                .collect();
857            format!("{{ {} }}", parts.join(", "))
858        }
859        Value::Map(entries) => {
860            let parts: Vec<String> = entries
861                .iter()
862                .map(|(k, v)| {
863                    let k = match k {
864                        Value::Str(s) => format!("{s:?}"),
865                        other => format!("{:?}", literal(other)),
866                    };
867                    format!("{k}: {}", literal(v))
868                })
869                .collect();
870            format!("{{ {} }}", parts.join(", "))
871        }
872        Value::Variant { tag, value } => match value.as_ref() {
873            Value::Null => format!("{{ $tag: {tag:?} }}"),
874            payload => format!("{{ $tag: {tag:?}, value: {} }}", literal(payload)),
875        },
876    }
877}
878
879/// A property name, quoted only when it has to be.
880fn key(name: &str) -> String {
881    let plain = !name.is_empty()
882        && name
883            .chars()
884            .next()
885            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
886        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
887    if plain {
888        name.to_string()
889    } else {
890        format!("{name:?}")
891    }
892}
893
894/// A float that reads back as a float rather than an integer.
895fn format_float(f: f64) -> String {
896    let plain = f.to_string();
897    if plain.contains(['.', 'e', 'E']) {
898        plain
899    } else {
900        format!("{plain}.0")
901    }
902}
903
904fn base64(bytes: &[u8]) -> String {
905    use base64::Engine as _;
906    base64::engine::general_purpose::STANDARD.encode(bytes)
907}
908
909/// The harness that makes a filled-in module reachable as a proof.
910const HARNESS: &str = r#"// Generated by unitype. Do not edit.
911//
912// This is the whole of what it takes for a Node module to take part: read a
913// message, do the work, write one back. One message per line, and reading lines
914// serves both ways of being called — if the parent sends one message and closes
915// the stream, this runs once and the process exits; if the parent keeps the
916// stream open, it keeps answering. Nothing here has to know which is happening.
917//
918// Pass a table of what this module proves, keyed by the entry name a manifest
919// points at:
920//
921//     import { unitypeMain } from "./unitype_harness.ts";
922//     import { sort } from "./demo.ts";
923//     unitypeMain({ bubble_sort: sort });
924//
925// Node 24 and later run that as it stands, which is why the paths say `.ts`.
926// Behind a compiler or a bundler, write them the way it expects.
927
928export type Proof = (...args: any[]) => unknown | Promise<unknown>;
929
930export async function unitypeMain(proves: Record<string, Proof>): Promise<void> {
931  let pending = "";
932  for await (const chunk of process.stdin) {
933    pending += chunk.toString("utf8");
934    let at: number;
935    while ((at = pending.indexOf("\n")) >= 0) {
936      const line = pending.slice(0, at).trim();
937      pending = pending.slice(at + 1);
938      if (line) await answer(proves, line);
939    }
940  }
941  // A parent that closed the stream without a trailing newline still sent a
942  // message, so whatever is left is one.
943  const last = pending.trim();
944  if (last) await answer(proves, last);
945}
946
947async function answer(proves: Record<string, Proof>, line: string): Promise<void> {
948  let request: any;
949  try {
950    request = JSON.parse(line);
951  } catch (error) {
952    return respond({ ok: false, error: { code: "bad_request", message: String(error) } });
953  }
954
955  if (request.unitype !== "1") {
956    return respond({
957      ok: false,
958      error: { code: "bad_version", message: `this module speaks version 1, not ${request.unitype}` },
959    });
960  }
961  if (request.kind !== "invoke") {
962    return respond({ ok: false, error: { code: "bad_kind", message: `cannot do ${request.kind}` } });
963  }
964
965  const proof = proves[request.entry];
966  if (proof === undefined) {
967    const known = Object.keys(proves).sort().join(", ") || "nothing";
968    return respond({
969      ok: false,
970      error: { code: "no_such_entry", message: `this module proves ${known}, not ${request.entry}` },
971    });
972  }
973
974  try {
975    respond({ ok: true, value: await proof(...(request.args ?? [])) });
976  } catch (error) {
977    // Reported as a failure of the proof, not of the process: exiting non-zero
978    // would say the environment is broken, which it is not.
979    respond({ ok: false, error: { code: "threw", message: String(error) } });
980  }
981}
982
983function respond(response: unknown): void {
984  // One line: a parent reading line by line needs the terminator to know the
985  // message is finished.
986  process.stdout.write(JSON.stringify(response) + "\n");
987}
988"#;
989
990#[cfg(test)]
991mod tests {
992    use super::*;
993    use unitype_core::Workspace;
994    use unitype_core::check::check_workspace;
995
996    fn generate(json: &str) -> String {
997        let ws = check_workspace(Workspace::from_json(json).expect("reads")).expect("checks");
998        let files = TypeScript
999            .generate(&ws, &GenOptions::default())
1000            .expect("generates");
1001        files
1002            .into_iter()
1003            .find(|f| f.path.to_string_lossy().ends_with("demo.ts"))
1004            .expect("a file for the demo universe")
1005            .contents
1006    }
1007
1008    const SHAPES: &str = r#"{"universes":[{"name":"demo","types":[
1009        {"k":"interface","name":"Identified","fields":[{"name":"id","ty":"str"}]},
1010        {"k":"struct","name":"Shape","implements":["Identified"],
1011         "fields":[{"name":"id","ty":"str"}]},
1012        {"k":"struct","name":"Circle","extends":"Shape","fields":[
1013            {"name":"kind","ty":{"k":"literal","value":{"str":"circle"}}},
1014            {"name":"radius","ty":"float"},
1015            {"name":"note","ty":"str?"}]},
1016        {"k":"struct","name":"Rect","extends":"Shape","fields":[
1017            {"name":"kind","ty":{"k":"literal","value":{"str":"rect"}}},
1018            {"name":"w","ty":"float"}]},
1019        {"k":"alias","name":"AnyShape","target":{"k":"union","members":["Circle","Rect"]}},
1020        {"k":"enum","name":"Colour","variants":[{"name":"Red"},{"name":"Custom","payload":"str"}]}],
1021      "functions":[
1022        {"name":"area","params":[{"name":"s","ty":"Circle"}],"ret":"float"}]}]}"#;
1023
1024    #[test]
1025    fn a_struct_becomes_an_interface() {
1026        let out = generate(SHAPES);
1027        assert!(
1028            out.contains("export interface Shape extends Identified {"),
1029            "{out}"
1030        );
1031        assert!(out.contains("id: string;"), "{out}");
1032    }
1033
1034    #[test]
1035    fn inheritance_becomes_extends_rather_than_being_flattened() {
1036        let out = generate(SHAPES);
1037        assert!(
1038            out.contains("export interface Circle extends Shape {"),
1039            "{out}"
1040        );
1041        assert!(
1042            !out.contains("export interface Circle extends Shape {\n    id: string;"),
1043            "the inherited field should not be repeated: {out}"
1044        );
1045    }
1046
1047    #[test]
1048    fn a_parent_is_declared_before_the_child_that_extends_it() {
1049        let out = generate(SHAPES);
1050        let shape = out.find("interface Shape").expect("declared");
1051        let circle = out.find("interface Circle").expect("declared");
1052        assert!(shape < circle, "{out}");
1053    }
1054
1055    #[test]
1056    fn a_discriminating_literal_keeps_its_value() {
1057        let out = generate(SHAPES);
1058        assert!(
1059            out.contains(r#"kind: "circle";"#),
1060            "the discriminator is what lets a reader tell the union apart: {out}"
1061        );
1062    }
1063
1064    #[test]
1065    fn a_field_that_may_be_absent_is_optional_and_nullable() {
1066        let out = generate(SHAPES);
1067        assert!(
1068            out.contains("note?: string | null;"),
1069            "the wire has one way of being absent and TypeScript has two: {out}"
1070        );
1071    }
1072
1073    #[test]
1074    fn an_alias_an_any_and_a_null_may_be_absent_too() {
1075        let out = generate(
1076            r#"{"universes":[{"name":"demo","types":[
1077                {"k":"alias","name":"Later","target":"i64?"},
1078                {"k":"struct","name":"Entry","fields":[
1079                    {"name":"at","ty":"i64"},{"name":"when","ty":"Later"},
1080                    {"name":"extra","ty":"any"},{"name":"nothing","ty":"null"}]}],
1081              "functions":[
1082                {"name":"entry","params":[{"name":"x","ty":"i64"}],"ret":"Entry",
1083                 "body":{"k":"make_record","ty":"Entry","fields":[
1084                    {"name":"at","value":{"k":"var","name":"x"}}]}}]}]}"#,
1085        );
1086        assert!(
1087            out.contains("when?: Later;"),
1088            "an alias of an optional is still one: {out}"
1089        );
1090        assert!(out.contains("extra?: unknown;"), "{out}");
1091        assert!(out.contains("nothing?: null;"), "{out}");
1092        assert!(
1093            out.contains("return { at: x };"),
1094            "a body may leave all three out, so the interface has to let it: {out}"
1095        );
1096        assert!(
1097            out.contains("at: number;"),
1098            "a field that has to be there still has to be there: {out}"
1099        );
1100    }
1101
1102    const READS: &str = r#"{"universes":[{"name":"demo","types":[
1103        {"k":"alias","name":"Later","target":"i64?"},
1104        {"k":"struct","name":"Circle","fields":[
1105            {"name":"radius","ty":"float"},{"name":"note","ty":"str?"},{"name":"when","ty":"Later"},
1106            {"name":"extra","ty":"any"},{"name":"nothing","ty":"null"}]},
1107        {"k":"struct","name":"Holder","fields":[{"name":"c","ty":"Circle"}]},
1108        {"k":"struct","name":"Painted","fields":[
1109            {"name":"shade","ty":{"k":"union","members":[
1110                {"k":"literal","value":{"str":"red"}},{"k":"literal","value":{"str":"blue"}}]}}]}],
1111      "functions":[
1112        {"name":"takes","params":[{"name":"s","ty":"str?"}],"ret":"str"},
1113        {"name":"returned","params":[{"name":"c","ty":"Circle"}],"ret":"str?",
1114         "body":{"k":"field","of":{"k":"var","name":"c"},"name":"note"}},
1115        {"name":"passed","params":[{"name":"c","ty":"Circle"}],"ret":"str",
1116         "body":{"k":"call","sig":"demo::takes","args":[
1117            {"k":"field","of":{"k":"var","name":"c"},"name":"note"}]}},
1118        {"name":"chosen","params":[{"name":"b","ty":"bool"},{"name":"c","ty":"Circle"}],"ret":"str?",
1119         "body":{"k":"let","name":"n",
1120                 "value":{"k":"if","cond":{"k":"var","name":"b"},
1121                          "then":{"k":"field","of":{"k":"var","name":"c"},"name":"note"},
1122                          "else":{"k":"lit","value":null}},
1123                 "body":{"k":"var","name":"n"}}},
1124        {"name":"later","params":[{"name":"c","ty":"Circle"}],"ret":"Later",
1125         "body":{"k":"field","of":{"k":"var","name":"c"},"name":"when"}},
1126        {"name":"extra","params":[{"name":"c","ty":"Circle"}],"ret":"any",
1127         "body":{"k":"field","of":{"k":"var","name":"c"},"name":"extra"}},
1128        {"name":"nothing","params":[{"name":"c","ty":"Circle"}],"ret":"null",
1129         "body":{"k":"field","of":{"k":"var","name":"c"},"name":"nothing"}},
1130        {"name":"radius","params":[{"name":"c","ty":"Circle"}],"ret":"float",
1131         "body":{"k":"field","of":{"k":"var","name":"c"},"name":"radius"}},
1132        {"name":"deep","params":[{"name":"h","ty":"Holder"}],"ret":"str?",
1133         "body":{"k":"field","of":{"k":"field","of":{"k":"var","name":"h"},"name":"c"},"name":"note"}},
1134        {"name":"loose","params":[{"name":"r","ty":{"k":"record","fields":[{"name":"note","ty":"str?"}]}}],
1135         "ret":"str?","body":{"k":"field","of":{"k":"var","name":"r"},"name":"note"}},
1136        {"name":"shaded","params":[{"name":"p","ty":"Painted"}],"ret":"any",
1137         "body":{"k":"let","name":"k","value":{"k":"field","of":{"k":"var","name":"p"},"name":"shade"},
1138                 "body":{"k":"var","name":"k"}}}]}]}"#;
1139
1140    #[test]
1141    fn a_field_that_may_be_absent_is_read_as_null_when_it_is() {
1142        let out = generate(READS);
1143        assert!(
1144            out.contains("return (c.note ?? null);"),
1145            "TypeScript reads an optional field as `undefined` too, which `string | null` \
1146             refuses: {out}"
1147        );
1148        assert!(out.contains("return takes((c.note ?? null));"), "{out}");
1149        assert!(
1150            out.contains("return ((n: string | null) => n)((b ? (c.note ?? null) : null));"),
1151            "a binding that says it holds `string | null` has to be given one: {out}"
1152        );
1153    }
1154
1155    #[test]
1156    fn an_alias_an_any_and_a_null_are_read_as_null_when_absent_too() {
1157        let out = generate(READS);
1158        assert!(out.contains("return (c.when ?? null);"), "{out}");
1159        assert!(out.contains("return (c.extra ?? null);"), "{out}");
1160        assert!(out.contains("return (c.nothing ?? null);"), "{out}");
1161    }
1162
1163    #[test]
1164    fn a_field_that_has_to_be_there_is_read_as_it_is() {
1165        let out = generate(READS);
1166        assert!(out.contains("return c.radius;"), "{out}");
1167        assert!(
1168            out.contains("return (h.c.note ?? null);"),
1169            "only the read that may find nothing is folded: {out}"
1170        );
1171    }
1172
1173    #[test]
1174    fn a_field_of_an_anonymous_record_is_read_as_null_when_absent() {
1175        let out = generate(READS);
1176        assert!(out.contains("return (r.note ?? null);"), "{out}");
1177    }
1178
1179    #[test]
1180    fn a_binding_of_a_field_declared_as_less_than_it_holds_says_nothing() {
1181        let out = generate(READS);
1182        assert!(out.contains("shade: unknown;"), "{out}");
1183        assert!(
1184            out.contains("return ((k ) => k)(p.shade);"),
1185            "a binding that said `\"blue\" | \"red\"` would refuse the `unknown` it is \
1186             given: {out}"
1187        );
1188    }
1189
1190    #[test]
1191    fn an_enum_becomes_a_union_tagged_the_way_the_wire_tags_it() {
1192        let out = generate(SHAPES);
1193        assert!(out.contains(r#"| { $tag: "Red" }"#), "{out}");
1194        assert!(
1195            out.contains(r#"| { $tag: "Custom"; value: string }"#),
1196            "{out}"
1197        );
1198    }
1199
1200    #[test]
1201    fn an_alias_to_a_union_becomes_a_union_type() {
1202        let out = generate(SHAPES);
1203        assert!(
1204            out.contains("export type AnyShape = Circle | Rect;"),
1205            "{out}"
1206        );
1207    }
1208
1209    #[test]
1210    fn a_proposition_with_no_proof_gets_a_skeleton_that_says_so() {
1211        let out = generate(SHAPES);
1212        assert!(
1213            out.contains("export function area(s: Circle): number {"),
1214            "{out}"
1215        );
1216        assert!(out.contains("is not implemented"), "{out}");
1217    }
1218
1219    const COMPARING: &str = r#"{"universes":[{"name":"demo","functions":[
1220        {"name":"same","params":[{"name":"a","ty":"[i64]"},{"name":"b","ty":"[i64]"}],"ret":"bool",
1221         "body":{"k":"prim","op":"eq","args":[{"k":"var","name":"a"},{"k":"var","name":"b"}]}},
1222        {"name":"plain","params":[{"name":"a","ty":"i64"}],"ret":"i64","body":{"k":"var","name":"a"}}]}]}"#;
1223
1224    #[test]
1225    fn equality_means_the_same_values_rather_than_the_same_array() {
1226        let out = generate(COMPARING);
1227        assert!(out.contains("unitypeEqual(a, b)"), "{out}");
1228        assert!(
1229            out.contains("function unitypeEqual("),
1230            "the helper ships with the module that uses it: {out}"
1231        );
1232        assert!(
1233            !out.contains("function unitypeCompare("),
1234            "and nothing that module does not use: {out}"
1235        );
1236    }
1237
1238    #[test]
1239    fn a_module_that_compares_nothing_carries_no_helpers() {
1240        let out = generate(SHAPES);
1241        assert!(!out.contains("function unitype"), "{out}");
1242    }
1243
1244    #[test]
1245    fn a_body_is_written_out_rather_than_left_as_a_hole() {
1246        let out = generate(
1247            r#"{"universes":[{"name":"demo","types":[
1248                {"k":"struct","name":"User","fields":[{"name":"first","ty":"str"}]},
1249                {"k":"struct","name":"Badge","fields":[
1250                    {"name":"label","ty":"str"},{"name":"sides","ty":"i64"}]}],
1251              "functions":[
1252                {"name":"badge_of","params":[{"name":"u","ty":"User"}],"ret":"Badge",
1253                 "body":{"k":"make_record","ty":"Badge","fields":[
1254                    {"name":"label","value":{"k":"field","of":{"k":"var","name":"u"},"name":"first"}},
1255                    {"name":"sides","value":{"k":"lit","value":4}}]}}]}]}"#,
1256        );
1257        assert!(
1258            out.contains("return { label: u.first, sides: 4 };"),
1259            "the body written once should become real TypeScript: {out}"
1260        );
1261        assert!(!out.contains("not implemented"), "{out}");
1262    }
1263
1264    #[test]
1265    fn mapping_through_a_list_becomes_a_map() {
1266        let out = generate(
1267            r#"{"universes":[{"name":"demo","types":[
1268                {"k":"struct","name":"User","fields":[{"name":"first","ty":"str"}]}],
1269              "functions":[
1270                {"name":"names","params":[{"name":"us","ty":"[User]"}],"ret":"[str]",
1271                 "body":{"k":"map_through","functor":"list","value":{"k":"var","name":"us"},
1272                         "var":"u","body":{"k":"field","of":{"k":"var","name":"u"},"name":"first"}}}]}]}"#,
1273        );
1274        assert!(out.contains("us.map((u) => u.first)"), "{out}");
1275    }
1276
1277    #[test]
1278    fn mapping_through_absence_checks_for_it() {
1279        let out = generate(
1280            r#"{"universes":[{"name":"demo","functions":[
1281                {"name":"trimmed","params":[{"name":"s","ty":"str?"}],"ret":"str?",
1282                 "body":{"k":"map_through","functor":"optional","value":{"k":"var","name":"s"},
1283                         "var":"x","body":{"k":"var","name":"x"}}}]}]}"#,
1284        );
1285        assert!(out.contains("=== null"), "absent has to stay absent: {out}");
1286    }
1287
1288    #[test]
1289    fn a_fold_carries_what_it_says_rather_than_what_it_starts_from() {
1290        let out = generate(
1291            r#"{"universes":[{"name":"demo","functions":[
1292                {"name":"last_of","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64?",
1293                 "body":{"k":"fold","list":{"k":"var","name":"xs"},"init":{"k":"lit","value":null},
1294                         "ty":"int?","acc":"p","item":"x","body":{"k":"var","name":"x"}}},
1295                {"name":"total","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64",
1296                 "body":{"k":"fold","list":{"k":"var","name":"xs"},"init":{"k":"lit","value":0},
1297                         "acc":"t","item":"x","body":{"k":"prim","op":"add","args":[
1298                            {"k":"var","name":"t"},{"k":"var","name":"x"}]}}}]}]}"#,
1299        );
1300        assert!(
1301            out.contains("xs.reduce<number | null>((p, x) => x, null)"),
1302            "starting from `null` alone, it could only ever carry `null`: {out}"
1303        );
1304        assert!(
1305            out.contains("xs.reduce((t, x) => (t + x), 0)"),
1306            "a count that starts at `0` already says it counts numbers: {out}"
1307        );
1308    }
1309
1310    #[test]
1311    fn a_fold_that_starts_from_a_value_it_builds_carries_the_whole_type() {
1312        let out = generate(
1313            r#"{"universes":[{"name":"demo","types":[
1314                {"k":"enum","name":"Size","variants":[{"name":"small"},{"name":"large","payload":"i64"}]},
1315                {"k":"struct","name":"Seen","fields":[{"name":"at","ty":"i64"},{"name":"first","ty":"i64?"}]}],
1316              "functions":[
1317                {"name":"biggest","params":[{"name":"xs","ty":"[i64]"}],"ret":"Size",
1318                 "body":{"k":"fold","list":{"k":"var","name":"xs"},
1319                         "init":{"k":"make_variant","ty":"Size","tag":"small"},"acc":"s","item":"x",
1320                         "body":{"k":"make_variant","ty":"Size","tag":"large","value":{"k":"var","name":"x"}}}},
1321                {"name":"seen","params":[{"name":"xs","ty":"[i64]"}],"ret":"Seen",
1322                 "body":{"k":"fold","list":{"k":"var","name":"xs"},
1323                         "init":{"k":"make_record","ty":"Seen","fields":[
1324                            {"name":"at","value":{"k":"lit","value":0}}]},"acc":"s","item":"x",
1325                         "body":{"k":"make_record","ty":"Seen","fields":[
1326                            {"name":"at","value":{"k":"var","name":"x"}},
1327                            {"name":"first","value":{"k":"field","of":{"k":"var","name":"s"},"name":"first"}}]}}}]}]}"#,
1328        );
1329        assert!(
1330            out.contains(
1331                "xs.reduce<Size>((s, x) => ({ $tag: \"large\", value: x }), { $tag: \"small\" })"
1332            ),
1333            "one variant is not the whole enum: {out}"
1334        );
1335        assert!(
1336            out.contains("xs.reduce<Seen>("),
1337            "a record that leaves a field out does not say the field is there: {out}"
1338        );
1339    }
1340
1341    #[test]
1342    fn a_type_only_a_fold_names_is_imported_too() {
1343        let out = generate(
1344            r#"{"universes":[
1345                {"name":"geo","types":[{"k":"struct","name":"Point",
1346                 "fields":[{"name":"x","ty":"i64"}]}]},
1347                {"name":"demo","functions":[
1348                {"name":"furthest","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64",
1349                 "body":{"k":"field","name":"x","of":{"k":"fold","list":{"k":"var","name":"xs"},
1350                         "init":{"k":"make_record","ty":"geo::Point","fields":[
1351                            {"name":"x","value":{"k":"lit","value":0}}]},"acc":"p","item":"x",
1352                         "body":{"k":"make_record","ty":"geo::Point","fields":[
1353                            {"name":"x","value":{"k":"var","name":"x"}}]}}}}]}]}"#,
1354        );
1355        assert!(out.contains("xs.reduce<Point>("), "{out}");
1356        assert!(
1357            out.contains(r#"import type { Point } from "./geo";"#),
1358            "no signature names it, but the fold does: {out}"
1359        );
1360    }
1361
1362    const BINDINGS: &str = r#"{"universes":[
1363        {"name":"geo","types":[{"k":"struct","name":"Point","fields":[{"name":"x","ty":"i64"}]}]},
1364        {"name":"demo","types":[
1365            {"k":"struct","name":"Circle","fields":[
1366                {"name":"kind","ty":{"k":"literal","value":{"str":"circle"}}},
1367                {"name":"radius","ty":"float"},{"name":"note","ty":"str?"}]},
1368            {"k":"alias","name":"Colour","target":{"k":"union","members":[
1369                {"k":"literal","value":{"str":"red"}},{"k":"literal","value":{"str":"blue"}}]}},
1370            {"k":"enum","name":"Size","variants":[{"name":"small"},{"name":"large","payload":"i64"}]}],
1371          "functions":[
1372            {"name":"measure","params":[{"name":"s","ty":"Size"}],"ret":"i64"},
1373            {"name":"paint","params":[{"name":"c","ty":"Colour"}],"ret":"Colour"},
1374            {"name":"pair","params":[],"ret":{"k":"tuple","items":["i64","str"]},
1375             "body":{"k":"let","name":"p",
1376                     "value":{"k":"make_tuple","items":[{"k":"lit","value":0},{"k":"lit","value":"a"}]},
1377                     "body":{"k":"var","name":"p"}}},
1378            {"name":"settled","params":[{"name":"b","ty":"bool"},{"name":"xs","ty":"[i64]"}],"ret":"i64",
1379             "body":{"k":"let","name":"s",
1380                     "value":{"k":"fold","list":{"k":"var","name":"xs"},
1381                              "init":{"k":"if","cond":{"k":"var","name":"b"},
1382                                      "then":{"k":"make_variant","ty":"Size","tag":"small"},
1383                                      "else":{"k":"make_variant","ty":"Size","tag":"large",
1384                                              "value":{"k":"lit","value":1}}},
1385                              "acc":"a","item":"x","body":{"k":"var","name":"a"}},
1386                     "body":{"k":"call","sig":"demo::measure","args":[{"k":"var","name":"s"}]}}},
1387            {"name":"circle","params":[],"ret":"Circle",
1388             "body":{"k":"let","name":"k","value":{"k":"lit","value":"circle"},
1389                     "body":{"k":"make_record","ty":"Circle","fields":[
1390                        {"name":"kind","value":{"k":"var","name":"k"}},
1391                        {"name":"radius","value":{"k":"lit","value":1.5}}]}}},
1392            {"name":"painted","params":[{"name":"b","ty":"bool"}],"ret":"Colour",
1393             "body":{"k":"let","name":"k",
1394                     "value":{"k":"if","cond":{"k":"var","name":"b"},
1395                              "then":{"k":"lit","value":"red"},"else":{"k":"lit","value":"blue"}},
1396                     "body":{"k":"call","sig":"demo::paint","args":[{"k":"var","name":"k"}]}}},
1397            {"name":"noted","params":[{"name":"c","ty":"Circle"}],"ret":"str",
1398             "body":{"k":"let","name":"n","value":{"k":"field","of":{"k":"var","name":"c"},"name":"note"},
1399                     "body":{"k":"case","value":{"k":"var","name":"n"},"var":"it",
1400                             "some":{"k":"var","name":"it"},"none":{"k":"lit","value":"none"}}}},
1401            {"name":"doubled","params":[{"name":"s","ty":"Size"}],"ret":"i64",
1402             "body":{"k":"let","name":"m","value":{"k":"call","sig":"demo::measure","args":[{"k":"var","name":"s"}]},
1403                     "body":{"k":"let","name":"d",
1404                             "value":{"k":"prim","op":"add","args":[{"k":"var","name":"m"},{"k":"var","name":"m"}]},
1405                             "body":{"k":"let","name":"e","value":{"k":"var","name":"d"},
1406                                     "body":{"k":"var","name":"e"}}}}},
1407            {"name":"at","params":[{"name":"x","ty":"i64"}],"ret":"i64",
1408             "body":{"k":"let","name":"p","value":{"k":"make_record","ty":"geo::Point","fields":[
1409                        {"name":"x","value":{"k":"var","name":"x"}}]},
1410                     "body":{"k":"field","of":{"k":"var","name":"p"},"name":"x"}}},
1411            {"name":"folded","params":[{"name":"xs","ty":"[i64]"}],"ret":{"k":"tuple","items":["i64","str"]},
1412             "body":{"k":"fold","list":{"k":"var","name":"xs"},
1413                     "init":{"k":"make_tuple","items":[{"k":"lit","value":0},{"k":"lit","value":"a"}]},
1414                     "ty":{"k":"tuple","items":["i64","str"]},"acc":"a","item":"x",
1415                     "body":{"k":"let","name":"q",
1416                             "value":{"k":"make_tuple","items":[{"k":"var","name":"x"},{"k":"lit","value":"b"}]},
1417                             "body":{"k":"var","name":"q"}}}},
1418            {"name":"mapped","params":[{"name":"xs","ty":"[i64]"}],
1419             "ret":{"k":"list","of":{"k":"tuple","items":["i64","str"]}},
1420             "body":{"k":"map_through","functor":"list","value":{"k":"var","name":"xs"},"var":"x",
1421                     "body":{"k":"let","name":"p",
1422                             "value":{"k":"make_tuple","items":[{"k":"var","name":"x"},{"k":"lit","value":"m"}]},
1423                             "body":{"k":"var","name":"p"}}}},
1424            {"name":"armed","params":[{"name":"s","ty":"Size"}],"ret":{"k":"tuple","items":["i64","str"]},
1425             "body":{"k":"match","ty":"Size","value":{"k":"var","name":"s"},"arms":[
1426                {"tag":"small","body":{"k":"make_tuple","items":[{"k":"lit","value":0},{"k":"lit","value":"y"}]}},
1427                {"tag":"large","var":"n","body":{"k":"let","name":"p",
1428                     "value":{"k":"make_tuple","items":[{"k":"var","name":"n"},{"k":"lit","value":"x"}]},
1429                     "body":{"k":"var","name":"p"}}}]}},
1430            {"name":"cased","params":[{"name":"c","ty":"Circle"}],"ret":{"k":"tuple","items":["str","i64"]},
1431             "body":{"k":"case","value":{"k":"field","of":{"k":"var","name":"c"},"name":"note"},"var":"it",
1432                     "some":{"k":"let","name":"p",
1433                             "value":{"k":"make_tuple","items":[{"k":"var","name":"it"},{"k":"lit","value":1}]},
1434                             "body":{"k":"var","name":"p"}},
1435                     "none":{"k":"make_tuple","items":[{"k":"lit","value":"none"},{"k":"lit","value":0}]}}},
1436            {"name":"either","params":[{"name":"b","ty":"bool"}],"ret":{"k":"tuple","items":["str","i64"]},
1437             "body":{"k":"let","name":"p","value":{"k":"make_tuple","items":[{"k":"lit","value":"a"},
1438                        {"k":"if","cond":{"k":"var","name":"b"},
1439                         "then":{"k":"lit","value":1},"else":{"k":"lit","value":2}}]},
1440                     "body":{"k":"var","name":"p"}}}]}]}"#;
1441
1442    #[test]
1443    fn a_binding_says_what_it_holds_where_typescript_would_widen_it() {
1444        let out = generate(BINDINGS);
1445        assert!(
1446            out.contains(r#"return ((p: [0, "a"]) => p)([0, "a"]);"#),
1447            "told nothing, TypeScript takes a pair to be an array of either: {out}"
1448        );
1449        assert!(
1450            out.contains("return ((s: Size) => measure(s))(xs.reduce((a, x) => a, (b ? "),
1451            "told nothing, it takes a variant's tag to be any string: {out}"
1452        );
1453    }
1454
1455    #[test]
1456    fn a_binding_keeps_the_values_a_discriminator_may_hold() {
1457        let out = generate(BINDINGS);
1458        assert!(
1459            out.contains(r#"((k: "circle") => ({ kind: k, radius: 1.5 }))("circle")"#),
1460            "{out}"
1461        );
1462        assert!(
1463            out.contains(r#"((k: "blue" | "red") => paint(k))((b ? "red" : "blue"))"#),
1464            "a union that is the whole type is written out as one: {out}"
1465        );
1466    }
1467
1468    #[test]
1469    fn a_binding_typescript_already_reads_off_a_declaration_says_nothing() {
1470        let out = generate(BINDINGS);
1471        assert!(
1472            out.contains("return ((n ) => "),
1473            "a field is read off its declaration, as a name is: {out}"
1474        );
1475        assert!(
1476            out.contains("return ((m ) => ((d ) => ((e ) => e)(d))((m + m)))(measure(s));"),
1477            "a call, an operation and a name are written as they were: {out}"
1478        );
1479    }
1480
1481    #[test]
1482    fn a_binding_knows_what_the_names_round_it_hold() {
1483        let out = generate(BINDINGS);
1484        assert!(
1485            out.contains(r#"((q: [number, "b"]) => q)([x, "b"])"#),
1486            "inside a fold: {out}"
1487        );
1488        assert!(
1489            out.contains(r#"((p: [number, "m"]) => p)([x, "m"])"#),
1490            "inside a map: {out}"
1491        );
1492        assert!(
1493            out.contains(r#"((p: [number, "x"]) => p)([n, "x"])"#),
1494            "inside an arm: {out}"
1495        );
1496        assert!(
1497            out.contains(r#"((p: [string, 1]) => p)([it, 1])"#),
1498            "inside a case: {out}"
1499        );
1500    }
1501
1502    #[test]
1503    fn a_binding_whose_type_has_no_spelling_says_nothing_rather_than_unknown() {
1504        let out = generate(BINDINGS);
1505        assert!(
1506            out.contains(r#"return ((p ) => p)(["a", (b ? 1 : 2)]);"#),
1507            "{out}"
1508        );
1509        assert!(!out.contains("unknown"), "{out}");
1510    }
1511
1512    #[test]
1513    fn a_type_only_a_binding_names_is_imported_too() {
1514        let out = generate(BINDINGS);
1515        assert!(out.contains("((p: Point) => p.x)({ x: x })"), "{out}");
1516        assert!(
1517            out.contains(r#"import type { Point } from "./geo";"#),
1518            "no signature names it, but the binding does: {out}"
1519        );
1520    }
1521
1522    #[test]
1523    fn where_precision_goes_is_written_next_to_the_field() {
1524        let out = generate(
1525            r#"{"universes":[{"name":"demo","types":[
1526                {"k":"struct","name":"Big","fields":[{"name":"n","ty":"i64"}]}]}]}"#,
1527        );
1528        assert!(
1529            out.contains("2^53"),
1530            "a reader deserves to know before they lose a digit: {out}"
1531        );
1532    }
1533
1534    #[test]
1535    fn a_type_from_another_universe_is_imported() {
1536        let out = generate(
1537            r#"{"universes":[
1538                {"name":"geo","types":[{"k":"struct","name":"Point",
1539                 "fields":[{"name":"x","ty":"float"}]}]},
1540                {"name":"demo","types":[{"k":"struct","name":"Pin",
1541                 "fields":[{"name":"at","ty":"geo::Point"}]}]}]}"#,
1542        );
1543        assert!(
1544            out.contains(r#"import type { Point } from "./geo";"#),
1545            "{out}"
1546        );
1547    }
1548
1549    #[test]
1550    fn a_reserved_word_is_not_emitted_as_a_name() {
1551        let out = generate(
1552            r#"{"universes":[{"name":"demo","types":[
1553                {"k":"struct","name":"Thing","fields":[{"name":"function","ty":"str"}]}]}]}"#,
1554        );
1555        assert!(out.contains("function_: string;"), "{out}");
1556    }
1557
1558    #[test]
1559    fn generating_twice_from_the_same_workspace_gives_the_same_bytes() {
1560        assert_eq!(generate(SHAPES), generate(SHAPES));
1561    }
1562
1563    #[test]
1564    fn the_header_says_what_this_came_from() {
1565        let out = generate(SHAPES);
1566        assert!(
1567            out.starts_with("// Generated by unitype from universe `demo`."),
1568            "{out}"
1569        );
1570        assert!(out.contains("Structural addresses:"), "{out}");
1571    }
1572
1573    #[test]
1574    fn the_harness_ships_alongside() {
1575        let ws = check_workspace(Workspace::from_json(SHAPES).expect("reads")).expect("checks");
1576        let files = TypeScript
1577            .generate(&ws, &GenOptions::default())
1578            .expect("generates");
1579        assert!(
1580            files.iter().any(|f| f.path.ends_with("unitype_harness.ts")),
1581            "a filled-in module should be reachable without anyone writing glue"
1582        );
1583    }
1584
1585    #[test]
1586    fn values_become_literals_that_read_back_as_themselves() {
1587        use unitype_core::value::Value;
1588        assert_eq!(literal(&Value::Int(3)), "3");
1589        assert_eq!(
1590            literal(&Value::Float(2.0)),
1591            "2.0",
1592            "otherwise it reads back as an integer"
1593        );
1594        assert_eq!(literal(&Value::Str("hi".into())), "\"hi\"");
1595        assert_eq!(literal(&Value::Null), "null");
1596        assert_eq!(literal(&Value::record([("a", Value::Int(1))])), "{ a: 1 }");
1597        assert_eq!(literal(&Value::unit_variant("Red")), r#"{ $tag: "Red" }"#);
1598    }
1599
1600    #[test]
1601    fn a_property_name_is_quoted_only_when_it_has_to_be() {
1602        use unitype_core::value::Value;
1603        assert_eq!(
1604            literal(&Value::record([("ok", Value::Int(1))])),
1605            "{ ok: 1 }"
1606        );
1607        assert_eq!(
1608            literal(&Value::record([("not-ok", Value::Int(1))])),
1609            r#"{ "not-ok": 1 }"#
1610        );
1611    }
1612
1613    #[test]
1614    fn generic_declarations_and_signatures_keep_their_parameters() {
1615        let ts = generate(crate::GENERIC);
1616        for expected in [
1617            "export interface Box<T> {",
1618            "export interface Labelled<T, N extends Named> extends Box<T> {",
1619            "export interface Tagged<T> extends Holder<T> {",
1620            "export type Outcome<T, E> =",
1621            "export type Swap<A, B> = [B, A];",
1622            "outcome: Outcome<number, string>;",
1623            "swapped: Swap<number, string>;",
1624            "export function pick<T extends Named>(xs: T[]): T | null {",
1625            "export function konst<A, B>(x: A, y: B): A {",
1626        ] {
1627            assert!(ts.contains(expected), "missing `{expected}` in:\n{ts}");
1628        }
1629    }
1630
1631    #[test]
1632    fn several_bounds_are_one_intersection() {
1633        let ts = generate(
1634            r#"{"universes":[{"name":"demo","types":[
1635                {"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
1636                {"k":"interface","name":"Sized","fields":[{"name":"size","ty":"i64"}]}],
1637              "functions":[{"name":"f","params_decl":[{"name":"T","bounds":["Named","Sized"]}],
1638                "params":[{"name":"x","ty":{"k":"param","name":"T"}}],"ret":"str"}]}]}"#,
1639        );
1640        assert!(
1641            ts.contains("export function f<T extends Named & Sized>(x: T): string {"),
1642            "{ts}"
1643        );
1644    }
1645}