polydat 0.5.2

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 (F-N12).
//!
//! The catalog used to be written by hand, and a hand-written listing
//! of a library that grows by attribute is wrong the week after it is
//! written. It was: it gave `hash.rs` one node where the file has
//! seven and `convert.rs` eleven where it has thirty-one, omitted
//! fourteen files outright, and documented names that are not nodes
//! and nodes that are not polydat's.
//!
//! 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
}

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

/// 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. The examples
/// used to be the parameters' names, which no program can pass.
#[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  ")
    );
}