Skip to main content

panproto_expr/
expr.rs

1//! Expression AST, pattern, and builtin operation types.
2//!
3//! The expression language is a pure functional language: lambda calculus
4//! with pattern matching, algebraic data types, and built-in operations on
5//! strings, numbers, records, and lists. Comparable to a pure subset of ML.
6
7use std::sync::Arc;
8
9use crate::Literal;
10
11/// An expression in the pure functional language.
12///
13/// All variants are serializable, content-addressable, and evaluate
14/// deterministically on any platform (including WASM).
15#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
16pub enum Expr {
17    /// Variable reference.
18    Var(Arc<str>),
19    /// Lambda abstraction: `λparam. body`.
20    Lam(Arc<str>, Box<Self>),
21    /// Function application: `func(arg)`.
22    App(Box<Self>, Box<Self>),
23    /// Literal value.
24    Lit(Literal),
25    /// Record construction: `{ name: expr, ... }`.
26    Record(Vec<(Arc<str>, Self)>),
27    /// List construction: `[expr, ...]`.
28    List(Vec<Self>),
29    /// Field access: `expr.field`.
30    Field(Box<Self>, Arc<str>),
31    /// Index access: `expr[index]`.
32    Index(Box<Self>, Box<Self>),
33    /// Pattern matching: `match scrutinee { pat => body, ... }`.
34    Match {
35        /// The value being matched against.
36        scrutinee: Box<Self>,
37        /// Arms: (pattern, body) pairs tried in order.
38        arms: Vec<(Pattern, Self)>,
39    },
40    /// Let binding: `let name = value in body`.
41    Let {
42        /// The bound variable name.
43        name: Arc<str>,
44        /// The value to bind.
45        value: Box<Self>,
46        /// The body where the binding is visible.
47        body: Box<Self>,
48    },
49    /// Built-in operation applied to arguments.
50    Builtin(BuiltinOp, Vec<Self>),
51}
52
53/// A destructuring pattern for match expressions.
54#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
55pub enum Pattern {
56    /// Matches anything, binds nothing.
57    Wildcard,
58    /// Matches anything, binds the value to a name.
59    Var(Arc<str>),
60    /// Matches a specific literal value.
61    Lit(Literal),
62    /// Matches a record with specific field patterns.
63    Record(Vec<(Arc<str>, Self)>),
64    /// Matches a list with element patterns.
65    List(Vec<Self>),
66    /// Matches a tagged constructor with argument patterns.
67    Constructor(Arc<str>, Vec<Self>),
68}
69
70/// Simple type classification for expressions.
71///
72/// This is a lightweight type system for the expression language,
73/// independent of the GAT type system in `panproto-gat`. Used for
74/// type inference and coercion validation within expressions.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
76pub enum ExprType {
77    /// 64-bit signed integer.
78    Int,
79    /// 64-bit IEEE 754 float.
80    Float,
81    /// UTF-8 string.
82    Str,
83    /// Boolean.
84    Bool,
85    /// Homogeneous list.
86    List,
87    /// Record (ordered map of fields to values).
88    Record,
89    /// Unknown or polymorphic type.
90    Any,
91}
92
93/// Built-in operations, grouped by domain.
94///
95/// Each operation has a fixed arity enforced at evaluation time.
96/// All operations are pure: no IO, no mutation, deterministic.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
98pub enum BuiltinOp {
99    // --- Arithmetic (7) ---
100    /// `add(a: int|float, b: int|float) → int|float`
101    Add,
102    /// `sub(a: int|float, b: int|float) → int|float`
103    Sub,
104    /// `mul(a: int|float, b: int|float) → int|float`
105    Mul,
106    /// `div(a: int|float, b: int|float) → int|float` (truncating for ints)
107    Div,
108    /// `mod_(a: int, b: int) → int`
109    Mod,
110    /// `neg(a: int|float) → int|float`
111    Neg,
112    /// `abs(a: int|float) → int|float`
113    Abs,
114
115    // --- Rounding (3) ---
116    /// `floor(a: float) → int`
117    Floor,
118    /// `ceil(a: float) → int`
119    Ceil,
120    /// `round(a: float) → int` (rounds to nearest, ties to even)
121    Round,
122
123    // --- Comparison (6) ---
124    /// `eq(a, b) → bool`
125    Eq,
126    /// `neq(a, b) → bool`
127    Neq,
128    /// `lt(a, b) → bool`
129    Lt,
130    /// `lte(a, b) → bool`
131    Lte,
132    /// `gt(a, b) → bool`
133    Gt,
134    /// `gte(a, b) → bool`
135    Gte,
136
137    // --- Boolean (3) ---
138    /// `and(a: bool, b: bool) → bool`
139    And,
140    /// `or(a: bool, b: bool) → bool`
141    Or,
142    /// `not(a: bool) → bool`
143    Not,
144
145    // --- String (10) ---
146    /// `concat(a: string, b: string) → string`
147    Concat,
148    /// `len(s: string) → int` (byte length)
149    Len,
150    /// `slice(s: string, start: int, end: int) → string`
151    Slice,
152    /// `upper(s: string) → string`
153    Upper,
154    /// `lower(s: string) → string`
155    Lower,
156    /// `trim(s: string) → string`
157    Trim,
158    /// `split(s: string, delim: string) → [string]`
159    Split,
160    /// `join(parts: [string], delim: string) → string`
161    Join,
162    /// `replace(s: string, from: string, to: string) → string`
163    Replace,
164    /// `contains(s: string, substr: string) → bool`
165    Contains,
166
167    // --- List (10) ---
168    /// `map(list: [a], f: a → b) → [b]`
169    Map,
170    /// `filter(list: [a], pred: a → bool) → [a]`
171    Filter,
172    /// `fold(list: [a], init: b, f: (b, a) → b) → b`
173    Fold,
174    /// `append(list: [a], item: a) → [a]`
175    Append,
176    /// `head(list: [a]) → a`
177    Head,
178    /// `tail(list: [a]) → [a]`
179    Tail,
180    /// `reverse(list: [a]) → [a]`
181    Reverse,
182    /// `flat_map(list: [a], f: a → [b]) → [b]`
183    FlatMap,
184    /// `length(list: [a]) → int` (list length, distinct from string Len)
185    Length,
186    /// `range(start: int, stop: int) → [int]` (inclusive of both bounds;
187    /// empty when `stop < start`)
188    Range,
189
190    // --- Record (4) ---
191    /// `merge(a: record, b: record) → record` (b fields override a)
192    MergeRecords,
193    /// `keys(r: record) → [string]`
194    Keys,
195    /// `values(r: record) → [any]`
196    Values,
197    /// `has_field(r: record, name: string) → bool`
198    HasField,
199
200    // --- Utility (3) ---
201    /// `default(x, fallback)`: returns fallback if x is null, else x.
202    DefaultVal,
203    /// `clamp(x, min, max)`: clamp a numeric value to the range [min, max].
204    Clamp,
205    /// `truncate_str(s, max_len)`: truncate a string to at most `max_len` bytes
206    /// (char-boundary safe).
207    TruncateStr,
208
209    // --- Type coercions (6) ---
210    /// `int_to_float(n: int) → float`
211    IntToFloat,
212    /// `float_to_int(f: float) → int` (truncates)
213    FloatToInt,
214    /// `int_to_str(n: int) → string`
215    IntToStr,
216    /// `float_to_str(f: float) → string`
217    FloatToStr,
218    /// `str_to_int(s: string) → int` (fails on non-numeric)
219    StrToInt,
220    /// `str_to_float(s: string) → float` (fails on non-numeric)
221    StrToFloat,
222
223    // --- Type inspection (3) ---
224    /// `type_of(v) → string` (returns type name)
225    TypeOf,
226    /// `is_null(v) → bool`
227    IsNull,
228    /// `is_list(v) → bool`
229    IsList,
230
231    // --- Graph traversal (5) ---
232    // These builtins require an instance context (`InstanceEnv` in
233    // panproto-inst) and are evaluated by `eval_with_instance`, not
234    // the standard `eval`. In the standard evaluator they return Null.
235    /// `edge(node_ref: string, edge_kind: string) → value`
236    /// Follow a named edge from a node in the instance tree.
237    Edge,
238    /// `children(node_ref: string) → [value]`
239    /// Get all children of a node in the instance tree.
240    Children,
241    /// `has_edge(node_ref: string, edge_kind: string) → bool`
242    /// Check if a node has a specific outgoing edge.
243    HasEdge,
244    /// `edge_count(node_ref: string) → int`
245    /// Count outgoing edges from a node.
246    EdgeCount,
247    /// `anchor(node_ref: string) → string`
248    /// Get the schema anchor (sort/kind) of a node.
249    Anchor,
250}
251
252impl BuiltinOp {
253    /// Returns the expected number of arguments for this builtin.
254    #[must_use]
255    pub const fn arity(self) -> usize {
256        match self {
257            // Unary
258            Self::Neg
259            | Self::Abs
260            | Self::Floor
261            | Self::Ceil
262            | Self::Round
263            | Self::Not
264            | Self::Upper
265            | Self::Lower
266            | Self::Trim
267            | Self::Head
268            | Self::Tail
269            | Self::Reverse
270            | Self::Keys
271            | Self::Values
272            | Self::IntToFloat
273            | Self::FloatToInt
274            | Self::IntToStr
275            | Self::FloatToStr
276            | Self::StrToInt
277            | Self::StrToFloat
278            | Self::TypeOf
279            | Self::IsNull
280            | Self::IsList
281            | Self::Len
282            | Self::Length
283            | Self::Children
284            | Self::EdgeCount
285            | Self::Anchor => 1,
286            // Binary
287            Self::Add
288            | Self::Sub
289            | Self::Mul
290            | Self::Div
291            | Self::Mod
292            | Self::Eq
293            | Self::Neq
294            | Self::Lt
295            | Self::Lte
296            | Self::Gt
297            | Self::Gte
298            | Self::And
299            | Self::Or
300            | Self::Concat
301            | Self::Split
302            | Self::Join
303            | Self::Append
304            | Self::Map
305            | Self::Filter
306            | Self::HasField
307            | Self::MergeRecords
308            | Self::Contains
309            | Self::FlatMap
310            | Self::Edge
311            | Self::HasEdge
312            | Self::DefaultVal
313            | Self::Range
314            | Self::TruncateStr => 2,
315            // Ternary
316            Self::Slice | Self::Replace | Self::Fold | Self::Clamp => 3,
317        }
318    }
319
320    /// Returns the type signature `(input_types, output_type)` for builtins
321    /// with a known, monomorphic signature. Polymorphic builtins (e.g., `Add`
322    /// works on both int and float) return `None`.
323    #[must_use]
324    pub const fn signature(self) -> Option<(&'static [ExprType], ExprType)> {
325        match self {
326            // Coercions: precise source→target signatures.
327            Self::IntToFloat => Some((&[ExprType::Int], ExprType::Float)),
328            Self::FloatToInt | Self::Floor | Self::Ceil | Self::Round => {
329                Some((&[ExprType::Float], ExprType::Int))
330            }
331            Self::IntToStr => Some((&[ExprType::Int], ExprType::Str)),
332            Self::FloatToStr => Some((&[ExprType::Float], ExprType::Str)),
333            Self::StrToInt | Self::Len => Some((&[ExprType::Str], ExprType::Int)),
334            Self::StrToFloat => Some((&[ExprType::Str], ExprType::Float)),
335
336            // Boolean operations.
337            Self::And | Self::Or => Some((&[ExprType::Bool, ExprType::Bool], ExprType::Bool)),
338            Self::Not => Some((&[ExprType::Bool], ExprType::Bool)),
339
340            // Comparison: polymorphic inputs, bool output.
341            Self::Eq | Self::Neq | Self::Lt | Self::Lte | Self::Gt | Self::Gte => {
342                Some((&[ExprType::Any, ExprType::Any], ExprType::Bool))
343            }
344
345            // String operations.
346            Self::Concat => Some((&[ExprType::Str, ExprType::Str], ExprType::Str)),
347            Self::Slice => Some((
348                &[ExprType::Str, ExprType::Int, ExprType::Int],
349                ExprType::Str,
350            )),
351            Self::Upper | Self::Lower | Self::Trim => Some((&[ExprType::Str], ExprType::Str)),
352            Self::Split => Some((&[ExprType::Str, ExprType::Str], ExprType::List)),
353            Self::Join => Some((&[ExprType::List, ExprType::Str], ExprType::Str)),
354            Self::Replace => Some((
355                &[ExprType::Str, ExprType::Str, ExprType::Str],
356                ExprType::Str,
357            )),
358            // Overloaded on the first argument: substring containment on a
359            // string, element membership on a list. Inputs are `Any`; only
360            // the `Bool` result is fixed.
361            Self::Contains => Some((&[ExprType::Any, ExprType::Any], ExprType::Bool)),
362            Self::TruncateStr => Some((&[ExprType::Str, ExprType::Int], ExprType::Str)),
363
364            // List operations.
365            Self::Length => Some((&[ExprType::List], ExprType::Int)),
366            Self::Range => Some((&[ExprType::Int, ExprType::Int], ExprType::List)),
367            Self::Reverse => Some((&[ExprType::List], ExprType::List)),
368
369            // Record operations.
370            Self::MergeRecords => Some((&[ExprType::Record, ExprType::Record], ExprType::Record)),
371            Self::Keys | Self::Values => Some((&[ExprType::Record], ExprType::List)),
372            Self::HasField => Some((&[ExprType::Record, ExprType::Str], ExprType::Bool)),
373
374            // Type inspection.
375            Self::TypeOf => Some((&[ExprType::Any], ExprType::Str)),
376            Self::IsNull | Self::IsList => Some((&[ExprType::Any], ExprType::Bool)),
377
378            // Polymorphic builtins: return None.
379            Self::Add
380            | Self::Sub
381            | Self::Mul
382            | Self::Div
383            | Self::Mod
384            | Self::Neg
385            | Self::Abs
386            | Self::Map
387            | Self::Filter
388            | Self::Fold
389            | Self::FlatMap
390            | Self::Append
391            | Self::Head
392            | Self::Tail
393            | Self::DefaultVal
394            | Self::Clamp
395            | Self::Edge
396            | Self::Children
397            | Self::HasEdge
398            | Self::EdgeCount
399            | Self::Anchor => None,
400        }
401    }
402}
403
404impl Expr {
405    /// Create a variable expression.
406    #[must_use]
407    pub fn var(name: impl Into<Arc<str>>) -> Self {
408        Self::Var(name.into())
409    }
410
411    /// Create a lambda expression.
412    #[must_use]
413    pub fn lam(param: impl Into<Arc<str>>, body: Self) -> Self {
414        Self::Lam(param.into(), Box::new(body))
415    }
416
417    /// Create an application expression.
418    #[must_use]
419    pub fn app(func: Self, arg: Self) -> Self {
420        Self::App(Box::new(func), Box::new(arg))
421    }
422
423    /// Create a let-binding expression.
424    #[must_use]
425    pub fn let_in(name: impl Into<Arc<str>>, value: Self, body: Self) -> Self {
426        Self::Let {
427            name: name.into(),
428            value: Box::new(value),
429            body: Box::new(body),
430        }
431    }
432
433    /// Create a field access expression.
434    #[must_use]
435    pub fn field(expr: Self, name: impl Into<Arc<str>>) -> Self {
436        Self::Field(Box::new(expr), name.into())
437    }
438
439    /// Create a builtin operation applied to arguments.
440    #[must_use]
441    pub const fn builtin(op: BuiltinOp, args: Vec<Self>) -> Self {
442        Self::Builtin(op, args)
443    }
444
445    /// Coerce an integer to a float.
446    #[must_use]
447    pub fn int_to_float(arg: Self) -> Self {
448        Self::Builtin(BuiltinOp::IntToFloat, vec![arg])
449    }
450
451    /// Coerce a float to an integer (truncates toward zero).
452    #[must_use]
453    pub fn float_to_int(arg: Self) -> Self {
454        Self::Builtin(BuiltinOp::FloatToInt, vec![arg])
455    }
456
457    /// Coerce an integer to a string.
458    #[must_use]
459    pub fn int_to_str(arg: Self) -> Self {
460        Self::Builtin(BuiltinOp::IntToStr, vec![arg])
461    }
462
463    /// Coerce a float to a string.
464    #[must_use]
465    pub fn float_to_str(arg: Self) -> Self {
466        Self::Builtin(BuiltinOp::FloatToStr, vec![arg])
467    }
468
469    /// Parse a string as an integer.
470    #[must_use]
471    pub fn str_to_int(arg: Self) -> Self {
472        Self::Builtin(BuiltinOp::StrToInt, vec![arg])
473    }
474
475    /// Parse a string as a float.
476    #[must_use]
477    pub fn str_to_float(arg: Self) -> Self {
478        Self::Builtin(BuiltinOp::StrToFloat, vec![arg])
479    }
480}
481
482#[cfg(test)]
483mod tests {
484    use super::*;
485
486    #[test]
487    fn builtin_arities() {
488        assert_eq!(BuiltinOp::Add.arity(), 2);
489        assert_eq!(BuiltinOp::Not.arity(), 1);
490        assert_eq!(BuiltinOp::Fold.arity(), 3);
491        assert_eq!(BuiltinOp::Slice.arity(), 3);
492    }
493
494    #[test]
495    fn expr_constructors() {
496        let e = Expr::let_in(
497            "x",
498            Expr::Lit(Literal::Int(42)),
499            Expr::builtin(
500                BuiltinOp::Add,
501                vec![Expr::var("x"), Expr::Lit(Literal::Int(1))],
502            ),
503        );
504        assert!(matches!(e, Expr::Let { .. }));
505    }
506}