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