Skip to main content

fuel_dispatch/fkc/
cost_expr.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Cost-expression mini-parser + evaluator (FKC §4.4 / adoption plan §2.3,
3//! strategy **(A)** — the AST half only).
4//!
5//! A cost expression (`flops`, `bytes_moved`, `overhead_ns`,
6//! `memory.device_bytes`) is a small arithmetic formula over shape /
7//! parameter symbols. This module parses such a string into a
8//! [`CompiledCostExpr`] AST and evaluates it against a `symbol_bindings`
9//! map ([`eval`]). It does **not** produce a `CostFn` fn-pointer — that
10//! is the next slice (the trampoline / global side-table /
11//! `register_into`). This slice stops at the parsed AST + a capacity-only
12//! evaluator.
13//!
14//! ## Grammar (§2.3)
15//!
16//! ```text
17//! expr    := term  (('+' | '-') term)*
18//! term    := factor (('*' | '/' | '%') factor)*
19//! factor  := number | symbol | '(' expr ')' | ('-' factor)
20//! number  := integer | float        (decimal; `1`, `4`, `2.5`)
21//! symbol  := identifier             (`m`, `n`, `k`, `dtype_bytes`, …)
22//! ```
23//!
24//! Accepted shape/param symbols are open: any identifier resolves at
25//! eval time from the supplied bindings (a missing symbol is an eval
26//! error, not a parse error — the §2.3 vocabulary `m`, `n`, `k`,
27//! `n`(=elem count), `dtype_bytes` plus any param name the kernel uses).
28//! Anything outside the grammar (a stray `(`, `==`, an empty expression,
29//! a bad character) is a parse error surfaced to the caller as
30//! [`FkcError::CostExprParse`].
31//!
32//! ## The `Unknown` sentinel
33//!
34//! A cost block that is absent, `class`-only, or `judge_measured` with no
35//! coefficient expressions compiles to [`CompiledCostExpr::Unknown`].
36//! The register slice maps that to the existing `unknown_cost` fn-pointer
37//! sentinel; this slice only records it.
38//!
39//! ## Eval is capacity-only (v1)
40//!
41//! [`eval`] evaluates over `u64`-equivalent `f64` symbol values
42//! (capacity / `Extent::bound()`), matching what today's `CostFn`
43//! receives. The per-tier `memory` beyond `device_bytes` and any
44//! `SymEnv`-resolved live-extent term are parsed-but-not-evaluated (held
45//! by the caller, documented at the construction site).
46
47use std::collections::HashMap;
48
49use crate::fused::CostEstimate;
50use crate::kernel::OpParams;
51use fuel_ir::dispatch::OpKind;
52use fuel_ir::{DType, Shape};
53
54/// A compiled cost-expression AST (FKC §4.4 / §2.3 strategy A).
55///
56/// Cloneable + comparable so it can ride on a resolved record and be
57/// asserted in tests. Held as data, never as a fn-pointer (this slice).
58#[derive(Debug, Clone, PartialEq)]
59pub enum CompiledCostExpr {
60    /// Sentinel: no cost claim (absent block / class-only /
61    /// judge_measured with no expressions). Maps to `unknown_cost` in the
62    /// register slice.
63    Unknown,
64    /// A parsed expression tree: the `flops` expression alone (a contract
65    /// that declares no `bytes_moved`, so `bytes_moved` evaluates to 0).
66    Expr(CostNode),
67    /// A contract that declares a `bytes_moved` expression (GAP-376) and/or an
68    /// `overhead_ns` (GAP-382). Any side may be absent: `flops: None` is a
69    /// bytes-only block, whose bytes formula must never be read as flops. Built
70    /// only by `compile_cost`.
71    Declared {
72        flops: Option<CostNode>,
73        bytes_moved: Option<CostNode>,
74        /// Declared launch overhead in ns: a number (held as a literal) or an
75        /// expression string. `None` for an absent or `~` field.
76        overhead_ns: Option<CostNode>,
77    },
78}
79
80/// One node of a cost-expression AST.
81#[derive(Debug, Clone, PartialEq)]
82pub enum CostNode {
83    /// A numeric literal (integer or float; held as `f64`).
84    Lit(f64),
85    /// A shape / param symbol resolved at eval time (`m`, `n`, `k`,
86    /// `dtype_bytes`, …). A dotted member path (`lhs.dim`, `x.dim`,
87    /// FKC §4.4 "shape dims by role") is carried as one dotted `Sym`.
88    Sym(String),
89    /// A binary arithmetic operation.
90    Bin {
91        op: BinOp,
92        lhs: Box<CostNode>,
93        rhs: Box<CostNode>,
94    },
95    /// Unary negation.
96    Neg(Box<CostNode>),
97    /// A shape-axis index: `base[index]` (FKC §3.5 `dim[i]`, §4.4
98    /// `lhs.dim[0]` / `out_shape[2]`). `base` is the symbol path, `index`
99    /// the (usually literal) axis expression.
100    Index {
101        base: Box<CostNode>,
102        index: Box<CostNode>,
103    },
104    /// A function-style term: `f(arg, ...)` (e.g. `block_bytes(quant_type)`
105    /// in the quant-matmul cost hints). Resolved at eval time from the
106    /// bindings by its canonical string spelling.
107    Call { name: String, args: Vec<CostNode> },
108}
109
110/// The four supported binary operators (§2.3: `+ - * / %`).
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum BinOp {
113    Add,
114    Sub,
115    Mul,
116    Div,
117    Rem,
118}
119
120/// A parse failure (kept local; the lower layer wraps it into
121/// [`crate::fkc::FkcError::CostExprParse`] with the field/section context).
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct CostParseError(pub String);
124
125impl std::fmt::Display for CostParseError {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        f.write_str(&self.0)
128    }
129}
130
131/// An eval failure (an undefined symbol, or division by zero).
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct CostEvalError(pub String);
134
135impl std::fmt::Display for CostEvalError {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        f.write_str(&self.0)
138    }
139}
140
141// ===========================================================================
142// Tokenizer
143// ===========================================================================
144
145#[derive(Debug, Clone, PartialEq)]
146enum Tok {
147    Num(f64),
148    Ident(String),
149    Plus,
150    Minus,
151    Star,
152    Slash,
153    Percent,
154    LParen,
155    RParen,
156    LBracket,
157    RBracket,
158    Comma,
159}
160
161fn tokenize(src: &str) -> Result<Vec<Tok>, CostParseError> {
162    let mut toks = Vec::new();
163    let bytes: Vec<char> = src.chars().collect();
164    let mut i = 0;
165    while i < bytes.len() {
166        let c = bytes[i];
167        match c {
168            ' ' | '\t' | '\n' | '\r' => {
169                i += 1;
170            }
171            '+' => {
172                toks.push(Tok::Plus);
173                i += 1;
174            }
175            '-' => {
176                toks.push(Tok::Minus);
177                i += 1;
178            }
179            '*' => {
180                toks.push(Tok::Star);
181                i += 1;
182            }
183            '/' => {
184                toks.push(Tok::Slash);
185                i += 1;
186            }
187            '%' => {
188                toks.push(Tok::Percent);
189                i += 1;
190            }
191            '(' => {
192                toks.push(Tok::LParen);
193                i += 1;
194            }
195            ')' => {
196                toks.push(Tok::RParen);
197                i += 1;
198            }
199            '[' => {
200                toks.push(Tok::LBracket);
201                i += 1;
202            }
203            ']' => {
204                toks.push(Tok::RBracket);
205                i += 1;
206            }
207            ',' => {
208                toks.push(Tok::Comma);
209                i += 1;
210            }
211            c if c.is_ascii_digit() => {
212                let start = i;
213                let mut seen_dot = false;
214                while i < bytes.len()
215                    && (bytes[i].is_ascii_digit() || (bytes[i] == '.' && !seen_dot))
216                {
217                    if bytes[i] == '.' {
218                        seen_dot = true;
219                    }
220                    i += 1;
221                }
222                let lit: String = bytes[start..i].iter().collect();
223                let val: f64 = lit
224                    .parse()
225                    .map_err(|_| CostParseError(format!("bad numeric literal `{lit}`")))?;
226                toks.push(Tok::Num(val));
227            }
228            c if c.is_ascii_alphabetic() || c == '_' => {
229                let start = i;
230                // An identifier may be a DOTTED member path (`lhs.dim`,
231                // `x.dim`, `out_shape`) per FKC §4.4 "shape dims by role". A
232                // `.` is consumed into the identifier only when followed by an
233                // alphabetic/underscore (a member name), so it is never
234                // confused with a decimal point.
235                loop {
236                    while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == '_') {
237                        i += 1;
238                    }
239                    if i + 1 < bytes.len()
240                        && bytes[i] == '.'
241                        && (bytes[i + 1].is_ascii_alphabetic() || bytes[i + 1] == '_')
242                    {
243                        i += 1; // consume the '.'
244                        continue;
245                    }
246                    break;
247                }
248                let ident: String = bytes[start..i].iter().collect();
249                toks.push(Tok::Ident(ident));
250            }
251            other => {
252                return Err(CostParseError(format!(
253                    "unexpected character `{other}` in cost expression"
254                )));
255            }
256        }
257    }
258    Ok(toks)
259}
260
261// ===========================================================================
262// Recursive-descent parser
263// ===========================================================================
264
265struct Parser {
266    toks: Vec<Tok>,
267    pos: usize,
268}
269
270impl Parser {
271    fn peek(&self) -> Option<&Tok> {
272        self.toks.get(self.pos)
273    }
274
275    fn bump(&mut self) -> Option<Tok> {
276        let t = self.toks.get(self.pos).cloned();
277        if t.is_some() {
278            self.pos += 1;
279        }
280        t
281    }
282
283    fn parse_expr(&mut self) -> Result<CostNode, CostParseError> {
284        let mut lhs = self.parse_term()?;
285        while let Some(tok) = self.peek() {
286            let op = match tok {
287                Tok::Plus => BinOp::Add,
288                Tok::Minus => BinOp::Sub,
289                _ => break,
290            };
291            self.bump();
292            let rhs = self.parse_term()?;
293            lhs = CostNode::Bin {
294                op,
295                lhs: Box::new(lhs),
296                rhs: Box::new(rhs),
297            };
298        }
299        Ok(lhs)
300    }
301
302    fn parse_term(&mut self) -> Result<CostNode, CostParseError> {
303        let mut lhs = self.parse_factor()?;
304        while let Some(tok) = self.peek() {
305            let op = match tok {
306                Tok::Star => BinOp::Mul,
307                Tok::Slash => BinOp::Div,
308                Tok::Percent => BinOp::Rem,
309                _ => break,
310            };
311            self.bump();
312            let rhs = self.parse_factor()?;
313            lhs = CostNode::Bin {
314                op,
315                lhs: Box::new(lhs),
316                rhs: Box::new(rhs),
317            };
318        }
319        Ok(lhs)
320    }
321
322    fn parse_factor(&mut self) -> Result<CostNode, CostParseError> {
323        let atom = match self.bump() {
324            Some(Tok::Num(v)) => CostNode::Lit(v),
325            Some(Tok::Ident(name)) => {
326                // A `(` immediately after an identifier is a function call
327                // (`block_bytes(quant_type)`, FKC §4.4 cost hints).
328                if matches!(self.peek(), Some(Tok::LParen)) {
329                    self.bump(); // consume '('
330                    let mut args = Vec::new();
331                    if !matches!(self.peek(), Some(Tok::RParen)) {
332                        loop {
333                            args.push(self.parse_expr()?);
334                            match self.peek() {
335                                Some(Tok::Comma) => {
336                                    self.bump();
337                                }
338                                _ => break,
339                            }
340                        }
341                    }
342                    match self.bump() {
343                        Some(Tok::RParen) => {}
344                        _ => {
345                            return Err(CostParseError(
346                                "unbalanced `(` in function call — expected `)`".into(),
347                            ));
348                        }
349                    }
350                    CostNode::Call { name, args }
351                } else {
352                    CostNode::Sym(name)
353                }
354            }
355            Some(Tok::Minus) => {
356                let inner = self.parse_factor()?;
357                return Ok(CostNode::Neg(Box::new(inner)));
358            }
359            Some(Tok::LParen) => {
360                let inner = self.parse_expr()?;
361                match self.bump() {
362                    Some(Tok::RParen) => inner,
363                    _ => return Err(CostParseError("unbalanced `(` — expected `)`".into())),
364                }
365            }
366            Some(other) => {
367                return Err(CostParseError(format!(
368                    "unexpected token `{other:?}` where a value was expected"
369                )));
370            }
371            None => {
372                return Err(CostParseError(
373                    "unexpected end of cost expression (expected a value)".into(),
374                ));
375            }
376        };
377        // Postfix `[index]` runs (shape-axis index: `dim[i]`, `out_shape[2]`,
378        // `lhs.dim[0]`; FKC §3.5 / §4.4). Chained indexing is allowed.
379        let mut node = atom;
380        while matches!(self.peek(), Some(Tok::LBracket)) {
381            self.bump(); // consume '['
382            let index = self.parse_expr()?;
383            match self.bump() {
384                Some(Tok::RBracket) => {}
385                _ => return Err(CostParseError("unbalanced `[` — expected `]`".into())),
386            }
387            node = CostNode::Index {
388                base: Box::new(node),
389                index: Box::new(index),
390            };
391        }
392        Ok(node)
393    }
394}
395
396/// Parse a single cost-expression string into a [`CostNode`] AST.
397///
398/// Returns [`CostParseError`] on anything outside the §2.3 grammar; the
399/// lower layer wraps it into [`crate::fkc::FkcError::CostExprParse`].
400pub fn parse_expr(src: &str) -> Result<CostNode, CostParseError> {
401    let toks = tokenize(src)?;
402    if toks.is_empty() {
403        return Err(CostParseError("empty cost expression".into()));
404    }
405    let mut parser = Parser { toks, pos: 0 };
406    let node = parser.parse_expr()?;
407    if parser.pos != parser.toks.len() {
408        return Err(CostParseError(format!(
409            "trailing tokens after a complete expression (at token {})",
410            parser.pos
411        )));
412    }
413    Ok(node)
414}
415
416/// Compile a single cost-field expression into a [`CompiledCostExpr`].
417/// `None` (an absent field, i.e. YAML `~`) compiles to
418/// [`CompiledCostExpr::Unknown`].
419pub fn compile_field(src: Option<&str>) -> Result<CompiledCostExpr, CostParseError> {
420    match src {
421        None => Ok(CompiledCostExpr::Unknown),
422        Some(s) if s.trim().is_empty() => Ok(CompiledCostExpr::Unknown),
423        Some(s) => Ok(CompiledCostExpr::Expr(parse_expr(s)?)),
424    }
425}
426
427// ===========================================================================
428// Evaluator (capacity-only)
429// ===========================================================================
430
431/// Evaluate a [`CompiledCostExpr`] against `bindings` (symbol → capacity
432/// value). The [`CompiledCostExpr::Unknown`] sentinel evaluates to `0.0`.
433///
434/// Symbols absent from `bindings` are an [`CostEvalError`] — the caller
435/// (the register slice) supplies the §2.3 vocabulary (`m`, `n`, `k`,
436/// element count, `dtype_bytes`, plus op-param names).
437pub fn eval(
438    expr: &CompiledCostExpr,
439    bindings: &HashMap<String, f64>,
440) -> Result<f64, CostEvalError> {
441    match expr {
442        CompiledCostExpr::Unknown => Ok(0.0),
443        CompiledCostExpr::Expr(node) => eval_node(node, bindings),
444        CompiledCostExpr::Declared { flops, .. } => match flops {
445            Some(node) => eval_node(node, bindings),
446            None => Ok(0.0),
447        },
448    }
449}
450
451/// Evaluate the declared `bytes_moved` side of a compiled cost (GAP-376).
452/// `Unknown` and a flops-only `Expr` declare no bytes, so they evaluate to
453/// `0.0`, exactly as before this field was carried.
454pub fn eval_bytes_moved(
455    expr: &CompiledCostExpr,
456    bindings: &HashMap<String, f64>,
457) -> Result<f64, CostEvalError> {
458    match expr {
459        CompiledCostExpr::Declared {
460            bytes_moved: Some(node),
461            ..
462        } => eval_node(node, bindings),
463        CompiledCostExpr::Unknown
464        | CompiledCostExpr::Expr(_)
465        | CompiledCostExpr::Declared {
466            bytes_moved: None, ..
467        } => Ok(0.0),
468    }
469}
470
471/// Evaluate the declared `overhead_ns` side of a compiled cost (GAP-382), in
472/// nanoseconds saturated into `u32` (the `CostEstimate::kernel_overhead_ns`
473/// width). `Unknown`, a flops-only `Expr` and a block with no `overhead_ns`
474/// declare none, so they evaluate to `0`, exactly as before this field was
475/// carried.
476pub fn eval_overhead_ns(
477    expr: &CompiledCostExpr,
478    bindings: &HashMap<String, f64>,
479) -> Result<u32, CostEvalError> {
480    match expr {
481        CompiledCostExpr::Declared {
482            overhead_ns: Some(node),
483            ..
484        } => {
485            let v = eval_node(node, bindings)?;
486            // f64 -> u32 `as` saturates (NaN -> 0); clamp the sign explicitly.
487            Ok(v.max(0.0) as u32)
488        }
489        CompiledCostExpr::Unknown
490        | CompiledCostExpr::Expr(_)
491        | CompiledCostExpr::Declared {
492            overhead_ns: None, ..
493        } => Ok(0),
494    }
495}
496
497fn eval_node(node: &CostNode, bindings: &HashMap<String, f64>) -> Result<f64, CostEvalError> {
498    match node {
499        CostNode::Lit(v) => Ok(*v),
500        CostNode::Sym(name) => bindings
501            .get(name)
502            .copied()
503            .ok_or_else(|| CostEvalError(format!("undefined cost symbol `{name}`"))),
504        CostNode::Index { base, index } => {
505            // Resolve by the canonical spelling `base[index]` from bindings
506            // (capacity-eval; the importer supplies the resolved axis values).
507            let key = canonical_key(node);
508            if let Some(v) = bindings.get(&key) {
509                return Ok(*v);
510            }
511            // Fall through: a numeric index against a bound `base` symbol is
512            // not statically resolvable here without a shape vector, so an
513            // unbound shape-index is an eval error (capacity-eval supplies the
514            // full key). Touch the children so a malformed index still errors.
515            let _ = eval_node(base, bindings);
516            let _ = eval_node(index, bindings);
517            Err(CostEvalError(format!("undefined cost shape-index `{key}`")))
518        }
519        CostNode::Call { .. } => {
520            let key = canonical_key(node);
521            bindings
522                .get(&key)
523                .copied()
524                .ok_or_else(|| CostEvalError(format!("undefined cost term `{key}`")))
525        }
526        CostNode::Neg(inner) => Ok(-eval_node(inner, bindings)?),
527        CostNode::Bin { op, lhs, rhs } => {
528            let l = eval_node(lhs, bindings)?;
529            let r = eval_node(rhs, bindings)?;
530            match op {
531                BinOp::Add => Ok(l + r),
532                BinOp::Sub => Ok(l - r),
533                BinOp::Mul => Ok(l * r),
534                BinOp::Div => {
535                    if r == 0.0 {
536                        Err(CostEvalError("division by zero in cost expression".into()))
537                    } else {
538                        Ok(l / r)
539                    }
540                }
541                BinOp::Rem => {
542                    if r == 0.0 {
543                        Err(CostEvalError("modulo by zero in cost expression".into()))
544                    } else {
545                        Ok(l % r)
546                    }
547                }
548            }
549        }
550    }
551}
552
553/// Bind the §2.3 cost-expression symbol vocabulary (`m`/`n`/`k`/`batch`/
554/// `dtype_bytes`, plus a generic element count) from a dispatch context, so a
555/// contract's *declared* cost expression can be evaluated to a concrete FLOP
556/// count. Op-specific symbols come from [`OpParams`]; the vocabulary extends as
557/// declared-cost contracts for more op families land.
558pub fn bind_cost_symbols(
559    _op: OpKind,
560    shapes: &[Shape],
561    dtypes: &[DType],
562    params: &OpParams,
563) -> HashMap<String, f64> {
564    let mut b = HashMap::new();
565    if let Some(out) = dtypes.last() {
566        b.insert("dtype_bytes".to_string(), out.size_in_bytes() as f64);
567    }
568    match params {
569        OpParams::Matmul {
570            lhs_batch_dims,
571            m,
572            n,
573            k,
574            ..
575        } => {
576            let batch = lhs_batch_dims.iter().copied().product::<usize>().max(1);
577            b.insert("batch".to_string(), batch as f64);
578            b.insert("m".to_string(), *m as f64);
579            b.insert("n".to_string(), *n as f64);
580            b.insert("k".to_string(), *k as f64);
581        }
582        _ => {
583            // Generic fallback: the total output element count as `n`.
584            if let Some(out_shape) = shapes.last() {
585                b.insert("n".to_string(), out_shape.elem_count() as f64);
586            }
587        }
588    }
589    b
590}
591
592/// The cost trampoline: evaluate a contract's *declared* cost expression against
593/// a dispatch context, turning a parsed [`CompiledCostExpr`] into a concrete
594/// [`CostEstimate`] — the value FKC import previously dropped in favor of the
595/// `unknown_cost` sentinel. An undefined symbol is a typed [`CostEvalError`]
596/// (never a panic, never a silent zero). `bytes_moved` is the declared
597/// `bytes_moved:` expression when the contract carries one, else 0 (GAP-376),
598/// and `kernel_overhead_ns` the declared `overhead_ns:` likewise (GAP-382).
599pub fn cost_estimate(
600    expr: &CompiledCostExpr,
601    op: OpKind,
602    shapes: &[Shape],
603    dtypes: &[DType],
604    params: &OpParams,
605) -> Result<CostEstimate, CostEvalError> {
606    let symbols = bind_cost_symbols(op, shapes, dtypes, params);
607    let flops = eval(expr, &symbols)?;
608    let bytes_moved = eval_bytes_moved(expr, &symbols)?;
609    let kernel_overhead_ns = eval_overhead_ns(expr, &symbols)?;
610    Ok(CostEstimate {
611        flops: flops.max(0.0) as u64,
612        bytes_moved: bytes_moved.max(0.0) as u64,
613        kernel_overhead_ns,
614    })
615}
616
617/// Reconstruct a canonical string spelling of a shape-index / call node so it
618/// can be looked up in the `bindings` map (the importer keys resolved
619/// shape-axis / term values by this spelling at capacity-eval time).
620fn canonical_key(node: &CostNode) -> String {
621    match node {
622        CostNode::Lit(v) => {
623            if v.fract() == 0.0 {
624                format!("{}", *v as i64)
625            } else {
626                format!("{v}")
627            }
628        }
629        CostNode::Sym(s) => s.clone(),
630        CostNode::Index { base, index } => {
631            format!("{}[{}]", canonical_key(base), canonical_key(index))
632        }
633        CostNode::Call { name, args } => {
634            let inner: Vec<String> = args.iter().map(canonical_key).collect();
635            format!("{name}({})", inner.join(","))
636        }
637        CostNode::Neg(inner) => format!("-{}", canonical_key(inner)),
638        CostNode::Bin { .. } => "<expr>".to_string(),
639    }
640}
641
642#[cfg(test)]
643mod tests {
644    use super::*;
645
646    fn b(pairs: &[(&str, f64)]) -> HashMap<String, f64> {
647        pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()
648    }
649
650    #[test]
651    fn parses_and_evals_3_times_n_times_4() {
652        // "3 * n * 4" with n=8 → 96 (the prompt's canonical case).
653        let expr = compile_field(Some("3 * n * 4")).expect("parses");
654        let v = eval(&expr, &b(&[("n", 8.0)])).expect("evals");
655        assert_eq!(v, 96.0);
656    }
657
658    #[test]
659    fn precedence_mul_binds_tighter_than_add() {
660        // 2 + 3 * 4 = 14, not 20.
661        let expr = compile_field(Some("2 + 3 * 4")).unwrap();
662        assert_eq!(eval(&expr, &b(&[])).unwrap(), 14.0);
663    }
664
665    #[test]
666    fn parens_override_precedence() {
667        let expr = compile_field(Some("(2 + 3) * 4")).unwrap();
668        assert_eq!(eval(&expr, &b(&[])).unwrap(), 20.0);
669    }
670
671    #[test]
672    fn matmul_flops_2_m_n_k() {
673        let expr = compile_field(Some("2 * m * n * k")).unwrap();
674        let v = eval(&expr, &b(&[("m", 4.0), ("n", 8.0), ("k", 16.0)])).unwrap();
675        assert_eq!(v, 2.0 * 4.0 * 8.0 * 16.0);
676    }
677
678    #[test]
679    fn rem_and_div_and_float_literal() {
680        assert_eq!(
681            eval(&compile_field(Some("10 % 3")).unwrap(), &b(&[])).unwrap(),
682            1.0
683        );
684        assert_eq!(
685            eval(&compile_field(Some("12 / 4")).unwrap(), &b(&[])).unwrap(),
686            3.0
687        );
688        assert_eq!(
689            eval(&compile_field(Some("2.5 * 2")).unwrap(), &b(&[])).unwrap(),
690            5.0
691        );
692    }
693
694    #[test]
695    fn unary_negation() {
696        assert_eq!(
697            eval(&compile_field(Some("-3 + 5")).unwrap(), &b(&[])).unwrap(),
698            2.0
699        );
700    }
701
702    #[test]
703    fn dtype_bytes_symbol() {
704        let expr = compile_field(Some("3 * n * dtype_bytes")).unwrap();
705        let v = eval(&expr, &b(&[("n", 10.0), ("dtype_bytes", 4.0)])).unwrap();
706        assert_eq!(v, 120.0);
707    }
708
709    #[test]
710    fn none_and_empty_are_unknown() {
711        assert_eq!(compile_field(None).unwrap(), CompiledCostExpr::Unknown);
712        assert_eq!(
713            compile_field(Some("   ")).unwrap(),
714            CompiledCostExpr::Unknown
715        );
716        // Unknown evaluates to 0.
717        assert_eq!(eval(&CompiledCostExpr::Unknown, &b(&[])).unwrap(), 0.0);
718    }
719
720    #[test]
721    fn malformed_expressions_are_parse_errors() {
722        // The prompt's garbage case (after a comparator that the grammar
723        // doesn't have) and other malformed forms.
724        assert!(compile_field(Some("k_len <= sk garbage(")).is_err());
725        assert!(compile_field(Some("2 *")).is_err());
726        assert!(compile_field(Some("(2 + 3")).is_err());
727        assert!(compile_field(Some("2 2")).is_err());
728        assert!(compile_field(Some("@")).is_err());
729        assert!(compile_field(Some("==")).is_err());
730    }
731
732    #[test]
733    fn undefined_symbol_is_eval_error() {
734        let expr = compile_field(Some("n * missing")).unwrap();
735        assert!(eval(&expr, &b(&[("n", 4.0)])).is_err());
736    }
737
738    // --- Extended grammar (FKC §3.5 / §4.4): shape-index, member path, call ---
739
740    #[test]
741    fn shape_index_and_member_path_parse() {
742        // The corpus conv cost expressions.
743        compile_field(Some(
744            "2 * out_shape[0] * (x_shape[1] / groups) * w_shape[2] * w_shape[3]",
745        ))
746        .expect("out_shape[i] parses");
747        compile_field(Some(
748            "2 * out_elems * (x.dim[1] / groups) * weight.dim[2] * weight.dim[3]",
749        ))
750        .expect("role.dim[i] parses");
751        compile_field(Some(
752            "2 * x.dim[0] * x.dim[1] * (x.dim[2] - weight.dim[2] + 1) * weight.dim[2]",
753        ))
754        .expect("causal-conv expr parses");
755    }
756
757    #[test]
758    fn function_call_term_parses() {
759        // The quant-matmul cost hint with a function-style term.
760        compile_field(Some(
761            "(batch_count*m*k*4 + n*k*block_bytes(quant_type) + batch_count*m*n*4)",
762        ))
763        .expect("block_bytes(quant_type) parses");
764    }
765
766    #[test]
767    fn shape_index_evaluates_from_canonical_binding() {
768        let expr = compile_field(Some("2 * out_shape[0]")).unwrap();
769        let v = eval(&expr, &b(&[("out_shape[0]", 8.0)])).unwrap();
770        assert_eq!(v, 16.0);
771    }
772
773    #[test]
774    fn member_path_is_one_dotted_symbol() {
775        // `x.dim` is a single dotted symbol, NOT `x` `.` `dim`.
776        let node = parse_expr("x.dim").unwrap();
777        assert_eq!(node, CostNode::Sym("x.dim".to_string()));
778    }
779
780    #[test]
781    fn unbalanced_bracket_is_parse_error() {
782        assert!(compile_field(Some("out_shape[0")).is_err());
783        assert!(compile_field(Some("x.dim 0]")).is_err());
784    }
785
786    #[test]
787    fn lone_dot_is_still_a_parse_error() {
788        // A bare `.` (not inside a number, not a member path) is rejected.
789        assert!(compile_field(Some("2 . 3")).is_err());
790    }
791}