TypeScript_Rust_Compiler/
parser.rs

1//! Parser for TypeScript code using nom parser combinators
2
3use crate::ast::*;
4use crate::error::{CompilerError, Result};
5use crate::lexer::{Token, Keyword};
6
7/// Parser for TypeScript code
8pub struct Parser {
9    tokens: Vec<Token>,
10    position: usize,
11}
12
13impl Parser {
14    /// Create a new parser
15    pub fn new(tokens: Vec<Token>) -> Self {
16        Self {
17            tokens,
18            position: 0,
19        }
20    }
21
22    /// Parse the tokens into an AST
23    pub fn parse(&mut self) -> Result<Program> {
24        let mut statements = Vec::new();
25        let mut iterations = 0;
26        let max_iterations = self.tokens.len() * 2; // Prevent infinite loops
27        let mut errors = Vec::new();
28
29        while self.position < self.tokens.len() && iterations < max_iterations {
30            let old_position = self.position;
31
32            match self.parse_statement() {
33                Ok(Some(statement)) => {
34                    statements.push(statement);
35                }
36                Ok(None) => {
37                    break;
38                }
39                Err(error) => {
40                    // Log error but continue parsing
41                    errors.push(error);
42                    // Skip current token and continue
43                    self.advance();
44                }
45            }
46            
47            // Check if we made progress
48            if self.position == old_position {
49                // No progress made, advance position to prevent infinite loop
50                self.position += 1;
51            }
52            
53            // If we encounter an error, try to recover by skipping tokens
54            if self.position < self.tokens.len() {
55                let current_token = &self.tokens[self.position];
56                if matches!(current_token, Token::EOF) {
57                    break;
58                }
59            }
60            
61            iterations += 1;
62        }
63
64        if iterations >= max_iterations {
65            return Err(CompilerError::parse_error(
66                self.position,
67                1,
68                "Parser stuck in infinite loop".to_string(),
69            ));
70        }
71
72        // If we have statements, return them even if there were errors
73        if !statements.is_empty() {
74            Ok(Program { statements })
75        } else if !errors.is_empty() {
76            // If no statements but we have errors, return the first error
77            Err(errors.into_iter().next().unwrap())
78        } else {
79            Ok(Program { statements })
80        }
81    }
82
83    /// Parse a statement
84    fn parse_statement(&mut self) -> Result<Option<Statement>> {
85        if self.position >= self.tokens.len() {
86            return Ok(None);
87        }
88
89        // Check if we've reached EOF
90        if self.current_token() == &Token::EOF {
91            return Ok(None);
92        }
93
94        let token = &self.tokens[self.position];
95
96        let statement = match token {
97            Token::EOF => return Ok(None),
98            Token::Keyword(keyword) => match keyword {
99                crate::lexer::Keyword::Let
100                | crate::lexer::Keyword::Var => self.parse_variable_declaration()?,
101                crate::lexer::Keyword::Const => {
102                    // Check if this is "const enum"
103                    if self.position + 1 < self.tokens.len() {
104                        if let Token::Keyword(crate::lexer::Keyword::Enum) = &self.tokens[self.position + 1] {
105                            // This is "const enum", parse as enum declaration
106                            self.parse_const_enum_declaration()?
107                        } else {
108                            // This is regular "const", parse as variable declaration
109                            self.parse_variable_declaration()?
110                        }
111                    } else {
112                        self.parse_variable_declaration()?
113                    }
114                },
115                crate::lexer::Keyword::Function => self.parse_function_declaration()?,
116                crate::lexer::Keyword::Class => self.parse_class_declaration()?,
117                crate::lexer::Keyword::Interface => self.parse_interface_declaration()?,
118                crate::lexer::Keyword::Type => self.parse_type_alias()?,
119                crate::lexer::Keyword::Enum => self.parse_enum_declaration()?,
120                crate::lexer::Keyword::Import => self.parse_import_declaration()?,
121                crate::lexer::Keyword::Export => self.parse_export_declaration()?,
122                crate::lexer::Keyword::Namespace => self.parse_namespace_declaration()?,
123                crate::lexer::Keyword::Module => self.parse_module_declaration()?,
124                crate::lexer::Keyword::Declare => self.parse_declare_statement()?,
125                crate::lexer::Keyword::Return => self.parse_return_statement()?,
126                crate::lexer::Keyword::Throw => self.parse_throw_statement()?,
127                crate::lexer::Keyword::If => self.parse_if_statement()?,
128                crate::lexer::Keyword::Else => self.parse_expression_statement()?,
129                _ => self.parse_expression_statement()?,
130            },
131            Token::LeftBrace => self.parse_block_statement()?,
132            Token::Semicolon => {
133                self.advance();
134                return self.parse_statement();
135            }
136            _ => {
137                // Try to parse as expression statement, but if it fails, skip the token
138                match self.parse_expression_statement() {
139                    Ok(expr_stmt) => expr_stmt,
140                    Err(_) => {
141                        // Skip problematic token and continue
142                        self.advance();
143                        return Ok(None);
144                    }
145                }
146            }
147        };
148
149        Ok(Some(statement))
150    }
151
152    /// Parse variable declaration
153    fn parse_variable_declaration(&mut self) -> Result<Statement> {
154        let keyword = self.expect_keyword()?;
155        let name = self.expect_identifier()?;
156        let type_annotation = if self.current_token() == &Token::Colon {
157            self.advance();
158            Some(self.parse_type()?)
159        } else {
160            None
161        };
162
163        let initializer = if self.current_token() == &Token::Assign {
164            self.advance();
165            Some(self.parse_expression()?)
166        } else {
167            None
168        };
169
170        self.expect_semicolon()?;
171
172        Ok(Statement::VariableDeclaration(VariableDeclaration {
173            keyword,
174            name,
175            type_annotation,
176            initializer,
177        }))
178    }
179
180    /// Parse function declaration
181    fn parse_function_declaration(&mut self) -> Result<Statement> {
182        self.expect_keyword()?; // consume 'function' keyword
183        let name = self.expect_identifier()?;
184        let type_parameters = self.parse_type_parameters()?;
185        let parameters = self.parse_parameters()?;
186        let return_type = if self.current_token() == &Token::Colon {
187            self.advance();
188            Some(self.parse_type()?)
189        } else {
190            None
191        };
192        let body = self.parse_block_statement()?;
193
194        Ok(Statement::FunctionDeclaration(FunctionDeclaration {
195            name,
196            type_parameters,
197            parameters,
198            return_type,
199            body: Box::new(body),
200        }))
201    }
202
203    /// Parse class declaration
204    fn parse_class_declaration(&mut self) -> Result<Statement> {
205        self.expect_keyword()?; // consume 'class' keyword
206        let name = self.expect_identifier()?;
207        let type_parameters = self.parse_type_parameters()?;
208        let extends = if self.current_token() == &Token::Keyword(crate::lexer::Keyword::Extends) {
209            self.advance();
210            Some(self.parse_type()?)
211        } else {
212            None
213        };
214        let implements = self.parse_implements()?;
215        let body = self.parse_class_body()?;
216
217        Ok(Statement::ClassDeclaration(ClassDeclaration {
218            name,
219            type_parameters,
220            extends,
221            implements,
222            body,
223        }))
224    }
225
226    /// Parse interface declaration
227    fn parse_interface_declaration(&mut self) -> Result<Statement> {
228        self.expect_keyword()?; // consume 'interface' keyword
229        let name = self.expect_identifier()?;
230        let type_parameters = self.parse_type_parameters()?;
231        let extends = self.parse_extends()?;
232        let body = self.parse_interface_body()?;
233
234        Ok(Statement::InterfaceDeclaration(InterfaceDeclaration {
235            name,
236            type_parameters,
237            extends,
238            body,
239        }))
240    }
241
242    /// Parse type alias
243    fn parse_type_alias(&mut self) -> Result<Statement> {
244        self.expect_keyword()?; // consume 'type' keyword
245        let name = self.expect_identifier()?;
246        let type_parameters = self.parse_type_parameters()?;
247        self.expect_token(&Token::Assign)?;
248        let type_definition = self.parse_type()?;
249        self.expect_semicolon()?;
250
251        Ok(Statement::TypeAlias(TypeAlias {
252            name,
253            type_parameters,
254            type_definition,
255        }))
256    }
257
258    /// Parse enum declaration
259    fn parse_enum_declaration(&mut self) -> Result<Statement> {
260        self.expect_keyword()?; // consume 'enum' keyword
261        let name = self.expect_identifier()?;
262        let members = self.parse_enum_members()?;
263
264        Ok(Statement::EnumDeclaration(EnumDeclaration {
265            name,
266            members,
267        }))
268    }
269
270    fn parse_const_enum_declaration(&mut self) -> Result<Statement> {
271        self.expect_keyword()?; // consume 'const' keyword
272        self.expect_keyword()?; // consume 'enum' keyword
273        let name = self.expect_identifier()?;
274        let members = self.parse_enum_members()?;
275
276        // For now, treat const enum the same as regular enum
277        // In a full implementation, we'd have a ConstEnumDeclaration type
278        Ok(Statement::EnumDeclaration(EnumDeclaration {
279            name,
280            members,
281        }))
282    }
283
284    /// Parse import declaration
285    fn parse_import_declaration(&mut self) -> Result<Statement> {
286        self.expect_keyword()?; // import
287        let specifiers = self.parse_import_specifiers()?;
288        self.expect_keyword()?; // from
289        let source = self.parse_string_literal()?;
290        self.expect_semicolon()?;
291
292        Ok(Statement::ImportDeclaration(ImportDeclaration {
293            specifiers,
294            source,
295        }))
296    }
297
298    /// Parse export declaration
299    fn parse_export_declaration(&mut self) -> Result<Statement> {
300        // Consume 'export' keyword
301        self.advance();
302        // Parse the specific declaration type directly
303        let token = self.current_token().clone();
304        let declaration = match token {
305            Token::Keyword(crate::lexer::Keyword::Class) => self.parse_class_declaration()?,
306            Token::Keyword(crate::lexer::Keyword::Interface) => {
307                self.parse_interface_declaration()?
308            }
309            Token::Keyword(crate::lexer::Keyword::Function) => self.parse_function_declaration()?,
310            Token::Keyword(crate::lexer::Keyword::Const) => self.parse_variable_declaration()?,
311            Token::Keyword(crate::lexer::Keyword::Let) => self.parse_variable_declaration()?,
312            Token::Keyword(crate::lexer::Keyword::Var) => self.parse_variable_declaration()?,
313            Token::Keyword(crate::lexer::Keyword::Enum) => self.parse_enum_declaration()?,
314            Token::Keyword(crate::lexer::Keyword::Type) => {
315                // Check if this is "export type { ... }" or "export type Name = ..."
316                if self.position + 1 < self.tokens.len() {
317                    if let Token::LeftBrace = &self.tokens[self.position + 1] {
318                        // This is "export type { ... }", parse as export type statement
319                        self.parse_export_type_statement()?
320                    } else {
321                        // This is "export type Name = ...", parse as type alias
322                        self.parse_type_alias()?
323                    }
324                } else {
325                    self.parse_type_alias()?
326                }
327            },
328            Token::LeftBrace => {
329                // This is "export { ... }", parse as export statement
330                self.parse_export_statement()?
331            },
332            _ => {
333                return Err(CompilerError::parse_error(
334                    1,
335                    1,
336                    format!("Unexpected token in export declaration: {:?}", token),
337                ))
338            }
339        };
340        Ok(Statement::ExportDeclaration(Box::new(ExportDeclaration {
341            declaration: Box::new(declaration),
342        })))
343    }
344
345    fn parse_export_statement(&mut self) -> Result<Statement> {
346        self.expect_token(&Token::LeftBrace)?; // consume '{'
347        
348        let mut exports = Vec::new();
349        while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
350            let name = self.expect_identifier()?;
351            exports.push(name);
352            
353            if self.current_token() == &Token::Comma {
354                self.advance(); // consume ','
355            }
356        }
357        
358        self.expect_token(&Token::RightBrace)?; // consume '}'
359        self.expect_semicolon()?;
360        
361        Ok(Statement::ExportDeclaration(Box::new(ExportDeclaration {
362            declaration: Box::new(Statement::ExpressionStatement(ExpressionStatement {
363                expression: Expression::Literal(Literal::String(format!("Export: {}", exports.join(", ")))),
364            })),
365        })))
366    }
367
368    fn parse_export_type_statement(&mut self) -> Result<Statement> {
369        self.expect_keyword()?; // consume 'type' keyword
370        self.expect_token(&Token::LeftBrace)?; // consume '{'
371        
372        let mut type_names = Vec::new();
373        while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
374            let name = self.expect_identifier()?;
375            type_names.push(name);
376            
377            if self.current_token() == &Token::Comma {
378                self.advance();
379            }
380        }
381        
382        self.expect_token(&Token::RightBrace)?; // consume '}'
383        self.expect_semicolon()?;
384        
385        // For now, create a simple export statement
386        // In a full implementation, we'd have a proper ExportTypeStatement type
387        Ok(Statement::ExportDeclaration(Box::new(ExportDeclaration {
388            declaration: Box::new(Statement::TypeAlias(TypeAlias {
389                name: "exported_types".to_string(),
390                type_parameters: Vec::new(),
391                type_definition: Type::Any,
392            })),
393        })))
394    }
395
396    /// Parse namespace declaration
397    fn parse_namespace_declaration(&mut self) -> Result<Statement> {
398        self.expect_keyword()?; // namespace
399        let name = self.expect_identifier()?;
400        let body = self.parse_block_statement()?;
401
402        Ok(Statement::NamespaceDeclaration(NamespaceDeclaration {
403            name,
404            body: Box::new(body),
405        }))
406    }
407
408    /// Parse module declaration
409    fn parse_module_declaration(&mut self) -> Result<Statement> {
410        self.expect_keyword()?; // module
411        let name = self.parse_string_literal()?;
412        let body = self.parse_block_statement()?;
413
414        Ok(Statement::ModuleDeclaration(ModuleDeclaration {
415            name,
416            body: Box::new(body),
417        }))
418    }
419
420    /// Parse declare statement
421    fn parse_declare_statement(&mut self) -> Result<Statement> {
422        self.expect_keyword()?; // declare
423        let declaration = self.parse_statement()?;
424        Ok(Statement::DeclareStatement(Box::new(DeclareStatement {
425            declaration: Box::new(declaration.unwrap()),
426        })))
427    }
428
429    /// Parse return statement
430    fn parse_return_statement(&mut self) -> Result<Statement> {
431        self.expect_keyword()?; // return
432
433        let argument = if self.current_token() == &Token::Semicolon {
434            None
435        } else {
436            Some(self.parse_expression()?)
437        };
438
439        // Optional semicolon
440        if self.current_token() == &Token::Semicolon {
441            self.advance();
442        }
443
444        Ok(Statement::ReturnStatement(ReturnStatement { argument }))
445    }
446
447    /// Parse throw statement
448    fn parse_throw_statement(&mut self) -> Result<Statement> {
449        self.expect_keyword()?; // throw
450
451        let argument = self.parse_expression()?;
452
453        // Optional semicolon
454        if self.current_token() == &Token::Semicolon {
455            self.advance();
456        }
457
458        Ok(Statement::ThrowStatement(ThrowStatement { argument }))
459    }
460
461    /// Parse expression statement
462    fn parse_expression_statement(&mut self) -> Result<Statement> {
463        let expression = self.parse_expression()?;
464        self.expect_semicolon()?;
465        Ok(Statement::ExpressionStatement(ExpressionStatement {
466            expression,
467        }))
468    }
469
470    /// Parse block statement
471    fn parse_block_statement(&mut self) -> Result<Statement> {
472        self.expect_token(&Token::LeftBrace)?;
473        let mut statements = Vec::new();
474
475        while self.current_token() != &Token::RightBrace {
476            if let Some(statement) = self.parse_statement()? {
477                statements.push(statement);
478            } else {
479                break;
480            }
481        }
482
483        self.expect_token(&Token::RightBrace)?;
484        Ok(Statement::BlockStatement(BlockStatement { statements }))
485    }
486
487    /// Parse expression
488    fn parse_expression(&mut self) -> Result<Expression> {
489        self.parse_assignment_expression()
490    }
491
492    /// Parse assignment expression
493    fn parse_assignment_expression(&mut self) -> Result<Expression> {
494        let left = self.parse_conditional_expression()?;
495
496        if self.is_assignment_operator() {
497            let operator = self.current_token().clone();
498            self.advance();
499            let right = self.parse_assignment_expression()?;
500            Ok(Expression::Assignment(AssignmentExpression {
501                left: Box::new(left),
502                operator,
503                right: Box::new(right),
504            }))
505        } else {
506            Ok(left)
507        }
508    }
509
510    /// Parse conditional expression
511    fn parse_conditional_expression(&mut self) -> Result<Expression> {
512        let test = self.parse_logical_or_expression()?;
513
514        if self.current_token() == &Token::QuestionMark {
515            self.advance();
516            let consequent = self.parse_expression()?;
517            self.expect_token(&Token::Colon)?;
518            let alternate = self.parse_expression()?;
519            Ok(Expression::Conditional(ConditionalExpression {
520                test: Box::new(test),
521                consequent: Box::new(consequent),
522                alternate: Box::new(alternate),
523            }))
524        } else {
525            Ok(test)
526        }
527    }
528
529    /// Parse logical OR expression
530    fn parse_logical_or_expression(&mut self) -> Result<Expression> {
531        let mut left = self.parse_logical_and_expression()?;
532
533        while self.current_token() == &Token::Or {
534            self.advance();
535            let right = self.parse_logical_and_expression()?;
536            left = Expression::Logical(LogicalExpression {
537                left: Box::new(left),
538                operator: Token::Or,
539                right: Box::new(right),
540            });
541        }
542
543        Ok(left)
544    }
545
546    /// Parse logical AND expression
547    fn parse_logical_and_expression(&mut self) -> Result<Expression> {
548        let mut left = self.parse_equality_expression()?;
549
550        while self.current_token() == &Token::And {
551            self.advance();
552            let right = self.parse_equality_expression()?;
553            left = Expression::Logical(LogicalExpression {
554                left: Box::new(left),
555                operator: Token::And,
556                right: Box::new(right),
557            });
558        }
559
560        Ok(left)
561    }
562
563    /// Parse equality expression
564    fn parse_equality_expression(&mut self) -> Result<Expression> {
565        let mut left = self.parse_relational_expression()?;
566
567        while self.is_equality_operator() {
568            let operator = self.current_token().clone();
569            self.advance();
570            let right = self.parse_relational_expression()?;
571            left = Expression::Binary(BinaryExpression {
572                left: Box::new(left),
573                operator,
574                right: Box::new(right),
575            });
576        }
577
578        Ok(left)
579    }
580
581    /// Parse relational expression
582    fn parse_relational_expression(&mut self) -> Result<Expression> {
583        let mut left = self.parse_additive_expression()?;
584
585        while self.is_relational_operator() {
586            let operator = self.current_token().clone();
587            self.advance();
588            let right = self.parse_additive_expression()?;
589            left = Expression::Binary(BinaryExpression {
590                left: Box::new(left),
591                operator,
592                right: Box::new(right),
593            });
594        }
595
596        Ok(left)
597    }
598
599    /// Parse additive expression
600    fn parse_additive_expression(&mut self) -> Result<Expression> {
601        let mut left = self.parse_multiplicative_expression()?;
602
603        while self.is_additive_operator() {
604            let operator = self.current_token().clone();
605            self.advance();
606            let right = self.parse_multiplicative_expression()?;
607            left = Expression::Binary(BinaryExpression {
608                left: Box::new(left),
609                operator,
610                right: Box::new(right),
611            });
612        }
613
614        Ok(left)
615    }
616
617    /// Parse multiplicative expression
618    fn parse_multiplicative_expression(&mut self) -> Result<Expression> {
619        let mut left = self.parse_unary_expression()?;
620
621        while self.is_multiplicative_operator() {
622            let operator = self.current_token().clone();
623            self.advance();
624            let right = self.parse_unary_expression()?;
625            left = Expression::Binary(BinaryExpression {
626                left: Box::new(left),
627                operator,
628                right: Box::new(right),
629            });
630        }
631
632        Ok(left)
633    }
634
635    /// Parse unary expression
636    fn parse_unary_expression(&mut self) -> Result<Expression> {
637        if self.is_unary_operator() {
638            let operator = self.current_token().clone();
639            self.advance();
640            let argument = self.parse_unary_expression()?;
641            Ok(Expression::Unary(UnaryExpression {
642                operator,
643                argument: Box::new(argument),
644            }))
645        } else {
646            self.parse_postfix_expression()
647        }
648    }
649
650    /// Parse postfix expression
651    fn parse_postfix_expression(&mut self) -> Result<Expression> {
652        let mut left = self.parse_primary_expression()?;
653
654        while self.is_postfix_operator() {
655            match self.current_token() {
656                Token::LeftParen => {
657                    self.advance();
658                    let arguments = self.parse_arguments()?;
659                    self.expect_token(&Token::RightParen)?;
660                    left = Expression::Call(CallExpression {
661                        callee: Box::new(left),
662                        arguments,
663                    });
664                }
665                Token::LeftBracket => {
666                    self.advance();
667                    let index = self.parse_expression()?;
668                    self.expect_token(&Token::RightBracket)?;
669                    left = Expression::Member(MemberExpression {
670                        object: Box::new(left),
671                        property: Box::new(index),
672                        computed: true,
673                    });
674                }
675                Token::Dot => {
676                    self.advance();
677                    let property = self.expect_identifier()?;
678                    left = Expression::Member(MemberExpression {
679                        object: Box::new(left),
680                        property: Box::new(Expression::Identifier(property)),
681                        computed: false,
682                    });
683                }
684                _ => break,
685            }
686        }
687
688        Ok(left)
689    }
690
691    /// Parse primary expression
692    fn parse_primary_expression(&mut self) -> Result<Expression> {
693        let token = self.current_token().clone();
694        match token {
695            Token::Number(n) => {
696                self.advance();
697                Ok(Expression::Literal(Literal::Number(n)))
698            }
699            Token::String(s) => {
700                self.advance();
701                Ok(Expression::Literal(Literal::String(s)))
702            }
703            Token::RegExp(pattern, flags) => {
704                self.advance();
705                Ok(Expression::Literal(Literal::RegExp(pattern.clone(), flags.clone())))
706            }
707            Token::TemplateLiteral(s) => {
708                self.advance();
709                // Create a simple template literal with one quasi
710                let template = TemplateLiteral {
711                    quasis: vec![TemplateElement {
712                        value: s,
713                        tail: true,
714                    }],
715                    expressions: vec![],
716                };
717                Ok(Expression::Template(template))
718            }
719            Token::Boolean(b) => {
720                self.advance();
721                Ok(Expression::Literal(Literal::Boolean(b)))
722            }
723            Token::Null => {
724                self.advance();
725                Ok(Expression::Literal(Literal::Null))
726            }
727            Token::Undefined => {
728                self.advance();
729                Ok(Expression::Literal(Literal::Undefined))
730            }
731            Token::Keyword(crate::lexer::Keyword::Null) => {
732                self.advance();
733                Ok(Expression::Literal(Literal::Null))
734            }
735            Token::Keyword(crate::lexer::Keyword::Undefined) => {
736                self.advance();
737                Ok(Expression::Literal(Literal::Undefined))
738            }
739            Token::Identifier(name) => {
740                self.advance();
741                Ok(Expression::Identifier(name))
742            }
743            Token::Keyword(crate::lexer::Keyword::This) => {
744                self.advance();
745                // Check for dot notation: this.prop
746                if self.current_token() == &Token::Dot {
747                    self.advance(); // consume '.'
748                    let property = self.expect_identifier()?;
749                    Ok(Expression::Member(MemberExpression {
750                        object: Box::new(Expression::This(ThisExpression)),
751                        property: Box::new(Expression::Identifier(property)),
752                        computed: false,
753                    }))
754                } else {
755                    Ok(Expression::This(ThisExpression))
756                }
757            }
758            Token::Keyword(crate::lexer::Keyword::Super) => {
759                self.advance();
760                Ok(Expression::Super(SuperExpression))
761            }
762            Token::Keyword(crate::lexer::Keyword::New) => {
763                self.advance();
764                let callee = self.parse_primary_expression()?;
765                let arguments = if self.current_token() == &Token::LeftParen {
766                    self.advance(); // consume '('
767                    let args = self.parse_arguments()?;
768                    self.expect_token(&Token::RightParen)?;
769                    args
770                } else {
771                    Vec::new()
772                };
773                Ok(Expression::New(NewExpression {
774                    callee: Box::new(callee),
775                    arguments,
776                }))
777            }
778            Token::LeftParen => {
779                // Look ahead to see if this is an arrow function
780                let mut pos = self.position + 1;
781                let mut paren_count = 1;
782                
783                // Skip to matching closing paren
784                while pos < self.tokens.len() && paren_count > 0 {
785                    match &self.tokens[pos] {
786                        Token::LeftParen => paren_count += 1,
787                        Token::RightParen => paren_count -= 1,
788                        _ => {}
789                    }
790                    pos += 1;
791                }
792                
793                // Check if next token is arrow
794                if pos < self.tokens.len() && self.tokens[pos] == Token::Arrow {
795                    // This is an arrow function
796                    self.advance(); // consume (
797                    let parameters = self.parse_parameter_list()?;
798                    self.expect_token(&Token::RightParen)?;
799                    self.expect_token(&Token::Arrow)?;
800                    let body = if self.current_token() == &Token::LeftBrace {
801                        self.parse_block_statement()?
802                    } else {
803                        let expr = self.parse_expression()?;
804                        Statement::ExpressionStatement(ExpressionStatement {
805                            expression: expr,
806                        })
807                    };
808                    
809                    Ok(Expression::Arrow(Box::new(ArrowFunctionExpression {
810                        type_parameters: Vec::new(),
811                        parameters,
812                        return_type: None,
813                        body: Box::new(body),
814                    })))
815                } else {
816                    // Regular parenthesized expression
817                    self.advance();
818                    let expression = self.parse_expression()?;
819                    self.expect_token(&Token::RightParen)?;
820                    Ok(Expression::Parenthesized(ParenthesizedExpression {
821                        expression: Box::new(expression),
822                    }))
823                }
824            }
825            Token::LeftBrace => self.parse_object_expression(),
826            Token::LeftBracket => self.parse_array_expression(),
827            _ => Err(CompilerError::parse_error(
828                self.position,
829                0,
830                format!("Unexpected token: {:?}", self.current_token()),
831            )),
832        }
833    }
834
835    /// Parse object expression
836    fn parse_object_expression(&mut self) -> Result<Expression> {
837        self.expect_token(&Token::LeftBrace)?;
838        let mut properties = Vec::new();
839
840        while self.current_token() != &Token::RightBrace {
841            let key = self.parse_property_key()?;
842            let value = if self.current_token() == &Token::Colon {
843                self.advance();
844                self.parse_expression()?
845            } else {
846                key.clone()
847            };
848
849            properties.push(ObjectProperty {
850                key,
851                value,
852                shorthand: false,
853                computed: false,
854                method: false,
855            });
856
857            if self.current_token() == &Token::Comma {
858                self.advance();
859            }
860        }
861
862        self.expect_token(&Token::RightBrace)?;
863        Ok(Expression::Object(ObjectExpression { properties }))
864    }
865
866    /// Parse array expression
867    fn parse_array_expression(&mut self) -> Result<Expression> {
868        self.expect_token(&Token::LeftBracket)?;
869        let mut elements = Vec::new();
870
871        while self.current_token() != &Token::RightBracket {
872            if self.current_token() == &Token::Comma {
873                self.advance();
874                elements.push(None);
875            } else {
876                elements.push(Some(self.parse_expression()?));
877                if self.current_token() == &Token::Comma {
878                    self.advance();
879                }
880            }
881        }
882
883        self.expect_token(&Token::RightBracket)?;
884        Ok(Expression::Array(ArrayExpression { elements }))
885    }
886
887    /// Parse type
888    fn parse_type(&mut self) -> Result<Type> {
889        let mut left_type = self.parse_primary_type()?;
890        
891        // Handle union and intersection types
892        while matches!(self.current_token(), Token::Union | Token::Intersection) {
893            let operator = self.current_token().clone();
894            self.advance();
895            let right_type = self.parse_primary_type()?;
896            
897            left_type = match operator {
898                Token::Union => Type::Union {
899                    left: Box::new(left_type),
900                    right: Box::new(right_type),
901                },
902                Token::Intersection => Type::Intersection {
903                    left: Box::new(left_type),
904                    right: Box::new(right_type),
905                },
906                _ => return Err(CompilerError::parse_error(
907                    1,
908                    1,
909                    "Expected union or intersection operator",
910                )),
911            };
912        }
913        
914        // Handle array types: T[]
915        while self.current_token() == &Token::LeftBracket {
916            self.advance(); // consume [
917            self.expect_token(&Token::RightBracket)?; // consume ]
918            left_type = Type::Array(Box::new(left_type));
919        }
920        
921        Ok(left_type)
922    }
923    
924    fn parse_primary_type(&mut self) -> Result<Type> {
925        let token = self.current_token().clone();
926        match token {
927            Token::Keyword(crate::lexer::Keyword::String) => {
928                self.advance();
929                Ok(Type::String)
930            }
931            Token::Keyword(crate::lexer::Keyword::Number) => {
932                self.advance();
933                Ok(Type::Number)
934            }
935            Token::Keyword(crate::lexer::Keyword::Boolean) => {
936                self.advance();
937                Ok(Type::Boolean)
938            }
939            Token::Keyword(crate::lexer::Keyword::Any) => {
940                self.advance();
941                Ok(Type::Any)
942            }
943            Token::Keyword(crate::lexer::Keyword::Void) => {
944                self.advance();
945                Ok(Type::Void)
946            }
947            Token::Keyword(crate::lexer::Keyword::Never) => {
948                self.advance();
949                Ok(Type::Never)
950            }
951            Token::Keyword(crate::lexer::Keyword::Unknown) => {
952                self.advance();
953                Ok(Type::Unknown)
954            }
955            Token::Keyword(crate::lexer::Keyword::Array) => {
956                self.advance();
957                if self.current_token() == &Token::LessThan {
958                    self.advance(); // consume <
959                    let element_type = self.parse_primary_type()?;
960                    self.expect_token(&Token::GreaterThan)?;
961                    Ok(Type::Array(Box::new(element_type)))
962                } else {
963                    Ok(Type::Array(Box::new(Type::Any)))
964                }
965            }
966            Token::Keyword(crate::lexer::Keyword::Readonly) => {
967                self.advance();
968                // Parse the type that follows readonly
969                let element_type = self.parse_primary_type()?;
970                // For now, just return the element type (readonly is handled at runtime)
971                Ok(element_type)
972            }
973            Token::Keyword(crate::lexer::Keyword::Keyof) => {
974                self.advance();
975                let _target_type = self.parse_type()?;
976                // For now, return string as keyof T resolves to string
977                Ok(Type::String)
978            }
979            Token::Keyword(crate::lexer::Keyword::Key) => {
980                self.advance();
981                Ok(Type::String) // Key -> string for now
982            }
983            Token::Keyword(crate::lexer::Keyword::Infer) => {
984                self.advance();
985                Ok(Type::Any) // infer -> any for now
986            }
987            Token::Keyword(crate::lexer::Keyword::Null) => {
988                self.advance();
989                Ok(Type::Null) // null -> null for now
990            }
991            Token::Keyword(crate::lexer::Keyword::Undefined) => {
992                self.advance();
993                Ok(Type::Undefined) // undefined -> undefined for now
994            }
995            Token::Null => {
996                self.advance();
997                Ok(Type::Null)
998            }
999            Token::Undefined => {
1000                self.advance();
1001                Ok(Type::Undefined)
1002            }
1003            Token::Identifier(name) => {
1004                // First, parse the base type (could be array type, generic type, etc.)
1005                let base_type = if self.current_token() == &Token::LessThan {
1006                    // Parse generic type
1007                    self.advance(); // consume <
1008                    let mut type_args = Vec::new();
1009
1010                    while self.current_token() != &Token::GreaterThan && self.current_token() != &Token::EOF {
1011                        let arg = self.parse_type()?;
1012                        type_args.push(arg);
1013
1014                        if self.current_token() == &Token::Comma {
1015                            self.advance(); // consume ,
1016                        } else {
1017                            break;
1018                        }
1019                    }
1020
1021                    self.expect_token(&Token::GreaterThan)?; // consume >
1022
1023                    self.advance(); // consume the identifier token
1024                    Type::GenericNamed {
1025                        name: name.to_string(),
1026                        type_arguments: type_args,
1027                    }
1028                } else {
1029                    self.advance(); // consume the identifier token
1030                    Type::Named(name.to_string())
1031                };
1032
1033                // Then check for array brackets
1034                if self.current_token() == &Token::LeftBracket {
1035                    self.advance(); // consume [
1036                    self.expect_token(&Token::RightBracket)?; // consume ]
1037                    Ok(Type::Array(Box::new(base_type)))
1038                } else {
1039                    Ok(base_type)
1040                }
1041            }
1042            Token::String(s) => {
1043                self.advance();
1044                // String literal type
1045                Ok(Type::Named(format!("\"{}\"", s)))
1046            }
1047            Token::Number(n) => {
1048                self.advance();
1049                // Number literal type
1050                Ok(Type::Named(n.to_string()))
1051            }
1052            Token::LeftParen => {
1053                self.advance();
1054                let type_ = self.parse_type()?;
1055                self.expect_token(&Token::RightParen)?;
1056                Ok(type_)
1057            }
1058       Token::LeftBrace => {
1059           // Parse object type: { prop: type; ... } or mapped type { [P in K]: T }
1060           self.advance(); // consume {
1061           let mut members = Vec::new();
1062
1063           while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
1064               // Check if this is a mapped type: [P in K] or index signature: [key: type]
1065               if self.current_token() == &Token::LeftBracket {
1066                   // Look ahead to determine if this is a mapped type or index signature
1067                   let mut pos = self.position + 1; // skip [
1068                   let mut is_mapped_type = false;
1069                   
1070                   // Look for 'in' keyword to distinguish mapped type from index signature
1071                   while pos < self.tokens.len() && self.tokens[pos] != Token::RightBracket {
1072                       if self.tokens[pos] == Token::Keyword(Keyword::In) {
1073                           is_mapped_type = true;
1074                           break;
1075                       }
1076                       pos += 1;
1077                   }
1078                   
1079                   if is_mapped_type {
1080                       let mapped_type = self.parse_mapped_type()?;
1081                       members.push(ObjectTypeMember::Property(PropertySignature {
1082                           name: mapped_type.type_parameter.name.clone(),
1083                           optional: false,
1084                           type_: Some(*mapped_type.type_.clone()),
1085                           readonly: mapped_type.readonly.unwrap_or(false),
1086                       }));
1087                       // parse_mapped_type already handles semicolon, so continue to next iteration
1088                       continue;
1089                   } else {
1090                       // This is an index signature, parse it as such
1091                       let index_sig = self.parse_index_signature()?;
1092                       members.push(ObjectTypeMember::Index(index_sig));
1093                       if self.current_token() == &Token::Semicolon {
1094                           self.advance();
1095                       }
1096                       continue;
1097                   }
1098               } else {
1099                   // Check for readonly modifier
1100                   let readonly = if self.current_token() == &Token::Keyword(Keyword::Readonly) {
1101                       self.advance(); // consume readonly
1102                       true
1103                   } else {
1104                       false
1105                   };
1106
1107                   let name = self.expect_identifier()?;
1108                   let optional = if self.current_token() == &Token::QuestionMark {
1109                       self.advance();
1110                       true
1111                   } else {
1112                       false
1113                   };
1114                   self.expect_token(&Token::Colon)?;
1115                   let type_ = self.parse_type()?;
1116
1117                   members.push(ObjectTypeMember::Property(PropertySignature {
1118                       name,
1119                       optional,
1120                       type_: Some(type_),
1121                       readonly,
1122                   }));
1123               }
1124
1125               if self.current_token() == &Token::Semicolon {
1126                   self.advance();
1127               }
1128           }
1129
1130           self.expect_token(&Token::RightBrace)?;
1131           Ok(Type::ObjectType(ObjectType { members }))
1132       }
1133            _ => Err(CompilerError::parse_error(
1134                self.position,
1135                0,
1136                format!("Unexpected token in type: {:?}", self.current_token()),
1137            )),
1138        }
1139    }
1140
1141    // Helper methods
1142    fn current_token(&self) -> &Token {
1143        &self.tokens[self.position]
1144    }
1145
1146    fn advance(&mut self) {
1147        if self.position < self.tokens.len() {
1148            self.position += 1;
1149        }
1150    }
1151
1152    fn expect_token(&mut self, expected: &Token) -> Result<()> {
1153        if self.current_token() == expected {
1154            self.advance();
1155            Ok(())
1156        } else {
1157            Err(CompilerError::parse_error(
1158                self.position,
1159                0,
1160                format!("Expected {:?}, found {:?}", expected, self.current_token()),
1161            ))
1162        }
1163    }
1164
1165    fn expect_keyword(&mut self) -> Result<crate::lexer::Keyword> {
1166        if let Token::Keyword(keyword) = self.current_token() {
1167            let keyword = keyword.clone();
1168            self.advance();
1169            Ok(keyword)
1170        } else {
1171            Err(CompilerError::parse_error(
1172                self.position,
1173                0,
1174                format!("Expected keyword, found {:?}", self.current_token()),
1175            ))
1176        }
1177    }
1178
1179    fn expect_identifier(&mut self) -> Result<String> {
1180        if let Token::Identifier(name) = self.current_token() {
1181            let name = name.clone();
1182            self.advance();
1183            Ok(name)
1184        } else {
1185            Err(CompilerError::parse_error(
1186                self.position,
1187                0,
1188                format!("Expected identifier, found {:?}", self.current_token()),
1189            ))
1190        }
1191    }
1192
1193    fn expect_semicolon(&mut self) -> Result<()> {
1194        self.expect_token(&Token::Semicolon)
1195    }
1196
1197    fn parse_string_literal(&mut self) -> Result<String> {
1198        if let Token::String(s) = self.current_token() {
1199            let s = s.clone();
1200            self.advance();
1201            Ok(s)
1202        } else {
1203            Err(CompilerError::parse_error(
1204                self.position,
1205                0,
1206                format!("Expected string literal, found {:?}", self.current_token()),
1207            ))
1208        }
1209    }
1210
1211    fn is_assignment_operator(&self) -> bool {
1212        matches!(
1213            self.current_token(),
1214            Token::Assign
1215                | Token::PlusAssign
1216                | Token::MinusAssign
1217                | Token::MultiplyAssign
1218                | Token::DivideAssign
1219        )
1220    }
1221
1222    fn is_equality_operator(&self) -> bool {
1223        matches!(
1224            self.current_token(),
1225            Token::Equal | Token::NotEqual | Token::StrictEqual | Token::StrictNotEqual
1226        )
1227    }
1228
1229    fn is_relational_operator(&self) -> bool {
1230        matches!(
1231            self.current_token(),
1232            Token::LessThan | Token::GreaterThan | Token::LessEqual | Token::GreaterEqual
1233        )
1234    }
1235
1236    fn is_additive_operator(&self) -> bool {
1237        matches!(self.current_token(), Token::Plus | Token::Minus)
1238    }
1239
1240    fn is_multiplicative_operator(&self) -> bool {
1241        matches!(
1242            self.current_token(),
1243            Token::Multiply | Token::Divide | Token::Modulo
1244        )
1245    }
1246
1247    fn is_unary_operator(&self) -> bool {
1248        matches!(
1249            self.current_token(),
1250            Token::Plus | Token::Minus | Token::Not | Token::Keyword(crate::lexer::Keyword::Typeof)
1251        )
1252    }
1253
1254    fn is_postfix_operator(&self) -> bool {
1255        matches!(
1256            self.current_token(),
1257            Token::LeftParen | Token::LeftBracket | Token::Dot
1258        )
1259    }
1260
1261    // Placeholder methods for complex parsing
1262    fn parse_type_parameters(&mut self) -> Result<Vec<TypeParameter>> {
1263        if self.current_token() == &Token::LessThan {
1264            self.advance();
1265            let mut type_parameters = Vec::new();
1266
1267            while self.current_token() != &Token::GreaterThan && self.current_token() != &Token::EOF {
1268                let name = self.expect_identifier()?;
1269
1270                let constraint =
1271                    if self.current_token() == &Token::Keyword(crate::lexer::Keyword::Extends) {
1272                        self.advance();
1273                        Some(self.parse_type()?)
1274                    } else {
1275                        None
1276                    };
1277
1278                let default_type = if self.current_token() == &Token::Assign {
1279                    self.advance();
1280                    Some(self.parse_type()?)
1281                } else {
1282                    None
1283                };
1284
1285                type_parameters.push(TypeParameter {
1286                    name,
1287                    constraint: constraint.map(Box::new),
1288                    default: default_type.map(Box::new),
1289                });
1290
1291                if self.current_token() == &Token::Comma {
1292                    self.advance();
1293                } else {
1294                    break;
1295                }
1296            }
1297
1298            self.expect_token(&Token::GreaterThan)?;
1299            Ok(type_parameters)
1300        } else {
1301            Ok(Vec::new())
1302        }
1303    }
1304
1305    fn parse_parameters(&mut self) -> Result<Vec<Parameter>> {
1306        self.expect_token(&Token::LeftParen)?;
1307        let mut parameters = Vec::new();
1308
1309        while self.current_token() != &Token::RightParen {
1310            // Handle access modifiers on parameters (TypeScript feature)
1311            let mut _modifiers = Vec::new();
1312            while let Token::Keyword(keyword) = self.current_token() {
1313                match keyword {
1314                    crate::lexer::Keyword::Public | 
1315                    crate::lexer::Keyword::Private | 
1316                    crate::lexer::Keyword::Protected | 
1317                    crate::lexer::Keyword::Readonly => {
1318                        _modifiers.push(keyword.clone());
1319                        self.advance();
1320                    }
1321                    _ => break,
1322                }
1323            }
1324            
1325            let name = self.expect_identifier()?;
1326            let optional = if self.current_token() == &Token::QuestionMark {
1327                self.advance();
1328                true
1329            } else {
1330                false
1331            };
1332
1333            let type_annotation = if self.current_token() == &Token::Colon {
1334                self.advance();
1335                Some(self.parse_type()?)
1336            } else {
1337                None
1338            };
1339
1340            let initializer = if self.current_token() == &Token::Assign {
1341                self.advance();
1342                Some(self.parse_expression()?)
1343            } else {
1344                None
1345            };
1346
1347            parameters.push(Parameter {
1348                name,
1349                optional,
1350                type_: type_annotation.map(Box::new),
1351                initializer,
1352                rest: false,
1353            });
1354
1355            if self.current_token() == &Token::Comma {
1356                self.advance();
1357            }
1358        }
1359
1360        self.expect_token(&Token::RightParen)?;
1361        Ok(parameters)
1362    }
1363    
1364    fn parse_parameter_list(&mut self) -> Result<Vec<Parameter>> {
1365        let mut parameters = Vec::new();
1366
1367        while self.current_token() != &Token::RightParen {
1368            // Handle access modifiers on parameters (TypeScript feature)
1369            let mut _modifiers = Vec::new();
1370            while let Token::Keyword(keyword) = self.current_token() {
1371                match keyword {
1372                    crate::lexer::Keyword::Public | 
1373                    crate::lexer::Keyword::Private | 
1374                    crate::lexer::Keyword::Protected | 
1375                    crate::lexer::Keyword::Readonly => {
1376                        _modifiers.push(keyword.clone());
1377                        self.advance();
1378                    }
1379                    _ => break,
1380                }
1381            }
1382            
1383            let name = self.expect_identifier()?;
1384            let optional = if self.current_token() == &Token::QuestionMark {
1385                self.advance();
1386                true
1387            } else {
1388                false
1389            };
1390
1391            let type_annotation = if self.current_token() == &Token::Colon {
1392                self.advance();
1393                Some(self.parse_type()?)
1394            } else {
1395                None
1396            };
1397
1398            let initializer = if self.current_token() == &Token::Assign {
1399                self.advance();
1400                Some(self.parse_expression()?)
1401            } else {
1402                None
1403            };
1404
1405            parameters.push(Parameter {
1406                name,
1407                optional,
1408                type_: type_annotation.map(Box::new),
1409                initializer,
1410                rest: false,
1411            });
1412
1413            if self.current_token() == &Token::Comma {
1414                self.advance();
1415            }
1416        }
1417
1418        Ok(parameters)
1419    }
1420
1421    fn parse_implements(&mut self) -> Result<Vec<Type>> {
1422        if self.current_token() == &Token::Keyword(crate::lexer::Keyword::Implements) {
1423            self.advance();
1424            let mut types = Vec::new();
1425
1426            loop {
1427                let type_ = self.parse_type()?;
1428                types.push(type_);
1429
1430                if self.current_token() == &Token::Comma {
1431                    self.advance();
1432                } else {
1433                    break;
1434                }
1435            }
1436
1437            Ok(types)
1438        } else {
1439            Ok(Vec::new())
1440        }
1441    }
1442
1443    fn parse_extends(&mut self) -> Result<Vec<Type>> {
1444        let mut extends = Vec::new();
1445        
1446        if self.current_token() == &Token::Keyword(crate::lexer::Keyword::Extends) {
1447            self.advance(); // consume 'extends'
1448            
1449            // Parse the first extended type
1450            let type_ = self.parse_type()?;
1451            extends.push(type_);
1452            
1453            // Parse additional extended types (comma-separated)
1454            while self.current_token() == &Token::Comma {
1455                self.advance(); // consume ','
1456                let type_ = self.parse_type()?;
1457                extends.push(type_);
1458            }
1459        }
1460        
1461        Ok(extends)
1462    }
1463
1464    fn parse_class_body(&mut self) -> Result<ClassBody> {
1465        self.expect_token(&Token::LeftBrace)?;
1466        let mut members = Vec::new();
1467
1468        while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
1469            let member = self.parse_class_member()?;
1470            members.push(member.clone());
1471
1472            // Handle decorator-only members
1473            if let ClassMember::Decorator(_) = &member {
1474                continue;
1475            }
1476        }
1477
1478        self.expect_token(&Token::RightBrace)?;
1479        Ok(ClassBody { members })
1480    }
1481
1482    fn parse_interface_body(&mut self) -> Result<InterfaceBody> {
1483        self.expect_token(&Token::LeftBrace)?;
1484        let mut members = Vec::new();
1485
1486        while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
1487            let member = self.parse_interface_member()?;
1488            members.push(member);
1489        }
1490        self.expect_token(&Token::RightBrace)?;
1491        Ok(InterfaceBody { members })
1492    }
1493
1494    fn parse_enum_members(&mut self) -> Result<Vec<EnumMember>> {
1495        self.expect_token(&Token::LeftBrace)?;
1496        let mut members = Vec::new();
1497
1498        while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
1499            let member = self.parse_enum_member()?;
1500            members.push(member);
1501
1502            if self.current_token() == &Token::Comma {
1503                self.advance();
1504            }
1505        }
1506
1507        self.expect_token(&Token::RightBrace)?;
1508        Ok(members)
1509    }
1510
1511    fn parse_import_specifiers(&mut self) -> Result<Vec<ImportSpecifier>> {
1512        let mut specifiers = Vec::new();
1513
1514        if self.current_token() == &Token::LeftBrace {
1515            self.advance(); // consume '{'
1516
1517            while self.current_token() != &Token::RightBrace {
1518                let name = self.expect_identifier()?;
1519                specifiers.push(ImportSpecifier::Named(NamedImportSpecifier {
1520                    imported: name.clone(),
1521                    name,
1522                }));
1523
1524                if self.current_token() == &Token::Comma {
1525                    self.advance();
1526                }
1527            }
1528
1529            self.expect_token(&Token::RightBrace)?; // consume '}'
1530        } else {
1531            // Default import
1532            let name = self.expect_identifier()?;
1533            specifiers.push(ImportSpecifier::Default(DefaultImportSpecifier { name }));
1534        }
1535
1536        Ok(specifiers)
1537    }
1538
1539    fn parse_arguments(&mut self) -> Result<Vec<Expression>> {
1540        let mut arguments = Vec::new();
1541
1542        while self.current_token() != &Token::RightParen {
1543            let argument = self.parse_expression()?;
1544            arguments.push(argument);
1545
1546            if self.current_token() == &Token::Comma {
1547                self.advance();
1548            } else if self.current_token() != &Token::RightParen {
1549                return Err(CompilerError::parse_error(
1550                    1,
1551                    1,
1552                    "Expected comma or closing parenthesis".to_string(),
1553                ));
1554            }
1555        }
1556
1557        Ok(arguments)
1558    }
1559
1560    fn parse_class_member(&mut self) -> Result<ClassMember> {
1561        let mut modifiers = Vec::new();
1562        let mut decorators = Vec::new();
1563
1564        // Parse decorators first
1565        while self.current_token() == &Token::At {
1566            self.advance(); // consume @
1567            let decorator_name = self.expect_identifier()?;
1568            decorators.push(decorator_name);
1569
1570            // Skip arguments for now (e.g., @log())
1571            if self.current_token() == &Token::LeftParen {
1572                self.advance(); // consume (
1573                // Skip arguments until closing paren
1574                let mut paren_count = 1;
1575                while paren_count > 0 && self.position < self.tokens.len() {
1576                    match self.current_token() {
1577                        Token::LeftParen => paren_count += 1,
1578                        Token::RightParen => paren_count -= 1,
1579                        _ => {}
1580                    }
1581                    self.advance();
1582                }
1583            }
1584        }
1585
1586        // Parse access modifiers
1587        while let Token::Keyword(keyword) = self.current_token() {
1588            match keyword {
1589                crate::lexer::Keyword::Public => {
1590                    modifiers.push(crate::ast::Modifier::Public);
1591                    self.advance();
1592                }
1593                crate::lexer::Keyword::Private => {
1594                    modifiers.push(crate::ast::Modifier::Private);
1595                    self.advance();
1596                }
1597                crate::lexer::Keyword::Protected => {
1598                    modifiers.push(crate::ast::Modifier::Protected);
1599                    self.advance();
1600                }
1601                crate::lexer::Keyword::Readonly => {
1602                    modifiers.push(crate::ast::Modifier::Readonly);
1603                    self.advance();
1604                }
1605                crate::lexer::Keyword::Static => {
1606                    modifiers.push(crate::ast::Modifier::Static);
1607                    self.advance();
1608                }
1609                _ => break,
1610            }
1611        }
1612
1613        // If we have decorators but no following member, return just the decorator
1614        if !decorators.is_empty() && self.position >= self.tokens.len() - 1 {
1615            return Ok(ClassMember::Decorator(decorators[0].clone()));
1616        }
1617
1618        let token = self.current_token().clone();
1619
1620        match token {
1621            Token::Keyword(crate::lexer::Keyword::Constructor) => {
1622                self.advance();
1623                let parameters = self.parse_parameters()?;
1624                let body = self.parse_block_statement()?;
1625
1626                Ok(ClassMember::Constructor(ConstructorDeclaration {
1627                    parameters,
1628                    body: Some(body),
1629                    modifiers,
1630                    decorators: decorators.clone(),
1631                }))
1632            }
1633            Token::Keyword(crate::lexer::Keyword::Get) => {
1634                self.advance();
1635                let name = if let Token::Identifier(name) = self.current_token() {
1636                    let name = name.clone();
1637                    self.advance();
1638                    name
1639                } else {
1640                    return Err(CompilerError::parse_error(
1641                        1,
1642                        1,
1643                        "Expected getter name".to_string(),
1644                    ));
1645                };
1646
1647                // Handle getter parameters (empty parentheses)
1648                if self.current_token() == &Token::LeftParen {
1649                    self.advance(); // consume '('
1650                    self.expect_token(&Token::RightParen)?; // consume ')'
1651                }
1652
1653                let return_type = if self.current_token() == &Token::Colon {
1654                    self.advance();
1655                    Some(self.parse_type()?)
1656                } else {
1657                    None
1658                };
1659                let body = if self.current_token() == &Token::LeftBrace {
1660                    self.parse_block_statement()?
1661                } else {
1662                    return Err(CompilerError::parse_error(
1663                        1,
1664                        1,
1665                        "Expected block statement for getter".to_string(),
1666                    ));
1667                };
1668
1669                Ok(ClassMember::Getter(GetterDeclaration {
1670                    name,
1671                    type_: return_type,
1672                    body: Some(body),
1673                    modifiers,
1674                    decorators,
1675                }))
1676            }
1677            Token::Keyword(crate::lexer::Keyword::Set) => {
1678                self.advance();
1679                let name = if let Token::Identifier(name) = self.current_token() {
1680                    let name = name.clone();
1681                    self.advance();
1682                    name
1683                } else {
1684                    return Err(CompilerError::parse_error(
1685                        1,
1686                        1,
1687                        "Expected setter name".to_string(),
1688                    ));
1689                };
1690
1691                let parameter = if self.current_token() == &Token::LeftParen {
1692                    self.advance(); // consume '('
1693                    let name = self.expect_identifier()?;
1694                    self.expect_token(&Token::Colon)?;
1695                    let type_annotation = self.parse_type()?;
1696                    self.expect_token(&Token::RightParen)?; // consume ')'
1697                    
1698                    Parameter {
1699                        name,
1700                        optional: false,
1701                        type_: Some(Box::new(type_annotation)),
1702                        initializer: None,
1703                        rest: false,
1704                    }
1705                } else {
1706                    return Err(CompilerError::parse_error(
1707                        1,
1708                        1,
1709                        "Expected setter parameter".to_string(),
1710                    ));
1711                };
1712
1713                let body = if self.current_token() == &Token::LeftBrace {
1714                    self.parse_block_statement()?
1715                } else {
1716                    return Err(CompilerError::parse_error(
1717                        1,
1718                        1,
1719                        "Expected block statement for setter".to_string(),
1720                    ));
1721                };
1722
1723                Ok(ClassMember::Setter(SetterDeclaration {
1724                    name,
1725                    parameter,
1726                    body: Some(body),
1727                    modifiers,
1728                    decorators,
1729                }))
1730            }
1731            Token::Identifier(name) => {
1732                self.advance();
1733
1734                // Special handling for constructor
1735                if name == "constructor" {
1736                    println!("DEBUG: parsing constructor");
1737                    // It's a constructor
1738                    let parameters = self.parse_parameters()?;
1739                    let body = self.parse_block_statement()?;
1740
1741                    Ok(ClassMember::Constructor(ConstructorDeclaration {
1742                        parameters,
1743                        body: Some(body),
1744                        modifiers,
1745                        decorators: decorators.clone(),
1746                    }))
1747                } else if self.current_token() == &Token::LeftParen {
1748                    // It's a method
1749                    let parameters = self.parse_parameters()?;
1750                    let return_type = if self.current_token() == &Token::Colon {
1751                        self.advance();
1752                        Some(self.parse_type()?)
1753                    } else {
1754                        None
1755                    };
1756                    let body = self.parse_block_statement()?;
1757
1758                    Ok(ClassMember::Method(MethodDeclaration {
1759                        name,
1760                        optional: false,
1761                        type_parameters: Vec::new(),
1762                        parameters,
1763                        return_type,
1764                        body: Some(body),
1765                        modifiers,
1766                        decorators,
1767                    }))
1768                } else if self.current_token() == &Token::Colon {
1769                    // It's a property
1770                    self.advance();
1771                    let type_annotation = self.parse_type()?;
1772                    
1773                    let initializer = if self.current_token() == &Token::Assign {
1774                        self.advance();
1775                        Some(self.parse_expression()?)
1776                    } else {
1777                        None
1778                    };
1779                    
1780                    self.expect_token(&Token::Semicolon)?;
1781
1782                    Ok(ClassMember::Property(PropertyDeclaration {
1783                        name,
1784                        optional: false,
1785                        type_: Some(type_annotation),
1786                        initializer,
1787                        modifiers,
1788                        decorators,
1789                    }))
1790                } else {
1791                    // It's a constructor
1792                    if name == "constructor" {
1793                        let parameters = self.parse_parameters()?;
1794                        let body = self.parse_block_statement()?;
1795
1796                    Ok(ClassMember::Constructor(ConstructorDeclaration {
1797                        parameters,
1798                        body: Some(body),
1799                        modifiers: Vec::new(),
1800                        decorators: Vec::new(),
1801                    }))
1802                    } else {
1803                        // If we can't parse as class member, try to skip the token
1804                        self.advance();
1805                        Err(CompilerError::parse_error(
1806                            self.position - 1,
1807                            1,
1808                            "Unexpected class member, skipping token".to_string(),
1809                        ))
1810                    }
1811                }
1812            }
1813            _ => {
1814                // If we can't parse as class member, try to skip the token
1815                self.advance();
1816                Err(CompilerError::parse_error(
1817                    self.position - 1,
1818                    1,
1819                    "Expected class member, skipping token".to_string(),
1820                ))
1821            }
1822        }
1823    }
1824
1825    fn parse_interface_member(&mut self) -> Result<ObjectTypeMember> {
1826        let mut readonly = false;
1827
1828        // Check for readonly modifier
1829        if let Token::Keyword(crate::lexer::Keyword::Readonly) = self.current_token() {
1830            readonly = true;
1831            self.advance();
1832            
1833            // Check if the next token is also 'readonly' (property name)
1834            if let Token::Keyword(crate::lexer::Keyword::Readonly) = self.current_token() {
1835                // Handle case where readonly is both modifier and property name: readonly readonly: boolean;
1836                let name = "readonly".to_string();
1837                self.advance(); // consume the property name 'readonly'
1838                
1839                if self.current_token() == &Token::Colon {
1840                    // It's a property signature
1841                    self.advance();
1842                    let type_annotation = self.parse_type()?;
1843                    self.expect_token(&Token::Semicolon)?;
1844
1845                    return Ok(ObjectTypeMember::Property(PropertySignature {
1846                        name,
1847                        optional: false,
1848                        type_: Some(type_annotation),
1849                        readonly,
1850                    }));
1851                } else {
1852                    return Err(CompilerError::parse_error(
1853                        1, 1,
1854                        "Expected colon after property name".to_string(),
1855                    ));
1856                }
1857            }
1858        }
1859        
1860        let token = self.current_token().clone();
1861
1862        match token {
1863            Token::Identifier(_) => {
1864                // This could be a method signature: methodName(params): ReturnType
1865                // First, check if there's a '(' after the identifier
1866                let name = if let Token::Identifier(name) = self.current_token() {
1867                    name.clone()
1868                } else {
1869                    return Err(CompilerError::parse_error(
1870                        1, 1,
1871                        "Expected identifier for interface member".to_string(),
1872                    ));
1873                };
1874
1875                // Look ahead to see if this is followed by '('
1876                if self.position + 1 < self.tokens.len() && self.tokens[self.position + 1] == Token::LeftParen {
1877                    // This is a method signature
1878                    self.advance(); // consume method name
1879                    let parameters = self.parse_parameters()?;
1880                    let return_type = if self.current_token() == &Token::Colon {
1881                        self.advance();
1882                        Some(self.parse_type()?)
1883                    } else {
1884                        None
1885                    };
1886                    self.expect_token(&Token::Semicolon)?;
1887
1888                    Ok(ObjectTypeMember::Method(MethodSignature {
1889                        name,
1890                        optional: false,
1891                        type_parameters: Vec::new(),
1892                        parameters,
1893                        return_type,
1894                    }))
1895                } else {
1896                    // This is a property signature
1897                    self.advance(); // consume property name
1898                    let optional = if self.current_token() == &Token::QuestionMark {
1899                        self.advance();
1900                        true
1901                    } else {
1902                        false
1903                    };
1904
1905                    self.expect_token(&Token::Colon)?;
1906                    let type_annotation = self.parse_type()?;
1907                    self.expect_token(&Token::Semicolon)?;
1908
1909                    Ok(ObjectTypeMember::Property(PropertySignature {
1910                        name,
1911                        optional,
1912                        type_: Some(type_annotation),
1913                        readonly,
1914                    }))
1915                }
1916            }
1917            Token::LeftParen => {
1918                // It's a call signature: (x: number, y: number): number;
1919                let parameters = self.parse_parameters()?;
1920                let return_type = if self.current_token() == &Token::Colon {
1921                    self.advance();
1922                    Some(self.parse_type()?)
1923                } else {
1924                    None
1925                };
1926                self.expect_token(&Token::Semicolon)?;
1927
1928                Ok(ObjectTypeMember::Method(MethodSignature {
1929                    name: "call".to_string(), // Use a default name for call signatures
1930                    optional: false,
1931                    type_parameters: Vec::new(),
1932                    parameters,
1933                    return_type,
1934                }))
1935            }
1936            Token::Keyword(crate::lexer::Keyword::New) => {
1937                // It's a construct signature: new (name: string): BasicInterface;
1938                self.advance(); // consume 'new'
1939                let parameters = self.parse_parameters()?;
1940                let return_type = if self.current_token() == &Token::Colon {
1941                    self.advance();
1942                    Some(self.parse_type()?)
1943                } else {
1944                    None
1945                };
1946                self.expect_token(&Token::Semicolon)?;
1947
1948                Ok(ObjectTypeMember::Method(MethodSignature {
1949                    name: "constructor".to_string(), // Use a default name for construct signatures
1950                    optional: false,
1951                    type_parameters: Vec::new(),
1952                    parameters,
1953                    return_type,
1954                }))
1955            }
1956            Token::Keyword(crate::lexer::Keyword::Readonly) => {
1957                // Handle case where readonly is the property name (without modifier)
1958                let name = "readonly".to_string();
1959                self.advance();
1960                
1961                if self.current_token() == &Token::Colon {
1962                    // It's a property signature
1963                    self.advance();
1964                    let type_annotation = self.parse_type()?;
1965                    self.expect_token(&Token::Semicolon)?;
1966
1967                    Ok(ObjectTypeMember::Property(PropertySignature {
1968                        name,
1969                        optional: false,
1970                        type_: Some(type_annotation),
1971                        readonly,
1972                    }))
1973                } else {
1974                    Err(CompilerError::parse_error(
1975                        1, 1,
1976                        "Expected colon after property name".to_string(),
1977                    ))
1978                }
1979            }
1980            Token::LeftBracket => {
1981                // It's an index signature: [key: string]: any;
1982                self.advance(); // consume '['
1983                let key_name = match self.current_token() {
1984                    Token::Identifier(name) => {
1985                        let name = name.clone();
1986                        self.advance();
1987                        name
1988                    }
1989                    Token::Keyword(crate::lexer::Keyword::Key) => {
1990                        self.advance();
1991                        "key".to_string()
1992                    }
1993                    _ => return Err(CompilerError::parse_error(
1994                        1, 1,
1995                        "Expected identifier or 'key' in index signature".to_string(),
1996                    ))
1997                };
1998                self.expect_token(&Token::Colon)?;
1999                let key_type = self.parse_type()?;
2000                self.expect_token(&Token::RightBracket)?;
2001                self.expect_token(&Token::Colon)?;
2002                let value_type = self.parse_type()?;
2003                self.expect_token(&Token::Semicolon)?;
2004
2005                Ok(ObjectTypeMember::Index(IndexSignature {
2006                    parameter: Box::new(Parameter {
2007                        name: key_name,
2008                        type_: Some(Box::new(key_type)),
2009                        optional: false,
2010                        initializer: None,
2011                        rest: false,
2012                    }),
2013                    type_: value_type,
2014                    readonly: false,
2015                }))
2016            }
2017            _ => Err(CompilerError::parse_error(
2018                1,
2019                1,
2020                "Expected interface member".to_string(),
2021            )),
2022        }
2023    }
2024
2025    fn parse_enum_member(&mut self) -> Result<EnumMember> {
2026        let name = self.expect_identifier()?;
2027
2028        let initializer = if self.current_token() == &Token::Assign {
2029            self.advance();
2030            Some(self.parse_expression()?)
2031        } else {
2032            None
2033        };
2034
2035        Ok(EnumMember { name, initializer })
2036    }
2037
2038    fn parse_if_statement(&mut self) -> Result<Statement> {
2039        self.expect_keyword()?; // if
2040
2041        self.expect_token(&Token::LeftParen)?;
2042        let test = self.parse_expression()?;
2043        self.expect_token(&Token::RightParen)?;
2044
2045        let consequent = self.parse_statement()?.unwrap();
2046
2047        let alternate = if self.current_token() == &Token::Keyword(crate::lexer::Keyword::Else) {
2048            self.advance();
2049            Some(self.parse_statement()?.unwrap())
2050        } else {
2051            None
2052        };
2053
2054        Ok(Statement::IfStatement(Box::new(IfStatement {
2055            condition: test,
2056            consequent: Box::new(consequent),
2057            alternate,
2058        })))
2059    }
2060
2061    fn parse_property_key(&mut self) -> Result<Expression> {
2062        // TODO: Implement property key parsing
2063        self.parse_expression()
2064    }
2065
2066    /// Parse index signature: [key: type]: returnType
2067    fn parse_index_signature(&mut self) -> Result<IndexSignature> {
2068        self.expect_token(&Token::LeftBracket)?;
2069        
2070        let key_name = match self.current_token() {
2071            Token::Identifier(name) => {
2072                let name = name.clone();
2073                self.advance();
2074                name
2075            }
2076            Token::Keyword(Keyword::Key) => {
2077                self.advance();
2078                "key".to_string()
2079            }
2080            _ => {
2081                return Err(CompilerError::parse_error(
2082                    self.position,
2083                    0,
2084                    format!("Expected identifier or 'key', found {:?}", self.current_token()),
2085                ));
2086            }
2087        };
2088        
2089        self.expect_token(&Token::Colon)?;
2090        let key_type = self.parse_type()?;
2091        self.expect_token(&Token::RightBracket)?;
2092        self.expect_token(&Token::Colon)?;
2093        let value_type = self.parse_type()?;
2094        
2095        Ok(IndexSignature {
2096            parameter: Box::new(Parameter {
2097                name: key_name,
2098                type_: Some(Box::new(key_type)),
2099                optional: false,
2100                initializer: None,
2101                rest: false,
2102            }),
2103            type_: value_type,
2104            readonly: false,
2105        })
2106    }
2107
2108    /// Parse mapped type: [P in K] or [P in keyof T]
2109    fn parse_mapped_type(&mut self) -> Result<MappedType> {
2110        // Parse [P in K]: T
2111        self.expect_token(&Token::LeftBracket)?;
2112        
2113        let type_parameter_name = match self.current_token() {
2114            Token::Identifier(name) => {
2115                let name = name.clone();
2116                self.advance();
2117                name
2118            }
2119            Token::Keyword(Keyword::Key) => {
2120                self.advance();
2121                "Key".to_string()
2122            }
2123            _ => {
2124                return Err(CompilerError::parse_error(
2125                    self.position,
2126                    0,
2127                    format!("Expected identifier or Key, found {:?}", self.current_token()),
2128                ));
2129            }
2130        };
2131        let type_parameter = TypeParameter {
2132            name: type_parameter_name.clone(),
2133            constraint: None,
2134            default: None,
2135        };
2136
2137        // Expect 'in' keyword
2138        if self.current_token() == &Token::Keyword(Keyword::In) {
2139            self.advance();
2140        } else {
2141            return Err(CompilerError::parse_error(
2142                self.position,
2143                0,
2144                format!("Expected 'in', found {:?}", self.current_token()),
2145            ));
2146        }
2147        
2148        let constraint_type = self.parse_type()?;
2149        
2150        self.expect_token(&Token::RightBracket)?;
2151        self.expect_token(&Token::Colon)?;
2152        
2153        let value_type = self.parse_type()?;
2154        
2155        // Skip semicolon if present (it's optional in mapped types)
2156        if self.current_token() == &Token::Semicolon {
2157            self.advance();
2158        }
2159        
2160        Ok(MappedType {
2161            type_parameter: Box::new(type_parameter),
2162            constraint: Some(Box::new(constraint_type)),
2163            name_type: None,
2164            type_: Box::new(value_type),
2165            readonly: None,
2166            optional: None,
2167        })
2168    }
2169
2170}