Skip to main content

fireline_grammar/
shape_expr.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Fuel's independent typed shape-expression AST + §6.19 canonical wire codec +
3//! evaluator (KISS-Ops §6.20). Byte-matches the KISS reference
4//! (`conformance/src/shape_expr.rs`), verified against the vendored golden vectors —
5//! the shape-side companion to the value oracle. The closed EXPRESSION core is
6//! `SameAs` + `DimExpr`; `WithDim`/`Dims` are the experimental umbrella-§6.4
7//! extension constructors (§6.20-0009/-0010, issue #80) — a whole-shape decoder
8//! ([`decode_shape`]) reads them while the `DimExpr` decoder ([`decode_dim`]) keeps
9//! declining them (a `Dim` is never a whole shape). The role/index-woven kind
10//! (reduce/gather/matmul) is a separate variant (Convergence-C C-2). Every
11//! malformed input is a typed decline, never a panic.
12
13// §6.20-0005 tag space (one byte; 0x00 reserved per §6.19-0006).
14pub const TAG_SAME_AS: u8 = 0x01;
15pub const TAG_EXTENT: u8 = 0x02;
16pub const TAG_CONST: u8 = 0x03;
17pub const TAG_PARAM: u8 = 0x04;
18pub const TAG_ADD: u8 = 0x05;
19pub const TAG_SUB: u8 = 0x06;
20pub const TAG_MUL: u8 = 0x07;
21pub const TAG_DIV: u8 = 0x08;
22pub const TAG_REDUCE: u8 = 0x09; // reserved (extension-registry) — reader rejects
23pub const TAG_WITH_DIM: u8 = 0x0A; // reserved
24pub const TAG_DIMS: u8 = 0x0B; // reserved
25
26/// Sentinel extent for a symbolic / data-dependent axis length → surfaced Gap (§6.20-0004).
27pub const SYMBOLIC: i64 = i64::MIN;
28
29/// Reserved `axis` sentinel = the trailing axis, resolved to `rank-1` at eval
30/// (§6.20-0002/-0003). Concrete axes are `0..MAX_RANK-1` (MAX_RANK=8), so `0xFF` is
31/// unambiguously `last`. DISTINCT from §6.19-0020's `0xFFFE` (u16 axis-set mask) — a
32/// different field, different width.
33pub const LAST: u8 = 0xFF;
34
35/// A single-dimension expression (`DimExpr`).
36#[derive(Debug, Clone, PartialEq, Eq, Hash)]
37pub enum Dim {
38    /// The size of `operand`'s `axis` (non-negative index, or [`LAST`] = trailing).
39    Extent {
40        operand: u8,
41        axis: u8,
42    },
43    Const(i64),
44    /// The op's `field`-th declared param.
45    Param(u8),
46    Add(Box<Dim>, Box<Dim>),
47    Sub(Box<Dim>, Box<Dim>),
48    Mul(Box<Dim>, Box<Dim>),
49    /// Floor division (toward −∞).
50    Div(Box<Dim>, Box<Dim>),
51}
52
53/// A whole-shape expression (`ShapeExpr`). The closed core is `SameAs`; `WithDim`
54/// and `Dims` are the experimental-range extension constructors registered via the
55/// KISS umbrella §6.4 registry (Ops §6.20-0009/-0010, issue #80), activating the
56/// §6.20-0005 tags `0x0A`/`0x0B`. `Reduce` (`0x09`) stays reserved (no consumer).
57#[derive(Debug, Clone, PartialEq, Eq, Hash)]
58pub enum ShapeExpr {
59    /// The operand's whole shape.
60    SameAs { operand: u8 },
61    /// EXPERIMENTAL (umbrella §6.4; tag `0x0A`, §6.20-0009). The `operand`'s shape
62    /// with the resolved `axis` (non-negative, or [`LAST`] = trailing) replaced by
63    /// `dim`. Functional spelling `with_dim(operand, axis, dim)`.
64    WithDim {
65        operand: u8,
66        axis: u8,
67        dim: Box<Dim>,
68    },
69    /// EXPERIMENTAL (umbrella §6.4; tag `0x0B`, §6.20-0010). A whole shape built
70    /// from `N >= 0` ordered `DimExpr`s (`N = 0` = the rank-0 scalar shape).
71    /// Functional spelling `dims([dim, …])`.
72    Dims(Vec<Dim>),
73}
74
75impl ShapeExpr {
76    /// Canonical wire bytes (§6.20-0005; the experimental extension tags
77    /// `0x0A`/`0x0B` per §6.20-0009/-0010, u16-LE length-prefixed children).
78    pub fn encode(&self) -> Vec<u8> {
79        match self {
80            ShapeExpr::SameAs { operand } => vec![TAG_SAME_AS, *operand],
81            // 0x0A, u8 operand, u8 axis (0xFF = last), one u16-LE length-prefixed
82            // child DimExpr blob (§6.20-0009).
83            ShapeExpr::WithDim { operand, axis, dim } => {
84                let child = dim.encode();
85                let mut v = vec![TAG_WITH_DIM, *operand, *axis];
86                v.extend_from_slice(&(child.len() as u16).to_le_bytes());
87                v.extend_from_slice(&child);
88                v
89            }
90            // 0x0B, u8 count, then count × (u16-LE length-prefixed child DimExpr
91            // blob) (§6.20-0010).
92            ShapeExpr::Dims(dims) => {
93                let mut v = vec![TAG_DIMS, dims.len() as u8];
94                for d in dims {
95                    let child = d.encode();
96                    v.extend_from_slice(&(child.len() as u16).to_le_bytes());
97                    v.extend_from_slice(&child);
98                }
99                v
100            }
101        }
102    }
103}
104
105impl Dim {
106    /// Canonical wire bytes (§6.20-0005).
107    pub fn encode(&self) -> Vec<u8> {
108        match self {
109            Dim::Extent { operand, axis } => vec![TAG_EXTENT, *operand, *axis],
110            Dim::Const(c) => {
111                let mut v = vec![TAG_CONST];
112                v.extend_from_slice(&c.to_le_bytes());
113                v
114            }
115            Dim::Param(f) => vec![TAG_PARAM, *f],
116            Dim::Add(a, b) => encode_binary(TAG_ADD, a, b),
117            Dim::Sub(a, b) => encode_binary(TAG_SUB, a, b),
118            Dim::Mul(a, b) => encode_binary(TAG_MUL, a, b),
119            Dim::Div(a, b) => encode_binary(TAG_DIV, a, b),
120        }
121    }
122}
123
124fn encode_binary(tag: u8, a: &Dim, b: &Dim) -> Vec<u8> {
125    let (ca, cb) = (a.encode(), b.encode());
126    let mut v = vec![tag];
127    v.extend_from_slice(&(ca.len() as u16).to_le_bytes());
128    v.extend_from_slice(&ca);
129    v.extend_from_slice(&(cb.len() as u16).to_le_bytes());
130    v.extend_from_slice(&cb);
131    v
132}
133
134/// A typed decline. A reader MUST refuse malformed input with one of these, never a
135/// panic (§6.20-0003/0006).
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum ShapeExprError {
138    ZeroTag,
139    ReservedTag { tag: u8 },
140    TruncatedBlob { need: usize, got: usize },
141    TrailingBytes { extra: usize },
142    AxisOutOfRange { axis: u8, rank: usize },
143    OperandOutOfRange { operand: u8, operands: usize },
144    ParamOutOfRange { field: u8, params: usize },
145    DivideByZero,
146}
147
148/// Decode one `DimExpr` blob, rejecting a malformed one with a typed decline. Round-trips:
149/// `decode_dim(&d.encode()) == Ok(d)`.
150pub fn decode_dim(blob: &[u8]) -> Result<Dim, ShapeExprError> {
151    let (d, consumed) = decode_dim_at(blob, 0)?;
152    if consumed != blob.len() {
153        return Err(ShapeExprError::TrailingBytes {
154            extra: blob.len() - consumed,
155        });
156    }
157    Ok(d)
158}
159
160fn decode_dim_at(blob: &[u8], pos: usize) -> Result<(Dim, usize), ShapeExprError> {
161    let tag = *blob.get(pos).ok_or(ShapeExprError::TruncatedBlob {
162        need: pos + 1,
163        got: blob.len(),
164    })?;
165    match tag {
166        0x00 => Err(ShapeExprError::ZeroTag),
167        TAG_EXTENT => {
168            need(blob, pos, 3)?;
169            Ok((
170                Dim::Extent {
171                    operand: blob[pos + 1],
172                    axis: blob[pos + 2],
173                },
174                pos + 3,
175            ))
176        }
177        TAG_CONST => {
178            need(blob, pos, 9)?;
179            let mut a = [0u8; 8];
180            a.copy_from_slice(&blob[pos + 1..pos + 9]);
181            Ok((Dim::Const(i64::from_le_bytes(a)), pos + 9))
182        }
183        TAG_PARAM => {
184            need(blob, pos, 2)?;
185            Ok((Dim::Param(blob[pos + 1]), pos + 2))
186        }
187        TAG_ADD | TAG_SUB | TAG_MUL | TAG_DIV => {
188            let (c1, p1) = read_child(blob, pos + 1)?;
189            let (c2, p2) = read_child(blob, p1)?;
190            let (a, b) = (Box::new(c1), Box::new(c2));
191            let d = match tag {
192                TAG_ADD => Dim::Add(a, b),
193                TAG_SUB => Dim::Sub(a, b),
194                TAG_MUL => Dim::Mul(a, b),
195                _ => Dim::Div(a, b),
196            };
197            Ok((d, p2))
198        }
199        // Whole-shape / reserved tags declined at the DimExpr grammar level: WithDim
200        // (0x0A) / Dims (0x0B) are WHOLE-SHAPE constructors — now active, but only via
201        // [`decode_shape`]; a `DimExpr` is never a whole shape, so they decline here
202        // (§6.20-0009/-0010). Reduce (0x09) stays reserved at both levels — no
203        // consumer (§6.20-0007 derives reduce-family shapes from op attrs).
204        TAG_REDUCE | TAG_WITH_DIM | TAG_DIMS => Err(ShapeExprError::ReservedTag { tag }),
205        other => Err(ShapeExprError::ReservedTag { tag: other }),
206    }
207}
208
209/// A `u16`-LE length-prefixed child expression at `pos`.
210fn read_child(blob: &[u8], pos: usize) -> Result<(Dim, usize), ShapeExprError> {
211    if blob.len() < pos + 2 {
212        return Err(ShapeExprError::TruncatedBlob {
213            need: 2,
214            got: blob.len().saturating_sub(pos),
215        });
216    }
217    let len = u16::from_le_bytes([blob[pos], blob[pos + 1]]) as usize;
218    let start = pos + 2;
219    if blob.len() < start + len {
220        return Err(ShapeExprError::TruncatedBlob {
221            need: len,
222            got: blob.len().saturating_sub(start),
223        });
224    }
225    let child = decode_dim(&blob[start..start + len])?; // child consumes its declared length exactly
226    Ok((child, start + len))
227}
228
229fn need(blob: &[u8], pos: usize, n: usize) -> Result<(), ShapeExprError> {
230    if blob.len() < pos + n {
231        Err(ShapeExprError::TruncatedBlob {
232            need: n,
233            got: blob.len().saturating_sub(pos),
234        })
235    } else {
236        Ok(())
237    }
238}
239
240/// Decode one whole-shape [`ShapeExpr`] blob, rejecting a malformed one with a typed
241/// decline (§6.20-0006). Reads `SameAs` (core) plus the registered experimental
242/// extension constructors `WithDim`/`Dims` (§6.20-0009/-0010); the still-reserved
243/// `Reduce` (`0x09`) and the `DimExpr`-only tags decline typed. A well-formed blob
244/// round-trips: `decode_shape(&s.encode()) == Ok(s)`. Distinct from [`decode_dim`],
245/// which reads the single-dimension grammar (a `Dim` is never a whole shape, so a
246/// whole-shape tag declines there, and vice-versa).
247pub fn decode_shape(blob: &[u8]) -> Result<ShapeExpr, ShapeExprError> {
248    let (s, consumed) = decode_shape_at(blob, 0)?;
249    if consumed != blob.len() {
250        return Err(ShapeExprError::TrailingBytes {
251            extra: blob.len() - consumed,
252        });
253    }
254    Ok(s)
255}
256
257fn decode_shape_at(blob: &[u8], pos: usize) -> Result<(ShapeExpr, usize), ShapeExprError> {
258    let tag = *blob.get(pos).ok_or(ShapeExprError::TruncatedBlob {
259        need: pos + 1,
260        got: blob.len(),
261    })?;
262    match tag {
263        0x00 => Err(ShapeExprError::ZeroTag),
264        TAG_SAME_AS => {
265            need(blob, pos, 2)?;
266            Ok((
267                ShapeExpr::SameAs {
268                    operand: blob[pos + 1],
269                },
270                pos + 2,
271            ))
272        }
273        // 0x0A, u8 operand, u8 axis, one u16-LE length-prefixed child (§6.20-0009).
274        TAG_WITH_DIM => {
275            need(blob, pos, 3)?;
276            let operand = blob[pos + 1];
277            let axis = blob[pos + 2];
278            let (child, next) = read_child(blob, pos + 3)?;
279            Ok((
280                ShapeExpr::WithDim {
281                    operand,
282                    axis,
283                    dim: Box::new(child),
284                },
285                next,
286            ))
287        }
288        // 0x0B, u8 count, then count × u16-LE length-prefixed children (§6.20-0010).
289        TAG_DIMS => {
290            need(blob, pos, 2)?;
291            let count = blob[pos + 1] as usize;
292            let mut dims = Vec::with_capacity(count);
293            let mut p = pos + 2;
294            for _ in 0..count {
295                let (child, next) = read_child(blob, p)?;
296                dims.push(child);
297                p = next;
298            }
299            Ok((ShapeExpr::Dims(dims), p))
300        }
301        // `Reduce` (0x09), the `DimExpr`-only tags, and any unallocated tag decline
302        // typed at the whole-shape grammar level (§6.20-0006).
303        other => Err(ShapeExprError::ReservedTag { tag: other }),
304    }
305}
306
307/// Evaluating a `DimExpr`: a concrete dim, or a surfaced gap (§6.20-0004).
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub enum DimValue {
310    Concrete(i64),
311    Gap,
312}
313
314/// Evaluating a `ShapeExpr`: a concrete shape, or a surfaced gap.
315#[derive(Debug, Clone, PartialEq, Eq)]
316pub enum ShapeValue {
317    Concrete(Vec<i64>),
318    Gap,
319}
320
321/// Resolve a non-negative `axis` (or [`LAST`]) against `rank` (§6.20-0003).
322/// `pub` since Increment C slice 1 (T2): the recipe-interior `axis_last`
323/// resolver (`fuel_graph::runtime_fused::resolve_rel_attrs`) reuses this as
324/// the single LAST→`rank−1` evaluator instead of growing a second one.
325pub fn resolve_axis(axis: u8, rank: usize) -> Result<usize, ShapeExprError> {
326    if axis == LAST {
327        return rank
328            .checked_sub(1)
329            .ok_or(ShapeExprError::AxisOutOfRange { axis, rank });
330    }
331    let a = axis as usize;
332    if a >= rank {
333        return Err(ShapeExprError::AxisOutOfRange { axis, rank });
334    }
335    Ok(a)
336}
337
338/// Floor division (toward −∞), unlike Rust's truncating `/`.
339fn floordiv(a: i64, b: i64) -> i64 {
340    let (q, r) = (a / b, a % b);
341    if r != 0 && ((r < 0) != (b < 0)) {
342        q - 1
343    } else {
344        q
345    }
346}
347
348fn eval_binary(
349    a: DimValue,
350    b: DimValue,
351    f: impl Fn(i64, i64) -> Result<i64, ShapeExprError>,
352) -> Result<DimValue, ShapeExprError> {
353    match (a, b) {
354        (DimValue::Concrete(x), DimValue::Concrete(y)) => Ok(DimValue::Concrete(f(x, y)?)),
355        _ => Ok(DimValue::Gap), // a gap in either operand propagates (§6.20-0004)
356    }
357}
358
359/// Evaluate a `DimExpr` against operand shapes + param values.
360pub fn eval_dim(
361    d: &Dim,
362    operands: &[Vec<i64>],
363    params: &[i64],
364) -> Result<DimValue, ShapeExprError> {
365    match d {
366        Dim::Extent { operand, axis } => {
367            let op = *operand as usize;
368            let shape = operands.get(op).ok_or(ShapeExprError::OperandOutOfRange {
369                operand: *operand,
370                operands: operands.len(),
371            })?;
372            let idx = resolve_axis(*axis, shape.len())?;
373            let ext = shape[idx];
374            Ok(if ext == SYMBOLIC {
375                DimValue::Gap
376            } else {
377                DimValue::Concrete(ext)
378            })
379        }
380        Dim::Const(c) => Ok(DimValue::Concrete(*c)),
381        Dim::Param(f) => {
382            let fi = *f as usize;
383            let v = params.get(fi).ok_or(ShapeExprError::ParamOutOfRange {
384                field: *f,
385                params: params.len(),
386            })?;
387            Ok(DimValue::Concrete(*v))
388        }
389        Dim::Add(a, b) => eval_binary(
390            eval_dim(a, operands, params)?,
391            eval_dim(b, operands, params)?,
392            |x, y| Ok(x + y),
393        ),
394        Dim::Sub(a, b) => eval_binary(
395            eval_dim(a, operands, params)?,
396            eval_dim(b, operands, params)?,
397            |x, y| Ok(x - y),
398        ),
399        Dim::Mul(a, b) => eval_binary(
400            eval_dim(a, operands, params)?,
401            eval_dim(b, operands, params)?,
402            |x, y| Ok(x * y),
403        ),
404        Dim::Div(a, b) => eval_binary(
405            eval_dim(a, operands, params)?,
406            eval_dim(b, operands, params)?,
407            |x, y| {
408                if y == 0 {
409                    Err(ShapeExprError::DivideByZero)
410                } else {
411                    Ok(floordiv(x, y))
412                }
413            },
414        ),
415    }
416}
417
418/// Evaluate a `ShapeExpr` to a concrete shape (or a surfaced gap).
419pub fn eval_shape(
420    s: &ShapeExpr,
421    operands: &[Vec<i64>],
422    params: &[i64],
423) -> Result<ShapeValue, ShapeExprError> {
424    match s {
425        ShapeExpr::SameAs { operand } => {
426            let op = *operand as usize;
427            let shape = operands.get(op).ok_or(ShapeExprError::OperandOutOfRange {
428                operand: *operand,
429                operands: operands.len(),
430            })?;
431            if shape.contains(&SYMBOLIC) {
432                Ok(ShapeValue::Gap)
433            } else {
434                Ok(ShapeValue::Concrete(shape.clone()))
435            }
436        }
437        // §6.20-0009 `with_dim`: the operand's shape with the resolved axis replaced
438        // by `dim`. A Gap replacement, or a symbolic extent in any KEPT axis,
439        // surfaces the whole shape as a Gap (§6.20-0004); an out-of-range axis is a
440        // typed decline (§6.20-0003), never a panic.
441        ShapeExpr::WithDim { operand, axis, dim } => {
442            let op = *operand as usize;
443            let shape = operands.get(op).ok_or(ShapeExprError::OperandOutOfRange {
444                operand: *operand,
445                operands: operands.len(),
446            })?;
447            let idx = resolve_axis(*axis, shape.len())?;
448            let replacement = eval_dim(dim, operands, params)?;
449            let mut out = shape.clone();
450            let mut gap = false;
451            for (i, e) in out.iter_mut().enumerate() {
452                if i == idx {
453                    match &replacement {
454                        DimValue::Concrete(v) => *e = *v,
455                        DimValue::Gap => gap = true,
456                    }
457                } else if *e == SYMBOLIC {
458                    gap = true;
459                }
460            }
461            if gap {
462                Ok(ShapeValue::Gap)
463            } else {
464                Ok(ShapeValue::Concrete(out))
465            }
466        }
467        // §6.20-0010 `dims`: build the whole shape from the ordered DimExprs. A Gap
468        // in ANY element surfaces the whole shape as a Gap (§6.20-0004); an empty
469        // list is the rank-0 scalar shape.
470        ShapeExpr::Dims(dims) => {
471            let mut out = Vec::with_capacity(dims.len());
472            let mut gap = false;
473            for d in dims {
474                match eval_dim(d, operands, params)? {
475                    DimValue::Concrete(v) => out.push(v),
476                    DimValue::Gap => gap = true,
477                }
478            }
479            if gap {
480                Ok(ShapeValue::Gap)
481            } else {
482                Ok(ShapeValue::Concrete(out))
483            }
484        }
485    }
486}
487
488// ---- §6.20-0007/0008 the ROLE/INDEX-WOVEN kind (Convergence-C C-2) ----------------
489// These ride the op's role/index structure, NOT the SameAs+DimExpr expression core —
490// a distinct shape-rule kind (§6.20-0008). Not expressible as a wire ShapeExpr.
491
492/// §6.20-0007 `reduce`-family shape rule: the input shape with `reduce_axes` removed
493/// (`keepdim=false`) or set to `1` (`keepdim=true`) — derived from op semantics.
494pub fn reduce_shape(input: &[i64], reduce_axes: &[usize], keepdim: bool) -> Vec<i64> {
495    let set: std::collections::BTreeSet<usize> = reduce_axes.iter().copied().collect();
496    let mut out = Vec::new();
497    for (i, &e) in input.iter().enumerate() {
498        if set.contains(&i) {
499            if keepdim {
500                out.push(1);
501            }
502        } else {
503            out.push(e);
504        }
505    }
506    out
507}
508
509/// §6.20-0008 `gather`/`index_select`/`embedding` shape rule: the data shape with the
510/// gathered `axis` replaced by the index shape (`data[..axis] ++ index ++ data[axis+1..]`).
511/// In general the output equals NO operand's shape — which is why advertising
512/// `same_as(data)` for a gather is a bug the shape oracle catches.
513pub fn gather_shape(data: &[i64], index: &[i64], axis: usize) -> Vec<i64> {
514    let mut out = Vec::with_capacity(data.len() - 1 + index.len());
515    out.extend_from_slice(&data[..axis]);
516    out.extend_from_slice(index);
517    out.extend_from_slice(&data[axis + 1..]);
518    out
519}
520
521/// §6.20-0008 `matmul` (contraction) shape rule: role-vector-derived (KISS-Classify
522/// §6.6-0016 M/N/K axis roles, carried as roles not a ShapeExpr). For the canonical
523/// same-rank ≥ 2 cell `lhs[..batch, M, K] · rhs[..batch, K, N] -> [..batch, M, N]`; the
524/// output equals neither operand (§6.20-0008).
525pub fn matmul_shape(lhs: &[i64], rhs: &[i64]) -> Vec<i64> {
526    let r = lhs.len();
527    let mut out = lhs[..r - 2].to_vec(); // aligned leading batch dims
528    out.push(lhs[r - 2]); // M (lhs second-last)
529    out.push(rhs[r - 1]); // N (rhs last)
530    out
531}
532
533/// KISS-CONTRACT-6.4-0011: the Interface `declared` output shape is consistent iff it
534/// equals the op's shape rule `computed` over the operand shapes. A surfaced `Gap`
535/// (symbolic/data-dependent output) is never a hard inconsistency — a consumer cannot
536/// assert a mismatch it cannot compute. The shape-side companion to the §6.4-0006 value
537/// oracle.
538pub fn shape_consistent(declared: &[i64], computed: &ShapeValue) -> bool {
539    match computed {
540        ShapeValue::Concrete(c) => declared == c.as_slice(),
541        ShapeValue::Gap => true,
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548
549    // §6.20-0005 canonical serialization — byte-identical to the KISS goldens.
550    #[test]
551    fn serialization_golden() {
552        assert_eq!(ShapeExpr::SameAs { operand: 0 }.encode(), vec![0x01, 0x00]);
553        assert_eq!(
554            Dim::Extent {
555                operand: 0,
556                axis: LAST
557            }
558            .encode(),
559            vec![0x02, 0x00, 0xFF]
560        );
561        assert_eq!(
562            Dim::Const(2).encode(),
563            vec![0x03, 0x02, 0, 0, 0, 0, 0, 0, 0]
564        );
565        assert_eq!(Dim::Param(0).encode(), vec![0x04, 0x00]);
566        // The rope-half anchor — the byte contract of record.
567        let half = Dim::Div(
568            Box::new(Dim::Extent {
569                operand: 0,
570                axis: LAST,
571            }),
572            Box::new(Dim::Const(2)),
573        );
574        assert_eq!(
575            half.encode(),
576            vec![
577                0x08, 0x03, 0x00, 0x02, 0x00, 0xFF, 0x09, 0x00, 0x03, 0x02, 0, 0, 0, 0, 0, 0, 0
578            ]
579        );
580    }
581
582    #[test]
583    fn decode_round_trip_and_declines() {
584        let half = Dim::Div(
585            Box::new(Dim::Extent {
586                operand: 0,
587                axis: LAST,
588            }),
589            Box::new(Dim::Const(2)),
590        );
591        assert_eq!(decode_dim(&half.encode()).unwrap(), half); // round-trip
592        // §6.20-0006 typed declines — never a panic.
593        assert_eq!(decode_dim(&[0x00]), Err(ShapeExprError::ZeroTag));
594        assert_eq!(
595            decode_dim(&[0x09, 0x00]),
596            Err(ShapeExprError::ReservedTag { tag: 0x09 })
597        );
598        assert_eq!(
599            decode_dim(&[0x03, 0x02, 0x00]),
600            Err(ShapeExprError::TruncatedBlob { need: 9, got: 3 })
601        );
602        assert_eq!(
603            decode_dim(&[0x04, 0x00, 0xAB]),
604            Err(ShapeExprError::TrailingBytes { extra: 1 })
605        );
606    }
607
608    // §6.20-0002/-0005 the DimExpr decoder declines the whole-shape / reserved tags
609    // BY NAME: WithDim (0x0A) / Dims (0x0B) are now active but only via
610    // `decode_shape` — a `DimExpr` is never a whole shape, so `decode_dim` still
611    // declines them; Reduce (0x09) stays reserved (no consumer, §6.20-0007 derives
612    // reduce shapes from attrs).
613    #[test]
614    fn reserved_extension_tags_decline_by_name() {
615        // Pin the allocated-reserved wire values (KISS §6.20-0005).
616        assert_eq!(TAG_REDUCE, 0x09);
617        assert_eq!(TAG_WITH_DIM, 0x0A);
618        assert_eq!(TAG_DIMS, 0x0B);
619        for tag in [TAG_REDUCE, TAG_WITH_DIM, TAG_DIMS] {
620            // Bare reserved tag: the typed decline names the tag, never a panic.
621            assert_eq!(decode_dim(&[tag]), Err(ShapeExprError::ReservedTag { tag }));
622            // A payload after a reserved tag does not rescue it.
623            assert_eq!(
624                decode_dim(&[tag, 0x00, 0x01]),
625                Err(ShapeExprError::ReservedTag { tag })
626            );
627        }
628        // A reserved tag in CHILD position (inside a binary node) declines identically.
629        assert_eq!(
630            decode_dim(&[TAG_ADD, 1, 0, TAG_WITH_DIM, 1, 0, TAG_DIMS]),
631            Err(ShapeExprError::ReservedTag { tag: TAG_WITH_DIM })
632        );
633        // The first UNALLOCATED tag past the reserved block also declines (the
634        // §6.20-0005 closed-vocabulary guard is open-ended, not just these three).
635        assert_eq!(
636            decode_dim(&[0x0C]),
637            Err(ShapeExprError::ReservedTag { tag: 0x0C })
638        );
639    }
640
641    // §6.20-0009 WithDim + §6.20-0010 Dims — the experimental umbrella-§6.4
642    // extension constructors, byte-matched against the KISS reference goldens
643    // (`conformance/tests/shape_expr.rs` @ 469abd5, PR #86). The exact golden hex
644    // from each KISS `assert_golden(...)` call is transcribed here as a LITERAL
645    // byte vector — Fuel is the second dissimilar implementation on the promotion
646    // path, so an equal byte sequence is the confirmation gate.
647    #[test]
648    fn with_dim_extension_golden_roundtrip_eval() {
649        // Golden — with_dim(operand=0, axis=1, Const(7)):
650        // KISS "0A 00 01 09 00 03 07 00 00 00 00 00 00 00".
651        let wd = ShapeExpr::WithDim {
652            operand: 0,
653            axis: 1,
654            dim: Box::new(Dim::Const(7)),
655        };
656        assert_eq!(
657            wd.encode(),
658            vec![
659                0x0A, 0x00, 0x01, 0x09, 0x00, 0x03, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
660            ]
661        );
662        // Golden — with_dim(operand=1, axis=last, Param(0)): KISS "0A 01 FF 02 00 04 00".
663        let wd_last = ShapeExpr::WithDim {
664            operand: 1,
665            axis: LAST,
666            dim: Box::new(Dim::Param(0)),
667        };
668        assert_eq!(
669            wd_last.encode(),
670            vec![0x0A, 0x01, 0xFF, 0x02, 0x00, 0x04, 0x00]
671        );
672
673        // Round-trip (the whole-shape decoder).
674        assert_eq!(decode_shape(&wd.encode()).unwrap(), wd);
675        assert_eq!(decode_shape(&wd_last.encode()).unwrap(), wd_last);
676
677        // §6.20-0006 typed declines — never a panic. Truncated before the axis
678        // byte; a child-length prefix that over-runs the buffer.
679        assert_eq!(
680            decode_shape(&[0x0A, 0x00]),
681            Err(ShapeExprError::TruncatedBlob { need: 3, got: 2 })
682        );
683        assert_eq!(
684            decode_shape(&[0x0A, 0x00, 0x01, 0x09, 0x00]),
685            Err(ShapeExprError::TruncatedBlob { need: 9, got: 0 })
686        );
687
688        // §6.20-0003 eval — axis-replacement.
689        let ops = vec![vec![2i64, 3, 5]];
690        assert_eq!(
691            eval_shape(
692                &ShapeExpr::WithDim {
693                    operand: 0,
694                    axis: 1,
695                    dim: Box::new(Dim::Const(9))
696                },
697                &ops,
698                &[]
699            )
700            .unwrap(),
701            ShapeValue::Concrete(vec![2, 9, 5])
702        );
703        // `last` resolves to the trailing axis.
704        assert_eq!(
705            eval_shape(
706                &ShapeExpr::WithDim {
707                    operand: 0,
708                    axis: LAST,
709                    dim: Box::new(Dim::Const(9))
710                },
711                &ops,
712                &[]
713            )
714            .unwrap(),
715            ShapeValue::Concrete(vec![2, 3, 9])
716        );
717        // §6.20-0004 gap propagation: a symbolic extent in a KEPT axis surfaces the
718        // whole shape as a Gap; REPLACING the symbolic axis clears it.
719        let sym = vec![vec![4i64, SYMBOLIC]];
720        assert_eq!(
721            eval_shape(
722                &ShapeExpr::WithDim {
723                    operand: 0,
724                    axis: 0,
725                    dim: Box::new(Dim::Const(7))
726                },
727                &sym,
728                &[]
729            )
730            .unwrap(),
731            ShapeValue::Gap
732        );
733        assert_eq!(
734            eval_shape(
735                &ShapeExpr::WithDim {
736                    operand: 0,
737                    axis: LAST,
738                    dim: Box::new(Dim::Const(7))
739                },
740                &sym,
741                &[]
742            )
743            .unwrap(),
744            ShapeValue::Concrete(vec![4, 7])
745        );
746        // A Gap REPLACEMENT expression also surfaces a whole-shape Gap.
747        assert_eq!(
748            eval_shape(
749                &ShapeExpr::WithDim {
750                    operand: 0,
751                    axis: 0,
752                    dim: Box::new(Dim::Extent {
753                        operand: 0,
754                        axis: LAST
755                    }),
756                },
757                &sym,
758                &[]
759            )
760            .unwrap(),
761            ShapeValue::Gap
762        );
763        // An out-of-range axis is a typed decline, never a panic (§6.20-0003).
764        assert_eq!(
765            eval_shape(
766                &ShapeExpr::WithDim {
767                    operand: 0,
768                    axis: 5,
769                    dim: Box::new(Dim::Const(1))
770                },
771                &[vec![2i64, 3]],
772                &[]
773            ),
774            Err(ShapeExprError::AxisOutOfRange { axis: 5, rank: 2 })
775        );
776        // Param threads through the replacement dim (whole-shape param plumbing).
777        assert_eq!(
778            eval_shape(
779                &ShapeExpr::WithDim {
780                    operand: 0,
781                    axis: 1,
782                    dim: Box::new(Dim::Param(0))
783                },
784                &ops,
785                &[42]
786            )
787            .unwrap(),
788            ShapeValue::Concrete(vec![2, 42, 5])
789        );
790    }
791
792    #[test]
793    fn dims_extension_golden_roundtrip_eval() {
794        // Golden — dims([Extent(0,0), Const(2)]):
795        // KISS "0B 02 03 00 02 00 00 09 00 03 02 00 00 00 00 00 00 00".
796        let dims = ShapeExpr::Dims(vec![
797            Dim::Extent {
798                operand: 0,
799                axis: 0,
800            },
801            Dim::Const(2),
802        ]);
803        assert_eq!(
804            dims.encode(),
805            vec![
806                0x0B, 0x02, 0x03, 0x00, 0x02, 0x00, 0x00, 0x09, 0x00, 0x03, 0x02, 0x00, 0x00, 0x00,
807                0x00, 0x00, 0x00, 0x00
808            ]
809        );
810        // Golden — the empty Dims (N=0) = the rank-0 scalar shape: KISS "0B 00".
811        let scalar = ShapeExpr::Dims(vec![]);
812        assert_eq!(scalar.encode(), vec![0x0B, 0x00]);
813
814        // Round-trip.
815        assert_eq!(decode_shape(&dims.encode()).unwrap(), dims);
816        assert_eq!(decode_shape(&scalar.encode()).unwrap(), scalar);
817
818        // §6.20-0006 typed declines — never a panic: a count promising children the
819        // blob lacks; the still-reserved Reduce (0x09, no consumer); trailing bytes.
820        assert_eq!(
821            decode_shape(&[0x0B, 0x02]),
822            Err(ShapeExprError::TruncatedBlob { need: 2, got: 0 })
823        );
824        assert_eq!(
825            decode_shape(&[0x09, 0x00]),
826            Err(ShapeExprError::ReservedTag { tag: 0x09 })
827        );
828        assert_eq!(
829            decode_shape(&[0x0B, 0x00, 0xAB]),
830            Err(ShapeExprError::TrailingBytes { extra: 1 })
831        );
832
833        // Eval — a qmatmul/scan-style whole-shape reweave across two operands.
834        let ops = vec![vec![8i64, 16, 32, 64], vec![1i64, 1, 1, 128]];
835        assert_eq!(
836            eval_shape(
837                &ShapeExpr::Dims(vec![
838                    Dim::Extent {
839                        operand: 0,
840                        axis: 0
841                    },
842                    Dim::Extent {
843                        operand: 0,
844                        axis: 2
845                    },
846                    Dim::Extent {
847                        operand: 0,
848                        axis: 3
849                    },
850                    Dim::Extent {
851                        operand: 1,
852                        axis: 3
853                    },
854                ]),
855                &ops,
856                &[]
857            )
858            .unwrap(),
859            ShapeValue::Concrete(vec![8, 32, 64, 128])
860        );
861        // The empty Dims evaluates to the rank-0 scalar shape.
862        assert_eq!(
863            eval_shape(&ShapeExpr::Dims(vec![]), &ops, &[]).unwrap(),
864            ShapeValue::Concrete(vec![])
865        );
866        // §6.20-0004 gap propagation: a symbolic extent in ANY element surfaces the
867        // whole shape as a Gap.
868        let sym = vec![vec![4i64, SYMBOLIC]];
869        assert_eq!(
870            eval_shape(
871                &ShapeExpr::Dims(vec![
872                    Dim::Extent {
873                        operand: 0,
874                        axis: 0
875                    },
876                    Dim::Extent {
877                        operand: 0,
878                        axis: LAST
879                    },
880                ]),
881                &sym,
882                &[]
883            )
884            .unwrap(),
885            ShapeValue::Gap
886        );
887    }
888
889    // The whole-shape decoder reads the core `SameAs` too, and declines a
890    // DimExpr-only tag; the DimExpr decoder in turn declines the whole-shape
891    // WithDim/Dims tags (a `Dim` is never a whole shape) — the two grammar levels
892    // stay disjoint (§6.20-0006).
893    #[test]
894    fn decode_shape_core_and_grammar_level_declines() {
895        assert_eq!(
896            decode_shape(&[0x01, 0x00]).unwrap(),
897            ShapeExpr::SameAs { operand: 0 }
898        );
899        // A DimExpr-only tag (Const 0x03) is not a whole-shape constructor.
900        assert_eq!(
901            decode_shape(&[0x03, 0x02, 0, 0, 0, 0, 0, 0, 0]),
902            Err(ShapeExprError::ReservedTag { tag: 0x03 })
903        );
904        // WithDim/Dims are whole-shape tags → the DimExpr reader declines them even
905        // with a well-formed whole-shape payload.
906        assert_eq!(
907            decode_dim(&[TAG_WITH_DIM, 0x00, 0x01, 0x02, 0x00, 0x04, 0x00]),
908            Err(ShapeExprError::ReservedTag { tag: TAG_WITH_DIM })
909        );
910        assert_eq!(
911            decode_dim(&[TAG_DIMS, 0x00]),
912            Err(ShapeExprError::ReservedTag { tag: TAG_DIMS })
913        );
914        // Reduce (0x09) stays reserved at BOTH levels — no consumer.
915        assert_eq!(
916            decode_shape(&[0x09, 0x00]),
917            Err(ShapeExprError::ReservedTag { tag: 0x09 })
918        );
919        assert_eq!(
920            decode_dim(&[0x09, 0x00]),
921            Err(ShapeExprError::ReservedTag { tag: 0x09 })
922        );
923    }
924
925    #[test]
926    fn eval_vocabulary_axis_floordiv_gap() {
927        // §6.20-0002 vocabulary.
928        let ops = vec![vec![2i64, 3, 4]];
929        let params = vec![7i64];
930        assert_eq!(
931            eval_shape(&ShapeExpr::SameAs { operand: 0 }, &ops, &params).unwrap(),
932            ShapeValue::Concrete(vec![2, 3, 4])
933        );
934        assert_eq!(
935            eval_dim(
936                &Dim::Extent {
937                    operand: 0,
938                    axis: 1
939                },
940                &ops,
941                &params
942            )
943            .unwrap(),
944            DimValue::Concrete(3)
945        );
946        assert_eq!(
947            eval_dim(&Dim::Const(5), &ops, &params).unwrap(),
948            DimValue::Concrete(5)
949        );
950        assert_eq!(
951            eval_dim(&Dim::Param(0), &ops, &params).unwrap(),
952            DimValue::Concrete(7)
953        );
954        // (extent(op0,axis0=2) * 3) + param0(7) = 13
955        let e = Dim::Add(
956            Box::new(Dim::Mul(
957                Box::new(Dim::Extent {
958                    operand: 0,
959                    axis: 0,
960                }),
961                Box::new(Dim::Const(3)),
962            )),
963            Box::new(Dim::Param(0)),
964        );
965        assert_eq!(eval_dim(&e, &ops, &params).unwrap(), DimValue::Concrete(13));
966
967        // §6.20-0003 axis + floor-div.
968        let r3 = vec![vec![2i64, 3, 5]];
969        assert_eq!(
970            eval_dim(
971                &Dim::Extent {
972                    operand: 0,
973                    axis: LAST
974                },
975                &r3,
976                &[]
977            )
978            .unwrap(),
979            DimValue::Concrete(5)
980        );
981        assert_eq!(
982            eval_dim(
983                &Dim::Extent {
984                    operand: 0,
985                    axis: 2
986                },
987                &r3,
988                &[]
989            )
990            .unwrap(),
991            DimValue::Concrete(5)
992        );
993        assert_eq!(
994            eval_dim(
995                &Dim::Extent {
996                    operand: 0,
997                    axis: 3
998                },
999                &r3,
1000                &[]
1001            ),
1002            Err(ShapeExprError::AxisOutOfRange { axis: 3, rank: 3 })
1003        );
1004        let fd = |a, b| {
1005            eval_dim(
1006                &Dim::Div(Box::new(Dim::Const(a)), Box::new(Dim::Const(b))),
1007                &r3,
1008                &[],
1009            )
1010        };
1011        assert_eq!(fd(7, 2).unwrap(), DimValue::Concrete(3));
1012        assert_eq!(fd(-7, 2).unwrap(), DimValue::Concrete(-4)); // floor(−3.5) = −4
1013        assert_eq!(fd(1, 0), Err(ShapeExprError::DivideByZero));
1014
1015        // §6.20-0004 symbolic → Gap, propagates.
1016        let sym = vec![vec![4i64, SYMBOLIC]];
1017        assert_eq!(
1018            eval_dim(
1019                &Dim::Extent {
1020                    operand: 0,
1021                    axis: LAST
1022                },
1023                &sym,
1024                &[]
1025            )
1026            .unwrap(),
1027            DimValue::Gap
1028        );
1029        let half = Dim::Div(
1030            Box::new(Dim::Extent {
1031                operand: 0,
1032                axis: LAST,
1033            }),
1034            Box::new(Dim::Const(2)),
1035        );
1036        assert_eq!(eval_dim(&half, &sym, &[]).unwrap(), DimValue::Gap);
1037        assert_eq!(
1038            eval_shape(&ShapeExpr::SameAs { operand: 0 }, &sym, &[]).unwrap(),
1039            ShapeValue::Gap
1040        );
1041        assert_eq!(
1042            eval_dim(
1043                &Dim::Extent {
1044                    operand: 0,
1045                    axis: 0
1046                },
1047                &sym,
1048                &[]
1049            )
1050            .unwrap(),
1051            DimValue::Concrete(4)
1052        );
1053    }
1054
1055    // §6.20-0007 reduce-family shape rule.
1056    #[test]
1057    fn reduce_shape_rule() {
1058        assert_eq!(reduce_shape(&[2, 3, 5], &[2], false), vec![2, 3]); // drop last
1059        assert_eq!(reduce_shape(&[2, 3, 5], &[2], true), vec![2, 3, 1]); // keepdim
1060        assert_eq!(reduce_shape(&[2, 3, 5], &[0, 2], false), vec![3]); // multi-axis
1061        assert_eq!(reduce_shape(&[8, 4096], &[1], false), vec![8]); // reduce(sum, last)
1062    }
1063
1064    // §6.20-0008 gather / matmul: the output equals no operand's shape.
1065    #[test]
1066    fn out_differs_from_operands() {
1067        // gather: data[..axis] ++ index ++ data[axis+1..].
1068        assert_eq!(gather_shape(&[8, 4096], &[16], 0), vec![16, 4096]);
1069        assert_eq!(gather_shape(&[1000, 64], &[2, 5], 0), vec![2, 5, 64]); // embedding
1070        // matmul: [M,K]·[K,N] -> [M,N], batched too.
1071        assert_eq!(matmul_shape(&[8, 4096], &[4096, 1024]), vec![8, 1024]);
1072        assert_eq!(matmul_shape(&[4, 8, 16], &[4, 16, 32]), vec![4, 8, 32]);
1073        // The oracle catches a false same_as(operand) claim: output ≠ either operand.
1074        let g = gather_shape(&[8, 4096], &[16], 0);
1075        assert!(!shape_consistent(&[8, 4096], &ShapeValue::Concrete(g)));
1076        let m = matmul_shape(&[8, 4096], &[4096, 1024]);
1077        assert!(!shape_consistent(
1078            &[8, 4096],
1079            &ShapeValue::Concrete(m.clone())
1080        ));
1081        assert!(!shape_consistent(&[4096, 1024], &ShapeValue::Concrete(m)));
1082    }
1083
1084    // KISS-CONTRACT-6.4-0011 declared ⟷ computed consistency (Gap is never a mismatch).
1085    #[test]
1086    fn contract_output_shape_consistency() {
1087        let computed = ShapeValue::Concrete(reduce_shape(&[8, 4096], &[1], false));
1088        assert!(shape_consistent(&[8], &computed)); // [8] matches reduce → [8]
1089        assert!(!shape_consistent(&[8, 4096], &computed)); // declaring rank-2 is the caught error
1090        assert!(shape_consistent(&[8], &ShapeValue::Gap)); // a Gap is never a hard mismatch
1091    }
1092}