Expand description
Conditional expression parsing and evaluation.
This module provides the parsing and evaluation infrastructure for conditional
expressions in the AIMX (Agentic Inference Markup Expressions) language. It
specifically handles the ternary conditional operator (? :), which has
right associativity and a specific precedence in the expression grammar.
§Operator Precedence
The conditional operator has higher precedence than closure expressions:
- Primary - Literals, references, parentheses
- Postfix - Method calls, indexing, function calls
- Unary - Prefix operators (
!,+,-, casts) - Multiplicative - Multiplication, division, modulo (
*,/,%) - Additive - Addition, subtraction (
+,-) - Relational - Comparison operators (
<,<=,>,>=) - Equality - Equality and inequality (
=,!=) - Logical - Logical AND and OR (
&,|) - Conditional - Ternary operator (
?,:) - Closure - Anonymous functions (
=>) - Procedure - Sequence expressions (
;)
§Grammar
The conditional operator has the following grammar:
conditional := or_expression (S? '?' S? expression S? ':' S? conditional)?Where S represents optional whitespace. The optional conditional part makes
the operator right associative, meaning a ? b : c ? d : e is parsed as
a ? b : (c ? d : e).
§Truthiness Evaluation
The condition expression is evaluated for truthiness using the following rules:
- Boolean values:
trueevaluates to truthy,falseto falsy - Arrays: Non-empty arrays are truthy, empty arrays are falsy
- Other types: Converted to boolean using Rust’s standard truthiness rules
- Numbers: Non-zero values are truthy, zero is falsy
- Text: Non-empty strings are truthy, empty strings are falsy
- Empty values: Always falsy
§AST Representation
The module uses AST flattening optimization where Conditional includes
variants for all lower-precedence expression types. This allows efficient
evaluation without deep recursion.
§Examples
§Basic Usage
5 > 3 ? "yes" : "no" // → "yes"
true ? 1 : 0 // → 1
x > 0 ? "positive" : "non-positive" // conditional assignment§Complex Conditions
is_valid & (x > threshold) ? "pass" : "fail"
status == "completed" ? final_score : pending_score§Right Associativity
a ? b : c ? d : e // Parsed as: a ? b : (c ? d : e)
x > 0 ? 1 : y > 0 ? 2 : 3 // Parsed as: x > 0 ? 1 : (y > 0 ? 2 : 3)§Runtime Behavior
- Short-circuit evaluation: Only the selected branch (true or false) is evaluated
- Error handling: Errors in the condition propagate immediately, errors in unselected branches are not evaluated
- Type safety: The true and false expressions can have different types
§Related Modules
logical- Higher precedence logical operations (&,|)expression- Top-level expression parsingevaluate- Core evaluation traitsprimary- Lower precedence expressions
Enums§
- Conditional
- A conditional expression node in the abstract syntax tree.
Functions§
- parse_
conditional - Parse a conditional expression.