Skip to main content

unitype_codegen/
rust.rs

1//! Writing a universe out as Rust.
2//!
3//! Rust has no inheritance, so there is a choice to make and it is worth being
4//! explicit about. A child could hold its parent in a flattened field, keeping
5//! the shape of the declaration; or it could carry every field it has,
6//! inherited or not. This does the second.
7//!
8//! Flattening wins because the wire is what matters. `Circle` serializes to the
9//! same object either way, but flattened it also *reads* like the object —
10//! `circle.id` rather than `circle.base.id`, one level however deep the
11//! hierarchy went. Rust was never going to give subtype polymorphism anyway;
12//! what it gives is traits, and an interface becomes one, so the polymorphism
13//! that does exist lands where Rust can actually use it.
14//!
15//! # Generics
16//!
17//! Generic declarations and signatures keep their parameters, and a bound,
18//! being an interface, is a trait bound. Two things differ from the universe:
19//!
20//! - Rust refuses a struct, an enum or an alias with a parameter it never
21//!   uses, and the checker already knows which those are, so they are left
22//!   out — of the declaration, and of every argument list that names it. A
23//!   parameter that is not used cannot change what a value holds, so nothing
24//!   on the wire moves.
25//! - A body clones what it reads and may compare what it is given, so a
26//!   signature with a body asks `Clone + PartialEq` of each of its parameters.
27//!   One without a body asks only what the universe asks.
28//!
29//! A type alias's bounds are left out too: Rust does not enforce them there and
30//! says so.
31//!
32//! # Bytes
33//!
34//! Bytes travel as base64 text, which is how every language's JSON can hold
35//! them. serde writes a `Vec<u8>` as an array of numbers instead, and cannot be
36//! told otherwise for a `Vec<Vec<u8>>` or an `Option<Vec<u8>>` without a
37//! wrapper, so bytes are a type of their own, `Bytes`. There is one, shared by
38//! every universe, in a module beside them named `unitype_support`, which is
39//! written only when something uses it.
40
41use std::collections::{BTreeMap, BTreeSet, HashMap};
42
43use heck::ToUpperCamelCase;
44use unitype_core::check::{CheckedWorkspace, Variance};
45use unitype_core::ir::{
46    AliasDef, EnumDef, Expr, Field, FunctionSig, InterfaceDef, LiteralValue, PrimOp, StructDef,
47    Type, TypeDef, TypeParamDecl, TypeRef, Universe,
48};
49use unitype_core::lang::{LanguageProfile, profile};
50use unitype_core::value::Value;
51use unitype_core::{Ident, QualifiedName};
52
53use crate::writer::CodeWriter;
54use crate::{Backend, GenError, GenOptions, GeneratedFile, header, ordered_defs, selected};
55
56/// What every generated type derives.
57const DERIVES: &str = "#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]";
58
59/// The Rust backend.
60pub struct Rust;
61
62impl Backend for Rust {
63    fn id(&self) -> &'static str {
64        "rust"
65    }
66
67    fn extension(&self) -> &'static str {
68        "rs"
69    }
70
71    fn generate(
72        &self,
73        ws: &CheckedWorkspace,
74        options: &GenOptions,
75    ) -> Result<Vec<GeneratedFile>, GenError> {
76        let profile = profile("rust")?;
77        let mut files = Vec::new();
78        let chosen = selected(ws, options);
79        for universe in &chosen {
80            files.push(GeneratedFile {
81                path: format!("rust/{}.rs", universe.name).into(),
82                contents: universe_file(ws, universe, &profile, options),
83            });
84        }
85        if chosen.iter().any(|u| mentions_bytes(u)) {
86            if let Some(clash) = chosen.iter().find(|u| u.name.as_str() == SUPPORT) {
87                return Err(GenError::Unsupported {
88                    language: "rust".into(),
89                    what: format!("a universe named `{}`", clash.name),
90                    detail: "that is the module the shared `Bytes` is written to".into(),
91                });
92            }
93            files.push(GeneratedFile {
94                path: format!("rust/{SUPPORT}.rs").into(),
95                contents: SUPPORT_MODULE.to_string(),
96            });
97        }
98        Ok(files)
99    }
100}
101
102fn universe_file(
103    ws: &CheckedWorkspace,
104    universe: &Universe,
105    profile: &LanguageProfile,
106    options: &GenOptions,
107) -> String {
108    let mut w = CodeWriter::new();
109
110    if options.header {
111        for line in header("//", universe, ws) {
112            w.line(line);
113        }
114        w.blank();
115    }
116    if let Some(doc) = &universe.doc {
117        w.comment("//! ", doc);
118        w.blank();
119    }
120
121    let uses = imports(universe);
122    if !uses.is_empty() {
123        for (from, names) in &uses {
124            w.write(format_args!("use super::{from}::{{{}}};", names.join(", ")));
125        }
126        w.blank();
127    }
128    if mentions_map(universe) {
129        w.line("use std::collections::BTreeMap;");
130        w.blank();
131    }
132    if mentions_bytes(universe) {
133        w.write(format_args!("use super::{SUPPORT}::Bytes;"));
134        w.blank();
135    }
136
137    for def in ordered_defs(universe) {
138        match def {
139            TypeDef::Struct(d) => emit_struct(&mut w, ws, universe, d, profile),
140            TypeDef::Interface(d) => emit_interface(&mut w, ws, universe, d, profile),
141            TypeDef::Enum(d) => emit_enum(&mut w, ws, universe, d, profile),
142            TypeDef::Alias(d) => emit_alias(&mut w, ws, universe, d, profile),
143        }
144        w.blank();
145    }
146
147    if options.stubs {
148        for sig in &universe.functions {
149            emit_signature(&mut w, ws, universe, sig, profile);
150            w.blank();
151        }
152    }
153
154    w.finish()
155}
156
157fn imports(universe: &Universe) -> Vec<(String, Vec<String>)> {
158    let mut found: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
159    for_each_type(universe, &mut |ty| {
160        crate::refs_in(ty, &mut |r| {
161            if let Some(from) = &r.universe {
162                if from != &universe.name {
163                    found
164                        .entry(from.to_string())
165                        .or_default()
166                        .insert(r.name.to_string());
167                }
168            }
169        });
170    });
171    found
172        .into_iter()
173        .map(|(from, names)| (from, names.into_iter().collect()))
174        .collect()
175}
176
177/// Whether anything here is a map, at any depth, so the import can be omitted
178/// when nothing needs it.
179fn mentions_map(universe: &Universe) -> bool {
180    fn anywhere(ty: &Type) -> bool {
181        matches!(ty, Type::Map { .. }) || ty.children().iter().any(|c| anywhere(c))
182    }
183    let mut found = false;
184    for_each_type(universe, &mut |ty| found |= anywhere(ty));
185    found
186}
187
188/// Whether anything here is bytes, at any depth, or a body writes some out.
189fn mentions_bytes(universe: &Universe) -> bool {
190    fn anywhere(ty: &Type) -> bool {
191        matches!(ty, Type::Bytes) || ty.children().iter().any(|c| anywhere(c))
192    }
193    fn holds(value: &Value) -> bool {
194        match value {
195            Value::Bytes(_) => true,
196            Value::List(items) | Value::Tuple(items) => items.iter().any(holds),
197            Value::Record(fields) => fields.values().any(holds),
198            Value::Map(entries) => entries.iter().any(|(k, v)| holds(k) || holds(v)),
199            Value::Variant { value, .. } => holds(value),
200            _ => false,
201        }
202    }
203    let mut found = false;
204    for_each_type(universe, &mut |ty| found |= anywhere(ty));
205    found
206        || crate::bodies_use(
207            universe,
208            |e| matches!(e, Expr::Lit { value } if holds(value)),
209        )
210}
211
212/// The module the shared definitions are written to, beside the universes.
213const SUPPORT: &str = "unitype_support";
214
215/// What generated Rust shares between universes: bytes, as base64 text.
216///
217/// Written out by hand, base64 and all, so that generated code needs nothing
218/// beyond the `serde` it already uses.
219const SUPPORT_MODULE: &str = r#"// Generated by unitype. Do not edit.
220//
221// What generated code shares between universes.
222
223/// Bytes, which travel as base64 text: JSON has no byte string, and an array of
224/// numbers is a poor way to write one.
225#[derive(Debug, Clone, PartialEq, Eq, Default)]
226pub struct Bytes(pub Vec<u8>);
227
228impl From<Vec<u8>> for Bytes {
229    fn from(bytes: Vec<u8>) -> Self {
230        Bytes(bytes)
231    }
232}
233
234impl From<Bytes> for Vec<u8> {
235    fn from(bytes: Bytes) -> Self {
236        bytes.0
237    }
238}
239
240impl std::ops::Deref for Bytes {
241    type Target = [u8];
242
243    fn deref(&self) -> &[u8] {
244        &self.0
245    }
246}
247
248const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
249
250fn encode(bytes: &[u8]) -> String {
251    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
252    for chunk in bytes.chunks(3) {
253        let n = (u32::from(chunk[0]) << 16)
254            | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8)
255            | u32::from(*chunk.get(2).unwrap_or(&0));
256        for (i, shift) in [18, 12, 6, 0].into_iter().enumerate() {
257            if i <= chunk.len() {
258                out.push(ALPHABET[(n >> shift & 63) as usize] as char);
259            } else {
260                out.push('=');
261            }
262        }
263    }
264    out
265}
266
267fn decode(text: &str) -> Result<Vec<u8>, String> {
268    let text = text.as_bytes();
269    if text.len() % 4 != 0 {
270        return Err("base64 text comes in groups of four".to_string());
271    }
272    let mut out = Vec::with_capacity(text.len() / 4 * 3);
273    for (i, group) in text.chunks(4).enumerate() {
274        let last = (i + 1) * 4 == text.len();
275        let padding = if last {
276            group.iter().rev().take_while(|&&c| c == b'=').count()
277        } else {
278            0
279        };
280        if padding > 2 {
281            return Err("too much padding".to_string());
282        }
283        let mut n = 0u32;
284        for (j, &c) in group.iter().enumerate() {
285            let sextet = if j >= 4 - padding {
286                0
287            } else {
288                ALPHABET
289                    .iter()
290                    .position(|&a| a == c)
291                    .ok_or_else(|| format!("`{}` is not base64", c as char))? as u32
292            };
293            n = n << 6 | sextet;
294        }
295        out.push((n >> 16) as u8);
296        if padding < 2 {
297            out.push((n >> 8) as u8);
298        }
299        if padding < 1 {
300            out.push(n as u8);
301        }
302    }
303    Ok(out)
304}
305
306impl serde::Serialize for Bytes {
307    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
308        serializer.serialize_str(&encode(&self.0))
309    }
310}
311
312impl<'de> serde::Deserialize<'de> for Bytes {
313    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
314        struct Text;
315
316        impl serde::de::Visitor<'_> for Text {
317            type Value = Bytes;
318
319            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
320                f.write_str("base64 text")
321            }
322
323            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Bytes, E> {
324                decode(text).map(Bytes).map_err(E::custom)
325            }
326        }
327
328        deserializer.deserialize_str(Text)
329    }
330}
331"#;
332
333fn for_each_type(universe: &Universe, f: &mut impl FnMut(&Type)) {
334    for def in &universe.types {
335        match def {
336            TypeDef::Struct(d) => d.fields.iter().for_each(|x| f(&x.ty)),
337            TypeDef::Interface(d) => d.fields.iter().for_each(|x| f(&x.ty)),
338            TypeDef::Enum(d) => d.variants.iter().for_each(|v| f(&v.payload)),
339            TypeDef::Alias(d) => f(&d.target),
340        }
341        for bound in def.params().iter().flat_map(|p| &p.bounds) {
342            f(&Type::Ref(bound.clone()));
343        }
344    }
345    for sig in &universe.functions {
346        sig.params.iter().for_each(|p| f(&p.ty));
347        f(&sig.ret);
348        for bound in sig.params_decl.iter().flat_map(|p| &p.bounds) {
349            f(&Type::Ref(bound.clone()));
350        }
351    }
352}
353
354/// How Rust writes a type: as the profile spells it, without the argument for
355/// any generic parameter the declaration it is given to never uses.
356fn spell(ws: &CheckedWorkspace, profile: &LanguageProfile, ty: &Type) -> String {
357    profile.spell(&used(ws, ty))
358}
359
360/// A type with every argument for an unused generic parameter left out.
361///
362/// The checker composes variance, so a parameter it calls unused is mentioned
363/// only where some other declaration ignores it. Leaving those arguments out
364/// everywhere leaves the parameter mentioned nowhere.
365fn used(ws: &CheckedWorkspace, ty: &Type) -> Type {
366    let kids: Vec<Type> = ty.children().into_iter().map(|c| used(ws, c)).collect();
367    match ty.with_children(kids) {
368        Type::Ref(mut r) => {
369            if let Some(variance) = ws.ref_target_of(&r).and_then(|q| ws.variance_of(&q)) {
370                r.args = r
371                    .args
372                    .into_iter()
373                    .zip(variance)
374                    .filter(|(_, v)| **v != Variance::Unused)
375                    .map(|(a, _)| a)
376                    .collect();
377            }
378            Type::Ref(r)
379        }
380        other => other,
381    }
382}
383
384/// A declaration's generic parameters that Rust will accept, which are the
385/// ones it uses.
386fn kept<'a>(
387    ws: &CheckedWorkspace,
388    name: &QualifiedName,
389    params: &'a [TypeParamDecl],
390) -> Vec<&'a TypeParamDecl> {
391    let variance = ws.variance_of(name).unwrap_or_default();
392    params
393        .iter()
394        .enumerate()
395        .filter(|(i, _)| variance.get(*i) != Some(&Variance::Unused))
396        .map(|(_, p)| p)
397        .collect()
398}
399
400/// Generic parameters as Rust writes them where they are declared — `<T: Named,
401/// U>` — or nothing when there are none.
402///
403/// `bounded` is false where Rust would not enforce a bound, and `also` is
404/// asked of every parameter on top of what the universe asks.
405fn generics(
406    ws: &CheckedWorkspace,
407    profile: &LanguageProfile,
408    params: &[&TypeParamDecl],
409    bounded: bool,
410    also: &[&str],
411) -> String {
412    if params.is_empty() {
413        return String::new();
414    }
415    let parts: Vec<String> = params
416        .iter()
417        .map(|p| {
418            let mut bounds: Vec<String> = Vec::new();
419            if bounded {
420                bounds.extend(
421                    p.bounds
422                        .iter()
423                        .map(|b| spell(ws, profile, &Type::Ref(b.clone()))),
424                );
425            }
426            bounds.extend(also.iter().map(ToString::to_string));
427            let name = profile.name(&p.name);
428            if bounds.is_empty() {
429                name
430            } else {
431                format!("{name}: {}", bounds.join(" + "))
432            }
433        })
434        .collect();
435    format!("<{}>", parts.join(", "))
436}
437
438/// Generic parameters as Rust writes them where they are used: `<T, U>`.
439fn arguments(profile: &LanguageProfile, params: &[&TypeParamDecl]) -> String {
440    if params.is_empty() {
441        return String::new();
442    }
443    let names: Vec<String> = params.iter().map(|p| profile.name(&p.name)).collect();
444    format!("<{}>", names.join(", "))
445}
446
447fn emit_struct(
448    w: &mut CodeWriter,
449    ws: &CheckedWorkspace,
450    universe: &Universe,
451    def: &StructDef,
452    profile: &LanguageProfile,
453) {
454    let name = QualifiedName::new(universe.name.clone(), def.name.clone());
455    // Every field it has, inherited or not: the wire has no notion of where a
456    // field came from, and neither does the reader.
457    let fields = ws
458        .flat_fields(&name)
459        .map(<[Field]>::to_vec)
460        .unwrap_or_default();
461
462    if let Some(doc) = &def.doc {
463        w.comment("/// ", doc);
464    }
465    if let Some(parent) = &def.extends {
466        w.comment(
467            "/// ",
468            &format!(
469                "Inherits from `{}`. Rust has no inheritance, so the fields are \
470                 carried here; the shape on the wire is unchanged.",
471                parent.name
472            ),
473        );
474    }
475    w.line(DERIVES);
476
477    let params = kept(ws, &name, &def.params);
478    let declared = format!(
479        "{}{}",
480        profile.name(&def.name),
481        generics(ws, profile, &params, true, &[])
482    );
483    if fields.is_empty() {
484        w.write(format_args!("pub struct {declared};"));
485    } else {
486        w.block(format!("pub struct {declared} {{"), "}", |w| {
487            emit_fields(w, ws, &fields, profile)
488        });
489    }
490
491    // What it claims to satisfy becomes what Rust can actually dispatch on.
492    for iface in &def.implements {
493        w.blank();
494        // What the interface asks for, at the arguments this struct gives it.
495        let iface = TypeRef {
496            universe: Some(iface.universe.clone().unwrap_or(universe.name.clone())),
497            name: iface.name.clone(),
498            args: iface.args.clone(),
499        };
500        w.block(
501            format!(
502                "impl{} {} for {}{} {{",
503                generics(ws, profile, &params, true, &[]),
504                spell(ws, profile, &Type::Ref(iface.clone())),
505                profile.name(&def.name),
506                arguments(profile, &params)
507            ),
508            "}",
509            |w| {
510                let required = ws.fields_of(&iface).unwrap_or_default();
511                for (i, field) in required.iter().enumerate() {
512                    if i > 0 {
513                        w.blank();
514                    }
515                    let spelled = spell(ws, profile, &field.ty);
516                    w.block(
517                        format!("fn {}(&self) -> &{spelled} {{", profile.name(&field.name)),
518                        "}",
519                        |w| w.write(format_args!("&self.{}", profile.name(&field.name))),
520                    );
521                }
522            },
523        );
524    }
525}
526
527fn emit_fields(
528    w: &mut CodeWriter,
529    ws: &CheckedWorkspace,
530    fields: &[Field],
531    profile: &LanguageProfile,
532) {
533    for field in fields {
534        if let Some(doc) = &field.doc {
535            w.comment("/// ", doc);
536        }
537        for caveat in profile.caveats(&field.ty) {
538            w.comment("// ", caveat);
539        }
540
541        let renamed = profile.name(&field.name) != field.name.as_str();
542        if renamed {
543            // The escape keeps the name usable in Rust; the rename keeps it
544            // correct on the wire.
545            w.write(format_args!("#[serde(rename = {:?})]", field.name.as_str()));
546        }
547        // Absent and null are one state, so an absent field neither has to be
548        // sent nor has to arrive. What may be absent is what the canonical
549        // form leaves out: anything that expands to `T?`, `null` or `any`. A
550        // `()` holds nothing else, so it is never sent at all.
551        let skip = match ws.expand_alias(&field.ty) {
552            Type::Optional { .. } => {
553                Some("#[serde(default, skip_serializing_if = \"Option::is_none\")]")
554            }
555            Type::Any => {
556                Some("#[serde(default, skip_serializing_if = \"serde_json::Value::is_null\")]")
557            }
558            Type::Unit => Some("#[serde(default, skip_serializing)]"),
559            _ => None,
560        };
561        if let Some(attribute) = skip {
562            w.line(attribute);
563        }
564        w.write(format_args!(
565            "pub {}: {},",
566            profile.name(&field.name),
567            spell(ws, profile, &field.ty)
568        ));
569    }
570}
571
572fn emit_interface(
573    w: &mut CodeWriter,
574    ws: &CheckedWorkspace,
575    universe: &Universe,
576    def: &InterfaceDef,
577    profile: &LanguageProfile,
578) {
579    if let Some(doc) = &def.doc {
580        w.comment("/// ", doc);
581    }
582    let name = QualifiedName::new(universe.name.clone(), def.name.clone());
583    let fields = ws
584        .flat_fields(&name)
585        .map(<[Field]>::to_vec)
586        .unwrap_or_default();
587
588    // A field contract is a trait of accessors: the closest thing Rust has to
589    // "anything with these fields".
590    let declared = format!(
591        "{}{}",
592        profile.name(&def.name),
593        generics(ws, profile, &kept(ws, &name, &def.params), true, &[])
594    );
595    if fields.is_empty() {
596        w.write(format_args!("pub trait {declared} {{}}"));
597        return;
598    }
599    w.block(format!("pub trait {declared} {{"), "}", |w| {
600        for (i, field) in fields.iter().enumerate() {
601            if i > 0 {
602                w.blank();
603            }
604            if let Some(doc) = &field.doc {
605                w.comment("/// ", doc);
606            }
607            w.write(format_args!(
608                "fn {}(&self) -> &{};",
609                profile.name(&field.name),
610                spell(ws, profile, &field.ty)
611            ));
612        }
613    });
614}
615
616fn emit_enum(
617    w: &mut CodeWriter,
618    ws: &CheckedWorkspace,
619    universe: &Universe,
620    def: &EnumDef,
621    profile: &LanguageProfile,
622) {
623    if let Some(doc) = &def.doc {
624        w.comment("/// ", doc);
625    }
626    let name = QualifiedName::new(universe.name.clone(), def.name.clone());
627    w.line(DERIVES);
628    // Adjacent tagging is exactly the wire form: a tag beside a payload.
629    w.line("#[serde(tag = \"$tag\", content = \"value\")]");
630    w.block(
631        format!(
632            "pub enum {}{} {{",
633            profile.name(&def.name),
634            generics(ws, profile, &kept(ws, &name, &def.params), true, &[])
635        ),
636        "}",
637        |w| {
638            for variant in &def.variants {
639                if let Some(doc) = &variant.doc {
640                    w.comment("/// ", doc);
641                }
642                if matches!(variant.payload, Type::Unit) {
643                    w.write(format_args!("{},", variant.name));
644                } else {
645                    w.write(format_args!(
646                        "{}({}),",
647                        variant.name,
648                        spell(ws, profile, &variant.payload)
649                    ));
650                }
651            }
652        },
653    );
654}
655
656fn emit_alias(
657    w: &mut CodeWriter,
658    ws: &CheckedWorkspace,
659    universe: &Universe,
660    def: &AliasDef,
661    profile: &LanguageProfile,
662) {
663    if let Some(doc) = &def.doc {
664        w.comment("/// ", doc);
665    }
666    let params = kept(
667        ws,
668        &QualifiedName::new(universe.name.clone(), def.name.clone()),
669        &def.params,
670    );
671    match &def.target {
672        // A union of nothing but strings is a set of names, and Rust has a
673        // word for that: an enum whose variants carry nothing, each one
674        // travelling as the string it stands for. Anything else would accept
675        // every string there is.
676        Type::Union { members } if members.iter().all(is_string_literal) => {
677            let mut taken = BTreeSet::new();
678            w.line(DERIVES);
679            w.block(
680                format!("pub enum {} {{", profile.name(&def.name)),
681                "}",
682                |w| {
683                    for member in members {
684                        let Type::Literal {
685                            value: LiteralValue::Str(text),
686                        } = member
687                        else {
688                            continue;
689                        };
690                        let case = distinct(named_after(text), &mut taken);
691                        w.write(format_args!("#[serde(rename = {text:?})]"));
692                        w.write(format_args!("{case},"));
693                    }
694                },
695            );
696        }
697        // Any other untagged union has to be a real enum in Rust, tried in
698        // order.
699        Type::Union { members } => {
700            let mut taken = BTreeSet::new();
701            w.line(DERIVES);
702            w.line("#[serde(untagged)]");
703            w.block(
704                format!(
705                    "pub enum {}{} {{",
706                    profile.name(&def.name),
707                    generics(ws, profile, &params, true, &[])
708                ),
709                "}",
710                |w| {
711                    for member in members {
712                        let spelled = spell(ws, profile, member);
713                        // Two arms can spell alike — two literals of one base
714                        // type do — and an enum cannot name two variants the
715                        // same thing.
716                        let case = distinct(variant_name(member, &spelled), &mut taken);
717                        w.write(format_args!("{case}({spelled}),"));
718                    }
719                },
720            );
721        }
722        other => w.write(format_args!(
723            "pub type {}{} = {};",
724            profile.name(&def.name),
725            generics(ws, profile, &params, false, &[]),
726            spell(ws, profile, other)
727        )),
728    }
729}
730
731fn is_string_literal(ty: &Type) -> bool {
732    matches!(
733        ty,
734        Type::Literal {
735            value: LiteralValue::Str(_)
736        }
737    )
738}
739
740/// A variant name for a string a union admits.
741///
742/// The string itself goes on the wire, by way of a rename, so this only has to
743/// be something Rust will accept and a reader will recognise.
744fn named_after(text: &str) -> String {
745    let name = text.to_upper_camel_case();
746    match name.chars().next() {
747        None => "Empty".to_string(),
748        Some(first) if first.is_ascii_alphabetic() => name,
749        Some(_) => format!("V{name}"),
750    }
751}
752
753/// A name nothing else in the same enum has taken, numbered if it has to be.
754fn distinct(name: String, taken: &mut BTreeSet<String>) -> String {
755    let mut candidate = name.clone();
756    let mut n = 2;
757    while !taken.insert(candidate.clone()) {
758        candidate = format!("{name}{n}");
759        n += 1;
760    }
761    candidate
762}
763
764/// A variant name for one arm of an untagged union.
765fn variant_name(member: &Type, spelled: &str) -> String {
766    match member {
767        Type::Ref(r) => r.name.to_string(),
768        _ => {
769            let mut out = String::new();
770            let mut capitalize = true;
771            for c in spelled.chars() {
772                if c.is_ascii_alphanumeric() {
773                    if capitalize {
774                        out.extend(c.to_uppercase());
775                        capitalize = false;
776                    } else {
777                        out.push(c);
778                    }
779                } else {
780                    capitalize = true;
781                }
782            }
783            if out.is_empty() { "Other".into() } else { out }
784        }
785    }
786}
787
788fn emit_signature(
789    w: &mut CodeWriter,
790    ws: &CheckedWorkspace,
791    universe: &Universe,
792    sig: &FunctionSig,
793    profile: &LanguageProfile,
794) {
795    if let Some(doc) = &sig.doc {
796        w.comment("/// ", doc);
797    }
798    let params: Vec<String> = sig
799        .params
800        .iter()
801        .map(|p| format!("{}: {}", profile.name(&p.name), spell(ws, profile, &p.ty)))
802        .collect();
803    let qualified = QualifiedName::new(universe.name.clone(), sig.name.clone());
804
805    // A future in the return type is what `async` means here.
806    let (keyword, ret) = match &sig.ret {
807        Type::Future { of } => ("pub async fn", spell(ws, profile, of)),
808        other => ("pub fn", spell(ws, profile, other)),
809    };
810    // A function may leave a parameter unused, so all of them are kept.
811    let also: &[&str] = if sig.body.is_some() {
812        &["Clone", "PartialEq"]
813    } else {
814        &[]
815    };
816    let head = format!(
817        "{keyword} {}{}({}) -> {ret} {{",
818        profile.name(&sig.name),
819        generics(
820            ws,
821            profile,
822            &sig.params_decl.iter().collect::<Vec<_>>(),
823            true,
824            also
825        ),
826        params.join(", ")
827    );
828
829    match &sig.body {
830        Some(body) => {
831            let env: Env = sig
832                .params
833                .iter()
834                .map(|p| (p.name.clone(), p.ty.clone()))
835                .collect();
836            let text = Body { ws, profile }.expression(body, &env, Some(&sig.ret));
837            w.block(head, "}", |w| w.line(text));
838        }
839        None => {
840            w.comment(
841                "/// ",
842                &format!("Implement this and register it as `{qualified}`."),
843            );
844            w.block(head, "}", |w| {
845                w.write(format_args!("todo!({:?})", qualified.to_string()));
846            });
847        }
848    }
849}
850
851/// What each name in scope holds, at some point in a body.
852type Env = HashMap<Ident, Type>;
853
854/// Writing a body as Rust.
855///
856/// The checker takes a `T` wherever a `T?` is wanted, because a value that is
857/// there is one of the things a value that may be absent can be. Python and
858/// TypeScript agree and write nothing for it. Rust does not: an `i64` is not an
859/// `Option<i64>` until it is put in `Some`. So writing a body takes knowing what
860/// each part of it produces and what the place it stands in wants, which the
861/// workspace can say. Wherever nothing needs saying, the body comes out as it
862/// would have without it.
863struct Body<'a> {
864    ws: &'a CheckedWorkspace,
865    profile: &'a LanguageProfile,
866}
867
868impl Body<'_> {
869    /// Writes `expr`, where `env` says what each name holds and `wanted` is
870    /// what the place it stands in expects, when that place says.
871    fn expression(&self, expr: &Expr, env: &Env, wanted: Option<&Type>) -> String {
872        let profile = self.profile;
873        match expr {
874            // A binding, a conditional, and taking a value apart each hand on
875            // what is wanted to whatever produces their result, so `Some` goes
876            // on the one arm that needs it rather than round all of them.
877            Expr::Let { name, value, body } => {
878                let mut inner = env.clone();
879                if let Some(bound) = self.ws.type_of_expr(value, env) {
880                    inner.insert(name.clone(), bound);
881                }
882                format!(
883                    "{{ let {} = {}; {} }}",
884                    profile.name(name),
885                    self.expression(value, env, None),
886                    self.expression(body, &inner, wanted)
887                )
888            }
889            Expr::If {
890                cond,
891                then,
892                otherwise,
893            } => {
894                let arms = self.shared(wanted, expr, env);
895                format!(
896                    "if {} {{ {} }} else {{ {} }}",
897                    self.expression(cond, env, None),
898                    self.expression(then, env, arms.as_ref()),
899                    self.expression(otherwise, env, arms.as_ref())
900                )
901            }
902            Expr::Case {
903                value,
904                var,
905                some,
906                none,
907            } => {
908                let arms = self.shared(wanted, expr, env);
909                let mut present = env.clone();
910                let inside =
911                    self.ws
912                        .type_of_expr(value, env)
913                        .map(|t| match self.ws.expand_alias(&t) {
914                            Type::Optional { of } => *of,
915                            // Only `null` gets here, so the present arm binds
916                            // something that is never there.
917                            _ => Type::Never,
918                        });
919                if let Some(inside) = inside {
920                    present.insert(var.clone(), inside);
921                }
922                format!(
923                    "match {} {{ Some({}) => {}, None => {} }}",
924                    self.expression(value, env, None),
925                    profile.name(var),
926                    self.expression(some, &present, arms.as_ref()),
927                    self.expression(none, env, arms.as_ref())
928                )
929            }
930            Expr::Match { ty, value, arms } => {
931                let wanted = self.shared(wanted, expr, env);
932                let variants = self.ws.variants_of(ty).unwrap_or_default();
933                let name = profile.name(&ty.name);
934                let arms: Vec<String> = arms
935                    .iter()
936                    .map(|arm| {
937                        let mut inner = env.clone();
938                        let payload = variants.iter().find(|v| v.name == arm.tag);
939                        if let (Some(var), Some(variant)) = (&arm.var, payload) {
940                            inner.insert(var.clone(), variant.payload.clone());
941                        }
942                        let body = self.expression(&arm.body, &inner, wanted.as_ref());
943                        match &arm.var {
944                            Some(var) => {
945                                format!("{name}::{}({}) => {body}", arm.tag, profile.name(var))
946                            }
947                            // Braces and `..` match a variant whatever it
948                            // carries, so an arm that ignores the payload need
949                            // not know whether there is one.
950                            None => format!("{name}::{} {{ .. }} => {body}", arm.tag),
951                        }
952                    })
953                    .collect();
954                format!(
955                    "match {} {{ {} }}",
956                    self.expression(value, env, None),
957                    arms.join(", ")
958                )
959            }
960            _ => {
961                // What is wanted of the value itself, once it is in `Some`.
962                let within = wanted.map(|w| match self.ws.expand_alias(w) {
963                    Type::Optional { of } => self.ws.expand_alias(&of),
964                    other => other,
965                });
966                let text = self.value(expr, env, within.as_ref());
967                if self.needs_some(expr, env, wanted) {
968                    format!("Some({text})")
969                } else {
970                    text
971                }
972            }
973        }
974    }
975
976    /// Writes an expression that is not a branch, where `wanted` is what is
977    /// expected of it with any `Option` round it already accounted for.
978    fn value(&self, expr: &Expr, env: &Env, wanted: Option<&Type>) -> String {
979        let profile = self.profile;
980        match expr {
981            Expr::Lit { value } => {
982                let target = wanted.cloned().or_else(|| self.ws.type_of_expr(expr, env));
983                self.constant(value, target.as_ref())
984            }
985            Expr::Var { name } => profile.name(name),
986            Expr::Field { of, name } => {
987                // Cloned because a body produces a value rather than borrowing
988                // one, and the alternative is deciding lifetimes for generated
989                // code.
990                format!(
991                    "{}.{}.clone()",
992                    self.expression(of, env, None),
993                    profile.name(name)
994                )
995            }
996            Expr::MakeRecord { ty, fields } => {
997                let declared = self.ws.fields_of(ty).unwrap_or_default();
998                let mut parts: Vec<String> = fields
999                    .iter()
1000                    .map(|f| {
1001                        let field = declared.iter().find(|d| d.name == f.name);
1002                        format!(
1003                            "{}: {}",
1004                            profile.name(&f.name),
1005                            self.expression(&f.value, env, field.map(|d| &d.ty))
1006                        )
1007                    })
1008                    .collect();
1009                // The checker lets a body leave out a field that may be
1010                // absent, but a Rust struct literal names every field it has.
1011                // A field left out is one that is not there, which is `null`
1012                // written as that field wants it.
1013                parts.extend(
1014                    declared
1015                        .iter()
1016                        .filter(|d| !fields.iter().any(|f| f.name == d.name))
1017                        .filter(|d| {
1018                            matches!(
1019                                self.ws.expand_alias(&d.ty),
1020                                Type::Optional { .. } | Type::Unit | Type::Any
1021                            )
1022                        })
1023                        .map(|d| {
1024                            format!(
1025                                "{}: {}",
1026                                profile.name(&d.name),
1027                                self.constant(&Value::Null, Some(&d.ty))
1028                            )
1029                        }),
1030                );
1031                format!("{} {{ {} }}", profile.name(&ty.name), parts.join(", "))
1032            }
1033            Expr::MakeList { items } => {
1034                // Every element of a `Vec` is one type, so if one of them may
1035                // be absent they all have to be written as though they might.
1036                let elements = match wanted {
1037                    Some(Type::List { of }) if self.may_be_absent(of) => Some(of.as_ref().clone()),
1038                    _ => self.ws.type_of_expr(expr, env).and_then(|t| {
1039                        match self.ws.expand_alias(&t) {
1040                            Type::List { of } => Some(*of),
1041                            _ => None,
1042                        }
1043                    }),
1044                };
1045                let parts: Vec<String> = items
1046                    .iter()
1047                    .map(|i| self.expression(i, env, elements.as_ref()))
1048                    .collect();
1049                format!("vec![{}]", parts.join(", "))
1050            }
1051            Expr::MakeTuple { items } => {
1052                let slots = match wanted {
1053                    Some(Type::Tuple { items: slots }) if slots.len() == items.len() => {
1054                        Some(slots.as_slice())
1055                    }
1056                    _ => None,
1057                };
1058                let parts: Vec<String> = items
1059                    .iter()
1060                    .enumerate()
1061                    .map(|(n, i)| self.expression(i, env, slots.map(|s| &s[n])))
1062                    .collect();
1063                if parts.len() == 1 {
1064                    format!("({},)", parts[0])
1065                } else {
1066                    format!("({})", parts.join(", "))
1067                }
1068            }
1069            Expr::MakeVariant { ty, tag, value } => match value {
1070                Some(v) => {
1071                    let payload = self
1072                        .ws
1073                        .variants_of(ty)
1074                        .and_then(|vs| vs.into_iter().find(|x| &x.name == tag))
1075                        .map(|x| x.payload);
1076                    format!(
1077                        "{}::{tag}({})",
1078                        profile.name(&ty.name),
1079                        self.expression(v, env, payload.as_ref())
1080                    )
1081                }
1082                None => format!("{}::{tag}", profile.name(&ty.name)),
1083            },
1084            Expr::Call { sig, args } => {
1085                let params = self.ws.sig(sig).map(|s| s.params.as_slice());
1086                let parts: Vec<String> = args
1087                    .iter()
1088                    .enumerate()
1089                    .map(|(n, a)| {
1090                        let param = params.and_then(|ps| ps.get(n)).map(|p| &p.ty);
1091                        self.expression(a, env, param)
1092                    })
1093                    .collect();
1094                format!("{}({})", profile.name(&sig.name), parts.join(", "))
1095            }
1096            Expr::MapThrough {
1097                functor,
1098                value,
1099                var,
1100                body,
1101            } => {
1102                use unitype_core::ir::Functor;
1103                let mut inner = env.clone();
1104                let subject_ty = self.ws.type_of_expr(value, env);
1105                if let Some(subject_ty) = subject_ty {
1106                    if let Some((_, inside)) = Functor::split(&self.ws.expand_alias(&subject_ty)) {
1107                        inner.insert(var.clone(), inside.clone());
1108                    }
1109                }
1110                // What is wanted of each thing inside is whatever is wanted
1111                // inside the result. For an optional that is already what is
1112                // wanted here, since the `Option` round it is the map's own.
1113                let each = match functor {
1114                    Functor::Optional => wanted.cloned(),
1115                    _ => wanted.and_then(|w| match Functor::split(w) {
1116                        Some((f, inside)) if f == *functor => Some(inside.clone()),
1117                        _ => None,
1118                    }),
1119                };
1120                let subject = self.expression(value, env, None);
1121                let bound = profile.name(var);
1122                let inner = self.expression(body, &inner, each.as_ref());
1123                match functor {
1124                    Functor::List => {
1125                        format!("{subject}.into_iter().map(|{bound}| {inner}).collect()")
1126                    }
1127                    // Absent stays absent, which Rust already has a word for.
1128                    Functor::Optional => format!("{subject}.map(|{bound}| {inner})"),
1129                    Functor::Future => format!("{{ let {bound} = {subject}.await; {inner} }}"),
1130                }
1131            }
1132            Expr::Prim { op, args } => {
1133                // Rust compares an `Option` only with another, so a value
1134                // compared with something that may be absent is put in `Some`
1135                // to be compared at all.
1136                let others: Vec<Option<Type>> = match (op, args.as_slice()) {
1137                    (PrimOp::Eq | PrimOp::Ne, [x, y]) => {
1138                        vec![self.ws.type_of_expr(y, env), self.ws.type_of_expr(x, env)]
1139                    }
1140                    _ => vec![None; args.len()],
1141                };
1142                let operands: Vec<String> = args
1143                    .iter()
1144                    .zip(&others)
1145                    .map(|(a, other)| self.expression(a, env, other.as_ref()))
1146                    .collect();
1147                match (op, operands.as_slice()) {
1148                    (PrimOp::Neg, [x]) => format!("(-{x})"),
1149                    (PrimOp::Not, [x]) => format!("(!{x})"),
1150                    // A length is a `usize` in Rust and an `i64` everywhere
1151                    // else here.
1152                    (PrimOp::Len, [x]) => format!("({x}.len() as i64)"),
1153                    (op, [x, y]) => format!("({x} {} {y})", infix(*op)),
1154                    _ => unreachable!("the checker holds every operation to its arity"),
1155                }
1156            }
1157            // Borrowed and cloned element by element, so the list is still
1158            // there for anything else in the body that mentions it.
1159            Expr::Fold {
1160                list,
1161                init,
1162                acc,
1163                item,
1164                body,
1165                ..
1166            } => {
1167                // The starting value and every step are one type, the one
1168                // carried, which is also what the fold as a whole produces.
1169                let carried = self.ws.type_of_expr(expr, env);
1170                let mut inner = env.clone();
1171                if let Some(carried) = &carried {
1172                    inner.insert(acc.clone(), carried.clone());
1173                }
1174                let element =
1175                    self.ws
1176                        .type_of_expr(list, env)
1177                        .and_then(|t| match self.ws.expand_alias(&t) {
1178                            Type::List { of } => Some(*of),
1179                            _ => None,
1180                        });
1181                if let Some(element) = element {
1182                    inner.insert(item.clone(), element);
1183                }
1184                format!(
1185                    "{}.iter().cloned().fold({}, |{}, {}| {})",
1186                    self.expression(list, env, None),
1187                    self.expression(init, env, carried.as_ref()),
1188                    profile.name(acc),
1189                    profile.name(item),
1190                    self.expression(body, &inner, carried.as_ref())
1191                )
1192            }
1193            Expr::Let { .. } | Expr::If { .. } | Expr::Case { .. } | Expr::Match { .. } => {
1194                unreachable!("a branch is written by `expression`, which hands on what is wanted")
1195            }
1196        }
1197    }
1198
1199    /// Writes a constant as `wanted` has it.
1200    ///
1201    /// [`literal`] has only the value to go on, so `[1, null]` comes out as
1202    /// `vec![1, None]`, which is two types to Rust. Where a `[i64?]` is
1203    /// wanted, the `1` is one that is there: `vec![Some(1), None]`. Whatever
1204    /// this has nothing to add to is written as [`literal`] writes it.
1205    fn constant(&self, value: &Value, wanted: Option<&Type>) -> String {
1206        let Some(wanted) = wanted else {
1207            return literal(value);
1208        };
1209        match (self.ws.expand_alias(wanted), value) {
1210            // `null` is the one value its type holds, and Rust spells both `()`.
1211            (Type::Unit, Value::Null) => "()".into(),
1212            // unitype takes an `any` that is absent and one that is null to
1213            // be the same state, and `serde_json::Value` has no way to be
1214            // absent but its `Null`.
1215            (Type::Any, Value::Null) => "serde_json::Value::Null".into(),
1216            (Type::Optional { .. }, Value::Null) => literal(value),
1217            (Type::Optional { of }, present) => {
1218                format!("Some({})", self.constant(present, Some(&of)))
1219            }
1220            (Type::List { of }, Value::List(items)) => {
1221                let parts: Vec<String> =
1222                    items.iter().map(|i| self.constant(i, Some(&of))).collect();
1223                format!("vec![{}]", parts.join(", "))
1224            }
1225            (Type::Tuple { items: slots }, Value::Tuple(items)) if slots.len() == items.len() => {
1226                let parts: Vec<String> = items
1227                    .iter()
1228                    .zip(&slots)
1229                    .map(|(i, slot)| self.constant(i, Some(slot)))
1230                    .collect();
1231                if parts.len() == 1 {
1232                    format!("({},)", parts[0])
1233                } else {
1234                    format!("({})", parts.join(", "))
1235                }
1236            }
1237            (Type::Map { key, value: of }, Value::Map(entries)) => {
1238                let parts: Vec<String> = entries
1239                    .iter()
1240                    .map(|(k, v)| {
1241                        format!(
1242                            "({}, {})",
1243                            self.constant(k, Some(&key)),
1244                            self.constant(v, Some(&of))
1245                        )
1246                    })
1247                    .collect();
1248                format!("BTreeMap::from([{}])", parts.join(", "))
1249            }
1250            _ => literal(value),
1251        }
1252    }
1253
1254    /// What several alternatives are each written as, so that they come out as
1255    /// one Rust type: what the place wants, if that may be absent, and
1256    /// otherwise what they come to together.
1257    fn shared(&self, wanted: Option<&Type>, expr: &Expr, env: &Env) -> Option<Type> {
1258        match wanted {
1259            Some(w) if self.may_be_absent(w) => Some(w.clone()),
1260            _ => self.ws.type_of_expr(expr, env),
1261        }
1262    }
1263
1264    /// Whether a type is one Rust writes as an `Option`.
1265    fn may_be_absent(&self, ty: &Type) -> bool {
1266        matches!(self.ws.expand_alias(ty), Type::Optional { .. })
1267    }
1268
1269    /// Whether what `expr` produces has to be put in `Some` to be what is
1270    /// wanted.
1271    ///
1272    /// Something that may itself be absent is already an `Option`, and `null`
1273    /// is written `None`; anything else, where something that may be absent is
1274    /// wanted, has to be said to be there.
1275    fn needs_some(&self, expr: &Expr, env: &Env, wanted: Option<&Type>) -> bool {
1276        if !wanted.is_some_and(|w| self.may_be_absent(w)) {
1277            return false;
1278        }
1279        self.ws.type_of_expr(expr, env).is_some_and(|produced| {
1280            !matches!(
1281                self.ws.expand_alias(&produced),
1282                Type::Optional { .. } | Type::Unit
1283            )
1284        })
1285    }
1286}
1287
1288/// How Rust writes a two-operand operation.
1289fn infix(op: PrimOp) -> &'static str {
1290    match op {
1291        PrimOp::Eq => "==",
1292        PrimOp::Ne => "!=",
1293        PrimOp::Lt => "<",
1294        PrimOp::Le => "<=",
1295        PrimOp::Gt => ">",
1296        PrimOp::Ge => ">=",
1297        PrimOp::Add => "+",
1298        PrimOp::Sub => "-",
1299        PrimOp::Mul => "*",
1300        PrimOp::And => "&&",
1301        PrimOp::Or => "||",
1302        PrimOp::Neg | PrimOp::Not | PrimOp::Len => unreachable!("not a two-operand operation"),
1303    }
1304}
1305
1306/// Writes a value as a Rust literal.
1307pub fn literal(value: &Value) -> String {
1308    match value {
1309        Value::Null => "None".into(),
1310        Value::Bool(b) => b.to_string(),
1311        Value::Int(i) => i.to_string(),
1312        Value::Float(f) => {
1313            let plain = f.to_string();
1314            if plain.contains(['.', 'e', 'E']) {
1315                plain
1316            } else {
1317                format!("{plain}.0")
1318            }
1319        }
1320        Value::Str(s) => format!("{s:?}.to_string()"),
1321        Value::Bytes(b) => {
1322            let parts: Vec<String> = b.iter().map(|x| x.to_string()).collect();
1323            format!("Bytes(vec![{}])", parts.join(", "))
1324        }
1325        Value::List(items) => {
1326            let parts: Vec<String> = items.iter().map(literal).collect();
1327            format!("vec![{}]", parts.join(", "))
1328        }
1329        Value::Tuple(items) => {
1330            let parts: Vec<String> = items.iter().map(literal).collect();
1331            if parts.len() == 1 {
1332                format!("({},)", parts[0])
1333            } else {
1334                format!("({})", parts.join(", "))
1335            }
1336        }
1337        // An anonymous record has no declared type to name here, so it is
1338        // written as the map it is on the wire.
1339        Value::Record(fields) => {
1340            let parts: Vec<String> = fields
1341                .iter()
1342                .map(|(k, v)| format!("({k:?}.to_string(), {})", literal(v)))
1343                .collect();
1344            format!("BTreeMap::from([{}])", parts.join(", "))
1345        }
1346        Value::Map(entries) => {
1347            let parts: Vec<String> = entries
1348                .iter()
1349                .map(|(k, v)| format!("({}, {})", literal(k), literal(v)))
1350                .collect();
1351            format!("BTreeMap::from([{}])", parts.join(", "))
1352        }
1353        Value::Variant { tag, value } => match value.as_ref() {
1354            Value::Null => tag.to_string(),
1355            payload => format!("{tag}({})", literal(payload)),
1356        },
1357    }
1358}
1359
1360#[cfg(test)]
1361mod tests {
1362    use super::*;
1363    use unitype_core::Workspace;
1364    use unitype_core::check::check_workspace;
1365
1366    fn generate(json: &str) -> String {
1367        let ws = check_workspace(Workspace::from_json(json).expect("reads")).expect("checks");
1368        Rust.generate(&ws, &GenOptions::default())
1369            .expect("generates")
1370            .into_iter()
1371            .find(|f| f.path.to_string_lossy().ends_with("demo.rs"))
1372            .expect("a file for the demo universe")
1373            .contents
1374    }
1375
1376    const SHAPES: &str = r#"{"universes":[{"name":"demo","types":[
1377        {"k":"interface","name":"Identified","fields":[{"name":"id","ty":"str"}]},
1378        {"k":"struct","name":"Shape","implements":["Identified"],
1379         "fields":[{"name":"id","ty":"str"}]},
1380        {"k":"struct","name":"Circle","extends":"Shape","fields":[
1381            {"name":"kind","ty":{"k":"literal","value":{"str":"circle"}}},
1382            {"name":"radius","ty":"float"},
1383            {"name":"note","ty":"str?"}]},
1384        {"k":"struct","name":"Rect","extends":"Shape","fields":[
1385            {"name":"kind","ty":{"k":"literal","value":{"str":"rect"}}},
1386            {"name":"w","ty":"float"}]},
1387        {"k":"alias","name":"AnyShape","target":{"k":"union","members":["Circle","Rect"]}},
1388        {"k":"enum","name":"Colour","variants":[{"name":"Red"},{"name":"Custom","payload":"str"}]}],
1389      "functions":[
1390        {"name":"area","params":[{"name":"s","ty":"Circle"}],"ret":"float"},
1391        {"name":"load","params":[{"name":"id","ty":"str"}],"ret":{"k":"future","of":"Shape"}}]}]}"#;
1392
1393    #[test]
1394    fn a_struct_carries_every_field_it_has() {
1395        let out = generate(SHAPES);
1396        let circle = out
1397            .split("pub struct Circle {")
1398            .nth(1)
1399            .expect("declared")
1400            .split('}')
1401            .next()
1402            .expect("closed");
1403        assert!(
1404            circle.contains("pub id: String"),
1405            "the inherited field is right here, not one level down: {circle}"
1406        );
1407        assert!(circle.contains("pub radius: f64"), "{circle}");
1408    }
1409
1410    #[test]
1411    fn the_flattening_is_explained_rather_than_left_to_be_discovered() {
1412        let out = generate(SHAPES);
1413        assert!(out.contains("Rust has no inheritance"), "{out}");
1414    }
1415
1416    #[test]
1417    fn an_interface_becomes_a_trait_and_the_struct_implements_it() {
1418        let out = generate(SHAPES);
1419        assert!(out.contains("pub trait Identified {"), "{out}");
1420        assert!(out.contains("fn id(&self) -> &String;"), "{out}");
1421        assert!(out.contains("impl Identified for Shape {"), "{out}");
1422    }
1423
1424    #[test]
1425    fn a_field_that_may_be_absent_need_not_be_sent_or_arrive() {
1426        let out = generate(SHAPES);
1427        assert!(
1428            out.contains("#[serde(default, skip_serializing_if = \"Option::is_none\")]"),
1429            "{out}"
1430        );
1431        assert!(out.contains("pub note: Option<String>,"), "{out}");
1432    }
1433
1434    #[test]
1435    fn an_enum_is_tagged_the_way_the_wire_tags_it() {
1436        let out = generate(SHAPES);
1437        assert!(
1438            out.contains(r#"#[serde(tag = "$tag", content = "value")]"#),
1439            "{out}"
1440        );
1441        assert!(out.contains("Custom(String),"), "{out}");
1442    }
1443
1444    #[test]
1445    fn an_alias_to_a_union_becomes_an_untagged_enum() {
1446        let out = generate(SHAPES);
1447        assert!(out.contains("#[serde(untagged)]"), "{out}");
1448        assert!(out.contains("pub enum AnyShape {"), "{out}");
1449        assert!(out.contains("Circle(Circle),"), "{out}");
1450    }
1451
1452    #[test]
1453    fn a_union_of_strings_becomes_the_names_it_admits() {
1454        let out = generate(
1455            r#"{"universes":[{"name":"demo","types":[
1456                {"k":"alias","name":"Method","target":{"k":"union","members":[
1457                    {"k":"literal","value":{"str":"GET"}},
1458                    {"k":"literal","value":{"str":"POST"}},
1459                    {"k":"literal","value":{"str":"get"}},
1460                    {"k":"literal","value":{"str":"2xx"}}]}}]}]}"#,
1461        );
1462        assert!(
1463            out.contains("#[serde(rename = \"GET\")]\n    Get,"),
1464            "{out}"
1465        );
1466        assert!(
1467            out.contains("#[serde(rename = \"POST\")]\n    Post,"),
1468            "{out}"
1469        );
1470        assert!(
1471            out.contains("#[serde(rename = \"get\")]\n    Get2,"),
1472            "two strings that fold to one name still need two variants: {out}"
1473        );
1474        assert!(
1475            out.contains("V2xx,"),
1476            "a name cannot start with a digit: {out}"
1477        );
1478        assert!(
1479            !out.contains("untagged"),
1480            "untagged over `String` would accept every string there is: {out}"
1481        );
1482    }
1483
1484    #[test]
1485    fn arms_that_spell_alike_still_get_names_of_their_own() {
1486        let out = generate(
1487            r#"{"universes":[{"name":"demo","types":[
1488                {"k":"alias","name":"Level","target":{"k":"union","members":[
1489                    {"k":"literal","value":{"int":1}},
1490                    {"k":"literal","value":{"int":2}},
1491                    "str"]}}]}]}"#,
1492        );
1493        assert!(out.contains("I64(i64),"), "{out}");
1494        assert!(out.contains("I642(i64),"), "{out}");
1495        assert!(out.contains("String(String),"), "{out}");
1496    }
1497
1498    #[test]
1499    fn a_promise_in_the_return_type_is_what_async_means() {
1500        let out = generate(SHAPES);
1501        assert!(
1502            out.contains("pub async fn load(id: String) -> Shape {"),
1503            "{out}"
1504        );
1505    }
1506
1507    #[test]
1508    fn a_proposition_with_no_proof_leaves_a_hole_that_will_not_compile_quietly() {
1509        let out = generate(SHAPES);
1510        assert!(out.contains("todo!(\"demo::area\")"), "{out}");
1511    }
1512
1513    #[test]
1514    fn a_body_is_written_out_as_rust() {
1515        let out = generate(
1516            r#"{"universes":[{"name":"demo","types":[
1517                {"k":"struct","name":"User","fields":[{"name":"first","ty":"str"}]},
1518                {"k":"struct","name":"Badge","fields":[
1519                    {"name":"label","ty":"str"},{"name":"sides","ty":"i64"}]}],
1520              "functions":[
1521                {"name":"badge_of","params":[{"name":"u","ty":"User"}],"ret":"Badge",
1522                 "body":{"k":"make_record","ty":"Badge","fields":[
1523                    {"name":"label","value":{"k":"field","of":{"k":"var","name":"u"},"name":"first"}},
1524                    {"name":"sides","value":{"k":"lit","value":4}}]}}]}]}"#,
1525        );
1526        assert!(
1527            out.contains("Badge { label: u.first.clone(), sides: 4 }"),
1528            "one body, three languages: {out}"
1529        );
1530    }
1531
1532    #[test]
1533    fn mapping_through_absence_is_what_rust_already_calls_it() {
1534        let out = generate(
1535            r#"{"universes":[{"name":"demo","functions":[
1536                {"name":"trimmed","params":[{"name":"s","ty":"str?"}],"ret":"str?",
1537                 "body":{"k":"map_through","functor":"optional","value":{"k":"var","name":"s"},
1538                         "var":"x","body":{"k":"var","name":"x"}}}]}]}"#,
1539        );
1540        assert!(out.contains("s.map(|x| x)"), "{out}");
1541    }
1542
1543    /// Bodies that each put a value where one that may be absent is wanted, or
1544    /// leave one out.
1545    const ABSENT: &str = r#"{"universes":[{"name":"demo","types":[
1546        {"k":"struct","name":"Mark","fields":[
1547            {"name":"at","ty":"i64"},{"name":"before","ty":"i64?"}]},
1548        {"k":"enum","name":"Size","variants":[{"name":"small"},{"name":"large","payload":"i64"}]},
1549        {"k":"alias","name":"Later","target":"i64?"},
1550        {"k":"struct","name":"Entry","extends":"Mark","fields":[
1551            {"name":"why","ty":"str?"},{"name":"when","ty":"Later"},
1552            {"name":"extra","ty":"any"},{"name":"nothing","ty":"null"}]}],
1553      "functions":[
1554        {"name":"entry","params":[{"name":"x","ty":"i64"}],"ret":"Entry",
1555         "body":{"k":"make_record","ty":"Entry","fields":[
1556            {"name":"why","value":{"k":"lit","value":"w"}},
1557            {"name":"at","value":{"k":"var","name":"x"}}]}},
1558        {"name":"gaps","params":[],"ret":"[i64?]","body":{"k":"lit","value":[1,null]}},
1559        {"name":"nested","params":[],"ret":"[[i64?]]","body":{"k":"lit","value":[[1,null],[2]]}},
1560        {"name":"pair","params":[],"ret":{"k":"tuple","items":["i64?","i64?","str"]},
1561         "body":{"k":"lit","value":{"$tuple":[3,null,"x"]}}},
1562        {"name":"counts","params":[],"ret":{"k":"map","key":"str","value":"i64?"},
1563         "body":{"k":"lit","value":{"$map":[["a",1],["b",null]]}}},
1564        {"name":"gap_count","params":[],"ret":"i64",
1565         "body":{"k":"let","name":"g","value":{"k":"lit","value":[1,null]},
1566                 "body":{"k":"prim","op":"len","args":[{"k":"var","name":"g"}]}}},
1567        {"name":"mark","params":[{"name":"x","ty":"i64"}],"ret":"Mark",
1568         "body":{"k":"make_record","ty":"Mark","fields":[
1569            {"name":"at","value":{"k":"var","name":"x"}},
1570            {"name":"before","value":{"k":"var","name":"x"}}]}},
1571        {"name":"last_of","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64?",
1572         "body":{"k":"fold","list":{"k":"var","name":"xs"},"init":{"k":"lit","value":null},
1573                 "ty":"int?","acc":"p","item":"x","body":{"k":"var","name":"x"}}},
1574        {"name":"some_of","params":[{"name":"x","ty":"i64"}],"ret":"i64?",
1575         "body":{"k":"var","name":"x"}},
1576        {"name":"positive","params":[{"name":"x","ty":"i64"}],"ret":"i64?",
1577         "body":{"k":"if","cond":{"k":"prim","op":"gt","args":[
1578                     {"k":"var","name":"x"},{"k":"lit","value":0}]},
1579                 "then":{"k":"var","name":"x"},"else":{"k":"lit","value":null}}},
1580        {"name":"or_else","params":[{"name":"x","ty":"i64?"},{"name":"y","ty":"i64?"}],
1581         "ret":"i64?",
1582         "body":{"k":"case","value":{"k":"var","name":"x"},"var":"n",
1583                 "some":{"k":"var","name":"n"},"none":{"k":"var","name":"y"}}},
1584        {"name":"hint","params":[{"name":"s","ty":"Size"}],"ret":"i64?",
1585         "body":{"k":"match","ty":"Size","value":{"k":"var","name":"s"},"arms":[
1586            {"tag":"small","body":{"k":"lit","value":null}},
1587            {"tag":"large","var":"n","body":{"k":"var","name":"n"}}]}},
1588        {"name":"chosen","params":[{"name":"c","ty":"bool"},{"name":"x","ty":"i64"}],"ret":"i64",
1589         "body":{"k":"let","name":"y",
1590                 "value":{"k":"if","cond":{"k":"var","name":"c"},
1591                          "then":{"k":"var","name":"x"},"else":{"k":"lit","value":null}},
1592                 "body":{"k":"case","value":{"k":"var","name":"y"},"var":"n",
1593                         "some":{"k":"var","name":"n"},"none":{"k":"lit","value":0}}}},
1594        {"name":"is","params":[{"name":"x","ty":"i64?"},{"name":"y","ty":"i64"}],"ret":"bool",
1595         "body":{"k":"prim","op":"eq","args":[{"k":"var","name":"x"},{"k":"var","name":"y"}]}}]}]}"#;
1596
1597    #[test]
1598    fn a_value_where_one_that_may_be_absent_is_wanted_is_put_in_some() {
1599        let out = generate(ABSENT);
1600        assert!(out.contains("Mark { at: x, before: Some(x) }"), "{out}");
1601        assert!(
1602            out.contains("xs.iter().cloned().fold(None, |p, x| Some(x))"),
1603            "the starting value and each step are both what is carried: {out}"
1604        );
1605        assert!(
1606            out.contains("pub fn some_of(x: i64) -> Option<i64> {\n    Some(x)\n}"),
1607            "{out}"
1608        );
1609    }
1610
1611    #[test]
1612    fn only_the_arm_that_needs_it_is_put_in_some() {
1613        let out = generate(ABSENT);
1614        assert!(
1615            out.contains("if (x > 0) { Some(x) } else { None }"),
1616            "{out}"
1617        );
1618        assert!(
1619            out.contains("match x { Some(n) => Some(n), None => y }"),
1620            "an arm that may already be absent is an `Option` already: {out}"
1621        );
1622        assert!(
1623            out.contains("match s { Size::small { .. } => None, Size::large(n) => Some(n) }"),
1624            "{out}"
1625        );
1626        assert!(!out.contains("Some(None)"), "{out}");
1627    }
1628
1629    #[test]
1630    fn arms_nothing_outside_asks_about_are_written_to_what_they_come_to_together() {
1631        let out = generate(ABSENT);
1632        assert!(
1633            out.contains("let y = if c { Some(x) } else { None };"),
1634            "one arm may be absent, so both are `Option`s: {out}"
1635        );
1636        assert!(out.contains("match y { Some(n) => n, None => 0 }"), "{out}");
1637    }
1638
1639    #[test]
1640    fn a_value_compared_with_one_that_may_be_absent_is_compared_as_an_option() {
1641        let out = generate(ABSENT);
1642        assert!(out.contains("(x == Some(y))"), "{out}");
1643    }
1644
1645    #[test]
1646    fn a_field_left_out_is_written_as_the_nothing_it_stands_for() {
1647        let out = generate(ABSENT);
1648        assert!(
1649            out.contains(
1650                "Entry { why: Some(\"w\".to_string()), at: x, before: None, when: None, \
1651                 extra: serde_json::Value::Null, nothing: () }"
1652            ),
1653            "what was given first, as given, then the rest as declared, \
1654             inherited ones included: {out}"
1655        );
1656    }
1657
1658    #[test]
1659    fn an_alias_an_any_and_a_null_need_not_be_sent_or_arrive_either() {
1660        let out = generate(ABSENT);
1661        assert!(
1662            out.contains(
1663                "#[serde(default, skip_serializing_if = \"Option::is_none\")]\n    pub when: Later,"
1664            ),
1665            "an alias of an optional is still one: {out}"
1666        );
1667        assert!(
1668            out.contains(
1669                "#[serde(default, skip_serializing_if = \"serde_json::Value::is_null\")]\n    \
1670                 pub extra: serde_json::Value,"
1671            ),
1672            "{out}"
1673        );
1674        assert!(
1675            out.contains("#[serde(default, skip_serializing)]\n    pub nothing: (),"),
1676            "a `()` holds nothing else, so it is never sent: {out}"
1677        );
1678        assert!(
1679            out.contains("pub struct Entry {\n    pub at: i64,"),
1680            "a field that has to be there is still sent and still has to arrive: {out}"
1681        );
1682    }
1683
1684    #[test]
1685    fn a_constant_is_written_as_what_is_wanted_of_it() {
1686        let out = generate(ABSENT);
1687        assert!(out.contains("vec![Some(1), None]\n}"), "{out}");
1688        assert!(
1689            out.contains("vec![vec![Some(1), None], vec![Some(2)]]"),
1690            "a list with nothing absent in it is still a list of what may be: {out}"
1691        );
1692        assert!(out.contains("(Some(3), None, \"x\".to_string())"), "{out}");
1693        assert!(
1694            out.contains(
1695                "BTreeMap::from([(\"a\".to_string(), Some(1)), (\"b\".to_string(), None)])"
1696            ),
1697            "{out}"
1698        );
1699        assert!(
1700            out.contains("{ let g = vec![Some(1), None]; (g.len() as i64) }"),
1701            "with nothing asked of it, a constant is what it comes to: {out}"
1702        );
1703        assert_eq!(
1704            literal(&Value::List(vec![Value::Int(1), Value::Null])),
1705            "vec![1, None]",
1706            "untyped, there is nothing to say a `1` might not have been there"
1707        );
1708    }
1709
1710    #[test]
1711    fn a_reserved_word_is_escaped_and_still_travels_under_its_own_name() {
1712        let out = generate(
1713            r#"{"universes":[{"name":"demo","types":[
1714                {"k":"struct","name":"Thing","fields":[{"name":"type","ty":"str"}]}]}]}"#,
1715        );
1716        assert!(out.contains("pub r#type: String,"), "{out}");
1717        assert!(
1718            out.contains(r#"#[serde(rename = "type")]"#),
1719            "the escape must not change the wire: {out}"
1720        );
1721    }
1722
1723    #[test]
1724    fn where_precision_goes_is_written_next_to_nothing_because_rust_holds_it() {
1725        let out = generate(
1726            r#"{"universes":[{"name":"demo","types":[
1727                {"k":"struct","name":"Big","fields":[{"name":"n","ty":"i64"}]}]}]}"#,
1728        );
1729        assert!(out.contains("pub n: i64,"), "{out}");
1730        assert!(
1731            !out.contains("2^53"),
1732            "Rust holds it exactly, so there is nothing to warn about: {out}"
1733        );
1734    }
1735
1736    #[test]
1737    fn generating_twice_gives_the_same_bytes() {
1738        assert_eq!(generate(SHAPES), generate(SHAPES));
1739    }
1740
1741    #[test]
1742    fn values_become_literals_rust_would_accept() {
1743        assert_eq!(literal(&Value::Str("hi".into())), "\"hi\".to_string()");
1744        assert_eq!(literal(&Value::Float(2.0)), "2.0");
1745        assert_eq!(
1746            literal(&Value::List(vec![Value::Int(1), Value::Int(2)])),
1747            "vec![1, 2]"
1748        );
1749        assert_eq!(literal(&Value::Null), "None");
1750    }
1751
1752    #[test]
1753    fn generic_declarations_and_signatures_keep_their_parameters() {
1754        let rs = generate(crate::GENERIC);
1755        for expected in [
1756            "pub struct Box<T> {",
1757            "pub struct Labelled<T, N: Named> {",
1758            "pub trait Holder<T> {",
1759            "impl<T> Holder<T> for Tagged<T> {\n    fn held(&self) -> &T {",
1760            "pub enum Outcome<T, E> {",
1761            "pub type Swap<A, B> = (B, A);",
1762            "pub outcome: Outcome<i64, String>,",
1763            "pub fn pick<T: Named>(xs: Vec<T>) -> Option<T> {",
1764        ] {
1765            assert!(rs.contains(expected), "missing `{expected}` in:\n{rs}");
1766        }
1767    }
1768
1769    #[test]
1770    fn a_parameter_nothing_uses_is_left_out_wherever_it_would_appear() {
1771        let rs = generate(crate::GENERIC);
1772        assert!(rs.contains("pub struct Ghost {"), "{rs}");
1773        assert!(rs.contains("pub ghost: Ghost,"), "{rs}");
1774    }
1775
1776    #[test]
1777    fn a_body_asks_what_it_needs_of_a_generic_parameter() {
1778        let rs = generate(crate::GENERIC);
1779        assert!(
1780            rs.contains(
1781                "pub fn konst<A: Clone + PartialEq, B: Clone + PartialEq>(x: A, y: B) -> A {"
1782            ),
1783            "{rs}"
1784        );
1785    }
1786
1787    fn files_for(json: &str) -> Result<Vec<crate::GeneratedFile>, GenError> {
1788        let ws = check_workspace(Workspace::from_json(json).expect("reads")).expect("checks");
1789        Rust.generate(&ws, &GenOptions::default())
1790    }
1791
1792    const WITH_BYTES: &str = r#"{"universes":[{"name":"demo","types":[
1793        {"k":"struct","name":"Doc","fields":[
1794            {"name":"blob","ty":"bytes"},{"name":"blobs","ty":"[bytes]"},
1795            {"name":"by_number","ty":"map<i64, str>"}]}]}]}"#;
1796
1797    #[test]
1798    fn bytes_are_a_type_of_their_own_that_every_universe_shares() {
1799        let files = files_for(WITH_BYTES).expect("generates");
1800        let paths: Vec<String> = files
1801            .iter()
1802            .map(|f| f.path.to_string_lossy().into())
1803            .collect();
1804        assert_eq!(paths, ["rust/demo.rs", "rust/unitype_support.rs"]);
1805
1806        let demo = &files[0].contents;
1807        assert!(
1808            demo.contains("use super::unitype_support::Bytes;"),
1809            "{demo}"
1810        );
1811        assert!(demo.contains("pub blob: Bytes,"), "{demo}");
1812        assert!(demo.contains("pub blobs: Vec<Bytes>,"), "{demo}");
1813        assert!(
1814            demo.contains("pub by_number: BTreeMap<i64, String>,"),
1815            "{demo}"
1816        );
1817        assert!(files[1].contents.contains("pub struct Bytes(pub Vec<u8>);"));
1818    }
1819
1820    #[test]
1821    fn nothing_is_shared_when_nothing_is_bytes() {
1822        let files = files_for(
1823            r#"{"universes":[{"name":"demo","types":[
1824                {"k":"struct","name":"Shape","fields":[{"name":"id","ty":"str"}]}]}]}"#,
1825        )
1826        .expect("generates");
1827        assert_eq!(
1828            files.len(),
1829            1,
1830            "no support module for a universe that needs none"
1831        );
1832        assert!(!files[0].contents.contains("unitype_support"));
1833    }
1834
1835    #[test]
1836    fn a_universe_may_not_take_the_name_of_the_module_bytes_live_in() {
1837        let err = files_for(
1838            r#"{"universes":[{"name":"unitype_support","types":[
1839                {"k":"struct","name":"Doc","fields":[{"name":"blob","ty":"bytes"}]}]}]}"#,
1840        )
1841        .unwrap_err();
1842        assert!(err.to_string().contains("unitype_support"), "{err}");
1843    }
1844
1845    #[test]
1846    fn bytes_in_a_literal_are_written_as_bytes() {
1847        assert_eq!(
1848            literal(&Value::Bytes(vec![1, 2])),
1849            "Bytes(vec![1, 2])",
1850            "a bare vec would not be the type a field of bytes has"
1851        );
1852    }
1853}