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