#![cfg(feature = "vectordata-fixtures")]
use std::path::PathBuf;
use std::sync::OnceLock;
use polydat_core::ast::Value;
use polydat_core::dsl::compile::compile_polydat_to_assembler;
use polydat_core::{Engine, JitMode, Provenance};
use vectordata::binding::{BindType, Layout, LayoutSource, Nullability};
use vectordata::formats::mnode::{MNode, MValue};
use vectordata::{TestDataGroup, TestDataView, TestDataViewExt};
const WIRES: [&str; 5] = ["str", "bool", "i64", "f64", "bytes"];
fn dataset() -> &'static str {
static PATH: OnceLock<String> = OnceLock::new();
PATH.get_or_init(|| {
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
.join(format!("record-fields-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("create {}: {e}", dir.display()));
let dataset = polydat_core::library::vectors::fixtures::predicated(&dir)
.unwrap_or_else(|e| panic!("write the fixture to {}: {e}", dir.display()));
dataset.to_string_lossy().replace('\\', "/")
})
}
fn view() -> std::sync::Arc<dyn TestDataView> {
TestDataGroup::load(dataset())
.unwrap_or_else(|e| panic!("load the fixture: {e}"))
.profile("default")
.expect("the fixture has a default profile")
}
fn wire_of(bind: &BindType) -> Option<&'static str> {
match bind {
BindType::Text | BindType::Ascii => Some("str"),
BindType::Bool => Some("bool"),
BindType::Int16 | BindType::Int32 | BindType::Int64 => Some("i64"),
BindType::Float16 | BindType::Float32 | BindType::Float64 => Some("f64"),
BindType::Blob => Some("bytes"),
_ => None,
}
}
fn wire_value(value: &MValue) -> Value {
match value {
MValue::Text(s) | MValue::Ascii(s) => Value::Str(s.as_str().into()),
MValue::Bool(b) => Value::Bool(*b),
MValue::Int(i) => Value::I64(*i),
MValue::Int32(i) => Value::I64(i64::from(*i)),
MValue::Short(i) => Value::I64(i64::from(*i)),
MValue::Float(f) => Value::F64(*f),
MValue::Float32(f) => Value::F64(f64::from(*f)),
MValue::Bytes(b) => Value::Bytes(b.as_slice().into()),
other => panic!("no scalar wire carries {other:?}"),
}
}
fn engines() -> Vec<Engine> {
let mut all = vec![
Engine::Interpreter(JitMode::Off),
Engine::Interpreter(JitMode::Force),
];
for m in [Provenance::Raw, Provenance::PushPull, Provenance::Auto] {
all.push(Engine::Closures(m));
all.push(Engine::Native(m));
}
if cfg!(feature = "jit") {
all.push(Engine::PureNative(Provenance::PushPull));
}
all
}
fn refusal(src: &str) -> String {
match compile_polydat_to_assembler(src)
.and_then(|asm| asm.compile_with(Engine::Interpreter(JitMode::Off)))
{
Ok(_) => panic!("built, and should have been refused:\n{src}"),
Err(e) => e.to_string(),
}
}
#[test]
fn the_fixture_declares_a_layout_with_scalar_fields() {
let view = view();
let layout = Layout::resolve(&*view).expect("the fixture has a layout");
assert_eq!(layout.source(), LayoutSource::LayoutFacet);
assert!(layout.unproven().is_empty(), "{:?}", layout.unproven());
let readable = layout
.types()
.iter()
.zip(layout.nullability())
.filter(|(t, n)| wire_of(t).is_some() && **n == Nullability::NeverNull)
.count();
assert!(
readable > 0,
"no never-null scalar field: {:?} {:?}",
layout.types(),
layout.nullability()
);
}
#[test]
fn a_field_reads_as_what_the_record_holds_on_every_engine() {
let view = view();
let layout = Layout::resolve(&*view).expect("the fixture has a layout");
let content = view
.open_facet_records("metadata_content")
.expect("the fixture has metadata records");
let count = content.count().expect("a record count");
let records: Vec<MNode> = (0..count)
.map(|i| MNode::from_bytes(&content.record_bytes(i).expect("a record")).expect("decodes"))
.collect();
let mut src = String::from("input cycle: u64\n");
let mut outputs: Vec<(String, String)> = Vec::new();
for (i, (name, bind)) in layout.names().iter().zip(layout.types()).enumerate() {
let Some(wire) = wire_of(bind) else { continue };
if layout.nullability()[i] == Nullability::Nullable {
continue;
}
src.push_str(&format!(
"field_{i} := record_field_{wire}(\"{}\", \"{name}\")\n\
out_{i} := record_{wire}_at(field_{i}, cycle)\n",
dataset()
));
outputs.push((format!("out_{i}"), name.clone()));
}
assert!(!outputs.is_empty(), "the fixture has a field to read");
let cycles: Vec<u64> = (0..count).chain([count, count + 1]).collect();
for engine in engines() {
let mut k = compile_polydat_to_assembler(&src)
.and_then(|asm| asm.compile_with(engine))
.unwrap_or_else(|e| panic!("{engine}: {e}\n{src}"));
for &c in &cycles {
k.set_inputs(&[c]);
let record = &records[(c % count) as usize];
for (out, name) in &outputs {
let held = record
.fields
.get(name)
.unwrap_or_else(|| panic!("record {c} has no `{name}`"));
assert_eq!(
k.pull(out).to_display_string(),
wire_value(held).to_display_string(),
"{engine}: `{name}` at cycle {c}"
);
}
}
}
}
#[test]
fn a_field_of_another_type_is_refused_when_the_program_is_built() {
let view = view();
let layout = Layout::resolve(&*view).expect("the fixture has a layout");
for (i, (name, bind)) in layout.names().iter().zip(layout.types()).enumerate() {
let nullable = layout.nullability()[i] == Nullability::Nullable;
for wire in WIRES {
let src = format!(
"input cycle: u64\n\
field := record_field_{wire}(\"{}\", \"{name}\")\n\
out := record_{wire}_at(field, cycle)\n",
dataset()
);
let built = compile_polydat_to_assembler(&src)
.and_then(|asm| asm.compile_with(Engine::Interpreter(JitMode::Off)));
if wire_of(bind) == Some(wire) && !nullable {
built.unwrap_or_else(|e| panic!("`{name}` ({bind:?}) as {wire}: {e}"));
continue;
}
let message = match built {
Ok(_) => panic!("`{name}` ({bind:?}, nullable: {nullable}) built as {wire}"),
Err(e) => e.to_string(),
};
let expected = if wire_of(bind) == Some(wire) {
"is declared nullable".to_string()
} else {
format!("is {bind:?}, which does not read as {wire}")
};
assert!(
message.contains(&format!("record_field_{wire}"))
&& message.contains(&format!("`{name}`"))
&& message.contains(&expected),
"`{name}` as {wire}: {message}"
);
}
}
}
#[test]
fn a_missing_field_is_refused_with_the_fields_the_records_have() {
let view = view();
let layout = Layout::resolve(&*view).expect("the fixture has a layout");
let missing = "no_such_field_in_any_record";
assert!(layout.position_of(missing).is_none());
let message = refusal(&format!(
"input cycle: u64\n\
field := record_field_str(\"{}\", \"{missing}\")\n\
out := record_str_at(field, cycle)\n",
dataset()
));
assert!(
message.contains(&format!("have no field `{missing}`")),
"{message}"
);
for name in layout.names() {
assert!(message.contains(name.as_str()), "`{name}` in: {message}");
}
}
#[test]
fn an_accessor_reads_only_a_field_resolved_for_its_type() {
let view = view();
let layout = Layout::resolve(&*view).expect("the fixture has a layout");
let (name, wire) = layout
.names()
.iter()
.zip(layout.types())
.zip(layout.nullability())
.find_map(|((name, bind), n)| {
(*n != Nullability::Nullable)
.then(|| wire_of(bind).map(|w| (name, w)))
.flatten()
})
.expect("the fixture has a scalar field");
let other = WIRES.iter().find(|w| **w != wire).expect("another type");
let src = format!(
"input cycle: u64\n\
field := record_field_{wire}(\"{}\", \"{name}\")\n\
out := record_{other}_at(field, cycle)\n",
dataset()
);
let outcome = std::panic::catch_unwind(|| {
let mut k = compile_polydat_to_assembler(&src)
.and_then(|asm| asm.compile_with(Engine::Interpreter(JitMode::Off)))?;
k.set_inputs(&[0]);
Ok::<_, polydat_core::KernelError>(k.pull("out").to_display_string())
});
let message = match outcome {
Ok(Ok(answer)) => panic!("read `{name}` ({wire}) as {other}: {answer}"),
Ok(Err(e)) => e.to_string(),
Err(panic) => panic
.downcast_ref::<String>()
.cloned()
.or_else(|| panic.downcast_ref::<&str>().map(|s| s.to_string()))
.unwrap_or_default(),
};
assert!(
message.contains(&format!(
"was resolved as {wire}, and this node reads {other}"
)),
"{message}"
);
}
#[test]
fn a_source_string_names_a_dataset_by_path() {
for profile in polydat_core::library::vectors::fixtures::PREDICATED_PROFILES {
let src = format!("n := vector_count(\"{}:{profile}\")\n", dataset());
let mut k = compile_polydat_to_assembler(&src)
.and_then(|asm| asm.compile_with(Engine::Interpreter(JitMode::Off)))
.unwrap_or_else(|e| panic!("{profile}: {e}"));
let expected = TestDataGroup::load(dataset())
.expect("load the fixture")
.profile(profile)
.unwrap_or_else(|| panic!("the fixture has profile {profile}"))
.base_vectors_as::<f32>()
.unwrap_or_else(|e| panic!("{profile}: {e}"))
.count();
assert_eq!(
k.pull("n").to_display_string(),
expected.to_string(),
"{profile}"
);
}
}