aether-azathoth 0.5.3

A lightweight, embeddable domain-specific language (DSL) interpreter with rich standard library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
// src/parser.rs
//! Parser for the Aether language
//!
//! Converts a stream of tokens into an Abstract Syntax Tree (AST)

use crate::ast::{BinOp, Expr, Program, Stmt, UnaryOp};
use crate::lexer::Lexer;
use crate::token::Token;

/// Parse errors with location information
#[derive(Debug, Clone, PartialEq)]
pub enum ParseError {
    UnexpectedToken {
        expected: String,
        found: Token,
        line: usize,
        column: usize,
    },
    UnexpectedEOF {
        line: usize,
        column: usize,
    },
    InvalidNumber(String),
    InvalidExpression {
        message: String,
        line: usize,
        column: usize,
    },
    InvalidStatement {
        message: String,
        line: usize,
        column: usize,
    },
    InvalidIdentifier {
        name: String,
        reason: String,
        line: usize,
        column: usize,
    },
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            ParseError::UnexpectedToken {
                expected,
                found,
                line,
                column,
            } => {
                write!(
                    f,
                    "Parse error at line {}, column {}: Expected {}, found {:?}",
                    line, column, expected, found
                )
            }
            ParseError::UnexpectedEOF { line, column } => {
                write!(
                    f,
                    "Parse error at line {}, column {}: Unexpected end of file",
                    line, column
                )
            }
            ParseError::InvalidNumber(s) => write!(f, "Parse error: Invalid number: {}", s),
            ParseError::InvalidExpression {
                message,
                line,
                column,
            } => {
                write!(
                    f,
                    "Parse error at line {}, column {}: Invalid expression - {}",
                    line, column, message
                )
            }
            ParseError::InvalidStatement {
                message,
                line,
                column,
            } => {
                write!(
                    f,
                    "Parse error at line {}, column {}: Invalid statement - {}",
                    line, column, message
                )
            }
            ParseError::InvalidIdentifier {
                name,
                reason,
                line,
                column,
            } => {
                write!(
                    f,
                    "Parse error at line {}, column {}: Invalid identifier '{}' - {}",
                    line, column, name, reason
                )
            }
        }
    }
}

impl std::error::Error for ParseError {}

/// Operator precedence (higher number = higher precedence)
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
enum Precedence {
    Lowest = 0,
    Or = 1,         // ||
    And = 2,        // &&
    Equals = 3,     // ==, !=
    Comparison = 4, // <, <=, >, >=
    Sum = 5,        // +, -
    Product = 6,    // *, /, %
    Prefix = 7,     // -, !
    Call = 8,       // func()
    Index = 9,      // array[index]
}

/// Parser state
pub struct Parser {
    lexer: Lexer,
    current_token: Token,
    peek_token: Token,
    current_line: usize,
    current_column: usize,
    current_had_whitespace: bool, // whether whitespace preceded current_token
    peek_had_whitespace: bool,    // whether whitespace preceded peek_token
}

impl Parser {
    /// Create a new parser from source code
    pub fn new(input: &str) -> Self {
        let mut lexer = Lexer::new(input);
        let current = lexer.next_token();
        let current_ws = lexer.had_whitespace();
        let peek = lexer.next_token();
        let peek_ws = lexer.had_whitespace();
        let line = lexer.line();
        let column = lexer.column();

        Parser {
            lexer,
            current_token: current,
            peek_token: peek,
            current_line: line,
            current_column: column,
            current_had_whitespace: current_ws,
            peek_had_whitespace: peek_ws,
        }
    }

    /// Advance to the next token
    fn next_token(&mut self) {
        self.current_token = self.peek_token.clone();
        self.current_had_whitespace = self.peek_had_whitespace;
        self.peek_token = self.lexer.next_token();
        self.peek_had_whitespace = self.lexer.had_whitespace();
        self.current_line = self.lexer.line();
        self.current_column = self.lexer.column();
    }

    /// Skip newline tokens (they're optional in many places)
    fn skip_newlines(&mut self) {
        while self.current_token == Token::Newline {
            self.next_token();
        }
    }

    /// Check if current token matches expected, advance if true
    fn expect_token(&mut self, expected: Token) -> Result<(), ParseError> {
        if self.current_token == expected {
            self.next_token();
            Ok(())
        } else {
            Err(ParseError::UnexpectedToken {
                expected: format!("{:?}", expected),
                found: self.current_token.clone(),
                line: self.current_line,
                column: self.current_column,
            })
        }
    }

    /// Helper to check if identifier follows naming convention (UPPER_SNAKE_CASE)
    fn validate_identifier(&self, name: &str) -> Result<(), ParseError> {
        self.validate_identifier_internal(name, false)
    }

    /// Helper to check if identifier follows naming convention
    /// For function parameters, we allow more flexible naming (can use lowercase)
    fn validate_identifier_internal(&self, name: &str, is_param: bool) -> Result<(), ParseError> {
        // Check it doesn't start with a number
        if name.chars().next().is_some_and(|c| c.is_numeric()) {
            return Err(ParseError::InvalidIdentifier {
                name: name.to_string(),
                reason: "标识符不能以数字开头".to_string(),
                line: self.current_line,
                column: self.current_column,
            });
        }

        // For function parameters, allow lowercase letters
        if is_param {
            let is_valid = name
                .chars()
                .all(|c| c.is_alphabetic() || c.is_numeric() || c == '_');

            if !is_valid {
                return Err(ParseError::InvalidIdentifier {
                    name: name.to_string(),
                    reason: "参数名只能包含字母、数字和下划线".to_string(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        } else {
            // For variables and function names, require uppercase
            let is_valid = name
                .chars()
                .all(|c| c.is_uppercase() || c.is_numeric() || c == '_');

            if !is_valid {
                return Err(ParseError::InvalidIdentifier {
                    name: name.to_string(),
                    reason:
                        "变量名和函数名必须使用全大写字母和下划线(例如:MY_VAR, CALCULATE_SUM)"
                            .to_string(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        }

        Ok(())
    }

    /// Get precedence of current token
    fn current_precedence(&self) -> Precedence {
        self.token_precedence(&self.current_token)
    }

    /// Get precedence of peek token
    #[allow(dead_code)]
    fn peek_precedence(&self) -> Precedence {
        self.token_precedence(&self.peek_token)
    }

    /// Get precedence of a token
    fn token_precedence(&self, token: &Token) -> Precedence {
        match token {
            Token::Or => Precedence::Or,
            Token::And => Precedence::And,
            Token::Equal | Token::NotEqual => Precedence::Equals,
            Token::Less | Token::LessEqual | Token::Greater | Token::GreaterEqual => {
                Precedence::Comparison
            }
            Token::Plus | Token::Minus => Precedence::Sum,
            Token::Multiply | Token::Divide | Token::Modulo => Precedence::Product,
            Token::LeftParen => Precedence::Call,
            Token::LeftBracket => Precedence::Index,
            _ => Precedence::Lowest,
        }
    }

    /// Parse a complete program
    pub fn parse_program(&mut self) -> Result<Program, ParseError> {
        let mut statements = Vec::new();

        self.skip_newlines();

        while self.current_token != Token::EOF {
            let stmt = self.parse_statement()?;
            statements.push(stmt);
            self.skip_newlines();
        }

        Ok(statements)
    }

    /// Parse a statement
    fn parse_statement(&mut self) -> Result<Stmt, ParseError> {
        match &self.current_token {
            Token::Set => self.parse_set_statement(),
            Token::Func => self.parse_func_definition(),
            Token::Generator => self.parse_generator_definition(),
            Token::Lazy => self.parse_lazy_definition(),
            Token::Return => self.parse_return_statement(),
            Token::Yield => self.parse_yield_statement(),
            Token::Break => self.parse_break_statement(),
            Token::Continue => self.parse_continue_statement(),
            Token::While => self.parse_while_statement(),
            Token::For => self.parse_for_statement(),
            Token::Switch => self.parse_switch_statement(),
            Token::Import => self.parse_import_statement(),
            Token::Export => self.parse_export_statement(),
            Token::Throw => self.parse_throw_statement(),
            _ => self.parse_expression_statement(),
        }
    }

    /// Parse: Set NAME value
    fn parse_set_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Set'

        // Parse the left-hand side (target)
        // This can be either an identifier or an index expression
        // We manually parse this to avoid consuming array literals as part of the target

        let name = match &self.current_token {
            Token::Identifier(n) => {
                self.validate_identifier(n)?;
                n.clone()
            }
            _ => {
                return Err(ParseError::UnexpectedToken {
                    expected: "identifier".to_string(),
                    found: self.current_token.clone(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        };

        self.next_token(); // move past identifier

        // Check if followed by '[' for index access
        // CRITICAL: Distinguish between:
        // 1. Set NAME[index] value  -> index assignment (NO space before '[')
        // 2. Set NAME [array]       -> array literal assignment (space before '[')
        //
        // We check if there was whitespace before the '[' token
        if self.current_token == Token::LeftBracket {
            // IMPORTANT: Check whitespace BEFORE calling next_token()
            // because had_whitespace() reflects the whitespace before current_token
            let has_space_before_bracket = self.current_had_whitespace;

            if has_space_before_bracket {
                // Space before '[' means this is: Set NAME [array_literal]
                // Parse the whole thing as a value expression
                let value = self.parse_expression(Precedence::Lowest)?;
                if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
                    self.next_token();
                }
                return Ok(Stmt::Set { name, value });
            }

            // No space before '[' means this is: Set NAME[index] value
            // This is an index assignment
            self.next_token(); // skip '['            // Parse the index expression
            let index = self.parse_expression(Precedence::Lowest)?;

            // Expect ']'
            if self.current_token != Token::RightBracket {
                return Err(ParseError::UnexpectedToken {
                    expected: "']' for index access".to_string(),
                    found: self.current_token.clone(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }

            self.next_token(); // skip ']'

            // Now parse the value to assign
            let value = self.parse_expression(Precedence::Lowest)?;

            if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
                self.next_token();
            }

            return Ok(Stmt::SetIndex {
                object: Box::new(Expr::Identifier(name)),
                index: Box::new(index),
                value,
            });
        }

        // Regular Set statement: Set NAME value
        let value = self.parse_expression(Precedence::Lowest)?;

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::Set { name, value })
    }

    /// Parse: Func NAME (params) { body }
    fn parse_func_definition(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Func'

        let name = match &self.current_token {
            Token::Identifier(name) => {
                // Validate function name
                self.validate_identifier(name)?;
                name.clone()
            }
            _ => {
                return Err(ParseError::UnexpectedToken {
                    expected: "identifier".to_string(),
                    found: self.current_token.clone(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        };

        self.next_token(); // move to '('
        self.expect_token(Token::LeftParen)?;

        let params = self.parse_parameter_list()?;

        self.expect_token(Token::RightParen)?;
        self.skip_newlines();
        self.expect_token(Token::LeftBrace)?;

        let body = self.parse_block()?;

        self.expect_token(Token::RightBrace)?;

        Ok(Stmt::FuncDef { name, params, body })
    }

    /// Parse: Generator NAME (params) { body }
    fn parse_generator_definition(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Generator'

        let name = match &self.current_token {
            Token::Identifier(name) => name.clone(),
            _ => {
                return Err(ParseError::UnexpectedToken {
                    expected: "identifier".to_string(),
                    found: self.current_token.clone(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        };

        self.next_token();
        self.expect_token(Token::LeftParen)?;

        let params = self.parse_parameter_list()?;

        self.expect_token(Token::RightParen)?;
        self.skip_newlines();
        self.expect_token(Token::LeftBrace)?;

        let body = self.parse_block()?;

        self.expect_token(Token::RightBrace)?;

        Ok(Stmt::GeneratorDef { name, params, body })
    }

    /// Parse: Lazy NAME (expr)
    fn parse_lazy_definition(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Lazy'

        let name = match &self.current_token {
            Token::Identifier(name) => name.clone(),
            _ => {
                return Err(ParseError::UnexpectedToken {
                    expected: "identifier".to_string(),
                    found: self.current_token.clone(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        };

        self.next_token();
        self.expect_token(Token::LeftParen)?;

        let expr = self.parse_expression(Precedence::Lowest)?;

        self.expect_token(Token::RightParen)?;

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::LazyDef { name, expr })
    }

    /// Parse: Return expr
    fn parse_return_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Return'

        let expr =
            if self.current_token == Token::Newline || self.current_token == Token::RightBrace {
                Expr::Null
            } else {
                self.parse_expression(Precedence::Lowest)?
            };

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::Return(expr))
    }

    /// Parse: Yield expr
    fn parse_yield_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Yield'

        let expr =
            if self.current_token == Token::Newline || self.current_token == Token::RightBrace {
                Expr::Null
            } else {
                self.parse_expression(Precedence::Lowest)?
            };

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::Yield(expr))
    }

    /// Parse: Break
    fn parse_break_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Break'

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::Break)
    }

    /// Parse: Continue
    fn parse_continue_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Continue'

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::Continue)
    }

    /// Parse: While (condition) { body }
    fn parse_while_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'While'
        self.expect_token(Token::LeftParen)?;

        let condition = self.parse_expression(Precedence::Lowest)?;

        self.expect_token(Token::RightParen)?;
        self.skip_newlines();
        self.expect_token(Token::LeftBrace)?;

        let body = self.parse_block()?;

        self.expect_token(Token::RightBrace)?;

        Ok(Stmt::While { condition, body })
    }

    /// Parse: For VAR In ITERABLE { body }
    fn parse_for_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'For'

        let first_var = match &self.current_token {
            Token::Identifier(name) => name.clone(),
            _ => {
                return Err(ParseError::UnexpectedToken {
                    expected: "identifier".to_string(),
                    found: self.current_token.clone(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        };

        self.next_token();

        // Check for indexed for loop: For INDEX, VALUE In ...
        if self.current_token == Token::Comma {
            self.next_token(); // skip comma

            let second_var = match &self.current_token {
                Token::Identifier(name) => name.clone(),
                _ => {
                    return Err(ParseError::UnexpectedToken {
                        expected: "identifier".to_string(),
                        found: self.current_token.clone(),
                        line: self.current_line,
                        column: self.current_column,
                    });
                }
            };

            self.next_token();
            self.expect_token(Token::In)?;

            let iterable = self.parse_expression(Precedence::Lowest)?;

            self.skip_newlines();
            self.expect_token(Token::LeftBrace)?;

            let body = self.parse_block()?;

            self.expect_token(Token::RightBrace)?;

            return Ok(Stmt::ForIndexed {
                index_var: first_var,
                value_var: second_var,
                iterable,
                body,
            });
        }

        // Simple for loop: For VAR In ...
        self.expect_token(Token::In)?;

        let iterable = self.parse_expression(Precedence::Lowest)?;

        self.skip_newlines();
        self.expect_token(Token::LeftBrace)?;

        let body = self.parse_block()?;

        self.expect_token(Token::RightBrace)?;

        Ok(Stmt::For {
            var: first_var,
            iterable,
            body,
        })
    }

    /// Parse: Switch (expr) { Case val: ... Default: ... }
    fn parse_switch_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Switch'
        self.expect_token(Token::LeftParen)?;

        let expr = self.parse_expression(Precedence::Lowest)?;

        self.expect_token(Token::RightParen)?;
        self.skip_newlines();
        self.expect_token(Token::LeftBrace)?;
        self.skip_newlines();

        let mut cases = Vec::new();
        let mut default = None;

        while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
            if self.current_token == Token::Case {
                self.next_token();
                let case_expr = self.parse_expression(Precedence::Lowest)?;
                self.expect_token(Token::Colon)?;
                self.skip_newlines();

                let mut case_body = Vec::new();
                while self.current_token != Token::Case
                    && self.current_token != Token::Default
                    && self.current_token != Token::RightBrace
                    && self.current_token != Token::EOF
                {
                    case_body.push(self.parse_statement()?);
                    self.skip_newlines();
                }

                cases.push((case_expr, case_body));
            } else if self.current_token == Token::Default {
                self.next_token();
                self.expect_token(Token::Colon)?;
                self.skip_newlines();

                let mut default_body = Vec::new();
                while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
                    default_body.push(self.parse_statement()?);
                    self.skip_newlines();
                }

                default = Some(default_body);
                break;
            } else {
                self.next_token();
            }
        }

        self.expect_token(Token::RightBrace)?;

        Ok(Stmt::Switch {
            expr,
            cases,
            default,
        })
    }

    /// Parse:
    /// - Import {NAME1, NAME2} From "path"
    /// - Import NAME As ALIAS From "path"
    /// - Import NS From "path" (namespace import)
    fn parse_import_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Import'

        let mut names = Vec::new();
        let mut aliases = Vec::new();
        let mut namespace: Option<String> = None;

        // Import {NAME1, NAME2, ...}
        if self.current_token == Token::LeftBrace {
            self.next_token();
            self.skip_newlines();

            while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
                let name = match &self.current_token {
                    Token::Identifier(n) => n.clone(),
                    _ => {
                        return Err(ParseError::UnexpectedToken {
                            expected: "identifier".to_string(),
                            found: self.current_token.clone(),
                            line: self.current_line,
                            column: self.current_column,
                        });
                    }
                };

                self.next_token();

                // Check for alias: as ALIAS
                let alias = if self.current_token == Token::As {
                    self.next_token();
                    if let Token::Identifier(a) = &self.current_token.clone() {
                        let alias_name = a.clone();
                        self.next_token();
                        Some(alias_name)
                    } else {
                        None
                    }
                } else {
                    None
                };

                names.push(name);
                aliases.push(alias);

                if self.current_token == Token::Comma {
                    self.next_token();
                    self.skip_newlines();
                } else {
                    break;
                }
            }

            self.expect_token(Token::RightBrace)?;
        } else {
            // Import NAME ...
            let name = match &self.current_token {
                Token::Identifier(n) => n.clone(),
                _ => {
                    return Err(ParseError::UnexpectedToken {
                        expected: "identifier".to_string(),
                        found: self.current_token.clone(),
                        line: self.current_line,
                        column: self.current_column,
                    });
                }
            };
            self.next_token();

            // If `As` present: named import with alias.
            // Otherwise, if directly followed by `From`: namespace import.
            if self.current_token == Token::As {
                self.next_token();
                let alias = if let Token::Identifier(a) = &self.current_token.clone() {
                    let alias_name = a.clone();
                    self.next_token();
                    Some(alias_name)
                } else {
                    None
                };
                names.push(name);
                aliases.push(alias);
            } else {
                // Namespace import
                namespace = Some(name);
            }
        }

        self.expect_token(Token::From)?;

        let path = match &self.current_token {
            Token::String(p) => p.clone(),
            _ => {
                return Err(ParseError::UnexpectedToken {
                    expected: "string".to_string(),
                    found: self.current_token.clone(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        };

        self.next_token();

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::Import {
            names,
            path,
            aliases,
            namespace,
        })
    }

    /// Parse: Export NAME
    fn parse_export_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Export'

        let name = match &self.current_token {
            Token::Identifier(n) => n.clone(),
            _ => {
                return Err(ParseError::UnexpectedToken {
                    expected: "identifier".to_string(),
                    found: self.current_token.clone(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        };

        self.next_token();

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::Export(name))
    }

    /// Parse: Throw expr
    fn parse_throw_statement(&mut self) -> Result<Stmt, ParseError> {
        self.next_token(); // skip 'Throw'

        let expr = self.parse_expression(Precedence::Lowest)?;

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::Throw(expr))
    }

    /// Parse expression as statement
    fn parse_expression_statement(&mut self) -> Result<Stmt, ParseError> {
        let expr = self.parse_expression(Precedence::Lowest)?;

        if self.current_token == Token::Newline || self.current_token == Token::Semicolon {
            self.next_token();
        }

        Ok(Stmt::Expression(expr))
    }

    /// Parse parameter list: (A, B, C)
    fn parse_parameter_list(&mut self) -> Result<Vec<String>, ParseError> {
        let mut params = Vec::new();

        if self.current_token == Token::RightParen {
            return Ok(params);
        }

        while let Token::Identifier(name) = &self.current_token {
            // Validate parameter name (allow flexible naming)
            self.validate_identifier_internal(name, true)?;
            params.push(name.clone());
            self.next_token();

            if self.current_token == Token::Comma {
                self.next_token();
            } else {
                break;
            }
        }

        Ok(params)
    }

    /// Parse a block of statements: { stmt1 stmt2 ... }
    fn parse_block(&mut self) -> Result<Vec<Stmt>, ParseError> {
        let mut statements = Vec::new();

        self.skip_newlines();

        while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
            statements.push(self.parse_statement()?);
            self.skip_newlines();
        }

        Ok(statements)
    }

    /// Parse an expression using Pratt parsing
    fn parse_expression(&mut self, precedence: Precedence) -> Result<Expr, ParseError> {
        let mut left = self.parse_prefix()?;

        // After parse_prefix, current_token is at the first token after the prefix expression
        while precedence < self.current_precedence()
            && self.current_token != Token::Newline
            && self.current_token != Token::Semicolon
            && self.current_token != Token::EOF
            && self.current_token != Token::RightParen
            && self.current_token != Token::RightBracket
            && self.current_token != Token::RightBrace
            && self.current_token != Token::Comma
            && self.current_token != Token::Colon
        {
            left = self.parse_infix(left)?;
        }

        Ok(left)
    }

    /// Parse prefix expressions
    fn parse_prefix(&mut self) -> Result<Expr, ParseError> {
        match &self.current_token.clone() {
            Token::Number(n) => {
                let num = *n;
                self.next_token();
                Ok(Expr::Number(num))
            }
            Token::BigInteger(s) => {
                let big_int_str = s.clone();
                self.next_token();
                Ok(Expr::BigInteger(big_int_str))
            }
            Token::String(s) => {
                let string = s.clone();
                self.next_token();
                Ok(Expr::String(string))
            }
            Token::Boolean(b) => {
                let bool_val = *b;
                self.next_token();
                Ok(Expr::Boolean(bool_val))
            }
            Token::Null => {
                self.next_token();
                Ok(Expr::Null)
            }
            Token::Identifier(name) => {
                let ident = name.clone();
                self.next_token();
                Ok(Expr::Identifier(ident))
            }
            Token::LeftParen => self.parse_grouped_expression(),
            Token::LeftBracket => self.parse_array_literal(),
            Token::LeftBrace => self.parse_dict_literal(),
            Token::Minus => self.parse_unary_expression(UnaryOp::Minus),
            Token::Not => self.parse_unary_expression(UnaryOp::Not),
            Token::If => self.parse_if_expression(),
            Token::Func => self.parse_lambda_expression(),
            Token::Lambda => self.parse_lambda_arrow_expression(),
            _ => Err(ParseError::InvalidExpression {
                message: "Unexpected token in expression".to_string(),
                line: self.current_line,
                column: self.current_column,
            }),
        }
    }

    /// Parse infix expressions
    fn parse_infix(&mut self, left: Expr) -> Result<Expr, ParseError> {
        match &self.current_token {
            Token::Plus
            | Token::Minus
            | Token::Multiply
            | Token::Divide
            | Token::Modulo
            | Token::Equal
            | Token::NotEqual
            | Token::Less
            | Token::LessEqual
            | Token::Greater
            | Token::GreaterEqual
            | Token::And
            | Token::Or => self.parse_binary_expression(left),
            Token::LeftParen => self.parse_call_expression(left),
            Token::LeftBracket => self.parse_index_expression(left),
            _ => Ok(left),
        }
    }

    /// Parse grouped expression: (expr)
    fn parse_grouped_expression(&mut self) -> Result<Expr, ParseError> {
        self.next_token(); // skip '('

        let expr = self.parse_expression(Precedence::Lowest)?;

        // parse_expression returns with current_token at the first token after the expression
        // which should be ')'
        if self.current_token == Token::RightParen {
            self.next_token(); // move past ')'
            Ok(expr)
        } else {
            Err(ParseError::UnexpectedToken {
                expected: "RightParen".to_string(),
                found: self.current_token.clone(),
                line: self.current_line,
                column: self.current_column,
            })
        }
    }
    /// Parse array literal: [1, 2, 3]
    fn parse_array_literal(&mut self) -> Result<Expr, ParseError> {
        self.next_token(); // skip '['

        let mut elements = Vec::new();

        self.skip_newlines();

        while self.current_token != Token::RightBracket && self.current_token != Token::EOF {
            elements.push(self.parse_expression(Precedence::Lowest)?);

            self.skip_newlines();

            if self.current_token == Token::Comma {
                self.next_token();
                self.skip_newlines();
            } else if self.current_token == Token::RightBracket {
                break;
            }
        }

        self.expect_token(Token::RightBracket)?;

        Ok(Expr::Array(elements))
    }

    /// Parse dictionary literal: {key: value, ...}
    fn parse_dict_literal(&mut self) -> Result<Expr, ParseError> {
        self.next_token(); // skip '{'

        let mut pairs = Vec::new();

        self.skip_newlines();

        while self.current_token != Token::RightBrace && self.current_token != Token::EOF {
            let key = match &self.current_token {
                Token::Identifier(k) => k.clone(),
                Token::String(k) => k.clone(),
                _ => {
                    return Err(ParseError::UnexpectedToken {
                        expected: "identifier or string".to_string(),
                        found: self.current_token.clone(),
                        line: self.current_line,
                        column: self.current_column,
                    });
                }
            };

            self.next_token();
            self.expect_token(Token::Colon)?;

            let value = self.parse_expression(Precedence::Lowest)?;

            pairs.push((key, value));

            self.skip_newlines();

            if self.current_token == Token::Comma {
                self.next_token();
                self.skip_newlines();
            } else if self.current_token == Token::RightBrace {
                break;
            }
        }

        self.expect_token(Token::RightBrace)?;

        Ok(Expr::Dict(pairs))
    }

    /// Parse unary expression: -expr or !expr
    fn parse_unary_expression(&mut self, op: UnaryOp) -> Result<Expr, ParseError> {
        self.next_token(); // skip operator

        let expr = self.parse_expression(Precedence::Prefix)?;

        Ok(Expr::unary(op, expr))
    }

    /// Parse binary expression: left op right
    fn parse_binary_expression(&mut self, left: Expr) -> Result<Expr, ParseError> {
        let op = match &self.current_token {
            Token::Plus => BinOp::Add,
            Token::Minus => BinOp::Subtract,
            Token::Multiply => BinOp::Multiply,
            Token::Divide => BinOp::Divide,
            Token::Modulo => BinOp::Modulo,
            Token::Equal => BinOp::Equal,
            Token::NotEqual => BinOp::NotEqual,
            Token::Less => BinOp::Less,
            Token::LessEqual => BinOp::LessEqual,
            Token::Greater => BinOp::Greater,
            Token::GreaterEqual => BinOp::GreaterEqual,
            Token::And => BinOp::And,
            Token::Or => BinOp::Or,
            _ => {
                return Err(ParseError::InvalidExpression {
                    message: "Invalid binary operator".to_string(),
                    line: self.current_line,
                    column: self.current_column,
                });
            }
        };

        let precedence = self.current_precedence();
        self.next_token();

        let right = self.parse_expression(precedence)?;

        Ok(Expr::binary(left, op, right))
    }

    /// Parse function call: func(arg1, arg2, ...)
    fn parse_call_expression(&mut self, func: Expr) -> Result<Expr, ParseError> {
        self.next_token(); // skip '('

        let mut args = Vec::new();

        self.skip_newlines();

        while self.current_token != Token::RightParen && self.current_token != Token::EOF {
            args.push(self.parse_expression(Precedence::Lowest)?);

            if self.current_token == Token::Comma {
                self.next_token();
                self.skip_newlines();
            } else {
                break;
            }
        }

        self.expect_token(Token::RightParen)?;

        Ok(Expr::call(func, args))
    }

    /// Parse index expression: object[index]
    fn parse_index_expression(&mut self, object: Expr) -> Result<Expr, ParseError> {
        self.next_token(); // skip '['

        let index = self.parse_expression(Precedence::Lowest)?;

        self.expect_token(Token::RightBracket)?;

        Ok(Expr::index(object, index))
    }

    /// Parse if expression: If (cond) { ... } Elif (cond) { ... } Else { ... }
    fn parse_if_expression(&mut self) -> Result<Expr, ParseError> {
        self.next_token(); // skip 'If'
        self.expect_token(Token::LeftParen)?;

        let condition = self.parse_expression(Precedence::Lowest)?;

        self.expect_token(Token::RightParen)?;
        self.skip_newlines();
        self.expect_token(Token::LeftBrace)?;

        let then_branch = self.parse_block()?;

        self.expect_token(Token::RightBrace)?;
        self.skip_newlines();

        let mut elif_branches = Vec::new();
        while self.current_token == Token::Elif {
            self.next_token();
            self.expect_token(Token::LeftParen)?;

            let elif_cond = self.parse_expression(Precedence::Lowest)?;

            self.expect_token(Token::RightParen)?;
            self.skip_newlines();
            self.expect_token(Token::LeftBrace)?;

            let elif_body = self.parse_block()?;

            self.expect_token(Token::RightBrace)?;
            self.skip_newlines();

            elif_branches.push((elif_cond, elif_body));
        }

        let else_branch = if self.current_token == Token::Else {
            self.next_token();
            self.skip_newlines();
            self.expect_token(Token::LeftBrace)?;

            let else_body = self.parse_block()?;

            self.expect_token(Token::RightBrace)?;

            Some(else_body)
        } else {
            None
        };

        Ok(Expr::If {
            condition: Box::new(condition),
            then_branch,
            elif_branches,
            else_branch,
        })
    }

    /// Parse lambda expression: Func(params) { body }
    fn parse_lambda_expression(&mut self) -> Result<Expr, ParseError> {
        self.next_token(); // skip 'Func'
        self.expect_token(Token::LeftParen)?;

        let params = self.parse_parameter_list()?;

        self.expect_token(Token::RightParen)?;
        self.skip_newlines();
        self.expect_token(Token::LeftBrace)?;

        let body = self.parse_block()?;

        self.expect_token(Token::RightBrace)?;

        Ok(Expr::Lambda { params, body })
    }

    /// Parse lambda arrow expression: Lambda X -> expr or Lambda (X, Y) -> expr
    fn parse_lambda_arrow_expression(&mut self) -> Result<Expr, ParseError> {
        self.next_token(); // skip 'Lambda'

        let params = if self.current_token == Token::LeftParen {
            // Multiple parameters: Lambda (X, Y) -> expr
            self.next_token(); // skip '('
            let params = self.parse_parameter_list()?;
            self.expect_token(Token::RightParen)?;
            params
        } else {
            // Single parameter: Lambda X -> expr
            match &self.current_token {
                Token::Identifier(name) => {
                    self.validate_identifier_internal(name, true)?;
                    let param = name.clone();
                    self.next_token();
                    vec![param]
                }
                _ => {
                    return Err(ParseError::UnexpectedToken {
                        expected: "identifier or '('".to_string(),
                        found: self.current_token.clone(),
                        line: self.current_line,
                        column: self.current_column,
                    });
                }
            }
        };

        // Expect arrow
        self.expect_token(Token::Arrow)?;

        // Parse the expression body
        let expr = self.parse_expression(Precedence::Lowest)?;

        // Wrap the expression in a Return statement
        let body = vec![Stmt::Return(expr)];

        Ok(Expr::Lambda { params, body })
    }
}