polydat 0.11.0

Polydat — a variates construction engine
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! The node catalog in `docs/reference/nodes.md`, generated from the
//! registry.
//!
//! A hand-written listing of a library that grows by attribute is
//! wrong the week after it is written, so the listing is generated the way the engine matrix beside it
//! is: the test renders the section and fails when the file does not
//! match, and `NODES_REFERENCE=overwrite` writes it.
//!
//! The reference documents the whole library, so the check runs in
//! the configuration that has the whole library. A build without
//! `jit` or without `vectordata` registers fewer nodes, and the file
//! would be wrong about the build a reader most likely has if it were
//! written from the smaller one.

#![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 -->";

/// A description rendered into a table cell: one line, with the cell
/// separator escaped.
fn cell(text: &str) -> String {
    text.replace('|', r"\|").replace('\n', " ")
}

fn section() -> String {
    // `__`-prefixed names are the conversion adapters the assembler
    // inserts between a wire and a port of another type. A program
    // rarely calls one, so they are counted here and catalogued by the
    // type system.
    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
}

/// The overloaded names: each with the node it builds for each set of
/// operand types, the first of which it builds for any other.
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"
    );
}

/// A constant argument for `p`: its example when it has one a program
/// can pass, and otherwise a value of its slot's kind.
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),
    })
}

/// How the closure tier takes a node, as `node_step_op` does: a plain
/// copy, the u64 kit, or the slot kit for the wire types the node was
/// built over.
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()
}

/// Every registered node, adapters and dataset nodes included, has a
/// form the closure tier runs. A node is built from its signature,
/// with each constant its example and every wire of one port type (a
/// variadic node taking two), over every port type it accepts, and
/// must have a closure form over at least one of them. A node
/// whose constants no example supplies (a file path, a weighted spec,
/// a compiled tile) is built by its hand-written coverage program
/// instead, which the closure tier must build.
#[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();
    // A build a signature's synthesized constants cannot satisfy
    // panics, and the walk tries the next wire type; the default hook
    // would print every one of those.
    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  ")
    );
}

/// Every parameter's example is a value a program can pass: `cycle`
/// for a wire, and for a constant either nothing or a literal of its
/// slot's kind that its own declared constraint accepts. A parameter's
/// name is not an example, because no program can pass it.
#[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  ")
    );
}