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