Skip to main content

cel_parser/
op_table.rs

1//! Operation table for dynamically dispatching operations based on type signatures.
2//!
3//! This module provides a scope-based registry for operations that can be looked up
4//! based on an operation name (string) and the types of the operands. Built-in operations
5//! use compile-time hash tables (via `phf`) for efficient lookup, while custom operations
6//! can be added dynamically through scope functions.
7//!
8//! # Design
9//!
10//! - **Operator symbols as names**: Operations are identified by their operator symbols
11//!   (e.g., `"+"`, `"-"`, `"*"`) to avoid conflicts with valid identifiers.
12//! - **Function pointers**: Built-in operations use stateless function pointers for
13//!   zero-allocation dispatch.
14//! - **Scope stack**: Custom operations are handled through a stack of scope functions
15//!   that can be pushed and popped as needed.
16//! - **Type optimization**: Most built-in operations are homogeneous (both operands share
17//!   a type), so signatures store a primary `TypeId` plus arity. Heterogeneous binary ops
18//!   (e.g. shifts, which accept every signed and unsigned integer RHS) additionally store an RHS
19//!   `TypeId` index.
20//!
21//! # Semantics
22//!
23//! Built-in operations follow Rust language semantics. Deviations are:
24//!
25//! - **Signed integer overflow**: CEL returns `Err` rather than panicking (debug) or wrapping
26//!   (release). Use wrapping arithmetic explicitly if overflow is intended.
27//! - **Bit-shift with out-of-range count**: CEL returns `Err` rather than panicking (debug)
28//!   or masking the shift count (release).
29
30use anyhow::{Result, anyhow};
31use cel_runtime::DynSegment;
32use once_cell::sync::Lazy;
33use phf::phf_map;
34use std::any::TypeId;
35
36use crate::SourceSpan;
37
38/// Wraps a runtime error with span context when the `span-diagnostics` feature is enabled.
39///
40/// When the feature is off this is a no-op and compiles to nothing.
41#[cfg(feature = "span-diagnostics")]
42#[inline]
43fn span_err(span: SourceSpan, e: anyhow::Error) -> anyhow::Error {
44    e.context(crate::SpanContext::new(span))
45}
46
47#[cfg(not(feature = "span-diagnostics"))]
48#[inline]
49fn span_err(_span: SourceSpan, e: anyhow::Error) -> anyhow::Error {
50    e
51}
52
53/// A function that pushes an operation onto a DynSegment.
54///
55/// Receives the segment and the source span of the expression that triggered
56/// this operation. This is a simple function pointer since built-in operations
57/// have no state.
58///
59/// # Examples
60/// See [`OpLookup::register_tuple_op`] for an operation emitter.
61pub type OpFn = fn(&mut DynSegment, SourceSpan) -> Result<()>;
62
63/// A signature for an operator/function whose selected operand is a tuple.
64///
65/// Matches when the operand at `tuple_operand_index` (0-based, in the same
66/// stack order [`DynSegment::peek_stack_infos`] returns) is a tuple whose
67/// element `TypeId`s equal `shape`, in order, and every other peeked operand's
68/// flat `TypeId` equals the corresponding entry in `operand_type_ids` (the
69/// entry at `tuple_operand_index` in `operand_type_ids` is never read).
70///
71/// `operand_type_ids` must have an entry for every non-tuple operand
72/// position: a missing entry (out of bounds, including an entirely empty
73/// vector when there are non-tuple operands) simply never matches, rather
74/// than panicking — it is only safe to omit the whole vector when
75/// `tuple_operand_index` is the *only* operand position.
76///
77/// `shape` is flat: an element position that is itself a nested tuple can
78/// only be recorded as a flat tuple `TypeId`, which matches *any* nested
79/// tuple at that position regardless of its inner arity or element types.
80/// Two registrations that would only differ by that inner shape are not
81/// distinguishable — do not rely on nested-tuple precision at this level.
82///
83/// # Examples
84/// See [`OpLookup::register_tuple_op`].
85pub struct TupleOpSignature {
86    /// Operator/function name this signature is registered under.
87    pub name: String,
88    /// Expected element `TypeId`s, in order, for the tuple-shaped operand.
89    /// See the struct-level note on nested tuples.
90    pub shape: Vec<TypeId>,
91    /// Which peeked operand position must be the tuple.
92    pub tuple_operand_index: usize,
93    /// Flat `TypeId`s expected for the non-tuple operands, in stack order
94    /// (the `tuple_operand_index` entry is ignored).
95    pub operand_type_ids: Vec<TypeId>,
96    /// Function that pushes the operation onto the segment.
97    pub op_fn: OpFn,
98}
99
100/// A scope function that attempts to resolve and apply an operation.
101///
102/// Receives the operation name, the segment, the number of operands on top of the stack,
103/// and the source span of the expression. The scope may call
104/// `segment.peek_stack_infos(num_operands)` to inspect types. Returns `Ok(true)` if
105/// handled, `Ok(false)` if not found, or `Err` on error.
106///
107/// Error messages returned by scope functions surface verbatim to the user. They should be
108/// lowercase, end without a period, and wrap identifiers and type names in backticks.
109///
110/// # Examples
111/// See [`OpLookup::push_scope`] for callback ownership and dispatch.
112pub type ScopeFn =
113    Box<dyn Fn(&str, &mut DynSegment, usize, SourceSpan) -> Result<bool> + Send + Sync>;
114
115/// A signature for a built-in operation.
116///
117/// For homogeneous ops (e.g. `u32 + u32`) `rhs_type_id_index` equals `type_id_index`.
118/// For heterogeneous binary ops (e.g. `u64 << u32`) they differ.
119#[derive(Clone, Copy)]
120struct OpSignature {
121    /// Index into TYPE_IDS for the LHS (or sole) operand type.
122    type_id_index: usize,
123    /// Index into TYPE_IDS for the RHS operand type; equals `type_id_index` for homogeneous ops.
124    rhs_type_id_index: usize,
125    /// Number of operands this operation accepts.
126    arity: u8,
127    /// Function pointer to the operation implementation.
128    op_fn: OpFn,
129}
130
131impl OpSignature {
132    /// Returns the `TypeId` of the LHS (or sole) operand.
133    fn lhs_type_id(&self) -> TypeId {
134        TYPE_IDS[self.type_id_index]
135    }
136
137    /// Returns the `TypeId` of the RHS operand.
138    fn rhs_type_id(&self) -> TypeId {
139        TYPE_IDS[self.rhs_type_id_index]
140    }
141}
142
143/// Single lazy-initialized vector containing all unique TypeIds for built-in types.
144///
145/// This avoids duplicating TypeId storage across all operation signatures.
146static TYPE_IDS: Lazy<Vec<TypeId>> = Lazy::new(|| {
147    vec![
148        TypeId::of::<u8>(),
149        TypeId::of::<u16>(),
150        TypeId::of::<u32>(),
151        TypeId::of::<u64>(),
152        TypeId::of::<u128>(),
153        TypeId::of::<usize>(),
154        TypeId::of::<i8>(),
155        TypeId::of::<i16>(),
156        TypeId::of::<i32>(),
157        TypeId::of::<i64>(),
158        TypeId::of::<i128>(),
159        TypeId::of::<isize>(),
160        TypeId::of::<f32>(),
161        TypeId::of::<f64>(),
162        TypeId::of::<bool>(),
163        TypeId::of::<String>(),
164    ]
165});
166
167// Type index constants for readability
168const TYPE_U8: usize = 0;
169const TYPE_U16: usize = 1;
170const TYPE_U32: usize = 2;
171const TYPE_U64: usize = 3;
172const TYPE_U128: usize = 4;
173const TYPE_USIZE: usize = 5;
174const TYPE_I8: usize = 6;
175const TYPE_I16: usize = 7;
176const TYPE_I32: usize = 8;
177const TYPE_I64: usize = 9;
178const TYPE_I128: usize = 10;
179const TYPE_ISIZE: usize = 11;
180const TYPE_F32: usize = 12;
181const TYPE_F64: usize = 13;
182const TYPE_BOOL: usize = 14;
183const TYPE_STR: usize = 15;
184
185// Helper macros to reduce boilerplate in signature definitions.
186// `sig!` builds a homogeneous signature; `sig_het!` a heterogeneous binary one.
187macro_rules! sig {
188    ($type_idx:expr, $arity:expr, $closure:expr) => {
189        OpSignature {
190            type_id_index: $type_idx,
191            rhs_type_id_index: $type_idx,
192            arity: $arity,
193            op_fn: $closure,
194        }
195    };
196}
197
198macro_rules! sig_het {
199    ($lhs_idx:expr, $rhs_idx:expr, $closure:expr) => {
200        OpSignature {
201            type_id_index: $lhs_idx,
202            rhs_type_id_index: $rhs_idx,
203            arity: 2,
204            op_fn: $closure,
205        }
206    };
207}
208
209// Addition signatures
210static ADD_SIGNATURES: &[OpSignature] = &[
211    sig!(TYPE_U8, 2, |seg, _span| seg
212        .op2(|a: u8, b: u8| a.wrapping_add(b))),
213    sig!(TYPE_U16, 2, |seg, _span| seg
214        .op2(|a: u16, b: u16| a.wrapping_add(b))),
215    sig!(TYPE_U32, 2, |seg, _span| seg
216        .op2(|a: u32, b: u32| a.wrapping_add(b))),
217    sig!(TYPE_U64, 2, |seg, _span| seg
218        .op2(|a: u64, b: u64| a.wrapping_add(b))),
219    sig!(TYPE_U128, 2, |seg, _span| seg
220        .op2(|a: u128, b: u128| a.wrapping_add(b))),
221    sig!(TYPE_USIZE, 2, |seg, _span| seg
222        .op2(|a: usize, b: usize| a.wrapping_add(b))),
223    sig!(TYPE_I8, 2, |seg, span| seg.op2r(move |a: i8, b: i8| a
224        .checked_add(b)
225        .ok_or_else(|| anyhow!("arithmetic overflow"))
226        .map_err(|e| span_err(span, e)))),
227    sig!(TYPE_I16, 2, |seg, span| seg.op2r(move |a: i16, b: i16| a
228        .checked_add(b)
229        .ok_or_else(|| anyhow!("arithmetic overflow"))
230        .map_err(|e| span_err(span, e)))),
231    sig!(TYPE_I32, 2, |seg, span| seg.op2r(move |a: i32, b: i32| a
232        .checked_add(b)
233        .ok_or_else(|| anyhow!("arithmetic overflow"))
234        .map_err(|e| span_err(span, e)))),
235    sig!(TYPE_I64, 2, |seg, span| seg.op2r(move |a: i64, b: i64| a
236        .checked_add(b)
237        .ok_or_else(|| anyhow!("arithmetic overflow"))
238        .map_err(|e| span_err(span, e)))),
239    sig!(TYPE_I128, 2, |seg, span| seg.op2r(
240        move |a: i128, b: i128| a
241            .checked_add(b)
242            .ok_or_else(|| anyhow!("arithmetic overflow"))
243            .map_err(|e| span_err(span, e))
244    )),
245    sig!(TYPE_ISIZE, 2, |seg, span| seg.op2r(
246        move |a: isize, b: isize| a
247            .checked_add(b)
248            .ok_or_else(|| anyhow!("arithmetic overflow"))
249            .map_err(|e| span_err(span, e))
250    )),
251    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a + b)),
252    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a + b)),
253    sig!(TYPE_STR, 2, |seg, _span| seg
254        .op2(|a: String, b: String| a + &b)),
255];
256
257// Subtraction signatures (both binary and unary)
258static SUB_SIGNATURES: &[OpSignature] = &[
259    // Binary subtraction
260    sig!(TYPE_U8, 2, |seg, _span| seg
261        .op2(|a: u8, b: u8| a.wrapping_sub(b))),
262    sig!(TYPE_U16, 2, |seg, _span| seg
263        .op2(|a: u16, b: u16| a.wrapping_sub(b))),
264    sig!(TYPE_U32, 2, |seg, _span| seg
265        .op2(|a: u32, b: u32| a.wrapping_sub(b))),
266    sig!(TYPE_U64, 2, |seg, _span| seg
267        .op2(|a: u64, b: u64| a.wrapping_sub(b))),
268    sig!(TYPE_U128, 2, |seg, _span| seg
269        .op2(|a: u128, b: u128| a.wrapping_sub(b))),
270    sig!(TYPE_USIZE, 2, |seg, _span| seg
271        .op2(|a: usize, b: usize| a.wrapping_sub(b))),
272    sig!(TYPE_I8, 2, |seg, span| seg.op2r(move |a: i8, b: i8| a
273        .checked_sub(b)
274        .ok_or_else(|| anyhow!("arithmetic overflow"))
275        .map_err(|e| span_err(span, e)))),
276    sig!(TYPE_I16, 2, |seg, span| seg.op2r(move |a: i16, b: i16| a
277        .checked_sub(b)
278        .ok_or_else(|| anyhow!("arithmetic overflow"))
279        .map_err(|e| span_err(span, e)))),
280    sig!(TYPE_I32, 2, |seg, span| seg.op2r(move |a: i32, b: i32| a
281        .checked_sub(b)
282        .ok_or_else(|| anyhow!("arithmetic overflow"))
283        .map_err(|e| span_err(span, e)))),
284    sig!(TYPE_I64, 2, |seg, span| seg.op2r(move |a: i64, b: i64| a
285        .checked_sub(b)
286        .ok_or_else(|| anyhow!("arithmetic overflow"))
287        .map_err(|e| span_err(span, e)))),
288    sig!(TYPE_I128, 2, |seg, span| seg.op2r(
289        move |a: i128, b: i128| a
290            .checked_sub(b)
291            .ok_or_else(|| anyhow!("arithmetic overflow"))
292            .map_err(|e| span_err(span, e))
293    )),
294    sig!(TYPE_ISIZE, 2, |seg, span| seg.op2r(
295        move |a: isize, b: isize| a
296            .checked_sub(b)
297            .ok_or_else(|| anyhow!("arithmetic overflow"))
298            .map_err(|e| span_err(span, e))
299    )),
300    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a - b)),
301    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a - b)),
302    // Unary negation
303    sig!(TYPE_I8, 1, |seg, span| seg.op1r(move |a: i8| a
304        .checked_neg()
305        .ok_or_else(|| anyhow!("arithmetic overflow"))
306        .map_err(|e| span_err(span, e)))),
307    sig!(TYPE_I16, 1, |seg, span| seg.op1r(move |a: i16| a
308        .checked_neg()
309        .ok_or_else(|| anyhow!("arithmetic overflow"))
310        .map_err(|e| span_err(span, e)))),
311    sig!(TYPE_I32, 1, |seg, span| seg.op1r(move |a: i32| a
312        .checked_neg()
313        .ok_or_else(|| anyhow!("arithmetic overflow"))
314        .map_err(|e| span_err(span, e)))),
315    sig!(TYPE_I64, 1, |seg, span| seg.op1r(move |a: i64| a
316        .checked_neg()
317        .ok_or_else(|| anyhow!("arithmetic overflow"))
318        .map_err(|e| span_err(span, e)))),
319    sig!(TYPE_I128, 1, |seg, span| seg.op1r(move |a: i128| a
320        .checked_neg()
321        .ok_or_else(|| anyhow!("arithmetic overflow"))
322        .map_err(|e| span_err(span, e)))),
323    sig!(TYPE_ISIZE, 1, |seg, span| seg.op1r(move |a: isize| a
324        .checked_neg()
325        .ok_or_else(|| anyhow!("arithmetic overflow"))
326        .map_err(|e| span_err(span, e)))),
327    sig!(TYPE_F32, 1, |seg, _span| seg.op1(|a: f32| -a)),
328    sig!(TYPE_F64, 1, |seg, _span| seg.op1(|a: f64| -a)),
329];
330
331// Multiplication signatures
332static MUL_SIGNATURES: &[OpSignature] = &[
333    sig!(TYPE_U8, 2, |seg, _span| seg
334        .op2(|a: u8, b: u8| a.wrapping_mul(b))),
335    sig!(TYPE_U16, 2, |seg, _span| seg
336        .op2(|a: u16, b: u16| a.wrapping_mul(b))),
337    sig!(TYPE_U32, 2, |seg, _span| seg
338        .op2(|a: u32, b: u32| a.wrapping_mul(b))),
339    sig!(TYPE_U64, 2, |seg, _span| seg
340        .op2(|a: u64, b: u64| a.wrapping_mul(b))),
341    sig!(TYPE_U128, 2, |seg, _span| seg
342        .op2(|a: u128, b: u128| a.wrapping_mul(b))),
343    sig!(TYPE_USIZE, 2, |seg, _span| seg
344        .op2(|a: usize, b: usize| a.wrapping_mul(b))),
345    sig!(TYPE_I8, 2, |seg, span| seg.op2r(move |a: i8, b: i8| a
346        .checked_mul(b)
347        .ok_or_else(|| anyhow!("arithmetic overflow"))
348        .map_err(|e| span_err(span, e)))),
349    sig!(TYPE_I16, 2, |seg, span| seg.op2r(move |a: i16, b: i16| a
350        .checked_mul(b)
351        .ok_or_else(|| anyhow!("arithmetic overflow"))
352        .map_err(|e| span_err(span, e)))),
353    sig!(TYPE_I32, 2, |seg, span| seg.op2r(move |a: i32, b: i32| a
354        .checked_mul(b)
355        .ok_or_else(|| anyhow!("arithmetic overflow"))
356        .map_err(|e| span_err(span, e)))),
357    sig!(TYPE_I64, 2, |seg, span| seg.op2r(move |a: i64, b: i64| a
358        .checked_mul(b)
359        .ok_or_else(|| anyhow!("arithmetic overflow"))
360        .map_err(|e| span_err(span, e)))),
361    sig!(TYPE_I128, 2, |seg, span| seg.op2r(
362        move |a: i128, b: i128| a
363            .checked_mul(b)
364            .ok_or_else(|| anyhow!("arithmetic overflow"))
365            .map_err(|e| span_err(span, e))
366    )),
367    sig!(TYPE_ISIZE, 2, |seg, span| seg.op2r(
368        move |a: isize, b: isize| a
369            .checked_mul(b)
370            .ok_or_else(|| anyhow!("arithmetic overflow"))
371            .map_err(|e| span_err(span, e))
372    )),
373    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a * b)),
374    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a * b)),
375];
376
377// Division signatures
378//
379// Integer division uses `checked_div` via `op2r` so that division by zero returns an error
380// instead of panicking. Float division keeps `op2` (IEEE 754 defines x/0.0 as inf/nan).
381static DIV_SIGNATURES: &[OpSignature] = &[
382    sig!(TYPE_U8, 2, |seg, span| seg.op2r(move |a: u8, b: u8| a
383        .checked_div(b)
384        .ok_or_else(|| anyhow!("division by zero"))
385        .map_err(|e| span_err(span, e)))),
386    sig!(TYPE_U16, 2, |seg, span| seg.op2r(move |a: u16, b: u16| a
387        .checked_div(b)
388        .ok_or_else(|| anyhow!("division by zero"))
389        .map_err(|e| span_err(span, e)))),
390    sig!(TYPE_U32, 2, |seg, span| seg.op2r(move |a: u32, b: u32| a
391        .checked_div(b)
392        .ok_or_else(|| anyhow!("division by zero"))
393        .map_err(|e| span_err(span, e)))),
394    sig!(TYPE_U64, 2, |seg, span| seg.op2r(move |a: u64, b: u64| a
395        .checked_div(b)
396        .ok_or_else(|| anyhow!("division by zero"))
397        .map_err(|e| span_err(span, e)))),
398    sig!(TYPE_U128, 2, |seg, span| seg.op2r(
399        move |a: u128, b: u128| a
400            .checked_div(b)
401            .ok_or_else(|| anyhow!("division by zero"))
402            .map_err(|e| span_err(span, e))
403    )),
404    sig!(TYPE_USIZE, 2, |seg, span| seg.op2r(
405        move |a: usize, b: usize| a
406            .checked_div(b)
407            .ok_or_else(|| anyhow!("division by zero"))
408            .map_err(|e| span_err(span, e))
409    )),
410    sig!(TYPE_I8, 2, |seg, span| seg.op2r(move |a: i8, b: i8| a
411        .checked_div(b)
412        .ok_or_else(|| anyhow!("division by zero"))
413        .map_err(|e| span_err(span, e)))),
414    sig!(TYPE_I16, 2, |seg, span| seg.op2r(move |a: i16, b: i16| a
415        .checked_div(b)
416        .ok_or_else(|| anyhow!("division by zero"))
417        .map_err(|e| span_err(span, e)))),
418    sig!(TYPE_I32, 2, |seg, span| seg.op2r(move |a: i32, b: i32| a
419        .checked_div(b)
420        .ok_or_else(|| anyhow!("division by zero"))
421        .map_err(|e| span_err(span, e)))),
422    sig!(TYPE_I64, 2, |seg, span| seg.op2r(move |a: i64, b: i64| a
423        .checked_div(b)
424        .ok_or_else(|| anyhow!("division by zero"))
425        .map_err(|e| span_err(span, e)))),
426    sig!(TYPE_I128, 2, |seg, span| seg.op2r(
427        move |a: i128, b: i128| a
428            .checked_div(b)
429            .ok_or_else(|| anyhow!("division by zero"))
430            .map_err(|e| span_err(span, e))
431    )),
432    sig!(TYPE_ISIZE, 2, |seg, span| seg.op2r(
433        move |a: isize, b: isize| a
434            .checked_div(b)
435            .ok_or_else(|| anyhow!("division by zero"))
436            .map_err(|e| span_err(span, e))
437    )),
438    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a / b)),
439    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a / b)),
440];
441
442// Modulo signatures
443//
444// Integer modulo uses `checked_rem` via `op2r` so that division by zero returns an error
445// instead of panicking. Float modulo keeps `op2` (x % 0.0 yields NaN without panicking).
446static MOD_SIGNATURES: &[OpSignature] = &[
447    sig!(TYPE_U8, 2, |seg, span| seg.op2r(move |a: u8, b: u8| a
448        .checked_rem(b)
449        .ok_or_else(|| anyhow!("division by zero"))
450        .map_err(|e| span_err(span, e)))),
451    sig!(TYPE_U16, 2, |seg, span| seg.op2r(move |a: u16, b: u16| a
452        .checked_rem(b)
453        .ok_or_else(|| anyhow!("division by zero"))
454        .map_err(|e| span_err(span, e)))),
455    sig!(TYPE_U32, 2, |seg, span| seg.op2r(move |a: u32, b: u32| a
456        .checked_rem(b)
457        .ok_or_else(|| anyhow!("division by zero"))
458        .map_err(|e| span_err(span, e)))),
459    sig!(TYPE_U64, 2, |seg, span| seg.op2r(move |a: u64, b: u64| a
460        .checked_rem(b)
461        .ok_or_else(|| anyhow!("division by zero"))
462        .map_err(|e| span_err(span, e)))),
463    sig!(TYPE_U128, 2, |seg, span| seg.op2r(
464        move |a: u128, b: u128| a
465            .checked_rem(b)
466            .ok_or_else(|| anyhow!("division by zero"))
467            .map_err(|e| span_err(span, e))
468    )),
469    sig!(TYPE_USIZE, 2, |seg, span| seg.op2r(
470        move |a: usize, b: usize| a
471            .checked_rem(b)
472            .ok_or_else(|| anyhow!("division by zero"))
473            .map_err(|e| span_err(span, e))
474    )),
475    sig!(TYPE_I8, 2, |seg, span| seg.op2r(move |a: i8, b: i8| a
476        .checked_rem(b)
477        .ok_or_else(|| anyhow!("division by zero"))
478        .map_err(|e| span_err(span, e)))),
479    sig!(TYPE_I16, 2, |seg, span| seg.op2r(move |a: i16, b: i16| a
480        .checked_rem(b)
481        .ok_or_else(|| anyhow!("division by zero"))
482        .map_err(|e| span_err(span, e)))),
483    sig!(TYPE_I32, 2, |seg, span| seg.op2r(move |a: i32, b: i32| a
484        .checked_rem(b)
485        .ok_or_else(|| anyhow!("division by zero"))
486        .map_err(|e| span_err(span, e)))),
487    sig!(TYPE_I64, 2, |seg, span| seg.op2r(move |a: i64, b: i64| a
488        .checked_rem(b)
489        .ok_or_else(|| anyhow!("division by zero"))
490        .map_err(|e| span_err(span, e)))),
491    sig!(TYPE_I128, 2, |seg, span| seg.op2r(
492        move |a: i128, b: i128| a
493            .checked_rem(b)
494            .ok_or_else(|| anyhow!("division by zero"))
495            .map_err(|e| span_err(span, e))
496    )),
497    sig!(TYPE_ISIZE, 2, |seg, span| seg.op2r(
498        move |a: isize, b: isize| a
499            .checked_rem(b)
500            .ok_or_else(|| anyhow!("division by zero"))
501            .map_err(|e| span_err(span, e))
502    )),
503    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a % b)),
504    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a % b)),
505];
506
507// Bitwise AND signatures
508static BITWISE_AND_SIGNATURES: &[OpSignature] = &[
509    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a & b)),
510    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a & b)),
511    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a & b)),
512    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a & b)),
513    sig!(TYPE_U128, 2, |seg, _span| seg.op2(|a: u128, b: u128| a & b)),
514    sig!(TYPE_USIZE, 2, |seg, _span| seg
515        .op2(|a: usize, b: usize| a & b)),
516    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a & b)),
517    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a & b)),
518    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a & b)),
519    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a & b)),
520    sig!(TYPE_I128, 2, |seg, _span| seg.op2(|a: i128, b: i128| a & b)),
521    sig!(TYPE_ISIZE, 2, |seg, _span| seg
522        .op2(|a: isize, b: isize| a & b)),
523];
524
525// Bitwise OR signatures
526static BITWISE_OR_SIGNATURES: &[OpSignature] = &[
527    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a | b)),
528    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a | b)),
529    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a | b)),
530    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a | b)),
531    sig!(TYPE_U128, 2, |seg, _span| seg.op2(|a: u128, b: u128| a | b)),
532    sig!(TYPE_USIZE, 2, |seg, _span| seg
533        .op2(|a: usize, b: usize| a | b)),
534    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a | b)),
535    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a | b)),
536    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a | b)),
537    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a | b)),
538    sig!(TYPE_I128, 2, |seg, _span| seg.op2(|a: i128, b: i128| a | b)),
539    sig!(TYPE_ISIZE, 2, |seg, _span| seg
540        .op2(|a: isize, b: isize| a | b)),
541];
542
543// Bitwise XOR signatures
544static BITWISE_XOR_SIGNATURES: &[OpSignature] = &[
545    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a ^ b)),
546    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a ^ b)),
547    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a ^ b)),
548    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a ^ b)),
549    sig!(TYPE_U128, 2, |seg, _span| seg.op2(|a: u128, b: u128| a ^ b)),
550    sig!(TYPE_USIZE, 2, |seg, _span| seg
551        .op2(|a: usize, b: usize| a ^ b)),
552    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a ^ b)),
553    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a ^ b)),
554    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a ^ b)),
555    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a ^ b)),
556    sig!(TYPE_I128, 2, |seg, _span| seg.op2(|a: i128, b: i128| a ^ b)),
557    sig!(TYPE_ISIZE, 2, |seg, _span| seg
558        .op2(|a: isize, b: isize| a ^ b)),
559];
560
561// Macros that push shift signatures onto a Vec as statements.
562// Rust macros may not expand to multiple comma-separated expressions in a static
563// array initialiser, so we use Lazy<Vec<_>> with push statements instead.
564//
565// RHS → u32 conversion (required by checked_shl / checked_shr):
566//   u8, u16              : u32::from  (infallible widening)
567//   u32                  : identity
568//   u64 / u128 / usize   : u32::try_from; fails if value > u32::MAX
569//   all signed types     : u32::try_from; fails if value < 0 or > u32::MAX
570//   In all failure cases the error is "shift overflow", matching Rust's
571//   debug-mode panic for shift-with-overflow.
572macro_rules! shl_push {
573    ($v:ident, $lhs_idx:expr, $lhs_ty:ty) => {
574        $v.push(sig_het!($lhs_idx, TYPE_U8, |seg, span| seg.op2r(
575            move |a: $lhs_ty, b: u8| a
576                .checked_shl(u32::from(b))
577                .ok_or_else(|| anyhow!("shift overflow"))
578                .map_err(|e| span_err(span, e))
579        )));
580        $v.push(sig_het!($lhs_idx, TYPE_U16, |seg, span| seg.op2r(
581            move |a: $lhs_ty, b: u16| a
582                .checked_shl(u32::from(b))
583                .ok_or_else(|| anyhow!("shift overflow"))
584                .map_err(|e| span_err(span, e))
585        )));
586        $v.push(sig_het!($lhs_idx, TYPE_U32, |seg, span| seg.op2r(
587            move |a: $lhs_ty, b: u32| a
588                .checked_shl(b)
589                .ok_or_else(|| anyhow!("shift overflow"))
590                .map_err(|e| span_err(span, e))
591        )));
592        $v.push(sig_het!($lhs_idx, TYPE_U64, |seg, span| seg.op2r(
593            move |a: $lhs_ty, b: u64| u32::try_from(b)
594                .ok()
595                .and_then(|r| a.checked_shl(r))
596                .ok_or_else(|| anyhow!("shift overflow"))
597                .map_err(|e| span_err(span, e))
598        )));
599        $v.push(sig_het!($lhs_idx, TYPE_U128, |seg, span| seg.op2r(
600            move |a: $lhs_ty, b: u128| u32::try_from(b)
601                .ok()
602                .and_then(|r| a.checked_shl(r))
603                .ok_or_else(|| anyhow!("shift overflow"))
604                .map_err(|e| span_err(span, e))
605        )));
606        $v.push(sig_het!($lhs_idx, TYPE_USIZE, |seg, span| seg.op2r(
607            move |a: $lhs_ty, b: usize| u32::try_from(b)
608                .ok()
609                .and_then(|r| a.checked_shl(r))
610                .ok_or_else(|| anyhow!("shift overflow"))
611                .map_err(|e| span_err(span, e))
612        )));
613        $v.push(sig_het!($lhs_idx, TYPE_I8, |seg, span| seg.op2r(
614            move |a: $lhs_ty, b: i8| u32::try_from(b)
615                .ok()
616                .and_then(|r| a.checked_shl(r))
617                .ok_or_else(|| anyhow!("shift overflow"))
618                .map_err(|e| span_err(span, e))
619        )));
620        $v.push(sig_het!($lhs_idx, TYPE_I16, |seg, span| seg.op2r(
621            move |a: $lhs_ty, b: i16| u32::try_from(b)
622                .ok()
623                .and_then(|r| a.checked_shl(r))
624                .ok_or_else(|| anyhow!("shift overflow"))
625                .map_err(|e| span_err(span, e))
626        )));
627        $v.push(sig_het!($lhs_idx, TYPE_I32, |seg, span| seg.op2r(
628            move |a: $lhs_ty, b: i32| u32::try_from(b)
629                .ok()
630                .and_then(|r| a.checked_shl(r))
631                .ok_or_else(|| anyhow!("shift overflow"))
632                .map_err(|e| span_err(span, e))
633        )));
634        $v.push(sig_het!($lhs_idx, TYPE_I64, |seg, span| seg.op2r(
635            move |a: $lhs_ty, b: i64| u32::try_from(b)
636                .ok()
637                .and_then(|r| a.checked_shl(r))
638                .ok_or_else(|| anyhow!("shift overflow"))
639                .map_err(|e| span_err(span, e))
640        )));
641        $v.push(sig_het!($lhs_idx, TYPE_I128, |seg, span| seg.op2r(
642            move |a: $lhs_ty, b: i128| u32::try_from(b)
643                .ok()
644                .and_then(|r| a.checked_shl(r))
645                .ok_or_else(|| anyhow!("shift overflow"))
646                .map_err(|e| span_err(span, e))
647        )));
648        $v.push(sig_het!($lhs_idx, TYPE_ISIZE, |seg, span| seg.op2r(
649            move |a: $lhs_ty, b: isize| u32::try_from(b)
650                .ok()
651                .and_then(|r| a.checked_shl(r))
652                .ok_or_else(|| anyhow!("shift overflow"))
653                .map_err(|e| span_err(span, e))
654        )));
655    };
656}
657
658macro_rules! shr_push {
659    ($v:ident, $lhs_idx:expr, $lhs_ty:ty) => {
660        $v.push(sig_het!($lhs_idx, TYPE_U8, |seg, span| seg.op2r(
661            move |a: $lhs_ty, b: u8| a
662                .checked_shr(u32::from(b))
663                .ok_or_else(|| anyhow!("shift overflow"))
664                .map_err(|e| span_err(span, e))
665        )));
666        $v.push(sig_het!($lhs_idx, TYPE_U16, |seg, span| seg.op2r(
667            move |a: $lhs_ty, b: u16| a
668                .checked_shr(u32::from(b))
669                .ok_or_else(|| anyhow!("shift overflow"))
670                .map_err(|e| span_err(span, e))
671        )));
672        $v.push(sig_het!($lhs_idx, TYPE_U32, |seg, span| seg.op2r(
673            move |a: $lhs_ty, b: u32| a
674                .checked_shr(b)
675                .ok_or_else(|| anyhow!("shift overflow"))
676                .map_err(|e| span_err(span, e))
677        )));
678        $v.push(sig_het!($lhs_idx, TYPE_U64, |seg, span| seg.op2r(
679            move |a: $lhs_ty, b: u64| u32::try_from(b)
680                .ok()
681                .and_then(|r| a.checked_shr(r))
682                .ok_or_else(|| anyhow!("shift overflow"))
683                .map_err(|e| span_err(span, e))
684        )));
685        $v.push(sig_het!($lhs_idx, TYPE_U128, |seg, span| seg.op2r(
686            move |a: $lhs_ty, b: u128| u32::try_from(b)
687                .ok()
688                .and_then(|r| a.checked_shr(r))
689                .ok_or_else(|| anyhow!("shift overflow"))
690                .map_err(|e| span_err(span, e))
691        )));
692        $v.push(sig_het!($lhs_idx, TYPE_USIZE, |seg, span| seg.op2r(
693            move |a: $lhs_ty, b: usize| u32::try_from(b)
694                .ok()
695                .and_then(|r| a.checked_shr(r))
696                .ok_or_else(|| anyhow!("shift overflow"))
697                .map_err(|e| span_err(span, e))
698        )));
699        $v.push(sig_het!($lhs_idx, TYPE_I8, |seg, span| seg.op2r(
700            move |a: $lhs_ty, b: i8| u32::try_from(b)
701                .ok()
702                .and_then(|r| a.checked_shr(r))
703                .ok_or_else(|| anyhow!("shift overflow"))
704                .map_err(|e| span_err(span, e))
705        )));
706        $v.push(sig_het!($lhs_idx, TYPE_I16, |seg, span| seg.op2r(
707            move |a: $lhs_ty, b: i16| u32::try_from(b)
708                .ok()
709                .and_then(|r| a.checked_shr(r))
710                .ok_or_else(|| anyhow!("shift overflow"))
711                .map_err(|e| span_err(span, e))
712        )));
713        $v.push(sig_het!($lhs_idx, TYPE_I32, |seg, span| seg.op2r(
714            move |a: $lhs_ty, b: i32| u32::try_from(b)
715                .ok()
716                .and_then(|r| a.checked_shr(r))
717                .ok_or_else(|| anyhow!("shift overflow"))
718                .map_err(|e| span_err(span, e))
719        )));
720        $v.push(sig_het!($lhs_idx, TYPE_I64, |seg, span| seg.op2r(
721            move |a: $lhs_ty, b: i64| u32::try_from(b)
722                .ok()
723                .and_then(|r| a.checked_shr(r))
724                .ok_or_else(|| anyhow!("shift overflow"))
725                .map_err(|e| span_err(span, e))
726        )));
727        $v.push(sig_het!($lhs_idx, TYPE_I128, |seg, span| seg.op2r(
728            move |a: $lhs_ty, b: i128| u32::try_from(b)
729                .ok()
730                .and_then(|r| a.checked_shr(r))
731                .ok_or_else(|| anyhow!("shift overflow"))
732                .map_err(|e| span_err(span, e))
733        )));
734        $v.push(sig_het!($lhs_idx, TYPE_ISIZE, |seg, span| seg.op2r(
735            move |a: $lhs_ty, b: isize| u32::try_from(b)
736                .ok()
737                .and_then(|r| a.checked_shr(r))
738                .ok_or_else(|| anyhow!("shift overflow"))
739                .map_err(|e| span_err(span, e))
740        )));
741    };
742}
743
744// Left shift: all 144 combinations T << U for integer T and U (mirrors Rust's Shl implementations).
745// Stored as Lazy<Vec<_>> because the shl_push! macro expands to statements, not array items.
746static LEFT_SHIFT_SIGNATURES: Lazy<Vec<OpSignature>> = Lazy::new(|| {
747    let mut v = Vec::with_capacity(144);
748    shl_push!(v, TYPE_U8, u8);
749    shl_push!(v, TYPE_U16, u16);
750    shl_push!(v, TYPE_U32, u32);
751    shl_push!(v, TYPE_U64, u64);
752    shl_push!(v, TYPE_U128, u128);
753    shl_push!(v, TYPE_USIZE, usize);
754    shl_push!(v, TYPE_I8, i8);
755    shl_push!(v, TYPE_I16, i16);
756    shl_push!(v, TYPE_I32, i32);
757    shl_push!(v, TYPE_I64, i64);
758    shl_push!(v, TYPE_I128, i128);
759    shl_push!(v, TYPE_ISIZE, isize);
760    v
761});
762
763// Right shift: all 144 combinations T >> U for integer T and U (mirrors Rust's Shr implementations).
764static RIGHT_SHIFT_SIGNATURES: Lazy<Vec<OpSignature>> = Lazy::new(|| {
765    let mut v = Vec::with_capacity(144);
766    shr_push!(v, TYPE_U8, u8);
767    shr_push!(v, TYPE_U16, u16);
768    shr_push!(v, TYPE_U32, u32);
769    shr_push!(v, TYPE_U64, u64);
770    shr_push!(v, TYPE_U128, u128);
771    shr_push!(v, TYPE_USIZE, usize);
772    shr_push!(v, TYPE_I8, i8);
773    shr_push!(v, TYPE_I16, i16);
774    shr_push!(v, TYPE_I32, i32);
775    shr_push!(v, TYPE_I64, i64);
776    shr_push!(v, TYPE_I128, i128);
777    shr_push!(v, TYPE_ISIZE, isize);
778    v
779});
780
781// Logical NOT signatures
782static LOGICAL_NOT_SIGNATURES: &[OpSignature] =
783    &[sig!(TYPE_BOOL, 1, |seg, _span| seg.op1(|a: bool| !a))];
784
785// Equality signatures
786static EQUAL_SIGNATURES: &[OpSignature] = &[
787    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a == b)),
788    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a == b)),
789    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a == b)),
790    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a == b)),
791    sig!(TYPE_U128, 2, |seg, _span| seg
792        .op2(|a: u128, b: u128| a == b)),
793    sig!(TYPE_USIZE, 2, |seg, _span| seg
794        .op2(|a: usize, b: usize| a == b)),
795    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a == b)),
796    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a == b)),
797    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a == b)),
798    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a == b)),
799    sig!(TYPE_I128, 2, |seg, _span| seg
800        .op2(|a: i128, b: i128| a == b)),
801    sig!(TYPE_ISIZE, 2, |seg, _span| seg
802        .op2(|a: isize, b: isize| a == b)),
803    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a == b)),
804    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a == b)),
805    sig!(TYPE_BOOL, 2, |seg, _span| seg
806        .op2(|a: bool, b: bool| a == b)),
807    sig!(TYPE_STR, 2, |seg, _span| seg
808        .op2(|a: String, b: String| a == b)),
809];
810
811// Inequality signatures
812static NOT_EQUAL_SIGNATURES: &[OpSignature] = &[
813    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a != b)),
814    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a != b)),
815    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a != b)),
816    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a != b)),
817    sig!(TYPE_U128, 2, |seg, _span| seg
818        .op2(|a: u128, b: u128| a != b)),
819    sig!(TYPE_USIZE, 2, |seg, _span| seg
820        .op2(|a: usize, b: usize| a != b)),
821    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a != b)),
822    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a != b)),
823    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a != b)),
824    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a != b)),
825    sig!(TYPE_I128, 2, |seg, _span| seg
826        .op2(|a: i128, b: i128| a != b)),
827    sig!(TYPE_ISIZE, 2, |seg, _span| seg
828        .op2(|a: isize, b: isize| a != b)),
829    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a != b)),
830    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a != b)),
831    sig!(TYPE_BOOL, 2, |seg, _span| seg
832        .op2(|a: bool, b: bool| a != b)),
833    sig!(TYPE_STR, 2, |seg, _span| seg
834        .op2(|a: String, b: String| a != b)),
835];
836
837// Less than signatures
838static LESS_THAN_SIGNATURES: &[OpSignature] = &[
839    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a < b)),
840    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a < b)),
841    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a < b)),
842    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a < b)),
843    sig!(TYPE_U128, 2, |seg, _span| seg.op2(|a: u128, b: u128| a < b)),
844    sig!(TYPE_USIZE, 2, |seg, _span| seg
845        .op2(|a: usize, b: usize| a < b)),
846    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a < b)),
847    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a < b)),
848    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a < b)),
849    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a < b)),
850    sig!(TYPE_I128, 2, |seg, _span| seg.op2(|a: i128, b: i128| a < b)),
851    sig!(TYPE_ISIZE, 2, |seg, _span| seg
852        .op2(|a: isize, b: isize| a < b)),
853    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a < b)),
854    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a < b)),
855    sig!(TYPE_STR, 2, |seg, _span| seg
856        .op2(|a: String, b: String| a < b)),
857];
858
859// Less than or equal signatures
860static LESS_THAN_OR_EQUAL_SIGNATURES: &[OpSignature] = &[
861    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a <= b)),
862    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a <= b)),
863    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a <= b)),
864    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a <= b)),
865    sig!(TYPE_U128, 2, |seg, _span| seg
866        .op2(|a: u128, b: u128| a <= b)),
867    sig!(TYPE_USIZE, 2, |seg, _span| seg
868        .op2(|a: usize, b: usize| a <= b)),
869    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a <= b)),
870    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a <= b)),
871    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a <= b)),
872    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a <= b)),
873    sig!(TYPE_I128, 2, |seg, _span| seg
874        .op2(|a: i128, b: i128| a <= b)),
875    sig!(TYPE_ISIZE, 2, |seg, _span| seg
876        .op2(|a: isize, b: isize| a <= b)),
877    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a <= b)),
878    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a <= b)),
879    sig!(TYPE_STR, 2, |seg, _span| seg
880        .op2(|a: String, b: String| a <= b)),
881];
882
883// Greater than signatures
884static GREATER_THAN_SIGNATURES: &[OpSignature] = &[
885    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a > b)),
886    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a > b)),
887    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a > b)),
888    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a > b)),
889    sig!(TYPE_U128, 2, |seg, _span| seg.op2(|a: u128, b: u128| a > b)),
890    sig!(TYPE_USIZE, 2, |seg, _span| seg
891        .op2(|a: usize, b: usize| a > b)),
892    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a > b)),
893    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a > b)),
894    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a > b)),
895    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a > b)),
896    sig!(TYPE_I128, 2, |seg, _span| seg.op2(|a: i128, b: i128| a > b)),
897    sig!(TYPE_ISIZE, 2, |seg, _span| seg
898        .op2(|a: isize, b: isize| a > b)),
899    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a > b)),
900    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a > b)),
901    sig!(TYPE_STR, 2, |seg, _span| seg
902        .op2(|a: String, b: String| a > b)),
903];
904
905// Greater than or equal signatures
906static GREATER_THAN_OR_EQUAL_SIGNATURES: &[OpSignature] = &[
907    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a >= b)),
908    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a >= b)),
909    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a >= b)),
910    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a >= b)),
911    sig!(TYPE_U128, 2, |seg, _span| seg
912        .op2(|a: u128, b: u128| a >= b)),
913    sig!(TYPE_USIZE, 2, |seg, _span| seg
914        .op2(|a: usize, b: usize| a >= b)),
915    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a >= b)),
916    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a >= b)),
917    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a >= b)),
918    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a >= b)),
919    sig!(TYPE_I128, 2, |seg, _span| seg
920        .op2(|a: i128, b: i128| a >= b)),
921    sig!(TYPE_ISIZE, 2, |seg, _span| seg
922        .op2(|a: isize, b: isize| a >= b)),
923    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a >= b)),
924    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a >= b)),
925    sig!(TYPE_STR, 2, |seg, _span| seg
926        .op2(|a: String, b: String| a >= b)),
927];
928
929// Range construction (`a..b`, `a..=b`) — no operations beyond construction; see the
930// design spec's "Compatibility Notes" for why the recognized structural form is a real
931// `RangeInclusive<T>` type rather than a name-matched builtin.
932static RANGE_SIGNATURES: &[OpSignature] = &[
933    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a..b)),
934    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a..b)),
935    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a..b)),
936    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a..b)),
937    sig!(TYPE_U128, 2, |seg, _span| seg.op2(|a: u128, b: u128| a..b)),
938    sig!(TYPE_USIZE, 2, |seg, _span| seg
939        .op2(|a: usize, b: usize| a..b)),
940    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a..b)),
941    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a..b)),
942    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a..b)),
943    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a..b)),
944    sig!(TYPE_I128, 2, |seg, _span| seg.op2(|a: i128, b: i128| a..b)),
945    sig!(TYPE_ISIZE, 2, |seg, _span| seg
946        .op2(|a: isize, b: isize| a..b)),
947    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a..b)),
948    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a..b)),
949];
950
951static RANGE_INCLUSIVE_SIGNATURES: &[OpSignature] = &[
952    sig!(TYPE_U8, 2, |seg, _span| seg.op2(|a: u8, b: u8| a..=b)),
953    sig!(TYPE_U16, 2, |seg, _span| seg.op2(|a: u16, b: u16| a..=b)),
954    sig!(TYPE_U32, 2, |seg, _span| seg.op2(|a: u32, b: u32| a..=b)),
955    sig!(TYPE_U64, 2, |seg, _span| seg.op2(|a: u64, b: u64| a..=b)),
956    sig!(TYPE_U128, 2, |seg, _span| seg.op2(|a: u128, b: u128| a..=b)),
957    sig!(TYPE_USIZE, 2, |seg, _span| seg
958        .op2(|a: usize, b: usize| a..=b)),
959    sig!(TYPE_I8, 2, |seg, _span| seg.op2(|a: i8, b: i8| a..=b)),
960    sig!(TYPE_I16, 2, |seg, _span| seg.op2(|a: i16, b: i16| a..=b)),
961    sig!(TYPE_I32, 2, |seg, _span| seg.op2(|a: i32, b: i32| a..=b)),
962    sig!(TYPE_I64, 2, |seg, _span| seg.op2(|a: i64, b: i64| a..=b)),
963    sig!(TYPE_I128, 2, |seg, _span| seg.op2(|a: i128, b: i128| a..=b)),
964    sig!(TYPE_ISIZE, 2, |seg, _span| seg
965        .op2(|a: isize, b: isize| a..=b)),
966    sig!(TYPE_F32, 2, |seg, _span| seg.op2(|a: f32, b: f32| a..=b)),
967    sig!(TYPE_F64, 2, |seg, _span| seg.op2(|a: f64, b: f64| a..=b)),
968];
969
970static RANGE_FROM_SIGNATURES: &[OpSignature] = &[
971    sig!(TYPE_U8, 1, |seg, _span| seg.op1(|a: u8| a..)),
972    sig!(TYPE_U16, 1, |seg, _span| seg.op1(|a: u16| a..)),
973    sig!(TYPE_U32, 1, |seg, _span| seg.op1(|a: u32| a..)),
974    sig!(TYPE_U64, 1, |seg, _span| seg.op1(|a: u64| a..)),
975    sig!(TYPE_U128, 1, |seg, _span| seg.op1(|a: u128| a..)),
976    sig!(TYPE_USIZE, 1, |seg, _span| seg.op1(|a: usize| a..)),
977    sig!(TYPE_I8, 1, |seg, _span| seg.op1(|a: i8| a..)),
978    sig!(TYPE_I16, 1, |seg, _span| seg.op1(|a: i16| a..)),
979    sig!(TYPE_I32, 1, |seg, _span| seg.op1(|a: i32| a..)),
980    sig!(TYPE_I64, 1, |seg, _span| seg.op1(|a: i64| a..)),
981    sig!(TYPE_I128, 1, |seg, _span| seg.op1(|a: i128| a..)),
982    sig!(TYPE_ISIZE, 1, |seg, _span| seg.op1(|a: isize| a..)),
983    sig!(TYPE_F32, 1, |seg, _span| seg.op1(|a: f32| a..)),
984    sig!(TYPE_F64, 1, |seg, _span| seg.op1(|a: f64| a..)),
985];
986
987static RANGE_TO_SIGNATURES: &[OpSignature] = &[
988    sig!(TYPE_U8, 1, |seg, _span| seg.op1(|a: u8| ..a)),
989    sig!(TYPE_U16, 1, |seg, _span| seg.op1(|a: u16| ..a)),
990    sig!(TYPE_U32, 1, |seg, _span| seg.op1(|a: u32| ..a)),
991    sig!(TYPE_U64, 1, |seg, _span| seg.op1(|a: u64| ..a)),
992    sig!(TYPE_U128, 1, |seg, _span| seg.op1(|a: u128| ..a)),
993    sig!(TYPE_USIZE, 1, |seg, _span| seg.op1(|a: usize| ..a)),
994    sig!(TYPE_I8, 1, |seg, _span| seg.op1(|a: i8| ..a)),
995    sig!(TYPE_I16, 1, |seg, _span| seg.op1(|a: i16| ..a)),
996    sig!(TYPE_I32, 1, |seg, _span| seg.op1(|a: i32| ..a)),
997    sig!(TYPE_I64, 1, |seg, _span| seg.op1(|a: i64| ..a)),
998    sig!(TYPE_I128, 1, |seg, _span| seg.op1(|a: i128| ..a)),
999    sig!(TYPE_ISIZE, 1, |seg, _span| seg.op1(|a: isize| ..a)),
1000    sig!(TYPE_F32, 1, |seg, _span| seg.op1(|a: f32| ..a)),
1001    sig!(TYPE_F64, 1, |seg, _span| seg.op1(|a: f64| ..a)),
1002];
1003
1004static RANGE_TO_INCLUSIVE_SIGNATURES: &[OpSignature] = &[
1005    sig!(TYPE_U8, 1, |seg, _span| seg.op1(|a: u8| ..=a)),
1006    sig!(TYPE_U16, 1, |seg, _span| seg.op1(|a: u16| ..=a)),
1007    sig!(TYPE_U32, 1, |seg, _span| seg.op1(|a: u32| ..=a)),
1008    sig!(TYPE_U64, 1, |seg, _span| seg.op1(|a: u64| ..=a)),
1009    sig!(TYPE_U128, 1, |seg, _span| seg.op1(|a: u128| ..=a)),
1010    sig!(TYPE_USIZE, 1, |seg, _span| seg.op1(|a: usize| ..=a)),
1011    sig!(TYPE_I8, 1, |seg, _span| seg.op1(|a: i8| ..=a)),
1012    sig!(TYPE_I16, 1, |seg, _span| seg.op1(|a: i16| ..=a)),
1013    sig!(TYPE_I32, 1, |seg, _span| seg.op1(|a: i32| ..=a)),
1014    sig!(TYPE_I64, 1, |seg, _span| seg.op1(|a: i64| ..=a)),
1015    sig!(TYPE_I128, 1, |seg, _span| seg.op1(|a: i128| ..=a)),
1016    sig!(TYPE_ISIZE, 1, |seg, _span| seg.op1(|a: isize| ..=a)),
1017    sig!(TYPE_F32, 1, |seg, _span| seg.op1(|a: f32| ..=a)),
1018    sig!(TYPE_F64, 1, |seg, _span| seg.op1(|a: f64| ..=a)),
1019];
1020
1021/// Compile-time perfect hash map for built-in operations.
1022///
1023/// Maps operator symbols to their signature arrays for O(1) lookup.
1024static BUILTINS: phf::Map<&'static str, &'static [OpSignature]> = phf_map! {
1025    "+" => ADD_SIGNATURES,
1026    "-" => SUB_SIGNATURES,
1027    "*" => MUL_SIGNATURES,
1028    "/" => DIV_SIGNATURES,
1029    "%" => MOD_SIGNATURES,
1030    "&" => BITWISE_AND_SIGNATURES,
1031    "|" => BITWISE_OR_SIGNATURES,
1032    "^" => BITWISE_XOR_SIGNATURES,
1033    "!" => LOGICAL_NOT_SIGNATURES,
1034    "==" => EQUAL_SIGNATURES,
1035    "!=" => NOT_EQUAL_SIGNATURES,
1036    "<" => LESS_THAN_SIGNATURES,
1037    "<=" => LESS_THAN_OR_EQUAL_SIGNATURES,
1038    ">" => GREATER_THAN_SIGNATURES,
1039    ">=" => GREATER_THAN_OR_EQUAL_SIGNATURES,
1040    "range" => RANGE_SIGNATURES,
1041    "range_inclusive" => RANGE_INCLUSIVE_SIGNATURES,
1042    "range_from" => RANGE_FROM_SIGNATURES,
1043    "range_to" => RANGE_TO_SIGNATURES,
1044    "range_to_inclusive" => RANGE_TO_INCLUSIVE_SIGNATURES,
1045};
1046
1047/// A single built-in overload's declared operand types, exposed for the static type checker
1048/// (`cel_parser::ty::check_expr`) — never `op_fn`, which is execution-only and stays private.
1049///
1050/// # Examples
1051/// See [`builtin_operand_types`] for inspecting overload metadata.
1052#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1053pub struct OperandTypes {
1054    /// Number of operands this overload accepts (1 or 2).
1055    pub arity: u8,
1056    /// The LHS (or sole, for arity 1) operand's `TypeId`.
1057    pub lhs: TypeId,
1058    /// The RHS operand's `TypeId`; equal to `lhs` for a homogeneous or arity-1 overload.
1059    pub rhs: TypeId,
1060}
1061
1062/// Returns every built-in overload's declared operand types for `name`, in registration order.
1063///
1064/// Reads the exact same static signature tables `BuiltinScope::lookup` dispatches against, so
1065/// the static type checker and the runtime dispatcher share one source of truth and can't drift
1066/// apart on which operand-type combinations a built-in operator accepts.
1067///
1068/// - Postcondition: returns an empty `Vec` if `name` names no built-in operator. A custom scope
1069///   registered via [`OpLookup::push_scope`] or a tuple-shaped op registered via
1070///   [`OpLookup::register_tuple_op`] is runtime-only (attached to one `OpLookup` instance, not
1071///   this module's static tables) and is not visible here — the type checker treats such an
1072///   operator as unchecked, not an error.
1073///
1074/// - Complexity: O(s) where s is the number of overloads registered for `name`.
1075///
1076/// # Examples
1077///
1078/// ```rust
1079/// use cel_parser::op_table::builtin_operand_types;
1080///
1081/// assert!(builtin_operand_types("+").iter().any(|sig| sig.arity == 2));
1082/// assert!(builtin_operand_types("not_an_operator").is_empty());
1083/// ```
1084pub fn builtin_operand_types(name: &str) -> Vec<OperandTypes> {
1085    let Some(signatures) = signatures_for(name) else {
1086        return Vec::new();
1087    };
1088    signatures
1089        .iter()
1090        .map(|sig| OperandTypes {
1091            arity: sig.arity,
1092            lhs: sig.lhs_type_id(),
1093            rhs: sig.rhs_type_id(),
1094        })
1095        .collect()
1096}
1097
1098/// Routes an operator name to its static signature table, or `None` if `name` names no built-in
1099/// operator. Shared by [`builtin_operand_types`] and [`BuiltinScope::lookup`] so a future
1100/// heterogeneous operator only needs its routing added in one place.
1101fn signatures_for(name: &str) -> Option<&'static [OpSignature]> {
1102    match name {
1103        "<<" => Some(&LEFT_SHIFT_SIGNATURES),
1104        ">>" => Some(&RIGHT_SHIFT_SIGNATURES),
1105        _ => BUILTINS.get(name).copied(),
1106    }
1107}
1108
1109// ─────────────────────────────────────────────────────────────────────────
1110// Casts (`expr as Type`)
1111// ─────────────────────────────────────────────────────────────────────────
1112//
1113// Covers every conversion Rust's own `as` operator supports among the
1114// built-in types this crate's `Ty` model recognizes: the 12 integer widths,
1115// `f32`/`f64`, `bool`, and `String`. A source/target pair not registered
1116// here is one Rust's `as` itself rejects at compile time - e.g. `x as bool`
1117// for a numeric `x` (E0054: "cannot cast ... as `bool`") or `x as f64` for
1118// a `bool` `x` (E0606: "casting `bool` as `f64` is invalid") - so `bool` and
1119// `String` are legitimate, fully-recognized cast *targets*, just ones with a
1120// narrow set of legal sources, not omitted types.
1121//
1122// Fallibility follows one rule, not Rust's `as` (which never fails - it
1123// saturates or truncates silently): a conversion that can always represent
1124// its source value exactly is infallible (`op1`); one that might not is
1125// checked and returns `Err` rather than silently losing information,
1126// matching this crate's established convention for arithmetic (see the
1127// module doc comment's "Semantics" section) and `round`'s own design.
1128//   - int -> int: checked via `TryFrom`, uniformly (including same-width and
1129//     identity pairs, which just always succeed).
1130//   - int -> float: infallible (`as`) - Rust's own behavior; precision loss
1131//     for very large integers is accepted, matching Rust exactly.
1132//   - float -> int: checked - `Err` for non-finite or out-of-range values;
1133//     a value with a fractional part is *truncated* toward zero, same as
1134//     Rust's `as` (checking is only about range/finiteness, not fractional
1135//     truncation policy - use a standard-library rounding function before
1136//     converting when nearest-integer behavior is needed).
1137//   - f32 -> f64: infallible (always exact). f64 -> f32: checked (may not
1138//     fit in `f32`'s finite range).
1139//   - bool -> int: infallible (`as`), matching Rust exactly (`true` -> `1`,
1140//     `false` -> `0`) for all 12 integer widths. Rust has no `bool -> float`
1141//     `as` cast (E0606), so none is registered here either.
1142//   - bool -> bool, String -> String: the only legal `as bool` / `as String`
1143//     sources are their own identity conversions (Rust allows `e as T`
1144//     whenever `e`'s type is already `T`, for any `T`, not just numerics);
1145//     infallible, a plain pass-through.
1146
1147/// A signature for a numeric cast (`expr as Type`): one per legal source
1148/// type for a given target type.
1149#[derive(Clone, Copy)]
1150struct CastSignature {
1151    /// Index into TYPE_IDS for the source (operand) type.
1152    source_type_id_index: usize,
1153    /// Function pointer to the conversion implementation.
1154    op_fn: OpFn,
1155}
1156
1157impl CastSignature {
1158    /// Returns the `TypeId` of the source (operand) type.
1159    fn source_type_id(&self) -> TypeId {
1160        TYPE_IDS[self.source_type_id_index]
1161    }
1162}
1163
1164/// Pushes one checked int->int `CastSignature` (via `TryFrom`) onto `$v`.
1165macro_rules! try_from_cast_push {
1166    ($v:ident, $src_idx:expr, $src_ty:ty, $tgt_ty:ty) => {
1167        $v.push(CastSignature {
1168            source_type_id_index: $src_idx,
1169            op_fn: |seg, span| {
1170                seg.op1r(move |x: $src_ty| -> Result<$tgt_ty> {
1171                    <$tgt_ty>::try_from(x).map_err(|_| {
1172                        span_err(
1173                            span,
1174                            anyhow!(concat!("value does not fit in `", stringify!($tgt_ty), "`")),
1175                        )
1176                    })
1177                })
1178            },
1179        });
1180    };
1181}
1182
1183/// Pushes all 12 checked int->int `CastSignature`s targeting `$tgt_ty` onto `$v`.
1184macro_rules! all_int_to_int_casts {
1185    ($v:ident, $tgt_ty:ty) => {
1186        try_from_cast_push!($v, TYPE_U8, u8, $tgt_ty);
1187        try_from_cast_push!($v, TYPE_U16, u16, $tgt_ty);
1188        try_from_cast_push!($v, TYPE_U32, u32, $tgt_ty);
1189        try_from_cast_push!($v, TYPE_U64, u64, $tgt_ty);
1190        try_from_cast_push!($v, TYPE_U128, u128, $tgt_ty);
1191        try_from_cast_push!($v, TYPE_USIZE, usize, $tgt_ty);
1192        try_from_cast_push!($v, TYPE_I8, i8, $tgt_ty);
1193        try_from_cast_push!($v, TYPE_I16, i16, $tgt_ty);
1194        try_from_cast_push!($v, TYPE_I32, i32, $tgt_ty);
1195        try_from_cast_push!($v, TYPE_I64, i64, $tgt_ty);
1196        try_from_cast_push!($v, TYPE_I128, i128, $tgt_ty);
1197        try_from_cast_push!($v, TYPE_ISIZE, isize, $tgt_ty);
1198    };
1199}
1200
1201/// Pushes one infallible int->float `CastSignature` (via `as`) onto `$v`.
1202macro_rules! as_cast_push {
1203    ($v:ident, $src_idx:expr, $src_ty:ty, $tgt_ty:ty) => {
1204        $v.push(CastSignature {
1205            source_type_id_index: $src_idx,
1206            op_fn: |seg, _span| seg.op1(|x: $src_ty| x as $tgt_ty),
1207        });
1208    };
1209}
1210
1211/// Pushes all 12 infallible int->float `CastSignature`s targeting `$tgt_ty` onto `$v`.
1212macro_rules! all_int_to_float_casts {
1213    ($v:ident, $tgt_ty:ty) => {
1214        as_cast_push!($v, TYPE_U8, u8, $tgt_ty);
1215        as_cast_push!($v, TYPE_U16, u16, $tgt_ty);
1216        as_cast_push!($v, TYPE_U32, u32, $tgt_ty);
1217        as_cast_push!($v, TYPE_U64, u64, $tgt_ty);
1218        as_cast_push!($v, TYPE_U128, u128, $tgt_ty);
1219        as_cast_push!($v, TYPE_USIZE, usize, $tgt_ty);
1220        as_cast_push!($v, TYPE_I8, i8, $tgt_ty);
1221        as_cast_push!($v, TYPE_I16, i16, $tgt_ty);
1222        as_cast_push!($v, TYPE_I32, i32, $tgt_ty);
1223        as_cast_push!($v, TYPE_I64, i64, $tgt_ty);
1224        as_cast_push!($v, TYPE_I128, i128, $tgt_ty);
1225        as_cast_push!($v, TYPE_ISIZE, isize, $tgt_ty);
1226    };
1227}
1228
1229/// Pushes one checked float->int `CastSignature` onto `$v`: `Err` for a
1230/// non-finite or out-of-range value, otherwise truncates toward zero (same
1231/// as Rust's `as`).
1232///
1233/// The upper bound is deliberately not `<$tgt_ty>::MAX as $src_ty`: `MAX` (`0b0111...1`) is one
1234/// less than the power of two `MAX + 1`, so whenever `$tgt_ty` has more value bits than
1235/// `$src_ty`'s mantissa (e.g. `i32::MAX as f32`), the conversion has nowhere to round to but
1236/// *up*, landing exactly on `MAX + 1` - a value that itself is genuinely out of range but would
1237/// then compare equal to (not greater than) the bound, silently passing the check and letting
1238/// Rust's `as` saturate it to `MAX` instead of returning `Err`. Deriving the exclusive upper
1239/// bound directly as a power of two (`2^bits` unsigned, `2^(bits-1)` signed) sidesteps the
1240/// rounding entirely: whenever that power of two is within `$src_ty`'s finite range, it's exact
1241/// (no mantissa bits are needed to represent a power of two, only the exponent). The one case
1242/// where it isn't - `u128` (`2^128`) as an `f32` source, since `2^128` exceeds `f32::MAX` - falls
1243/// back to `f32::INFINITY` as the bound, which is still correct: every finite `f32` value is
1244/// already below `u128::MAX`, so a bound of infinity never wrongly accepts one.
1245macro_rules! float_to_int_cast_push {
1246    ($v:ident, $src_idx:expr, $src_ty:ty, $tgt_ty:ty) => {
1247        $v.push(CastSignature {
1248            source_type_id_index: $src_idx,
1249            op_fn: |seg, span| {
1250                seg.op1r(move |x: $src_ty| -> Result<$tgt_ty> {
1251                    if !x.is_finite() {
1252                        return Err(span_err(span, anyhow!("value is not finite")));
1253                    }
1254                    let is_unsigned = <$tgt_ty>::MIN == 0;
1255                    let bits = <$tgt_ty>::BITS as i32;
1256                    let exponent = if is_unsigned { bits } else { bits - 1 };
1257                    let upper_exclusive: $src_ty = (2.0 as $src_ty).powi(exponent);
1258                    if x < <$tgt_ty>::MIN as $src_ty || x >= upper_exclusive {
1259                        return Err(span_err(
1260                            span,
1261                            anyhow!(concat!("value does not fit in `", stringify!($tgt_ty), "`")),
1262                        ));
1263                    }
1264                    Ok(x as $tgt_ty)
1265                })
1266            },
1267        });
1268    };
1269}
1270
1271/// Pushes both checked float->int `CastSignature`s (`f32`, `f64`) targeting `$tgt_ty` onto `$v`.
1272macro_rules! all_float_to_int_casts {
1273    ($v:ident, $tgt_ty:ty) => {
1274        float_to_int_cast_push!($v, TYPE_F32, f32, $tgt_ty);
1275        float_to_int_cast_push!($v, TYPE_F64, f64, $tgt_ty);
1276    };
1277}
1278
1279macro_rules! int_cast_sources {
1280    ($name:ident, $tgt_ty:ty) => {
1281        static $name: Lazy<Vec<CastSignature>> = Lazy::new(|| {
1282            let mut v = Vec::with_capacity(15);
1283            all_int_to_int_casts!(v, $tgt_ty);
1284            all_float_to_int_casts!(v, $tgt_ty);
1285            as_cast_push!(v, TYPE_BOOL, bool, $tgt_ty);
1286            v
1287        });
1288    };
1289}
1290
1291int_cast_sources!(U8_CAST_SOURCES, u8);
1292int_cast_sources!(U16_CAST_SOURCES, u16);
1293int_cast_sources!(U32_CAST_SOURCES, u32);
1294int_cast_sources!(U64_CAST_SOURCES, u64);
1295int_cast_sources!(U128_CAST_SOURCES, u128);
1296int_cast_sources!(USIZE_CAST_SOURCES, usize);
1297int_cast_sources!(I8_CAST_SOURCES, i8);
1298int_cast_sources!(I16_CAST_SOURCES, i16);
1299int_cast_sources!(I32_CAST_SOURCES, i32);
1300int_cast_sources!(I64_CAST_SOURCES, i64);
1301int_cast_sources!(I128_CAST_SOURCES, i128);
1302int_cast_sources!(ISIZE_CAST_SOURCES, isize);
1303
1304static F32_CAST_SOURCES: Lazy<Vec<CastSignature>> = Lazy::new(|| {
1305    let mut v = vec![
1306        // f64 -> f32: checked (may not fit in f32's finite range). Unlike the int-narrowing
1307        // checks below, comparing directly against `f32::MAX as f64` is safe here rather than
1308        // needing the power-of-two-derived bound: f64's 53-bit mantissa always represents
1309        // f32::MAX exactly (f32 needs at most 24 significant bits), so this conversion never
1310        // rounds and the bound is exact.
1311        CastSignature {
1312            source_type_id_index: TYPE_F64,
1313            op_fn: |seg, span| {
1314                seg.op1r(move |x: f64| -> Result<f32> {
1315                    if !x.is_finite() {
1316                        return Err(span_err(span, anyhow!("value is not finite")));
1317                    }
1318                    if x.abs() > f32::MAX as f64 {
1319                        return Err(span_err(span, anyhow!("value does not fit in `f32`")));
1320                    }
1321                    Ok(x as f32)
1322                })
1323            },
1324        },
1325        CastSignature {
1326            source_type_id_index: TYPE_F32,
1327            op_fn: |seg, _span| seg.op1(|x: f32| x),
1328        },
1329    ];
1330    all_int_to_float_casts!(v, f32);
1331    v
1332});
1333
1334static F64_CAST_SOURCES: Lazy<Vec<CastSignature>> = Lazy::new(|| {
1335    let mut v = vec![
1336        // f32 -> f64: always exact.
1337        CastSignature {
1338            source_type_id_index: TYPE_F32,
1339            op_fn: |seg, _span| seg.op1(|x: f32| x as f64),
1340        },
1341        CastSignature {
1342            source_type_id_index: TYPE_F64,
1343            op_fn: |seg, _span| seg.op1(|x: f64| x),
1344        },
1345    ];
1346    all_int_to_float_casts!(v, f64);
1347    v
1348});
1349
1350/// `bool`'s only legal `as` source is `bool` itself (Rust has no
1351/// int/float/String -> `bool` `as` cast - E0054): a no-op identity
1352/// conversion.
1353static BOOL_CAST_SOURCES: Lazy<Vec<CastSignature>> = Lazy::new(|| {
1354    vec![CastSignature {
1355        source_type_id_index: TYPE_BOOL,
1356        op_fn: |seg, _span| seg.op1(|x: bool| x),
1357    }]
1358});
1359
1360/// `String`'s only legal `as` source is `String` itself (Rust's `as` has no
1361/// conversion at all to `String` from any other type): a no-op identity
1362/// conversion.
1363static STRING_CAST_SOURCES: Lazy<Vec<CastSignature>> = Lazy::new(|| {
1364    vec![CastSignature {
1365        source_type_id_index: TYPE_STR,
1366        op_fn: |seg, _span| seg.op1(|x: String| x),
1367    }]
1368});
1369
1370/// Routes a cast target type name to its static signature table (one legal
1371/// source per entry), or `None` if `target_name` names no type this
1372/// language's `as` operator recognizes as a cast target at all. Shared by
1373/// [`cast_source_types`] (the type checker) and [`OpLookup::lookup_cast`]
1374/// (execution) so they can't drift.
1375fn signatures_for_cast(target_name: &str) -> Option<&'static [CastSignature]> {
1376    match target_name {
1377        "u8" => Some(&U8_CAST_SOURCES),
1378        "u16" => Some(&U16_CAST_SOURCES),
1379        "u32" => Some(&U32_CAST_SOURCES),
1380        "u64" => Some(&U64_CAST_SOURCES),
1381        "u128" => Some(&U128_CAST_SOURCES),
1382        "usize" => Some(&USIZE_CAST_SOURCES),
1383        "i8" => Some(&I8_CAST_SOURCES),
1384        "i16" => Some(&I16_CAST_SOURCES),
1385        "i32" => Some(&I32_CAST_SOURCES),
1386        "i64" => Some(&I64_CAST_SOURCES),
1387        "i128" => Some(&I128_CAST_SOURCES),
1388        "isize" => Some(&ISIZE_CAST_SOURCES),
1389        "f32" => Some(&F32_CAST_SOURCES),
1390        "f64" => Some(&F64_CAST_SOURCES),
1391        "bool" => Some(&BOOL_CAST_SOURCES),
1392        "String" => Some(&STRING_CAST_SOURCES),
1393        _ => None,
1394    }
1395}
1396
1397/// Lists every source `TypeId` with a registered cast to `target_name`. Used by the type checker
1398/// (`ty.rs`) to validate a cast without needing to touch a [`DynSegment`] - reads the exact same
1399/// tables [`OpLookup::lookup_cast`] does, so the two can't drift out of sync.
1400///
1401/// - Postcondition: yields no items if `target_name` names no recognized cast-target type.
1402///
1403/// - Complexity: O(s) where s is the number of registered sources for `target_name`.
1404///
1405/// # Examples
1406///
1407/// ```rust
1408/// use cel_parser::op_table::cast_source_types;
1409///
1410/// assert!(cast_source_types("i32").count() > 0);
1411/// assert_eq!(cast_source_types("not_a_type").count(), 0);
1412/// ```
1413pub fn cast_source_types(target_name: &str) -> impl Iterator<Item = TypeId> {
1414    signatures_for_cast(target_name)
1415        .into_iter()
1416        .flat_map(|sigs| sigs.iter().map(CastSignature::source_type_id))
1417}
1418
1419/// One built-in name and its clone-capable runtime descriptor.
1420///
1421/// The default type resolver shares the scalar name set with [`signatures_for_cast`];
1422/// configured resolvers may additionally supply host-registered descriptors.
1423pub(crate) struct BuiltinScalarType {
1424    pub(crate) type_name: &'static str,
1425    /// Builds complete metadata at the concrete built-in registration site.
1426    pub(crate) value_type: fn() -> cel_runtime::value_type::ValueType,
1427}
1428
1429/// Builds independent clone, equality, and formatting plans for a known built-in leaf.
1430fn complete_builtin_leaf<T: Clone + PartialEq + std::fmt::Debug + 'static>()
1431-> cel_runtime::value_type::ValueType {
1432    use cel_runtime::value_type::{Leaf, ValueType};
1433    ValueType::cloneable_leaf::<T>()
1434        .with_equality::<Leaf<T>>()
1435        .expect("same concrete leaf")
1436        .with_debug::<Leaf<T>>()
1437        .expect("same concrete leaf")
1438}
1439
1440/// Declares the one built-in scalar table every built-in name lookup reads: the test-only name list
1441/// `BUILTIN_SCALAR_NAMES` exposes and the descriptors [`builtin_scalar_type`] resolves, so a
1442/// name can never be recognized by one and missed by the other.
1443macro_rules! builtin_scalars {
1444    ($($name:literal => $ty:ty),* $(,)?) => {
1445        /// Every built-in scalar type name, in table order. Used by the cross-table consistency
1446        /// tests that keep this table, [`crate::Ty`], and the CEL type resolver in agreement.
1447        pub(crate) const BUILTIN_SCALAR_NAMES: &[&str] = &[$($name),*];
1448
1449        /// Returns complete scalar metadata from concrete registration factories.
1450        pub(crate) fn builtin_value_type(id: TypeId) -> Option<cel_runtime::ValueType> {
1451            $(if id == TypeId::of::<$ty>() {
1452                return Some(complete_builtin_leaf::<$ty>());
1453            })*
1454            None
1455        }
1456
1457        /// Resolves a built-in scalar type's bare identifier (a closure parameter annotation, a
1458        /// CEL array annotation leaf) to its full descriptor, or `None` if `name` names no
1459        /// recognized scalar type.
1460        ///
1461        /// - Complexity: O(1).
1462        pub(crate) fn builtin_scalar_type(name: &str) -> Option<BuiltinScalarType> {
1463            Some(match name {
1464                $($name => BuiltinScalarType {
1465                    type_name: $name,
1466                    value_type: complete_builtin_leaf::<$ty>,
1467                },)*
1468                _ => return None,
1469            })
1470        }
1471    };
1472}
1473
1474builtin_scalars! {
1475    "u8" => u8,
1476    "u16" => u16,
1477    "u32" => u32,
1478    "u64" => u64,
1479    "u128" => u128,
1480    "usize" => usize,
1481    "i8" => i8,
1482    "i16" => i16,
1483    "i32" => i32,
1484    "i64" => i64,
1485    "i128" => i128,
1486    "isize" => isize,
1487    "f32" => f32,
1488    "f64" => f64,
1489    "bool" => bool,
1490    "String" => String,
1491}
1492
1493/// Declares concrete argument/result descriptors for the builtin range constructors.
1494macro_rules! builtin_generic_types {
1495    ($($generic:literal => { $($arg_name:literal => $ty:ty),* $(,)? }),* $(,)?) => {
1496        /// Builds the finite builtin type-function set from concrete descriptors.
1497        pub(crate) fn builtin_type_functions() -> crate::type_functions::TypeFunctionRegistry {
1498            let mut functions = crate::type_functions::TypeFunctionRegistry::new();
1499            $($(
1500                let argument = builtin_scalar_type($arg_name).expect("builtin argument");
1501                let argument = crate::ResolvedType::from(crate::ResolvedLeafType::new(
1502                    $arg_name, (argument.value_type)()));
1503                functions.register($generic, &[argument], crate::ResolvedLeafType::new(
1504                    concat!($generic, "(", $arg_name, ")"), complete_builtin_leaf::<$ty>()))
1505                    .expect("builtin type function");
1506            )*)*
1507            functions.register("RangeFull", &[], crate::ResolvedLeafType::new(
1508                "RangeFull", complete_builtin_leaf::<std::ops::RangeFull>()))
1509                .expect("builtin zero-argument type function");
1510            functions
1511        }
1512
1513    };
1514}
1515
1516builtin_generic_types! {
1517    "Range" => {
1518        "u8" => std::ops::Range<u8>, "u16" => std::ops::Range<u16>,
1519        "u32" => std::ops::Range<u32>, "u64" => std::ops::Range<u64>,
1520        "u128" => std::ops::Range<u128>, "usize" => std::ops::Range<usize>,
1521        "i8" => std::ops::Range<i8>, "i16" => std::ops::Range<i16>,
1522        "i32" => std::ops::Range<i32>, "i64" => std::ops::Range<i64>,
1523        "i128" => std::ops::Range<i128>, "isize" => std::ops::Range<isize>,
1524        "f32" => std::ops::Range<f32>, "f64" => std::ops::Range<f64>,
1525    },
1526    "RangeInclusive" => {
1527        "u8" => std::ops::RangeInclusive<u8>, "u16" => std::ops::RangeInclusive<u16>,
1528        "u32" => std::ops::RangeInclusive<u32>, "u64" => std::ops::RangeInclusive<u64>,
1529        "u128" => std::ops::RangeInclusive<u128>, "usize" => std::ops::RangeInclusive<usize>,
1530        "i8" => std::ops::RangeInclusive<i8>, "i16" => std::ops::RangeInclusive<i16>,
1531        "i32" => std::ops::RangeInclusive<i32>, "i64" => std::ops::RangeInclusive<i64>,
1532        "i128" => std::ops::RangeInclusive<i128>, "isize" => std::ops::RangeInclusive<isize>,
1533        "f32" => std::ops::RangeInclusive<f32>, "f64" => std::ops::RangeInclusive<f64>,
1534    },
1535    "RangeFrom" => {
1536        "u8" => std::ops::RangeFrom<u8>, "u16" => std::ops::RangeFrom<u16>,
1537        "u32" => std::ops::RangeFrom<u32>, "u64" => std::ops::RangeFrom<u64>,
1538        "u128" => std::ops::RangeFrom<u128>, "usize" => std::ops::RangeFrom<usize>,
1539        "i8" => std::ops::RangeFrom<i8>, "i16" => std::ops::RangeFrom<i16>,
1540        "i32" => std::ops::RangeFrom<i32>, "i64" => std::ops::RangeFrom<i64>,
1541        "i128" => std::ops::RangeFrom<i128>, "isize" => std::ops::RangeFrom<isize>,
1542        "f32" => std::ops::RangeFrom<f32>, "f64" => std::ops::RangeFrom<f64>,
1543    },
1544    "RangeTo" => {
1545        "u8" => std::ops::RangeTo<u8>, "u16" => std::ops::RangeTo<u16>,
1546        "u32" => std::ops::RangeTo<u32>, "u64" => std::ops::RangeTo<u64>,
1547        "u128" => std::ops::RangeTo<u128>, "usize" => std::ops::RangeTo<usize>,
1548        "i8" => std::ops::RangeTo<i8>, "i16" => std::ops::RangeTo<i16>,
1549        "i32" => std::ops::RangeTo<i32>, "i64" => std::ops::RangeTo<i64>,
1550        "i128" => std::ops::RangeTo<i128>, "isize" => std::ops::RangeTo<isize>,
1551        "f32" => std::ops::RangeTo<f32>, "f64" => std::ops::RangeTo<f64>,
1552    },
1553    "RangeToInclusive" => {
1554        "u8" => std::ops::RangeToInclusive<u8>, "u16" => std::ops::RangeToInclusive<u16>,
1555        "u32" => std::ops::RangeToInclusive<u32>, "u64" => std::ops::RangeToInclusive<u64>,
1556        "u128" => std::ops::RangeToInclusive<u128>, "usize" => std::ops::RangeToInclusive<usize>,
1557        "i8" => std::ops::RangeToInclusive<i8>, "i16" => std::ops::RangeToInclusive<i16>,
1558        "i32" => std::ops::RangeToInclusive<i32>, "i64" => std::ops::RangeToInclusive<i64>,
1559        "i128" => std::ops::RangeToInclusive<i128>, "isize" => std::ops::RangeToInclusive<isize>,
1560        "f32" => std::ops::RangeToInclusive<f32>, "f64" => std::ops::RangeToInclusive<f64>,
1561    },
1562}
1563
1564/// Built-in operation scope.
1565///
1566/// Provides lookup for standard operations using a compile-time hash table.
1567struct BuiltinScope;
1568
1569impl BuiltinScope {
1570    /// Attempts to find and apply a built-in operation.
1571    ///
1572    /// Returns `Ok(true)` if found and applied, `Ok(false)` if not found.
1573    ///
1574    /// - Complexity: O(s) where s is the number of signatures registered for `name`.
1575    fn lookup(
1576        &self,
1577        name: &str,
1578        segment: &mut DynSegment,
1579        num_operands: usize,
1580        span: SourceSpan,
1581    ) -> Result<bool> {
1582        let stack_infos = segment.peek_stack_infos(num_operands);
1583        let Some(signatures) = signatures_for(name) else {
1584            return Ok(false);
1585        };
1586        for sig in signatures {
1587            let arity = sig.arity as usize;
1588            let matches = arity == stack_infos.len()
1589                && stack_infos[0].value_type.type_id() == sig.lhs_type_id()
1590                && (arity < 2 || stack_infos[1].value_type.type_id() == sig.rhs_type_id());
1591            if matches {
1592                (sig.op_fn)(segment, span)?;
1593                return Ok(true);
1594            }
1595        }
1596        Ok(false)
1597    }
1598}
1599
1600/// Scope function implementing the arity-0 `range_full` internal op: constructs
1601/// `std::ops::RangeFull`, the value a bare `..` produces. There is no second
1602/// half because `RangeFull` is never called with arguments.
1603///
1604/// Registered by every [`OpLookup::new()`] (see there). `"range_full"` is an internal
1605/// dispatch name the parser selects when it recognizes a bare `..` with neither a left
1606/// nor right endpoint — never a name CEL source can reference directly, matching
1607/// `"range"`/`"range_inclusive"`/`"range_from"`/`"range_to"`/`"range_to_inclusive"`.
1608fn range_full_scope(
1609    name: &str,
1610    segment: &mut DynSegment,
1611    num_operands: usize,
1612    _span: SourceSpan,
1613) -> Result<bool> {
1614    match (name, num_operands) {
1615        ("range_full", 0) => {
1616            segment.op0(|| std::ops::RangeFull);
1617            Ok(true)
1618        }
1619        _ => Ok(false),
1620    }
1621}
1622
1623/// Operation lookup with scope stack support.
1624///
1625/// Resolves scopes in LIFO order, then persistent named registrations, tuple
1626/// signatures, and built-in operations. Named registrations survive scope isolation.
1627///
1628/// # Examples
1629///
1630/// ```rust
1631/// use cel_parser::op_table::OpLookup;
1632/// use cel_runtime::DynSegment;
1633/// use std::any::TypeId;
1634///
1635/// let mut lookup = OpLookup::new();
1636///
1637/// // Use built-in addition
1638/// let mut segment = DynSegment::new::<()>();
1639/// segment.just(10u32);
1640/// segment.just(20u32);
1641/// lookup.lookup("+", &mut segment, 2, proc_macro2::Span::call_site(), proc_macro2::Span::call_site()).unwrap();
1642/// assert_eq!(segment.call0::<u32>().unwrap(), 30);
1643/// ```
1644pub struct OpLookup {
1645    pub(crate) registered: crate::registered_ops::RegisteredOps,
1646    scopes: Vec<ScopeFn>,
1647    library_scope_count: usize,
1648    builtin_scope: BuiltinScope,
1649    tuple_signatures: Vec<TupleOpSignature>,
1650}
1651
1652impl OpLookup {
1653    /// Reports opaque scopes and legacy signatures that cannot describe offline checking.
1654    pub(crate) fn unsupported_checking_metadata(&self) -> Option<&'static str> {
1655        if self.scopes.len() != 1 {
1656            Some("callback-only scope")
1657        } else if !self.tuple_signatures.is_empty() {
1658            Some("legacy tuple registration")
1659        } else {
1660            None
1661        }
1662    }
1663
1664    /// Creates a new operation lookup with only built-in operations - the
1665    /// infix/prefix operators, the cast operator (`as`), and range syntax.
1666    ///
1667    /// # Examples
1668    ///
1669    /// ```rust
1670    /// use cel_parser::OpLookup;
1671    ///
1672    /// let lookup = OpLookup::new();
1673    /// ```
1674    pub fn new() -> Self {
1675        let mut lookup = OpLookup {
1676            registered: Default::default(),
1677            scopes: Vec::new(),
1678            library_scope_count: 0,
1679            builtin_scope: BuiltinScope,
1680            tuple_signatures: Vec::new(),
1681        };
1682        lookup.push_library_scope(range_full_scope);
1683        lookup
1684    }
1685
1686    /// Registers a tuple-shaped operator signature, matched by element
1687    /// `TypeId` sequence the same way built-in operators are matched by flat
1688    /// `TypeId`.
1689    ///
1690    /// - Complexity: Amortized O(1) registration, transferring the owned signature.
1691    ///
1692    /// # Examples
1693    /// ```
1694    /// use cel_parser::op_table::{OpLookup, TupleOpSignature};
1695    /// use cel_runtime::DynSegment;
1696    /// use proc_macro2::Span;
1697    /// use std::any::TypeId;
1698    /// let mut lookup = OpLookup::new();
1699    /// lookup.register_tuple_op(TupleOpSignature {
1700    ///     name: "first".into(),
1701    ///     shape: vec![TypeId::of::<i32>()],
1702    ///     tuple_operand_index: 0,
1703    ///     operand_type_ids: Vec::new(),
1704    ///     op_fn: |segment, _| segment.tuple_index(0),
1705    /// });
1706    /// let mut segment = DynSegment::new::<()>();
1707    /// segment.just(42i32);
1708    /// segment.make_tuple(1, 0).unwrap();
1709    /// lookup.lookup("first", &mut segment, 1, Span::call_site(), Span::call_site()).unwrap();
1710    /// assert_eq!(segment.call0::<i32>().unwrap(), 42);
1711    /// ```
1712    pub fn register_tuple_op(&mut self, signature: TupleOpSignature) {
1713        self.tuple_signatures.push(signature);
1714    }
1715
1716    /// Attempts to find and apply a registered tuple-shaped signature.
1717    ///
1718    /// Returns `Ok(true)` if found and applied, `Ok(false)` if not found.
1719    ///
1720    /// - Complexity: O(s) where s is the number of registered tuple signatures.
1721    fn lookup_tuple_signature(
1722        &self,
1723        name: &str,
1724        segment: &mut DynSegment,
1725        num_operands: usize,
1726        span: SourceSpan,
1727    ) -> Result<bool> {
1728        let stack_infos = segment.peek_stack_infos(num_operands);
1729        for sig in &self.tuple_signatures {
1730            if sig.name != name || sig.tuple_operand_index >= stack_infos.len() {
1731                continue;
1732            }
1733            let tuple_info = &stack_infos[sig.tuple_operand_index];
1734            let shape_matches = tuple_info
1735                .value_type
1736                .tuple_elements()
1737                .is_some_and(|elements| {
1738                    elements.len() == sig.shape.len()
1739                        && elements
1740                            .iter()
1741                            .zip(&sig.shape)
1742                            .all(|(a, t)| a.value_type.type_id() == *t)
1743                });
1744            if !shape_matches {
1745                continue;
1746            }
1747            let others_match = stack_infos.iter().enumerate().all(|(i, info)| {
1748                i == sig.tuple_operand_index
1749                    || sig.operand_type_ids.get(i) == Some(&info.value_type.type_id())
1750            });
1751            if others_match {
1752                (sig.op_fn)(segment, span)?;
1753                return Ok(true);
1754            }
1755        }
1756        Ok(false)
1757    }
1758
1759    /// Pushes a new scope onto the stack.
1760    ///
1761    /// Accepts a closure directly; it is boxed internally. The scope should return
1762    /// `Ok(true)` if it handled the operation, `Ok(false)` to pass to the next scope,
1763    /// or `Err` on error. Error messages surface verbatim; they should be lowercase, end
1764    /// without a period, and wrap identifiers and type names in backticks.
1765    ///
1766    /// - Complexity: Amortized O(1) registration, including owned callback storage.
1767    ///
1768    /// # Examples
1769    /// ```
1770    /// use cel_parser::OpLookup;
1771    /// use cel_runtime::DynSegment;
1772    /// use proc_macro2::Span;
1773    /// let mut lookup = OpLookup::new();
1774    /// lookup.push_library_scope(|name, segment, arity, _| {
1775    ///     if name == "answer" && arity == 0 {
1776    ///         segment.just(42i32);
1777    ///         Ok(true)
1778    ///     } else {
1779    ///         Ok(false)
1780    ///     }
1781    /// });
1782    /// lookup.push_scope(|_, _, _, _| Ok(false));
1783    /// assert!(lookup.pop_scope().is_some());
1784    /// let mut segment = DynSegment::new::<()>();
1785    /// lookup.lookup("answer", &mut segment, 0, Span::call_site(), Span::call_site()).unwrap();
1786    /// assert_eq!(segment.call0::<i32>().unwrap(), 42);
1787    /// ```
1788    pub fn push_scope<F>(&mut self, scope: F)
1789    where
1790        F: Fn(&str, &mut DynSegment, usize, SourceSpan) -> Result<bool> + Send + Sync + 'static,
1791    {
1792        self.scopes.push(Box::new(scope));
1793    }
1794
1795    /// Pops the most recent scope from the stack.
1796    ///
1797    /// Returns the popped scope, or `None` if the stack is empty.
1798    ///
1799    /// - Precondition: must not remove a library scope registered via
1800    ///   [`push_library_scope`](Self::push_library_scope) — those are permanent setup-time
1801    ///   registrations that must survive across multiple parses.
1802    ///
1803    /// # Examples
1804    /// See [`Self::push_scope`] for adding and removing a transient scope without removing a library.
1805    pub fn pop_scope(&mut self) -> Option<ScopeFn> {
1806        debug_assert!(
1807            self.scopes.len() > self.library_scope_count,
1808            "pop_scope must not remove a library scope — use isolate_scopes/restore_scopes semantics instead"
1809        );
1810        self.scopes.pop()
1811    }
1812
1813    /// Registers a permanent, library-level scope that is reachable from every parse,
1814    /// including inside closure bodies.
1815    ///
1816    /// Used for built-in language features and statically-installed library
1817    /// functions (like `round` and `clamp` from a `cel-std`-style crate). These scopes are registered
1818    /// once at setup time and must always be available, even when [`isolate_scopes`](Self::isolate_scopes)
1819    /// is active — library scopes are *never* isolated.
1820    ///
1821    /// Do not use for scopes tied to a single parse's lifetime — use [`push_scope`](Self::push_scope)
1822    /// for those, which can be isolated during nested body compilation (closures).
1823    ///
1824    /// - Precondition: no transient scopes are installed.
1825    /// - Complexity: Amortized O(1) registration, including owned callback storage.
1826    ///
1827    /// # Examples
1828    /// See [`Self::push_scope`] for permanent and transient registrations.
1829    pub fn push_library_scope<F>(&mut self, scope: F)
1830    where
1831        F: Fn(&str, &mut DynSegment, usize, SourceSpan) -> Result<bool> + Send + Sync + 'static,
1832    {
1833        debug_assert!(
1834            self.scopes.len() == self.library_scope_count,
1835            "push_library_scope must not be called after a transient scope — use isolate_scopes/restore_scopes semantics instead"
1836        );
1837        self.scopes.push(Box::new(scope));
1838        self.library_scope_count = self.scopes.len();
1839    }
1840
1841    /// Temporarily removes every transient scope (those pushed via [`push_scope`](Self::push_scope)),
1842    /// returning them so a later [`restore_scopes`](Self::restore_scopes) call can put them back.
1843    /// Library scopes registered via [`push_library_scope`](Self::push_library_scope) are *never*
1844    /// isolated and remain reachable.
1845    ///
1846    /// Used when compiling an independent nested body (a closure literal) that must resolve names
1847    /// against only its own declared parameters and library functions (like `round`, `clamp`) —
1848    /// never whatever transient per-parse scopes happen to be active. This maintains the invariant
1849    /// that library functions are always available, including inside closures, while per-declaration
1850    /// scopes (which tie to a single outer parse's lifetime) are hidden from nested bodies.
1851    ///
1852    /// - Postcondition: library scopes remain reachable; transient scopes are inaccessible until
1853    ///   [`restore_scopes`](Self::restore_scopes) is called.
1854    ///
1855    /// # Examples
1856    ///
1857    /// ```rust
1858    /// use cel_parser::OpLookup;
1859    /// use cel_runtime::DynSegment;
1860    ///
1861    /// let mut lookup = OpLookup::new();
1862    /// lookup.push_scope(|name, segment, arity, _span| {
1863    ///     if name == "custom" && arity == 0 {
1864    ///         segment.just(42i32);
1865    ///         Ok(true)
1866    ///     } else {
1867    ///         Ok(false)
1868    ///     }
1869    /// });
1870    ///
1871    /// let saved = lookup.isolate_scopes();
1872    /// // Now the custom scope is inaccessible
1873    /// let mut segment = DynSegment::new::<()>();
1874    /// let result = lookup.lookup("custom", &mut segment, 0, proc_macro2::Span::call_site(), proc_macro2::Span::call_site());
1875    /// assert!(result.is_err());
1876    ///
1877    /// lookup.restore_scopes(saved);
1878    /// // Now the custom scope is reachable again
1879    /// let mut segment = DynSegment::new::<()>();
1880    /// let result = lookup.lookup("custom", &mut segment, 0, proc_macro2::Span::call_site(), proc_macro2::Span::call_site());
1881    /// assert!(result.is_ok());
1882    /// ```
1883    pub fn isolate_scopes(&mut self) -> Vec<ScopeFn> {
1884        self.scopes.split_off(self.library_scope_count)
1885    }
1886
1887    /// Restores a scope stack previously removed by [`isolate_scopes`](Self::isolate_scopes),
1888    /// discarding whatever scopes were pushed while isolated.
1889    ///
1890    /// Library scopes (those registered via [`push_library_scope`](Self::push_library_scope))
1891    /// are unaffected by isolation and restoration — they persist across the entire operation.
1892    ///
1893    /// - Precondition: `scopes` came from a matching `isolate_scopes()` call on this same
1894    ///   `OpLookup` — restoring an arbitrary `Vec<ScopeFn>` is well-typed but not a meaningful use
1895    ///   of this method.
1896    ///
1897    /// # Examples
1898    ///
1899    /// ```rust
1900    /// use cel_parser::OpLookup;
1901    /// use cel_runtime::DynSegment;
1902    ///
1903    /// let mut lookup = OpLookup::new();
1904    /// lookup.push_scope(|name, segment, arity, _span| {
1905    ///     if name == "outer" && arity == 0 {
1906    ///         segment.just(100i32);
1907    ///         Ok(true)
1908    ///     } else {
1909    ///         Ok(false)
1910    ///     }
1911    /// });
1912    ///
1913    /// let saved = lookup.isolate_scopes();
1914    /// lookup.restore_scopes(saved);
1915    /// // The outer scope is now reachable again
1916    /// ```
1917    pub fn restore_scopes(&mut self, scopes: Vec<ScopeFn>) {
1918        self.scopes.truncate(self.library_scope_count);
1919        self.scopes.extend(scopes);
1920    }
1921
1922    /// Looks up and applies an operation, attaching the expression span to any error.
1923    ///
1924    /// Searches scopes in LIFO order, then persistent named registrations, tuple
1925    /// signatures, and built-in operations.
1926    ///
1927    /// # Errors
1928    ///
1929    /// Returns a [`crate::ParseError`] spanning `start..=end` if no scope or built-in
1930    /// handles the request, or if a scope itself returns an error.
1931    ///
1932    /// - Complexity: O(k) in the number of registered scopes, plus O(s) for the built-in
1933    ///   signature scan where s is the number of signatures for the operator.
1934    ///
1935    /// # Examples
1936    ///
1937    /// ```rust
1938    /// use proc_macro2::Span;
1939    /// use cel_parser::OpLookup;
1940    /// use cel_runtime::DynSegment;
1941    ///
1942    /// let lookup = OpLookup::new();
1943    /// let mut seg = DynSegment::new::<()>();
1944    /// // A lookup with zero operands for a known operator succeeds when types match.
1945    /// // This example shows the signature only; real usage requires pushed types.
1946    /// let result = lookup.lookup("+", &mut seg, 2, Span::call_site(), Span::call_site());
1947    /// // result is Err because no operands are on the segment
1948    /// assert!(result.is_err());
1949    /// ```
1950    pub fn lookup(
1951        &self,
1952        name: &str,
1953        segment: &mut DynSegment,
1954        num_operands: usize,
1955        start: proc_macro2::Span,
1956        end: proc_macro2::Span,
1957    ) -> std::result::Result<(), crate::ParseError> {
1958        self.lookup_scoped(
1959            name,
1960            segment,
1961            num_operands,
1962            crate::ExprSpan { start, end },
1963            false,
1964            false,
1965        )
1966    }
1967
1968    /// Applies a direct named operation without looking up a zero-arity value binding.
1969    ///
1970    /// Scopes retain LIFO precedence for nonzero operand counts; registered operations,
1971    /// tuple signatures and built-ins provide the fallbacks. A declined signature
1972    /// leaves the stack unchanged.
1973    ///
1974    /// # Errors
1975    /// Returns a spanned error if no operation matches or an emitter fails.
1976    ///
1977    /// - Complexity: O(k + s * a * d) for k scopes, s signatures, a operands
1978    ///   and descriptor depth d.
1979    ///
1980    /// # Examples
1981    /// ```
1982    /// use cel_parser::OpLookup;
1983    /// use cel_runtime::DynSegment;
1984    /// use proc_macro2::Span;
1985    /// let mut segment = DynSegment::new::<()>();
1986    /// segment.just(1u32);
1987    /// segment.just(2u32);
1988    /// OpLookup::new().lookup_member("+", &mut segment, 2,
1989    ///     Span::call_site(), Span::call_site()).unwrap();
1990    /// assert_eq!(segment.call0::<u32>().unwrap(), 3);
1991    /// ```
1992    pub fn lookup_member(
1993        &self,
1994        name: &str,
1995        segment: &mut DynSegment,
1996        arity: usize,
1997        start: proc_macro2::Span,
1998        end: proc_macro2::Span,
1999    ) -> crate::Result<()> {
2000        self.lookup_scoped(
2001            name,
2002            segment,
2003            arity,
2004            crate::ExprSpan { start, end },
2005            true,
2006            false,
2007        )
2008    }
2009
2010    /// Resolves direct operations with either all scopes or only persistent library scopes.
2011    ///
2012    /// Zero-operand dispatch skips scopes, which cannot distinguish value bindings
2013    /// from direct operations at that arity.
2014    ///
2015    /// # Errors
2016    /// Returns the selected scope or registered emitter error.
2017    /// - Complexity: O(k + s * a * d) for k scopes, s signatures, a operands and depth d.
2018    pub(crate) fn lookup_direct_operation_scoped(
2019        &self,
2020        name: &str,
2021        segment: &mut DynSegment,
2022        arity: usize,
2023        span: SourceSpan,
2024        library_only: bool,
2025    ) -> Result<bool> {
2026        if arity > 0 {
2027            let scopes = if library_only {
2028                &self.scopes[..self.library_scope_count]
2029            } else {
2030                &self.scopes
2031            };
2032            for scope in scopes.iter().rev() {
2033                if scope(name, segment, arity, span)? {
2034                    return Ok(true);
2035                }
2036            }
2037        }
2038        self.lookup_registered_operation(name, segment, arity, span)
2039    }
2040
2041    /// Applies scoped lookup with either ordinary callable or operation-only dispatch.
2042    ///
2043    /// - Complexity: O(k + s * a * d) for k scopes, s signatures, a operands
2044    ///   and descriptor depth d.
2045    pub(crate) fn lookup_scoped(
2046        &self,
2047        name: &str,
2048        segment: &mut DynSegment,
2049        num_operands: usize,
2050        span: crate::ExprSpan,
2051        member: bool,
2052        library_only: bool,
2053    ) -> crate::Result<()> {
2054        let crate::ExprSpan { start, end } = span;
2055        let source_span = SourceSpan::from_proc_macro2_range(start, end);
2056        let scopes = if library_only {
2057            &self.scopes[..self.library_scope_count]
2058        } else {
2059            &self.scopes
2060        };
2061        for scope in scopes.iter().rev().filter(|_| !member) {
2062            match scope(name, segment, num_operands, source_span) {
2063                Ok(true) => return Ok(()),
2064                Ok(false) => {}
2065                Err(e) => return Err(crate::ParseError::new_range(e.to_string(), start, end)),
2066            }
2067        }
2068
2069        let registered = if member {
2070            self.lookup_direct_operation_scoped(
2071                name,
2072                segment,
2073                num_operands,
2074                source_span,
2075                library_only,
2076            )
2077        } else {
2078            self.lookup_registered(name, segment, num_operands, source_span, library_only)
2079        };
2080        match registered {
2081            Ok(true) => return Ok(()),
2082            Ok(false) => {}
2083            Err(error) => return Err(crate::ParseError::new_range(error.to_string(), start, end)),
2084        }
2085
2086        match self.lookup_tuple_signature(name, segment, num_operands, source_span) {
2087            Ok(true) => return Ok(()),
2088            Ok(false) => {}
2089            Err(e) => {
2090                return Err(crate::ParseError::new_range(
2091                    format!("operation error: {}", e),
2092                    start,
2093                    end,
2094                ));
2095            }
2096        }
2097
2098        match self
2099            .builtin_scope
2100            .lookup(name, segment, num_operands, source_span)
2101        {
2102            Ok(true) => return Ok(()),
2103            Ok(false) => {}
2104            Err(e) => {
2105                return Err(crate::ParseError::new_range(
2106                    format!("operation error: {}", e),
2107                    start,
2108                    end,
2109                ));
2110            }
2111        }
2112
2113        if !member
2114            && name == "()"
2115            && num_operands > 0
2116            && segment
2117                .peek_stack_infos(num_operands)
2118                .first()
2119                .is_some_and(|info| {
2120                    info.value_type.type_id() == TypeId::of::<cel_runtime::DynClosure>()
2121                })
2122        {
2123            return segment
2124                .invoke_closure(num_operands - 1)
2125                .map_err(|error| crate::ParseError::new_range(error.to_string(), start, end));
2126        }
2127
2128        if num_operands == 0 {
2129            return Err(crate::ParseError::new(
2130                format!("undefined identifier: `{name}`"),
2131                start,
2132            ));
2133        }
2134        let infos = segment.peek_stack_infos(num_operands);
2135        let mut type_names = String::new();
2136        for (i, info) in infos.iter().enumerate() {
2137            if i > 0 {
2138                type_names.push_str(", ");
2139            }
2140            type_names.push('`');
2141            type_names.push_str(info.value_type.type_name());
2142            type_names.push('`');
2143        }
2144        Err(crate::ParseError::new_range(
2145            format!("no operation `{name}` for types [{type_names}]"),
2146            start,
2147            end,
2148        ))
2149    }
2150
2151    /// Looks up and applies a cast (`expr as Type`), attaching the expression span to any error.
2152    ///
2153    /// - Postcondition: on success, an operation is queued onto `segment` that replaces its
2154    ///   top-of-stack operand with the converted value once the segment is run (e.g. via
2155    ///   [`DynSegment::call0`]) - like every other op this crate queues rather than executes
2156    ///   immediately.
2157    ///
2158    /// # Errors
2159    ///
2160    /// Returns a [`crate::ParseError`] spanning `start..=end` if `segment`'s stack is empty, if
2161    /// `type_name` isn't a recognized cast-target type, or if no cast from the operand's type to
2162    /// it is registered. A registered conversion's own value-range failure (e.g. an out-of-range
2163    /// or non-finite value) is deferred to execution - it surfaces from running the segment, not
2164    /// from this function (see `cast_errors_when_the_value_does_not_fit_in_the_target_type`
2165    /// below).
2166    ///
2167    /// - Complexity: O(s) in the number of registered sources for `type_name`.
2168    ///
2169    /// # Examples
2170    ///
2171    /// ```rust
2172    /// use proc_macro2::Span;
2173    /// use cel_parser::OpLookup;
2174    /// use cel_runtime::DynSegment;
2175    ///
2176    /// let lookup = OpLookup::new();
2177    /// let mut seg = DynSegment::new::<()>();
2178    /// seg.just(1024i32);
2179    /// lookup
2180    ///     .lookup_cast("f64", &mut seg, Span::call_site(), Span::call_site())
2181    ///     .unwrap();
2182    /// assert_eq!(seg.call0::<f64>().unwrap(), 1024.0);
2183    /// ```
2184    pub fn lookup_cast(
2185        &self,
2186        type_name: &str,
2187        segment: &mut DynSegment,
2188        start: proc_macro2::Span,
2189        end: proc_macro2::Span,
2190    ) -> std::result::Result<(), crate::ParseError> {
2191        let source_span = SourceSpan::from_proc_macro2_range(start, end);
2192        let Some(signatures) = signatures_for_cast(type_name) else {
2193            return Err(crate::ParseError::new_range(
2194                format!("unknown type `{type_name}`"),
2195                start,
2196                end,
2197            ));
2198        };
2199        let Some(operand) = segment.peek_stack_infos(1).first() else {
2200            return Err(crate::ParseError::new_range(
2201                "cast requires an operand on the stack".to_string(),
2202                start,
2203                end,
2204            ));
2205        };
2206        let source_type_id = operand.value_type.type_id();
2207        for sig in signatures {
2208            if sig.source_type_id() == source_type_id {
2209                (sig.op_fn)(segment, source_span).map_err(|e| {
2210                    crate::ParseError::new_range(format!("cast error: {}", e), start, end)
2211                })?;
2212                return Ok(());
2213            }
2214        }
2215        Err(crate::ParseError::new_range(
2216            format!(
2217                "no cast from `{}` to `{type_name}`",
2218                operand.value_type.type_name()
2219            ),
2220            start,
2221            end,
2222        ))
2223    }
2224}
2225
2226impl Default for OpLookup {
2227    fn default() -> Self {
2228        Self::new()
2229    }
2230}
2231
2232#[cfg(test)]
2233mod tests {
2234    use super::*;
2235    use proc_macro2::Span;
2236
2237    type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
2238
2239    #[test]
2240    fn test_addition_u32() -> Result<()> {
2241        let lookup = OpLookup::new();
2242        let mut segment = DynSegment::new::<()>();
2243        segment.just(10u32);
2244        segment.just(20u32);
2245        lookup.lookup("+", &mut segment, 2, Span::call_site(), Span::call_site())?;
2246        assert_eq!(segment.call0::<u32>()?, 30);
2247        Ok(())
2248    }
2249
2250    #[test]
2251    fn test_subtraction_i32() -> Result<()> {
2252        let lookup = OpLookup::new();
2253        let mut segment = DynSegment::new::<()>();
2254        segment.just(50i32);
2255        segment.just(20i32);
2256        lookup.lookup("-", &mut segment, 2, Span::call_site(), Span::call_site())?;
2257        assert_eq!(segment.call0::<i32>()?, 30);
2258        Ok(())
2259    }
2260
2261    #[test]
2262    fn test_arithmetic_overflow() -> Result<()> {
2263        let lookup = OpLookup::new();
2264        let mut segment = DynSegment::new::<()>();
2265        segment.just(i32::MAX);
2266        segment.just(1i32);
2267        lookup.lookup("+", &mut segment, 2, Span::call_site(), Span::call_site())?;
2268        let result = segment.call0::<i32>();
2269        assert!(result.is_err());
2270        let err = result.unwrap_err();
2271        let message = format!("{:#}", err);
2272        assert!(
2273            message.contains("arithmetic overflow"),
2274            "error message should mention arithmetic overflow, got: {message}"
2275        );
2276        Ok(())
2277    }
2278
2279    #[test]
2280    fn test_division_by_zero() -> Result<()> {
2281        let lookup = OpLookup::new();
2282        let mut segment = DynSegment::new::<()>();
2283        segment.just(10i32);
2284        segment.just(0i32);
2285        lookup.lookup("/", &mut segment, 2, Span::call_site(), Span::call_site())?;
2286        let result = segment.call0::<i32>();
2287        assert!(result.is_err());
2288        let err = result.unwrap_err();
2289        let message = format!("{:#}", err);
2290        assert!(
2291            message.contains("division by zero"),
2292            "error message should mention division by zero, got: {message}"
2293        );
2294        Ok(())
2295    }
2296
2297    #[test]
2298    fn test_modulo_by_zero() -> Result<()> {
2299        let lookup = OpLookup::new();
2300        let mut segment = DynSegment::new::<()>();
2301        segment.just(10u32);
2302        segment.just(0u32);
2303        lookup.lookup("%", &mut segment, 2, Span::call_site(), Span::call_site())?;
2304        let result = segment.call0::<u32>();
2305        assert!(result.is_err());
2306        let err = result.unwrap_err();
2307        let message = format!("{:#}", err);
2308        assert!(
2309            message.contains("division by zero"),
2310            "error message should mention division by zero, got: {message}"
2311        );
2312        Ok(())
2313    }
2314
2315    #[test]
2316    fn test_multiplication_f64() -> Result<()> {
2317        let lookup = OpLookup::new();
2318        let mut segment = DynSegment::new::<()>();
2319        segment.just(3.5f64);
2320        segment.just(2.0f64);
2321        lookup.lookup("*", &mut segment, 2, Span::call_site(), Span::call_site())?;
2322        assert_eq!(segment.call0::<f64>()?, 7.0);
2323        Ok(())
2324    }
2325
2326    #[test]
2327    fn test_comparison_less_than() -> Result<()> {
2328        let lookup = OpLookup::new();
2329        let mut segment = DynSegment::new::<()>();
2330        segment.just(10u32);
2331        segment.just(20u32);
2332        lookup.lookup("<", &mut segment, 2, Span::call_site(), Span::call_site())?;
2333        assert!(segment.call0::<bool>()?);
2334        Ok(())
2335    }
2336
2337    #[test]
2338    fn test_bitwise_and() -> Result<()> {
2339        let lookup = OpLookup::new();
2340        let mut segment = DynSegment::new::<()>();
2341        segment.just(0b1010u32);
2342        segment.just(0b1100u32);
2343        lookup.lookup("&", &mut segment, 2, Span::call_site(), Span::call_site())?;
2344        assert_eq!(segment.call0::<u32>()?, 0b1000);
2345        Ok(())
2346    }
2347
2348    #[test]
2349    fn test_unary_negation() -> Result<()> {
2350        let lookup = OpLookup::new();
2351        let mut segment = DynSegment::new::<()>();
2352        segment.just(42i32);
2353        lookup.lookup("-", &mut segment, 1, Span::call_site(), Span::call_site())?;
2354        assert_eq!(segment.call0::<i32>()?, -42);
2355        Ok(())
2356    }
2357
2358    #[test]
2359    fn test_logical_not() -> Result<()> {
2360        let lookup = OpLookup::new();
2361        let mut segment = DynSegment::new::<()>();
2362        segment.just(true);
2363        lookup.lookup("!", &mut segment, 1, Span::call_site(), Span::call_site())?;
2364        assert!(!segment.call0::<bool>()?);
2365        Ok(())
2366    }
2367
2368    #[test]
2369    fn test_unregistered_operation() {
2370        let lookup = OpLookup::new();
2371        let mut segment = DynSegment::new::<()>();
2372        segment.just(10u32);
2373        segment.just(20u32);
2374        let result = lookup.lookup(
2375            "unknown_op",
2376            &mut segment,
2377            2,
2378            Span::call_site(),
2379            Span::call_site(),
2380        );
2381        assert!(result.is_err());
2382    }
2383
2384    #[test]
2385    fn test_custom_scope() -> Result<()> {
2386        let mut lookup = OpLookup::new();
2387
2388        lookup.push_scope(|name, segment, num_operands, _span| {
2389            let matches = {
2390                let top = segment.peek_stack_infos(num_operands);
2391                name == "double"
2392                    && top.len() == 1
2393                    && top[0].value_type.type_id() == TypeId::of::<u32>()
2394            };
2395            if matches {
2396                segment.op1(|a: u32| a * 2)?;
2397                Ok(true)
2398            } else {
2399                Ok(false)
2400            }
2401        });
2402
2403        let mut segment = DynSegment::new::<()>();
2404        segment.just(21u32);
2405        lookup.lookup(
2406            "double",
2407            &mut segment,
2408            1,
2409            Span::call_site(),
2410            Span::call_site(),
2411        )?;
2412        assert_eq!(segment.call0::<u32>()?, 42);
2413
2414        Ok(())
2415    }
2416
2417    #[test]
2418    fn test_scope_override() -> Result<()> {
2419        let mut lookup = OpLookup::new();
2420
2421        lookup.push_scope(|name, segment, num_operands, _span| {
2422            let matches = {
2423                let top = segment.peek_stack_infos(num_operands);
2424                name == "+" && top.len() == 2 && top[0].value_type.type_id() == TypeId::of::<u32>()
2425            };
2426            if matches {
2427                segment.op2(|_a: u32, _b: u32| 100u32)?;
2428                Ok(true)
2429            } else {
2430                Ok(false)
2431            }
2432        });
2433
2434        let mut segment = DynSegment::new::<()>();
2435        segment.just(10u32);
2436        segment.just(20u32);
2437        lookup.lookup("+", &mut segment, 2, Span::call_site(), Span::call_site())?;
2438        assert_eq!(segment.call0::<u32>()?, 100);
2439
2440        Ok(())
2441    }
2442
2443    #[test]
2444    fn lookup_cast_errors_rather_than_panics_on_an_empty_stack() -> Result<()> {
2445        // Regression test: `lookup_cast` used to index `peek_stack_infos(1)[0]` unconditionally,
2446        // which panicked (rather than returning a `ParseError`) when the stack was empty -
2447        // reachable directly through this public API without going through the grammar, which
2448        // always pushes the operand first.
2449        let lookup = OpLookup::new();
2450        let mut segment = DynSegment::new::<()>();
2451        let result = lookup.lookup_cast("i32", &mut segment, Span::call_site(), Span::call_site());
2452        assert!(result.is_err());
2453        Ok(())
2454    }
2455
2456    #[test]
2457    fn cast_widens_i32_to_f64_exactly() -> Result<()> {
2458        let lookup = OpLookup::new();
2459        let mut segment = DynSegment::new::<()>();
2460        segment.just(1024i32);
2461        lookup.lookup_cast("f64", &mut segment, Span::call_site(), Span::call_site())?;
2462        assert_eq!(segment.call0::<f64>()?, 1024.0);
2463        Ok(())
2464    }
2465
2466    #[test]
2467    fn cast_narrows_f64_to_i32_when_the_value_fits() -> Result<()> {
2468        let lookup = OpLookup::new();
2469        let mut segment = DynSegment::new::<()>();
2470        segment.just(1024.0f64);
2471        lookup.lookup_cast("i32", &mut segment, Span::call_site(), Span::call_site())?;
2472        assert_eq!(segment.call0::<i32>()?, 1024);
2473        Ok(())
2474    }
2475
2476    #[test]
2477    fn cast_errors_when_the_value_does_not_fit_in_the_target_type() -> Result<()> {
2478        // lookup_cast's own Result only reports type-checking failures (unknown type, no
2479        // registered source) - a checked cast's own out-of-range failure is deferred to
2480        // execution, same as any other fallible op (see DynSegment::op1r's doc comment), so
2481        // it's asserted via call0.
2482        let lookup = OpLookup::new();
2483        let mut segment = DynSegment::new::<()>();
2484        segment.just(1.0e20f64);
2485        lookup.lookup_cast("i32", &mut segment, Span::call_site(), Span::call_site())?;
2486        assert!(segment.call0::<i32>().is_err());
2487        Ok(())
2488    }
2489
2490    #[test]
2491    fn cast_errors_just_past_the_target_types_max_even_when_max_is_not_exactly_representable()
2492    -> Result<()> {
2493        // Regression test: `i32::MAX as f32` isn't exactly representable (f32's 24-bit mantissa
2494        // can't hold all 31 value bits) and rounds *up* to exactly `i32::MAX as i64 + 1`
2495        // (2147483648.0, a power of two). A bound check comparing against that rounded value
2496        // with `>` would let this value silently pass, then Rust's saturating `as` would turn it
2497        // into `i32::MAX` instead of the `Err` a genuinely out-of-range value should produce.
2498        let lookup = OpLookup::new();
2499        let mut segment = DynSegment::new::<()>();
2500        segment.just(2147483648.0f32); // i32::MAX + 1, exactly representable in f32
2501        lookup.lookup_cast("i32", &mut segment, Span::call_site(), Span::call_site())?;
2502        assert!(segment.call0::<i32>().is_err());
2503        Ok(())
2504    }
2505
2506    #[test]
2507    fn cast_accepts_the_target_types_actual_max_value() -> Result<()> {
2508        let lookup = OpLookup::new();
2509        let mut segment = DynSegment::new::<()>();
2510        segment.just(2147483520.0f32); // largest f32 value below i32::MAX + 1
2511        lookup.lookup_cast("i32", &mut segment, Span::call_site(), Span::call_site())?;
2512        assert_eq!(segment.call0::<i32>()?, 2147483520);
2513        Ok(())
2514    }
2515
2516    #[test]
2517    fn cast_errors_just_past_i64_max_from_f64() -> Result<()> {
2518        // Same rounding pitfall as the f32 -> i32 case above, but for the f64 -> i64 pair (f64's
2519        // 53-bit mantissa can't hold i64's 63 value bits either).
2520        let lookup = OpLookup::new();
2521        let mut segment = DynSegment::new::<()>();
2522        segment.just(9223372036854775808.0f64); // i64::MAX + 1, exactly representable in f64
2523        lookup.lookup_cast("i64", &mut segment, Span::call_site(), Span::call_site())?;
2524        assert!(segment.call0::<i64>().is_err());
2525        Ok(())
2526    }
2527
2528    #[test]
2529    fn cast_errors_for_an_unknown_target_type() -> Result<()> {
2530        let lookup = OpLookup::new();
2531        let mut segment = DynSegment::new::<()>();
2532        segment.just(1i32);
2533        let result = lookup.lookup_cast(
2534            "nonsense",
2535            &mut segment,
2536            Span::call_site(),
2537            Span::call_site(),
2538        );
2539        assert!(result.is_err());
2540        Ok(())
2541    }
2542
2543    #[test]
2544    fn cast_errors_for_an_unregistered_source_type() -> Result<()> {
2545        // String -> i32 has no registered cast: Rust's own `as` has no conversion from `String`
2546        // to anything (see the "Casts" section's doc comment).
2547        let lookup = OpLookup::new();
2548        let mut segment = DynSegment::new::<()>();
2549        segment.just("1".to_string());
2550        let result = lookup.lookup_cast("i32", &mut segment, Span::call_site(), Span::call_site());
2551        assert!(result.is_err());
2552        Ok(())
2553    }
2554
2555    #[test]
2556    fn cast_from_bool_is_registered_for_every_integer_width() -> Result<()> {
2557        // Matches Rust's own `bool as <int>`: infallible for all 12 integer widths.
2558        let lookup = OpLookup::new();
2559        for target in [
2560            "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize",
2561        ] {
2562            let mut segment = DynSegment::new::<()>();
2563            segment.just(true);
2564            lookup.lookup_cast(target, &mut segment, Span::call_site(), Span::call_site())?;
2565        }
2566        Ok(())
2567    }
2568
2569    #[test]
2570    fn cast_widens_bool_to_a_specific_integer_value() -> Result<()> {
2571        // Matches Rust's own `bool as <int>`: `true` -> 1, `false` -> 0.
2572        let lookup = OpLookup::new();
2573        let mut segment = DynSegment::new::<()>();
2574        segment.just(true);
2575        lookup.lookup_cast("i32", &mut segment, Span::call_site(), Span::call_site())?;
2576        assert_eq!(segment.call0::<i32>()?, 1);
2577
2578        let mut segment = DynSegment::new::<()>();
2579        segment.just(false);
2580        lookup.lookup_cast("u64", &mut segment, Span::call_site(), Span::call_site())?;
2581        assert_eq!(segment.call0::<u64>()?, 0);
2582        Ok(())
2583    }
2584
2585    #[test]
2586    fn cast_bool_to_bool_is_a_no_op_identity_conversion() -> Result<()> {
2587        let lookup = OpLookup::new();
2588        let mut segment = DynSegment::new::<()>();
2589        segment.just(true);
2590        lookup.lookup_cast("bool", &mut segment, Span::call_site(), Span::call_site())?;
2591        assert!(segment.call0::<bool>()?);
2592        Ok(())
2593    }
2594
2595    #[test]
2596    fn cast_string_to_string_is_a_no_op_identity_conversion() -> Result<()> {
2597        let lookup = OpLookup::new();
2598        let mut segment = DynSegment::new::<()>();
2599        segment.just("hello".to_string());
2600        lookup.lookup_cast("String", &mut segment, Span::call_site(), Span::call_site())?;
2601        assert_eq!(segment.call0::<String>()?, "hello");
2602        Ok(())
2603    }
2604
2605    #[test]
2606    fn cast_errors_from_a_number_to_bool() -> Result<()> {
2607        // Rust's own `as` rejects `<int> as bool` (E0054) - no int/float -> bool conversion is
2608        // registered, matching Rust exactly, not just "unknown type".
2609        let lookup = OpLookup::new();
2610        let mut segment = DynSegment::new::<()>();
2611        segment.just(1i32);
2612        let result = lookup.lookup_cast("bool", &mut segment, Span::call_site(), Span::call_site());
2613        assert!(result.is_err());
2614        Ok(())
2615    }
2616
2617    #[test]
2618    fn cast_errors_from_bool_to_a_float() -> Result<()> {
2619        // Rust's own `as` rejects `bool as f64` (E0606: "cast through an integer first").
2620        let lookup = OpLookup::new();
2621        let mut segment = DynSegment::new::<()>();
2622        segment.just(true);
2623        let result = lookup.lookup_cast("f64", &mut segment, Span::call_site(), Span::call_site());
2624        assert!(result.is_err());
2625        Ok(())
2626    }
2627
2628    #[test]
2629    fn cast_errors_between_string_and_bool_in_both_directions() -> Result<()> {
2630        let lookup = OpLookup::new();
2631        let mut segment = DynSegment::new::<()>();
2632        segment.just(true);
2633        assert!(
2634            lookup
2635                .lookup_cast("String", &mut segment, Span::call_site(), Span::call_site())
2636                .is_err()
2637        );
2638
2639        let mut segment = DynSegment::new::<()>();
2640        segment.just("true".to_string());
2641        assert!(
2642            lookup
2643                .lookup_cast("bool", &mut segment, Span::call_site(), Span::call_site())
2644                .is_err()
2645        );
2646        Ok(())
2647    }
2648
2649    #[test]
2650    fn cast_errors_between_string_and_numbers_in_both_directions() -> Result<()> {
2651        let lookup = OpLookup::new();
2652        let mut segment = DynSegment::new::<()>();
2653        segment.just(1i32);
2654        assert!(
2655            lookup
2656                .lookup_cast("String", &mut segment, Span::call_site(), Span::call_site())
2657                .is_err()
2658        );
2659
2660        let mut segment = DynSegment::new::<()>();
2661        segment.just("1".to_string());
2662        assert!(
2663            lookup
2664                .lookup_cast("i32", &mut segment, Span::call_site(), Span::call_site())
2665                .is_err()
2666        );
2667        Ok(())
2668    }
2669
2670    #[test]
2671    fn test_left_shift_u64() -> Result<()> {
2672        let lookup = OpLookup::new();
2673        let mut segment = DynSegment::new::<()>();
2674        segment.just(1u64);
2675        segment.just(3u32);
2676        lookup.lookup("<<", &mut segment, 2, Span::call_site(), Span::call_site())?;
2677        assert_eq!(segment.call0::<u64>()?, 8);
2678        Ok(())
2679    }
2680
2681    #[test]
2682    fn test_right_shift_i32() -> Result<()> {
2683        let lookup = OpLookup::new();
2684        let mut segment = DynSegment::new::<()>();
2685        segment.just(16i32);
2686        segment.just(2u32);
2687        lookup.lookup(">>", &mut segment, 2, Span::call_site(), Span::call_site())?;
2688        assert_eq!(segment.call0::<i32>()?, 4);
2689        Ok(())
2690    }
2691
2692    #[test]
2693    fn test_shift_overflow() -> Result<()> {
2694        let lookup = OpLookup::new();
2695        let mut segment = DynSegment::new::<()>();
2696        segment.just(1u32);
2697        segment.just(32u32);
2698        lookup.lookup("<<", &mut segment, 2, Span::call_site(), Span::call_site())?;
2699        let result = segment.call0::<u32>();
2700        assert!(result.is_err());
2701        let err = result.unwrap_err();
2702        let message = format!("{:#}", err);
2703        assert!(
2704            message.contains("shift overflow"),
2705            "error message should mention shift overflow, got: {message}"
2706        );
2707        Ok(())
2708    }
2709
2710    #[test]
2711    fn test_shift_i32_rhs() -> Result<()> {
2712        let lookup = OpLookup::new();
2713        let mut segment = DynSegment::new::<()>();
2714        segment.just(1u32);
2715        segment.just(3i32);
2716        lookup.lookup("<<", &mut segment, 2, Span::call_site(), Span::call_site())?;
2717        assert_eq!(segment.call0::<u32>()?, 8);
2718        Ok(())
2719    }
2720
2721    #[test]
2722    fn test_shift_negative_rhs_errors() -> Result<()> {
2723        let lookup = OpLookup::new();
2724        let mut segment = DynSegment::new::<()>();
2725        segment.just(1u32);
2726        segment.just(-1i32);
2727        lookup.lookup("<<", &mut segment, 2, Span::call_site(), Span::call_site())?;
2728        let result = segment.call0::<u32>();
2729        assert!(result.is_err());
2730        let err = result.unwrap_err();
2731        let message = format!("{:#}", err);
2732        assert!(message.contains("shift overflow"), "got: {message}");
2733        Ok(())
2734    }
2735
2736    #[test]
2737    fn test_shift_wide_rhs_overflow_errors() -> Result<()> {
2738        let lookup = OpLookup::new();
2739        let mut segment = DynSegment::new::<()>();
2740        segment.just(1u32);
2741        segment.just(u32::MAX as u64 + 1);
2742        lookup.lookup("<<", &mut segment, 2, Span::call_site(), Span::call_site())?;
2743        let result = segment.call0::<u32>();
2744        assert!(result.is_err());
2745        let err = result.unwrap_err();
2746        let message = format!("{:#}", err);
2747        assert!(message.contains("shift overflow"), "got: {message}");
2748        Ok(())
2749    }
2750
2751    #[test]
2752    fn test_shift_rejects_float_rhs() {
2753        let lookup = OpLookup::new();
2754        let mut segment = DynSegment::new::<()>();
2755        segment.just(1u32);
2756        segment.just(3.0f64);
2757        assert!(
2758            lookup
2759                .lookup("<<", &mut segment, 2, Span::call_site(), Span::call_site())
2760                .is_err()
2761        );
2762    }
2763
2764    #[test]
2765    fn test_scope_pop() -> Result<()> {
2766        let mut lookup = OpLookup::new();
2767
2768        lookup.push_scope(|name, segment, num_operands, _span| {
2769            let matches = {
2770                let top = segment.peek_stack_infos(num_operands);
2771                name == "+" && top.len() == 2 && top[0].value_type.type_id() == TypeId::of::<u32>()
2772            };
2773            if matches {
2774                segment.op2(|_a: u32, _b: u32| 100u32)?;
2775                Ok(true)
2776            } else {
2777                Ok(false)
2778            }
2779        });
2780
2781        let mut segment = DynSegment::new::<()>();
2782        segment.just(10u32);
2783        segment.just(20u32);
2784        lookup.lookup("+", &mut segment, 2, Span::call_site(), Span::call_site())?;
2785        assert_eq!(segment.call0::<u32>()?, 100);
2786
2787        lookup.pop_scope();
2788        let mut segment = DynSegment::new::<()>();
2789        segment.just(10u32);
2790        segment.just(20u32);
2791        lookup.lookup("+", &mut segment, 2, Span::call_site(), Span::call_site())?;
2792        assert_eq!(segment.call0::<u32>()?, 30);
2793
2794        Ok(())
2795    }
2796
2797    #[test]
2798    fn lookup_not_found_error_carries_span() {
2799        let lookup = OpLookup::new();
2800        let mut segment = DynSegment::new::<()>();
2801        segment.just(10u32);
2802        segment.just(20.0f64);
2803        let err = lookup
2804            .lookup("+", &mut segment, 2, Span::call_site(), Span::call_site())
2805            .unwrap_err();
2806        assert!(
2807            err.message().starts_with("no operation"),
2808            "expected 'no operation' prefix, got: {}",
2809            err.message()
2810        );
2811        assert!(err.message().contains("`+`"));
2812        assert!(err.message().contains("`u32`"));
2813        assert!(err.message().contains("`f64`"));
2814    }
2815
2816    #[test]
2817    fn lookup_not_found_error_has_range() {
2818        let lookup = OpLookup::new();
2819        let mut segment = DynSegment::new::<()>();
2820        segment.just(10u32);
2821        segment.just(20.0f64);
2822        let err = lookup
2823            .lookup("+", &mut segment, 2, Span::call_site(), Span::call_site())
2824            .unwrap_err();
2825        assert!(
2826            err.end_span().is_some(),
2827            "op-lookup errors should carry an end span"
2828        );
2829    }
2830
2831    /// Verifies that `ScopeFn` closures compile when written with an explicit `SourceSpan`
2832    /// parameter, confirming the type alias signature is correct.
2833    #[cfg(feature = "span-diagnostics")]
2834    #[test]
2835    fn scope_fn_accepts_source_span_parameter() {
2836        let mut lookup = OpLookup::new();
2837        lookup.push_scope(
2838            |name: &str, segment: &mut DynSegment, arity: usize, span: crate::SourceSpan| {
2839                if name != "value" || arity != 0 {
2840                    return Ok(false);
2841                }
2842                assert_eq!(span, crate::SourceSpan::new(1, 4, 1, 9));
2843                segment.just(span.start.column);
2844                Ok(true)
2845            },
2846        );
2847        let span = crate::ExprSpan::for_text("    value");
2848        let mut segment = DynSegment::new::<()>();
2849        lookup
2850            .lookup("value", &mut segment, 0, span.start, span.end)
2851            .unwrap();
2852        assert_eq!(segment.call0::<usize>().unwrap(), 4);
2853    }
2854
2855    /// Verifies that `FormatRustcStyle` on an `anyhow::Error` without a `SpanContext`
2856    /// falls back to the plain error message — the expected behavior for errors from
2857    /// client-added ops that do not attach span context.
2858    #[test]
2859    fn format_rustc_style_falls_back_for_client_added_op_error() {
2860        use crate::FormatRustcStyle;
2861        use annotate_snippets::Renderer;
2862
2863        let mut lookup = OpLookup::new();
2864        lookup.push_scope(|name, segment, arity, _| {
2865            if name != "failure" || arity != 0 {
2866                return Ok(false);
2867            }
2868            segment.just(0i32);
2869            segment
2870                .op1r(|_: i32| -> anyhow::Result<i32> { anyhow::bail!("custom domain error") })?;
2871            Ok(true)
2872        });
2873        let mut segment = crate::CELParser::new(lookup).parse_str("failure").unwrap();
2874        let err = segment.call0::<i32>().unwrap_err();
2875        let output = err.format_rustc_style("unused source", "unused.cel", 1, &Renderer::plain());
2876        assert_eq!(output, "custom domain error");
2877    }
2878
2879    #[cfg(feature = "span-diagnostics")]
2880    #[test]
2881    fn runtime_error_carries_span_context() {
2882        use crate::{CELParser, FormatRustcStyle, SpanContext};
2883        use annotate_snippets::Renderer;
2884
2885        let mut parser = CELParser::new(OpLookup::new());
2886        let source = "1i32 + 2147483647i32"; // i32::MAX + 1 → overflow
2887        let mut segment = parser.parse_str(source).expect("should parse");
2888        let err = segment.call0::<i32>().expect_err("should overflow");
2889        let ctx = err
2890            .downcast_ref::<SpanContext>()
2891            .expect("expected SpanContext on runtime error");
2892        // The span is on line 1 (1-indexed). In test mode, proc_macro2 with
2893        // span-locations assigns spans relative to the parsed string, starting
2894        // at column 0 for the first token on each line.
2895        assert_eq!(ctx.span().start.line, 1);
2896        // End-to-end rendering must mention the error and mark the source location.
2897        let rendered = err.format_rustc_style(source, "test.cel", 1, &Renderer::plain());
2898        assert!(
2899            rendered.contains("arithmetic overflow"),
2900            "expected 'arithmetic overflow' in rendered output, got: {rendered}"
2901        );
2902        assert!(
2903            rendered.contains('^'),
2904            "expected caret marker in rendered output, got: {rendered}"
2905        );
2906    }
2907
2908    #[test]
2909    fn tuple_shaped_signature_matches_and_dispatches() -> Result<()> {
2910        let mut lookup = OpLookup::new();
2911        lookup.register_tuple_op(TupleOpSignature {
2912            name: "greet".to_string(),
2913            shape: vec![TypeId::of::<String>(), TypeId::of::<i32>()],
2914            tuple_operand_index: 0,
2915            operand_type_ids: vec![],
2916            op_fn: |seg, _span| {
2917                seg.tuple_index(1)?;
2918                seg.op1(|_ignored: i32| true)
2919            },
2920        });
2921
2922        let mut segment = DynSegment::new::<()>();
2923        let ambient_start = segment.current_stack_offset();
2924        segment.op0(|| "hi".to_string());
2925        segment.op0(|| 7i32);
2926        segment.make_tuple(2, ambient_start)?;
2927
2928        lookup.lookup(
2929            "greet",
2930            &mut segment,
2931            1,
2932            Span::call_site(),
2933            Span::call_site(),
2934        )?;
2935        assert!(segment.call0::<bool>()?);
2936        Ok(())
2937    }
2938
2939    #[test]
2940    fn tuple_shaped_signature_does_not_match_wrong_shape() {
2941        let mut lookup = OpLookup::new();
2942        lookup.register_tuple_op(TupleOpSignature {
2943            name: "greet".to_string(),
2944            shape: vec![TypeId::of::<String>(), TypeId::of::<i32>()],
2945            tuple_operand_index: 0,
2946            operand_type_ids: vec![],
2947            op_fn: |seg, _span| {
2948                seg.tuple_index(1)?;
2949                seg.op1(|_ignored: i32| true)
2950            },
2951        });
2952
2953        let mut segment = DynSegment::new::<()>();
2954        let ambient_start = segment.current_stack_offset();
2955        segment.op0(|| 1i32);
2956        segment.op0(|| 2i32);
2957        segment.make_tuple(2, ambient_start).unwrap();
2958
2959        let result = lookup.lookup(
2960            "greet",
2961            &mut segment,
2962            1,
2963            Span::call_site(),
2964            Span::call_site(),
2965        );
2966        assert!(
2967            result.is_err(),
2968            "shape (i32, i32) should not match (String, i32)"
2969        );
2970    }
2971
2972    #[test]
2973    fn tuple_shaped_signature_with_empty_shape_does_not_match_non_tuple() {
2974        // Regression test: a 0-element `shape` must only match an actual
2975        // 0-arity tuple, not any non-tuple operand (which also reports an
2976        // empty `associated` list).
2977        let mut lookup = OpLookup::new();
2978        lookup.register_tuple_op(TupleOpSignature {
2979            name: "unit_greet".to_string(),
2980            shape: vec![],
2981            tuple_operand_index: 0,
2982            operand_type_ids: vec![],
2983            op_fn: |seg, _span| seg.op1(|_ignored: i32| true),
2984        });
2985
2986        let mut segment = DynSegment::new::<()>();
2987        segment.op0(|| 42i32);
2988
2989        let result = lookup.lookup(
2990            "unit_greet",
2991            &mut segment,
2992            1,
2993            Span::call_site(),
2994            Span::call_site(),
2995        );
2996        assert!(
2997            result.is_err(),
2998            "empty-shape tuple signature must not match a non-tuple operand"
2999        );
3000    }
3001
3002    #[test]
3003    fn builtin_operand_types_reports_a_binary_arithmetic_overload() {
3004        let sigs = builtin_operand_types("+");
3005        assert!(
3006            sigs.iter().any(|s| s.arity == 2
3007                && s.lhs == TypeId::of::<i32>()
3008                && s.rhs == TypeId::of::<i32>())
3009        );
3010    }
3011
3012    #[test]
3013    fn builtin_operand_types_reports_a_unary_overload() {
3014        let sigs = builtin_operand_types("!");
3015        assert!(
3016            sigs.iter()
3017                .any(|s| s.arity == 1 && s.lhs == TypeId::of::<bool>())
3018        );
3019    }
3020
3021    #[test]
3022    fn builtin_operand_types_includes_unary_negation_but_only_for_signed_and_float_types() {
3023        let sigs = builtin_operand_types("-");
3024        assert!(
3025            sigs.iter()
3026                .any(|s| s.arity == 1 && s.lhs == TypeId::of::<i32>())
3027        );
3028        assert!(
3029            sigs.iter()
3030                .any(|s| s.arity == 2 && s.lhs == TypeId::of::<i32>())
3031        );
3032        assert!(
3033            !sigs
3034                .iter()
3035                .any(|s| s.arity == 1 && s.lhs == TypeId::of::<u32>()),
3036            "unsigned types have no unary negation overload"
3037        );
3038    }
3039
3040    #[test]
3041    fn builtin_operand_types_covers_heterogeneous_shift_signatures() {
3042        let integers = [
3043            TypeId::of::<u8>(),
3044            TypeId::of::<u16>(),
3045            TypeId::of::<u32>(),
3046            TypeId::of::<u64>(),
3047            TypeId::of::<u128>(),
3048            TypeId::of::<usize>(),
3049            TypeId::of::<i8>(),
3050            TypeId::of::<i16>(),
3051            TypeId::of::<i32>(),
3052            TypeId::of::<i64>(),
3053            TypeId::of::<i128>(),
3054            TypeId::of::<isize>(),
3055        ];
3056        for operator in ["<<", ">>"] {
3057            let signatures = builtin_operand_types(operator);
3058            assert_eq!(signatures.len(), integers.len() * integers.len());
3059            for lhs in integers {
3060                for rhs in integers {
3061                    assert_eq!(
3062                        signatures
3063                            .iter()
3064                            .filter(|s| s.arity == 2 && s.lhs == lhs && s.rhs == rhs)
3065                            .count(),
3066                        1
3067                    );
3068                }
3069            }
3070        }
3071    }
3072
3073    #[test]
3074    fn builtin_operand_types_is_empty_for_an_unregistered_name() {
3075        assert!(builtin_operand_types("not_an_operator").is_empty());
3076    }
3077
3078    #[test]
3079    fn builtin_operand_types_is_empty_for_a_runtime_only_tuple_op() {
3080        // Tuple-shaped ops are registered on an OpLookup instance at runtime
3081        // (OpLookup::register_tuple_op), never in the static BUILTINS table this function reads —
3082        // confirming they're invisible here, not an oversight.
3083        assert!(builtin_operand_types("greet").is_empty());
3084    }
3085
3086    #[test]
3087    fn builtin_scalar_type_resolves_every_documented_name() {
3088        for name in BUILTIN_SCALAR_NAMES {
3089            let scalar =
3090                builtin_scalar_type(name).unwrap_or_else(|| panic!("expected `{name}` to resolve"));
3091            assert_eq!(scalar.type_name, *name);
3092        }
3093        assert!(builtin_scalar_type("not_a_type").is_none());
3094    }
3095
3096    #[test]
3097    fn builtin_scalar_type_i32_matches_std_any_type_id() {
3098        let scalar = builtin_scalar_type("i32").unwrap();
3099        assert_eq!((scalar.value_type)().type_id(), TypeId::of::<i32>());
3100        assert_eq!((scalar.value_type)().size(), std::mem::size_of::<i32>());
3101        assert_eq!((scalar.value_type)().align(), std::mem::align_of::<i32>());
3102    }
3103
3104    #[test]
3105    fn builtin_scalar_type_push_arg_declares_a_readable_argument() {
3106        let scalar = builtin_scalar_type("i32").unwrap();
3107        let mut segment = DynSegment::new::<()>();
3108        (scalar.value_type)()
3109            .push_argument(&mut segment, 0)
3110            .unwrap();
3111        let value = 42i32;
3112        let result: i32 = segment.call_dyn(&[&value]).unwrap();
3113        assert_eq!(result, 42);
3114    }
3115
3116    #[test]
3117    fn builtin_generic_type_resolves_every_range_family_member_for_every_numeric_type() {
3118        macro_rules! check {
3119            ($($ty:ty),* $(,)?) => {$(
3120                for (generic, identity, size, align) in [
3121                    ("Range", TypeId::of::<std::ops::Range<$ty>>(), std::mem::size_of::<std::ops::Range<$ty>>(), std::mem::align_of::<std::ops::Range<$ty>>()),
3122                    ("RangeInclusive", TypeId::of::<std::ops::RangeInclusive<$ty>>(), std::mem::size_of::<std::ops::RangeInclusive<$ty>>(), std::mem::align_of::<std::ops::RangeInclusive<$ty>>()),
3123                    ("RangeFrom", TypeId::of::<std::ops::RangeFrom<$ty>>(), std::mem::size_of::<std::ops::RangeFrom<$ty>>(), std::mem::align_of::<std::ops::RangeFrom<$ty>>()),
3124                    ("RangeTo", TypeId::of::<std::ops::RangeTo<$ty>>(), std::mem::size_of::<std::ops::RangeTo<$ty>>(), std::mem::align_of::<std::ops::RangeTo<$ty>>()),
3125                    ("RangeToInclusive", TypeId::of::<std::ops::RangeToInclusive<$ty>>(), std::mem::size_of::<std::ops::RangeToInclusive<$ty>>(), std::mem::align_of::<std::ops::RangeToInclusive<$ty>>()),
3126                ] {
3127                    let argument = crate::ResolvedLeafType::leaf::<$ty>("Alias").unwrap().into();
3128                    let resolved = crate::resolve_builtin_named_type(generic, &[argument]).unwrap();
3129                    let descriptor = resolved.element_type();
3130                    assert_eq!(resolved.type_name(), format!("{generic}({})", stringify!($ty)));
3131                    assert_eq!(descriptor.type_id(), identity);
3132                    assert_eq!(descriptor.size(), size);
3133                    assert_eq!(descriptor.align(), align);
3134                }
3135            )*};
3136        }
3137        check!(
3138            u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64
3139        );
3140    }
3141
3142    #[test]
3143    fn builtin_generic_type_range_inclusive_f64_matches_std_any_type_id() {
3144        let argument = crate::ResolvedLeafType::leaf::<f64>("Alias")
3145            .unwrap()
3146            .into();
3147        let resolved = crate::resolve_builtin_named_type("RangeInclusive", &[argument]).unwrap();
3148        assert_eq!(
3149            resolved.type_id(),
3150            TypeId::of::<std::ops::RangeInclusive<f64>>()
3151        );
3152        assert_eq!(
3153            resolved.element_type().size(),
3154            std::mem::size_of::<std::ops::RangeInclusive<f64>>()
3155        );
3156    }
3157
3158    #[test]
3159    fn builtin_generic_type_is_none_for_unknown_generic_or_argument() {
3160        let argument = crate::ResolvedLeafType::leaf::<f64>("Alias")
3161            .unwrap()
3162            .into();
3163        assert!(crate::resolve_builtin_named_type("NotAGeneric", &[argument]).is_none());
3164        for argument in [
3165            crate::ResolvedLeafType::leaf::<bool>("i32").unwrap().into(),
3166            crate::ResolvedLeafType::leaf::<String>("i32")
3167                .unwrap()
3168                .into(),
3169            crate::ResolvedType::Tuple { elements: vec![] },
3170        ] {
3171            assert!(crate::resolve_builtin_named_type("Range", &[argument]).is_none());
3172        }
3173    }
3174
3175    #[test]
3176    fn builtin_generic_type_0_resolves_range_full() {
3177        let resolved = crate::resolve_builtin_named_type("RangeFull", &[]).unwrap();
3178        assert_eq!(resolved.type_name(), "RangeFull");
3179        assert_eq!(resolved.type_id(), TypeId::of::<std::ops::RangeFull>());
3180        assert!(crate::resolve_builtin_named_type("NotAGeneric", &[]).is_none());
3181    }
3182
3183    #[test]
3184    fn builtin_generic_type_push_arg_declares_a_readable_argument() {
3185        let argument = crate::ResolvedLeafType::leaf::<i32>("Alias")
3186            .unwrap()
3187            .into();
3188        let resolved = crate::resolve_builtin_named_type("RangeInclusive", &[argument]).unwrap();
3189        let mut segment = DynSegment::new::<()>();
3190        resolved
3191            .element_type()
3192            .push_argument(&mut segment, 0)
3193            .unwrap();
3194        let value = 1i32..=5i32;
3195        let result: std::ops::RangeInclusive<i32> = segment.call_dyn(&[&value]).unwrap();
3196        assert_eq!(result, 1..=5);
3197    }
3198
3199    #[test]
3200    fn isolate_scopes_removes_pushed_scopes_until_restored() {
3201        let mut lookup = OpLookup::new();
3202        lookup.push_scope(|name, segment, arity, _span| {
3203            if name == "custom" && arity == 0 {
3204                segment.just(1i32);
3205                Ok(true)
3206            } else {
3207                Ok(false)
3208            }
3209        });
3210
3211        let mut segment = DynSegment::new::<()>();
3212        let isolated = lookup.isolate_scopes();
3213        let err = lookup.lookup(
3214            "custom",
3215            &mut segment,
3216            0,
3217            proc_macro2::Span::call_site(),
3218            proc_macro2::Span::call_site(),
3219        );
3220        assert!(
3221            err.is_err(),
3222            "custom scope must not be reachable while isolated"
3223        );
3224
3225        lookup.restore_scopes(isolated);
3226        let mut segment = DynSegment::new::<()>();
3227        lookup
3228            .lookup(
3229                "custom",
3230                &mut segment,
3231                0,
3232                proc_macro2::Span::call_site(),
3233                proc_macro2::Span::call_site(),
3234            )
3235            .unwrap();
3236        assert_eq!(segment.call0::<i32>().unwrap(), 1);
3237    }
3238
3239    #[test]
3240    fn isolate_scopes_leaves_library_scopes_reachable() {
3241        let mut lookup = OpLookup::new();
3242        lookup.push_library_scope(|name, segment, arity, _| {
3243            if name != "persistent" || arity != 0 {
3244                return Ok(false);
3245            }
3246            segment.just(42i32);
3247            Ok(true)
3248        });
3249        let mut segment = DynSegment::new::<()>();
3250        let isolated = lookup.isolate_scopes();
3251        lookup
3252            .lookup(
3253                "persistent",
3254                &mut segment,
3255                0,
3256                proc_macro2::Span::call_site(),
3257                proc_macro2::Span::call_site(),
3258            )
3259            .expect("installed library callbacks survive isolation");
3260        assert_eq!(segment.call0::<i32>().unwrap(), 42);
3261        lookup.restore_scopes(isolated);
3262        let mut segment = DynSegment::new::<()>();
3263        lookup
3264            .lookup(
3265                "persistent",
3266                &mut segment,
3267                0,
3268                Span::call_site(),
3269                Span::call_site(),
3270            )
3271            .unwrap();
3272        assert_eq!(segment.call0::<i32>().unwrap(), 42);
3273    }
3274
3275    #[test]
3276    fn range_i32_constructs_a_range() -> Result<()> {
3277        let lookup = OpLookup::new();
3278        let mut segment = DynSegment::new::<()>();
3279        segment.just(1i32);
3280        segment.just(5i32);
3281        lookup.lookup(
3282            "range",
3283            &mut segment,
3284            2,
3285            Span::call_site(),
3286            Span::call_site(),
3287        )?;
3288        assert_eq!(segment.call0::<std::ops::Range<i32>>()?, 1i32..5i32);
3289        Ok(())
3290    }
3291
3292    #[test]
3293    fn range_f64_constructs_a_range() -> Result<()> {
3294        let lookup = OpLookup::new();
3295        let mut segment = DynSegment::new::<()>();
3296        segment.just(1.5f64);
3297        segment.just(5.5f64);
3298        lookup.lookup(
3299            "range",
3300            &mut segment,
3301            2,
3302            Span::call_site(),
3303            Span::call_site(),
3304        )?;
3305        assert_eq!(segment.call0::<std::ops::Range<f64>>()?, 1.5f64..5.5f64);
3306        Ok(())
3307    }
3308
3309    #[test]
3310    fn range_inclusive_i32_constructs_a_range_inclusive() -> Result<()> {
3311        let lookup = OpLookup::new();
3312        let mut segment = DynSegment::new::<()>();
3313        segment.just(1i32);
3314        segment.just(5i32);
3315        lookup.lookup(
3316            "range_inclusive",
3317            &mut segment,
3318            2,
3319            Span::call_site(),
3320            Span::call_site(),
3321        )?;
3322        assert_eq!(
3323            segment.call0::<std::ops::RangeInclusive<i32>>()?,
3324            1i32..=5i32
3325        );
3326        Ok(())
3327    }
3328
3329    #[test]
3330    fn range_rejects_mismatched_operand_types() {
3331        let lookup = OpLookup::new();
3332        let mut segment = DynSegment::new::<()>();
3333        segment.just(1i32);
3334        segment.just(5.0f64);
3335        let result = lookup.lookup(
3336            "range",
3337            &mut segment,
3338            2,
3339            Span::call_site(),
3340            Span::call_site(),
3341        );
3342        assert!(result.is_err(), "expected a type-mismatch error, got Ok");
3343    }
3344
3345    #[test]
3346    fn range_from_i32_constructs_a_range_from() -> Result<()> {
3347        let lookup = OpLookup::new();
3348        let mut segment = DynSegment::new::<()>();
3349        segment.just(3i32);
3350        lookup.lookup(
3351            "range_from",
3352            &mut segment,
3353            1,
3354            Span::call_site(),
3355            Span::call_site(),
3356        )?;
3357        assert_eq!(segment.call0::<std::ops::RangeFrom<i32>>()?, 3i32..);
3358        Ok(())
3359    }
3360
3361    #[test]
3362    fn range_to_i32_constructs_a_range_to() -> Result<()> {
3363        let lookup = OpLookup::new();
3364        let mut segment = DynSegment::new::<()>();
3365        segment.just(7i32);
3366        lookup.lookup(
3367            "range_to",
3368            &mut segment,
3369            1,
3370            Span::call_site(),
3371            Span::call_site(),
3372        )?;
3373        assert_eq!(segment.call0::<std::ops::RangeTo<i32>>()?, ..7i32);
3374        Ok(())
3375    }
3376
3377    #[test]
3378    fn range_to_inclusive_i32_constructs_a_range_to_inclusive() -> Result<()> {
3379        let lookup = OpLookup::new();
3380        let mut segment = DynSegment::new::<()>();
3381        segment.just(7i32);
3382        lookup.lookup(
3383            "range_to_inclusive",
3384            &mut segment,
3385            1,
3386            Span::call_site(),
3387            Span::call_site(),
3388        )?;
3389        assert_eq!(segment.call0::<std::ops::RangeToInclusive<i32>>()?, ..=7i32);
3390        Ok(())
3391    }
3392
3393    #[test]
3394    fn range_full_constructs_a_range_full() -> Result<()> {
3395        let lookup = OpLookup::new();
3396        let mut segment = DynSegment::new::<()>();
3397        lookup.lookup(
3398            "range_full",
3399            &mut segment,
3400            0,
3401            Span::call_site(),
3402            Span::call_site(),
3403        )?;
3404        segment.call0::<std::ops::RangeFull>()?;
3405        Ok(())
3406    }
3407}