use polydat::ast::Value;
use polydat::compile::assembly::{PolydatAssembler, WireRef};
use polydat::dsl::compile::{
CompileOptions, compile_polydat, compile_polydat_interpreter,
compile_polydat_interpreter_with_log, compile_polydat_interpreter_with_options,
compile_polydat_kernel, compile_polydat_kernel_with_options, compile_polydat_to_assembler,
compile_polydat_to_assembler_with, compile_polydat_with, compile_polydat_with_engine,
};
use polydat::dsl::events::CompileEventLog;
use polydat::{Engine, JitMode, Kernel, KernelError, Provenance};
const SRC: &str = "input cycle: u64\nh := hash(cycle)\nk := mod_wire(h, 7)\ns := \"k={k}\"\n";
fn engines() -> Vec<Engine> {
let mut all = vec![
Engine::Interpreter(JitMode::Auto),
Engine::Closures(Provenance::Auto),
Engine::Closures(Provenance::Raw),
];
if cfg!(feature = "jit") {
all.push(Engine::Native(Provenance::Auto));
all.push(Engine::Native(Provenance::Raw));
all.push(Engine::PureNative(Provenance::Auto));
all.push(Engine::PureNative(Provenance::Raw));
}
all
}
fn values(k: &mut dyn Kernel, cycle: u64) -> Vec<Value> {
k.set_inputs(&[cycle]);
k.output_names().iter().map(|o| k.pull(o)).collect()
}
#[test]
fn every_entry_point_reaches_the_same_kernel() {
let mut oracle = compile_polydat_interpreter(SRC).unwrap();
let want: Vec<Value> = values(&mut oracle, 5);
let options = CompileOptions::default();
let mut log = CompileEventLog::new();
let mut kernels: Vec<(&str, Box<dyn Kernel>)> = vec![
(
"compile_polydat_kernel",
compile_polydat_kernel(SRC).unwrap(),
),
(
"compile_polydat_kernel_with_options",
compile_polydat_kernel_with_options(SRC, &options, Some(&mut log)).unwrap(),
),
(
"compile_polydat_interpreter_with_options",
Box::new(compile_polydat_interpreter_with_options(SRC, &options, None).unwrap()),
),
(
"compile_polydat_interpreter_with_log",
Box::new(
compile_polydat_interpreter_with_log(SRC, &mut CompileEventLog::new()).unwrap(),
),
),
(
"compile_polydat_to_assembler",
compile_polydat_to_assembler(SRC)
.unwrap()
.compile_kernel()
.unwrap(),
),
(
"compile_polydat_to_assembler_with",
Box::new(
compile_polydat_to_assembler_with(SRC, &options)
.unwrap()
.compile()
.unwrap(),
),
),
];
for engine in engines() {
if let Ok(k) = compile_polydat_with(SRC, engine) {
kernels.push(("compile_polydat_with", k));
}
if let Ok(k) = compile_polydat_with_engine(SRC, engine, &options, None) {
kernels.push(("compile_polydat_with_engine", k));
}
if let Ok(k) = compile_polydat_to_assembler(SRC)
.unwrap()
.compile_with(engine)
{
kernels.push(("PolydatAssembler::compile_with", k));
}
}
for (name, k) in kernels.iter_mut() {
assert_eq!(
k.output_names(),
oracle.output_names(),
"{name} on {}",
k.engine()
);
assert_eq!(values(k.as_mut(), 5), want, "{name} on {}", k.engine());
}
}
#[test]
fn a_hand_built_assembler_compiles_on_every_engine() {
fn build() -> PolydatAssembler {
let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
use polydat::ast::PortType;
let hash = polydat::dsl::factory::build_node(
"hash",
&[WireRef::input("cycle")],
&[PortType::U64],
&[],
)
.unwrap();
asm.add_node("h", hash, vec![WireRef::input("cycle")]);
let m = polydat::dsl::factory::build_node(
"mod",
&[WireRef::node("h")],
&[PortType::U64],
&[polydat::dsl::ConstArg::Int(7)],
)
.unwrap();
asm.add_node("k", m, vec![WireRef::node("h")]);
asm.add_output("h", WireRef::node("h"));
asm.add_output("k", WireRef::node("k"));
asm
}
fn hk(k: &mut dyn Kernel) -> (Value, Value) {
k.set_inputs(&[9]);
(k.pull("h"), k.pull("k"))
}
let mut from_source =
compile_polydat_interpreter("input cycle: u64\nh := hash(cycle)\nk := mod(h, 7)\n")
.unwrap();
let want = hk(&mut from_source);
let mut p1 = build().compile().unwrap();
assert_eq!(hk(&mut p1), want);
for engine in engines() {
let mut k = match build().compile_with(engine) {
Ok(k) => k,
Err(KernelError::Refused { .. }) => continue,
Err(e) => panic!("{engine}: {e}"),
};
assert_eq!(hk(k.as_mut()), want, "{engine}");
}
let mut default = build().compile_kernel().unwrap();
assert!(matches!(
(default.engine(), Engine::default()),
(Engine::Native(_), Engine::Native(_)) | (Engine::Closures(_), Engine::Closures(_))
));
assert_eq!(hk(default.as_mut()), want);
}
#[test]
fn strict_refuses_implicit_coercions_on_every_engine() {
let src = "input cycle: u64\nh := hash(cycle)\nf := sqrt(h)\n";
let strict = CompileOptions {
strict: true,
..CompileOptions::default()
};
assert!(compile_polydat_interpreter_with_options(src, &strict, None).is_err());
for engine in engines() {
let outcome = compile_polydat_with_engine(src, engine, &strict, None);
assert!(
matches!(
outcome,
Err(KernelError::Assembly(_)) | Err(KernelError::Source(_))
),
"{engine}: strict must refuse the implicit coercion, got {:?}",
outcome.map(|k| k.engine())
);
let lax = compile_polydat_with_engine(src, engine, &CompileOptions::default(), None);
assert!(
lax.is_ok() || matches!(lax, Err(KernelError::Refused { .. })),
"{engine}: {:?}",
lax.err()
);
}
}
#[test]
fn the_slot_surface_is_a_subtrait_reachable_without_a_kernel_type() {
use polydat::SlotKernel;
let mut oracle = compile_polydat_interpreter(SRC).unwrap();
let want = values(&mut oracle, 5);
for engine in engines() {
if matches!(engine, Engine::Interpreter(_)) {
match compile_polydat_to_assembler(SRC)
.unwrap()
.compile_slots(engine)
{
Err(KernelError::Refused { reason, .. }) => {
assert!(reason.contains("slot"), "{reason}")
}
Err(e) => panic!("expected a refusal naming the slot buffer, got {e}"),
Ok(_) => panic!("the interpreter has no slot buffer to hand back"),
}
continue;
}
let mut k = match compile_polydat_to_assembler(SRC)
.unwrap()
.compile_slots(engine)
{
Ok(k) => k,
Err(KernelError::Refused { .. }) => continue,
Err(e) => panic!("{engine}: {e}"),
};
let slot = SlotKernel::resolve_output(k.as_ref(), "k").expect("a named output");
let raw = k.eval_for_slot(&[5], slot);
assert_eq!(raw, SlotKernel::get(k.as_ref(), "k"));
assert_eq!(k.engine(), engine_of(engine, k.engine()));
assert_eq!(values(k.as_mut(), 5), want, "{engine}");
assert_eq!(k.pull("k").as_u64(), raw, "{engine}");
}
}
fn engine_of(asked: Engine, reported: Engine) -> Engine {
match (asked, reported) {
(Engine::Closures(Provenance::Auto), r @ Engine::Closures(_)) => r,
(Engine::Native(Provenance::Auto), r @ Engine::Native(_)) => r,
(Engine::PureNative(Provenance::Auto), r @ Engine::PureNative(_)) => r,
_ => asked,
}
}
#[test]
#[cfg(feature = "jit")]
fn the_pure_tier_names_itself_and_refuses_the_modes_it_lacks() {
let mut oracle = compile_polydat_interpreter(SRC).unwrap();
let want = values(&mut oracle, 5);
for prov in [Provenance::Auto, Provenance::Raw, Provenance::PushPull] {
let engine = Engine::PureNative(prov);
let mut k = compile_polydat_with(SRC, engine).unwrap_or_else(|e| panic!("{engine}: {e}"));
let ran = k.engine();
assert!(
matches!(ran, Engine::PureNative(_)),
"{engine}: reported {ran}",
);
if prov != Provenance::Auto {
assert_eq!(ran, engine, "a named mode is honoured or refused");
}
assert_eq!(values(k.as_mut(), 5), want, "{engine}");
}
for prov in [Provenance::Push, Provenance::Pull] {
let engine = Engine::PureNative(prov);
match compile_polydat_with(SRC, engine) {
Err(KernelError::Refused {
engine: named,
reason,
}) => {
assert!(matches!(named, Engine::PureNative(_)), "{named}");
assert!(reason.contains("pure native"), "{reason}");
}
other => panic!(
"{engine}: expected a refusal, got {:?}",
other.map(|k| k.engine())
),
}
}
}
#[test]
fn every_engine_folds_its_constants_at_build() {
let src = "input cycle: u64\nn := mod_wire(10, 0)\nv := n + cycle\n";
for engine in engines() {
let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
compile_polydat_with(src, engine).map(|k| k.engine())
}))
.unwrap_or_else(|_| panic!("{engine}: a build failure is an error, never a panic"));
match built {
Err(KernelError::ConstantFold { reason }) => assert!(
reason.contains("zero") && reason.contains("mod_wire"),
"{engine}: the message carries the node's own failure: {reason}",
),
other => panic!(
"{engine}: a constant that cannot be computed is a ConstantFold error at \
build, got {other:?}",
),
}
}
let dynamic = "input cycle: u64\nn := mod_wire(10, cycle)\n";
for engine in engines() {
assert!(
compile_polydat_with(dynamic, engine).is_ok(),
"{engine}: a dynamic divisor is not a compile-time constant",
);
}
}
#[test]
#[cfg(feature = "jit")]
fn the_two_native_tiers_agree_in_value_and_differ_in_name() {
let mut hybrid = compile_polydat_with(SRC, Engine::Native(Provenance::Auto)).unwrap();
let mut pure = compile_polydat_with(SRC, Engine::PureNative(Provenance::Auto)).unwrap();
assert!(matches!(hybrid.engine(), Engine::Native(_)));
assert!(matches!(pure.engine(), Engine::PureNative(_)));
assert_eq!(values(hybrid.as_mut(), 9), values(pure.as_mut(), 9));
}
#[test]
fn the_diagnostic_entry_point_agrees_with_the_compile_it_diagnoses() {
use polydat::dsl::compile::compile_polydat_checked;
for (label, src) in [
("plain", "input cycle: u64\nh := hash(cycle)\n"),
(
"traversal",
"input cycle: u64\nfor k in 1..3 {\n y := k * 10\n}\n",
),
(
"pragma",
"pragma strict_types\ninput cycle: u64\nh := hash(cycle)\n",
),
("tile", "input cycle: u64\ntile t := \"c=${cycle}\"\n"),
(
"module",
"input cycle: u64\nd(a: u64) -> (o: u64) := {\n o := a + 1\n}\nx := d(cycle)\n",
),
("broken", "input cycle: u64\nh := no_such_function(cycle)\n"),
] {
let compiles = compile_polydat_kernel(src).is_ok();
let (checked, report) = compile_polydat_checked(src);
assert_eq!(
checked.is_ok(),
compiles,
"{label}: the diagnostic entry disagrees with the compile it diagnoses"
);
assert_eq!(
report.errors().is_empty(),
compiles,
"{label}: the report should carry an error exactly when the compile fails"
);
}
assert!(compile_polydat_to_assembler("input cycle: u64\nh := hash(cycle)\n").is_ok());
assert!(
compile_polydat_to_assembler("input cycle: u64\nfor k in 1..3 {\n y := k * 10\n}\n")
.is_err(),
"an assembler holds no traversal, so it refuses a program with one"
);
}
#[test]
fn the_logged_compile_accepts_a_traversal() {
let src = "input cycle: u64\nfor k in 1..3 {\n y := k * 10\n}\n";
let mut log = CompileEventLog::new();
let k = compile_polydat_interpreter_with_log(src, &mut log)
.expect("a for statement compiles with a log");
assert_eq!(k.traversals().len(), 1);
}
#[test]
fn deferred_cursor_extents_resolve_on_every_engine() {
let src = "input cycle: u64\nn := 10 + 5\ncursor q = range(0, n)\nv := hash(q.ordinal)\n";
let want = compile_polydat_interpreter(src).unwrap().cursor_schemas()[0].extent;
assert_eq!(want, Some(15));
for engine in engines() {
let k = match compile_polydat_with(src, engine) {
Ok(k) => k,
Err(KernelError::Refused { .. }) => continue,
Err(e) => panic!("{engine}: {e}"),
};
assert_eq!(k.cursor_schemas()[0].extent, want, "{engine}");
}
}
#[test]
fn a_program_module_is_visible_inside_a_traversal_body() {
let src = "\
input cycle: u64
twice(x: u64) -> (y: u64) := {
y := x * 2
}
for k in 1..4 {
d := twice(k)
}
";
for engine in engines() {
let mut k = match compile_polydat_with(src, engine) {
Ok(k) => k,
Err(KernelError::Refused { .. }) => continue,
Err(e) => panic!("{engine}: {e}"),
};
k.set_inputs(&[0]);
let streams = k.traverse_all().unwrap();
let mut seen = Vec::new();
for s in &streams {
for i in 0..s.len() {
let mut act = s.activation(i).unwrap();
act.kernel.set_inputs(&[0]);
seen.push(act.kernel.pull("d").as_u64());
}
}
assert_eq!(seen, vec![2, 4, 6], "{engine}");
}
}
#[test]
fn the_engine_less_entry_points_build_the_default_engine() {
let src = "out := hash(cycle)\n";
let expected = Engine::default();
for (name, kernel) in [
(
"compile_polydat",
compile_polydat(src).expect("it compiles"),
),
(
"compile_polydat_kernel",
compile_polydat_kernel(src).expect("it compiles"),
),
(
"compile_polydat_kernel_with_options",
compile_polydat_kernel_with_options(src, &CompileOptions::default(), None)
.expect("it compiles"),
),
] {
let got = kernel.engine();
assert_ne!(
got,
Engine::Interpreter(JitMode::Off),
"{name} built the interpreter; an engine-less entry point builds {expected}"
);
assert!(
matches!(got, Engine::Native(_) | Engine::Closures(_)),
"{name} built {got}, which is neither tier of {expected}"
);
}
}
#[test]
fn the_interpreter_is_reached_by_naming_it() {
let src = "out := hash(cycle)\n";
let named = compile_polydat_interpreter(src).expect("it compiles");
assert!(
matches!(Kernel::engine(&named), Engine::Interpreter(_)),
"compile_polydat_interpreter must build the interpreter"
);
let mut configured = {
let options = CompileOptions {
engine: Engine::Interpreter(JitMode::Off),
..CompileOptions::default()
};
compile_polydat_kernel_with_options(src, &options, None).expect("it compiles")
};
assert!(
matches!(configured.engine(), Engine::Interpreter(_)),
"an engine asked for in the options is the engine that is built"
);
let mut default_engine = compile_polydat(src).expect("it compiles");
for cycle in [0u64, 1, 7, 99] {
assert_eq!(
values(configured.as_mut(), cycle),
values(default_engine.as_mut(), cycle),
"cycle {cycle}"
);
}
}