use std::path::{Path, PathBuf};
use std::process::Command;
use unitype_codegen::{Backend, GenOptions, haskell, python, rust, typescript};
use unitype_core::check::{CheckedWorkspace, check_workspace};
use unitype_core::ir::{Type, TypeRef};
use unitype_core::{Ident, Workspace};
const UNIVERSE: &str = r#"{"universes":[{"name":"demo",
"doc":"Shapes, and the things done to them.",
"types":[
{"k":"struct","name":"Shape",
"doc":"Anything with an outline. Said at enough length that the comment has to wrap onto a second line, and with a */ in it that must not end the comment early.",
"fields":[{"name":"id","ty":"str","doc":"What it is called."}]},
{"k":"struct","name":"Circle","extends":"Shape","fields":[
{"name":"kind","ty":{"k":"literal","value":{"str":"circle"}}},
{"name":"radius","ty":"float"},
{"name":"centre","ty":{"k":"tuple","items":["float","float"]}},
{"name":"tags","ty":"[str]"},
{"name":"note","ty":"str?"}]},
{"k":"alias","name":"Colour","doc":"The ones there are.","target":{"k":"union","members":[
{"k":"literal","value":{"str":"red"}},
{"k":"literal","value":{"str":"blue"}}]}},
{"k":"struct","name":"Label","fields":[
{"name":"text","ty":"str"},{"name":"sides","ty":"i64"}]},
{"k":"struct","name":"Step","fields":[
{"name":"ok","ty":"bool"},{"name":"prev","ty":"i64"},{"name":"started","ty":"bool"}]},
{"k":"struct","name":"Mark","fields":[
{"name":"at","ty":"i64"},{"name":"before","ty":"i64?"}]},
{"k":"struct","name":"Pin","extends":"Mark","fields":[{"name":"label","ty":"str?"}]},
{"k":"alias","name":"Later","target":"i64?"},
{"k":"struct","name":"Loose","fields":[
{"name":"at","ty":"i64"},{"name":"when","ty":"Later"},
{"name":"extra","ty":"any"},{"name":"nothing","ty":"null"}]},
{"k":"enum","name":"Size","variants":[{"name":"small"},{"name":"large","payload":"i64"}]}],
"functions":[
{"name":"label_of","doc":"Describes a circle.",
"params":[{"name":"c","ty":"Circle"}],"ret":"Label",
"body":{"k":"make_record","ty":"Label","fields":[
{"name":"text","value":{"k":"field","of":{"k":"var","name":"c"},"name":"id"}},
{"name":"sides","value":{"k":"lit","value":0}}]}},
{"name":"area","params":[{"name":"c","ty":"Circle"}],"ret":"float"},
{"name":"total","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64",
"body":{"k":"fold","list":{"k":"var","name":"xs"},"init":{"k":"lit","value":0},
"acc":"t","item":"x",
"body":{"k":"prim","op":"add","args":[{"k":"var","name":"t"},{"k":"var","name":"x"}]}}},
{"name":"ordered","params":[{"name":"xs","ty":"[i64]"}],"ret":"bool",
"body":{"k":"field","name":"ok","of":
{"k":"fold","list":{"k":"var","name":"xs"},
"init":{"k":"make_record","ty":"Step","fields":[
{"name":"ok","value":{"k":"lit","value":true}},
{"name":"prev","value":{"k":"lit","value":0}},
{"name":"started","value":{"k":"lit","value":false}}]},
"acc":"s","item":"x",
"body":{"k":"make_record","ty":"Step","fields":[
{"name":"ok","value":{"k":"prim","op":"and","args":[
{"k":"field","of":{"k":"var","name":"s"},"name":"ok"},
{"k":"prim","op":"or","args":[
{"k":"prim","op":"not","args":[{"k":"field","of":{"k":"var","name":"s"},"name":"started"}]},
{"k":"prim","op":"le","args":[{"k":"field","of":{"k":"var","name":"s"},"name":"prev"},
{"k":"var","name":"x"}]}]}]}},
{"name":"prev","value":{"k":"var","name":"x"}},
{"name":"started","value":{"k":"lit","value":true}}]}}}},
{"name":"note_or","params":[{"name":"c","ty":"Circle"}],"ret":"str",
"body":{"k":"case","value":{"k":"field","of":{"k":"var","name":"c"},"name":"note"},"var":"it",
"some":{"k":"var","name":"it"},"none":{"k":"lit","value":"none"}}},
{"name":"measure","params":[{"name":"s","ty":"Size"}],"ret":"i64",
"body":{"k":"match","ty":"Size","value":{"k":"var","name":"s"},"arms":[
{"tag":"small","body":{"k":"lit","value":0}},
{"tag":"large","var":"n","body":{"k":"prim","op":"mul","args":[
{"k":"var","name":"n"},{"k":"lit","value":2}]}}]}},
{"name":"two_tags","params":[{"name":"c","ty":"Circle"}],"ret":"bool",
"body":{"k":"prim","op":"and","args":[
{"k":"prim","op":"eq","args":[
{"k":"prim","op":"len","args":[{"k":"field","of":{"k":"var","name":"c"},"name":"tags"}]},
{"k":"lit","value":2}]},
{"k":"prim","op":"ne","args":[
{"k":"field","of":{"k":"var","name":"c"},"name":"id"},{"k":"lit","value":"x"}]}]}},
{"name":"mark","params":[{"name":"x","ty":"i64"}],"ret":"Mark",
"body":{"k":"make_record","ty":"Mark","fields":[
{"name":"at","value":{"k":"var","name":"x"}},
{"name":"before","value":{"k":"var","name":"x"}}]}},
{"name":"last_of","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64?",
"body":{"k":"fold","list":{"k":"var","name":"xs"},"init":{"k":"lit","value":null},
"ty":"int?","acc":"p","item":"x","body":{"k":"var","name":"x"}}},
{"name":"radius_of","params":[{"name":"c","ty":"Circle"}],"ret":"float?",
"body":{"k":"field","of":{"k":"var","name":"c"},"name":"radius"}},
{"name":"positive","params":[{"name":"x","ty":"i64"}],"ret":"i64?",
"body":{"k":"if","cond":{"k":"prim","op":"gt","args":[{"k":"var","name":"x"},{"k":"lit","value":0}]},
"then":{"k":"var","name":"x"},"else":{"k":"lit","value":null}}},
{"name":"note_or_else","params":[{"name":"c","ty":"Circle"},{"name":"fallback","ty":"str?"}],
"ret":"str?",
"body":{"k":"case","value":{"k":"field","of":{"k":"var","name":"c"},"name":"note"},"var":"n",
"some":{"k":"var","name":"n"},"none":{"k":"var","name":"fallback"}}},
{"name":"hint","params":[{"name":"s","ty":"Size"}],"ret":"i64?",
"body":{"k":"match","ty":"Size","value":{"k":"var","name":"s"},"arms":[
{"tag":"small","body":{"k":"lit","value":null}},
{"tag":"large","var":"n","body":{"k":"var","name":"n"}}]}},
{"name":"noted_as","params":[{"name":"c","ty":"Circle"},{"name":"s","ty":"str"}],"ret":"bool",
"body":{"k":"prim","op":"eq","args":[
{"k":"field","of":{"k":"var","name":"c"},"name":"note"},{"k":"var","name":"s"}]}},
{"name":"with_gap","params":[{"name":"x","ty":"i64"}],"ret":"[i64?]",
"body":{"k":"make_list","items":[{"k":"var","name":"x"},{"k":"lit","value":null}]}},
{"name":"pin_at","params":[{"name":"x","ty":"i64"}],"ret":"Pin",
"body":{"k":"make_record","ty":"Pin","fields":[{"name":"at","value":{"k":"var","name":"x"}}]}},
{"name":"loose_at","params":[{"name":"x","ty":"i64"}],"ret":"Loose",
"body":{"k":"make_record","ty":"Loose","fields":[{"name":"at","value":{"k":"var","name":"x"}}]}},
{"name":"gaps","params":[],"ret":"[[i64?]]","body":{"k":"lit","value":[[1,null],[2]]}},
{"name":"pair","params":[],"ret":{"k":"tuple","items":["i64?","i64?","str"]},
"body":{"k":"lit","value":{"$tuple":[3,null,"x"]}}},
{"name":"bound_pair","params":[{"name":"x","ty":"i64"}],"ret":{"k":"tuple","items":["i64","str"]},
"body":{"k":"let","name":"p",
"value":{"k":"make_tuple","items":[{"k":"var","name":"x"},{"k":"lit","value":"x"}]},
"body":{"k":"var","name":"p"}}},
{"name":"settled","params":[{"name":"xs","ty":"[i64]"}],"ret":"i64",
"body":{"k":"let","name":"s",
"value":{"k":"fold","list":{"k":"var","name":"xs"},
"init":{"k":"if","cond":{"k":"prim","op":"gt","args":[
{"k":"prim","op":"len","args":[{"k":"var","name":"xs"}]},{"k":"lit","value":2}]},
"then":{"k":"make_variant","ty":"Size","tag":"small"},
"else":{"k":"make_variant","ty":"Size","tag":"large","value":{"k":"lit","value":1}}},
"acc":"a","item":"x","body":{"k":"var","name":"a"}},
"body":{"k":"call","sig":"demo::measure","args":[{"k":"var","name":"s"}]}}}]}]}"#;
const LABEL: &str = r#"{"text":"c-1","sides":0}"#;
const FORMS: &str = r#"{"total":10,"ordered":true,"unordered":false,"note":"none",
"small":0,"large":42,"two_tags":true,
"mark":{"at":5,"before":5},"last":3,"last_empty":null,"radius":2.5,
"positive":3,"not_positive":null,"fallback":"x","no_fallback":null,"noted":"hi",
"small_hint":null,"large_hint":21,"noted_as":true,"not_noted_as":false,
"with_gap":[5,null],"pin":{"at":5},"loose":{"at":5},"gaps":[[1,null],[2]],
"pair":[3,null,"x"],"bound_pair":[5,"x"],"settled_small":0,"settled_large":2}"#;
fn workspace() -> CheckedWorkspace {
check_workspace(Workspace::from_json(UNIVERSE).expect("reads")).expect("checks")
}
fn circle_type() -> Type {
Type::Ref(TypeRef::qualified(
Ident::new("demo").unwrap(),
Ident::new("Circle").unwrap(),
))
}
fn loose_json() -> String {
let ws = workspace();
let loose = Type::Ref(TypeRef::qualified(
Ident::new("demo").unwrap(),
Ident::new("Loose").unwrap(),
));
let value = ws
.read_json(
r#"{"at":5,"when":null,"extra":null,"nothing":null}"#,
&loose,
)
.expect("a real Loose");
ws.write_json(&value, &loose).expect("writes")
}
fn expected_json() -> String {
let ws = workspace();
let circle = ws
.read_json(
r#"{"id":"c-1","kind":"circle","radius":2.5,"centre":[1.5,-0.5],
"tags":["round","blue"],"note":null}"#,
&circle_type(),
)
.expect("a real Circle");
ws.write_json(&circle, &circle_type()).expect("writes")
}
fn normalize(json: &str) -> String {
let parsed: serde_json::Value = serde_json::from_str(json).expect("valid JSON");
fn sort(value: &serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::Object(map) => {
let mut sorted = serde_json::Map::new();
let mut keys: Vec<&String> = map.keys().collect();
keys.sort();
for key in keys {
sorted.insert(key.clone(), sort(&map[key]));
}
serde_json::Value::Object(sorted)
}
serde_json::Value::Array(items) => {
serde_json::Value::Array(items.iter().map(sort).collect())
}
other => other.clone(),
}
}
serde_json::to_string(&sort(&parsed)).expect("re-encodes")
}
fn emit(backend: &dyn Backend, into: &Path) -> PathBuf {
emit_from(&workspace(), backend, into)
}
fn emit_from(ws: &CheckedWorkspace, backend: &dyn Backend, into: &Path) -> PathBuf {
let files = backend
.generate(ws, &GenOptions::default())
.expect("generates");
let root = into.join(backend.id());
for file in files {
let path = root.join(file.path.file_name().expect("a file name"));
std::fs::create_dir_all(path.parent().expect("a parent")).expect("makes the directory");
std::fs::write(&path, file.contents).expect("writes the file");
}
root
}
fn scratch(name: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name);
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("makes a scratch directory");
dir
}
fn have(program: &str) -> bool {
Command::new(program)
.arg("--version")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|s| s.success())
}
fn run(program: &str, args: &[&str], in_dir: &Path) -> String {
let output = Command::new(program)
.args(args)
.current_dir(in_dir)
.output()
.unwrap_or_else(|e| panic!("could not run {program}: {e}"));
assert!(
output.status.success(),
"{program} failed:\n{}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout).expect("output is text")
}
#[test]
fn the_generated_python_produces_the_shape_it_promised() {
if !have("python3") {
eprintln!("no python3 on this machine; skipping");
return;
}
let dir = scratch("python_wire");
let root = emit(&python::Python, &dir);
std::fs::write(
root.join("check.py"),
r#"import dataclasses, json
from demo import Circle
circle = Circle(id="c-1", kind="circle", radius=2.5, centre=(1.5, -0.5), tags=["round", "blue"])
shape = dataclasses.asdict(circle)
# Absent and null are one state, so a field with nothing in it is not sent.
shape = {k: v for k, v in shape.items() if v is not None}
print(json.dumps(shape))
"#,
)
.expect("writes the driver");
let produced = run("python3", &["check.py"], &root);
assert_eq!(
normalize(&produced),
normalize(&expected_json()),
"the generated dataclass produced a different shape than unitype says \
the value has"
);
}
fn node_reads_typescript() -> bool {
let Ok(output) = Command::new("node").arg("--version").output() else {
return false;
};
String::from_utf8_lossy(&output.stdout)
.trim()
.trim_start_matches('v')
.split('.')
.next()
.and_then(|major| major.parse::<u32>().ok())
.is_some_and(|major| major >= 24)
}
#[test]
fn the_generated_typescript_loads_and_produces_the_shape_it_promised() {
if !node_reads_typescript() {
eprintln!("no node that reads TypeScript on this machine; skipping");
return;
}
let dir = scratch("typescript_wire");
let root = emit(&typescript::TypeScript, &dir);
std::fs::write(root.join("package.json"), "{\"type\": \"module\"}\n").expect("writes");
std::fs::write(
root.join("check.mjs"),
r#"import {
bound_pair, gaps, hint, label_of, last_of, loose_at, mark, measure, note_or, note_or_else,
noted_as, ordered, pair, pin_at, positive, radius_of, settled, total, two_tags, with_gap,
} from "./demo.ts";
// Written against the generated `Circle` interface: every field it requires,
// and nothing for the one that may be absent.
const circle = {
id: "c-1",
kind: "circle",
radius: 2.5,
centre: [1.5, -0.5],
tags: ["round", "blue"],
};
const noted = { ...circle, note: "hi" };
const forms = {
total: total([1, 2, 3, 4]),
ordered: ordered([1, 2, 2, 5]),
unordered: ordered([3, 1]),
note: note_or(circle),
small: measure({ $tag: "small" }),
large: measure({ $tag: "large", value: 21 }),
two_tags: two_tags(circle),
mark: mark(5),
last: last_of([1, 2, 3]),
last_empty: last_of([]),
radius: radius_of(circle),
positive: positive(3),
not_positive: positive(-1),
fallback: note_or_else(circle, "x"),
no_fallback: note_or_else(circle, null),
noted: note_or_else(noted, null),
small_hint: hint({ $tag: "small" }),
large_hint: hint({ $tag: "large", value: 21 }),
noted_as: noted_as(noted, "hi"),
not_noted_as: noted_as(circle, "hi"),
with_gap: with_gap(5),
pin: pin_at(5),
loose: loose_at(5),
gaps: gaps(),
pair: pair(),
bound_pair: bound_pair(5),
settled_small: settled([1, 2, 3]),
settled_large: settled([4]),
};
process.stdout.write(JSON.stringify({ circle, label: label_of(circle), forms }));
"#,
)
.expect("writes the driver");
let produced: serde_json::Value =
serde_json::from_str(&run("node", &["check.mjs"], &root)).expect("valid JSON");
assert_eq!(
normalize(&produced["circle"].to_string()),
normalize(&expected_json()),
"what a value written against the generated interface serializes to \
differs from what unitype says it is"
);
assert_eq!(
normalize(&produced["label"].to_string()),
normalize(LABEL),
"the body, as TypeScript, answered differently"
);
assert_eq!(
normalize(&produced["forms"].to_string()),
normalize(FORMS),
"the bodies, as TypeScript, answered differently"
);
}
#[test]
fn the_generated_python_runs_the_body_it_was_given() {
if !have("python3") {
return;
}
let dir = scratch("python_body");
let root = emit(&python::Python, &dir);
std::fs::write(
root.join("check.py"),
r#"import dataclasses, json
from demo import (
Circle, bound_pair, gaps, hint, label_of, last_of, loose_at, mark, measure, note_or,
note_or_else, noted_as, ordered, pair, pin_at, positive, radius_of, settled, total, two_tags,
with_gap,
)
def sent(record):
# Absent and null are one state, so a field with nothing in it is not sent.
return {k: v for k, v in dataclasses.asdict(record).items() if v is not None}
circle = Circle(id="c-1", kind="circle", radius=2.5, centre=(1.5, -0.5), tags=["round", "blue"])
noted = dataclasses.replace(circle, note="hi")
forms = {
"total": total([1, 2, 3, 4]),
"ordered": ordered([1, 2, 2, 5]),
"unordered": ordered([3, 1]),
"note": note_or(circle),
"small": measure({"$tag": "small"}),
"large": measure({"$tag": "large", "value": 21}),
"two_tags": two_tags(circle),
"mark": dataclasses.asdict(mark(5)),
"last": last_of([1, 2, 3]),
"last_empty": last_of([]),
"radius": radius_of(circle),
"positive": positive(3),
"not_positive": positive(-1),
"fallback": note_or_else(circle, "x"),
"no_fallback": note_or_else(circle, None),
"noted": note_or_else(noted, None),
"small_hint": hint({"$tag": "small"}),
"large_hint": hint({"$tag": "large", "value": 21}),
"noted_as": noted_as(noted, "hi"),
"not_noted_as": noted_as(circle, "hi"),
"with_gap": with_gap(5),
"pin": sent(pin_at(5)),
"loose": sent(loose_at(5)),
"gaps": gaps(),
"pair": pair(),
"bound_pair": bound_pair(5),
"settled_small": settled([1, 2, 3]),
"settled_large": settled([4]),
}
print(json.dumps({"label": dataclasses.asdict(label_of(circle)), "forms": forms}))
"#,
)
.expect("writes the driver");
let produced: serde_json::Value =
serde_json::from_str(&run("python3", &["check.py"], &root)).expect("valid JSON");
assert_eq!(
normalize(&produced["label"].to_string()),
normalize(LABEL),
"the body, as Python, answered differently"
);
assert_eq!(
normalize(&produced["forms"].to_string()),
normalize(FORMS),
"the bodies, as Python, answered differently"
);
}
#[test]
fn the_generated_rust_compiles_and_produces_the_shape_it_promised() {
let dir = scratch("rust_wire");
let root = emit(&rust::Rust, &dir);
std::fs::create_dir_all(dir.join("src")).expect("makes src");
std::fs::rename(root.join("demo.rs"), dir.join("src/demo.rs")).expect("moves the module");
std::fs::write(
dir.join("Cargo.toml"),
r#"[package]
name = "wire-check"
version = "0.0.0"
edition = "2024"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[workspace]
"#,
)
.expect("writes the manifest");
std::fs::write(
dir.join("src/main.rs"),
r#"#[allow(dead_code, unused_variables)]
mod demo;
fn main() {
// Read the way it arrives, written the way it leaves: what comes out is
// whatever the generated struct believes the shape to be.
let arrived = std::env::args().nth(1).expect("a circle");
let circle: demo::Circle = serde_json::from_str(&arrived).expect("reads as a Circle");
let label = demo::label_of(circle.clone());
let noted = demo::Circle {
note: Some("hi".to_string()),
..circle.clone()
};
let arrived = std::env::args().nth(2).expect("a loose record");
let loose: demo::Loose = serde_json::from_str(&arrived).expect("reads as a Loose");
let red: demo::Colour = serde_json::from_str("\"red\"").expect("red is one of them");
let green = serde_json::from_str::<demo::Colour>("\"green\"").is_ok();
let forms = serde_json::json!({
"total": demo::total(vec![1, 2, 3, 4]),
"ordered": demo::ordered(vec![1, 2, 2, 5]),
"unordered": demo::ordered(vec![3, 1]),
"note": demo::note_or(circle.clone()),
"small": demo::measure(demo::Size::small),
"large": demo::measure(demo::Size::large(21)),
"two_tags": demo::two_tags(circle.clone()),
"mark": demo::mark(5),
"last": demo::last_of(vec![1, 2, 3]),
"last_empty": demo::last_of(vec![]),
"radius": demo::radius_of(circle.clone()),
"positive": demo::positive(3),
"not_positive": demo::positive(-1),
"fallback": demo::note_or_else(circle.clone(), Some("x".to_string())),
"no_fallback": demo::note_or_else(circle.clone(), None),
"noted": demo::note_or_else(noted.clone(), None),
"small_hint": demo::hint(demo::Size::small),
"large_hint": demo::hint(demo::Size::large(21)),
"noted_as": demo::noted_as(noted.clone(), "hi".to_string()),
"not_noted_as": demo::noted_as(circle.clone(), "hi".to_string()),
"with_gap": demo::with_gap(5),
"pin": demo::pin_at(5),
"loose": demo::loose_at(5),
"gaps": demo::gaps(),
"pair": demo::pair(),
"bound_pair": demo::bound_pair(5),
"settled_small": demo::settled(vec![1, 2, 3]),
"settled_large": demo::settled(vec![4]),
});
println!(
"{}",
serde_json::json!({
"circle": circle, "loose": loose, "label": label, "red": red, "green": green,
"forms": forms,
})
);
}
"#,
)
.expect("writes the driver");
let target = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("rust_wire_target");
let cargo = |args: &[&str]| {
Command::new(env!("CARGO"))
.args(args)
.env("CARGO_TARGET_DIR", &target)
.current_dir(&dir)
.output()
.expect("runs cargo")
};
let built = cargo(&["build", "--quiet", "--offline"]);
let said = String::from_utf8_lossy(&built.stderr);
if !built.status.success() && !said.contains("error[") && !said.contains("could not compile") {
eprintln!("serde is not available offline; skipping\n{said}");
return;
}
assert!(
built.status.success(),
"the generated Rust did not build:\n{said}"
);
let output = cargo(&[
"run",
"--quiet",
"--offline",
"--",
&expected_json(),
&loose_json(),
]);
assert!(
output.status.success(),
"the generated Rust failed when it ran:\n{}",
String::from_utf8_lossy(&output.stderr)
);
let produced: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
assert_eq!(
normalize(&produced["circle"].to_string()),
normalize(&expected_json()),
"the generated struct read and wrote a different shape than unitype \
says the value has"
);
assert_eq!(
normalize(&produced["loose"].to_string()),
normalize(&loose_json()),
"fields that may be absent have to read when they are not there, and \
be left out again when they are written"
);
assert_eq!(
normalize(&produced["label"].to_string()),
normalize(LABEL),
"the body, as Rust, answered differently"
);
assert_eq!(
normalize(&produced["forms"].to_string()),
normalize(FORMS),
"the bodies, as Rust, answered differently"
);
assert_eq!(produced["red"], "red", "a name travels as the string it is");
assert_eq!(
produced["green"], false,
"a string the union does not admit should be refused"
);
}
#[test]
fn every_backend_names_the_same_fields() {
let ws = workspace();
let wanted: Vec<String> = ws
.flat_fields(&"demo::Circle".parse().unwrap())
.expect("declared")
.iter()
.map(|f| f.name.to_string())
.collect();
for backend in [
Box::new(typescript::TypeScript) as Box<dyn Backend>,
Box::new(python::Python),
Box::new(rust::Rust),
Box::new(haskell::Haskell),
] {
let files = backend
.generate(&ws, &GenOptions::default())
.expect("generates");
let source: String = files
.iter()
.filter(|f| !f.path.to_string_lossy().contains("harness"))
.map(|f| f.contents.clone())
.collect();
for field in &wanted {
assert!(
source.contains(field.as_str()),
"{} never mentions `{field}`",
backend.id()
);
}
}
}
#[test]
fn what_the_generated_python_accepts_is_what_unitype_would_accept() {
if !have("python3") {
return;
}
let dir = scratch("python_reject");
let root = emit(&python::Python, &dir);
std::fs::write(
root.join("check.py"),
r#"from demo import Circle
# `radius` is required, so leaving it out has to fail. If the generated class
# accepted it, the class would be describing something looser than the type.
try:
Circle(id="c-1", kind="circle", tags=[])
print("accepted")
except TypeError:
print("refused")
"#,
)
.expect("writes the driver");
assert_eq!(
run("python3", &["check.py"], &root).trim(),
"refused",
"a required field left out should be refused, as unitype would refuse it"
);
let ws = workspace();
assert!(
ws.read_json(r#"{"id":"c-1","kind":"circle","tags":[]}"#, &circle_type())
.is_err(),
"and unitype does refuse it"
);
}
const GENERIC_UNIVERSE: &str = r#"{"universes":[{"name":"generic","types":[
{"k":"interface","name":"Named","fields":[{"name":"name","ty":"str"}]},
{"k":"struct","name":"Person","implements":["Named"],"fields":[{"name":"name","ty":"str"}]},
{"k":"struct","name":"Box","params":[{"name":"T"}],
"fields":[{"name":"value","ty":{"k":"param","name":"T"}}]},
{"k":"struct","name":"Labelled","params":[{"name":"T"},{"name":"N","bounds":["Named"]}],
"extends":{"name":"Box","args":[{"k":"param","name":"T"}]},
"fields":[{"name":"label","ty":{"k":"param","name":"N"}}]},
{"k":"enum","name":"Outcome","params":[{"name":"T"},{"name":"E"}],"variants":[
{"name":"Ok","payload":{"k":"param","name":"T"}},
{"name":"Err","payload":{"k":"param","name":"E"}},
{"name":"Pending"}]},
{"k":"alias","name":"Flip","params":[{"name":"A"},{"name":"B"}],
"target":{"k":"ref","name":"Outcome","args":[{"k":"param","name":"B"},{"k":"param","name":"A"}]}},
{"k":"alias","name":"Swap","params":[{"name":"A"},{"name":"B"}],
"target":{"k":"tuple","items":[{"k":"param","name":"B"},{"k":"param","name":"A"}]}},
{"k":"struct","name":"Ghost","params":[{"name":"T"}],"fields":[{"name":"id","ty":"str"}]},
{"k":"struct","name":"Uses","fields":[
{"name":"boxed","ty":{"k":"ref","name":"Box","args":["[i64]"]}},
{"name":"labelled","ty":{"k":"ref","name":"Labelled","args":["str","Person"]}},
{"name":"outcome","ty":{"k":"ref","name":"Outcome","args":["i64","str"]}},
{"name":"pending","ty":{"k":"ref","name":"Outcome","args":["i64","str"]}},
{"name":"flipped","ty":{"k":"ref","name":"Flip","args":["i64","str"]}},
{"name":"swapped","ty":{"k":"ref","name":"Swap","args":["i64","str"]}},
{"name":"ghost","ty":{"k":"ref","name":"Ghost","args":["bool"]}}]}],
"functions":[
{"name":"konst","params_decl":[{"name":"A"},{"name":"B"}],
"params":[{"name":"x","ty":{"k":"param","name":"A"}},{"name":"y","ty":{"k":"param","name":"B"}}],
"ret":{"k":"param","name":"A"},"body":{"k":"var","name":"x"}},
{"name":"unbox","params_decl":[{"name":"T"}],
"params":[{"name":"b","ty":{"k":"ref","name":"Box","args":[{"k":"param","name":"T"}]}}],
"ret":{"k":"param","name":"T"},
"body":{"k":"field","of":{"k":"var","name":"b"},"name":"value"}}]}]}"#;
const USES: &str = r#"{"boxed":{"value":[1,2]},"labelled":{"value":"x","label":{"name":"n"}},
"outcome":{"$tag":"Err","value":"bad"},"pending":{"$tag":"Pending"},
"flipped":{"$tag":"Ok","value":"a"},"swapped":["a",1],"ghost":{"id":"g"}}"#;
const GENERIC_ANSWERS: &str = r#"{"konst":3,"unbox":[4]}"#;
fn generic_workspace() -> CheckedWorkspace {
check_workspace(Workspace::from_json(GENERIC_UNIVERSE).expect("reads")).expect("checks")
}
fn uses_json() -> String {
let ws = generic_workspace();
let uses = Type::Ref(TypeRef::qualified(
Ident::new("generic").unwrap(),
Ident::new("Uses").unwrap(),
));
let value = ws.read_json(USES, &uses).expect("a real Uses");
ws.write_json(&value, &uses).expect("writes")
}
fn agrees(language: &str, produced: &str) {
let produced: serde_json::Value = serde_json::from_str(produced).expect("valid JSON");
assert_eq!(
normalize(&produced["uses"].to_string()),
normalize(&uses_json()),
"a value built from the generated {language} generics has a different shape than \
unitype says it does"
);
let answers = serde_json::json!({"konst": produced["konst"], "unbox": produced["unbox"]});
assert_eq!(
normalize(&answers.to_string()),
normalize(GENERIC_ANSWERS),
"the generic bodies, as {language}, answered differently"
);
}
fn python_reads_type_parameters() -> bool {
Command::new("python3")
.args([
"-c",
"import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)",
])
.status()
.is_ok_and(|s| s.success())
}
#[test]
fn generated_python_generics_load_and_hold_what_unitype_says() {
if !python_reads_type_parameters() {
eprintln!("no python3 of 3.12 or later on this machine; skipping");
return;
}
let dir = scratch("python_generic");
let root = emit_from(&generic_workspace(), &python::Python, &dir);
std::fs::write(
root.join("check.py"),
r#"import dataclasses, json
from generic import Box, Ghost, Labelled, Person, Uses, konst, unbox
uses = Uses(
boxed=Box(value=[1, 2]),
labelled=Labelled(value="x", label=Person(name="n")),
outcome={"$tag": "Err", "value": "bad"},
pending={"$tag": "Pending"},
flipped={"$tag": "Ok", "value": "a"},
swapped=("a", 1),
ghost=Ghost(id="g"),
)
print(json.dumps({
"uses": dataclasses.asdict(uses),
"konst": konst(3, "a"),
"unbox": unbox(Box(value=[4])),
}))
"#,
)
.expect("writes the driver");
agrees("Python", &run("python3", &["check.py"], &root));
}
#[test]
fn generated_typescript_generics_load_and_hold_what_unitype_says() {
if !node_reads_typescript() {
eprintln!("no node that reads TypeScript on this machine; skipping");
return;
}
let dir = scratch("typescript_generic");
let root = emit_from(&generic_workspace(), &typescript::TypeScript, &dir);
std::fs::write(root.join("package.json"), "{\"type\": \"module\"}\n").expect("writes");
std::fs::write(
root.join("check.mjs"),
r#"import { konst, unbox } from "./generic.ts";
const uses = {
boxed: { value: [1, 2] },
labelled: { value: "x", label: { name: "n" } },
outcome: { $tag: "Err", value: "bad" },
pending: { $tag: "Pending" },
flipped: { $tag: "Ok", value: "a" },
swapped: ["a", 1],
ghost: { id: "g" },
};
process.stdout.write(JSON.stringify({ uses, konst: konst(3, "a"), unbox: unbox({ value: [4] }) }));
"#,
)
.expect("writes the driver");
agrees("TypeScript", &run("node", &["check.mjs"], &root));
}
#[test]
fn generated_rust_generics_compile_and_hold_what_unitype_says() {
let dir = scratch("rust_generic");
let root = emit_from(&generic_workspace(), &rust::Rust, &dir);
std::fs::create_dir_all(dir.join("src")).expect("makes src");
std::fs::rename(root.join("generic.rs"), dir.join("src/generic.rs")).expect("moves the module");
std::fs::write(
dir.join("Cargo.toml"),
r#"[package]
name = "generic-check"
version = "0.0.0"
edition = "2024"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[workspace]
"#,
)
.expect("writes the manifest");
std::fs::write(
dir.join("src/main.rs"),
r#"#[allow(dead_code, unused_variables)]
mod generic;
fn main() {
let arrived = std::env::args().nth(1).expect("a Uses");
let uses: generic::Uses = serde_json::from_str(&arrived).expect("reads as a Uses");
println!(
"{}",
serde_json::json!({
"uses": uses,
"konst": generic::konst(3, "a".to_string()),
"unbox": generic::unbox(generic::Box { value: vec![4i64] }),
})
);
}
"#,
)
.expect("writes the driver");
let target = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("rust_wire_target");
let cargo = |args: &[&str]| {
Command::new(env!("CARGO"))
.args(args)
.env("CARGO_TARGET_DIR", &target)
.current_dir(&dir)
.output()
.expect("runs cargo")
};
let built = cargo(&["build", "--quiet", "--offline"]);
let said = String::from_utf8_lossy(&built.stderr);
if !built.status.success() && !said.contains("error[") && !said.contains("could not compile") {
eprintln!("serde is not available offline; skipping\n{said}");
return;
}
assert!(
built.status.success(),
"the generated Rust did not build:\n{said}"
);
let output = cargo(&["run", "--quiet", "--offline", "--", &uses_json()]);
assert!(
output.status.success(),
"the generated Rust failed when it ran:\n{}",
String::from_utf8_lossy(&output.stderr)
);
agrees(
"Rust",
&String::from_utf8(output.stdout).expect("output is text"),
);
}
const CARRIED_UNIVERSE: &str = r#"{"universes":[{"name":"carried","types":[
{"k":"struct","name":"Doc","fields":[
{"name":"by_number","ty":"map<i64, str>"},
{"name":"by_name","ty":"map<str, i64>"},
{"name":"blob","ty":"bytes"},
{"name":"blobs","ty":"[bytes]"},
{"name":"maybe","ty":"bytes?"},
{"name":"later","ty":"bytes?"},
{"name":"labels","ty":"map<i64, bytes>"}]}]}]}"#;
const DOC: &str = r#"{"by_number":{"1":"one","20":"twenty"},"by_name":{"a":1,"b":2},
"blob":"AQID","blobs":["","AQ==","AQI="],"maybe":"AAEC","labels":{"7":"/w=="}}"#;
fn carried_workspace() -> CheckedWorkspace {
check_workspace(Workspace::from_json(CARRIED_UNIVERSE).expect("reads")).expect("checks")
}
fn doc_type() -> Type {
Type::Ref(TypeRef::qualified(
Ident::new("carried").unwrap(),
Ident::new("Doc").unwrap(),
))
}
fn holds_the_doc(language: &str, produced: &serde_json::Value) {
let ws = carried_workspace();
let written = ws
.write_json(
&ws.read_json(DOC, &doc_type()).expect("a real Doc"),
&doc_type(),
)
.expect("writes");
assert_eq!(
normalize(&written),
normalize(DOC),
"unitype wrote a Doc some other way than the plain shapes"
);
assert_eq!(
normalize(&produced.to_string()),
normalize(&written),
"the generated {language} produced a different Doc than unitype says it is"
);
assert!(
ws.read_json(&produced.to_string(), &doc_type()).is_ok(),
"and unitype reads back what the generated {language} wrote"
);
}
#[test]
fn generated_python_holds_maps_keyed_by_integers_and_bytes_the_way_unitype_writes_them() {
if !have("python3") {
eprintln!("no python3 on this machine; skipping");
return;
}
let dir = scratch("python_carried");
let root = emit_from(&carried_workspace(), &python::Python, &dir);
std::fs::write(
root.join("check.py"),
r#"import dataclasses, json
from carried import Doc
doc = Doc(
by_number={"1": "one", "20": "twenty"},
by_name={"a": 1, "b": 2},
blob="AQID",
blobs=["", "AQ==", "AQI="],
maybe="AAEC",
labels={"7": "/w=="},
)
print(json.dumps({k: v for k, v in dataclasses.asdict(doc).items() if v is not None}))
"#,
)
.expect("writes the driver");
let produced: serde_json::Value =
serde_json::from_str(&run("python3", &["check.py"], &root)).expect("valid JSON");
holds_the_doc("Python", &produced);
let source = std::fs::read_to_string(root.join("carried.py")).expect("reads the module");
for expected in [
"by_number: dict[str, str]",
"blob: str",
"blobs: list[str]",
"labels: dict[str, str]",
] {
assert!(
source.contains(expected),
"missing `{expected}` in:\n{source}"
);
}
}
#[test]
fn generated_typescript_holds_maps_keyed_by_integers_and_bytes_the_way_unitype_writes_them() {
if !node_reads_typescript() {
eprintln!("no node that reads TypeScript on this machine; skipping");
return;
}
let dir = scratch("typescript_carried");
let root = emit_from(&carried_workspace(), &typescript::TypeScript, &dir);
std::fs::write(root.join("package.json"), "{\"type\": \"module\"}\n").expect("writes");
std::fs::write(
root.join("check.mjs"),
r#"import "./carried.ts";
const doc = {
by_number: { 1: "one", 20: "twenty" },
by_name: { a: 1, b: 2 },
blob: "AQID",
blobs: ["", "AQ==", "AQI="],
maybe: "AAEC",
labels: { 7: "/w==" },
};
process.stdout.write(JSON.stringify(doc));
"#,
)
.expect("writes the driver");
let produced: serde_json::Value =
serde_json::from_str(&run("node", &["check.mjs"], &root)).expect("valid JSON");
holds_the_doc("TypeScript", &produced);
let source = std::fs::read_to_string(root.join("carried.ts")).expect("reads the module");
for expected in [
"by_number: Record<number, string>;",
"blob: string;",
"blobs: string[];",
"labels: Record<number, string>;",
] {
assert!(
source.contains(expected),
"missing `{expected}` in:\n{source}"
);
}
}
#[test]
fn generated_rust_holds_maps_keyed_by_integers_and_bytes_the_way_unitype_writes_them() {
let dir = scratch("rust_carried");
let root = emit_from(&carried_workspace(), &rust::Rust, &dir);
std::fs::create_dir_all(dir.join("src")).expect("makes src");
for module in ["carried.rs", "unitype_support.rs"] {
std::fs::rename(root.join(module), dir.join("src").join(module)).expect("moves a module");
}
std::fs::write(
dir.join("Cargo.toml"),
r#"[package]
name = "carried-check"
version = "0.0.0"
edition = "2024"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[workspace]
"#,
)
.expect("writes the manifest");
std::fs::write(
dir.join("src/main.rs"),
r#"#[allow(dead_code, unused_variables)]
mod carried;
mod unitype_support;
use unitype_support::Bytes;
fn main() {
let arrived = std::env::args().nth(1).expect("a Doc");
let doc: carried::Doc = serde_json::from_str(&arrived).expect("reads as a Doc");
// Every length from nothing up, so that each amount of padding is written.
let lengths: Vec<serde_json::Value> = (0..=7u8)
.map(|n| {
let bytes = Bytes((0..n).map(|i| i.wrapping_mul(37).wrapping_add(250)).collect());
serde_json::to_value(&bytes).expect("writes")
})
.collect();
// Text that is not base64 as unitype writes it, or not text at all.
let refused: Vec<bool> = ["\"A\"", "\"A===\"", "\"A!==\"", "\"=AAA\"", "\"AA=A\"", "[1,2]"]
.iter()
.map(|bad| serde_json::from_str::<Bytes>(bad).is_err())
.collect();
println!(
"{}",
serde_json::json!({
"doc": doc, "lengths": lengths, "refused": refused,
"blob": doc.blob.to_vec(), "blobs": doc.blobs.iter().map(|b| b.len()).collect::<Vec<_>>(),
})
);
}
"#,
)
.expect("writes the driver");
let target = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("rust_wire_target");
let cargo = |args: &[&str]| {
Command::new(env!("CARGO"))
.args(args)
.env("CARGO_TARGET_DIR", &target)
.current_dir(&dir)
.output()
.expect("runs cargo")
};
let built = cargo(&["build", "--quiet", "--offline"]);
let said = String::from_utf8_lossy(&built.stderr);
if !built.status.success() && !said.contains("error[") && !said.contains("could not compile") {
eprintln!("serde is not available offline; skipping\n{said}");
return;
}
assert!(
built.status.success(),
"the generated Rust did not build:\n{said}"
);
let output = cargo(&["run", "--quiet", "--offline", "--", &DOC.replace('\n', "")]);
assert!(
output.status.success(),
"the generated Rust failed when it ran:\n{}",
String::from_utf8_lossy(&output.stderr)
);
let produced: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
holds_the_doc("Rust", &produced["doc"]);
use base64::Engine as _;
let want: Vec<String> = (0..=7u8)
.map(|n| {
let bytes: Vec<u8> = (0..n)
.map(|i| i.wrapping_mul(37).wrapping_add(250))
.collect();
base64::engine::general_purpose::STANDARD.encode(bytes)
})
.collect();
assert_eq!(
produced["lengths"],
serde_json::json!(want),
"the bytes were written some other way than standard, padded base64"
);
assert_eq!(
produced["refused"],
serde_json::json!([true, true, true, true, true, true]),
"text that is not base64 should be refused"
);
assert_eq!(
produced["blob"],
serde_json::json!([1, 2, 3]),
"and what is read is the bytes"
);
assert_eq!(produced["blobs"], serde_json::json!([0, 1, 2]));
}
fn build_haskell(root: &Path, main: &str) -> PathBuf {
let built = Command::new("ghc")
.args(["-v0", "-O0", "-outputdir", "obj", "-o", "check", main])
.current_dir(root)
.output()
.expect("runs ghc");
assert!(
built.status.success(),
"the generated Haskell did not build:\n{}",
String::from_utf8_lossy(&built.stderr)
);
root.join("check")
}
fn run_haskell(program: &Path, args: &[&str]) -> serde_json::Value {
let output = Command::new(program)
.args(args)
.output()
.expect("runs the program");
assert!(
output.status.success(),
"the generated Haskell failed when it ran:\n{}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("valid JSON")
}
#[test]
fn the_generated_haskell_compiles_and_produces_the_shape_it_promised() {
if !have("ghc") {
eprintln!("no ghc on this machine; skipping");
return;
}
let dir = scratch("haskell_wire");
let root = emit(&haskell::Haskell, &dir);
std::fs::write(
root.join("Check.hs"),
r#"{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import System.Environment (getArgs)
import UnitypeSupport
import Demo
decode :: FromJson a => Text -> IO a
decode text = either fail pure (parseJson text >>= fromJson)
-- Read the way it arrives, written the way it leaves: what comes out is
-- whatever the generated types believe the shape to be.
main :: IO ()
main = do
[arrived, looseArrived] <- map T.pack <$> getArgs
circle <- decode arrived :: IO Circle
loose <- decode looseArrived :: IO Loose
let noted = circle {circleNote = Just "hi"}
red = fromJson (JString "red") :: Either String Colour
green = fromJson (JString "green") :: Either String Colour
forms = JObject $ Map.fromList
[ ("total", toJson (total [1, 2, 3, 4]))
, ("ordered", toJson (ordered [1, 2, 2, 5]))
, ("unordered", toJson (ordered [3, 1]))
, ("note", toJson (note_or circle))
, ("small", toJson (measure SizeSmall))
, ("large", toJson (measure (SizeLarge 21)))
, ("two_tags", toJson (two_tags circle))
, ("mark", toJson (mark 5))
, ("last", toJson (last_of [1, 2, 3]))
, ("last_empty", toJson (last_of []))
, ("radius", toJson (radius_of circle))
, ("positive", toJson (positive 3))
, ("not_positive", toJson (positive (-1)))
, ("fallback", toJson (note_or_else circle (Just "x")))
, ("no_fallback", toJson (note_or_else circle Nothing))
, ("noted", toJson (note_or_else noted Nothing))
, ("small_hint", toJson (hint SizeSmall))
, ("large_hint", toJson (hint (SizeLarge 21)))
, ("noted_as", toJson (noted_as noted "hi"))
, ("not_noted_as", toJson (noted_as circle "hi"))
, ("with_gap", toJson (with_gap 5))
, ("pin", toJson (pin_at 5))
, ("loose", toJson (loose_at 5))
, ("gaps", toJson gaps)
, ("pair", toJson pair)
, ("bound_pair", toJson (bound_pair 5))
, ("settled_small", toJson (settled [1, 2, 3]))
, ("settled_large", toJson (settled [4]))
]
out = JObject $ Map.fromList
[ ("circle", toJson circle)
, ("loose", toJson loose)
, ("label", toJson (label_of circle))
, ("red", JString (either (const "refused") (const "red") red))
, ("green", JBool (either (const False) (const True) green))
, ("forms", forms)
]
either fail TIO.putStrLn (renderJson out)
"#,
)
.expect("writes the driver");
let program = build_haskell(&root, "Check.hs");
let produced = run_haskell(&program, &[&expected_json(), &loose_json()]);
assert_eq!(
normalize(&produced["circle"].to_string()),
normalize(&expected_json()),
"the generated record read and wrote a different shape than unitype \
says the value has"
);
assert_eq!(
normalize(&produced["loose"].to_string()),
normalize(&loose_json()),
"fields that may be absent have to read when they are not there, and \
be left out again when they are written"
);
assert_eq!(
normalize(&produced["label"].to_string()),
normalize(LABEL),
"the body, as Haskell, answered differently"
);
assert_eq!(
normalize(&produced["forms"].to_string()),
normalize(FORMS),
"the bodies, as Haskell, answered differently"
);
assert_eq!(produced["red"], "red", "a name travels as the string it is");
assert_eq!(
produced["green"], false,
"a string the union does not admit should be refused"
);
}
#[test]
fn generated_haskell_generics_compile_and_hold_what_unitype_says() {
if !have("ghc") {
eprintln!("no ghc on this machine; skipping");
return;
}
let dir = scratch("haskell_generic");
let root = emit_from(&generic_workspace(), &haskell::Haskell, &dir);
std::fs::write(
root.join("Check.hs"),
r#"{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Data.Int (Int64)
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import System.Environment (getArgs)
import UnitypeSupport
import Generic
main :: IO ()
main = do
[arrived] <- map T.pack <$> getArgs
uses <- either fail pure (parseJson arrived >>= fromJson) :: IO Uses
let out = JObject $ Map.fromList
[ ("uses", toJson uses)
, ("konst", toJson (konst (3 :: Int64) ("a" :: Text)))
, ("unbox", toJson (unbox (Box [4 :: Int64])))
]
either fail TIO.putStrLn (renderJson out)
"#,
)
.expect("writes the driver");
let program = build_haskell(&root, "Check.hs");
let produced = run_haskell(&program, &[&uses_json()]);
agrees("Haskell", &produced.to_string());
}
#[test]
fn generated_haskell_holds_maps_keyed_by_integers_and_bytes_the_way_unitype_writes_them() {
if !have("ghc") {
eprintln!("no ghc on this machine; skipping");
return;
}
let dir = scratch("haskell_carried");
let root = emit_from(&carried_workspace(), &haskell::Haskell, &dir);
std::fs::write(
root.join("Check.hs"),
r#"{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as Map
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Data.Word (Word8)
import System.Environment (getArgs)
import UnitypeSupport
import Carried
main :: IO ()
main = do
[arrived] <- map T.pack <$> getArgs
doc <- either fail pure (parseJson arrived >>= fromJson) :: IO Doc
-- Every length from nothing up, so that each amount of padding is written.
let lengths = [toJson (BS.pack (map (\i -> i * 37 + 250) [0 .. n])) | n <- [0 .. 7 :: Word8], n > 0]
++ [toJson (BS.empty)]
-- Text that is not base64 as unitype writes it, or not text at all.
refused =
[ either (const True) (const False) (fromJson j :: Either String BS.ByteString)
| j <- map JString ["A", "A===", "A!==", "=AAA", "AA=A"] ++ [JArray [JInt 1, JInt 2]]
]
out = JObject $ Map.fromList
[ ("doc", toJson doc)
, ("lengths", JArray lengths)
, ("refused", JArray (map JBool refused))
, ("blob", JArray (map (JInt . toInteger) (BS.unpack (docBlob doc))))
, ("blobs", JArray (map (JInt . toInteger . BS.length) (docBlobs doc)))
]
either fail TIO.putStrLn (renderJson out)
"#,
)
.expect("writes the driver");
let program = build_haskell(&root, "Check.hs");
let produced = run_haskell(&program, &[&DOC.replace('\n', "")]);
holds_the_doc("Haskell", &produced["doc"]);
use base64::Engine as _;
let mut want: Vec<String> = (1..=7u8)
.map(|n| {
let bytes: Vec<u8> = (0..=n)
.map(|i| i.wrapping_mul(37).wrapping_add(250))
.collect();
base64::engine::general_purpose::STANDARD.encode(bytes)
})
.collect();
want.push(String::new());
assert_eq!(
produced["lengths"],
serde_json::json!(want),
"the bytes were written some other way than standard, padded base64"
);
assert_eq!(
produced["refused"],
serde_json::json!([true, true, true, true, true, true]),
"text that is not base64 should be refused"
);
assert_eq!(
produced["blob"],
serde_json::json!([1, 2, 3]),
"and what is read is the bytes"
);
assert_eq!(produced["blobs"], serde_json::json!([0, 1, 2]));
let source = std::fs::read_to_string(root.join("Carried.hs")).expect("reads the module");
for expected in [
"docBy_number :: Map Int64 Text",
"docBlob :: ByteString",
"docBlobs :: [ByteString]",
"docLabels :: Map Int64 ByteString",
] {
assert!(
source.contains(expected),
"missing `{expected}` in:\n{source}"
);
}
}
#[test]
fn a_value_cast_as_haskell_compiles_and_means_the_value_it_was_cast_from() {
if !have("ghc") {
eprintln!("no ghc on this machine; skipping");
return;
}
let mut universes = Vec::new();
for text in [UNIVERSE, CARRIED_UNIVERSE] {
let parsed: serde_json::Value = serde_json::from_str(text).expect("valid JSON");
universes.extend(parsed["universes"].as_array().cloned().expect("universes"));
}
let ws = check_workspace(
Workspace::from_json(&serde_json::json!({ "universes": universes }).to_string())
.expect("reads"),
)
.expect("checks");
let cases: [(&str, &str, &str); 7] = [
(
"demo::Circle",
"Circle",
r#"{"id":"c-1","kind":"circle","radius":2.5,"centre":[1.5,-0.5],
"tags":["round","say \"hi\" é"],"note":"hi"}"#,
),
("demo::Pin", "Pin", r#"{"at":-5,"before":3,"label":"x"}"#),
(
"demo::Loose",
"Loose",
r#"{"at":5,"when":7,"extra":{"a":[1,2.5,null,"s"]},"nothing":null}"#,
),
("demo::Size", "Size", r#"{"$tag":"large","value":21}"#),
("demo::Size", "Size", r#"{"$tag":"small"}"#),
("demo::Colour", "Colour", r#""blue""#),
(
"carried::Doc",
"Doc",
r#"{"by_number":{"1":"one","20":"twenty"},"by_name":{"a":1},"blob":"AQID",
"blobs":["","AQ=="],"maybe":"AAEC","labels":{"7":"/w=="}}"#,
),
];
let how = unitype_codegen::constructors("haskell").expect("has constructors");
let profile = unitype_core::lang::profile("haskell").expect("ships");
let mut items = Vec::new();
let mut expected = Vec::new();
for (qualified, short, data) in cases {
let name: unitype_core::QualifiedName = qualified.parse().expect("a name");
let ty = Type::Ref(TypeRef::qualified(name.universe.clone(), name.name.clone()));
let value = ws.read_json(data, &ty).expect("a real value");
let literal = unitype_codegen::literal::typed(&ws, &profile, &how, &value, &ty);
items.push(format!("toJson ({literal} :: {short})"));
expected.push(ws.write_json(&value, &ty).expect("writes"));
}
let dir = scratch("haskell_cast");
let root = dir.join("haskell");
std::fs::create_dir_all(&root).expect("makes the directory");
for file in haskell::Haskell
.generate(&ws, &GenOptions::default())
.expect("generates")
{
std::fs::write(
root.join(file.path.file_name().expect("a name")),
file.contents,
)
.expect("writes");
}
std::fs::write(
root.join("Check.hs"),
format!(
r#"{{-# LANGUAGE OverloadedStrings #-}}
module Main (main) where
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as Map
import qualified Data.Text.IO as TIO
import Carried (Doc (..))
import Demo (Circle (..), Colour (..), Loose (..), Pin (..), Size (..))
import UnitypeSupport
main :: IO ()
main = mapM_ (either fail TIO.putStrLn . renderJson)
[ {}
]
"#,
items.join("\n , ")
),
)
.expect("writes the driver");
let built = Command::new("ghc")
.args(["-v0", "-O0", "-outputdir", "obj", "-o", "check", "Check.hs"])
.current_dir(&root)
.output()
.expect("runs ghc");
assert!(
built.status.success(),
"a literal written for Haskell did not compile:\n{}\n{}",
String::from_utf8_lossy(&built.stderr),
std::fs::read_to_string(root.join("Check.hs")).unwrap_or_default()
);
let output = Command::new(root.join("check")).output().expect("runs");
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let written = String::from_utf8(output.stdout).expect("text");
let produced: Vec<&str> = written.lines().collect();
assert_eq!(produced.len(), expected.len(), "{written}");
for ((got, want), (qualified, _, _)) in produced.iter().zip(&expected).zip(cases) {
assert_eq!(
normalize(got),
normalize(want),
"the literal written for {qualified} means some other value"
);
}
}