polydat 0.1.0

Polydat — generation kernel for deterministic variate generation in nb-rs (formerly nbrs-variates)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Per-statement compilation for the GK DSL compiler.
//!
//! `compile_binding` maps each AST statement to assembler operations:
//! function calls become nodes, literals become constant nodes, and
//! identifiers become identity (alias) nodes.
//!
//! Literal promotion: when a literal constant (integer, float, string)
//! appears in a position where the function's signature expects a wire
//! input, the compiler automatically inserts an anonymous `ConstU64`,
//! `ConstF64`, or `ConstStr` node and wires from it.  This lets you
//! write `pow(x, 3.0)` or `f64_mul(x, 0.1)` directly without first
//! binding the constant to a name.

use crate::assembly::{GkAssembler, WireRef};
use crate::dsl::ast::*;
use crate::dsl::factory::{build_node, ConstArg};
use crate::dsl::registry;
use crate::node::{PortType, SlotType};
use crate::nodes::fixed::*;
use crate::nodes::identity::*;
use crate::nodes::format::*;

use super::compile::Compiler;
use crate::dsl::lexer::Span;

/// Wrap an expression in a `to_f64(expr)` call. Used by the
/// `if(cond, a, b)` desugar to widen a u64 branch when the other
/// branch is f64.
/// Does the string literal contain at least one `{...}` placeholder
/// whose body is *not* literal content (a quoted JSON / CQL map
/// fragment)? Used by the binding compiler to decide whether to
/// desugar a string literal as a printf interpolation node or
/// emit it as a plain `ConstStr`.
///
/// Mirrors `nbrs_workload::bindpoints::is_literal_content` so the
/// compile-time and parse-time disambiguation rules stay aligned:
/// a `{...}` whose trimmed body starts with `'` or `"` is literal
/// content (e.g. `{'class': 'SimpleStrategy'}`,
/// `{"a": 1, "b": 2}`), never a bind point.
fn string_lit_has_real_placeholder(s: &str) -> bool {
    let chars: Vec<char> = s.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '{' {
            let body_start = i + 1;
            let mut body_end = body_start;
            while body_end < chars.len() && chars[body_end] != '}' {
                body_end += 1;
            }
            let body: String = chars[body_start..body_end].iter().collect();
            let trimmed = body.trim();
            if !trimmed.is_empty()
                && !trimmed.starts_with('\'')
                && !trimmed.starts_with('"')
            {
                return true;
            }
            i = body_end + 1;
        } else {
            i += 1;
        }
    }
    false
}

fn wrap_to_f64(inner: Expr) -> Expr {
    let span = match &inner {
        Expr::IntLit(_, s) | Expr::FloatLit(_, s) | Expr::StringLit(_, s)
            | Expr::Ident(_, s) | Expr::UnaryNeg(_, s) | Expr::UnaryBitNot(_, s)
            | Expr::ArrayLit(_, s) => *s,
        Expr::Call(c) => c.span,
        Expr::FieldAccess { span, .. } => *span,
        Expr::BinOp(..) => Span { line: 0, col: 0 },
    };
    Expr::Call(crate::dsl::ast::CallExpr {
        func: "to_f64".into(),
        args: vec![Arg::Positional(inner)],
        span,
    })
}

/// Flatten an `+`-tree of Str operands into a single sequence.
///
/// `"a" + b + "c"` parses as `BinOp(BinOp("a", +, b), +, "c")`; this
/// walks the left/right spines and emits each leaf so the str_concat
/// desugar can produce a single variadic node instead of a chain of
/// 2-arg concats.
fn flatten_str_add(expr: &Expr, out: &mut Vec<Expr>) {
    match expr {
        Expr::BinOp(l, BinOpKind::Add, r) => {
            flatten_str_add(l, out);
            flatten_str_add(r, out);
        }
        _ => out.push(expr.clone()),
    }
}

/// Infer the output `PortType` of an expression without compiling it.
///
/// Uses heuristics to determine whether an expression produces a u64 or f64
/// value. This drives type-aware operator dispatch: when both operands of
/// an arithmetic operator are u64, the compiler selects the u64 variant
/// (e.g. `u64_mul`) instead of the f64 variant (`f64_mul`).
///
/// For unknown cases, defaults to `PortType::U64`.
fn infer_expr_type(
    expr: &Expr,
    asm: &GkAssembler,
    input_names: &[String],
) -> PortType {
    match expr {
        Expr::IntLit(_, _) => PortType::U64,
        Expr::FloatLit(_, _) => PortType::F64,
        Expr::StringLit(_, _) => PortType::Str,
        Expr::Ident(name, _) => {
            // Coordinate inputs are always u64.
            if input_names.contains(name) {
                return PortType::U64;
            }
            // Check if it's a known binding — look up output type from assembler.
            asm.output_type(name).unwrap_or(PortType::U64)
        }
        Expr::Call(call) => {
            // Heuristic based on function name prefix/membership.
            let f = call.func.as_str();
            if f.starts_with("f64_") || f.starts_with("to_f64")
                || ["sin", "cos", "tan", "asin", "acos", "atan", "atan2",
                    "sqrt", "abs_f64", "ln", "exp", "pow", "lerp",
                    "scale_range", "unit_interval", "clamp_f64",
                    "quantize", "discretize", "f64_mod",
                    "icd_normal", "icd_uniform",
                ].contains(&f) {
                PortType::F64
            } else {
                PortType::U64
            }
        }
        Expr::BinOp(lhs, op, rhs) => {
            match op {
                BinOpKind::BitAnd | BinOpKind::BitOr | BinOpKind::BitXor |
                BinOpKind::Shl | BinOpKind::Shr => PortType::U64,
                BinOpKind::Pow => PortType::F64,
                // Comparison operators always produce a u64 truth
                // value (0 or 1) regardless of operand types — the
                // type-aware desugar in compile_binding picks the
                // right input variant.
                BinOpKind::Eq | BinOpKind::Ne |
                BinOpKind::Lt | BinOpKind::Gt |
                BinOpKind::Le | BinOpKind::Ge => PortType::U64,
                _ => {
                    let lt = infer_expr_type(lhs, asm, input_names);
                    let rt = infer_expr_type(rhs, asm, input_names);
                    if matches!(op, BinOpKind::Add)
                        && (lt == PortType::Str || rt == PortType::Str)
                    {
                        PortType::Str
                    } else if lt == PortType::F64 || rt == PortType::F64 {
                        PortType::F64
                    } else {
                        PortType::U64
                    }
                }
            }
        }
        Expr::UnaryNeg(_, _) => PortType::F64,
        Expr::UnaryBitNot(_, _) => PortType::U64,
        Expr::ArrayLit(_, _) => PortType::U64,
        Expr::FieldAccess { source, field, .. } => {
            // Treat as an identifier reference — check assembler for output type.
            let wire_name = format!("{source}__{field}");
            asm.output_type(&wire_name).unwrap_or(PortType::U64)
        }
    }
}

impl Compiler {
    /// Compile one binding statement into the assembler.
    ///
    /// `targets` are the LHS names, `value` is the RHS expression.
    /// Single-target bindings produce a single node.  Multi-target
    /// bindings (destructuring) produce an internal node plus one
    /// `Identity` node per target that fans out each output port.
    pub(super) fn compile_binding(
        &mut self,
        asm: &mut GkAssembler,
        targets: &[String],
        value: &Expr,
    ) -> Result<(), String> {
        // Track the LHS as the "current binding" so anon_name() prefixes
        // intermediate node names with it. Saved/restored so nested
        // recursive calls (e.g. the `if` desugar that re-enters
        // compile_binding) keep the outer binding visible.
        let prior_binding = self.current_binding.take();
        self.current_binding = targets.first().cloned().or(prior_binding.clone());
        let result = self.compile_binding_inner(asm, targets, value);
        self.current_binding = prior_binding;
        result
    }

    fn compile_binding_inner(
        &mut self,
        asm: &mut GkAssembler,
        targets: &[String],
        value: &Expr,
    ) -> Result<(), String> {
        match value {
            Expr::Call(call) => {
                // `if(cond, a, b)` is a compiler intrinsic — desugar
                // to `select_u64(cond, a, b)` or `select_f64(cond, a, b)`
                // based on the inferred types of the two branches.
                // Mismatched branch types are widened: any u64 branch
                // is wrapped in `to_f64(...)` when the other branch is
                // f64. Both branches always evaluate (no short-circuit);
                // see SRD 10 §"Conditional selection" for the rationale.
                if call.func == "if" {
                    if call.args.len() != 3 {
                        return Err(format!(
                            "if({}): expected 3 arguments (cond, a, b), got {}",
                            targets[0], call.args.len()
                        ));
                    }
                    let cond_arg = call.args[0].clone();
                    let a_expr = match &call.args[1] {
                        Arg::Positional(e) => e.clone(),
                        Arg::Named(_, e) => e.clone(),
                    };
                    let b_expr = match &call.args[2] {
                        Arg::Positional(e) => e.clone(),
                        Arg::Named(_, e) => e.clone(),
                    };
                    let a_type = infer_expr_type(&a_expr, asm, &self.input_names);
                    let b_type = infer_expr_type(&b_expr, asm, &self.input_names);
                    // Branch-type priority: Str > F64 > U64. When
                    // either branch is Str, route through select_str
                    // (the other branch auto-converts to Str at wire
                    // resolution per PortType's "any → Str" rule).
                    // Otherwise the existing F64/U64 widening path
                    // applies.
                    let str_path = a_type == PortType::Str || b_type == PortType::Str;
                    let f64_path = !str_path
                        && (a_type == PortType::F64 || b_type == PortType::F64);
                    let widened_a = if f64_path && a_type == PortType::U64 {
                        wrap_to_f64(a_expr.clone())
                    } else { a_expr };
                    let widened_b = if f64_path && b_type == PortType::U64 {
                        wrap_to_f64(b_expr.clone())
                    } else { b_expr };
                    let func_name = if str_path { "select_str" }
                                    else if f64_path { "select_f64" }
                                    else { "select_u64" };
                    let new_call = crate::dsl::ast::CallExpr {
                        func: func_name.into(),
                        args: vec![
                            cond_arg,
                            Arg::Positional(widened_a),
                            Arg::Positional(widened_b),
                        ],
                        span: call.span,
                    };
                    return self.compile_binding(asm, targets, &Expr::Call(new_call));
                }

                let node_name = if targets.len() == 1 {
                    targets[0].clone()
                } else {
                    // For destructuring, the node gets the first target's name
                    // as a base, and we wire the output ports separately.
                    targets[0].clone()
                };

                // Resolve arguments to wire refs
                let mut wire_refs = Vec::new();
                let mut const_args = Vec::new();

                // Look up the function signature so we can determine which
                // arg positions are wire slots vs const slots.  When a
                // literal appears in a wire slot we promote it to an
                // anonymous const node and wire from it instead of
                // treating it as a build-time constant.
                let sig = registry::lookup(&call.func);

                // Build an iterator over the param slot-types.  We step
                // through it once per argument, wire-position by wire-position
                // or const-position by const-position, depending on what each
                // arg is.  For functions without a registry entry (or variadic
                // ones) we fall back to the original literal-as-const behaviour.
                let param_slot_types: Vec<SlotType> = sig
                    .map(|s| s.params.iter().map(|p| p.slot_type).collect())
                    .unwrap_or_default();

                // For functions whose arity declares variadic wires
                // (e.g. `pick(b0, b1, …, bN-1, v0, v1, …, vN-1)`),
                // the params spec typically lists only one entry —
                // signature is "all positions are wires." Honour
                // that so trailing literal arguments are promoted
                // to anonymous const-wire nodes instead of being
                // collected as build-time const_args (which the
                // variadic ctor would silently drop, producing a
                // truncated node with the wrong shape).
                let variadic_wires = sig
                    .map(|s| matches!(s.arity, super::registry::Arity::VariadicWires { .. }))
                    .unwrap_or(false);

                // Cursor into the param list.  We advance it for each call arg.
                let mut param_cursor = 0usize;

                for arg in &call.args {
                    let (expr, _name) = match arg {
                        Arg::Positional(e) => (e, None),
                        Arg::Named(n, e) => (e, Some(n.as_str())),
                    };

                    // Determine the expected slot type for this argument
                    // position, if known from the signature. For
                    // variadic-wires functions, positions past the
                    // explicit params list are still wires.
                    let expected_slot = param_slot_types.get(param_cursor).copied();
                    param_cursor += 1;

                    // Helper: is this arg position expected to be a wire input?
                    let wants_wire = expected_slot
                        .map(|s| s.is_wire())
                        .unwrap_or(variadic_wires);

                    match expr {
                        Expr::Ident(id, _) => {
                            // Is it a coordinate?
                            if self.input_names.contains(id) {
                                wire_refs.push(WireRef::input(id));
                            } else {
                                wire_refs.push(WireRef::node(id));
                            }
                        }
                        Expr::IntLit(v, _) => {
                            if wants_wire {
                                // Promote to an anonymous ConstU64 wire node.
                                let anon = self.anon_name();
                                asm.add_node(&anon, Box::new(ConstU64::new(*v)), vec![]);
                                wire_refs.push(WireRef::node(anon));
                            } else {
                                const_args.push(ConstArg::Int(*v));
                            }
                        }
                        Expr::FloatLit(v, _) => {
                            if wants_wire {
                                // Promote to an anonymous ConstF64 wire node.
                                let anon = self.anon_name();
                                asm.add_node(&anon, Box::new(ConstF64::new(*v)), vec![]);
                                wire_refs.push(WireRef::node(anon));
                            } else {
                                const_args.push(ConstArg::Float(*v));
                            }
                        }
                        Expr::StringLit(s, _) => {
                            if wants_wire {
                                // Promote to an anonymous ConstStr wire node.
                                let anon = self.anon_name();
                                asm.add_node(&anon, Box::new(ConstStr::new(s.clone())), vec![]);
                                wire_refs.push(WireRef::node(anon));
                            } else {
                                const_args.push(ConstArg::Str(s.clone()));
                            }
                        }
                        Expr::Call(inner) => {
                            // Inline nesting: desugar to an anonymous node
                            let anon = self.anon_name();
                            self.compile_binding(asm, &[anon.clone()], &Expr::Call(inner.clone()))?;
                            wire_refs.push(WireRef::node(anon));
                        }
                        Expr::ArrayLit(elems, _) => {
                            let floats: Vec<f64> = elems.iter().map(|e| match e {
                                Expr::FloatLit(v, _) => *v,
                                Expr::IntLit(v, _) => *v as f64,
                                _ => 0.0,
                            }).collect();
                            const_args.push(ConstArg::FloatArray(floats));
                        }
                        Expr::UnaryNeg(inner, _) => {
                            // Special case: `-literal` as a constant or wire argument.
                            // e.g. lerp(u, -10.0, 10.0) treats -10.0 as const.
                            // e.g. pow(x, -2.0) promotes to a ConstF64 wire node.
                            match inner.as_ref() {
                                Expr::FloatLit(v, _) => {
                                    if wants_wire {
                                        let anon = self.anon_name();
                                        asm.add_node(&anon, Box::new(ConstF64::new(-v)), vec![]);
                                        wire_refs.push(WireRef::node(anon));
                                    } else {
                                        const_args.push(ConstArg::Float(-v));
                                    }
                                }
                                Expr::IntLit(v, _) => {
                                    if wants_wire {
                                        // Negative integer: promote as ConstF64
                                        let anon = self.anon_name();
                                        asm.add_node(&anon, Box::new(ConstF64::new(-(*v as f64))), vec![]);
                                        wire_refs.push(WireRef::node(anon));
                                    } else {
                                        // Wrapping negate for u64 (effectively i64 reinterpret)
                                        const_args.push(ConstArg::Float(-(*v as f64)));
                                    }
                                }
                                _ => {
                                    // General case: wire input via anonymous node
                                    let anon = self.anon_name();
                                    self.compile_binding(asm, &[anon.clone()], expr)?;
                                    wire_refs.push(WireRef::node(anon));
                                }
                            }
                        }
                        Expr::BinOp(..) | Expr::UnaryBitNot(..) => {
                            // Inline arithmetic: desugar to an anonymous node
                            let anon = self.anon_name();
                            self.compile_binding(asm, &[anon.clone()], expr)?;
                            wire_refs.push(WireRef::node(anon));
                        }
                        Expr::FieldAccess { source, field, .. } => {
                            let wire_name = format!("{source}__{field}");
                            wire_refs.push(WireRef::node(&wire_name));
                        }
                    }
                }

                // SRD 23 §"Mutation entry points → GK": install
                // the enclosing binding's name as attribution for
                // any node that records it (e.g. `control_set`).
                // The scope guard clears on Drop so nested
                // compilation never leaks an outer attribution.
                let _binding_scope = targets.first().map(|n|
                    crate::dsl::factory::compile_ctx::scoped_binding(n));
                let wire_types: Vec<PortType> = wire_refs.iter()
                    .map(|w| asm.wire_type(w).unwrap_or(PortType::U64))
                    .collect();
                let node = match build_node(&call.func, &wire_refs, &wire_types, &const_args) {
                    Ok(n) => n,
                    Err(e) if e.contains("unknown function") => {
                        // Try module resolution before giving up
                        if self.try_inline_module(asm, &call.func, &call.args, targets)? {
                            return Ok(());
                        }
                        return Err(e);
                    }
                    Err(e) => return Err(e),
                };

                // SRD 53 §"Source-string call-site sugar": for each
                // Handle-typed input port whose wire produces a Str
                // value, splice in the resolver named by the
                // function's `default_resolver` hint. Performs the
                // auto-promotion defined as "string-conversion node
                // insertion" — works the same as the assembler's
                // type-adapter pass, but is parameterized by the
                // consumer's resolver hint (which the type-adapter
                // pass can't see at the wire-type-only granularity).
                self.auto_promote_handle_inputs(
                    asm, &call.func, &node, &mut wire_refs,
                )?;

                if targets.len() == 1 {
                    asm.add_node(&node_name, node, wire_refs);
                    self.all_names.push(node_name);
                } else {
                    // Multi-output: add the node under an internal name,
                    // then add identity nodes for each destructured target
                    // that reference specific output ports.
                    let internal_name = format!("__destruct_{}", self.anon_counter);
                    self.anon_counter += 1;
                    asm.add_node(&internal_name, node, wire_refs);

                    for (i, target) in targets.iter().enumerate() {
                        asm.add_node(
                            target,
                            Box::new(Identity::new()),
                            vec![WireRef::node_port(&internal_name, i)],
                        );
                        self.all_names.push(target.clone());
                    }
                }
            }
            Expr::StringLit(s, _) => {
                // String interpolation: "{code}-{seq}" desugars to a
                // string template node. Same disambiguation rule as
                // `nbrs_workload::bindpoints::is_literal_content` —
                // a `{...}` whose body starts with a quote (`'` or
                // `"`) is literal content (e.g. CQL map literal
                // `{'class': 'SimpleStrategy'}`, JSON object
                // `{"a": 1}`), not a bind point. When ALL `{...}`
                // placeholders in the string are literal-content,
                // emit the whole string as a `ConstStr` — no
                // interpolation, no wire wiring.
                let has_braces = s.contains('{') && s.contains('}');
                let any_real_placeholder = has_braces
                    && string_lit_has_real_placeholder(s);
                if any_real_placeholder {
                    // Parse bind points
                    let mut bind_names = Vec::new();
                    let mut i = 0;
                    let chars: Vec<char> = s.chars().collect();
                    while i < chars.len() {
                        if chars[i] == '{' {
                            i += 1;
                            let start = i;
                            while i < chars.len() && chars[i] != '}' { i += 1; }
                            let body: String = chars[start..i].iter().collect();
                            // Skip literal-content `{...}` (matches
                            // `is_literal_content`); they stay as
                            // text in the format string.
                            let trimmed = body.trim();
                            if !trimmed.starts_with('\'')
                                && !trimmed.starts_with('"')
                                && !bind_names.contains(&body)
                            {
                                bind_names.push(body);
                            }
                            i += 1;
                        } else {
                            i += 1;
                        }
                    }

                    // For now, use a Printf node with U64ToString adapters
                    // This is a simplified desugar — a full implementation
                    // would handle mixed types.
                    let wire_refs: Vec<WireRef> = bind_names.iter()
                        .map(|n| {
                            if self.input_names.contains(n) {
                                WireRef::input(n)
                            } else {
                                WireRef::node(n)
                            }
                        })
                        .collect();

                    // Build format string. Real placeholders
                    // collapse to `{}`; literal-content `{...}`
                    // (CQL map / JSON object) reproduces verbatim
                    // so the printf output preserves the braces.
                    let mut fmt_str = String::new();
                    let mut ci = 0;
                    while ci < chars.len() {
                        if chars[ci] == '{' {
                            let body_start = ci + 1;
                            let mut body_end = body_start;
                            while body_end < chars.len() && chars[body_end] != '}' {
                                body_end += 1;
                            }
                            let body: String = chars[body_start..body_end].iter().collect();
                            let trimmed = body.trim();
                            if trimmed.starts_with('\'') || trimmed.starts_with('"') {
                                // Literal content — keep as-is.
                                fmt_str.push('{');
                                fmt_str.push_str(&body);
                                if body_end < chars.len() {
                                    fmt_str.push('}');
                                }
                            } else {
                                fmt_str.push_str("{}");
                            }
                            ci = body_end + 1;
                        } else {
                            fmt_str.push(chars[ci]);
                            ci += 1;
                        }
                    }

                    // All inputs treated as Str via auto-adapters
                    let input_types = vec![crate::node::PortType::Str; bind_names.len()];
                    let node = Box::new(Printf::new(&fmt_str, &input_types));
                    let name = &targets[0];
                    asm.add_node(name, node, wire_refs);
                    self.all_names.push(name.clone());
                } else {
                    // Plain string constant
                    let name = &targets[0];
                    asm.add_node(name, Box::new(ConstStr::new(s.clone())), vec![]);
                    self.all_names.push(name.clone());
                }
            }
            Expr::Ident(id, _) => {
                // Simple alias: target := source. The passthrough's
                // port type is inferred from the source wire so an
                // f64 / bool / json alias doesn't clash with
                // Identity's hardcoded u64 ports. Falls back to u64
                // when the type can't be resolved at this point —
                // preserves the legacy Identity behaviour for the
                // unknown-source case.
                let name = &targets[0];
                let wire = if self.input_names.contains(id) {
                    WireRef::input(id)
                } else {
                    WireRef::node(id)
                };
                let src_type = asm.wire_type(&wire).unwrap_or(PortType::U64);
                if src_type == PortType::U64 {
                    asm.add_node(name, Box::new(Identity::new()), vec![wire]);
                } else {
                    asm.add_node(
                        name,
                        Box::new(PortPassthrough::new(name, src_type)),
                        vec![wire],
                    );
                }
                self.all_names.push(name.clone());
            }
            Expr::IntLit(v, _) => {
                let name = &targets[0];
                asm.add_node(name, Box::new(ConstU64::new(*v)), vec![]);
                self.all_names.push(name.clone());
            }
            Expr::FloatLit(v, _) => {
                let name = &targets[0];
                asm.add_node(name, Box::new(ConstF64::new(*v)), vec![]);
                self.all_names.push(name.clone());
            }
            Expr::BinOp(lhs, op, rhs) => {
                // Desugar infix arithmetic to the equivalent function call node.
                // Type-aware dispatch: infer operand types and select the
                // appropriate u64 or f64 variant. When one operand is u64 and
                // the other is f64, the u64 operand is auto-widened via to_f64.
                let lhs_type = infer_expr_type(lhs, asm, &self.input_names);
                let rhs_type = infer_expr_type(rhs, asm, &self.input_names);

                // Str + anything → str_concat. Either side being Str
                // routes the `+` operator to the variadic concat node.
                // Adjacent Str+ operations are flattened so
                // `"a" + b + "c"` lowers to a single
                // `str_concat("a", b, "c")` call.
                if matches!(op, BinOpKind::Add)
                    && (lhs_type == PortType::Str || rhs_type == PortType::Str)
                {
                    let mut operands: Vec<Expr> = Vec::new();
                    flatten_str_add(lhs, &mut operands);
                    flatten_str_add(rhs, &mut operands);
                    let mut wire_refs = Vec::with_capacity(operands.len());
                    for operand in &operands {
                        wire_refs.push(self.compile_binop_operand(asm, operand)?);
                    }
                    let wire_types: Vec<PortType> = wire_refs.iter()
                        .map(|w| asm.wire_type(w).unwrap_or(PortType::U64))
                        .collect();
                    let node = build_node("str_concat", &wire_refs, &wire_types, &[])?;
                    let name = &targets[0];
                    asm.add_node(name, node, wire_refs);
                    self.all_names.push(name.clone());
                    return Ok(());
                }

                let (func_name, need_widen_lhs, need_widen_rhs) = match op {
                    BinOpKind::Add | BinOpKind::Sub | BinOpKind::Mul |
                    BinOpKind::Div | BinOpKind::Mod => {
                        if lhs_type == PortType::U64 && rhs_type == PortType::U64 {
                            let name = match op {
                                BinOpKind::Add => "u64_add",
                                BinOpKind::Sub => "u64_sub",
                                BinOpKind::Mul => "u64_mul",
                                BinOpKind::Div => "u64_div",
                                BinOpKind::Mod => "u64_mod",
                                _ => unreachable!(),
                            };
                            (name, false, false)
                        } else {
                            let name = match op {
                                BinOpKind::Add => "f64_add",
                                BinOpKind::Sub => "f64_sub",
                                BinOpKind::Mul => "f64_mul",
                                BinOpKind::Div => "f64_div",
                                BinOpKind::Mod => "f64_mod",
                                _ => unreachable!(),
                            };
                            (name, lhs_type == PortType::U64, rhs_type == PortType::U64)
                        }
                    }
                    BinOpKind::Pow => ("pow", lhs_type == PortType::U64, rhs_type == PortType::U64),
                    BinOpKind::BitAnd => ("u64_and", false, false),
                    BinOpKind::BitOr  => ("u64_or", false, false),
                    BinOpKind::BitXor => ("u64_xor", false, false),
                    BinOpKind::Shl    => ("u64_shl", false, false),
                    BinOpKind::Shr    => ("u64_shr", false, false),
                    // Comparison: pick u64 or f64 input variant. If
                    // either operand is f64 we widen the u64 side via
                    // ToF64 so both inputs share a type and the
                    // f64-suffixed comparison node fires.
                    BinOpKind::Eq | BinOpKind::Ne |
                    BinOpKind::Lt | BinOpKind::Gt |
                    BinOpKind::Le | BinOpKind::Ge => {
                        // Three operand-type families: Str takes
                        // priority (str_eq / str_ne are the only
                        // ordered ops we support on Str so far —
                        // <, >, <=, >= on Str fall through to the
                        // u64 path which will surface a type
                        // mismatch). f64 wins over u64 when either
                        // side is f64 (with widening). u64 is the
                        // default.
                        let str_path = lhs_type == PortType::Str || rhs_type == PortType::Str;
                        let f64_path = !str_path
                            && (lhs_type == PortType::F64 || rhs_type == PortType::F64);
                        let prefix = if str_path { "str" }
                                     else if f64_path { "f64" }
                                     else { "u64" };
                        let suffix = match op {
                            BinOpKind::Eq => "eq",
                            BinOpKind::Ne => "ne",
                            BinOpKind::Lt => "lt",
                            BinOpKind::Gt => "gt",
                            BinOpKind::Le => "le",
                            BinOpKind::Ge => "ge",
                            _ => unreachable!(),
                        };
                        let name: &'static str = match (prefix, suffix) {
                            ("u64", "eq") => "u64_eq", ("u64", "ne") => "u64_ne",
                            ("u64", "lt") => "u64_lt", ("u64", "gt") => "u64_gt",
                            ("u64", "le") => "u64_le", ("u64", "ge") => "u64_ge",
                            ("f64", "eq") => "f64_eq", ("f64", "ne") => "f64_ne",
                            ("f64", "lt") => "f64_lt", ("f64", "gt") => "f64_gt",
                            ("f64", "le") => "f64_le", ("f64", "ge") => "f64_ge",
                            ("str", "eq") => "str_eq", ("str", "ne") => "str_ne",
                            ("str", _) => return Err(format!(
                                "comparison operator `{suffix}` is not supported for String operands; only `==` and `!=` work on strings",
                            )),
                            _ => unreachable!(),
                        };
                        // Widen u64→f64 only on the f64 path. The
                        // str path takes both sides as Str via
                        // automatic conversion at wire-resolution
                        // time (any type → Str is implicit per
                        // PortType doc).
                        let widen_lhs = f64_path && lhs_type == PortType::U64;
                        let widen_rhs = f64_path && rhs_type == PortType::U64;
                        (name, widen_lhs, widen_rhs)
                    }
                };

                // Compile each operand. Simple identifiers and literals
                // are resolved directly as wire references to avoid
                // inserting Identity nodes that lose type information.
                let lhs_ref = self.compile_binop_operand(asm, lhs)?;
                let rhs_ref = self.compile_binop_operand(asm, rhs)?;

                // Insert to_f64 widening adapters where needed.
                let lhs_final = if need_widen_lhs {
                    let adapted = self.anon_name();
                    asm.add_node(
                        &adapted,
                        Box::new(crate::nodes::convert::ToF64::new()),
                        vec![lhs_ref],
                    );
                    WireRef::node(&adapted)
                } else {
                    lhs_ref
                };
                let rhs_final = if need_widen_rhs {
                    let adapted = self.anon_name();
                    asm.add_node(
                        &adapted,
                        Box::new(crate::nodes::convert::ToF64::new()),
                        vec![rhs_ref],
                    );
                    WireRef::node(&adapted)
                } else {
                    rhs_ref
                };

                let wire_refs = vec![lhs_final, rhs_final];
                let wire_types: Vec<PortType> = wire_refs.iter()
                    .map(|w| asm.wire_type(w).unwrap_or(PortType::U64))
                    .collect();
                let node = build_node(func_name, &wire_refs, &wire_types, &[])?;
                let name = &targets[0];
                asm.add_node(name, node, wire_refs);
                self.all_names.push(name.clone());
            }
            Expr::UnaryNeg(inner, _) => {
                // Desugar `-x` to `f64_sub(0.0, x)`.
                let zero_name = self.anon_name();
                asm.add_node(&zero_name, Box::new(ConstF64::new(0.0)), vec![]);

                let inner_name = self.anon_name();
                self.compile_binding(asm, &[inner_name.clone()], inner)?;

                let wire_refs = vec![WireRef::node(&zero_name), WireRef::node(&inner_name)];
                let wire_types: Vec<PortType> = wire_refs.iter()
                    .map(|w| asm.wire_type(w).unwrap_or(PortType::U64))
                    .collect();
                let node = build_node("f64_sub", &wire_refs, &wire_types, &[])?;
                let name = &targets[0];
                asm.add_node(name, node, wire_refs);
                self.all_names.push(name.clone());
            }
            Expr::UnaryBitNot(inner, _) => {
                // Desugar `!x` to `u64_not(x)`.
                let inner_name = self.anon_name();
                self.compile_binding(asm, &[inner_name.clone()], inner)?;

                let wire_refs = vec![WireRef::node(&inner_name)];
                let wire_types: Vec<PortType> = wire_refs.iter()
                    .map(|w| asm.wire_type(w).unwrap_or(PortType::U64))
                    .collect();
                let node = build_node("u64_not", &wire_refs, &wire_types, &[])?;
                let name = &targets[0];
                asm.add_node(name, node, wire_refs);
                self.all_names.push(name.clone());
            }
            Expr::FieldAccess { source, field, .. } => {
                // Source projection: wire target to the source__field node.
                let wire_name = format!("{source}__{field}");
                let name = &targets[0];
                // Infer the passthrough's port type from the source
                // wire (e.g. `q.cursor` → Ext when q is partition-bound).
                // Without this inference, Ext-typed projections like
                // SRD 71's `q.cursor` would be forced to u64 and fail
                // downstream type-checking.
                let port_type = asm.output_type(&wire_name)
                    .unwrap_or(crate::node::PortType::U64);
                let identity = Box::new(
                    crate::nodes::identity::PortPassthrough::new(name, port_type)
                );
                asm.add_node(name, identity, vec![WireRef::node(&wire_name)]);
                self.all_names.push(name.clone());
            }
            _ => {
                return Err("unsupported expression in binding".to_string());
            }
        }
        Ok(())
    }

    /// Compile a BinOp operand, returning a `WireRef` without creating
    /// unnecessary Identity intermediates.
    ///
    /// Simple identifiers resolve directly to wire refs. Literals become
    /// anonymous const nodes. Complex expressions (calls, nested BinOps)
    /// are compiled into anonymous intermediate nodes.
    fn compile_binop_operand(
        &mut self,
        asm: &mut GkAssembler,
        expr: &Expr,
    ) -> Result<WireRef, String> {
        match expr {
            Expr::Ident(id, _) => {
                if self.input_names.contains(id) {
                    Ok(WireRef::input(id))
                } else {
                    Ok(WireRef::node(id))
                }
            }
            Expr::FieldAccess { source, field, .. } => {
                Ok(WireRef::node(&format!("{source}__{field}")))
            }
            Expr::IntLit(v, _) => {
                let anon = self.anon_name();
                asm.add_node(&anon, Box::new(ConstU64::new(*v)), vec![]);
                Ok(WireRef::node(anon))
            }
            Expr::FloatLit(v, _) => {
                let anon = self.anon_name();
                asm.add_node(&anon, Box::new(ConstF64::new(*v)), vec![]);
                Ok(WireRef::node(anon))
            }
            _ => {
                let anon = self.anon_name();
                self.compile_binding(asm, &[anon.clone()], expr)?;
                Ok(WireRef::node(anon))
            }
        }
    }
}