Skip to main content

aether/
parser.rs

1// src/parser.rs
2//! Parser for the Aether language
3//!
4//! Converts a stream of tokens into an Abstract Syntax Tree (AST)
5
6use crate::ast::{BinOp, Expr, Located, Program, Stmt, UnaryOp, located};
7use crate::lexer::Lexer;
8use crate::token::Token;
9
10/// Parse errors with location information
11#[derive(Debug, Clone, PartialEq)]
12pub enum ParseError {
13    UnexpectedToken {
14        expected: String,
15        found: Token,
16        line: usize,
17        column: usize,
18    },
19    UnexpectedEOF {
20        line: usize,
21        column: usize,
22    },
23    InvalidNumber(String),
24    InvalidExpression {
25        message: String,
26        line: usize,
27        column: usize,
28    },
29    InvalidStatement {
30        message: String,
31        line: usize,
32        column: usize,
33    },
34    InvalidIdentifier {
35        name: String,
36        reason: String,
37        line: usize,
38        column: usize,
39    },
40}
41
42impl std::fmt::Display for ParseError {
43    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
44        match self {
45            ParseError::UnexpectedToken {
46                expected,
47                found,
48                line,
49                column,
50            } => {
51                write!(
52                    f,
53                    "Parse error at line {}, column {}: Expected {}, found {:?}",
54                    line, column, expected, found
55                )
56            }
57            ParseError::UnexpectedEOF { line, column } => {
58                write!(
59                    f,
60                    "Parse error at line {}, column {}: Unexpected end of file",
61                    line, column
62                )
63            }
64            ParseError::InvalidNumber(s) => write!(f, "Parse error: Invalid number: {}", s),
65            ParseError::InvalidExpression {
66                message,
67                line,
68                column,
69            } => {
70                write!(
71                    f,
72                    "Parse error at line {}, column {}: Invalid expression - {}",
73                    line, column, message
74                )
75            }
76            ParseError::InvalidStatement {
77                message,
78                line,
79                column,
80            } => {
81                write!(
82                    f,
83                    "Parse error at line {}, column {}: Invalid statement - {}",
84                    line, column, message
85                )
86            }
87            ParseError::InvalidIdentifier {
88                name,
89                reason,
90                line,
91                column,
92            } => {
93                write!(
94                    f,
95                    "Parse error at line {}, column {}: Invalid identifier '{}' - {}",
96                    line, column, name, reason
97                )
98            }
99        }
100    }
101}
102
103impl std::error::Error for ParseError {}
104
105/// Operator precedence (higher number = higher precedence)
106#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
107enum Precedence {
108    Lowest = 0,
109    Or = 1,         // ||
110    And = 2,        // &&
111    BitOr = 3,      // |
112    BitXor = 4,     // ^
113    BitAnd = 5,     // &
114    Equals = 6,     // ==, !=
115    Comparison = 7, // <, <=, >, >=
116    Shift = 8,      // <<, >>
117    Sum = 9,        // +, -
118    Product = 10,   // *, /, %
119    Prefix = 11,    // -, !
120    Call = 12,      // func()
121    Index = 13,     // array[index]
122}
123
124/// Parser state
125pub struct Parser {
126    lexer: Lexer,
127    current_token: Token,
128    peek_token: Token,
129    current_line: usize,
130    current_column: usize,
131    current_had_whitespace: bool, // whether whitespace preceded current_token
132    peek_had_whitespace: bool,    // whether whitespace preceded peek_token
133    // current_token / peek_token 各自所在的行(token 产生时 lexer 所在行),
134    // 供语句包装 Located 行号使用;与 current_line(错误报告用,可能领先于
135    // current_token)语义不同,故单独追踪
136    current_token_line: usize,
137    peek_token_line: usize,
138}
139
140impl Parser {
141    /// Create a new parser from source code
142    pub fn new(input: &str) -> Self {
143        Self::with_bigint_threshold(input, crate::lexer::DEFAULT_BIGINT_THRESHOLD)
144    }
145
146    /// Create a new parser with a custom big-integer threshold
147    pub fn with_bigint_threshold(input: &str, bigint_threshold: usize) -> Self {
148        let mut lexer = Lexer::with_bigint_threshold(input, bigint_threshold);
149        let current = lexer.next_token();
150        let current_ws = lexer.had_whitespace();
151        let current_tok_line = lexer.line();
152        let peek = lexer.next_token();
153        let peek_ws = lexer.had_whitespace();
154        let line = lexer.line();
155        let column = lexer.column();
156
157        Parser {
158            lexer,
159            current_token: current,
160            peek_token: peek,
161            current_line: line,
162            current_column: column,
163            current_had_whitespace: current_ws,
164            peek_had_whitespace: peek_ws,
165            current_token_line: current_tok_line,
166            peek_token_line: line,
167        }
168    }
169
170    /// 解析独立表达式字符串(调试器条件断点使用):
171    /// 解析单个表达式后要求输入恰好耗尽(允许首尾换行),
172    /// 有多余 token 视为非法条件。
173    pub fn parse_expression_source(input: &str) -> Result<Expr, ParseError> {
174        let mut parser = Parser::new(input);
175        parser.skip_newlines();
176        let expr = parser.parse_expression(Precedence::Lowest)?;
177        parser.skip_newlines();
178        if parser.current_token != Token::EOF {
179            return Err(ParseError::InvalidExpression {
180                message: "条件中存在多余内容".to_string(),
181                line: parser.current_line,
182                column: parser.current_column,
183            });
184        }
185        Ok(expr)
186    }
187
188    /// Advance to the next token
189    fn next_token(&mut self) {
190        self.current_token = self.peek_token.clone();
191        self.current_had_whitespace = self.peek_had_whitespace;
192        self.current_token_line = self.peek_token_line;
193        self.peek_token = self.lexer.next_token();
194        self.peek_had_whitespace = self.lexer.had_whitespace();
195        self.peek_token_line = self.lexer.line();
196        self.current_line = self.lexer.line();
197        self.current_column = self.lexer.column();
198    }
199
200    /// current_token 所在行,即以待解析语句首 token 所在行作为语句行号
201    fn stmt_start_line(&self) -> usize {
202        self.current_token_line
203    }
204
205    /// Skip newline tokens (they're optional in many places)
206    fn skip_newlines(&mut self) {
207        while self.current_token == Token::Newline {
208            self.next_token();
209        }
210    }
211
212    /// Check if current token matches expected, advance if true
213    fn expect_token(&mut self, expected: Token) -> Result<(), ParseError> {
214        if self.current_token == expected {
215            self.next_token();
216            Ok(())
217        } else {
218            Err(ParseError::UnexpectedToken {
219                expected: format!("{:?}", expected),
220                found: self.current_token.clone(),
221                line: self.current_line,
222                column: self.current_column,
223            })
224        }
225    }
226
227    /// Helper to check if identifier follows naming convention (UPPER_SNAKE_CASE)
228    fn validate_identifier(&self, name: &str) -> Result<(), ParseError> {
229        self.validate_identifier_internal(name, false)
230    }
231
232    /// Helper to check if identifier follows naming convention
233    /// For function parameters, we allow more flexible naming (can use lowercase)
234    fn validate_identifier_internal(&self, name: &str, is_param: bool) -> Result<(), ParseError> {
235        // Check it doesn't start with a number
236        if name.chars().next().is_some_and(|c| c.is_numeric()) {
237            return Err(ParseError::InvalidIdentifier {
238                name: name.to_string(),
239                reason: "标识符不能以数字开头".to_string(),
240                line: self.current_line,
241                column: self.current_column,
242            });
243        }
244
245        // For function parameters, allow lowercase letters
246        if is_param {
247            let is_valid = name
248                .chars()
249                .all(|c| c.is_alphabetic() || c.is_numeric() || c == '_');
250
251            if !is_valid {
252                return Err(ParseError::InvalidIdentifier {
253                    name: name.to_string(),
254                    reason: "参数名只能包含字母、数字和下划线".to_string(),
255                    line: self.current_line,
256                    column: self.current_column,
257                });
258            }
259        } else {
260            // For variables and function names, require uppercase
261            let is_valid = name
262                .chars()
263                .all(|c| c.is_uppercase() || c.is_numeric() || c == '_');
264
265            if !is_valid {
266                return Err(ParseError::InvalidIdentifier {
267                    name: name.to_string(),
268                    reason:
269                        "变量名和函数名必须使用全大写字母和下划线(例如:MY_VAR, CALCULATE_SUM)"
270                            .to_string(),
271                    line: self.current_line,
272                    column: self.current_column,
273                });
274            }
275        }
276
277        Ok(())
278    }
279
280    /// Get precedence of current token
281    fn current_precedence(&self) -> Precedence {
282        self.token_precedence(&self.current_token)
283    }
284
285    /// Get precedence of peek token
286    #[allow(dead_code)]
287    /// Get precedence of a token
288    fn token_precedence(&self, token: &Token) -> Precedence {
289        match token {
290            Token::Or => Precedence::Or,
291            Token::And => Precedence::And,
292            Token::Equal | Token::NotEqual => Precedence::Equals,
293            Token::Less | Token::LessEqual | Token::Greater | Token::GreaterEqual => {
294                Precedence::Comparison
295            }
296            Token::Plus | Token::Minus => Precedence::Sum,
297            Token::Multiply | Token::Divide | Token::Modulo => Precedence::Product,
298            Token::BitAnd => Precedence::BitAnd,
299            Token::BitOr => Precedence::BitOr,
300            Token::BitXor => Precedence::BitXor,
301            Token::Shl | Token::Shr => Precedence::Shift,
302            Token::LeftParen => Precedence::Call,
303            Token::LeftBracket => Precedence::Index,
304            _ => Precedence::Lowest,
305        }
306    }
307
308    /// Parse a complete program
309    pub fn parse_program(&mut self) -> Result<Program, ParseError> {
310        let mut statements = Vec::new();
311
312        self.skip_newlines();
313
314        while self.current_token != Token::EOF {
315            let line = self.stmt_start_line();
316            let stmt = self.parse_statement()?;
317            statements.push(located(line, stmt));
318            self.skip_newlines();
319        }
320
321        Ok(statements)
322    }
323
324    /// Parse a statement
325    fn parse_statement(&mut self) -> Result<Stmt, ParseError> {
326        match &self.current_token {
327            Token::Set => self.parse_set_statement(),
328            Token::Func => self.parse_func_definition(),
329            Token::Generator => self.parse_generator_definition(),
330            Token::Lazy => self.parse_lazy_definition(),
331            Token::Return => self.parse_return_statement(),
332            Token::Yield => self.parse_yield_statement(),
333            Token::Break => self.parse_break_statement(),
334            Token::Continue => self.parse_continue_statement(),
335            Token::While => self.parse_while_statement(),
336            Token::For => self.parse_for_statement(),
337            Token::Switch => self.parse_switch_statement(),
338            Token::Import => self.parse_import_statement(),
339            Token::Export => self.parse_export_statement(),
340            Token::Throw => self.parse_throw_statement(),
341            _ => self.parse_expression_statement(),
342        }
343    }
344
345    /// Parse: Set NAME value
346    fn parse_set_statement(&mut self) -> Result<Stmt, ParseError> {
347        self.next_token(); // skip 'Set'
348
349        // Parse the left-hand side (target)
350        // This can be either an identifier or an index expression
351        // We manually parse this to avoid consuming array literals as part of the target
352
353        let name = match &self.current_token {
354            Token::Identifier(n) => {
355                self.validate_identifier(n)?;
356                n.clone()
357            }
358            _ => {
359                return Err(ParseError::UnexpectedToken {
360                    expected: "identifier".to_string(),
361                    found: self.current_token.clone(),
362                    line: self.current_line,
363                    column: self.current_column,
364                });
365            }
366        };
367
368        self.next_token(); // move past identifier
369
370        // Check if followed by '[' for index access
371        // CRITICAL: Distinguish between:
372        // 1. Set NAME[index] value  -> index assignment (NO space before '[')
373        // 2. Set NAME [array]       -> array literal assignment (space before '[')
374        //
375        // We check if there was whitespace before the '[' token
376        if self.current_token == Token::LeftBracket {
377            // IMPORTANT: Check whitespace BEFORE calling next_token()
378            // because had_whitespace() reflects the whitespace before current_token
379            let has_space_before_bracket = self.current_had_whitespace;
380
381            if has_space_before_bracket {
382                // Space before '[' means this is: Set NAME [array_literal]
383                // Parse the whole thing as a value expression
384                let value = self.parse_expression(Precedence::Lowest)?;
385                if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
386                    self.next_token();
387                }
388                return Ok(Stmt::Set { name, value });
389            }
390
391            // No space before '[' means this is: Set NAME[index] value
392            // This is an index assignment
393            self.next_token(); // skip '['            // Parse the index expression
394            let index = self.parse_expression(Precedence::Lowest)?;
395
396            // Expect ']'
397            if self.current_token != Token::RightBracket {
398                return Err(ParseError::UnexpectedToken {
399                    expected: "']' for index access".to_string(),
400                    found: self.current_token.clone(),
401                    line: self.current_line,
402                    column: self.current_column,
403                });
404            }
405
406            self.next_token(); // skip ']'
407
408            // Now parse the value to assign
409            let value = self.parse_expression(Precedence::Lowest)?;
410
411            if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
412                self.next_token();
413            }
414
415            return Ok(Stmt::SetIndex {
416                object: Box::new(Expr::Identifier(name)),
417                index: Box::new(index),
418                value,
419            });
420        }
421
422        // Regular Set statement: Set NAME value
423        let value = self.parse_expression(Precedence::Lowest)?;
424
425        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
426            self.next_token();
427        }
428
429        Ok(Stmt::Set { name, value })
430    }
431
432    /// Parse: Func NAME (params) { body }
433    fn parse_func_definition(&mut self) -> Result<Stmt, ParseError> {
434        self.next_token(); // skip 'Func'
435
436        let name = match &self.current_token {
437            Token::Identifier(name) => {
438                // Validate function name
439                self.validate_identifier(name)?;
440                name.clone()
441            }
442            _ => {
443                return Err(ParseError::UnexpectedToken {
444                    expected: "identifier".to_string(),
445                    found: self.current_token.clone(),
446                    line: self.current_line,
447                    column: self.current_column,
448                });
449            }
450        };
451
452        self.next_token(); // move to '('
453        self.expect_token(Token::LeftParen)?;
454
455        let params = self.parse_parameter_list()?;
456
457        self.expect_token(Token::RightParen)?;
458        self.skip_newlines();
459        self.expect_token(Token::LeftBrace)?;
460
461        let body = self.parse_block()?;
462
463        self.expect_token(Token::RightBrace)?;
464
465        Ok(Stmt::FuncDef { name, params, body })
466    }
467
468    /// Parse: Generator NAME (params) { body }
469    fn parse_generator_definition(&mut self) -> Result<Stmt, ParseError> {
470        self.next_token(); // skip 'Generator'
471
472        let name = match &self.current_token {
473            Token::Identifier(name) => name.clone(),
474            _ => {
475                return Err(ParseError::UnexpectedToken {
476                    expected: "identifier".to_string(),
477                    found: self.current_token.clone(),
478                    line: self.current_line,
479                    column: self.current_column,
480                });
481            }
482        };
483
484        self.next_token();
485        self.expect_token(Token::LeftParen)?;
486
487        let params = self.parse_parameter_list()?;
488
489        self.expect_token(Token::RightParen)?;
490        self.skip_newlines();
491        self.expect_token(Token::LeftBrace)?;
492
493        let body = self.parse_block()?;
494
495        self.expect_token(Token::RightBrace)?;
496
497        Ok(Stmt::GeneratorDef { name, params, body })
498    }
499
500    /// Parse: Lazy NAME (expr)
501    fn parse_lazy_definition(&mut self) -> Result<Stmt, ParseError> {
502        self.next_token(); // skip 'Lazy'
503
504        let name = match &self.current_token {
505            Token::Identifier(name) => name.clone(),
506            _ => {
507                return Err(ParseError::UnexpectedToken {
508                    expected: "identifier".to_string(),
509                    found: self.current_token.clone(),
510                    line: self.current_line,
511                    column: self.current_column,
512                });
513            }
514        };
515
516        self.next_token();
517        self.expect_token(Token::LeftParen)?;
518
519        // 括号内允许换行书写长表达式(与函数调用的多行参数一致)
520        self.skip_newlines();
521        let expr = self.parse_expression(Precedence::Lowest)?;
522        self.skip_newlines();
523
524        self.expect_token(Token::RightParen)?;
525
526        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
527            self.next_token();
528        }
529
530        Ok(Stmt::LazyDef { name, expr })
531    }
532
533    /// Parse: Return expr
534    fn parse_return_statement(&mut self) -> Result<Stmt, ParseError> {
535        self.next_token(); // skip 'Return'
536
537        let expr =
538            if self.current_token == Token::Newline || self.current_token == Token::RightBrace {
539                Expr::Null
540            } else {
541                self.parse_expression(Precedence::Lowest)?
542            };
543
544        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
545            self.next_token();
546        }
547
548        Ok(Stmt::Return(expr))
549    }
550
551    /// Parse: Yield expr
552    fn parse_yield_statement(&mut self) -> Result<Stmt, ParseError> {
553        self.next_token(); // skip 'Yield'
554
555        let expr =
556            if self.current_token == Token::Newline || self.current_token == Token::RightBrace {
557                Expr::Null
558            } else {
559                self.parse_expression(Precedence::Lowest)?
560            };
561
562        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
563            self.next_token();
564        }
565
566        Ok(Stmt::Yield(expr))
567    }
568
569    /// Parse: Break
570    fn parse_break_statement(&mut self) -> Result<Stmt, ParseError> {
571        self.next_token(); // skip 'Break'
572
573        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
574            self.next_token();
575        }
576
577        Ok(Stmt::Break)
578    }
579
580    /// Parse: Continue
581    fn parse_continue_statement(&mut self) -> Result<Stmt, ParseError> {
582        self.next_token(); // skip 'Continue'
583
584        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
585            self.next_token();
586        }
587
588        Ok(Stmt::Continue)
589    }
590
591    /// Parse: While (condition) { body }
592    fn parse_while_statement(&mut self) -> Result<Stmt, ParseError> {
593        self.next_token(); // skip 'While'
594        self.expect_token(Token::LeftParen)?;
595
596        let condition = self.parse_expression(Precedence::Lowest)?;
597
598        self.expect_token(Token::RightParen)?;
599        self.skip_newlines();
600        self.expect_token(Token::LeftBrace)?;
601
602        let body = self.parse_block()?;
603
604        self.expect_token(Token::RightBrace)?;
605
606        Ok(Stmt::While { condition, body })
607    }
608
609    /// Parse: For VAR In ITERABLE { body }
610    fn parse_for_statement(&mut self) -> Result<Stmt, ParseError> {
611        self.next_token(); // skip 'For'
612
613        let first_var = match &self.current_token {
614            Token::Identifier(name) => name.clone(),
615            _ => {
616                return Err(ParseError::UnexpectedToken {
617                    expected: "identifier".to_string(),
618                    found: self.current_token.clone(),
619                    line: self.current_line,
620                    column: self.current_column,
621                });
622            }
623        };
624
625        self.next_token();
626
627        // Check for indexed for loop: For INDEX, VALUE In ...
628        if self.current_token == Token::Comma {
629            self.next_token(); // skip comma
630
631            let second_var = match &self.current_token {
632                Token::Identifier(name) => name.clone(),
633                _ => {
634                    return Err(ParseError::UnexpectedToken {
635                        expected: "identifier".to_string(),
636                        found: self.current_token.clone(),
637                        line: self.current_line,
638                        column: self.current_column,
639                    });
640                }
641            };
642
643            self.next_token();
644            self.expect_token(Token::In)?;
645
646            let iterable = self.parse_expression(Precedence::Lowest)?;
647
648            self.skip_newlines();
649            self.expect_token(Token::LeftBrace)?;
650
651            let body = self.parse_block()?;
652
653            self.expect_token(Token::RightBrace)?;
654
655            return Ok(Stmt::ForIndexed {
656                index_var: first_var,
657                value_var: second_var,
658                iterable,
659                body,
660            });
661        }
662
663        // Simple for loop: For VAR In ...
664        self.expect_token(Token::In)?;
665
666        let iterable = self.parse_expression(Precedence::Lowest)?;
667
668        self.skip_newlines();
669        self.expect_token(Token::LeftBrace)?;
670
671        let body = self.parse_block()?;
672
673        self.expect_token(Token::RightBrace)?;
674
675        Ok(Stmt::For {
676            var: first_var,
677            iterable,
678            body,
679        })
680    }
681
682    /// Parse: Switch (expr) { Case val: ... Default: ... }
683    fn parse_switch_statement(&mut self) -> Result<Stmt, ParseError> {
684        self.next_token(); // skip 'Switch'
685        self.expect_token(Token::LeftParen)?;
686
687        let expr = self.parse_expression(Precedence::Lowest)?;
688
689        self.expect_token(Token::RightParen)?;
690        self.skip_newlines();
691        self.expect_token(Token::LeftBrace)?;
692        self.skip_newlines();
693
694        let mut cases = Vec::new();
695        let mut default = None;
696
697        while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
698            if self.current_token == Token::Case {
699                self.next_token();
700                let case_expr = self.parse_expression(Precedence::Lowest)?;
701                self.expect_token(Token::Colon)?;
702                self.skip_newlines();
703
704                let mut case_body = Vec::new();
705                while self.current_token != Token::Case
706                    && self.current_token != Token::Default
707                    && self.current_token != Token::RightBrace
708                    && self.current_token != Token::EOF
709                {
710                    let line = self.stmt_start_line();
711                    let stmt = self.parse_statement()?;
712                    case_body.push(located(line, stmt));
713                    self.skip_newlines();
714                }
715
716                cases.push((case_expr, case_body));
717            } else if self.current_token == Token::Default {
718                self.next_token();
719                self.expect_token(Token::Colon)?;
720                self.skip_newlines();
721
722                let mut default_body = Vec::new();
723                while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
724                    let line = self.stmt_start_line();
725                    let stmt = self.parse_statement()?;
726                    default_body.push(located(line, stmt));
727                    self.skip_newlines();
728                }
729
730                default = Some(default_body);
731                break;
732            } else {
733                self.next_token();
734            }
735        }
736
737        self.expect_token(Token::RightBrace)?;
738
739        Ok(Stmt::Switch {
740            expr,
741            cases,
742            default,
743        })
744    }
745
746    /// Parse:
747    /// - Import {NAME1, NAME2} From "path"
748    /// - Import NAME As ALIAS From "path"
749    /// - Import NS From "path" (namespace import)
750    fn parse_import_statement(&mut self) -> Result<Stmt, ParseError> {
751        self.next_token(); // skip 'Import'
752
753        let mut names = Vec::new();
754        let mut aliases = Vec::new();
755        let mut namespace: Option<String> = None;
756
757        // Import {NAME1, NAME2, ...}
758        if self.current_token == Token::LeftBrace {
759            self.next_token();
760            self.skip_newlines();
761
762            while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
763                let name = match &self.current_token {
764                    Token::Identifier(n) => n.clone(),
765                    _ => {
766                        return Err(ParseError::UnexpectedToken {
767                            expected: "identifier".to_string(),
768                            found: self.current_token.clone(),
769                            line: self.current_line,
770                            column: self.current_column,
771                        });
772                    }
773                };
774
775                self.next_token();
776
777                // Check for alias: as ALIAS
778                let alias = if self.current_token == Token::As {
779                    self.next_token();
780                    if let Token::Identifier(a) = &self.current_token.clone() {
781                        let alias_name = a.clone();
782                        self.next_token();
783                        Some(alias_name)
784                    } else {
785                        None
786                    }
787                } else {
788                    None
789                };
790
791                names.push(name);
792                aliases.push(alias);
793
794                if self.current_token == Token::Comma {
795                    self.next_token();
796                    self.skip_newlines();
797                } else {
798                    break;
799                }
800            }
801
802            self.expect_token(Token::RightBrace)?;
803        } else {
804            // Import NAME ...
805            let name = match &self.current_token {
806                Token::Identifier(n) => n.clone(),
807                _ => {
808                    return Err(ParseError::UnexpectedToken {
809                        expected: "identifier".to_string(),
810                        found: self.current_token.clone(),
811                        line: self.current_line,
812                        column: self.current_column,
813                    });
814                }
815            };
816            self.next_token();
817
818            // If `As` present: named import with alias.
819            // Otherwise, if directly followed by `From`: namespace import.
820            if self.current_token == Token::As {
821                self.next_token();
822                let alias = if let Token::Identifier(a) = &self.current_token.clone() {
823                    let alias_name = a.clone();
824                    self.next_token();
825                    Some(alias_name)
826                } else {
827                    None
828                };
829                names.push(name);
830                aliases.push(alias);
831            } else {
832                // Namespace import
833                namespace = Some(name);
834            }
835        }
836
837        self.expect_token(Token::From)?;
838
839        let path = match &self.current_token {
840            Token::String(p) => p.clone(),
841            _ => {
842                return Err(ParseError::UnexpectedToken {
843                    expected: "string".to_string(),
844                    found: self.current_token.clone(),
845                    line: self.current_line,
846                    column: self.current_column,
847                });
848            }
849        };
850
851        self.next_token();
852
853        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
854            self.next_token();
855        }
856
857        Ok(Stmt::Import {
858            names,
859            path,
860            aliases,
861            namespace,
862        })
863    }
864
865    /// Parse: Export NAME
866    fn parse_export_statement(&mut self) -> Result<Stmt, ParseError> {
867        self.next_token(); // skip 'Export'
868
869        let name = match &self.current_token {
870            Token::Identifier(n) => n.clone(),
871            _ => {
872                return Err(ParseError::UnexpectedToken {
873                    expected: "identifier".to_string(),
874                    found: self.current_token.clone(),
875                    line: self.current_line,
876                    column: self.current_column,
877                });
878            }
879        };
880
881        self.next_token();
882
883        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
884            self.next_token();
885        }
886
887        Ok(Stmt::Export(name))
888    }
889
890    /// Parse: Throw expr
891    fn parse_throw_statement(&mut self) -> Result<Stmt, ParseError> {
892        self.next_token(); // skip 'Throw'
893
894        let expr = self.parse_expression(Precedence::Lowest)?;
895
896        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
897            self.next_token();
898        }
899
900        Ok(Stmt::Throw(expr))
901    }
902
903    /// Parse expression as statement
904    fn parse_expression_statement(&mut self) -> Result<Stmt, ParseError> {
905        let expr = self.parse_expression(Precedence::Lowest)?;
906
907        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
908            self.next_token();
909        }
910
911        Ok(Stmt::Expression(expr))
912    }
913
914    /// Parse parameter list: (A, B, C)
915    fn parse_parameter_list(&mut self) -> Result<Vec<String>, ParseError> {
916        let mut params = Vec::new();
917
918        if self.current_token == Token::RightParen {
919            return Ok(params);
920        }
921
922        while let Token::Identifier(name) = &self.current_token {
923            // Validate parameter name (allow flexible naming)
924            self.validate_identifier_internal(name, true)?;
925            params.push(name.clone());
926            self.next_token();
927
928            if self.current_token == Token::Comma {
929                self.next_token();
930            } else {
931                break;
932            }
933        }
934
935        Ok(params)
936    }
937
938    /// Parse a block of statements: { stmt1 stmt2 ... }
939    fn parse_block(&mut self) -> Result<Vec<Located>, ParseError> {
940        let mut statements = Vec::new();
941
942        self.skip_newlines();
943
944        while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
945            let line = self.stmt_start_line();
946            let stmt = self.parse_statement()?;
947            statements.push(located(line, stmt));
948            self.skip_newlines();
949        }
950
951        Ok(statements)
952    }
953
954    /// Parse an expression using Pratt parsing
955    fn parse_expression(&mut self, precedence: Precedence) -> Result<Expr, ParseError> {
956        let mut left = self.parse_prefix()?;
957
958        // After parse_prefix, current_token is at the first token after the prefix expression
959        while precedence < self.current_precedence()
960            && self.current_token != Token::Newline
961            && self.current_token != Token::Semicolon
962            && self.current_token != Token::EOF
963            && self.current_token != Token::RightParen
964            && self.current_token != Token::RightBracket
965            && self.current_token != Token::RightBrace
966            && self.current_token != Token::Comma
967            && self.current_token != Token::Colon
968        {
969            left = self.parse_infix(left)?;
970        }
971
972        Ok(left)
973    }
974
975    /// Parse prefix expressions
976    fn parse_prefix(&mut self) -> Result<Expr, ParseError> {
977        match &self.current_token.clone() {
978            Token::Number(n) => {
979                let num = *n;
980                self.next_token();
981                Ok(Expr::Number(num))
982            }
983            Token::BigInteger(s) => {
984                // 解析期一次性构造 BigInt,避免每次求值重复解析字符串
985                let big_int =
986                    num_bigint::BigInt::parse_bytes(s.as_bytes(), 10).ok_or_else(|| {
987                        ParseError::InvalidExpression {
988                            message: format!("Invalid big integer literal: {}", s),
989                            line: self.current_line,
990                            column: self.current_column,
991                        }
992                    })?;
993                self.next_token();
994                Ok(Expr::BigInteger(big_int))
995            }
996            Token::String(s) => {
997                let string = s.clone();
998                self.next_token();
999                Ok(Expr::String(string))
1000            }
1001            Token::Boolean(b) => {
1002                let bool_val = *b;
1003                self.next_token();
1004                Ok(Expr::Boolean(bool_val))
1005            }
1006            Token::Null => {
1007                self.next_token();
1008                Ok(Expr::Null)
1009            }
1010            Token::Identifier(name) => {
1011                let ident = name.clone();
1012                self.next_token();
1013                Ok(Expr::Identifier(ident))
1014            }
1015            Token::LeftParen => self.parse_grouped_expression(),
1016            Token::LeftBracket => self.parse_array_literal(),
1017            Token::LeftBrace => self.parse_dict_literal(),
1018            Token::Minus => self.parse_unary_expression(UnaryOp::Minus),
1019            Token::Not => self.parse_unary_expression(UnaryOp::Not),
1020            Token::If => self.parse_if_expression(),
1021            Token::Func => self.parse_lambda_expression(),
1022            Token::Lambda => self.parse_lambda_arrow_expression(),
1023            _ => Err(ParseError::InvalidExpression {
1024                message: "Unexpected token in expression".to_string(),
1025                line: self.current_line,
1026                column: self.current_column,
1027            }),
1028        }
1029    }
1030
1031    /// Parse infix expressions
1032    fn parse_infix(&mut self, left: Expr) -> Result<Expr, ParseError> {
1033        match &self.current_token {
1034            Token::Plus
1035            | Token::Minus
1036            | Token::Multiply
1037            | Token::Divide
1038            | Token::Modulo
1039            | Token::Equal
1040            | Token::NotEqual
1041            | Token::Less
1042            | Token::LessEqual
1043            | Token::Greater
1044            | Token::GreaterEqual
1045            | Token::And
1046            | Token::Or
1047            | Token::BitAnd
1048            | Token::BitOr
1049            | Token::BitXor
1050            | Token::Shl
1051            | Token::Shr => self.parse_binary_expression(left),
1052            Token::LeftParen => self.parse_call_expression(left),
1053            Token::LeftBracket => self.parse_index_expression(left),
1054            _ => Ok(left),
1055        }
1056    }
1057
1058    /// Parse grouped expression: (expr)
1059    fn parse_grouped_expression(&mut self) -> Result<Expr, ParseError> {
1060        self.next_token(); // skip '('
1061
1062        let expr = self.parse_expression(Precedence::Lowest)?;
1063
1064        // parse_expression returns with current_token at the first token after the expression
1065        // which should be ')'
1066        if self.current_token == Token::RightParen {
1067            self.next_token(); // move past ')'
1068            Ok(expr)
1069        } else {
1070            Err(ParseError::UnexpectedToken {
1071                expected: "RightParen".to_string(),
1072                found: self.current_token.clone(),
1073                line: self.current_line,
1074                column: self.current_column,
1075            })
1076        }
1077    }
1078    /// Parse array literal: [1, 2, 3]
1079    fn parse_array_literal(&mut self) -> Result<Expr, ParseError> {
1080        self.next_token(); // skip '['
1081
1082        let mut elements = Vec::new();
1083
1084        self.skip_newlines();
1085
1086        while self.current_token != Token::RightBracket && self.current_token != Token::EOF {
1087            elements.push(self.parse_expression(Precedence::Lowest)?);
1088
1089            self.skip_newlines();
1090
1091            if self.current_token == Token::Comma {
1092                self.next_token();
1093                self.skip_newlines();
1094            } else if self.current_token == Token::RightBracket {
1095                break;
1096            }
1097        }
1098
1099        self.expect_token(Token::RightBracket)?;
1100
1101        Ok(Expr::Array(elements))
1102    }
1103
1104    /// Parse dictionary literal: {key: value, ...}
1105    fn parse_dict_literal(&mut self) -> Result<Expr, ParseError> {
1106        self.next_token(); // skip '{'
1107
1108        let mut pairs = Vec::new();
1109
1110        self.skip_newlines();
1111
1112        while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
1113            let key = match &self.current_token {
1114                Token::Identifier(k) => k.clone(),
1115                Token::String(k) => k.clone(),
1116                _ => {
1117                    return Err(ParseError::UnexpectedToken {
1118                        expected: "identifier or string".to_string(),
1119                        found: self.current_token.clone(),
1120                        line: self.current_line,
1121                        column: self.current_column,
1122                    });
1123                }
1124            };
1125
1126            self.next_token();
1127            self.expect_token(Token::Colon)?;
1128
1129            let value = self.parse_expression(Precedence::Lowest)?;
1130
1131            pairs.push((key, value));
1132
1133            self.skip_newlines();
1134
1135            if self.current_token == Token::Comma {
1136                self.next_token();
1137                self.skip_newlines();
1138            } else if self.current_token == Token::RightBrace {
1139                break;
1140            }
1141        }
1142
1143        self.expect_token(Token::RightBrace)?;
1144
1145        Ok(Expr::Dict(pairs))
1146    }
1147
1148    /// Parse unary expression: -expr or !expr
1149    fn parse_unary_expression(&mut self, op: UnaryOp) -> Result<Expr, ParseError> {
1150        self.next_token(); // skip operator
1151
1152        let expr = self.parse_expression(Precedence::Prefix)?;
1153
1154        Ok(Expr::unary(op, expr))
1155    }
1156
1157    /// Parse binary expression: left op right
1158    fn parse_binary_expression(&mut self, left: Expr) -> Result<Expr, ParseError> {
1159        let op = match &self.current_token {
1160            Token::Plus => BinOp::Add,
1161            Token::Minus => BinOp::Subtract,
1162            Token::Multiply => BinOp::Multiply,
1163            Token::Divide => BinOp::Divide,
1164            Token::Modulo => BinOp::Modulo,
1165            Token::Equal => BinOp::Equal,
1166            Token::NotEqual => BinOp::NotEqual,
1167            Token::Less => BinOp::Less,
1168            Token::LessEqual => BinOp::LessEqual,
1169            Token::Greater => BinOp::Greater,
1170            Token::GreaterEqual => BinOp::GreaterEqual,
1171            Token::And => BinOp::And,
1172            Token::Or => BinOp::Or,
1173            Token::BitAnd => BinOp::BitAnd,
1174            Token::BitOr => BinOp::BitOr,
1175            Token::BitXor => BinOp::BitXor,
1176            Token::Shl => BinOp::Shl,
1177            Token::Shr => BinOp::Shr,
1178            _ => {
1179                return Err(ParseError::InvalidExpression {
1180                    message: "Invalid binary operator".to_string(),
1181                    line: self.current_line,
1182                    column: self.current_column,
1183                });
1184            }
1185        };
1186
1187        let precedence = self.current_precedence();
1188        self.next_token();
1189
1190        let right = self.parse_expression(precedence)?;
1191
1192        Ok(Expr::binary(left, op, right))
1193    }
1194
1195    /// Parse function call: func(arg1, arg2, ...)
1196    fn parse_call_expression(&mut self, func: Expr) -> Result<Expr, ParseError> {
1197        self.next_token(); // skip '('
1198
1199        let mut args = Vec::new();
1200
1201        self.skip_newlines();
1202
1203        while self.current_token != Token::RightParen && self.current_token != Token::EOF {
1204            args.push(self.parse_expression(Precedence::Lowest)?);
1205
1206            if self.current_token == Token::Comma {
1207                self.next_token();
1208                self.skip_newlines();
1209            } else {
1210                break;
1211            }
1212        }
1213
1214        self.expect_token(Token::RightParen)?;
1215
1216        Ok(Expr::call(func, args))
1217    }
1218
1219    /// Parse index expression: object[index]
1220    fn parse_index_expression(&mut self, object: Expr) -> Result<Expr, ParseError> {
1221        self.next_token(); // skip '['
1222
1223        let index = self.parse_expression(Precedence::Lowest)?;
1224
1225        self.expect_token(Token::RightBracket)?;
1226
1227        Ok(Expr::index(object, index))
1228    }
1229
1230    /// Parse if expression: If (cond) { ... } Elif (cond) { ... } Else { ... }
1231    fn parse_if_expression(&mut self) -> Result<Expr, ParseError> {
1232        self.next_token(); // skip 'If'
1233        self.expect_token(Token::LeftParen)?;
1234
1235        let condition = self.parse_expression(Precedence::Lowest)?;
1236
1237        self.expect_token(Token::RightParen)?;
1238        self.skip_newlines();
1239        self.expect_token(Token::LeftBrace)?;
1240
1241        let then_branch = self.parse_block()?;
1242
1243        self.expect_token(Token::RightBrace)?;
1244        self.skip_newlines();
1245
1246        let mut elif_branches = Vec::new();
1247        while self.current_token == Token::Elif {
1248            self.next_token();
1249            self.expect_token(Token::LeftParen)?;
1250
1251            let elif_cond = self.parse_expression(Precedence::Lowest)?;
1252
1253            self.expect_token(Token::RightParen)?;
1254            self.skip_newlines();
1255            self.expect_token(Token::LeftBrace)?;
1256
1257            let elif_body = self.parse_block()?;
1258
1259            self.expect_token(Token::RightBrace)?;
1260            self.skip_newlines();
1261
1262            elif_branches.push((elif_cond, elif_body));
1263        }
1264
1265        let else_branch = if self.current_token == Token::Else {
1266            self.next_token();
1267            self.skip_newlines();
1268            self.expect_token(Token::LeftBrace)?;
1269
1270            let else_body = self.parse_block()?;
1271
1272            self.expect_token(Token::RightBrace)?;
1273
1274            Some(else_body)
1275        } else {
1276            None
1277        };
1278
1279        Ok(Expr::If {
1280            condition: Box::new(condition),
1281            then_branch,
1282            elif_branches,
1283            else_branch,
1284        })
1285    }
1286
1287    /// Parse lambda expression: Func(params) { body }
1288    fn parse_lambda_expression(&mut self) -> Result<Expr, ParseError> {
1289        self.next_token(); // skip 'Func'
1290        self.expect_token(Token::LeftParen)?;
1291
1292        let params = self.parse_parameter_list()?;
1293
1294        self.expect_token(Token::RightParen)?;
1295        self.skip_newlines();
1296        self.expect_token(Token::LeftBrace)?;
1297
1298        let body = self.parse_block()?;
1299
1300        self.expect_token(Token::RightBrace)?;
1301
1302        Ok(Expr::Lambda { params, body })
1303    }
1304
1305    /// Parse lambda arrow expression: Lambda X -> expr or Lambda (X, Y) -> expr
1306    fn parse_lambda_arrow_expression(&mut self) -> Result<Expr, ParseError> {
1307        self.next_token(); // skip 'Lambda'
1308        let lambda_line = self.stmt_start_line();
1309
1310        let params = if self.current_token == Token::LeftParen {
1311            // Multiple parameters: Lambda (X, Y) -> expr
1312            self.next_token(); // skip '('
1313            let params = self.parse_parameter_list()?;
1314            self.expect_token(Token::RightParen)?;
1315            params
1316        } else {
1317            // Single parameter: Lambda X -> expr
1318            match &self.current_token {
1319                Token::Identifier(name) => {
1320                    self.validate_identifier_internal(name, true)?;
1321                    let param = name.clone();
1322                    self.next_token();
1323                    vec![param]
1324                }
1325                _ => {
1326                    return Err(ParseError::UnexpectedToken {
1327                        expected: "identifier or '('".to_string(),
1328                        found: self.current_token.clone(),
1329                        line: self.current_line,
1330                        column: self.current_column,
1331                    });
1332                }
1333            }
1334        };
1335
1336        // Expect arrow
1337        self.expect_token(Token::Arrow)?;
1338
1339        // Parse the expression body
1340        let expr = self.parse_expression(Precedence::Lowest)?;
1341
1342        // Wrap the expression in a Return statement
1343        // (行号取 Lambda 关键字所在行:表达式解析完后 peek 可能已扫到下一行)
1344        let body = vec![located(lambda_line, Stmt::Return(expr))];
1345
1346        Ok(Expr::Lambda { params, body })
1347    }
1348}