polydat_core/dsl/factory.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Node factory: maps Polydat function names to runtime node instances.
5//!
6//! `build_node` is the single dispatch point used by the compiler's
7//! `compile_binding` to turn a parsed call expression into a `Box<dyn PolydatNode>`.
8//! `ConstArg` captures assembly-time constant arguments extracted from the AST.
9//!
10//! Dispatch is decentralized: each node module exposes its own `build_node`
11//! function returning `Option<Result<...>>`. The top-level `build_node` here
12//! tries each module in turn and falls back to the registry for variadic nodes.
13
14use crate::ast::PolydatNode;
15use crate::compile::assembly::WireRef;
16use crate::library::identity::ConstU64;
17
18use crate::dsl::registry;
19
20/// Constant arguments extracted from the AST.
21///
22/// Holds assembly-time values (integers, floats, strings, float arrays)
23/// that are baked into node constructors rather than passed as wire inputs.
24///
25/// `pub` visibility is required so that `NodeRegistration::build` function
26/// pointers (which are `pub` fields) can name this type.
27#[derive(Debug, Clone)]
28pub enum ConstArg {
29 /// An integer literal.
30 Int(u64),
31 /// A float literal.
32 Float(f64),
33 /// A string literal.
34 Str(String),
35 /// A list of float literals.
36 FloatArray(#[allow(dead_code)] Vec<f64>),
37 /// SRD-80b Phase C — workload-list const carrier for the
38 /// `Const<Vec<C>>` shape. Each inner [`ConstArg`] is one
39 /// element; `<Vec<C> as ConstSource>::extract` walks the
40 /// list and calls `C::extract` per element. Distinct from
41 /// `FloatArray` because the latter is the array-literal
42 /// lowering for the `ConstVecF64` slot type while `List`
43 /// is the typed-element variadic-const slot.
44 List(Vec<ConstArg>),
45}
46impl ConstArg {
47 /// Return the value as a `u64`, or 0 if incompatible.
48 pub fn as_u64(&self) -> u64 {
49 match self {
50 ConstArg::Int(v) => *v,
51 _ => 0,
52 }
53 }
54
55 /// Return the value as an `f64`, or 0.0 if incompatible.
56 ///
57 /// Integer literals are widened to f64.
58 pub fn as_f64(&self) -> f64 {
59 match self {
60 ConstArg::Float(v) => *v,
61 ConstArg::Int(v) => *v as f64,
62 _ => 0.0,
63 }
64 }
65
66 /// Return the value as a `&str`, or `""` if incompatible.
67 pub fn as_str(&self) -> &str {
68 match self {
69 ConstArg::Str(s) => s,
70 _ => "",
71 }
72 }
73
74 /// Return the value as a float slice, or `&[]` if incompatible.
75 #[allow(dead_code)]
76 pub fn as_float_array(&self) -> &[f64] {
77 match self {
78 ConstArg::FloatArray(v) => v,
79 _ => &[],
80 }
81 }
82}
83
84/// Source-binding attribution, set by the compiler before each
85/// `build_node` call and read by factories that want to record
86/// which DSL binding caused the node to exist. The
87/// `control_set` factory is the canonical consumer:
88/// `rate_adj := control_set("rate", target)` calls the factory
89/// with `current_binding()` returning `"rate_adj"`, which the
90/// node stores for runtime attribution in
91/// `ControlOrigin::Polydat { binding }`.
92pub mod compile_ctx {
93 use std::cell::RefCell;
94 thread_local! {
95 static BINDING: RefCell<Option<String>> = const { RefCell::new(None) };
96 }
97
98 /// Install the current binding name for the duration of a
99 /// single `build_node` call. Returns a guard that clears
100 /// the thread-local on drop so nested compilation can't
101 /// leak attribution across callers.
102 pub fn scoped_binding(name: &str) -> BindingScope {
103 BINDING.with(|b| *b.borrow_mut() = Some(name.to_string()));
104 BindingScope(())
105 }
106
107 /// Read the current binding attribution. Returns `None`
108 /// when called outside a [`scoped_binding`] scope (e.g.
109 /// ad-hoc tests that call [`super::build_node`] directly).
110 pub fn current_binding() -> Option<String> {
111 BINDING.with(|b| b.borrow().clone())
112 }
113
114 /// RAII guard that clears the binding slot on drop.
115 pub struct BindingScope(());
116 impl Drop for BindingScope {
117 fn drop(&mut self) {
118 BINDING.with(|b| *b.borrow_mut() = None);
119 }
120 }
121}
122
123/// Build the node `func` takes for the given wires, their types, and
124/// constant arguments, through the registry; an unknown function or a
125/// mismatched signature is an error naming it.
126///
127/// Dispatch order: inventory registrations (constraint checks, then
128/// the module validator, then `build`), then the registry's variadic
129/// fallback.
130pub fn build_node(
131 func: &str,
132 wires: &[WireRef],
133 wire_types: &[crate::ast::PortType],
134 consts: &[ConstArg],
135) -> Result<Box<dyn PolydatNode>, String> {
136 // --- Per-module dispatch via inventory ---
137
138 use crate::dsl::registry::NodeRegistration;
139 for reg in inventory::iter::<NodeRegistration> {
140 // Only run this module's validator if it owns `func`.
141 // Signatures are the authoritative "does this module
142 // handle this name" list — probing `build` first would
143 // invert the ordering (construction before validation)
144 // and give an opt-in validator no chance to reject bad
145 // constants before the constructor panics.
146 let sigs = (reg.signatures)();
147 let owning_sig = sigs.iter().find(|s| s.name == func);
148 if owning_sig.is_none() {
149 continue;
150 }
151 let sig = owning_sig.unwrap();
152
153 // Pass 1: walk declared `ParamSpec.constraint`s and run
154 // each per-param check. Constraints declared on individual
155 // params cover the bulk of "must be in [0,1]" /
156 // "must be one of {2,8,10,16}" / "spec must parse" cases.
157 // SRD 15 §"Const Constraint Metadata".
158 if let Err(msg) = check_param_constraints(sig, consts) {
159 return Err(format!("bad constant {func}: {msg}"));
160 }
161
162 // Pass 2: per-module imperative validator for relational
163 // and cross-param rules (e.g. `n_of`'s n ≤ m). Eventually
164 // migrates onto a `FuncSig.validator` field; until then,
165 // each module declares its relational constraint here.
166 if let Some(validator) = reg.validate
167 && let Err(reason) = validator(func, consts)
168 {
169 return Err(format!("bad constant {func}: {reason}"));
170 }
171
172 if let Some(result) = (reg.build)(func, wires, wire_types, consts) {
173 return result;
174 }
175 }
176
177 // --- Sampling functions without a dedicated node module ---
178 //
179 // `identity` migrated to `#[polydat_node]` per SRD-80 PR B.8.
180 // `dist_*` / `icd_*` / `histribution` / `dist_empirical`
181 // migrated to `#[polydat_node]` via `#[poly_const]` setup
182 // (SRD-80b Phase E); the inventory-registered build closure
183 // now handles each name, so the hand-dispatch arms here are
184 // gone.
185
186 // --- Registry variadic fallback ---
187 if let Some(sig) = registry::lookup(func)
188 && sig.is_variadic()
189 {
190 if wires.is_empty() {
191 if let Some(id) = sig.identity {
192 return Ok(Box::new(ConstU64::new(id)));
193 }
194 return Err(format!(
195 "variadic function '{func}' requires at least one input"
196 ));
197 }
198 if let Some(ctor) = sig.variadic_ctor {
199 return Ok(ctor(wires.len()));
200 }
201 }
202
203 let mut msg = format!("unknown function: '{func}'\n");
204 if let Some(suggestion) = registry::suggest_function(func) {
205 msg.push_str(&format!("\n Did you mean '{suggestion}'?"));
206 }
207 msg.push_str("\n\n This function is not registered in the wiring function library.");
208 msg.push_str("\n See the registered wiring functions for the available names.");
209 Err(msg)
210}
211
212/// Walk `sig.params`, applying every declared `ConstConstraint`
213/// to the corresponding positional `ConstArg`. Parameters with no
214/// constraint are skipped; missing optional arguments are skipped
215/// (the `required` flag handles mandatory presence elsewhere).
216fn check_param_constraints(
217 sig: &crate::dsl::registry::FuncSig,
218 consts: &[ConstArg],
219) -> Result<(), String> {
220 use crate::ast::SlotType;
221 // Const args appear in positional order, but `sig.params`
222 // mixes wire and const slots. Walk both in lockstep, pulling
223 // const args from a separate counter.
224 let mut const_idx = 0usize;
225 for spec in sig.params {
226 if matches!(spec.slot_type, SlotType::Wire) {
227 continue;
228 }
229 if let Some(constraint) = &spec.constraint
230 && let Some(arg) = consts.get(const_idx)
231 {
232 constraint.check(arg, spec.name)?;
233 }
234 const_idx += 1;
235 }
236 Ok(())
237}