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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Printf-style formatting node.
//!
//! Takes a format string and N inputs, produces a formatted String.
//! Uses `{}` placeholders (Rust-style, not C printf-style), with
//! optional format specifiers.
//!
//! Supported specifiers:
//! - `{}` — default display
//! - `{:05}` — zero-padded to width 5 (u64)
//! - `{:.2}` — 2 decimal places (f64)
//! - `{:x}` — lowercase hex (u64)
//! - `{:X}` — uppercase hex (u64)
//! - `{:b}` — binary (u64)
//! - `{:o}` — octal (u64)

use crate::node::{GkNode, NodeMeta, Port, PortType, Slot, Value};

/// A parsed format segment: either literal text or a placeholder.
#[derive(Debug, Clone)]
enum Segment {
    Literal(String),
    Placeholder(FormatSpec),
}

#[derive(Debug, Clone)]
struct FormatSpec {
    /// Input index (sequential, 0-based)
    index: usize,
    /// Optional width
    width: Option<usize>,
    /// Optional precision (decimal places)
    precision: Option<usize>,
    /// Fill character for width (default space, '0' for zero-pad)
    fill: char,
    /// Conversion: 'd' (decimal, default), 'x' (hex), 'X' (HEX), 'b' (binary), 'o' (octal)
    conversion: char,
}

/// Printf-style N→1 formatting node. Variadic: accepts 0..N wire inputs.
///
/// Signature: `printf(format: String, in_0, in_1, ...) -> (String)`
///
/// Format string uses Rust-style `{}` placeholders with optional specifiers:
/// `{:05}` (zero-pad), `{:.2}` (precision), `{:x}` (hex), `{:X}` (HEX),
/// `{:b}` (binary), `{:o}` (octal). Inputs are matched positionally.
///
/// Use for constructing complex formatted strings from multiple GK wires:
/// `printf("user-{:05}-score-{:.1}", id, score)` → "user-00042-score-98.6"
///
/// All Value types are accepted at eval time regardless of declared port
/// types. The format specifier determines how each value renders.
///
/// JIT level: P1 (String output).
pub struct Printf {
    meta: NodeMeta,
    segments: Vec<Segment>,
}

impl Printf {
    /// Create from a format string with explicit input port types.
    pub fn new(fmt: &str, input_types: &[PortType]) -> Self {
        let segments = parse_format(fmt);
        let placeholder_count = segments.iter().filter(|s| matches!(s, Segment::Placeholder(_))).count();
        assert_eq!(
            placeholder_count, input_types.len(),
            "format string has {placeholder_count} placeholders but {n} input types provided",
            n = input_types.len()
        );

        let inputs: Vec<Port> = input_types
            .iter()
            .enumerate()
            .map(|(i, &typ)| Port::new(format!("in_{i}"), typ))
            .collect();
        let slots: Vec<Slot> = inputs.iter().map(|p| Slot::Wire(p.clone())).collect();

        Self {
            meta: NodeMeta {
                name: "printf".into(),
                outs: vec![Port::new("output", PortType::Str)],
                ins: slots,
            },
            segments,
        }
    }

    /// Create from a format string with N wire inputs, all typed as u64.
    ///
    /// For variadic DSL use. Port types are declared as u64 but the eval
    /// method accepts any Value type — the assembler skips type checking
    /// for printf inputs.
    pub fn variadic(fmt: &str, wire_count: usize) -> Self {
        let segments = parse_format(fmt);
        let inputs: Vec<Port> = (0..wire_count)
            .map(|i| Port::new(format!("in_{i}"), PortType::U64))
            .collect();
        let slots: Vec<Slot> = inputs.iter().map(|p| Slot::Wire(p.clone())).collect();
        Self {
            meta: NodeMeta {
                name: "printf".into(),
                outs: vec![Port::new("output", PortType::Str)],
                ins: slots,
            },
            segments,
        }
    }
}

impl GkNode for Printf {
    fn meta(&self) -> &NodeMeta {
        &self.meta
    }

    fn eval(&self, inputs: &[Value], outputs: &mut [Value]) {
        // SRD-73 follow-up: None propagation through string
        // interpolation. If any REFERENCED input is Value::None,
        // the whole result is Value::None — not the literal text
        // "None" (which was the pre-fix Debug-formatting path),
        // not Value::Str("").
        //
        // Rationale: Value::None is the canonical "absent"
        // sentinel. The GK kernel's `lookup` / `get_constant`
        // already treat None-valued outputs as "not present in
        // this scope" and fall through to the parent scope.
        // String interpolation is the surface where that
        // discipline was being silently broken — an unresolved
        // `{X}` in a source-level string literal compiles to a
        // `printf` call with the unresolved name's slot, and
        // when that slot evaluates to None the printf result
        // should likewise be None so the binding doesn't
        // shadow upstream defaults.
        //
        // SQL-style propagation: any None input → None output.
        // Only inputs actually referenced by a `{}` placeholder
        // are checked (not unused trailing args).
        for seg in &self.segments {
            if let Segment::Placeholder(spec) = seg
                && matches!(&inputs[spec.index], Value::None)
            {
                outputs[0] = Value::None;
                return;
            }
        }

        let mut result = String::new();
        for seg in &self.segments {
            match seg {
                Segment::Literal(s) => result.push_str(s),
                Segment::Placeholder(spec) => {
                    let val = &inputs[spec.index];
                    let formatted = format_value(val, spec);
                    result.push_str(&formatted);
                }
            }
        }
        outputs[0] = Value::Str(result.into());
    }
}

fn format_value(val: &Value, spec: &FormatSpec) -> String {
    match val {
        Value::U64(v) => format_u64(*v, spec),
        Value::F64(v) => format_f64(*v, spec),
        Value::Bool(v) => v.to_string(),
        Value::Str(v) => {
            if let Some(w) = spec.width {
                format!("{:>width$}", v, width = w)
            } else {
                v.to_string()
            }
        }
        _ => format!("{val:?}"),
    }
}

fn format_u64(v: u64, spec: &FormatSpec) -> String {
    let raw = match spec.conversion {
        'x' => format!("{v:x}"),
        'X' => format!("{v:X}"),
        'b' => format!("{v:b}"),
        'o' => format!("{v:o}"),
        _ => v.to_string(),
    };
    apply_width(&raw, spec)
}

fn format_f64(v: f64, spec: &FormatSpec) -> String {
    let raw = if let Some(prec) = spec.precision {
        format!("{v:.prec$}")
    } else {
        // Bare `{}` for f64 uses Debug formatting so whole-number
        // floats render as `1.0` instead of `1`, matching
        // `Value::F64::to_display_string`. Authors who want
        // integer-style output for whole floats specify a
        // precision (`{:.0}`) or convert via `format_u64`.
        format!("{v:?}")
    };
    apply_width(&raw, spec)
}

fn apply_width(s: &str, spec: &FormatSpec) -> String {
    if let Some(w) = spec.width {
        if s.len() < w {
            let pad = w - s.len();
            let fill = spec.fill;
            format!("{}{s}", std::iter::repeat_n(fill, pad).collect::<String>())
        } else {
            s.to_string()
        }
    } else {
        s.to_string()
    }
}

fn parse_format(fmt: &str) -> Vec<Segment> {
    let mut segments = Vec::new();
    let mut literal = String::new();
    let chars: Vec<char> = fmt.chars().collect();
    let mut i = 0;
    let mut placeholder_idx = 0;

    while i < chars.len() {
        if chars[i] == '{' && i + 1 < chars.len() && chars[i + 1] == '{' {
            literal.push('{');
            i += 2;
        } else if chars[i] == '{' {
            if !literal.is_empty() {
                segments.push(Segment::Literal(std::mem::take(&mut literal)));
            }
            // Find closing }
            let start = i + 1;
            while i < chars.len() && chars[i] != '}' {
                i += 1;
            }
            let spec_str: String = chars[start..i].iter().collect();
            let spec = parse_spec(&spec_str, placeholder_idx);
            segments.push(Segment::Placeholder(spec));
            placeholder_idx += 1;
            i += 1; // skip }
        } else if chars[i] == '}' && i + 1 < chars.len() && chars[i + 1] == '}' {
            literal.push('}');
            i += 2;
        } else {
            literal.push(chars[i]);
            i += 1;
        }
    }

    if !literal.is_empty() {
        segments.push(Segment::Literal(literal));
    }

    segments
}

fn parse_spec(spec: &str, index: usize) -> FormatSpec {
    let mut result = FormatSpec {
        index,
        width: None,
        precision: None,
        fill: ' ',
        conversion: 'd',
    };

    if spec.is_empty() {
        return result;
    }

    // Strip leading ':'
    let spec = spec.strip_prefix(':').unwrap_or(spec);
    if spec.is_empty() {
        return result;
    }

    let chars: Vec<char> = spec.chars().collect();
    let mut pos = 0;

    // Check for zero-fill
    if pos < chars.len() && chars[pos] == '0' && pos + 1 < chars.len() && chars[pos + 1].is_ascii_digit() {
        result.fill = '0';
        pos += 1;
    }

    // Width
    let width_start = pos;
    while pos < chars.len() && chars[pos].is_ascii_digit() {
        pos += 1;
    }
    if pos > width_start {
        let w: String = chars[width_start..pos].iter().collect();
        result.width = Some(w.parse().unwrap());
    }

    // Precision
    if pos < chars.len() && chars[pos] == '.' {
        pos += 1;
        let prec_start = pos;
        while pos < chars.len() && chars[pos].is_ascii_digit() {
            pos += 1;
        }
        if pos > prec_start {
            let p: String = chars[prec_start..pos].iter().collect();
            result.precision = Some(p.parse().unwrap());
        }
    }

    // Conversion
    if pos < chars.len() {
        result.conversion = chars[pos];
    }

    result
}

// ---------------------------------------------------------------------------
// Signature declarations for the DSL registry
// ---------------------------------------------------------------------------

use crate::dsl::registry::{Arity, FuncCategory, FuncSig, ParamSpec};
use crate::node::SlotType;

/// Signatures for string formatting nodes.
pub fn signatures() -> &'static [FuncSig] {
    use FuncCategory as C;
    &[
        FuncSig {
            name: "printf", category: C::Formatting,
            outputs: 1, description: "printf-style formatting: printf(fmt, a, b, ...) -> String",
            identity: None, variadic_ctor: None,
            params: &[
                ParamSpec { name: "format", slot_type: SlotType::ConstStr, required: true, example: "\"%d\"", constraint: None },
            ],
            arity: Arity::VariadicWires { min_wires: 0 },
            commutativity: crate::node::Commutativity::Positional,
            help: "Printf-style string formatting with positional wire inputs.\nFormat string uses Rust-style {} placeholders with optional specifiers:\n  {:05} zero-pad, {:.2} precision, {:x} hex, {:X} HEX, {:b} binary, {:o} octal.\nParameters:\n  format   — format string constant (e.g. \"user-{:05}-score-{:.1}\")\n  input... — wire inputs matched positionally to placeholders\nExample: printf(\"id={:08x} val={:.2}\", hash(cycle), score)",
            default_resolver: None,
            output_type: crate::dsl::registry::OutputType::Fixed,
        },
    ]
}

/// Try to build a format node from a function name, const args, and wire refs.
///
/// Returns `None` if the name is not handled by this module.
pub(crate) fn build_node(name: &str, wires: &[crate::assembly::WireRef], _wire_types: &[crate::node::PortType], consts: &[crate::dsl::factory::ConstArg]) -> Option<Result<Box<dyn crate::node::GkNode>, String>> {
    match name {
        "printf" => {
            let fmt = consts.first()
                .map(|c| c.as_str())
                .unwrap_or("{}");
            // Reject format/wire-count mismatches at assembly time
            // so `Printf::new`'s placeholder/types assertion can't
            // fire from a DSL call. The user-facing diagnostic is
            // clearer than the constructor panic and the node stays
            // infallible (SRD 15 §"Input Validity Model").
            let placeholder_count = parse_format(fmt)
                .iter()
                .filter(|s| matches!(s, Segment::Placeholder(_)))
                .count();
            if placeholder_count != wires.len() {
                return Some(Err(format!(
                    "printf: format has {placeholder_count} placeholders but {} wire inputs supplied",
                    wires.len(),
                )));
            }
            // Infer input types: all wire inputs default to u64.
            // The Printf node handles any Value type at eval time,
            // so u64 ports work as the default — the actual value
            // type is determined by what's wired upstream.
            let types: Vec<crate::node::PortType> = (0..wires.len()).map(|_| crate::node::PortType::U64).collect();
            Some(Ok(Box::new(Printf::new(fmt, &types))))
        }
        _ => None,
    }
}

crate::register_nodes!(signatures, build_node);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn printf_simple() {
        let node = Printf::new("hello {}", &[PortType::U64]);
        let mut out = [Value::None];
        node.eval(&[Value::U64(42)], &mut out);
        assert_eq!(out[0].as_str(), "hello 42");
    }

    #[test]
    fn printf_multiple() {
        let node = Printf::new("{} + {} = {}", &[PortType::U64, PortType::U64, PortType::U64]);
        let mut out = [Value::None];
        node.eval(&[Value::U64(1), Value::U64(2), Value::U64(3)], &mut out);
        assert_eq!(out[0].as_str(), "1 + 2 = 3");
    }

    #[test]
    fn printf_zero_pad() {
        let node = Printf::new("{:05}", &[PortType::U64]);
        let mut out = [Value::None];
        node.eval(&[Value::U64(42)], &mut out);
        assert_eq!(out[0].as_str(), "00042");
    }

    #[test]
    fn printf_hex() {
        let node = Printf::new("{:x}", &[PortType::U64]);
        let mut out = [Value::None];
        node.eval(&[Value::U64(255)], &mut out);
        assert_eq!(out[0].as_str(), "ff");
    }

    #[test]
    fn printf_hex_upper() {
        let node = Printf::new("{:X}", &[PortType::U64]);
        let mut out = [Value::None];
        node.eval(&[Value::U64(255)], &mut out);
        assert_eq!(out[0].as_str(), "FF");
    }

    #[test]
    fn printf_precision() {
        let node = Printf::new("{:.2}", &[PortType::F64]);
        let mut out = [Value::None];
        node.eval(&[Value::F64(3.14159)], &mut out);
        assert_eq!(out[0].as_str(), "3.14");
    }

    #[test]
    fn printf_mixed() {
        let node = Printf::new("id={:05} val={:.1}", &[PortType::U64, PortType::F64]);
        let mut out = [Value::None];
        node.eval(&[Value::U64(7), Value::F64(98.6)], &mut out);
        assert_eq!(out[0].as_str(), "id=00007 val=98.6");
    }

    #[test]
    fn printf_literal_braces() {
        let node = Printf::new("{{escaped}} {}", &[PortType::U64]);
        let mut out = [Value::None];
        node.eval(&[Value::U64(1)], &mut out);
        assert_eq!(out[0].as_str(), "{escaped} 1");
    }

    #[test]
    fn printf_no_placeholders() {
        let node = Printf::new("just text", &[]);
        let mut out = [Value::None];
        node.eval(&[], &mut out);
        assert_eq!(out[0].as_str(), "just text");
    }

    #[test]
    fn printf_string_input() {
        let node = Printf::new("hello {}", &[PortType::Str]);
        let mut out = [Value::None];
        node.eval(&[Value::Str("world".into())], &mut out);
        assert_eq!(out[0].as_str(), "hello world");
    }

    // ────────────────────────────────────────────────────────
    // None propagation (SRD-73 follow-up)
    //
    // String interpolation evaluates to Value::None when any
    // referenced input is Value::None. Distinguishing the
    // "absent" sentinel from an empty-string-that-is-present
    // is required for the GK scope chain's fall-through
    // semantics: lookup() filters Value::None out of a scope's
    // outputs, so a const whose RHS interpolation yields None
    // doesn't shadow the parent scope — workload-param defaults
    // win. Silently substituting the literal text "None" (the
    // pre-fix _ => format!("{val:?}") path) corrupted wire-
    // protocol bytes, e.g. sent `'source_model': 'None'` to a
    // CQL cluster when the intended iter-var shadow was unbound.
    // ────────────────────────────────────────────────────────

    #[test]
    fn printf_none_input_yields_none() {
        let node = Printf::new("hello {}", &[PortType::Str]);
        // Start `out` non-None so we prove the eval overwrote it.
        let mut out = [Value::Str("untouched".into())];
        node.eval(&[Value::None], &mut out);
        assert!(matches!(out[0], Value::None), "got: {:?}", out[0]);
    }

    #[test]
    fn printf_partial_none_taints_whole_result() {
        // Multi-placeholder: a single None argument taints the
        // entire result. Mirrors SQL NULL propagation and Rust's
        // `?`: any absent input yields an absent output.
        let node = Printf::new("a={} b={}", &[PortType::U64, PortType::U64]);
        let mut out = [Value::Str("untouched".into())];
        node.eval(&[Value::U64(1), Value::None], &mut out);
        assert!(matches!(out[0], Value::None), "got: {:?}", out[0]);
    }

    #[test]
    fn printf_all_present_unchanged() {
        // Sanity: with no None inputs the existing path is
        // unchanged. This is the regression guard for the
        // overwhelming common case.
        let node = Printf::new("a={} b={}", &[PortType::U64, PortType::U64]);
        let mut out = [Value::None];
        node.eval(&[Value::U64(1), Value::U64(2)], &mut out);
        assert_eq!(out[0].as_str(), "a=1 b=2");
    }

    #[test]
    fn printf_no_placeholders_still_renders() {
        // Edge: a format with no placeholders is unaffected by
        // None propagation (nothing to be None about). The
        // result is the literal string.
        let node = Printf::new("static text", &[]);
        let mut out = [Value::None];
        node.eval(&[], &mut out);
        assert_eq!(out[0].as_str(), "static text");
    }
}