Skip to main content

cel_parser/
lib.rs

1//! A recursive descent parser for CEL (Common Expression Language) expressions.
2//!
3//! This crate provides a parser that can parse CEL expressions into executable segments.
4//! The parser follows the CEL grammar specification and provides detailed error reporting
5//! with source location information.
6//!
7//! # Canonical typed execution
8//!
9//! Arrays, tuples, unit, registered leaves, and `Fn` signatures compose
10//! recursively without registering each aggregate shape. [`ResolvedType`] and
11//! [`Ty`] retain complete shapes; shared physical carrier IDs are not identities.
12//! Preparation validates concrete witnesses before the body executes:
13//!
14//! ```
15//! use cel_parser::{CELParser, OpLookup};
16//! use cel_runtime::{ArrayOf, Cons, IntoCStackList, IntoRustTuple, Leaf, Nil};
17//! type Pair = Cons<Leaf<i32>, Cons<Leaf<bool>, Nil>>;
18//! let body = CELParser::new(OpLookup::new()).parse_str("[(7, true)]").unwrap();
19//! let mut prepared = body.prepare::<Nil, ArrayOf<Pair>>().unwrap();
20//! let pairs = prepared.call(&().into_c_stack_list()).unwrap().into_vec();
21//! assert_eq!(pairs.into_iter().next().unwrap().into_rust_tuple(), (7, true));
22//! ```
23//!
24//! Repeated prepared calls do not repeat recursive type checks. Arbitrary
25//! erased host imports remain checked external boundaries. Cloning borrowed
26//! argument reads, comparing values, and formatting values require their own
27//! capabilities; merely moving a value into a container does not. Source
28//! `Fn((A,), R)` names one parameter and `Fn((), R)` names none. The typed
29//! Rust carrier is [`cel_runtime::Callable`], witnessed by [`cel_runtime::FnOf`].
30//! `cel-rs-macros` validates source; no native macro backend is implemented.
31//!
32//! # Error Handling
33//!
34//! Parse errors are returned as [`ParseError`], which carries a `proc_macro2::Span` for precise diagnostics.
35//! Convert to [`CELError`] (via `From`) when the error must be stored or sent across thread boundaries.
36//! All errors result from malformed input (syntax errors, type mismatches, undefined identifiers).
37//!
38//! # Grammar
39//!
40//! For a prose reference manual with the same grammar, see the standalone
41//! [CEL book](../cel-book/index.html) and its
42//! [reference chapter](../cel-book/reference.html).
43//!
44//! ```text
45//! expression = closure_expression | range_expression.
46//! range_expression = ".." [ or_expression ]
47//!                  | "..=" or_expression
48//!                  | or_expression [ ".." [ or_expression ] | "..=" or_expression ].
49//! or_expression = and_expression { "||" and_expression }.
50//! and_expression = comparison_expression { "&&" comparison_expression }.
51//! comparison_expression = bitwise_or_expression [ comparison_operator bitwise_or_expression ].
52//! bitwise_or_expression = bitwise_xor_expression { "|" bitwise_xor_expression }.
53//! bitwise_xor_expression = bitwise_and_expression { "^" bitwise_and_expression }.
54//! bitwise_and_expression = bitwise_shift_expression { "&" bitwise_shift_expression }.
55//! bitwise_shift_expression = additive_expression { ("<<" | ">>") additive_expression }.
56//! additive_expression = multiplicative_expression { ("+" | "-") multiplicative_expression }.
57//! multiplicative_expression = cast_expression { ("*" | "/" | "%") cast_expression }.
58//! cast_expression = unary_expression { "as" identifier }.
59//! unary_expression = ("-" | "!") unary_expression | postfix_expression.
60//! postfix_expression = primary_expression { postfix_suffix }.
61//! postfix_suffix = "(" [ parameter_list ] ")" | "." (unsuffixed_integer | identifier).
62//! comparison_operator = "==" | "!=" | "<" | ">" | "<=" | ">=".
63//! primary_expression = literal | value_identifier [ record_fields ] | tuple_or_group
64//!                    | array_expression | if_expression.
65//! record_fields = "{" [ identifier ":" expression { "," identifier ":" expression } ] "}".
66//! tuple_or_group = "(" [ expression ["," [ expression { "," expression } ]] ] ")".
67//! array_expression = "[" [ expression { "," expression } ] "]" [ ":" type_expression ].
68//! if_expression = "if" expression "{" expression "}" [ "else" ( "{" expression "}" | if_expression ) ].
69//! closure_expression = ("||" | "|" closure_param { "," closure_param } "|") expression.
70//! closure_param = identifier ":" type_expression.
71//! parameter_list = expression { "," expression }.
72//!
73//! type_expression = identifier [ "(" [ type_expression { "," type_expression } ] ")" ]
74//!                  | "[" type_expression "]"
75//!                  | "(" [ type_expression ["," [ type_expression { "," type_expression } ]] ] ")".
76//!
77//! literal_pattern = ["-"] literal.
78//! ```
79//!
80//! The productions encode operator precedence and left associativity; comparisons and ranges
81//! do not chain. A closure is a complete expression, not a primary operand. Its body consumes
82//! the remaining expression in its current delimiter boundary. Group a closure before applying
83//! an operator or postfix suffix to it: `(|x: i32| x + 1)(2)`. Arguments and collection elements
84//! are complete expressions and accept bare closures. Postfix calls directly following a named
85//! member dispatch that member; grouping the member first calls its result instead.
86//!
87//! Expand these productions in ordinary and header modes. Header mode omits `record_fields`
88//! from its primary production, so its following `{` belongs to the host body. Groups, argument
89//! lists, arrays, record field values and branch bodies enter ordinary mode; closure bodies
90//! inherit their enclosing mode. A condition enters header mode. The first token distinguishes
91//! closures (`|` or `||`) from range expressions. Each precedence level selects its continuation
92//! from the current token and returns at a lower-precedence operator or expression boundary.
93//! Boundaries include closing delimiters, commas, body braces and end of input.
94//! `value_identifier` excludes the five reserved words.
95//!
96//! Registered records use a constructor namespace independent of value bindings and evaluate
97//! fields once in written order. All schema fields are required exactly once with exact types.
98//! An `if` condition (or an embedded host header) reserves its body brace: write
99//! `if (Point { x: 0.0 }).x == 0.0 { 1 } else { 2 }` to explicitly allow a record there.
100//! Delimited argument lists, arrays, field values, and branch bodies parse ordinarily.
101//!
102//! `literal_pattern` is a separate entry point, not reachable from `expression` — it exists for
103//! grammars that embed CEL literals in pattern position (e.g. adam-lang's `conditional_branch`)
104//! and need Rust's own `LiteralPattern` rule: a bare literal, or one directly negated by a
105//! leading `-` (no `!`, no chained `--`, no arbitrary unary/postfix operand) — see
106//! <https://doc.rust-lang.org/reference/patterns.html#literal-patterns>.
107//!
108//! `type_expression` is the single, reusable recursive type grammar shared by array type
109//! ascriptions (`[1, 2]: [i32]`), closure parameters (`|x: RangeInclusive(f64)| ...`), and
110//! adam-lang cell/source/out type annotations (`cell x: (i32, f64);`). A bare identifier
111//! resolves through the configured [`TypeResolver`] (array/closure contexts) or a host
112//! `TypeRegistry` (adam-lang cell contexts); `Name(args)` names a parameterized/generic type
113//! (e.g. `RangeInclusive(f64)`, the type produced by CEL's own `..=` range operator) resolved
114//! against the same [`TypeResolver`]; `[T]` composes nested array types (`[i32]`, `[[i32]]`);
115//! and parenthesized tuple syntax names a (possibly nested) tuple type. Every context that
116//! accepts `type_expression` documents its own narrower support boundary where one exists.
117//! CEL types recursively compose registered cloneable leaves, tuples, arrays, and callables:
118//! arrays can contain tuples or callables, and tuples and callable signatures can contain
119//! further compound types. `Fn((A, B), R)` names a callable with two parameters and result
120//! `R`; use `Fn((A,), R)` for one parameter and `Fn((), R)` for none.
121//! Adam-lang shares this recursive resolution for persistent cells, including registered
122//! generic leaves. Adam requires cloning and value equality before storing a cell:
123//! callable values remain valid CEL values, but a callable without equality cannot become
124//! an Adam cell. Compound host access uses explicit canonical representation witnesses;
125//! registered primitive and foreign leaf cells retain their concrete Rust access APIs.
126//!
127//! # Examples
128//!
129//! ```rust
130//! use cel_parser::{CELParser, OpLookup};
131//!
132//! let mut segment = CELParser::new(OpLookup::new()).parse_str("10u32 + 20u32 * 5u32").unwrap();
133//! let result = segment.call0::<u32>();
134//! assert!(result.is_ok());
135//! assert_eq!(result.unwrap(), 110); // 10 + 20 * 5 = 10 + 100
136//! ```
137//!
138//! ## Basic Usage
139//!
140//! ```rust
141//! use cel_parser::CELParser;
142//! use cel_parser::OpLookup;
143//! use proc_macro2::TokenStream;
144//! use std::str::FromStr;
145//!
146//! let input = TokenStream::from_str("10").unwrap();
147//! let mut parser = CELParser::new(OpLookup::new());
148//! let result = parser.parse_tokens(input.into_iter());
149//! assert!(result.is_ok());
150//! ```
151//!
152//! ## Receiver Operations
153//!
154//! `receiver.name` and `receiver.name()` both invoke a unary named operation directly.
155//! `receiver.name(arg1, arg2)` passes the receiver first, then the explicit arguments;
156//! execution evaluates each operand once in source order. Value bindings named `name` do
157//! not hide dot operations. Grouping changes call behavior: `(receiver.name)()` calls the
158//! operation's result through the ordinary callable lookup instead.
159//!
160//! Host libraries supply these operations through [`OpLookup`]; the parser imposes no
161//! domain-specific receiver types. AST parsing preserves the spelling and the member's name
162//! span without resolving the operation:
163//!
164//! ```rust
165//! use cel_parser::{AstContext, Expr, OpLookup, Parser, format_expr};
166//! let source = "a.center().x";
167//! let expr = Parser::<AstContext>::new(OpLookup::new()).parse_str_ast(source).unwrap();
168//! assert!(matches!(&expr, Expr::Member { args: None, .. }));
169//! assert_eq!(format_expr(&expr, source, 0), source);
170//! ```
171//!
172//! ## Metadata-aware static checking
173//!
174//! [`ty::check_expr_with_type_resolver`] takes the host's [`OpLookup`] as its fourth argument.
175//! It checks record fields against schemas and receiver operations against signatures without
176//! invoking emitters. Known custom leaves retain [`Ty::Registered`] semantic identities; unrelated
177//! known types never unify. Unknown constructors are diagnostic, while genuinely unresolved
178//! values and custom calls without metadata remain best-effort. Every child is still checked,
179//! and constructor/field/member labels never enter the value resolver. No integer-to-float
180//! coercion occurs. [`ty::check_expr`] remains the primitive convenience entry with an empty lookup.
181//!
182//! Use [`checking::CheckingBuilder`] to project retained registrations once and
183//! [`checking::CheckingEnvironment::from_description`] to import serializable, callback-free
184//! metadata. [`checking::check_expr_with_environment`] shares the same checker and separates
185//! definite errors from unavailable host facts. Its value resolver returns `Some(Ty::Any)` for
186//! a declared unresolved value and `None` for an absent declaration. Nominal lexical types
187//! come from the owning environment; aliases share identity within that environment, while
188//! independent imports do not. Callback-only scopes and legacy tuple registrations remain
189//! runtime APIs but cannot supply complete offline catalogs.
190//!
191//! ```rust
192//! use cel_parser::{AstContext, OpLookup, OperationSignature, Parser, ResolvedLeafType, Ty};
193//! use cel_runtime::ValueType;
194//!
195//! let scalar = ResolvedLeafType::new("f64", ValueType::leaf::<f64>());
196//! let mut lookup = OpLookup::new();
197//! lookup.register_operation(OperationSignature {
198//!     name: "twice",
199//!     operands: vec![scalar.clone().into()],
200//!     result: scalar.into(),
201//!     emit: Box::new(|s, _| s.op1(|value: f64| value * 2.0)),
202//! }).unwrap();
203//! let expr = Parser::<AstContext>::new(OpLookup::new())
204//!     .parse_str_ast("3.0.twice() + true").unwrap();
205//! let (_, diagnostics) = cel_parser::ty::check_expr_with_type_resolver(
206//!     &expr, &|_| Ty::Any, cel_parser::builtin_type_resolver().as_ref(), &lookup,
207//! );
208//! assert_eq!(diagnostics.len(), 1);
209//! ```
210//!
211//! ## Array Literals
212//!
213//! A `[...]` literal constructs one canonical [`cel_runtime::Array`] owning every element.
214//! Checked host calls return [`cel_runtime::OwnedValue`]; prepared calls use exact
215//! recursive witnesses directly.
216//! Unannotated non-empty arrays keep their existing inference, while postfix annotations let
217//! callers state complete recursive array, tuple, callable, and custom-leaf shapes
218//! explicitly. Elements must share one complete recursive runtime type — a heterogeneous literal
219//! such as `[1i32, 2.0f64]`, an unannotated empty literal `[]`, or a trailing comma is a parse
220//! error — and the evaluated array converts to the corresponding `Vec<T>` without moving or
221//! reallocating its elements:
222//!
223//! ```rust
224//! use cel_parser::{CELParser, OpLookup};
225//!
226//!
227//! let mut segment = CELParser::new(OpLookup::new())
228//!     .parse_str("[0, 1, 2]: [i32]")
229//!     .unwrap();
230//! let array = segment.call0::<cel_runtime::OwnedValue>().unwrap().try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>().unwrap();
231//! assert_eq!(array.into_vec(), vec![0, 1, 2]);
232//!
233//! let mut segment = CELParser::new(OpLookup::new()).parse_str("[]: [i32]").unwrap();
234//! let array = segment.call0::<cel_runtime::OwnedValue>().unwrap().try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>().unwrap();
235//! assert!(array.into_vec().is_empty());
236//! ```
237//!
238//! Tuple arrays and callable arrays use canonical witnesses rather than external erased wrappers.
239//! Singleton tuple types retain their trailing comma. `Fn((A, B), R)` has two parameters,
240//! `Fn((A,), R)` has one, and `Fn((), R)` has none:
241//!
242//! ```
243//! use cel_parser::{CELParser, OpLookup};
244//! use cel_runtime::{ArrayOf, Cons, FnOf, IntoCStackList, Leaf, Nil};
245//! type F = FnOf<Cons<Leaf<i32>, Nil>, ArrayOf<Leaf<i32>>>;
246//! let body = CELParser::new(OpLookup::new())
247//!     .parse_str("[]: [Fn((i32,), [i32])]").unwrap();
248//! let values = body.prepare::<Nil, ArrayOf<F>>().unwrap()
249//!     .call(&().into_c_stack_list()).unwrap();
250//! assert!(values.is_empty());
251//! ```
252//!
253//! Hosts may also resolve custom registry-backed leaf names by constructing the parser with
254//! [`CELParser::with_type_resolver`]:
255//!
256//! ```rust
257//! use cel_parser::{CELParser, OpLookup, ResolvedLeafType};
258//! use cel_runtime::ValueType;
259//!
260//! #[derive(Clone)]
261//! struct Custom;
262//!
263//! let resolver = [(
264//!     "Custom",
265//!     ResolvedLeafType::new("Custom", ValueType::leaf::<Custom>()),
266//! )];
267//! let mut segment = CELParser::with_type_resolver(OpLookup::new(), resolver)
268//!     .parse_str("[]: [Custom]")
269//!     .unwrap();
270//! let array = segment.call0::<cel_runtime::OwnedValue>().unwrap().try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<Custom>>>().unwrap();
271//! assert!(array.into_vec().is_empty());
272//! ```
273//!
274//! Nested literals accept recursive array annotations; each inner value uses the
275//! same canonical array ABI with a complete element witness:
276//!
277//! ```rust
278//! use cel_parser::{CELParser, OpLookup};
279//!
280//!
281//! let mut segment = CELParser::new(OpLookup::new())
282//!     .parse_str("[[0], [1]]: [[i32]]")
283//!     .unwrap();
284//! let array = segment.call0::<cel_runtime::OwnedValue>().unwrap().try_into_typed::<cel_runtime::ArrayOf<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>>().unwrap();
285//! let rows = array.into_vec();
286//! assert_eq!(rows.len(), 2);
287//! assert_eq!(rows[0].as_slice(), &[0]);
288//! ```
289//!
290//! Exact annotation failures stay precise:
291//!
292//! ```rust
293//! use cel_parser::{CELParser, OpLookup};
294//!
295//! let err = match CELParser::new(OpLookup::new()).parse_str("[0, 1]: [f64]") {
296//!     Ok(_) => panic!("the annotation should reject i32 elements"),
297//!     Err(err) => err,
298//! };
299//! assert_eq!(
300//!     err.message(),
301//!     "array element 0 has type i32, expected f64"
302//! );
303//!
304//! let err = match CELParser::new(OpLookup::new()).parse_str("[0]: [Nope]") {
305//!     Ok(_) => panic!("the unknown leaf name should be rejected"),
306//!     Err(err) => err,
307//! };
308//! assert_eq!(err.message(), "unknown type `Nope`");
309//! ```
310//!
311//! ### Known limitations
312//!
313//! - An unannotated empty literal (`[]`) is a parse error: with no element there is nothing to
314//!   infer the array's element type from (<https://github.com/stlab/cel-rs/issues/212>).
315//! - A type-mismatch diagnostic from the compiling path ([`CELParser`], which type-checks
316//!   elements against their compiled runtime types) spans the whole `[...]` literal and names the
317//!   offending element only in its message text (`array element 1 has type ...`). The static
318//!   [`ty::check_expr`] checker, which runs over an [`AstContext`] tree instead, already reports
319//!   the offending element's own span (<https://github.com/stlab/cel-rs/issues/215>).
320//!
321//! ## Error Formatting
322//!
323//! ```rust
324//! use annotate_snippets::Renderer;
325//! use cel_parser::CELParser;
326//! use cel_parser::OpLookup;
327//! use proc_macro2::TokenStream;
328//! use std::str::FromStr;
329//!
330//! let line = line!() + 1;
331//! let source = r#"
332//!   10 20
333//! "#; // Invalid: missing operator
334//! let input = TokenStream::from_str(source).unwrap();
335//! let mut parser = CELParser::new(OpLookup::new());
336//!
337//! if let Err(e) = parser.parse_tokens(input.into_iter()) {
338//!     // Format error starting at line 1
339//!     println!("{}", e.format_rustc_style(source, file!(), line, &Renderer::plain()));
340//! }
341//! ```
342
343pub mod ast;
344mod compile;
345pub use compile::compile_expr;
346mod error;
347mod fmt;
348pub mod lex_lexer;
349pub mod op_table;
350pub mod registered_ops;
351pub use registered_ops::{
352    OperationEmitter, OperationSignature, RecordEmitter, RecordField, RecordSchema,
353};
354pub mod checking;
355pub mod parser_context;
356pub mod trivia;
357pub mod ty;
358pub mod type_expr;
359pub mod type_functions;
360
361pub use ast::{AstContext, ClosureParam, Expr, ExprSpan, Literal, LogicalOp, RecordInit};
362pub use error::{
363    CELError, FormatRustcStyle, ParseError, SourceSpan, SpanContext, SpanLabel, format_multi_span,
364};
365pub use fmt::{
366    format_expr, format_expr_header, format_expr_header_with_layout, format_expr_restricted,
367    format_expr_with_layout,
368};
369pub use op_table::{OpLookup, OperandTypes, builtin_operand_types};
370pub use parser_context::{DynSegmentContext, ParserContext};
371pub use proc_macro2::LineColumn;
372pub use trivia::Comment;
373pub use ty::Ty;
374pub use type_expr::{
375    ResolvedArrayType, ResolvedLeafType, ResolvedType, TypeExpr, TypeIdentity, TypeResolver,
376    builtin_type_resolver, resolve_builtin_named_type,
377};
378
379use lex_lexer::{LexLexer, Literal as CelLiteral, Token, TokenStreamIter};
380
381use cel_runtime::DynSegment;
382use proc_macro2::{Delimiter, Span, TokenStream};
383#[cfg(test)]
384use std::any::TypeId;
385use std::collections::HashMap;
386use std::iter::Peekable;
387use std::str::FromStr;
388
389/// Parser result type.
390///
391/// # Examples
392/// See [`Parser::parse_str`] for a fallible parsing result.
393pub type Result<T> = std::result::Result<T, ParseError>;
394
395/// Pushes a literal value from `token` onto `output`.
396///
397/// # Errors
398///
399/// Returns `Err` if the literal type or numeric suffix is unsupported, the exponent
400/// sign is misplaced, or a numeric literal cannot be parsed as its type.
401///
402/// - Complexity: O(n) time and space for a literal with n characters.
403fn push_literal_token<C: ParserContext>(output: &mut C, lit: CelLiteral) -> Result<()> {
404    let lit = lex_lexer::normalize_literal(lit)
405        .map_err(|error| ParseError::new(error.to_string(), error.span()))?;
406    push_normalized_literal(output, lit)
407}
408
409/// Pushes a normalized syntax literal's concrete value.
410///
411/// # Errors
412/// Returns an error for an unsupported literal or an unrepresentable numeric value.
413///
414/// - Complexity: O(n) time and space for n literal characters.
415fn push_normalized_literal<C: ParserContext>(output: &mut C, lit: CelLiteral) -> Result<()> {
416    match lit {
417        CelLiteral::Int(integer) => {
418            let span = integer.span();
419            match integer.suffix() {
420                "" | "i32" => output.push_literal(
421                    integer.base10_parse::<i32>().map_err(|e| {
422                        ParseError::new(
423                            format!("invalid i32 literal `{integer}`: {e}"),
424                            integer.span(),
425                        )
426                    })?,
427                    span,
428                ),
429                "u8" => output.push_literal(
430                    integer.base10_parse::<u8>().map_err(|e| {
431                        ParseError::new(
432                            format!("invalid u8 literal `{integer}`: {e}"),
433                            integer.span(),
434                        )
435                    })?,
436                    span,
437                ),
438                "u16" => output.push_literal(
439                    integer.base10_parse::<u16>().map_err(|e| {
440                        ParseError::new(
441                            format!("invalid u16 literal `{integer}`: {e}"),
442                            integer.span(),
443                        )
444                    })?,
445                    span,
446                ),
447                "u32" => output.push_literal(
448                    integer.base10_parse::<u32>().map_err(|e| {
449                        ParseError::new(
450                            format!("invalid u32 literal `{integer}`: {e}"),
451                            integer.span(),
452                        )
453                    })?,
454                    span,
455                ),
456                "u64" => output.push_literal(
457                    integer.base10_parse::<u64>().map_err(|e| {
458                        ParseError::new(
459                            format!("invalid u64 literal `{integer}`: {e}"),
460                            integer.span(),
461                        )
462                    })?,
463                    span,
464                ),
465                "u128" => output.push_literal(
466                    integer.base10_parse::<u128>().map_err(|e| {
467                        ParseError::new(
468                            format!("invalid u128 literal `{integer}`: {e}"),
469                            integer.span(),
470                        )
471                    })?,
472                    span,
473                ),
474                "usize" => output.push_literal(
475                    integer.base10_parse::<usize>().map_err(|e| {
476                        ParseError::new(
477                            format!("invalid usize literal `{integer}`: {e}"),
478                            integer.span(),
479                        )
480                    })?,
481                    span,
482                ),
483                "i8" => output.push_literal(
484                    integer.base10_parse::<i8>().map_err(|e| {
485                        ParseError::new(
486                            format!("invalid i8 literal `{integer}`: {e}"),
487                            integer.span(),
488                        )
489                    })?,
490                    span,
491                ),
492                "i16" => output.push_literal(
493                    integer.base10_parse::<i16>().map_err(|e| {
494                        ParseError::new(
495                            format!("invalid i16 literal `{integer}`: {e}"),
496                            integer.span(),
497                        )
498                    })?,
499                    span,
500                ),
501                "i64" => output.push_literal(
502                    integer.base10_parse::<i64>().map_err(|e| {
503                        ParseError::new(
504                            format!("invalid i64 literal `{integer}`: {e}"),
505                            integer.span(),
506                        )
507                    })?,
508                    span,
509                ),
510                "i128" => output.push_literal(
511                    integer.base10_parse::<i128>().map_err(|e| {
512                        ParseError::new(
513                            format!("invalid i128 literal `{integer}`: {e}"),
514                            integer.span(),
515                        )
516                    })?,
517                    span,
518                ),
519                "isize" => output.push_literal(
520                    integer.base10_parse::<isize>().map_err(|e| {
521                        ParseError::new(
522                            format!("invalid isize literal `{integer}`: {e}"),
523                            integer.span(),
524                        )
525                    })?,
526                    span,
527                ),
528                suffix => {
529                    return Err(ParseError::new(
530                        format!("invalid integer literal suffix: `{suffix}`"),
531                        integer.span(),
532                    ));
533                }
534            };
535        }
536        CelLiteral::Float(float) => {
537            let span = float.span();
538            match float.suffix() {
539                "" | "f64" => output.push_literal(
540                    float.base10_parse::<f64>().map_err(|e| {
541                        ParseError::new(format!("invalid f64 literal `{float}`: {e}"), float.span())
542                    })?,
543                    span,
544                ),
545                "f32" => output.push_literal(
546                    float.base10_parse::<f32>().map_err(|e| {
547                        ParseError::new(format!("invalid f32 literal `{float}`: {e}"), float.span())
548                    })?,
549                    span,
550                ),
551                suffix => {
552                    return Err(ParseError::new(
553                        format!("invalid float literal suffix: `{suffix}`"),
554                        float.span(),
555                    ));
556                }
557            };
558        }
559        CelLiteral::Str(string) => {
560            let span = string.span();
561            output.push_literal(string.value(), span);
562        }
563        CelLiteral::Bool(lit_bool) => {
564            let span = lit_bool.span();
565            output.push_literal(lit_bool.value, span);
566        }
567        CelLiteral::Char(ch) => {
568            let span = ch.span();
569            output.push_literal(ch.value(), span);
570        }
571        CelLiteral::Byte(byte) => {
572            let span = byte.span();
573            output.push_literal(byte.value(), span);
574        }
575        CelLiteral::ByteStr(byte_str) => {
576            let span = byte_str.span();
577            output.push_literal(byte_str.value(), span);
578        }
579        CelLiteral::CStr(c_str) => {
580            let span = c_str.span();
581            output.push_literal(c_str.value(), span);
582        }
583        other => {
584            return Err(ParseError::new(
585                format!("unsupported literal: {other:?}"),
586                other.span(),
587            ));
588        }
589    }
590    Ok(())
591}
592
593/// Validates a syntax literal using the expression parser's value rules.
594///
595/// Floating-point overflow produces infinity; unrepresentable integers are rejected.
596///
597/// # Errors
598///
599/// Returns `Err` for an unsupported literal kind or numeric suffix, a misplaced
600/// exponent sign, or a numeric value that cannot be parsed as its type.
601///
602/// - Complexity: Includes literal-token cloning and value parsing for the token's text.
603///
604/// # Examples
605/// ```
606/// let literal: syn::Lit = syn::parse_str("42i32").unwrap();
607/// cel_parser::validate_literal(&literal).unwrap();
608/// let float: syn::Lit = syn::parse_str("1f64").unwrap();
609/// cel_parser::validate_literal(&float).unwrap();
610/// ```
611pub fn validate_literal(lit: &CelLiteral) -> Result<()> {
612    push_literal_token(&mut DynSegmentContext::new_context(), lit.clone())
613}
614
615/// Validates `literal_pattern = ["-"] literal.` against its signed value.
616///
617/// Signed minima are valid only with a leading minus. Negated unsigned and
618/// non-numeric literals are rejected. Floating-point overflow produces infinity.
619///
620/// # Errors
621/// Returns an error for an invalid literal, unsupported suffix, or invalid negation.
622///
623/// - Complexity: O(n) time and space for n literal characters.
624///
625/// # Examples
626/// ```
627/// let literal: syn::Lit = syn::parse_str("9223372036854775808i64")?;
628/// cel_parser::validate_literal_pattern(&literal, true)?;
629/// assert!(cel_parser::validate_literal_pattern(&literal, false).is_err());
630/// # Ok::<(), Box<dyn std::error::Error>>(())
631/// ```
632pub fn validate_literal_pattern(lit: &CelLiteral, negated: bool) -> Result<()> {
633    let span = lit.span();
634    push_literal_pattern_token(
635        &mut DynSegmentContext::new_context(),
636        &OpLookup::new(),
637        lit.clone(),
638        negated,
639        ExprSpan {
640            start: span,
641            end: span,
642        },
643    )
644}
645
646/// Pushes a directly negated signed minimum, or leaves `output` unchanged.
647///
648/// Returns whether the token's magnitude is its signed type's minimum magnitude.
649/// Other tokens remain subject to ordinary literal validation and negation.
650///
651/// - Complexity: O(n) time for n integer digits.
652fn push_negated_minimum<C: ParserContext>(
653    output: &mut C,
654    lit: &CelLiteral,
655    span: ExprSpan,
656) -> bool {
657    let CelLiteral::Int(integer) = lit else {
658        return false;
659    };
660    let Ok(magnitude) = integer.base10_parse::<u128>() else {
661        return false;
662    };
663    macro_rules! push_minimum {
664        ($ty:ty) => {
665            if magnitude == <$ty>::MIN.unsigned_abs() as u128 {
666                output.push_literal(<$ty>::MIN, span.start.join(span.end).unwrap_or(span.end));
667                return true;
668            }
669        };
670    }
671    match integer.suffix() {
672        "" | "i32" => push_minimum!(i32),
673        "i8" => push_minimum!(i8),
674        "i16" => push_minimum!(i16),
675        "i64" => push_minimum!(i64),
676        "i128" => push_minimum!(i128),
677        "isize" => push_minimum!(isize),
678        _ => {}
679    }
680    false
681}
682
683/// Emits a literal pattern, combining a signed minimum before magnitude validation.
684///
685/// # Errors
686/// Returns a literal-validation or negation-dispatch error.
687///
688/// - Complexity: O(n) time and space for n literal characters, plus operator lookup.
689fn push_literal_pattern_token<C: ParserContext>(
690    output: &mut C,
691    lookup: &OpLookup,
692    lit: CelLiteral,
693    negated: bool,
694    span: ExprSpan,
695) -> Result<()> {
696    let lit = lex_lexer::normalize_literal(lit)
697        .map_err(|error| ParseError::new(error.to_string(), error.span()))?;
698    let can_negate = match &lit {
699        CelLiteral::Int(integer) => matches!(
700            integer.suffix(),
701            "" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize"
702        ),
703        CelLiteral::Float(_) => true,
704        _ => false,
705    };
706    if negated && push_negated_minimum(output, &lit, span) {
707        return Ok(());
708    }
709    push_normalized_literal(output, lit)?;
710    if negated {
711        if !can_negate {
712            return Err(ParseError::new(
713                "literal pattern: `-` can only negate a signed integer or float literal",
714                span.start,
715            ));
716        }
717        output.apply_op(lookup, "-", 1, span.start, span.end)?;
718    }
719    Ok(())
720}
721
722/// Converts one syntax literal into retained expression syntax without executing code.
723///
724/// Preserves the token's source span and concrete numeric width using the same validation
725/// as expression parsing. Floating-point overflow produces infinity.
726///
727/// # Errors
728/// Rejects unsupported literal kinds, invalid suffixes, misplaced exponent signs,
729/// and numeric values that cannot be parsed as their types.
730/// - Complexity: O(n) literal bytes.
731///
732/// # Examples
733/// ```
734/// let token: syn::Lit = syn::parse_str("42i32")?;
735/// assert!(matches!(cel_parser::literal_expr(&token)?,
736///     cel_parser::Expr::Literal { value: cel_parser::Literal::I32(42), .. }));
737/// let overflow: syn::Lit = syn::parse_str("340282366920938463463374607431768211456f32")?;
738/// cel_parser::validate_literal(&overflow)?;
739/// assert!(matches!(cel_parser::literal_expr(&overflow)?,
740///     cel_parser::Expr::Literal { value: cel_parser::Literal::F32(value), .. }
741///     if value.is_infinite() && value.is_sign_positive()));
742/// # Ok::<(), Box<dyn std::error::Error>>(())
743/// ```
744pub fn literal_expr(lit: &CelLiteral) -> Result<Expr> {
745    let mut context = AstContext::new_context();
746    push_literal_token(&mut context, lit.clone())?;
747    Ok(context.into_expr())
748}
749
750/// Converts a literal pattern into retained syntax with its sign and concrete numeric width.
751///
752/// `span` covers the optional minus and literal token. Floating-point overflow
753/// produces infinity.
754///
755/// # Errors
756/// Returns an error for an invalid literal, unsupported suffix, or invalid negation.
757///
758/// - Complexity: O(n) time and space for n literal characters.
759///
760/// # Examples
761/// ```
762/// use cel_parser::{Expr, ExprSpan, Literal, literal_pattern_expr};
763/// let mut tokens = "-128i8".parse::<proc_macro2::TokenStream>()?.into_iter();
764/// let start = tokens.next().unwrap().span();
765/// let token = tokens.next().unwrap();
766/// let span = ExprSpan { start, end: token.span() };
767/// let literal = syn::parse2(token.into())?;
768/// assert!(matches!(literal_pattern_expr(&literal, true, span)?,
769///     Expr::Literal { value: Literal::I8(-128), .. }));
770/// # Ok::<(), Box<dyn std::error::Error>>(())
771/// ```
772pub fn literal_pattern_expr(lit: &CelLiteral, negated: bool, span: ExprSpan) -> Result<Expr> {
773    let mut context = AstContext::new_context();
774    push_literal_pattern_token(&mut context, &OpLookup::new(), lit.clone(), negated, span)?;
775    Ok(context.into_expr())
776}
777
778/// Resolves a closure annotation through the configured registry without erasing its shape.
779///
780/// # Errors
781/// Returns annotation resolution errors or unrepresentable layout errors.
782/// - Complexity: O(number of type nodes).
783fn closure_param_type_from_type_expr(
784    type_expr: &TypeExpr,
785    resolver: &dyn TypeResolver,
786) -> Result<cel_runtime::ValueType> {
787    type_expr
788        .resolve(resolver)?
789        .into_value_type()
790        .map_err(|error| {
791            let span = type_expr.span();
792            ParseError::new_range(error.to_string(), span.start, span.end)
793        })
794}
795
796/// A recursive descent parser for expressions, generic over the [`ParserContext`] it emits
797/// into.
798///
799/// [`CELParser`] is a type alias for `Parser<DynSegmentContext>` and remains the concrete type
800/// most callers use; it behaves identically to how `CELParser` always has, before this type
801/// became generic.
802///
803/// # Examples
804///
805/// ## Basic Usage
806///
807/// ```rust
808/// use cel_parser::OpLookup;
809/// use cel_parser::CELParser;
810/// use proc_macro2::TokenStream;
811/// use std::str::FromStr;
812///
813/// let input = TokenStream::from_str("10").unwrap();
814/// let mut parser = CELParser::new(OpLookup::new());
815/// let result = parser.parse_tokens(input.into_iter());
816/// assert!(result.is_ok());
817/// ```
818///
819/// ## Error Formatting
820///
821/// ```rust
822/// use annotate_snippets::Renderer;
823/// use cel_parser::OpLookup;
824/// use cel_parser::CELParser;
825/// use proc_macro2::TokenStream;
826/// use std::str::FromStr;
827///
828/// let line = line!() + 1;
829/// let source = r#"
830///   10 + 20 30
831/// "#; // Invalid: missing operator
832/// let input = TokenStream::from_str(source).unwrap();
833/// let mut parser = CELParser::new(OpLookup::new());
834///
835/// if let Err(e) = parser.parse_tokens(input.into_iter()) {
836///     // Format error starting at line 1
837///     println!("{}", e.format_rustc_style(source, file!(), line, &Renderer::plain()));
838/// }
839/// ```
840pub struct Parser<C: ParserContext> {
841    tokens: Option<Peekable<LexLexer>>,
842    context: C,
843    op_lookup: OpLookup,
844    type_resolver: Box<dyn TypeResolver>,
845    last_span: Span,
846    /// Net count of `Delimiter::Brace`/`Delimiter::Bracket`/`Delimiter::Parenthesis` tokens
847    /// consumed since the last [`set_tokens`](Self::set_tokens)/
848    /// [`set_lex_tokens`](Self::set_lex_tokens) call that remain unmatched: incremented for an
849    /// `OpenDelim`, decremented for a `CloseDelim`. See
850    /// [`unbalanced_delimiter_count`](Self::unbalanced_delimiter_count).
851    unbalanced_delimiters: i32,
852    restriction: ExpressionRestriction,
853}
854
855/// Selects whether a header reserves an identifier's following brace for its body.
856///
857/// Explicit delimiters establish ordinary expression boundaries; unary, binary, and closure
858/// expressions inherit the surrounding restriction.
859///
860/// # Examples
861/// ```
862/// use cel_parser::{CELParser, ExpressionRestriction, OpLookup};
863/// let mut parser = CELParser::new(OpLookup::new());
864/// parser.set_tokens("true {}".parse::<proc_macro2::TokenStream>().unwrap().into_iter());
865/// parser.parse_expression_restricted(ExpressionRestriction::NoStructLiteral).unwrap();
866/// ```
867#[derive(Clone, Copy, Debug, PartialEq, Eq)]
868pub enum ExpressionRestriction {
869    /// Allows ordinary record literals.
870    None,
871    /// Leaves an unparenthesized identifier's following brace to the enclosing grammar.
872    NoStructLiteral,
873}
874
875/// A recursive descent parser that executes directly into a [`DynSegment`].
876///
877/// This is the parser every existing caller uses; behavior is unchanged from before [`Parser`]
878/// became generic over [`ParserContext`].
879///
880/// # Examples
881/// See [`Parser::parse_str`] for parsing and execution.
882pub type CELParser = Parser<DynSegmentContext>;
883
884impl<C: ParserContext> Parser<C> {
885    /// Creates a new CEL parser with the given operation lookup.
886    ///
887    /// No tokens are set at construction; use [`set_tokens`](Self::set_tokens),
888    /// [`parse_tokens_ctx`](Self::parse_tokens_ctx), or [`parse_str_ctx`](Self::parse_str_ctx)
889    /// to parse.
890    ///
891    /// # Arguments
892    ///
893    /// * `op_lookup` - Operation lookup for resolving operators and identifiers
894    ///
895    /// # Examples
896    /// See [`Self::parse_str_ctx`] for constructing and using a parser.
897    pub fn new(op_lookup: OpLookup) -> Self {
898        Self::with_boxed_type_resolver(op_lookup, type_expr::builtin_type_resolver())
899    }
900
901    /// Creates a new CEL parser with the given operation lookup and leaf type resolver.
902    ///
903    /// Existing callers that need only the built-in CEL scalar types should continue to use
904    /// [`new`](Self::new); this constructor is for hosts that want additional named CEL types
905    /// without coupling `cel-parser` to their own registry implementation.
906    ///
907    /// # Examples
908    ///
909    /// ```rust
910    /// use cel_parser::{CELParser, OpLookup, ResolvedLeafType};
911    /// use cel_runtime::ValueType;
912    ///
913    /// #[derive(Clone)]
914    /// struct Celsius(i32);
915    ///
916    /// let resolver = [(
917    ///     "Celsius",
918    ///     ResolvedLeafType::new("Celsius", ValueType::leaf::<Celsius>()),
919    /// )];
920    /// let mut segment = CELParser::with_type_resolver(OpLookup::new(), resolver)
921    ///     .parse_str("[]: [Celsius]")
922    ///     .unwrap();
923    /// let array = segment.call0::<cel_runtime::OwnedValue>().unwrap().try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<Celsius>>>().unwrap();
924    /// assert!(array.into_vec().is_empty());
925    /// ```
926    pub fn with_type_resolver<R>(op_lookup: OpLookup, type_resolver: R) -> Self
927    where
928        R: TypeResolver + 'static,
929    {
930        Self::with_boxed_type_resolver(op_lookup, Box::new(type_resolver))
931    }
932
933    /// Creates a parser that uniquely owns its compile-time type resolver.
934    fn with_boxed_type_resolver(op_lookup: OpLookup, type_resolver: Box<dyn TypeResolver>) -> Self {
935        Parser {
936            tokens: None,
937            context: C::new_context(),
938            op_lookup,
939            type_resolver,
940            last_span: Span::call_site(),
941            unbalanced_delimiters: 0,
942            restriction: ExpressionRestriction::None,
943        }
944    }
945
946    /// Replaces this parser's named-type resolver.
947    ///
948    /// Every subsequent parse resolves annotation type names through `type_resolver` instead of
949    /// the one this parser was built with.
950    ///
951    /// # Examples
952    ///
953    /// ```rust
954    /// use cel_parser::{CELParser, OpLookup, ResolvedLeafType};
955    /// use cel_runtime::ValueType;
956    ///
957    /// #[derive(Clone)]
958    /// struct Celsius(i32);
959    ///
960    /// let mut parser = CELParser::new(OpLookup::new());
961    /// assert!(parser.parse_str("[]: [Celsius]").is_err());
962    ///
963    /// parser.set_type_resolver([(
964    ///     "Celsius",
965    ///     ResolvedLeafType::new("Celsius", ValueType::leaf::<Celsius>()),
966    /// )]);
967    /// assert!(parser.parse_str("[]: [Celsius]").is_ok());
968    /// ```
969    pub fn set_type_resolver<R>(&mut self, type_resolver: R)
970    where
971        R: TypeResolver + 'static,
972    {
973        self.type_resolver = Box::new(type_resolver);
974    }
975
976    /// Resolves `expr` through this parser's configured leaf type resolver.
977    ///
978    /// # Errors
979    ///
980    /// Returns `Err` if some named leaf in `expr` is not recognized.
981    ///
982    /// # Examples
983    /// See [`Self::parse_type_expr_str`] for resolving parsed type syntax.
984    pub fn resolve_type_expr(&self, expr: &TypeExpr) -> Result<ResolvedType> {
985        expr.resolve(self.type_resolver.as_ref())
986    }
987
988    /// Sets the token stream for parsing, resetting internal state.
989    ///
990    /// Call before [`is_expression`](Self::is_expression) or use
991    /// [`parse_tokens_ctx`](Self::parse_tokens_ctx) which sets tokens and parses in one step.
992    ///
993    /// # Examples
994    /// See [`Self::parse_tokens_ctx`] for setting and consuming a token cursor.
995    pub fn set_tokens(&mut self, tokens: TokenStreamIter) {
996        self.tokens = Some(LexLexer::new(tokens).peekable());
997        self.context = C::new_context();
998        self.last_span = Span::call_site();
999        self.unbalanced_delimiters = 0;
1000    }
1001
1002    /// Sets the token stream from an existing [`LexLexer`] iterator for inline expression parsing.
1003    ///
1004    /// Resets the context. Use together with [`parse_expression_ctx`](Self::parse_expression_ctx)
1005    /// and [`take_lex_tokens`](Self::take_lex_tokens) to share a token stream between adam-lang and
1006    /// [`CELParser`].
1007    ///
1008    /// # Examples
1009    /// See [`Self::parse_tokens_ctx`] for installing an already lexed cursor.
1010    pub fn set_lex_tokens(&mut self, tokens: std::iter::Peekable<lex_lexer::LexLexer>) {
1011        self.tokens = Some(tokens);
1012        self.context = C::new_context();
1013        self.last_span = Span::call_site();
1014        self.unbalanced_delimiters = 0;
1015    }
1016
1017    /// Returns the net number of opening delimiters this parser has consumed since the last
1018    /// [`set_tokens`](Self::set_tokens)/[`set_lex_tokens`](Self::set_lex_tokens) call, that
1019    /// remain unmatched by a corresponding closing delimiter.
1020    ///
1021    /// Always `0` after a successful top-level parse: every delimiter this grammar opens (an
1022    /// `if`-expression's branch braces, a tuple/group literal's or call's parens), it also
1023    /// closes. Positive after a parse that returned `Err` from partway through a production that
1024    /// had already consumed one or more opening delimiters before failing — e.g. an
1025    /// `if`-expression whose then-branch fails to parse consumes the branch's opening `{` before
1026    /// erroring out, never reaching the matching `}`.
1027    ///
1028    /// An embedding caller that shares its own token stream with this parser (via
1029    /// [`set_lex_tokens`](Self::set_lex_tokens)/[`take_lex_tokens`](Self::take_lex_tokens)), and
1030    /// tracks its own nesting depth over that same stream, cannot otherwise tell a delimiter this
1031    /// parser left dangling apart from one still genuinely open in the caller's own grammar,
1032    /// since both use the same `Delimiter` kinds. Reading this count immediately after reclaiming
1033    /// the stream — regardless of whether the parse succeeded or failed — and folding it into the
1034    /// caller's own depth counter keeps that counter consistent with the physical nesting left
1035    /// behind in the stream.
1036    ///
1037    /// # Examples
1038    /// See [`Self::parse_tokens_ctx`] for the balanced-input case.
1039    pub fn unbalanced_delimiter_count(&self) -> i32 {
1040        self.unbalanced_delimiters
1041    }
1042
1043    /// Parses one `expression` from the current token stream and returns the built context.
1044    ///
1045    /// Unlike [`parse_str_ctx`](Self::parse_str_ctx), this method does not require
1046    /// end-of-stream, allowing adam-lang to parse an expression embedded within a larger token
1047    /// stream.
1048    ///
1049    /// # Errors
1050    ///
1051    /// Returns an error if the input does not contain a valid `expression`.
1052    ///
1053    /// - Complexity: O(n) in the number of tokens in the expression.
1054    ///
1055    /// # Examples
1056    /// See [`Self::parse_tokens_ctx`] for parsing from an installed cursor.
1057    pub fn parse_expression_ctx(&mut self) -> Result<C> {
1058        self.parse_expression_ctx_restricted(ExpressionRestriction::None)
1059    }
1060
1061    /// Parses one expression under `restriction`, restoring the previous mode on every result.
1062    ///
1063    /// Does not require end-of-stream, so the enclosing grammar retains its body brace.
1064    ///
1065    /// - Complexity: O(n) in the expression's token count.
1066    ///
1067    /// # Errors
1068    /// Returns an error for a malformed expression or a context's semantic rejection.
1069    ///
1070    /// # Examples
1071    /// See [`ExpressionRestriction`].
1072    pub fn parse_expression_ctx_restricted(
1073        &mut self,
1074        restriction: ExpressionRestriction,
1075    ) -> Result<C> {
1076        if !self.with_restriction(restriction, |p| p.is_expression())? {
1077            return Err(self.error_at("expression expected"));
1078        }
1079        Ok(std::mem::replace(&mut self.context, C::new_context()))
1080    }
1081
1082    /// Runs a grammar production in a temporary mode, restoring it on success and error.
1083    ///
1084    /// - Complexity: the invoked production's complexity.
1085    fn with_restriction<T>(
1086        &mut self,
1087        restriction: ExpressionRestriction,
1088        parse: impl FnOnce(&mut Self) -> Result<T>,
1089    ) -> Result<T> {
1090        let previous = std::mem::replace(&mut self.restriction, restriction);
1091        let result = parse(self);
1092        self.restriction = previous;
1093        result
1094    }
1095
1096    /// `ordinary_expression = expression.` Explicit delimiters lift header restrictions.
1097    ///
1098    /// # Errors
1099    /// Returns the nested expression's syntax or context error.
1100    /// - Complexity: O(n) in the expression's token count.
1101    fn is_ordinary_expression(&mut self) -> Result<bool> {
1102        self.with_restriction(ExpressionRestriction::None, |p| p.is_expression())
1103    }
1104
1105    /// Parses one `literal_pattern` from the current token stream and returns the built context.
1106    ///
1107    /// Like [`parse_expression_ctx`](Self::parse_expression_ctx), this does not require
1108    /// end-of-stream, letting a caller (e.g. adam-lang's `conditional_branch`) parse just the
1109    /// pattern before continuing with its own grammar.
1110    ///
1111    /// # Errors
1112    ///
1113    /// Returns an error if the input does not contain a valid `literal_pattern`.
1114    ///
1115    /// # Examples
1116    /// ```
1117    /// use cel_parser::{CELParser, OpLookup};
1118    /// use proc_macro2::TokenStream;
1119    /// let mut parser = CELParser::new(OpLookup::new());
1120    /// parser.set_tokens("7".parse::<TokenStream>().unwrap().into_iter());
1121    /// let context = parser.parse_literal_pattern_ctx().unwrap();
1122    /// assert_eq!(context.into_inner().call0::<i32>().unwrap(), 7);
1123    /// parser.set_tokens("8".parse::<TokenStream>().unwrap().into_iter());
1124    /// assert_eq!(parser.parse_literal_pattern().unwrap().call0::<i32>().unwrap(), 8);
1125    /// ```
1126    pub fn parse_literal_pattern_ctx(&mut self) -> Result<C> {
1127        if !self.is_literal_pattern()? {
1128            return Err(self.error_at("literal pattern expected"));
1129        }
1130        Ok(std::mem::replace(&mut self.context, C::new_context()))
1131    }
1132
1133    /// Compiles a fully independent nested context — used for a closure literal's body — by
1134    /// swapping `self.context` out for a fresh one, running `f` against it, then swapping the
1135    /// original context back in and returning the finished nested one.
1136    ///
1137    /// Unlike [`parse_expression_ctx`](Self::parse_expression_ctx), this does not reset
1138    /// `self.tokens`/`self.op_lookup`/`self.last_span` — it's for compiling a sub-expression in the
1139    /// middle of an already-in-progress outer parse, not starting a fresh top-level parse.
1140    ///
1141    /// # Errors
1142    ///
1143    /// Returns `Err` if `f` does, or if `f` returns `Ok(false)` (no expression found) — in both
1144    /// cases the outer context is still restored before returning.
1145    ///
1146    /// - Complexity: whatever `f`'s own parse cost is.
1147    pub(crate) fn parse_nested_context<F>(&mut self, f: F) -> Result<C>
1148    where
1149        F: FnOnce(&mut Self) -> Result<bool>,
1150    {
1151        let outer = std::mem::replace(&mut self.context, C::new_context());
1152        let outcome = f(self);
1153        let nested = std::mem::replace(&mut self.context, outer);
1154        match outcome {
1155            Ok(true) => Ok(nested),
1156            Ok(false) => Err(self.error_at("expected expression")),
1157            Err(e) => Err(e),
1158        }
1159    }
1160
1161    /// Returns the remaining token stream after expression parsing.
1162    ///
1163    /// Call after [`parse_expression_ctx`](Self::parse_expression_ctx) to recover the
1164    /// shared [`LexLexer`] for continued adam-lang parsing.
1165    ///
1166    /// # Examples
1167    /// See [`Self::parse_tokens_ctx`] for recovering the remaining cursor.
1168    pub fn take_lex_tokens(&mut self) -> Option<std::iter::Peekable<lex_lexer::LexLexer>> {
1169        self.tokens.take()
1170    }
1171
1172    /// Parses a token stream into a context value.
1173    ///
1174    /// Sets the token source, runs the expression grammar, and returns the context on success.
1175    ///
1176    /// # Errors
1177    ///
1178    /// Returns an error if the input does not contain a valid CEL expression.
1179    ///
1180    /// # Examples
1181    /// ```
1182    /// use cel_parser::{CELParser, OpLookup, lex_lexer::LexLexer};
1183    /// use proc_macro2::TokenStream;
1184    /// let mut parser = CELParser::new(OpLookup::new());
1185    /// parser.set_tokens("42".parse::<TokenStream>().unwrap().into_iter());
1186    /// assert!(parser.is_expression().unwrap());
1187    /// assert_eq!(parser.unbalanced_delimiter_count(), 0);
1188    /// assert!(parser.take_lex_tokens().unwrap().peek().is_none());
1189    /// let tokens = "42".parse::<TokenStream>().unwrap();
1190    /// parser.set_lex_tokens(LexLexer::new(tokens.into_iter()).peekable());
1191    /// let context = parser.parse_expression_ctx().unwrap();
1192    /// assert_eq!(context.into_inner().call0::<i32>().unwrap(), 42);
1193    /// assert!(parser.take_lex_tokens().unwrap().peek().is_none());
1194    /// let tokens = "43".parse::<TokenStream>().unwrap();
1195    /// let context = parser.parse_tokens_ctx(tokens.into_iter()).unwrap();
1196    /// assert_eq!(context.into_inner().call0::<i32>().unwrap(), 43);
1197    /// ```
1198    pub fn parse_tokens_ctx(&mut self, tokens: TokenStreamIter) -> Result<C> {
1199        self.set_tokens(tokens);
1200        if !self.is_expression()? {
1201            return Err(self.error_at("expression expected"));
1202        }
1203        if self.peek_token().is_some() {
1204            return Err(self.error_at("unexpected token"));
1205        }
1206        Ok(std::mem::replace(&mut self.context, C::new_context()))
1207    }
1208
1209    /// Parses a string into a context value.
1210    ///
1211    /// Tokenizes the string then parses; equivalent to
1212    /// `parse_tokens_ctx(TokenStream::from_str(s)?.into_iter())`.
1213    ///
1214    /// # Errors
1215    ///
1216    /// Returns an error on lex failure or if the input does not contain a valid CEL expression.
1217    ///
1218    /// # Examples
1219    /// ```
1220    /// use cel_parser::{CELParser, OpLookup};
1221    /// let context = CELParser::new(OpLookup::new()).parse_str_ctx("40 + 2").unwrap();
1222    /// assert_eq!(context.into_inner().call0::<i32>().unwrap(), 42);
1223    /// ```
1224    pub fn parse_str_ctx(&mut self, s: &str) -> Result<C> {
1225        let input = TokenStream::from_str(s).map_err(|e| ParseError::from_lex_error(s, e))?;
1226        self.parse_tokens_ctx(input.into_iter())
1227    }
1228
1229    /// Parses one complete `type_expr` from the current token stream.
1230    ///
1231    /// Unlike [`parse_type_expr_str`](Self::parse_type_expr_str), this method does not require
1232    /// ownership of the whole source string; it consumes only as many tokens as the type
1233    /// expression itself needs from the current stream.
1234    ///
1235    /// # Errors
1236    ///
1237    /// Returns an error if the current token stream does not begin with a valid type expression.
1238    ///
1239    /// # Examples
1240    /// See [`Self::parse_type_expr_str`] for parsing from strings and installed cursors.
1241    pub fn parse_type_expr(&mut self) -> Result<TypeExpr> {
1242        self.parse_type_expression()
1243    }
1244
1245    /// Parses one complete `type_expr` from `tokens`.
1246    ///
1247    /// # Errors
1248    ///
1249    /// Returns an error if `tokens` does not contain a valid complete type expression.
1250    ///
1251    /// # Examples
1252    /// See [`Self::parse_type_expr_str`] for parsing a complete token stream.
1253    pub fn parse_type_expr_tokens(&mut self, tokens: TokenStreamIter) -> Result<TypeExpr> {
1254        self.set_tokens(tokens);
1255        let expr = self.parse_type_expr()?;
1256        if self.peek_token().is_some() {
1257            return Err(self.error_at("unexpected token"));
1258        }
1259        Ok(expr)
1260    }
1261
1262    /// Parses one complete `type_expr` from `s`.
1263    ///
1264    /// # Errors
1265    ///
1266    /// Returns an error on lex failure or if `s` does not contain a valid complete type
1267    /// expression.
1268    ///
1269    /// # Examples
1270    /// ```
1271    /// use cel_parser::{CELParser, OpLookup};
1272    /// use proc_macro2::TokenStream;
1273    /// let mut parser = CELParser::new(OpLookup::new());
1274    /// let syntax = parser.parse_type_expr_str("[i32]").unwrap();
1275    /// assert_eq!(parser.resolve_type_expr(&syntax).unwrap().display_name(), "[i32]");
1276    /// let tokens = "u32".parse::<TokenStream>().unwrap();
1277    /// let syntax = parser.parse_type_expr_tokens(tokens.into_iter()).unwrap();
1278    /// assert_eq!(parser.resolve_type_expr(&syntax).unwrap().display_name(), "u32");
1279    /// parser.set_tokens("bool".parse::<TokenStream>().unwrap().into_iter());
1280    /// let syntax = parser.parse_type_expr().unwrap();
1281    /// assert_eq!(parser.resolve_type_expr(&syntax).unwrap().display_name(), "bool");
1282    /// parser.set_tokens("i64".parse::<TokenStream>().unwrap().into_iter());
1283    /// let syntax = parser.parse_type_expression().unwrap();
1284    /// assert_eq!(parser.resolve_type_expr(&syntax).unwrap().display_name(), "i64");
1285    /// ```
1286    pub fn parse_type_expr_str(&mut self, s: &str) -> Result<TypeExpr> {
1287        let input = TokenStream::from_str(s).map_err(|e| ParseError::from_lex_error(s, e))?;
1288        self.parse_type_expr_tokens(input.into_iter())
1289    }
1290
1291    /// Returns a mutable reference to the operation lookup.
1292    ///
1293    /// This allows customization of the operations available during parsing,
1294    /// such as adding new scopes for custom operations or identifiers.
1295    ///
1296    /// # Examples
1297    ///
1298    /// ```rust
1299    /// use cel_parser::op_table::OpLookup;
1300    /// use cel_parser::CELParser;
1301    /// use cel_runtime::DynSegment;
1302    /// use proc_macro2::TokenStream;
1303    /// use std::any::TypeId;
1304    /// use std::str::FromStr;
1305    ///
1306    /// let input = TokenStream::from_str("10 + 20").unwrap();
1307    /// let mut lookup = OpLookup::new();
1308    /// lookup.push_scope(|name, segment, num_operands, _span| {
1309    ///     let matches = {
1310    ///         let top = segment.peek_stack_infos(num_operands);
1311    ///         name == "+" && top.len() == 2 && top[0].value_type.type_id() == TypeId::of::<i32>()
1312    ///     };
1313    ///     if matches {
1314    ///         segment.op2(|a: i32, b: i32| a + b + 1)?; // Custom addition
1315    ///         Ok(true)
1316    ///     } else {
1317    ///         Ok(false)
1318    ///     }
1319    /// });
1320    /// let mut parser = CELParser::new(lookup);
1321    /// parser.set_tokens(input.into_iter());
1322    /// ```
1323    pub fn op_lookup_mut(&mut self) -> &mut OpLookup {
1324        &mut self.op_lookup
1325    }
1326
1327    /// Advances past the current token, recording its span in `last_span`.
1328    ///
1329    /// - Postcondition: [`unbalanced_delimiter_count`](Self::unbalanced_delimiter_count) is
1330    ///   incremented if the consumed token is an `OpenDelim`, decremented if it is a
1331    ///   `CloseDelim` (of `Delimiter::Brace`, `Delimiter::Bracket`, or `Delimiter::Parenthesis`;
1332    ///   `Delimiter::None` never appears in a token stream this parser is given, since it only
1333    ///   ever arises from `proc_macro2`'s macro-hygiene groups, not from parsing source text).
1334    ///
1335    /// # Panics
1336    ///
1337    /// Panics if no token stream has been set or if there is no current token.
1338    fn advance(&mut self) {
1339        use lex_lexer::HasSpan;
1340        let token = self
1341            .tokens
1342            .as_mut()
1343            .expect("tokens set")
1344            .next()
1345            .expect("token required to advance");
1346        match &token {
1347            Token::OpenDelim {
1348                delimiter: Delimiter::Brace | Delimiter::Bracket | Delimiter::Parenthesis,
1349                ..
1350            } => self.unbalanced_delimiters += 1,
1351            Token::CloseDelim {
1352                delimiter: Delimiter::Brace | Delimiter::Bracket | Delimiter::Parenthesis,
1353                ..
1354            } => self.unbalanced_delimiters -= 1,
1355            _ => {}
1356        }
1357        self.last_span = token.span();
1358    }
1359
1360    /// Returns the span of the next token without consuming it, or `None` if exhausted.
1361    fn peek_span(&mut self) -> Option<Span> {
1362        self.peek_token().map(|token| {
1363            use lex_lexer::HasSpan;
1364            token.span()
1365        })
1366    }
1367
1368    /// Peeks at the current token without consuming it.
1369    ///
1370    /// Returns `None` if there are no more tokens.
1371    fn peek_token(&mut self) -> Option<&Token> {
1372        self.tokens.as_mut().expect("tokens set").peek()
1373    }
1374
1375    /// Builds a [`ParseError`] at the current token's span (or call_site if no token).
1376    fn error_at(&mut self, message: &str) -> ParseError {
1377        let span = match self.peek_token() {
1378            Some(token) => {
1379                use lex_lexer::HasSpan;
1380                token.span()
1381            }
1382            None => Span::call_site(),
1383        };
1384        ParseError::new(message, span)
1385    }
1386
1387    /// Consumes and returns `true` if the next token is punctuation matching `target`.
1388    fn is_punctuation(&mut self, target: &str) -> bool {
1389        match self.peek_token() {
1390            Some(Token::Punct { op, .. }) if op == target => {
1391                self.advance();
1392                true
1393            }
1394            _ => false,
1395        }
1396    }
1397
1398    /// Consumes and returns `true` if the next token is an identifier matching `keyword`.
1399    fn is_keyword(&mut self, keyword: &str) -> bool {
1400        match self.peek_token() {
1401            Some(Token::Identifier(ident)) if ident == keyword => {
1402                self.advance();
1403                true
1404            }
1405            _ => false,
1406        }
1407    }
1408
1409    /// Consumes and returns the next token's text if it is an identifier.
1410    ///
1411    /// # Errors
1412    ///
1413    /// Returns an error with `message` if the next token is not an identifier.
1414    fn expect_identifier(&mut self, message: &str) -> Result<String> {
1415        match self.peek_token() {
1416            Some(Token::Identifier(ident)) => {
1417                let name = ident.to_string();
1418                self.advance();
1419                Ok(name)
1420            }
1421            _ => Err(self.error_at(message)),
1422        }
1423    }
1424
1425    /// Consumes and returns `true` if the next token is an opening parenthesis `(`.
1426    fn is_open_paren(&mut self) -> bool {
1427        if matches!(
1428            self.peek_token(),
1429            Some(Token::OpenDelim {
1430                delimiter: Delimiter::Parenthesis,
1431                ..
1432            })
1433        ) {
1434            self.advance();
1435            true
1436        } else {
1437            false
1438        }
1439    }
1440
1441    /// Consumes and returns `true` if the next token is a closing parenthesis `)`.
1442    fn is_close_paren(&mut self) -> bool {
1443        if matches!(
1444            self.peek_token(),
1445            Some(Token::CloseDelim {
1446                delimiter: Delimiter::Parenthesis,
1447                ..
1448            })
1449        ) {
1450            self.advance();
1451            true
1452        } else {
1453            false
1454        }
1455    }
1456
1457    /// Consumes and returns `true` if the next token is a closing bracket `]`.
1458    fn is_close_bracket(&mut self) -> bool {
1459        if matches!(
1460            self.peek_token(),
1461            Some(Token::CloseDelim {
1462                delimiter: Delimiter::Bracket,
1463                ..
1464            })
1465        ) {
1466            self.advance();
1467            true
1468        } else {
1469            false
1470        }
1471    }
1472
1473    /// `expression = closure_expression | range_expression.`
1474    ///
1475    /// # Examples
1476    /// See [`Self::parse_tokens_ctx`] for recognizing an expression on the current cursor.
1477    pub fn is_expression(&mut self) -> Result<bool> {
1478        if self.is_punctuation("||") {
1479            self.is_closure_expression(true)
1480        } else if self.is_punctuation("|") {
1481            self.is_closure_expression(false)
1482        } else {
1483            self.is_range_expression()
1484        }
1485    }
1486
1487    /// `or_expression = and_expression { "||" and_expression }.`
1488    ///
1489    /// # Errors
1490    ///
1491    /// Returns an error if the RHS is missing after `||`, if the RHS does not
1492    /// produce a `bool`, or if any sub-expression returns an error.
1493    fn is_or_expression(&mut self) -> Result<bool> {
1494        let start_span = self.peek_span();
1495        if self.is_and_expression()? {
1496            while self.is_punctuation("||") {
1497                let mut rhs_fragment = self.context.new_fragment();
1498                std::mem::swap(&mut self.context, &mut rhs_fragment);
1499                if !self.is_and_expression()? {
1500                    return Err(self.error_at("expected and_expression"));
1501                }
1502                std::mem::swap(&mut self.context, &mut rhs_fragment);
1503                self.context.apply_logical(
1504                    "||",
1505                    rhs_fragment,
1506                    start_span.expect("production has token at start"),
1507                    self.last_span,
1508                )?;
1509            }
1510            Ok(true)
1511        } else {
1512            Ok(false)
1513        }
1514    }
1515
1516    /// `and_expression = comparison_expression { "&&" comparison_expression }.`
1517    ///
1518    /// # Errors
1519    ///
1520    /// Returns an error if the RHS is missing after `&&`, if the RHS does not
1521    /// produce a `bool`, or if any sub-expression returns an error.
1522    fn is_and_expression(&mut self) -> Result<bool> {
1523        let start_span = self.peek_span();
1524        if self.is_comparison_expression()? {
1525            while self.is_punctuation("&&") {
1526                let mut rhs_fragment = self.context.new_fragment();
1527                std::mem::swap(&mut self.context, &mut rhs_fragment);
1528                if !self.is_comparison_expression()? {
1529                    return Err(self.error_at("expected comparison_expression"));
1530                }
1531                std::mem::swap(&mut self.context, &mut rhs_fragment);
1532                self.context.apply_logical(
1533                    "&&",
1534                    rhs_fragment,
1535                    start_span.expect("production has token at start"),
1536                    self.last_span,
1537                )?;
1538            }
1539            Ok(true)
1540        } else {
1541            Ok(false)
1542        }
1543    }
1544
1545    /// `comparison_expression = bitwise_or_expression
1546    ///     [ ("==" | "!=" | "<" | ">" | "<=" | ">=") bitwise_or_expression ].`
1547    fn is_comparison_expression(&mut self) -> Result<bool> {
1548        let start_span = self.peek_span();
1549        if self.is_bitwise_or_expression()? {
1550            // Longer operators first: must check "==" before "=", "<=" before "<", etc.
1551            let op_name = if self.is_punctuation("==") {
1552                Some("==")
1553            } else if self.is_punctuation("!=") {
1554                Some("!=")
1555            } else if self.is_punctuation("<=") {
1556                Some("<=")
1557            } else if self.is_punctuation(">=") {
1558                Some(">=")
1559            } else if self.is_punctuation("<") {
1560                Some("<")
1561            } else if self.is_punctuation(">") {
1562                Some(">")
1563            } else {
1564                None
1565            };
1566
1567            if let Some(op_name) = op_name {
1568                if !self.is_bitwise_or_expression()? {
1569                    return Err(self.error_at("expected bitwise_or_expression"));
1570                }
1571                self.context.apply_op(
1572                    &self.op_lookup,
1573                    op_name,
1574                    2,
1575                    start_span.expect("production has token at start"),
1576                    self.last_span,
1577                )?;
1578            }
1579            Ok(true)
1580        } else {
1581            Ok(false)
1582        }
1583    }
1584
1585    /// `range_expression = or_expression [ ".." [ or_expression ] | "..=" or_expression ]
1586    ///                   | ".." [ or_expression ]
1587    ///                   | "..=" or_expression.`
1588    ///
1589    /// Left-factored so every alternative is chosen by one concrete leading token rather
1590    /// than by first deciding whether an optional `or_expression` is present: the three
1591    /// alternatives start with `or_expression`'s own FIRST set, the literal `".."`, or the
1592    /// literal `"..="` respectively — pairwise disjoint (`..`/`..=` can never be the first
1593    /// token of an `or_expression`), so picking among them needs exactly one token, and none
1594    /// of them opens with a bracketed, possibly-empty non-terminal.
1595    ///
1596    /// `..`'s right operand is optional wherever it appears (covering, across the three
1597    /// alternatives, `Range`/`RangeFrom`/`RangeTo`/`RangeFull`); `..=`'s right operand is
1598    /// never optional (covering `RangeInclusive`/`RangeToInclusive`) — there is no
1599    /// inclusive-from-only range in Rust, and no such form is registered in the op-table for
1600    /// it to dispatch to, so a bare `..=`, or a left operand followed by `..=` and nothing
1601    /// after, is a parse error, not a valid empty match.
1602    ///
1603    /// Operands are `or_expression` — matching Rust's own precedence, where `..`/`..=` bind
1604    /// *looser* than `||` (and everything below it: `&&`, comparisons, bitwise ops,
1605    /// arithmetic). So `1 + 2..3 * 4` still groups as `(1 + 2)..(3 * 4)` (arithmetic is well
1606    /// inside `or_expression`'s own chain), and `a == b..c == d` groups the *whole*
1607    /// comparisons as the two endpoints: `(a == b)..(c == d)`, not `a == (b..c) == d`.
1608    fn is_range_expression(&mut self) -> Result<bool> {
1609        let start_span = self.peek_span();
1610
1611        if self.is_punctuation("..=") {
1612            if !self.is_or_expression()? {
1613                return Err(self.error_at("expected or_expression"));
1614            }
1615            self.context.apply_op(
1616                &self.op_lookup,
1617                "range_to_inclusive",
1618                1,
1619                start_span.expect("production has token at start"),
1620                self.last_span,
1621            )?;
1622            return Ok(true);
1623        }
1624
1625        if self.is_punctuation("..") {
1626            if self.is_or_expression()? {
1627                self.context.apply_op(
1628                    &self.op_lookup,
1629                    "range_to",
1630                    1,
1631                    start_span.expect("production has token at start"),
1632                    self.last_span,
1633                )?;
1634            } else {
1635                self.context.apply_op(
1636                    &self.op_lookup,
1637                    "range_full",
1638                    0,
1639                    start_span.expect("production has token at start"),
1640                    self.last_span,
1641                )?;
1642            }
1643            return Ok(true);
1644        }
1645
1646        if self.is_or_expression()? {
1647            if self.is_punctuation("..=") {
1648                if !self.is_or_expression()? {
1649                    return Err(self.error_at("expected or_expression"));
1650                }
1651                self.context.apply_op(
1652                    &self.op_lookup,
1653                    "range_inclusive",
1654                    2,
1655                    start_span.expect("production has token at start"),
1656                    self.last_span,
1657                )?;
1658            } else if self.is_punctuation("..") {
1659                if self.is_or_expression()? {
1660                    self.context.apply_op(
1661                        &self.op_lookup,
1662                        "range",
1663                        2,
1664                        start_span.expect("production has token at start"),
1665                        self.last_span,
1666                    )?;
1667                } else {
1668                    self.context.apply_op(
1669                        &self.op_lookup,
1670                        "range_from",
1671                        1,
1672                        start_span.expect("production has token at start"),
1673                        self.last_span,
1674                    )?;
1675                }
1676            }
1677            Ok(true)
1678        } else {
1679            Ok(false)
1680        }
1681    }
1682
1683    /// `bitwise_or_expression = bitwise_xor_expression { "|" bitwise_xor_expression }.`
1684    fn is_bitwise_or_expression(&mut self) -> Result<bool> {
1685        let start_span = self.peek_span();
1686        if self.is_bitwise_xor_expression()? {
1687            while self.is_punctuation("|") {
1688                if !self.is_bitwise_xor_expression()? {
1689                    return Err(self.error_at("expected bitwise_xor_expression"));
1690                }
1691                self.context.apply_op(
1692                    &self.op_lookup,
1693                    "|",
1694                    2,
1695                    start_span.expect("production has token at start"),
1696                    self.last_span,
1697                )?;
1698            }
1699            Ok(true)
1700        } else {
1701            Ok(false)
1702        }
1703    }
1704
1705    /// `bitwise_xor_expression = bitwise_and_expression { "^" bitwise_and_expression }.`
1706    fn is_bitwise_xor_expression(&mut self) -> Result<bool> {
1707        let start_span = self.peek_span();
1708        if self.is_bitwise_and_expression()? {
1709            while self.is_punctuation("^") {
1710                if !self.is_bitwise_and_expression()? {
1711                    return Err(self.error_at("expected bitwise_and_expression"));
1712                }
1713                self.context.apply_op(
1714                    &self.op_lookup,
1715                    "^",
1716                    2,
1717                    start_span.expect("production has token at start"),
1718                    self.last_span,
1719                )?;
1720            }
1721            Ok(true)
1722        } else {
1723            Ok(false)
1724        }
1725    }
1726
1727    /// `bitwise_and_expression = bitwise_shift_expression { "&" bitwise_shift_expression }.`
1728    fn is_bitwise_and_expression(&mut self) -> Result<bool> {
1729        let start_span = self.peek_span();
1730        if self.is_bitwise_shift_expression()? {
1731            while self.is_punctuation("&") {
1732                if !self.is_bitwise_shift_expression()? {
1733                    return Err(self.error_at("expected bitwise_shift_expression"));
1734                }
1735                self.context.apply_op(
1736                    &self.op_lookup,
1737                    "&",
1738                    2,
1739                    start_span.expect("production has token at start"),
1740                    self.last_span,
1741                )?;
1742            }
1743            Ok(true)
1744        } else {
1745            Ok(false)
1746        }
1747    }
1748
1749    /// `bitwise_shift_expression = additive_expression { ("<<" | ">>") additive_expression }.`
1750    fn is_bitwise_shift_expression(&mut self) -> Result<bool> {
1751        let start_span = self.peek_span();
1752        if self.is_additive_expression()? {
1753            loop {
1754                let op_name = if self.is_punctuation("<<") {
1755                    Some("<<")
1756                } else if self.is_punctuation(">>") {
1757                    Some(">>")
1758                } else {
1759                    None
1760                };
1761
1762                if let Some(op_name) = op_name {
1763                    if !self.is_additive_expression()? {
1764                        return Err(self.error_at("expected additive_expression"));
1765                    }
1766                    self.context.apply_op(
1767                        &self.op_lookup,
1768                        op_name,
1769                        2,
1770                        start_span.expect("production has token at start"),
1771                        self.last_span,
1772                    )?;
1773                } else {
1774                    break;
1775                }
1776            }
1777            Ok(true)
1778        } else {
1779            Ok(false)
1780        }
1781    }
1782
1783    /// `additive_expression = multiplicative_expression { ("+" | "-") multiplicative_expression }.`
1784    fn is_additive_expression(&mut self) -> Result<bool> {
1785        let start_span = self.peek_span();
1786        if self.is_multiplicative_expression()? {
1787            loop {
1788                let op_name = if self.is_punctuation("+") {
1789                    Some("+")
1790                } else if self.is_punctuation("-") {
1791                    Some("-")
1792                } else {
1793                    None
1794                };
1795
1796                if let Some(op_name) = op_name {
1797                    if !self.is_multiplicative_expression()? {
1798                        return Err(self.error_at("expected multiplicative_expression"));
1799                    }
1800                    self.context.apply_op(
1801                        &self.op_lookup,
1802                        op_name,
1803                        2,
1804                        start_span.expect("production has token at start"),
1805                        self.last_span,
1806                    )?;
1807                } else {
1808                    break;
1809                }
1810            }
1811            Ok(true)
1812        } else {
1813            Ok(false)
1814        }
1815    }
1816
1817    /// `multiplicative_expression = cast_expression { ("*" | "/" | "%") cast_expression }.`
1818    fn is_multiplicative_expression(&mut self) -> Result<bool> {
1819        let start_span = self.peek_span();
1820        if self.is_cast_expression()? {
1821            loop {
1822                let op_name = if self.is_punctuation("*") {
1823                    Some("*")
1824                } else if self.is_punctuation("/") {
1825                    Some("/")
1826                } else if self.is_punctuation("%") {
1827                    Some("%")
1828                } else {
1829                    None
1830                };
1831
1832                if let Some(op_name) = op_name {
1833                    if !self.is_cast_expression()? {
1834                        return Err(self.error_at("expected cast_expression"));
1835                    }
1836                    self.context.apply_op(
1837                        &self.op_lookup,
1838                        op_name,
1839                        2,
1840                        start_span.expect("production has token at start"),
1841                        self.last_span,
1842                    )?;
1843                } else {
1844                    break;
1845                }
1846            }
1847            Ok(true)
1848        } else {
1849            Ok(false)
1850        }
1851    }
1852
1853    /// `cast_expression = unary_expression { "as" identifier }.`
1854    ///
1855    /// Binds tighter than `* / %` but looser than unary prefix and postfix, matching Rust: `-x as
1856    /// f64` is `(-x) as f64`, and `x as i32 as f64` applies left-to-right (`(x as i32) as f64`).
1857    ///
1858    /// # Errors
1859    ///
1860    /// Returns an error if `"as"` isn't followed by an identifier, or if any sub-expression
1861    /// returns an error.
1862    fn is_cast_expression(&mut self) -> Result<bool> {
1863        let start_span = self.peek_span();
1864        if self.is_unary_expression()? {
1865            while self.is_keyword("as") {
1866                let type_name = match self.peek_token() {
1867                    Some(Token::Identifier(ident)) => ident.to_string(),
1868                    _ => return Err(self.error_at("expected type name after `as`")),
1869                };
1870                self.advance();
1871                self.context.apply_cast(
1872                    &self.op_lookup,
1873                    &type_name,
1874                    start_span.expect("production has token at start"),
1875                    self.last_span,
1876                )?;
1877            }
1878            Ok(true)
1879        } else {
1880            Ok(false)
1881        }
1882    }
1883
1884    /// `unary_expression = ("-" | "!") unary_expression | postfix_expression.`
1885    fn is_unary_expression(&mut self) -> Result<bool> {
1886        let start_span = self.peek_span();
1887        let op_name = if self.is_punctuation("-") {
1888            Some("-")
1889        } else if self.is_punctuation("!") {
1890            Some("!")
1891        } else {
1892            None
1893        };
1894
1895        if let Some(op_name) = op_name {
1896            if op_name == "-"
1897                && let Some(Token::Literal(lit)) = self.peek_token()
1898            {
1899                let lit = lit.clone();
1900                let literal_span = lit.span();
1901                self.advance();
1902                let has_postfix = matches!(self.peek_token(),
1903                    Some(Token::Punct { op, .. }) if op == ".")
1904                    || matches!(
1905                        self.peek_token(),
1906                        Some(Token::OpenDelim {
1907                            delimiter: Delimiter::Parenthesis,
1908                            ..
1909                        })
1910                    );
1911                if !has_postfix
1912                    && push_negated_minimum(
1913                        &mut self.context,
1914                        &lit,
1915                        ExprSpan {
1916                            start: start_span.expect("production has token at start"),
1917                            end: self.last_span,
1918                        },
1919                    )
1920                {
1921                    return Ok(true);
1922                }
1923                push_literal_token(&mut self.context, lit)?;
1924                self.postfix_suffixes(literal_span)?;
1925            } else if !self.is_unary_expression()? {
1926                return Err(self.error_at("expected unary_expression"));
1927            }
1928            self.context.apply_op(
1929                &self.op_lookup,
1930                op_name,
1931                1,
1932                start_span.expect("production has token at start"),
1933                self.last_span,
1934            )?;
1935            Ok(true)
1936        } else {
1937            self.is_postfix_expression()
1938        }
1939    }
1940
1941    /// `literal_pattern = ["-"] literal.`
1942    ///
1943    /// A deliberately narrower relative of [`is_unary_expression`](Self::is_unary_expression):
1944    /// Rust's own pattern grammar allows a leading unary `-` only directly on a literal (no
1945    /// `!`, no chained `--`, and the operand must be a bare literal token, not an arbitrary
1946    /// `postfix_expression`).
1947    ///
1948    /// # Errors
1949    ///
1950    /// Returns an error if a leading `-` is not followed by a literal, or if the literal or its
1951    /// negation fails (e.g. an out-of-range suffixed integer, or negating an unsigned literal).
1952    fn is_literal_pattern(&mut self) -> Result<bool> {
1953        let start_span = self.peek_span();
1954        let negated = self.is_punctuation("-");
1955        match self.peek_token() {
1956            Some(Token::Literal(lit)) => {
1957                let lit_clone = lit.clone();
1958                self.advance();
1959                push_literal_pattern_token(
1960                    &mut self.context,
1961                    &self.op_lookup,
1962                    lit_clone,
1963                    negated,
1964                    ExprSpan {
1965                        start: start_span.expect("production has token at start"),
1966                        end: self.last_span,
1967                    },
1968                )?;
1969                Ok(true)
1970            }
1971            _ if negated => Err(self.error_at("expected literal after `-`")),
1972            _ => Ok(false),
1973        }
1974    }
1975
1976    /// `postfix_expression = primary_expression { postfix_suffix }.`
1977    ///
1978    /// `postfix_suffix = "(" [ parameter_list ] ")" | "." (unsuffixed_integer | identifier).`
1979    ///
1980    /// The repetition allows chained indices (`t.0.1`): each `"." unsuffixed_integer`
1981    /// is applied in turn to whatever value the previous step left on top of the
1982    /// stack. Source text like `.0.1` tokenizes as a single `.` followed by one
1983    /// float literal `0.1` (Rust's own lexer maximally munches the digits after
1984    /// the second `.`), so that case is detected and split back into its two
1985    /// integer indices — see the `Token::Literal(CelLiteral::Float(..))` arm below.
1986    /// Named members consume their optional argument list as one operation, not a call
1987    /// of a previously evaluated scalar result.
1988    ///
1989    /// # Errors
1990    ///
1991    /// Returns malformed selector conversion errors at the original selector token,
1992    /// including a single maximally munched float token containing chained indices.
1993    fn is_postfix_expression(&mut self) -> Result<bool> {
1994        let start_span = self.peek_span();
1995        if !self.is_primary_expression()? {
1996            return Ok(false);
1997        }
1998        self.postfix_suffixes(start_span.expect("production has token at start"))?;
1999        Ok(true)
2000    }
2001
2002    /// `postfix_suffixes = { postfix_suffix }.`
2003    ///
2004    /// - Precondition: the primary expression starting at `start_span` is emitted.
2005    /// - Complexity: O(n) in the suffix tokens and argument expressions.
2006    ///
2007    /// # Errors
2008    /// Returns malformed suffix or context-emission errors.
2009    fn postfix_suffixes(&mut self, start_span: Span) -> Result<()> {
2010        loop {
2011            if let Some(arg_count) = self.postfix_arguments()? {
2012                // Stack order is [callee, arg1, arg2, ...]; lookup peeks top (arg_count + 1) entries.
2013                self.context.apply_op(
2014                    &self.op_lookup,
2015                    "()",
2016                    arg_count + 1,
2017                    start_span,
2018                    self.last_span,
2019                )?;
2020            } else if self.is_punctuation(".") {
2021                match self.peek_token() {
2022                    Some(Token::Identifier(_)) => {
2023                        let name_start = self.peek_span().expect("member has a name token");
2024                        let name = self.expect_identifier("expected member name")?;
2025                        let name_span = ExprSpan {
2026                            start: name_start,
2027                            end: name_start,
2028                        };
2029                        let explicit_args = self.postfix_arguments()?;
2030                        self.context.apply_member(
2031                            &self.op_lookup,
2032                            &name,
2033                            name_span,
2034                            explicit_args,
2035                            start_span,
2036                            self.last_span,
2037                        )?;
2038                    }
2039                    Some(Token::Literal(CelLiteral::Int(integer))) => {
2040                        let integer = integer.clone();
2041                        if !integer.suffix().is_empty() {
2042                            return Err(self.error_at("tuple index must be an unsuffixed integer"));
2043                        }
2044                        self.advance();
2045                        let index = integer.base10_parse::<usize>().map_err(|e| {
2046                            ParseError::new(
2047                                format!("invalid tuple index `{integer}`: {e}"),
2048                                integer.span(),
2049                            )
2050                        })?;
2051                        self.apply_tuple_index(index, start_span)?;
2052                    }
2053                    Some(Token::Literal(CelLiteral::Float(float))) => {
2054                        let float = float.clone();
2055                        if !float.suffix().is_empty() {
2056                            return Err(self.error_at("tuple index must be an unsuffixed integer"));
2057                        }
2058                        // base10_digits() returns the decimal digits with underscores
2059                        // stripped and the suffix removed, e.g. "0.1" or "10.25" for
2060                        // ordinary decimal floats — splitting on '.' recovers the two
2061                        // chained integer indices. Scientific-notation floats (e.g.
2062                        // `1e2`) normalize to digits with no '.' at all; reject those
2063                        // as a parse error (checked before advancing, so the error
2064                        // span still points at the float token) rather than assuming
2065                        // a '.' is always present.
2066                        let digits = float.base10_digits();
2067                        let Some((first, second)) = digits.split_once('.') else {
2068                            return Err(self.error_at(
2069                                "tuple index chain must use decimal notation (e.g. `.0.1`)",
2070                            ));
2071                        };
2072                        self.advance();
2073                        let first_index = first.parse::<usize>().map_err(|e| {
2074                            ParseError::new(
2075                                format!("invalid tuple index `{first}`: {e}"),
2076                                float.span(),
2077                            )
2078                        })?;
2079                        let second_index = second.parse::<usize>().map_err(|e| {
2080                            ParseError::new(
2081                                format!("invalid tuple index `{second}`: {e}"),
2082                                float.span(),
2083                            )
2084                        })?;
2085                        self.apply_tuple_index(first_index, start_span)?;
2086                        self.apply_tuple_index(second_index, start_span)?;
2087                    }
2088                    _ => return Err(self.error_at("expected integer or member name after '.'")),
2089                }
2090            } else {
2091                break;
2092            }
2093        }
2094        Ok(())
2095    }
2096
2097    /// `postfix_arguments = [ "(" [ parameter_list ] ")" ].`
2098    ///
2099    /// Returns `None` without consuming input when no argument list follows.
2100    ///
2101    /// # Errors
2102    /// Returns an error for malformed arguments or a missing closing parenthesis.
2103    ///
2104    /// - Complexity: O(n) in the parsed argument expressions.
2105    fn postfix_arguments(&mut self) -> Result<Option<usize>> {
2106        if !self.is_open_paren() {
2107            return Ok(None);
2108        }
2109        if self.is_close_paren() {
2110            return Ok(Some(0));
2111        }
2112        let count = self.parameter_list()?;
2113        if !self.is_close_paren() {
2114            return Err(self.error_at("expected closing parenthesis"));
2115        }
2116        Ok(Some(count))
2117    }
2118
2119    /// Applies `.N`, leaving semantic bounds validation to the owning context.
2120    ///
2121    /// # Errors
2122    /// Returns an error if the top of stack isn't a tuple, or if `index` is
2123    /// out of range for its arity.
2124    fn apply_tuple_index(&mut self, index: usize, start: Span) -> Result<()> {
2125        self.context.tuple_index(index, start, self.last_span)?;
2126        Ok(())
2127    }
2128
2129    /// `parameter_list = expression { "," expression }.`
2130    ///
2131    /// Always parses at least one `expression` — callers that need to allow zero
2132    /// arguments (`postfix_expression`'s `"(" [ parameter_list ] ")"`) check for that
2133    /// possibility themselves before calling, rather than `parameter_list` swallowing it.
2134    ///
2135    /// Returns the argument count.
2136    ///
2137    /// # Errors
2138    /// Returns an error if the first token can't start an `expression`, or if a comma
2139    /// isn't followed by one.
2140    fn parameter_list(&mut self) -> Result<usize> {
2141        if !self.is_ordinary_expression()? {
2142            return Err(self.error_at("expected expression"));
2143        }
2144        let mut count = 1;
2145        while self.is_punctuation(",") {
2146            if !self.is_ordinary_expression()? {
2147                return Err(self.error_at("expected expression after comma"));
2148            }
2149            count += 1;
2150        }
2151        Ok(count)
2152    }
2153
2154    /// `primary_expression = literal | value_identifier [ record_fields ] | tuple_or_group |
2155    /// array_expression | if_expression.`
2156    ///
2157    /// Dispatches to [`is_if_expression`](Self::is_if_expression) when the `if` keyword is seen,
2158    /// to [`is_tuple_or_group`](Self::is_tuple_or_group) when `(` is seen, to
2159    /// [`is_array_expression`](Self::is_array_expression) when `[` is seen.
2160    /// A closure reaches this production only through a parenthesized expression.
2161    ///
2162    /// # Errors
2163    ///
2164    /// Returns an error if:
2165    /// - A literal value cannot be parsed (e.g., integer out of range).
2166    /// - An identifier is not found in the op lookup table.
2167    /// - A tuple-or-group expression fails to parse.
2168    /// - An array literal fails to parse or is rejected by the context it emits into.
2169    /// - An `if` expression fails to parse.
2170    fn is_primary_expression(&mut self) -> Result<bool> {
2171        match self.peek_token() {
2172            Some(Token::Literal(lit)) => {
2173                let lit_clone = lit.clone();
2174                self.advance();
2175                push_literal_token(&mut self.context, lit_clone)?;
2176                Ok(true)
2177            }
2178            Some(Token::Identifier(ident)) => {
2179                let ident_name = ident.to_string();
2180                let ident_span = ident.span();
2181                self.advance();
2182
2183                if ident_name == "if" {
2184                    return self.is_if_expression(ident_span);
2185                }
2186                if matches!(ident_name.as_str(), "else" | "as") {
2187                    return Err(ParseError::new(
2188                        "reserved keyword is not a value name",
2189                        ident_span,
2190                    ));
2191                }
2192
2193                if self.restriction == ExpressionRestriction::None
2194                    && matches!(
2195                        self.peek_token(),
2196                        Some(Token::OpenDelim {
2197                            delimiter: Delimiter::Brace,
2198                            ..
2199                        })
2200                    )
2201                {
2202                    return self.is_record_fields(&ident_name, ident_span);
2203                }
2204
2205                self.context
2206                    .push_identifier(&self.op_lookup, &ident_name, ident_span)?;
2207
2208                Ok(true)
2209            }
2210            Some(Token::OpenDelim {
2211                delimiter: Delimiter::Parenthesis,
2212                ..
2213            }) => self.is_tuple_or_group(),
2214            Some(Token::OpenDelim {
2215                delimiter: Delimiter::Bracket,
2216                ..
2217            }) => self.is_array_expression(),
2218            _ => Ok(false),
2219        }
2220    }
2221
2222    /// `record_fields = "{" [ identifier ":" expression { "," identifier ":" expression } ] "}".`
2223    ///
2224    /// - Precondition: the constructor identifier is consumed and the next token is `{`.
2225    /// - Postcondition: fields are emitted once in source order before the constructor.
2226    /// - Complexity: O(n + f² + f * d + r) for n tokens, f fields, descriptor depth d and r schemas.
2227    ///
2228    /// # Errors
2229    /// Returns malformed field syntax errors or the context's record validation error.
2230    fn is_record_fields(&mut self, name: &str, name_token: Span) -> Result<bool> {
2231        self.advance();
2232        let ambient_start = self.context.current_stack_offset();
2233        let mut fields = Vec::new();
2234        if !matches!(
2235            self.peek_token(),
2236            Some(Token::CloseDelim {
2237                delimiter: Delimiter::Brace,
2238                ..
2239            })
2240        ) {
2241            loop {
2242                let Some(Token::Identifier(field)) = self.peek_token() else {
2243                    return Err(self.error_at("expected record field name"));
2244                };
2245                let field_name = field.to_string();
2246                let field_span = field.span();
2247                self.advance();
2248                if !self.is_punctuation(":") {
2249                    return Err(self.error_at("expected `:` after record field name"));
2250                }
2251                if !self.is_ordinary_expression()? {
2252                    return Err(self.error_at("expected record field expression"));
2253                }
2254                fields.push((
2255                    field_name,
2256                    ExprSpan {
2257                        start: field_span,
2258                        end: field_span,
2259                    },
2260                ));
2261                if !self.is_punctuation(",") {
2262                    break;
2263                }
2264            }
2265        }
2266        if !matches!(
2267            self.peek_token(),
2268            Some(Token::CloseDelim {
2269                delimiter: Delimiter::Brace,
2270                ..
2271            })
2272        ) {
2273            return Err(self.error_at("expected `,` or `}` after record field"));
2274        }
2275        self.advance();
2276        self.context.make_record(
2277            &self.op_lookup,
2278            name,
2279            ExprSpan {
2280                start: name_token,
2281                end: name_token,
2282            },
2283            fields,
2284            ambient_start,
2285            name_token,
2286            self.last_span,
2287        )?;
2288        Ok(true)
2289    }
2290
2291    /// `tuple_or_group = "(" [ expression ["," [ expression { "," expression } ]] ] ")".`
2292    ///
2293    /// `()` parses as unit, `(expr)` as grouping, `(expr,)` as a 1-tuple, and
2294    /// `(expr, expr, ...)` as an n-tuple.
2295    ///
2296    /// - Precondition: The next token is `Token::OpenDelim` with `Delimiter::Parenthesis`.
2297    ///
2298    /// # Errors
2299    ///
2300    /// Returns an error if the parenthesized expression or tuple literal is malformed, has a
2301    /// missing or misplaced comma, or is missing its closing `)`.
2302    fn is_tuple_or_group(&mut self) -> Result<bool> {
2303        let open_span = self
2304            .peek_span()
2305            .expect("tuple_or_group requires an opening '(' token");
2306        self.advance();
2307        // Unit expression: ()
2308        if matches!(
2309            self.peek_token(),
2310            Some(Token::CloseDelim {
2311                delimiter: Delimiter::Parenthesis,
2312                ..
2313            })
2314        ) {
2315            self.advance();
2316            self.context.make_tuple(
2317                0,
2318                self.context.current_stack_offset(),
2319                open_span,
2320                self.last_span,
2321            )?;
2322            return Ok(true);
2323        }
2324        let ambient_start = self.context.current_stack_offset();
2325        if !self.is_ordinary_expression()? {
2326            return Err(self.error_at("expected expression"));
2327        }
2328        if matches!(
2329            self.peek_token(),
2330            Some(Token::CloseDelim {
2331                delimiter: Delimiter::Parenthesis,
2332                ..
2333            })
2334        ) {
2335            // Grouping: exactly one expression, no comma.
2336            self.advance();
2337            return Ok(true);
2338        }
2339        if !self.is_punctuation(",") {
2340            return Err(self.error_at("expected ',' or closing parenthesis"));
2341        }
2342        let mut count = 1;
2343        if matches!(
2344            self.peek_token(),
2345            Some(Token::CloseDelim {
2346                delimiter: Delimiter::Parenthesis,
2347                ..
2348            })
2349        ) {
2350            // Single element + trailing comma: 1-tuple.
2351            self.advance();
2352            self.context
2353                .make_tuple(count, ambient_start, open_span, self.last_span)?;
2354            return Ok(true);
2355        }
2356        loop {
2357            if !self.is_ordinary_expression()? {
2358                return Err(self.error_at("expected expression after ','"));
2359            }
2360            count += 1;
2361            if matches!(
2362                self.peek_token(),
2363                Some(Token::CloseDelim {
2364                    delimiter: Delimiter::Parenthesis,
2365                    ..
2366                })
2367            ) {
2368                self.advance();
2369                break;
2370            }
2371            if !self.is_punctuation(",") {
2372                return Err(self.error_at("expected ',' or closing parenthesis"));
2373            }
2374        }
2375        self.context
2376            .make_tuple(count, ambient_start, open_span, self.last_span)?;
2377        Ok(true)
2378    }
2379
2380    /// `array_expression = "[" [ expression { "," expression } ] "]" [ ":" type_expr ] .`
2381    ///
2382    /// Every comma requires another element, so the production stays Wirth-style LL(1) — each
2383    /// decision is made by inspecting exactly the current token — and a trailing comma
2384    /// (`[0i32,]`) is a parse error, unlike the 1-tuple form `(0i32,)` where the comma is what
2385    /// distinguishes a tuple from a grouping.
2386    ///
2387    /// - Precondition: The next token is `Token::OpenDelim` with `Delimiter::Bracket`.
2388    ///
2389    /// # Errors
2390    ///
2391    /// Returns an error if the literal is empty and unannotated (`[]` has no inferable element
2392    /// type; see <https://github.com/stlab/cel-rs/issues/212>), if an element expression is
2393    /// missing or malformed, if a comma or the closing `]` is missing, if the type annotation is
2394    /// malformed or names a non-array type, or if the context this emits into rejects the
2395    /// collected elements (e.g. heterogeneous element types).
2396    ///
2397    /// - Postcondition: Returns `Ok(true)` on success; `Ok(false)` is never returned.
2398    fn is_array_expression(&mut self) -> Result<bool> {
2399        let open_span = self
2400            .peek_span()
2401            .expect("array_expression requires an opening '[' token");
2402        self.advance();
2403        let ambient_start = self.context.current_stack_offset();
2404        let mut count = 0usize;
2405        if !self.is_close_bracket() {
2406            if !self.is_ordinary_expression()? {
2407                return Err(self.error_at("expected expression"));
2408            }
2409            count = 1;
2410            loop {
2411                if self.is_close_bracket() {
2412                    break;
2413                }
2414                if !self.is_punctuation(",") {
2415                    return Err(self.error_at("expected ',' or closing ']'"));
2416                }
2417                // A comma always requires another element: `]` here (a trailing comma) can't
2418                // start an `expression`, so this is where `[0i32,]` is rejected.
2419                if !self.is_ordinary_expression()? {
2420                    return Err(self.error_at("expected expression after ','"));
2421                }
2422                count += 1;
2423            }
2424        }
2425
2426        let mut type_annotation = None;
2427        let mut annotation_span = None;
2428        if self.is_punctuation(":") {
2429            let colon_span = self.last_span;
2430            let annotation = self.parse_type_expression()?;
2431            let annotation_end = annotation.span().end;
2432            annotation_span = Some(ExprSpan {
2433                start: colon_span,
2434                end: annotation_end,
2435            });
2436            type_annotation = Some(annotation);
2437        }
2438
2439        if count == 0 && type_annotation.is_none() {
2440            return Err(ParseError::new_range(
2441                "an empty array literal has no inferable element type; \
2442                 see https://github.com/stlab/cel-rs/issues/212"
2443                    .to_string(),
2444                open_span,
2445                self.last_span,
2446            ));
2447        }
2448
2449        let type_resolver = self.type_resolver.as_ref();
2450        let mut resolve_array_type = |type_expr: &TypeExpr| {
2451            let resolved = type_expr.resolve(type_resolver)?;
2452            ResolvedArrayType::from_resolved_type(resolved, type_expr.span())
2453        };
2454        self.context.make_annotated_array(
2455            count,
2456            ambient_start,
2457            parser_context::AnnotatedArray::new(
2458                &mut resolve_array_type,
2459                type_annotation,
2460                annotation_span,
2461            ),
2462            open_span,
2463            self.last_span,
2464        )?;
2465        Ok(true)
2466    }
2467
2468    /// `type_expression = identifier [ "(" [ type_expression { "," type_expression } ] ")" ]
2469    ///                  | "[" type_expression "]"
2470    ///                  | "(" [ type_expression ["," [ type_expression { "," type_expression } ]] ] ")" .`
2471    ///
2472    /// `()` is the empty tuple type (0 elements); `(T)` is grouping (same as bare `T`); `(T,)`
2473    /// is a 1-element tuple; `(T, U, ...)` is n-element, no trailing comma. `[T]` names an
2474    /// array type whose elements have type `T`. `Name(A, B)` applies zero or more type
2475    /// arguments to a named (generic) type.
2476    ///
2477    /// # Errors
2478    ///
2479    /// Returns an error if a named leaf is missing, if an array, tuple, or type-argument list is
2480    /// malformed, or if a closing `]`/`)` is missing.
2481    ///
2482    /// # Examples
2483    /// See [`Self::parse_type_expr_str`] for recognizing type syntax on the current cursor.
2484    pub fn parse_type_expression(&mut self) -> Result<TypeExpr> {
2485        if let Some(Token::Identifier(_)) = self.peek_token() {
2486            let name = self.expect_identifier("expected a type name")?;
2487            let name_span = self.last_span;
2488            let mut args = Vec::new();
2489            let mut end_span = name_span;
2490            if self.is_open_paren() {
2491                if !self.is_close_paren() {
2492                    args.push(self.parse_type_expression()?);
2493                    while self.is_punctuation(",") {
2494                        args.push(self.parse_type_expression()?);
2495                    }
2496                    if !self.is_close_paren() {
2497                        return Err(
2498                            self.error_at("expected ',' or closing ')' in type argument list")
2499                        );
2500                    }
2501                }
2502                end_span = self.last_span;
2503            }
2504            return Ok(TypeExpr::Named {
2505                name,
2506                args,
2507                span: ExprSpan {
2508                    start: name_span,
2509                    end: end_span,
2510                },
2511            });
2512        }
2513
2514        if matches!(
2515            self.peek_token(),
2516            Some(Token::OpenDelim {
2517                delimiter: Delimiter::Bracket,
2518                ..
2519            })
2520        ) {
2521            let open_span = self
2522                .peek_span()
2523                .expect("array type expression requires an opening '[' token");
2524            self.advance();
2525            if self.is_close_bracket() {
2526                return Err(ParseError::new_range(
2527                    "expected a type expression after '['".to_string(),
2528                    open_span,
2529                    self.last_span,
2530                ));
2531            }
2532            let element = self.parse_type_expression()?;
2533            if !self.is_close_bracket() {
2534                return Err(self.error_at("expected closing ']' after array type expression"));
2535            }
2536            return Ok(TypeExpr::Array {
2537                element: Box::new(element),
2538                span: ExprSpan {
2539                    start: open_span,
2540                    end: self.last_span,
2541                },
2542            });
2543        }
2544
2545        if !self.is_open_paren() {
2546            return Err(self.error_at("expected a type name, '[' or '('"));
2547        }
2548        let open_span = self.last_span;
2549        if self.is_close_paren() {
2550            return Ok(TypeExpr::Tuple {
2551                elements: Vec::new(),
2552                span: ExprSpan {
2553                    start: open_span,
2554                    end: self.last_span,
2555                },
2556            });
2557        }
2558
2559        let first = self.parse_type_expression()?;
2560        if self.is_close_paren() {
2561            let span = ExprSpan {
2562                start: open_span,
2563                end: self.last_span,
2564            };
2565            return Ok(match first {
2566                TypeExpr::Named { name, args, .. } => TypeExpr::Named { name, args, span },
2567                TypeExpr::Array { element, .. } => TypeExpr::Array { element, span },
2568                TypeExpr::Tuple { elements, .. } => TypeExpr::Tuple { elements, span },
2569            });
2570        }
2571        if !self.is_punctuation(",") {
2572            return Err(self.error_at("expected ',' or closing ')'"));
2573        }
2574        if self.is_close_paren() {
2575            return Ok(TypeExpr::Tuple {
2576                elements: vec![first],
2577                span: ExprSpan {
2578                    start: open_span,
2579                    end: self.last_span,
2580                },
2581            });
2582        }
2583        let mut elements = vec![first];
2584        loop {
2585            elements.push(self.parse_type_expression()?);
2586            if self.is_close_paren() {
2587                break;
2588            }
2589            if !self.is_punctuation(",") {
2590                return Err(self.error_at("expected ',' or closing ')'"));
2591            }
2592        }
2593        Ok(TypeExpr::Tuple {
2594            elements,
2595            span: ExprSpan {
2596                start: open_span,
2597                end: self.last_span,
2598            },
2599        })
2600    }
2601
2602    /// `closure_expression = ("||" | "|" [ closure_param { "," closure_param } ] "|") expression .`
2603    /// `closure_param = identifier ":" type_expression .`
2604    ///
2605    /// Compiles the body as a fully independent nested context (via
2606    /// [`parse_nested_context`](Self::parse_nested_context)) whose only visible names are its
2607    /// own declared parameters plus whatever library/built-in functions are always reachable —
2608    /// [`OpLookup::isolate_scopes`] hides every other transient scope (including one an enclosing
2609    /// caller, e.g. adam-lang, pushed around this whole parse) for the duration of the body
2610    /// parse, so a closure never resolves a free variable from its lexical surroundings.
2611    ///
2612    /// Runtime contexts resolve each annotation through the configured [`TypeResolver`] into
2613    /// its exact [`cel_runtime::ValueType`]. Syntax-only contexts retain the unresolved,
2614    /// span-carrying [`TypeExpr`] without consulting runtime tables. Both use the same
2615    /// [`parse_type_expression`](Self::parse_type_expression) production.
2616    ///
2617    /// - Precondition: the opening `|` (`params_already_closed == false`) or the combined `||`
2618    ///   token naming an empty parameter list (`params_already_closed == true`) has already been
2619    ///   consumed by [`is_primary_expression`](Self::is_primary_expression); `self.last_span` is
2620    ///   its span.
2621    ///
2622    /// # Errors
2623    ///
2624    /// Returns an error if a parameter name is reserved or duplicated, its `:`, its type,
2625    /// or the closing `|` is malformed
2626    /// or missing; if a runtime parameter names an unrecognized type or unsupported array
2627    /// element shape; if a used parameter lacks clone support; if the body is missing or malformed;
2628    /// or if this `ParserContext` implementation's `push_closure` rejects the closure (e.g.
2629    /// `DynSegmentContext` when the body doesn't produce exactly one value).
2630    ///
2631    /// - Postcondition: Returns `Ok(true)` on success; `Ok(false)` is never returned.
2632    fn is_closure_expression(&mut self, params_already_closed: bool) -> Result<bool> {
2633        let start_span = self.last_span;
2634        let mut params: Vec<(String, Span, Option<cel_runtime::ValueType>, TypeExpr)> = Vec::new();
2635        if !params_already_closed {
2636            loop {
2637                let name = self.expect_identifier("expected closure parameter name")?;
2638                let name_span = self.last_span;
2639                if !self.is_punctuation(":") {
2640                    return Err(self.error_at("expected ':' after closure parameter name"));
2641                }
2642                let ty_ast = self.parse_type_expression()?;
2643                let ty = if C::resolves_closure_types() {
2644                    Some(closure_param_type_from_type_expr(
2645                        &ty_ast,
2646                        self.type_resolver.as_ref(),
2647                    )?)
2648                } else {
2649                    None
2650                };
2651                params.push((name, name_span, ty, ty_ast));
2652                if self.is_punctuation(",") {
2653                    continue;
2654                }
2655                break;
2656            }
2657            if !self.is_punctuation("|") {
2658                return Err(self.error_at("expected ',' or closing '|'"));
2659            }
2660        }
2661
2662        let mut param_types = Vec::with_capacity(params.len());
2663        let mut ast_params = Vec::with_capacity(params.len());
2664        let mut param_table = HashMap::with_capacity(params.len());
2665        // Transfer each type tree once; runtime formals and syntax retain independent names.
2666        for (index, (name, name_span, ty, ty_ast)) in params.into_iter().enumerate() {
2667            if let Some(ty) = &ty {
2668                param_types.push(ty.clone());
2669            }
2670            ast_params.push(ClosureParam {
2671                name: name.clone(),
2672                name_span: ExprSpan {
2673                    start: name_span,
2674                    end: name_span,
2675                },
2676                type_expr: ty_ast,
2677            });
2678            param_table.insert(name, (index, ty));
2679        }
2680        if let Some(error) = ast::closure_parameter_diagnostics(&ast_params)
2681            .into_iter()
2682            .next()
2683        {
2684            return Err(error);
2685        }
2686        let isolated = self.op_lookup.isolate_scopes();
2687        self.op_lookup
2688            .push_scope(move |name, segment, arity, _span| {
2689                if arity != 0 {
2690                    return Ok(false);
2691                }
2692                let Some((idx, ty)) = param_table.get(name) else {
2693                    return Ok(false);
2694                };
2695                if let Some(ty) = ty {
2696                    ty.push_argument(segment, *idx)?;
2697                }
2698                Ok(true)
2699            });
2700
2701        let body_result = self.parse_nested_context(|p| p.is_expression());
2702        self.op_lookup.pop_scope();
2703        self.op_lookup.restore_scopes(isolated);
2704        let body = body_result?;
2705
2706        self.context
2707            .push_closure(param_types, ast_params, body, start_span)?;
2708        Ok(true)
2709    }
2710
2711    /// `if_expression = "if" expression "{" expression "}" [ "else" ( "{" expression "}" | if_expression ) ].`
2712    ///
2713    /// - Precondition: The `if` keyword has already been consumed by the caller; `if_span` is
2714    ///   its span.
2715    ///
2716    /// # Errors
2717    ///
2718    /// Returns an error if the condition is missing, if a `{` or `}` delimiter is missing,
2719    /// if the then-branch or else-branch expression is missing, or if the then and else
2720    /// branch types do not match (as detected by `join2`).
2721    ///
2722    /// - Postcondition: Returns `Ok(true)` on success; `Ok(false)` is never returned.
2723    fn is_if_expression(&mut self, if_span: Span) -> Result<bool> {
2724        if !self.with_restriction(ExpressionRestriction::NoStructLiteral, |p| {
2725            p.is_expression()
2726        })? {
2727            return Err(self.error_at("expected condition after `if`"));
2728        }
2729        match self.peek_token() {
2730            Some(Token::OpenDelim {
2731                delimiter: Delimiter::Brace,
2732                ..
2733            }) => {
2734                self.advance();
2735            }
2736            _ => return Err(self.error_at("expected `{` after if condition")),
2737        }
2738        let mut then_fragment = self.context.new_fragment();
2739        std::mem::swap(&mut self.context, &mut then_fragment);
2740        if !self.is_ordinary_expression()? {
2741            return Err(self.error_at("expected expression in then-branch"));
2742        }
2743        std::mem::swap(&mut self.context, &mut then_fragment);
2744        match self.peek_token() {
2745            Some(Token::CloseDelim {
2746                delimiter: Delimiter::Brace,
2747                ..
2748            }) => {
2749                self.advance();
2750            }
2751            _ => return Err(self.error_at("expected `}` after then-branch")),
2752        }
2753        let else_fragment = if self.is_keyword("else") {
2754            if self.is_keyword("if") {
2755                // else if: recursively parse another if_expression
2756                let elif_span = self.last_span;
2757                let mut fragment = self.context.new_fragment();
2758                std::mem::swap(&mut self.context, &mut fragment);
2759                self.is_if_expression(elif_span)?;
2760                std::mem::swap(&mut self.context, &mut fragment);
2761                Some(fragment)
2762            } else {
2763                // else { expr }
2764                match self.peek_token() {
2765                    Some(Token::OpenDelim {
2766                        delimiter: Delimiter::Brace,
2767                        ..
2768                    }) => {
2769                        self.advance();
2770                    }
2771                    _ => return Err(self.error_at("expected `{` or `if` after `else`")),
2772                }
2773                let mut fragment = self.context.new_fragment();
2774                std::mem::swap(&mut self.context, &mut fragment);
2775                if !self.is_ordinary_expression()? {
2776                    return Err(self.error_at("expected expression in else-branch"));
2777                }
2778                std::mem::swap(&mut self.context, &mut fragment);
2779                match self.peek_token() {
2780                    Some(Token::CloseDelim {
2781                        delimiter: Delimiter::Brace,
2782                        ..
2783                    }) => {
2784                        self.advance();
2785                    }
2786                    _ => return Err(self.error_at("expected `}` after else-branch")),
2787                }
2788                Some(fragment)
2789            }
2790        } else {
2791            // No `else`/`else if` in the source — each ParserContext::join2 impl decides what
2792            // this means (DynSegmentContext synthesizes an implicit `()` fragment;
2793            // AstContext records `None` directly on Expr::If).
2794            None
2795        };
2796        self.context
2797            .join2(then_fragment, else_fragment, if_span, self.last_span)
2798            .map_err(|e| ParseError::new_range(e.to_string(), if_span, self.last_span))?;
2799        Ok(true)
2800    }
2801}
2802
2803impl Parser<DynSegmentContext> {
2804    /// Parses one `expression` from the current token stream and returns the segment.
2805    ///
2806    /// Unlike [`parse_str`](Self::parse_str), this method does not require end-of-stream,
2807    /// allowing adam-lang to parse an expression embedded within a larger token stream.
2808    ///
2809    /// # Errors
2810    ///
2811    /// Returns an error if the input does not contain a valid `expression`.
2812    ///
2813    /// - Complexity: O(n) in the number of tokens in the expression.
2814    ///
2815    /// # Examples
2816    /// See [`Self::parse_tokens`] for executing an expression from an installed cursor.
2817    pub fn parse_expression(&mut self) -> Result<DynSegment> {
2818        self.parse_expression_ctx()
2819            .map(DynSegmentContext::into_inner)
2820    }
2821
2822    /// Parses one embedded expression with a header brace restriction.
2823    ///
2824    /// - Complexity: O(n) in the expression's token count.
2825    ///
2826    /// # Errors
2827    /// Returns syntax, type, or operation-resolution errors.
2828    ///
2829    /// # Examples
2830    /// See [`ExpressionRestriction`].
2831    pub fn parse_expression_restricted(
2832        &mut self,
2833        restriction: ExpressionRestriction,
2834    ) -> Result<DynSegment> {
2835        self.parse_expression_ctx_restricted(restriction)
2836            .map(DynSegmentContext::into_inner)
2837    }
2838
2839    /// Parses one `literal_pattern` from the current token stream and returns the segment.
2840    ///
2841    /// Unlike [`parse_str`](Self::parse_str), this method does not require end-of-stream.
2842    ///
2843    /// # Errors
2844    ///
2845    /// Returns an error if the input does not contain a valid `literal_pattern`.
2846    ///
2847    /// # Examples
2848    /// See [`Self::parse_literal_pattern_ctx`] for parsing and executing literal patterns.
2849    pub fn parse_literal_pattern(&mut self) -> Result<DynSegment> {
2850        self.parse_literal_pattern_ctx()
2851            .map(DynSegmentContext::into_inner)
2852    }
2853
2854    /// Parses a token stream into a [`DynSegment`].
2855    ///
2856    /// Sets the token source, runs the expression grammar, and returns the segment on success.
2857    ///
2858    /// # Errors
2859    ///
2860    /// Returns an error if the input does not contain a valid CEL expression.
2861    ///
2862    /// - Complexity: O(n) in the number of tokens.
2863    ///
2864    /// # Examples
2865    /// ```
2866    /// use cel_parser::{CELParser, OpLookup};
2867    /// use proc_macro2::TokenStream;
2868    /// let mut parser = CELParser::new(OpLookup::new());
2869    /// let tokens = "42".parse::<TokenStream>().unwrap();
2870    /// assert_eq!(parser.parse_tokens(tokens.into_iter()).unwrap().call0::<i32>().unwrap(), 42);
2871    /// parser.set_tokens("43".parse::<TokenStream>().unwrap().into_iter());
2872    /// assert_eq!(parser.parse_expression().unwrap().call0::<i32>().unwrap(), 43);
2873    /// ```
2874    pub fn parse_tokens(&mut self, tokens: TokenStreamIter) -> Result<DynSegment> {
2875        self.parse_tokens_ctx(tokens)
2876            .map(DynSegmentContext::into_inner)
2877    }
2878
2879    /// Parses a string into a [`DynSegment`].
2880    ///
2881    /// Tokenizes the string then parses; equivalent to
2882    /// `parse_tokens(TokenStream::from_str(s)?.into_iter())`.
2883    ///
2884    /// # Errors
2885    ///
2886    /// Returns an error on lex failure or if the input does not contain a valid CEL expression.
2887    ///
2888    /// - Complexity: O(n) in the length of `s`.
2889    ///
2890    /// # Examples
2891    /// ```
2892    /// use cel_parser::{CELParser, OpLookup};
2893    /// let mut segment = CELParser::new(OpLookup::new()).parse_str("40 + 2").unwrap();
2894    /// assert_eq!(segment.call0::<i32>().unwrap(), 42);
2895    /// ```
2896    pub fn parse_str(&mut self, s: &str) -> Result<DynSegment> {
2897        self.parse_str_ctx(s).map(DynSegmentContext::into_inner)
2898    }
2899}
2900
2901impl Parser<AstContext> {
2902    /// Parses one `expression` from the current token stream and returns the built [`Expr`].
2903    ///
2904    /// Unlike [`parse_str_ast`](Self::parse_str_ast), this method does not require
2905    /// end-of-stream, allowing adam-lang to parse an expression embedded within a larger token
2906    /// stream.
2907    ///
2908    /// # Errors
2909    ///
2910    /// Returns an error if the input does not contain a valid `expression`.
2911    ///
2912    /// - Complexity: O(n) in the number of tokens in the expression.
2913    ///
2914    /// # Examples
2915    /// See [`Self::parse_tokens_ast`] for retaining syntax from an installed cursor.
2916    pub fn parse_expression_ast(&mut self) -> Result<Expr> {
2917        self.parse_expression_ctx().map(AstContext::into_expr)
2918    }
2919
2920    /// Parses a token stream into an [`Expr`] tree.
2921    ///
2922    /// Sets the token source, runs the expression grammar, and returns the tree on success.
2923    ///
2924    /// # Errors
2925    ///
2926    /// Returns an error if the input does not contain a valid CEL expression.
2927    ///
2928    /// - Complexity: O(n) in the number of tokens.
2929    ///
2930    /// # Examples
2931    /// ```
2932    /// use cel_parser::{AstContext, Expr, Literal, OpLookup, Parser};
2933    /// use proc_macro2::TokenStream;
2934    /// let mut parser = Parser::<AstContext>::new(OpLookup::new());
2935    /// let tokens = "42".parse::<TokenStream>().unwrap();
2936    /// assert!(matches!(parser.parse_tokens_ast(tokens.into_iter()).unwrap(),
2937    ///     Expr::Literal { value: Literal::I32(42), .. }));
2938    /// parser.set_tokens("43".parse::<TokenStream>().unwrap().into_iter());
2939    /// assert!(matches!(parser.parse_expression_ast().unwrap(),
2940    ///     Expr::Literal { value: Literal::I32(43), .. }));
2941    /// ```
2942    pub fn parse_tokens_ast(&mut self, tokens: TokenStreamIter) -> Result<Expr> {
2943        self.parse_tokens_ctx(tokens).map(AstContext::into_expr)
2944    }
2945
2946    /// Parses a string into an [`Expr`] tree.
2947    ///
2948    /// Tokenizes the string then parses; equivalent to
2949    /// `parse_tokens_ast(TokenStream::from_str(s)?.into_iter())`.
2950    ///
2951    /// # Errors
2952    ///
2953    /// Returns an error on lex failure or if the input does not contain a valid CEL expression.
2954    ///
2955    /// - Complexity: O(n) in the length of `s`.
2956    ///
2957    /// # Examples
2958    ///
2959    /// ```rust
2960    /// use cel_parser::{AstContext, Expr, OpLookup, Parser};
2961    ///
2962    /// let mut parser = Parser::<AstContext>::new(OpLookup::new());
2963    /// let expr = parser.parse_str_ast("1 + 2").unwrap();
2964    /// assert!(matches!(expr, Expr::Op { .. }));
2965    /// ```
2966    pub fn parse_str_ast(&mut self, s: &str) -> Result<Expr> {
2967        self.parse_str_ctx(s).map(AstContext::into_expr)
2968    }
2969}
2970
2971#[cfg(test)]
2972mod tests {
2973    use super::*;
2974    use annotate_snippets::Renderer;
2975
2976    #[test]
2977    fn simple_expression() {
2978        let mut parser = CELParser::new(OpLookup::new());
2979        let result = parser.parse_str("10");
2980        assert!(result.is_ok());
2981        assert_eq!(result.unwrap().call0::<i32>().unwrap(), 10);
2982    }
2983
2984    #[test]
2985    fn parse_nested_context_compiles_an_independent_segment_without_disturbing_the_outer_one()
2986    -> anyhow::Result<()> {
2987        let mut parser = CELParser::new(OpLookup::new());
2988        parser.set_tokens(quote::quote! { 1 + 2 }.into_iter());
2989        // Start the outer expression: push a literal directly onto the (not-yet-swapped) context.
2990        parser
2991            .context
2992            .push_literal(100i32, proc_macro2::Span::call_site());
2993
2994        let nested = parser
2995            .parse_nested_context(|p| p.is_or_expression())
2996            .map_err(|e| anyhow::anyhow!("{}", e))?;
2997
2998        // The outer context still only has the one literal pushed before the nested parse.
2999        assert_eq!(parser.context.into_inner().call0::<i32>()?, 100);
3000        // The nested context has its own, independently-evaluated result.
3001        assert_eq!(nested.into_inner().call0::<i32>()?, 3);
3002        Ok(())
3003    }
3004
3005    #[test]
3006    fn unbalanced_delimiter_count_is_zero_before_any_parse() {
3007        let parser = CELParser::new(OpLookup::new());
3008        assert_eq!(parser.unbalanced_delimiter_count(), 0);
3009    }
3010
3011    #[test]
3012    fn unbalanced_delimiter_count_is_zero_after_a_successful_parse() {
3013        let mut parser = CELParser::new(OpLookup::new());
3014        parser.parse_str("(1 + 2)").unwrap();
3015        assert_eq!(parser.unbalanced_delimiter_count(), 0);
3016    }
3017
3018    #[test]
3019    fn unbalanced_delimiter_count_reports_a_brace_left_dangling_by_a_failed_if_expression() {
3020        let mut parser = CELParser::new(OpLookup::new());
3021        let err = match parser.parse_str("if true { }") {
3022            Err(e) => e,
3023            Ok(_) => panic!("an empty then-branch must fail to parse"),
3024        };
3025        assert!(err.message().contains("then-branch"));
3026        assert_eq!(parser.unbalanced_delimiter_count(), 1);
3027    }
3028
3029    #[test]
3030    fn unbalanced_delimiter_count_reports_a_paren_left_dangling_by_a_failed_tuple_literal() {
3031        let mut parser = CELParser::new(OpLookup::new());
3032        if parser.parse_str("(+)").is_ok() {
3033            panic!("`+` alone cannot start an expression");
3034        }
3035        assert_eq!(parser.unbalanced_delimiter_count(), 1);
3036    }
3037
3038    #[test]
3039    fn unbalanced_delimiter_count_resets_when_a_new_parse_begins() {
3040        let mut parser = CELParser::new(OpLookup::new());
3041        if parser.parse_str("(+)").is_ok() {
3042            panic!("`+` alone cannot start an expression");
3043        }
3044        assert_eq!(parser.unbalanced_delimiter_count(), 1);
3045        parser.parse_str("1 + 2").unwrap();
3046        assert_eq!(parser.unbalanced_delimiter_count(), 0);
3047    }
3048
3049    #[test]
3050    fn integer_literal_i32_suffix() {
3051        let mut parser = CELParser::new(OpLookup::new());
3052        let result = parser.parse_str("10i32");
3053        assert!(result.is_ok());
3054        assert_eq!(result.unwrap().call0::<i32>().unwrap(), 10);
3055    }
3056
3057    #[test]
3058    fn invalid_integer_suffix() {
3059        let mut parser = CELParser::new(OpLookup::new());
3060        let err = match parser.parse_str("10xyz") {
3061            Err(e) => e,
3062            Ok(_) => panic!("expected parse error for invalid integer suffix"),
3063        };
3064        assert!(err.message().contains("invalid integer literal suffix"));
3065        assert!(err.message().contains("xyz"));
3066    }
3067
3068    #[test]
3069    fn validate_literal_accepts_a_well_formed_integer() {
3070        let lit: lex_lexer::Literal = syn::parse_str("5i32").unwrap();
3071        assert!(validate_literal(&lit).is_ok());
3072    }
3073
3074    #[test]
3075    fn validate_literal_accepts_a_well_formed_float() {
3076        let lit: lex_lexer::Literal = syn::parse_str("1.5f64").unwrap();
3077        assert!(validate_literal(&lit).is_ok());
3078    }
3079
3080    #[test]
3081    fn validate_literal_rejects_an_unrecognized_integer_suffix() {
3082        let lit: lex_lexer::Literal = syn::parse_str("10xyz").unwrap();
3083        let err = validate_literal(&lit).expect_err("unrecognized suffix must be rejected");
3084        assert!(err.message().contains("invalid integer literal suffix"));
3085    }
3086
3087    #[test]
3088    fn validate_literal_rejects_an_out_of_range_integer() {
3089        let lit: lex_lexer::Literal = syn::parse_str("999i8").unwrap();
3090        let err = validate_literal(&lit).expect_err("out-of-range literal must be rejected");
3091        assert!(err.message().contains("invalid i8 literal"));
3092    }
3093
3094    #[test]
3095    fn float_literal() {
3096        let mut parser = CELParser::new(OpLookup::new());
3097        let result = parser.parse_str("42.14");
3098        assert!(result.is_ok());
3099        let value = result.unwrap().call0::<f64>().unwrap();
3100        assert!((value - 42.14).abs() < 1e-10);
3101    }
3102
3103    #[test]
3104    fn float_literal_f64_suffix() {
3105        let mut parser = CELParser::new(OpLookup::new());
3106        let result = parser.parse_str("42.14f64");
3107        assert!(result.is_ok());
3108        let value = result.unwrap().call0::<f64>().unwrap();
3109        assert!((value - 42.14).abs() < 1e-10);
3110    }
3111
3112    #[test]
3113    fn float_literal_f32_suffix() {
3114        let mut parser = CELParser::new(OpLookup::new());
3115        let result = parser.parse_str("42.14f32");
3116        assert!(result.is_ok());
3117        let value = result.unwrap().call0::<f32>().unwrap();
3118        assert!((value - 42.14f32).abs() < 1e-6);
3119    }
3120
3121    /// Evaluates and retains valid exponent spellings through all literal entry points.
3122    #[test]
3123    fn exponent_sign_precedes_underscores_in_literal_values() {
3124        for (source, expected) in [
3125            ("1e+_2f64", 100.0),
3126            ("1e__2f64", 100.0),
3127            ("1e-__2f64", 0.01),
3128            ("1.0E+__2f64", 100.0),
3129        ] {
3130            let literal: lex_lexer::Literal = syn::parse_str(source).unwrap();
3131            validate_literal(&literal).unwrap();
3132            let expression = literal_expr(&literal).unwrap();
3133            assert!(matches!(
3134                &expression,
3135                Expr::Literal { value: Literal::F64(value), .. } if *value == expected
3136            ));
3137            assert_eq!(format_expr(&expression, source, 0), source);
3138            let mut parser = CELParser::new(OpLookup::new());
3139            assert_eq!(
3140                parser.parse_str(source).unwrap().call0::<f64>().unwrap(),
3141                expected,
3142                "{source}"
3143            );
3144            parser.set_tokens(
3145                source
3146                    .parse::<proc_macro2::TokenStream>()
3147                    .unwrap()
3148                    .into_iter(),
3149            );
3150            assert_eq!(
3151                parser
3152                    .parse_literal_pattern()
3153                    .unwrap()
3154                    .call0::<f64>()
3155                    .unwrap(),
3156                expected,
3157                "{source}"
3158            );
3159        }
3160        let literal: lex_lexer::Literal = syn::parse_str("1e+_2f32").unwrap();
3161        validate_literal(&literal).unwrap();
3162        let expression = literal_expr(&literal).unwrap();
3163        assert!(matches!(
3164            &expression,
3165            Expr::Literal {
3166                value: Literal::F32(100.0),
3167                ..
3168            }
3169        ));
3170        assert_eq!(format_expr(&expression, "1e+_2f32", 0), "1e+_2f32");
3171        let mut parser = CELParser::new(OpLookup::new());
3172        assert_eq!(
3173            parser
3174                .parse_str("1e+_2f32")
3175                .unwrap()
3176                .call0::<f32>()
3177                .unwrap(),
3178            100.0
3179        );
3180        parser.set_tokens(
3181            "1e+_2f32"
3182                .parse::<proc_macro2::TokenStream>()
3183                .unwrap()
3184                .into_iter(),
3185        );
3186        assert_eq!(
3187            parser
3188                .parse_literal_pattern()
3189                .unwrap()
3190                .call0::<f32>()
3191                .unwrap(),
3192            100.0
3193        );
3194    }
3195
3196    /// Rejects misplaced exponent signs in validation, expressions, and patterns.
3197    #[test]
3198    fn exponent_sign_after_underscores_is_rejected_by_all_literal_entry_points() {
3199        for source in [
3200            "1e_+2f64",
3201            "1e__-2f64",
3202            "1e_+_2f64",
3203            "1.0e_+2f64",
3204            "1E__+2f64",
3205            "1e_+2f32",
3206            "1_e_+_2",
3207        ] {
3208            let literal: lex_lexer::Literal = syn::parse_str(source).unwrap();
3209            let error = validate_literal(&literal).expect_err(source);
3210            assert_eq!(error.span().source_text().as_deref(), Some(source));
3211            assert!(literal_expr(&literal).is_err(), "{source}");
3212            let mut parser = CELParser::new(OpLookup::new());
3213            assert!(parser.parse_str(source).is_err(), "{source}");
3214            parser.set_tokens(
3215                source
3216                    .parse::<proc_macro2::TokenStream>()
3217                    .unwrap()
3218                    .into_iter(),
3219            );
3220            assert!(parser.parse_literal_pattern().is_err(), "{source}");
3221        }
3222        let negative: lex_lexer::Literal = syn::parse_str("-1e_+2f64").unwrap();
3223        assert!(validate_literal(&negative).is_err());
3224        assert!(literal_expr(&negative).is_err());
3225    }
3226
3227    /// Rejects exponent-form tuple indices and retains their diagnostic spans.
3228    #[test]
3229    fn exponent_sign_literals_do_not_become_tuple_indices() {
3230        let mut parser = CELParser::new(OpLookup::new());
3231        let error = parser
3232            .parse_str("(1.0,).0e+_0f64")
3233            .err()
3234            .expect("an exponent is not a tuple index");
3235        assert_eq!(error.message(), "tuple index must be an unsuffixed integer");
3236        assert_eq!(error.span().source_text().as_deref(), Some("0e+_0f64"));
3237        assert!(parser.parse_str("(1.0,).0e_+0f64").is_err());
3238    }
3239
3240    /// Evaluates decimal integer-form literals as f64 values.
3241    #[test]
3242    fn integer_form_float_f64_literals_evaluate() {
3243        let mut parser = CELParser::new(OpLookup::new());
3244        for (source, expected) in [
3245            ("1f64", 1.0),
3246            ("1_f64", 1.0),
3247            ("0f64", 0.0),
3248            ("1_000f64", 1000.0),
3249            ("9007199254740993f64", 9007199254740992.0),
3250            (
3251                "340_282_366_920_938_463_463_374_607_431_768_211_456f64",
3252                2.0f64.powi(128),
3253            ),
3254            ("1f64 + 2.0f64", 3.0),
3255        ] {
3256            let mut segment = parser.parse_str(source).unwrap();
3257            assert_eq!(segment.call0::<f64>().unwrap(), expected, "{source}");
3258        }
3259        let mut negative_zero = parser.parse_str("-0f64").unwrap();
3260        assert!(negative_zero.call0::<f64>().unwrap().is_sign_negative());
3261    }
3262
3263    /// Evaluates decimal integer-form literals as f32 values.
3264    #[test]
3265    fn integer_form_float_f32_literals_evaluate() {
3266        let mut parser = CELParser::new(OpLookup::new());
3267        for (source, expected) in [
3268            ("1f32", 1.0f32),
3269            ("0_f32", 0.0),
3270            ("16777217f32", 16777216.0),
3271            (
3272                "170_141_183_460_469_231_731_687_303_715_884_105_728f32",
3273                2.0f32.powi(127),
3274            ),
3275            ("1f32 + 2.0f32", 3.0),
3276        ] {
3277            let mut segment = parser.parse_str(source).unwrap();
3278            assert_eq!(segment.call0::<f32>().unwrap(), expected, "{source}");
3279        }
3280        let mut negative_zero = parser.parse_str("-0f32").unwrap();
3281        assert!(negative_zero.call0::<f32>().unwrap().is_sign_negative());
3282    }
3283
3284    /// Validates and retains the type of literal tokens supplied directly by Syn.
3285    #[test]
3286    fn integer_form_float_literals_validate_without_a_lexer() {
3287        for (source, expected) in [
3288            ("1f64", 1.0),
3289            ("1_f64", 1.0),
3290            ("0f64", 0.0),
3291            ("-1_f64", -1.0),
3292        ] {
3293            let literal: lex_lexer::Literal = syn::parse_str(source).unwrap();
3294            validate_literal(&literal).unwrap();
3295            let original_span = lex_lexer::HasSpan::span(&literal);
3296            let Expr::Literal {
3297                value: Literal::F64(value),
3298                span,
3299            } = literal_expr(&literal).unwrap()
3300            else {
3301                panic!("{source} must retain an f64 value");
3302            };
3303            assert_eq!(value, expected);
3304            assert_eq!(span.start.source_text(), original_span.source_text());
3305            assert_eq!(span.end.source_text(), original_span.source_text());
3306        }
3307        let literal: lex_lexer::Literal = syn::parse_str("1f32").unwrap();
3308        validate_literal(&literal).unwrap();
3309        assert!(matches!(
3310            literal_expr(&literal).unwrap(),
3311            Expr::Literal {
3312                value: Literal::F32(1.0),
3313                ..
3314            }
3315        ));
3316        for (source, message) in [
3317            ("-0b1f64", "invalid integer literal suffix: `f64`"),
3318            ("-0o7_f64", "invalid integer literal suffix: `f64`"),
3319            ("-0b1f32", "invalid integer literal suffix: `f32`"),
3320            ("-0o7_f32", "invalid integer literal suffix: `f32`"),
3321        ] {
3322            let literal: lex_lexer::Literal = syn::parse_str(source).unwrap();
3323            let error = validate_literal(&literal).unwrap_err();
3324            assert_eq!(error.message(), message);
3325        }
3326    }
3327
3328    /// Retains integer and selector boundaries around suffixed floating literals.
3329    #[test]
3330    fn integer_form_float_literals_preserve_numeric_boundaries() {
3331        let mut parser = CELParser::new(OpLookup::new());
3332        for (source, expected) in [("0x1f64", 8036), ("0b101", 5), ("0o77", 63)] {
3333            let mut segment = parser.parse_str(source).unwrap();
3334            assert_eq!(segment.call0::<i32>().unwrap(), expected, "{source}");
3335        }
3336        let mut cast = parser.parse_str("1 as f64").unwrap();
3337        assert_eq!(cast.call0::<f64>().unwrap(), 1.0);
3338        for source in [
3339            "1f64x", "1f64_", "1f640", "0b1f64", "0o7_f64", "1f32x", "0b1f32", "0o7_f32",
3340        ] {
3341            assert!(parser.parse_str(source).is_err(), "{source}");
3342        }
3343        for (source, selector) in [
3344            ("(10,20).0f64", "0f64"),
3345            ("(10,20).1f32", "1f32"),
3346            ("(10,20).0_f64", "0_f64"),
3347        ] {
3348            let error = parser
3349                .parse_str(source)
3350                .err()
3351                .expect("suffix must be rejected");
3352            assert_eq!(error.message(), "tuple index must be an unsuffixed integer");
3353            assert_eq!(error.span().source_text().as_deref(), Some(selector));
3354        }
3355        let mut selected = parser.parse_str("(10,20).1").unwrap();
3356        assert_eq!(selected.call0::<i32>().unwrap(), 20);
3357    }
3358
3359    #[test]
3360    fn invalid_float_suffix() {
3361        let mut parser = CELParser::new(OpLookup::new());
3362        let err = match parser.parse_str("3.14xyz") {
3363            Err(e) => e,
3364            Ok(_) => panic!("expected parse error for invalid float suffix"),
3365        };
3366        assert!(err.message().contains("invalid float literal suffix"));
3367        assert!(err.message().contains("xyz"));
3368    }
3369
3370    #[test]
3371    fn boolean_literal() {
3372        let mut parser = CELParser::new(OpLookup::new());
3373        let result = parser.parse_str("true");
3374        assert!(result.is_ok());
3375        assert!(result.unwrap().call0::<bool>().unwrap());
3376    }
3377
3378    #[test]
3379    fn string_literal() {
3380        let mut parser = CELParser::new(OpLookup::new());
3381        let result = parser.parse_str(r#""hello""#);
3382        assert!(result.is_ok());
3383        assert_eq!(result.unwrap().call0::<String>().unwrap(), "hello");
3384    }
3385
3386    #[test]
3387    fn string_concatenation() {
3388        let mut parser = CELParser::new(OpLookup::new());
3389        let result = parser.parse_str(r#""a" + "b""#);
3390        assert!(result.is_ok());
3391        assert_eq!(result.unwrap().call0::<String>().unwrap(), "ab");
3392    }
3393
3394    #[test]
3395    fn incomplete_expression() {
3396        let mut parser = CELParser::new(OpLookup::new());
3397        let result = parser.parse_str("10 + 25 25");
3398        let err = match result {
3399            Ok(_) => panic!("expected parse error"),
3400            Err(e) => e,
3401        };
3402        assert_eq!(err.message(), "unexpected token");
3403    }
3404
3405    #[test]
3406    fn arithmetic_expression() {
3407        let mut parser = CELParser::new(OpLookup::new());
3408        let result = parser.parse_str("10 + 20 * 30");
3409        assert!(result.is_ok());
3410    }
3411
3412    #[test]
3413    fn parenthesized_expression() {
3414        let mut parser = CELParser::new(OpLookup::new());
3415        let result = parser.parse_str("(10 + 20) * 30");
3416        assert!(result.is_ok());
3417    }
3418
3419    #[test]
3420    fn unit_still_parses_as_unit() {
3421        let mut parser = CELParser::new(OpLookup::new());
3422        let mut seg = parser.parse_str("()").unwrap();
3423        seg.call0::<()>().unwrap();
3424    }
3425
3426    #[test]
3427    fn single_paren_expression_is_grouping_not_tuple() {
3428        let mut parser = CELParser::new(OpLookup::new());
3429        let mut seg = parser.parse_str("(1i32 + 2i32)").unwrap();
3430        assert_eq!(seg.call0::<i32>().unwrap(), 3);
3431    }
3432
3433    #[test]
3434    fn one_tuple_requires_trailing_comma() {
3435        let mut parser = CELParser::new(OpLookup::new());
3436        let mut seg = parser.parse_str("(1i32,)").unwrap();
3437        assert_eq!(seg.peek_tuple_arity(), Some(1));
3438        seg.tuple_index(0).unwrap();
3439        assert_eq!(seg.call0::<i32>().unwrap(), 1);
3440    }
3441
3442    #[test]
3443    fn two_element_tuple_no_trailing_comma() {
3444        let mut parser = CELParser::new(OpLookup::new());
3445        let seg: DynSegment = parser.parse_str(r#"("Hello", 42i32)"#).unwrap();
3446        assert_eq!(seg.peek_tuple_arity(), Some(2));
3447    }
3448
3449    #[test]
3450    fn trailing_comma_rejected_for_arity_two() {
3451        let mut parser = CELParser::new(OpLookup::new());
3452        let result = parser.parse_str("(1i32, 2i32,)");
3453        assert!(result.is_err(), "trailing comma is only valid for 1-tuples");
3454    }
3455
3456    #[test]
3457    fn missing_comma_between_elements_is_an_error() {
3458        let mut parser = CELParser::new(OpLookup::new());
3459        let result = parser.parse_str("(1i32 2i32)");
3460        assert!(result.is_err());
3461    }
3462
3463    #[test]
3464    fn index_first_element_of_tuple() {
3465        let mut parser = CELParser::new(OpLookup::new());
3466        let mut seg = parser.parse_str("(10i32, 20i32).0").unwrap();
3467        assert_eq!(seg.call0::<i32>().unwrap(), 10);
3468    }
3469
3470    #[test]
3471    fn tuple_element_can_be_arithmetic_expression() {
3472        let mut parser = CELParser::new(OpLookup::new());
3473        let mut seg = parser.parse_str("(1i32 + 2i32, 3i32).0").unwrap();
3474        assert_eq!(seg.call0::<i32>().unwrap(), 3);
3475    }
3476
3477    #[test]
3478    fn tuple_second_element_can_be_arithmetic_expression() {
3479        let mut parser = CELParser::new(OpLookup::new());
3480        let mut seg = parser.parse_str("(1i32 + 2i32, 3i32).1").unwrap();
3481        assert_eq!(seg.call0::<i32>().unwrap(), 3);
3482    }
3483
3484    #[test]
3485    fn tuple_ambient_start_correct_after_sibling_expression() {
3486        // Regression test: a fully-evaluated sibling subexpression earlier in
3487        // the same additive chain must not shift where the following tuple
3488        // literal thinks its elements land on the real stack.
3489        let mut parser = CELParser::new(OpLookup::new());
3490        let mut seg = parser
3491            .parse_str("(1i32 + 2i32) + 3i32 + (4i32, 5i32).0")
3492            .unwrap();
3493        assert_eq!(seg.call0::<i32>().unwrap(), 10);
3494    }
3495
3496    #[test]
3497    fn tuple_index_inside_if_then_branch() {
3498        // Regression test: `join2` pops the condition bool before running
3499        // the chosen fragment, so a tuple literal inside that fragment must
3500        // compute its layout as if that pop already happened.
3501        let mut parser = CELParser::new(OpLookup::new());
3502        let mut seg = parser
3503            .parse_str("if true { (10i32, 20i32).1 } else { 0i32 }")
3504            .unwrap();
3505        assert_eq!(seg.call0::<i32>().unwrap(), 20);
3506    }
3507
3508    #[test]
3509    fn tuple_index_inside_if_else_branch() {
3510        let mut parser = CELParser::new(OpLookup::new());
3511        let mut seg = parser
3512            .parse_str("if false { 0i32 } else { (10i32, 20i32).1 }")
3513            .unwrap();
3514        assert_eq!(seg.call0::<i32>().unwrap(), 20);
3515    }
3516
3517    #[test]
3518    fn tuple_index_inside_and_rhs() {
3519        let mut parser = CELParser::new(OpLookup::new());
3520        let mut seg = parser
3521            .parse_str("(1i32, 2i32).1 == 2i32 && (10i32, 20i32).1 == 20i32")
3522            .unwrap();
3523        assert!(seg.call0::<bool>().unwrap());
3524    }
3525
3526    #[test]
3527    fn tuple_index_inside_or_rhs() {
3528        let mut parser = CELParser::new(OpLookup::new());
3529        let mut seg = parser
3530            .parse_str("(1i32, 2i32).1 == 99i32 || (10i32, 20i32).1 == 20i32")
3531            .unwrap();
3532        assert!(seg.call0::<bool>().unwrap());
3533    }
3534
3535    #[test]
3536    fn tuple_containing_indexed_nested_tuple_result() {
3537        // Regression test: extracting an element from a misaligned nested
3538        // tuple must not leave the tuple's own leading padding as dead space
3539        // on the stack — otherwise a later tuple literal built from this
3540        // result computes its element offsets against the wrong ambient
3541        // start and reads garbage. (7, not 1: the dead gap's own marker
3542        // byte is hardcoded to value 1, so a value of 1 here would pass
3543        // even when reading the wrong offset.)
3544        let mut parser = CELParser::new(OpLookup::new());
3545        let mut seg = parser.parse_str("(0u8, (7u8, 2u64).0).1").unwrap();
3546        assert_eq!(seg.call0::<u8>().unwrap(), 7);
3547    }
3548
3549    #[test]
3550    fn index_second_element_of_tuple() {
3551        let mut parser = CELParser::new(OpLookup::new());
3552        let mut seg = parser.parse_str("(10i32, 20i32).1").unwrap();
3553        assert_eq!(seg.call0::<i32>().unwrap(), 20);
3554    }
3555
3556    #[test]
3557    fn indexing_combined_with_addition() {
3558        let mut parser = CELParser::new(OpLookup::new());
3559        let mut seg = parser.parse_str("5i32 + (0i32, 1i32).1").unwrap();
3560        assert_eq!(seg.call0::<i32>().unwrap(), 6);
3561    }
3562
3563    #[test]
3564    fn indexing_combined_with_addition_on_the_right() {
3565        let mut parser = CELParser::new(OpLookup::new());
3566        let mut seg = parser.parse_str("(0i32, 1i32).1 + 5i32").unwrap();
3567        assert_eq!(seg.call0::<i32>().unwrap(), 6);
3568    }
3569
3570    #[test]
3571    fn out_of_range_index_is_a_parse_error() {
3572        let mut parser = CELParser::new(OpLookup::new());
3573        let result = parser.parse_str("(1i32, 2i32).5");
3574        assert!(result.is_err());
3575    }
3576
3577    #[test]
3578    fn indexing_a_non_tuple_is_a_parse_error() {
3579        let mut parser = CELParser::new(OpLookup::new());
3580        let result = parser.parse_str("1i32.0");
3581        assert!(result.is_err());
3582    }
3583
3584    #[test]
3585    fn suffixed_index_is_a_parse_error() {
3586        let mut parser = CELParser::new(OpLookup::new());
3587        let result = parser.parse_str("(1i32, 2i32).0i32");
3588        assert!(result.is_err());
3589    }
3590
3591    #[test]
3592    fn chained_tuple_index_into_nested_tuple() {
3593        // `.1` selects the inner tuple `(10i32, 20i32)`, then `.0` selects its
3594        // first element. Source text `.1.0` tokenizes as a single float
3595        // literal `1.0`, which must be split back into the chained indices
3596        // `1` then `0` — using a shape/value where applying the indices to
3597        // the wrong operand or in the wrong order gives a different (wrong)
3598        // answer than 10 (e.g. swapping order would try `.0` on an i32 and
3599        // fail to parse; picking element 0 first would return "a" or 10
3600        // depending on order, not confusably 10 either way, so pick values
3601        // that make a mix-up obvious).
3602        let mut parser = CELParser::new(OpLookup::new());
3603        let mut seg = parser
3604            .parse_str(r#"("a", (10i32, 20i32)).1.0"#)
3605            .expect("chained .1.0 index should parse");
3606        assert_eq!(seg.call0::<i32>().unwrap(), 10);
3607    }
3608
3609    #[test]
3610    fn chained_tuple_index_suffixed_second_part_is_a_parse_error() {
3611        // The suffix lands on the whole `0.1i32` float token; the existing
3612        // unsuffixed-integer rule must still reject it.
3613        let mut parser = CELParser::new(OpLookup::new());
3614        let result = parser.parse_str("(1i32, 2i32).0.1i32");
3615        assert!(result.is_err());
3616    }
3617
3618    #[test]
3619    fn chained_tuple_index_scientific_notation_is_a_parse_error_not_a_panic() {
3620        // `1e2` normalizes to digits with no '.' at all (scientific notation),
3621        // unlike ordinary decimal floats like `0.1` — must be a graceful parse
3622        // error, not a panic on the assumption that '.' is always present.
3623        let mut parser = CELParser::new(OpLookup::new());
3624        let result = parser.parse_str("(1i32, 2i32).1e2");
3625        assert!(result.is_err());
3626    }
3627
3628    /// Retains malformed selector intervals even after the token has been consumed.
3629    #[test]
3630    fn invalid_tuple_selector_conversion_retains_its_token_span() {
3631        let mut parser = CELParser::new(OpLookup::new());
3632        for (source, expected) in [
3633            ("(1.0f64,).184467440737095516160", 10..31),
3634            ("(1.0f64,).0.1e0", 10..15),
3635            ("(1.0f64,).184467440737095516160, host", 10..31),
3636            ("(1.0f64,).0.1e0, host", 10..15),
3637        ] {
3638            let error = parser.parse_str(source).err().expect("invalid selector");
3639            assert_eq!(
3640                SourceSpan::from_proc_macro2_range(
3641                    error.span(),
3642                    error.end_span().unwrap_or(error.span())
3643                )
3644                .to_byte_range(source),
3645                expected,
3646                "{source}"
3647            );
3648        }
3649    }
3650
3651    #[test]
3652    fn complex_expression() {
3653        let mut parser = CELParser::new(OpLookup::new());
3654        let result = parser.parse_str("10 + 20 * (30 - 5) / 2");
3655        assert!(result.is_ok());
3656    }
3657
3658    #[test]
3659    fn logical_expression() {
3660        let mut parser = CELParser::new(OpLookup::new());
3661        let result = parser.parse_str("true && false || true");
3662        assert!(result.is_ok());
3663    }
3664
3665    #[test]
3666    fn comparison_expression() {
3667        let mut parser = CELParser::new(OpLookup::new());
3668        let result = parser.parse_str("10 == 20 && 30 > 40");
3669        assert!(result.is_ok());
3670    }
3671
3672    #[test]
3673    fn bitwise_expression() {
3674        let mut parser = CELParser::new(OpLookup::new());
3675        let result = parser.parse_str("1 | 2 & 3 ^ 4");
3676        assert!(result.is_ok());
3677    }
3678
3679    #[test]
3680    fn shift_expression() {
3681        let mut parser = CELParser::new(OpLookup::new());
3682        let result = parser.parse_str("8u32 << 2u32 + 16u32 >> 1u32");
3683        assert!(result.is_ok());
3684    }
3685
3686    #[test]
3687    fn unary_expression() {
3688        let mut parser = CELParser::new(OpLookup::new());
3689        let result = parser.parse_str("-10 + -20");
3690        assert!(result.is_ok());
3691    }
3692
3693    #[test]
3694    fn double_negation() {
3695        let mut parser = CELParser::new(OpLookup::new());
3696        let result = parser.parse_str("!!true");
3697        assert!(
3698            result.is_ok(),
3699            "Failed to parse !!true: {}",
3700            result.err().unwrap()
3701        );
3702        assert!(result.unwrap().call0::<bool>().unwrap());
3703    }
3704
3705    #[test]
3706    fn double_minus() {
3707        let mut parser = CELParser::new(OpLookup::new());
3708        let result = parser.parse_str("--5");
3709        assert!(
3710            result.is_ok(),
3711            "Failed to parse --5: {}",
3712            result.err().unwrap()
3713        );
3714        assert_eq!(result.unwrap().call0::<i32>().unwrap(), 5);
3715    }
3716
3717    #[test]
3718    fn chained_unary_expression() {
3719        let mut parser = CELParser::new(OpLookup::new());
3720        let result = parser.parse_str("!!false || !!true");
3721        if let Err(ref e) = result {
3722            eprintln!("Error: {:?}", e);
3723            eprintln!("Error message: {}", e.message());
3724        }
3725        assert!(result.is_ok(), "Failed to parse: {}", result.err().unwrap());
3726        assert!(result.unwrap().call0::<bool>().unwrap());
3727    }
3728
3729    #[test]
3730    fn cast_expression_parses_and_executes() {
3731        let mut parser = CELParser::new(OpLookup::new());
3732        let result = parser.parse_str("1024i32 as f64");
3733        assert_eq!(result.unwrap().call0::<f64>().unwrap(), 1024.0);
3734    }
3735
3736    #[test]
3737    fn cast_expression_chains_left_to_right() {
3738        // `x as i32 as f64` must apply left-to-right: `(x as i32) as f64`, not
3739        // `x as (i32 as f64)` (which isn't even expressible - a cast target is a bare
3740        // identifier, not another cast expression).
3741        let mut parser = CELParser::new(OpLookup::new());
3742        let result = parser.parse_str("1.5f64 as i32 as f64");
3743        assert_eq!(result.unwrap().call0::<f64>().unwrap(), 1.0);
3744    }
3745
3746    #[test]
3747    fn unary_negation_binds_tighter_than_cast() {
3748        // `-x as u32` must parse as `(-x) as u32` (matching Rust): the negative operand hits the
3749        // checked int->int cast's own out-of-range check at execution, not a "no operation `-`
3750        // for `u32`" error at parse time, which is what parsing it as `-(x as u32)` would
3751        // produce instead - `u32` has no registered unary negation, matching Rust (u32 doesn't
3752        // implement `Neg`).
3753        let mut parser = CELParser::new(OpLookup::new());
3754        let mut seg = parser.parse_str("-1i32 as u32").expect(
3755            "parses: unary negation is registered for i32, and i32 -> u32 is a valid cast pair",
3756        );
3757        let err = seg.call0::<u32>().unwrap_err();
3758        // The cast's own error is wrapped in a `SpanContext` (see `span_err`), which becomes the
3759        // outermost context and so is what plain `Display`/`to_string()` shows - the underlying
3760        // "does not fit" message is further down the `anyhow` chain, hence `{:#}`.
3761        let full = format!("{err:#}");
3762        assert!(
3763            full.contains("does not fit"),
3764            "expected an out-of-range cast error, got: {full}"
3765        );
3766    }
3767
3768    #[test]
3769    fn cast_binds_tighter_than_multiplicative_operators() {
3770        // `*` requires homogeneous operand types, so if `as` binds tighter than `*` (matching
3771        // Rust), this parses as `2i32 * (3i32 as f64)` - an `i32 * f64` mismatch, which this
3772        // grammar's eager, statically-typed segment construction rejects immediately at parse
3773        // time (operator/operand-type matching isn't deferred to execution, unlike a cast's own
3774        // value-range check). If `as` bound looser instead, this would parse as
3775        // `(2i32 * 3i32) as f64` and succeed.
3776        let mut parser = CELParser::new(OpLookup::new());
3777        let result = parser.parse_str("2i32 * 3i32 as f64");
3778        assert!(result.is_err(), "expected a type-mismatch parse error");
3779    }
3780
3781    #[test]
3782    fn cast_binds_tighter_than_additive_operators() {
3783        // Same reasoning as the multiplicative case: `1i32 + 2i32 as f64` must parse as
3784        // `1i32 + (2i32 as f64)` (an `i32 + f64` mismatch, a parse-time error), not
3785        // `(1i32 + 2i32) as f64` (which would succeed).
3786        let mut parser = CELParser::new(OpLookup::new());
3787        let result = parser.parse_str("1i32 + 2i32 as f64");
3788        assert!(result.is_err(), "expected a type-mismatch parse error");
3789    }
3790
3791    #[test]
3792    fn invalid_expression() {
3793        let mut parser = CELParser::new(OpLookup::new());
3794        let result = parser.parse_str("+");
3795        assert!(result.is_err());
3796    }
3797
3798    #[test]
3799    fn error_formatting() {
3800        let source = "10 + 20 30";
3801        let mut parser = CELParser::new(OpLookup::new());
3802        let result = parser.parse_str(source);
3803
3804        assert!(result.is_err());
3805
3806        let err = match &result {
3807            Ok(_) => panic!("expected parse error"),
3808            Err(e) => e,
3809        };
3810        assert_eq!(err.message(), "unexpected token");
3811
3812        let formatted = err.format_rustc_style(source, "test.cel", 1u32, &Renderer::plain());
3813        assert!(formatted.contains("error: unexpected token"));
3814        assert!(formatted.contains("test.cel:1:"));
3815        assert!(formatted.contains("1 | 10 + 20 30"));
3816        assert!(formatted.contains("^"));
3817    }
3818
3819    #[test]
3820    fn error_formatting_with_line_offset() {
3821        let source = "10 + 20 30";
3822        let mut parser = CELParser::new(OpLookup::new());
3823        let result = parser.parse_str(source);
3824
3825        assert!(result.is_err());
3826
3827        let err = match &result {
3828            Ok(_) => panic!("expected parse error"),
3829            Err(e) => e,
3830        };
3831        let formatted = err.format_rustc_style(source, "large_file.rs", 42u32, &Renderer::plain());
3832        assert!(formatted.contains("error: unexpected token"));
3833        assert!(formatted.contains("large_file.rs:42:"));
3834        assert!(formatted.contains("42 | 10 + 20 30"));
3835        assert!(formatted.contains("^"));
3836    }
3837
3838    #[test]
3839    fn print_error_formatting() {
3840        let line = line!() + 1;
3841        let source = r#"
3842
3843         10 + 20  30 // Unexpected token
3844
3845     "#;
3846
3847        let mut parser = CELParser::new(OpLookup::new());
3848        let result = parser.parse_str(source);
3849
3850        assert!(result.is_err(), "Expected parsing to fail");
3851
3852        let err = match &result {
3853            Ok(_) => panic!("expected parse error"),
3854            Err(e) => e,
3855        };
3856        eprintln!(
3857            "DEBUG: span.start.line = {}, span.start.column = {}",
3858            err.span().start().line,
3859            err.span().start().column
3860        );
3861
3862        let formatted_error = err.format_rustc_style(source, file!(), line, &Renderer::plain());
3863        println!("{}", formatted_error);
3864
3865        let formatted = formatted_error;
3866
3867        let expected_line = line + 2;
3868
3869        assert!(
3870            formatted.contains("error: unexpected token"),
3871            "Should contain error message, got: {}",
3872            formatted
3873        );
3874        assert!(
3875            formatted.contains(&format!("{}:", expected_line)),
3876            "Should show error on line {}, got: {}",
3877            expected_line,
3878            formatted
3879        );
3880        assert!(
3881            formatted.contains("30"),
3882            "Should show the source line with '30', got: {}",
3883            formatted
3884        );
3885        assert!(
3886            formatted.contains("^"),
3887            "Should have carets pointing to error, got: {}",
3888            formatted
3889        );
3890    }
3891
3892    #[test]
3893    fn test_addition_execution() -> anyhow::Result<()> {
3894        let mut parser = CELParser::new(OpLookup::new());
3895        let mut segment = parser
3896            .parse_str("10 + 20")
3897            .map_err(|e| anyhow::anyhow!("{}", e))?;
3898        let result = segment.call0::<i32>()?;
3899        assert_eq!(result, 30);
3900        Ok(())
3901    }
3902
3903    #[test]
3904    fn test_multiplication_execution() -> anyhow::Result<()> {
3905        let mut parser = CELParser::new(OpLookup::new());
3906        let mut segment = parser
3907            .parse_str("3 * 7")
3908            .map_err(|e| anyhow::anyhow!("{}", e))?;
3909        let result = segment.call0::<i32>()?;
3910        assert_eq!(result, 21);
3911        Ok(())
3912    }
3913
3914    #[test]
3915    fn test_complex_arithmetic_execution() -> anyhow::Result<()> {
3916        let mut parser = CELParser::new(OpLookup::new());
3917        let mut segment = parser
3918            .parse_str("10 + 20 * 3")
3919            .map_err(|e| anyhow::anyhow!("{}", e))?;
3920        let result = segment.call0::<i32>()?;
3921        assert_eq!(result, 70);
3922        Ok(())
3923    }
3924
3925    #[test]
3926    fn test_parenthesized_arithmetic_execution() -> anyhow::Result<()> {
3927        let mut parser = CELParser::new(OpLookup::new());
3928        let mut segment = parser
3929            .parse_str("(10 + 20) * 3")
3930            .map_err(|e| anyhow::anyhow!("{}", e))?;
3931        let result = segment.call0::<i32>()?;
3932        assert_eq!(result, 90);
3933        Ok(())
3934    }
3935
3936    #[test]
3937    fn test_comparison_execution() -> anyhow::Result<()> {
3938        let mut parser = CELParser::new(OpLookup::new());
3939        let mut segment = parser
3940            .parse_str("10 < 20")
3941            .map_err(|e| anyhow::anyhow!("{}", e))?;
3942        let result = segment.call0::<bool>()?;
3943        assert!(result);
3944        Ok(())
3945    }
3946
3947    #[test]
3948    fn test_logical_and_execution() -> anyhow::Result<()> {
3949        let mut parser = CELParser::new(OpLookup::new());
3950        let mut segment = parser
3951            .parse_str("true && false")
3952            .map_err(|e| anyhow::anyhow!("{}", e))?;
3953        let result = segment.call0::<bool>()?;
3954        assert!(!result);
3955        Ok(())
3956    }
3957
3958    #[test]
3959    fn test_unary_negation_execution() -> anyhow::Result<()> {
3960        let mut parser = CELParser::new(OpLookup::new());
3961        let mut segment = parser
3962            .parse_str("-42")
3963            .map_err(|e| anyhow::anyhow!("{}", e))?;
3964        let result = segment.call0::<i32>()?;
3965        assert_eq!(result, -42);
3966        Ok(())
3967    }
3968
3969    #[test]
3970    fn test_logical_not_execution() -> anyhow::Result<()> {
3971        let mut parser = CELParser::new(OpLookup::new());
3972        let mut segment = parser
3973            .parse_str("!true")
3974            .map_err(|e| anyhow::anyhow!("{}", e))?;
3975        let result = segment.call0::<bool>()?;
3976        assert!(!result);
3977        Ok(())
3978    }
3979
3980    #[test]
3981    fn test_u32_addition_execution() -> anyhow::Result<()> {
3982        let mut parser = CELParser::new(OpLookup::new());
3983        let mut segment = parser
3984            .parse_str("10u32 + 20u32")
3985            .map_err(|e| anyhow::anyhow!("{}", e))?;
3986        let result = segment.call0::<u32>()?;
3987        assert_eq!(result, 30);
3988        Ok(())
3989    }
3990
3991    #[test]
3992    fn test_identifier_with_scope() -> anyhow::Result<()> {
3993        let mut lookup = OpLookup::new();
3994        lookup.push_scope(|name, segment, num_operands, _span| {
3995            if num_operands == 0 {
3996                match name {
3997                    "x" => {
3998                        segment.op0(|| 10i32);
3999                        Ok(true)
4000                    }
4001                    "y" => {
4002                        segment.op0(|| 20i32);
4003                        Ok(true)
4004                    }
4005                    _ => Ok(false),
4006                }
4007            } else {
4008                Ok(false)
4009            }
4010        });
4011        let mut parser = CELParser::new(lookup);
4012        let mut segment = parser
4013            .parse_str("x + y")
4014            .map_err(|e| anyhow::anyhow!("{}", e))?;
4015        let result = segment.call0::<i32>()?;
4016        assert_eq!(result, 30);
4017        Ok(())
4018    }
4019
4020    #[test]
4021    fn test_undefined_identifier_error() {
4022        let mut parser = CELParser::new(OpLookup::new());
4023        let result = parser.parse_str("undefined_var + 10");
4024
4025        assert!(result.is_err());
4026        if let Err(e) = result {
4027            let error_msg = format!("{:?}", e);
4028            assert!(
4029                error_msg.contains("undefined identifier: `undefined_var`"),
4030                "Error message should contain 'undefined identifier: `undefined_var`', got: {}",
4031                error_msg
4032            );
4033        }
4034    }
4035
4036    #[test]
4037    fn test_identifier_scope_error_propagated() {
4038        let mut lookup = OpLookup::new();
4039        lookup.push_scope(|name, _segment, num_operands, _span| {
4040            if name == "bad_id" && num_operands == 0 {
4041                return Err(anyhow::anyhow!("custom identifier rejected"));
4042            }
4043            Ok(false)
4044        });
4045        let mut parser = CELParser::new(lookup);
4046        let err = match parser.parse_str("bad_id + 1") {
4047            Err(e) => e,
4048            Ok(_) => panic!("scope Err should propagate, not become Undefined identifier"),
4049        };
4050        assert!(
4051            err.message().contains("custom identifier rejected"),
4052            "expected scope error message, got: {}",
4053            err.message()
4054        );
4055        assert!(
4056            !err.message().contains("undefined identifier:"),
4057            "scope Err must not be rewritten as undefined identifier"
4058        );
4059    }
4060
4061    #[test]
4062    fn test_undefined_identifier_error_formatting() {
4063        let input = "undefined_var + 10";
4064        let mut parser = CELParser::new(OpLookup::new());
4065        let result = parser.parse_str(input);
4066
4067        assert!(result.is_err());
4068        if let Err(e) = result {
4069            let formatted_error = e.format_rustc_style(input, "test.cel", 1, &Renderer::plain());
4070            assert!(formatted_error.contains("undefined identifier"));
4071            assert!(formatted_error.contains("undefined_var"));
4072            assert!(formatted_error.contains("test.cel"));
4073        }
4074    }
4075
4076    #[test]
4077    fn test_float_arithmetic_execution() -> anyhow::Result<()> {
4078        let mut parser = CELParser::new(OpLookup::new());
4079        let mut segment = parser
4080            .parse_str("3.5 * 2.0")
4081            .map_err(|e| anyhow::anyhow!("{}", e))?;
4082        let result = segment.call0::<f64>()?;
4083        assert_eq!(result, 7.0);
4084        Ok(())
4085    }
4086
4087    #[test]
4088    fn call_empty_arg_list() -> anyhow::Result<()> {
4089        let mut lookup = OpLookup::new();
4090        lookup.push_scope(
4091            |name, segment, num_operands, _span| match (name, num_operands) {
4092                ("f", 0) => {
4093                    segment.op0(|| 0i32);
4094                    Ok(true)
4095                }
4096                ("()", 1) => {
4097                    segment.op1(|_callee: i32| 99i32)?;
4098                    Ok(true)
4099                }
4100                _ => Ok(false),
4101            },
4102        );
4103        let mut parser = CELParser::new(lookup);
4104        let mut segment = parser
4105            .parse_str("f()")
4106            .map_err(|e| anyhow::anyhow!("{}", e))?;
4107        assert_eq!(segment.call0::<i32>()?, 99);
4108        Ok(())
4109    }
4110
4111    #[test]
4112    fn call_single_arg() -> anyhow::Result<()> {
4113        let mut lookup = OpLookup::new();
4114        lookup.push_scope(
4115            |name, segment, num_operands, _span| match (name, num_operands) {
4116                ("f", 0) => {
4117                    segment.op0(|| 0i32);
4118                    Ok(true)
4119                }
4120                ("()", 2) => {
4121                    segment.op2(|_callee: i32, arg: i32| arg)?;
4122                    Ok(true)
4123                }
4124                _ => Ok(false),
4125            },
4126        );
4127        let mut parser = CELParser::new(lookup);
4128        let mut segment = parser
4129            .parse_str("f(42)")
4130            .map_err(|e| anyhow::anyhow!("{}", e))?;
4131        assert_eq!(segment.call0::<i32>()?, 42);
4132        Ok(())
4133    }
4134
4135    #[test]
4136    fn call_multiple_args() -> anyhow::Result<()> {
4137        let mut lookup = OpLookup::new();
4138        lookup.push_scope(
4139            |name, segment, num_operands, _span| match (name, num_operands) {
4140                ("f", 0) => {
4141                    segment.op0(|| 0i32);
4142                    Ok(true)
4143                }
4144                ("()", 3) => {
4145                    segment.op3(|_callee: i32, arg1: i32, arg2: i32| arg1 + arg2)?;
4146                    Ok(true)
4147                }
4148                _ => Ok(false),
4149            },
4150        );
4151        let mut parser = CELParser::new(lookup);
4152        let mut segment = parser
4153            .parse_str("f(10, 32)")
4154            .map_err(|e| anyhow::anyhow!("{}", e))?;
4155        assert_eq!(segment.call0::<i32>()?, 42);
4156        Ok(())
4157    }
4158
4159    #[test]
4160    fn call_missing_closing_paren() {
4161        let mut lookup = OpLookup::new();
4162        lookup.push_scope(
4163            |name, segment, num_operands, _span| match (name, num_operands) {
4164                ("f", 0) => {
4165                    segment.op0(|| 0i32);
4166                    Ok(true)
4167                }
4168                _ => Ok(false),
4169            },
4170        );
4171        let mut parser = CELParser::new(lookup);
4172        let err = match parser.parse_str("f(42 43)") {
4173            Err(e) => e,
4174            Ok(_) => panic!("expected parse error for missing closing parenthesis"),
4175        };
4176        assert_eq!(err.message(), "expected closing parenthesis");
4177    }
4178
4179    #[test]
4180    fn call_trailing_comma() {
4181        let mut lookup = OpLookup::new();
4182        lookup.push_scope(
4183            |name, segment, num_operands, _span| match (name, num_operands) {
4184                ("f", 0) => {
4185                    segment.op0(|| 0i32);
4186                    Ok(true)
4187                }
4188                _ => Ok(false),
4189            },
4190        );
4191        let mut parser = CELParser::new(lookup);
4192        let err = match parser.parse_str("f(42,)") {
4193            Err(e) => e,
4194            Ok(_) => panic!("expected parse error for trailing comma"),
4195        };
4196        assert_eq!(err.message(), "expected expression after comma");
4197    }
4198
4199    #[test]
4200    fn call_undefined_call_op() {
4201        let mut lookup = OpLookup::new();
4202        lookup.push_scope(
4203            |name, segment, num_operands, _span| match (name, num_operands) {
4204                ("f", 0) => {
4205                    segment.op0(|| 0i32);
4206                    Ok(true)
4207                }
4208                _ => Ok(false),
4209            },
4210        );
4211        let mut parser = CELParser::new(lookup);
4212        let err = match parser.parse_str("f()") {
4213            Err(e) => e,
4214            Ok(_) => panic!("expected error when () operator is not registered"),
4215        };
4216        assert!(
4217            err.message().starts_with("no operation"),
4218            "error should report no operation found, got: {}",
4219            err.message()
4220        );
4221    }
4222
4223    #[test]
4224    fn call_leading_comma_reports_expected_expression_at_the_comma() {
4225        let mut lookup = OpLookup::new();
4226        lookup.push_scope(
4227            |name, segment, num_operands, _span| match (name, num_operands) {
4228                ("f", 0) => {
4229                    segment.op0(|| 0i32);
4230                    Ok(true)
4231                }
4232                _ => Ok(false),
4233            },
4234        );
4235        let mut parser = CELParser::new(lookup);
4236        let err = match parser.parse_str("f(,5)") {
4237            Err(e) => e,
4238            Ok(_) => panic!("expected parse error for leading comma"),
4239        };
4240        assert_eq!(err.message(), "expected expression");
4241    }
4242
4243    #[test]
4244    fn call_chained() -> anyhow::Result<()> {
4245        let mut lookup = OpLookup::new();
4246        lookup.push_scope(
4247            |name, segment, num_operands, _span| match (name, num_operands) {
4248                ("f", 0) => {
4249                    segment.op0(|| 0i32);
4250                    Ok(true)
4251                }
4252                ("()", 1) => {
4253                    segment.op1r(|callee: i32| {
4254                        callee
4255                            .checked_add(7)
4256                            .ok_or_else(|| anyhow::anyhow!("overflow"))
4257                    })?;
4258                    Ok(true)
4259                }
4260                _ => Ok(false),
4261            },
4262        );
4263        let mut parser = CELParser::new(lookup);
4264        let mut segment = parser
4265            .parse_str("f()()")
4266            .map_err(|e| anyhow::anyhow!("{}", e))?;
4267        assert_eq!(segment.call0::<i32>()?, 14);
4268        Ok(())
4269    }
4270
4271    #[test]
4272    fn op_type_mismatch_error_spans_full_expression() {
4273        let source = r#""Hello" + 32.0"#;
4274        let mut parser = CELParser::new(OpLookup::new());
4275        let err = match parser.parse_str(source) {
4276            Err(e) => e,
4277            Ok(_) => panic!("expected parse error for type mismatch"),
4278        };
4279        assert!(
4280            err.message().starts_with("no operation"),
4281            "expected 'no operation' prefix, got: {}",
4282            err.message()
4283        );
4284        let end_span = err.end_span().expect("op-lookup errors carry an end span");
4285        assert!(
4286            end_span.end().column >= 14,
4287            "end span should reach the end of 32.0 (expected end.column >= 14, got {})",
4288            end_span.end().column
4289        );
4290    }
4291
4292    #[test]
4293    fn and_short_circuits_on_false() {
4294        // Without short-circuit the RHS executes and division-by-zero errors.
4295        // With short-circuit the RHS fragment is skipped, returning false directly.
4296        let mut parser = CELParser::new(OpLookup::new());
4297        let mut segment = parser
4298            .parse_str("false && (1i32 / 0i32 == 0i32)")
4299            .expect("should parse");
4300        assert!(!segment.call0::<bool>().unwrap());
4301    }
4302
4303    #[test]
4304    fn and_evaluates_rhs_when_lhs_true() {
4305        let mut parser = CELParser::new(OpLookup::new());
4306        let mut segment = parser.parse_str("true && false").expect("should parse");
4307        assert!(!segment.call0::<bool>().unwrap());
4308    }
4309
4310    #[test]
4311    fn and_chained_short_circuits() {
4312        let mut parser = CELParser::new(OpLookup::new());
4313        let mut segment = parser
4314            .parse_str("true && false && (1i32 / 0i32 == 0i32)")
4315            .expect("should parse");
4316        assert!(!segment.call0::<bool>().unwrap());
4317    }
4318
4319    #[test]
4320    fn and_lhs_type_error() {
4321        // LHS is i32, not bool — join2 must reject it at parse time.
4322        let mut parser = CELParser::new(OpLookup::new());
4323        let err = match parser.parse_str("1i32 && true") {
4324            Err(e) => e,
4325            Ok(_) => panic!("lhs i32 should fail for &&"),
4326        };
4327        assert!(err.end_span().is_some());
4328    }
4329
4330    #[test]
4331    fn or_lhs_type_error() {
4332        // LHS is i32, not bool — join2 must reject it at parse time.
4333        let mut parser = CELParser::new(OpLookup::new());
4334        let err = match parser.parse_str("1i32 || true") {
4335            Err(e) => e,
4336            Ok(_) => panic!("lhs i32 should fail for ||"),
4337        };
4338        assert!(err.end_span().is_some());
4339    }
4340
4341    #[test]
4342    fn or_short_circuits_on_true() {
4343        // Without short-circuit the RHS executes and division-by-zero errors.
4344        // With short-circuit the RHS fragment is skipped, returning true directly.
4345        let mut parser = CELParser::new(OpLookup::new());
4346        let mut segment = parser
4347            .parse_str("true || (1i32 / 0i32 == 0i32)")
4348            .expect("should parse");
4349        assert!(segment.call0::<bool>().unwrap());
4350    }
4351
4352    #[test]
4353    fn or_evaluates_rhs_when_lhs_false() {
4354        let mut parser = CELParser::new(OpLookup::new());
4355        let mut segment = parser.parse_str("false || true").expect("should parse");
4356        assert!(segment.call0::<bool>().unwrap());
4357    }
4358
4359    #[test]
4360    fn or_chained() {
4361        let mut parser = CELParser::new(OpLookup::new());
4362        let mut segment = parser
4363            .parse_str("true || false || false")
4364            .expect("should parse");
4365        assert!(segment.call0::<bool>().unwrap());
4366    }
4367
4368    #[test]
4369    fn if_true_branch_selected() {
4370        let mut parser = CELParser::new(OpLookup::new());
4371        let mut segment = parser
4372            .parse_str("if true { 1i32 } else { 2i32 }")
4373            .expect("should parse");
4374        assert_eq!(segment.call0::<i32>().unwrap(), 1);
4375    }
4376
4377    #[test]
4378    fn if_false_branch_selected() {
4379        let mut parser = CELParser::new(OpLookup::new());
4380        let mut segment = parser
4381            .parse_str("if false { 1i32 } else { 2i32 }")
4382            .expect("should parse");
4383        assert_eq!(segment.call0::<i32>().unwrap(), 2);
4384    }
4385
4386    #[test]
4387    fn if_else_if_first_branch() {
4388        let mut parser = CELParser::new(OpLookup::new());
4389        let mut segment = parser
4390            .parse_str("if true { 1i32 } else if false { 2i32 } else { 3i32 }")
4391            .expect("should parse");
4392        assert_eq!(segment.call0::<i32>().unwrap(), 1);
4393    }
4394
4395    #[test]
4396    fn if_else_if_middle_branch() {
4397        let mut parser = CELParser::new(OpLookup::new());
4398        let mut segment = parser
4399            .parse_str("if false { 1i32 } else if true { 2i32 } else { 3i32 }")
4400            .expect("should parse");
4401        assert_eq!(segment.call0::<i32>().unwrap(), 2);
4402    }
4403
4404    #[test]
4405    fn if_else_if_last_branch() {
4406        let mut parser = CELParser::new(OpLookup::new());
4407        let mut segment = parser
4408            .parse_str("if false { 1i32 } else if false { 2i32 } else { 3i32 }")
4409            .expect("should parse");
4410        assert_eq!(segment.call0::<i32>().unwrap(), 3);
4411    }
4412
4413    #[test]
4414    fn if_omitted_else_unit_branch() {
4415        let mut parser = CELParser::new(OpLookup::new());
4416        let mut segment = parser.parse_str("if true { () }").expect("should parse");
4417        segment.call0::<()>().expect("should execute");
4418    }
4419
4420    #[test]
4421    fn if_omitted_else_rejects_non_unit_then() {
4422        // then-branch returns i32, implicit else returns () — types must match.
4423        let mut parser = CELParser::new(OpLookup::new());
4424        assert!(parser.parse_str("if false { 1i32 }").is_err());
4425    }
4426
4427    #[test]
4428    fn if_branch_type_mismatch_is_error() {
4429        let mut parser = CELParser::new(OpLookup::new());
4430        assert!(parser.parse_str("if true { 1i32 } else { true }").is_err());
4431    }
4432
4433    #[test]
4434    fn if_branch_tuple_arity_mismatch_is_error() {
4435        // Regression test: a flat erased tuple identity
4436        // marker type, so a naive type_id comparison would accept branches
4437        // with genuinely different tuple shapes — join2 must compare shapes,
4438        // not just the marker type, and reject this.
4439        let mut parser = CELParser::new(OpLookup::new());
4440        let result = parser.parse_str("if false { (1i32, 2i32) } else { (3i64, 4i64, 5i64) }.0");
4441        assert!(
4442            result.is_err(),
4443            "branches with different tuple shapes must not be accepted"
4444        );
4445    }
4446
4447    #[test]
4448    fn if_branch_tuple_element_type_mismatch_is_error() {
4449        let mut parser = CELParser::new(OpLookup::new());
4450        let result = parser.parse_str("if false { (1i32, 2i32) } else { (3i64, 4i64) }.0");
4451        assert!(
4452            result.is_err(),
4453            "branches with the same arity but different element types must not be accepted"
4454        );
4455    }
4456
4457    #[test]
4458    fn if_missing_open_brace_is_error() {
4459        let mut parser = CELParser::new(OpLookup::new());
4460        assert!(parser.parse_str("if true 1i32 } else { 2i32 }").is_err());
4461    }
4462
4463    #[test]
4464    fn if_missing_else_after_brace_is_fine() {
4465        // Omitting else is allowed; result type must be ().
4466        let mut parser = CELParser::new(OpLookup::new());
4467        let mut segment = parser.parse_str("if false { () }").expect("should parse");
4468        segment.call0::<()>().expect("should execute");
4469    }
4470
4471    #[test]
4472    fn if_trailing_else_is_error() {
4473        // `else` with no body is a parse error.
4474        let mut parser = CELParser::new(OpLookup::new());
4475        assert!(parser.parse_str("if true { () } else").is_err());
4476    }
4477
4478    #[test]
4479    fn parse_expression_stops_before_comma() -> anyhow::Result<()> {
4480        use lex_lexer::LexLexer;
4481        let stream: proc_macro2::TokenStream = "10i32 + 20i32, 5i32".parse().unwrap();
4482        let mut parser = CELParser::new(OpLookup::new());
4483        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4484        let mut seg = parser
4485            .parse_expression()
4486            .map_err(|e| anyhow::anyhow!("{}", e))?;
4487        let result: i32 = seg.call0()?;
4488        assert_eq!(result, 30);
4489        let remaining: Vec<_> = parser.take_lex_tokens().expect("tokens present").collect();
4490        // The comma and "5i32" should remain unconsumed.
4491        assert_eq!(
4492            remaining.len(),
4493            2,
4494            "expected 2 remaining tokens (comma and 5i32)"
4495        );
4496        Ok(())
4497    }
4498
4499    #[test]
4500    fn parse_expression_on_empty_input_returns_error() {
4501        use lex_lexer::LexLexer;
4502        let stream: proc_macro2::TokenStream = "".parse().unwrap();
4503        let mut parser = CELParser::new(OpLookup::new());
4504        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4505        let result = parser.parse_expression();
4506        assert!(result.is_err(), "expected Err for empty input");
4507    }
4508
4509    #[test]
4510    fn parse_literal_pattern_accepts_a_bare_literal() -> anyhow::Result<()> {
4511        use lex_lexer::LexLexer;
4512        let stream: proc_macro2::TokenStream = "5i32".parse().unwrap();
4513        let mut parser = CELParser::new(OpLookup::new());
4514        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4515        let mut seg = parser
4516            .parse_literal_pattern()
4517            .map_err(|e| anyhow::anyhow!("{}", e))?;
4518        assert_eq!(seg.call0::<i32>()?, 5);
4519        Ok(())
4520    }
4521
4522    #[test]
4523    fn parse_literal_pattern_accepts_a_negated_integer_literal() -> anyhow::Result<()> {
4524        use lex_lexer::LexLexer;
4525        let stream: proc_macro2::TokenStream = "-5i32".parse().unwrap();
4526        let mut parser = CELParser::new(OpLookup::new());
4527        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4528        let mut seg = parser
4529            .parse_literal_pattern()
4530            .map_err(|e| anyhow::anyhow!("{}", e))?;
4531        assert_eq!(seg.call0::<i32>()?, -5);
4532        Ok(())
4533    }
4534
4535    #[test]
4536    fn parse_literal_pattern_accepts_a_negated_float_literal() -> anyhow::Result<()> {
4537        use lex_lexer::LexLexer;
4538        let stream: proc_macro2::TokenStream = "-1.5f64".parse().unwrap();
4539        let mut parser = CELParser::new(OpLookup::new());
4540        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4541        let mut seg = parser
4542            .parse_literal_pattern()
4543            .map_err(|e| anyhow::anyhow!("{}", e))?;
4544        assert_eq!(seg.call0::<f64>()?, -1.5);
4545        Ok(())
4546    }
4547
4548    /// Compiles integer-form float literals in literal patterns.
4549    #[test]
4550    fn integer_form_float_literal_patterns_preserve_width_and_sign() {
4551        let mut parser = CELParser::new(OpLookup::new());
4552        parser.set_tokens(
4553            "-1_f64"
4554                .parse::<proc_macro2::TokenStream>()
4555                .unwrap()
4556                .into_iter(),
4557        );
4558        let mut f64_pattern = parser.parse_literal_pattern().unwrap();
4559        assert_eq!(f64_pattern.call0::<f64>().unwrap(), -1.0);
4560
4561        parser.set_tokens(
4562            "1f32"
4563                .parse::<proc_macro2::TokenStream>()
4564                .unwrap()
4565                .into_iter(),
4566        );
4567        let mut f32_pattern = parser.parse_literal_pattern().unwrap();
4568        assert_eq!(f32_pattern.call0::<f32>().unwrap(), 1.0);
4569    }
4570
4571    #[test]
4572    fn parse_literal_pattern_stops_before_a_trailing_operator() -> anyhow::Result<()> {
4573        use lex_lexer::LexLexer;
4574        let stream: proc_macro2::TokenStream = "1i32 + 2i32".parse().unwrap();
4575        let mut parser = CELParser::new(OpLookup::new());
4576        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4577        let mut seg = parser
4578            .parse_literal_pattern()
4579            .map_err(|e| anyhow::anyhow!("{}", e))?;
4580        assert_eq!(seg.call0::<i32>()?, 1);
4581        let remaining: Vec<_> = parser.take_lex_tokens().expect("tokens present").collect();
4582        assert_eq!(
4583            remaining.len(),
4584            2,
4585            "expected 2 remaining tokens (+ and 2i32)"
4586        );
4587        Ok(())
4588    }
4589
4590    #[test]
4591    fn parse_literal_pattern_rejects_a_dash_not_followed_by_a_literal() {
4592        use lex_lexer::LexLexer;
4593        let stream: proc_macro2::TokenStream = "-mode".parse().unwrap();
4594        let mut parser = CELParser::new(OpLookup::new());
4595        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4596        assert!(parser.parse_literal_pattern().is_err());
4597    }
4598
4599    #[test]
4600    fn parse_literal_pattern_rejects_negating_an_unsigned_literal() {
4601        use lex_lexer::LexLexer;
4602        let stream: proc_macro2::TokenStream = "-1u32".parse().unwrap();
4603        let mut parser = CELParser::new(OpLookup::new());
4604        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4605        assert!(parser.parse_literal_pattern().is_err());
4606    }
4607
4608    #[test]
4609    fn parse_literal_pattern_rejects_a_bare_identifier() {
4610        use lex_lexer::LexLexer;
4611        let stream: proc_macro2::TokenStream = "mode".parse().unwrap();
4612        let mut parser = CELParser::new(OpLookup::new());
4613        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4614        assert!(parser.parse_literal_pattern().is_err());
4615    }
4616
4617    #[test]
4618    fn parse_literal_pattern_rejects_a_tuple() {
4619        use lex_lexer::LexLexer;
4620        let stream: proc_macro2::TokenStream = "(1i32, 2i32)".parse().unwrap();
4621        let mut parser = CELParser::new(OpLookup::new());
4622        parser.set_lex_tokens(LexLexer::new(stream.into_iter()).peekable());
4623        assert!(parser.parse_literal_pattern().is_err());
4624    }
4625
4626    #[test]
4627    fn closure_literal_with_one_param_compiles_and_calls() -> anyhow::Result<()> {
4628        let mut parser = CELParser::new(OpLookup::new());
4629        let mut segment = parser
4630            .parse_str("|x: i32| x + 1")
4631            .map_err(|e| anyhow::anyhow!("{}", e))?;
4632        let closure: cel_runtime::DynClosure = segment.call0()?;
4633        let x = 5i32;
4634        assert_eq!(closure.call::<i32>(&[&x])?, 6);
4635        Ok(())
4636    }
4637
4638    #[test]
4639    fn closure_literal_with_zero_params_compiles_and_calls() -> anyhow::Result<()> {
4640        let mut parser = CELParser::new(OpLookup::new());
4641        let mut segment = parser
4642            .parse_str("|| 42")
4643            .map_err(|e| anyhow::anyhow!("{}", e))?;
4644        let closure: cel_runtime::DynClosure = segment.call0()?;
4645        assert_eq!(closure.call::<i32>(&[])?, 42);
4646        Ok(())
4647    }
4648
4649    #[test]
4650    fn closure_literal_with_two_params_compiles_and_calls_in_order() -> anyhow::Result<()> {
4651        let mut parser = CELParser::new(OpLookup::new());
4652        let mut segment = parser
4653            .parse_str("|a: i32, b: i32| a - b")
4654            .map_err(|e| anyhow::anyhow!("{}", e))?;
4655        let closure: cel_runtime::DynClosure = segment.call0()?;
4656        let (a, b) = (10i32, 3i32);
4657        assert_eq!(closure.call::<i32>(&[&a, &b])?, 7);
4658        Ok(())
4659    }
4660
4661    #[test]
4662    fn closure_literal_with_tuple_typed_param_compiles_and_calls() -> anyhow::Result<()> {
4663        let mut parser = CELParser::new(OpLookup::new());
4664        let mut segment = parser
4665            .parse_str("|r: (i32, i32)| r.0 + r.1")
4666            .map_err(|e| anyhow::anyhow!("{}", e))?;
4667        let closure: cel_runtime::DynClosure = segment.call0()?;
4668
4669        // Borrow a canonical whole-value owner at the checked closure boundary.
4670        let mut pair = DynSegment::new::<()>();
4671        let ambient_start = pair.current_stack_offset();
4672        pair.just(10i32);
4673        pair.annotate_top(crate::op_table::builtin_value_type(TypeId::of::<i32>()).unwrap())?;
4674        pair.just(20i32);
4675        pair.annotate_top(crate::op_table::builtin_value_type(TypeId::of::<i32>()).unwrap())?;
4676        pair.make_tuple(2, ambient_start)?;
4677        let pair = pair.call_dyn_value(&[])?;
4678
4679        assert_eq!(closure.call::<i32>(&[&pair])?, 30);
4680        Ok(())
4681    }
4682
4683    #[test]
4684    fn closure_param_accepts_a_builtin_generic_type() -> anyhow::Result<()> {
4685        let mut parser = CELParser::new(OpLookup::new());
4686        let mut segment = parser
4687            .parse_str("|r: RangeInclusive(f64)| r")
4688            .map_err(|e| anyhow::anyhow!("{}", e))?;
4689        let closure: cel_runtime::DynClosure = segment.call0()?;
4690        let range = 1.0f64..=2.0f64;
4691        assert_eq!(
4692            closure.call::<std::ops::RangeInclusive<f64>>(&[&range])?,
4693            1.0..=2.0
4694        );
4695        Ok(())
4696    }
4697
4698    #[test]
4699    fn closure_param_accepts_an_array_type() {
4700        let mut parser = CELParser::new(OpLookup::new());
4701        let mut segment = parser.parse_str("(|xs: [i32]| xs)([1, 2])").unwrap();
4702        let array = segment
4703            .call0::<cel_runtime::OwnedValue>()
4704            .unwrap()
4705            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()
4706            .unwrap();
4707        assert_eq!(array.as_slice(), &[1, 2]);
4708    }
4709
4710    #[test]
4711    fn closure_body_referencing_an_undeclared_name_is_a_parse_error() {
4712        let mut parser = CELParser::new(OpLookup::new());
4713        let err = parser.parse_str("|x: i32| x + y");
4714        assert!(err.is_err());
4715    }
4716
4717    #[test]
4718    fn nested_closure_referencing_only_its_own_param_compiles_and_calls() -> anyhow::Result<()> {
4719        let mut parser = CELParser::new(OpLookup::new());
4720        // The outer closure's own parameter `x` must NOT be visible inside the inner closure
4721        // body — a bare nested closure literal parses fine directly as the outer body's
4722        // `expression`, with no extra block grouping needed (this grammar has no bare
4723        // block-expression production, only `if`'s own braces, so `{ ... }` grouping isn't an
4724        // option here anyway).
4725        let mut segment = parser
4726            .parse_str("|x: i32| |y: i32| y + 1")
4727            .map_err(|e| anyhow::anyhow!("{}", e))?;
4728        let outer: cel_runtime::DynClosure = segment.call0()?;
4729        let x = 0i32;
4730        let inner: cel_runtime::DynClosure = outer.call(&[&x])?;
4731        let y = 41i32;
4732        assert_eq!(inner.call::<i32>(&[&y])?, 42);
4733        Ok(())
4734    }
4735
4736    #[test]
4737    fn closure_body_cannot_see_an_enclosing_scopes_names() {
4738        // A scope pushed before parsing (standing in for e.g. adam-lang's own cell-name scope)
4739        // must not leak into a closure body's name resolution.
4740        let mut lookup = OpLookup::new();
4741        lookup.push_scope(|name, segment, arity, _span| {
4742            if name == "outer_only" && arity == 0 {
4743                segment.just(1i32);
4744                Ok(true)
4745            } else {
4746                Ok(false)
4747            }
4748        });
4749        let mut parser = CELParser::new(lookup);
4750        let err = parser.parse_str("|x: i32| x + outer_only");
4751        assert!(err.is_err());
4752    }
4753
4754    #[test]
4755    fn ast_context_parses_a_one_param_closure() {
4756        let mut parser = Parser::<AstContext>::new(OpLookup::new());
4757        let expr = parser.parse_str_ast("|x: i32| x").unwrap();
4758        let Expr::Closure { params, body, .. } = expr else {
4759            panic!("expected Closure");
4760        };
4761        assert_eq!(params.len(), 1);
4762        assert_eq!(params[0].name, "x");
4763        assert!(matches!(
4764            &params[0].type_expr,
4765            TypeExpr::Named { name, args, .. } if name == "i32" && args.is_empty()
4766        ));
4767        assert!(matches!(*body, Expr::Ident { ref name, .. } if name == "x"));
4768    }
4769
4770    #[test]
4771    fn ast_context_parses_a_zero_param_closure() {
4772        let mut parser = Parser::<AstContext>::new(OpLookup::new());
4773        let expr = parser.parse_str_ast("|| 1i32").unwrap();
4774        let Expr::Closure { params, .. } = expr else {
4775            panic!("expected Closure");
4776        };
4777        assert!(params.is_empty());
4778    }
4779
4780    #[test]
4781    fn ast_context_parses_a_tuple_typed_closure_param() {
4782        let mut parser = Parser::<AstContext>::new(OpLookup::new());
4783        let expr = parser.parse_str_ast("|x: (i32, f64)| x.0").unwrap();
4784        let Expr::Closure { params, .. } = expr else {
4785            panic!("expected Closure");
4786        };
4787        match &params[0].type_expr {
4788            TypeExpr::Tuple { elements, .. } => assert_eq!(elements.len(), 2),
4789            other => panic!("expected Tuple, got {other:?}"),
4790        }
4791    }
4792
4793    #[test]
4794    fn range_expression_constructs_a_range() {
4795        let mut parser = CELParser::new(OpLookup::new());
4796        let mut seg = parser.parse_str("1i32..5i32").unwrap();
4797        assert_eq!(seg.call0::<std::ops::Range<i32>>().unwrap(), 1i32..5i32);
4798    }
4799
4800    #[test]
4801    fn range_inclusive_expression_constructs_a_range_inclusive() {
4802        let mut parser = CELParser::new(OpLookup::new());
4803        let mut seg = parser.parse_str("1i32..=5i32").unwrap();
4804        assert_eq!(
4805            seg.call0::<std::ops::RangeInclusive<i32>>().unwrap(),
4806            1i32..=5i32
4807        );
4808    }
4809
4810    #[test]
4811    fn range_from_expression_constructs_a_range_from() {
4812        let mut parser = CELParser::new(OpLookup::new());
4813        let mut seg = parser.parse_str("3i32..").unwrap();
4814        assert_eq!(seg.call0::<std::ops::RangeFrom<i32>>().unwrap(), 3i32..);
4815    }
4816
4817    #[test]
4818    fn range_to_expression_constructs_a_range_to() {
4819        let mut parser = CELParser::new(OpLookup::new());
4820        let mut seg = parser.parse_str("..7i32").unwrap();
4821        assert_eq!(seg.call0::<std::ops::RangeTo<i32>>().unwrap(), ..7i32);
4822    }
4823
4824    #[test]
4825    fn range_to_inclusive_expression_constructs_a_range_to_inclusive() {
4826        let mut parser = CELParser::new(OpLookup::new());
4827        let mut seg = parser.parse_str("..=7i32").unwrap();
4828        assert_eq!(
4829            seg.call0::<std::ops::RangeToInclusive<i32>>().unwrap(),
4830            ..=7i32
4831        );
4832    }
4833
4834    #[test]
4835    fn range_full_expression_constructs_a_range_full() {
4836        let mut parser = CELParser::new(OpLookup::new());
4837        let mut seg = parser.parse_str("..").unwrap();
4838        seg.call0::<std::ops::RangeFull>().unwrap();
4839    }
4840
4841    #[test]
4842    fn range_endpoints_are_full_or_expressions() {
4843        // `1 + 2..3 * 4` must group as `(1 + 2)..(3 * 4)`, matching Rust's own precedence
4844        // (range binds looser than every arithmetic/bitwise operator).
4845        let mut parser = CELParser::new(OpLookup::new());
4846        let mut seg = parser.parse_str("1i32 + 2i32..3i32 * 4i32").unwrap();
4847        assert_eq!(seg.call0::<std::ops::Range<i32>>().unwrap(), 3i32..12i32);
4848    }
4849
4850    #[test]
4851    fn chained_ranges_are_a_parse_error() {
4852        // Ranges don't chain, matching Rust (`1..2..3` is also a compile error there). No
4853        // special "non-chainable" check is needed in `is_range_expression` itself: after
4854        // parsing `1..2`, the leftover `..3` fails `parse_tokens_ctx`'s end-of-stream check
4855        // the same way `"10 + 25 25"` already does (see `incomplete_expression`).
4856        let mut parser = CELParser::new(OpLookup::new());
4857        let result = parser.parse_str("1i32..2i32..3i32");
4858        assert!(result.is_err(), "expected a parse error, got Ok");
4859    }
4860
4861    #[test]
4862    fn range_to_inclusive_without_a_right_operand_is_a_parse_error() {
4863        // `..=` always requires a right endpoint — there is no inclusive-from-only range.
4864        let mut parser = CELParser::new(OpLookup::new());
4865        let result = parser.parse_str("..=");
4866        assert!(result.is_err(), "expected a parse error, got Ok");
4867    }
4868
4869    #[test]
4870    fn range_endpoint_absorbs_a_trailing_comparison_confirming_or_expression_operands() {
4871        // Confirms range operands are `or_expression`, not `bitwise_or_expression`: in
4872        // `1i32..5i32 == true`, `5i32 == true` must group together as the range's right
4873        // endpoint's own `or_expression` and fail *there* (`i32` vs `bool`) — proving the
4874        // endpoint absorbed the whole comparison, rather than `..` grabbing only `5i32` and
4875        // `==` applying afterward to an already-built `Range`.
4876        let mut parser = CELParser::new(OpLookup::new());
4877        let err = match parser.parse_str("1i32..5i32 == true") {
4878            Err(e) => e,
4879            Ok(_) => panic!("expected a parse error"),
4880        };
4881        let message = err.message();
4882        assert!(
4883            message.starts_with("no operation `==`"),
4884            "expected a 'no operation `==`' error, got: {message}"
4885        );
4886        assert!(
4887            !message.contains("Range"),
4888            "expected the error to be about `i32`/`bool` (the inner endpoint's own comparison), \
4889             not `Range<i32>` (which would mean `..` grabbed only `5i32` and `==` applied afterward \
4890             to an already-built range) — got: {message}"
4891        );
4892    }
4893
4894    #[test]
4895    fn parameter_list_accepts_a_range_expression() -> anyhow::Result<()> {
4896        let mut lookup = OpLookup::new();
4897        lookup.push_scope(
4898            |name, segment, num_operands, _span| match (name, num_operands) {
4899                ("f", 0) => {
4900                    segment.op0(|| 0i32);
4901                    Ok(true)
4902                }
4903                ("()", 2) => {
4904                    segment.op2(|_callee: i32, arg: std::ops::Range<i32>| arg)?;
4905                    Ok(true)
4906                }
4907                _ => Ok(false),
4908            },
4909        );
4910        let mut parser = CELParser::new(lookup);
4911        let mut segment = parser
4912            .parse_str("f(1i32..5i32)")
4913            .map_err(|e| anyhow::anyhow!("{}", e))?;
4914        assert_eq!(segment.call0::<std::ops::Range<i32>>()?, 1i32..5i32);
4915        Ok(())
4916    }
4917
4918    #[test]
4919    fn tuple_or_group_accepts_a_range_expression() -> anyhow::Result<()> {
4920        let mut parser = CELParser::new(OpLookup::new());
4921        let mut seg = parser.parse_str("(1i32..5i32)").unwrap();
4922        assert_eq!(seg.call0::<std::ops::Range<i32>>().unwrap(), 1i32..5i32);
4923        Ok(())
4924    }
4925
4926    #[test]
4927    fn if_expression_branches_accept_range_expressions() {
4928        let mut parser = CELParser::new(OpLookup::new());
4929        let mut seg = parser
4930            .parse_str("if true { 1i32..5i32 } else { 2i32..6i32 }")
4931            .unwrap();
4932        assert_eq!(seg.call0::<std::ops::Range<i32>>().unwrap(), 1i32..5i32);
4933    }
4934
4935    #[test]
4936    fn closure_body_accepts_a_range_expression() -> anyhow::Result<()> {
4937        let mut parser = CELParser::new(OpLookup::new());
4938        let mut segment = parser
4939            .parse_str("|| 1i32..5i32")
4940            .map_err(|e| anyhow::anyhow!("{}", e))?;
4941        let closure: cel_runtime::DynClosure = segment.call0()?;
4942        assert_eq!(closure.call::<std::ops::Range<i32>>(&[])?, 1i32..5i32);
4943        Ok(())
4944    }
4945
4946    /// Returns the [`ParseError`] the runtime-executing parser must produce for `source`.
4947    fn array_parse_error(source: &str) -> ParseError {
4948        let mut parser = CELParser::new(OpLookup::new());
4949        match parser.parse_str(source) {
4950            Err(e) => e,
4951            Ok(_) => panic!("expected a parse error for `{source}`"),
4952        }
4953    }
4954
4955    #[test]
4956    fn array_literal_evaluates_to_its_elements_in_source_order() -> anyhow::Result<()> {
4957        let mut parser = CELParser::new(OpLookup::new());
4958        let mut segment = parser
4959            .parse_str("[0i32, 1i32, 2i32]")
4960            .map_err(|e| anyhow::anyhow!("{}", e))?;
4961        let array = segment
4962            .call0::<cel_runtime::OwnedValue>()?
4963            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
4964        assert_eq!(array.into_vec(), vec![0, 1, 2]);
4965        Ok(())
4966    }
4967
4968    #[test]
4969    fn typed_array_annotation_preserves_unsuffixed_non_empty_inference() -> anyhow::Result<()> {
4970        let mut parser = CELParser::new(OpLookup::new());
4971        let mut segment = parser
4972            .parse_str("[0, 1]")
4973            .map_err(|e| anyhow::anyhow!("{}", e))?;
4974        let array = segment
4975            .call0::<cel_runtime::OwnedValue>()?
4976            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
4977        assert_eq!(array.into_vec(), vec![0, 1]);
4978        Ok(())
4979    }
4980
4981    #[test]
4982    fn typed_array_annotation_evaluates_to_the_declared_scalar_type() -> anyhow::Result<()> {
4983        let mut parser = CELParser::new(OpLookup::new());
4984        let mut segment = parser
4985            .parse_str("[0, 1]: [i32]")
4986            .map_err(|e| anyhow::anyhow!("{}", e))?;
4987        let array = segment
4988            .call0::<cel_runtime::OwnedValue>()?
4989            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
4990        assert_eq!(array.into_vec(), vec![0, 1]);
4991        Ok(())
4992    }
4993
4994    #[test]
4995    fn typed_array_annotation_evaluates_to_the_declared_f64_type() -> anyhow::Result<()> {
4996        let mut parser = CELParser::new(OpLookup::new());
4997        let mut segment = parser
4998            .parse_str("[1.0, 42.5]: [f64]")
4999            .map_err(|e| anyhow::anyhow!("{}", e))?;
5000        let array = segment
5001            .call0::<cel_runtime::OwnedValue>()?
5002            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<f64>>>()?;
5003        assert_eq!(array.into_vec(), vec![1.0, 42.5]);
5004        Ok(())
5005    }
5006
5007    #[test]
5008    fn typed_array_annotation_constructs_a_typed_empty_array() -> anyhow::Result<()> {
5009        let mut parser = CELParser::new(OpLookup::new());
5010        let mut segment = parser
5011            .parse_str("[]: [i32]")
5012            .map_err(|e| anyhow::anyhow!("{}", e))?;
5013        let array = segment
5014            .call0::<cel_runtime::OwnedValue>()?
5015            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
5016        assert!(array.into_vec().is_empty());
5017        Ok(())
5018    }
5019
5020    #[test]
5021    fn typed_array_annotation_constructs_a_nested_typed_empty_array() -> anyhow::Result<()> {
5022        let mut parser = CELParser::new(OpLookup::new());
5023        let mut segment = parser
5024            .parse_str("[]: [[i32]]")
5025            .map_err(|e| anyhow::anyhow!("{}", e))?;
5026        let array = segment
5027            .call0::<cel_runtime::OwnedValue>()?
5028            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>>(
5029            )?;
5030        assert!(array.into_vec().is_empty());
5031        Ok(())
5032    }
5033
5034    #[test]
5035    fn single_element_array_literal_needs_no_trailing_comma() -> anyhow::Result<()> {
5036        let mut parser = CELParser::new(OpLookup::new());
5037        let mut segment = parser
5038            .parse_str("[7i32]")
5039            .map_err(|e| anyhow::anyhow!("{}", e))?;
5040        let array = segment
5041            .call0::<cel_runtime::OwnedValue>()?
5042            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
5043        assert_eq!(array.into_vec(), vec![7]);
5044        Ok(())
5045    }
5046
5047    #[test]
5048    fn array_elements_can_be_arbitrary_expressions() -> anyhow::Result<()> {
5049        let mut parser = CELParser::new(OpLookup::new());
5050        let mut segment = parser
5051            .parse_str("[1i32 + 2i32, if true { 4i32 } else { 5i32 }]")
5052            .map_err(|e| anyhow::anyhow!("{}", e))?;
5053        let array = segment
5054            .call0::<cel_runtime::OwnedValue>()?
5055            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
5056        assert_eq!(array.into_vec(), vec![3, 4]);
5057        Ok(())
5058    }
5059
5060    #[test]
5061    fn empty_array_literal_is_rejected_with_a_dedicated_diagnostic() {
5062        let err = array_parse_error("[]");
5063        assert!(
5064            err.message().contains("empty array"),
5065            "got: {}",
5066            err.message()
5067        );
5068        assert!(
5069            err.message().contains("issues/212"),
5070            "the diagnostic must reference the contextual-typing issue, got: {}",
5071            err.message()
5072        );
5073    }
5074
5075    #[test]
5076    fn array_literal_rejects_a_trailing_comma() {
5077        let err = array_parse_error("[0i32,]");
5078        assert!(
5079            err.message().contains("expected expression after ','"),
5080            "got: {}",
5081            err.message()
5082        );
5083    }
5084
5085    #[test]
5086    fn array_literal_requires_a_comma_between_elements() {
5087        let err = array_parse_error("[0i32 1i32]");
5088        assert!(
5089            err.message().contains("expected ',' or closing ']'"),
5090            "got: {}",
5091            err.message()
5092        );
5093    }
5094
5095    #[test]
5096    fn array_literal_rejects_a_mismatched_element_naming_its_index() {
5097        let err = array_parse_error("[0i32, 1.0f64]");
5098        assert!(
5099            err.message().contains("array element 1"),
5100            "got: {}",
5101            err.message()
5102        );
5103    }
5104
5105    #[test]
5106    fn array_literal_accepts_a_tuple_element() {
5107        use cel_runtime::{ArrayOf, Cons, Leaf, Nil};
5108        let body = CELParser::new(OpLookup::new())
5109            .parse_str("[(0i32, 1i32)]")
5110            .unwrap();
5111        assert!(
5112            body.prepare::<Nil, ArrayOf<Cons<Leaf<i32>, Cons<Leaf<i32>, Nil>>>>()
5113                .is_ok()
5114        );
5115    }
5116
5117    #[test]
5118    fn nested_array_literal_evaluates_to_an_array_of_arrays() -> anyhow::Result<()> {
5119        let mut parser = CELParser::new(OpLookup::new());
5120        let mut segment = parser
5121            .parse_str("[[0i32], [1i32]]")
5122            .map_err(|e| anyhow::anyhow!("{}", e))?;
5123        let array = segment
5124            .call0::<cel_runtime::OwnedValue>()?
5125            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>>(
5126            )?;
5127        let rows: Vec<_> = array
5128            .into_vec()
5129            .into_iter()
5130            .map(|row| row.into_vec())
5131            .collect();
5132        assert_eq!(rows, vec![vec![0], vec![1]]);
5133        Ok(())
5134    }
5135
5136    #[test]
5137    fn nested_array_literal_rejects_a_recursive_element_mismatch() {
5138        let err = array_parse_error("[[0i32], [1.0f64]]");
5139        assert!(
5140            err.message().contains("array element 1"),
5141            "got: {}",
5142            err.message()
5143        );
5144    }
5145
5146    #[test]
5147    fn nested_array_literal_rejects_a_depth_mismatch() {
5148        let err = array_parse_error("[[0i32], [[1i32]]]");
5149        assert!(
5150            err.message().contains("array element 1"),
5151            "got: {}",
5152            err.message()
5153        );
5154    }
5155
5156    #[test]
5157    fn typed_array_annotation_rejects_an_exact_element_type_mismatch() {
5158        let err = array_parse_error("[0, 1]: [f64]");
5159        assert!(
5160            err.message().contains("expected f64"),
5161            "got: {}",
5162            err.message()
5163        );
5164        assert!(err.message().contains("type i32"), "got: {}", err.message());
5165    }
5166
5167    #[test]
5168    fn typed_array_annotation_rejects_a_recursive_element_type_mismatch() {
5169        // The annotation's mismatch is one level below the outer array: the values are nested
5170        // `i32` arrays, the annotation names nested `f64` arrays.
5171        let err = array_parse_error("[[0, 1]]: [[f64]]");
5172        assert!(
5173            err.message().contains("expected [f64]"),
5174            "got: {}",
5175            err.message()
5176        );
5177        assert!(
5178            err.message().contains("type [i32]"),
5179            "got: {}",
5180            err.message()
5181        );
5182    }
5183
5184    #[test]
5185    fn typed_array_annotation_mismatch_names_the_registered_type_not_its_rust_path() {
5186        let resolver = [(
5187            "Celsius",
5188            ResolvedLeafType::new("Celsius", cel_runtime::ValueType::leaf::<Celsius>()),
5189        )];
5190        let mut parser = CELParser::with_type_resolver(OpLookup::new(), resolver);
5191        let err = match parser.parse_str("[0]: [Celsius]") {
5192            Err(e) => e,
5193            Ok(_) => panic!("expected `[0]: [Celsius]` to reject its `i32` element"),
5194        };
5195        assert!(
5196            err.message().contains("expected Celsius"),
5197            "the registered annotation name must survive into the diagnostic, got: {}",
5198            err.message()
5199        );
5200        assert!(
5201            !err.message().contains("::"),
5202            "no Rust type path may leak into the diagnostic, got: {}",
5203            err.message()
5204        );
5205    }
5206
5207    /// The runtime rejects a nested literal whose own annotation names a different custom element
5208    /// type — the mismatch `ty::check_expr` must also report statically.
5209    #[test]
5210    fn typed_array_annotation_rejects_a_nested_custom_element_type_mismatch() {
5211        #[derive(Clone)]
5212        struct CustomB;
5213
5214        let resolver = [
5215            (
5216                "Celsius",
5217                ResolvedLeafType::new("Celsius", cel_runtime::ValueType::leaf::<Celsius>()),
5218            ),
5219            (
5220                "CustomB",
5221                ResolvedLeafType::new("CustomB", cel_runtime::ValueType::leaf::<CustomB>()),
5222            ),
5223        ];
5224        let mut parser = CELParser::with_type_resolver(OpLookup::new(), resolver);
5225        let err = match parser.parse_str("[[]: [Celsius]]: [[CustomB]]") {
5226            Err(e) => e,
5227            Ok(_) => panic!("expected the inner annotation to conflict with the outer one"),
5228        };
5229        assert!(
5230            err.message().contains("expected [CustomB]"),
5231            "got: {}",
5232            err.message()
5233        );
5234        assert!(
5235            err.message().contains("[Celsius]"),
5236            "got: {}",
5237            err.message()
5238        );
5239    }
5240
5241    #[test]
5242    fn typed_array_annotation_rejects_an_unknown_type_name() {
5243        let err = array_parse_error("[0]: [Nope]");
5244        assert!(
5245            err.message().contains("unknown type `Nope`"),
5246            "got: {}",
5247            err.message()
5248        );
5249    }
5250
5251    #[test]
5252    fn typed_array_annotation_requires_a_complete_array_type() {
5253        let err = array_parse_error("[0]: i32");
5254        assert!(
5255            err.message()
5256                .contains("array annotations must name a complete array type"),
5257            "got: {}",
5258            err.message()
5259        );
5260    }
5261
5262    #[test]
5263    fn typed_array_annotation_accepts_tuple_array_elements() {
5264        use cel_runtime::{ArrayOf, Cons, Leaf, Nil};
5265        let body = CELParser::new(OpLookup::new())
5266            .parse_str("[]: [(i32, f64)]")
5267            .unwrap();
5268        assert!(
5269            body.prepare::<Nil, ArrayOf<Cons<Leaf<i32>, Cons<Leaf<f64>, Nil>>>>()
5270                .is_ok()
5271        );
5272    }
5273
5274    #[test]
5275    fn array_literal_is_accepted_as_a_call_argument() -> anyhow::Result<()> {
5276        let mut lookup = OpLookup::new();
5277        lookup.push_scope(
5278            |name, segment, num_operands, _span| match (name, num_operands) {
5279                ("len", 0) => {
5280                    segment.op0(|| 0i32);
5281                    Ok(true)
5282                }
5283                ("()", 2) => {
5284                    segment.op2_repr::<cel_runtime::Leaf<i32>, cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>, cel_runtime::Leaf<i32>, _>(
5285                        |_callee, arg| arg.len() as i32)?;
5286                    Ok(true)
5287                }
5288                _ => Ok(false),
5289            },
5290        );
5291        let mut parser = CELParser::new(lookup);
5292        let mut segment = parser
5293            .parse_str("len([1i32, 2i32, 3i32])")
5294            .map_err(|e| anyhow::anyhow!("{}", e))?;
5295        assert_eq!(segment.call0::<i32>()?, 3);
5296        Ok(())
5297    }
5298
5299    #[test]
5300    fn array_literal_is_accepted_as_a_tuple_element() -> anyhow::Result<()> {
5301        let mut parser = CELParser::new(OpLookup::new());
5302        let mut segment = parser
5303            .parse_str("([1i32, 2i32], 3i32).0")
5304            .map_err(|e| anyhow::anyhow!("{}", e))?;
5305        let array = segment
5306            .call0::<cel_runtime::OwnedValue>()?
5307            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
5308        assert_eq!(array.into_vec(), vec![1, 2]);
5309        Ok(())
5310    }
5311
5312    #[test]
5313    fn array_literal_is_accepted_inside_an_if_branch() -> anyhow::Result<()> {
5314        let mut parser = CELParser::new(OpLookup::new());
5315        let mut segment = parser
5316            .parse_str("if true { [1i32, 2i32] } else { [3i32, 4i32] }")
5317            .map_err(|e| anyhow::anyhow!("{}", e))?;
5318        let array = segment
5319            .call0::<cel_runtime::OwnedValue>()?
5320            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
5321        assert_eq!(array.into_vec(), vec![1, 2]);
5322        Ok(())
5323    }
5324
5325    #[test]
5326    fn array_literal_is_accepted_as_a_closure_body() -> anyhow::Result<()> {
5327        let mut parser = CELParser::new(OpLookup::new());
5328        let mut segment = parser
5329            .parse_str("|x: i32| [x, x]")
5330            .map_err(|e| anyhow::anyhow!("{}", e))?;
5331        let closure: cel_runtime::DynClosure = segment.call0()?;
5332        let x = 5i32;
5333        let array = closure
5334            .call::<cel_runtime::OwnedValue>(&[&x])?
5335            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
5336        assert_eq!(array.into_vec(), vec![5, 5]);
5337        Ok(())
5338    }
5339
5340    #[test]
5341    fn array_ambient_start_is_correct_after_a_sibling_expression() -> anyhow::Result<()> {
5342        // Regression guard mirroring `tuple_ambient_start_correct_after_sibling_expression`: the
5343        // array literal is deliberately *not* the first sub-expression, and its sibling has a
5344        // different alignment than its element type. The `u8` sum is pushed first (offset 0,
5345        // align 1), so the `i32` elements start at a nonzero offset that is only correct if the
5346        // ambient start is both threaded through from the sibling and padded up to `i32`'s
5347        // alignment.
5348        let mut parser = CELParser::new(OpLookup::new());
5349        let mut segment = parser
5350            .parse_str("(1u8 + 2u8, [3i32, 4i32]).1")
5351            .map_err(|e| anyhow::anyhow!("{}", e))?;
5352        let array = segment
5353            .call0::<cel_runtime::OwnedValue>()?
5354            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()?;
5355        assert_eq!(array.into_vec(), vec![3, 4]);
5356        Ok(())
5357    }
5358
5359    /// A custom element type implementing no trait beyond `'static` — not `Copy`, `Clone`,
5360    /// `Debug`, or `PartialEq` — so an array of it exercises the minimum element bound.
5361    struct Celsius(i32);
5362
5363    /// A second custom element type, distinct from [`Celsius`], so one call in an otherwise
5364    /// homogeneous literal can return a different type.
5365    struct Fahrenheit(i32);
5366
5367    /// The unapplied nullary function `f`.
5368    struct FName;
5369
5370    /// The unapplied nullary function `g`.
5371    struct GName;
5372
5373    /// The unapplied nullary function `h`.
5374    struct HName;
5375
5376    /// Returns an [`OpLookup`] resolving the nullary calls `f()`, `g()`, and `h()`, where `f`
5377    /// and `g` return [`Celsius`] values and `h` returns a [`Celsius`] when `homogeneous` and a
5378    /// [`Fahrenheit`] otherwise.
5379    fn temperature_lookup(homogeneous: bool) -> OpLookup {
5380        let mut lookup = OpLookup::new();
5381        lookup.push_scope(
5382            move |name, segment, num_operands, _span| match (name, num_operands) {
5383                ("f", 0) => {
5384                    segment.op0(|| FName);
5385                    Ok(true)
5386                }
5387                ("g", 0) => {
5388                    segment.op0(|| GName);
5389                    Ok(true)
5390                }
5391                ("h", 0) => {
5392                    segment.op0(|| HName);
5393                    Ok(true)
5394                }
5395                ("()", 1) => {
5396                    let Some(callee) = segment
5397                        .peek_stack_infos(1)
5398                        .first()
5399                        .map(|i| i.value_type.type_id())
5400                    else {
5401                        return Ok(false);
5402                    };
5403                    if callee == TypeId::of::<FName>() {
5404                        segment.op1(|_: FName| Celsius(0))?;
5405                    } else if callee == TypeId::of::<GName>() {
5406                        segment.op1(|_: GName| Celsius(1))?;
5407                    } else if callee == TypeId::of::<HName>() {
5408                        if homogeneous {
5409                            segment.op1(|_: HName| Celsius(2))?;
5410                        } else {
5411                            segment.op1(|_: HName| Fahrenheit(2))?;
5412                        }
5413                    } else {
5414                        return Ok(false);
5415                    }
5416                    Ok(true)
5417                }
5418                _ => Ok(false),
5419            },
5420        );
5421        lookup
5422    }
5423
5424    #[test]
5425    fn array_literal_of_calls_returning_a_custom_type_converts_to_its_vector() -> anyhow::Result<()>
5426    {
5427        let mut parser = CELParser::new(temperature_lookup(true));
5428        let mut segment = parser
5429            .parse_str("[f(), g(), h()]")
5430            .map_err(|e| anyhow::anyhow!("{}", e))?;
5431        let array = segment
5432            .call0::<cel_runtime::OwnedValue>()?
5433            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<Celsius>>>()?;
5434        let degrees: Vec<i32> = array.into_vec().into_iter().map(|c| c.0).collect();
5435        assert_eq!(degrees, vec![0, 1, 2]);
5436        Ok(())
5437    }
5438
5439    #[test]
5440    fn array_literal_of_one_custom_typed_call_evaluates_to_that_type() -> anyhow::Result<()> {
5441        // The same registration the mismatch test below uses: `h` alone is a perfectly good
5442        // array element, so that test's failure is about element homogeneity, not about `h`.
5443        let mut parser = CELParser::new(temperature_lookup(false));
5444        let mut segment = parser
5445            .parse_str("[h()]")
5446            .map_err(|e| anyhow::anyhow!("{}", e))?;
5447        let array = segment
5448            .call0::<cel_runtime::OwnedValue>()?
5449            .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<Fahrenheit>>>()?;
5450        let degrees: Vec<i32> = array.into_vec().into_iter().map(|f| f.0).collect();
5451        assert_eq!(degrees, vec![2]);
5452        Ok(())
5453    }
5454
5455    #[test]
5456    fn array_literal_of_calls_rejects_a_mismatched_return_type_before_execution() {
5457        // `parse_str` compiles the literal, so a mismatch is reported here — the segment is
5458        // never built and therefore never executed.
5459        let mut parser = CELParser::new(temperature_lookup(false));
5460        let err = match parser.parse_str("[f(), g(), h()]") {
5461            Err(e) => e,
5462            Ok(_) => panic!("expected `[f(), g(), h()]` with a mismatched `h` to fail"),
5463        };
5464        let message = err.message();
5465        assert!(message.contains("array element 2"), "got: {message}");
5466        assert!(message.contains("Fahrenheit"), "got: {message}");
5467        assert!(message.contains("Celsius"), "got: {message}");
5468    }
5469
5470    #[test]
5471    fn static_check_and_execution_agree_on_a_nested_custom_typed_array() -> anyhow::Result<()> {
5472        const SOURCE: &str = "[[f(), g()], [h()]]";
5473
5474        // The static checker sees only the AST, where `Celsius` — a host-registered type with no
5475        // `Ty` variant — infers as `Ty::Any`, so the literal infers as an array of arrays of it:
5476        // an under-approximation of the runtime type, reported without diagnostics.
5477        let mut ast_parser = Parser::<AstContext>::new(OpLookup::new());
5478        let expr = ast_parser
5479            .parse_str_ast(SOURCE)
5480            .map_err(|e| anyhow::anyhow!("{}", e))?;
5481        let (ty, diagnostics) = ty::check_expr(&expr, &|_name| Ty::Any);
5482        let messages: Vec<String> = diagnostics
5483            .iter()
5484            .map(|d| d.message().to_string())
5485            .collect();
5486        assert!(messages.is_empty(), "unexpected diagnostics: {messages:?}");
5487        assert_eq!(ty, Ty::Array(Box::new(Ty::Array(Box::new(Ty::Any)))));
5488
5489        // The same source, compiled and executed, produces the value the checker accepted.
5490        let mut parser = CELParser::new(temperature_lookup(true));
5491        let mut segment = parser
5492            .parse_str(SOURCE)
5493            .map_err(|e| anyhow::anyhow!("{}", e))?;
5494        let array = segment.call0::<cel_runtime::OwnedValue>()?.try_into_typed::<cel_runtime::ArrayOf<cel_runtime::ArrayOf<cel_runtime::Leaf<Celsius>>>>()?;
5495        let mut rows: Vec<Vec<i32>> = Vec::new();
5496        for row in array.into_vec() {
5497            rows.push(row.into_vec().into_iter().map(|c| c.0).collect());
5498        }
5499        assert_eq!(rows, vec![vec![0, 1], vec![2]]);
5500        Ok(())
5501    }
5502}
5503
5504#[cfg(test)]
5505mod playground {
5506    use super::*;
5507    use annotate_snippets::Renderer;
5508
5509    #[test]
5510    fn custom_scope_identifier() -> Result<()> {
5511        let mut lookup = OpLookup::new();
5512        lookup.push_scope(|name, segment, _num_operands, _span| {
5513            if name == "constant" {
5514                segment.just(42i64);
5515                return Ok(true);
5516            }
5517            Ok(false)
5518        });
5519        let mut parser = CELParser::new(lookup);
5520        let mut segment = parser.parse_str("constant == 42i64 && 15i64 < constant")?;
5521        assert!(segment.call0::<bool>().unwrap());
5522        Ok(())
5523    }
5524    #[test]
5525    fn literal_types() {
5526        use CELParser;
5527        use op_table::OpLookup;
5528        let source = r#"
5529            b'a'
5530        "#;
5531        assert_eq!(
5532            CELParser::new(OpLookup::new())
5533                .parse_str(source)
5534                .unwrap()
5535                .call0::<u8>()
5536                .unwrap(),
5537            b'a'
5538        );
5539    }
5540
5541    #[test]
5542    fn expression_macro_error3() {
5543        use CELParser;
5544        use op_table::OpLookup;
5545
5546        let line = line!() + 1;
5547        let source = r#"
5548            "Hello" + "World" + 32.0
5549        "#;
5550        match CELParser::new(OpLookup::new()).parse_str(source) {
5551            Ok(_) => panic!("expected parse error"),
5552            Err(e) => println!(
5553                "{}",
5554                e.format_rustc_style(source, file!(), line, &Renderer::styled())
5555            ),
5556        }
5557    }
5558
5559    #[test]
5560    fn arithmetic_overflow_error() {
5561        use error::FormatRustcStyle;
5562
5563        let line = line!() + 1;
5564        let source = r#"
5565           1 + 1 +
5566                2147483646 + 1
5567        "#;
5568        let mut seg = CELParser::new(OpLookup::new())
5569            .parse_str(source)
5570            .expect("parses successfully");
5571        match seg.call0::<i32>() {
5572            Ok(v) => panic!("expected overflow, got {v}"),
5573            Err(e) => println!(
5574                "{}",
5575                e.format_rustc_style(source, file!(), line, &Renderer::styled())
5576            ),
5577        }
5578    }
5579}