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