Skip to main content

cel_parser/
ast.rs

1//! A span-carrying CEL expression AST, built by [`AstContext`] as an
2//! alternative to [`DynSegmentContext`](crate::parser_context::DynSegmentContext)'s direct
3//! execution. Consumed as-is by adam-lang (method bodies/initializers), the language server, the
4//! formatter, and the future macro-compilation backend. Carries no resolved types or operator
5//! overloads: resolution and type/range validation are deferred to a later, separate phase.
6//!
7//! Array nodes preserve optional recursive type ascriptions exactly as written — for example
8//! `[0, 1]: [i32]`, `[]: [[i32]]`, or `[]: [Custom]` — using unresolved [`TypeExpr`] leaves so a
9//! later checker can resolve names through built-in CEL types or a host registry. Recursive
10//! tuple, array, and callable types compose without per-shape host registrations.
11
12use std::any::Any;
13use std::ffi::CString;
14
15use proc_macro2::Span;
16
17use crate::op_table::OpLookup;
18use crate::parser_context::ParserContext;
19use crate::type_expr::TypeExpr;
20
21/// Source range of an AST node: start of its first token to end of its last.
22///
23/// Two `proc_macro2::Span`s (not a [`crate::SourceSpan`]) so the future macro-compilation backend
24/// can attach `compile_error!`/`quote_spanned!`, and so the (separate, deferred) comment/trivia
25/// pass can call `Span::source_text()`. `crate::SourceSpan` remains the `Send + Sync` wire format
26/// used only at the `CELError` diagnostic boundary; this AST is an internal parser artifact using
27/// the same span currency the parser itself already does.
28///
29/// `proc_macro2::Span` isn't `PartialEq`, so neither is this type — shape tests should match
30/// structurally and ignore spans rather than assert exact span equality.
31///
32/// # Examples
33/// See [`Self::for_text`].
34#[derive(Clone, Copy, Debug)]
35pub struct ExprSpan {
36    /// Start of the first token of the node.
37    pub start: Span,
38    /// End of the last token of the node.
39    pub end: Span,
40}
41
42impl ExprSpan {
43    /// A single-token range where start and end coincide.
44    fn point(span: Span) -> Self {
45        ExprSpan {
46            start: span,
47            end: span,
48        }
49    }
50
51    /// Creates a span whose `source_text()` returns exactly `text`, by
52    /// tokenizing it and taking the resulting token's span. For hand-built
53    /// AST nodes (not produced by parsing real source), this gives leaves
54    /// like a type name or literal a span the formatter can read back
55    /// text from, the same way `cel-rs-macros` already does internally.
56    ///
57    /// - Precondition: `text` tokenizes to exactly one token tree.
58    ///
59    /// - Complexity: O(n) in `text.len()` (it lexes `text`).
60    ///
61    /// # Examples
62    ///
63    /// ```
64    /// use cel_parser::ExprSpan;
65    ///
66    /// let span = ExprSpan::for_text("i64");
67    /// assert_eq!(span.start.source_text().as_deref(), Some("i64"));
68    /// ```
69    #[must_use]
70    pub fn for_text(text: &str) -> Self {
71        let tokens: proc_macro2::TokenStream = text
72            .parse()
73            .expect("ExprSpan::for_text: text must be valid tokens");
74        let mut iter = tokens.into_iter();
75        let first = iter
76            .next()
77            .expect("ExprSpan::for_text: text must be non-empty");
78        debug_assert!(
79            iter.next().is_none(),
80            "ExprSpan::for_text: text must tokenize to exactly one token"
81        );
82        let span = first.span();
83        ExprSpan {
84            start: span,
85            end: span,
86        }
87    }
88}
89
90/// A CEL literal, one variant per concrete Rust type [`crate::ParserContext::push_literal`] can
91/// receive from `push_literal_token` in `lib.rs`.
92///
93/// `Byte` literals (`b'A'`) and `u8`-suffixed integer literals (`65u8`) both arrive as `u8` and
94/// are indistinguishable here — both become `Literal::U8`; a formatter that must reproduce exact
95/// original syntax should re-slice the node's original source text from its span instead of
96/// relying on this enum to recover lexical form.
97///
98/// # Examples
99/// See [`crate::Parser::parse_tokens_ast`] for retained literal values.
100#[derive(Clone, Debug, PartialEq)]
101pub enum Literal {
102    /// `i8` literal (e.g. `1i8`).
103    I8(i8),
104    /// `i16` literal (e.g. `1i16`).
105    I16(i16),
106    /// `i32` literal, the default integer suffix (e.g. `1` or `1i32`).
107    I32(i32),
108    /// `i64` literal (e.g. `1i64`).
109    I64(i64),
110    /// `i128` literal (e.g. `1i128`).
111    I128(i128),
112    /// `isize` literal (e.g. `1isize`).
113    Isize(isize),
114    /// `u8` literal or byte literal (e.g. `1u8` or `b'A'`).
115    U8(u8),
116    /// `u16` literal (e.g. `1u16`).
117    U16(u16),
118    /// `u32` literal (e.g. `1u32`).
119    U32(u32),
120    /// `u64` literal (e.g. `1u64`).
121    U64(u64),
122    /// `u128` literal (e.g. `1u128`).
123    U128(u128),
124    /// `usize` literal (e.g. `1usize`).
125    Usize(usize),
126    /// `f32` literal (e.g. `1.0f32`).
127    F32(f32),
128    /// `f64` literal, the default float suffix (e.g. `1.0` or `1.0f64`).
129    F64(f64),
130    /// Boolean literal (`true`/`false`).
131    Bool(bool),
132    /// Character literal (e.g. `'a'`).
133    Char(char),
134    /// String literal (e.g. `"x"`).
135    Str(String),
136    /// Byte-string literal (e.g. `b"x"`).
137    ByteStr(Vec<u8>),
138    /// C-string literal (e.g. `c"x"`).
139    CStr(CString),
140    /// Unit (`()`).
141    Unit,
142}
143
144/// The two short-circuiting logical operators.
145///
146/// # Examples
147/// See [`crate::ParserContext::apply_logical`] for lazy logical composition.
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub enum LogicalOp {
150    /// `&&`.
151    And,
152    /// `||`.
153    Or,
154}
155
156/// A parsed CEL expression with source spans on every node.
157///
158/// Built by [`AstContext`]; consumed as-is by adam-lang (method
159/// bodies/initializers), the language server (hover/goto), the formatter, and the future
160/// macro-compilation backend. Carries no resolved types or operator overloads — resolution is
161/// deferred to a later, separate type-checking phase.
162///
163/// `Logical` is kept distinct from `If` (rather than desugaring `a || b` to
164/// `if a { true } else { b }`, which is how [`DynSegmentContext`](crate::parser_context::DynSegmentContext)
165/// executes it) so a formatter can round-trip `a || b` as `a || b`.
166///
167/// # Examples
168/// See [`crate::Parser::parse_tokens_ast`] for building retained expressions.
169#[derive(Clone, Debug)]
170pub enum Expr {
171    /// A named record constructor, unresolved until semantic checking.
172    ///
173    /// # Examples
174    /// ```
175    /// use cel_parser::{AstContext, Expr, OpLookup, Parser};
176    /// let expr = Parser::<AstContext>::new(OpLookup::new())
177    ///     .parse_str_ast("Point { x: 1.0 }").unwrap();
178    /// assert!(matches!(expr, Expr::Struct { fields, .. } if fields.len() == 1));
179    /// ```
180    Struct {
181        /// The constructor's type name, not a value reference.
182        name: String,
183        /// The constructor name token's span.
184        name_span: ExprSpan,
185        /// Field labels and expressions in their written evaluation order.
186        fields: Vec<RecordInit>,
187        /// The whole constructor, including the closing brace.
188        span: ExprSpan,
189    },
190    /// A literal value (`10i32`, `"x"`, `true`, `()`, ...).
191    Literal {
192        /// The literal's value.
193        value: Literal,
194        /// The literal token's span.
195        span: ExprSpan,
196    },
197    /// A bare identifier reference or zero-arg builtin lookup (`x`, `pi`) — unresolved.
198    Ident {
199        /// The identifier's name.
200        name: String,
201        /// The identifier token's span.
202        span: ExprSpan,
203    },
204    /// A prefix (arity 1) or infix (arity 2) operator application (`-x`, `a + b`, `a == b`).
205    Op {
206        /// The operator's name (e.g. `"+"`, `"-"`, `"=="`).
207        name: String,
208        /// The operand sub-expressions, in source order.
209        operands: Vec<Expr>,
210        /// The span of the whole operator application.
211        span: ExprSpan,
212    },
213    /// A call: `callee(args...)` — the grammar's `"()"` operator.
214    Apply {
215        /// The expression being called.
216        callee: Box<Expr>,
217        /// The argument sub-expressions, in source order.
218        args: Vec<Expr>,
219        /// The span of the whole call, including its argument list.
220        span: ExprSpan,
221    },
222    /// A direct receiver operation (`receiver.name` or `receiver.name(args...)`).
223    ///
224    /// The label is not an identifier reference. Type and overload resolution are deferred.
225    ///
226    /// # Examples
227    /// ```
228    /// use cel_parser::{AstContext, Expr, OpLookup, Parser};
229    /// let expr = Parser::<AstContext>::new(OpLookup::new()).parse_str_ast("a.x()").unwrap();
230    /// assert!(matches!(expr, Expr::Member { args: Some(args), .. } if args.is_empty()));
231    /// ```
232    Member {
233        /// The receiver, evaluated before explicit arguments.
234        receiver: Box<Expr>,
235        /// The operation's name.
236        name: String,
237        /// The member name token's span.
238        name_span: ExprSpan,
239        /// Explicit arguments in source order; `None` preserves property spelling.
240        args: Option<Vec<Expr>>,
241        /// The span from the receiver through the name or closing parenthesis.
242        span: ExprSpan,
243    },
244    /// A tuple literal (`(a, b, ...)`; a 1-tuple is `(a,)`).
245    Tuple {
246        /// The element sub-expressions, in source order.
247        elements: Vec<Expr>,
248        /// The span of the whole tuple, including its parentheses.
249        span: ExprSpan,
250    },
251    /// An array literal (`[a, b, ...]`, `[a, b]: [T]`, or `[]: [T]`). An unannotated empty array
252    /// is still rejected by the grammar (see <https://github.com/stlab/cel-rs/issues/212>), but
253    /// a typed empty array is recorded here with `elements.is_empty()`. `type_annotation` stores
254    /// the complete recursive array type exactly as written, including nested arrays and custom
255    /// leaf names such as `Custom`. Whether the elements share one type, whether
256    /// `type_annotation` names a complete array type are deferred to the later type-checking phase (see the module doc
257    /// comment), same as `TupleIndex`'s deferred bounds check.
258    Array {
259        /// The element sub-expressions, in source order.
260        elements: Vec<Expr>,
261        /// The optional declared array type, as written after `:`.
262        type_annotation: Option<TypeExpr>,
263        /// The span from the `:` token through the end of the declared type, when present.
264        annotation_span: Option<ExprSpan>,
265        /// The span of the whole array literal, including its brackets and any annotation.
266        span: ExprSpan,
267    },
268    /// A tuple index (`base.N`). Whether `base` is actually a tuple and `N` is in range is
269    /// unchecked here — deferred to the type-checking phase (see the module doc comment).
270    TupleIndex {
271        /// The expression being indexed.
272        base: Box<Expr>,
273        /// The index.
274        index: usize,
275        /// The span from the start of `base` through the index token.
276        span: ExprSpan,
277    },
278    /// An `if cond { then } else { else_ }` expression.
279    If {
280        /// The condition.
281        cond: Box<Expr>,
282        /// The then-branch.
283        then_branch: Box<Expr>,
284        /// The else-branch, or `None` if no `else`/`else if` was written.
285        else_branch: Option<Box<Expr>>,
286        /// The span of the whole `if`/`else` construct.
287        span: ExprSpan,
288    },
289    /// A short-circuiting `&&`/`||`.
290    Logical {
291        /// Which logical operator.
292        op: LogicalOp,
293        /// The left-hand side.
294        lhs: Box<Expr>,
295        /// The right-hand side.
296        rhs: Box<Expr>,
297        /// The span of the whole logical expression.
298        span: ExprSpan,
299    },
300    /// A cast (`expr as Type`). Whether `type_name` is a recognized type and whether a
301    /// conversion from `expr`'s type exists is unchecked here — deferred to the type-checking
302    /// phase (see the module doc comment), same as `TupleIndex`'s deferred bounds check.
303    Cast {
304        /// The expression being converted.
305        expr: Box<Expr>,
306        /// The target type's name, as written (e.g. `"i32"`) - unresolved.
307        type_name: String,
308        /// The span of the whole `expr as Type` construct.
309        span: ExprSpan,
310    },
311    /// A closure literal (`|x: i32| x + 1`, or `|| 1i32` with no parameters).
312    Closure {
313        /// The closure's declared parameters, in source order.
314        params: Vec<ClosureParam>,
315        /// The closure's body expression.
316        body: Box<Expr>,
317        /// The span of the whole closure literal, from its opening `|`/`||` through `body`.
318        span: ExprSpan,
319    },
320}
321
322impl Expr {
323    /// Returns this node's source span.
324    ///
325    /// # Examples
326    /// ```
327    /// use cel_parser::{AstContext, OpLookup, Parser};
328    /// let expr = Parser::<AstContext>::new(OpLookup::new()).parse_str_ast("1 + 2").unwrap();
329    /// assert_eq!(expr.span().start.start().column, 0);
330    /// assert_eq!(expr.span().end.end().column, 5);
331    /// ```
332    pub fn span(&self) -> ExprSpan {
333        match self {
334            Expr::Literal { span, .. }
335            | Expr::Struct { span, .. }
336            | Expr::Ident { span, .. }
337            | Expr::Op { span, .. }
338            | Expr::Apply { span, .. }
339            | Expr::Member { span, .. }
340            | Expr::Tuple { span, .. }
341            | Expr::Array { span, .. }
342            | Expr::TupleIndex { span, .. }
343            | Expr::If { span, .. }
344            | Expr::Logical { span, .. }
345            | Expr::Cast { span, .. }
346            | Expr::Closure { span, .. } => *span,
347        }
348    }
349}
350
351/// One required record field initializer, retaining its written name, span, and value.
352///
353/// # Examples
354/// ```
355/// use cel_parser::{AstContext, Expr, OpLookup, Parser};
356/// let expr = Parser::<AstContext>::new(OpLookup::new())
357///     .parse_str_ast("Point { x: value }").unwrap();
358/// if let Expr::Struct { fields, .. } = expr {
359///     assert_eq!(fields[0].name, "x");
360/// }
361/// ```
362#[derive(Clone, Debug)]
363pub struct RecordInit {
364    /// The field label, not an identifier reference.
365    pub name: String,
366    /// The field label token's span.
367    pub name_span: ExprSpan,
368    /// The source-order value expression.
369    pub value: Expr,
370}
371
372/// One `closure_param = identifier ":" type_expression` — a closure literal's declared
373/// parameter.
374///
375/// # Examples
376/// ```
377/// use cel_parser::{AstContext, Expr, OpLookup, Parser};
378/// let expr = Parser::<AstContext>::new(OpLookup::new()).parse_str_ast("|x: i32| x").unwrap();
379/// let Expr::Closure { params, .. } = expr else { unreachable!() };
380/// assert_eq!(params[0].name, "x");
381/// ```
382#[derive(Clone, Debug)]
383pub struct ClosureParam {
384    /// The parameter's declared name.
385    pub name: String,
386    /// The name token's span.
387    pub name_span: ExprSpan,
388    /// The parameter's declared, unresolved type.
389    pub type_expr: crate::TypeExpr,
390}
391
392/// Reports reserved or repeated parameter names without resolving their type annotations.
393///
394/// - Complexity: Expected O(n + b) time and O(n) space for n parameters and b name bytes.
395pub(crate) fn closure_parameter_diagnostics(params: &[ClosureParam]) -> Vec<crate::ParseError> {
396    let mut names = std::collections::HashSet::with_capacity(params.len());
397    params
398        .iter()
399        .filter_map(|param| {
400            let message = if matches!(param.name.as_str(), "if" | "else" | "as" | "true" | "false")
401            {
402                "reserved keyword is not a closure parameter name"
403            } else if !names.insert(param.name.as_str()) {
404                "duplicate closure parameter name"
405            } else {
406                return None;
407            };
408            Some(crate::ParseError::new_range(
409                message,
410                param.name_span.start,
411                param.name_span.end,
412            ))
413        })
414        .collect()
415}
416
417/// Converts a statically-known literal value into its [`Literal`] variant, transferring owned buffers.
418///
419/// - Precondition: `T` is one of the concrete types `push_literal_token` (`lib.rs`) pushes:
420///   the signed/unsigned integer widths, `f32`/`f64`, `bool`, `char`, `String`, `Vec<u8>`,
421///   `CString`, or `()`.
422fn to_literal<T: 'static>(value: T) -> Literal {
423    // Taking an Option transfers even CString without constructing a replacement buffer.
424    let mut value = Some(value);
425    let any = &mut value as &mut dyn Any;
426    macro_rules! map {
427        ($($t:ty => $variant:path),+ $(,)?) => {
428            $( if let Some(x) = any.downcast_mut::<Option<$t>>() {
429                return $variant(x.take().expect("literal is transferred once"));
430            } )+
431        };
432    }
433    map! {
434        i8 => Literal::I8, i16 => Literal::I16, i32 => Literal::I32, i64 => Literal::I64,
435        i128 => Literal::I128, isize => Literal::Isize,
436        u8 => Literal::U8, u16 => Literal::U16, u32 => Literal::U32, u64 => Literal::U64,
437        u128 => Literal::U128, usize => Literal::Usize,
438        f32 => Literal::F32, f64 => Literal::F64,
439        bool => Literal::Bool, char => Literal::Char, String => Literal::Str,
440        Vec<u8> => Literal::ByteStr, CString => Literal::CStr,
441    }
442    if any.is::<Option<()>>() {
443        return Literal::Unit;
444    }
445    unreachable!("push_literal called with an unsupported literal type")
446}
447
448/// [`ParserContext`] implementation that builds a span-carrying [`Expr`] tree instead of
449/// executing. Consults no [`OpLookup`], inspects no runtime types, and never fails on semantic
450/// grounds — resolution and type/range checking are deferred to a later, separate
451/// type-checking phase (see the module doc comment).
452///
453/// # Examples
454///
455/// ```rust
456/// use cel_parser::{AstContext, ParserContext};
457/// use proc_macro2::Span;
458///
459/// let mut ctx = AstContext::new_context();
460/// ctx.push_literal(10i32, Span::call_site());
461/// ```
462#[derive(Debug, Default)]
463pub struct AstContext {
464    /// Finished sub-trees; a completed parse leaves exactly one.
465    values: Vec<Expr>,
466}
467
468impl AstContext {
469    /// Removes and returns the top node.
470    ///
471    /// - Precondition: at least one node is present.
472    fn pop(&mut self) -> Expr {
473        self.values
474            .pop()
475            .expect("operand present on AST value stack")
476    }
477
478    /// Removes and returns the top `n` nodes, in source order.
479    ///
480    /// - Precondition: at least `n` nodes are present.
481    /// - Complexity: O(n) time and space for the returned nodes.
482    fn pop_n(&mut self, n: usize) -> Vec<Expr> {
483        let at = self.values.len() - n;
484        self.values.split_off(at)
485    }
486
487    /// Consumes the context, returning the single parsed expression.
488    ///
489    /// - Precondition: parsing completed successfully (exactly one node remains).
490    ///
491    /// # Examples
492    /// ```
493    /// use cel_parser::{AstContext, ParserContext, Expr, Literal};
494    /// let mut context = AstContext::new_context();
495    /// context.push_literal(7i32, proc_macro2::Span::call_site());
496    /// assert!(matches!(context.into_expr(), Expr::Literal { value: Literal::I32(7), .. }));
497    /// ```
498    pub fn into_expr(mut self) -> Expr {
499        debug_assert_eq!(
500            self.values.len(),
501            1,
502            "a successfully parsed expression leaves exactly one node"
503        );
504        self.pop()
505    }
506}
507
508impl ParserContext for AstContext {
509    /// Defers closure annotation resolution to semantic checking or compilation.
510    fn resolves_closure_types() -> bool {
511        false
512    }
513
514    /// Creates an empty syntax stack.
515    fn new_context() -> Self {
516        AstContext { values: Vec::new() }
517    }
518
519    /// Creates an independent empty syntax stack.
520    fn new_fragment(&self) -> Self {
521        AstContext { values: Vec::new() }
522    }
523
524    /// Transfers one supported literal into a leaf node without copying owned buffers.
525    fn push_literal<T: 'static + Clone>(&mut self, value: T, span: Span) {
526        self.values.push(Expr::Literal {
527            value: to_literal(value),
528            span: ExprSpan::point(span),
529        });
530    }
531
532    /// Records an unresolved identifier reference.
533    ///
534    /// - Complexity: O(n) time and space for n name bytes.
535    fn push_identifier(&mut self, _lookup: &OpLookup, name: &str, span: Span) -> crate::Result<()> {
536        self.values.push(Expr::Ident {
537            name: name.to_string(),
538            span: ExprSpan::point(span),
539        });
540        Ok(())
541    }
542
543    /// Records an ordinary call or operator with source-order operands.
544    ///
545    /// - Precondition: the stack contains `arity` operands, including a callee for `"()"`.
546    /// - Complexity: O(a + b) time and space for a operands and b name bytes.
547    fn apply_op(
548        &mut self,
549        _op_lookup: &OpLookup,
550        name: &str,
551        arity: usize,
552        start: Span,
553        end: Span,
554    ) -> crate::Result<()> {
555        let span = ExprSpan { start, end };
556        if name == "()" {
557            let mut operands = self.pop_n(arity); // [callee, arg1, ...]
558            let callee = operands.remove(0);
559            self.values.push(Expr::Apply {
560                callee: Box::new(callee),
561                args: operands,
562                span,
563            });
564        } else {
565            let operands = self.pop_n(arity); // arity 1 = prefix, 2 = infix
566            self.values.push(Expr::Op {
567                name: name.to_string(),
568                operands,
569                span,
570            });
571        }
572        Ok(())
573    }
574
575    /// Records member spelling and source-order operands without resolving their types.
576    ///
577    /// - Complexity: O(n) in the number of explicit arguments.
578    fn apply_member(
579        &mut self,
580        _lookup: &OpLookup,
581        name: &str,
582        name_span: ExprSpan,
583        explicit_args: Option<usize>,
584        start: Span,
585        end: Span,
586    ) -> crate::Result<()> {
587        debug_assert!(self.values.len() > explicit_args.unwrap_or(0));
588        let args = explicit_args.map(|count| self.pop_n(count));
589        let receiver = self.pop();
590        self.values.push(Expr::Member {
591            receiver: Box::new(receiver),
592            name: name.to_string(),
593            name_span,
594            args,
595            span: ExprSpan { start, end },
596        });
597        Ok(())
598    }
599
600    /// Records source-order field names and values without resolving a constructor.
601    ///
602    /// - Complexity: O(f) in the number of fields.
603    fn make_record(
604        &mut self,
605        _lookup: &OpLookup,
606        name: &str,
607        name_span: ExprSpan,
608        fields: Vec<(String, ExprSpan)>,
609        _ambient_start: usize,
610        start: Span,
611        end: Span,
612    ) -> crate::Result<()> {
613        let values = self.pop_n(fields.len());
614        let fields = fields
615            .into_iter()
616            .zip(values)
617            .map(|((name, name_span), value)| RecordInit {
618                name,
619                name_span,
620                value,
621            })
622            .collect();
623        self.values.push(Expr::Struct {
624            name: name.to_string(),
625            name_span,
626            fields,
627            span: ExprSpan { start, end },
628        });
629        Ok(())
630    }
631
632    /// Records a lazy logical operation without replacing it with conditional syntax.
633    ///
634    /// - Precondition: `name` is `"&&"` or `"||"`; each side contains one expression.
635    fn apply_logical(
636        &mut self,
637        name: &str,
638        mut rhs: Self,
639        start: Span,
640        end: Span,
641    ) -> crate::Result<()> {
642        let op = match name {
643            "||" => LogicalOp::Or,
644            "&&" => LogicalOp::And,
645            other => unreachable!("apply_logical called with unsupported operator `{other}`"),
646        };
647        let lhs = self.pop();
648        debug_assert_eq!(
649            rhs.values.len(),
650            1,
651            "rhs fragment produces exactly one value"
652        );
653        let rhs_expr = rhs.pop();
654        self.values.push(Expr::Logical {
655            op,
656            lhs: Box::new(lhs),
657            rhs: Box::new(rhs_expr),
658            span: ExprSpan { start, end },
659        });
660        Ok(())
661    }
662
663    /// Records one conditional, preserving an absent `else` rather than synthesizing syntax.
664    ///
665    /// - Precondition: the condition and each supplied branch contain one expression.
666    fn join2(
667        &mut self,
668        mut then_fragment: Self,
669        else_fragment: Option<Self>,
670        start: Span,
671        end: Span,
672    ) -> anyhow::Result<()> {
673        let cond = self.pop();
674        debug_assert_eq!(
675            then_fragment.values.len(),
676            1,
677            "then fragment produces exactly one value"
678        );
679        let then_branch = then_fragment.pop();
680        let else_branch = else_fragment.map(|mut fragment| {
681            debug_assert_eq!(
682                fragment.values.len(),
683                1,
684                "else fragment produces exactly one value"
685            );
686            Box::new(fragment.pop())
687        });
688        self.values.push(Expr::If {
689            cond: Box::new(cond),
690            then_branch: Box::new(then_branch),
691            else_branch,
692            span: ExprSpan { start, end },
693        });
694        Ok(())
695    }
696
697    /// Collects source-order elements into a tuple, representing the empty tuple as unit.
698    ///
699    /// - Precondition: exactly `n` nodes follow `ambient_start`.
700    /// - Complexity: O(n) time and space for n elements.
701    fn make_tuple(
702        &mut self,
703        n: usize,
704        ambient_start: usize,
705        start: Span,
706        end: Span,
707    ) -> crate::Result<()> {
708        if n == 0 {
709            self.values.push(Expr::Literal {
710                value: Literal::Unit,
711                span: ExprSpan { start, end },
712            });
713            return Ok(());
714        }
715        let elements = self.values.split_off(ambient_start);
716        debug_assert_eq!(
717            elements.len(),
718            n,
719            "make_tuple splits off exactly n elements"
720        );
721        self.values.push(Expr::Tuple {
722            elements,
723            span: ExprSpan { start, end },
724        });
725        Ok(())
726    }
727
728    /// Collects source-order elements into an unannotated array node.
729    ///
730    /// - Precondition: exactly `n` nodes follow `ambient_start`.
731    /// - Complexity: O(n) time and space for n elements.
732    fn make_array(
733        &mut self,
734        n: usize,
735        ambient_start: usize,
736        start: Span,
737        end: Span,
738    ) -> crate::Result<()> {
739        let elements = self.values.split_off(ambient_start);
740        debug_assert_eq!(
741            elements.len(),
742            n,
743            "make_array splits off exactly n elements"
744        );
745        self.values.push(Expr::Array {
746            elements,
747            type_annotation: None,
748            annotation_span: None,
749            span: ExprSpan { start, end },
750        });
751        Ok(())
752    }
753
754    /// Collects elements and retains unresolved annotation syntax and its source boundary.
755    ///
756    /// - Precondition: exactly `n` nodes follow `ambient_start`.
757    /// - Complexity: O(n) time and space for n elements.
758    fn make_annotated_array(
759        &mut self,
760        n: usize,
761        ambient_start: usize,
762        annotation: crate::parser_context::AnnotatedArray<'_>,
763        start: Span,
764        end: Span,
765    ) -> crate::Result<()> {
766        let elements = self.values.split_off(ambient_start);
767        debug_assert_eq!(
768            elements.len(),
769            n,
770            "make_annotated_array splits off exactly n elements"
771        );
772        let (type_annotation, annotation_span) = annotation.into_parts();
773        self.values.push(Expr::Array {
774            elements,
775            type_annotation,
776            annotation_span,
777            span: ExprSpan { start, end },
778        });
779        Ok(())
780    }
781
782    /// Reports no semantic tuple arity during syntax-only parsing.
783    fn peek_tuple_arity(&self) -> Option<usize> {
784        None
785    }
786
787    /// Records every representable tuple index without prematurely checking its base type.
788    ///
789    /// - Precondition: one base expression is present.
790    fn tuple_index(&mut self, index: usize, start: Span, end: Span) -> crate::Result<()> {
791        let base = self.pop();
792        self.values.push(Expr::TupleIndex {
793            base: Box::new(base),
794            index,
795            span: ExprSpan { start, end },
796        });
797        Ok(())
798    }
799
800    /// Returns the node offset used to delimit the current element list.
801    fn current_stack_offset(&self) -> usize {
802        self.values.len()
803    }
804
805    /// Records a cast without resolving its target type.
806    ///
807    /// - Precondition: one operand is present.
808    /// - Complexity: O(b) time and space for b type-name bytes.
809    fn apply_cast(
810        &mut self,
811        _op_lookup: &OpLookup,
812        type_name: &str,
813        start: Span,
814        end: Span,
815    ) -> crate::Result<()> {
816        let expr = self.pop();
817        self.values.push(Expr::Cast {
818            expr: Box::new(expr),
819            type_name: type_name.to_string(),
820            span: ExprSpan { start, end },
821        });
822        Ok(())
823    }
824
825    /// Transfers parameter syntax and its sole body expression into a closure node.
826    ///
827    /// - Precondition: `body` contains exactly one expression.
828    fn push_closure(
829        &mut self,
830        param_types: Vec<cel_runtime::ValueType>,
831        params: Vec<ClosureParam>,
832        body: Self,
833        span: Span,
834    ) -> crate::Result<()> {
835        let _ = param_types;
836        let body_expr = body.into_expr();
837        let end = body_expr.span().end;
838        self.values.push(Expr::Closure {
839            params,
840            body: Box::new(body_expr),
841            span: ExprSpan { start: span, end },
842        });
843        Ok(())
844    }
845}
846
847#[cfg(test)]
848mod tests {
849    use super::*;
850    use crate::Parser;
851
852    /// Name validation reports the duplicate or reserved formal at its own source location.
853    #[test]
854    fn parameter_diagnostics_use_the_offending_formals_span() {
855        let Expr::Closure { mut params, .. } = Parser::<AstContext>::new(OpLookup::new())
856            .parse_str_ast("|x: i32, y: bool| x")
857            .unwrap()
858        else {
859            panic!("closure")
860        };
861        assert!(closure_parameter_diagnostics(&params).is_empty());
862        params[1].name = "x".to_owned();
863        let errors = closure_parameter_diagnostics(&params);
864        assert_eq!(errors.len(), 1);
865        assert!(errors[0].message().contains("duplicate"));
866        assert_eq!(errors[0].span().start().column, 9);
867        params[1].name = "as".to_owned();
868        assert!(
869            closure_parameter_diagnostics(&params)[0]
870                .message()
871                .contains("reserved")
872        );
873    }
874
875    /// Converting owned literals retains their existing allocations and contents.
876    #[test]
877    fn owned_literal_buffers_transfer_without_copying() {
878        let text = String::from("owned");
879        let pointer = text.as_ptr();
880        let Literal::Str(text) = to_literal(text) else {
881            panic!("string literal")
882        };
883        assert_eq!(text, "owned");
884        assert_eq!(text.as_ptr(), pointer);
885        let bytes = vec![1u8, 2, 3];
886        let pointer = bytes.as_ptr();
887        let Literal::ByteStr(bytes) = to_literal(bytes) else {
888            panic!("byte string literal")
889        };
890        assert_eq!(bytes, [1, 2, 3]);
891        assert_eq!(bytes.as_ptr(), pointer);
892        let text = CString::new("owned").unwrap();
893        let pointer = text.as_ptr();
894        let Literal::CStr(text) = to_literal(text) else {
895            panic!("C string literal")
896        };
897        assert_eq!(text.to_bytes(), b"owned");
898        assert_eq!(text.as_ptr(), pointer);
899    }
900
901    /// Supplies a real range distinct from call-site and nested fixture spans.
902    fn distinct_span() -> ExprSpan {
903        let tokens: proc_macro2::TokenStream = "\n outer\n end".parse().unwrap();
904        let mut tokens = tokens.into_iter();
905        ExprSpan {
906            start: tokens.next().unwrap().span(),
907            end: tokens.next().unwrap().span(),
908        }
909    }
910    use proc_macro2::Span;
911
912    #[test]
913    fn span_returns_the_range_stored_on_a_leaf_variant() {
914        let target = distinct_span();
915        let expr = Expr::Ident {
916            name: "x".to_string(),
917            span: target,
918        };
919        assert_eq!(
920            crate::SourceSpan::from_proc_macro2_range(expr.span().start, expr.span().end),
921            crate::SourceSpan::new(2, 1, 3, 4)
922        );
923    }
924
925    #[test]
926    fn span_returns_the_range_stored_on_a_composite_variant() {
927        let target = distinct_span();
928        let expr = Expr::If {
929            cond: Box::new(Expr::Literal {
930                value: Literal::Bool(true),
931                span: ExprSpan::point(Span::call_site()),
932            }),
933            then_branch: Box::new(Expr::Literal {
934                value: Literal::I32(1),
935                span: ExprSpan::point(Span::call_site()),
936            }),
937            else_branch: Some(Box::new(Expr::Literal {
938                value: Literal::I32(2),
939                span: ExprSpan::point(Span::call_site()),
940            })),
941            span: target,
942        };
943        assert_eq!(
944            crate::SourceSpan::from_proc_macro2_range(expr.span().start, expr.span().end),
945            crate::SourceSpan::new(2, 1, 3, 4)
946        );
947    }
948
949    #[test]
950    fn closure_span_is_the_stored_span() {
951        let target = distinct_span();
952        let expr = Expr::Closure {
953            params: Vec::new(),
954            body: Box::new(Expr::Literal {
955                value: Literal::I32(1),
956                span: ExprSpan::point(Span::call_site()),
957            }),
958            span: target,
959        };
960        assert_eq!(
961            crate::SourceSpan::from_proc_macro2_range(expr.span().start, expr.span().end),
962            crate::SourceSpan::new(2, 1, 3, 4)
963        );
964    }
965
966    #[test]
967    fn literal_variants_are_distinguishable_and_comparable() {
968        assert_eq!(Literal::I32(1), Literal::I32(1));
969        assert_ne!(Literal::I32(1), Literal::I32(2));
970        assert_ne!(Literal::I32(1), Literal::U8(1));
971        assert_eq!(Literal::Unit, Literal::Unit);
972    }
973
974    #[test]
975    fn logical_op_equality() {
976        assert_eq!(LogicalOp::And, LogicalOp::And);
977        assert_ne!(LogicalOp::And, LogicalOp::Or);
978    }
979
980    #[test]
981    fn push_literal_dispatches_every_concrete_literal_type() {
982        fn literal_of<T: 'static + Clone>(value: T) -> Literal {
983            let mut ctx = AstContext::new_context();
984            ctx.push_literal(value, Span::call_site());
985            match ctx.into_expr() {
986                Expr::Literal { value, .. } => value,
987                other => panic!("expected Literal, got {other:?}"),
988            }
989        }
990        assert_eq!(literal_of(1i8), Literal::I8(1));
991        assert_eq!(literal_of(1i16), Literal::I16(1));
992        assert_eq!(literal_of(1i32), Literal::I32(1));
993        assert_eq!(literal_of(1i64), Literal::I64(1));
994        assert_eq!(literal_of(1i128), Literal::I128(1));
995        assert_eq!(literal_of(1isize), Literal::Isize(1));
996        assert_eq!(literal_of(1u8), Literal::U8(1));
997        assert_eq!(literal_of(1u16), Literal::U16(1));
998        assert_eq!(literal_of(1u32), Literal::U32(1));
999        assert_eq!(literal_of(1u64), Literal::U64(1));
1000        assert_eq!(literal_of(1u128), Literal::U128(1));
1001        assert_eq!(literal_of(1usize), Literal::Usize(1));
1002        assert_eq!(literal_of(1.0f32), Literal::F32(1.0));
1003        assert_eq!(literal_of(1.0f64), Literal::F64(1.0));
1004        assert_eq!(literal_of(true), Literal::Bool(true));
1005        assert_eq!(literal_of('a'), Literal::Char('a'));
1006        assert_eq!(literal_of("s".to_string()), Literal::Str("s".to_string()));
1007        assert_eq!(literal_of(vec![1u8, 2u8]), Literal::ByteStr(vec![1, 2]));
1008        assert_eq!(
1009            literal_of(CString::new("c").unwrap()),
1010            Literal::CStr(CString::new("c").unwrap())
1011        );
1012        assert_eq!(literal_of(()), Literal::Unit);
1013    }
1014
1015    #[test]
1016    fn push_identifier_records_an_ident_node() {
1017        let mut ctx = AstContext::new_context();
1018        let lookup = OpLookup::new();
1019        ctx.push_identifier(&lookup, "x", Span::call_site())
1020            .unwrap();
1021        assert!(matches!(ctx.into_expr(), Expr::Ident { name, .. } if name == "x"));
1022    }
1023
1024    #[test]
1025    fn apply_op_with_the_call_operator_records_an_apply_node() {
1026        let mut ctx = AstContext::new_context();
1027        let lookup = OpLookup::new();
1028        ctx.push_identifier(&lookup, "x", Span::call_site())
1029            .unwrap(); // callee
1030        ctx.push_literal(1i32, Span::call_site()); // arg
1031        ctx.apply_op(&lookup, "()", 2, Span::call_site(), Span::call_site())
1032            .unwrap();
1033        match ctx.into_expr() {
1034            Expr::Apply { callee, args, .. } => {
1035                assert!(matches!(*callee, Expr::Ident { ref name, .. } if name == "x"));
1036                assert_eq!(args.len(), 1);
1037            }
1038            other => panic!("expected Apply, got {other:?}"),
1039        }
1040    }
1041
1042    #[test]
1043    fn apply_op_with_arity_two_records_an_op_node() {
1044        let mut ctx = AstContext::new_context();
1045        let lookup = OpLookup::new();
1046        ctx.push_literal(1i32, Span::call_site());
1047        ctx.push_literal(2i32, Span::call_site());
1048        ctx.apply_op(&lookup, "+", 2, Span::call_site(), Span::call_site())
1049            .unwrap();
1050        match ctx.into_expr() {
1051            Expr::Op { name, operands, .. } => {
1052                assert_eq!(name, "+");
1053                assert_eq!(operands.len(), 2);
1054            }
1055            other => panic!("expected Op, got {other:?}"),
1056        }
1057    }
1058
1059    #[test]
1060    fn apply_logical_records_a_logical_node() {
1061        let mut ctx = AstContext::new_context();
1062        ctx.push_literal(true, Span::call_site());
1063        let mut rhs = ctx.new_fragment();
1064        rhs.push_literal(false, Span::call_site());
1065        ctx.apply_logical("||", rhs, Span::call_site(), Span::call_site())
1066            .unwrap();
1067        match ctx.into_expr() {
1068            Expr::Logical { op, lhs, rhs, .. } => {
1069                assert_eq!(op, LogicalOp::Or);
1070                assert!(matches!(
1071                    *lhs,
1072                    Expr::Literal {
1073                        value: Literal::Bool(true),
1074                        ..
1075                    }
1076                ));
1077                assert!(matches!(
1078                    *rhs,
1079                    Expr::Literal {
1080                        value: Literal::Bool(false),
1081                        ..
1082                    }
1083                ));
1084            }
1085            other => panic!("expected Logical, got {other:?}"),
1086        }
1087    }
1088
1089    #[test]
1090    fn join2_records_an_if_node() {
1091        let mut ctx = AstContext::new_context();
1092        ctx.push_literal(true, Span::call_site());
1093        let mut then_fragment = ctx.new_fragment();
1094        then_fragment.push_literal(1i32, Span::call_site());
1095        let mut else_fragment = ctx.new_fragment();
1096        else_fragment.push_literal(2i32, Span::call_site());
1097        ctx.join2(
1098            then_fragment,
1099            Some(else_fragment),
1100            Span::call_site(),
1101            Span::call_site(),
1102        )
1103        .unwrap();
1104        match ctx.into_expr() {
1105            Expr::If {
1106                cond,
1107                then_branch,
1108                else_branch,
1109                ..
1110            } => {
1111                assert!(matches!(
1112                    *cond,
1113                    Expr::Literal {
1114                        value: Literal::Bool(true),
1115                        ..
1116                    }
1117                ));
1118                assert!(matches!(
1119                    *then_branch,
1120                    Expr::Literal {
1121                        value: Literal::I32(1),
1122                        ..
1123                    }
1124                ));
1125                let else_branch = else_branch.expect("explicit else was given");
1126                assert!(matches!(
1127                    *else_branch,
1128                    Expr::Literal {
1129                        value: Literal::I32(2),
1130                        ..
1131                    }
1132                ));
1133            }
1134            other => panic!("expected If, got {other:?}"),
1135        }
1136    }
1137
1138    #[test]
1139    fn join2_with_none_records_no_else_branch() {
1140        let mut ctx = AstContext::new_context();
1141        ctx.push_literal(true, Span::call_site());
1142        let mut then_fragment = ctx.new_fragment();
1143        then_fragment.push_literal(1i32, Span::call_site());
1144        ctx.join2(then_fragment, None, Span::call_site(), Span::call_site())
1145            .unwrap();
1146        match ctx.into_expr() {
1147            Expr::If { else_branch, .. } => assert!(else_branch.is_none()),
1148            other => panic!("expected If, got {other:?}"),
1149        }
1150    }
1151
1152    #[test]
1153    fn make_tuple_and_tuple_index_roundtrip() {
1154        let mut ctx = AstContext::new_context();
1155        let ambient_start = ctx.current_stack_offset();
1156        ctx.push_literal(1i32, Span::call_site());
1157        ctx.push_literal(2i32, Span::call_site());
1158        ctx.make_tuple(2, ambient_start, Span::call_site(), Span::call_site())
1159            .unwrap();
1160        assert_eq!(ctx.peek_tuple_arity(), None);
1161        ctx.tuple_index(1, Span::call_site(), Span::call_site())
1162            .unwrap();
1163        match ctx.into_expr() {
1164            Expr::TupleIndex { base, index, .. } => {
1165                assert_eq!(index, 1);
1166                assert!(matches!(*base, Expr::Tuple { ref elements, .. } if elements.len() == 2));
1167            }
1168            other => panic!("expected TupleIndex, got {other:?}"),
1169        }
1170    }
1171
1172    #[test]
1173    fn tuple_arity_is_unknown_during_syntax_only_parsing() {
1174        let mut ctx = AstContext::new_context();
1175        ctx.push_literal(5i32, Span::call_site());
1176        assert_eq!(ctx.peek_tuple_arity(), None);
1177    }
1178
1179    #[test]
1180    fn additive_binds_looser_than_multiplicative() {
1181        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1182        let expr = parser.parse_str_ast("1 + 2 * 3").unwrap();
1183        let Expr::Op { name, operands, .. } = expr else {
1184            panic!("expected Op");
1185        };
1186        assert_eq!(name, "+");
1187        assert!(matches!(
1188            operands[0],
1189            Expr::Literal {
1190                value: Literal::I32(1),
1191                ..
1192            }
1193        ));
1194        let Expr::Op {
1195            name: inner_name,
1196            operands: mul_operands,
1197            ..
1198        } = &operands[1]
1199        else {
1200            panic!("expected nested Op");
1201        };
1202        assert_eq!(inner_name, "*");
1203        assert!(matches!(
1204            mul_operands[0],
1205            Expr::Literal {
1206                value: Literal::I32(2),
1207                ..
1208            }
1209        ));
1210        assert!(matches!(
1211            mul_operands[1],
1212            Expr::Literal {
1213                value: Literal::I32(3),
1214                ..
1215            }
1216        ));
1217    }
1218
1219    #[test]
1220    fn unary_minus_and_not_are_recorded_as_arity_one_op_nodes() {
1221        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1222        let expr = parser.parse_str_ast("-1i32").unwrap();
1223        let Expr::Op { name, operands, .. } = expr else {
1224            panic!("expected Op");
1225        };
1226        assert_eq!(name, "-");
1227        assert_eq!(operands.len(), 1);
1228
1229        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1230        let expr = parser.parse_str_ast("!true").unwrap();
1231        let Expr::Op { name, operands, .. } = expr else {
1232            panic!("expected Op");
1233        };
1234        assert_eq!(name, "!");
1235        assert_eq!(operands.len(), 1);
1236    }
1237
1238    #[test]
1239    fn bare_identifier_is_an_ident_node() {
1240        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1241        let expr = parser.parse_str_ast("x").unwrap();
1242        assert!(matches!(expr, Expr::Ident { name, .. } if name == "x"));
1243    }
1244
1245    #[test]
1246    fn call_with_no_args_and_with_args() {
1247        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1248        let expr = parser.parse_str_ast("f()").unwrap();
1249        let Expr::Apply { callee, args, .. } = expr else {
1250            panic!("expected Apply");
1251        };
1252        assert!(matches!(*callee, Expr::Ident { ref name, .. } if name == "f"));
1253        assert_eq!(args.len(), 0);
1254
1255        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1256        let expr = parser.parse_str_ast("f(1i32, 2i32)").unwrap();
1257        let Expr::Apply { args, .. } = expr else {
1258            panic!("expected Apply");
1259        };
1260        assert_eq!(args.len(), 2);
1261    }
1262
1263    #[test]
1264    fn chained_calls_nest_apply_nodes() {
1265        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1266        let expr = parser.parse_str_ast("f()()").unwrap();
1267        let Expr::Apply { callee, args, .. } = expr else {
1268            panic!("expected outer Apply");
1269        };
1270        assert_eq!(args.len(), 0);
1271        assert!(matches!(*callee, Expr::Apply { .. }));
1272    }
1273
1274    #[test]
1275    fn unit_grouping_and_tuples() {
1276        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1277        assert!(matches!(
1278            parser.parse_str_ast("()").unwrap(),
1279            Expr::Literal {
1280                value: Literal::Unit,
1281                ..
1282            }
1283        ));
1284
1285        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1286        // Grouping: (1i32 + 2i32) has no Tuple wrapper, just the inner Op.
1287        assert!(matches!(
1288            parser.parse_str_ast("(1i32 + 2i32)").unwrap(),
1289            Expr::Op { .. }
1290        ));
1291
1292        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1293        let expr = parser.parse_str_ast("(1i32,)").unwrap();
1294        assert!(matches!(expr, Expr::Tuple { ref elements, .. } if elements.len() == 1));
1295
1296        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1297        let expr = parser.parse_str_ast("(1i32, 2i32, 3i32)").unwrap();
1298        assert!(matches!(expr, Expr::Tuple { ref elements, .. } if elements.len() == 3));
1299    }
1300
1301    #[test]
1302    fn tuple_index_single_and_chained() {
1303        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1304        let expr = parser.parse_str_ast("(1i32, 2i32).1").unwrap();
1305        let Expr::TupleIndex { base, index, .. } = expr else {
1306            panic!("expected TupleIndex");
1307        };
1308        assert_eq!(index, 1);
1309        assert!(matches!(*base, Expr::Tuple { ref elements, .. } if elements.len() == 2));
1310
1311        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1312        // Chained `.0.1` tokenizes as one float literal `0.1` split back into two indices.
1313        let expr = parser.parse_str_ast("((1i32, 2i32), 3i32).0.1").unwrap();
1314        let Expr::TupleIndex { base, index, .. } = expr else {
1315            panic!("expected outer TupleIndex");
1316        };
1317        assert_eq!(index, 1);
1318        assert!(matches!(*base, Expr::TupleIndex { index: 0, .. }));
1319    }
1320
1321    #[test]
1322    fn tuple_index_on_a_call_result_still_builds_a_tree() {
1323        // Deferred validation: DynSegmentContext would reject an out-of-range index at parse
1324        // time, but AstContext can't know a call's return arity without type inference, so it
1325        // must still build a tree here rather than fail to parse.
1326        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1327        let expr = parser.parse_str_ast("f().5").unwrap();
1328        assert!(matches!(expr, Expr::TupleIndex { index: 5, .. }));
1329    }
1330
1331    #[test]
1332    fn if_without_else_has_no_else_branch() {
1333        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1334        let expr = parser.parse_str_ast("if true { 1i32 }").unwrap();
1335        let Expr::If {
1336            cond,
1337            then_branch,
1338            else_branch,
1339            ..
1340        } = expr
1341        else {
1342            panic!("expected If");
1343        };
1344        assert!(matches!(
1345            *cond,
1346            Expr::Literal {
1347                value: Literal::Bool(true),
1348                ..
1349            }
1350        ));
1351        assert!(matches!(
1352            *then_branch,
1353            Expr::Literal {
1354                value: Literal::I32(1),
1355                ..
1356            }
1357        ));
1358        assert!(else_branch.is_none());
1359    }
1360
1361    #[test]
1362    fn if_else_and_else_if_chain() {
1363        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1364        let expr = parser
1365            .parse_str_ast("if true { 1i32 } else { 2i32 }")
1366            .unwrap();
1367        let Expr::If { else_branch, .. } = expr else {
1368            panic!("expected If");
1369        };
1370        assert!(matches!(
1371            else_branch.as_deref(),
1372            Some(Expr::Literal {
1373                value: Literal::I32(2),
1374                ..
1375            })
1376        ));
1377
1378        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1379        let expr = parser
1380            .parse_str_ast("if true { 1i32 } else if false { 2i32 } else { 3i32 }")
1381            .unwrap();
1382        let Expr::If { else_branch, .. } = expr else {
1383            panic!("expected outer If");
1384        };
1385        assert!(matches!(else_branch.as_deref(), Some(Expr::If { .. })));
1386    }
1387
1388    #[test]
1389    fn logical_or_is_not_desugared_to_if() {
1390        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1391        let expr = parser.parse_str_ast("a || b").unwrap();
1392        let Expr::Logical { op, lhs, rhs, .. } = expr else {
1393            panic!("expected Logical");
1394        };
1395        assert_eq!(op, LogicalOp::Or);
1396        assert!(matches!(*lhs, Expr::Ident { ref name, .. } if name == "a"));
1397        assert!(matches!(*rhs, Expr::Ident { ref name, .. } if name == "b"));
1398    }
1399
1400    #[test]
1401    fn logical_and_is_not_desugared_to_if() {
1402        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1403        let expr = parser.parse_str_ast("a && b").unwrap();
1404        let Expr::Logical { op, .. } = expr else {
1405            panic!("expected Logical");
1406        };
1407        assert_eq!(op, LogicalOp::And);
1408    }
1409
1410    #[test]
1411    fn logical_mixes_with_comparison_at_the_right_precedence() {
1412        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1413        // `&&` binds looser than `==`, so this is `(a == 1i32) && (b == 2i32)`.
1414        let expr = parser.parse_str_ast("a == 1i32 && b == 2i32").unwrap();
1415        let Expr::Logical { op, lhs, rhs, .. } = expr else {
1416            panic!("expected Logical");
1417        };
1418        assert_eq!(op, LogicalOp::And);
1419        assert!(matches!(*lhs, Expr::Op { ref name, .. } if name == "=="));
1420        assert!(matches!(*rhs, Expr::Op { ref name, .. } if name == "=="));
1421    }
1422
1423    #[test]
1424    fn for_text_produces_a_span_whose_source_text_matches() {
1425        let span = ExprSpan::for_text("i64");
1426        assert_eq!(span.start.source_text().as_deref(), Some("i64"));
1427        assert_eq!(span.end.source_text().as_deref(), Some("i64"));
1428    }
1429
1430    #[test]
1431    fn for_text_works_for_a_string_literal() {
1432        let span = ExprSpan::for_text("\"hello\"");
1433        assert_eq!(span.start.source_text().as_deref(), Some("\"hello\""));
1434    }
1435
1436    #[test]
1437    fn make_array_pushes_one_array_node_holding_the_elements_in_source_order() {
1438        let mut ctx = AstContext::new_context();
1439        let ambient_start = ctx.current_stack_offset();
1440        ctx.push_literal(1i32, Span::call_site());
1441        ctx.push_literal(2i32, Span::call_site());
1442        ctx.make_array(2, ambient_start, Span::call_site(), Span::call_site())
1443            .unwrap();
1444        match ctx.into_expr() {
1445            Expr::Array { elements, .. } => {
1446                assert!(matches!(
1447                    elements[0],
1448                    Expr::Literal {
1449                        value: Literal::I32(1),
1450                        ..
1451                    }
1452                ));
1453                assert!(matches!(
1454                    elements[1],
1455                    Expr::Literal {
1456                        value: Literal::I32(2),
1457                        ..
1458                    }
1459                ));
1460            }
1461            other => panic!("expected Array, got {other:?}"),
1462        }
1463    }
1464
1465    #[test]
1466    fn array_literal_records_elements_in_source_order_with_an_enclosing_span() {
1467        let source = "[0i32, 1i32, 2i32]";
1468        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1469        let expr = parser.parse_str_ast(source).unwrap();
1470        let Expr::Array { elements, span, .. } = expr else {
1471            panic!("expected Array");
1472        };
1473        assert_eq!(elements.len(), 3);
1474        for (index, element) in elements.iter().enumerate() {
1475            let Expr::Literal { value, .. } = element else {
1476                panic!("expected a literal element");
1477            };
1478            assert_eq!(*value, Literal::I32(i32::try_from(index).unwrap()));
1479        }
1480        assert_eq!(span.start.source_text().as_deref(), Some(source));
1481        assert_eq!(span.end.source_text().as_deref(), Some(source));
1482    }
1483
1484    #[test]
1485    fn nested_array_literal_nests_array_nodes() {
1486        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1487        let expr = parser.parse_str_ast("[[0i32], [1i32]]").unwrap();
1488        let Expr::Array { elements, .. } = expr else {
1489            panic!("expected outer Array");
1490        };
1491        assert_eq!(elements.len(), 2);
1492        for element in &elements {
1493            assert!(matches!(element, Expr::Array { elements, .. } if elements.len() == 1));
1494        }
1495    }
1496
1497    #[test]
1498    fn typed_array_literal_still_builds_an_array_node() {
1499        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1500        let expr = parser.parse_str_ast("[0, 1]: [i32]").unwrap();
1501        let Expr::Array {
1502            elements,
1503            type_annotation,
1504            annotation_span,
1505            ..
1506        } = expr
1507        else {
1508            panic!("expected Array");
1509        };
1510        assert_eq!(elements.len(), 2);
1511        assert!(annotation_span.is_some());
1512        match type_annotation {
1513            Some(TypeExpr::Array { element, .. }) => {
1514                assert!(matches!(*element, TypeExpr::Named { ref name, .. } if name == "i32"));
1515            }
1516            other => panic!("expected an array type annotation, got {other:?}"),
1517        }
1518    }
1519
1520    #[test]
1521    fn typed_empty_array_literal_builds_an_empty_array_node() {
1522        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1523        let expr = parser.parse_str_ast("[]: [i32]").unwrap();
1524        assert!(matches!(
1525            expr,
1526            Expr::Array {
1527                ref elements,
1528                type_annotation: Some(_),
1529                annotation_span: Some(_),
1530                ..
1531            } if elements.is_empty()
1532        ));
1533    }
1534
1535    #[test]
1536    fn typed_array_literal_preserves_the_exact_annotation_span() {
1537        let source = "[1.0, 42.5]: [f64]";
1538        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1539        let expr = parser.parse_str_ast(source).unwrap();
1540        let Expr::Array {
1541            type_annotation: Some(_),
1542            annotation_span: Some(annotation_span),
1543            ..
1544        } = expr
1545        else {
1546            panic!("expected Array");
1547        };
1548        let start = annotation_span.start.start();
1549        let end = annotation_span.end.end();
1550        assert_eq!(&source[start.column..end.column], ": [f64]");
1551    }
1552
1553    #[test]
1554    fn array_literals_build_nodes_in_call_argument_and_tuple_positions() {
1555        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1556        let expr = parser.parse_str_ast("f([1i32], (2i32, [3i32]))").unwrap();
1557        let Expr::Apply { args, .. } = expr else {
1558            panic!("expected Apply");
1559        };
1560        assert!(matches!(args[0], Expr::Array { ref elements, .. } if elements.len() == 1));
1561        let Expr::Tuple { elements, .. } = &args[1] else {
1562            panic!("expected a tuple argument");
1563        };
1564        assert!(matches!(elements[1], Expr::Array { .. }));
1565    }
1566
1567    #[test]
1568    fn array_literals_build_nodes_in_if_branch_and_closure_body_positions() {
1569        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1570        let expr = parser
1571            .parse_str_ast("if true { [1i32] } else { [2i32] }")
1572            .unwrap();
1573        let Expr::If {
1574            then_branch,
1575            else_branch,
1576            ..
1577        } = expr
1578        else {
1579            panic!("expected If");
1580        };
1581        assert!(matches!(*then_branch, Expr::Array { .. }));
1582        assert!(matches!(else_branch.as_deref(), Some(Expr::Array { .. })));
1583
1584        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1585        let expr = parser.parse_str_ast("|x: i32| [x]").unwrap();
1586        let Expr::Closure { body, .. } = expr else {
1587            panic!("expected Closure");
1588        };
1589        assert!(matches!(*body, Expr::Array { .. }));
1590    }
1591
1592    #[test]
1593    fn array_literal_with_a_tuple_element_still_builds_a_tree() {
1594        // Syntax-only parsing records tuple elements without resolving their shapes.
1595        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1596        let expr = parser.parse_str_ast("[(1i32, 2i32)]").unwrap();
1597        assert!(matches!(expr, Expr::Array { ref elements, .. } if elements.len() == 1));
1598    }
1599
1600    #[test]
1601    fn ast_context_still_rejects_an_empty_array_literal() {
1602        // The empty-literal diagnostic is a grammar-level rejection (see #212), so it applies to
1603        // every `ParserContext`, not only the one that resolves runtime types.
1604        let mut parser = Parser::<AstContext>::new(OpLookup::new());
1605        let err = parser
1606            .parse_str_ast("[]")
1607            .expect_err("an empty array literal has no inferable element type");
1608        assert!(
1609            err.message().contains("empty array"),
1610            "got: {}",
1611            err.message()
1612        );
1613    }
1614}