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