Skip to main content

unitype_codegen/
python.rs

1//! Writing a universe out as Python.
2//!
3//! Structs become keyword-only dataclasses and inheritance becomes class
4//! inheritance, so a `Circle` really is a `Shape` to anything asking. Keyword-
5//! only is not a style choice: without it, a dataclass cannot have a field with
6//! a default before one without, and a parent with an optional field would stop
7//! a child from adding a required one. Making every field keyword-only removes
8//! the ordering constraint, so declaration order survives from the universe to
9//! the generated class.
10//!
11//! Enums are the one place this reaches for `TypedDict` instead. The wire tags
12//! a variant with `$tag`, which is not a name a dataclass field can have, and
13//! describing something other than what actually arrives would defeat the
14//! purpose.
15//!
16//! # Generics
17//!
18//! Anything generic is written with the type parameter syntax of PEP 695 —
19//! `class Box[T]:`, `def reverse[T](xs: list[T])`, `type Swap[A, B] = …` — so
20//! generated code that declares one needs Python 3.12. Everything else still
21//! reads on 3.10. The older way, a module-level `TypeVar`, cannot say which
22//! order an alias takes its parameters in: `Swap = tuple[B, A]` would take `B`
23//! first, because Python orders them by where they first appear. A bound is
24//! written as one, and several bounds are left out with a comment saying so,
25//! since Python has no way to say a type must be two things at once.
26//!
27//! A variant that carries a generic parameter is a class: a `TypedDict` made
28//! the functional way holds the `$tag`, and a generic class inheriting from it
29//! adds the payload, which is the only way a `TypedDict` with a `$tag` in it
30//! can be generic.
31
32use std::collections::{BTreeMap, BTreeSet};
33
34use unitype_core::check::CheckedWorkspace;
35use unitype_core::ir::{
36    AliasDef, EnumDef, Expr, Field, FunctionSig, Functor, InterfaceDef, PrimOp, StructDef, Type,
37    TypeDef, TypeParamDecl, Universe,
38};
39use unitype_core::lang::{LanguageProfile, profile};
40use unitype_core::value::Value;
41use unitype_core::{Ident, QualifiedName};
42
43use crate::writer::CodeWriter;
44use crate::{
45    Backend, GenError, GenOptions, GeneratedFile, bodies_use, header, ordered_defs, selected,
46};
47
48/// The Python backend.
49pub struct Python;
50
51impl Backend for Python {
52    fn id(&self) -> &'static str {
53        "python"
54    }
55
56    fn extension(&self) -> &'static str {
57        "py"
58    }
59
60    fn generate(
61        &self,
62        ws: &CheckedWorkspace,
63        options: &GenOptions,
64    ) -> Result<Vec<GeneratedFile>, GenError> {
65        let profile = profile("python")?;
66        crate::refuse_higher_order(ws, options, "python")?;
67        let mut files = Vec::new();
68
69        for universe in selected(ws, options) {
70            files.push(GeneratedFile {
71                path: format!("python/{}.py", universe.name).into(),
72                contents: universe_file(ws, universe, &profile, options),
73            });
74        }
75
76        if options.harness {
77            files.push(GeneratedFile {
78                path: "python/unitype_harness.py".into(),
79                contents: HARNESS.to_string(),
80            });
81        }
82        Ok(files)
83    }
84}
85
86fn universe_file(
87    ws: &CheckedWorkspace,
88    universe: &Universe,
89    profile: &LanguageProfile,
90    options: &GenOptions,
91) -> String {
92    let mut w = CodeWriter::new();
93
94    if options.header {
95        for line in header("#", universe, ws) {
96            w.line(line);
97        }
98        w.blank();
99    }
100    if let Some(doc) = &universe.doc {
101        w.line("\"\"\"");
102        w.comment("", doc);
103        w.line("\"\"\"");
104        w.blank();
105    }
106
107    // Postponed annotations, so a class may name one declared further down.
108    w.line("from __future__ import annotations");
109    w.blank();
110    if options.stubs && bodies_use(universe, |e| matches!(e, Expr::Fold { .. })) {
111        w.line("import functools");
112    }
113    w.line("import typing");
114    w.line("from dataclasses import dataclass, field");
115    for (from, names) in imports(universe) {
116        w.write(format_args!("from .{from} import {}", names.join(", ")));
117    }
118    w.blank();
119
120    for def in ordered_defs(universe) {
121        match def {
122            TypeDef::Struct(d) => emit_struct(&mut w, ws, d, profile),
123            TypeDef::Interface(d) => emit_interface(&mut w, ws, d, profile),
124            TypeDef::Enum(d) => emit_enum(&mut w, ws, d, profile),
125            TypeDef::Alias(d) => emit_alias(&mut w, ws, d, profile),
126        }
127        w.blank();
128    }
129
130    if options.stubs {
131        for sig in &universe.functions {
132            emit_signature(&mut w, ws, universe, sig, profile);
133            w.blank();
134        }
135    }
136
137    w.finish()
138}
139
140fn imports(universe: &Universe) -> Vec<(String, Vec<String>)> {
141    let mut found: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
142    let mut note = |ty: &Type| {
143        crate::refs_in(ty, &mut |r| {
144            if let Some(from) = &r.universe {
145                if from != &universe.name {
146                    found
147                        .entry(from.to_string())
148                        .or_default()
149                        .insert(r.name.to_string());
150                }
151            }
152        });
153    };
154    for def in &universe.types {
155        match def {
156            TypeDef::Struct(d) => d.fields.iter().for_each(|f| note(&f.ty)),
157            TypeDef::Interface(d) => d.fields.iter().for_each(|f| note(&f.ty)),
158            TypeDef::Enum(d) => d.variants.iter().for_each(|v| note(&v.payload)),
159            TypeDef::Alias(d) => note(&d.target),
160        }
161        for bound in def.params().iter().flat_map(|p| &p.bounds) {
162            note(&Type::Ref(bound.clone()));
163        }
164    }
165    for sig in &universe.functions {
166        sig.params.iter().for_each(|p| note(&p.ty));
167        note(&sig.ret);
168        for bound in sig.params_decl.iter().flat_map(|p| &p.bounds) {
169            note(&Type::Ref(bound.clone()));
170        }
171    }
172    found
173        .into_iter()
174        .map(|(from, names)| (from, names.into_iter().collect()))
175        .collect()
176}
177
178fn emit_struct(
179    w: &mut CodeWriter,
180    ws: &CheckedWorkspace,
181    def: &StructDef,
182    profile: &LanguageProfile,
183) {
184    let generics = type_params(w, &def.params, profile);
185    // Keyword-only, so a parent's optional field cannot stop a child adding a
186    // required one.
187    w.line("@dataclass(kw_only=True)");
188    let bases: Vec<String> = def
189        .extends
190        .iter()
191        .chain(&def.implements)
192        .map(|r| spell(ws, profile, &Type::Ref(r.clone())))
193        .collect();
194    let head = if bases.is_empty() {
195        format!("class {}{generics}:", profile.name(&def.name))
196    } else {
197        format!(
198            "class {}{generics}({}):",
199            profile.name(&def.name),
200            bases.join(", ")
201        )
202    };
203
204    w.block(head, "", |w| {
205        if let Some(doc) = &def.doc {
206            docstring(w, doc);
207        }
208        if def.fields.is_empty() {
209            if def.doc.is_none() {
210                w.line("pass");
211            }
212            return;
213        }
214        emit_fields(w, ws, &def.fields, profile);
215    });
216}
217
218fn emit_interface(
219    w: &mut CodeWriter,
220    ws: &CheckedWorkspace,
221    def: &InterfaceDef,
222    profile: &LanguageProfile,
223) {
224    // A field contract is a protocol: anything with these fields satisfies it,
225    // which is what the interface actually says.
226    let generics = type_params(w, &def.params, profile);
227    let mut bases: Vec<String> = def
228        .extends
229        .iter()
230        .map(|r| spell(ws, profile, &Type::Ref(r.clone())))
231        .collect();
232    if bases.is_empty() {
233        bases.push("typing.Protocol".to_string());
234    }
235    w.block(
236        format!(
237            "class {}{generics}({}):",
238            profile.name(&def.name),
239            bases.join(", ")
240        ),
241        "",
242        |w| {
243            if let Some(doc) = &def.doc {
244                docstring(w, doc);
245            }
246            if def.fields.is_empty() {
247                if def.doc.is_none() {
248                    w.line("pass");
249                }
250                return;
251            }
252            for field in &def.fields {
253                w.write(format_args!(
254                    "{}: {}",
255                    profile.name(&field.name),
256                    spell(ws, profile, &field.ty)
257                ));
258            }
259        },
260    );
261}
262
263fn emit_fields(
264    w: &mut CodeWriter,
265    ws: &CheckedWorkspace,
266    fields: &[Field],
267    profile: &LanguageProfile,
268) {
269    for f in fields {
270        if profile.name(&f.name) != f.name.as_str() {
271            w.comment(
272                "# ",
273                &format!(
274                    "`{}` is a reserved word here, so this is renamed. It still \
275                     travels under its own name.",
276                    f.name
277                ),
278            );
279        }
280        for caveat in profile.caveats(&f.ty) {
281            w.comment("# ", &caveat);
282        }
283        if let Some(doc) = &f.doc {
284            w.comment("# ", doc);
285        }
286
287        if has_integer_keys(ws, &f.ty) {
288            w.comment("# ", INTEGER_KEYS);
289        }
290        let spelled = spell(ws, profile, &f.ty);
291        // A field that may be absent defaults to absent, so a caller need not
292        // spell out what they do not have. That is anything that expands to
293        // `T?`, `null` or `any`, which is what a body may leave out.
294        let absent = matches!(
295            ws.expand_alias(&f.ty),
296            Type::Optional { .. } | Type::Unit | Type::Any
297        );
298        match &f.ty {
299            _ if absent => w.write(format_args!("{}: {spelled} = None", profile.name(&f.name))),
300            Type::List { .. } => w.write(format_args!(
301                "{}: {spelled} = field(default_factory=list)",
302                profile.name(&f.name)
303            )),
304            _ => w.write(format_args!("{}: {spelled}", profile.name(&f.name))),
305        }
306    }
307}
308
309fn emit_enum(w: &mut CodeWriter, ws: &CheckedWorkspace, def: &EnumDef, profile: &LanguageProfile) {
310    if let Some(doc) = &def.doc {
311        w.comment("# ", doc);
312    }
313    // `$tag` is not a name a class attribute can have, so the functional form
314    // of TypedDict is used. What it describes is exactly what arrives.
315    let name = profile.name(&def.name);
316    let mut variants = Vec::new();
317    for variant in &def.variants {
318        let variant_name = format!("{name}{}", variant.name);
319        let tag = format!("\"$tag\": typing.Literal[{:?}]", variant.name.as_str());
320        // The enum's generic parameters this variant's payload mentions, in
321        // the order the enum declares them.
322        let carried: Vec<TypeParamDecl> = def
323            .params
324            .iter()
325            .filter(|p| mentions(&variant.payload, &p.name))
326            .cloned()
327            .collect();
328        if carried.is_empty() {
329            let members = if matches!(variant.payload, Type::Unit) {
330                tag
331            } else {
332                format!("{tag}, \"value\": {}", spell(ws, profile, &variant.payload))
333            };
334            w.write(format_args!(
335                "{variant_name} = typing.TypedDict({variant_name:?}, {{{members}}})"
336            ));
337            variants.push(variant_name);
338            continue;
339        }
340        // Only a class can be generic, and a class cannot have a field called
341        // `$tag`, so the tag goes in a functional `TypedDict` the class
342        // inherits from.
343        let tagged = format!("_{variant_name}");
344        w.write(format_args!(
345            "{tagged} = typing.TypedDict({tagged:?}, {{{tag}}})"
346        ));
347        let generics = type_params(w, &carried, profile);
348        w.block(
349            format!("class {variant_name}{generics}({tagged}):"),
350            "",
351            |w| {
352                w.write(format_args!(
353                    "value: {}",
354                    spell(ws, profile, &variant.payload)
355                ));
356            },
357        );
358        let args: Vec<String> = carried.iter().map(|p| profile.name(&p.name)).collect();
359        variants.push(format!("{variant_name}[{}]", args.join(", ")));
360    }
361    if def.params.is_empty() {
362        w.write(format_args!("{name} = {}", variants.join(" | ")));
363    } else {
364        let generics = type_params(w, &def.params, profile);
365        w.write(format_args!(
366            "type {name}{generics} = {}",
367            variants.join(" | ")
368        ));
369    }
370}
371
372/// Whether a generic parameter appears anywhere in a type.
373fn mentions(ty: &Type, param: &Ident) -> bool {
374    matches!(ty, Type::Param { name } if name == param)
375        || ty.children().into_iter().any(|c| mentions(c, param))
376}
377
378/// Generic parameters in the syntax of PEP 695 — `[T, N: Named]` — or nothing
379/// when there are none.
380///
381/// Python has no way to say a type must be several things at once, so a
382/// parameter with more than one bound is left unbounded, and a comment says
383/// what it was meant to be.
384fn type_params(w: &mut CodeWriter, params: &[TypeParamDecl], profile: &LanguageProfile) -> String {
385    if params.is_empty() {
386        return String::new();
387    }
388    let spell = |b: &unitype_core::ir::TypeRef| profile.spell(&Type::Ref(b.clone()));
389    let parts: Vec<String> = params
390        .iter()
391        .map(|p| {
392            let name = profile.name(&p.name);
393            match p.bounds.as_slice() {
394                [] => name,
395                [only] => format!("{name}: {}", spell(only)),
396                several => {
397                    let all: Vec<String> = several.iter().map(spell).collect();
398                    w.comment(
399                        "# ",
400                        &format!(
401                            "`{name}` has to be each of {}, which Python has no way to say, \
402                             so it is left unbounded here.",
403                            all.join(", ")
404                        ),
405                    );
406                    name
407                }
408            }
409        })
410        .collect();
411    format!("[{}]", parts.join(", "))
412}
413
414fn emit_alias(
415    w: &mut CodeWriter,
416    ws: &CheckedWorkspace,
417    def: &AliasDef,
418    profile: &LanguageProfile,
419) {
420    if let Some(doc) = &def.doc {
421        w.comment("# ", doc);
422    }
423    let spelled = match &def.target {
424        Type::Union { members } => members
425            .iter()
426            .map(|m| spell(ws, profile, m))
427            .collect::<Vec<_>>()
428            .join(" | "),
429        other => spell(ws, profile, other),
430    };
431    // A generic alias says which order it takes its parameters in, which only
432    // a `type` statement can.
433    if def.params.is_empty() {
434        w.write(format_args!("{} = {spelled}", profile.name(&def.name)));
435    } else {
436        let generics = type_params(w, &def.params, profile);
437        w.write(format_args!(
438            "type {}{generics} = {spelled}",
439            profile.name(&def.name)
440        ));
441    }
442}
443
444fn emit_signature(
445    w: &mut CodeWriter,
446    ws: &CheckedWorkspace,
447    universe: &Universe,
448    sig: &FunctionSig,
449    profile: &LanguageProfile,
450) {
451    let params: Vec<String> = sig
452        .params
453        .iter()
454        .map(|p| format!("{}: {}", profile.name(&p.name), spell(ws, profile, &p.ty)))
455        .collect();
456    // A body that waits for something has to be a coroutine to be allowed to,
457    // and what it returns is then what the future held.
458    let awaits = sig.body.as_ref().is_some_and(|body| {
459        let mut found = false;
460        body.walk(&mut |e| {
461            found |= matches!(
462                e,
463                Expr::MapThrough {
464                    functor: Functor::Future,
465                    ..
466                }
467            )
468        });
469        found
470    });
471    let (keyword, ret) = match &sig.ret {
472        Type::Future { of } if awaits => ("async def", spell(ws, profile, of)),
473        other => ("def", spell(ws, profile, other)),
474    };
475    let generics = type_params(w, &sig.params_decl, profile);
476    let head = format!(
477        "{keyword} {}{generics}({}) -> {ret}:",
478        profile.name(&sig.name),
479        params.join(", "),
480    );
481    let qualified = QualifiedName::new(universe.name.clone(), sig.name.clone());
482
483    w.block(head, "", |w| {
484        if let Some(doc) = &sig.doc {
485            docstring(w, doc);
486        }
487        match &sig.body {
488            // A body is a proof already, so it is written out rather than left
489            // as a hole for someone to fill.
490            Some(body) => w.write(format_args!("return {}", expression(body, profile))),
491            None => {
492                w.comment(
493                    "# ",
494                    &format!("Implement this and register it as `{qualified}`."),
495                );
496                w.write(format_args!(
497                    "raise NotImplementedError({:?})",
498                    qualified.to_string()
499                ));
500            }
501        }
502    });
503}
504
505/// What a field holding an integer-keyed map says about its keys.
506const INTEGER_KEYS: &str = "Integer keys arrive as text, because a JSON object's property names \
507are text: {1: ...} is {\"1\": ...}.";
508
509/// How Python spells a type: as the profile does, except that the keys of a map
510/// that is keyed by integers are `str`.
511///
512/// A proof is handed what JSON gives it, and JSON has no object with an
513/// integer for a name, so `{1: "one"}` arrives as `{"1": "one"}`. `dict[int,
514/// str]` would be a type nothing ever has. The other direction already
515/// agrees: `json.dumps({1: "one"})` writes `{"1": "one"}`.
516fn spell(ws: &CheckedWorkspace, profile: &LanguageProfile, ty: &Type) -> String {
517    profile.spell(&textual_keys(ws, ty))
518}
519
520fn textual_keys(ws: &CheckedWorkspace, ty: &Type) -> Type {
521    let kids: Vec<Type> = ty
522        .children()
523        .into_iter()
524        .map(|c| textual_keys(ws, c))
525        .collect();
526    match ty.with_children(kids) {
527        Type::Map { key, value } if integer_keys(ws, &key) => Type::Map {
528            key: Box::new(Type::String),
529            value,
530        },
531        other => other,
532    }
533}
534
535/// Whether every key a type admits is an integer.
536fn integer_keys(ws: &CheckedWorkspace, key: &Type) -> bool {
537    match ws.expand_alias(key) {
538        Type::I32
539        | Type::I64
540        | Type::Literal {
541            value: unitype_core::ir::LiteralValue::Int(_),
542        } => true,
543        Type::Union { members } => {
544            !members.is_empty() && members.iter().all(|m| integer_keys(ws, m))
545        }
546        Type::Bounded { of, .. } => integer_keys(ws, &of),
547        _ => false,
548    }
549}
550
551/// Whether a map keyed by integers appears anywhere in a type.
552fn has_integer_keys(ws: &CheckedWorkspace, ty: &Type) -> bool {
553    matches!(ty, Type::Map { key, .. } if integer_keys(ws, key))
554        || ty.children().into_iter().any(|c| has_integer_keys(ws, c))
555}
556
557fn docstring(w: &mut CodeWriter, text: &str) {
558    let single = text.trim().replace('\n', " ");
559    if single.len() < 68 && !single.contains('"') {
560        w.write(format_args!("\"\"\"{single}\"\"\""));
561        return;
562    }
563    w.line("\"\"\"");
564    w.comment("", text);
565    w.line("\"\"\"");
566}
567
568/// Writes an expression body as Python.
569pub(crate) fn expression(expr: &Expr, profile: &LanguageProfile) -> String {
570    match expr {
571        Expr::Lit { value } => literal(value),
572        Expr::Var { name } => profile.name(name),
573        Expr::Field { of, name } => {
574            format!("{}.{}", expression(of, profile), profile.name(name))
575        }
576        Expr::MakeRecord { ty, fields } => {
577            let parts: Vec<String> = fields
578                .iter()
579                .map(|f| {
580                    format!(
581                        "{}={}",
582                        profile.name(&f.name),
583                        expression(&f.value, profile)
584                    )
585                })
586                .collect();
587            format!("{}({})", profile.name(&ty.name), parts.join(", "))
588        }
589        Expr::MakeList { items } => {
590            let parts: Vec<String> = items.iter().map(|i| expression(i, profile)).collect();
591            format!("[{}]", parts.join(", "))
592        }
593        Expr::MakeTuple { items } => {
594            let parts: Vec<String> = items.iter().map(|i| expression(i, profile)).collect();
595            // A one-element tuple needs the comma, or it is just brackets.
596            if parts.len() == 1 {
597                format!("({},)", parts[0])
598            } else {
599                format!("({})", parts.join(", "))
600            }
601        }
602        Expr::MakeVariant { tag, value, .. } => match value {
603            Some(v) => format!(
604                "{{\"$tag\": {:?}, \"value\": {}}}",
605                tag.as_str(),
606                expression(v, profile)
607            ),
608            None => format!("{{\"$tag\": {:?}}}", tag.as_str()),
609        },
610        Expr::Call { sig, args } => {
611            let parts: Vec<String> = args.iter().map(|a| expression(a, profile)).collect();
612            format!("{}({})", profile.name(&sig.name), parts.join(", "))
613        }
614        // Python has no expression-level binding other than this, and a body is
615        // one expression, so this is the honest translation.
616        Expr::Let { name, value, body } => format!(
617            "(lambda {}: {})({})",
618            profile.name(name),
619            expression(body, profile),
620            expression(value, profile)
621        ),
622        Expr::If {
623            cond,
624            then,
625            otherwise,
626        } => format!(
627            "({} if {} else {})",
628            expression(then, profile),
629            expression(cond, profile),
630            expression(otherwise, profile)
631        ),
632        Expr::MapThrough {
633            functor,
634            value,
635            var,
636            body,
637        } => {
638            let subject = expression(value, profile);
639            let bound = profile.name(var);
640            let inner = expression(body, profile);
641            match functor {
642                Functor::List => format!("[{inner} for {bound} in {subject}]"),
643                Functor::Optional => {
644                    format!("(lambda {bound}: None if {bound} is None else {inner})({subject})")
645                }
646                Functor::Future => {
647                    format!("(lambda {bound}: {inner})(await {subject})")
648                }
649            }
650        }
651        Expr::Prim { op, args } => {
652            let operands: Vec<String> = args.iter().map(|a| expression(a, profile)).collect();
653            match (op, operands.as_slice()) {
654                (PrimOp::Neg, [x]) => format!("(-{x})"),
655                (PrimOp::Not, [x]) => format!("(not {x})"),
656                (PrimOp::Len, [x]) => format!("len({x})"),
657                (op, [x, y]) => {
658                    let sign = match op {
659                        PrimOp::Eq => "==",
660                        PrimOp::Ne => "!=",
661                        PrimOp::Lt => "<",
662                        PrimOp::Le => "<=",
663                        PrimOp::Gt => ">",
664                        PrimOp::Ge => ">=",
665                        PrimOp::Add => "+",
666                        PrimOp::Sub => "-",
667                        PrimOp::Mul => "*",
668                        PrimOp::And => "and",
669                        _ => "or",
670                    };
671                    format!("({x} {sign} {y})")
672                }
673                _ => unreachable!("the checker holds every operation to its arity"),
674            }
675        }
676        Expr::Fold {
677            list,
678            init,
679            acc,
680            item,
681            body,
682            ..
683        } => format!(
684            "functools.reduce(lambda {}, {}: {}, {}, {})",
685            profile.name(acc),
686            profile.name(item),
687            expression(body, profile),
688            expression(list, profile),
689            expression(init, profile)
690        ),
691        // `_case` and `_match` are reserved in this profile, so a body that
692        // binds either name has it escaped rather than captured.
693        Expr::Case {
694            value,
695            var,
696            some,
697            none,
698        } => format!(
699            "(lambda _case: {} if _case is None else (lambda {}: {})(_case))({})",
700            expression(none, profile),
701            profile.name(var),
702            expression(some, profile),
703            expression(value, profile)
704        ),
705        Expr::Match { value, arms, .. } => {
706            let subject = expression(value, profile);
707            let Some((last, rest)) = arms.split_last() else {
708                return format!("(lambda _match: None)({subject})");
709            };
710            let arm = |a: &unitype_core::ir::MatchArm| {
711                let body = expression(&a.body, profile);
712                match &a.var {
713                    Some(var) => format!(
714                        "(lambda {}: {body})(_match.get(\"value\"))",
715                        profile.name(var)
716                    ),
717                    None => body,
718                }
719            };
720            // Every variant has an arm, so the last needs no test.
721            let mut chain = arm(last);
722            for a in rest.iter().rev() {
723                chain = format!(
724                    "({} if _match[\"$tag\"] == {:?} else {chain})",
725                    arm(a),
726                    a.tag.as_str()
727                );
728            }
729            format!("(lambda _match: {chain})({subject})")
730        }
731    }
732}
733
734/// Writes a value as a Python literal.
735pub fn literal(value: &Value) -> String {
736    match value {
737        Value::Null => "None".into(),
738        Value::Bool(b) => if *b { "True" } else { "False" }.into(),
739        Value::Int(i) => i.to_string(),
740        Value::Float(f) => {
741            let plain = f.to_string();
742            if plain.contains(['.', 'e', 'E']) {
743                plain
744            } else {
745                format!("{plain}.0")
746            }
747        }
748        Value::Str(s) => format!("{s:?}"),
749        // Base64 text, which is what a Python proof is handed and what it
750        // writes back (see the profile's note on `bytes`).
751        Value::Bytes(b) => {
752            use base64::Engine as _;
753            format!("{:?}", base64::engine::general_purpose::STANDARD.encode(b))
754        }
755        Value::List(items) => {
756            let parts: Vec<String> = items.iter().map(literal).collect();
757            format!("[{}]", parts.join(", "))
758        }
759        Value::Tuple(items) => {
760            let parts: Vec<String> = items.iter().map(literal).collect();
761            if parts.len() == 1 {
762                format!("({},)", parts[0])
763            } else {
764                format!("({})", parts.join(", "))
765            }
766        }
767        Value::Record(fields) => {
768            let parts: Vec<String> = fields
769                .iter()
770                .map(|(k, v)| format!("{k:?}: {}", literal(v)))
771                .collect();
772            format!("{{{}}}", parts.join(", "))
773        }
774        Value::Map(entries) => {
775            let parts: Vec<String> = entries
776                .iter()
777                .map(|(k, v)| {
778                    // A property name is text, whatever the key was.
779                    let name = match k {
780                        Value::Int(i) => format!("{:?}", i.to_string()),
781                        other => literal(other),
782                    };
783                    format!("{name}: {}", literal(v))
784                })
785                .collect();
786            format!("{{{}}}", parts.join(", "))
787        }
788        Value::Variant { tag, value } => match value.as_ref() {
789            Value::Null => format!("{{\"$tag\": {tag:?}}}"),
790            payload => format!("{{\"$tag\": {tag:?}, \"value\": {}}}", literal(payload)),
791        },
792    }
793}
794
795/// A name that does not collide with a generated class.
796#[allow(dead_code)]
797fn distinct(name: &Ident, taken: &BTreeSet<String>) -> String {
798    let mut candidate = name.to_string();
799    while taken.contains(&candidate) {
800        candidate.push('_');
801    }
802    candidate
803}
804
805/// The harness that makes a filled-in module reachable as a proof.
806const HARNESS: &str = r#"# Generated by unitype. Do not edit.
807"""Makes a Python module reachable as a proof, over standard input and output.
808
809This is the whole of what it takes to take part: read a message, do the work,
810write one back. One message per line, and reading lines serves both ways of
811being called — if the parent sends one message and closes the stream, this runs
812once and the process exits; if the parent keeps the stream open, it keeps
813answering. Nothing here has to know which is happening.
814
815Pass a table of what this module proves, keyed by the entry name a manifest
816points at:
817
818    from unitype_harness import unitype_main
819    from demo import sort
820
821    if __name__ == "__main__":
822        unitype_main({"bubble_sort": sort})
823"""
824
825import json
826import sys
827
828
829def unitype_main(proves):
830    for line in sys.stdin:
831        line = line.strip()
832        if line:
833            _answer(proves, line)
834
835
836def _answer(proves, line):
837    try:
838        request = json.loads(line)
839    except ValueError as exc:
840        return _fail("bad_request", f"could not read the request: {exc}")
841
842    if request.get("unitype") != "1":
843        return _fail(
844            "bad_version",
845            f"this module speaks version 1, not {request.get('unitype')!r}",
846        )
847    if request.get("kind") != "invoke":
848        return _fail("bad_kind", f"cannot do {request.get('kind')!r}")
849
850    entry = request.get("entry")
851    proof = proves.get(entry)
852    if proof is None:
853        known = ", ".join(sorted(proves)) or "nothing"
854        return _fail("no_such_entry", f"this module proves {known}, not {entry!r}")
855
856    try:
857        return _succeed(proof(*request.get("args", [])))
858    except Exception as exc:  # noqa: BLE001 — whatever it raises is its answer
859        return _fail(type(exc).__name__, str(exc))
860
861
862def _succeed(value):
863    _send({"ok": True, "value": value})
864
865
866def _fail(code, message):
867    # Reported as a failure of the proof, not of the process: exiting non-zero
868    # would say the environment is broken, which it is not.
869    _send({"ok": False, "error": {"code": code, "message": message}})
870
871
872def _send(response):
873    # One line, flushed: a parent waiting on the next line would otherwise wait
874    # on a buffer that never fills.
875    json.dump(response, sys.stdout)
876    sys.stdout.write("\n")
877    sys.stdout.flush()
878"#;
879
880#[cfg(test)]
881mod tests {
882    use super::*;
883    use unitype_core::Workspace;
884    use unitype_core::check::check_workspace;
885
886    fn generate(json: &str) -> String {
887        let ws = check_workspace(Workspace::from_json(json).expect("reads")).expect("checks");
888        Python
889            .generate(&ws, &GenOptions::default())
890            .expect("generates")
891            .into_iter()
892            .find(|f| f.path.to_string_lossy().ends_with("demo.py"))
893            .expect("a file for the demo universe")
894            .contents
895    }
896
897    const SHAPES: &str = r#"{"universes":[{"name":"demo","types":[
898        {"k":"interface","name":"Identified","fields":[{"name":"id","ty":"str"}]},
899        {"k":"struct","name":"Shape","implements":["Identified"],
900         "fields":[{"name":"id","ty":"str"}]},
901        {"k":"struct","name":"Circle","extends":"Shape","fields":[
902            {"name":"kind","ty":{"k":"literal","value":{"str":"circle"}}},
903            {"name":"radius","ty":"float"},
904            {"name":"note","ty":"str?"}]},
905        {"k":"enum","name":"Colour","variants":[{"name":"Red"},{"name":"Custom","payload":"str"}]},
906        {"k":"alias","name":"Either","target":{"k":"union","members":["Circle","Shape"]}}],
907      "functions":[
908        {"name":"area","params":[{"name":"s","ty":"Circle"}],"ret":"float"}]}]}"#;
909
910    #[test]
911    fn a_struct_becomes_a_keyword_only_dataclass() {
912        let out = generate(SHAPES);
913        assert!(out.contains("@dataclass(kw_only=True)"), "{out}");
914        assert!(out.contains("class Shape(Identified):"), "{out}");
915        assert!(out.contains("id: str"), "{out}");
916    }
917
918    #[test]
919    fn keyword_only_is_what_lets_a_child_add_a_required_field() {
920        // Circle inherits an optional-free parent but adds `note`, which has a
921        // default. Without kw_only, adding a required field in a later subclass
922        // would be impossible.
923        let out = generate(SHAPES);
924        assert!(out.contains("note: str | None = None"), "{out}");
925        assert!(
926            out.matches("@dataclass(kw_only=True)").count() >= 2,
927            "every dataclass needs it, not just the awkward one: {out}"
928        );
929    }
930
931    #[test]
932    fn a_parent_is_defined_before_the_child() {
933        let out = generate(SHAPES);
934        let shape = out.find("class Shape").expect("declared");
935        let circle = out.find("class Circle").expect("declared");
936        assert!(
937            shape < circle,
938            "Python cannot inherit from what is later: {out}"
939        );
940    }
941
942    #[test]
943    fn an_interface_becomes_a_protocol() {
944        let out = generate(SHAPES);
945        assert!(out.contains("class Identified(typing.Protocol):"), "{out}");
946    }
947
948    #[test]
949    fn a_discriminating_literal_keeps_its_value() {
950        let out = generate(SHAPES);
951        assert!(out.contains(r#"kind: typing.Literal["circle"]"#), "{out}");
952    }
953
954    #[test]
955    fn an_enum_is_described_as_what_actually_arrives() {
956        let out = generate(SHAPES);
957        assert!(
958            out.contains(r#""$tag": typing.Literal["Red"]"#),
959            "the wire tags it `$tag`, which no attribute could be called: {out}"
960        );
961        assert!(out.contains("Colour = ColourRed | ColourCustom"), "{out}");
962    }
963
964    #[test]
965    fn an_alias_an_any_and_a_null_default_to_absent_too() {
966        let out = generate(
967            r#"{"universes":[{"name":"demo","types":[
968                {"k":"alias","name":"Later","target":"i64?"},
969                {"k":"struct","name":"Entry","fields":[
970                    {"name":"at","ty":"i64"},{"name":"when","ty":"Later"},
971                    {"name":"extra","ty":"any"},{"name":"nothing","ty":"null"}]}],
972              "functions":[
973                {"name":"entry","params":[{"name":"x","ty":"i64"}],"ret":"Entry",
974                 "body":{"k":"make_record","ty":"Entry","fields":[
975                    {"name":"at","value":{"k":"var","name":"x"}}]}}]}]}"#,
976        );
977        assert!(out.contains("when: Later = None"), "{out}");
978        assert!(out.contains("extra: typing.Any = None"), "{out}");
979        assert!(out.contains("nothing: None = None"), "{out}");
980        assert!(
981            out.contains("return Entry(at=x)"),
982            "a body may leave all three out, so the class has to let it: {out}"
983        );
984        assert!(out.contains("    at: int\n"), "{out}");
985    }
986
987    #[test]
988    fn a_list_field_defaults_to_an_empty_list_rather_than_a_shared_one() {
989        let out = generate(
990            r#"{"universes":[{"name":"demo","types":[
991                {"k":"struct","name":"Bag","fields":[{"name":"items","ty":"[str]"}]}]}]}"#,
992        );
993        assert!(
994            out.contains("field(default_factory=list)"),
995            "a mutable default would be shared between instances: {out}"
996        );
997    }
998
999    #[test]
1000    fn a_proposition_with_no_proof_raises_rather_than_returning_nothing() {
1001        let out = generate(SHAPES);
1002        assert!(out.contains("def area(s: Circle) -> float:"), "{out}");
1003        assert!(out.contains("raise NotImplementedError"), "{out}");
1004    }
1005
1006    #[test]
1007    fn a_fold_brings_its_import_and_nothing_else_does() {
1008        let folding = generate(
1009            r#"{"universes":[{"name":"demo","functions":[
1010                {"name":"total","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64",
1011                 "body":{"k":"fold","list":{"k":"var","name":"xs"},"init":{"k":"lit","value":0},
1012                         "acc":"t","item":"x",
1013                         "body":{"k":"prim","op":"add","args":[{"k":"var","name":"t"},{"k":"var","name":"x"}]}}}]}]}"#,
1014        );
1015        assert!(folding.contains("import functools"), "{folding}");
1016        assert!(
1017            folding.contains("functools.reduce(lambda t, x: (t + x), xs, 0)"),
1018            "{folding}"
1019        );
1020        assert!(!generate(SHAPES).contains("functools"));
1021    }
1022
1023    #[test]
1024    fn a_body_that_waits_is_a_coroutine() {
1025        let out = generate(
1026            r#"{"universes":[{"name":"demo","functions":[
1027                {"name":"later","params":[{"name":"n","ty":{"k":"future","of":"i64"}}],
1028                 "ret":{"k":"future","of":"i64"},
1029                 "body":{"k":"map_through","functor":"future","value":{"k":"var","name":"n"},
1030                         "var":"x","body":{"k":"var","name":"x"}}}]}]}"#,
1031        );
1032        assert!(
1033            out.contains("async def later(n: typing.Awaitable[int]) -> int:"),
1034            "an `await` is only allowed inside `async def`: {out}"
1035        );
1036    }
1037
1038    #[test]
1039    fn a_name_the_generated_code_uses_for_itself_is_escaped_in_a_body() {
1040        let out = generate(
1041            r#"{"universes":[{"name":"demo","functions":[
1042                {"name":"f","params":[{"name":"_case","ty":"i64?"}],"ret":"i64",
1043                 "body":{"k":"case","value":{"k":"var","name":"_case"},"var":"it",
1044                         "some":{"k":"var","name":"it"},"none":{"k":"lit","value":0}}}]}]}"#,
1045        );
1046        assert!(
1047            out.contains("(lambda _case: 0 if _case is None else (lambda it: it)(_case))(_case_)"),
1048            "{out}"
1049        );
1050    }
1051
1052    #[test]
1053    fn a_body_is_written_out_as_python() {
1054        let out = generate(
1055            r#"{"universes":[{"name":"demo","types":[
1056                {"k":"struct","name":"User","fields":[{"name":"first","ty":"str"}]},
1057                {"k":"struct","name":"Badge","fields":[
1058                    {"name":"label","ty":"str"},{"name":"sides","ty":"i64"}]}],
1059              "functions":[
1060                {"name":"badge_of","params":[{"name":"u","ty":"User"}],"ret":"Badge",
1061                 "body":{"k":"make_record","ty":"Badge","fields":[
1062                    {"name":"label","value":{"k":"field","of":{"k":"var","name":"u"},"name":"first"}},
1063                    {"name":"sides","value":{"k":"lit","value":4}}]}}]}]}"#,
1064        );
1065        assert!(
1066            out.contains("return Badge(label=u.first, sides=4)"),
1067            "the same body that became TypeScript should become Python: {out}"
1068        );
1069    }
1070
1071    #[test]
1072    fn mapping_through_a_list_becomes_a_comprehension() {
1073        let out = generate(
1074            r#"{"universes":[{"name":"demo","types":[
1075                {"k":"struct","name":"User","fields":[{"name":"first","ty":"str"}]}],
1076              "functions":[
1077                {"name":"names","params":[{"name":"us","ty":"[User]"}],"ret":"[str]",
1078                 "body":{"k":"map_through","functor":"list","value":{"k":"var","name":"us"},
1079                         "var":"u","body":{"k":"field","of":{"k":"var","name":"u"},"name":"first"}}}]}]}"#,
1080        );
1081        assert!(out.contains("[u.first for u in us]"), "{out}");
1082    }
1083
1084    #[test]
1085    fn a_reserved_word_is_renamed_and_the_rename_is_explained() {
1086        let out = generate(
1087            r#"{"universes":[{"name":"demo","types":[
1088                {"k":"struct","name":"Thing","fields":[{"name":"class","ty":"str"}]}]}]}"#,
1089        );
1090        assert!(out.contains("class_: str"), "{out}");
1091        assert!(
1092            out.contains("reserved word"),
1093            "the rename changes what the reader sees, so it should be explained: {out}"
1094        );
1095    }
1096
1097    #[test]
1098    fn annotations_are_postponed_so_order_never_bites() {
1099        let out = generate(SHAPES);
1100        assert!(out.contains("from __future__ import annotations"), "{out}");
1101    }
1102
1103    #[test]
1104    fn generating_twice_gives_the_same_bytes() {
1105        assert_eq!(generate(SHAPES), generate(SHAPES));
1106    }
1107
1108    #[test]
1109    fn values_become_literals_python_would_accept() {
1110        assert_eq!(literal(&Value::Bool(true)), "True");
1111        assert_eq!(literal(&Value::Null), "None");
1112        assert_eq!(literal(&Value::Float(2.0)), "2.0");
1113        assert_eq!(
1114            literal(&Value::Tuple(vec![Value::Int(1)])),
1115            "(1,)",
1116            "without the comma it is just brackets"
1117        );
1118        assert_eq!(
1119            literal(&Value::record([("a", Value::Int(1))])),
1120            r#"{"a": 1}"#
1121        );
1122    }
1123
1124    #[test]
1125    fn generic_declarations_and_signatures_use_type_parameter_syntax() {
1126        let py = generate(crate::GENERIC);
1127        for expected in [
1128            "class Box[T]:",
1129            "class Labelled[T, N: Named](Box[T]):",
1130            "class Tagged[T](Holder[T]):",
1131            "class Holder[T](typing.Protocol):",
1132            "type Swap[A, B] = tuple[B, A]",
1133            "outcome: Outcome[int, str]",
1134            "def pick[T: Named](xs: list[T]) -> T | None:",
1135            "def konst[A, B](x: A, y: B) -> A:",
1136        ] {
1137            assert!(py.contains(expected), "missing `{expected}` in:\n{py}");
1138        }
1139    }
1140
1141    #[test]
1142    fn a_variant_that_carries_a_generic_parameter_is_a_class_on_top_of_its_tag() {
1143        let py = generate(crate::GENERIC);
1144        for expected in [
1145            "_OutcomeOk = typing.TypedDict(\"_OutcomeOk\", {\"$tag\": typing.Literal[\"Ok\"]})",
1146            "class OutcomeOk[T](_OutcomeOk):\n    value: T",
1147            "class OutcomeErr[E](_OutcomeErr):\n    value: E",
1148            "OutcomePending = typing.TypedDict(\"OutcomePending\", {\"$tag\": typing.Literal[\"Pending\"]})",
1149            "type Outcome[T, E] = OutcomeOk[T] | OutcomeErr[E] | OutcomePending",
1150        ] {
1151            assert!(py.contains(expected), "missing `{expected}` in:\n{py}");
1152        }
1153    }
1154
1155    #[test]
1156    fn several_bounds_are_left_out_and_said_to_be() {
1157        let py = generate(
1158            r#"{"universes":[{"name":"demo","types":[
1159                {"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
1160                {"k":"interface","name":"Sized","fields":[{"name":"size","ty":"i64"}]}],
1161              "functions":[{"name":"f","params_decl":[{"name":"T","bounds":["Named","Sized"]}],
1162                "params":[{"name":"x","ty":{"k":"param","name":"T"}}],"ret":"str"}]}]}"#,
1163        );
1164        assert!(py.contains("def f[T](x: T) -> str:"), "{py}");
1165        assert!(py.contains("`T` has to be each of Named, Sized"), "{py}");
1166    }
1167
1168    #[test]
1169    fn nothing_that_is_not_generic_needs_a_newer_python() {
1170        let py = generate(SHAPES);
1171        // A `type` statement, or type parameters before a class's bases or a
1172        // function's parameters.
1173        let newer = |line: &str| {
1174            line.starts_with("type ")
1175                || ["class ", "def "].iter().any(|kw| {
1176                    line.strip_prefix(kw).is_some_and(|rest| {
1177                        rest.split(['(', ':']).next().unwrap_or("").contains('[')
1178                    })
1179                })
1180        };
1181        assert!(!py.lines().any(newer), "{py}");
1182    }
1183
1184    #[test]
1185    fn what_a_proof_is_handed_is_what_the_annotations_say() {
1186        let py = generate(
1187            r#"{"universes":[{"name":"demo","types":[
1188                {"k":"struct","name":"Doc","fields":[
1189                    {"name":"blob","ty":"bytes"},
1190                    {"name":"by_number","ty":"map<i64, [bytes]>"},
1191                    {"name":"by_name","ty":"map<str, i64>"}]}]}]}"#,
1192        );
1193        // Base64 text for bytes, and text for the keys of a map that is
1194        // keyed by integers, because that is what JSON can hold.
1195        assert!(py.contains("blob: str"), "{py}");
1196        assert!(py.contains("by_number: dict[str, list[str]]"), "{py}");
1197        assert!(py.contains("by_name: dict[str, int]"), "{py}");
1198        assert_eq!(
1199            py.matches("Integer keys arrive as text").count(),
1200            1,
1201            "said once, beside the one field it is true of: {py}"
1202        );
1203    }
1204
1205    #[test]
1206    fn a_literal_bytes_value_is_the_text_it_travels_as() {
1207        assert_eq!(literal(&Value::Bytes(vec![1, 2, 3])), "\"AQID\"");
1208        assert_eq!(
1209            literal(&Value::Map(vec![(Value::Int(1), Value::Str("one".into()))])),
1210            "{\"1\": \"one\"}"
1211        );
1212    }
1213}