Skip to main content

polydat_core/library/
exactly_one.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! `exactly_one_value` — explicit unwrap of a unary structural body
5//! (library_catalog.md, "`exactly_one_value` — motivation and semantics").
6//!
7//! The motivating use case has a CQL `describe keyspace` op whose
8//! body is a single row × single text column. To regex-match the
9//! schema text, the workload asserts unary shape and unwraps. No
10//! implicit modal projection — identical workload source against a
11//! non-unary body must surface a clear shape diagnostic, not silently
12//! diverge from intent.
13//!
14//! Scalars pass through; typed vectors must have exactly one element;
15//! a `Json` body is walked as rows × columns × leaf and rejected with
16//! the diagnostic below when not unary:
17//!
18//! ```text
19//! exactly_one_value: expected unary structure (1 row × 1 column),
20//!                    found <r> rows × <c> columns
21//! ```
22
23use crate::ast::Value;
24
25/// Assert that the input value is a unary structure and return its
26/// single cell as a String. See module docs.
27///
28/// **Output is always `Str`** (the function returns `String`, so the
29/// macro emits a fixed `PortType::Str` output port). The function
30/// accepts any `Value` variant the upstream wire produces and
31/// renders the unwrapped leaf to its display form. This matches the
32/// load-bearing workload pattern `schema_text := exactly_one_value(body)`
33/// where downstream nodes (regex_match, format, …) take `&str`.
34///
35/// A polymorphic-output variant that preserves leaf types
36/// (Bool/U64/F64/…) would require a port-type declaration that
37/// reflects the runtime unwrap result rather than the input port,
38/// which the macro can't express without generic-over-Wire
39/// instantiation. When such a variant is needed it becomes its own
40/// node.
41#[crate::polydat_node(category = Diagnostic)]
42fn exactly_one_value(body: Value) -> String {
43    if crate::library::debug_nodes_enabled() {
44        // Per-cycle visibility into what the structural unwrap
45        // saw and produced. Body's display form is truncated for
46        // long Json arrays so the trace stays scannable.
47        let body_disp = body.to_display_string();
48        let snippet: String = body_disp.chars().take(400).collect();
49        let ellipsis = if body_disp.len() > snippet.len() {
50            "…"
51        } else {
52            ""
53        };
54        eprintln!(
55            "[DEBUG] exactly_one_value: body.variant={:?} body.len={} snippet={}{ellipsis}",
56            body.port_type(),
57            body_disp.len(),
58            snippet,
59        );
60    }
61    let leaf_value: Value = match &body {
62        // Already-scalar values pass through unchanged. They came
63        // from a body projection that already collapsed the row ×
64        // column structure.
65        Value::Str(_)
66        | Value::Bool(_)
67        | Value::U64(_)
68        | Value::I64(_)
69        | Value::U128(_)
70        | Value::I128(_)
71        | Value::F64(_) => body.clone(),
72
73        // Typed vector carriers: the structural shape is "1 row × 1
74        // column" iff the slice has exactly one element.
75        Value::VecF32(arc) => {
76            if arc.len() != 1 {
77                panic!(
78                    "exactly_one_value: expected unary structure \
79                     (1 row × 1 column), found vec_f32 of length {}",
80                    arc.len()
81                );
82            }
83            Value::F64(arc[0] as f64)
84        }
85        Value::VecI32(arc) => {
86            if arc.len() != 1 {
87                panic!(
88                    "exactly_one_value: expected unary structure \
89                     (1 row × 1 column), found vec_i32 of length {}",
90                    arc.len()
91                );
92            }
93            Value::I64(arc[0] as i64)
94        }
95        Value::VecF64(arc) => {
96            if arc.len() != 1 {
97                panic!(
98                    "exactly_one_value: expected unary structure \
99                     (1 row × 1 column), found vec_f64 of length {}",
100                    arc.len()
101                );
102            }
103            Value::F64(arc[0])
104        }
105        Value::VecI64(arc) => {
106            if arc.len() != 1 {
107                panic!(
108                    "exactly_one_value: expected unary structure \
109                     (1 row × 1 column), found vec_i64 of length {}",
110                    arc.len()
111                );
112            }
113            Value::I64(arc[0])
114        }
115        Value::VecF16(arc) => {
116            if arc.len() != 1 {
117                panic!(
118                    "exactly_one_value: expected unary structure \
119                     (1 row × 1 column), found vec_f16 of length {}",
120                    arc.len()
121                );
122            }
123            Value::F64(arc[0].to_f32() as f64)
124        }
125        Value::VecI16(arc) => {
126            if arc.len() != 1 {
127                panic!(
128                    "exactly_one_value: expected unary structure \
129                     (1 row × 1 column), found vec_i16 of length {}",
130                    arc.len()
131                );
132            }
133            Value::I64(arc[0] as i64)
134        }
135        Value::VecI8(arc) => {
136            if arc.len() != 1 {
137                panic!(
138                    "exactly_one_value: expected unary structure \
139                     (1 row × 1 column), found vec_i8 of length {}",
140                    arc.len()
141                );
142            }
143            Value::I64(arc[0] as i64)
144        }
145
146        Value::None => panic!(
147            "exactly_one_value: empty body (Value::None); the upstream \
148             op produced no result to unwrap"
149        ),
150
151        // Structural body walk: array = row dim, object = column
152        // dim, leaf = result. Unary shape = 1 × 1 × 1.
153        Value::Json(j) => unwrap_unary_json(j),
154
155        // Other carriers pass through (already collapsed).
156        // Register words render via their view's display form.
157        Value::Bytes(_)
158        | Value::Ext(_)
159        | Value::Handle(_)
160        | Value::Dataset(_)
161        | Value::Reg128(_, _) => body.clone(),
162    };
163    // Render to String for the declared Str output port. Non-Str
164    // leaves render via the Value display form (Bool → "true"/"false",
165    // U64 → "42", F64 → "3.14", etc.).
166    match leaf_value {
167        Value::Str(s) => s.to_string(),
168        other => other.to_display_string(),
169    }
170}
171
172/// Walk a JSON value asserting unary row × column × leaf shape.
173/// Returns the matching `Value` variant for the leaf cell.
174///
175/// The shape diagnostic names actual dimensions when the input
176/// doesn't match the unary contract.
177fn unwrap_unary_json(j: &serde_json::Value) -> Value {
178    use serde_json::Value as J;
179    // Row dimension: an array. Length 0 / >1 → shape error.
180    let row = match j {
181        J::Array(arr) => match arr.len() {
182            0 => panic!(
183                "exactly_one_value: expected unary structure (1 row × 1 column), \
184                 found 0 rows"
185            ),
186            1 => &arr[0],
187            n => panic!(
188                "exactly_one_value: expected unary structure (1 row × 1 column), \
189                 found {n} rows"
190            ),
191        },
192        // No row wrapper — treat the whole value as the single
193        // row and continue to column inspection. Adapters that
194        // produce a single-row unwrapped projection (rare; CQL
195        // doesn't) take this path naturally.
196        other => other,
197    };
198    // Column dimension: an object. Length 0 / >1 → shape error.
199    let leaf = match row {
200        J::Object(obj) => match obj.len() {
201            0 => panic!(
202                "exactly_one_value: expected unary structure (1 row × 1 column), \
203                 found 1 row × 0 columns"
204            ),
205            1 => obj.values().next().expect("len==1"),
206            n => panic!(
207                "exactly_one_value: expected unary structure (1 row × 1 column), \
208                 found 1 row × {n} columns"
209            ),
210        },
211        // No column wrapper — the row IS the leaf. Common for
212        // non-tabular bodies (e.g. a HTTP body that's a bare
213        // string).
214        other => other,
215    };
216    match leaf {
217        J::String(s) => Value::Str(s.as_str().into()),
218        J::Bool(b) => Value::Bool(*b),
219        // Total, lossless number extraction mirroring
220        // serde_json::Number's three leaves (PosInt / NegInt /
221        // Float) — a negative integer lands in the honest signed
222        // carrier instead of degrading to F64.
223        J::Number(n) => {
224            if let Some(u) = n.as_u64() {
225                Value::U64(u)
226            } else if let Some(i) = n.as_i64() {
227                Value::I64(i)
228            } else if let Some(f) = n.as_f64() {
229                Value::F64(f)
230            } else {
231                panic!(
232                    "exactly_one_value: numeric leaf is not representable as u64, i64, or f64: {n}"
233                )
234            }
235        }
236        J::Null => panic!("exactly_one_value: leaf cell is null; expected a non-null value"),
237        // Nested structural leaf — the body has more than two
238        // levels of nesting. That is not a unary shape
239        // (library_catalog.md `exactly_one_value`); the
240        // diagnostic names what was found.
241        J::Array(_) | J::Object(_) => panic!(
242            "exactly_one_value: leaf cell is itself structural ({}); \
243             expected a scalar (string, number, or boolean)",
244            describe_json_kind(leaf)
245        ),
246    }
247}
248
249fn describe_json_kind(j: &serde_json::Value) -> &'static str {
250    use serde_json::Value as J;
251    match j {
252        J::Null => "null",
253        J::Bool(_) => "bool",
254        J::Number(_) => "number",
255        J::String(_) => "string",
256        J::Array(_) => "array",
257        J::Object(_) => "object",
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::ast::PolydatNode;
265
266    fn run(input: Value) -> Value {
267        // Macro emits `ExactlyOneValue::new(input_type)` for a
268        // PolyWire-in node; pass the input's port type so the
269        // input slot's port-type metadata matches the upstream
270        // wire. (Output port is fixed `Str` regardless of input.)
271        let node = ExactlyOneValue::new(input.port_type());
272        let mut out = [Value::None];
273        node.eval(&[input], &mut out);
274        out.into_iter().next().unwrap()
275    }
276
277    #[test]
278    fn passes_through_str() {
279        let v = run(Value::Str("hello".into()));
280        assert_eq!(v.as_str(), "hello");
281    }
282
283    #[test]
284    fn passes_through_bool() {
285        // Bool leaves render to "true"/"false" (Str output).
286        let v = run(Value::Bool(true));
287        assert_eq!(v.as_str(), "true");
288    }
289
290    #[test]
291    fn passes_through_u64() {
292        // Numeric leaves render to their display form.
293        let v = run(Value::U64(42));
294        assert_eq!(v.as_str(), "42");
295    }
296
297    #[test]
298    fn passes_through_f64() {
299        let v = run(Value::F64(2.5));
300        assert_eq!(v.as_str(), "2.5");
301    }
302
303    #[test]
304    fn unwraps_singleton_vec_f32() {
305        let v = Value::VecF32(crate::ast::SliceArc::from_vec(vec![1.5_f32]));
306        let out = run(v);
307        assert_eq!(out.as_str(), "1.5");
308    }
309
310    #[test]
311    #[should_panic(expected = "expected unary structure")]
312    fn rejects_multi_element_vec_f32() {
313        let v = Value::VecF32(crate::ast::SliceArc::from_vec(vec![1.0_f32, 2.0]));
314        run(v);
315    }
316
317    #[test]
318    #[should_panic(expected = "exactly_one_value: empty body")]
319    fn rejects_none() {
320        run(Value::None);
321    }
322
323    // ---------------------------------------------------------------
324    // Structural Json walk
325    // ---------------------------------------------------------------
326
327    #[test]
328    fn unwraps_unary_json_describe_keyspace_shape() {
329        let j = serde_json::json!([
330            {"create_statement": "VIRTUAL TABLE system_views.sai_column_indexes (\n  ...\n)"}
331        ]);
332        let out = run(Value::Json(std::sync::Arc::new(j)));
333        let s = out.as_str();
334        assert!(s.starts_with("VIRTUAL TABLE"), "got: {s:?}");
335    }
336
337    #[test]
338    fn unwraps_unary_json_string_leaf() {
339        let j = serde_json::json!([{"value": "hello"}]);
340        let out = run(Value::Json(std::sync::Arc::new(j)));
341        assert_eq!(out.as_str(), "hello");
342    }
343
344    #[test]
345    fn unwraps_unary_json_numeric_leaf() {
346        let j = serde_json::json!([{"n": 42}]);
347        let out = run(Value::Json(std::sync::Arc::new(j)));
348        assert_eq!(out.as_str(), "42");
349    }
350
351    #[test]
352    fn unwraps_unary_json_bool_leaf() {
353        let j = serde_json::json!([{"b": true}]);
354        let out = run(Value::Json(std::sync::Arc::new(j)));
355        assert_eq!(out.as_str(), "true");
356    }
357
358    #[test]
359    #[should_panic(expected = "found 0 rows")]
360    fn rejects_empty_json_array() {
361        run(Value::Json(std::sync::Arc::new(serde_json::json!([]))));
362    }
363
364    #[test]
365    #[should_panic(expected = "found 2 rows")]
366    fn rejects_multi_row_json() {
367        let j = serde_json::json!([{"a": 1}, {"a": 2}]);
368        run(Value::Json(std::sync::Arc::new(j)));
369    }
370
371    #[test]
372    #[should_panic(expected = "found 1 row × 2 columns")]
373    fn rejects_multi_column_json() {
374        let j = serde_json::json!([{"a": 1, "b": 2}]);
375        run(Value::Json(std::sync::Arc::new(j)));
376    }
377
378    #[test]
379    #[should_panic(expected = "leaf cell is null")]
380    fn rejects_json_null_leaf() {
381        let j = serde_json::json!([{"a": null}]);
382        run(Value::Json(std::sync::Arc::new(j)));
383    }
384
385    #[test]
386    #[should_panic(expected = "leaf cell is itself structural")]
387    fn rejects_json_nested_structural_leaf() {
388        let j = serde_json::json!([{"a": {"nested": 1}}]);
389        run(Value::Json(std::sync::Arc::new(j)));
390    }
391}