cel_parser/parser_context.rs
1//! `ParserContext`: the pluggable target a CEL grammar production emits into.
2//!
3//! The recursive-descent grammar in `lib.rs` is generic over `C: ParserContext` so the same
4//! grammar can drive different backends without duplicating it. [`DynSegmentContext`] is the
5//! first implementation: it reproduces exactly what `CELParser` did before this trait existed,
6//! wrapping a [`DynSegment`] one-for-one. [`crate::AstContext`] retains syntax for the language
7//! server, formatter, and retained compiler.
8
9use cel_runtime::DynSegment;
10use proc_macro2::Span;
11
12use crate::ExprSpan;
13use crate::ast::ClosureParam;
14use crate::op_table::OpLookup;
15use crate::type_expr::TypeExpr;
16
17/// Bundles the optional type-ascription inputs for array construction.
18///
19/// A [`ParserContext`] implementation receives one of these in
20/// [`ParserContext::make_annotated_array`] and decides how to consume it: an implementation that
21/// needs runtime array metadata immediately resolves it with
22/// [`resolve_element_type`](Self::resolve_element_type); one that defers semantic checking keeps
23/// the syntax with [`into_parts`](Self::into_parts).
24///
25/// # Examples
26///
27/// ```rust
28/// use cel_parser::{ExprSpan, TypeExpr};
29/// use cel_parser::parser_context::AnnotatedArray;
30/// use proc_macro2::Span;
31///
32/// fn ignore(_: &TypeExpr) -> cel_parser::Result<cel_parser::ResolvedArrayType> {
33/// unreachable!("this example only inspects stored syntax")
34/// }
35///
36/// let span = ExprSpan {
37/// start: Span::call_site(),
38/// end: Span::call_site(),
39/// };
40/// let mut resolve = ignore;
41/// let annotation = AnnotatedArray::new(
42/// &mut resolve,
43/// Some(TypeExpr::Array {
44/// element: Box::new(TypeExpr::Named {
45/// name: "i32".to_string(),
46/// args: Vec::new(),
47/// span,
48/// }),
49/// span,
50/// }),
51/// Some(span),
52/// );
53///
54/// assert!(matches!(annotation.type_annotation(), Some(TypeExpr::Array { .. })));
55/// assert!(annotation.annotation_span().is_some());
56/// ```
57pub struct AnnotatedArray<'a> {
58 resolve_array_type: &'a mut dyn FnMut(&TypeExpr) -> crate::Result<crate::ResolvedArrayType>,
59 type_annotation: Option<TypeExpr>,
60 annotation_span: Option<ExprSpan>,
61}
62
63impl<'a> AnnotatedArray<'a> {
64 /// Creates a bundle from the parsed array annotation inputs.
65 ///
66 /// `type_annotation` is the syntax written after `:` (or `None` for an unannotated literal),
67 /// `annotation_span` covers `: type_expr`, and `resolve_array_type` resolves the annotation
68 /// against the parser's configured type resolver on demand.
69 ///
70 /// # Examples
71 ///
72 /// ```rust
73 /// use cel_parser::{ExprSpan, TypeExpr};
74 /// use cel_parser::parser_context::AnnotatedArray;
75 /// use proc_macro2::Span;
76 ///
77 /// fn ignore(_: &TypeExpr) -> cel_parser::Result<cel_parser::ResolvedArrayType> {
78 /// unreachable!("this example only bundles parsed inputs")
79 /// }
80 ///
81 /// let span = ExprSpan {
82 /// start: Span::call_site(),
83 /// end: Span::call_site(),
84 /// };
85 /// let mut resolve = ignore;
86 /// let annotation = AnnotatedArray::new(
87 /// &mut resolve,
88 /// Some(TypeExpr::Array {
89 /// element: Box::new(TypeExpr::Named {
90 /// name: "i32".to_string(),
91 /// args: Vec::new(),
92 /// span,
93 /// }),
94 /// span,
95 /// }),
96 /// Some(span),
97 /// );
98 ///
99 /// assert!(annotation.annotation_span().is_some());
100 /// ```
101 pub fn new(
102 resolve_array_type: &'a mut dyn FnMut(&TypeExpr) -> crate::Result<crate::ResolvedArrayType>,
103 type_annotation: Option<TypeExpr>,
104 annotation_span: Option<ExprSpan>,
105 ) -> Self {
106 Self {
107 resolve_array_type,
108 type_annotation,
109 annotation_span,
110 }
111 }
112
113 /// Returns the unresolved annotation syntax, or `None` for an unannotated array literal.
114 ///
115 /// # Examples
116 ///
117 /// ```rust
118 /// use cel_parser::{ExprSpan, TypeExpr};
119 /// use cel_parser::parser_context::AnnotatedArray;
120 /// use proc_macro2::Span;
121 ///
122 /// fn ignore(_: &TypeExpr) -> cel_parser::Result<cel_parser::ResolvedArrayType> {
123 /// unreachable!("this example only reads the stored annotation")
124 /// }
125 ///
126 /// let span = ExprSpan {
127 /// start: Span::call_site(),
128 /// end: Span::call_site(),
129 /// };
130 /// let mut resolve = ignore;
131 /// let annotation = AnnotatedArray::new(
132 /// &mut resolve,
133 /// Some(TypeExpr::Array {
134 /// element: Box::new(TypeExpr::Named {
135 /// name: "i32".to_string(),
136 /// args: Vec::new(),
137 /// span,
138 /// }),
139 /// span,
140 /// }),
141 /// Some(span),
142 /// );
143 ///
144 /// match annotation.type_annotation() {
145 /// Some(TypeExpr::Array { element, .. }) => assert!(matches!(
146 /// element.as_ref(),
147 /// TypeExpr::Named { name, .. } if name == "i32"
148 /// )),
149 /// other => panic!("expected [i32], got {other:?}"),
150 /// }
151 /// ```
152 #[must_use]
153 pub fn type_annotation(&self) -> Option<&TypeExpr> {
154 self.type_annotation.as_ref()
155 }
156
157 /// Returns the span covering `: type_expr`, or `None` for an unannotated array literal.
158 ///
159 /// # Examples
160 ///
161 /// ```rust
162 /// use cel_parser::ExprSpan;
163 /// use cel_parser::parser_context::AnnotatedArray;
164 /// use proc_macro2::Span;
165 ///
166 /// fn ignore(_: &cel_parser::TypeExpr) -> cel_parser::Result<cel_parser::ResolvedArrayType> {
167 /// unreachable!("this example only reads the stored span")
168 /// }
169 ///
170 /// fn ignore_none(
171 /// _: &cel_parser::TypeExpr,
172 /// ) -> cel_parser::Result<cel_parser::ResolvedArrayType> {
173 /// unreachable!("this example only checks the None case")
174 /// }
175 ///
176 /// let span = ExprSpan {
177 /// start: Span::call_site(),
178 /// end: Span::call_site(),
179 /// };
180 /// let mut resolve = ignore;
181 /// let annotation = AnnotatedArray::new(
182 /// &mut resolve,
183 /// None,
184 /// Some(span),
185 /// );
186 ///
187 /// assert!(annotation.annotation_span().is_some());
188 /// let mut without_span = ignore_none;
189 /// assert!(
190 /// AnnotatedArray::new(&mut without_span, None, None)
191 /// .annotation_span()
192 /// .is_none()
193 /// );
194 /// ```
195 #[must_use]
196 pub fn annotation_span(&self) -> Option<ExprSpan> {
197 self.annotation_span
198 }
199
200 /// Resolves the declared array element metadata when a type ascription is present.
201 ///
202 /// - Postcondition: returns `Ok(None)` exactly when
203 /// [`type_annotation`](Self::type_annotation) is `None`.
204 ///
205 /// # Errors
206 ///
207 /// Returns `Err` if the annotation names an unknown type, does not name a complete array
208 /// type, or has an unrepresentable canonical layout.
209 ///
210 /// - Complexity: O(1) bundling overhead plus the configured annotation resolver's cost.
211 ///
212 /// # Examples
213 ///
214 /// ```rust
215 /// use cel_parser::{ExprSpan, ResolvedArrayType, TypeExpr};
216 /// use cel_parser::parser_context::AnnotatedArray;
217 /// use cel_runtime::ValueType;
218 /// use proc_macro2::Span;
219 ///
220 /// fn resolve_i32(_: &TypeExpr) -> cel_parser::Result<ResolvedArrayType> {
221 /// Ok(ResolvedArrayType::from_element_type(
222 /// ValueType::leaf::<i32>(),
223 /// ))
224 /// }
225 ///
226 /// let span = ExprSpan {
227 /// start: Span::call_site(),
228 /// end: Span::call_site(),
229 /// };
230 /// let mut resolve = resolve_i32;
231 /// let mut annotation = AnnotatedArray::new(
232 /// &mut resolve,
233 /// Some(TypeExpr::Array {
234 /// element: Box::new(TypeExpr::Named {
235 /// name: "i32".to_string(),
236 /// args: Vec::new(),
237 /// span,
238 /// }),
239 /// span,
240 /// }),
241 /// Some(span),
242 /// );
243 ///
244 /// let element_type = annotation.resolve_element_type().unwrap().unwrap();
245 /// assert_eq!(element_type.type_name(), "i32");
246 /// ```
247 pub fn resolve_element_type(&mut self) -> crate::Result<Option<cel_runtime::ValueType>> {
248 self.type_annotation
249 .as_ref()
250 .map(|type_annotation| {
251 (self.resolve_array_type)(type_annotation)
252 .map(|resolved| resolved.into_element_type())
253 })
254 .transpose()
255 }
256
257 /// Returns the parsed syntax-level annotation inputs unchanged.
258 ///
259 /// # Examples
260 ///
261 /// ```rust
262 /// use cel_parser::{ExprSpan, TypeExpr};
263 /// use cel_parser::parser_context::AnnotatedArray;
264 /// use proc_macro2::Span;
265 ///
266 /// fn ignore(_: &TypeExpr) -> cel_parser::Result<cel_parser::ResolvedArrayType> {
267 /// unreachable!("this example only unpacks stored parts")
268 /// }
269 ///
270 /// let span = ExprSpan {
271 /// start: Span::call_site(),
272 /// end: Span::call_site(),
273 /// };
274 /// let mut resolve = ignore;
275 /// let annotation = AnnotatedArray::new(
276 /// &mut resolve,
277 /// Some(TypeExpr::Array {
278 /// element: Box::new(TypeExpr::Named {
279 /// name: "i32".to_string(),
280 /// args: Vec::new(),
281 /// span,
282 /// }),
283 /// span,
284 /// }),
285 /// Some(span),
286 /// );
287 ///
288 /// let (type_annotation, annotation_span) = annotation.into_parts();
289 /// assert!(annotation_span.is_some());
290 /// match type_annotation {
291 /// Some(TypeExpr::Array { element, .. }) => assert!(matches!(
292 /// element.as_ref(),
293 /// TypeExpr::Named { name, .. } if name == "i32"
294 /// )),
295 /// other => panic!("expected [i32], got {other:?}"),
296 /// }
297 /// ```
298 #[must_use]
299 pub fn into_parts(self) -> (Option<TypeExpr>, Option<ExprSpan>) {
300 (self.type_annotation, self.annotation_span)
301 }
302}
303
304/// The pluggable target a grammar production emits into.
305///
306/// Each method mirrors one operation the grammar in `lib.rs` needs. Implementations decide what
307/// "emitting" means: [`DynSegmentContext`] builds stack-machine operations;
308/// [`crate::AstContext`] records syntax without executing it.
309///
310/// Emission costs depend on the selected context, including its storage, descriptor traversal,
311/// literal cloning and host callbacks.
312///
313/// # Examples
314/// See [`Self::apply_op`] for runtime emission and [`Self::apply_member`] for syntax construction.
315pub trait ParserContext: Sized {
316 /// Returns whether closure annotations must resolve while parsing rather than remain syntax.
317 ///
318 /// # Examples
319 /// ```
320 /// use cel_parser::{AstContext, parser_context::ParserContext};
321 /// assert!(!AstContext::resolves_closure_types());
322 /// ```
323 fn resolves_closure_types() -> bool {
324 true
325 }
326
327 /// Creates a fresh, empty context with no operations recorded yet.
328 ///
329 /// # Examples
330 /// ```
331 /// use cel_parser::{DynSegmentContext, ParserContext};
332 /// assert_eq!(DynSegmentContext::new_context().current_stack_offset(), 0);
333 /// ```
334 fn new_context() -> Self;
335
336 /// Creates an empty fragment for building an alternate branch (one side of a
337 /// short-circuiting `||`/`&&`, or an `if`/`else` branch), independent of `self`.
338 ///
339 /// - Precondition: `self` matches whatever precondition the implementation's equivalent of
340 /// `DynSegment::new_fragment` requires (for `DynSegmentContext`, a condition value already
341 /// present).
342 ///
343 /// # Examples
344 /// See [`Self::apply_logical`] for an independent right-hand-side fragment.
345 fn new_fragment(&self) -> Self;
346
347 /// Pushes a literal value with the source span of the token it came from.
348 ///
349 /// - Precondition: the selected context supports `T` as a literal type.
350 ///
351 /// # Examples
352 /// See [`Self::apply_op`] for literal operands.
353 fn push_literal<T: 'static + Clone>(&mut self, value: T, span: Span);
354
355 /// Pushes an identifier reference, resolving it through `lookup` in runtime contexts.
356 ///
357 /// - Complexity: O(n) for n name bytes, plus runtime scope lookup.
358 ///
359 /// # Errors
360 /// Returns an error if a runtime context cannot resolve `name`.
361 ///
362 /// # Examples
363 /// ```
364 /// use cel_parser::{AstContext, Expr, OpLookup, ParserContext};
365 /// let mut context = AstContext::new_context();
366 /// context.push_identifier(&OpLookup::new(), "range_full",
367 /// proc_macro2::Span::call_site()).unwrap();
368 /// assert!(matches!(context.into_expr(), Expr::Ident { .. }));
369 /// ```
370 fn push_identifier(&mut self, lookup: &OpLookup, name: &str, span: Span) -> crate::Result<()>;
371
372 /// Applies a named operator, using `op_lookup` to resolve it
373 /// against whatever this context currently holds.
374 ///
375 /// # Errors
376 ///
377 /// Returns `Err` if `op_lookup` cannot resolve `name` for `arity` operands.
378 ///
379 /// # Examples
380 /// ```
381 /// use cel_parser::{DynSegmentContext, OpLookup, ParserContext};
382 /// use proc_macro2::Span;
383 /// let mut context = DynSegmentContext::new_context();
384 /// let span = Span::call_site();
385 /// context.push_literal(40i32, span);
386 /// context.push_literal(2i32, span);
387 /// context.apply_op(&OpLookup::new(), "+", 2, span, span).unwrap();
388 /// assert_eq!(context.into_inner().call0::<i32>().unwrap(), 42);
389 /// ```
390 fn apply_op(
391 &mut self,
392 op_lookup: &OpLookup,
393 name: &str,
394 arity: usize,
395 start: Span,
396 end: Span,
397 ) -> crate::Result<()>;
398
399 /// Applies a direct named operation to the receiver and explicit arguments in source order.
400 ///
401 /// `None` preserves `.name`; `Some(0)` preserves `.name()`. Both consume one receiver.
402 /// `name_span` identifies the member label for diagnostics; `start`/`end` cover the expression.
403 ///
404 /// - Precondition: the receiver and `explicit_args.unwrap_or(0)` arguments are emitted.
405 /// - Complexity: O(n) for n operands, plus operation lookup in runtime contexts.
406 ///
407 /// # Errors
408 /// Returns an error if a runtime context cannot resolve the operation.
409 ///
410 /// # Examples
411 /// ```
412 /// use cel_parser::{AstContext, ExprSpan, OpLookup};
413 /// use cel_parser::parser_context::ParserContext;
414 /// use proc_macro2::Span;
415 /// let mut context = AstContext::new_context();
416 /// let span = Span::call_site();
417 /// context.push_literal(1i32, span);
418 /// context.apply_member(&OpLookup::new(), "custom", ExprSpan { start: span, end: span },
419 /// None, span, span).unwrap();
420 /// ```
421 fn apply_member(
422 &mut self,
423 lookup: &OpLookup,
424 name: &str,
425 name_span: ExprSpan,
426 explicit_args: Option<usize>,
427 start: Span,
428 end: Span,
429 ) -> crate::Result<()>;
430
431 /// Constructs a record from named fields emitted exactly once in source order.
432 ///
433 /// - Precondition: one value per field follows `ambient_start` in this context.
434 /// - Complexity: O(f² + f * d + r) for f fields, descriptor depth d and r schemas.
435 ///
436 /// # Errors
437 /// Runtime contexts reject unknown schemas, invalid field sets, mismatched types,
438 /// or constructor emitter failures; syntax-only contexts preserve unresolved names.
439 ///
440 /// # Examples
441 /// See [`OpLookup::construct_record`].
442 #[allow(clippy::too_many_arguments)]
443 fn make_record(
444 &mut self,
445 lookup: &OpLookup,
446 name: &str,
447 name_span: ExprSpan,
448 fields: Vec<(String, ExprSpan)>,
449 ambient_start: usize,
450 start: Span,
451 end: Span,
452 ) -> crate::Result<()>;
453
454 /// Applies a short-circuiting logical operator (`"||"` or `"&&"`), consuming a leading
455 /// condition value already present on `self` and folding in `rhs`, the already-parsed
456 /// right-hand-side fragment.
457 ///
458 /// - Precondition: `name` is `"||"` or `"&&"`, and `rhs` produces exactly one value.
459 ///
460 /// # Errors
461 ///
462 /// Implementations that validate operand types during parsing (e.g. [`DynSegmentContext`])
463 /// return `Err` if the leading condition value isn't a `bool`. Implementations that defer
464 /// type validation to a later phase (e.g. [`crate::ast::AstContext`]) never return `Err`
465 /// here.
466 ///
467 /// # Examples
468 /// ```
469 /// use cel_parser::{DynSegmentContext, ParserContext};
470 /// use proc_macro2::Span;
471 /// let mut context = DynSegmentContext::new_context();
472 /// let span = Span::call_site();
473 /// context.push_literal(false, span);
474 /// let mut rhs = context.new_fragment();
475 /// rhs.push_literal(true, span);
476 /// context.apply_logical("&&", rhs, span, span).unwrap();
477 /// assert!(!context.into_inner().call0::<bool>().unwrap());
478 /// ```
479 fn apply_logical(&mut self, name: &str, rhs: Self, start: Span, end: Span)
480 -> crate::Result<()>;
481
482 /// Joins a previously-built fragment into `self`, consuming a leading condition value already
483 /// present on `self`. `then_fragment`'s contribution is used when the condition is `true`;
484 /// `else_fragment`'s when `false`, or `None` if the source had no `else`/`else if` at all.
485 /// `start`/`end` cover the whole `if`/`else` construct.
486 ///
487 /// - Precondition: neither fragment takes arguments, and each produces exactly one value.
488 ///
489 /// # Errors
490 ///
491 /// Implementations that validate operand types during parsing (e.g. [`DynSegmentContext`])
492 /// return `Err` if the leading condition value isn't a `bool` or if the fragments' produced
493 /// types don't match — including when `else_fragment` is `None`, which such implementations
494 /// treat as an implicit `()` fragment (so a non-`()` then-branch with no `else` is still an
495 /// error). Implementations that defer type validation to a later phase (e.g.
496 /// [`crate::ast::AstContext`]) never return `Err` here, and record whether `else_fragment` was
497 /// `None` directly (see [`crate::Expr::If`]) instead of synthesizing anything.
498 ///
499 /// # Examples
500 /// ```
501 /// use cel_parser::{DynSegmentContext, ParserContext};
502 /// use proc_macro2::Span;
503 /// let mut context = DynSegmentContext::new_context();
504 /// let span = Span::call_site();
505 /// context.push_literal(true, span);
506 /// let mut yes = context.new_fragment();
507 /// yes.push_literal(42i32, span);
508 /// let mut no = context.new_fragment();
509 /// no.push_literal(0i32, span);
510 /// context.join2(yes, Some(no), span, span).unwrap();
511 /// assert_eq!(context.into_inner().call0::<i32>().unwrap(), 42);
512 /// ```
513 fn join2(
514 &mut self,
515 then_fragment: Self,
516 else_fragment: Option<Self>,
517 start: Span,
518 end: Span,
519 ) -> anyhow::Result<()>;
520
521 /// Combines the last `n` emitted values into a single tuple value. `start`/`end` cover the
522 /// whole `(...)` construct.
523 ///
524 /// # Errors
525 /// Returns an error if the tuple's frame or canonical layout cannot be represented.
526 ///
527 /// # Examples
528 /// ```
529 /// use cel_parser::{DynSegmentContext, ParserContext};
530 /// use proc_macro2::Span;
531 /// let mut context = DynSegmentContext::new_context();
532 /// let span = Span::call_site();
533 /// let ambient = context.current_stack_offset();
534 /// context.push_literal(42i32, span);
535 /// context.push_literal(false, span);
536 /// context.make_tuple(2, ambient, span, span).unwrap();
537 /// assert_eq!(context.peek_tuple_arity(), Some(2));
538 /// context.tuple_index(0, span, span).unwrap();
539 /// assert_eq!(context.into_inner().call0::<i32>().unwrap(), 42);
540 /// ```
541 fn make_tuple(
542 &mut self,
543 n: usize,
544 ambient_start: usize,
545 start: Span,
546 end: Span,
547 ) -> crate::Result<()>;
548
549 /// Combines the last `n` emitted values into a single homogeneous array value. `start`/`end`
550 /// cover the whole `[...]` construct, and `ambient_start` is the stack offset the first
551 /// element was emitted at (as reported by [`Self::current_stack_offset`] before parsing it).
552 ///
553 /// - Precondition: `n >= 1` and exactly `n` values have been emitted since `ambient_start`.
554 ///
555 /// # Errors
556 ///
557 /// Implementations that validate operand types during parsing (e.g. [`DynSegmentContext`])
558 /// return `Err` if the elements' complete recursive runtime shapes differ, or if the array's storage
559 /// layout cannot be represented. Implementations that defer type validation to a later phase
560 /// (e.g. [`crate::ast::AstContext`]) never return `Err` here.
561 ///
562 /// # Examples
563 /// ```
564 /// use cel_parser::{AstContext, Expr, ParserContext};
565 /// use proc_macro2::Span;
566 /// let mut context = AstContext::new_context();
567 /// let span = Span::call_site();
568 /// let ambient = context.current_stack_offset();
569 /// context.push_literal(1i32, span);
570 /// context.push_literal(2i32, span);
571 /// context.make_array(2, ambient, span, span).unwrap();
572 /// assert!(matches!(context.into_expr(), Expr::Array { elements, .. } if elements.len() == 2));
573 /// ```
574 fn make_array(
575 &mut self,
576 n: usize,
577 ambient_start: usize,
578 start: Span,
579 end: Span,
580 ) -> crate::Result<()>;
581
582 /// Combines the last `n` emitted values into a single array value, honoring `annotation`'s
583 /// optional type ascription.
584 ///
585 /// This is the method the grammar actually calls for every array literal; [`Self::make_array`]
586 /// is the unannotated special case an implementation may delegate to. There is deliberately
587 /// no default implementation: an annotation changes what the literal means (`[]: [Celsius]`
588 /// is an empty array *of a specific type*), so an implementation that silently dropped it
589 /// would misreport the literal's type rather than fail to compile.
590 ///
591 /// An implementation that needs runtime array metadata immediately (e.g.
592 /// [`DynSegmentContext`]) calls [`AnnotatedArray::resolve_element_type`]; one that defers
593 /// semantic checking (e.g. [`crate::ast::AstContext`]) records the syntax returned by
594 /// [`AnnotatedArray::into_parts`].
595 ///
596 /// - Precondition: exactly `n` values have been emitted since `ambient_start`.
597 ///
598 /// # Errors
599 ///
600 /// Returns `Err` under [`Self::make_array`]'s conditions, and additionally — for an
601 /// implementation that resolves the annotation here — if the annotation names an unknown
602 /// type, does not name a complete array type, or disagrees with the collected elements.
603 ///
604 /// # Examples
605 /// See [`AnnotatedArray::resolve_element_type`] for annotation resolution and
606 /// [`Self::make_array`] for element emission.
607 fn make_annotated_array(
608 &mut self,
609 n: usize,
610 ambient_start: usize,
611 annotation: AnnotatedArray<'_>,
612 start: Span,
613 end: Span,
614 ) -> crate::Result<()>;
615
616 /// Returns the known tuple arity, or `None` for a non-tuple or unresolved value.
617 ///
618 /// # Examples
619 /// See [`Self::make_tuple`] for a resolved two-field tuple.
620 fn peek_tuple_arity(&self) -> Option<usize>;
621
622 /// Replaces the tuple on top with its `index`-th element. `start`/`end` cover the base
623 /// expression through the index token.
624 ///
625 /// # Errors
626 /// Returns an error if a resolved value is not a tuple, its index is out of bounds,
627 /// or the selected field's transfer frame cannot be represented.
628 /// Syntax-only contexts retain the index without imposing semantic bounds.
629 ///
630 /// # Examples
631 /// See [`Self::make_tuple`] for selection from a resolved tuple.
632 fn tuple_index(&mut self, index: usize, start: Span, end: Span) -> crate::Result<()>;
633
634 /// Returns the current stack offset, used to compute tuple layouts.
635 ///
636 /// # Examples
637 /// See [`Self::make_tuple`] for recording the offset before emitting fields.
638 fn current_stack_offset(&self) -> usize;
639
640 /// Applies a cast (`expr as Type`), consuming the operand already present on `self`
641 /// and replacing it with the converted value. `type_name` is the target type's bare
642 /// identifier text (e.g. `"i32"`, `"bool"`, `"String"`), unresolved by the grammar itself.
643 ///
644 /// # Errors
645 ///
646 /// Implementations that validate operand types during parsing (e.g. [`DynSegmentContext`])
647 /// return `Err` if `type_name` isn't a recognized cast-target type, or if no conversion
648 /// from the operand's current type to it is registered. Implementations that defer type
649 /// validation to a later phase (e.g. [`crate::ast::AstContext`]) never return `Err` here.
650 ///
651 /// # Examples
652 /// ```
653 /// use cel_parser::{DynSegmentContext, OpLookup, ParserContext};
654 /// use proc_macro2::Span;
655 /// let mut context = DynSegmentContext::new_context();
656 /// let span = Span::call_site();
657 /// context.push_literal(7i32, span);
658 /// context.apply_cast(&OpLookup::new(), "i64", span, span).unwrap();
659 /// assert_eq!(context.output_type_id(), Some(std::any::TypeId::of::<i64>()));
660 /// assert_eq!(context.into_inner().call0::<i64>().unwrap(), 7);
661 /// ```
662 fn apply_cast(
663 &mut self,
664 op_lookup: &OpLookup,
665 type_name: &str,
666 start: Span,
667 end: Span,
668 ) -> crate::Result<()>;
669
670 /// Packages a fully-parsed, independent nested context — the body of a closure literal — as
671 /// a value pushed onto `self`, given the closure's declared parameter types in two parallel
672 /// forms: `param_types` (each parameter's complete runtime shape, in order) for an implementation
673 /// that executes, and `params` (each parameter's name, span, and unresolved type expression)
674 /// for one that builds an AST instead. An implementation uses whichever it needs and ignores
675 /// the other.
676 ///
677 /// The default implementation reports closures as unsupported, so a `ParserContext`
678 /// implementation that has no use for them needs no changes to keep compiling.
679 ///
680 /// - Precondition: `body` was built via `Self::new_context()` and its own argument-binding
681 /// mechanism, in the same style [`Self::new_context`]'s other consumers already use.
682 ///
683 /// # Errors
684 ///
685 /// Returns `Err` if this `ParserContext` implementation doesn't support closures, or (for an
686 /// implementation that validates during parsing) if `body` is otherwise unsuitable — e.g.
687 /// [`DynSegmentContext`] rejects a `body` that doesn't produce exactly one value.
688 ///
689 /// # Examples
690 /// ```
691 /// use cel_parser::{AstContext, Expr, ParserContext};
692 /// use proc_macro2::Span;
693 /// let mut context = AstContext::new_context();
694 /// let span = Span::call_site();
695 /// let mut body = AstContext::new_context();
696 /// body.push_literal(42i32, span);
697 /// context.push_closure(Vec::new(), Vec::new(), body, span).unwrap();
698 /// assert!(matches!(context.into_expr(), Expr::Closure { params, .. } if params.is_empty()));
699 /// ```
700 fn push_closure(
701 &mut self,
702 param_types: Vec<cel_runtime::ValueType>,
703 params: Vec<ClosureParam>,
704 body: Self,
705 span: Span,
706 ) -> crate::Result<()> {
707 let _ = (param_types, params, body);
708 Err(crate::ParseError::new_range(
709 "closures are not supported in this context".to_string(),
710 span,
711 span,
712 ))
713 }
714
715 /// Returns the `TypeId` of the single value `self` currently holds, or `None` if that isn't
716 /// known/applicable for this `ParserContext` implementation.
717 ///
718 /// Used by the closure-literal grammar production to infer a closure's return type from its
719 /// already-compiled body, mirroring [`Self::peek_tuple_arity`]'s "ask the context what it
720 /// currently holds" shape, generalized from "is it a tuple" to "what type is it".
721 ///
722 /// The default implementation returns `None`. A syntax-only context can retain closures
723 /// without answering this runtime query; [`Self::resolves_closure_types`] selects that policy.
724 ///
725 /// # Examples
726 /// See [`Self::apply_cast`] for a known runtime output type.
727 fn output_type_id(&self) -> Option<std::any::TypeId> {
728 None
729 }
730}
731
732/// [`ParserContext`] implementation that executes directly into a [`DynSegment`], reproducing
733/// the runtime-execution behavior `CELParser` always had before this trait existed.
734///
735/// # Examples
736///
737/// ```rust
738/// use cel_parser::parser_context::{DynSegmentContext, ParserContext};
739/// use proc_macro2::Span;
740///
741/// let mut ctx = DynSegmentContext::new_context();
742/// ctx.push_literal(10i32, Span::call_site());
743/// ```
744pub struct DynSegmentContext(pub(crate) DynSegment);
745
746impl DynSegmentContext {
747 /// Returns the wrapped [`DynSegment`], consuming `self`.
748 ///
749 /// # Examples
750 /// See [`ParserContext::apply_op`] for executing the returned segment.
751 pub fn into_inner(self) -> DynSegment {
752 self.0
753 }
754
755 /// Emits ordinary or member dispatch through the selected borrowed scope environment.
756 ///
757 /// # Errors
758 /// Returns a spanned lookup or output annotation error.
759 /// - Complexity: O(k + s * a * d) for k scopes, s signatures, a operands and depth d.
760 pub(crate) fn apply_scoped_op(
761 &mut self,
762 lookup: &OpLookup,
763 name: &str,
764 arity: usize,
765 span: ExprSpan,
766 member: bool,
767 library_only: bool,
768 ) -> crate::Result<()> {
769 lookup.lookup_scoped(name, &mut self.0, arity, span, member, library_only)?;
770 if !member
771 && let Some(ty) = self
772 .0
773 .peek_output_type_id()
774 .and_then(crate::op_table::builtin_value_type)
775 {
776 self.0.annotate_top(ty).map_err(|error| {
777 crate::ParseError::new_range(error.to_string(), span.start, span.end)
778 })?;
779 }
780 Ok(())
781 }
782
783 /// Collects array elements using an already resolved optional annotation.
784 ///
785 /// # Errors
786 /// Returns a spanned error if element shapes differ or storage cannot be represented.
787 /// - Complexity: O(n * d) for n elements of descriptor depth d.
788 pub(crate) fn make_resolved_array(
789 &mut self,
790 n: usize,
791 ambient_start: usize,
792 element_type: Option<cel_runtime::ValueType>,
793 span: ExprSpan,
794 ) -> crate::Result<()> {
795 match element_type {
796 Some(element_type) => self
797 .0
798 .make_typed_array(n, ambient_start, element_type)
799 .map_err(|error| {
800 crate::ParseError::new_range(error.to_string(), span.start, span.end)
801 }),
802 None => self.make_array(n, ambient_start, span.start, span.end),
803 }
804 }
805}
806
807impl std::ops::Deref for DynSegmentContext {
808 /// The execution owner borrowed through this context.
809 type Target = DynSegment;
810
811 /// Borrows the execution segment without transferring ownership.
812 fn deref(&self) -> &DynSegment {
813 &self.0
814 }
815}
816
817impl std::ops::DerefMut for DynSegmentContext {
818 /// Exclusively borrows the execution segment.
819 fn deref_mut(&mut self) -> &mut DynSegment {
820 &mut self.0
821 }
822}
823
824impl ParserContext for DynSegmentContext {
825 /// Creates an empty execution owner with no arguments.
826 fn new_context() -> Self {
827 DynSegmentContext(DynSegment::new::<()>())
828 }
829
830 /// Creates an independent branch owner preserving the argument layout.
831 fn new_fragment(&self) -> Self {
832 DynSegmentContext(self.0.new_fragment())
833 }
834
835 /// Emits an owned literal and attaches its builtin descriptor when available.
836 fn push_literal<T: 'static + Clone>(&mut self, value: T, _span: Span) {
837 self.0.just(value);
838 if let Some(ty) = crate::op_table::builtin_value_type(std::any::TypeId::of::<T>()) {
839 self.0.annotate_top(ty).expect("same concrete literal");
840 }
841 }
842
843 /// Emits an identifier lookup or reports a source-anchored dispatch error.
844 fn push_identifier(&mut self, lookup: &OpLookup, name: &str, span: Span) -> crate::Result<()> {
845 self.apply_op(lookup, name, 0, span, span)
846 }
847
848 /// Emits a matching operation or reports a source-anchored dispatch error.
849 fn apply_op(
850 &mut self,
851 op_lookup: &OpLookup,
852 name: &str,
853 arity: usize,
854 start: Span,
855 end: Span,
856 ) -> crate::Result<()> {
857 self.apply_scoped_op(
858 op_lookup,
859 name,
860 arity,
861 ExprSpan { start, end },
862 false,
863 false,
864 )
865 }
866
867 /// Emits receiver-first direct dispatch with diagnostics anchored to the member name.
868 fn apply_member(
869 &mut self,
870 lookup: &OpLookup,
871 name: &str,
872 name_span: ExprSpan,
873 explicit_args: Option<usize>,
874 _start: Span,
875 _end: Span,
876 ) -> crate::Result<()> {
877 let arity = explicit_args.unwrap_or(0) + 1;
878 debug_assert_eq!(self.0.peek_stack_infos(arity).len(), arity);
879 self.apply_scoped_op(lookup, name, arity, name_span, true, false)
880 }
881
882 /// Validates and emits the registered constructor without rearranging field values.
883 fn make_record(
884 &mut self,
885 lookup: &OpLookup,
886 name: &str,
887 _name_span: ExprSpan,
888 fields: Vec<(String, ExprSpan)>,
889 ambient_start: usize,
890 start: Span,
891 end: Span,
892 ) -> crate::Result<()> {
893 lookup.construct_record(name, &fields, ambient_start, &mut self.0, start, end)
894 }
895
896 /// Emits lazy branching with the nonselected branch left unexecuted.
897 fn apply_logical(
898 &mut self,
899 name: &str,
900 rhs: Self,
901 start: Span,
902 end: Span,
903 ) -> crate::Result<()> {
904 let mut bypass = self.new_fragment();
905 let result = match name {
906 "||" => {
907 bypass.0.just(true);
908 self.0.join2(bypass.0, rhs.0)
909 }
910 "&&" => {
911 bypass.0.just(false);
912 self.0.join2(rhs.0, bypass.0)
913 }
914 other => unreachable!("apply_logical called with unsupported operator `{other}`"),
915 };
916 result.map_err(|e| crate::ParseError::new_range(e.to_string(), start, end))
917 }
918
919 /// Joins compatible branch outputs, supplying unit for an absent alternative.
920 fn join2(
921 &mut self,
922 then_fragment: Self,
923 else_fragment: Option<Self>,
924 _start: Span,
925 _end: Span,
926 ) -> anyhow::Result<()> {
927 // No `else`/`else if` in the source: synthesize the implicit `()` fragment here instead
928 // of receiving one pre-built from `is_if_expression` (lib.rs) — execution still needs a
929 // concrete fragment to select on `false`, even though `AstContext::join2` (ast.rs)
930 // records this case as `None` rather than a synthesized node.
931 let else_fragment = if let Some(fragment) = else_fragment {
932 fragment
933 } else {
934 let mut fragment = self.new_fragment();
935 fragment
936 .0
937 .make_tuple(0, fragment.0.current_stack_offset())?;
938 fragment
939 };
940 self.0.join2(then_fragment.0, else_fragment.0)
941 }
942
943 /// Builds a checked tuple layout from the current source-order fields.
944 fn make_tuple(
945 &mut self,
946 n: usize,
947 ambient_start: usize,
948 start: Span,
949 end: Span,
950 ) -> crate::Result<()> {
951 self.0
952 .make_tuple(n, ambient_start)
953 .map_err(|error| crate::ParseError::new_range(error.to_string(), start, end))
954 }
955
956 /// Builds an array or reports a source-anchored element-shape error.
957 fn make_array(
958 &mut self,
959 n: usize,
960 ambient_start: usize,
961 start: Span,
962 end: Span,
963 ) -> crate::Result<()> {
964 self.0
965 .make_array(n, ambient_start)
966 // The error spans the whole `[...]` literal: `DynSegment::make_array` names the
967 // offending element's index only in its message text, with no structured index to map
968 // back to that element's own span (see https://github.com/stlab/cel-rs/issues/215).
969 .map_err(|e| crate::ParseError::new_range(e.to_string(), start, end))
970 }
971
972 /// Resolves an annotation before constructing its checked array representation.
973 fn make_annotated_array(
974 &mut self,
975 n: usize,
976 ambient_start: usize,
977 mut annotation: AnnotatedArray<'_>,
978 start: Span,
979 end: Span,
980 ) -> crate::Result<()> {
981 self.make_resolved_array(
982 n,
983 ambient_start,
984 annotation.resolve_element_type()?,
985 ExprSpan { start, end },
986 )
987 }
988
989 /// Returns the execution stack's known tuple arity.
990 fn peek_tuple_arity(&self) -> Option<usize> {
991 self.0.peek_tuple_arity()
992 }
993
994 /// Validates a resolved tuple index before emitting its checked field transfer.
995 ///
996 /// # Errors
997 /// Returns a spanned error for a non-tuple, out-of-bounds index, or unrepresentable frame.
998 fn tuple_index(&mut self, index: usize, start: Span, end: Span) -> crate::Result<()> {
999 let arity = self
1000 .0
1001 .peek_tuple_arity()
1002 .ok_or_else(|| crate::ParseError::new_range("'.N' requires a tuple", start, end))?;
1003 if index >= arity {
1004 return Err(crate::ParseError::new_range(
1005 format!("tuple index `{index}` out of range for tuple of arity {arity}"),
1006 start,
1007 end,
1008 ));
1009 }
1010 self.0
1011 .tuple_index(index)
1012 .map_err(|error| crate::ParseError::new_range(error.to_string(), start, end))
1013 }
1014
1015 /// Returns the execution stack's current byte offset.
1016 fn current_stack_offset(&self) -> usize {
1017 self.0.current_stack_offset()
1018 }
1019
1020 /// Emits a checked cast or reports its source-anchored dispatch error.
1021 fn apply_cast(
1022 &mut self,
1023 op_lookup: &OpLookup,
1024 type_name: &str,
1025 start: Span,
1026 end: Span,
1027 ) -> crate::Result<()> {
1028 op_lookup.lookup_cast(type_name, &mut self.0, start, end)
1029 }
1030
1031 /// Installs a typed noncapturing body with its complete parameter and result shapes.
1032 fn push_closure(
1033 &mut self,
1034 param_types: Vec<cel_runtime::ValueType>,
1035 params: Vec<ClosureParam>,
1036 body: Self,
1037 span: Span,
1038 ) -> crate::Result<()> {
1039 let _ = params;
1040 let closure = cel_runtime::DynClosure::typed(param_types, body.into_inner())
1041 .map_err(|error| crate::ParseError::new_range(error.to_string(), span, span))?;
1042 self.0
1043 .push_closure(closure)
1044 .map_err(|error| crate::ParseError::new_range(error.to_string(), span, span))
1045 }
1046
1047 /// Returns the sole execution result's known concrete identity.
1048 fn output_type_id(&self) -> Option<std::any::TypeId> {
1049 self.0.peek_output_type_id()
1050 }
1051}
1052
1053#[cfg(test)]
1054mod tests {
1055 use super::*;
1056 use crate::op_table::OpLookup;
1057 use proc_macro2::Span;
1058
1059 #[test]
1060 fn new_context_is_empty_and_ready_for_literals() {
1061 let mut ctx = DynSegmentContext::new_context();
1062 ctx.push_literal(10i32, Span::call_site());
1063 assert_eq!(ctx.into_inner().call0::<i32>().unwrap(), 10);
1064 }
1065
1066 #[test]
1067 fn apply_op_dispatches_builtin_addition() {
1068 let mut ctx = DynSegmentContext::new_context();
1069 ctx.push_literal(10i32, Span::call_site());
1070 ctx.push_literal(20i32, Span::call_site());
1071 let lookup = OpLookup::new();
1072 ctx.apply_op(&lookup, "+", 2, Span::call_site(), Span::call_site())
1073 .unwrap();
1074 assert_eq!(ctx.into_inner().call0::<i32>().unwrap(), 30);
1075 }
1076
1077 #[test]
1078 fn apply_op_propagates_lookup_error() {
1079 let mut ctx = DynSegmentContext::new_context();
1080 ctx.push_literal(10i32, Span::call_site());
1081 ctx.push_literal("hi".to_string(), Span::call_site());
1082 let lookup = OpLookup::new();
1083 let err = ctx
1084 .apply_op(&lookup, "+", 2, Span::call_site(), Span::call_site())
1085 .expect_err("mismatched operand types must fail");
1086 assert!(err.message().starts_with("no operation"));
1087 }
1088
1089 /// Renders a type expression as its source-level text, for recording in assertions.
1090 fn render(type_expr: &TypeExpr) -> String {
1091 match type_expr {
1092 TypeExpr::Named { name, .. } => name.clone(),
1093 TypeExpr::Array { element, .. } => format!("[{}]", render(element)),
1094 TypeExpr::Tuple { elements, .. } => format!(
1095 "({})",
1096 elements.iter().map(render).collect::<Vec<_>>().join(", ")
1097 ),
1098 }
1099 }
1100
1101 /// Stands in for an out-of-tree [`ParserContext`] implementation: it records only what array
1102 /// construction hands it, so a dropped annotation would be observable.
1103 #[derive(Default)]
1104 struct RecordingContext {
1105 values: usize,
1106 arrays: Vec<(usize, Option<String>)>,
1107 }
1108
1109 impl ParserContext for RecordingContext {
1110 fn new_context() -> Self {
1111 Self::default()
1112 }
1113
1114 fn new_fragment(&self) -> Self {
1115 Self::default()
1116 }
1117
1118 fn push_literal<T: 'static + Clone>(&mut self, _value: T, _span: Span) {
1119 self.values += 1;
1120 }
1121
1122 /// Rejects identifiers outside this array-only test context.
1123 fn push_identifier(
1124 &mut self,
1125 _lookup: &OpLookup,
1126 _name: &str,
1127 _span: Span,
1128 ) -> crate::Result<()> {
1129 unimplemented!("RecordingContext only records array construction")
1130 }
1131
1132 fn apply_op(
1133 &mut self,
1134 _op_lookup: &OpLookup,
1135 _name: &str,
1136 _arity: usize,
1137 _start: Span,
1138 _end: Span,
1139 ) -> crate::Result<()> {
1140 unimplemented!("RecordingContext only records array construction")
1141 }
1142
1143 /// Rejects records outside this array-only test context.
1144 fn make_record(
1145 &mut self,
1146 _lookup: &OpLookup,
1147 _name: &str,
1148 _name_span: ExprSpan,
1149 _fields: Vec<(String, ExprSpan)>,
1150 _ambient_start: usize,
1151 _start: Span,
1152 _end: Span,
1153 ) -> crate::Result<()> {
1154 unimplemented!("RecordingContext only records array construction")
1155 }
1156
1157 /// Rejects member operations outside this array-only test context.
1158 fn apply_member(
1159 &mut self,
1160 _lookup: &OpLookup,
1161 _name: &str,
1162 _name_span: ExprSpan,
1163 _explicit_args: Option<usize>,
1164 _start: Span,
1165 _end: Span,
1166 ) -> crate::Result<()> {
1167 unimplemented!("RecordingContext only records array construction")
1168 }
1169
1170 fn apply_logical(
1171 &mut self,
1172 _name: &str,
1173 _rhs: Self,
1174 _start: Span,
1175 _end: Span,
1176 ) -> crate::Result<()> {
1177 unimplemented!("RecordingContext only records array construction")
1178 }
1179
1180 fn join2(
1181 &mut self,
1182 _then_fragment: Self,
1183 _else_fragment: Option<Self>,
1184 _start: Span,
1185 _end: Span,
1186 ) -> anyhow::Result<()> {
1187 unimplemented!("RecordingContext only records array construction")
1188 }
1189
1190 fn make_tuple(
1191 &mut self,
1192 _n: usize,
1193 _ambient_start: usize,
1194 _start: Span,
1195 _end: Span,
1196 ) -> crate::Result<()> {
1197 unimplemented!("RecordingContext only records array construction")
1198 }
1199
1200 fn make_array(
1201 &mut self,
1202 n: usize,
1203 ambient_start: usize,
1204 _start: Span,
1205 _end: Span,
1206 ) -> crate::Result<()> {
1207 self.values = ambient_start;
1208 self.arrays.push((n, None));
1209 self.values += 1;
1210 Ok(())
1211 }
1212
1213 fn make_annotated_array(
1214 &mut self,
1215 n: usize,
1216 ambient_start: usize,
1217 annotation: AnnotatedArray<'_>,
1218 start: Span,
1219 end: Span,
1220 ) -> crate::Result<()> {
1221 let (type_annotation, _span) = annotation.into_parts();
1222 let Some(type_annotation) = type_annotation else {
1223 return self.make_array(n, ambient_start, start, end);
1224 };
1225 self.values = ambient_start;
1226 self.arrays.push((n, Some(render(&type_annotation))));
1227 self.values += 1;
1228 Ok(())
1229 }
1230
1231 fn peek_tuple_arity(&self) -> Option<usize> {
1232 None
1233 }
1234
1235 fn tuple_index(&mut self, _index: usize, _start: Span, _end: Span) -> crate::Result<()> {
1236 unimplemented!("RecordingContext only records array construction")
1237 }
1238
1239 fn current_stack_offset(&self) -> usize {
1240 self.values
1241 }
1242
1243 fn apply_cast(
1244 &mut self,
1245 _op_lookup: &OpLookup,
1246 _type_name: &str,
1247 _start: Span,
1248 _end: Span,
1249 ) -> crate::Result<()> {
1250 unimplemented!("RecordingContext only records array construction")
1251 }
1252 }
1253
1254 /// The grammar hands every array annotation to the context, and a context that keeps it sees
1255 /// the complete declared type — including for the nested literal inside an annotated one.
1256 #[test]
1257 fn the_grammar_delivers_array_annotations_to_any_parser_context() {
1258 let mut parser = crate::Parser::<RecordingContext>::new(OpLookup::new());
1259 let ctx = parser
1260 .parse_str_ctx("[[]: [i32]]: [[i32]]")
1261 .expect("annotated nested array literal parses");
1262
1263 assert_eq!(
1264 ctx.arrays,
1265 vec![
1266 (0, Some("[i32]".to_string())),
1267 (1, Some("[[i32]]".to_string()))
1268 ]
1269 );
1270 }
1271
1272 /// An unannotated literal still reaches the same method, with no annotation to record.
1273 #[test]
1274 fn the_grammar_reports_no_annotation_for_an_unannotated_array() {
1275 let mut parser = crate::Parser::<RecordingContext>::new(OpLookup::new());
1276 let ctx = parser
1277 .parse_str_ctx("[1i32, 2i32]")
1278 .expect("unannotated array literal parses");
1279
1280 assert_eq!(ctx.arrays, vec![(2, None)]);
1281 }
1282
1283 #[test]
1284 fn make_tuple_and_tuple_index_roundtrip() {
1285 let mut ctx = DynSegmentContext::new_context();
1286 let ambient_start = ctx.current_stack_offset();
1287 ctx.push_literal(1i32, Span::call_site());
1288 ctx.push_literal(2i32, Span::call_site());
1289 ctx.make_tuple(2, ambient_start, Span::call_site(), Span::call_site())
1290 .unwrap();
1291 assert_eq!(ctx.peek_tuple_arity(), Some(2));
1292 ctx.tuple_index(1, Span::call_site(), Span::call_site())
1293 .unwrap();
1294 assert_eq!(ctx.into_inner().call0::<i32>().unwrap(), 2);
1295 }
1296
1297 #[test]
1298 fn make_array_collects_homogeneous_values_into_one_array() {
1299 let mut ctx = DynSegmentContext::new_context();
1300 let ambient_start = ctx.current_stack_offset();
1301 ctx.push_literal(1i32, Span::call_site());
1302 ctx.push_literal(2i32, Span::call_site());
1303 ctx.make_array(2, ambient_start, Span::call_site(), Span::call_site())
1304 .unwrap();
1305 let array = ctx
1306 .into_inner()
1307 .call0::<cel_runtime::OwnedValue>()
1308 .unwrap()
1309 .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()
1310 .unwrap();
1311 assert_eq!(array.into_vec(), vec![1, 2]);
1312 }
1313
1314 #[test]
1315 fn make_array_reports_a_mismatched_element_as_a_parse_error() {
1316 let mut ctx = DynSegmentContext::new_context();
1317 let ambient_start = ctx.current_stack_offset();
1318 ctx.push_literal(1i32, Span::call_site());
1319 ctx.push_literal(2.0f64, Span::call_site());
1320 let err = ctx
1321 .make_array(2, ambient_start, Span::call_site(), Span::call_site())
1322 .expect_err("array elements must share one type");
1323 assert!(
1324 err.message().contains("array element 1"),
1325 "got: {}",
1326 err.message()
1327 );
1328 }
1329
1330 #[test]
1331 fn make_annotated_array_with_none_preserves_unannotated_array_inference() {
1332 let mut ctx = DynSegmentContext::new_context();
1333 let ambient_start = ctx.current_stack_offset();
1334 ctx.push_literal(1i32, Span::call_site());
1335 ctx.push_literal(2i32, Span::call_site());
1336 ctx.make_annotated_array(
1337 2,
1338 ambient_start,
1339 AnnotatedArray::new(
1340 &mut |_| unreachable!("unannotated arrays do not resolve a declared type"),
1341 None,
1342 None,
1343 ),
1344 Span::call_site(),
1345 Span::call_site(),
1346 )
1347 .unwrap();
1348 let array = ctx
1349 .into_inner()
1350 .call0::<cel_runtime::OwnedValue>()
1351 .unwrap()
1352 .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()
1353 .unwrap();
1354 assert_eq!(array.into_vec(), vec![1, 2]);
1355 }
1356
1357 #[test]
1358 fn make_annotated_array_with_a_resolved_descriptor_collects_a_typed_empty_array() {
1359 let mut ctx = DynSegmentContext::new_context();
1360 let ambient_start = ctx.current_stack_offset();
1361 let annotation = TypeExpr::Array {
1362 element: Box::new(TypeExpr::Named {
1363 name: "i32".to_string(),
1364 args: Vec::new(),
1365 span: ExprSpan {
1366 start: Span::call_site(),
1367 end: Span::call_site(),
1368 },
1369 }),
1370 span: ExprSpan {
1371 start: Span::call_site(),
1372 end: Span::call_site(),
1373 },
1374 };
1375 ctx.make_annotated_array(
1376 0,
1377 ambient_start,
1378 AnnotatedArray::new(
1379 &mut |_| {
1380 Ok(crate::ResolvedArrayType::from_element_type(
1381 cel_runtime::ValueType::leaf::<i32>(),
1382 ))
1383 },
1384 Some(annotation),
1385 Some(ExprSpan {
1386 start: Span::call_site(),
1387 end: Span::call_site(),
1388 }),
1389 ),
1390 Span::call_site(),
1391 Span::call_site(),
1392 )
1393 .unwrap();
1394 let array = ctx
1395 .into_inner()
1396 .call0::<cel_runtime::OwnedValue>()
1397 .unwrap()
1398 .try_into_typed::<cel_runtime::ArrayOf<cel_runtime::Leaf<i32>>>()
1399 .unwrap();
1400 assert!(array.into_vec().is_empty());
1401 }
1402
1403 #[test]
1404 fn peek_tuple_arity_is_none_for_non_tuple() {
1405 let mut ctx = DynSegmentContext::new_context();
1406 ctx.push_literal(5i32, Span::call_site());
1407 assert_eq!(ctx.peek_tuple_arity(), None);
1408 }
1409
1410 #[test]
1411 fn join2_selects_then_fragment_when_condition_true() {
1412 let mut ctx = DynSegmentContext::new_context();
1413 ctx.push_literal(true, Span::call_site());
1414 let mut then_fragment = ctx.new_fragment();
1415 then_fragment.push_literal(1i32, Span::call_site());
1416 let mut else_fragment = ctx.new_fragment();
1417 else_fragment.push_literal(2i32, Span::call_site());
1418 ctx.join2(
1419 then_fragment,
1420 Some(else_fragment),
1421 Span::call_site(),
1422 Span::call_site(),
1423 )
1424 .unwrap();
1425 assert_eq!(ctx.into_inner().call0::<i32>().unwrap(), 1);
1426 }
1427
1428 #[test]
1429 fn join2_selects_else_fragment_when_condition_false() {
1430 let mut ctx = DynSegmentContext::new_context();
1431 ctx.push_literal(false, Span::call_site());
1432 let mut then_fragment = ctx.new_fragment();
1433 then_fragment.push_literal(1i32, Span::call_site());
1434 let mut else_fragment = ctx.new_fragment();
1435 else_fragment.push_literal(2i32, Span::call_site());
1436 ctx.join2(
1437 then_fragment,
1438 Some(else_fragment),
1439 Span::call_site(),
1440 Span::call_site(),
1441 )
1442 .unwrap();
1443 assert_eq!(ctx.into_inner().call0::<i32>().unwrap(), 2);
1444 }
1445
1446 #[test]
1447 fn join2_with_none_synthesizes_an_implicit_unit_else_fragment() {
1448 let mut ctx = DynSegmentContext::new_context();
1449 ctx.push_literal(false, Span::call_site());
1450 let mut then_fragment = ctx.new_fragment();
1451 then_fragment
1452 .make_tuple(
1453 0,
1454 then_fragment.current_stack_offset(),
1455 Span::call_site(),
1456 Span::call_site(),
1457 )
1458 .unwrap();
1459 ctx.join2(then_fragment, None, Span::call_site(), Span::call_site())
1460 .unwrap();
1461 ctx.into_inner().call0::<()>().unwrap();
1462 }
1463
1464 #[test]
1465 fn deref_gives_transparent_access_to_dyn_segment_methods() {
1466 // Proves DynSegmentContext doesn't need `.into_inner()` for read-only DynSegment
1467 // methods not part of ParserContext itself (e.g. peek_output_type_id).
1468 let mut ctx = DynSegmentContext::new_context();
1469 ctx.push_literal(7i32, Span::call_site());
1470 assert_eq!(
1471 ctx.peek_output_type_id(),
1472 Some(std::any::TypeId::of::<i32>())
1473 );
1474 ctx.op1r(|value: i32| {
1475 value
1476 .checked_add(1)
1477 .ok_or_else(|| anyhow::anyhow!("overflow"))
1478 })
1479 .unwrap();
1480 assert_eq!(ctx.call0::<i32>().unwrap(), 8);
1481 }
1482
1483 /// Defaults resolve runtime annotations, report unknown output, and reject closures.
1484 #[test]
1485 fn default_context_policy_is_explicit() {
1486 assert!(RecordingContext::resolves_closure_types());
1487 let mut context = RecordingContext::new_context();
1488 assert_eq!(context.output_type_id(), None);
1489 let error = context
1490 .push_closure(
1491 Vec::new(),
1492 Vec::new(),
1493 RecordingContext::new_context(),
1494 Span::call_site(),
1495 )
1496 .unwrap_err();
1497 assert!(error.message().contains("not supported"));
1498 }
1499
1500 /// Annotation accessors retain syntax and source while resolution reports host failures.
1501 #[test]
1502 fn annotation_accessors_and_resolution_errors_are_observable() {
1503 let syntax = crate::CELParser::new(OpLookup::new())
1504 .parse_type_expr_str("[i32]")
1505 .unwrap();
1506 let span = syntax.span();
1507 let mut resolve = |_: &TypeExpr| -> crate::Result<crate::ResolvedArrayType> {
1508 Err(crate::ParseError::new(
1509 "host resolution failed",
1510 Span::call_site(),
1511 ))
1512 };
1513 let mut annotation = AnnotatedArray::new(&mut resolve, Some(syntax), Some(span));
1514 assert!(matches!(
1515 annotation.type_annotation(),
1516 Some(TypeExpr::Array { .. })
1517 ));
1518 assert_eq!(
1519 annotation.annotation_span().unwrap().start.start().column,
1520 0
1521 );
1522 assert!(
1523 annotation
1524 .resolve_element_type()
1525 .unwrap_err()
1526 .message()
1527 .contains("host resolution failed")
1528 );
1529 }
1530
1531 #[test]
1532 fn apply_logical_or_short_circuits_to_lhs_when_true() {
1533 let mut ctx = DynSegmentContext::new_context();
1534 ctx.push_literal(true, Span::call_site());
1535 let mut rhs = ctx.new_fragment();
1536 rhs.push_literal(false, Span::call_site());
1537 ctx.apply_logical("||", rhs, Span::call_site(), Span::call_site())
1538 .unwrap();
1539 assert!(ctx.into_inner().call0::<bool>().unwrap());
1540 }
1541
1542 #[test]
1543 fn apply_logical_and_short_circuits_to_false_when_lhs_false() {
1544 let mut ctx = DynSegmentContext::new_context();
1545 ctx.push_literal(false, Span::call_site());
1546 let mut rhs = ctx.new_fragment();
1547 rhs.push_literal(true, Span::call_site());
1548 ctx.apply_logical("&&", rhs, Span::call_site(), Span::call_site())
1549 .unwrap();
1550 assert!(!ctx.into_inner().call0::<bool>().unwrap());
1551 }
1552
1553 #[test]
1554 fn dyn_segment_context_push_closure_builds_a_callable_closure() {
1555 let mut outer = DynSegmentContext::new_context();
1556 let mut body = DynSegmentContext::new_context();
1557 body.0.push_arg::<i32>(0);
1558 body.0.op1(|x: i32| x + 1).unwrap();
1559
1560 outer
1561 .push_closure(
1562 vec![cel_runtime::ValueType::leaf::<i32>()],
1563 Vec::new(),
1564 body,
1565 Span::call_site(),
1566 )
1567 .unwrap();
1568
1569 let closure: cel_runtime::DynClosure = outer.into_inner().call0().unwrap();
1570 let x = 5i32;
1571 assert_eq!(closure.call::<i32>(&[&x]).unwrap(), 6);
1572 }
1573}