Skip to main content

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