Skip to main content

unitype_codegen/
haskell.rs

1//! Writing a universe out as Haskell.
2//!
3//! Structs become records and enums become sums, each with a `ToJson` and a
4//! `FromJson` instance that read and write exactly the wire form, so a value
5//! built from the generated types is the value unitype says it is.
6//!
7//! # No JSON library
8//!
9//! GHC ships none, and the usual one is a build of its own dependency tree. So
10//! the instances are written against a small module generated beside the
11//! universes, `UnitypeSupport`, the way Rust's shared `Bytes` is: it reads and
12//! writes JSON and base64 using only what comes with GHC — `base`,
13//! `bytestring`, `containers`, `text`. A generated universe compiles with a
14//! bare `ghc`, with no package database and no network.
15//!
16//! # Names
17//!
18//! Haskell puts every field, constructor and function in a module into one
19//! space, where the other targets give each struct its own. Two structs that
20//! both have an `id` cannot both have a field called `id`, and an inherited
21//! one is carried by the child too. So a field is named after the type that
22//! holds it — `circleId`, `circleRadius` — which is also what a reserved word
23//! cannot be, and a variant after its enum — `SizeLarge`. The wire keeps its
24//! own names, written into the instances. If two declarations would still come
25//! out as one name, generation says so rather than choosing.
26//!
27//! # Inheritance
28//!
29//! Haskell has none, so a child carries every field it has, inherited or not,
30//! as Rust does. An interface becomes a class of accessors, and a struct that
31//! claims one gets an instance, so a bound on a generic parameter is a class
32//! constraint.
33//!
34//! # Bodies
35//!
36//! A body is written with the Prelude qualified, so a parameter called `length`
37//! or `map` cannot capture what the body means by them; nothing from the
38//! Prelude is imported by name but the types and the operators. The checker
39//! takes a `T` wherever a `T?` is wanted and Haskell does not, so a body is
40//! written knowing what each part produces and what the place it stands in
41//! wants, which is `Just` where a value that is there goes into one that may
42//! not be.
43
44use std::collections::{BTreeMap, BTreeSet, HashMap};
45
46use unitype_core::check::CheckedWorkspace;
47use unitype_core::ir::{
48    AliasDef, EnumDef, Expr, Field, FunctionSig, InterfaceDef, LiteralValue, PrimOp, StructDef,
49    Type, TypeDef, TypeParamDecl, TypeRef, Universe,
50};
51use unitype_core::lang::{LanguageProfile, profile};
52use unitype_core::value::Value;
53use unitype_core::{Ident, QualifiedName};
54
55use crate::writer::CodeWriter;
56use crate::{
57    Backend, GenError, GenOptions, GeneratedFile, header, ordered_defs, refs_in, selected,
58};
59
60/// The Haskell backend.
61pub struct Haskell;
62
63/// The module every universe's instances are written against.
64const SUPPORT: &str = "UnitypeSupport";
65
66/// The module that makes a filled-in file reachable as a proof.
67const HARNESS: &str = "UnitypeHarness";
68
69/// The largest tuple the support module can read and write.
70const TUPLE_LIMIT: usize = 7;
71
72impl Backend for Haskell {
73    fn id(&self) -> &'static str {
74        "haskell"
75    }
76
77    fn extension(&self) -> &'static str {
78        "hs"
79    }
80
81    fn generate(
82        &self,
83        ws: &CheckedWorkspace,
84        options: &GenOptions,
85    ) -> Result<Vec<GeneratedFile>, GenError> {
86        let profile = profile("haskell")?;
87        crate::refuse_higher_order(ws, options, "haskell")?;
88        let chosen = selected(ws, options);
89
90        let mut modules: BTreeMap<String, &Ident> = BTreeMap::new();
91        for universe in &chosen {
92            let module = module_name(&universe.name);
93            if module == SUPPORT || module == HARNESS {
94                return Err(unsupported(
95                    format!("a universe named `{}`", universe.name),
96                    format!("that is the module `{module}`, which is written beside the universes"),
97                ));
98            }
99            if let Some(other) = modules.insert(module.clone(), &universe.name) {
100                return Err(unsupported(
101                    format!("universes named `{other}` and `{}`", universe.name),
102                    format!("both would be the module `{module}`"),
103                ));
104            }
105        }
106
107        check_cycles(ws, &chosen, options)?;
108
109        let mut files = Vec::new();
110        for universe in &chosen {
111            files.push(GeneratedFile {
112                path: format!("haskell/{}.hs", module_name(&universe.name)).into(),
113                contents: universe_file(ws, universe, &profile, options)?,
114            });
115        }
116        files.push(GeneratedFile {
117            path: format!("haskell/{SUPPORT}.hs").into(),
118            contents: SUPPORT_MODULE.to_string(),
119        });
120        if options.harness {
121            files.push(GeneratedFile {
122                path: format!("haskell/{HARNESS}.hs").into(),
123                contents: HARNESS_MODULE.to_string(),
124            });
125        }
126        Ok(files)
127    }
128}
129
130/// What every generated universe is written against.
131const SUPPORT_MODULE: &str = include_str!("haskell/UnitypeSupport.hs");
132
133/// The harness that makes a filled-in module reachable as a proof.
134const HARNESS_MODULE: &str = include_str!("haskell/UnitypeHarness.hs");
135
136fn unsupported(what: String, detail: String) -> GenError {
137    GenError::Unsupported {
138        language: "haskell".into(),
139        what,
140        detail,
141    }
142}
143
144// ---------------------------------------------------------------------------
145// Names
146
147fn ident(text: &str) -> Ident {
148    Ident::new(text).expect("a name built out of identifiers is one")
149}
150
151fn upper_first(text: &str) -> String {
152    let mut chars = text.chars();
153    match chars.next() {
154        Some(first) => first.to_uppercase().chain(chars).collect(),
155        None => String::new(),
156    }
157}
158
159fn lower_first(text: &str) -> String {
160    let mut chars = text.chars();
161    match chars.next() {
162        Some(first) => first.to_lowercase().chain(chars).collect(),
163        None => String::new(),
164    }
165}
166
167/// The module a universe is written to: its name, beginning with a capital.
168fn module_name(universe: &Ident) -> String {
169    let name = upper_first(universe.as_str());
170    if name.starts_with(|c: char| c.is_ascii_uppercase()) {
171        name
172    } else {
173        format!("U{name}")
174    }
175}
176
177/// What a type is called. Haskell's begin with a capital.
178fn type_name(profile: &LanguageProfile, name: &Ident) -> String {
179    let named = upper_first(name.as_str());
180    let named = if named.starts_with(|c: char| c.is_ascii_uppercase()) {
181        named
182    } else {
183        format!("U{named}")
184    };
185    profile.name(&ident(&named))
186}
187
188/// What one alternative of an enum is called: after the enum, since a
189/// constructor is named in a space shared with every other in the module.
190fn variant_name(profile: &LanguageProfile, owner: &Ident, tag: &str) -> String {
191    let owner = type_name(profile, owner);
192    profile.name(&ident(&format!("{owner}{}", upper_first(tag))))
193}
194
195/// What a field is called: after the type that holds it.
196fn field_name(profile: &LanguageProfile, owner: &Ident, field: &Ident) -> String {
197    let owner = lower_first(&type_name(profile, owner));
198    profile.name(&ident(&format!("{owner}{}", upper_first(field.as_str()))))
199}
200
201/// What a generic parameter is called. Haskell's begin with a lower-case letter.
202fn tyvar(profile: &LanguageProfile, name: &Ident) -> String {
203    let named = lower_first(name.as_str());
204    let named = if named.starts_with('_') {
205        format!("t{named}")
206    } else {
207        named
208    };
209    profile.name(&ident(&named))
210}
211
212/// What a function, a parameter or a local binding is called.
213fn var(profile: &LanguageProfile, name: &Ident) -> String {
214    profile.name(&ident(&lower_first(name.as_str())))
215}
216
217/// A name nothing else in the same declaration has taken, numbered if it has to
218/// be.
219fn distinct(name: String, taken: &mut BTreeSet<String>) -> String {
220    let mut candidate = name.clone();
221    let mut n = 2;
222    while !taken.insert(candidate.clone()) {
223        candidate = format!("{name}{n}");
224        n += 1;
225    }
226    candidate
227}
228
229/// A declaration's parameters, as Haskell names them.
230fn tyvars(profile: &LanguageProfile, params: &[TypeParamDecl]) -> Vec<String> {
231    params.iter().map(|p| tyvar(profile, &p.name)).collect()
232}
233
234/// A declaration's head: its name, then its parameters.
235fn head(name: &str, vars: &[String]) -> String {
236    if vars.is_empty() {
237        name.to_string()
238    } else {
239        format!("{name} {}", vars.join(" "))
240    }
241}
242
243/// A declaration's head, bracketed to stand as an instance's subject.
244fn subject(name: &str, vars: &[String]) -> String {
245    if vars.is_empty() {
246        name.to_string()
247    } else {
248        format!("({})", head(name, vars))
249    }
250}
251
252// ---------------------------------------------------------------------------
253// Spelling
254
255/// How Haskell writes a type.
256fn spell(profile: &LanguageProfile, ty: &Type) -> String {
257    profile.spell(&named(profile, ty))
258}
259
260/// A type with every name it mentions as Haskell has it, so that the profile
261/// spells it rather than the universe's own.
262fn named(profile: &LanguageProfile, ty: &Type) -> Type {
263    let kids: Vec<Type> = ty
264        .children()
265        .into_iter()
266        .map(|c| named(profile, c))
267        .collect();
268    match ty.with_children(kids) {
269        Type::Ref(mut r) => {
270            r.name = ident(&type_name(profile, &r.name));
271            Type::Ref(r)
272        }
273        Type::Param { name } => Type::Param {
274            name: ident(&tyvar(profile, &name)),
275        },
276        Type::Map { key, value } => Type::Map {
277            key: Box::new(map_key(*key)),
278            value,
279        },
280        other => other,
281    }
282}
283
284/// What the keys of a map are held as.
285///
286/// A key may be a literal, or a union of them, and Haskell has no type that is
287/// only some strings. It is held as the kind of key it is made of, which is
288/// also what it is on the wire: the text of a property name.
289fn map_key(key: Type) -> Type {
290    match key {
291        Type::Literal { value } => value.base(),
292        Type::Union { members } => {
293            let held: Vec<Type> = members.into_iter().map(map_key).collect();
294            if held.iter().all(|k| matches!(k, Type::I32 | Type::I64)) {
295                Type::I64
296            } else {
297                Type::String
298            }
299        }
300        other => other,
301    }
302}
303
304/// Whether Haskell holds a type as parsed JSON, for want of a name for it.
305fn is_json(ty: &Type) -> bool {
306    matches!(
307        ty,
308        Type::Any | Type::Union { .. } | Type::Record { .. } | Type::Function { .. }
309    )
310}
311
312fn is_string_literal(ty: &Type) -> bool {
313    matches!(
314        ty,
315        Type::Literal {
316            value: LiteralValue::Str(_)
317        }
318    )
319}
320
321/// An alternative of an untagged union, as the sum type written for it has it.
322struct Member {
323    /// The constructor.
324    ctor: String,
325    /// What it carries.
326    ty: Type,
327    /// The text it stands for, when the union is nothing but strings.
328    text: Option<String>,
329}
330
331/// The alternatives of an alias that is a union.
332///
333/// A union of nothing but strings is a set of names, and Haskell has a word for
334/// that: a sum whose constructors carry nothing, each one travelling as the
335/// string it stands for. Any other union is tried in order.
336fn union_members(profile: &LanguageProfile, def: &AliasDef) -> Vec<Member> {
337    let Type::Union { members } = &def.target else {
338        return Vec::new();
339    };
340    let owner = type_name(profile, &def.name);
341    let names = members.iter().all(is_string_literal);
342    let mut taken = BTreeSet::new();
343    members
344        .iter()
345        .map(|member| {
346            let (stem, text) = match member {
347                Type::Literal {
348                    value: LiteralValue::Str(text),
349                } if names => (name_for(text), Some(text.clone())),
350                Type::Ref(r) => (upper_first(r.name.as_str()), None),
351                other => (name_for(&spell(profile, other)), None),
352            };
353            Member {
354                ctor: distinct(profile.name(&ident(&format!("{owner}{stem}"))), &mut taken),
355                ty: member.clone(),
356                text,
357            }
358        })
359        .collect()
360}
361
362/// A constructor's name for some text: its words, capitalised and run together.
363fn name_for(text: &str) -> String {
364    let mut out = String::new();
365    let mut capitalize = true;
366    for c in text.chars() {
367        if c.is_ascii_alphanumeric() {
368            if capitalize {
369                out.extend(c.to_uppercase());
370                capitalize = false;
371            } else {
372                out.push(c);
373            }
374        } else {
375            capitalize = true;
376        }
377    }
378    if out.is_empty() { "Other".into() } else { out }
379}
380
381/// Whether a declaration is a sum type written for a union.
382fn is_union_alias(def: &TypeDef) -> bool {
383    matches!(def, TypeDef::Alias(a) if matches!(a.target, Type::Union { .. }))
384}
385
386// ---------------------------------------------------------------------------
387// A universe
388
389fn universe_file(
390    ws: &CheckedWorkspace,
391    universe: &Universe,
392    profile: &LanguageProfile,
393    options: &GenOptions,
394) -> Result<String, GenError> {
395    check_expressible(ws, universe)?;
396    let defs = ordered_defs(universe);
397    check_names(ws, profile, universe, &defs, options)?;
398
399    let mut w = CodeWriter::with_indent("  ");
400    if options.header {
401        for line in header("--", universe, ws) {
402            w.line(line);
403        }
404        w.blank();
405    }
406
407    w.line("{-# LANGUAGE OverloadedStrings #-}");
408    if needs_classes_over_several_types(universe) {
409        w.line("{-# LANGUAGE FlexibleContexts #-}");
410        w.line("{-# LANGUAGE FlexibleInstances #-}");
411        w.line("{-# LANGUAGE FunctionalDependencies #-}");
412        w.line("{-# LANGUAGE MultiParamTypeClasses #-}");
413    }
414    // What is imported is what a universe might need, not what this one does.
415    w.line("{-# OPTIONS_GHC -Wno-unused-imports #-}");
416    if let Some(doc) = &universe.doc {
417        haddock(&mut w, doc);
418    }
419    w.write(format_args!("module {} where", module_name(&universe.name)));
420    w.blank();
421
422    imports(&mut w, ws, universe, options);
423
424    for def in defs {
425        match def {
426            TypeDef::Struct(d) => emit_struct(&mut w, ws, universe, d, profile),
427            TypeDef::Interface(d) => emit_interface(&mut w, ws, universe, d, profile),
428            TypeDef::Enum(d) => emit_enum(&mut w, d, profile),
429            TypeDef::Alias(d) => emit_alias(&mut w, d, profile),
430        }
431        w.blank();
432    }
433
434    if options.stubs {
435        for sig in &universe.functions {
436            emit_signature(&mut w, ws, universe, sig, profile);
437            w.blank();
438        }
439    }
440
441    Ok(w.finish())
442}
443
444/// Refuses what the support module has no way to carry.
445fn check_expressible(ws: &CheckedWorkspace, universe: &Universe) -> Result<(), GenError> {
446    let mut refusal = None;
447    for_each_type(universe, &mut |ty| {
448        fn too_wide(ty: &Type) -> Option<usize> {
449            match ty {
450                Type::Tuple { items } if items.len() > TUPLE_LIMIT => Some(items.len()),
451                _ => ty.children().into_iter().find_map(too_wide),
452            }
453        }
454        if refusal.is_none() {
455            refusal = too_wide(ty);
456        }
457    });
458    if let Some(size) = refusal {
459        return Err(unsupported(
460            format!("a tuple of {size}"),
461            format!("the support module reads and writes tuples of up to {TUPLE_LIMIT}"),
462        ));
463    }
464    // A class is not a type: `Named` can be required of a parameter, but a
465    // field of that type would have to be of some type it names, and which one
466    // is not something JSON says.
467    for (place, ty) in held(universe) {
468        if let Some(interface) = interface_in(ws, ty) {
469            return Err(unsupported(
470                format!("`{place}`, whose type is the interface `{interface}`"),
471                "a Haskell class is not a type, so nothing can have one for its type; \
472                 bound a generic parameter by it instead"
473                    .into(),
474            ));
475        }
476    }
477    for def in &universe.types {
478        if matches!(def, TypeDef::Enum(d) if d.variants.is_empty()) {
479            return Err(unsupported(
480                format!("the enum `{}`", def.name()),
481                "it has no variants, so there is nothing for a constructor to be".into(),
482            ));
483        }
484        // What travels is read and written as JSON, and a wait is neither.
485        let held: Vec<(String, &Type)> = match def {
486            TypeDef::Struct(d) => d
487                .fields
488                .iter()
489                .map(|f| (format!("{}.{}", d.name, f.name), &f.ty))
490                .collect(),
491            TypeDef::Enum(d) => d
492                .variants
493                .iter()
494                .map(|v| (format!("{}.{}", d.name, v.name), &v.payload))
495                .collect(),
496            TypeDef::Alias(d) if matches!(d.target, Type::Union { .. }) => {
497                vec![(d.name.to_string(), &d.target)]
498            }
499            _ => Vec::new(),
500        };
501        for (place, ty) in held {
502            if waits(ws, ty) {
503                return Err(unsupported(
504                    format!("`{place}`, which holds a future"),
505                    "a wait cannot be written as JSON, so a type that travels cannot hold one"
506                        .into(),
507                ));
508            }
509        }
510    }
511    Ok(())
512}
513
514/// Every place a universe holds a value of some type: a field, a payload, a
515/// parameter, a result, and what an alias stands for. Where a type only bounds
516/// a parameter is not one.
517fn held(universe: &Universe) -> Vec<(String, &Type)> {
518    let mut out: Vec<(String, &Type)> = Vec::new();
519    for def in &universe.types {
520        match def {
521            TypeDef::Struct(d) => out.extend(
522                d.fields
523                    .iter()
524                    .map(|f| (format!("{}.{}", d.name, f.name), &f.ty)),
525            ),
526            TypeDef::Interface(d) => out.extend(
527                d.fields
528                    .iter()
529                    .map(|f| (format!("{}.{}", d.name, f.name), &f.ty)),
530            ),
531            TypeDef::Enum(d) => out.extend(
532                d.variants
533                    .iter()
534                    .map(|v| (format!("{}.{}", d.name, v.name), &v.payload)),
535            ),
536            TypeDef::Alias(d) => out.push((d.name.to_string(), &d.target)),
537        }
538    }
539    for sig in &universe.functions {
540        out.extend(
541            sig.params
542                .iter()
543                .map(|p| (format!("{}({})", sig.name, p.name), &p.ty)),
544        );
545        out.push((format!("{} returns", sig.name), &sig.ret));
546    }
547    out
548}
549
550/// The interface a type is, or holds, if there is one.
551fn interface_in(ws: &CheckedWorkspace, ty: &Type) -> Option<Ident> {
552    let ty = Resolver { ws }.resolve(ty);
553    if let Type::Ref(r) = &ty {
554        if let Some(TypeDef::Interface(_)) = ws.ref_target_of(r).and_then(|q| ws.def(&q)) {
555            return Some(r.name.clone());
556        }
557    }
558    ty.children()
559        .into_iter()
560        .find_map(|child| interface_in(ws, child))
561}
562
563/// Whether a type has a future anywhere in it, through any alias.
564fn waits(ws: &CheckedWorkspace, ty: &Type) -> bool {
565    let ty = Resolver { ws }.resolve(ty);
566    matches!(ty, Type::Future { .. }) || ty.children().into_iter().any(|child| waits(ws, child))
567}
568
569/// Refuses a universe where two declarations would come out as one name.
570///
571/// Haskell keeps every type, every constructor and every field or function in a
572/// module in a space of its own, so a clash is only a clash within one.
573fn check_names(
574    ws: &CheckedWorkspace,
575    profile: &LanguageProfile,
576    universe: &Universe,
577    defs: &[&TypeDef],
578    options: &GenOptions,
579) -> Result<(), GenError> {
580    let mut types: BTreeMap<String, String> = BTreeMap::new();
581    let mut constructors: BTreeMap<String, String> = BTreeMap::new();
582    let mut values: BTreeMap<String, String> = BTreeMap::new();
583
584    let claim = |space: &mut BTreeMap<String, String>, name: String, what: String| match space
585        .insert(name.clone(), what.clone())
586    {
587        Some(first) if first != what => Err(unsupported(
588            format!("`{first}` and `{what}`"),
589            format!(
590                "both would be written as `{name}`, and Haskell has one \
591                     space for them in a module"
592            ),
593        )),
594        _ => Ok(()),
595    };
596
597    for def in defs {
598        let what = |part: &str| format!("{}.{part}", def.name());
599        claim(
600            &mut types,
601            type_name(profile, def.name()),
602            def.name().to_string(),
603        )?;
604        match def {
605            TypeDef::Struct(d) => {
606                claim(
607                    &mut constructors,
608                    type_name(profile, &d.name),
609                    def.name().to_string(),
610                )?;
611                // Every field it has, inherited or not, is a function of its own.
612                for field in fields_of(ws, universe, def.name()) {
613                    claim(
614                        &mut values,
615                        field_name(profile, &d.name, &field.name),
616                        what(field.name.as_str()),
617                    )?;
618                }
619            }
620            TypeDef::Interface(d) => {
621                for field in fields_of(ws, universe, def.name()) {
622                    claim(
623                        &mut values,
624                        field_name(profile, &d.name, &field.name),
625                        what(field.name.as_str()),
626                    )?;
627                }
628            }
629            TypeDef::Enum(d) => {
630                for variant in &d.variants {
631                    claim(
632                        &mut constructors,
633                        variant_name(profile, &d.name, variant.name.as_str()),
634                        what(variant.name.as_str()),
635                    )?;
636                }
637            }
638            TypeDef::Alias(d) => {
639                for member in union_members(profile, d) {
640                    claim(&mut constructors, member.ctor, def.name().to_string())?;
641                }
642            }
643        }
644        let vars = tyvars(profile, def.params());
645        let unique: BTreeSet<&String> = vars.iter().collect();
646        if unique.len() != vars.len() {
647            return Err(unsupported(
648                format!("the parameters of `{}`", def.name()),
649                "two of them would be written as one name".into(),
650            ));
651        }
652    }
653    if options.stubs {
654        for sig in &universe.functions {
655            claim(
656                &mut values,
657                var(profile, &sig.name),
658                format!("the function `{}`", sig.name),
659            )?;
660            let params: BTreeSet<String> =
661                sig.params.iter().map(|p| var(profile, &p.name)).collect();
662            if params.len() != sig.params.len() {
663                return Err(unsupported(
664                    format!("the parameters of `{}`", sig.name),
665                    "two of them would be written as one name".into(),
666                ));
667            }
668        }
669    }
670    Ok(())
671}
672
673/// Every field a struct or an interface has, inherited ones included.
674fn fields_of(ws: &CheckedWorkspace, universe: &Universe, name: &Ident) -> Vec<Field> {
675    ws.flat_fields(&QualifiedName::new(universe.name.clone(), name.clone()))
676        .map(<[Field]>::to_vec)
677        .unwrap_or_default()
678}
679
680fn for_each_type(universe: &Universe, f: &mut impl FnMut(&Type)) {
681    for def in &universe.types {
682        match def {
683            TypeDef::Struct(d) => d.fields.iter().for_each(|x| f(&x.ty)),
684            TypeDef::Interface(d) => d.fields.iter().for_each(|x| f(&x.ty)),
685            TypeDef::Enum(d) => d.variants.iter().for_each(|v| f(&v.payload)),
686            TypeDef::Alias(d) => f(&d.target),
687        }
688        for bound in def.params().iter().flat_map(|p| &p.bounds) {
689            f(&Type::Ref(bound.clone()));
690        }
691    }
692    for sig in &universe.functions {
693        sig.params.iter().for_each(|p| f(&p.ty));
694        f(&sig.ret);
695        for bound in sig.params_decl.iter().flat_map(|p| &p.bounds) {
696            f(&Type::Ref(bound.clone()));
697        }
698    }
699}
700
701/// Whether anything here is a class over more than the type it is for: a
702/// generic interface, or a bound or a claim that gives one arguments.
703fn needs_classes_over_several_types(universe: &Universe) -> bool {
704    let applied = |r: &TypeRef| !r.args.is_empty();
705    universe.types.iter().any(|def| match def {
706        TypeDef::Interface(d) => !d.params.is_empty(),
707        TypeDef::Struct(d) => d.implements.iter().any(applied),
708        _ => false,
709    }) || universe
710        .types
711        .iter()
712        .flat_map(|d| d.params())
713        .chain(universe.functions.iter().flat_map(|f| &f.params_decl))
714        .flat_map(|p| &p.bounds)
715        .any(applied)
716}
717
718// ---------------------------------------------------------------------------
719// Imports
720
721/// A declaration another universe's module has to be asked for.
722struct Wanted {
723    /// Whether its constructors, fields or methods come with it.
724    open: bool,
725}
726
727fn imports(w: &mut CodeWriter, ws: &CheckedWorkspace, universe: &Universe, options: &GenOptions) {
728    // Only operators and types by name: every other word the Prelude has is
729    // reached as `P.word`, so that nothing a universe declares can clash.
730    w.line("import Prelude");
731    w.indented(|w| {
732        w.line("( Bool (..)");
733        w.line(", Double");
734        w.line(", Either (..)");
735        w.line(", Eq");
736        w.line(", IO");
737        w.line(", Maybe (..)");
738        w.line(", Ord");
739        w.line(", Show");
740        w.line(", (&&), (||), (==), (/=), (<), (<=), (>), (>=), (+), (-), (*), (<$>), (<*>)");
741        w.line(")");
742    });
743    w.line("import qualified Prelude as P");
744    w.line("import Data.ByteString (ByteString)");
745    w.line("import qualified Data.ByteString as BS");
746    w.line("import Data.Int (Int32, Int64)");
747    w.line("import qualified Data.List");
748    w.line("import Data.Map.Strict (Map)");
749    w.line("import qualified Data.Map.Strict as Map");
750    w.line("import Data.Text (Text)");
751    w.line("import Data.Void (Void)");
752    w.write(format_args!("import {SUPPORT} (Json (..))"));
753    w.write(format_args!("import qualified {SUPPORT} as U"));
754
755    // Asked for by module, in the order modules sort.
756    let asked = needs(ws, universe, options);
757    let mut modules: BTreeMap<String, Vec<String>> = BTreeMap::new();
758    for (from, wanted) in &asked.types {
759        let names = modules.entry(module_name(from)).or_default();
760        for (name, wanted) in wanted {
761            names.push(if wanted.open {
762                format!("{name} (..)")
763            } else {
764                name.clone()
765            });
766        }
767    }
768    for (from, called) in &asked.functions {
769        modules
770            .entry(module_name(from))
771            .or_default()
772            .extend(called.iter().cloned());
773    }
774    for (module, names) in modules {
775        w.write(format_args!("import {module} ({})", names.join(", ")));
776    }
777    w.blank();
778}
779
780/// What a universe asks of the others: the declarations it names and the
781/// functions it calls, by the universe that has them and as Haskell names them.
782#[derive(Default)]
783struct Needs {
784    types: BTreeMap<Ident, BTreeMap<String, Wanted>>,
785    functions: BTreeMap<Ident, BTreeSet<String>>,
786}
787
788fn needs(ws: &CheckedWorkspace, universe: &Universe, options: &GenOptions) -> Needs {
789    let profile = profile("haskell").expect("ships");
790    let mut asked = Needs::default();
791
792    let mut want_type = |r: &TypeRef| {
793        let Some(from) = &r.universe else { return };
794        if from == &universe.name {
795            return;
796        }
797        let open = ws
798            .def(&QualifiedName::new(from.clone(), r.name.clone()))
799            .is_none_or(|def| !matches!(def, TypeDef::Alias(_)) || is_union_alias(def));
800        asked
801            .types
802            .entry(from.clone())
803            .or_default()
804            .insert(type_name(&profile, &r.name), Wanted { open });
805    };
806    let mut note = |ty: &Type| refs_in(ty, &mut |r| want_type(r));
807    for_each_type(universe, &mut |ty| note(ty));
808    for def in &universe.types {
809        match def {
810            TypeDef::Struct(d) => d
811                .extends
812                .iter()
813                .chain(&d.implements)
814                .for_each(|r| note(&Type::Ref(r.clone()))),
815            TypeDef::Interface(d) => d.extends.iter().for_each(|r| note(&Type::Ref(r.clone()))),
816            _ => {}
817        }
818    }
819    let mut called_elsewhere: Vec<&QualifiedName> = Vec::new();
820    if options.stubs {
821        for sig in &universe.functions {
822            let Some(body) = &sig.body else { continue };
823            body.walk(&mut |e| match e {
824                Expr::MakeRecord { ty, .. }
825                | Expr::MakeVariant { ty, .. }
826                | Expr::Match { ty, .. } => note(&Type::Ref(ty.clone())),
827                Expr::Call { sig: called, .. } if called.universe != universe.name => {
828                    called_elsewhere.push(called);
829                }
830                _ => {}
831            });
832        }
833    }
834    for called in called_elsewhere {
835        asked
836            .functions
837            .entry(called.universe.clone())
838            .or_default()
839            .insert(var(&profile, &called.name));
840    }
841    asked
842}
843
844/// Refuses universes that import each other, which Haskell modules cannot.
845fn check_cycles(
846    ws: &CheckedWorkspace,
847    chosen: &[&Universe],
848    options: &GenOptions,
849) -> Result<(), GenError> {
850    let graph: BTreeMap<Ident, BTreeSet<Ident>> = chosen
851        .iter()
852        .map(|u| {
853            let asked = needs(ws, u, options);
854            let wanted = asked.types.into_keys().chain(asked.functions.into_keys());
855            (u.name.clone(), wanted.collect())
856        })
857        .collect();
858
859    fn visit<'a>(
860        at: &'a Ident,
861        graph: &'a BTreeMap<Ident, BTreeSet<Ident>>,
862        path: &mut Vec<&'a Ident>,
863        cleared: &mut BTreeSet<&'a Ident>,
864    ) -> Option<Vec<&'a Ident>> {
865        if let Some(start) = path.iter().position(|seen| *seen == at) {
866            return Some(path[start..].to_vec());
867        }
868        if cleared.contains(at) {
869            return None;
870        }
871        path.push(at);
872        for next in graph.get(at).into_iter().flatten() {
873            // A universe that was not asked for is not written, so cannot be
874            // one end of a cycle.
875            if graph.contains_key(next) {
876                if let Some(cycle) = visit(next, graph, path, cleared) {
877                    return Some(cycle);
878                }
879            }
880        }
881        path.pop();
882        cleared.insert(at);
883        None
884    }
885
886    let mut cleared = BTreeSet::new();
887    for start in graph.keys() {
888        if let Some(cycle) = visit(start, &graph, &mut Vec::new(), &mut cleared) {
889            let mut names: Vec<String> = cycle.iter().map(|u| format!("`{u}`")).collect();
890            names.push(format!("`{}`", cycle[0]));
891            return Err(unsupported(
892                format!("universes that refer to each other: {}", names.join(" -> ")),
893                "each is a module that imports the next, and Haskell modules cannot import \
894                 each other in a cycle"
895                    .into(),
896            ));
897        }
898    }
899    Ok(())
900}
901
902// ---------------------------------------------------------------------------
903// Documentation
904
905/// Writes prose as a Haddock comment: `-- |` once, then `--` for the rest.
906fn haddock(w: &mut CodeWriter, text: &str) {
907    w.comment("-- ", &format!("| {text}"));
908}
909
910/// Writes prose as a Haddock comment on what came before it: `-- ^`.
911fn trailing(w: &mut CodeWriter, text: &str) {
912    w.comment("-- ", &format!("^ {text}"));
913}
914
915// ---------------------------------------------------------------------------
916// Instances
917
918/// The context an instance of a class asks of a declaration's parameters.
919fn context(class: &str, vars: &[String]) -> String {
920    match vars {
921        [] => String::new(),
922        [only] => format!("{class} {only} => "),
923        several => format!(
924            "({}) => ",
925            several
926                .iter()
927                .map(|v| format!("{class} {v}"))
928                .collect::<Vec<_>>()
929                .join(", ")
930        ),
931    }
932}
933
934fn instance_head(class: &str, name: &str, vars: &[String]) -> String {
935    format!(
936        "instance {}{class} {} where",
937        context(class, vars),
938        subject(name, vars)
939    )
940}
941
942/// What a field is read as: one that may be left out is read from nothing.
943///
944/// Anything that expands to `T?`, `null` or `any` may be absent, and so may a
945/// bare generic parameter, since the argument may be one of those.
946fn may_be_left_out(ws: &CheckedWorkspace, ty: &Type) -> bool {
947    matches!(
948        Resolver { ws }.resolve(ty),
949        Type::Optional { .. } | Type::Unit | Type::Any | Type::Param { .. }
950    )
951}
952
953// ---------------------------------------------------------------------------
954// Structs
955
956fn emit_struct(
957    w: &mut CodeWriter,
958    ws: &CheckedWorkspace,
959    universe: &Universe,
960    def: &StructDef,
961    profile: &LanguageProfile,
962) {
963    // Every field it has, inherited or not: the wire has no notion of where a
964    // field came from, and neither does the reader.
965    let fields = fields_of(ws, universe, &def.name);
966    let type_ = type_name(profile, &def.name);
967    let vars = tyvars(profile, &def.params);
968
969    if let Some(doc) = &def.doc {
970        haddock(w, doc);
971    }
972    if let Some(parent) = &def.extends {
973        w.comment(
974            "-- ",
975            &format!(
976                "Inherits from `{}`. Haskell has no inheritance, so the fields are \
977                 carried here; the shape on the wire is unchanged.",
978                parent.name
979            ),
980        );
981    }
982
983    if fields.is_empty() {
984        w.write(format_args!(
985            "data {} = {type_} deriving (Eq, Show)",
986            head(&type_, &vars)
987        ));
988    } else {
989        w.write(format_args!("data {} = {type_}", head(&type_, &vars)));
990        w.indented(|w| {
991            for (i, field) in fields.iter().enumerate() {
992                let open = if i == 0 { "{" } else { "," };
993                for caveat in profile.caveats(&field.ty) {
994                    w.comment("-- ", &caveat);
995                }
996                w.write(format_args!(
997                    "{open} {} :: {}",
998                    field_name(profile, &def.name, &field.name),
999                    spell(profile, &field.ty)
1000                ));
1001                if let Some(doc) = &field.doc {
1002                    w.indented(|w| trailing(w, doc));
1003                }
1004            }
1005            w.line("}");
1006            w.line("deriving (Eq, Show)");
1007        });
1008    }
1009
1010    // How it travels.
1011    w.blank();
1012    w.line(instance_head("U.ToJson", &type_, &vars));
1013    w.indented(|w| {
1014        if fields.is_empty() {
1015            w.line("toJson _ = U.object []");
1016            return;
1017        }
1018        w.line("toJson x =");
1019        w.indented(|w| {
1020            w.line("U.object");
1021            w.indented(|w| {
1022                for (i, field) in fields.iter().enumerate() {
1023                    w.write(format_args!(
1024                        "{} U.field {:?} ({} x)",
1025                        if i == 0 { "[" } else { "," },
1026                        field.name.as_str(),
1027                        field_name(profile, &def.name, &field.name)
1028                    ));
1029                }
1030                w.line("]");
1031            });
1032        });
1033    });
1034    w.blank();
1035    w.line(instance_head("U.FromJson", &type_, &vars));
1036    w.indented(|w| {
1037        w.line("fromJson j = do");
1038        w.indented(|w| {
1039            if fields.is_empty() {
1040                w.write(format_args!("_ <- U.asObject {:?} j", type_));
1041                w.write(format_args!("P.pure {type_}"));
1042                return;
1043            }
1044            w.write(format_args!("o <- U.asObject {:?} j", type_));
1045            w.line(&type_);
1046            w.indented(|w| {
1047                for (i, field) in fields.iter().enumerate() {
1048                    let read = if may_be_left_out(ws, &field.ty) {
1049                        "optional"
1050                    } else {
1051                        "required"
1052                    };
1053                    w.write(format_args!(
1054                        "{} U.{read} {:?} o",
1055                        if i == 0 { "<$>" } else { "<*>" },
1056                        field.name.as_str()
1057                    ));
1058                }
1059            });
1060        });
1061    });
1062
1063    // What it claims to satisfy becomes what Haskell can actually dispatch on.
1064    for iface in &def.implements {
1065        let mut applied = iface.clone();
1066        applied.universe = Some(iface.universe.clone().unwrap_or(universe.name.clone()));
1067        let this = Type::Ref(TypeRef {
1068            universe: Some(universe.name.clone()),
1069            name: def.name.clone(),
1070            args: def
1071                .params
1072                .iter()
1073                .map(|p| Type::Param {
1074                    name: p.name.clone(),
1075                })
1076                .collect(),
1077        });
1078        // The class is over the struct first, then whatever it was given.
1079        let mut over = vec![this];
1080        over.extend(applied.args.iter().cloned());
1081        let class = Type::Ref(TypeRef {
1082            universe: applied.universe.clone(),
1083            name: applied.name.clone(),
1084            args: over,
1085        });
1086        w.blank();
1087        w.write(format_args!("instance {} where", spell(profile, &class)));
1088        w.indented(|w| {
1089            for required in ws.fields_of(&applied).unwrap_or_default() {
1090                w.write(format_args!(
1091                    "{} = {}",
1092                    field_name(profile, &applied.name, &required.name),
1093                    field_name(profile, &def.name, &required.name)
1094                ));
1095            }
1096        });
1097    }
1098}
1099
1100// ---------------------------------------------------------------------------
1101// Interfaces
1102
1103fn emit_interface(
1104    w: &mut CodeWriter,
1105    ws: &CheckedWorkspace,
1106    universe: &Universe,
1107    def: &InterfaceDef,
1108    profile: &LanguageProfile,
1109) {
1110    if let Some(doc) = &def.doc {
1111        haddock(w, doc);
1112    }
1113    let fields = fields_of(ws, universe, &def.name);
1114
1115    // A field contract is a class of accessors: the closest thing Haskell has
1116    // to "anything with these fields". It is over the type that has them, and
1117    // over whatever the interface is generic in, which that type decides.
1118    let vars = tyvars(profile, &def.params);
1119    let mut this = "self".to_string();
1120    while vars.contains(&this) {
1121        this.push('\'');
1122    }
1123    let mut over = vec![this.clone()];
1124    over.extend(vars.iter().cloned());
1125    let mut declared = format!("class {}", head(&type_name(profile, &def.name), &over));
1126    if !vars.is_empty() {
1127        declared.push_str(&format!(" | {this} -> {}", vars.join(" ")));
1128    }
1129    if fields.is_empty() {
1130        w.line(declared);
1131        return;
1132    }
1133    w.write(format_args!("{declared} where"));
1134    w.indented(|w| {
1135        for (i, field) in fields.iter().enumerate() {
1136            if i > 0 {
1137                w.blank();
1138            }
1139            w.write(format_args!(
1140                "{} :: {this} -> {}",
1141                field_name(profile, &def.name, &field.name),
1142                spell(profile, &field.ty)
1143            ));
1144            if let Some(doc) = &field.doc {
1145                w.indented(|w| trailing(w, doc));
1146            }
1147        }
1148    });
1149}
1150
1151// ---------------------------------------------------------------------------
1152// Enums
1153
1154fn emit_enum(w: &mut CodeWriter, def: &EnumDef, profile: &LanguageProfile) {
1155    if let Some(doc) = &def.doc {
1156        haddock(w, doc);
1157    }
1158    let type_ = type_name(profile, &def.name);
1159    let vars = tyvars(profile, &def.params);
1160
1161    w.write(format_args!("data {}", head(&type_, &vars)));
1162    w.indented(|w| {
1163        for (i, variant) in def.variants.iter().enumerate() {
1164            let open = if i == 0 { "=" } else { "|" };
1165            let ctor = variant_name(profile, &def.name, variant.name.as_str());
1166            if matches!(variant.payload, Type::Unit) {
1167                w.write(format_args!("{open} {ctor}"));
1168            } else {
1169                w.write(format_args!(
1170                    "{open} {ctor} {}",
1171                    atom_type(profile, &variant.payload)
1172                ));
1173            }
1174            if let Some(doc) = &variant.doc {
1175                w.indented(|w| trailing(w, doc));
1176            }
1177        }
1178        w.line("deriving (Eq, Show)");
1179    });
1180
1181    // The wire tags a variant `$tag` and puts what it carries beside it.
1182    w.blank();
1183    w.line(instance_head("U.ToJson", &type_, &vars));
1184    w.indented(|w| {
1185        for variant in &def.variants {
1186            let ctor = variant_name(profile, &def.name, variant.name.as_str());
1187            if matches!(variant.payload, Type::Unit) {
1188                w.write(format_args!(
1189                    "toJson {ctor} = U.variant {:?} Nothing",
1190                    variant.name.as_str()
1191                ));
1192            } else {
1193                w.write(format_args!(
1194                    "toJson ({ctor} x) = U.variant {:?} (Just (U.toJson x))",
1195                    variant.name.as_str()
1196                ));
1197            }
1198        }
1199    });
1200    w.blank();
1201    w.line(instance_head("U.FromJson", &type_, &vars));
1202    w.indented(|w| {
1203        w.line("fromJson j = do");
1204        w.indented(|w| {
1205            w.write(format_args!("(tag, carried) <- U.asVariant {:?} j", type_));
1206            w.line("case tag of");
1207            w.indented(|w| {
1208                for variant in &def.variants {
1209                    let ctor = variant_name(profile, &def.name, variant.name.as_str());
1210                    if matches!(variant.payload, Type::Unit) {
1211                        w.write(format_args!("{:?} -> P.pure {ctor}", variant.name.as_str()));
1212                    } else {
1213                        w.write(format_args!(
1214                            "{:?} -> {ctor} <$> U.payload {:?} carried",
1215                            variant.name.as_str(),
1216                            variant.name.as_str()
1217                        ));
1218                    }
1219                }
1220                w.write(format_args!("_ -> Left (U.unknownTag {:?} tag)", type_));
1221            });
1222        });
1223    });
1224}
1225
1226/// A type written to stand as the argument of a constructor.
1227fn atom_type(profile: &LanguageProfile, ty: &Type) -> String {
1228    let spelled = spell(profile, ty);
1229    if spelled.contains(' ') && !is_bracketed(&spelled) {
1230        format!("({spelled})")
1231    } else {
1232        spelled
1233    }
1234}
1235
1236/// Whether the whole of some text is one bracketed group.
1237fn is_bracketed(text: &str) -> bool {
1238    let close = match text.chars().next() {
1239        Some('(') => ')',
1240        Some('[') => ']',
1241        _ => return false,
1242    };
1243    let mut closed_at = None;
1244    scan(text, |i, c, nesting| {
1245        if closed_at.is_none() && nesting == 0 && c == close {
1246            closed_at = Some(i + c.len_utf8());
1247        }
1248    });
1249    closed_at == Some(text.len())
1250}
1251
1252/// Walks some Haskell text, telling `visit` each character that is not inside
1253/// a string and how many brackets deep it is, counted before it.
1254fn scan(text: &str, mut visit: impl FnMut(usize, char, usize)) {
1255    let mut depth = 0usize;
1256    let mut in_string = false;
1257    let mut escaped = false;
1258    for (i, c) in text.char_indices() {
1259        if in_string {
1260            match (escaped, c) {
1261                (true, _) => escaped = false,
1262                (false, '\\') => escaped = true,
1263                (false, '"') => in_string = false,
1264                _ => {}
1265            }
1266            continue;
1267        }
1268        match c {
1269            '"' => in_string = true,
1270            '(' | '[' | '{' => {
1271                // An opening bracket is at the depth outside it.
1272                visit(i, c, depth);
1273                depth += 1;
1274            }
1275            ')' | ']' | '}' => {
1276                depth = depth.saturating_sub(1);
1277                visit(i, c, depth);
1278            }
1279            _ => visit(i, c, depth),
1280        }
1281    }
1282}
1283
1284/// Whether some text has a comma that is not inside brackets or a string.
1285fn has_top_level_comma(text: &str) -> bool {
1286    let mut found = false;
1287    scan(text, |_, c, depth| found |= c == ',' && depth == 0);
1288    found
1289}
1290
1291// ---------------------------------------------------------------------------
1292// Aliases
1293
1294fn emit_alias(w: &mut CodeWriter, def: &AliasDef, profile: &LanguageProfile) {
1295    if let Some(doc) = &def.doc {
1296        haddock(w, doc);
1297    }
1298    let type_ = type_name(profile, &def.name);
1299    let vars = tyvars(profile, &def.params);
1300
1301    let Type::Union { .. } = &def.target else {
1302        w.write(format_args!(
1303            "type {} = {}",
1304            head(&type_, &vars),
1305            spell(profile, &def.target)
1306        ));
1307        return;
1308    };
1309    let members = union_members(profile, def);
1310    let names = members.iter().all(|m| m.text.is_some());
1311
1312    w.write(format_args!("data {}", head(&type_, &vars)));
1313    w.indented(|w| {
1314        for (i, member) in members.iter().enumerate() {
1315            let open = if i == 0 { "=" } else { "|" };
1316            if names {
1317                w.write(format_args!("{open} {}", member.ctor));
1318            } else {
1319                w.write(format_args!(
1320                    "{open} {} {}",
1321                    member.ctor,
1322                    atom_type(profile, &member.ty)
1323                ));
1324            }
1325        }
1326        w.line("deriving (Eq, Show)");
1327    });
1328
1329    w.blank();
1330    w.line(instance_head("U.ToJson", &type_, &vars));
1331    w.indented(|w| {
1332        for member in &members {
1333            match &member.text {
1334                Some(text) if names => w.write(format_args!(
1335                    "toJson {} = U.JString {}",
1336                    member.ctor,
1337                    string_literal(text)
1338                )),
1339                _ => w.write(format_args!("toJson ({} x) = U.toJson x", member.ctor)),
1340            }
1341        }
1342    });
1343    w.blank();
1344    w.line(instance_head("U.FromJson", &type_, &vars));
1345    w.indented(|w| {
1346        if names {
1347            w.line("fromJson j = do");
1348            w.indented(|w| {
1349                w.write(format_args!("name <- U.asText {:?} j", type_));
1350                w.line("case name of");
1351                w.indented(|w| {
1352                    for member in &members {
1353                        if let Some(text) = &member.text {
1354                            w.write(format_args!(
1355                                "{} -> P.pure {}",
1356                                string_literal(text),
1357                                member.ctor
1358                            ));
1359                        }
1360                    }
1361                    w.write(format_args!("_ -> Left (U.unknownName {:?} name)", type_));
1362                });
1363            });
1364        } else {
1365            w.write(format_args!("fromJson j = U.firstOf {:?}", type_));
1366            w.indented(|w| {
1367                for (i, member) in members.iter().enumerate() {
1368                    let open = if i == 0 { "[" } else { "," };
1369                    w.write(format_args!("{open} {} <$> U.fromJson j", member.ctor));
1370                }
1371                w.line("]");
1372            });
1373        }
1374    });
1375}
1376
1377// ---------------------------------------------------------------------------
1378// Signatures
1379
1380fn emit_signature(
1381    w: &mut CodeWriter,
1382    ws: &CheckedWorkspace,
1383    universe: &Universe,
1384    sig: &FunctionSig,
1385    profile: &LanguageProfile,
1386) {
1387    let qualified = QualifiedName::new(universe.name.clone(), sig.name.clone());
1388    if let Some(doc) = &sig.doc {
1389        haddock(w, doc);
1390    }
1391    if sig.body.is_none() {
1392        w.comment(
1393            "-- ",
1394            &format!("Implement this and register it as `{qualified}`."),
1395        );
1396    }
1397
1398    // A bound, being an interface, is a class constraint.
1399    let mut constraints: Vec<String> = Vec::new();
1400    for param in &sig.params_decl {
1401        for bound in &param.bounds {
1402            let mut over = vec![Type::Param {
1403                name: param.name.clone(),
1404            }];
1405            over.extend(bound.args.iter().cloned());
1406            constraints.push(spell(
1407                profile,
1408                &Type::Ref(TypeRef {
1409                    universe: bound.universe.clone(),
1410                    name: bound.name.clone(),
1411                    args: over,
1412                }),
1413            ));
1414        }
1415    }
1416    // A body may compare what it is handed.
1417    let compares = sig.body.as_ref().is_some_and(|body| {
1418        let mut found = false;
1419        body.walk(&mut |e| {
1420            found |= matches!(
1421                e,
1422                Expr::Prim {
1423                    op: PrimOp::Eq | PrimOp::Ne,
1424                    ..
1425                }
1426            )
1427        });
1428        found
1429    });
1430    if compares {
1431        for param in &sig.params_decl {
1432            let mentioned = sig.params.iter().any(|p| mentions(&p.ty, &param.name))
1433                || mentions(&sig.ret, &param.name);
1434            if mentioned {
1435                constraints.push(format!("Eq {}", tyvar(profile, &param.name)));
1436            }
1437        }
1438    }
1439
1440    let mut parts: Vec<String> = sig.params.iter().map(|p| spell(profile, &p.ty)).collect();
1441    parts.push(spell(profile, &sig.ret));
1442    let name = var(profile, &sig.name);
1443    let context = match constraints.as_slice() {
1444        [] => String::new(),
1445        [only] => format!("{only} => "),
1446        several => format!("({}) => ", several.join(", ")),
1447    };
1448    w.write(format_args!("{name} :: {context}{}", parts.join(" -> ")));
1449
1450    // A parameter the body never mentions is named so that GHC need not be told.
1451    let mut mentioned: BTreeSet<Ident> = BTreeSet::new();
1452    if let Some(body) = &sig.body {
1453        body.walk(&mut |e| {
1454            if let Expr::Var { name } = e {
1455                mentioned.insert(name.clone());
1456            }
1457        });
1458    }
1459    let params: Vec<String> = sig
1460        .params
1461        .iter()
1462        .map(|p| {
1463            let name = var(profile, &p.name);
1464            if sig.body.is_some() && !mentioned.contains(&p.name) {
1465                format!("_{name}")
1466            } else {
1467                name
1468            }
1469        })
1470        .collect();
1471    match &sig.body {
1472        // A body is a proof already, so it is written out rather than left as a
1473        // hole for someone to fill.
1474        Some(body) => {
1475            let env: Env = sig
1476                .params
1477                .iter()
1478                .map(|p| (p.name.clone(), p.ty.clone()))
1479                .collect();
1480            let text = Body {
1481                ws,
1482                profile,
1483                bounds: &sig.params_decl,
1484            }
1485            .expression(body, &env, Some(&sig.ret));
1486            w.write(format_args!(
1487                "{} = {}",
1488                head(&name, &params),
1489                strip_outer(&text)
1490            ));
1491        }
1492        None => {
1493            let holes = vec!["_".to_string(); params.len()];
1494            w.write(format_args!(
1495                "{} = P.error {}",
1496                head(&name, &holes),
1497                string_literal(&format!("not implemented: {qualified}"))
1498            ));
1499        }
1500    }
1501}
1502
1503/// Whether a generic parameter appears anywhere in a type.
1504fn mentions(ty: &Type, param: &Ident) -> bool {
1505    matches!(ty, Type::Param { name } if name == param)
1506        || ty.children().into_iter().any(|c| mentions(c, param))
1507}
1508
1509// ---------------------------------------------------------------------------
1510// Bodies
1511
1512/// What each name in scope holds, at some point in a body.
1513type Env = HashMap<Ident, Type>;
1514
1515/// Looking through a name for what it stands for.
1516struct Resolver<'a> {
1517    ws: &'a CheckedWorkspace,
1518}
1519
1520impl Resolver<'_> {
1521    /// A type with its aliases expanded, except those that are a sum type of
1522    /// their own here, which have to be left as the name of one.
1523    fn resolve(&self, ty: &Type) -> Type {
1524        if self.is_sum(ty) {
1525            ty.clone()
1526        } else {
1527            self.ws.expand_alias(ty)
1528        }
1529    }
1530
1531    /// Whether a name leads, through other names, to an alias that is a union.
1532    fn is_sum(&self, ty: &Type) -> bool {
1533        let mut current = ty.clone();
1534        for _ in 0..16 {
1535            let Type::Ref(r) = &current else {
1536                return false;
1537            };
1538            let Some(TypeDef::Alias(alias)) = self
1539                .ws
1540                .ref_target_of(r)
1541                .and_then(|target| self.ws.def(&target))
1542            else {
1543                return false;
1544            };
1545            if matches!(alias.target, Type::Union { .. }) {
1546                return true;
1547            }
1548            current = alias.target.clone();
1549        }
1550        false
1551    }
1552}
1553
1554/// Writing a body as Haskell.
1555///
1556/// Every part that is not a single word is bracketed where it is made, so that
1557/// parts compose without anyone asking what binds tighter than what.
1558struct Body<'a> {
1559    ws: &'a CheckedWorkspace,
1560    profile: &'a LanguageProfile,
1561    /// The bounds of the signature's parameters, for the fields a bound gives.
1562    bounds: &'a [TypeParamDecl],
1563}
1564
1565impl Body<'_> {
1566    fn resolver(&self) -> Resolver<'_> {
1567        Resolver { ws: self.ws }
1568    }
1569
1570    /// A name a body binds, written so that GHC is not told off for one the
1571    /// body never reads.
1572    fn bound(&self, name: &Ident, scope: &Expr) -> String {
1573        let mut read = false;
1574        scope.walk(&mut |e| read |= matches!(e, Expr::Var { name: n } if n == name));
1575        let written = var(self.profile, name);
1576        if read { written } else { format!("_{written}") }
1577    }
1578
1579    /// Writes `expr`, where `env` says what each name holds and `wanted` is
1580    /// what the place it stands in expects, when that place says.
1581    fn expression(&self, expr: &Expr, env: &Env, wanted: Option<&Type>) -> String {
1582        let profile = self.profile;
1583        match expr {
1584            // A constant is written as what is wanted, which takes it into
1585            // `Just` and into parsed JSON itself.
1586            Expr::Lit { value } => {
1587                let target = wanted.cloned().or_else(|| self.ws.type_of_expr(expr, env));
1588                match target {
1589                    Some(target) => typed(self.ws, profile, value, &target),
1590                    None => untyped(value, true),
1591                }
1592            }
1593            // A binding, a conditional, and taking a value apart each hand on
1594            // what is wanted to whatever produces their result, so `Just` goes
1595            // on the one arm that needs it rather than round all of them.
1596            Expr::Let { name, value, body } => {
1597                let mut inner = env.clone();
1598                if let Some(bound) = self.ws.type_of_expr(value, env) {
1599                    inner.insert(name.clone(), bound);
1600                }
1601                // A lambda rather than `let`, which is recursive: a body that
1602                // rebinds a name to something made from it would never end.
1603                format!(
1604                    "((\\{} -> {}) {})",
1605                    self.bound(name, body),
1606                    self.expression(body, &inner, wanted),
1607                    self.expression(value, env, None)
1608                )
1609            }
1610            Expr::If {
1611                cond,
1612                then,
1613                otherwise,
1614            } => {
1615                let arms = self.shared(wanted, expr, env);
1616                format!(
1617                    "(if {} then {} else {})",
1618                    self.expression(cond, env, None),
1619                    self.expression(then, env, arms.as_ref()),
1620                    self.expression(otherwise, env, arms.as_ref())
1621                )
1622            }
1623            Expr::Case {
1624                value,
1625                var: bound,
1626                some,
1627                none,
1628            } => {
1629                let arms = self.shared(wanted, expr, env);
1630                let mut present = env.clone();
1631                let inside =
1632                    self.ws
1633                        .type_of_expr(value, env)
1634                        .map(|t| match self.resolver().resolve(&t) {
1635                            Type::Optional { of } => *of,
1636                            // Only `null` gets here, so the present arm binds
1637                            // something that is never there.
1638                            _ => Type::Never,
1639                        });
1640                if let Some(inside) = inside {
1641                    present.insert(bound.clone(), inside);
1642                }
1643                format!(
1644                    "(case {} of {{ Just {} -> {}; Nothing -> {} }})",
1645                    self.expression(value, env, None),
1646                    self.bound(bound, some),
1647                    self.expression(some, &present, arms.as_ref()),
1648                    self.expression(none, env, arms.as_ref())
1649                )
1650            }
1651            Expr::Match { ty, value, arms } => {
1652                let wanted = self.shared(wanted, expr, env);
1653                let variants = self.ws.variants_of(ty).unwrap_or_default();
1654                let arms: Vec<String> = arms
1655                    .iter()
1656                    .map(|arm| {
1657                        let mut inner = env.clone();
1658                        let variant = variants.iter().find(|v| v.name == arm.tag);
1659                        let carries = variant.is_some_and(|v| !matches!(v.payload, Type::Unit));
1660                        if let (Some(bound), Some(variant)) = (&arm.var, variant) {
1661                            inner.insert(bound.clone(), variant.payload.clone());
1662                        }
1663                        let body = self.expression(&arm.body, &inner, wanted.as_ref());
1664                        let ctor = variant_name(profile, &ty.name, arm.tag.as_str());
1665                        match (&arm.var, carries) {
1666                            (Some(bound), _) => {
1667                                format!("{ctor} {} -> {body}", self.bound(bound, &arm.body))
1668                            }
1669                            // An arm that ignores the payload need not name it.
1670                            (None, true) => format!("{ctor} _ -> {body}"),
1671                            (None, false) => format!("{ctor} -> {body}"),
1672                        }
1673                    })
1674                    .collect();
1675                format!(
1676                    "(case {} of {{ {} }})",
1677                    self.expression(value, env, None),
1678                    arms.join("; ")
1679                )
1680            }
1681            _ => {
1682                // What is wanted of the value itself, once it is in `Just`.
1683                let within = wanted.map(|w| match self.resolver().resolve(w) {
1684                    Type::Optional { of } => self.resolver().resolve(&of),
1685                    other => other,
1686                });
1687                let text = self.value(expr, env, within.as_ref());
1688                let produced = self.ws.type_of_expr(expr, env);
1689                self.adapt(text, produced.as_ref(), wanted)
1690            }
1691        }
1692    }
1693
1694    /// Writes an expression that is not a branch or a constant, where `wanted`
1695    /// is what is expected of it with any `Maybe` round it already accounted
1696    /// for.
1697    fn value(&self, expr: &Expr, env: &Env, wanted: Option<&Type>) -> String {
1698        let profile = self.profile;
1699        match expr {
1700            Expr::Var { name } => var(profile, name),
1701            Expr::Field { of, name } => {
1702                let subject = self.ws.type_of_expr(of, env);
1703                format!(
1704                    "({} {})",
1705                    self.accessor(subject.as_ref(), name),
1706                    self.expression(of, env, None)
1707                )
1708            }
1709            Expr::MakeRecord { ty, fields } => {
1710                let declared = self.ws.fields_of(ty).unwrap_or_default();
1711                let mut parts: Vec<String> = fields
1712                    .iter()
1713                    .map(|f| {
1714                        let field = declared.iter().find(|d| d.name == f.name);
1715                        format!(
1716                            "{} = {}",
1717                            field_name(profile, &ty.name, &f.name),
1718                            self.expression(&f.value, env, field.map(|d| &d.ty))
1719                        )
1720                    })
1721                    .collect();
1722                // The checker lets a body leave out a field that may be
1723                // absent, but a record names every field it has, and one left
1724                // out would fail when something read it.
1725                parts.extend(
1726                    declared
1727                        .iter()
1728                        .filter(|d| !fields.iter().any(|f| f.name == d.name))
1729                        .filter(|d| {
1730                            matches!(
1731                                self.resolver().resolve(&d.ty),
1732                                Type::Optional { .. } | Type::Unit | Type::Any
1733                            )
1734                        })
1735                        .map(|d| {
1736                            format!(
1737                                "{} = {}",
1738                                field_name(profile, &ty.name, &d.name),
1739                                typed(self.ws, profile, &Value::Null, &d.ty)
1740                            )
1741                        }),
1742                );
1743                let ctor = type_name(profile, &ty.name);
1744                if parts.is_empty() {
1745                    ctor
1746                } else {
1747                    format!("({ctor} {{ {} }})", parts.join(", "))
1748                }
1749            }
1750            Expr::MakeList { items } => {
1751                // Every element of a list is one type, so if one of them may be
1752                // absent they all have to be written as though they might.
1753                let elements = match wanted {
1754                    Some(Type::List { of }) if self.may_be_absent(of) => Some(of.as_ref().clone()),
1755                    _ => self.ws.type_of_expr(expr, env).and_then(|t| {
1756                        match self.resolver().resolve(&t) {
1757                            Type::List { of } => Some(*of),
1758                            _ => None,
1759                        }
1760                    }),
1761                };
1762                let parts: Vec<String> = items
1763                    .iter()
1764                    .map(|i| self.expression(i, env, elements.as_ref()))
1765                    .collect();
1766                format!("[{}]", parts.join(", "))
1767            }
1768            Expr::MakeTuple { items } => {
1769                let slots = match wanted {
1770                    Some(Type::Tuple { items: slots }) if slots.len() == items.len() => {
1771                        Some(slots.as_slice())
1772                    }
1773                    _ => None,
1774                };
1775                let parts: Vec<String> = items
1776                    .iter()
1777                    .enumerate()
1778                    .map(|(n, i)| self.expression(i, env, slots.map(|s| &s[n])))
1779                    .collect();
1780                match parts.as_slice() {
1781                    [] => "()".to_string(),
1782                    // There is no tuple of one, and the canonical form has none.
1783                    [only] => only.clone(),
1784                    _ => format!("({})", parts.join(", ")),
1785                }
1786            }
1787            Expr::MakeVariant { ty, tag, value } => {
1788                let ctor = variant_name(profile, &ty.name, tag.as_str());
1789                match value {
1790                    Some(v) => {
1791                        let payload = self
1792                            .ws
1793                            .variants_of(ty)
1794                            .and_then(|vs| vs.into_iter().find(|x| &x.name == tag))
1795                            .map(|x| x.payload);
1796                        format!("({ctor} {})", self.expression(v, env, payload.as_ref()))
1797                    }
1798                    None => ctor,
1799                }
1800            }
1801            Expr::Call { sig, args } => {
1802                let params = self.ws.sig(sig).map(|s| s.params.as_slice());
1803                let parts: Vec<String> = args
1804                    .iter()
1805                    .enumerate()
1806                    .map(|(n, a)| {
1807                        let param = params.and_then(|ps| ps.get(n)).map(|p| &p.ty);
1808                        self.expression(a, env, param)
1809                    })
1810                    .collect();
1811                let name = var(profile, &sig.name);
1812                if parts.is_empty() {
1813                    name
1814                } else {
1815                    format!("({name} {})", parts.join(" "))
1816                }
1817            }
1818            Expr::MapThrough {
1819                functor,
1820                value,
1821                var: bound,
1822                body,
1823            } => {
1824                use unitype_core::ir::Functor;
1825                let mut inner = env.clone();
1826                if let Some(subject) = self.ws.type_of_expr(value, env) {
1827                    if let Some((_, inside)) = Functor::split(&self.resolver().resolve(&subject)) {
1828                        inner.insert(bound.clone(), inside.clone());
1829                    }
1830                }
1831                // What is wanted of each thing inside is whatever is wanted
1832                // inside the result. For an optional that is already what is
1833                // wanted here, since the `Maybe` round it is the map's own.
1834                let each = match functor {
1835                    Functor::Optional => wanted.cloned(),
1836                    _ => wanted.and_then(|w| match Functor::split(w) {
1837                        Some((f, inside)) if f == *functor => Some(inside.clone()),
1838                        _ => None,
1839                    }),
1840                };
1841                // A list, a value that may be absent and a wait are all
1842                // things `fmap` goes through.
1843                format!(
1844                    "(P.fmap (\\{} -> {}) {})",
1845                    self.bound(bound, body),
1846                    self.expression(body, &inner, each.as_ref()),
1847                    self.expression(value, env, None)
1848                )
1849            }
1850            Expr::Prim { op, args } => {
1851                // Haskell compares a `Maybe` only with another, so a value
1852                // compared with something that may be absent is put in `Just`
1853                // to be compared at all.
1854                let produced: Vec<Option<Type>> =
1855                    args.iter().map(|a| self.ws.type_of_expr(a, env)).collect();
1856                let others: Vec<Option<Type>> = match (op, produced.as_slice()) {
1857                    (PrimOp::Eq | PrimOp::Ne, [x, y]) => vec![y.clone(), x.clone()],
1858                    _ => vec![None; args.len()],
1859                };
1860                let mut operands: Vec<String> = args
1861                    .iter()
1862                    .zip(&others)
1863                    .map(|(a, other)| self.expression(a, env, other.as_ref()))
1864                    .collect();
1865                // A 32-bit integer beside a 64-bit one is the narrower one
1866                // widened, which Haskell will not do unasked.
1867                if let [x, y] = operands.as_mut_slice() {
1868                    let kinds: Vec<Option<Type>> = produced
1869                        .iter()
1870                        .map(|t| t.as_ref().map(|t| self.resolver().resolve(t)))
1871                        .collect();
1872                    match kinds.as_slice() {
1873                        [Some(Type::I32), Some(Type::I64)] => *x = format!("(P.fromIntegral {x})"),
1874                        [Some(Type::I64), Some(Type::I32)] => *y = format!("(P.fromIntegral {y})"),
1875                        _ => {}
1876                    }
1877                }
1878                match (op, operands.as_slice()) {
1879                    (PrimOp::Neg, [x]) => format!("(P.negate {x})"),
1880                    (PrimOp::Not, [x]) => format!("(P.not {x})"),
1881                    // A length is an `Int` in Haskell and an `i64` everywhere
1882                    // else here.
1883                    (PrimOp::Len, [x]) => format!("(P.fromIntegral (P.length {x}) :: Int64)"),
1884                    (op, [x, y]) => format!("({x} {} {y})", infix(*op)),
1885                    _ => unreachable!("the checker holds every operation to its arity"),
1886                }
1887            }
1888            Expr::Fold {
1889                list,
1890                init,
1891                acc,
1892                item,
1893                body,
1894                ..
1895            } => {
1896                // The starting value and every step are one type, the one
1897                // carried, which is also what the fold as a whole produces.
1898                let carried = self.ws.type_of_expr(expr, env);
1899                let mut inner = env.clone();
1900                if let Some(carried) = &carried {
1901                    inner.insert(acc.clone(), carried.clone());
1902                }
1903                let element = self.ws.type_of_expr(list, env).and_then(|t| {
1904                    match self.resolver().resolve(&t) {
1905                        Type::List { of } => Some(*of),
1906                        _ => None,
1907                    }
1908                });
1909                if let Some(element) = element {
1910                    inner.insert(item.clone(), element);
1911                }
1912                format!(
1913                    "(Data.List.foldl' (\\{} {} -> {}) {} {})",
1914                    self.bound(acc, body),
1915                    self.bound(item, body),
1916                    self.expression(body, &inner, carried.as_ref()),
1917                    self.expression(init, env, carried.as_ref()),
1918                    self.expression(list, env, None)
1919                )
1920            }
1921            Expr::Lit { .. }
1922            | Expr::Let { .. }
1923            | Expr::If { .. }
1924            | Expr::Case { .. }
1925            | Expr::Match { .. } => {
1926                unreachable!("a branch is written by `expression`, which hands on what is wanted")
1927            }
1928        }
1929    }
1930
1931    /// The function that reads a field out of something of type `subject`.
1932    fn accessor(&self, subject: Option<&Type>, field: &Ident) -> String {
1933        let profile = self.profile;
1934        match subject.map(|t| self.resolver().resolve(t)) {
1935            Some(Type::Ref(r)) => field_name(profile, &r.name, field),
1936            // What a bound says a parameter has is read through its class.
1937            Some(Type::Param { name }) => self
1938                .bounds
1939                .iter()
1940                .filter(|p| p.name == name)
1941                .flat_map(|p| &p.bounds)
1942                .find(|bound| {
1943                    self.ws
1944                        .fields_of(bound)
1945                        .is_some_and(|fs| fs.iter().any(|f| &f.name == field))
1946                })
1947                .map(|bound| field_name(profile, &bound.name, field))
1948                .unwrap_or_else(|| field.to_string()),
1949            _ => field.to_string(),
1950        }
1951    }
1952
1953    /// What several alternatives are each written as, so that they come out as
1954    /// one Haskell type: what the place wants, if that may be absent, and
1955    /// otherwise what they come to together.
1956    fn shared(&self, wanted: Option<&Type>, expr: &Expr, env: &Env) -> Option<Type> {
1957        match wanted {
1958            Some(w) if self.may_be_absent(w) => Some(w.clone()),
1959            _ => self.ws.type_of_expr(expr, env),
1960        }
1961    }
1962
1963    /// Whether a type is one Haskell writes as a `Maybe`.
1964    fn may_be_absent(&self, ty: &Type) -> bool {
1965        matches!(self.resolver().resolve(ty), Type::Optional { .. })
1966    }
1967
1968    /// Makes what an expression produces what the place it stands in wants,
1969    /// for the three ways the checker lets one fit where Haskell will not: a
1970    /// value that is there where one that may be absent is wanted, a 32-bit
1971    /// integer where a wider number is, and anything where parsed JSON is.
1972    fn adapt(&self, text: String, produced: Option<&Type>, wanted: Option<&Type>) -> String {
1973        let (Some(produced), Some(wanted)) = (produced, wanted) else {
1974            return text;
1975        };
1976        let produced = self.resolver().resolve(produced);
1977        let wanted = self.resolver().resolve(wanted);
1978        // Bounds do not change what a value is, so a bounded `i32` widens like
1979        // any other; and a bounded type never wraps an optional, so looking
1980        // through them loses nothing the arms below ask about.
1981        match (produced.unbounded(), wanted.unbounded()) {
1982            // Already one, or the `null` that is the absence of one.
1983            (Type::Optional { .. } | Type::Unit | Type::Never, Type::Optional { .. }) => text,
1984            (_, Type::Optional { of }) => {
1985                format!("(Just {})", self.adapt(text, Some(&produced), Some(of)))
1986            }
1987            (Type::I32, Type::I64 | Type::F64) => format!("(P.fromIntegral {text})"),
1988            (_, w) if is_json(w) && !is_json(&produced) => format!("(U.toJson {text})"),
1989            _ => text,
1990        }
1991    }
1992}
1993
1994/// How Haskell writes a two-operand operation.
1995fn infix(op: PrimOp) -> &'static str {
1996    match op {
1997        PrimOp::Eq => "==",
1998        PrimOp::Ne => "/=",
1999        PrimOp::Lt => "<",
2000        PrimOp::Le => "<=",
2001        PrimOp::Gt => ">",
2002        PrimOp::Ge => ">=",
2003        PrimOp::Add => "+",
2004        PrimOp::Sub => "-",
2005        PrimOp::Mul => "*",
2006        PrimOp::And => "&&",
2007        PrimOp::Or => "||",
2008        PrimOp::Neg | PrimOp::Not | PrimOp::Len => unreachable!("not a two-operand operation"),
2009    }
2010}
2011
2012/// Takes off one pair of brackets round the whole of some text, if it has one.
2013///
2014/// A tuple keeps its own, and so does `()`.
2015fn strip_outer(text: &str) -> &str {
2016    if text.starts_with('(') && is_bracketed(text) {
2017        let inner = &text[1..text.len() - 1];
2018        if !inner.is_empty() && !has_top_level_comma(inner) {
2019            return inner;
2020        }
2021    }
2022    text
2023}
2024
2025// ---------------------------------------------------------------------------
2026// Literals
2027
2028/// Writes a Haskell string literal.
2029///
2030/// Anything outside printable ASCII is written as its code point in decimal,
2031/// which is how Haskell spells a character it cannot see; `\&` keeps a digit
2032/// that follows from being read as part of one.
2033pub fn string_literal(text: &str) -> String {
2034    let mut out = String::with_capacity(text.len() + 2);
2035    out.push('"');
2036    let mut chars = text.chars().peekable();
2037    while let Some(c) = chars.next() {
2038        match c {
2039            '"' => out.push_str("\\\""),
2040            '\\' => out.push_str("\\\\"),
2041            '\n' => out.push_str("\\n"),
2042            '\t' => out.push_str("\\t"),
2043            '\r' => out.push_str("\\r"),
2044            ' '..='~' => out.push(c),
2045            other => {
2046                out.push_str(&format!("\\{}", other as u32));
2047                if chars.peek().is_some_and(char::is_ascii_digit) {
2048                    out.push_str("\\&");
2049                }
2050            }
2051        }
2052    }
2053    out.push('"');
2054    out
2055}
2056
2057/// Writes a number so that it stands as an argument: a negative one is
2058/// bracketed, because `f -1` is a subtraction.
2059fn number(text: String) -> String {
2060    if text.starts_with('-') {
2061        format!("({text})")
2062    } else {
2063        text
2064    }
2065}
2066
2067fn float(f: f64) -> String {
2068    let plain = f.to_string();
2069    number(if plain.contains(['.', 'e', 'E']) {
2070        plain
2071    } else {
2072        format!("{plain}.0")
2073    })
2074}
2075
2076/// Writes a value as a Haskell literal, with nothing but the value to go on.
2077///
2078/// What a string is, or a list of them, is up to whatever it is put in, which
2079/// is what `OverloadedStrings` is for. `annotated` says it is `Text`, for the
2080/// places that have nothing else to settle it.
2081fn untyped(value: &Value, annotated: bool) -> String {
2082    match value {
2083        Value::Null => "Nothing".into(),
2084        Value::Bool(b) => if *b { "True" } else { "False" }.into(),
2085        Value::Int(i) => number(i.to_string()),
2086        Value::Float(f) => float(*f),
2087        Value::Str(s) if annotated => format!("({} :: Text)", string_literal(s)),
2088        Value::Str(s) => string_literal(s),
2089        Value::Bytes(b) => {
2090            let parts: Vec<String> = b.iter().map(u8::to_string).collect();
2091            format!("(BS.pack [{}])", parts.join(", "))
2092        }
2093        Value::List(items) => {
2094            let parts: Vec<String> = items.iter().map(|i| untyped(i, annotated)).collect();
2095            format!("[{}]", parts.join(", "))
2096        }
2097        Value::Tuple(items) => {
2098            let parts: Vec<String> = items.iter().map(|i| untyped(i, annotated)).collect();
2099            match parts.as_slice() {
2100                [only] => only.clone(),
2101                _ => format!("({})", parts.join(", ")),
2102            }
2103        }
2104        // An anonymous record has no declared type to name here, so it is
2105        // written as the map it is on the wire.
2106        Value::Record(fields) => {
2107            let parts: Vec<String> = fields
2108                .iter()
2109                .map(|(k, v)| format!("({}, {})", string_literal(k), untyped(v, annotated)))
2110                .collect();
2111            format!("(Map.fromList [{}])", parts.join(", "))
2112        }
2113        Value::Map(entries) => {
2114            let parts: Vec<String> = entries
2115                .iter()
2116                .map(|(k, v)| format!("({}, {})", untyped(k, annotated), untyped(v, annotated)))
2117                .collect();
2118            format!("(Map.fromList [{}])", parts.join(", "))
2119        }
2120        Value::Variant { .. } => json(value),
2121    }
2122}
2123
2124/// Writes a value as the parsed JSON that holds it, which is what an `any` is
2125/// and what a type with no name of its own is held as.
2126///
2127/// With no type to say, the shapes JSON has no word for take the escapes the
2128/// protocol gives them.
2129fn json(value: &Value) -> String {
2130    let object = |entries: Vec<(&str, String)>| {
2131        let parts: Vec<String> = entries
2132            .into_iter()
2133            .map(|(k, v)| format!("({}, {v})", string_literal(k)))
2134            .collect();
2135        format!("(JObject (Map.fromList [{}]))", parts.join(", "))
2136    };
2137    match value {
2138        Value::Null => "JNull".into(),
2139        Value::Bool(b) => format!("(JBool {})", if *b { "True" } else { "False" }),
2140        Value::Int(i) => format!("(JInt {})", number(i.to_string())),
2141        Value::Float(f) => format!("(JFloat {})", float(*f)),
2142        Value::Str(s) => format!("(JString {})", string_literal(s)),
2143        Value::Bytes(b) => {
2144            use base64::Engine as _;
2145            let text = base64::engine::general_purpose::STANDARD.encode(b);
2146            object(vec![(
2147                "$bytes",
2148                format!("(JString {})", string_literal(&text)),
2149            )])
2150        }
2151        Value::List(items) => {
2152            let parts: Vec<String> = items.iter().map(json).collect();
2153            format!("(JArray [{}])", parts.join(", "))
2154        }
2155        Value::Tuple(items) => {
2156            let parts: Vec<String> = items.iter().map(json).collect();
2157            object(vec![("$tuple", format!("(JArray [{}])", parts.join(", ")))])
2158        }
2159        Value::Record(fields) => {
2160            let parts: Vec<String> = fields
2161                .iter()
2162                .map(|(k, v)| format!("({}, {})", string_literal(k), json(v)))
2163                .collect();
2164            format!("(JObject (Map.fromList [{}]))", parts.join(", "))
2165        }
2166        Value::Map(entries) => {
2167            let pairs: Vec<String> = entries
2168                .iter()
2169                .map(|(k, v)| format!("(JArray [{}, {}])", json(k), json(v)))
2170                .collect();
2171            object(vec![("$map", format!("(JArray [{}])", pairs.join(", ")))])
2172        }
2173        Value::Variant { tag, value } => {
2174            let mut entries = vec![("$tag", format!("(JString {})", string_literal(tag)))];
2175            if !matches!(value.as_ref(), Value::Null) {
2176                entries.push(("value", json(value)));
2177            }
2178            object(entries)
2179        }
2180    }
2181}
2182
2183/// Writes a value as a Haskell literal of `ty`.
2184///
2185/// This is the language's way of writing a literal against its type, and the
2186/// body writer's way of writing a constant. Every result stands as an argument.
2187pub fn typed_literal(ws: &CheckedWorkspace, value: &Value, ty: &Type) -> String {
2188    typed(ws, &profile("haskell").expect("ships"), value, ty)
2189}
2190
2191fn typed(ws: &CheckedWorkspace, profile: &LanguageProfile, value: &Value, ty: &Type) -> String {
2192    let resolver = Resolver { ws };
2193    let ty = resolver.resolve(ty);
2194    match (&ty, value) {
2195        (Type::Ref(r), _) => named_literal(ws, profile, r, value),
2196        // Bounds change nothing about how a value is written.
2197        (Type::Bounded { of, .. }, _) => typed(ws, profile, value, of),
2198        (Type::Optional { .. }, Value::Null) => "Nothing".into(),
2199        (Type::Optional { of }, present) => {
2200            format!("(Just {})", typed(ws, profile, present, of))
2201        }
2202        (Type::Unit, Value::Null) => "()".into(),
2203        (t, v) if is_json(t) => json(v),
2204        (Type::Never, _) => "(P.error \"no value has this type\")".into(),
2205        // Absence, where the type is not one that says so, is still `Nothing`:
2206        // a body reaches this with the type inside a `Maybe` it is about to add.
2207        (_, Value::Null) => "Nothing".into(),
2208        (Type::Literal { value: lit }, v) => typed(ws, profile, v, &lit.base()),
2209        (Type::Bool, Value::Bool(_)) | (Type::I32 | Type::I64, Value::Int(_)) => {
2210            untyped(value, false)
2211        }
2212        (Type::F64, Value::Int(i)) => float(*i as f64),
2213        (Type::F64, Value::Float(_)) | (Type::String, Value::Str(_)) => untyped(value, false),
2214        (Type::Bytes, Value::Bytes(_)) => untyped(value, false),
2215        (Type::List { of }, Value::List(items)) => {
2216            let parts: Vec<String> = items.iter().map(|i| typed(ws, profile, i, of)).collect();
2217            format!("[{}]", parts.join(", "))
2218        }
2219        (Type::Tuple { items: types }, Value::Tuple(items)) if types.len() == items.len() => {
2220            let parts: Vec<String> = types
2221                .iter()
2222                .zip(items)
2223                .map(|(t, i)| typed(ws, profile, i, t))
2224                .collect();
2225            format!("({})", parts.join(", "))
2226        }
2227        (Type::Map { key, value: of }, Value::Map(entries)) => {
2228            let key = map_key(resolver.resolve(key));
2229            let parts: Vec<String> = entries
2230                .iter()
2231                .map(|(k, v)| {
2232                    format!(
2233                        "({}, {})",
2234                        typed(ws, profile, k, &key),
2235                        typed(ws, profile, v, of)
2236                    )
2237                })
2238                .collect();
2239            format!("(Map.fromList [{}])", parts.join(", "))
2240        }
2241        // An object read against a map type whose keys are text.
2242        (Type::Map { key, value: of }, Value::Record(entries)) => {
2243            let key = map_key(resolver.resolve(key));
2244            let parts: Vec<String> = entries
2245                .iter()
2246                .map(|(k, v)| {
2247                    format!(
2248                        "({}, {})",
2249                        typed(ws, profile, &Value::Str(k.clone()), &key),
2250                        typed(ws, profile, v, of)
2251                    )
2252                })
2253                .collect();
2254            format!("(Map.fromList [{}])", parts.join(", "))
2255        }
2256        _ => untyped(value, false),
2257    }
2258}
2259
2260/// Writes a value of a declared type: a record, an alternative of an enum, or
2261/// one of the names a union stands for.
2262fn named_literal(
2263    ws: &CheckedWorkspace,
2264    profile: &LanguageProfile,
2265    r: &TypeRef,
2266    value: &Value,
2267) -> String {
2268    let Some(def) = ws.ref_target_of(r).and_then(|q| ws.def(&q)) else {
2269        return untyped(value, false);
2270    };
2271    match (def, value) {
2272        (TypeDef::Struct(_), Value::Record(entries)) => {
2273            let declared = ws.fields_of(r).unwrap_or_default();
2274            // Declaration order, not whatever order the value arrived in:
2275            // generated code should look the way the declaration does.
2276            let parts: Vec<String> = declared
2277                .iter()
2278                .filter_map(|field| {
2279                    let present = entries.get(field.name.as_str());
2280                    let written = match present {
2281                        Some(entry) if !matches!(entry, Value::Null) => {
2282                            typed(ws, profile, entry, &field.ty)
2283                        }
2284                        // A field that is not there is written as nothing, if
2285                        // that is something its type can hold. A record names
2286                        // every field it has.
2287                        _ if may_be_left_out(ws, &field.ty) => {
2288                            typed(ws, profile, &Value::Null, &field.ty)
2289                        }
2290                        _ => return None,
2291                    };
2292                    Some(format!(
2293                        "{} = {written}",
2294                        field_name(profile, &r.name, &field.name)
2295                    ))
2296                })
2297                .collect();
2298            let ctor = type_name(profile, &r.name);
2299            if parts.is_empty() {
2300                ctor
2301            } else {
2302                format!("({ctor} {{ {} }})", parts.join(", "))
2303            }
2304        }
2305        (
2306            TypeDef::Enum(_),
2307            Value::Variant {
2308                tag,
2309                value: payload,
2310            },
2311        ) => {
2312            let ctor = variant_name(profile, &r.name, tag);
2313            let carried = ws
2314                .variants_of(r)
2315                .unwrap_or_default()
2316                .into_iter()
2317                .find(|v| v.name.as_str() == tag)
2318                .filter(|v| !matches!(v.payload, Type::Unit));
2319            match carried {
2320                Some(variant) => {
2321                    format!("({ctor} {})", typed(ws, profile, payload, &variant.payload))
2322                }
2323                None => ctor,
2324            }
2325        }
2326        (TypeDef::Alias(alias), v) if matches!(alias.target, Type::Union { .. }) => {
2327            let members = union_members(profile, alias);
2328            let names = members.iter().all(|m| m.text.is_some());
2329            let chosen = if names {
2330                members
2331                    .iter()
2332                    .find(|m| v.as_str().is_some() && m.text.as_deref() == v.as_str())
2333            } else {
2334                // Whichever alternative it actually is decides how it is
2335                // written, which is what makes a union come out right.
2336                members.iter().find(|m| ws.validate(v, &m.ty).is_ok())
2337            };
2338            match chosen {
2339                Some(member) if names => member.ctor.clone(),
2340                Some(member) => format!("({} {})", member.ctor, typed(ws, profile, v, &member.ty)),
2341                None => untyped(v, false),
2342            }
2343        }
2344        _ => untyped(value, false),
2345    }
2346}
2347
2348/// Builds a named struct from its `field = value` parts.
2349pub fn record(name: &str, fields: &[(String, String)]) -> String {
2350    let parts: Vec<String> = fields.iter().map(|(f, v)| format!("{f} = {v}")).collect();
2351    format!("{name} {{ {} }}", parts.join(", "))
2352}
2353
2354/// Builds one alternative of a named enum.
2355pub fn variant(name: &str, tag: &str, payload: Option<&str>) -> String {
2356    match payload {
2357        Some(value) => format!("{name}{} {}", upper_first(tag), bracketed(value)),
2358        None => format!("{name}{}", upper_first(tag)),
2359    }
2360}
2361
2362fn bracketed(text: &str) -> String {
2363    if text.contains(' ') && !is_bracketed(text) && !text.starts_with('"') {
2364        format!("({text})")
2365    } else {
2366        text.to_string()
2367    }
2368}
2369
2370/// Writes a value as a Haskell literal, with no type to guide it.
2371pub fn literal(value: &Value) -> String {
2372    untyped(value, false)
2373}
2374
2375#[cfg(test)]
2376mod tests {
2377    use super::*;
2378    use unitype_core::Workspace;
2379    use unitype_core::check::check_workspace;
2380
2381    fn checked(json: &str) -> CheckedWorkspace {
2382        check_workspace(Workspace::from_json(json).expect("reads")).expect("checks")
2383    }
2384
2385    fn generate(json: &str) -> String {
2386        generate_module(json, "Demo.hs")
2387    }
2388
2389    fn generate_module(json: &str, file: &str) -> String {
2390        Haskell
2391            .generate(&checked(json), &GenOptions::default())
2392            .expect("generates")
2393            .into_iter()
2394            .find(|f| f.path.to_string_lossy().ends_with(file))
2395            .unwrap_or_else(|| panic!("a file called {file}"))
2396            .contents
2397    }
2398
2399    const SHAPES: &str = r#"{"universes":[{"name":"demo","types":[
2400        {"k":"interface","name":"Identified","fields":[{"name":"id","ty":"str"}]},
2401        {"k":"struct","name":"Shape","implements":["Identified"],
2402         "fields":[{"name":"id","ty":"str"}]},
2403        {"k":"struct","name":"Circle","extends":"Shape","fields":[
2404            {"name":"kind","ty":{"k":"literal","value":{"str":"circle"}}},
2405            {"name":"radius","ty":"float"},
2406            {"name":"note","ty":"str?"}]},
2407        {"k":"enum","name":"Colour","variants":[{"name":"Red"},{"name":"Custom","payload":"str"}]},
2408        {"k":"alias","name":"Either","target":{"k":"union","members":["Circle","Shape"]}},
2409        {"k":"alias","name":"Tone","target":{"k":"union","members":[
2410            {"k":"literal","value":{"str":"light"}},{"k":"literal","value":{"str":"dark"}}]}}],
2411      "functions":[
2412        {"name":"area","params":[{"name":"s","ty":"Circle"}],"ret":"float"}]}]}"#;
2413
2414    #[test]
2415    fn a_struct_becomes_a_record_whose_fields_are_named_after_it() {
2416        let out = generate(SHAPES);
2417        assert!(
2418            out.contains("data Shape = Shape\n  { shapeId :: Text\n  }"),
2419            "{out}"
2420        );
2421        assert!(out.contains("{ circleId :: Text"), "{out}");
2422        assert!(out.contains(", circleRadius :: Double"), "{out}");
2423        assert!(out.contains(", circleNote :: Maybe Text"), "{out}");
2424        assert!(out.contains("deriving (Eq, Show)"), "{out}");
2425    }
2426
2427    #[test]
2428    fn a_child_carries_the_fields_it_inherited() {
2429        let out = generate(SHAPES);
2430        let circle = out.find("data Circle").expect("declared");
2431        let end = circle + out[circle..].find("deriving").expect("derives");
2432        assert!(out[circle..end].contains("circleId :: Text"), "{out}");
2433        assert!(
2434            out[..circle]
2435                .trim_end()
2436                .ends_with("the shape on the wire is unchanged."),
2437            "it says where the fields came from: {out}"
2438        );
2439    }
2440
2441    #[test]
2442    fn an_interface_is_a_class_of_accessors_and_a_claim_is_an_instance() {
2443        let out = generate(SHAPES);
2444        assert!(
2445            out.contains("class Identified self where\n  identifiedId :: self -> Text"),
2446            "{out}"
2447        );
2448        assert!(
2449            out.contains("instance Identified Shape where\n  identifiedId = shapeId"),
2450            "{out}"
2451        );
2452    }
2453
2454    #[test]
2455    fn an_enum_is_a_sum_tagged_the_way_the_wire_tags_it() {
2456        let out = generate(SHAPES);
2457        assert!(
2458            out.contains(
2459                "data Colour\n  = ColourRed\n  | ColourCustom Text\n  deriving (Eq, Show)"
2460            ),
2461            "{out}"
2462        );
2463        assert!(
2464            out.contains("toJson ColourRed = U.variant \"Red\" Nothing"),
2465            "{out}"
2466        );
2467        assert!(
2468            out.contains("\"Custom\" -> ColourCustom <$> U.payload \"Custom\" carried"),
2469            "{out}"
2470        );
2471    }
2472
2473    #[test]
2474    fn a_union_of_names_is_a_sum_of_nothing() {
2475        let out = generate(SHAPES);
2476        assert!(
2477            out.contains("data Tone\n  = ToneDark\n  | ToneLight\n  deriving (Eq, Show)"),
2478            "{out}"
2479        );
2480        assert!(
2481            out.contains("toJson ToneLight = U.JString \"light\""),
2482            "{out}"
2483        );
2484        assert!(
2485            !out.contains("MapKey"),
2486            "the checker admits no such key: {out}"
2487        );
2488    }
2489
2490    #[test]
2491    fn any_other_union_is_tried_in_order() {
2492        let out = generate(SHAPES);
2493        assert!(
2494            out.contains("data Either_\n  = Either_Circle Circle\n  | Either_Shape Shape"),
2495            "a universe's own `Either` must not be taken for the Prelude's: {out}"
2496        );
2497        assert!(
2498            out.contains("fromJson j = U.firstOf \"Either_\"\n    [ Either_Circle <$> U.fromJson j\n    , Either_Shape <$> U.fromJson j\n    ]"),
2499            "{out}"
2500        );
2501    }
2502
2503    #[test]
2504    fn a_proposition_with_no_proof_is_an_error_rather_than_nothing() {
2505        let out = generate(SHAPES);
2506        assert!(out.contains("area :: Circle -> Double"), "{out}");
2507        assert!(
2508            out.contains("area _ = P.error \"not implemented: demo::area\""),
2509            "{out}"
2510        );
2511        assert!(
2512            out.contains("Implement this and register it as `demo::area`."),
2513            "{out}"
2514        );
2515    }
2516
2517    #[test]
2518    fn fields_that_may_be_left_out_are_read_from_nothing_and_not_sent() {
2519        let out = generate(SHAPES);
2520        assert!(out.contains("<*> U.optional \"note\" o"), "{out}");
2521        assert!(out.contains("<*> U.required \"radius\" o"), "{out}");
2522    }
2523
2524    #[test]
2525    fn a_reserved_word_cannot_be_a_field_because_a_field_is_prefixed() {
2526        let out = generate(
2527            r#"{"universes":[{"name":"demo","types":[
2528                {"k":"struct","name":"Thing","fields":[{"name":"class","ty":"str"}]}]}]}"#,
2529        );
2530        assert!(out.contains("thingClass :: Text"), "{out}");
2531        assert!(
2532            out.contains("U.field \"class\" (thingClass x)"),
2533            "the wire keeps its own name: {out}"
2534        );
2535    }
2536
2537    #[test]
2538    fn a_type_named_for_something_that_is_imported_is_renamed() {
2539        let out = generate(
2540            r#"{"universes":[{"name":"demo","types":[
2541                {"k":"struct","name":"Map","fields":[{"name":"cells","ty":"[str]"}]},
2542                {"k":"struct","name":"World","fields":[{"name":"map","ty":"Map"}]}]}]}"#,
2543        );
2544        assert!(out.contains("data Map_ = Map_"), "{out}");
2545        assert!(out.contains("worldMap :: Map_"), "{out}");
2546    }
2547
2548    #[test]
2549    fn two_declarations_that_would_be_one_name_are_refused_rather_than_merged() {
2550        let ws = checked(
2551            r#"{"universes":[{"name":"demo","types":[
2552                {"k":"struct","name":"Foo","fields":[{"name":"barBaz","ty":"str"}]},
2553                {"k":"struct","name":"FooBar","fields":[{"name":"baz","ty":"str"}]}]}]}"#,
2554        );
2555        let refused = Haskell.generate(&ws, &GenOptions::default());
2556        assert!(
2557            matches!(&refused, Err(GenError::Unsupported { what, .. }) if what.contains("barBaz") || what.contains("baz")),
2558            "{refused:?}"
2559        );
2560    }
2561
2562    #[test]
2563    fn a_record_that_holds_a_wait_is_refused_because_a_wait_cannot_travel() {
2564        let ws = checked(
2565            r#"{"universes":[{"name":"demo","types":[
2566                {"k":"alias","name":"Soon","target":{"k":"future","of":"i64"}},
2567                {"k":"struct","name":"Pending","fields":[{"name":"later","ty":"[Soon]"}]}]}]}"#,
2568        );
2569        assert!(matches!(
2570            Haskell.generate(&ws, &GenOptions::default()),
2571            Err(GenError::Unsupported { what, .. }) if what.contains("Pending.later")
2572        ));
2573    }
2574
2575    #[test]
2576    fn a_wait_is_fine_where_it_does_not_have_to_travel() {
2577        let out = generate(
2578            r#"{"universes":[{"name":"demo","types":[
2579                {"k":"alias","name":"Soon","target":{"k":"future","of":"i64"}}],
2580              "functions":[
2581                {"name":"fetch","params":[{"name":"url","ty":"str"}],"ret":"Soon"}]}]}"#,
2582        );
2583        assert!(out.contains("type Soon = IO Int64"), "{out}");
2584        assert!(out.contains("fetch :: Text -> Soon"), "{out}");
2585    }
2586
2587    #[test]
2588    fn universes_that_import_each_other_are_refused_because_modules_cannot() {
2589        let ws = checked(
2590            r#"{"universes":[
2591                {"name":"a","types":[{"k":"struct","name":"Pa","fields":[{"name":"other","ty":"b::Pb?"}]}]},
2592                {"name":"b","types":[{"k":"struct","name":"Pb","fields":[{"name":"back","ty":"a::Pa?"}]}]}]}"#,
2593        );
2594        let refused = Haskell.generate(&ws, &GenOptions::default());
2595        assert!(
2596            matches!(&refused, Err(GenError::Unsupported { what, .. }) if what.contains("`a` -> `b` -> `a`")),
2597            "{refused:?}"
2598        );
2599
2600        // Asked for one of them alone, there is no cycle to write.
2601        let alone = GenOptions {
2602            universes: Some(vec![ident("a")]),
2603            ..GenOptions::default()
2604        };
2605        assert!(Haskell.generate(&ws, &alone).is_ok());
2606    }
2607
2608    #[test]
2609    fn a_universe_that_imports_another_one_way_is_not_a_cycle() {
2610        let ws = checked(
2611            r#"{"universes":[
2612                {"name":"a","types":[{"k":"struct","name":"Pa","fields":[{"name":"other","ty":"b::Pb?"}]}]},
2613                {"name":"b","types":[{"k":"struct","name":"Pb","fields":[{"name":"n","ty":"i64"}]}]}]}"#,
2614        );
2615        assert!(Haskell.generate(&ws, &GenOptions::default()).is_ok());
2616    }
2617
2618    #[test]
2619    fn a_value_typed_by_an_interface_is_refused_but_a_bound_is_not() {
2620        let ws = checked(
2621            r#"{"universes":[{"name":"demo","types":[
2622                {"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
2623                {"k":"struct","name":"Holder","fields":[{"name":"who","ty":"[Named]"}]}]}]}"#,
2624        );
2625        assert!(matches!(
2626            Haskell.generate(&ws, &GenOptions::default()),
2627            Err(GenError::Unsupported { what, .. }) if what.contains("Holder.who")
2628        ));
2629
2630        // Bounding a parameter by it is what an interface is for.
2631        let out = generate(crate::GENERIC);
2632        assert!(out.contains("pick :: Named t => [t] -> Maybe t"), "{out}");
2633    }
2634
2635    #[test]
2636    fn a_tuple_the_support_module_cannot_carry_is_refused() {
2637        let ws = checked(
2638            r#"{"universes":[{"name":"demo","types":[
2639                {"k":"struct","name":"Wide","fields":[{"name":"all","ty":{"k":"tuple","items":
2640                    ["i64","i64","i64","i64","i64","i64","i64","i64"]}}]}]}]}"#,
2641        );
2642        assert!(matches!(
2643            Haskell.generate(&ws, &GenOptions::default()),
2644            Err(GenError::Unsupported { .. })
2645        ));
2646    }
2647
2648    #[test]
2649    fn generic_declarations_and_signatures_keep_their_parameters() {
2650        let hs = generate(crate::GENERIC);
2651        for expected in [
2652            "data Box t = Box",
2653            "{ boxValue :: t",
2654            "data Labelled t n = Labelled",
2655            "{ labelledValue :: t",
2656            ", labelledLabel :: n",
2657            "instance (U.ToJson t, U.ToJson n) => U.ToJson (Labelled t n) where",
2658            "data Outcome t e\n  = OutcomeOk t\n  | OutcomeErr e\n  | OutcomePending",
2659            "type Swap a b = (b, a)",
2660            "usesOutcome :: Outcome Int64 Text",
2661            "pick :: Named t => [t] -> Maybe t",
2662            "konst :: a -> b -> a",
2663            "konst x _y = x",
2664        ] {
2665            assert!(hs.contains(expected), "missing `{expected}` in:\n{hs}");
2666        }
2667    }
2668
2669    #[test]
2670    fn a_generic_interface_is_a_class_over_the_type_that_has_it_and_what_it_is_given() {
2671        let hs = generate(crate::GENERIC);
2672        for expected in [
2673            "class Holder self t | self -> t where\n  holderHeld :: self -> t",
2674            "instance Holder (Tagged t) t where\n  holderHeld = taggedHeld",
2675            "{-# LANGUAGE FunctionalDependencies #-}",
2676        ] {
2677            assert!(hs.contains(expected), "missing `{expected}` in:\n{hs}");
2678        }
2679        assert!(
2680            !generate(SHAPES).contains("FunctionalDependencies"),
2681            "a universe with nothing generic does not need the extension"
2682        );
2683    }
2684
2685    #[test]
2686    fn a_parameter_nothing_uses_is_still_one() {
2687        // Haskell accepts a phantom parameter, so nothing is left out.
2688        let hs = generate(crate::GENERIC);
2689        assert!(hs.contains("data Ghost t = Ghost"), "{hs}");
2690        assert!(hs.contains("usesGhost :: Ghost Int64"), "{hs}");
2691    }
2692
2693    #[test]
2694    fn bodies_are_written_with_the_prelude_qualified() {
2695        let out = generate(
2696            r#"{"universes":[{"name":"demo","functions":[
2697                {"name":"length","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64",
2698                 "body":{"k":"prim","op":"len","args":[{"k":"var","name":"xs"}]}}]}]}"#,
2699        );
2700        assert!(
2701            out.contains("length xs = P.fromIntegral (P.length xs) :: Int64"),
2702            "a function called `length` must not capture the one the body means: {out}"
2703        );
2704    }
2705
2706    #[test]
2707    fn a_value_that_is_there_goes_in_just_where_one_that_may_not_be_is_wanted() {
2708        let out = generate(
2709            r#"{"universes":[{"name":"demo","types":[
2710                {"k":"struct","name":"Mark","fields":[
2711                    {"name":"at","ty":"i64"},{"name":"before","ty":"i64?"}]}],
2712              "functions":[
2713                {"name":"mark","params":[{"name":"x","ty":"i64"}],"ret":"Mark",
2714                 "body":{"k":"make_record","ty":"Mark","fields":[
2715                    {"name":"at","value":{"k":"var","name":"x"}},
2716                    {"name":"before","value":{"k":"var","name":"x"}}]}},
2717                {"name":"bare","params":[{"name":"x","ty":"i64"}],"ret":"Mark",
2718                 "body":{"k":"make_record","ty":"Mark","fields":[
2719                    {"name":"at","value":{"k":"var","name":"x"}}]}}]}]}"#,
2720        );
2721        assert!(
2722            out.contains("mark x = Mark { markAt = x, markBefore = (Just x) }"),
2723            "{out}"
2724        );
2725        assert!(
2726            out.contains("bare x = Mark { markAt = x, markBefore = Nothing }"),
2727            "a record names every field it has: {out}"
2728        );
2729    }
2730
2731    #[test]
2732    fn a_fold_binding_and_a_branch_are_written_without_recursion() {
2733        let out = generate(
2734            r#"{"universes":[{"name":"demo","functions":[
2735                {"name":"total","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64",
2736                 "body":{"k":"fold","list":{"k":"var","name":"xs"},"init":{"k":"lit","value":0},
2737                         "acc":"t","item":"x",
2738                         "body":{"k":"prim","op":"add","args":[{"k":"var","name":"t"},{"k":"var","name":"x"}]}}},
2739                {"name":"twice","params":[{"name":"x","ty":"i64"}],"ret":"i64",
2740                 "body":{"k":"let","name":"x","value":{"k":"prim","op":"add","args":[
2741                            {"k":"var","name":"x"},{"k":"var","name":"x"}]},
2742                         "body":{"k":"var","name":"x"}}}]}]}"#,
2743        );
2744        assert!(
2745            out.contains("total xs = Data.List.foldl' (\\t x -> (t + x)) 0 xs"),
2746            "{out}"
2747        );
2748        assert!(
2749            out.contains("twice x = (\\x -> x) (x + x)"),
2750            "`let x = x + x` would never end, so a binding is a lambda: {out}"
2751        );
2752    }
2753
2754    #[test]
2755    fn a_body_that_takes_an_enum_apart_names_the_constructor_and_ignores_what_it_may() {
2756        let out = generate(
2757            r#"{"universes":[{"name":"demo","types":[
2758                {"k":"enum","name":"Size","variants":[{"name":"small"},{"name":"large","payload":"i64"}]}],
2759              "functions":[
2760                {"name":"is_large","params":[{"name":"s","ty":"Size"}],"ret":"bool",
2761                 "body":{"k":"match","ty":"Size","value":{"k":"var","name":"s"},"arms":[
2762                    {"tag":"small","body":{"k":"lit","value":false}},
2763                    {"tag":"large","body":{"k":"lit","value":true}}]}}]}]}"#,
2764        );
2765        assert!(
2766            out.contains("is_large s = case s of { SizeSmall -> False; SizeLarge _ -> True }"),
2767            "{out}"
2768        );
2769    }
2770
2771    #[test]
2772    fn a_thirty_two_bit_integer_is_widened_where_a_wider_number_is_wanted() {
2773        let out = generate(
2774            r#"{"universes":[{"name":"demo","functions":[
2775                {"name":"widen","params":[{"name":"x","ty":"i32"}],"ret":"i64",
2776                 "body":{"k":"var","name":"x"}}]}]}"#,
2777        );
2778        assert!(out.contains("widen x = P.fromIntegral x"), "{out}");
2779    }
2780
2781    #[test]
2782    fn string_literals_are_written_so_that_haskell_reads_the_same_text() {
2783        assert_eq!(string_literal("plain"), "\"plain\"");
2784        assert_eq!(string_literal("a \"q\" \\ b"), "\"a \\\"q\\\" \\\\ b\"");
2785        assert_eq!(string_literal("line\nbreak"), "\"line\\nbreak\"");
2786        // A character outside ASCII is its code point, and a digit after it
2787        // must not be read as more of the number.
2788        assert_eq!(string_literal("é1"), "\"\\233\\&1\"");
2789        assert_eq!(string_literal("😀"), "\"\\128512\"");
2790    }
2791
2792    #[test]
2793    fn values_become_literals_haskell_would_accept() {
2794        assert_eq!(literal(&Value::Bool(true)), "True");
2795        assert_eq!(literal(&Value::Null), "Nothing");
2796        assert_eq!(literal(&Value::Float(2.0)), "2.0");
2797        assert_eq!(
2798            literal(&Value::Int(-3)),
2799            "(-3)",
2800            "`f -3` is a subtraction, so a negative number is bracketed"
2801        );
2802        assert_eq!(
2803            literal(&Value::Tuple(vec![Value::Int(1), Value::Str("a".into())])),
2804            "(1, \"a\")"
2805        );
2806        assert_eq!(literal(&Value::Bytes(vec![1, 2, 3])), "(BS.pack [1, 2, 3])");
2807    }
2808
2809    #[test]
2810    fn a_universe_is_a_module_named_for_it_beside_the_support() {
2811        let ws = checked(SHAPES);
2812        let files = Haskell
2813            .generate(&ws, &GenOptions::default())
2814            .expect("generates");
2815        let paths: Vec<String> = files
2816            .iter()
2817            .map(|f| f.path.to_string_lossy().into_owned())
2818            .collect();
2819        assert_eq!(
2820            paths,
2821            [
2822                "haskell/Demo.hs",
2823                "haskell/UnitypeSupport.hs",
2824                "haskell/UnitypeHarness.hs"
2825            ]
2826        );
2827        assert!(generate(SHAPES).contains("module Demo where"));
2828    }
2829
2830    #[test]
2831    fn a_universe_cannot_take_the_name_of_the_module_written_beside_it() {
2832        let ws = checked(r#"{"universes":[{"name":"unitypeSupport"}]}"#);
2833        assert!(matches!(
2834            Haskell.generate(&ws, &GenOptions::default()),
2835            Err(GenError::Unsupported { .. })
2836        ));
2837    }
2838
2839    #[test]
2840    fn nothing_is_written_beside_a_universe_that_was_not_asked_for() {
2841        let ws = checked(SHAPES);
2842        let files = Haskell
2843            .generate(
2844                &ws,
2845                &GenOptions {
2846                    harness: false,
2847                    ..GenOptions::default()
2848                },
2849            )
2850            .expect("generates");
2851        assert!(!files.iter().any(|f| f.path.ends_with("UnitypeHarness.hs")));
2852    }
2853
2854    #[test]
2855    fn generating_twice_gives_the_same_bytes() {
2856        assert_eq!(generate(SHAPES), generate(SHAPES));
2857    }
2858
2859    #[test]
2860    fn what_another_universe_declares_is_imported_with_what_comes_with_it() {
2861        let ws = checked(
2862            r#"{"universes":[
2863                {"name":"geo","types":[
2864                    {"k":"struct","name":"Point","fields":[{"name":"x","ty":"f64"}]},
2865                    {"k":"alias","name":"Pair","target":{"k":"tuple","items":["f64","f64"]}}]},
2866                {"name":"map","types":[
2867                    {"k":"struct","name":"Pin","fields":[
2868                        {"name":"at","ty":"geo::Point"},{"name":"span","ty":"geo::Pair"}]}]}]}"#,
2869        );
2870        let out = Haskell
2871            .generate(&ws, &GenOptions::default())
2872            .expect("generates")
2873            .into_iter()
2874            .find(|f| f.path.ends_with("Map.hs"))
2875            .expect("a module for it")
2876            .contents;
2877        assert!(out.contains("import Geo (Pair, Point (..))"), "{out}");
2878        assert!(out.contains("module Map where"), "{out}");
2879    }
2880}