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