Skip to main content

fic/ast/
expr.rs

1//! Expression AST nodes for the Fiducia expression language.
2//!
3//! # Grammar
4//!
5//! ```text
6//! e   ::= v                       -- literal
7//!       | x                       -- variable reference
8//!       | alias.fn(args)          -- function call
9//!       | sizeof(T)               -- size of type T
10//!       | uop e                   -- unary
11//!       | e binop e               -- binary
12//!
13//!       | e.field                 -- field access (base restricted to
14//!                                    a variable, call, or field chain)
15//!
16//! v   ::= int_lit                 -- decimal integer, e.g. 42
17//!       | hex_lit                 -- hex integer, e.g. 0xFF
18//!       | bool_lit                -- true | false
19//!
20//! uop   ::= - | ! | ~
21//! binop ::= + | - | * | / | %
22//!         | == | != | < | <= | > | >=
23//!         | && | ||
24//!         | & | | | ^ | << | >>
25//! ```
26//!
27//! # Operator precedence (loosest → tightest)
28//!
29//! | Level | Operators              |
30//! |-------|------------------------|
31//! | 1     | `\|\|`                 |
32//! | 2     | `&&`                   |
33//! | 3     | `\|`                   |
34//! | 4     | `^`                    |
35//! | 5     | `&`                    |
36//! | 6     | `==`, `!=`             |
37//! | 7     | `<`, `<=`, `>`, `>=`   |
38//! | 8     | `<<`, `>>`             |
39//! | 9     | `+`, `-`               |
40//! | 10    | `*`, `/`, `%`          |
41//! | 11    | unary `-`, `!`, `~`    |
42//! | 12    | primary atoms          |
43//!
44//! Language reference: [Expressions](https://fiducia-lang.github.io/docs/lang-spec/expressions.html).
45
46use std::ops::Range;
47
48use serde::Serialize;
49
50use super::types::Type;
51
52// ============================================================================
53// Literal values
54// ============================================================================
55
56/// A literal value — the base case of the expression grammar.
57#[derive(Debug, Clone, PartialEq, Serialize)]
58pub enum Lit {
59    /// Decimal integer literal, e.g. `42`.
60    Int(i64),
61    /// Hex integer literal, e.g. `0xFF` or `0x3_000_000`.
62    Hex(u64),
63    /// Boolean literal: `true` or `false`.
64    Bool(bool),
65}
66
67// ============================================================================
68// Operators
69// ============================================================================
70
71/// Unary operators.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
73pub enum UnaryOp {
74    /// Arithmetic negation: `-e`
75    Neg,
76    /// Logical not: `!e`
77    Not,
78    /// Bitwise complement: `~e`
79    BitNot,
80}
81
82impl UnaryOp {
83    /// The operator's spelling.
84    pub fn symbol(self) -> &'static str {
85        match self {
86            UnaryOp::Neg => "-",
87            UnaryOp::Not => "!",
88            UnaryOp::BitNot => "~",
89        }
90    }
91}
92
93/// Binary operators, grouped by category.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
95pub enum BinaryOp {
96    // Arithmetic
97    /// `+`
98    Add,
99    /// `-`
100    Sub,
101    /// `*`
102    Mul,
103    /// `/`
104    Div,
105    /// `%`
106    Mod,
107
108    // Comparison
109    /// `==`
110    Eq,
111    /// `!=`
112    Ne,
113    /// `<`
114    Lt,
115    /// `<=`
116    Le,
117    /// `>`
118    Gt,
119    /// `>=`
120    Ge,
121
122    // Logical
123    /// `&&`
124    And,
125    /// `||`
126    Or,
127
128    // Bitwise
129    /// `&`
130    BitAnd,
131    /// `|`
132    BitOr,
133    /// `^`
134    BitXor,
135    /// `<<`
136    Shl,
137    /// `>>`
138    Shr,
139}
140
141impl BinaryOp {
142    /// `== != < <= > >=`: the operators that give a `bool` from two values
143    /// of one type.
144    #[must_use]
145    pub fn is_comparison(self) -> bool {
146        matches!(
147            self,
148            BinaryOp::Eq | BinaryOp::Ne | BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge
149        )
150    }
151
152    /// `&& ||`: the operators over two `bool`s.
153    #[must_use]
154    pub fn is_logical(self) -> bool {
155        matches!(self, BinaryOp::And | BinaryOp::Or)
156    }
157
158    /// The operator's spelling.
159    pub fn symbol(self) -> &'static str {
160        match self {
161            BinaryOp::Add => "+",
162            BinaryOp::Sub => "-",
163            BinaryOp::Mul => "*",
164            BinaryOp::Div => "/",
165            BinaryOp::Mod => "%",
166            BinaryOp::Eq => "==",
167            BinaryOp::Ne => "!=",
168            BinaryOp::Lt => "<",
169            BinaryOp::Le => "<=",
170            BinaryOp::Gt => ">",
171            BinaryOp::Ge => ">=",
172            BinaryOp::And => "&&",
173            BinaryOp::Or => "||",
174            BinaryOp::BitAnd => "&",
175            BinaryOp::BitOr => "|",
176            BinaryOp::BitXor => "^",
177            BinaryOp::Shl => "<<",
178            BinaryOp::Shr => ">>",
179        }
180    }
181
182    /// Binding power (precedence level, higher = tighter).
183    /// Left-associative for all operators — right side recurses at `prec + 1`.
184    pub fn prec(self) -> u8 {
185        match self {
186            BinaryOp::Or => 1,
187            BinaryOp::And => 2,
188            BinaryOp::BitOr => 3,
189            BinaryOp::BitXor => 4,
190            BinaryOp::BitAnd => 5,
191            BinaryOp::Eq | BinaryOp::Ne => 6,
192            BinaryOp::Lt | BinaryOp::Le | BinaryOp::Gt | BinaryOp::Ge => 7,
193            BinaryOp::Shl | BinaryOp::Shr => 8,
194            BinaryOp::Add | BinaryOp::Sub => 9,
195            BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod => 10,
196        }
197    }
198}
199
200// ============================================================================
201// Expression AST
202// ============================================================================
203
204/// A Fiducia expression: a node kind together with its source byte range.
205///
206/// `span` is a half-open interval `[start, end)` into the original source
207/// string passed to the top-level parser, present on every node (not just
208/// the outermost) so diagnostics can point to the precise sub-expression
209/// that caused a type error or validation failure.
210#[derive(Debug, Clone, Serialize)]
211pub struct Expr {
212    /// The expression's variant and payload.
213    pub kind: ExprKind,
214    /// Byte offset range `[start, end)` in the source string.
215    pub span: Range<usize>,
216}
217
218/// The variant and payload of an [`Expr`].
219#[derive(Debug, Clone, Serialize)]
220pub enum ExprKind {
221    /// A literal value.
222    Lit(Lit),
223    /// A variable reference: `x`.
224    Var(String),
225    /// A function call: `alias.fn_name(args)`.
226    Call(CExpr),
227    /// `sizeof(T)` — byte size of type `T`.
228    Sizeof(Type),
229    /// Unary operation: `-e`, `!e`, `~e`.
230    Unary {
231        /// The operator.
232        op: UnaryOp,
233        /// Operand.
234        operand: Box<Expr>,
235    },
236    /// Binary operation: `lhs op rhs`.
237    Binary {
238        /// The operator.
239        op: BinaryOp,
240        /// Left-hand side.
241        lhs: Box<Expr>,
242        /// Right-hand side.
243        rhs: Box<Expr>,
244    },
245    /// Field access: `expr.field`.
246    Field {
247        /// The expression being accessed.
248        expr: Box<Expr>,
249        /// The field name.
250        field: String,
251    },
252    /// An explicit conversion: `expr as T`. Tighter than every binary
253    /// operator, looser than unary: `-x as uint` is `(-x) as uint`,
254    /// `a + x as uint` is `a + (x as uint)`.
255    Cast {
256        /// The value converted.
257        expr: Box<Expr>,
258        /// The type it becomes.
259        ty: Type,
260    },
261}
262
263// ============================================================================
264// Function call expression
265// ============================================================================
266
267/// Function call expression: `alias '.' fn_name '(' args ')'`.
268///
269/// All callables are functions defined in imported C/Pancake files, so the
270/// alias is required — there are no local callables. Arguments are
271/// parsed as comma-separated expressions.
272#[derive(Debug, Clone, Serialize)]
273pub struct CExpr {
274    /// Module/import alias prefix (the `as` name from an `import` declaration).
275    pub alias: String,
276    /// Function name being called.
277    pub fn_name: String,
278    /// Argument expressions, in order.
279    pub args: Vec<Expr>,
280    /// Byte span of the whole `alias.fn(args)` call.
281    pub span: Range<usize>,
282}