#![cfg(all(feature = "jit", feature = "vectordata"))]
use polydat::dsl::registry::registry;
use std::collections::BTreeMap;
use std::path::Path;
const START: &str = "<!-- node catalog: generated by tests/nodes_reference.rs; regenerate with NODES_REFERENCE=overwrite -->";
const END: &str = "<!-- /node catalog -->";
fn cell(text: &str) -> String {
text.replace('|', r"\|").replace('\n', " ")
}
fn section() -> String {
let (public, adapters): (Vec<_>, Vec<_>) = registry()
.into_iter()
.partition(|s| !s.name.starts_with("__"));
let mut by_category: BTreeMap<String, Vec<(&'static str, &'static str)>> = BTreeMap::new();
for sig in &public {
by_category
.entry(format!("{:?}", sig.category))
.or_default()
.push((sig.name, sig.description));
}
for names in by_category.values_mut() {
names.sort_unstable();
names.dedup();
}
let mut out = String::new();
out.push_str(&format!(
"\n{} nodes are callable by name from a program, in {} categories. A \
further {} conversion adapters, whose names begin with `__`, are \
inserted by the assembler where a wire and a port disagree about \
type. A program can call one by name like any other node, though\n\
it rarely needs to, and\n\
[type_system.md](../design/type_system.md) §3 is their catalog.\n\n",
by_category.values().map(Vec::len).sum::<usize>(),
by_category.len(),
adapters.len(),
));
for (category, names) in &by_category {
out.push_str(&format!("### {category} ({})\n\n", names.len()));
out.push_str("| Node | What it does |\n|---|---|\n");
for (name, description) in names {
out.push_str(&format!("| `{name}` | {} |\n", cell(description)));
}
out.push('\n');
}
out.push_str(&overloads_section());
out
}
fn overloads_section() -> String {
let mut overloads: Vec<_> = polydat::dsl::registry::overloads().collect();
overloads.sort_unstable_by_key(|o| o.name);
let mut out = format!(
"### Overloaded names ({})\n\n\
Each of these names stands for one node per operand type. A call \
builds the node agreeing with the most of its operands' types, the \
first listed among equals, and the assembler's adapters reach the \
node's other ports.\n\n\
| Name | Builds |\n|---|---|\n",
overloads.len()
);
for o in overloads {
let forms: Vec<String> = o
.forms
.iter()
.map(|f| {
let types: Vec<&str> = f.wires.iter().map(|t| t.to_keyword()).collect();
format!("`{}` for ({})", f.func, types.join(", "))
})
.collect();
out.push_str(&format!("| `{}` | {} |\n", o.name, forms.join("; ")));
}
out.push('\n');
out
}
#[test]
fn the_node_catalog_is_the_registry() {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("docs/reference/nodes.md");
let doc = std::fs::read_to_string(&path)
.unwrap_or_default()
.replace("\r\n", "\n");
let (Some(start), Some(end)) = (doc.find(START), doc.find(END)) else {
panic!("docs/reference/nodes.md lacks the node catalog markers");
};
let inner_start = start + START.len();
let rendered = section();
if std::env::var("NODES_REFERENCE").as_deref() == Ok("overwrite") {
let updated = format!("{}{}{}", &doc[..inner_start], rendered, &doc[end..]);
std::fs::write(&path, updated).unwrap();
return;
}
assert_eq!(
&doc[inner_start..end],
rendered,
"the node catalog in docs/reference/nodes.md is not the registry; \
regenerate with NODES_REFERENCE=overwrite"
);
}
fn const_arg_for(p: &polydat::dsl::registry::ParamSpec) -> polydat::dsl::factory::ConstArg {
use polydat::ast::SlotType;
use polydat::dsl::factory::ConstArg;
let e = p.example;
let from_example = match p.slot_type {
SlotType::ConstU64 => e.parse().ok().map(ConstArg::Int),
SlotType::ConstF64 => e.parse().ok().map(ConstArg::Float),
SlotType::ConstStr => e
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
.map(|s| ConstArg::Str(s.to_string())),
_ => None,
};
from_example.unwrap_or(match p.slot_type {
SlotType::ConstF64 => ConstArg::Float(1.0),
SlotType::ConstStr => ConstArg::Str("a".into()),
SlotType::ConstVecU64 | SlotType::ConstVec => ConstArg::List(vec![ConstArg::Int(1)]),
SlotType::ConstVecF64 => ConstArg::List(vec![ConstArg::Float(1.0)]),
_ => ConstArg::Int(3),
})
}
fn has_closure_form(node: &dyn polydat::ast::PolydatNode) -> bool {
use polydat::ast::Slot;
let meta = node.meta();
if (meta.name == "identity" || meta.name.starts_with("__port_")) && meta.outs.len() == 1 {
return true;
}
if node.compiled_u64().is_some() {
return true;
}
let wire_types: Vec<_> = meta
.ins
.iter()
.filter_map(|s| match s {
Slot::Wire(p) => Some(p.typ),
_ => None,
})
.collect();
node.compiled_slot(
&wire_types,
polydat::Engine::Closures(polydat::Provenance::Auto),
)
.is_some()
}
#[test]
fn every_registered_node_has_a_closure_form() {
use polydat::ast::PortType;
use polydat::compile::assembly::WireRef;
use polydat::dsl::compile::compile_polydat_to_assembler;
use polydat::dsl::factory::build_node;
let (csv, jsonl, txt) = super::common::coverage_cases::fixtures();
let programs = super::common::coverage_cases::overrides(&csv, &jsonl, &txt);
let closures = polydat::Engine::Closures(polydat::Provenance::Auto);
let mut gaps = Vec::new();
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
for sig in registry() {
let consts: Vec<_> = sig
.params
.iter()
.filter(|p| p.slot_type.is_const())
.map(const_arg_for)
.collect();
let n = if sig.is_variadic() {
sig.wire_input_count().max(2)
} else {
sig.wire_input_count()
};
let wires: Vec<WireRef> = (0..n).map(|i| WireRef::input(format!("w{i}"))).collect();
let built: Vec<bool> = PortType::ALL
.iter()
.filter_map(|&t| {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
build_node(
&polydat::dsl::factory::BuildContext::default(),
sig.name,
&wires,
&vec![t; n],
&consts,
)
}))
.ok()
.and_then(Result::ok)
.map(|node| has_closure_form(node.as_ref()))
})
.collect();
match (built.is_empty(), programs.get(sig.name)) {
(false, _) => {
if !built.contains(&true) {
gaps.push(format!(
"{}: no closure form over any wire type it builds with",
sig.name
));
}
}
(true, Some(src)) => {
let built = compile_polydat_to_assembler(src)
.map_err(|e| e.to_string())
.and_then(|asm| {
asm.compile_with(closures)
.map(|_| ())
.map_err(|e| e.to_string())
});
if let Err(e) = built {
gaps.push(format!("{}: {e}", sig.name));
}
}
(true, None) => gaps.push(format!(
"{}: neither its signature nor a coverage program builds it",
sig.name
)),
}
}
std::panic::set_hook(hook);
assert!(
gaps.is_empty(),
"nodes the closure tier cannot run:\n {}",
gaps.join("\n ")
);
}
#[test]
fn every_parameter_example_is_a_passable_value() {
use polydat::ast::SlotType;
use polydat::dsl::factory::ConstArg;
let mut bad = Vec::new();
for sig in polydat::dsl::registry::registry() {
for p in sig.params {
let e = p.example;
let arg = match p.slot_type {
SlotType::Wire => {
if e != "cycle" {
bad.push(format!("{}.{}: wire example {e:?}", sig.name, p.name));
}
continue;
}
_ if e.is_empty() => continue,
SlotType::ConstU64 => e.parse().ok().map(ConstArg::Int),
SlotType::ConstF64 => e.parse().ok().map(ConstArg::Float),
SlotType::ConstStr => e
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
.map(|s| ConstArg::Str(s.to_string())),
_ => continue,
};
match arg {
None => bad.push(format!(
"{}.{}: {e:?} is not a {:?} literal",
sig.name, p.name, p.slot_type
)),
Some(a) => {
if let Some(Err(msg)) = p.constraint.map(|c| c.check(&a, p.name)) {
bad.push(format!("{}.{}: {e:?} refused: {msg}", sig.name, p.name));
}
}
}
}
}
assert!(
bad.is_empty(),
"examples a program cannot pass:\n {}",
bad.join("\n ")
);
}