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                    Type::GenericNamed {
1024                        name: name.to_string(),
1025                        type_arguments: type_args,
1026                    }
1027                } else {
1028                    Type::Named(name.to_string())
1029                };
1030
1031                // Then check for array brackets
1032                if self.current_token() == &Token::LeftBracket {
1033                    self.advance(); // consume [
1034                    self.expect_token(&Token::RightBracket)?; // consume ]
1035                    Ok(Type::Array(Box::new(base_type)))
1036                } else {
1037                    Ok(base_type)
1038                }
1039            }
1040            Token::String(s) => {
1041                self.advance();
1042                // String literal type
1043                Ok(Type::Named(format!("\"{}\"", s)))
1044            }
1045            Token::Number(n) => {
1046                self.advance();
1047                // Number literal type
1048                Ok(Type::Named(n.to_string()))
1049            }
1050            Token::LeftParen => {
1051                self.advance();
1052                let type_ = self.parse_type()?;
1053                self.expect_token(&Token::RightParen)?;
1054                Ok(type_)
1055            }
1056       Token::LeftBrace => {
1057           // Parse object type: { prop: type; ... } or mapped type { [P in K]: T }
1058           self.advance(); // consume {
1059           let mut members = Vec::new();
1060
1061           while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
1062               // Check if this is a mapped type: [P in K] or index signature: [key: type]
1063               if self.current_token() == &Token::LeftBracket {
1064                   // Look ahead to determine if this is a mapped type or index signature
1065                   let mut pos = self.position + 1; // skip [
1066                   let mut is_mapped_type = false;
1067                   
1068                   // Look for 'in' keyword to distinguish mapped type from index signature
1069                   while pos < self.tokens.len() && self.tokens[pos] != Token::RightBracket {
1070                       if self.tokens[pos] == Token::Keyword(Keyword::In) {
1071                           is_mapped_type = true;
1072                           break;
1073                       }
1074                       pos += 1;
1075                   }
1076                   
1077                   if is_mapped_type {
1078                       let mapped_type = self.parse_mapped_type()?;
1079                       members.push(ObjectTypeMember::Property(PropertySignature {
1080                           name: mapped_type.type_parameter.name.clone(),
1081                           optional: false,
1082                           type_: Some(*mapped_type.type_.clone()),
1083                           readonly: mapped_type.readonly.unwrap_or(false),
1084                       }));
1085                       // parse_mapped_type already handles semicolon, so continue to next iteration
1086                       continue;
1087                   } else {
1088                       // This is an index signature, parse it as such
1089                       let index_sig = self.parse_index_signature()?;
1090                       members.push(ObjectTypeMember::Index(index_sig));
1091                       if self.current_token() == &Token::Semicolon {
1092                           self.advance();
1093                       }
1094                       continue;
1095                   }
1096               } else {
1097                   // Check for readonly modifier
1098                   let readonly = if self.current_token() == &Token::Keyword(Keyword::Readonly) {
1099                       self.advance(); // consume readonly
1100                       true
1101                   } else {
1102                       false
1103                   };
1104
1105                   let name = self.expect_identifier()?;
1106                   let optional = if self.current_token() == &Token::QuestionMark {
1107                       self.advance();
1108                       true
1109                   } else {
1110                       false
1111                   };
1112                   self.expect_token(&Token::Colon)?;
1113                   let type_ = self.parse_type()?;
1114
1115                   members.push(ObjectTypeMember::Property(PropertySignature {
1116                       name,
1117                       optional,
1118                       type_: Some(type_),
1119                       readonly,
1120                   }));
1121               }
1122
1123               if self.current_token() == &Token::Semicolon {
1124                   self.advance();
1125               }
1126           }
1127
1128           self.expect_token(&Token::RightBrace)?;
1129           Ok(Type::ObjectType(ObjectType { members }))
1130       }
1131            _ => Err(CompilerError::parse_error(
1132                self.position,
1133                0,
1134                format!("Unexpected token in type: {:?}", self.current_token()),
1135            )),
1136        }
1137    }
1138
1139    // Helper methods
1140    fn current_token(&self) -> &Token {
1141        &self.tokens[self.position]
1142    }
1143
1144    fn advance(&mut self) {
1145        if self.position < self.tokens.len() {
1146            self.position += 1;
1147        }
1148    }
1149
1150    fn expect_token(&mut self, expected: &Token) -> Result<()> {
1151        if self.current_token() == expected {
1152            self.advance();
1153            Ok(())
1154        } else {
1155            Err(CompilerError::parse_error(
1156                self.position,
1157                0,
1158                format!("Expected {:?}, found {:?}", expected, self.current_token()),
1159            ))
1160        }
1161    }
1162
1163    fn expect_keyword(&mut self) -> Result<crate::lexer::Keyword> {
1164        if let Token::Keyword(keyword) = self.current_token() {
1165            let keyword = keyword.clone();
1166            self.advance();
1167            Ok(keyword)
1168        } else {
1169            Err(CompilerError::parse_error(
1170                self.position,
1171                0,
1172                format!("Expected keyword, found {:?}", self.current_token()),
1173            ))
1174        }
1175    }
1176
1177    fn expect_identifier(&mut self) -> Result<String> {
1178        if let Token::Identifier(name) = self.current_token() {
1179            let name = name.clone();
1180            self.advance();
1181            Ok(name)
1182        } else {
1183            Err(CompilerError::parse_error(
1184                self.position,
1185                0,
1186                format!("Expected identifier, found {:?}", self.current_token()),
1187            ))
1188        }
1189    }
1190
1191    fn expect_semicolon(&mut self) -> Result<()> {
1192        self.expect_token(&Token::Semicolon)
1193    }
1194
1195    fn parse_string_literal(&mut self) -> Result<String> {
1196        if let Token::String(s) = self.current_token() {
1197            let s = s.clone();
1198            self.advance();
1199            Ok(s)
1200        } else {
1201            Err(CompilerError::parse_error(
1202                self.position,
1203                0,
1204                format!("Expected string literal, found {:?}", self.current_token()),
1205            ))
1206        }
1207    }
1208
1209    fn is_assignment_operator(&self) -> bool {
1210        matches!(
1211            self.current_token(),
1212            Token::Assign
1213                | Token::PlusAssign
1214                | Token::MinusAssign
1215                | Token::MultiplyAssign
1216                | Token::DivideAssign
1217        )
1218    }
1219
1220    fn is_equality_operator(&self) -> bool {
1221        matches!(
1222            self.current_token(),
1223            Token::Equal | Token::NotEqual | Token::StrictEqual | Token::StrictNotEqual
1224        )
1225    }
1226
1227    fn is_relational_operator(&self) -> bool {
1228        matches!(
1229            self.current_token(),
1230            Token::LessThan | Token::GreaterThan | Token::LessEqual | Token::GreaterEqual
1231        )
1232    }
1233
1234    fn is_additive_operator(&self) -> bool {
1235        matches!(self.current_token(), Token::Plus | Token::Minus)
1236    }
1237
1238    fn is_multiplicative_operator(&self) -> bool {
1239        matches!(
1240            self.current_token(),
1241            Token::Multiply | Token::Divide | Token::Modulo
1242        )
1243    }
1244
1245    fn is_unary_operator(&self) -> bool {
1246        matches!(
1247            self.current_token(),
1248            Token::Plus | Token::Minus | Token::Not | Token::Keyword(crate::lexer::Keyword::Typeof)
1249        )
1250    }
1251
1252    fn is_postfix_operator(&self) -> bool {
1253        matches!(
1254            self.current_token(),
1255            Token::LeftParen | Token::LeftBracket | Token::Dot
1256        )
1257    }
1258
1259    // Placeholder methods for complex parsing
1260    fn parse_type_parameters(&mut self) -> Result<Vec<TypeParameter>> {
1261        if self.current_token() == &Token::LessThan {
1262            self.advance();
1263            let mut type_parameters = Vec::new();
1264
1265            while self.current_token() != &Token::GreaterThan {
1266                let name = self.expect_identifier()?;
1267                let constraint =
1268                    if self.current_token() == &Token::Keyword(crate::lexer::Keyword::Extends) {
1269                        self.advance();
1270                        Some(self.parse_type()?)
1271                    } else {
1272                        None
1273                    };
1274
1275                let default_type = if self.current_token() == &Token::Assign {
1276                    self.advance();
1277                    Some(self.parse_type()?)
1278                } else {
1279                    None
1280                };
1281
1282                type_parameters.push(TypeParameter {
1283                    name,
1284                    constraint: constraint.map(Box::new),
1285                    default: default_type.map(Box::new),
1286                });
1287
1288                if self.current_token() == &Token::Comma {
1289                    self.advance();
1290                }
1291            }
1292
1293            self.expect_token(&Token::GreaterThan)?;
1294            Ok(type_parameters)
1295        } else {
1296            Ok(Vec::new())
1297        }
1298    }
1299
1300    fn parse_parameters(&mut self) -> Result<Vec<Parameter>> {
1301        self.expect_token(&Token::LeftParen)?;
1302        let mut parameters = Vec::new();
1303
1304        while self.current_token() != &Token::RightParen {
1305            // Handle access modifiers on parameters (TypeScript feature)
1306            let mut _modifiers = Vec::new();
1307            while let Token::Keyword(keyword) = self.current_token() {
1308                match keyword {
1309                    crate::lexer::Keyword::Public | 
1310                    crate::lexer::Keyword::Private | 
1311                    crate::lexer::Keyword::Protected | 
1312                    crate::lexer::Keyword::Readonly => {
1313                        _modifiers.push(keyword.clone());
1314                        self.advance();
1315                    }
1316                    _ => break,
1317                }
1318            }
1319            
1320            let name = self.expect_identifier()?;
1321            let optional = if self.current_token() == &Token::QuestionMark {
1322                self.advance();
1323                true
1324            } else {
1325                false
1326            };
1327
1328            let type_annotation = if self.current_token() == &Token::Colon {
1329                self.advance();
1330                Some(self.parse_type()?)
1331            } else {
1332                None
1333            };
1334
1335            let initializer = if self.current_token() == &Token::Assign {
1336                self.advance();
1337                Some(self.parse_expression()?)
1338            } else {
1339                None
1340            };
1341
1342            parameters.push(Parameter {
1343                name,
1344                optional,
1345                type_: type_annotation.map(Box::new),
1346                initializer,
1347                rest: false,
1348            });
1349
1350            if self.current_token() == &Token::Comma {
1351                self.advance();
1352            }
1353        }
1354
1355        self.expect_token(&Token::RightParen)?;
1356        Ok(parameters)
1357    }
1358    
1359    fn parse_parameter_list(&mut self) -> Result<Vec<Parameter>> {
1360        let mut parameters = Vec::new();
1361
1362        while self.current_token() != &Token::RightParen {
1363            // Handle access modifiers on parameters (TypeScript feature)
1364            let mut _modifiers = Vec::new();
1365            while let Token::Keyword(keyword) = self.current_token() {
1366                match keyword {
1367                    crate::lexer::Keyword::Public | 
1368                    crate::lexer::Keyword::Private | 
1369                    crate::lexer::Keyword::Protected | 
1370                    crate::lexer::Keyword::Readonly => {
1371                        _modifiers.push(keyword.clone());
1372                        self.advance();
1373                    }
1374                    _ => break,
1375                }
1376            }
1377            
1378            let name = self.expect_identifier()?;
1379            let optional = if self.current_token() == &Token::QuestionMark {
1380                self.advance();
1381                true
1382            } else {
1383                false
1384            };
1385
1386            let type_annotation = if self.current_token() == &Token::Colon {
1387                self.advance();
1388                Some(self.parse_type()?)
1389            } else {
1390                None
1391            };
1392
1393            let initializer = if self.current_token() == &Token::Assign {
1394                self.advance();
1395                Some(self.parse_expression()?)
1396            } else {
1397                None
1398            };
1399
1400            parameters.push(Parameter {
1401                name,
1402                optional,
1403                type_: type_annotation.map(Box::new),
1404                initializer,
1405                rest: false,
1406            });
1407
1408            if self.current_token() == &Token::Comma {
1409                self.advance();
1410            }
1411        }
1412
1413        Ok(parameters)
1414    }
1415
1416    fn parse_implements(&mut self) -> Result<Vec<Type>> {
1417        if self.current_token() == &Token::Keyword(crate::lexer::Keyword::Implements) {
1418            self.advance();
1419            let mut types = Vec::new();
1420
1421            loop {
1422                let type_ = self.parse_type()?;
1423                types.push(type_);
1424
1425                if self.current_token() == &Token::Comma {
1426                    self.advance();
1427                } else {
1428                    break;
1429                }
1430            }
1431
1432            Ok(types)
1433        } else {
1434            Ok(Vec::new())
1435        }
1436    }
1437
1438    fn parse_extends(&mut self) -> Result<Vec<Type>> {
1439        let mut extends = Vec::new();
1440        
1441        if self.current_token() == &Token::Keyword(crate::lexer::Keyword::Extends) {
1442            self.advance(); // consume 'extends'
1443            
1444            // Parse the first extended type
1445            let type_ = self.parse_type()?;
1446            extends.push(type_);
1447            
1448            // Parse additional extended types (comma-separated)
1449            while self.current_token() == &Token::Comma {
1450                self.advance(); // consume ','
1451                let type_ = self.parse_type()?;
1452                extends.push(type_);
1453            }
1454        }
1455        
1456        Ok(extends)
1457    }
1458
1459    fn parse_class_body(&mut self) -> Result<ClassBody> {
1460        self.expect_token(&Token::LeftBrace)?;
1461        let mut members = Vec::new();
1462
1463        while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
1464            let member = self.parse_class_member()?;
1465            members.push(member.clone());
1466
1467            // Handle decorator-only members
1468            if let ClassMember::Decorator(_) = &member {
1469                continue;
1470            }
1471        }
1472
1473        self.expect_token(&Token::RightBrace)?;
1474        Ok(ClassBody { members })
1475    }
1476
1477    fn parse_interface_body(&mut self) -> Result<InterfaceBody> {
1478        self.expect_token(&Token::LeftBrace)?;
1479        let mut members = Vec::new();
1480
1481        while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
1482            let member = self.parse_interface_member()?;
1483            members.push(member);
1484        }
1485        self.expect_token(&Token::RightBrace)?;
1486        Ok(InterfaceBody { members })
1487    }
1488
1489    fn parse_enum_members(&mut self) -> Result<Vec<EnumMember>> {
1490        self.expect_token(&Token::LeftBrace)?;
1491        let mut members = Vec::new();
1492
1493        while self.current_token() != &Token::RightBrace && self.current_token() != &Token::EOF {
1494            let member = self.parse_enum_member()?;
1495            members.push(member);
1496
1497            if self.current_token() == &Token::Comma {
1498                self.advance();
1499            }
1500        }
1501
1502        self.expect_token(&Token::RightBrace)?;
1503        Ok(members)
1504    }
1505
1506    fn parse_import_specifiers(&mut self) -> Result<Vec<ImportSpecifier>> {
1507        let mut specifiers = Vec::new();
1508
1509        if self.current_token() == &Token::LeftBrace {
1510            self.advance(); // consume '{'
1511
1512            while self.current_token() != &Token::RightBrace {
1513                let name = self.expect_identifier()?;
1514                specifiers.push(ImportSpecifier::Named(NamedImportSpecifier {
1515                    imported: name.clone(),
1516                    name,
1517                }));
1518
1519                if self.current_token() == &Token::Comma {
1520                    self.advance();
1521                }
1522            }
1523
1524            self.expect_token(&Token::RightBrace)?; // consume '}'
1525        } else {
1526            // Default import
1527            let name = self.expect_identifier()?;
1528            specifiers.push(ImportSpecifier::Default(DefaultImportSpecifier { name }));
1529        }
1530
1531        Ok(specifiers)
1532    }
1533
1534    fn parse_arguments(&mut self) -> Result<Vec<Expression>> {
1535        let mut arguments = Vec::new();
1536
1537        while self.current_token() != &Token::RightParen {
1538            let argument = self.parse_expression()?;
1539            arguments.push(argument);
1540
1541            if self.current_token() == &Token::Comma {
1542                self.advance();
1543            } else if self.current_token() != &Token::RightParen {
1544                return Err(CompilerError::parse_error(
1545                    1,
1546                    1,
1547                    "Expected comma or closing parenthesis".to_string(),
1548                ));
1549            }
1550        }
1551
1552        Ok(arguments)
1553    }
1554
1555    fn parse_class_member(&mut self) -> Result<ClassMember> {
1556        let mut modifiers = Vec::new();
1557        let mut decorators = Vec::new();
1558
1559        // Parse decorators first
1560        while self.current_token() == &Token::At {
1561            self.advance(); // consume @
1562            let decorator_name = self.expect_identifier()?;
1563            decorators.push(decorator_name);
1564
1565            // Skip arguments for now (e.g., @log())
1566            if self.current_token() == &Token::LeftParen {
1567                self.advance(); // consume (
1568                // Skip arguments until closing paren
1569                let mut paren_count = 1;
1570                while paren_count > 0 && self.position < self.tokens.len() {
1571                    match self.current_token() {
1572                        Token::LeftParen => paren_count += 1,
1573                        Token::RightParen => paren_count -= 1,
1574                        _ => {}
1575                    }
1576                    self.advance();
1577                }
1578            }
1579        }
1580
1581        // Parse access modifiers
1582        while let Token::Keyword(keyword) = self.current_token() {
1583            match keyword {
1584                crate::lexer::Keyword::Public => {
1585                    modifiers.push(crate::ast::Modifier::Public);
1586                    self.advance();
1587                }
1588                crate::lexer::Keyword::Private => {
1589                    modifiers.push(crate::ast::Modifier::Private);
1590                    self.advance();
1591                }
1592                crate::lexer::Keyword::Protected => {
1593                    modifiers.push(crate::ast::Modifier::Protected);
1594                    self.advance();
1595                }
1596                crate::lexer::Keyword::Readonly => {
1597                    modifiers.push(crate::ast::Modifier::Readonly);
1598                    self.advance();
1599                }
1600                crate::lexer::Keyword::Static => {
1601                    modifiers.push(crate::ast::Modifier::Static);
1602                    self.advance();
1603                }
1604                _ => break,
1605            }
1606        }
1607
1608        // If we have decorators but no following member, return just the decorator
1609        if !decorators.is_empty() && self.position >= self.tokens.len() - 1 {
1610            return Ok(ClassMember::Decorator(decorators[0].clone()));
1611        }
1612
1613        let token = self.current_token().clone();
1614
1615        match token {
1616            Token::Keyword(crate::lexer::Keyword::Constructor) => {
1617                self.advance();
1618                let parameters = self.parse_parameters()?;
1619                let body = self.parse_block_statement()?;
1620
1621                Ok(ClassMember::Constructor(ConstructorDeclaration {
1622                    parameters,
1623                    body: Some(body),
1624                    modifiers,
1625                    decorators: decorators.clone(),
1626                }))
1627            }
1628            Token::Keyword(crate::lexer::Keyword::Get) => {
1629                self.advance();
1630                let name = if let Token::Identifier(name) = self.current_token() {
1631                    let name = name.clone();
1632                    self.advance();
1633                    name
1634                } else {
1635                    return Err(CompilerError::parse_error(
1636                        1,
1637                        1,
1638                        "Expected getter name".to_string(),
1639                    ));
1640                };
1641
1642                // Handle getter parameters (empty parentheses)
1643                if self.current_token() == &Token::LeftParen {
1644                    self.advance(); // consume '('
1645                    self.expect_token(&Token::RightParen)?; // consume ')'
1646                }
1647
1648                let return_type = if self.current_token() == &Token::Colon {
1649                    self.advance();
1650                    Some(self.parse_type()?)
1651                } else {
1652                    None
1653                };
1654                let body = if self.current_token() == &Token::LeftBrace {
1655                    self.parse_block_statement()?
1656                } else {
1657                    return Err(CompilerError::parse_error(
1658                        1,
1659                        1,
1660                        "Expected block statement for getter".to_string(),
1661                    ));
1662                };
1663
1664                Ok(ClassMember::Getter(GetterDeclaration {
1665                    name,
1666                    type_: return_type,
1667                    body: Some(body),
1668                    modifiers,
1669                    decorators,
1670                }))
1671            }
1672            Token::Keyword(crate::lexer::Keyword::Set) => {
1673                self.advance();
1674                let name = if let Token::Identifier(name) = self.current_token() {
1675                    let name = name.clone();
1676                    self.advance();
1677                    name
1678                } else {
1679                    return Err(CompilerError::parse_error(
1680                        1,
1681                        1,
1682                        "Expected setter name".to_string(),
1683                    ));
1684                };
1685
1686                let parameter = if self.current_token() == &Token::LeftParen {
1687                    self.advance(); // consume '('
1688                    let name = self.expect_identifier()?;
1689                    self.expect_token(&Token::Colon)?;
1690                    let type_annotation = self.parse_type()?;
1691                    self.expect_token(&Token::RightParen)?; // consume ')'
1692                    
1693                    Parameter {
1694                        name,
1695                        optional: false,
1696                        type_: Some(Box::new(type_annotation)),
1697                        initializer: None,
1698                        rest: false,
1699                    }
1700                } else {
1701                    return Err(CompilerError::parse_error(
1702                        1,
1703                        1,
1704                        "Expected setter parameter".to_string(),
1705                    ));
1706                };
1707
1708                let body = if self.current_token() == &Token::LeftBrace {
1709                    self.parse_block_statement()?
1710                } else {
1711                    return Err(CompilerError::parse_error(
1712                        1,
1713                        1,
1714                        "Expected block statement for setter".to_string(),
1715                    ));
1716                };
1717
1718                Ok(ClassMember::Setter(SetterDeclaration {
1719                    name,
1720                    parameter,
1721                    body: Some(body),
1722                    modifiers,
1723                    decorators,
1724                }))
1725            }
1726            Token::Identifier(name) => {
1727                self.advance();
1728
1729                // Special handling for constructor
1730                if name == "constructor" {
1731                    println!("DEBUG: parsing constructor");
1732                    // It's a constructor
1733                    let parameters = self.parse_parameters()?;
1734                    let body = self.parse_block_statement()?;
1735
1736                    Ok(ClassMember::Constructor(ConstructorDeclaration {
1737                        parameters,
1738                        body: Some(body),
1739                        modifiers,
1740                        decorators: decorators.clone(),
1741                    }))
1742                } else if self.current_token() == &Token::LeftParen {
1743                    // It's a method
1744                    let parameters = self.parse_parameters()?;
1745                    let return_type = if self.current_token() == &Token::Colon {
1746                        self.advance();
1747                        Some(self.parse_type()?)
1748                    } else {
1749                        None
1750                    };
1751                    let body = self.parse_block_statement()?;
1752
1753                    Ok(ClassMember::Method(MethodDeclaration {
1754                        name,
1755                        optional: false,
1756                        type_parameters: Vec::new(),
1757                        parameters,
1758                        return_type,
1759                        body: Some(body),
1760                        modifiers,
1761                        decorators,
1762                    }))
1763                } else if self.current_token() == &Token::Colon {
1764                    // It's a property
1765                    self.advance();
1766                    let type_annotation = self.parse_type()?;
1767                    
1768                    let initializer = if self.current_token() == &Token::Assign {
1769                        self.advance();
1770                        Some(self.parse_expression()?)
1771                    } else {
1772                        None
1773                    };
1774                    
1775                    self.expect_token(&Token::Semicolon)?;
1776
1777                    Ok(ClassMember::Property(PropertyDeclaration {
1778                        name,
1779                        optional: false,
1780                        type_: Some(type_annotation),
1781                        initializer,
1782                        modifiers,
1783                        decorators,
1784                    }))
1785                } else {
1786                    // It's a constructor
1787                    if name == "constructor" {
1788                        let parameters = self.parse_parameters()?;
1789                        let body = self.parse_block_statement()?;
1790
1791                    Ok(ClassMember::Constructor(ConstructorDeclaration {
1792                        parameters,
1793                        body: Some(body),
1794                        modifiers: Vec::new(),
1795                        decorators: Vec::new(),
1796                    }))
1797                    } else {
1798                        // If we can't parse as class member, try to skip the token
1799                        self.advance();
1800                        Err(CompilerError::parse_error(
1801                            self.position - 1,
1802                            1,
1803                            "Unexpected class member, skipping token".to_string(),
1804                        ))
1805                    }
1806                }
1807            }
1808            _ => {
1809                // If we can't parse as class member, try to skip the token
1810                self.advance();
1811                Err(CompilerError::parse_error(
1812                    self.position - 1,
1813                    1,
1814                    "Expected class member, skipping token".to_string(),
1815                ))
1816            }
1817        }
1818    }
1819
1820    fn parse_interface_member(&mut self) -> Result<ObjectTypeMember> {
1821        let mut readonly = false;
1822        
1823        // Check for readonly modifier
1824        if let Token::Keyword(crate::lexer::Keyword::Readonly) = self.current_token() {
1825            readonly = true;
1826            self.advance();
1827            
1828            // Check if the next token is also 'readonly' (property name)
1829            if let Token::Keyword(crate::lexer::Keyword::Readonly) = self.current_token() {
1830                // Handle case where readonly is both modifier and property name: readonly readonly: boolean;
1831                let name = "readonly".to_string();
1832                self.advance(); // consume the property name 'readonly'
1833                
1834                if self.current_token() == &Token::Colon {
1835                    // It's a property signature
1836                    self.advance();
1837                    let type_annotation = self.parse_type()?;
1838                    self.expect_token(&Token::Semicolon)?;
1839
1840                    return Ok(ObjectTypeMember::Property(PropertySignature {
1841                        name,
1842                        optional: false,
1843                        type_: Some(type_annotation),
1844                        readonly,
1845                    }));
1846                } else {
1847                    return Err(CompilerError::parse_error(
1848                        1, 1,
1849                        "Expected colon after property name".to_string(),
1850                    ));
1851                }
1852            }
1853        }
1854        
1855        let token = self.current_token().clone();
1856
1857        match token {
1858            Token::Identifier(_) => {
1859                // This could be a method signature: methodName(params): ReturnType
1860                // First, check if there's a '(' after the identifier
1861                let name = if let Token::Identifier(name) = self.current_token() {
1862                    name.clone()
1863                } else {
1864                    return Err(CompilerError::parse_error(
1865                        1, 1,
1866                        "Expected identifier for interface member".to_string(),
1867                    ));
1868                };
1869
1870                // Look ahead to see if this is followed by '('
1871                if self.position + 1 < self.tokens.len() && self.tokens[self.position + 1] == Token::LeftParen {
1872                    // This is a method signature
1873                    self.advance(); // consume method name
1874                    let parameters = self.parse_parameters()?;
1875                    let return_type = if self.current_token() == &Token::Colon {
1876                        self.advance();
1877                        Some(self.parse_type()?)
1878                    } else {
1879                        None
1880                    };
1881                    self.expect_token(&Token::Semicolon)?;
1882
1883                    Ok(ObjectTypeMember::Method(MethodSignature {
1884                        name,
1885                        optional: false,
1886                        type_parameters: Vec::new(),
1887                        parameters,
1888                        return_type,
1889                    }))
1890                } else {
1891                    // This is a property signature
1892                    self.advance(); // consume property name
1893                    let optional = if self.current_token() == &Token::QuestionMark {
1894                        self.advance();
1895                        true
1896                    } else {
1897                        false
1898                    };
1899
1900                    self.expect_token(&Token::Colon)?;
1901                    let type_annotation = self.parse_type()?;
1902                    self.expect_token(&Token::Semicolon)?;
1903
1904                    Ok(ObjectTypeMember::Property(PropertySignature {
1905                        name,
1906                        optional,
1907                        type_: Some(type_annotation),
1908                        readonly,
1909                    }))
1910                }
1911            }
1912            Token::LeftParen => {
1913                // It's a call signature: (x: number, y: number): number;
1914                let parameters = self.parse_parameters()?;
1915                let return_type = if self.current_token() == &Token::Colon {
1916                    self.advance();
1917                    Some(self.parse_type()?)
1918                } else {
1919                    None
1920                };
1921                self.expect_token(&Token::Semicolon)?;
1922
1923                Ok(ObjectTypeMember::Method(MethodSignature {
1924                    name: "call".to_string(), // Use a default name for call signatures
1925                    optional: false,
1926                    type_parameters: Vec::new(),
1927                    parameters,
1928                    return_type,
1929                }))
1930            }
1931            Token::Keyword(crate::lexer::Keyword::New) => {
1932                // It's a construct signature: new (name: string): BasicInterface;
1933                self.advance(); // consume 'new'
1934                let parameters = self.parse_parameters()?;
1935                let return_type = if self.current_token() == &Token::Colon {
1936                    self.advance();
1937                    Some(self.parse_type()?)
1938                } else {
1939                    None
1940                };
1941                self.expect_token(&Token::Semicolon)?;
1942
1943                Ok(ObjectTypeMember::Method(MethodSignature {
1944                    name: "constructor".to_string(), // Use a default name for construct signatures
1945                    optional: false,
1946                    type_parameters: Vec::new(),
1947                    parameters,
1948                    return_type,
1949                }))
1950            }
1951            Token::Keyword(crate::lexer::Keyword::Readonly) => {
1952                // Handle case where readonly is the property name (without modifier)
1953                let name = "readonly".to_string();
1954                self.advance();
1955                
1956                if self.current_token() == &Token::Colon {
1957                    // It's a property signature
1958                    self.advance();
1959                    let type_annotation = self.parse_type()?;
1960                    self.expect_token(&Token::Semicolon)?;
1961
1962                    Ok(ObjectTypeMember::Property(PropertySignature {
1963                        name,
1964                        optional: false,
1965                        type_: Some(type_annotation),
1966                        readonly,
1967                    }))
1968                } else {
1969                    Err(CompilerError::parse_error(
1970                        1, 1,
1971                        "Expected colon after property name".to_string(),
1972                    ))
1973                }
1974            }
1975            Token::LeftBracket => {
1976                // It's an index signature: [key: string]: any;
1977                self.advance(); // consume '['
1978                let key_name = match self.current_token() {
1979                    Token::Identifier(name) => {
1980                        let name = name.clone();
1981                        self.advance();
1982                        name
1983                    }
1984                    Token::Keyword(crate::lexer::Keyword::Key) => {
1985                        self.advance();
1986                        "key".to_string()
1987                    }
1988                    _ => return Err(CompilerError::parse_error(
1989                        1, 1,
1990                        "Expected identifier or 'key' in index signature".to_string(),
1991                    ))
1992                };
1993                self.expect_token(&Token::Colon)?;
1994                let key_type = self.parse_type()?;
1995                self.expect_token(&Token::RightBracket)?;
1996                self.expect_token(&Token::Colon)?;
1997                let value_type = self.parse_type()?;
1998                self.expect_token(&Token::Semicolon)?;
1999
2000                Ok(ObjectTypeMember::Index(IndexSignature {
2001                    parameter: Box::new(Parameter {
2002                        name: key_name,
2003                        type_: Some(Box::new(key_type)),
2004                        optional: false,
2005                        initializer: None,
2006                        rest: false,
2007                    }),
2008                    type_: value_type,
2009                    readonly: false,
2010                }))
2011            }
2012            _ => Err(CompilerError::parse_error(
2013                1,
2014                1,
2015                "Expected interface member".to_string(),
2016            )),
2017        }
2018    }
2019
2020    fn parse_enum_member(&mut self) -> Result<EnumMember> {
2021        let name = self.expect_identifier()?;
2022
2023        let initializer = if self.current_token() == &Token::Assign {
2024            self.advance();
2025            Some(self.parse_expression()?)
2026        } else {
2027            None
2028        };
2029
2030        Ok(EnumMember { name, initializer })
2031    }
2032
2033    fn parse_if_statement(&mut self) -> Result<Statement> {
2034        self.expect_keyword()?; // if
2035
2036        self.expect_token(&Token::LeftParen)?;
2037        let test = self.parse_expression()?;
2038        self.expect_token(&Token::RightParen)?;
2039
2040        let consequent = self.parse_statement()?.unwrap();
2041
2042        let alternate = if self.current_token() == &Token::Keyword(crate::lexer::Keyword::Else) {
2043            self.advance();
2044            Some(self.parse_statement()?.unwrap())
2045        } else {
2046            None
2047        };
2048
2049        Ok(Statement::IfStatement(Box::new(IfStatement {
2050            condition: test,
2051            consequent: Box::new(consequent),
2052            alternate,
2053        })))
2054    }
2055
2056    fn parse_property_key(&mut self) -> Result<Expression> {
2057        // TODO: Implement property key parsing
2058        self.parse_expression()
2059    }
2060
2061    /// Parse index signature: [key: type]: returnType
2062    fn parse_index_signature(&mut self) -> Result<IndexSignature> {
2063        self.expect_token(&Token::LeftBracket)?;
2064        
2065        let key_name = match self.current_token() {
2066            Token::Identifier(name) => {
2067                let name = name.clone();
2068                self.advance();
2069                name
2070            }
2071            Token::Keyword(Keyword::Key) => {
2072                self.advance();
2073                "key".to_string()
2074            }
2075            _ => {
2076                return Err(CompilerError::parse_error(
2077                    self.position,
2078                    0,
2079                    format!("Expected identifier or 'key', found {:?}", self.current_token()),
2080                ));
2081            }
2082        };
2083        
2084        self.expect_token(&Token::Colon)?;
2085        let key_type = self.parse_type()?;
2086        self.expect_token(&Token::RightBracket)?;
2087        self.expect_token(&Token::Colon)?;
2088        let value_type = self.parse_type()?;
2089        
2090        Ok(IndexSignature {
2091            parameter: Box::new(Parameter {
2092                name: key_name,
2093                type_: Some(Box::new(key_type)),
2094                optional: false,
2095                initializer: None,
2096                rest: false,
2097            }),
2098            type_: value_type,
2099            readonly: false,
2100        })
2101    }
2102
2103    /// Parse mapped type: [P in K] or [P in keyof T]
2104    fn parse_mapped_type(&mut self) -> Result<MappedType> {
2105        // Parse [P in K]: T
2106        self.expect_token(&Token::LeftBracket)?;
2107        
2108        let type_parameter_name = match self.current_token() {
2109            Token::Identifier(name) => {
2110                let name = name.clone();
2111                self.advance();
2112                name
2113            }
2114            Token::Keyword(Keyword::Key) => {
2115                self.advance();
2116                "Key".to_string()
2117            }
2118            _ => {
2119                return Err(CompilerError::parse_error(
2120                    self.position,
2121                    0,
2122                    format!("Expected identifier or Key, found {:?}", self.current_token()),
2123                ));
2124            }
2125        };
2126        let type_parameter = TypeParameter {
2127            name: type_parameter_name.clone(),
2128            constraint: None,
2129            default: None,
2130        };
2131
2132        // Expect 'in' keyword
2133        if self.current_token() == &Token::Keyword(Keyword::In) {
2134            self.advance();
2135        } else {
2136            return Err(CompilerError::parse_error(
2137                self.position,
2138                0,
2139                format!("Expected 'in', found {:?}", self.current_token()),
2140            ));
2141        }
2142        
2143        let constraint_type = self.parse_type()?;
2144        
2145        self.expect_token(&Token::RightBracket)?;
2146        self.expect_token(&Token::Colon)?;
2147        
2148        let value_type = self.parse_type()?;
2149        
2150        // Skip semicolon if present (it's optional in mapped types)
2151        if self.current_token() == &Token::Semicolon {
2152            self.advance();
2153        }
2154        
2155        Ok(MappedType {
2156            type_parameter: Box::new(type_parameter),
2157            constraint: Some(Box::new(constraint_type)),
2158            name_type: None,
2159            type_: Box::new(value_type),
2160            readonly: None,
2161            optional: None,
2162        })
2163    }
2164
2165}