Skip to main content

aether/
ast.rs

1// src/ast.rs
2//! Abstract Syntax Tree (AST) definitions for Aether
3//!
4//! This module defines the structure of Aether programs as a tree of nodes.
5
6use std::collections::HashSet;
7
8/// Binary operators
9#[derive(Debug, Clone, PartialEq)]
10pub enum BinOp {
11    // Arithmetic
12    Add,      // +
13    Subtract, // -
14    Multiply, // *
15    Divide,   // /
16    Modulo,   // %
17
18    // Comparison
19    Equal,        // ==
20    NotEqual,     // !=
21    Less,         // <
22    LessEqual,    // <=
23    Greater,      // >
24    GreaterEqual, // >=
25
26    // Logical
27    And, // &&
28    Or,  // ||
29
30    // Bitwise
31    BitAnd, // &
32    BitOr,  // |
33    BitXor, // ^
34    Shl,    // <<
35    Shr,    // >>
36}
37
38/// Unary operators
39#[derive(Debug, Clone, PartialEq)]
40pub enum UnaryOp {
41    Minus, // -
42    Not,   // !
43}
44
45/// Expressions - things that evaluate to values
46#[derive(Debug, Clone, PartialEq)]
47pub enum Expr {
48    // Literals
49    Number(f64),
50    BigInteger(num_bigint::BigInt), // 大整数字面量(解析期一次性构造)
51    String(String),
52    Boolean(bool),
53    Null,
54
55    // Identifier (variable reference)
56    Identifier(String),
57
58    // Binary operation: (left op right)
59    Binary {
60        left: Box<Expr>,
61        op: BinOp,
62        right: Box<Expr>,
63    },
64
65    // Unary operation: (op expr)
66    Unary {
67        op: UnaryOp,
68        expr: Box<Expr>,
69    },
70
71    // Function call: FUNC(arg1, arg2, ...)
72    Call {
73        func: Box<Expr>,
74        args: Vec<Expr>,
75    },
76
77    // Array literal: [1, 2, 3]
78    Array(Vec<Expr>),
79
80    // Dictionary literal: {key: value, ...}
81    Dict(Vec<(String, Expr)>),
82
83    // Array/Dict access: array[index] or dict[key]
84    Index {
85        object: Box<Expr>,
86        index: Box<Expr>,
87    },
88
89    // If expression (can return value)
90    If {
91        condition: Box<Expr>,
92        then_branch: Vec<Located>,
93        elif_branches: Vec<(Expr, Vec<Located>)>, // (condition, body) pairs
94        else_branch: Option<Vec<Located>>,
95    },
96
97    // Anonymous function
98    Lambda {
99        params: Vec<String>,
100        body: Vec<Located>,
101    },
102}
103
104/// Statements - things that perform actions
105#[derive(Debug, Clone, PartialEq)]
106pub enum Stmt {
107    // Variable assignment: Set NAME value
108    Set {
109        name: String,
110        value: Expr,
111    },
112
113    // Index assignment: Set OBJECT[INDEX] value (for arrays and dicts)
114    SetIndex {
115        object: Box<Expr>,
116        index: Box<Expr>,
117        value: Expr,
118    },
119
120    // Function definition: Func NAME (params) { body }
121    FuncDef {
122        name: String,
123        params: Vec<String>,
124        body: Vec<Located>,
125    },
126
127    // Generator definition: Generator NAME (params) { body }
128    GeneratorDef {
129        name: String,
130        params: Vec<String>,
131        body: Vec<Located>,
132    },
133
134    // Lazy variable: Lazy NAME (expr)
135    LazyDef {
136        name: String,
137        expr: Expr,
138    },
139
140    // Return statement: Return expr
141    Return(Expr),
142
143    // Yield statement (for generators): Yield expr
144    Yield(Expr),
145
146    // Break statement: Break (exit loop)
147    Break,
148
149    // Continue statement: Continue (skip to next iteration)
150    Continue,
151
152    // While loop: While (condition) { body }
153    While {
154        condition: Expr,
155        body: Vec<Located>,
156    },
157
158    // For loop: For VAR In ITERABLE { body }
159    For {
160        var: String,
161        iterable: Expr,
162        body: Vec<Located>,
163    },
164
165    // For loop with index: For INDEX, VAR In ITERABLE { body }
166    ForIndexed {
167        index_var: String,
168        value_var: String,
169        iterable: Expr,
170        body: Vec<Located>,
171    },
172
173    // Switch statement: Switch (expr) { Case val: body ... Default: body }
174    Switch {
175        expr: Expr,
176        cases: Vec<(Expr, Vec<Located>)>,
177        default: Option<Vec<Located>>,
178    },
179
180    // Import statement:
181    // - Named imports: Import {NAME1, NAME2} From PATH
182    // - Named import with alias: Import NAME As ALIAS From PATH
183    // - Namespace import: Import NS From PATH  (bind module exports as Dict to NS)
184    Import {
185        names: Vec<String>,
186        path: String,
187        aliases: Vec<Option<String>>, // Optional aliases (As NAME)
188        namespace: Option<String>,    // Namespace binding name
189    },
190
191    // Export statement: Export NAME
192    Export(String),
193
194    // Throw statement: Throw message
195    Throw(Expr),
196
197    // Expression statement (expression as statement)
198    Expression(Expr),
199}
200
201/// 带源码行号的语句包装(行号为语句首 token 所在行,供调试器断点定位)
202#[derive(Debug, Clone)]
203pub struct Located {
204    pub line: usize,
205    pub stmt: Stmt,
206}
207
208// 手工实现并忽略 line:行号是位置元数据而非程序语义,
209// 优化器改写或测试构造的 AST 不应因行号差异而不相等
210impl PartialEq for Located {
211    fn eq(&self, other: &Self) -> bool {
212        self.stmt == other.stmt
213    }
214}
215impl Eq for Located {}
216
217/// 包装语句并标注行号的便捷构造
218pub fn located(line: usize, stmt: Stmt) -> Located {
219    Located { line, stmt }
220}
221
222/// A complete program is a list of statements
223pub type Program = Vec<Located>;
224
225/// 递归收集程序中所有语句起始行号(供调试器校验断点行是否可命中)
226pub fn collect_breakable_lines(program: &Program) -> HashSet<usize> {
227    let mut lines = HashSet::new();
228    for l in program {
229        lines.insert(l.line);
230        collect_stmt_lines(&l.stmt, &mut lines);
231    }
232    lines
233}
234
235fn collect_stmt_lines(stmt: &Stmt, lines: &mut HashSet<usize>) {
236    let body_of = |body: &Vec<Located>, lines: &mut HashSet<usize>| {
237        for l in body {
238            lines.insert(l.line);
239            collect_stmt_lines(&l.stmt, lines);
240        }
241    };
242    match stmt {
243        Stmt::FuncDef { body, .. } | Stmt::GeneratorDef { body, .. } => body_of(body, lines),
244        Stmt::While { body, .. } | Stmt::For { body, .. } | Stmt::ForIndexed { body, .. } => {
245            body_of(body, lines)
246        }
247        Stmt::Switch { cases, default, .. } => {
248            for (_, body) in cases {
249                body_of(body, lines);
250            }
251            if let Some(body) = default {
252                body_of(body, lines);
253            }
254        }
255        Stmt::Expression(Expr::If {
256            then_branch,
257            elif_branches,
258            else_branch,
259            ..
260        }) => {
261            body_of(then_branch, lines);
262            for (_, body) in elif_branches {
263                body_of(body, lines);
264            }
265            if let Some(body) = else_branch {
266                body_of(body, lines);
267            }
268        }
269        _ => {}
270    }
271}
272
273impl Expr {
274    /// Helper to create a binary expression
275    pub fn binary(left: Expr, op: BinOp, right: Expr) -> Self {
276        Expr::Binary {
277            left: Box::new(left),
278            op,
279            right: Box::new(right),
280        }
281    }
282
283    /// Helper to create a unary expression
284    pub fn unary(op: UnaryOp, expr: Expr) -> Self {
285        Expr::Unary {
286            op,
287            expr: Box::new(expr),
288        }
289    }
290
291    /// Helper to create a function call
292    pub fn call(func: Expr, args: Vec<Expr>) -> Self {
293        Expr::Call {
294            func: Box::new(func),
295            args,
296        }
297    }
298
299    /// Helper to create an index expression
300    pub fn index(object: Expr, index: Expr) -> Self {
301        Expr::Index {
302            object: Box::new(object),
303            index: Box::new(index),
304        }
305    }
306}
307
308impl std::fmt::Display for BinOp {
309    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
310        match self {
311            BinOp::Add => write!(f, "+"),
312            BinOp::Subtract => write!(f, "-"),
313            BinOp::Multiply => write!(f, "*"),
314            BinOp::Divide => write!(f, "/"),
315            BinOp::Modulo => write!(f, "%"),
316            BinOp::BitAnd => write!(f, "&"),
317            BinOp::BitOr => write!(f, "|"),
318            BinOp::BitXor => write!(f, "^"),
319            BinOp::Shl => write!(f, "<<"),
320            BinOp::Shr => write!(f, ">>"),
321            BinOp::Equal => write!(f, "=="),
322            BinOp::NotEqual => write!(f, "!="),
323            BinOp::Less => write!(f, "<"),
324            BinOp::LessEqual => write!(f, "<="),
325            BinOp::Greater => write!(f, ">"),
326            BinOp::GreaterEqual => write!(f, ">="),
327            BinOp::And => write!(f, "&&"),
328            BinOp::Or => write!(f, "||"),
329        }
330    }
331}
332
333impl std::fmt::Display for UnaryOp {
334    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
335        match self {
336            UnaryOp::Minus => write!(f, "-"),
337            UnaryOp::Not => write!(f, "!"),
338        }
339    }
340}