polydat_derive/lib.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! `polydat-derive` — proc-macro implementation of
5//! [`#[polydat_node]`](polydat_node).
6//!
7//! The attribute turns a typed free function into a polydat node.
8//! From one `fn` it emits the node struct (named after the function
9//! in PascalCase), its `new()` constructor, the `PolydatNode` impl
10//! (`meta`, `eval`, and the compiled forms the signature allows),
11//! and a link-time `NodeRegistration` carrying the `FuncSig` the
12//! DSL registry serves. The function's `///` comment becomes the
13//! struct's documentation and the signature's `description` (first
14//! paragraph) and `help` (the rest).
15//!
16//! ## Arguments
17//!
18//! Each argument is classified by its type and attributes:
19//!
20//! - **Wire** — a per-cycle input. Scalars (`u64`, `i64`, `f64`,
21//! `bool`, the narrower ints, `f32`, `f16`, `u128`, `i128`),
22//! strings (`&str`, `String`, `Arc<str>`), bytes (`&[u8]`,
23//! `Vec<u8>`, `Arc<[u8]>`), JSON (`&serde_json::Value`,
24//! `Arc<serde_json::Value>`), typed vectors (`&[f32]`, `Vec<i64>`,
25//! ...), SIMD registers (`Bits128`, `[i32; 4]`, ...), `Arc<T>`
26//! handles, and host `Ext` types. `Option<T>` marks an input that
27//! may be unset; `Config<T>` marks a configuration-cost wire.
28//! `#[constraint(Variant)]` attaches a `ConstConstraint` to a
29//! wire input.
30//! - **PolyWire** — a `Value` argument: any runtime type; the output
31//! type of a `Value` return tracks the first PolyWire input.
32//! - **Variadic** — a `&[T]` argument for `T` in `u64`, `bool`,
33//! `&str`, `String`, `Value`; two consecutive slices form a
34//! split-halves shape. `variadic_min` and `identity` describe the
35//! arity.
36//! - **Const** — `Const<u64 | f64 | bool | &str>`, a workload
37//! constant captured at construction; `#[poly_default(EXPR)]`
38//! supplies its default. `Const<Vec<C>>` (last) captures every
39//! trailing constant of the call.
40//! - **Setup** — a `&T` argument with
41//! `#[poly_const(setup_fn, from = source)]`: derived state
42//! computed once in `new()` from the named const arguments
43//! (`from = ()` for none, `from = (a, b)` for several). `T`
44//! implements `PolydatSetup`. `ctx` first in the list,
45//! `from = (ctx, a)`, passes the node's `&BuildContext` as the
46//! setup's first argument, so the node captures its binding or
47//! its tree's resource scope at construction; `new()` then takes
48//! the context first, and the kit clones the captured `T`.
49//! A `BuildContext` argument anywhere else is refused.
50//!
51//! ## Returns
52//!
53//! A single wire type; a tuple of wire types (multi-output, named
54//! by `output_names(...)`); `Value` (polymorphic); `Result<T, E>`
55//! for a body that runs once at construction and caches its value;
56//! or a dynamic-output list over a `Const<Vec<C>>` argument.
57//!
58//! ## Attribute parameters
59//!
60//! - `category = <FuncCategory>` — required.
61//! - `struct_name = <Ident>` — the Rust name of the node struct.
62//! - `compiled_u64 = <path>` — `fn(&Node) -> CompiledU64Op`,
63//! replacing the macro's u64-buffer closure.
64//! - `compiled_slot = <path>` — `fn(&Node, &[PortType]) ->
65//! CompiledSlotKit`, replacing the slot kit's closure.
66//! - `state = <path>` — per-state scratch: `scratch_layout` and
67//! `eval_in` delegate to `<path>::layout` / `<path>::eval`.
68//! - `jit_constants = <path>` — `fn(&Node) -> Vec<u64>`.
69//! - `validate = <path>` — a node-level check the factory runs when
70//! the node is built.
71//! - `decompose = <path>` — `fn(&Node) -> DecomposedGraph`, emitting
72//! `impl FusedNode`.
73//! - `simd = "<node>"`, `simd_total` — an exact register-typed
74//! implementation of the scalar function.
75//! - `purity = <Purity>`, `identity = <expr>`,
76//! `commutativity = <Commutativity>`, `variadic_min = <int>`.
77//! - `output_names(a, b, ...)` — the ports of a tuple return.
78
79use proc_macro::TokenStream;
80use proc_macro2::TokenStream as TokenStream2;
81use quote::{format_ident, quote};
82use syn::{
83 FnArg, Ident, ItemFn, Meta, Pat, ReturnType, Token, Type, parse::Parser, parse_macro_input,
84 punctuated::Punctuated,
85};
86
87/// `#[polydat_node]` — derive a polydat node from a typed Rust
88/// function signature.
89///
90/// See the crate docs for the argument and return shapes the
91/// macro accepts.
92///
93/// ## Attribute parameters
94///
95/// - `category = <ident>` — the polydat `FuncCategory` variant
96/// the node belongs to (`Comparison`, `Math`, `String`, etc.).
97/// Required; there is no default.
98/// - `struct_name = <Ident>` — the Rust name of the generated node
99/// struct. Defaults to the function name in PascalCase, so a node
100/// `fn geo_cell` produces `struct GeoCell`; set this when that name
101/// is already taken, typically by the value type the node returns.
102/// The DSL name is always the function name.
103/// - `simd = "<node-name>"` declares an exact, lane-independent
104/// register-typed implementation of the scalar function.
105/// - `simd_total` certifies that the declared SIMD implementation is defined
106/// for the complete scalar input domain. It requires `simd`.
107#[proc_macro_attribute]
108pub fn polydat_node(attr: TokenStream, item: TokenStream) -> TokenStream {
109 let func = parse_macro_input!(item as ItemFn);
110
111 let attrs = match parse_attrs(attr.into()) {
112 Ok(a) => a,
113 Err(e) => return e.to_compile_error().into(),
114 };
115
116 match generate(func, attrs) {
117 Ok(ts) => ts.into(),
118 Err(e) => e.to_compile_error().into(),
119 }
120}
121
122/// Parsed `#[polydat_node(...)]` attribute parameters.
123struct NodeAttrs {
124 /// `FuncCategory` variant name — required (no default).
125 /// Forcing the operator to declare the category keeps the
126 /// `describe` / help / categorization surface coherent.
127 category: Ident,
128 /// Override path for `compiled_u64()`. When
129 /// set, the macro emits `compiled_u64(&self) -> Some(<path>(self))`
130 /// instead of building the closure from the body. Free-fn
131 /// signature: `fn(&Node) -> CompiledU64Op`, so setup-derived
132 /// state on the node is reachable. Escape hatch for hand-tuned
133 /// SIMD / FFI / unusual carriers.
134 compiled_u64_override: Option<syn::ExprPath>,
135 /// `validate = <path>`: a node-level check the factory runs when
136 /// the node is built.
137 validate_fn: Option<syn::ExprPath>,
138 /// Override path for `compiled_slot()`. When set, the macro emits
139 /// `compiled_slot(&self, wire_types) -> Some(<path>(self,
140 /// wire_types))` instead of the slot kit's closure. Free-fn
141 /// signature: `fn(&Node, &[PortType]) -> CompiledSlotKit`. For a
142 /// node whose closure reads its slots as borrowed views.
143 compiled_slot_override: Option<syn::ExprPath>,
144 /// Override path for `jit_constants()`.
145 /// Free-fn signature: `fn(&Node) -> Vec<u64>`. Macro emits
146 /// `jit_constants(&self) -> <path>(self)`.
147 jit_constants_override: Option<syn::ExprPath>,
148 /// `state = <path>`: the node keeps state of its own per
149 /// evaluating kernel state (axiom S3: storage belongs to the
150 /// state, never to the shared node). The macro emits
151 /// `scratch_layout` delegating to `<path>::layout(&self)` and
152 /// `eval_in` delegating to `<path>::eval(&self, scratch, inputs,
153 /// outputs)`; the plain `eval` stays the body over fresh scratch.
154 state: Option<syn::ExprPath>,
155 /// `decompose = path`. When set, the
156 /// macro emits `impl FusedNode for <Struct>` whose
157 /// `decomposed(&self)` delegates to the named free function.
158 /// Free-fn signature: `fn(&Self) -> DecomposedGraph`. The
159 /// fusion compiler reaches the equivalent unfused subgraph
160 /// through this path. Operators with bespoke fusion logic
161 /// can still `impl FusedNode` by hand alongside the macro
162 /// emission — the attribute is the canonical sugar for the
163 /// "decompose by calling one free fn" case.
164 decompose: Option<syn::ExprPath>,
165 /// Declared `Purity` (Pure / SideChannel /
166 /// Nondeterministic). Defaults to `Pure` (the trait
167 /// default). Macro emits `fn purity(&self) -> Purity::<expr>`
168 /// when present.
169 ///
170 /// Two attribute forms recognized:
171 ///
172 /// - `purity = Nondeterministic` (path) — emits `Purity::Nondeterministic`.
173 /// - `purity = SideChannel(LogBuffer)` (call) — emits the
174 /// struct-variant form `Purity::SideChannel { sink:
175 /// SideChannelSink::LogBuffer }`. The call-form variant
176 /// makes the struct-variant inline attribute parse-able
177 /// (Rust attribute grammar doesn't accept inline `{ ... }`
178 /// struct literals as attribute values).
179 purity: Option<syn::Expr>,
180 /// DSL name of an exact, lane-wise register implementation.
181 simd: Option<syn::LitStr>,
182 /// Declares the SIMD variant total over the scalar input domain. Without
183 /// this flag the variant remains usable only after range/error proof.
184 simd_total: bool,
185 /// Variadic node identity value (the result
186 /// when called with zero inputs). Emitted into
187 /// `FuncSig.identity: Option<u64>`. Required for variadic
188 /// numeric reductions whose group has an identity (sum=0,
189 /// product=1, min=u64::MAX, max=0). Skip for variadics with
190 /// no meaningful identity (str_concat — empty list yields "").
191 identity: Option<syn::Expr>,
192 /// `Commutativity` variant. Defaults to
193 /// `Positional`. Variadic reductions typically pass
194 /// `AllCommutative` (sum/product/min/max all hold regardless
195 /// of input order).
196 commutativity: Option<Ident>,
197 /// Minimum required wire count for variadic
198 /// nodes. Defaults to 0 (callable with zero inputs).
199 variadic_min: Option<syn::LitInt>,
200 /// Names for the elements of a tuple
201 /// return type, paired positionally with the tuple
202 /// elements. Defaults to `out_0`, `out_1`, ... when
203 /// absent. Length must match tuple arity — operator gets a
204 /// compile error otherwise.
205 output_names: Option<Vec<Ident>>,
206 /// Rust name for the generated node struct. Defaults to the
207 /// function name in PascalCase; set it when that name would
208 /// collide with a type the operator already has in scope,
209 /// such as a `ReflectedValue` type the node produces.
210 struct_name: Option<Ident>,
211}
212
213fn parse_attrs(attr: TokenStream2) -> syn::Result<NodeAttrs> {
214 if attr.is_empty() {
215 return Err(syn::Error::new(
216 proc_macro2::Span::call_site(),
217 "#[polydat_node] requires `category = <FuncCategory variant>`. \
218 Example: #[polydat_node(category = Comparison)]",
219 ));
220 }
221
222 let parser = Punctuated::<Meta, Token![,]>::parse_terminated;
223 let items = parser.parse2(attr)?;
224
225 let mut category: Option<Ident> = None;
226 let mut compiled_u64_override: Option<syn::ExprPath> = None;
227 let mut state: Option<syn::ExprPath> = None;
228 // A node-level `validate = <path>`: checked by the factory when
229 // the node is built, so a rule that no single parameter can state
230 // — a relation between two of them — is enforced once and on every
231 // engine, rather than from a body that native code never runs.
232 let mut validate_fn: Option<syn::ExprPath> = None;
233 let mut compiled_slot_override: Option<syn::ExprPath> = None;
234 let mut jit_constants_override: Option<syn::ExprPath> = None;
235 let mut decompose: Option<syn::ExprPath> = None;
236 let mut purity: Option<syn::Expr> = None;
237 let mut simd: Option<syn::LitStr> = None;
238 let mut simd_total = false;
239 let mut identity: Option<syn::Expr> = None;
240 let mut commutativity: Option<Ident> = None;
241 let mut variadic_min: Option<syn::LitInt> = None;
242 let mut output_names: Option<Vec<Ident>> = None;
243 let mut struct_name: Option<Ident> = None;
244
245 for item in items {
246 match item {
247 Meta::Path(p) => {
248 let key = p
249 .get_ident()
250 .ok_or_else(|| {
251 syn::Error::new_spanned(
252 &p,
253 "#[polydat_node] flag keys must be bare identifiers",
254 )
255 })?
256 .clone();
257 match key.to_string().as_str() {
258 "simd_total" => {
259 simd_total = true;
260 }
261 other => {
262 return Err(syn::Error::new_spanned(
263 &key,
264 format!(
265 "#[polydat_node] does not recognize flag `{other}`. \
266 Flags: `simd_total`.",
267 ),
268 ));
269 }
270 }
271 }
272 Meta::NameValue(nv) => {
273 let key = nv
274 .path
275 .get_ident()
276 .ok_or_else(|| {
277 syn::Error::new_spanned(
278 &nv.path,
279 "#[polydat_node] parameter keys must be bare identifiers",
280 )
281 })?
282 .clone();
283 match key.to_string().as_str() {
284 "category" => {
285 let syn::Expr::Path(p) = &nv.value else {
286 return Err(syn::Error::new_spanned(
287 &nv.value,
288 "`category` value must be a bare identifier \
289 (a polydat `FuncCategory` variant name).",
290 ));
291 };
292 category = Some(
293 p.path
294 .get_ident()
295 .ok_or_else(|| {
296 syn::Error::new_spanned(
297 &nv.value,
298 "`category` value must be a single identifier.",
299 )
300 })?
301 .clone(),
302 );
303 }
304 "compiled_u64" => {
305 let syn::Expr::Path(p) = &nv.value else {
306 return Err(syn::Error::new_spanned(
307 &nv.value,
308 "`compiled_u64` value must be a path to a free \
309 function with signature `fn(&Node) -> CompiledU64Op`.",
310 ));
311 };
312 compiled_u64_override = Some(p.clone());
313 }
314 "state" => {
315 let syn::Expr::Path(p) = &nv.value else {
316 return Err(syn::Error::new_spanned(
317 &nv.value,
318 "`state` value must be a path to a module with \
319 `layout(&Node) -> Vec<ScratchElem>` and \
320 `eval(&Node, &mut [ScratchBuf], &[Value], &mut [Value])`.",
321 ));
322 };
323 state = Some(p.clone());
324 }
325 "validate" => {
326 let syn::Expr::Path(p) = &nv.value else {
327 return Err(syn::Error::new_spanned(
328 &nv.value,
329 "`validate` value must be a path to a free function \
330 with signature \
331 `fn(&str, &[ConstArg]) -> Result<(), String>`.",
332 ));
333 };
334 validate_fn = Some(p.clone());
335 }
336 "compiled_slot" => {
337 let syn::Expr::Path(p) = &nv.value else {
338 return Err(syn::Error::new_spanned(
339 &nv.value,
340 "`compiled_slot` value must be a path to a free \
341 function with signature \
342 `fn(&Node, &[PortType]) -> CompiledSlotKit`.",
343 ));
344 };
345 compiled_slot_override = Some(p.clone());
346 }
347 "jit_constants" => {
348 let syn::Expr::Path(p) = &nv.value else {
349 return Err(syn::Error::new_spanned(
350 &nv.value,
351 "`jit_constants` value must be a path to a free \
352 function with signature `fn(&Node) -> Vec<u64>`.",
353 ));
354 };
355 jit_constants_override = Some(p.clone());
356 }
357 "decompose" => {
358 let syn::Expr::Path(p) = &nv.value else {
359 return Err(syn::Error::new_spanned(
360 &nv.value,
361 "`decompose` value must be a path to a free \
362 function with signature \
363 `fn(&Self) -> DecomposedGraph`.",
364 ));
365 };
366 decompose = Some(p.clone());
367 }
368 "purity" => {
369 // Accept either:
370 // purity = Nondeterministic (path)
371 // purity = SideChannel(LogBuffer) (call)
372 // The codegen dispatches on the shape.
373 match &nv.value {
374 syn::Expr::Path(_) | syn::Expr::Call(_) => {
375 purity = Some(nv.value.clone());
376 }
377 _ => {
378 return Err(syn::Error::new_spanned(
379 &nv.value,
380 "`purity` value must be a Purity variant: \
381 `Pure`, `Nondeterministic`, or \
382 `SideChannel(<sink>)` where `<sink>` is a \
383 `SideChannelSink` variant ident.",
384 ));
385 }
386 }
387 }
388 "simd" => {
389 let syn::Expr::Lit(syn::ExprLit {
390 lit: syn::Lit::Str(name),
391 ..
392 }) = &nv.value
393 else {
394 return Err(syn::Error::new_spanned(
395 &nv.value,
396 "`simd` value must be the string name of a register-typed node.",
397 ));
398 };
399 simd = Some(name.clone());
400 }
401 "identity" => {
402 // Variadic identity element.
403 // Any constant-evaluable expression is fine.
404 identity = Some(nv.value.clone());
405 }
406 "commutativity" => {
407 let syn::Expr::Path(p) = &nv.value else {
408 return Err(syn::Error::new_spanned(
409 &nv.value,
410 "`commutativity` value must be a `Commutativity` \
411 variant ident (Positional / AllCommutative / ...).",
412 ));
413 };
414 commutativity = Some(
415 p.path
416 .get_ident()
417 .ok_or_else(|| {
418 syn::Error::new_spanned(
419 &nv.value,
420 "`commutativity` value must be a single identifier.",
421 )
422 })?
423 .clone(),
424 );
425 }
426 "variadic_min" => {
427 let syn::Expr::Lit(syn::ExprLit {
428 lit: syn::Lit::Int(n),
429 ..
430 }) = &nv.value
431 else {
432 return Err(syn::Error::new_spanned(
433 &nv.value,
434 "`variadic_min` value must be an integer literal.",
435 ));
436 };
437 variadic_min = Some(n.clone());
438 }
439 "struct_name" => {
440 // The generated Rust struct is named after the
441 // function in PascalCase by default; a host whose
442 // module already has a type of that name picks
443 // another one here. The DSL name is unchanged.
444 let syn::Expr::Path(p) = &nv.value else {
445 return Err(syn::Error::new_spanned(
446 &nv.value,
447 "`struct_name` value must be a bare identifier, \
448 e.g. `struct_name = GeoCellNode`.",
449 ));
450 };
451 struct_name = Some(p.path.get_ident()
452 .ok_or_else(|| syn::Error::new_spanned(
453 &nv.value,
454 "`struct_name` value must be a single identifier, not a path.",
455 ))?
456 .clone());
457 }
458 other => {
459 return Err(syn::Error::new_spanned(
460 &key,
461 format!(
462 "#[polydat_node] does not recognize parameter `{other}`. \
463 Registration: `category = <FuncCategory>`, \
464 `struct_name = <Ident>`. \
465 Engines: `compiled_u64 = <path>`, \
466 `compiled_slot = <path>`, `state = <path>`, \
467 `jit_constants = <path>`, `decompose = <path>`, \
468 `simd = \"<node>\"`, `simd_total`. \
469 Semantics: `purity = <Purity>`, `identity = <expr>`, \
470 `commutativity = <Commutativity>`, `variadic_min = <int>`. \
471 Shapes: `output_names(...)`.",
472 ),
473 ));
474 }
475 }
476 }
477 Meta::List(list) => {
478 let key = list
479 .path
480 .get_ident()
481 .ok_or_else(|| {
482 syn::Error::new_spanned(
483 &list.path,
484 "#[polydat_node] list-form keys must be bare identifiers",
485 )
486 })?
487 .clone();
488 match key.to_string().as_str() {
489 "output_names" => {
490 let names: Punctuated<Ident, Token![,]> =
491 list.parse_args_with(Punctuated::parse_terminated)?;
492 if names.is_empty() {
493 return Err(syn::Error::new_spanned(
494 &list,
495 "`output_names(...)` requires at least one name.",
496 ));
497 }
498 output_names = Some(names.into_iter().collect());
499 }
500 other => {
501 return Err(syn::Error::new_spanned(
502 &key,
503 format!(
504 "#[polydat_node] does not recognize list-form key `{other}`. \
505 Recognised: `output_names(...)`.",
506 ),
507 ));
508 }
509 }
510 }
511 }
512 }
513
514 let category = category.ok_or_else(|| {
515 syn::Error::new(
516 proc_macro2::Span::call_site(),
517 "#[polydat_node] requires `category = <FuncCategory variant>`.",
518 )
519 })?;
520
521 if simd_total && simd.is_none() {
522 return Err(syn::Error::new(
523 proc_macro2::Span::call_site(),
524 "`simd_total` requires `simd = \"<register node>\"`.",
525 ));
526 }
527
528 Ok(NodeAttrs {
529 category,
530 compiled_u64_override,
531 compiled_slot_override,
532 validate_fn,
533 jit_constants_override,
534 state,
535 decompose,
536 purity,
537 simd,
538 simd_total,
539 identity,
540 commutativity,
541 variadic_min,
542 output_names,
543 struct_name,
544 })
545}
546
547/// One classified function argument. Drives every downstream
548/// piece of the generated output: NodeMeta slot, FuncSig
549/// param, struct field (for consts), build closure const
550/// extraction, eval-time wrapper construction.
551struct ClassifiedArg {
552 name: syn::Ident,
553 /// Original Rust type from the function signature.
554 declared_ty: Type,
555 /// Whether the arg was declared as `Const<T>`.
556 kind: ArgKind,
557 /// For const args: optional default value expression parsed
558 /// from `#[poly_default(VAL)]`. Present → the const is
559 /// optional in FuncSig and the build closure falls back to
560 /// the default when the consts slice doesn't supply one.
561 default_value: Option<syn::Expr>,
562 /// `#[constraint(<Variant>)]`, if the argument declared one. The
563 /// variant name maps to `ConstConstraint::*`. On a wire arg the
564 /// emitted `Port` carries the constraint so strict-wire mode can
565 /// auto-insert upstream assertion nodes; on a const arg it lands
566 /// in the parameter's `ParamSpec`.
567 constraint: Option<syn::Expr>,
568}
569
570/// How a `Const` list argument asked for its elements: borrowed from
571/// the node's own field, or cloned out of it for each evaluation.
572#[derive(Clone, Copy, PartialEq)]
573enum ListForm {
574 /// `Const<&[C]>` — a borrow, free per evaluation.
575 Borrowed,
576 /// `Const<Vec<C>>` — an owned clone, the older spelling.
577 Owned,
578}
579#[derive(Clone)]
580enum ArgKind {
581 Wire,
582 Const(ConstShape),
583 /// `Const<Vec<C>>` workload-list const.
584 /// Inner ConstShape gives the element type (u64/f64/bool/Str).
585 /// The macro emits ONE ParamSpec in the FuncSig with the
586 /// inner element's slot type, sets `Arity::VariadicConsts`,
587 /// and at build time collects every matching ConstArg from
588 /// the tail of `consts[..]` into a `Vec<inner>` field.
589 ///
590 /// The flag is how the body asked for the list. `Const<&[C]>`
591 /// borrows the field, which costs nothing per evaluation and is
592 /// what the borrowed string shape `Const<&str>` already does;
593 /// `Const<Vec<C>>` clones it, which is an allocation per
594 /// evaluation of a list that never changes after construction.
595 /// Both are accepted and the owned one is the older spelling.
596 ConstVec(ConstShape, ListForm),
597 /// `&T` argument with `#[poly_const(<fn_path>, from = <arg>)]`.
598 /// Generates a struct field of type `T`, computed once in
599 /// `new()` by calling `<fn_path>(<source>)` where `<source>`
600 /// is the field-access expression for the named `from` arg.
601 /// Boxed: `SetupSpec` is ~424 bytes, dwarfing the other
602 /// variants — indirection keeps `ArgKind` small.
603 Setup(Box<SetupSpec>),
604 /// `Value` argument. Polymorphic wire whose
605 /// port type is resolved at construction (`new()` takes a
606 /// runtime `PortType`). Body sees a cloned `Value`, with no
607 /// conversion.
608 /// Triggers `OutputType::SameAsInput(<this idx>)` when the
609 /// return type is also `Value`.
610 PolyWire,
611 /// `&[T]` argument (variadic wire). Construction
612 /// is runtime-arity (`new(n_wires)`); the macro emits N wire
613 /// slots, an `Arity::VariadicWires { min_wires }` FuncSig
614 /// entry, and a `variadic_ctor` thunk that builds with `n`
615 /// at compile time.
616 Variadic(VariadicElement),
617}
618
619/// Element type of a `&[T]` variadic arg. Determines the
620/// per-element port type, whether the node stays JIT-eligible,
621/// and how `eval()` materialises the slice for the body call.
622#[derive(Clone, Copy, PartialEq, Eq)]
623enum VariadicElement {
624 U64,
625 Bool,
626 BorrowedStr,
627 OwnedString,
628 /// `&[Value]` — polymorphic per-element type. The body sees
629 /// each element as the polydat runtime carrier; type
630 /// inspection / coercion is the body's responsibility.
631 Value,
632}
633
634impl VariadicElement {
635 fn port_type_tokens(self) -> TokenStream2 {
636 // A `Value` variadic's per-slot type is nominal: the slot is
637 // marked `accepts_any_type`, so the assembler reads the wire
638 // and inserts nothing, and the body dispatches on the `Value`
639 // variant itself. `Str` is the spelling of the placeholder,
640 // not a claim about the wire.
641 match self {
642 VariadicElement::U64 => quote!(polydat::ast::PortType::U64),
643 VariadicElement::Bool => quote!(polydat::ast::PortType::Bool),
644 VariadicElement::BorrowedStr => quote!(polydat::ast::PortType::Str),
645 VariadicElement::OwnedString => quote!(polydat::ast::PortType::Str),
646 VariadicElement::Value => quote!(polydat::ast::PortType::Str),
647 }
648 }
649
650 /// Expression that converts a single `&Value` to the body's
651 /// element type. Used to build the per-call slice in eval().
652 fn extract_from_value(self) -> TokenStream2 {
653 match self {
654 VariadicElement::U64 => quote!(|v: &polydat::ast::Value| v.as_u64()),
655 VariadicElement::Bool => quote!(|v: &polydat::ast::Value| v.as_bool()),
656 VariadicElement::BorrowedStr => quote!(|v: &polydat::ast::Value| v.as_str()),
657 VariadicElement::OwnedString => {
658 quote!(|v: &polydat::ast::Value| v.as_str().to_string())
659 }
660 VariadicElement::Value => quote!(|v: &polydat::ast::Value| v.clone()),
661 }
662 }
663}
664
665#[derive(Clone)]
666struct SetupSpec {
667 /// `T` — the type the field stores (inner type of `&T`).
668 inner_ty: Type,
669 /// Operator-provided constructor path, e.g.
670 /// `ParsedPattern::from_pattern`.
671 setup_fn: syn::Expr,
672 /// Names of the const args whose field-values are passed to
673 /// `setup_fn`. Empty when declared as `from = ()` — the
674 /// setup fn takes no arguments and captures session-static
675 /// state (env, system clock, etc.). Length 1 for the common
676 /// single-source case (`from = ident`); length N for
677 /// multi-source `from = (a, b, c)`.
678 source_args: Vec<syn::Ident>,
679 /// The `ctx` that `from` names first, when it does: the setup fn
680 /// takes the node's `&BuildContext` before the consts, and `new()`
681 /// takes it as its first parameter. The call passes this ident, so
682 /// a setup fn of the wrong type is reported at the `from` list.
683 /// `ctx` is not in `source_args`.
684 ctx: Option<syn::Ident>,
685}
686
687impl SetupSpec {
688 /// Whether the setup reads the build context.
689 fn takes_ctx(&self) -> bool {
690 self.ctx.is_some()
691 }
692}
693
694/// The name a `from` list gives the node's build context.
695const CTX_SOURCE: &str = "ctx";
696
697#[derive(Clone, Copy, PartialEq, Eq)]
698enum ConstShape {
699 U64,
700 F64,
701 Bool,
702 Str,
703 /// `Const<Arc<T>>` — a value the compiler built, carried as
704 /// [`ConstArg::Opaque`] and downcast to `T` at construction. The
705 /// concrete `T` comes from the argument's declared type, so this
706 /// variant carries none and the enum stays `Copy`.
707 Opaque,
708}
709
710impl ConstShape {
711 /// Token stream for the `SlotType::Const*` variant.
712 fn slot_type_tokens(self) -> TokenStream2 {
713 match self {
714 ConstShape::U64 => quote!(polydat::ast::SlotType::ConstU64),
715 ConstShape::F64 => quote!(polydat::ast::SlotType::ConstF64),
716 ConstShape::Bool => quote!(polydat::ast::SlotType::ConstU64),
717 ConstShape::Str => quote!(polydat::ast::SlotType::ConstStr),
718 // An opaque const has no literal form, so it is not a
719 // const slot on the node's meta; the assembler and the
720 // JIT walkers see the wires and nothing else.
721 ConstShape::Opaque => quote!(polydat::ast::SlotType::ConstStr),
722 }
723 }
724
725 /// Token stream for the struct field type that stores the
726 /// captured const value. `Const<&str>` → `String` (owned
727 /// backing store). Other shapes are Copy and stored
728 /// directly.
729 fn field_type_tokens(self, opaque: Option<&Type>) -> TokenStream2 {
730 match self {
731 ConstShape::U64 => quote!(u64),
732 ConstShape::F64 => quote!(f64),
733 ConstShape::Bool => quote!(bool),
734 ConstShape::Str => quote!(String),
735 ConstShape::Opaque => {
736 let t = opaque.expect("an opaque const names its type");
737 quote!(std::sync::Arc<#t>)
738 }
739 }
740 }
741
742 /// Token stream that extracts a value from a `ConstArg`.
743 /// `c` is the `ConstArg` binding in scope at the call site.
744 fn extract_from_const_arg(self, c: TokenStream2, opaque: Option<&Type>) -> TokenStream2 {
745 match self {
746 ConstShape::U64 => quote!(#c.as_u64()),
747 ConstShape::F64 => quote!(#c.as_f64()),
748 ConstShape::Bool => quote!(#c.as_u64() != 0),
749 ConstShape::Str => quote!(#c.as_str().to_string()),
750 ConstShape::Opaque => {
751 let t = opaque.expect("an opaque const names its type");
752 quote!(match #c.as_opaque::<#t>() {
753 Some(v) => v,
754 None => return Some(Err(format!(
755 "{}: expected a compiler-built {} for this argument",
756 name,
757 std::any::type_name::<#t>()
758 ))),
759 })
760 }
761 }
762 }
763
764 /// Token stream that wraps a struct-field expression as
765 /// `Const<T>` for handoff into the user's function body.
766 /// `field_ref` is the borrow / value expression for the
767 /// stored field (e.g. `&self.pattern` or `self.seed`).
768 fn wrap_as_const(self, field_ref: TokenStream2) -> TokenStream2 {
769 match self {
770 ConstShape::U64 => quote!(polydat::derive_support::Const(#field_ref)),
771 ConstShape::F64 => quote!(polydat::derive_support::Const(#field_ref)),
772 ConstShape::Bool => quote!(polydat::derive_support::Const(#field_ref)),
773 ConstShape::Str => quote!(polydat::derive_support::Const(#field_ref.as_str())),
774 ConstShape::Opaque => quote!(polydat::derive_support::Const(#field_ref.clone())),
775 }
776 }
777}
778
779/// Primitive types that fit the JIT u64 buffer.
780/// A node is Phase-2 eligible iff every wire arg / const arg /
781/// return type maps to a `JitType` and no `#[poly_const]` setup arg
782/// is declared (setup carries non-primitive derived state).
783#[derive(Clone, Copy, PartialEq, Eq)]
784enum JitType {
785 U64,
786 I64,
787 F64,
788 Bool,
789 // Narrow widths (alignment §8.1): each rides the u64 slot per
790 // its Wire storage convention — unsigned zero-extended, signed
791 // sign-extended (through the i64 carrier), floats bit-stuffed.
792 // The variant carries enough width information for the buffer
793 // read/write tokens to emit the exact narrowing/widening casts.
794 U8,
795 U16,
796 U32,
797 I8,
798 I16,
799 I32,
800 F32,
801 F16,
802 // Two-slot values (alignment §8.4 layer 1): 128-bit integers
803 // and register words ride two consecutive u64 slots in
804 // little-endian limb order, reconstructed through
805 // `polydat::ast::Bits128`.
806 U128,
807 I128,
808 RegRaw,
809 RegI8x16,
810 RegI16x8,
811 RegI32x4,
812 RegI64x2,
813 RegF16x8,
814 RegF32x4,
815 RegF64x2,
816}
817
818impl JitType {
819 /// Buffer slots this carrier occupies (alignment §8.4 layer
820 /// 1): 1 for everything riding a single u64; 2 for 128-bit
821 /// values (limb pairs).
822 fn width(self) -> usize {
823 match self {
824 JitType::U128
825 | JitType::I128
826 | JitType::RegRaw
827 | JitType::RegI8x16
828 | JitType::RegI16x8
829 | JitType::RegI32x4
830 | JitType::RegI64x2
831 | JitType::RegF16x8
832 | JitType::RegF32x4
833 | JitType::RegF64x2 => 2,
834 _ => 1,
835 }
836 }
837
838 /// Tokens reading a typed value from the Phase-2 u64 buffer
839 /// at slot offset `idx` (the prefix sum of the widths of all
840 /// preceding wire args). f64/bool are bit-reinterpreted from
841 /// the u64 carrier (the buffer-level convention shared with
842 /// every existing hand-written `compiled_u64`); two-slot
843 /// values reassemble through `Bits128`.
844 fn read_from_u64_buffer(self, idx: usize) -> TokenStream2 {
845 let i = syn::Index::from(idx);
846 let i1 = syn::Index::from(idx + 1);
847 let limbs = quote!(polydat::ast::Bits128([inputs[#i], inputs[#i1]]));
848 match self {
849 JitType::U64 => quote!(inputs[#i]),
850 JitType::I64 => quote!(inputs[#i] as i64),
851 JitType::F64 => quote!(f64::from_bits(inputs[#i])),
852 JitType::Bool => quote!(inputs[#i] != 0),
853 JitType::U8 => quote!(inputs[#i] as u8),
854 JitType::U16 => quote!(inputs[#i] as u16),
855 JitType::U32 => quote!(inputs[#i] as u32),
856 JitType::I8 => quote!((inputs[#i] as i64) as i8),
857 JitType::I16 => quote!((inputs[#i] as i64) as i16),
858 JitType::I32 => quote!((inputs[#i] as i64) as i32),
859 JitType::F32 => quote!(f32::from_bits(inputs[#i] as u32)),
860 JitType::F16 => quote!(polydat::half::f16::from_bits(inputs[#i] as u16)),
861 JitType::U128 => quote!((#limbs).as_u128()),
862 JitType::I128 => quote!((#limbs).as_i128()),
863 JitType::RegRaw => limbs,
864 JitType::RegI8x16 => quote!((#limbs).lanes_i8()),
865 JitType::RegI16x8 => quote!((#limbs).lanes_i16()),
866 JitType::RegI32x4 => quote!((#limbs).lanes_i32()),
867 JitType::RegI64x2 => quote!((#limbs).lanes_i64()),
868 JitType::RegF16x8 => quote!((#limbs).lanes_f16()),
869 JitType::RegF32x4 => quote!((#limbs).lanes_f32()),
870 JitType::RegF64x2 => quote!((#limbs).lanes_f64()),
871 }
872 }
873
874 /// Tokens writing a typed value into the Phase-2 u64 output
875 /// buffer at slot offset `base`. Inverse of the read.
876 fn write_to_u64_buffer_at(self, base: usize, result: TokenStream2) -> TokenStream2 {
877 let o = syn::Index::from(base);
878 let o1 = syn::Index::from(base + 1);
879 let write_limbs = |from: TokenStream2| {
880 quote! {{
881 let __limbs = #from;
882 outputs[#o] = __limbs.0[0];
883 outputs[#o1] = __limbs.0[1];
884 }}
885 };
886 match self {
887 JitType::U64 => quote!(outputs[#o] = #result;),
888 JitType::I64 => quote!(outputs[#o] = (#result) as u64;),
889 JitType::F64 => quote!(outputs[#o] = (#result).to_bits();),
890 JitType::Bool => quote!(outputs[#o] = if #result { 1 } else { 0 };),
891 JitType::U8 | JitType::U16 | JitType::U32 => quote!(outputs[#o] = (#result) as u64;),
892 JitType::I8 | JitType::I16 | JitType::I32 => {
893 quote!(outputs[#o] = ((#result) as i64) as u64;)
894 }
895 JitType::F32 => quote!(outputs[#o] = (#result).to_bits() as u64;),
896 JitType::F16 => quote!(outputs[#o] = (#result).to_bits() as u64;),
897 JitType::U128 => write_limbs(quote!(polydat::ast::Bits128::from_u128(#result))),
898 JitType::I128 => write_limbs(quote!(polydat::ast::Bits128::from_i128(#result))),
899 JitType::RegRaw => write_limbs(quote!(#result)),
900 JitType::RegI8x16 => write_limbs(quote!(polydat::ast::Bits128::from_lanes_i8(#result))),
901 JitType::RegI16x8 => {
902 write_limbs(quote!(polydat::ast::Bits128::from_lanes_i16(#result)))
903 }
904 JitType::RegI32x4 => {
905 write_limbs(quote!(polydat::ast::Bits128::from_lanes_i32(#result)))
906 }
907 JitType::RegI64x2 => {
908 write_limbs(quote!(polydat::ast::Bits128::from_lanes_i64(#result)))
909 }
910 JitType::RegF16x8 => {
911 write_limbs(quote!(polydat::ast::Bits128::from_lanes_f16(#result)))
912 }
913 JitType::RegF32x4 => {
914 write_limbs(quote!(polydat::ast::Bits128::from_lanes_f32(#result)))
915 }
916 JitType::RegF64x2 => {
917 write_limbs(quote!(polydat::ast::Bits128::from_lanes_f64(#result)))
918 }
919 }
920 }
921
922 /// Single-return write at offset 0.
923 fn write_to_u64_buffer(self, result: TokenStream2) -> TokenStream2 {
924 self.write_to_u64_buffer_at(0, result)
925 }
926
927 /// Tokens encoding the captured Copy value of a const field
928 /// as a `u64` for `jit_constants()` (Phase-3 classifier).
929 fn const_field_as_u64(self, field_ref: TokenStream2) -> TokenStream2 {
930 match self {
931 JitType::U64 => quote!(#field_ref),
932 JitType::I64 => quote!((#field_ref) as u64),
933 JitType::F64 => quote!((#field_ref).to_bits()),
934 JitType::Bool => quote!(if #field_ref { 1 } else { 0 }),
935 JitType::U8 | JitType::U16 | JitType::U32 => quote!((#field_ref) as u64),
936 JitType::I8 | JitType::I16 | JitType::I32 => quote!(((#field_ref) as i64) as u64),
937 JitType::F32 | JitType::F16 => quote!((#field_ref).to_bits() as u64),
938 // ConstShape has no 128-bit / register forms, so these
939 // never appear in const position.
940 JitType::U128
941 | JitType::I128
942 | JitType::RegRaw
943 | JitType::RegI8x16
944 | JitType::RegI16x8
945 | JitType::RegI32x4
946 | JitType::RegI64x2
947 | JitType::RegF16x8
948 | JitType::RegF32x4
949 | JitType::RegF64x2 => {
950 unreachable!("128-bit/register types have no const shape")
951 }
952 }
953 }
954}
955
956/// A `#[poly_default(...)]` expression as the literal a program writes:
957/// `4u64` is `4`, `100.0f64` is `100.0`, `-1.5` is `-1.5`, and a string
958/// keeps its quotes. `None` for an expression that is not a literal.
959fn program_literal(e: &syn::Expr) -> Option<String> {
960 match e {
961 syn::Expr::Lit(l) => match &l.lit {
962 syn::Lit::Int(i) => Some(i.base10_digits().to_string()),
963 syn::Lit::Float(f) => {
964 let d = f.base10_digits();
965 // The program reads a number without a point as an
966 // integer, so a float default keeps one.
967 Some(if d.contains(['.', 'e', 'E']) {
968 d.to_string()
969 } else {
970 format!("{d}.0")
971 })
972 }
973 syn::Lit::Str(s) => Some(format!("{:?}", s.value())),
974 // A `Const<bool>` rides the integer slot, and the grammar
975 // reads `true` and `false` in an argument as wire names, so
976 // the value a program passes is `1` or `0`.
977 syn::Lit::Bool(b) => Some(if b.value { "1" } else { "0" }.to_string()),
978 _ => None,
979 },
980 syn::Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => {
981 program_literal(&u.expr).map(|v| format!("-{v}"))
982 }
983 syn::Expr::Group(g) => program_literal(&g.expr),
984 syn::Expr::Paren(p) => program_literal(&p.expr),
985 _ => None,
986 }
987}
988
989/// Map a `ConstShape` to its JIT-compatible primitive carrier,
990/// or `None` if the shape can't live in the u64 buffer.
991fn const_shape_to_jit_type(s: ConstShape) -> Option<JitType> {
992 match s {
993 ConstShape::U64 => Some(JitType::U64),
994 ConstShape::F64 => Some(JitType::F64),
995 ConstShape::Bool => Some(JitType::Bool),
996 // A string constant never rides the buffer: the kits capture
997 // it by clone, and native lowerings read it from the node.
998 // Nor does a compiler-built value, which is an `Arc` the node
999 // holds rather than bits.
1000 ConstShape::Str | ConstShape::Opaque => None,
1001 }
1002}
1003
1004/// Map a wire arg's declared Rust type to its JIT carrier, or
1005/// `None` for types that can't fit in the buffer.
1006fn wire_type_to_jit_type(ty: &Type) -> Option<JitType> {
1007 // type_to_string joins every token with a space, and a token
1008 // may itself be a bracketed group (`& [u8]`, `half : : f16`,
1009 // `[ f32 ; 4 ]`), so every form compares whitespace-stripped.
1010 // The two-slot types ride limb pairs per alignment §8.4 layer 1.
1011 let flat: String = type_to_string(ty).split_whitespace().collect();
1012 match flat.as_str() {
1013 "u64" => Some(JitType::U64),
1014 "i64" => Some(JitType::I64),
1015 "f64" => Some(JitType::F64),
1016 "bool" => Some(JitType::Bool),
1017 "u8" => Some(JitType::U8),
1018 "u16" => Some(JitType::U16),
1019 "u32" => Some(JitType::U32),
1020 "i8" => Some(JitType::I8),
1021 "i16" => Some(JitType::I16),
1022 "i32" => Some(JitType::I32),
1023 "f32" => Some(JitType::F32),
1024 "u128" => Some(JitType::U128),
1025 "i128" => Some(JitType::I128),
1026 "half::f16" | "f16" => Some(JitType::F16),
1027 "Bits128" | "crate::ast::Bits128" | "polydat::ast::Bits128" | "ast::Bits128" => {
1028 Some(JitType::RegRaw)
1029 }
1030 "[i8;16]" => Some(JitType::RegI8x16),
1031 "[i16;8]" => Some(JitType::RegI16x8),
1032 "[i32;4]" => Some(JitType::RegI32x4),
1033 "[i64;2]" => Some(JitType::RegI64x2),
1034 "[half::f16;8]" | "[f16;8]" => Some(JitType::RegF16x8),
1035 "[f32;4]" => Some(JitType::RegF32x4),
1036 "[f64;2]" => Some(JitType::RegF64x2),
1037 _ => None,
1038 }
1039}
1040
1041/// The `T` of an `Option<T>` argument, by its last path segment.
1042fn option_inner(ty: &Type) -> Option<&Type> {
1043 generic_inner(ty, "Option")
1044}
1045
1046/// The `T` of a `Config<T>` argument, by its last path segment.
1047fn config_inner(ty: &Type) -> Option<&Type> {
1048 generic_inner(ty, "Config")
1049}
1050
1051fn generic_inner<'a>(ty: &'a Type, wrapper: &str) -> Option<&'a Type> {
1052 let syn::Type::Path(p) = ty else {
1053 return None;
1054 };
1055 let last = p.path.segments.last()?;
1056 if last.ident != wrapper {
1057 return None;
1058 }
1059 let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
1060 return None;
1061 };
1062 args.args.iter().find_map(|a| match a {
1063 syn::GenericArgument::Type(t) => Some(t),
1064 _ => None,
1065 })
1066}
1067
1068/// Detect `Const<T>` in arg-type position. Returns `Some(shape)`
1069/// for recognized inner types; `None` for bare types (wire) or
1070/// unrecognized shapes. The recognition is structural — matches
1071/// the last segment of the path as `Const` with a single
1072/// generic argument resolving to a primitive type the macro
1073/// supports.
1074fn classify_type(ty: &Type) -> Option<ConstShape> {
1075 let syn::Type::Path(p) = ty else {
1076 return None;
1077 };
1078 let last = p.path.segments.last()?;
1079 if last.ident != "Const" {
1080 return None;
1081 }
1082 let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
1083 return None;
1084 };
1085 let inner = args.args.iter().find_map(|a| {
1086 if let syn::GenericArgument::Type(t) = a {
1087 Some(t)
1088 } else {
1089 None
1090 }
1091 })?;
1092 let s = type_to_string(inner);
1093 match s.as_str() {
1094 "u64" => Some(ConstShape::U64),
1095 "f64" => Some(ConstShape::F64),
1096 "bool" => Some(ConstShape::Bool),
1097 "& str" | "&str" => Some(ConstShape::Str),
1098 // `Const<Arc<T>>` — a value the compiler built and hands the
1099 // node as it is, rather than a literal the source wrote. The
1100 // concrete `T` is read from the declared type where it is
1101 // needed; the shape itself carries no type so it stays `Copy`
1102 // with the rest.
1103 _ if is_generic_named(inner, "Arc") => Some(ConstShape::Opaque),
1104 _ => None,
1105 }
1106}
1107
1108/// The `T` of a `Const<Arc<T>>` argument's declared type.
1109fn opaque_inner_type(ty: &Type) -> Option<Type> {
1110 let Type::Path(p) = ty else { return None };
1111 let last = p.path.segments.last()?;
1112 if last.ident != "Const" {
1113 return None;
1114 }
1115 let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
1116 return None;
1117 };
1118 let inner = args.args.iter().find_map(|a| match a {
1119 syn::GenericArgument::Type(t) => Some(t),
1120 _ => None,
1121 })?;
1122 let Type::Path(arc) = inner else { return None };
1123 let arc_last = arc.path.segments.last()?;
1124 if arc_last.ident != "Arc" {
1125 return None;
1126 }
1127 let syn::PathArguments::AngleBracketed(arc_args) = &arc_last.arguments else {
1128 return None;
1129 };
1130 arc_args.args.iter().find_map(|a| match a {
1131 syn::GenericArgument::Type(t) => Some(t.clone()),
1132 _ => None,
1133 })
1134}
1135
1136/// Detect `Const<Vec<T>>` in arg position.
1137/// Returns the inner element shape on match. Distinct path
1138/// from [`classify_type`]: the macro recognises the variadic-
1139/// const shape before the scalar `Const<T>` shape, so a
1140/// signature using `Const<Vec<u64>>` doesn't get misclassified.
1141fn classify_const_vec(ty: &Type) -> Option<(ConstShape, ListForm)> {
1142 // Outer must be Const<...>.
1143 let syn::Type::Path(p) = ty else {
1144 return None;
1145 };
1146 let last = p.path.segments.last()?;
1147 if last.ident != "Const" {
1148 return None;
1149 }
1150 let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
1151 return None;
1152 };
1153 let inner = args.args.iter().find_map(|a| {
1154 if let syn::GenericArgument::Type(t) = a {
1155 Some(t)
1156 } else {
1157 None
1158 }
1159 })?;
1160 // Inner is `&[X]`, the borrowed list, or `Vec<X>`, the owned one.
1161 if let syn::Type::Reference(r) = inner
1162 && let syn::Type::Slice(slice) = r.elem.as_ref()
1163 {
1164 return const_shape_of(&slice.elem).map(|s| (s, ListForm::Borrowed));
1165 }
1166 let syn::Type::Path(vp) = inner else {
1167 return None;
1168 };
1169 let vlast = vp.path.segments.last()?;
1170 if vlast.ident != "Vec" {
1171 return None;
1172 }
1173 let syn::PathArguments::AngleBracketed(vargs) = &vlast.arguments else {
1174 return None;
1175 };
1176 let velem = vargs.args.iter().find_map(|a| {
1177 if let syn::GenericArgument::Type(t) = a {
1178 Some(t)
1179 } else {
1180 None
1181 }
1182 })?;
1183 const_shape_of(velem).map(|s| (s, ListForm::Owned))
1184}
1185
1186/// The element shape of a const list, from the element type as
1187/// written. Shared by the borrowed and owned spellings so the two
1188/// accept exactly the same element types.
1189fn const_shape_of(elem: &Type) -> Option<ConstShape> {
1190 match type_to_string(elem).as_str() {
1191 "u64" => Some(ConstShape::U64),
1192 "f64" => Some(ConstShape::F64),
1193 "bool" => Some(ConstShape::Bool),
1194 "String" => Some(ConstShape::Str),
1195 "& str" | "&str" => Some(ConstShape::Str),
1196 _ => None,
1197 }
1198}
1199
1200/// Dynamic-output shape — detect
1201/// `DynamicOutputs<T>` in return position. Returns the inner
1202/// element type `T` on match. The macro pairs this with the
1203/// function's `Const<Vec<C>>` arg to compute the output port
1204/// count at construction time.
1205fn classify_dynamic_outputs(ty: &Type) -> Option<Type> {
1206 let syn::Type::Path(p) = ty else {
1207 return None;
1208 };
1209 let last = p.path.segments.last()?;
1210 if last.ident != "DynamicOutputs" {
1211 return None;
1212 }
1213 let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
1214 return None;
1215 };
1216 args.args.iter().find_map(|a| {
1217 if let syn::GenericArgument::Type(t) = a {
1218 Some(t.clone())
1219 } else {
1220 None
1221 }
1222 })
1223}
1224
1225/// Extract a `#[poly_default(EXPR)]` attribute from an arg's
1226/// outer attributes, if present. Returns the inner expression
1227/// token stream so the build closure can use it as the
1228/// fallback when the runtime `consts` slice is shorter than
1229/// the declared param list.
1230fn parse_poly_default(attrs: &[syn::Attribute]) -> syn::Result<Option<syn::Expr>> {
1231 for attr in attrs {
1232 if !attr.path().is_ident("poly_default") {
1233 continue;
1234 }
1235 let expr: syn::Expr = attr.parse_args()?;
1236 return Ok(Some(expr));
1237 }
1238 Ok(None)
1239}
1240
1241/// Extract a `#[constraint(<Variant>)]` attribute, on a wire or a
1242/// const argument. What follows `ConstConstraint::` — a bare variant
1243/// such as `NonZero`, or one with fields such as
1244/// `RangeF64 { min: 0.0, max: 1.0 }`.
1245///
1246/// On a **wire** arg it is strict-wire metadata:
1247/// strict mode reads it and inserts an assertion node upstream.
1248///
1249/// On a **const** arg it lands in the parameter's `ParamSpec`, and the
1250/// factory checks it when the node is built, before the node exists.
1251/// A program with an out-of-range constant therefore fails to assemble
1252/// with the parameter named, rather than panicking on some later cycle
1253/// from inside a node body.
1254fn parse_constraint(attrs: &[syn::Attribute]) -> syn::Result<Option<syn::Expr>> {
1255 for attr in attrs {
1256 if !attr.path().is_ident("constraint") {
1257 continue;
1258 }
1259 let expr: syn::Expr = attr.parse_args()?;
1260 return Ok(Some(expr));
1261 }
1262 Ok(None)
1263}
1264
1265/// Extract a `#[poly_const(<fn_expr>, from = <source>)]` attribute
1266/// from an arg's outer attributes, if present. Returns the
1267/// constructor expression and the source identifiers.
1268///
1269/// `from` accepts three shapes:
1270/// - `from = ()` — empty source. Setup fn takes no args;
1271/// captures session-static state (env, system clock).
1272/// - `from = ident` — single source. Setup fn called as
1273/// `setup_fn(ident_value)`.
1274/// - `from = (a, b, c)` — multi-source.
1275/// Setup fn called as `setup_fn(a_value, b_value, c_value)`.
1276/// Order matches the tuple. Each name must reference a
1277/// `Const<T>` arg declared in the same function signature.
1278fn parse_poly_const(attrs: &[syn::Attribute]) -> syn::Result<Option<(syn::Expr, Vec<syn::Ident>)>> {
1279 for attr in attrs {
1280 if !attr.path().is_ident("poly_const") {
1281 continue;
1282 }
1283 let parser = |input: syn::parse::ParseStream| -> syn::Result<(syn::Expr, Vec<syn::Ident>)> {
1284 let fn_expr: syn::Expr = input.parse()?;
1285 let _comma: Token![,] = input.parse()?;
1286 let from_kw: syn::Ident = input.parse()?;
1287 if from_kw != "from" {
1288 return Err(syn::Error::new_spanned(
1289 from_kw,
1290 "#[poly_const(...)] requires a `from = <source>` clause. \
1291 Supported shapes: `from = ()` (empty), `from = ident` \
1292 (single), `from = (a, b, c)` (multi-source).",
1293 ));
1294 }
1295 let _eq: Token![=] = input.parse()?;
1296 // Parenthesised forms: `from = ()` or `from = (a, b, c)`.
1297 if input.peek(syn::token::Paren) {
1298 let inner;
1299 let _paren = syn::parenthesized!(inner in input);
1300 if inner.is_empty() {
1301 return Ok((fn_expr, Vec::new()));
1302 }
1303 let parsed: Punctuated<syn::Ident, Token![,]> =
1304 Punctuated::parse_terminated(&inner)?;
1305 if parsed.is_empty() {
1306 return Err(syn::Error::new_spanned(
1307 from_kw,
1308 "#[poly_const(..., from = (...))] — the parenthesised \
1309 form expects a comma-separated list of source-arg \
1310 identifiers, or an empty `()` for session-static \
1311 setup.",
1312 ));
1313 }
1314 return Ok((fn_expr, parsed.into_iter().collect()));
1315 }
1316 // Bare `from = ident` — single source.
1317 let source: syn::Ident = input.parse()?;
1318 Ok((fn_expr, vec![source]))
1319 };
1320 let parsed = attr.parse_args_with(parser)?;
1321 return Ok(Some(parsed));
1322 }
1323 Ok(None)
1324}
1325
1326/// Detect `&T` for some `T` in arg-type position. Returns
1327/// `Some(inner_t)` on match, `None` otherwise. Used for the
1328/// setup-arg dispatch.
1329fn classify_borrowed(ty: &Type) -> Option<Type> {
1330 let syn::Type::Reference(r) = ty else {
1331 return None;
1332 };
1333 if r.mutability.is_some() {
1334 return None;
1335 }
1336 Some((*r.elem).clone())
1337}
1338
1339/// Whether `ty` is the build context, by value or borrowed, however
1340/// its path is qualified: its last path segment is `BuildContext`.
1341fn names_build_context(ty: &Type) -> bool {
1342 let ty = match ty {
1343 syn::Type::Reference(r) => &*r.elem,
1344 other => other,
1345 };
1346 let syn::Type::Path(p) = ty else {
1347 return false;
1348 };
1349 p.path
1350 .segments
1351 .last()
1352 .is_some_and(|s| s.ident == "BuildContext")
1353}
1354
1355/// Detect `Value` in arg-type position, for
1356/// polymorphic wire dispatch. Matches the last path segment
1357/// being `Value`, so both `Value` and `polydat::ast::Value`
1358/// (and any other fully-qualified path ending in `Value`) work.
1359fn classify_polywire(ty: &Type) -> bool {
1360 let syn::Type::Path(p) = ty else {
1361 return false;
1362 };
1363 p.path
1364 .segments
1365 .last()
1366 .map(|s| s.ident == "Value")
1367 .unwrap_or(false)
1368}
1369
1370/// Structural classifier for the
1371/// wrapper-typed wire arg shapes. Returns the matching wire
1372/// kind, or `None` if the type isn't one of the recognised
1373/// wrapper shapes.
1374#[derive(Clone, Copy, PartialEq, Eq)]
1375enum WrapperWire {
1376 Bytes,
1377 Json,
1378 /// `Arc<T>` for some T that isn't `[u8]` or `serde_json::Value`.
1379 /// Inline-downcast in arg_bindings; inline-upcast in
1380 /// result_to_outputs. Handle dispatch.
1381 Handle,
1382 /// One of the seven typed vector variants: `VecF32` / `VecI32`
1383 /// / `VecF64` / `VecI64` / `VecF16` / `VecI16` / `VecI8`. The
1384 /// macro emits the matching `PortType::Vec*`; the Wire impls in
1385 /// derive_support are autogenerated from a macro_rules!
1386 /// expansion per element type.
1387 VecF32,
1388 VecI32,
1389 VecF64,
1390 VecI64,
1391 VecF16,
1392 VecI16,
1393 VecI8,
1394}
1395
1396fn classify_wrapper_wire(ty: &Type) -> Option<WrapperWire> {
1397 // Typed vectors. Check first to catch
1398 // `Vec<f32>` etc. before they fall into Handle territory
1399 // (which is the catch-all for Arc<T>).
1400 if let Some(kind) = classify_vec_wire(ty) {
1401 return Some(kind);
1402 }
1403
1404 // `Arc<[u8]>` — Arc with [u8] generic.
1405 if let Some(inner) = strip_arc(ty)
1406 && let syn::Type::Slice(slc) = inner
1407 && let syn::Type::Path(p) = &*slc.elem
1408 && p.path.is_ident("u8")
1409 {
1410 return Some(WrapperWire::Bytes);
1411 }
1412 // `Arc<serde_json::Value>` / `Arc<Value>` (last segment).
1413 if let Some(inner) = strip_arc(ty)
1414 && let syn::Type::Path(p) = inner
1415 && last_segment_is(p, "Value")
1416 && path_contains_segment(p, "serde_json")
1417 {
1418 return Some(WrapperWire::Json);
1419 }
1420 // `Arc<str>` — Str port via the dedicated Wire impl. Don't
1421 // route through Handle (str isn't Sized so the Handle's
1422 // `Value::handle<T: Sized>` constructor would reject it).
1423 if let Some(inner) = strip_arc(ty)
1424 && let syn::Type::Path(p) = inner
1425 && p.path.is_ident("str")
1426 {
1427 return None;
1428 }
1429 // `Arc<dyn Any + Send + Sync>` — Handle via the dedicated
1430 // Wire impl. Fall through to trait dispatch rather than
1431 // the structural Handle path (which expects a concrete
1432 // Arc<ConcreteT> for the downcast).
1433 if let Some(inner) = strip_arc(ty)
1434 && matches!(inner, syn::Type::TraitObject(_))
1435 {
1436 return None;
1437 }
1438 // Any other `Arc<T>` is a Handle.
1439 if strip_arc(ty).is_some() {
1440 return Some(WrapperWire::Handle);
1441 }
1442 // `Vec<u8>`.
1443 if let syn::Type::Path(p) = ty
1444 && let Some(last) = p.path.segments.last()
1445 && last.ident == "Vec"
1446 && let syn::PathArguments::AngleBracketed(args) = &last.arguments
1447 && let Some(syn::GenericArgument::Type(syn::Type::Path(elem))) = args.args.first()
1448 && elem.path.is_ident("u8")
1449 {
1450 return Some(WrapperWire::Bytes);
1451 }
1452 // `&[u8]` — borrowed bytes.
1453 if let syn::Type::Reference(r) = ty
1454 && r.mutability.is_none()
1455 && let syn::Type::Slice(slc) = &*r.elem
1456 && let syn::Type::Path(p) = &*slc.elem
1457 && p.path.is_ident("u8")
1458 {
1459 return Some(WrapperWire::Bytes);
1460 }
1461 // `&serde_json::Value`.
1462 if let syn::Type::Reference(r) = ty
1463 && r.mutability.is_none()
1464 && let syn::Type::Path(p) = &*r.elem
1465 && last_segment_is(p, "Value")
1466 && path_contains_segment(p, "serde_json")
1467 {
1468 return Some(WrapperWire::Json);
1469 }
1470 None
1471}
1472
1473fn strip_arc(ty: &Type) -> Option<&Type> {
1474 let syn::Type::Path(p) = ty else {
1475 return None;
1476 };
1477 let last = p.path.segments.last()?;
1478 if last.ident != "Arc" {
1479 return None;
1480 }
1481 let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
1482 return None;
1483 };
1484 args.args.iter().find_map(|a| match a {
1485 syn::GenericArgument::Type(t) => Some(t),
1486 _ => None,
1487 })
1488}
1489
1490fn last_segment_is(p: &syn::TypePath, name: &str) -> bool {
1491 p.path
1492 .segments
1493 .last()
1494 .map(|s| s.ident == name)
1495 .unwrap_or(false)
1496}
1497
1498fn path_contains_segment(p: &syn::TypePath, name: &str) -> bool {
1499 p.path.segments.iter().any(|s| s.ident == name)
1500}
1501
1502/// For a `Handle` arg, extract the inner T (the downcast target).
1503fn extract_handle_inner(ty: &Type) -> Option<Type> {
1504 strip_arc(ty).cloned()
1505}
1506
1507/// `Option<T>` recognition. Returns `true` if the type's last
1508/// path segment is `Option` with a single generic argument. Used
1509/// to decide whether to auto-emit `accepts_none_inputs() -> true`
1510/// — the runtime kernel's None rule (engines.md §3.3) short-circuits `Value::None`
1511/// inputs on opt-in nodes; `Option<T>` wires are the canonical
1512/// opt-in shape.
1513fn is_option_arg(ty: &Type) -> bool {
1514 let syn::Type::Path(p) = ty else {
1515 return false;
1516 };
1517 let Some(last) = p.path.segments.last() else {
1518 return false;
1519 };
1520 if last.ident != "Option" {
1521 return false;
1522 }
1523 matches!(&last.arguments,
1524 syn::PathArguments::AngleBracketed(args)
1525 if args.args.iter().any(|a| matches!(a, syn::GenericArgument::Type(_))))
1526}
1527
1528/// Borrow-shape detection. The macro
1529/// dispatches owned types through `<T as Wire>::extract` / `::inject`;
1530/// borrow shapes are recognised syntactically and emitted as
1531/// direct `match`-on-`Value` extraction at the eval call site.
1532/// This keeps the [`Wire`] trait bound at `Sized + 'static` without
1533/// needing lifetime parameters.
1534///
1535/// Returns the matched `Value::<Variant>(inner)` pattern and the
1536/// accessor expression that yields the body's expected borrow.
1537#[derive(Clone)]
1538enum BorrowWire {
1539 /// `&str` → `Value::Str(arc)` → `arc.as_ref()` (`&str`).
1540 Str,
1541 /// `&[u8]` → `Value::Bytes(arc)` → `arc.as_ref()` (`&[u8]`).
1542 Bytes,
1543 /// `&serde_json::Value` → `Value::Json(j)` → `j.as_ref()`.
1544 Json,
1545 /// `&[T]` for T in {f32, i32, f64, i64, f16, i16} — typed
1546 /// vector borrow. Variant tracked separately so we can emit
1547 /// the right `Value::Vec*` arm; element type is recovered
1548 /// from the syntactic recognition.
1549 Vec(
1550 &'static str, /* variant name */
1551 TokenStream2, /* PortType expr */
1552 ),
1553}
1554
1555/// `Ext<T>` for some `T`: an extension value that rides a `Ref2`
1556/// pair into step-owned scratch (compiled_handles.md §3) and reaches
1557/// the body through `Wire::extract`. The generic path handles it on
1558/// the interpreter; this recognizer lets the slot kit carry it too.
1559fn is_ext_wire(ty: &Type) -> bool {
1560 is_generic_named(ty, "Ext")
1561}
1562
1563/// Whether `ty` is a path type whose last segment is `name` with
1564/// angle-bracketed arguments, however the path is qualified: `Ext<T>`,
1565/// `crate::derive_support::Ext<T>`, and `polydat::derive_support::Ext<T>`
1566/// all match `"Ext"`. The type is read by its syn path rather than by
1567/// its rendered tokens, which space a `::` as `: :`.
1568fn is_generic_named(ty: &Type, name: &str) -> bool {
1569 let Type::Path(p) = ty else { return false };
1570 p.qself.is_none()
1571 && p.path.segments.last().is_some_and(|last| {
1572 last.ident == name && matches!(last.arguments, syn::PathArguments::AngleBracketed(_))
1573 })
1574}
1575
1576fn is_borrow_wire_shape(ty: &Type) -> Option<BorrowWire> {
1577 let syn::Type::Reference(r) = ty else {
1578 return None;
1579 };
1580 if r.mutability.is_some() {
1581 return None;
1582 }
1583 match &*r.elem {
1584 // `&str`
1585 syn::Type::Path(p) if p.path.is_ident("str") => Some(BorrowWire::Str),
1586 // `&[T]` — bytes (T=u8) and typed vectors.
1587 syn::Type::Slice(slc) => {
1588 if let syn::Type::Path(p) = &*slc.elem {
1589 if p.path.is_ident("u8") {
1590 return Some(BorrowWire::Bytes);
1591 }
1592 let elem_name = p.path.segments.last()?.ident.to_string();
1593 let (variant, port_expr) = match elem_name.as_str() {
1594 "f32" => ("VecF32", quote!(polydat::ast::PortType::VecF32)),
1595 "i32" => ("VecI32", quote!(polydat::ast::PortType::VecI32)),
1596 "f64" => ("VecF64", quote!(polydat::ast::PortType::VecF64)),
1597 "i64" => ("VecI64", quote!(polydat::ast::PortType::VecI64)),
1598 "f16" => ("VecF16", quote!(polydat::ast::PortType::VecF16)),
1599 "i16" => ("VecI16", quote!(polydat::ast::PortType::VecI16)),
1600 "i8" => ("VecI8", quote!(polydat::ast::PortType::VecI8)),
1601 _ => return None,
1602 };
1603 return Some(BorrowWire::Vec(variant, port_expr));
1604 }
1605 None
1606 }
1607 // `&serde_json::Value` — recognise by last segment `Value`
1608 // alongside `serde_json` somewhere in the path.
1609 syn::Type::Path(p)
1610 if last_segment_is(p, "Value") && path_contains_segment(p, "serde_json") =>
1611 {
1612 Some(BorrowWire::Json)
1613 }
1614 _ => None,
1615 }
1616}
1617
1618/// Token stream for extracting a borrow-shape wire from
1619/// `&inputs[idx]`. The macro emits this directly (no trait
1620/// dispatch) so the borrow's lifetime is bound to the eval
1621/// call's `&inputs` borrow naturally — no `unsafe transmute`.
1622fn borrow_extract_tokens(shape: BorrowWire, input_expr: TokenStream2) -> TokenStream2 {
1623 match shape {
1624 BorrowWire::Str => quote! {
1625 match #input_expr {
1626 polydat::ast::Value::Str(__arc) => __arc.as_ref(),
1627 __other => panic!("expected Str wire, got {__other:?}"),
1628 }
1629 },
1630 BorrowWire::Bytes => quote! {
1631 match #input_expr {
1632 polydat::ast::Value::Bytes(__arc) => __arc.as_ref(),
1633 __other => panic!("expected Bytes wire, got {__other:?}"),
1634 }
1635 },
1636 BorrowWire::Json => quote! {
1637 match #input_expr {
1638 polydat::ast::Value::Json(__arc) => __arc.as_ref(),
1639 __other => panic!("expected Json wire, got {__other:?}"),
1640 }
1641 },
1642 BorrowWire::Vec(variant, _port) => {
1643 let v = syn::Ident::new(variant, proc_macro2::Span::call_site());
1644 quote! {
1645 match #input_expr {
1646 polydat::ast::Value::#v(__arc) => __arc.as_slice(),
1647 __other => panic!(
1648 concat!("expected ", stringify!(#v), " wire, got {:?}"),
1649 __other),
1650 }
1651 }
1652 }
1653 }
1654}
1655
1656/// Token stream for the static `PortType` of a borrow-shape wire.
1657fn borrow_port_type(shape: &BorrowWire) -> TokenStream2 {
1658 match shape {
1659 BorrowWire::Str => quote!(polydat::ast::PortType::Str),
1660 BorrowWire::Bytes => quote!(polydat::ast::PortType::Bytes),
1661 BorrowWire::Json => quote!(polydat::ast::PortType::Json),
1662 BorrowWire::Vec(_, port_expr) => port_expr.clone(),
1663 }
1664}
1665
1666/// Typed-vector classifier. Recognises three
1667/// input shapes per element type: `SliceArc<T>`, `Vec<T>`,
1668/// `&[T]`. The element type's last path segment selects the
1669/// `WrapperWire::Vec*` variant.
1670fn classify_vec_wire(ty: &Type) -> Option<WrapperWire> {
1671 // Extract the element type from whichever of the three shapes
1672 // matches; none matching means this is not a typed vector.
1673 let elem: Type = strip_vec(ty)
1674 .or_else(|| strip_slice_arc(ty))
1675 .or_else(|| strip_borrowed_slice(ty))?
1676 .clone();
1677
1678 let syn::Type::Path(p) = &elem else {
1679 return None;
1680 };
1681 let last = p.path.segments.last()?;
1682 // f16 lives in the `half` crate, so the element path can
1683 // be `f16`, `half::f16`, etc. — match by last segment.
1684 match last.ident.to_string().as_str() {
1685 "f32" => Some(WrapperWire::VecF32),
1686 "i32" => Some(WrapperWire::VecI32),
1687 "f64" => Some(WrapperWire::VecF64),
1688 "i64" => Some(WrapperWire::VecI64),
1689 "f16" => Some(WrapperWire::VecF16),
1690 "i16" => Some(WrapperWire::VecI16),
1691 "i8" => Some(WrapperWire::VecI8),
1692 _ => None,
1693 }
1694}
1695
1696fn strip_vec(ty: &Type) -> Option<&Type> {
1697 let syn::Type::Path(p) = ty else {
1698 return None;
1699 };
1700 let last = p.path.segments.last()?;
1701 if last.ident != "Vec" {
1702 return None;
1703 }
1704 let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
1705 return None;
1706 };
1707 args.args.iter().find_map(|a| match a {
1708 syn::GenericArgument::Type(t) => Some(t),
1709 _ => None,
1710 })
1711}
1712
1713fn strip_slice_arc(ty: &Type) -> Option<&Type> {
1714 let syn::Type::Path(p) = ty else {
1715 return None;
1716 };
1717 let last = p.path.segments.last()?;
1718 if last.ident != "SliceArc" {
1719 return None;
1720 }
1721 let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
1722 return None;
1723 };
1724 args.args.iter().find_map(|a| match a {
1725 syn::GenericArgument::Type(t) => Some(t),
1726 _ => None,
1727 })
1728}
1729
1730fn strip_borrowed_slice(ty: &Type) -> Option<&Type> {
1731 let syn::Type::Reference(r) = ty else {
1732 return None;
1733 };
1734 if r.mutability.is_some() {
1735 return None;
1736 }
1737 let syn::Type::Slice(slc) = &*r.elem else {
1738 return None;
1739 };
1740 Some(&slc.elem)
1741}
1742
1743/// Detect `&[T]` (variadic) in arg-type position.
1744/// Returns the recognised element type for the supported primitive
1745/// element set; `None` otherwise (bare reference, non-slice, or
1746/// unsupported element type). Structural match — works regardless
1747/// of how the inner type is written (`Value` / `polydat::ast::Value`).
1748fn classify_variadic(ty: &Type) -> Option<VariadicElement> {
1749 let syn::Type::Reference(r) = ty else {
1750 return None;
1751 };
1752 if r.mutability.is_some() {
1753 return None;
1754 }
1755 let syn::Type::Slice(s) = &*r.elem else {
1756 return None;
1757 };
1758
1759 // `&[&str]` — element is a Type::Reference to a path "str".
1760 if let syn::Type::Reference(inner_r) = &*s.elem
1761 && inner_r.mutability.is_none()
1762 && let syn::Type::Path(p) = &*inner_r.elem
1763 && p.path.is_ident("str")
1764 {
1765 return Some(VariadicElement::BorrowedStr);
1766 }
1767
1768 // Bare-path element types — match by last path segment ident.
1769 let syn::Type::Path(p) = &*s.elem else {
1770 return None;
1771 };
1772 let last = p.path.segments.last()?;
1773 if !last.arguments.is_empty() {
1774 return None;
1775 }
1776 match last.ident.to_string().as_str() {
1777 "u64" => Some(VariadicElement::U64),
1778 // NOTE: `&[f64]` is deliberately NOT variadic — it is the
1779 // `VecF64` vector wire, uniform with every other lane
1780 // element (`&[f32]`/`&[i32]`/…). A variadic run of f64
1781 // wires would need an explicit `Variadic<f64>` spelling.
1782 "bool" => Some(VariadicElement::Bool),
1783 "String" => Some(VariadicElement::OwnedString),
1784 "Value" => Some(VariadicElement::Value),
1785 _ => None,
1786 }
1787}
1788
1789/// Detect `Result<T, E>` return type for
1790/// fallible-construction nodes. Returns `Some(T)` (the Ok type)
1791/// when the return is a `Result<T, _>`; `None` otherwise. Matches
1792/// any path ending in `Result` so both bare `Result` and fully
1793/// qualified `std::result::Result` work.
1794///
1795/// The Err arm is consumed for its `Into<String>` projection at
1796/// emission time, so we don't pin its shape here — any E that
1797/// satisfies `Into<String>` (including `String` itself) is fine.
1798fn classify_result_return(ty: &Type) -> Option<Type> {
1799 let syn::Type::Path(p) = ty else {
1800 return None;
1801 };
1802 let last = p.path.segments.last()?;
1803 if last.ident != "Result" {
1804 return None;
1805 }
1806 let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
1807 return None;
1808 };
1809 // Two args expected: <Ok, Err>. Tolerate `Result<T>` (rare alias)
1810 // by requiring at least one type arg.
1811 let mut tys = args.args.iter().filter_map(|a| match a {
1812 syn::GenericArgument::Type(t) => Some(t.clone()),
1813 _ => None,
1814 });
1815 tys.next()
1816}
1817
1818fn generate(func: ItemFn, attrs: NodeAttrs) -> syn::Result<TokenStream2> {
1819 let fn_name = &func.sig.ident;
1820 // Strip `r#` from raw identifiers (`fn r#mod`,
1821 // `fn r#type`, etc.) so the Rust struct name comes out clean.
1822 let fn_name_raw = fn_name.to_string();
1823 let rust_name_str = fn_name_raw
1824 .strip_prefix("r#")
1825 .unwrap_or(&fn_name_raw)
1826 .to_string();
1827 let struct_name = attrs
1828 .struct_name
1829 .clone()
1830 .unwrap_or_else(|| format_ident!("{}", to_camel_case(&rust_name_str)));
1831 let func_name_str = rust_name_str.clone();
1832 let category = &attrs.category;
1833
1834 // Classify each function arg: wire or const? Reject any
1835 // unsupported pattern (self, complex destructuring, bare-
1836 // type wires the macro doesn't recognize).
1837 let mut args: Vec<ClassifiedArg> = Vec::new();
1838 for input in &func.sig.inputs {
1839 match input {
1840 FnArg::Receiver(r) => {
1841 return Err(syn::Error::new_spanned(
1842 r,
1843 "#[polydat_node] does not support `self` parameters; \
1844 a node keeps state through `state = <path>` or a `#[poly_const]` setup argument.",
1845 ));
1846 }
1847 FnArg::Typed(pat_ty) => {
1848 let ident = match &*pat_ty.pat {
1849 Pat::Ident(p) => p.ident.clone(),
1850 other => {
1851 return Err(syn::Error::new_spanned(
1852 other,
1853 "#[polydat_node] requires plain identifier parameters; \
1854 pattern matching in argument position isn't supported.",
1855 ));
1856 }
1857 };
1858 let declared_ty = (*pat_ty.ty).clone();
1859 let default_value = parse_poly_default(&pat_ty.attrs)?;
1860 let setup_attr = parse_poly_const(&pat_ty.attrs)?;
1861 let constraint = parse_constraint(&pat_ty.attrs)?;
1862 let is_polywire = classify_polywire(&declared_ty);
1863 let variadic_elem = classify_variadic(&declared_ty);
1864
1865 // The build context reaches a node at construction,
1866 // through a setup; the body runs per evaluation and
1867 // takes no context.
1868 if setup_attr.is_none() && names_build_context(&declared_ty) {
1869 return Err(syn::Error::new_spanned(
1870 pat_ty,
1871 "a node reads its build context at construction, through a setup: \
1872 `#[poly_const(setup, from = ctx)] name: &T` with \
1873 `fn setup(ctx: &BuildContext) -> T`. The body runs on every \
1874 evaluation and takes no build context.",
1875 ));
1876 }
1877
1878 let kind = if let Some(elem) = variadic_elem {
1879 if default_value.is_some() || setup_attr.is_some() || is_polywire {
1880 return Err(syn::Error::new_spanned(
1881 pat_ty,
1882 "variadic `&[T]` args don't combine with \
1883 #[poly_default(...)], #[poly_const(...)], or `Value`.",
1884 ));
1885 }
1886 ArgKind::Variadic(elem)
1887 } else if is_polywire {
1888 if default_value.is_some() || setup_attr.is_some() {
1889 return Err(syn::Error::new_spanned(
1890 pat_ty,
1891 "`Value` args (PolyWire) don't combine with \
1892 #[poly_default(...)] or #[poly_const(...)]; \
1893 the runtime port type comes from the upstream wire \
1894 at construction time.",
1895 ));
1896 }
1897 ArgKind::PolyWire
1898 } else if let Some((setup_fn, source_args)) = setup_attr {
1899 // `#[poly_const(...)]` requires `&T` arg type.
1900 let inner_ty = classify_borrowed(&declared_ty).ok_or_else(|| {
1901 syn::Error::new_spanned(
1902 &declared_ty,
1903 "#[poly_const(...)] requires the argument type to be \
1904 a borrow `&T` — the macro stores the computed `T` \
1905 in a struct field and hands the body a borrow each \
1906 eval.",
1907 )
1908 })?;
1909 if default_value.is_some() {
1910 return Err(syn::Error::new_spanned(
1911 pat_ty,
1912 "#[poly_default(...)] cannot combine with \
1913 #[poly_const(...)]; defaults belong on the source \
1914 Const arg, not on the derived setup arg.",
1915 ));
1916 }
1917 // `ctx` names the build context, and only as the
1918 // setup fn's first argument.
1919 let mut source_args = source_args;
1920 let ctx = if source_args.first().is_some_and(|s| s == CTX_SOURCE) {
1921 Some(source_args.remove(0))
1922 } else {
1923 None
1924 };
1925 if let Some(late) = source_args.iter().find(|s| *s == CTX_SOURCE) {
1926 return Err(syn::Error::new(
1927 late.span(),
1928 "`ctx`, the build context, is the setup fn's first argument: \
1929 write `from = (ctx, ...)` and `fn setup(ctx: &BuildContext, ...)`.",
1930 ));
1931 }
1932 ArgKind::Setup(Box::new(SetupSpec {
1933 inner_ty,
1934 setup_fn,
1935 source_args,
1936 ctx,
1937 }))
1938 } else if let Some(list) = classify_const_vec(&declared_ty) {
1939 // `Const<Vec<C>>` variadic
1940 // workload-list. `poly_default` doesn't apply
1941 // (the empty list IS the default); other
1942 // attributes don't compose.
1943 if default_value.is_some() {
1944 return Err(syn::Error::new_spanned(
1945 pat_ty,
1946 "#[poly_default(...)] cannot combine with \
1947 `Const<Vec<C>>`; the empty Vec IS the implicit \
1948 default. Use `Const<C>` with a poly_default \
1949 literal for a single-value default instead.",
1950 ));
1951 }
1952 if setup_attr.is_some() {
1953 return Err(syn::Error::new_spanned(
1954 pat_ty,
1955 "`Const<Vec<C>>` doesn't combine with \
1956 #[poly_const(...)]; route the derived state \
1957 from a scalar `Const<C>` source instead.",
1958 ));
1959 }
1960 ArgKind::ConstVec(list.0, list.1)
1961 } else {
1962 match classify_type(&declared_ty) {
1963 Some(shape) => ArgKind::Const(shape),
1964 None => {
1965 if default_value.is_some() {
1966 return Err(syn::Error::new_spanned(
1967 pat_ty,
1968 "#[poly_default(...)] only applies to const args \
1969 (`Const<T>`); bare-type wire args don't have \
1970 assembly-time defaults.",
1971 ));
1972 }
1973 ArgKind::Wire
1974 }
1975 }
1976 };
1977 args.push(ClassifiedArg {
1978 name: ident,
1979 declared_ty,
1980 kind,
1981 default_value,
1982 constraint,
1983 });
1984 }
1985 }
1986 }
1987
1988 // `Const<Vec<C>>` consumes the tail of
1989 // `consts[..]` at build time, so at most one ConstVec arg is
1990 // allowed per node and it must be the last const arg in
1991 // declaration order. Validate before emission.
1992 {
1993 let const_vec_positions: Vec<usize> = args
1994 .iter()
1995 .enumerate()
1996 .filter_map(|(i, a)| {
1997 if matches!(a.kind, ArgKind::ConstVec(..)) {
1998 Some(i)
1999 } else {
2000 None
2001 }
2002 })
2003 .collect();
2004 if const_vec_positions.len() > 1 {
2005 return Err(syn::Error::new_spanned(
2006 &args[const_vec_positions[1]].declared_ty,
2007 "#[polydat_node] supports at most one `Const<Vec<C>>` arg \
2008 per function; the variadic-const surface consumes the \
2009 tail of the consts slice and a second one would have no \
2010 entries to claim.",
2011 ));
2012 }
2013 if let Some(&pos) = const_vec_positions.first() {
2014 // Any Const(_) declared AFTER the ConstVec would never
2015 // bind (its index ≥ ConstVec's tail-start).
2016 for later in &args[pos + 1..] {
2017 if matches!(later.kind, ArgKind::Const(_)) {
2018 return Err(syn::Error::new_spanned(
2019 &later.declared_ty,
2020 "scalar `Const<T>` arg declared after a \
2021 `Const<Vec<C>>` arg is unreachable — the variadic \
2022 consumes everything from its position to the end \
2023 of the consts slice. Move the scalar consts BEFORE \
2024 the `Const<Vec<C>>` in the function signature.",
2025 ));
2026 }
2027 }
2028 }
2029 }
2030
2031 // Every name a setup's `from = ...` lists is a const argument of
2032 // the same function: the setup runs at construction, when only
2033 // the consts are known.
2034 for a in &args {
2035 let ArgKind::Setup(spec) = &a.kind else {
2036 continue;
2037 };
2038 for src in &spec.source_args {
2039 let is_const = args.iter().any(|c| {
2040 c.name == *src && matches!(c.kind, ArgKind::Const(_) | ArgKind::ConstVec(..))
2041 });
2042 if !is_const {
2043 return Err(syn::Error::new(
2044 src.span(),
2045 format!(
2046 "#[poly_const(... from = ... {src} ...)] — `{src}` is not \
2047 declared as a `Const<T>` arg in the same function signature."
2048 ),
2049 ));
2050 }
2051 }
2052 }
2053
2054 // A setup that reads the build context makes `ctx` the first
2055 // parameter of `new()`, and `from` lists read `ctx` as the
2056 // context, so no argument of the node takes the name.
2057 let takes_ctx = args
2058 .iter()
2059 .any(|a| matches!(&a.kind, ArgKind::Setup(spec) if spec.takes_ctx()));
2060 if takes_ctx && let Some(clash) = args.iter().find(|a| a.name == CTX_SOURCE) {
2061 return Err(syn::Error::new(
2062 clash.name.span(),
2063 "`ctx` names the build context in a `from` list; rename this argument.",
2064 ));
2065 }
2066
2067 // Map a bare wire-arg type to a PortType expression.
2068 //
2069 // The canonical answer is `<#ty as Wire>::PORT` —
2070 // any owned type that impls [`Wire`] is admitted, and adding
2071 // a new wire type means adding one Wire impl (no macro
2072 // source change). Three exceptions stay structural because
2073 // they can't be expressed through the trait:
2074 //
2075 // 1. Borrow shapes (`&str`, `&[u8]`, `&[T]`,
2076 // `&serde_json::Value`) — `Wire` is `Sized + 'static`
2077 // so borrowed refs can't impl it. The macro emits the
2078 // literal `PortType` here and direct `match`-on-`Value`
2079 // extraction elsewhere.
2080 //
2081 // 2. `Arc<T>` Handle (non-special T) — would conflict with
2082 // the concrete `Arc<[u8]>` / `Arc<serde_json::Value>`
2083 // impls if expressed as a blanket. Kept as inline
2084 // downcast at the extract site; port type is the static
2085 // `Handle`.
2086 //
2087 // 3. PolyWire (`Value`-typed wire) — polymorphic at
2088 // runtime; no static `PortType`. The `ArgKind::PolyWire`
2089 // path handles this independently of `wire_port_type_for`.
2090 //
2091 // Everything else — including `Option<T>`, `Ext<T>`, and any
2092 // future combinator added by impl'ing `Wire` — flows through
2093 // trait dispatch.
2094 let wire_port_type_for = |ty: &Type| -> syn::Result<TokenStream2> {
2095 if let Some(kind) = classify_wrapper_wire(ty) {
2096 return Ok(match kind {
2097 WrapperWire::Bytes => quote!(polydat::ast::PortType::Bytes),
2098 WrapperWire::Json => quote!(polydat::ast::PortType::Json),
2099 WrapperWire::Handle => quote!(polydat::ast::PortType::Handle),
2100 WrapperWire::VecF32 => quote!(polydat::ast::PortType::VecF32),
2101 WrapperWire::VecI32 => quote!(polydat::ast::PortType::VecI32),
2102 WrapperWire::VecF64 => quote!(polydat::ast::PortType::VecF64),
2103 WrapperWire::VecI64 => quote!(polydat::ast::PortType::VecI64),
2104 WrapperWire::VecF16 => quote!(polydat::ast::PortType::VecF16),
2105 WrapperWire::VecI16 => quote!(polydat::ast::PortType::VecI16),
2106 WrapperWire::VecI8 => quote!(polydat::ast::PortType::VecI8),
2107 });
2108 }
2109 if let Some(borrow) = is_borrow_wire_shape(ty) {
2110 return Ok(borrow_port_type(&borrow));
2111 }
2112 // Fall through to trait dispatch — `<T as Wire>::PORT` is
2113 // a const associated, evaluable at codegen time. Types
2114 // without a `Wire` impl produce a clean E0277 at the
2115 // function's call site, naming the missing trait bound.
2116 Ok(quote!(<#ty as polydat::derive_support::Wire>::PORT))
2117 };
2118
2119 // Build the NodeMeta `ins` slot list — one entry per arg,
2120 // dispatched by kind. Wire args get `Slot::Wire(...)`;
2121 // const args get `Slot::Const { ... }` populated with the
2122 // captured field value at construction time.
2123 let mut slot_exprs: Vec<TokenStream2> = Vec::new();
2124 for a in &args {
2125 let name_str = a.name.to_string();
2126 match &a.kind {
2127 ArgKind::Wire => {
2128 let pt = wire_port_type_for(&a.declared_ty)?;
2129 let ty = &a.declared_ty;
2130 // Optional `#[constraint(Variant)]`.
2131 let constraint_chain = if let Some(variant) = &a.constraint {
2132 quote! {
2133 .with_constraint(
2134 polydat::dsl::const_constraints::ConstConstraint::#variant)
2135 }
2136 } else {
2137 quote!()
2138 };
2139 // `Wire::WIRE_COST` is read
2140 // from the trait at codegen. Owned/non-borrow
2141 // wire types route here; borrow shapes don't
2142 // impl Wire so they get the default Data cost
2143 // (the WireCost::Config opt-in only applies to
2144 // owned types wrapped in `Config<T>`).
2145 let cost_chain = if is_borrow_wire_shape(ty).is_none()
2146 && classify_wrapper_wire(ty) != Some(WrapperWire::Handle)
2147 {
2148 quote! {
2149 .with_cost(<#ty as polydat::derive_support::Wire>::WIRE_COST)
2150 }
2151 } else {
2152 quote!()
2153 };
2154 slot_exprs.push(quote! {
2155 polydat::ast::Slot::Wire(
2156 polydat::ast::Port::new(#name_str, #pt)
2157 #constraint_chain
2158 #cost_chain
2159 )
2160 });
2161 }
2162 ArgKind::Const(shape) => {
2163 let field_name = &a.name;
2164 let const_value_ctor = match shape {
2165 ConstShape::U64 => quote!(polydat::ast::ConstValue::U64(#field_name)),
2166 ConstShape::F64 => quote!(polydat::ast::ConstValue::F64(#field_name)),
2167 ConstShape::Bool => {
2168 quote!(polydat::ast::ConstValue::U64(if #field_name { 1 } else { 0 }))
2169 }
2170 ConstShape::Str => quote!(polydat::ast::ConstValue::Str(#field_name.clone())),
2171 // A compiler-built value has no literal form. Its
2172 // slot names the argument and says what it is, so
2173 // the meta reads honestly and no walker mistakes
2174 // it for a constant it can fold.
2175 ConstShape::Opaque => {
2176 quote!(polydat::ast::ConstValue::Str(
2177 "<compiler-built>".to_string()
2178 ))
2179 }
2180 };
2181 slot_exprs.push(quote! {
2182 polydat::ast::Slot::Const {
2183 name: #name_str.into(),
2184 value: #const_value_ctor,
2185 }
2186 });
2187 }
2188 ArgKind::Setup(_) => {
2189 // Setup args don't appear in NodeMeta.ins —
2190 // they're derived state, not declared params.
2191 // The source Const arg already carries the
2192 // introspectable value.
2193 }
2194 ArgKind::PolyWire => {
2195 // Port type is the `<argname>_type` parameter
2196 // passed to `new()`; the variable is in scope
2197 // because the macro emits it as a `new()` param.
2198 let pt_param = format_ident!("{}_type", a.name);
2199 slot_exprs.push(quote! {
2200 polydat::ast::Slot::Wire(polydat::ast::Port::new(
2201 #name_str, #pt_param))
2202 });
2203 }
2204 ArgKind::Variadic(_) => {
2205 // Variadic emits per-element slots at construction.
2206 // The macro generates `extend` into the slot vec
2207 // from a 0..n_wires loop. Each slot is named
2208 // `<argname>_<i>` to keep the meta diff-friendly.
2209 // (Handled in the new() body via a separate pass —
2210 // see `variadic_slot_extends` below.)
2211 }
2212 ArgKind::ConstVec(inner, _) => {
2213 // `Const<Vec<C>>` emits a `Slot::Const`
2214 // entry when the inner element has a matching
2215 // `ConstValue::Vec*` variant (u64, f64). This
2216 // makes the captured list visible to JIT slot-
2217 // walkers and introspection (`jit_constants_from_slots`).
2218 // For element types without a parallel
2219 // `ConstValue` variant (bool, Str), no slot is
2220 // emitted; the FuncSig's `Arity::VariadicConsts`
2221 // tracks the surface and the stored Vec<C> field
2222 // is the canonical storage.
2223 let field_name = &a.name;
2224 match inner {
2225 ConstShape::U64 => slot_exprs.push(quote! {
2226 polydat::ast::Slot::Const {
2227 name: #name_str.into(),
2228 value: polydat::ast::ConstValue::VecU64(#field_name.clone()),
2229 }
2230 }),
2231 ConstShape::F64 => slot_exprs.push(quote! {
2232 polydat::ast::Slot::Const {
2233 name: #name_str.into(),
2234 value: polydat::ast::ConstValue::VecF64(#field_name.clone()),
2235 }
2236 }),
2237 _ => {}
2238 }
2239 }
2240 }
2241 }
2242 // For each variadic arg, also emit a runtime loop that
2243 // appends N slots to the `Slot` vec.
2244 let variadic_slot_extends: Vec<TokenStream2> = args
2245 .iter()
2246 .filter_map(|a| match &a.kind {
2247 ArgKind::Variadic(elem) => {
2248 let name_str = a.name.to_string();
2249 let pt = elem.port_type_tokens();
2250 // A `&[Value]` variadic takes each wire as it is: the
2251 // body reads the `Value` variant, so an adapter into
2252 // the slot's nominal type would change what it sees.
2253 let any_type = if matches!(elem, VariadicElement::Value) {
2254 quote!(.any_type())
2255 } else {
2256 quote!()
2257 };
2258 Some(quote! {
2259 for __i in 0..n_wires {
2260 ins.push(polydat::ast::Slot::Wire(
2261 polydat::ast::Port::new(
2262 format!("{}_{__i}", #name_str),
2263 #pt,
2264 )#any_type));
2265 }
2266 })
2267 }
2268 _ => None,
2269 })
2270 .collect();
2271
2272 // Build the FuncSig.params static slice — one ParamSpec
2273 // per declared arg (Wire and Const). Setup args don't
2274 // appear in the FuncSig surface — they're macro-internal
2275 // derived state.
2276 let param_specs: Vec<TokenStream2> = args
2277 .iter()
2278 .filter_map(|a| {
2279 let name_str = a.name.to_string();
2280 // Variadic args declare `required: false` — they accept
2281 // any count from `variadic_min` (default 0) upward.
2282 // `ConstVec` follows the same pattern (empty is valid).
2283 let required = match &a.kind {
2284 ArgKind::Variadic(_) | ArgKind::ConstVec(..) => false,
2285 _ => a.default_value.is_none(),
2286 };
2287 let slot_type = match &a.kind {
2288 ArgKind::Wire | ArgKind::PolyWire | ArgKind::Variadic(_) => {
2289 quote!(polydat::ast::SlotType::Wire)
2290 }
2291 ArgKind::Const(shape) => shape.slot_type_tokens(),
2292 ArgKind::ConstVec(inner, _) => inner.slot_type_tokens(),
2293 ArgKind::Setup(_) => return None,
2294 };
2295 // A declared `#[constraint(...)]` on a const argument
2296 // reaches the factory, which checks it when the node is
2297 // built. On a wire argument the same attribute is the
2298 // strict-wire metadata and rides on the port instead, so
2299 // it is not repeated here.
2300 let constraint = match (&a.kind, &a.constraint) {
2301 (ArgKind::Wire | ArgKind::PolyWire | ArgKind::Variadic(_), _) | (_, None) => {
2302 quote!(None)
2303 }
2304 (_, Some(c)) => {
2305 quote!(Some(polydat::dsl::const_constraints::ConstConstraint::#c))
2306 }
2307 };
2308 // The example is a value a program can pass, as the field's
2309 // documentation says: `cycle` for a wire, the declared
2310 // default for a constant that has one, written as program
2311 // text, and empty when there is none to offer. It is never
2312 // the parameter's own name, which no program can pass.
2313 let example = match &a.kind {
2314 ArgKind::Wire | ArgKind::PolyWire | ArgKind::Variadic(_) => "cycle".to_string(),
2315 _ => a
2316 .default_value
2317 .as_ref()
2318 .and_then(program_literal)
2319 .unwrap_or_default(),
2320 };
2321 // `ParamSpec` is `#[non_exhaustive]`, so the spec starts from
2322 // its constructor and each field the signature decides is
2323 // set on it.
2324 Some(quote! {
2325 {
2326 let mut spec = polydat::dsl::registry::ParamSpec::new(#name_str, #slot_type);
2327 spec.required = #required;
2328 spec.example = #example;
2329 spec.constraint = #constraint;
2330 spec
2331 }
2332 })
2333 })
2334 .collect();
2335
2336 // Output type. The simple case requires a concrete return
2337 // type (-> T); unit / unspecified isn't supported.
2338 let declared_ret_ty = match &func.sig.output {
2339 ReturnType::Default => {
2340 return Err(syn::Error::new_spanned(
2341 &func.sig,
2342 "#[polydat_node] requires an explicit return type; \
2343 nodes always produce a value.",
2344 ));
2345 }
2346 ReturnType::Type(_, t) => (**t).clone(),
2347 };
2348 // Fallible construction. When the body
2349 // returns `Result<T, E>`, the macro treats T as the effective
2350 // node-output type and emits a `try_new(...) -> Result<Self,
2351 // String>` constructor that runs the body once at
2352 // construction, caches the Ok value, and propagates Err. Only
2353 // valid for nodes with no wire/polywire inputs — the body has
2354 // to be fully resolvable at construction.
2355 let fallible_inner_ty: Option<Type> = classify_result_return(&declared_ret_ty);
2356 let is_fallible = fallible_inner_ty.is_some();
2357 let ret_ty = fallible_inner_ty
2358 .clone()
2359 .unwrap_or_else(|| declared_ret_ty.clone());
2360 let ret_is_polywire = classify_polywire(&ret_ty);
2361
2362 if is_fallible {
2363 // Wire / polywire / variadic inputs are not supported in
2364 // fallible mode: the body executes once at construction,
2365 // not per-eval. Const args are fine — they're all known
2366 // by the time `try_new` runs.
2367 for a in &args {
2368 match &a.kind {
2369 ArgKind::Wire | ArgKind::PolyWire | ArgKind::Variadic(_) => {
2370 return Err(syn::Error::new_spanned(
2371 &a.declared_ty,
2372 "fallible-construction nodes (-> Result<T, E>) must \
2373 have only Const args. Wire/PolyWire/variadic inputs \
2374 can't be evaluated at construction time. Use the \
2375 #[poly_const(setup_fn, from = ...)] shape instead \
2376 when per-eval inputs are needed.",
2377 ));
2378 }
2379 ArgKind::Setup(_) | ArgKind::Const(_) | ArgKind::ConstVec(..) => {}
2380 }
2381 }
2382 }
2383
2384 // Detect tuple-typed return for multi-output.
2385 let tuple_ret_elems: Option<Vec<Type>> = match &ret_ty {
2386 syn::Type::Tuple(t) => Some(t.elems.iter().cloned().collect()),
2387 _ => None,
2388 };
2389
2390 // Dynamic-output shape — detect `DynamicOutputs<T>`
2391 // return and locate the `Const<Vec<C>>` arg whose length
2392 // drives the output port count at construction.
2393 let dynamic_outputs_inner: Option<Type> = classify_dynamic_outputs(&ret_ty);
2394 let dynamic_outputs_count_arg: Option<syn::Ident> = if dynamic_outputs_inner.is_some() {
2395 let const_vec_args: Vec<&syn::Ident> = args
2396 .iter()
2397 .filter_map(|a| match &a.kind {
2398 ArgKind::ConstVec(..) => Some(&a.name),
2399 _ => None,
2400 })
2401 .collect();
2402 if const_vec_args.len() != 1 {
2403 return Err(syn::Error::new_spanned(
2404 &ret_ty,
2405 format!(
2406 "`DynamicOutputs<T>` return requires exactly one \
2407 `Const<Vec<C>>` arg to drive the output port count \
2408 (got {}). Declare one `Const<Vec<C>>` arg whose length \
2409 determines the number of output ports.",
2410 const_vec_args.len(),
2411 ),
2412 ));
2413 }
2414 Some(const_vec_args[0].clone())
2415 } else {
2416 None
2417 };
2418
2419 if tuple_ret_elems.is_some() && ret_is_polywire {
2420 // Type::Tuple isn't Type::Path so this is impossible, but
2421 // belt-and-suspenders for future return-shape changes.
2422 return Err(syn::Error::new_spanned(
2423 &ret_ty,
2424 "tuple return + PolyWire don't compose (SameAsInput is a \
2425 single-output dispatch).",
2426 ));
2427 }
2428
2429 // When the return type is `Value`, the
2430 // output port type tracks the first PolyWire arg's runtime
2431 // port type (SameAsInput). Otherwise it's the primitive's
2432 // fixed PortType.
2433 let first_polywire_idx: Option<usize> = args
2434 .iter()
2435 .enumerate()
2436 .find(|(_, a)| matches!(a.kind, ArgKind::PolyWire))
2437 .map(|(i, _)| i);
2438
2439 // Per-output port-type token streams, indexed positionally.
2440 // Single-output → 1-element vec; tuple → N elements.
2441 let output_port_types: Vec<TokenStream2> = if let Some(elems) = &tuple_ret_elems {
2442 elems
2443 .iter()
2444 .map(wire_port_type_for)
2445 .collect::<syn::Result<Vec<_>>>()?
2446 } else if ret_is_polywire {
2447 // Prefer a singleton PolyWire arg for SameAsInput
2448 // dispatch; fall back to a variadic `&[Value]` arg
2449 // (split-halves shape) whose runtime element types
2450 // drive the output polymorphism. The static slot
2451 // gets a `PortType::U64` placeholder (assembler skips
2452 // type-check for these); eval enforces uniformity.
2453 if let Some(polywire_arg) = args.iter().find(|a| matches!(a.kind, ArgKind::PolyWire)) {
2454 let pt_ident = format_ident!("{}_type", polywire_arg.name);
2455 vec![quote!(#pt_ident)]
2456 } else if args
2457 .iter()
2458 .any(|a| matches!(&a.kind, ArgKind::Variadic(VariadicElement::Value)))
2459 {
2460 // The output type is the type the variadic's wires
2461 // carry, resolved by the assembler and handed to
2462 // `new()` — the same answer a `Value` argument gets.
2463 // A `PortType::U64` placeholder here would be read
2464 // downstream as a fact: a `Str` from `pick` into a `Str`
2465 // port would get a `U64ToString` adapter inserted between
2466 // them, reading the string's pointer as a number.
2467 vec![quote!(__variadic_out_type)]
2468 } else {
2469 return Err(syn::Error::new_spanned(
2470 &ret_ty,
2471 "function returns `Value` but has no `Value` arg — the macro \
2472 needs at least one PolyWire (`Value`) arg or a `&[Value]` \
2473 variadic to source the runtime port type for the output.",
2474 ));
2475 }
2476 } else if let Some(inner) = &dynamic_outputs_inner {
2477 // Single per-element port type for the dynamic case.
2478 // The count is determined at construction time; this
2479 // entry is used by the codegen as the port type each
2480 // output port carries.
2481 vec![wire_port_type_for(inner)?]
2482 } else {
2483 vec![wire_port_type_for(&ret_ty)?]
2484 };
2485
2486 // Output names. Operator-supplied via
2487 // `output_names(a, b, c)`; falls back to `out_0`, `out_1`, ...
2488 // for tuple returns; just "output" for single returns.
2489 let output_names_strs: Vec<String> = match (&tuple_ret_elems, &attrs.output_names) {
2490 (Some(elems), Some(names)) => {
2491 if names.len() != elems.len() {
2492 return Err(syn::Error::new_spanned(
2493 &ret_ty,
2494 format!(
2495 "tuple return has {} elements but `output_names(...)` \
2496 lists {}; lengths must match.",
2497 elems.len(),
2498 names.len(),
2499 ),
2500 ));
2501 }
2502 names.iter().map(|n| n.to_string()).collect()
2503 }
2504 (Some(elems), None) => (0..elems.len()).map(|i| format!("out_{i}")).collect(),
2505 (None, Some(names)) if names.len() != 1 => {
2506 return Err(syn::Error::new_spanned(
2507 &ret_ty,
2508 "single-output return doesn't accept multi-name `output_names(...)`.",
2509 ));
2510 }
2511 (None, Some(names)) => vec![names[0].to_string()],
2512 (None, None) => vec!["output".to_string()],
2513 };
2514
2515 // FuncSig::output_port — the statically-known return port for
2516 // single fixed-output nodes; None for tuple / polymorphic /
2517 // dynamic shapes (the DSL type inference then falls back to
2518 // its heuristic).
2519 let output_port_field: TokenStream2 =
2520 if tuple_ret_elems.is_some() || ret_is_polywire || dynamic_outputs_inner.is_some() {
2521 quote!(None)
2522 } else {
2523 let pt = &output_port_types[0];
2524 quote!(Some(#pt))
2525 };
2526
2527 let output_count = if dynamic_outputs_inner.is_some() {
2528 0
2529 } else {
2530 output_port_types.len()
2531 };
2532 // `0` in the FuncSig signals "dynamic, determined at compile
2533 // time" (the FuncSig convention).
2534 let output_count_lit =
2535 syn::LitInt::new(&output_count.to_string(), proc_macro2::Span::call_site());
2536
2537 // When return is `Value`, prefer SameAsInput dispatch
2538 // against a singleton PolyWire arg; for the split-halves
2539 // `&[Value]` case there's no singleton to point at, so
2540 // fall back to OutputType::Fixed (the static slot's
2541 // placeholder PortType is used and eval enforces type
2542 // uniformity).
2543 let output_type_tokens: TokenStream2 = match (ret_is_polywire, first_polywire_idx) {
2544 (true, Some(idx)) => {
2545 let i = syn::Index::from(idx);
2546 quote!(polydat::dsl::registry::OutputType::SameAsInput(#i))
2547 }
2548 _ => quote!(polydat::dsl::registry::OutputType::Fixed),
2549 };
2550
2551 // Struct fields. Wire/PolyWire/Variadic → no field (arity
2552 // reflected in `meta.ins.len()`); Const → owned-typed field;
2553 // ConstVec → Vec<inner>; Setup → field of the borrowed
2554 // inner type.
2555 let struct_fields: Vec<TokenStream2> = args
2556 .iter()
2557 .filter_map(|a| match &a.kind {
2558 ArgKind::Wire | ArgKind::PolyWire | ArgKind::Variadic(_) => None,
2559 ArgKind::Const(shape) => {
2560 let n = &a.name;
2561 let ft = shape.field_type_tokens(opaque_inner_type(&a.declared_ty).as_ref());
2562 let doc = format!("The `{n}` argument, as given at construction.");
2563 Some(quote!(#[doc = #doc] pub #n: #ft))
2564 }
2565 ArgKind::ConstVec(inner, _) => {
2566 let n = &a.name;
2567 let ft = inner.field_type_tokens(None);
2568 let doc = format!("The `{n}` arguments, as given at construction.");
2569 Some(quote!(#[doc = #doc] pub #n: Vec<#ft>))
2570 }
2571 ArgKind::Setup(spec) => {
2572 let n = &a.name;
2573 let ty = &spec.inner_ty;
2574 let doc = format!("The `{n}` value, computed once at construction.");
2575 Some(quote!(#[doc = #doc] pub #n: #ty))
2576 }
2577 })
2578 .collect();
2579
2580 // `new(<polywire_types..>, <consts..>)` constructor params, in
2581 // declaration order. Const args contribute their owned-typed
2582 // value; PolyWire args contribute a `<argname>_type: PortType`
2583 // parameter that names the runtime port type the assembler
2584 // resolved for the upstream wire. Setup args are computed
2585 // inside new(), not parameters.
2586 let new_params: Vec<TokenStream2> = args
2587 .iter()
2588 .filter_map(|a| match &a.kind {
2589 ArgKind::Wire => None,
2590 ArgKind::Const(shape) => {
2591 let n = &a.name;
2592 let ft = shape.field_type_tokens(opaque_inner_type(&a.declared_ty).as_ref());
2593 Some(quote!(#n: #ft))
2594 }
2595 ArgKind::ConstVec(inner, _) => {
2596 let n = &a.name;
2597 let ft = inner.field_type_tokens(None);
2598 Some(quote!(#n: Vec<#ft>))
2599 }
2600 ArgKind::Setup(_) => None,
2601 ArgKind::PolyWire => {
2602 let n = format_ident!("{}_type", a.name);
2603 Some(quote!(#n: polydat::ast::PortType))
2604 }
2605 // Variadic args don't add their OWN per-arg param —
2606 // the variadic-arity is supplied via a SINGLE
2607 // `n_wires: usize` parameter appended once at the end
2608 // (see `variadic_n_wires_param` below).
2609 ArgKind::Variadic(_) => None,
2610 })
2611 .collect();
2612
2613 // Append a single `n_wires: usize` parameter
2614 // to `new()` when the function declares any variadic arg.
2615 // Split-halves variadic: TWO variadics in succession
2616 // share a single `n_wires` param (interpreted as "count per
2617 // half"). The macro emits 2*n_wires wire slots and slices
2618 // the inputs at the midpoint at eval time. Used by `pick`'s
2619 // `(b0,...,bN,v0,...,vN)` workload syntax (library_catalog.md
2620 // "`pick` — semantics").
2621 let has_variadic = args.iter().any(|a| matches!(a.kind, ArgKind::Variadic(_)));
2622 let variadic_count = args
2623 .iter()
2624 .filter(|a| matches!(a.kind, ArgKind::Variadic(_)))
2625 .count();
2626 if variadic_count > 2 {
2627 return Err(syn::Error::new_spanned(
2628 &func.sig,
2629 "`#[polydat_node]` supports at most two variadic `&[T]` args (split-halves shape). \
2630 Functions declaring more than two are not expressible in any `#[polydat_node]` shape.",
2631 ));
2632 }
2633 // A node's arity is either a wire list or a const list: the
2634 // registry's `Arity` names one, and each list takes the tail of
2635 // its own argument kind.
2636 if has_variadic
2637 && let Some(list) = args
2638 .iter()
2639 .find(|a| matches!(a.kind, ArgKind::ConstVec(..)))
2640 {
2641 return Err(syn::Error::new_spanned(
2642 &list.declared_ty,
2643 "a const list (`Const<&[C]>` or `Const<Vec<C>>`) does not combine with \
2644 a variadic `&[T]` wire list; a node's arity is one variadic kind.",
2645 ));
2646 }
2647 let is_split_halves = variadic_count == 2;
2648 // Positional index of each Variadic arg in declaration
2649 // order, used by `arg_bindings` to slice `inputs` at the
2650 // midpoint in split-halves mode.
2651 let variadic_positions: std::collections::HashMap<String, usize> = args
2652 .iter()
2653 .filter(|a| matches!(a.kind, ArgKind::Variadic(_)))
2654 .enumerate()
2655 .map(|(i, a)| (a.name.to_string(), i))
2656 .collect();
2657 // A `Value` return sourced from a `&[Value]` variadic takes the
2658 // output's port type as a constructor parameter, resolved from
2659 // the wires by the build closure.
2660 let needs_variadic_out_type = ret_is_polywire
2661 && first_polywire_idx.is_none()
2662 && args
2663 .iter()
2664 .any(|a| matches!(&a.kind, ArgKind::Variadic(VariadicElement::Value)));
2665 let new_params: Vec<TokenStream2> = if has_variadic {
2666 let mut v = new_params;
2667 v.push(quote!(n_wires: usize));
2668 if needs_variadic_out_type {
2669 v.push(quote!(__variadic_out_type: polydat::ast::PortType));
2670 }
2671 v
2672 } else {
2673 new_params
2674 };
2675 // A setup that reads the build context takes it from `new()`'s
2676 // first parameter.
2677 let new_params: Vec<TokenStream2> = if takes_ctx {
2678 std::iter::once(quote!(ctx: &polydat::dsl::factory::BuildContext))
2679 .chain(new_params)
2680 .collect()
2681 } else {
2682 new_params
2683 };
2684
2685 // Build a lookup from arg name → const-shape category so the
2686 // Setup pre-compute step can dispatch on the source's shape
2687 // to produce the right access expression.
2688 #[derive(Clone, Copy)]
2689 enum ConstSourceShape {
2690 /// Scalar `Const<u64>` / `Const<f64>` / `Const<bool>`.
2691 ScalarValue,
2692 /// `Const<&str>` / `Const<String>` — backing field is
2693 /// `String`; setup fn typically wants `&str`.
2694 ScalarStr,
2695 /// `Const<Vec<C>>` — backing field is `Vec<C>`; setup fn
2696 /// typically wants `&Vec<C>` or `&[C]`.
2697 VecValues,
2698 }
2699 let const_shape_by_name: std::collections::HashMap<String, ConstSourceShape> = args
2700 .iter()
2701 .filter_map(|a| match &a.kind {
2702 ArgKind::Const(ConstShape::Str) => {
2703 Some((a.name.to_string(), ConstSourceShape::ScalarStr))
2704 }
2705 ArgKind::Const(_) => Some((a.name.to_string(), ConstSourceShape::ScalarValue)),
2706 ArgKind::ConstVec(..) => Some((a.name.to_string(), ConstSourceShape::VecValues)),
2707 _ => None,
2708 })
2709 .collect();
2710
2711 // Setup pre-compute lines, emitted at the top of `new()`
2712 // BEFORE `Self { ... }` so they can borrow the const
2713 // locals before those values are moved into self.
2714 let setup_precomputes: Vec<TokenStream2> = args
2715 .iter()
2716 .filter_map(|a| match &a.kind {
2717 ArgKind::Wire
2718 | ArgKind::Const(_)
2719 | ArgKind::ConstVec(..)
2720 | ArgKind::PolyWire
2721 | ArgKind::Variadic(_) => None,
2722 ArgKind::Setup(spec) => {
2723 let n = &a.name;
2724 let setup_fn = &spec.setup_fn;
2725 // `source_args` may be empty
2726 // (session-static setup), single (the common
2727 // case), or multi (joint derivation). Per-source
2728 // access dispatch reads each named const's
2729 // shape and emits the right body-side expression.
2730 let mut src_exprs: Vec<TokenStream2> = Vec::new();
2731 let mut err: Option<TokenStream2> = None;
2732 for src in &spec.source_args {
2733 let shape = const_shape_by_name.get(&src.to_string());
2734 let expr = match shape {
2735 Some(ConstSourceShape::ScalarStr) => quote!(#src.as_str()),
2736 Some(ConstSourceShape::ScalarValue) => quote!(#src),
2737 // ConstVec source: pass a borrow of the
2738 // Vec. Setup fn signatures like
2739 // `fn build(w: &Vec<f64>)` or
2740 // `fn build(w: &[f64])` both work via
2741 // Deref / unsized coercion.
2742 Some(ConstSourceShape::VecValues) => quote!(&#src),
2743 None => {
2744 err = Some(
2745 syn::Error::new(
2746 src.span(),
2747 format!(
2748 "#[poly_const(... from = ... {src} ...)] — \
2749 `{src}` is not declared as a `Const<T>` \
2750 arg in the same function signature."
2751 ),
2752 )
2753 .to_compile_error(),
2754 );
2755 break;
2756 }
2757 };
2758 src_exprs.push(expr);
2759 }
2760 if let Some(e) = err {
2761 return Some(e);
2762 }
2763 if let Some(ctx) = &spec.ctx {
2764 src_exprs.insert(0, quote!(#ctx));
2765 }
2766 let call = quote!(#setup_fn( #( #src_exprs ),* ));
2767 Some(quote! {
2768 let #n = #call;
2769 })
2770 }
2771 })
2772 .collect();
2773
2774 // Self { ... } field-init list. Const args use field-name
2775 // shorthand; Setup args use the local computed above.
2776 // Wire/PolyWire contribute nothing (no field).
2777 let new_field_inits: Vec<TokenStream2> = args
2778 .iter()
2779 .filter_map(|a| match &a.kind {
2780 ArgKind::Wire | ArgKind::PolyWire | ArgKind::Variadic(_) => None,
2781 ArgKind::Const(_) | ArgKind::ConstVec(..) | ArgKind::Setup(_) => {
2782 let n = &a.name;
2783 Some(quote!(#n))
2784 }
2785 })
2786 .collect();
2787
2788 // Per-arg bindings the eval body sees. Wire args unbox via
2789 // FromValue; const args wrap the struct field as `Const<T>`
2790 // so the user's body code sees the wrapper type matching
2791 // its function signature.
2792 let mut wire_idx = 0usize;
2793 let arg_bindings: Vec<TokenStream2> = args
2794 .iter()
2795 .map(|a| {
2796 let n = &a.name;
2797 match &a.kind {
2798 ArgKind::Wire => {
2799 let idx = syn::Index::from(wire_idx);
2800 wire_idx += 1;
2801 let ty = &a.declared_ty;
2802 // Dispatch:
2803 // 1. `Arc<T>` Handle (non-special T) → inline
2804 // downcast (no blanket impl works).
2805 // 2. Borrow shape (`&str`, `&[u8]`, `&[T]`,
2806 // `&serde_json::Value`) → direct
2807 // `match`-on-`Value`. Lifetime is naturally
2808 // `&inputs[i]`'s; no `unsafe` transmute.
2809 // 3. Otherwise → `<#ty as Wire>::extract`.
2810 if classify_wrapper_wire(ty) == Some(WrapperWire::Handle) {
2811 let inner = extract_handle_inner(ty)
2812 .expect("Handle classification implies Arc<T> shape");
2813 quote! {
2814 let #n: std::sync::Arc<#inner> = match &inputs[#idx] {
2815 polydat::ast::Value::Handle(arc) => arc.clone()
2816 .downcast::<#inner>()
2817 .expect("Handle type mismatch — wiring bug"),
2818 other => panic!("expected Handle, got {other:?}"),
2819 };
2820 }
2821 } else if let Some(borrow) = is_borrow_wire_shape(ty) {
2822 let extract = borrow_extract_tokens(borrow, quote!(&inputs[#idx]));
2823 quote! {
2824 let #n = #extract;
2825 }
2826 } else {
2827 quote! {
2828 let #n = <#ty as polydat::derive_support::Wire>::extract(&inputs[#idx]);
2829 }
2830 }
2831 }
2832 ArgKind::Const(shape) => {
2833 let wrap = shape.wrap_as_const(quote!(self.#n));
2834 quote! {
2835 let #n = #wrap;
2836 }
2837 }
2838 ArgKind::Setup(_) => {
2839 // Setup arg: body sees a borrow of the
2840 // construction-time computed field. No
2841 // wrapping needed — the field is the
2842 // user's named type and `&T` matches the
2843 // function-signature borrow.
2844 quote! {
2845 let #n = &self.#n;
2846 }
2847 }
2848 ArgKind::PolyWire => {
2849 // PolyWire — clone the
2850 // `Value` directly into a local. Body sees
2851 // an owned `Value`.
2852 let idx = syn::Index::from(wire_idx);
2853 wire_idx += 1;
2854 quote! {
2855 let #n: polydat::ast::Value = inputs[#idx].clone();
2856 }
2857 }
2858 ArgKind::Variadic(elem) => {
2859 // Variadic and split-halves — materialise a Vec<T> from the inputs
2860 // slice (per-element extraction), then bind
2861 // the body local as `&[T]`. In single-
2862 // variadic mode, the slice is `inputs` (all
2863 // of them after the leading wires consumed
2864 // their indices). In split-halves mode, the
2865 // first variadic gets `inputs[0..n_wires]`
2866 // and the second gets `inputs[n_wires..]`.
2867 let extractor = elem.extract_from_value();
2868 let owned = format_ident!("__{}_owned", a.name);
2869 // Split-halves divides `inputs` at the
2870 // midpoint at eval time. `inputs.len() / 2`
2871 // is the per-half count; first variadic
2872 // gets the low half, second gets the high.
2873 let slice_expr = if is_split_halves {
2874 let pos = variadic_positions[&a.name.to_string()];
2875 if pos == 0 {
2876 quote!({
2877 let __half = inputs.len() / 2;
2878 &inputs[..__half]
2879 })
2880 } else {
2881 quote!({
2882 let __half = inputs.len() / 2;
2883 &inputs[__half..]
2884 })
2885 }
2886 } else {
2887 quote!(inputs)
2888 };
2889 quote! {
2890 let #owned: Vec<_> = #slice_expr.iter().map(#extractor).collect();
2891 let #n: &[_] = #owned.as_slice();
2892 }
2893 }
2894 // A const list's body view. The
2895 // elements live in the node's own field either way; the
2896 // declared type says whether the body wanted a borrow
2897 // of them or a copy.
2898 ArgKind::ConstVec(_, ListForm::Borrowed) => quote! {
2899 let #n = polydat::derive_support::Const(&self.#n[..]);
2900 },
2901 ArgKind::ConstVec(_, ListForm::Owned) => quote! {
2902 let #n = polydat::derive_support::Const(self.#n.clone());
2903 },
2904 }
2905 })
2906 .collect();
2907
2908 // Build closure const-extraction logic. For each const arg
2909 // (in declaration order), pull from `consts: &[ConstArg]`
2910 // by index; fall back to the `poly_default` value if the
2911 // slice is shorter than the const arg list.
2912 //
2913 // For `ConstVec` args, collect every remaining entry from
2914 // `consts[i..]` into a `Vec<inner>` via the inner shape's
2915 // extractor — this consumes the tail of the consts slice
2916 // (only one ConstVec arg per function, enforced earlier).
2917 let mut const_idx_for_extract = 0usize;
2918 let const_extracts: Vec<TokenStream2> = args
2919 .iter()
2920 .filter_map(|a| match &a.kind {
2921 ArgKind::Wire | ArgKind::Setup(_) | ArgKind::PolyWire | ArgKind::Variadic(_) => None,
2922 ArgKind::Const(shape) => {
2923 let n = &a.name;
2924 let i = const_idx_for_extract;
2925 const_idx_for_extract += 1;
2926 let i_lit = syn::Index::from(i);
2927 let extract_present = shape
2928 .extract_from_const_arg(quote!(c), opaque_inner_type(&a.declared_ty).as_ref());
2929 let fallback = match &a.default_value {
2930 Some(default_expr) => {
2931 // Default is an expression evaluating to
2932 // the field type (`u64`, `f64`, `bool`,
2933 // `String`). For Str: the expression
2934 // should produce a `&str` or `String`; we
2935 // call `.to_string()` to land on owned.
2936 match shape {
2937 ConstShape::Str => quote!((#default_expr).to_string()),
2938 _ => quote!(#default_expr),
2939 }
2940 }
2941 None => {
2942 let msg = format!(
2943 "missing required const arg '{n}' for function '{func_name_str}'"
2944 );
2945 quote!(return Some(Err(#msg.to_string())))
2946 }
2947 };
2948 Some(quote! {
2949 let #n: _ = match consts.get(#i_lit) {
2950 Some(c) => #extract_present,
2951 None => #fallback,
2952 };
2953 })
2954 }
2955 ArgKind::ConstVec(inner, _) => {
2956 let n = &a.name;
2957 let i = const_idx_for_extract;
2958 // ConstVec consumes everything from index `i`
2959 // onward. const_idx_for_extract is intentionally
2960 // NOT bumped — by construction (validated below)
2961 // there's at most one ConstVec arg and it must be
2962 // the last arg, so no subsequent Const reads need
2963 // a higher base index.
2964 let i_lit = syn::LitInt::new(&i.to_string(), proc_macro2::Span::call_site());
2965 let extract_one = inner.extract_from_const_arg(quote!(c), None);
2966 Some(quote! {
2967 let #n: Vec<_> = consts[#i_lit..].iter()
2968 .map(|c| #extract_one)
2969 .collect();
2970 })
2971 }
2972 })
2973 .collect();
2974
2975 // Names to pass to `Self::new(...)` from the build closure,
2976 // in declaration order. Const → `<name>`; PolyWire →
2977 // `<name>_type` (the local extracted from `wire_types`).
2978 let mut new_call_args: Vec<TokenStream2> = args
2979 .iter()
2980 .filter_map(|a| match &a.kind {
2981 ArgKind::Wire | ArgKind::Setup(_) | ArgKind::Variadic(_) => None,
2982 ArgKind::Const(_) | ArgKind::ConstVec(..) => {
2983 let n = &a.name;
2984 Some(quote!(#n))
2985 }
2986 ArgKind::PolyWire => {
2987 let n = format_ident!("{}_type", a.name);
2988 Some(quote!(#n))
2989 }
2990 })
2991 .collect();
2992 if has_variadic {
2993 new_call_args.push(quote!(n_wires));
2994 if needs_variadic_out_type {
2995 new_call_args.push(quote!(__variadic_out_type));
2996 }
2997 }
2998 if takes_ctx {
2999 new_call_args.insert(0, quote!(_ctx));
3000 }
3001
3002 // When the function has a variadic arg, extract `n_wires`
3003 // from the `_wires: &[WireRef]` slice in the build closure.
3004 // The whole `_wires.len()` is the variadic count, halved under
3005 // the split-halves shape.
3006 let variadic_n_wires_extract: TokenStream2 = if has_variadic {
3007 // Split-halves: assembler hands TOTAL wires; new() takes
3008 // the per-half count, so divide by 2 here too (matches
3009 // the variadic_ctor field's `n / 2`).
3010 let n = if is_split_halves {
3011 quote! { let n_wires: usize = _wires.len() / 2; }
3012 } else {
3013 quote! { let n_wires: usize = _wires.len(); }
3014 };
3015 // The wires the variadic's values come from: all of them,
3016 // or the second half under the split-halves shape, whose
3017 // first half is the selectors. Their common type is the
3018 // output's; `eval` enforces that they agree, and reports
3019 // the disagreement by name when they do not.
3020 let out_type = if needs_variadic_out_type {
3021 let first = if is_split_halves {
3022 quote!(_wire_types.get(n_wires))
3023 } else {
3024 quote!(_wire_types.first())
3025 };
3026 quote! {
3027 let __variadic_out_type = #first
3028 .copied()
3029 .unwrap_or(polydat::ast::PortType::U64);
3030 }
3031 } else {
3032 quote!()
3033 };
3034 quote! { #n #out_type }
3035 } else {
3036 quote!()
3037 };
3038
3039 // Extract resolved PolyWire port types from
3040 // the `wire_types: &[PortType]` slice the assembler hands
3041 // the build closure. Wire/PolyWire share the same slot
3042 // counter (both consume a wire input position); we count
3043 // through args in declaration order.
3044 let polywire_extracts: Vec<TokenStream2> = {
3045 let mut wire_idx = 0usize;
3046 let mut out = Vec::new();
3047 for a in &args {
3048 match &a.kind {
3049 ArgKind::Wire => {
3050 wire_idx += 1;
3051 }
3052 ArgKind::Variadic(_) => {
3053 // Variadic args consume the REMAINDER of the
3054 // wire slots.
3055 wire_idx += 0; // no positional increment
3056 }
3057 ArgKind::PolyWire => {
3058 let pt_ident = format_ident!("{}_type", a.name);
3059 let i = syn::Index::from(wire_idx);
3060 let n_str = a.name.to_string();
3061 let err = format!(
3062 "polywire arg '{n_str}' for '{func_name_str}': assembler \
3063 did not resolve a port type at wire index {wire_idx}"
3064 );
3065 out.push(quote! {
3066 let #pt_ident: polydat::ast::PortType = match _wire_types.get(#i) {
3067 Some(t) => *t,
3068 None => return Some(Err(#err.to_string())),
3069 };
3070 });
3071 wire_idx += 1;
3072 }
3073 ArgKind::Const(_) | ArgKind::ConstVec(..) | ArgKind::Setup(_) => {}
3074 }
3075 }
3076 out
3077 };
3078
3079 let block = &func.block;
3080
3081 // `default_resolver` emission. Each wire
3082 // arg's `Wire::RESOLVER` const exposes the auto-resolver
3083 // intent at codegen time; the cascade picks the first
3084 // non-None among the wire-typed args. Non-Resolved wire
3085 // types contribute `None` (the trait default), so this
3086 // collapses cleanly to a no-resolver FuncSig for the
3087 // overwhelming majority of nodes.
3088 let default_resolver_field: TokenStream2 = {
3089 // Borrow shapes (`&str`, `&[u8]`, ...) don't impl `Wire`,
3090 // and `PolyWire` is excluded by ArgKind; only the
3091 // owned-type wire args contribute resolver intent.
3092 let wire_tys: Vec<&Type> = args
3093 .iter()
3094 .filter_map(|a| match &a.kind {
3095 ArgKind::Wire
3096 if is_borrow_wire_shape(&a.declared_ty).is_none()
3097 && classify_wrapper_wire(&a.declared_ty) != Some(WrapperWire::Handle) =>
3098 {
3099 Some(&a.declared_ty)
3100 }
3101 _ => None,
3102 })
3103 .collect();
3104 if wire_tys.is_empty() {
3105 quote!(None)
3106 } else {
3107 // Build a right-to-left match cascade so the first
3108 // wire arg with a Some(_) resolver wins. Each step:
3109 // match <ty as Wire>::RESOLVER { Some(r) => Some(r), None => <rest> }
3110 let mut acc = quote!(None);
3111 for ty in wire_tys.iter().rev() {
3112 acc = quote! {
3113 match <#ty as polydat::derive_support::Wire>::RESOLVER {
3114 Some(__r) => Some(__r),
3115 None => #acc,
3116 }
3117 };
3118 }
3119 acc
3120 }
3121 };
3122
3123 // Emit `Default` only when there are no const args AND no
3124 // setup args. Both require captured values to construct.
3125 let has_non_wire = args.iter().any(|a| !matches!(a.kind, ArgKind::Wire));
3126 let default_impl = if has_non_wire {
3127 quote!()
3128 } else {
3129 quote! {
3130 impl Default for #struct_name {
3131 fn default() -> Self { Self::new() }
3132 }
3133 }
3134 };
3135
3136 // `#[polydat_node(decompose =
3137 // path)]` emits the FusedNode impl by delegating to the
3138 // named free function. Operators with bespoke fusion
3139 // logic (e.g. WeightedPick whose `decomposed()` body
3140 // builds a spec string) can still write their own
3141 // `impl FusedNode` block alongside the macro emission;
3142 // both compose because `decompose` is opt-in.
3143 let fused_node_impl: TokenStream2 = if let Some(path) = &attrs.decompose {
3144 quote! {
3145 impl polydat::compile::fusion::FusedNode for #struct_name {
3146 fn decomposed(&self) -> polydat::compile::fusion::DecomposedGraph {
3147 #path(self)
3148 }
3149 }
3150 }
3151 } else {
3152 quote!()
3153 };
3154
3155 // ── JIT eligibility + hook emission ──
3156 //
3157 // A node is Phase-2 eligible when every arg + return maps
3158 // to a `JitType` and no `#[poly_const]` setup arg is declared
3159 // (setup carries non-primitive derived state that can't fit a
3160 // u64 buffer). Override attributes (`compiled_u64 = ...`,
3161 // `jit_constants = ...`) bypass eligibility — they win
3162 // unconditionally.
3163
3164 let has_setup = args.iter().any(|a| matches!(a.kind, ArgKind::Setup(_)));
3165 let ret_jit_type = wire_type_to_jit_type(&ret_ty);
3166
3167 let arg_jit_types: Option<Vec<JitType>> = if has_setup {
3168 None
3169 } else {
3170 args.iter()
3171 .map(|a| match &a.kind {
3172 ArgKind::Wire => wire_type_to_jit_type(&a.declared_ty),
3173 // A const is captured by clone and never rides the
3174 // buffer, so its carrier is immaterial to eligibility.
3175 ArgKind::Const(shape) => {
3176 Some(const_shape_to_jit_type(*shape).unwrap_or(JitType::U64))
3177 }
3178 // ConstVec is JIT-ineligible (the JIT u64 buffer
3179 // has no slot shape for a variable-length list).
3180 ArgKind::Setup(_) | ArgKind::PolyWire | ArgKind::ConstVec(..) => None,
3181 // Variadic JIT — only `&[u64]`
3182 // rides the Phase 2 closure cleanly (the buffer
3183 // IS the slice). For f64/bool/Str variadics
3184 // the closure would need a per-call Vec
3185 // allocation to bit-reinterpret, so they are not
3186 // eligible.
3187 ArgKind::Variadic(elem) => match elem {
3188 VariadicElement::U64 => Some(JitType::U64),
3189 _ => None,
3190 },
3191 })
3192 .collect()
3193 };
3194
3195 // A tuple return is JIT-eligible
3196 // when every element is JIT-eligible. The compiled_u64
3197 // closure destructures the result and writes each element
3198 // to its `outputs[i]` slot via the matching JitType.
3199 let tuple_ret_jit_types: Option<Vec<JitType>> = tuple_ret_elems.as_ref().and_then(|elems| {
3200 elems
3201 .iter()
3202 .map(wire_type_to_jit_type)
3203 .collect::<Option<Vec<_>>>()
3204 });
3205
3206 let jit_eligible = !is_fallible
3207 && arg_jit_types.is_some()
3208 && (ret_jit_type.is_some() || tuple_ret_jit_types.is_some());
3209
3210 // ── The slot kit (`compiled_slot`): the general compiled closure
3211 // over the flat slot buffer, for every node the u64 kit does not
3212 // carry (type_system_alignment.md §8.4 layer 3; jit_boundary.md,
3213 // axioms S1–S10). A scalar rides its slots as in the u64 kit.
3214 // Every `Ref2` port rides a `(ptr, len)` pair: a typed vector, a
3215 // string, or a byte string as a slice of its elements, and a JSON,
3216 // extension, or polymorphic value as a one-element slice holding
3217 // the `Value`. A `Ref2` output is written into the step's own
3218 // scratch entry, which the kernel owns and hands the closure
3219 // (axiom S3), and its pair is republished on every run; a `Ref2`
3220 // input is read through one dereference of the pair its producer
3221 // published (axiom S7). A polymorphic port and a variadic decode by
3222 // the wire types the kernel hands the kit, and a polymorphic return
3223 // encodes by the node's resolved output type. A const or const
3224 // list is captured by clone; a setup derived from consts is
3225 // recomputed from the captured consts, and a session-static setup
3226 // or one over the build context is captured from the node by
3227 // clone; an `Option<T>` or `Config<T>`
3228 // over a carrier is the carrier's slot, wrapped.
3229 enum SlotArg {
3230 Jit(JitType),
3231 /// `Option<T>` over a one-slot carrier. A compiled kernel
3232 /// never carries `None` on a scalar slot (an unset extern is
3233 /// refused before the run), so the value is always present.
3234 Option(JitType),
3235 /// `Config<T>` over a carrier, the same slot wrapped, or over
3236 /// an owned string or byte string, copied out and wrapped.
3237 Config(ConfigInner),
3238 /// A typed vector slice, `&[T]`.
3239 Vec(&'static str),
3240 /// `&str`, or an owned `String` / `Arc<str>` copied out of
3241 /// the producer's bytes.
3242 Str {
3243 owned: bool,
3244 },
3245 /// `&[u8]`, or an owned `Vec<u8>` / `Arc<[u8]>` copied out.
3246 Bytes {
3247 owned: bool,
3248 },
3249 JsonRef,
3250 JsonArc,
3251 Ext,
3252 /// `Arc<T>` for a concrete `T`: the `Value::Handle` the pair
3253 /// points at, downcast to `T` as the interpreter downcasts it.
3254 HandleArc(Box<Type>),
3255 /// Any other `Wire` type, admitted only when its port is
3256 /// `Handle` (the kit checks `Wire::PORT` when it is built, and
3257 /// declines otherwise): read through `Wire::extract` from the
3258 /// `Value` the pair points at.
3259 HandleWire,
3260 Poly,
3261 Variadic(VariadicElement),
3262 Const(ConstShape),
3263 /// A const list. The form says whether the body asked to
3264 /// borrow the kit's own copy or to take one of its own.
3265 ConstVec(ListForm),
3266 Setup,
3267 /// A session-static setup (`from = ()`) or one over the build
3268 /// context (`from = (ctx, ...)`), captured from the node by
3269 /// clone: the closure sees what the node captured at
3270 /// construction, as the native form does through
3271 /// `jit_constants`.
3272 SetupStatic,
3273 }
3274 /// What a `Config<T>` wraps.
3275 #[derive(Clone, Copy)]
3276 enum ConfigInner {
3277 Jit(JitType),
3278 Str,
3279 Bytes,
3280 }
3281 /// One element of a return: a carrier, or a `Ref2` kind that
3282 /// takes a scratch entry of its own.
3283 #[derive(Clone, Copy)]
3284 enum SlotElem {
3285 Jit(JitType),
3286 Vec(&'static str),
3287 /// A `SliceArc<T>`, its elements copied into the scratch
3288 /// vector.
3289 VecShared(&'static str),
3290 Str,
3291 Bytes,
3292 Json,
3293 Ext,
3294 /// `Arc<T>` for a concrete `T`, written as `Value::Handle`.
3295 HandleArc,
3296 /// Any other `Wire` type whose port is `Handle`, written
3297 /// through `Wire::inject`; the kit checks the port when it is
3298 /// built. A `None` is written as the empty pair.
3299 HandleWire,
3300 }
3301 impl SlotElem {
3302 fn is_ref(self) -> bool {
3303 !matches!(self, SlotElem::Jit(_))
3304 }
3305 fn width(self) -> usize {
3306 match self {
3307 SlotElem::Jit(jt) => jt.width(),
3308 _ => 2,
3309 }
3310 }
3311 fn scratch_elem(self) -> Option<TokenStream2> {
3312 let name = match self {
3313 SlotElem::Jit(_) => return None,
3314 SlotElem::Vec(e) | SlotElem::VecShared(e) => e,
3315 SlotElem::Str => "Str",
3316 SlotElem::Bytes => "Bytes",
3317 SlotElem::Json | SlotElem::Ext | SlotElem::HandleArc | SlotElem::HandleWire => {
3318 "Value"
3319 }
3320 };
3321 let id = syn::Ident::new(name, proc_macro2::Span::call_site());
3322 Some(quote!(polydat::ast::ScratchElem::#id))
3323 }
3324 }
3325 enum SlotRet {
3326 Elem(SlotElem),
3327 /// A polymorphic `Value` return, encoded by the node's
3328 /// resolved output type.
3329 Poly,
3330 /// A tuple return: each element written by shape.
3331 Tuple(Vec<SlotElem>),
3332 }
3333 impl SlotRet {
3334 /// Whether any element takes a scratch entry.
3335 fn has_ref(&self) -> bool {
3336 match self {
3337 SlotRet::Elem(e) => e.is_ref(),
3338 SlotRet::Poly => true,
3339 SlotRet::Tuple(elems) => elems.iter().any(|e| e.is_ref()),
3340 }
3341 }
3342 }
3343 let owned_str_ty = |ty: &Type| -> bool {
3344 let flat: String = type_to_string(ty).split_whitespace().collect();
3345 matches!(flat.as_str(), "String" | "Arc<str>" | "std::sync::Arc<str>")
3346 };
3347 let owned_bytes_ty = |ty: &Type| -> bool {
3348 let flat: String = type_to_string(ty).split_whitespace().collect();
3349 matches!(
3350 flat.as_str(),
3351 "Vec<u8>" | "Arc<[u8]>" | "std::sync::Arc<[u8]>"
3352 )
3353 };
3354 let vec_ret_elem = |ty: &Type| -> Option<&'static str> {
3355 let flat: String = type_to_string(ty).split_whitespace().collect();
3356 match flat.as_str() {
3357 "Vec<f32>" => Some("F32"),
3358 "Vec<f64>" => Some("F64"),
3359 "Vec<half::f16>" | "Vec<f16>" => Some("F16"),
3360 "Vec<i8>" => Some("I8"),
3361 "Vec<i16>" => Some("I16"),
3362 "Vec<i32>" => Some("I32"),
3363 "Vec<i64>" => Some("I64"),
3364 _ => None,
3365 }
3366 };
3367 // A shared typed vector, `SliceArc<T>`, written by copying its
3368 // elements into the step's scratch vector.
3369 let slice_arc_ret_elem = |ty: &Type| -> Option<&'static str> {
3370 let flat: String = type_to_string(ty).split_whitespace().collect();
3371 let elem = flat
3372 .strip_suffix('>')?
3373 .rsplit_once("SliceArc<")
3374 .map(|(_, e)| e)?;
3375 match elem {
3376 "f32" => Some("F32"),
3377 "f64" => Some("F64"),
3378 "half::f16" | "f16" => Some("F16"),
3379 "i8" => Some("I8"),
3380 "i16" => Some("I16"),
3381 "i32" => Some("I32"),
3382 "i64" => Some("I64"),
3383 _ => None,
3384 }
3385 };
3386 let classify_elem = |ty: &Type| -> Option<SlotElem> {
3387 if classify_wrapper_wire(ty) == Some(WrapperWire::Json) {
3388 Some(SlotElem::Json)
3389 } else if classify_wrapper_wire(ty) == Some(WrapperWire::Handle) {
3390 Some(SlotElem::HandleArc)
3391 } else if is_ext_wire(ty) {
3392 Some(SlotElem::Ext)
3393 } else if let Some(e) = vec_ret_elem(ty) {
3394 Some(SlotElem::Vec(e))
3395 } else if let Some(e) = slice_arc_ret_elem(ty) {
3396 Some(SlotElem::VecShared(e))
3397 } else if owned_str_ty(ty) {
3398 Some(SlotElem::Str)
3399 } else if owned_bytes_ty(ty) {
3400 Some(SlotElem::Bytes)
3401 } else if let Some(jt) = wire_type_to_jit_type(ty) {
3402 Some(SlotElem::Jit(jt))
3403 } else if matches!(ty, Type::Path(_)) && !classify_polywire(ty) {
3404 Some(SlotElem::HandleWire)
3405 } else {
3406 None
3407 }
3408 };
3409 // The return shape the kit can write: a carrier, a `Ref2` kind, a
3410 // polymorphic value, or a tuple of carriers and `Ref2` kinds.
3411 let classify_ret_shape = || -> Option<SlotRet> {
3412 if ret_is_polywire {
3413 return Some(SlotRet::Poly);
3414 }
3415 if let Some(elems) = &tuple_ret_elems {
3416 let shapes: Option<Vec<SlotElem>> = elems.iter().map(classify_elem).collect();
3417 return shapes.map(SlotRet::Tuple);
3418 }
3419 classify_elem(&ret_ty).map(SlotRet::Elem)
3420 };
3421 let slot_plan: Option<(Vec<SlotArg>, SlotRet)> = (|| {
3422 if is_fallible || dynamic_outputs_inner.is_some() {
3423 return None;
3424 }
3425 let ret_shape = classify_ret_shape()?;
3426 let mut shapes = Vec::with_capacity(args.len());
3427 for a in &args {
3428 let ty = &a.declared_ty;
3429 let shape = match &a.kind {
3430 ArgKind::Wire => match is_borrow_wire_shape(ty) {
3431 Some(BorrowWire::Str) => SlotArg::Str { owned: false },
3432 Some(BorrowWire::Bytes) => SlotArg::Bytes { owned: false },
3433 Some(BorrowWire::Json) => SlotArg::JsonRef,
3434 Some(BorrowWire::Vec(variant, _)) => match variant {
3435 "VecF32" => SlotArg::Vec("F32"),
3436 "VecF64" => SlotArg::Vec("F64"),
3437 "VecF16" => SlotArg::Vec("F16"),
3438 "VecI8" => SlotArg::Vec("I8"),
3439 "VecI16" => SlotArg::Vec("I16"),
3440 "VecI32" => SlotArg::Vec("I32"),
3441 "VecI64" => SlotArg::Vec("I64"),
3442 _ => return None,
3443 },
3444 None => {
3445 if classify_wrapper_wire(ty) == Some(WrapperWire::Json) {
3446 SlotArg::JsonArc
3447 } else if is_ext_wire(ty) {
3448 SlotArg::Ext
3449 } else if owned_str_ty(ty) {
3450 SlotArg::Str { owned: true }
3451 } else if owned_bytes_ty(ty) {
3452 SlotArg::Bytes { owned: true }
3453 } else if let Some(inner) = option_inner(ty) {
3454 let jt = wire_type_to_jit_type(inner)?;
3455 if jt.width() != 1 {
3456 return None;
3457 }
3458 SlotArg::Option(jt)
3459 } else if let Some(inner) = config_inner(ty) {
3460 SlotArg::Config(if owned_str_ty(inner) {
3461 ConfigInner::Str
3462 } else if owned_bytes_ty(inner) {
3463 ConfigInner::Bytes
3464 } else {
3465 ConfigInner::Jit(wire_type_to_jit_type(inner)?)
3466 })
3467 } else if classify_wrapper_wire(ty) == Some(WrapperWire::Handle) {
3468 SlotArg::HandleArc(Box::new(extract_handle_inner(ty)?))
3469 } else if let Some(jt) = wire_type_to_jit_type(ty) {
3470 SlotArg::Jit(jt)
3471 } else {
3472 SlotArg::HandleWire
3473 }
3474 }
3475 },
3476 ArgKind::PolyWire => SlotArg::Poly,
3477 ArgKind::Variadic(elem) => SlotArg::Variadic(*elem),
3478 ArgKind::Const(shape) => SlotArg::Const(*shape),
3479 ArgKind::ConstVec(_, form) => SlotArg::ConstVec(*form),
3480 ArgKind::Setup(spec) => {
3481 // A setup over the build context is not a function
3482 // of the consts alone, so the kit takes the node's.
3483 if spec.source_args.is_empty() || spec.takes_ctx() {
3484 SlotArg::SetupStatic
3485 } else {
3486 SlotArg::Setup
3487 }
3488 }
3489 };
3490 shapes.push(shape);
3491 }
3492 // The u64 kit carries every node it is eligible for; this
3493 // kit takes the rest.
3494 if jit_eligible {
3495 return None;
3496 }
3497 Some((shapes, ret_shape))
3498 })();
3499 let slot_eligible = slot_plan.is_some();
3500
3501 // A fallible body ran once at construction; its cached value is
3502 // what every run writes. The shape decides which kit carries it.
3503 let fallible_ret: Option<SlotRet> = if is_fallible {
3504 classify_ret_shape()
3505 } else {
3506 None
3507 };
3508
3509 // Publish scratch entry `k`'s pair into the output slots at `o`.
3510 let publish = |k: usize, o: usize| -> TokenStream2 {
3511 let k = syn::Index::from(k);
3512 let o0 = syn::Index::from(o);
3513 let o1 = syn::Index::from(o + 1);
3514 quote! {
3515 let (__ptr, __len) = scratch[#k].ptr_len();
3516 outputs[#o0] = __ptr;
3517 outputs[#o1] = __len;
3518 }
3519 };
3520 // The write of one element `value` (typed `ty`) at output slot
3521 // `o`: a carrier as its bits, a `Ref2` kind into scratch entry
3522 // `k` with its pair republished (axiom S3).
3523 let write_elem = |e: SlotElem,
3524 ty: &Type,
3525 k: usize,
3526 o: usize,
3527 value: TokenStream2|
3528 -> TokenStream2 {
3529 let kk = syn::Index::from(k);
3530 let publish = publish(k, o);
3531 match e {
3532 SlotElem::Jit(jt) => jt.write_to_u64_buffer_at(o, value),
3533 SlotElem::Vec(elem) => {
3534 let se = syn::Ident::new(elem, proc_macro2::Span::call_site());
3535 quote! {
3536 {
3537 let polydat::ast::ScratchBuf::#se(__buf) = &mut scratch[#kk] else {
3538 unreachable!("scratch element type mismatch");
3539 };
3540 *__buf = #value;
3541 }
3542 #publish
3543 }
3544 }
3545 SlotElem::Str => quote! {
3546 scratch[#kk].set_str(::core::convert::AsRef::<str>::as_ref(&#value));
3547 #publish
3548 },
3549 SlotElem::Bytes => quote! {
3550 scratch[#kk].set_bytes(::core::convert::AsRef::<[u8]>::as_ref(&#value));
3551 #publish
3552 },
3553 SlotElem::Json => quote! {
3554 scratch[#kk].set_value(polydat::ast::Value::Json(#value));
3555 #publish
3556 },
3557 SlotElem::VecShared(elem) => {
3558 let se = syn::Ident::new(elem, proc_macro2::Span::call_site());
3559 quote! {
3560 {
3561 let polydat::ast::ScratchBuf::#se(__buf) = &mut scratch[#kk] else {
3562 unreachable!("scratch element type mismatch");
3563 };
3564 __buf.clear();
3565 __buf.extend_from_slice((#value).as_slice());
3566 }
3567 #publish
3568 }
3569 }
3570 SlotElem::Ext => quote! {
3571 scratch[#kk].set_value(<#ty as polydat::derive_support::Wire>::inject(#value));
3572 #publish
3573 },
3574 SlotElem::HandleArc => quote! {
3575 scratch[#kk].set_value(polydat::ast::Value::handle(#value));
3576 #publish
3577 },
3578 SlotElem::HandleWire => quote! {
3579 scratch[#kk].set_ref_value(<#ty as polydat::derive_support::Wire>::inject(#value));
3580 #publish
3581 },
3582 }
3583 };
3584 // The write of `result` (typed `ret_ty`) by shape.
3585 let write_for = |shape: &SlotRet| -> TokenStream2 {
3586 match shape {
3587 SlotRet::Elem(e) => write_elem(*e, &ret_ty, 0, 0, quote!(result)),
3588 SlotRet::Poly => quote! {
3589 polydat::derive_support::write_poly(__out_type, result, scratch, outputs);
3590 },
3591 SlotRet::Tuple(elems) => {
3592 let types = tuple_ret_elems
3593 .as_ref()
3594 .expect("a tuple shape comes from a tuple return");
3595 let locals: Vec<Ident> = (0..elems.len())
3596 .map(|i| format_ident!("__r_{}", i))
3597 .collect();
3598 let mut k = 0usize;
3599 let mut o = 0usize;
3600 let writes: Vec<TokenStream2> = elems
3601 .iter()
3602 .enumerate()
3603 .map(|(i, e)| {
3604 let local = &locals[i];
3605 let w = write_elem(*e, &types[i], k, o, quote!(#local));
3606 if e.is_ref() {
3607 k += 1;
3608 }
3609 o += e.width();
3610 w
3611 })
3612 .collect();
3613 quote! {
3614 let ( #( #locals ),* ) = result;
3615 #( #writes )*
3616 }
3617 }
3618 }
3619 };
3620 // A `HandleWire` element is admitted by its `Wire` port, which is a
3621 // constant of the type the macro cannot read: the kit checks it
3622 // when it is built and declines a port other than `Handle`.
3623 let handle_port_check = |ty: &Type| -> TokenStream2 {
3624 quote! {
3625 if <#ty as polydat::derive_support::Wire>::PORT != polydat::ast::PortType::Handle {
3626 return None;
3627 }
3628 }
3629 };
3630 let ret_port_checks = |shape: &SlotRet| -> TokenStream2 {
3631 match shape {
3632 SlotRet::Elem(SlotElem::HandleWire) => handle_port_check(&ret_ty),
3633 SlotRet::Tuple(elems) => {
3634 let types = tuple_ret_elems
3635 .as_ref()
3636 .expect("a tuple shape comes from a tuple return");
3637 let checks: Vec<TokenStream2> = elems
3638 .iter()
3639 .zip(types.iter())
3640 .filter(|(e, _)| matches!(e, SlotElem::HandleWire))
3641 .map(|(_, t)| handle_port_check(t))
3642 .collect();
3643 quote!( #( #checks )* )
3644 }
3645 _ => quote!(),
3646 }
3647 };
3648 // The scratch entries a return shape owns, in port order.
3649 let scratch_for = |shape: &SlotRet| -> TokenStream2 {
3650 match shape {
3651 SlotRet::Elem(e) => {
3652 let elems: Vec<TokenStream2> = e.scratch_elem().into_iter().collect();
3653 quote!(vec![ #( #elems ),* ])
3654 }
3655 SlotRet::Poly => quote!(
3656 polydat::ast::SlotShape::scratch_elem(&__out_type)
3657 .into_iter()
3658 .collect::<Vec<_>>()
3659 ),
3660 SlotRet::Tuple(elems) => {
3661 let elems: Vec<TokenStream2> =
3662 elems.iter().filter_map(|e| e.scratch_elem()).collect();
3663 quote!(vec![ #( #elems ),* ])
3664 }
3665 }
3666 };
3667 // A polymorphic return encodes by the node's resolved output type,
3668 // which for the split-halves shape is the type of the first value
3669 // wire, the graph's own slot for the output being a placeholder
3670 // there. The graph colored the output slot by the declared port,
3671 // so a resolved type of another color has no slot to land in and
3672 // the node stays interpreted.
3673 let out_type_for = |shape: &SlotRet, fixed_ports: usize| -> TokenStream2 {
3674 if !matches!(shape, SlotRet::Poly) {
3675 return quote!();
3676 }
3677 let fixed = syn::Index::from(fixed_ports);
3678 let resolve = if is_split_halves {
3679 quote!(*wire_types.get(#fixed + (wire_types.len() - #fixed) / 2)?)
3680 } else {
3681 quote!(self.meta().outs[0].typ)
3682 };
3683 quote! {
3684 let __out_type: polydat::ast::PortType = #resolve;
3685 if polydat::ast::SlotShape::slot_color(&__out_type) != polydat::ast::SlotShape::slot_color(&self.meta().outs[0].typ) {
3686 return None;
3687 }
3688 }
3689 };
3690 let elem_ty_tokens = |elem: &str| -> TokenStream2 {
3691 match elem {
3692 "F32" => quote!(f32),
3693 "F64" => quote!(f64),
3694 "F16" => quote!(polydat::half::f16),
3695 "I8" => quote!(i8),
3696 "I16" => quote!(i16),
3697 "I32" => quote!(i32),
3698 "I64" => quote!(i64),
3699 _ => unreachable!(),
3700 }
3701 };
3702
3703 let compiled_slot_impl: TokenStream2 = if let Some(path) = &attrs.compiled_slot_override {
3704 quote! {
3705 fn compiled_slot(&self, wire_types: &[polydat::ast::PortType], engine: polydat::Engine) -> Option<polydat::ast::CompiledSlotKit> {
3706 Some(#path(self, wire_types, engine))
3707 }
3708 }
3709 } else if let Some((shapes, ret_shape)) = &slot_plan {
3710 // Captures: consts and const lists by clone, then setups
3711 // recomputed from those captured consts exactly as `new()`
3712 // computes them (a setup is a pure function of its consts).
3713 let mut captures: Vec<TokenStream2> = Vec::new();
3714 for (a, shape) in args.iter().zip(shapes.iter()) {
3715 let n = &a.name;
3716 match shape {
3717 SlotArg::Const(_) | SlotArg::ConstVec(_) | SlotArg::SetupStatic => {
3718 captures.push(quote!(let #n = self.#n.clone();))
3719 }
3720 _ => {}
3721 }
3722 }
3723 for (a, shape) in args.iter().zip(shapes.iter()) {
3724 if let (SlotArg::Setup, ArgKind::Setup(spec)) = (shape, &a.kind) {
3725 let n = &a.name;
3726 let setup_fn = &spec.setup_fn;
3727 let src_exprs: Vec<TokenStream2> = spec
3728 .source_args
3729 .iter()
3730 .map(|src| match const_shape_by_name.get(&src.to_string()) {
3731 Some(ConstSourceShape::ScalarStr) => quote!(#src.as_str()),
3732 Some(ConstSourceShape::ScalarValue) => quote!(#src),
3733 Some(ConstSourceShape::VecValues) => quote!(&#src),
3734 None => quote!(#src),
3735 })
3736 .collect();
3737 captures.push(quote!(let #n = #setup_fn( #( #src_exprs ),* );));
3738 }
3739 }
3740 // The reads walk the input slots with two run-time counters:
3741 // `__i`, the slot the next read starts at, and `__p`, its port,
3742 // which indexes the wire types the kernel handed the kit. A
3743 // polymorphic port and a variadic element are as wide as the
3744 // wire that feeds them, so their widths are read at run time.
3745 let fixed_ports: usize = shapes
3746 .iter()
3747 .filter(|s| {
3748 matches!(
3749 s,
3750 SlotArg::Jit(_)
3751 | SlotArg::Option(_)
3752 | SlotArg::Config(_)
3753 | SlotArg::Vec(_)
3754 | SlotArg::Str { .. }
3755 | SlotArg::Bytes { .. }
3756 | SlotArg::JsonRef
3757 | SlotArg::JsonArc
3758 | SlotArg::Ext
3759 | SlotArg::HandleArc(_)
3760 | SlotArg::HandleWire
3761 | SlotArg::Poly
3762 )
3763 })
3764 .count();
3765 let fixed = syn::Index::from(fixed_ports);
3766 // SAFETY (emitted): the pair was published by the producing
3767 // step into storage with a proven owner (its own scratch, an
3768 // extern's stored value, an interned constant, or a boundary
3769 // value alive for the call), and the layer-3 ownership rule
3770 // keeps it alive until that producer reruns.
3771 let pair_slice = |elem: TokenStream2| -> TokenStream2 {
3772 quote!(unsafe {
3773 ::core::slice::from_raw_parts(
3774 inputs[__i] as usize as *const #elem,
3775 inputs[__i + 1] as usize,
3776 )
3777 })
3778 };
3779 let str_read = {
3780 let s = pair_slice(quote!(u8));
3781 quote!(unsafe { ::core::str::from_utf8_unchecked(#s) })
3782 };
3783 let bytes_read = pair_slice(quote!(u8));
3784 let arg_reads: Vec<TokenStream2> = args
3785 .iter()
3786 .zip(shapes.iter())
3787 .map(|(a, shape)| {
3788 let n = &a.name;
3789 let ty = &a.declared_ty;
3790 match shape {
3791 SlotArg::Jit(jt) => {
3792 let read = jt.read_from_u64_buffer(0);
3793 let w = jt.width();
3794 quote! {
3795 let #n = { let inputs = &inputs[__i..]; #read };
3796 __i += #w;
3797 __p += 1;
3798 }
3799 }
3800 SlotArg::Option(jt) => {
3801 let read = jt.read_from_u64_buffer(0);
3802 quote! {
3803 let #n: #ty = Some({ let inputs = &inputs[__i..]; #read });
3804 __i += 1;
3805 __p += 1;
3806 }
3807 }
3808 SlotArg::Config(ConfigInner::Jit(jt)) => {
3809 let read = jt.read_from_u64_buffer(0);
3810 let w = jt.width();
3811 quote! {
3812 let #n: #ty = polydat::derive_support::Config({ let inputs = &inputs[__i..]; #read });
3813 __i += #w;
3814 __p += 1;
3815 }
3816 }
3817 SlotArg::Config(ConfigInner::Str) => quote! {
3818 let __s: &str = #str_read;
3819 let #n: #ty = polydat::derive_support::Config(::core::convert::From::from(__s));
3820 __i += 2;
3821 __p += 1;
3822 },
3823 SlotArg::Config(ConfigInner::Bytes) => quote! {
3824 let __b: &[u8] = #bytes_read;
3825 let #n: #ty = polydat::derive_support::Config(::core::convert::From::from(__b));
3826 __i += 2;
3827 __p += 1;
3828 },
3829 SlotArg::Vec(elem) => {
3830 let et = elem_ty_tokens(elem);
3831 let s = pair_slice(et.clone());
3832 quote! {
3833 let #n: &[#et] = #s;
3834 __i += 2;
3835 __p += 1;
3836 }
3837 }
3838 SlotArg::Str { owned } => {
3839 let bind = if *owned {
3840 quote!(let #n: #ty = ::core::convert::From::from(__s);)
3841 } else {
3842 quote!(let #n: &str = __s;)
3843 };
3844 quote! {
3845 let __s: &str = #str_read;
3846 #bind
3847 __i += 2;
3848 __p += 1;
3849 }
3850 }
3851 SlotArg::Bytes { owned } => {
3852 let bind = if *owned {
3853 quote!(let #n: #ty = ::core::convert::From::from(__b);)
3854 } else {
3855 quote!(let #n: &[u8] = __b;)
3856 };
3857 quote! {
3858 let __b: &[u8] = #bytes_read;
3859 #bind
3860 __i += 2;
3861 __p += 1;
3862 }
3863 }
3864 SlotArg::JsonRef => quote! {
3865 let #n = match polydat::derive_support::ref_value(&inputs[__i..]) {
3866 polydat::ast::Value::Json(__j) => &**__j,
3867 __other => panic!("expected Json wire, got {__other:?}"),
3868 };
3869 __i += 2;
3870 __p += 1;
3871 },
3872 SlotArg::JsonArc => quote! {
3873 let #n = match polydat::derive_support::ref_value(&inputs[__i..]) {
3874 polydat::ast::Value::Json(__j) => __j.clone(),
3875 __other => panic!("expected Json wire, got {__other:?}"),
3876 };
3877 __i += 2;
3878 __p += 1;
3879 },
3880 SlotArg::Ext | SlotArg::HandleWire => quote! {
3881 let #n: #ty = <#ty as polydat::derive_support::Wire>::extract(
3882 polydat::derive_support::ref_value(&inputs[__i..]),
3883 );
3884 __i += 2;
3885 __p += 1;
3886 },
3887 SlotArg::HandleArc(inner) => quote! {
3888 let #n: std::sync::Arc<#inner> =
3889 match polydat::derive_support::ref_value(&inputs[__i..]) {
3890 polydat::ast::Value::Handle(__h) => __h
3891 .clone()
3892 .downcast::<#inner>()
3893 .expect("Handle type mismatch — wiring bug"),
3894 __other => panic!("expected Handle, got {__other:?}"),
3895 };
3896 __i += 2;
3897 __p += 1;
3898 },
3899 SlotArg::Poly => quote! {
3900 let #n: polydat::ast::Value =
3901 polydat::derive_support::read_poly(__wire_types[__p], &inputs[__i..]);
3902 __i += polydat::ast::SlotShape::slot_width(&__wire_types[__p]);
3903 __p += 1;
3904 },
3905 SlotArg::Variadic(elem) => {
3906 // A variadic takes every remaining port, or in
3907 // the split-halves shape (`pick`), its half of
3908 // them: the selectors first, then the values.
3909 let count = if is_split_halves {
3910 let pos = variadic_positions[&a.name.to_string()];
3911 if pos == 0 {
3912 quote!((__wire_types.len() - #fixed) / 2)
3913 } else {
3914 quote!(__wire_types.len() - #fixed - (__wire_types.len() - #fixed) / 2)
3915 }
3916 } else {
3917 quote!(__wire_types.len() - #fixed)
3918 };
3919 let owned = format_ident!("__{}_owned", a.name);
3920 let (elem_ty, extract, width) = match elem {
3921 VariadicElement::U64 => (quote!(u64), quote!(inputs[__i]), quote!(1)),
3922 VariadicElement::Bool => (quote!(bool), quote!(inputs[__i] != 0), quote!(1)),
3923 VariadicElement::BorrowedStr => (quote!(&str), str_read.clone(), quote!(2)),
3924 VariadicElement::OwnedString => {
3925 (quote!(String), quote!((#str_read).to_string()), quote!(2))
3926 }
3927 VariadicElement::Value => (
3928 quote!(polydat::ast::Value),
3929 quote!(polydat::derive_support::read_poly(__wire_types[__p], &inputs[__i..])),
3930 quote!(polydat::ast::SlotShape::slot_width(&__wire_types[__p])),
3931 ),
3932 };
3933 quote! {
3934 let mut #owned: Vec<#elem_ty> = Vec::with_capacity(#count);
3935 for _ in 0..#count {
3936 let __v: #elem_ty = #extract;
3937 __i += #width;
3938 __p += 1;
3939 #owned.push(__v);
3940 }
3941 let #n = &#owned[..];
3942 }
3943 }
3944 SlotArg::Const(shape) => {
3945 let wrap = shape.wrap_as_const(quote!(#n));
3946 quote!(let #n = #wrap;)
3947 }
3948 SlotArg::ConstVec(ListForm::Borrowed) => {
3949 quote!(let #n = polydat::derive_support::Const(&#n[..]);)
3950 }
3951 SlotArg::ConstVec(ListForm::Owned) => {
3952 quote!(let #n = polydat::derive_support::Const(#n.clone());)
3953 }
3954 SlotArg::Setup | SlotArg::SetupStatic => quote!(let #n = &#n;),
3955 }
3956 })
3957 .collect();
3958 let arg_names: Vec<&syn::Ident> = args.iter().map(|a| &a.name).collect();
3959 let write = write_for(ret_shape);
3960 let scratch = scratch_for(ret_shape);
3961 let out_type = out_type_for(ret_shape, fixed_ports);
3962 let arg_port_checks: Vec<TokenStream2> = args
3963 .iter()
3964 .zip(shapes.iter())
3965 .filter(|(_, s)| matches!(s, SlotArg::HandleWire))
3966 .map(|(a, _)| handle_port_check(&a.declared_ty))
3967 .collect();
3968 let ret_checks = ret_port_checks(ret_shape);
3969 quote! {
3970 #[allow(unused_mut, unused_variables, unused_assignments, clippy::unused_unit)]
3971 fn compiled_slot(&self, wire_types: &[polydat::ast::PortType], _engine: polydat::Engine) -> Option<polydat::ast::CompiledSlotKit> {
3972 #( #arg_port_checks )*
3973 #ret_checks
3974 #( #captures )*
3975 #out_type
3976 let __wire_types: Vec<polydat::ast::PortType> = wire_types.to_vec();
3977 let __scratch: Vec<polydat::ast::ScratchElem> = #scratch;
3978 Some(polydat::ast::CompiledSlotKit {
3979 scratch: __scratch,
3980 op: Box::new(move |inputs: &[u64], outputs: &mut [u64], scratch: &mut [polydat::ast::ScratchBuf]| {
3981 let mut __i: usize = 0;
3982 let mut __p: usize = 0;
3983 #( #arg_reads )*
3984 let result: #ret_ty = Self::__polydat_body( #( #arg_names ),* );
3985 #write
3986 }),
3987 })
3988 }
3989 }
3990 } else if let Some(shape) = fallible_ret.as_ref().filter(|s| s.has_ref()) {
3991 // A fallible node whose cached value is a `Ref2` kind: the
3992 // closure writes the same value into its scratch every run it
3993 // is asked for, which is once, since nothing reaches it.
3994 let write = write_for(shape);
3995 let scratch = scratch_for(shape);
3996 let out_type = out_type_for(shape, 0);
3997 let ret_checks = ret_port_checks(shape);
3998 quote! {
3999 #[allow(unused_variables)]
4000 fn compiled_slot(&self, wire_types: &[polydat::ast::PortType], _engine: polydat::Engine) -> Option<polydat::ast::CompiledSlotKit> {
4001 #ret_checks
4002 #out_type
4003 let __cached = self.__polydat_cached.clone();
4004 Some(polydat::ast::CompiledSlotKit {
4005 scratch: #scratch,
4006 op: Box::new(move |_inputs: &[u64], outputs: &mut [u64], scratch: &mut [polydat::ast::ScratchBuf]| {
4007 let result: #ret_ty = __cached.clone();
4008 #write
4009 }),
4010 })
4011 }
4012 }
4013 } else {
4014 quote!()
4015 };
4016
4017 let emit_jit_constants = attrs.jit_constants_override.is_some() || jit_eligible;
4018
4019 // Body sharing: extract the function body into a private
4020 // associated fn `__polydat_body` when JIT is emitted. Both
4021 // `eval()` (Value boxing path) and `compiled_u64()` (u64
4022 // buffer path) call it. Single source of truth.
4023 //
4024 // When JIT is not emitted, the body stays inlined inside
4025 // `eval()`'s current `#[allow(unused_variables)]` block
4026 // (Setup-bearing nodes need this — their body references
4027 // setup-derived locals via `let n = &self.n` bindings).
4028
4029 let use_shared_body = jit_eligible || slot_eligible;
4030
4031 // Body-fn parameter list — every arg in its DECLARED form
4032 // (wire as bare type, const as `Const<T>`, setup as `&T`).
4033 let body_params: Vec<TokenStream2> = args
4034 .iter()
4035 .map(|a| {
4036 let n = &a.name;
4037 let t = &a.declared_ty;
4038 // A `Const<T>` is spelled by its bare name in the source
4039 // signature; the shared body must not depend on the
4040 // module having imported it.
4041 if let (ArgKind::Const(_) | ArgKind::ConstVec(..), syn::Type::Path(p)) = (&a.kind, t)
4042 && let Some(last) = p.path.segments.last()
4043 && last.ident == "Const"
4044 {
4045 let generics = &last.arguments;
4046 return quote!(#n: polydat::derive_support::Const #generics);
4047 }
4048 quote!(#n: #t)
4049 })
4050 .collect();
4051
4052 let body_fn_def: TokenStream2 = if is_fallible {
4053 // Fallible body. Body returns the
4054 // declared Result<T, E>; try_new runs it once at
4055 // construction and propagates Err as String via Into.
4056 quote! {
4057 #[inline(always)]
4058 #[allow(unused_variables)]
4059 #[allow(clippy::ptr_arg)]
4060 fn __polydat_body( #( #body_params ),* ) -> #declared_ret_ty #block
4061 }
4062 } else if use_shared_body {
4063 quote! {
4064 #[inline(always)]
4065 #[allow(unused_variables)]
4066 #[allow(clippy::ptr_arg)]
4067 fn __polydat_body( #( #body_params ),* ) -> #ret_ty #block
4068 }
4069 } else {
4070 quote!()
4071 };
4072
4073 // Helper: emit `outputs[idx] = <conversion>(value)` for a
4074 // given element type. Owned types route
4075 // through `<T as Wire>::inject`; Handle keeps its inline
4076 // upcast (no blanket impl works). Returning a borrow shape
4077 // (`&str`, `&[u8]`, etc.) from a node body is unusual but
4078 // supported: the borrow's `into()` already exists for the
4079 // canonical `Value` constructor; we emit that directly.
4080 let output_assign = |idx_lit: TokenStream2,
4081 elem_ty: &Type,
4082 local: TokenStream2|
4083 -> TokenStream2 {
4084 if classify_wrapper_wire(elem_ty) == Some(WrapperWire::Handle) {
4085 quote! {
4086 outputs[#idx_lit] = polydat::ast::Value::handle(#local);
4087 }
4088 } else if classify_polywire(elem_ty) {
4089 // PolyWire return: body returns `Value` directly, move
4090 // it into the outputs slot. No trait dispatch — Value
4091 // has no static port type (it's polymorphic at runtime).
4092 quote! {
4093 outputs[#idx_lit] = #local;
4094 }
4095 } else if let Some(borrow) = is_borrow_wire_shape(elem_ty) {
4096 // Borrow-typed returns: construct the matching Value
4097 // variant from the borrow via the existing
4098 // `Into<Value>` / Arc::from path. `&str` →
4099 // `Value::Str(arc)`; `&[u8]` → `Value::Bytes(arc)`;
4100 // typed-vec borrows → `Value::Vec*(SliceArc::from(slice))`.
4101 match borrow {
4102 BorrowWire::Str => quote! {
4103 outputs[#idx_lit] = polydat::ast::Value::Str((#local).into());
4104 },
4105 BorrowWire::Bytes => quote! {
4106 outputs[#idx_lit] = polydat::ast::Value::Bytes((#local).into());
4107 },
4108 BorrowWire::Json => quote! {
4109 outputs[#idx_lit] = polydat::ast::Value::Json(::std::sync::Arc::new((#local).clone()));
4110 },
4111 BorrowWire::Vec(variant, _) => {
4112 let v = syn::Ident::new(variant, proc_macro2::Span::call_site());
4113 quote! {
4114 outputs[#idx_lit] = polydat::ast::Value::#v(polydat::ast::SliceArc::from_vec((#local).to_vec()));
4115 }
4116 }
4117 }
4118 } else {
4119 quote! {
4120 outputs[#idx_lit] = <#elem_ty as polydat::derive_support::Wire>::inject(#local);
4121 }
4122 }
4123 };
4124
4125 // `DynamicOutputs<T>` — build the `outs:` vec at
4126 // construction from the driving `Const<Vec<C>>` arg's
4127 // length. Used by both the infallible `new()` and the
4128 // fallible `try_new()` paths below.
4129 let outs_build: TokenStream2 = if let (Some(inner), Some(count_arg)) =
4130 (&dynamic_outputs_inner, &dynamic_outputs_count_arg)
4131 {
4132 quote! {
4133 let outs: Vec<polydat::ast::Port> = (0..#count_arg.len())
4134 .map(|__i| polydat::ast::Port::new(
4135 format!("d{}", __i),
4136 <#inner as polydat::derive_support::Wire>::PORT,
4137 ))
4138 .collect();
4139 }
4140 } else {
4141 quote! {
4142 let outs = vec![ #(
4143 polydat::ast::Port::new(#output_names_strs, #output_port_types)
4144 ),* ];
4145 }
4146 };
4147
4148 // Result → outputs translation. For
4149 // single-output, write `outputs[0] = ...(result)`. For
4150 // tuple-output, destructure and per-element write. For
4151 // `DynamicOutputs<T>`, iterate the returned Vec
4152 // and inject each element via the inner type's Wire impl.
4153 let result_to_outputs: TokenStream2 = if let Some(inner) = &dynamic_outputs_inner {
4154 let inject_one = if classify_polywire(inner) {
4155 quote!(__elem)
4156 } else if let Some(borrow) = is_borrow_wire_shape(inner) {
4157 match borrow {
4158 BorrowWire::Str => quote!(polydat::ast::Value::Str((__elem).into())),
4159 BorrowWire::Bytes => quote!(polydat::ast::Value::Bytes((__elem).into())),
4160 BorrowWire::Json => quote!(polydat::ast::Value::Json(::std::sync::Arc::new(
4161 (__elem).clone()
4162 ))),
4163 BorrowWire::Vec(variant, _) => {
4164 let v = syn::Ident::new(variant, proc_macro2::Span::call_site());
4165 quote!(polydat::ast::Value::#v(polydat::ast::SliceArc::from_vec((__elem).to_vec())))
4166 }
4167 }
4168 } else {
4169 quote!(<#inner as polydat::derive_support::Wire>::inject(__elem))
4170 };
4171 quote! {
4172 for (__i, __elem) in result.0.into_iter().enumerate() {
4173 outputs[__i] = #inject_one;
4174 }
4175 }
4176 } else if let Some(elems) = &tuple_ret_elems {
4177 let locals: Vec<Ident> = (0..elems.len())
4178 .map(|i| format_ident!("__r_{}", i))
4179 .collect();
4180 let writes: Vec<TokenStream2> = elems
4181 .iter()
4182 .enumerate()
4183 .map(|(i, elem_ty)| {
4184 let local = &locals[i];
4185 let idx = syn::Index::from(i);
4186 output_assign(quote!(#idx), elem_ty, quote!(#local))
4187 })
4188 .collect();
4189 quote! {
4190 let ( #( #locals ),* ) = result;
4191 #( #writes )*
4192 }
4193 } else {
4194 output_assign(quote!(0), &ret_ty, quote!(result))
4195 };
4196
4197 // Eval-path arg bindings + body-call. When JIT is emitted,
4198 // eval() unboxes from Values and calls `__polydat_body`.
4199 // When JIT is not emitted, the body stays inline in
4200 // `eval()` for back-compat with Setup-bearing nodes.
4201 let eval_body: TokenStream2 = if use_shared_body {
4202 let arg_names: Vec<&syn::Ident> = args.iter().map(|a| &a.name).collect();
4203 quote! {
4204 #[allow(unused_variables)]
4205 {
4206 #( #arg_bindings )*
4207 let result: #ret_ty = Self::__polydat_body( #( #arg_names ),* );
4208 #result_to_outputs
4209 }
4210 }
4211 } else {
4212 quote! {
4213 #[allow(unused_variables)]
4214 {
4215 #( #arg_bindings )*
4216 let result: #ret_ty = (|| #block)();
4217 #result_to_outputs
4218 }
4219 }
4220 };
4221
4222 // compiled_u64() emission. Three cases:
4223 // (a) Override path supplied → call it.
4224 // (b) JIT eligible and not opted out → emit closure that
4225 // reads from u64 buffer, captures const fields by
4226 // Copy, calls __polydat_body, writes back.
4227 // (c) Otherwise → don't override the trait default
4228 // (returns None).
4229 let state_impl: TokenStream2 = if let Some(path) = &attrs.state {
4230 quote! {
4231 fn scratch_layout(&self) -> Vec<polydat::ast::ScratchElem> {
4232 #path::layout(self)
4233 }
4234 fn eval_in(
4235 &self,
4236 scratch: &mut [polydat::ast::ScratchBuf],
4237 inputs: &[polydat::ast::Value],
4238 outputs: &mut [polydat::ast::Value],
4239 ) {
4240 #path::eval(self, scratch, inputs, outputs)
4241 }
4242 }
4243 } else {
4244 quote!()
4245 };
4246
4247 let compiled_u64_impl: TokenStream2 = if let Some(path) = &attrs.compiled_u64_override {
4248 // Pass `&self` to the override fn so setup-derived state
4249 // (round_keys, half_bits, etc.) is reachable. The override
4250 // fn signature is `fn(&Self) -> CompiledU64Op`.
4251 quote! {
4252 fn compiled_u64(&self) -> Option<polydat::ast::CompiledU64Op> {
4253 Some(#path(self))
4254 }
4255 }
4256 } else if let Some(shape) = fallible_ret.as_ref().filter(|s| !s.has_ref()) {
4257 // A fallible node whose cached value is a carrier (or a tuple
4258 // of carriers): the closure writes it every run.
4259 let write = write_for(shape);
4260 quote! {
4261 fn compiled_u64(&self) -> Option<polydat::ast::CompiledU64Op> {
4262 let __cached = self.__polydat_cached.clone();
4263 Some(Box::new(move |_inputs: &[u64], outputs: &mut [u64]| {
4264 let result: #ret_ty = __cached.clone();
4265 #write
4266 }))
4267 }
4268 }
4269 } else if jit_eligible {
4270 // Per-arg jit handling. Wire args read from inputs at
4271 // the next sequential index. Const args capture by Copy
4272 // from self at closure-creation time, then re-wrap as
4273 // `Const<T>` inside the closure for handoff to body.
4274 let jit_types = arg_jit_types.as_ref().unwrap();
4275 let mut wire_buf_idx = 0usize;
4276
4277 let captures: Vec<TokenStream2> = args
4278 .iter()
4279 .filter_map(|a| match &a.kind {
4280 ArgKind::Wire | ArgKind::Variadic(_) => None,
4281 ArgKind::Const(_) => {
4282 let n = &a.name;
4283 Some(quote!(let #n = self.#n.clone();))
4284 }
4285 ArgKind::Setup(_) | ArgKind::PolyWire | ArgKind::ConstVec(..) => {
4286 unreachable!("setup/polywire/constvec excludes JIT eligibility")
4287 }
4288 })
4289 .collect();
4290
4291 let arg_reads: Vec<TokenStream2> = args
4292 .iter()
4293 .zip(jit_types.iter())
4294 .map(|(a, jt)| {
4295 let n = &a.name;
4296 let _ = jt;
4297 match &a.kind {
4298 ArgKind::Wire => {
4299 let read = jt.read_from_u64_buffer(wire_buf_idx);
4300 wire_buf_idx += jt.width();
4301 quote!(let #n = #read;)
4302 }
4303 ArgKind::Const(shape) => {
4304 if *shape == ConstShape::Str {
4305 quote!(let #n = polydat::derive_support::Const(#n.as_str());)
4306 } else {
4307 quote!(let #n = polydat::derive_support::Const(#n);)
4308 }
4309 }
4310 ArgKind::Variadic(_) => {
4311 // u64 variadic — pass the
4312 // whole `inputs: &[u64]` buffer directly
4313 // to the body. Zero allocation, zero conversion.
4314 // (Non-u64 variadics aren't JIT-eligible —
4315 // this branch is only reached for u64 elems.)
4316 quote!(let #n: &[u64] = inputs;)
4317 }
4318 ArgKind::Setup(_) | ArgKind::PolyWire | ArgKind::ConstVec(..) => unreachable!(),
4319 }
4320 })
4321 .collect();
4322
4323 let arg_names: Vec<&syn::Ident> = args.iter().map(|a| &a.name).collect();
4324 // Multi-output write. For single-output
4325 // ret, `write` emits `outputs[0] = bits(result)`. For
4326 // tuple-output, destructure into locals and emit a
4327 // per-element write line.
4328 let write = if let Some(tuple_jits) = &tuple_ret_jit_types {
4329 let locals: Vec<Ident> = (0..tuple_jits.len())
4330 .map(|i| format_ident!("__jit_r_{}", i))
4331 .collect();
4332 // Per-element write at the element's slot OFFSET (the
4333 // prefix sum of preceding element widths — §8.4 L1).
4334 let mut out_off = 0usize;
4335 let writes: Vec<TokenStream2> = tuple_jits
4336 .iter()
4337 .enumerate()
4338 .map(|(i, jt)| {
4339 let local = &locals[i];
4340 let w = jt.write_to_u64_buffer_at(out_off, quote!(#local));
4341 out_off += jt.width();
4342 w
4343 })
4344 .collect();
4345 quote! {
4346 let ( #( #locals ),* ) = result;
4347 #( #writes )*
4348 }
4349 } else {
4350 let ret_jit = ret_jit_type.unwrap();
4351 ret_jit.write_to_u64_buffer(quote!(result))
4352 };
4353
4354 quote! {
4355 fn compiled_u64(&self) -> Option<polydat::ast::CompiledU64Op> {
4356 #( #captures )*
4357 Some(Box::new(move |inputs: &[u64], outputs: &mut [u64]| {
4358 #( #arg_reads )*
4359 let result: #ret_ty = Self::__polydat_body( #( #arg_names ),* );
4360 #write
4361 }))
4362 }
4363 }
4364 } else {
4365 quote!()
4366 };
4367
4368 // jit_constants() emission. Three cases:
4369 // (a) Override path supplied → call it with `&self`.
4370 // (b) JIT eligible and not opted out → emit a Vec<u64>
4371 // built from const fields in declaration order,
4372 // bit-reinterpreting f64 and 0/1-encoding bool.
4373 // (c) Otherwise → don't override the trait default.
4374 let jit_constants_impl: TokenStream2 = if let Some(path) = &attrs.jit_constants_override {
4375 quote! {
4376 fn jit_constants(&self) -> Vec<u64> {
4377 #path(self)
4378 }
4379 }
4380 } else if emit_jit_constants {
4381 let const_encodings: Vec<TokenStream2> = args
4382 .iter()
4383 .filter_map(|a| match &a.kind {
4384 ArgKind::Const(shape) => {
4385 let jt = const_shape_to_jit_type(*shape)?;
4386 let n = &a.name;
4387 Some(jt.const_field_as_u64(quote!(self.#n)))
4388 }
4389 _ => None,
4390 })
4391 .collect();
4392
4393 quote! {
4394 fn jit_constants(&self) -> Vec<u64> {
4395 vec![ #( #const_encodings ),* ]
4396 }
4397 }
4398 } else {
4399 quote!()
4400 };
4401
4402 // purity() emission — only when attribute is set; otherwise
4403 // the trait default (`Pure`) is used.
4404 //
4405 // Two attribute shapes:
4406 // - `Expr::Path` (e.g. `Nondeterministic`)
4407 // → `Purity::Nondeterministic`
4408 // - `Expr::Call` (e.g. `SideChannel(LogBuffer)`)
4409 // → `Purity::SideChannel { sink: SideChannelSink::LogBuffer }`
4410 let purity_impl: TokenStream2 = match &attrs.purity {
4411 None => quote!(),
4412 Some(syn::Expr::Path(p)) => {
4413 let variant = &p.path;
4414 quote! {
4415 fn purity(&self) -> polydat::ast::Purity {
4416 polydat::ast::Purity::#variant
4417 }
4418 }
4419 }
4420 Some(syn::Expr::Call(c)) => {
4421 // Dispatch on the variant head.
4422 // SideChannel(<SideChannelSink variant>) →
4423 // Purity::SideChannel { sink: SideChannelSink::<arg> }
4424 // Nondeterministic(<&'static str reason>) →
4425 // Purity::Nondeterministic { reason: <arg> }
4426 let syn::Expr::Path(head_path) = &*c.func else {
4427 return Err(syn::Error::new_spanned(
4428 &c.func,
4429 "purity call-form expects a Purity variant ident as the head.",
4430 ));
4431 };
4432 let head_ident = head_path.path.get_ident().ok_or_else(|| {
4433 syn::Error::new_spanned(
4434 &c.func,
4435 "purity call-form head must be a single Purity variant ident.",
4436 )
4437 })?;
4438 let arg = c.args.first().ok_or_else(|| {
4439 syn::Error::new_spanned(c, "purity call-form requires one argument.")
4440 })?;
4441 match head_ident.to_string().as_str() {
4442 "SideChannel" => quote! {
4443 fn purity(&self) -> polydat::ast::Purity {
4444 polydat::ast::Purity::SideChannel {
4445 sink: polydat::ast::SideChannelSink::#arg,
4446 }
4447 }
4448 },
4449 "Nondeterministic" => quote! {
4450 fn purity(&self) -> polydat::ast::Purity {
4451 polydat::ast::Purity::Nondeterministic { reason: #arg }
4452 }
4453 },
4454 other => {
4455 return Err(syn::Error::new_spanned(
4456 head_ident,
4457 format!(
4458 "purity call-form head `{other}` not recognized. \
4459 Use `SideChannel(<sink>)` or `Nondeterministic(<reason>)`."
4460 ),
4461 ));
4462 }
4463 }
4464 }
4465 Some(other) => {
4466 return Err(syn::Error::new_spanned(
4467 other,
4468 "purity attribute must be a Purity variant path or call form",
4469 ));
4470 }
4471 };
4472
4473 let simd_variant_impl: TokenStream2 = match &attrs.simd {
4474 None => quote!(),
4475 Some(vector_node) if attrs.simd_total => quote! {
4476 fn simd_variant(&self) -> Option<polydat::ast::SimdVariant> {
4477 Some(polydat::ast::SimdVariant::exact_total(#vector_node))
4478 }
4479 },
4480 Some(vector_node) => quote! {
4481 fn simd_variant(&self) -> Option<polydat::ast::SimdVariant> {
4482 Some(polydat::ast::SimdVariant::exact_fallible(#vector_node))
4483 }
4484 },
4485 };
4486
4487 // Conditional FuncSig fields.
4488 let identity_field: TokenStream2 = if let Some(expr) = &attrs.identity {
4489 quote!(Some(#expr))
4490 } else {
4491 quote!(None)
4492 };
4493
4494 // `variadic_ctor` only emitted for pure-variadic nodes (no
4495 // const args, no PolyWire). Const+variadic mixing would need
4496 // the ctor to thread the const values through, which it does
4497 // not do.
4498 let has_const_arg = args.iter().any(|a| matches!(a.kind, ArgKind::Const(_)));
4499 let has_polywire = args.iter().any(|a| matches!(a.kind, ArgKind::PolyWire));
4500 // A node whose output type is resolved from its wires cannot be
4501 // built from an arity alone, so it has no arity-only thunk; the
4502 // build closure, which has the wire types, is its one path. Nor
4503 // can a node whose setup reads the build context.
4504 let variadic_ctor_field: TokenStream2 = if has_variadic
4505 && !has_const_arg
4506 && !has_polywire
4507 && !needs_variadic_out_type
4508 && !takes_ctx
4509 {
4510 // Split-halves: assembler passes TOTAL wire count; the
4511 // struct's `new()` takes per-half count, so divide by 2.
4512 if is_split_halves {
4513 quote!(Some(|n| Box::new(#struct_name::new(n / 2))))
4514 } else {
4515 quote!(Some(|n| Box::new(#struct_name::new(n))))
4516 }
4517 } else {
4518 quote!(None)
4519 };
4520
4521 // An `Option<T>` arg auto-emits
4522 // `accepts_none_inputs() -> true`. The runtime kernel's
4523 // None propagation (engines.md §3.3) short-circuits `Value::None`
4524 // inputs by default; `Option<T>` is the canonical opt-in
4525 // shape that wants None routed to the body instead.
4526 // `Option<T>` wire args declare
4527 // None-tolerance via the type system; PolyWire (`Value`) args
4528 // ARE inherently None-tolerant (`Value::None` is just one of
4529 // the polymorphic variants). Both opt the node out of the
4530 // kernel's None short-circuit.
4531 let has_none_aware_arg = args.iter().any(|a| match &a.kind {
4532 ArgKind::Wire => is_option_arg(&a.declared_ty),
4533 ArgKind::PolyWire => true,
4534 _ => false,
4535 });
4536 let accepts_none_impl: TokenStream2 = if has_none_aware_arg {
4537 quote! {
4538 fn accepts_none_inputs(&self) -> bool { true }
4539 }
4540 } else {
4541 quote!()
4542 };
4543
4544 // `Const<Vec<C>>` implies
4545 // `Arity::VariadicConsts`. Mutually exclusive with the
4546 // wire-variadic case (the macro rejects mixing them earlier).
4547 let has_const_vec = args.iter().any(|a| matches!(a.kind, ArgKind::ConstVec(..)));
4548 let arity_field: TokenStream2 = if has_variadic {
4549 // Split-halves: `variadic_min` is interpreted
4550 // as PAIRS count; the FuncSig advertises 2× as total
4551 // wires so the assembler enforces the right floor.
4552 let min_wires = match (&attrs.variadic_min, is_split_halves) {
4553 (Some(v), true) => quote!(2 * (#v)),
4554 (Some(v), false) => quote!(#v),
4555 (None, _) => quote!(0),
4556 };
4557 quote!(polydat::dsl::registry::Arity::VariadicWires { min_wires: #min_wires })
4558 } else if has_const_vec {
4559 // min_consts = 0 by default; the workload-list shape
4560 // permits empty lists. Authors who want a minimum
4561 // declare it via `#[poly_default]` on the inner type or
4562 // by validating in the body.
4563 quote!(polydat::dsl::registry::Arity::VariadicConsts { min_consts: 0 })
4564 } else {
4565 quote!(polydat::dsl::registry::Arity::Fixed)
4566 };
4567
4568 let commutativity_field: TokenStream2 = if let Some(c) = &attrs.commutativity {
4569 quote!(polydat::ast::Commutativity::#c)
4570 } else {
4571 quote!(polydat::ast::Commutativity::Positional)
4572 };
4573
4574 // Fallible-mode emission. When the body
4575 // returns Result<T, E>, the macro:
4576 // * adds a cached `__polydat_cached: T` struct field,
4577 // * replaces `new(...)` with `try_new(...) -> Result<Self, String>`,
4578 // * runs the body once inside try_new, captures Ok into the
4579 // cache, propagates Err via Into<String>,
4580 // * makes eval read the cached value (no per-eval body call).
4581 let ctor_doc = format!("A `{func_name_str}` node with the given constant arguments.");
4582 let (ctor_emission, eval_emission, build_call_emission): (
4583 TokenStream2,
4584 TokenStream2,
4585 TokenStream2,
4586 ) = if is_fallible {
4587 // body-arg pass list. In try_new() Const args arrive as
4588 // their `field_type_tokens()` form (String for Str, raw
4589 // primitive otherwise) and need wrapping as `Const<T>` for
4590 // the body's declared signature. Setup args are locals
4591 // produced by `setup_precomputes` — body takes `&local`.
4592 let body_arg_passes: Vec<TokenStream2> = args
4593 .iter()
4594 .map(|a| {
4595 let n = &a.name;
4596 match &a.kind {
4597 ArgKind::Const(shape) => shape.wrap_as_const(quote!(#n)),
4598 ArgKind::Setup(_) => quote!(&#n),
4599 // Wire / PolyWire / Variadic are rejected
4600 // earlier for fallible nodes — unreachable.
4601 _ => quote!(#n),
4602 }
4603 })
4604 .collect();
4605 // Local wrapping: each Const arg comes in as the wrapper
4606 // (matching new_params), so we forward it directly. The
4607 // body receives `Const<T>` and unwraps via .0 or .as_str()
4608 // in its own code.
4609 let try_new = quote! {
4610 #[doc = #ctor_doc]
4611 pub fn try_new( #( #new_params ),* ) -> ::std::result::Result<Self, String> {
4612 #( #setup_precomputes )*
4613 let mut ins: Vec<polydat::ast::Slot> = vec![ #( #slot_exprs ),* ];
4614 #( #variadic_slot_extends )*
4615 #outs_build
4616 // Invoke the body once; propagate Err as String.
4617 let __polydat_cached = match Self::__polydat_body( #( #body_arg_passes ),* ) {
4618 Ok(v) => v,
4619 Err(e) => return Err(Into::<String>::into(e)),
4620 };
4621 Ok(Self {
4622 meta: polydat::ast::NodeMeta {
4623 name: #func_name_str.into(),
4624 ins,
4625 outs,
4626 },
4627 #( #new_field_inits, )*
4628 __polydat_cached,
4629 })
4630 }
4631 };
4632 // eval reads the cached value; no body call.
4633 let out_assign = output_assign(quote!(0), &ret_ty, quote!(self.__polydat_cached.clone()));
4634 let ev = quote! {
4635 #[allow(unused_variables)]
4636 { #out_assign }
4637 };
4638 // build closure: call try_new and propagate Err.
4639 let bc = quote! {
4640 Some(match #struct_name::try_new( #( #new_call_args ),* ) {
4641 Ok(n) => Ok(Box::new(n) as Box<dyn polydat::ast::PolydatNode>),
4642 Err(e) => Err(e),
4643 })
4644 };
4645 (try_new, ev, bc)
4646 } else {
4647 let ctor = quote! {
4648 #[doc = #ctor_doc]
4649 pub fn new( #( #new_params ),* ) -> Self {
4650 // Setup pre-computes (FnOnce-
4651 // equivalent — emitted once by the macro,
4652 // never reachable by any other code path).
4653 #( #setup_precomputes )*
4654 // Build the `ins` slot list. Const args and
4655 // singleton wires already appear in `slot_exprs`;
4656 // variadic args append N slots per `n_wires`.
4657 let mut ins: Vec<polydat::ast::Slot> = vec![ #( #slot_exprs ),* ];
4658 #( #variadic_slot_extends )*
4659 #outs_build
4660 Self {
4661 meta: polydat::ast::NodeMeta {
4662 name: #func_name_str.into(),
4663 ins,
4664 outs,
4665 },
4666 #( #new_field_inits, )*
4667 }
4668 }
4669 };
4670 let ev = quote!(#eval_body);
4671 // Wrap `new()` in `catch_unwind` so that panics from
4672 // `#[poly_const]` setup functions (Regex parse failures,
4673 // file-not-found from filename consts, "value:weight"
4674 // parse failures, etc.) surface as build-closure `Err`
4675 // values rather than unwinding through the compile path.
4676 // The runtime sees `name` here as the DSL-registered
4677 // function name; the message is prefixed for traceability.
4678 let bc = quote! {
4679 Some(match ::std::panic::catch_unwind(
4680 ::std::panic::AssertUnwindSafe(|| #struct_name::new( #( #new_call_args ),* ))
4681 ) {
4682 Ok(node) => Ok(Box::new(node) as Box<dyn polydat::ast::PolydatNode>),
4683 Err(panic) => {
4684 let msg = panic.downcast_ref::<&str>().copied()
4685 .or_else(|| panic.downcast_ref::<String>().map(|s| s.as_str()))
4686 .unwrap_or("<non-string panic>");
4687 Err(format!("{}: construction failed: {}", #func_name_str, msg))
4688 }
4689 })
4690 };
4691 (ctor, ev, bc)
4692 };
4693
4694 // Cached field for fallible mode. T = `ret_ty` (the Ok inner).
4695 let cached_field: TokenStream2 = if is_fallible {
4696 quote!(__polydat_cached: #ret_ty,)
4697 } else {
4698 quote!()
4699 };
4700
4701 // The node's documentation: the function's own doc comments on the
4702 // struct the macro generates, or a line naming the node, and a line
4703 // for the constructor, so a generated node is documented as the
4704 // function that defines it is. The same text fills the registered
4705 // signature: the first paragraph is its `description`, the rest
4706 // its `help`.
4707 let fn_docs: Vec<&syn::Attribute> = func
4708 .attrs
4709 .iter()
4710 .filter(|a| a.path().is_ident("doc"))
4711 .collect();
4712 let struct_doc = if fn_docs.is_empty() {
4713 let text = format!("The `{func_name_str}` node.");
4714 quote! { #[doc = #text] }
4715 } else {
4716 quote! { #( #fn_docs )* }
4717 };
4718 let (description, help) = doc_text(&fn_docs);
4719 let description_lit = syn::LitStr::new(&description, proc_macro2::Span::call_site());
4720 let help_lit = syn::LitStr::new(&help, proc_macro2::Span::call_site());
4721 // The node's own validator, when it declared one.
4722 let validate_emission = match &attrs.validate_fn {
4723 Some(p) => quote!(Some(#p as polydat::dsl::const_constraints::NodeValidator)),
4724 None => quote!(None),
4725 };
4726
4727 let result = quote! {
4728 #struct_doc
4729 pub struct #struct_name {
4730 meta: polydat::ast::NodeMeta,
4731 #( #struct_fields, )*
4732 #cached_field
4733 }
4734
4735 #default_impl
4736
4737 #fused_node_impl
4738
4739 impl #struct_name {
4740 #ctor_emission
4741
4742 // Shared `__polydat_body` extracted
4743 // when the node is JIT-eligible. Both `eval()` and
4744 // `compiled_u64()` call it. Empty token stream when
4745 // JIT is not emitted (body stays inlined in eval).
4746 #body_fn_def
4747 }
4748
4749 impl polydat::ast::PolydatNode for #struct_name {
4750 fn meta(&self) -> &polydat::ast::NodeMeta { &self.meta }
4751
4752 fn eval(
4753 &self,
4754 inputs: &[polydat::ast::Value],
4755 outputs: &mut [polydat::ast::Value],
4756 ) {
4757 #eval_emission
4758 }
4759
4760 #state_impl
4761 #compiled_u64_impl
4762 #compiled_slot_impl
4763 #jit_constants_impl
4764 #purity_impl
4765 #simd_variant_impl
4766 #accepts_none_impl
4767 }
4768
4769 // Link-time registration via the `NodeRegistration`
4770 // inventory channel (library_catalog.md "Registration").
4771 // The build closure pulls const args from the runtime
4772 // `consts` slice, falling back to per-arg
4773 // `#[poly_default(...)]` values if the slice is short.
4774 const _: () = {
4775 // `FuncSig` is `#[non_exhaustive]`: the signature starts
4776 // from its constructor and sets each field this node
4777 // decides, commutativity through its setter because the
4778 // value it replaces cannot be dropped in a `const`.
4779 static PARAMS: &[polydat::dsl::registry::ParamSpec] = &[ #( #param_specs ),* ];
4780 static SIGS: &[polydat::dsl::registry::FuncSig] = &[{
4781 let mut sig = polydat::dsl::registry::FuncSig::new(
4782 #func_name_str,
4783 polydat::dsl::registry::FuncCategory::#category,
4784 PARAMS,
4785 )
4786 .with_commutativity(#commutativity_field);
4787 sig.outputs = #output_count_lit;
4788 sig.description = #description_lit;
4789 sig.help = #help_lit;
4790 sig.identity = #identity_field;
4791 sig.variadic_ctor = #variadic_ctor_field;
4792 sig.arity = #arity_field;
4793 sig.default_resolver = #default_resolver_field;
4794 sig.output_type = #output_type_tokens;
4795 sig.output_port = #output_port_field;
4796 sig
4797 }];
4798
4799 fn signatures() -> &'static [polydat::dsl::registry::FuncSig] { SIGS }
4800
4801 fn build(
4802 _ctx: &polydat::dsl::factory::BuildContext,
4803 name: &str,
4804 _wires: &[polydat::compile::assembly::WireRef],
4805 _wire_types: &[polydat::ast::PortType],
4806 consts: &[polydat::dsl::factory::ConstArg],
4807 ) -> Option<Result<Box<dyn polydat::ast::PolydatNode>, String>> {
4808 if name != #func_name_str { return None; }
4809 #( #const_extracts )*
4810 #( #polywire_extracts )*
4811 #variadic_n_wires_extract
4812 #build_call_emission
4813 }
4814
4815 ::polydat::inventory::submit! {
4816 polydat::dsl::registry::NodeRegistration {
4817 signatures,
4818 build,
4819 validate: #validate_emission,
4820 }
4821 }
4822 };
4823 };
4824
4825 Ok(result)
4826}
4827
4828/// Split a function's `///` comments into the registered
4829/// `description` (the first paragraph, joined onto one line) and
4830/// `help` (every paragraph after it, lines kept). Each line loses
4831/// the one space rustdoc puts after `///`.
4832fn doc_text(doc_attrs: &[&syn::Attribute]) -> (String, String) {
4833 let mut lines: Vec<String> = Vec::new();
4834 for attr in doc_attrs {
4835 if let syn::Meta::NameValue(nv) = &attr.meta
4836 && let syn::Expr::Lit(syn::ExprLit {
4837 lit: syn::Lit::Str(s),
4838 ..
4839 }) = &nv.value
4840 {
4841 let raw = s.value();
4842 lines.push(raw.strip_prefix(' ').unwrap_or(&raw).to_string());
4843 }
4844 }
4845 while lines.first().is_some_and(|l| l.trim().is_empty()) {
4846 lines.remove(0);
4847 }
4848 while lines.last().is_some_and(|l| l.trim().is_empty()) {
4849 lines.pop();
4850 }
4851 let split = lines
4852 .iter()
4853 .position(|l| l.trim().is_empty())
4854 .unwrap_or(lines.len());
4855 let description = lines[..split]
4856 .iter()
4857 .map(|l| l.trim())
4858 .collect::<Vec<_>>()
4859 .join(" ");
4860 let rest = &lines[split..];
4861 let rest_start = rest
4862 .iter()
4863 .position(|l| !l.trim().is_empty())
4864 .unwrap_or(rest.len());
4865 let help = rest[rest_start..]
4866 .iter()
4867 .map(|l| l.trim_end())
4868 .collect::<Vec<_>>()
4869 .join("\n");
4870 (description, help)
4871}
4872
4873/// `snake_case` → `PascalCase` (for the generated struct name).
4874fn to_camel_case(s: &str) -> String {
4875 let mut out = String::with_capacity(s.len());
4876 let mut up = true;
4877 for c in s.chars() {
4878 if c == '_' {
4879 up = true;
4880 continue;
4881 }
4882 if up {
4883 out.extend(c.to_uppercase());
4884 up = false;
4885 } else {
4886 out.push(c);
4887 }
4888 }
4889 out
4890}
4891
4892/// Stringify a `syn::Type` minimally — used for primitive-type
4893/// dispatch. Not a robust pretty-printer; only handles the
4894/// shapes the simple-case allows (bare path, `&str`, `String`).
4895fn type_to_string(ty: &Type) -> String {
4896 use quote::ToTokens;
4897 let mut s = String::new();
4898 for t in ty.to_token_stream() {
4899 s.push_str(&t.to_string());
4900 s.push(' ');
4901 }
4902 s.trim().to_string()
4903}