polydat_core/dsl/registry.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Function registry: known function signatures for DSL validation.
5//!
6//! Each registered function declares its name, category, expected wire
7//! inputs, constant parameters, output count, and variadic behavior.
8//! The compiler uses this to validate calls at parse time and to
9//! generically dispatch variadic functions.
10//!
11//! Categories are a type-safe enum — every function must declare one.
12//! Categories group the registry for listings (`by_category`). The
13//! stdlib files carry a `// @category: Name` line for readers;
14//! `FuncCategory::parse` maps that text but no compile path consumes
15//! it.
16//!
17//! Signatures are owned by their respective node modules. This file
18//! defines the shared types and the collector function.
19
20pub use crate::ast::CompileLevel;
21use crate::compile::assembly::WireRef;
22use crate::dsl::factories::NodeFactory;
23
24/// Builder for a node module: `(build context, name, wires, resolved
25/// wire port types, const args) -> Some(Ok(node)) / Some(Err(msg))`,
26/// or `None` when the name isn't handled by this module. The build
27/// context carries the bindings under construction and the program
28/// tree's resource scope ([`crate::dsl::factory::BuildContext`]).
29pub type NodeBuildFn = fn(
30 &crate::dsl::factory::BuildContext,
31 &str,
32 &[WireRef],
33 &[crate::ast::PortType],
34 &[crate::dsl::factory::ConstArg],
35) -> Option<Result<Box<dyn crate::ast::PolydatNode>, String>>;
36
37/// A node module's registration: signatures + builder.
38///
39/// Each node module submits one of these at link time via `inventory::submit!`.
40/// The runtime collects all submissions to build the function registry and
41/// dispatch table without any explicit module list.
42///
43/// A registration is a [`NodeFactory`]: its `build` is the factory's
44/// body, and the registry builds its nodes through that factory as it
45/// builds every other node ([`crate::dsl::factory::build_node`]).
46pub struct NodeRegistration {
47 /// Returns the static slice of `FuncSig` entries for this module.
48 pub signatures: fn() -> &'static [FuncSig],
49 /// Builds a node for the given function name: the body of this
50 /// registration's [`NodeFactory::build`].
51 ///
52 /// Returns `Some(Ok(node))` / `Some(Err(msg))` for a name it
53 /// builds, and `None` for one it leaves to its signature: a
54 /// variadic function then gets its signature's identity element or
55 /// variadic constructor, and any other name is an unknown function.
56 ///
57 /// `wire_types[i]` is the resolved [`crate::ast::PortType`] of
58 /// `wires[i]` — the output type of the upstream node feeding
59 /// that wire input. Modules that build type-polymorphic nodes
60 /// (e.g. `log_info`, whose output type equals its input type)
61 /// read this to construct the node with the correct port
62 /// types. Modules whose nodes have type-fixed signatures can
63 /// ignore the slice. When the assembler can't resolve a
64 /// wire's type (forward reference, dangling), the slot
65 /// defaults to [`crate::ast::PortType::U64`].
66 pub build: NodeBuildFn,
67 /// Optional assembly-time validator for this module's constants.
68 ///
69 /// The factory calls this **before** `build` whenever the name
70 /// matches one of this module's functions. Returning `Err` makes
71 /// the compile fail with a structured `bad constant` error, so
72 /// the node itself never sees a malformed literal and can keep
73 /// its constructor and `eval()` branch-free.
74 pub validate: Option<crate::dsl::const_constraints::NodeValidator>,
75}
76
77inventory::collect!(NodeRegistration);
78
79impl NodeFactory for NodeRegistration {
80 fn signatures(&self) -> &[FuncSig] {
81 (self.signatures)()
82 }
83
84 fn validate(&self, name: &str, consts: &[crate::dsl::factory::ConstArg]) -> Result<(), String> {
85 match self.validate {
86 Some(validator) => validator(name, consts),
87 None => Ok(()),
88 }
89 }
90
91 /// The registered builder's node. A builder that declines a name its
92 /// signatures list leaves a variadic function to its signature: the
93 /// identity element for no wires, the variadic constructor otherwise.
94 fn build(
95 &self,
96 ctx: &crate::dsl::factory::BuildContext,
97 name: &str,
98 wires: &[WireRef],
99 wire_types: &[crate::ast::PortType],
100 consts: &[crate::dsl::factory::ConstArg],
101 ) -> Result<Box<dyn crate::ast::PolydatNode>, String> {
102 if let Some(result) = (self.build)(ctx, name, wires, wire_types, consts) {
103 return result;
104 }
105 let sig = (self.signatures)().iter().find(|s| s.name == name);
106 match sig {
107 Some(sig) => crate::dsl::factory::variadic_node(sig, wires.len()),
108 None => Err(format!("unknown function: '{name}'")),
109 }
110 }
111}
112
113/// A host's own [`NodeFactory`], linked into the registry.
114///
115/// A host submits one at link time, as a node module submits its
116/// [`NodeRegistration`]:
117///
118/// ```ignore
119/// static FACTORY: MyFactory = MyFactory;
120/// polydat::inventory::submit! {
121/// polydat::dsl::registry::FactoryRegistration { factory: &FACTORY }
122/// }
123/// ```
124///
125/// The registry lists the factory's signatures and builds every call to
126/// one of them through its `build`, on every engine.
127pub struct FactoryRegistration {
128 /// The factory.
129 pub factory: &'static dyn NodeFactory,
130}
131
132inventory::collect!(FactoryRegistration);
133
134/// Every factory linked into the registry: each node module's
135/// [`NodeRegistration`], then each host [`FactoryRegistration`]. A
136/// function name belongs to the first factory whose signatures list it.
137pub fn factories() -> impl Iterator<Item = &'static dyn NodeFactory> {
138 inventory::iter::<NodeRegistration>
139 .into_iter()
140 .map(|reg| reg as &'static dyn NodeFactory)
141 .chain(
142 inventory::iter::<FactoryRegistration>
143 .into_iter()
144 .map(|reg| reg.factory),
145 )
146}
147
148/// A function name that stands for one node per argument type, as
149/// `vec_dot` stands for `vec_dot_f32` and `vec_dot_f64`
150/// (polydat_grammar.md §18.1, `T-Call-OverloadResolve`).
151///
152/// A call to the name builds, among the forms every operand reaches by
153/// its own type or through a lossless adapter, the one agreeing with
154/// the most of the call's wire types, position by position, and the
155/// earliest such form when several agree with as many
156/// ([`Overload::resolve`]). The assembler's adapters then reach the
157/// form's other ports, as they reach any node's. So `vec_scale(v, 2)`
158/// over a `vec_f64` builds the f64 form and widens the integer, and
159/// `vec_dot(a_f64, b_f32)` builds the f64 form and widens `b`, rather
160/// than narrowing an operand to reach a form. The first form is the one
161/// the name meant before it had others, so operands that reach every
162/// form equally build it, and a program that compiled against the name
163/// still does. A node module submits one at
164/// link time:
165///
166/// ```ignore
167/// polydat::inventory::submit! {
168/// Overload::new(
169/// "vec_dot",
170/// &[
171/// OverloadForm::new(&[PortType::VecF32, PortType::VecF32], "vec_dot_f32"),
172/// OverloadForm::new(&[PortType::VecF64, PortType::VecF64], "vec_dot_f64"),
173/// ],
174/// )
175/// }
176/// ```
177///
178/// Every form takes the same parameters in the same order, so the name's
179/// parameters are those of any form; only the wires' types differ.
180///
181/// Built with [`Overload::new`], a `const fn`, so a field added later
182/// does not break the hosts that submit one.
183#[non_exhaustive]
184pub struct Overload {
185 /// The name programs call.
186 pub name: &'static str,
187 /// The forms the name resolves to, the default first.
188 pub forms: &'static [OverloadForm],
189}
190
191/// One form of an [`Overload`]: the registered function a call builds
192/// when its wires have these types. Built with [`OverloadForm::new`].
193#[non_exhaustive]
194pub struct OverloadForm {
195 /// The port types of the form's wire inputs, in order.
196 pub wires: &'static [crate::ast::PortType],
197 /// The registered function this form builds.
198 pub func: &'static str,
199}
200
201impl OverloadForm {
202 /// The form that builds `func` for wires of the types `wires`.
203 pub const fn new(wires: &'static [crate::ast::PortType], func: &'static str) -> Self {
204 Self { wires, func }
205 }
206}
207
208inventory::collect!(Overload);
209
210impl Overload {
211 /// The overloaded name `name` of `forms`, the default first. A
212 /// node module submits it with `inventory::submit!`.
213 pub const fn new(name: &'static str, forms: &'static [OverloadForm]) -> Self {
214 Self { name, forms }
215 }
216
217 /// The function a call whose wires have `wire_types` builds.
218 ///
219 /// Among the forms every wire reaches, by its own type or through
220 /// a lossless adapter ([`auto_adapter`]), the one agreeing with the
221 /// most of the wire types, the earliest among equals. So
222 /// `vec_dot(a_f64, b_f32)` builds the f64 form and widens `b`,
223 /// rather than narrowing `a`. When no form is reachable so, the
224 /// form agreeing with the most wire types, the earliest among
225 /// equals, and the assembler names the operand it cannot connect.
226 ///
227 /// [`auto_adapter`]: crate::compile::assembly::auto_adapter
228 pub fn resolve(&self, wire_types: &[crate::ast::PortType]) -> &'static str {
229 let agreement = |form: &OverloadForm| {
230 form.wires
231 .iter()
232 .zip(wire_types)
233 .filter(|(declared, given)| declared == given)
234 .count()
235 };
236 let reachable = |form: &OverloadForm| {
237 form.wires.iter().zip(wire_types).all(|(declared, given)| {
238 declared == given
239 || crate::compile::assembly::auto_adapter(*given, *declared).is_some()
240 })
241 };
242 let best_of = |forms: &mut dyn Iterator<Item = &'static OverloadForm>| {
243 let mut best: Option<&'static OverloadForm> = None;
244 for form in forms {
245 if best.is_none_or(|b| agreement(form) > agreement(b)) {
246 best = Some(form);
247 }
248 }
249 best
250 };
251 best_of(&mut self.forms.iter().filter(|f| reachable(f)))
252 .or_else(|| best_of(&mut self.forms.iter()))
253 .map_or(self.forms[0].func, |form| form.func)
254 }
255
256 /// The signature of the first form, which a call to the name is
257 /// checked against before its wire types are known: every form
258 /// shares its parameters. Its `name` is the form's, such as
259 /// `vec_dot_f32`, not the overload's. `None` only when the first
260 /// form names no registered function.
261 pub fn signature(&self) -> Option<&'static FuncSig> {
262 lookup_registered(self.forms[0].func)
263 }
264
265 /// The category the name is listed under: its first form's, or
266 /// [`FuncCategory::Uncategorised`] when the first form names no
267 /// registered function.
268 pub fn category(&self) -> FuncCategory {
269 self.signature()
270 .map_or(FuncCategory::Uncategorised, |sig| sig.category)
271 }
272}
273
274/// Every overloaded name linked into the registry.
275pub fn overloads() -> impl Iterator<Item = &'static Overload> {
276 inventory::iter::<Overload>.into_iter()
277}
278
279/// The overloaded name `name`, if it is one.
280pub fn overload(name: &str) -> Option<&'static Overload> {
281 overloads().find(|o| o.name == name)
282}
283
284/// The function a call to `name` with wires of `wire_types` builds:
285/// the resolved form when `name` is an [`Overload`], `name` itself
286/// otherwise.
287pub fn resolve_call<'a>(name: &'a str, wire_types: &[crate::ast::PortType]) -> &'a str {
288 overload(name).map_or(name, |o| o.resolve(wire_types))
289}
290
291/// Every overloaded name, grouped by its [`Overload::category`] in
292/// display order and sorted by name within a category: the names
293/// [`by_category`] leaves out, since it lists registered functions.
294/// A listing of what a program can call shows both.
295///
296/// An overload whose first form names no registered function is
297/// listed under [`FuncCategory::Uncategorised`], last; nothing can call
298/// it, and [`unlisted_overloads`] names those registration errors.
299pub fn overloads_by_category() -> Vec<(FuncCategory, Vec<&'static Overload>)> {
300 let mut groups: std::collections::HashMap<FuncCategory, Vec<&'static Overload>> =
301 std::collections::HashMap::new();
302 for o in overloads() {
303 groups.entry(o.category()).or_default().push(o);
304 }
305 FuncCategory::display_order()
306 .iter()
307 .filter_map(|cat| {
308 groups.remove(cat).map(|mut names| {
309 names.sort_unstable_by_key(|o| o.name);
310 (*cat, names)
311 })
312 })
313 .collect()
314}
315
316/// Every overload whose first form names no registered function,
317/// sorted by name: a registration error, such as a misspelled form or
318/// a form whose module is not linked. [`lookup`] answers `None` for
319/// these names and [`overloads_by_category`] lists them under
320/// [`FuncCategory::Uncategorised`], so a host checks that this is
321/// empty, in a test or at startup, to find its own broken
322/// registrations.
323pub fn unlisted_overloads() -> Vec<&'static Overload> {
324 let mut unlisted: Vec<_> = overloads().filter(|o| o.signature().is_none()).collect();
325 unlisted.sort_unstable_by_key(|o| o.name);
326 unlisted
327}
328
329/// Register a node module's signatures and builder with the Polydat runtime.
330///
331/// Place this call at module scope in each node module. The inventory crate
332/// arranges for the registration to run before `main` so that `registry()`
333/// and `build_node()` see all entries.
334///
335/// Two forms:
336///
337/// - `register_nodes!(signatures, build_node)` — no assembly-time
338/// validation. The builder is responsible for handling any bad
339/// input itself (usually by trusting the caller or panicking).
340/// - `register_nodes!(signatures, build_node, validate_node)` — the
341/// factory calls `validate_node(name, consts)` before `build_node`.
342/// Use this to declare [`ConstConstraint`]-style checks so
343/// constructors can stay infallible.
344///
345/// [`ConstConstraint`]: crate::dsl::const_constraints::ConstConstraint
346#[macro_export]
347macro_rules! register_nodes {
348 ($sigs:expr, $builder:expr) => {
349 inventory::submit! {
350 $crate::dsl::registry::NodeRegistration {
351 signatures: $sigs,
352 build: $builder,
353 validate: None,
354 }
355 }
356 };
357 ($sigs:expr, $builder:expr, $validator:expr) => {
358 inventory::submit! {
359 $crate::dsl::registry::NodeRegistration {
360 signatures: $sigs,
361 build: $builder,
362 validate: Some($validator),
363 }
364 }
365 };
366}
367
368/// Functional category for a Polydat node function.
369///
370/// Every native node and stdlib module belongs to exactly one category.
371/// Categories group the registry for listings (`by_category`) and provide
372/// semantic organization for documentation and discovery.
373///
374/// The set grows as the library does, so a `match` over it outside
375/// this crate needs a `_` arm.
376#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
377#[non_exhaustive]
378pub enum FuncCategory {
379 /// Core deterministic hashing.
380 Hashing,
381 /// Integer arithmetic with constant parameters.
382 Arithmetic,
383 /// Comparison and selection: ==, !=, <, >, <=, >=, if(...).
384 /// Comparison nodes return u64 truth values (0 or 1); select
385 /// nodes pick between two operand values based on a u64 cond.
386 Comparison,
387 /// Variadic N-ary operations (sum, product, min, max).
388 Variadic,
389 /// Type conversions between u64, f64, String, etc.
390 Conversions,
391 /// Statistical distribution LUT builders and samplers.
392 Distributions,
393 /// Date and time generation and decomposition.
394 Datetime,
395 /// HTML, URL, hex, base64 encoding/decoding.
396 Encoding,
397 /// Linear interpolation, range mapping, quantization.
398 Interpolation,
399 /// Trigonometric and mathematical functions (sin, cos, sqrt, etc.).
400 Math,
401 /// Probability modeling: coins, selection, conditionals.
402 Probability,
403 /// Weighted categorical selection.
404 Weighted,
405 /// Printf-style and structured string formatting.
406 Formatting,
407 /// String generation: combinations, number words.
408 String,
409 /// JSON construction, serialization, merging.
410 Json,
411 /// Byte buffer construction and manipulation.
412 ByteBuffers,
413 /// Cryptographic and non-cryptographic digests.
414 Digest,
415 /// Coherent noise: Perlin, simplex.
416 Noise,
417 /// Regular expression matching and substitution.
418 Regex,
419 /// Bijective permutations and shuffles.
420 Permutation,
421 /// Real-world data: names, places, codes.
422 RealData,
423 /// Non-deterministic context: wall clock, counters.
424 Context,
425 /// Debugging and introspection.
426 Diagnostic,
427 /// File-based data access: CSV, JSONL, text files.
428 Data,
429 /// No category: an [`Overload`] whose first form names no
430 /// registered function, listed here by [`overloads_by_category`]
431 /// so a listing shows the broken registration instead of leaving
432 /// it out ([`unlisted_overloads`]). No registered function has it.
433 Uncategorised,
434}
435
436impl FuncCategory {
437 /// Display name for the category (used in describe output).
438 pub fn display_name(&self) -> &'static str {
439 match self {
440 Self::Hashing => "Hashing",
441 Self::Arithmetic => "Arithmetic",
442 Self::Comparison => "Comparison",
443 Self::Variadic => "Variadic",
444 Self::Conversions => "Conversions",
445 Self::Distributions => "Distributions",
446 Self::Datetime => "Datetime",
447 Self::Encoding => "Encoding",
448 Self::Interpolation => "Interpolation",
449 Self::Math => "Math",
450 Self::Probability => "Probability",
451 Self::Weighted => "Weighted",
452 Self::Formatting => "Formatting",
453 Self::String => "String",
454 Self::Json => "JSON",
455 Self::ByteBuffers => "Byte Buffers",
456 Self::Digest => "Digest",
457 Self::Noise => "Noise",
458 Self::Regex => "Regex",
459 Self::Permutation => "Permutation",
460 Self::RealData => "Real Data",
461 Self::Context => "Context",
462 Self::Diagnostic => "Diagnostic",
463 Self::Data => "Data",
464 Self::Uncategorised => "Uncategorised",
465 }
466 }
467
468 /// Parse a category name from a string (case-insensitive): the
469 /// text of a stdlib file's `// @category: Name` line. No compile
470 /// path consumes it.
471 pub fn parse(s: &str) -> Option<Self> {
472 match s.trim().to_lowercase().as_str() {
473 "hashing" => Some(Self::Hashing),
474 "arithmetic" => Some(Self::Arithmetic),
475 "comparison" | "compare" => Some(Self::Comparison),
476 "variadic" => Some(Self::Variadic),
477 "conversions" | "conversion" => Some(Self::Conversions),
478 "distributions" | "distribution" => Some(Self::Distributions),
479 "datetime" | "date" | "time" => Some(Self::Datetime),
480 "encoding" => Some(Self::Encoding),
481 "interpolation" | "lerp" => Some(Self::Interpolation),
482 "math" | "trig" | "trigonometry" => Some(Self::Math),
483 "probability" => Some(Self::Probability),
484 "weighted" => Some(Self::Weighted),
485 "formatting" | "format" | "printf" => Some(Self::Formatting),
486 "string" | "strings" => Some(Self::String),
487 "json" => Some(Self::Json),
488 "byte buffers" | "bytebuffers" | "bytes" => Some(Self::ByteBuffers),
489 "digest" => Some(Self::Digest),
490 "noise" => Some(Self::Noise),
491 "regex" => Some(Self::Regex),
492 "permutation" | "shuffle" => Some(Self::Permutation),
493 "real data" | "realdata" | "realer" => Some(Self::RealData),
494 "context" => Some(Self::Context),
495 "diagnostic" | "diagnostics" | "debug" => Some(Self::Diagnostic),
496 "data" | "datafile" | "csv" | "jsonl" => Some(Self::Data),
497 "uncategorised" | "uncategorized" => Some(Self::Uncategorised),
498 _ => None,
499 }
500 }
501
502 /// Canonical ordering for display (same order as the enum definition).
503 pub fn display_order() -> &'static [Self] {
504 &[
505 Self::Hashing,
506 Self::Arithmetic,
507 Self::Comparison,
508 Self::Variadic,
509 Self::Conversions,
510 Self::Distributions,
511 Self::Datetime,
512 Self::Encoding,
513 Self::Interpolation,
514 Self::Math,
515 Self::Probability,
516 Self::Weighted,
517 Self::Formatting,
518 Self::String,
519 Self::Json,
520 Self::ByteBuffers,
521 Self::Digest,
522 Self::Noise,
523 Self::Regex,
524 Self::Permutation,
525 Self::RealData,
526 Self::Context,
527 Self::Diagnostic,
528 Self::Data,
529 Self::Uncategorised,
530 ]
531 }
532}
533
534// ---------------------------------------------------------------------------
535// Unified parameter specification (library_catalog.md, "Shapes")
536// ---------------------------------------------------------------------------
537
538use crate::ast::SlotType;
539
540/// Describes one parameter in a function's call signature.
541///
542/// A "slot template" — the type-level version of a `Slot` without
543/// a concrete value. Parameters are listed in positional order
544/// matching the DSL syntax.
545///
546/// A parameter is built with [`ParamSpec::new`] or [`ParamSpec::wire`]
547/// and the `with_` methods, all `const`, so a signature can live in a
548/// `static`. The struct is `#[non_exhaustive]`: a field added later is
549/// not a breaking change to a host that builds one.
550#[derive(Debug, Clone, Copy)]
551#[non_exhaustive]
552pub struct ParamSpec {
553 /// Parameter name (for error messages and describe output).
554 pub name: &'static str,
555 /// Wire or constant, and if constant, what type.
556 pub slot_type: SlotType,
557 /// Whether this parameter must be provided.
558 pub required: bool,
559 /// Example value for this parameter, as program text, used for
560 /// probing compile level and for documentation. Wire params use
561 /// `"cycle"`; a const param with a declared default uses that
562 /// default, which passes validation; a const param without one is
563 /// empty, since the signature offers no value to show.
564 pub example: &'static str,
565 /// Optional assembly-time validation rule. The factory enforces this before
566 /// `build_node` so node constructors can stay infallible and
567 /// branch-free at runtime. `None` = no constraint declared
568 /// (default for wires and unconstrained constants).
569 pub constraint: Option<crate::dsl::const_constraints::ConstConstraint>,
570}
571
572impl ParamSpec {
573 /// A required parameter `name` of the slot type `slot_type`, with no
574 /// constraint. Its example is `cycle` for a wire, which every
575 /// program can pass, and empty for a constant, which has none to
576 /// offer until [`Self::with_example`] gives one.
577 pub const fn new(name: &'static str, slot_type: SlotType) -> Self {
578 Self {
579 name,
580 slot_type,
581 required: true,
582 example: if matches!(slot_type, SlotType::Wire) {
583 "cycle"
584 } else {
585 ""
586 },
587 constraint: None,
588 }
589 }
590
591 /// A required wire parameter `name`.
592 pub const fn wire(name: &'static str) -> Self {
593 Self::new(name, SlotType::Wire)
594 }
595
596 /// The parameter, but one a call may leave out: a constant with a
597 /// default, or a variadic tail that may be empty.
598 pub const fn optional(mut self) -> Self {
599 self.required = false;
600 self
601 }
602
603 /// The parameter with `example` as its example value, written as
604 /// program text.
605 pub const fn with_example(mut self, example: &'static str) -> Self {
606 self.example = example;
607 self
608 }
609
610 /// The parameter with the constraint `c`, which the factory checks
611 /// before it builds the node.
612 pub const fn with_constraint(
613 mut self,
614 c: crate::dsl::const_constraints::ConstConstraint,
615 ) -> Self {
616 self.constraint = Some(c);
617 self
618 }
619}
620
621/// Arity specification for a function signature.
622///
623/// Describes which parts of the parameter list are fixed vs repeatable.
624#[derive(Debug, Clone, Default)]
625pub enum Arity {
626 /// Exactly the parameters declared in `params`.
627 #[default]
628 Fixed,
629 /// Trailing wire parameters repeat (sum, product, min, max).
630 VariadicWires {
631 /// The fewest trailing wires allowed.
632 min_wires: usize,
633 },
634 /// Trailing constant parameters repeat (mixed_radix).
635 VariadicConsts {
636 /// The fewest trailing constants allowed.
637 min_consts: usize,
638 },
639 /// A repeating group of slot types (weighted_sum).
640 VariadicGroup {
641 /// The slot types of one repetition, in order.
642 group: &'static [SlotType],
643 /// The fewest repetitions allowed.
644 min_repeats: usize,
645 },
646}
647
648/// Output-type contract for a registered function.
649///
650/// Most nodes have fixed port types declared by their constructor's
651/// `NodeMeta`. Some — `log_info`, `identity`, anything documented
652/// as "pass-through" — produce an output whose type matches one
653/// of their inputs. Declaring this here makes the contract visible
654/// to the assembler, the build-node dispatch path, registry
655/// listings, and any future static analysis, instead of being
656/// buried inside an `eval` that silently passes values through a
657/// wire whose declared type lies.
658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
659pub enum OutputType {
660 /// Output types are whatever the constructor's `NodeMeta`
661 /// declares — independent of input wire types. The default;
662 /// covers the vast majority of nodes (`hash`, `regex_match`,
663 /// `mod`, …) whose I/O contract is type-fixed.
664 Fixed,
665 /// The function's single output port has the same type as the
666 /// input wire at the given index. The build dispatch resolves
667 /// the wire's type from the assembler and the module's
668 /// `build_node` reads it from the supplied `wire_types` slice
669 /// to construct a port-typed node. Used by pass-through
670 /// nodes (`log_info`, `log_debug`, …).
671 SameAsInput(usize),
672}
673
674/// Description of a registered function's signature.
675///
676/// A signature is built with [`FuncSig::new`] and the `with_` methods,
677/// all `const`, so a module's signatures can live in a `static`:
678///
679/// ```
680/// use polydat_core::ast::{PortType, SlotType};
681/// use polydat_core::dsl::registry::{FuncCategory, FuncSig, ParamSpec};
682///
683/// static SIGS: &[FuncSig] = &[FuncSig::new(
684/// "counted_mod",
685/// FuncCategory::Arithmetic,
686/// &[ParamSpec::wire("x"), ParamSpec::new("m", SlotType::ConstU64).with_example("7")],
687/// )
688/// .with_description("mod, built by a host factory")
689/// .with_output_port(PortType::U64)];
690/// # assert_eq!(SIGS[0].outputs, 1);
691/// ```
692///
693/// The struct is `#[non_exhaustive]`: a field added later is not a
694/// breaking change to a host that builds one, since the new field
695/// arrives with its default.
696#[non_exhaustive]
697pub struct FuncSig {
698 /// Function name as used in the DSL.
699 pub name: &'static str,
700 /// Functional category.
701 pub category: FuncCategory,
702 /// Number of output ports (0 = dynamic, determined at compile time).
703 pub outputs: usize,
704 /// Short description for help/error messages.
705 pub description: &'static str,
706 /// Detailed help text: theory, usage examples, parameter meanings.
707 /// Long-form help text for listings and documentation.
708 pub help: &'static str,
709 /// For variadic functions: the identity element for zero inputs.
710 pub identity: Option<u64>,
711 /// Factory for variadic nodes: takes wire count, returns node.
712 pub variadic_ctor: Option<fn(usize) -> Box<dyn crate::ast::PolydatNode>>,
713 /// Positional parameter list: wires and constants in call order.
714 pub params: &'static [ParamSpec],
715 /// Arity specification.
716 pub arity: Arity,
717 /// Input commutativity for this function.
718 pub commutativity: crate::ast::Commutativity,
719 /// Optional resolver hint for `Handle`-typed input ports. When
720 /// the binding compiler emits this function and a `Handle`
721 /// input is wired to a `Str`-producing source, it splices in
722 /// the named resolver to convert the string into a handle. This
723 /// is the "string-conversion node insertion" mechanism of
724 /// source-string call-site sugar. `None` means no
725 /// auto-promotion — the caller must pass a `Handle` directly.
726 pub default_resolver: Option<DefaultResolver>,
727 /// Output-type contract — `Fixed` for the vast majority of
728 /// nodes; `SameAsInput(idx)` for type-polymorphic pass-throughs
729 /// (e.g. `log_info` whose output type tracks its sole input).
730 pub output_type: OutputType,
731 /// Concrete port type of the single output, when statically
732 /// known (`#[polydat_node]` emits it from the return type's
733 /// `Wire::PORT`). `None` for tuple/dynamic/polymorphic outputs
734 /// and for hand registrations that don't declare one. The DSL
735 /// type inference (`binding::infer_expr_type`) reads this
736 /// FIRST — the name-prefix heuristic is only the fallback —
737 /// so call-expression operand typing flows from the symbol
738 /// registry, not from a hand-maintained list.
739 pub output_port: Option<crate::ast::PortType>,
740}
741
742/// Auto-resolver kind attached to handle-taking functions. Tells the
743/// binding compiler which resolver to splice in when a string source
744/// is wired to a handle input port.
745#[derive(Debug, Clone, Copy)]
746pub enum DefaultResolver {
747 /// Insert `dataset_open(<source_wire>, "<facet>")` between the
748 /// string source and the handle input.
749 Facet(&'static str),
750 /// Insert `dataset_group_open(<source_wire>)` between the string
751 /// source and the handle input.
752 Group,
753}
754
755impl FuncSig {
756 /// The signature of `name` in `category` taking `params`: one
757 /// output of a fixed type not stated here, a fixed arity, positional
758 /// inputs, no description or help, and none of the optional parts.
759 /// The `with_` methods change each of these.
760 pub const fn new(
761 name: &'static str,
762 category: FuncCategory,
763 params: &'static [ParamSpec],
764 ) -> Self {
765 Self {
766 name,
767 category,
768 outputs: 1,
769 description: "",
770 help: "",
771 identity: None,
772 variadic_ctor: None,
773 params,
774 arity: Arity::Fixed,
775 commutativity: crate::ast::Commutativity::Positional,
776 default_resolver: None,
777 output_type: OutputType::Fixed,
778 output_port: None,
779 }
780 }
781
782 /// The signature with `outputs` output ports (0 for a count fixed at
783 /// compile time).
784 pub const fn with_outputs(mut self, outputs: usize) -> Self {
785 self.outputs = outputs;
786 self
787 }
788
789 /// The signature with the short description `description`.
790 pub const fn with_description(mut self, description: &'static str) -> Self {
791 self.description = description;
792 self
793 }
794
795 /// The signature with the long-form help text `help`.
796 pub const fn with_help(mut self, help: &'static str) -> Self {
797 self.help = help;
798 self
799 }
800
801 /// The signature of a variadic function whose identity element, for
802 /// zero inputs, is `identity`.
803 pub const fn with_identity(mut self, identity: u64) -> Self {
804 self.identity = Some(identity);
805 self
806 }
807
808 /// The signature of a variadic function whose node for a given
809 /// wire count `ctor` builds.
810 pub const fn with_variadic_ctor(
811 mut self,
812 ctor: fn(usize) -> Box<dyn crate::ast::PolydatNode>,
813 ) -> Self {
814 self.variadic_ctor = Some(ctor);
815 self
816 }
817
818 /// The signature with the arity `arity`.
819 pub const fn with_arity(mut self, arity: Arity) -> Self {
820 self.arity = arity;
821 self
822 }
823
824 /// The signature with the input commutativity `commutativity`.
825 pub const fn with_commutativity(mut self, commutativity: crate::ast::Commutativity) -> Self {
826 // `Commutativity::Groups` owns a `Vec`, so a `const fn` cannot
827 // drop the value it replaces and forgets it instead. A static
828 // signature cannot hold a `Groups` (no `Vec` is built in a
829 // `const` context), so what is forgotten there owns nothing;
830 // a runtime caller replacing a `Groups` leaks its lists.
831 let replaced = std::mem::replace(&mut self.commutativity, commutativity);
832 std::mem::forget(replaced);
833 self
834 }
835
836 /// The signature whose `Handle` inputs, wired from a `Str`, are
837 /// resolved by `resolver`.
838 pub const fn with_default_resolver(mut self, resolver: DefaultResolver) -> Self {
839 self.default_resolver = Some(resolver);
840 self
841 }
842
843 /// The signature with the output-type contract `output_type`.
844 pub const fn with_output_type(mut self, output_type: OutputType) -> Self {
845 self.output_type = output_type;
846 self
847 }
848
849 /// The signature whose single output has the port type `port`.
850 pub const fn with_output_port(mut self, port: crate::ast::PortType) -> Self {
851 self.output_port = Some(port);
852 self
853 }
854
855 /// Number of wire inputs in the fixed parameter list.
856 pub fn wire_input_count(&self) -> usize {
857 self.params.iter().filter(|p| p.slot_type.is_wire()).count()
858 }
859
860 /// Whether this function accepts variadic arguments.
861 pub fn is_variadic(&self) -> bool {
862 !matches!(self.arity, Arity::Fixed)
863 }
864
865 /// Constant parameter names and whether they're required.
866 pub fn const_param_info(&self) -> Vec<(&'static str, bool)> {
867 self.params
868 .iter()
869 .filter(|p| p.slot_type.is_const())
870 .map(|p| (p.name, p.required))
871 .collect()
872 }
873}
874
875impl std::fmt::Debug for FuncSig {
876 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
877 f.debug_struct("FuncSig")
878 .field("name", &self.name)
879 .field("category", &self.category)
880 .field("params", &self.params)
881 .field("arity", &self.arity)
882 .finish()
883 }
884}
885
886impl Clone for FuncSig {
887 fn clone(&self) -> Self {
888 Self {
889 name: self.name,
890 category: self.category,
891 outputs: self.outputs,
892 description: self.description,
893 help: self.help,
894 identity: self.identity,
895 variadic_ctor: self.variadic_ctor,
896 params: self.params,
897 arity: self.arity.clone(),
898 commutativity: self.commutativity.clone(),
899 default_resolver: self.default_resolver,
900 output_type: self.output_type,
901 output_port: self.output_port,
902 }
903 }
904}
905
906/// Return the full registry of known functions: the signatures of every
907/// linked factory ([`factories`]).
908pub fn registry() -> Vec<FuncSig> {
909 let mut funcs = Vec::new();
910 for factory in factories() {
911 funcs.extend_from_slice(factory.signatures());
912 }
913 funcs
914}
915
916/// Return functions grouped by category in display order.
917pub fn by_category() -> Vec<(FuncCategory, Vec<FuncSig>)> {
918 let reg = registry();
919 let mut groups: std::collections::HashMap<FuncCategory, Vec<FuncSig>> =
920 std::collections::HashMap::new();
921 for sig in reg {
922 groups.entry(sig.category).or_default().push(sig);
923 }
924 FuncCategory::display_order()
925 .iter()
926 .filter_map(|cat| groups.remove(cat).map(|funcs| (*cat, funcs)))
927 .collect()
928}
929
930/// Find the closest function name to a misspelling, among the
931/// registered functions and the [`Overload`] names.
932pub fn suggest_function(name: &str) -> Option<&'static str> {
933 let reg = registry();
934 let names = reg
935 .iter()
936 .map(|sig| sig.name)
937 .chain(overloads().map(|o| o.name));
938 let mut best: Option<(&str, usize)> = None;
939 for candidate in names {
940 let dist = edit_distance(name, candidate);
941 if dist <= 3 && (best.is_none() || dist < best.unwrap().1) {
942 best = Some((candidate, dist));
943 }
944 }
945 best.map(|(name, _)| name)
946}
947
948/// The signature of what a program calls by `name`: the registered
949/// function `name`, or, for an [`Overload`] such as `vec_dot`, its
950/// first form's ([`Overload::signature`]), whose parameters every form
951/// shares. `None` means no call to `name` can build. For an overload
952/// the signature's `name` is the form's, such as `vec_dot_f32`;
953/// [`resolve_call`] names the form a call with given wire types builds,
954/// and [`lookup_registered`] answers only for registered functions.
955/// Every factory is `'static`, so its signatures are too, and no
956/// allocation is needed.
957pub fn lookup(name: &str) -> Option<&'static FuncSig> {
958 lookup_registered(name).or_else(|| overload(name).and_then(Overload::signature))
959}
960
961/// Find a registered function by its exact name: the signature of the
962/// factory that builds it. Unlike [`lookup`], it answers `None` for an
963/// overloaded name, which no factory builds itself.
964pub fn lookup_registered(name: &str) -> Option<&'static FuncSig> {
965 factories().find_map(|factory| factory.signatures().iter().find(|sig| sig.name == name))
966}
967
968fn edit_distance(a: &str, b: &str) -> usize {
969 let a: Vec<char> = a.chars().collect();
970 let b: Vec<char> = b.chars().collect();
971 let mut matrix = vec![vec![0usize; b.len() + 1]; a.len() + 1];
972 for (i, row) in matrix.iter_mut().enumerate() {
973 row[0] = i;
974 }
975 for (j, cell) in matrix[0].iter_mut().enumerate() {
976 *cell = j;
977 }
978 for i in 1..=a.len() {
979 for j in 1..=b.len() {
980 let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
981 matrix[i][j] = (matrix[i - 1][j] + 1)
982 .min(matrix[i][j - 1] + 1)
983 .min(matrix[i - 1][j - 1] + cost);
984 }
985 }
986 matrix[a.len()][b.len()]
987}
988
989#[cfg(test)]
990mod tests {
991 use super::*;
992
993 #[test]
994 fn suggest_no_match() {
995 assert_eq!(suggest_function("zzzzzzzzz"), None);
996 }
997
998 #[test]
999 fn lookup_missing() {
1000 assert!(lookup("nonexistent").is_none());
1001 }
1002
1003 #[test]
1004 fn every_function_has_category() {
1005 let reg = registry();
1006 for sig in ® {
1007 // Just verify the category display name is non-empty
1008 assert!(
1009 !sig.category.display_name().is_empty(),
1010 "function '{}' has no category display name",
1011 sig.name
1012 );
1013 }
1014 }
1015
1016 #[test]
1017 fn lookup_answers_for_an_overloaded_name_and_lookup_registered_does_not() {
1018 for o in overloads().filter(|o| lookup_registered(o.forms[0].func).is_some()) {
1019 let sig = lookup(o.name).unwrap_or_else(|| panic!("{} is not callable", o.name));
1020 assert_eq!(sig.name, o.forms[0].func, "{}", o.name);
1021 assert!(lookup_registered(o.name).is_none(), "{}", o.name);
1022 }
1023 }
1024
1025 #[test]
1026 fn overloads_by_category_lists_every_overload_once() {
1027 let listed: usize = overloads_by_category().iter().map(|(_, o)| o.len()).sum();
1028 assert_eq!(listed, overloads().count());
1029 }
1030
1031 // An overload whose first form is not registered, as a host's
1032 // misspelled registration would be.
1033 inventory::submit! {
1034 Overload::new(
1035 "registry_test_misspelled_overload",
1036 &[OverloadForm::new(
1037 &[crate::ast::PortType::U64],
1038 "registry_test_no_such_function",
1039 )],
1040 )
1041 }
1042
1043 #[test]
1044 fn an_overload_of_no_registered_function_is_uncategorised_and_uncallable() {
1045 let name = "registry_test_misspelled_overload";
1046 let unlisted: Vec<_> = unlisted_overloads().iter().map(|o| o.name).collect();
1047 assert_eq!(unlisted, [name]);
1048 assert!(lookup(name).is_none());
1049 let (category, names) = overloads_by_category()
1050 .pop()
1051 .expect("the misspelled overload is listed");
1052 assert_eq!(category, FuncCategory::Uncategorised);
1053 assert_eq!(names.iter().map(|o| o.name).collect::<Vec<_>>(), [name]);
1054 }
1055
1056 #[test]
1057 fn no_registered_function_is_uncategorised() {
1058 assert!(
1059 registry()
1060 .iter()
1061 .all(|sig| sig.category != FuncCategory::Uncategorised)
1062 );
1063 }
1064
1065 #[test]
1066 fn by_category_covers_all() {
1067 let grouped = by_category();
1068 let total: usize = grouped.iter().map(|(_, funcs)| funcs.len()).sum();
1069 let reg = registry();
1070 assert_eq!(
1071 total,
1072 reg.len(),
1073 "by_category must cover all registered functions"
1074 );
1075 }
1076
1077 #[test]
1078 fn category_parse_roundtrip() {
1079 for cat in FuncCategory::display_order() {
1080 let name = cat.display_name();
1081 let parsed = FuncCategory::parse(name);
1082 assert_eq!(parsed, Some(*cat), "failed to parse category '{name}'");
1083 }
1084 }
1085
1086 #[test]
1087 fn registry_has_entries() {
1088 let reg = registry();
1089 assert!(reg.len() > 50, "registry should have 50+ functions");
1090 }
1091
1092 // --- Unified param model tests ---
1093
1094 #[test]
1095 fn printf_has_const_str_param() {
1096 // printf is a `#[polydat_node]` with a `Const<&str> format`
1097 // arg + `&[Value] parts` variadic. The macro lists both in
1098 // `params` (the variadic arg appears as a SlotType::Wire
1099 // entry whose count is governed by the node's
1100 // `Arity::VariadicWires`). The load-bearing assertion is that
1101 // the FIRST param is the format ConstStr and the arity is
1102 // variadic.
1103 let sig = lookup("printf").unwrap();
1104 assert!(
1105 !sig.params.is_empty(),
1106 "printf must have at least the format param"
1107 );
1108 assert!(matches!(sig.params[0].slot_type, SlotType::ConstStr));
1109 assert!(matches!(sig.arity, Arity::VariadicWires { .. }));
1110 }
1111}