openscript 0.1.0

High-performance AI-powered scripting language runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! Parser for OpenScript
//!
//! This module implements a recursive descent parser that converts tokens
//! into an Abstract Syntax Tree (AST).

use crate::ast::*;
use crate::error::{Error, Result};
use crate::lexer::{Token, TokenKind};
use crate::value::Value;
use std::collections::HashMap;

/// Recursive descent parser for OpenScript
pub struct Parser {
    tokens: Vec<Token>,
    current: usize,
}

impl Parser {
    /// Create a new parser with the given tokens
    pub fn new(tokens: Vec<Token>) -> Self {
        Self { tokens, current: 0 }
    }

    /// Parse the tokens into a program AST
    pub fn parse(&mut self) -> Result<Program> {
        let mut statements = Vec::new();
        
        while !self.is_at_end() {
            // Skip newlines at the top level
            if self.match_token(&TokenKind::Newline) {
                continue;
            }
            
            statements.push(self.declaration()?);
        }
        
        Ok(Program { statements })
    }

    /// Parse a declaration (variable, function, or statement)
    fn declaration(&mut self) -> Result<Statement> {
        if self.match_token(&TokenKind::Let) {
            self.var_declaration(false)
        } else if self.match_token(&TokenKind::Const) {
            self.var_declaration(true)
        } else if self.match_token(&TokenKind::Function) {
            self.function_declaration()
        } else {
            self.statement()
        }
    }

    /// Parse a variable declaration
    fn var_declaration(&mut self, is_const: bool) -> Result<Statement> {
        let name = self.consume_identifier("Expected variable name")?;
        
        self.consume(&TokenKind::Assign, "Expected '=' after variable name")?;
        
        let value = self.expression()?;
        
        self.consume_statement_terminator()?;
        Ok(Statement::VarDeclaration {
            name,
            value,
            is_const,
        })
    }

    /// Parse a function declaration
    fn function_declaration(&mut self) -> Result<Statement> {
        let name = self.consume_identifier("Expected function name")?;
        
        self.consume(&TokenKind::LeftParen, "Expected '(' after function name")?;
        
        let mut parameters = Vec::new();
        if !self.check(&TokenKind::RightParen) {
            loop {
                let param_name = self.consume_identifier("Expected parameter name")?;
                let param_type = if self.match_token(&TokenKind::Colon) {
                    Some(self.parse_type()?)
                } else {
                    None
                };
                let default_value = if self.match_token(&TokenKind::Assign) {
                    Some(self.expression()?)
                } else {
                    None
                };
                
                parameters.push(Parameter {
                    name: param_name,
                    param_type,
                    default_value,
                });
                
                if !self.match_token(&TokenKind::Comma) {
                    break;
                }
            }
        }
        
        self.consume(&TokenKind::RightParen, "Expected ')' after parameters")?;
        
        let return_type = if self.match_token(&TokenKind::Arrow) {
            Some(self.parse_type()?)
        } else {
            None
        };
        
        self.consume(&TokenKind::LeftBrace, "Expected '{' before function body")?;
        let body = self.block_statement()?;
        
        Ok(Statement::Function {
            name,
            parameters,
            body: vec![body],
            return_type,
        })
    }

    /// Parse a type annotation
    fn parse_type(&mut self) -> Result<Type> {
        match &self.advance().kind {
            TokenKind::Identifier(name) => match name.as_str() {
                "string" => Ok(Type::String),
                "number" => Ok(Type::Number),
                "boolean" => Ok(Type::Boolean),
                "any" => Ok(Type::Any),
                "null" => Ok(Type::Null),
                _ => Err(self.error("Unknown type")),
            },
            TokenKind::LeftBracket => {
                let element_type = self.parse_type()?;
                self.consume(&TokenKind::RightBracket, "Expected ']' after array element type")?;
                Ok(Type::Array(Box::new(element_type)))
            }
            TokenKind::LeftBrace => {
                let mut fields = HashMap::new();
                
                while !self.check(&TokenKind::RightBrace) && !self.is_at_end() {
                    let field_name = self.consume_identifier("Expected field name")?;
                    self.consume(&TokenKind::Colon, "Expected ':' after field name")?;
                    let field_type = self.parse_type()?;
                    fields.insert(field_name, field_type);
                    
                    if !self.match_token(&TokenKind::Comma) {
                        break;
                    }
                }
                
                self.consume(&TokenKind::RightBrace, "Expected '}' after object type")?;
                Ok(Type::Object(fields))
            }
            _ => Err(self.error("Expected type")),
        }
    }

    /// Parse a statement
    fn statement(&mut self) -> Result<Statement> {
        if self.match_token(&TokenKind::If) {
            self.if_statement()
        } else if self.match_token(&TokenKind::While) {
            self.while_statement()
        } else if self.match_token(&TokenKind::For) {
            self.for_statement()
        } else if self.match_token(&TokenKind::Return) {
            self.return_statement()
        } else if self.match_token(&TokenKind::Break) {
            self.consume_statement_terminator()?;
            Ok(Statement::Break)
        } else if self.match_token(&TokenKind::Continue) {
            self.consume_statement_terminator()?;
            Ok(Statement::Continue)
        } else if self.match_token(&TokenKind::LeftBrace) {
            self.block_statement()
        } else {
            self.expression_statement()
        }
    }

    /// Parse an if statement
    fn if_statement(&mut self) -> Result<Statement> {
        let condition = self.expression()?;
        
        self.consume(&TokenKind::LeftBrace, "Expected '{' after if condition")?;
        let then_branch = self.block_body()?;
        
        let else_branch = if self.match_token(&TokenKind::Else) {
            if self.match_token(&TokenKind::If) {
                // Handle else if
                Some(vec![self.if_statement()?])
            } else {
                self.consume(&TokenKind::LeftBrace, "Expected '{' after else")?;
                Some(self.block_body()?)
            }
        } else {
            None
        };
        
        Ok(Statement::If {
            condition,
            then_branch,
            else_branch,
        })
    }

    /// Parse a while statement
    fn while_statement(&mut self) -> Result<Statement> {
        let condition = self.expression()?;
        self.consume(&TokenKind::LeftBrace, "Expected '{' after while condition")?;
        let body = self.block_body()?;
        
        Ok(Statement::While { condition, body })
    }

    /// Parse a for statement
    fn for_statement(&mut self) -> Result<Statement> {
        let variable = self.consume_identifier("Expected variable name in for loop")?;
        self.consume(&TokenKind::In, "Expected 'in' after for loop variable")?;
        let iterable = self.expression()?;
        
        self.consume(&TokenKind::LeftBrace, "Expected '{' after for loop iterable")?;
        let body = self.block_body()?;
        
        Ok(Statement::For {
            variable,
            iterable,
            body,
        })
    }

    /// Parse a return statement
    fn return_statement(&mut self) -> Result<Statement> {
        let value = if self.check(&TokenKind::Newline) || self.check(&TokenKind::Semicolon) || self.is_at_end() {
            None
        } else {
            Some(self.expression()?)
        };
        
        self.consume_statement_terminator()?;
        Ok(Statement::Return(value))
    }

    /// Parse a block statement
    fn block_statement(&mut self) -> Result<Statement> {
        let statements = self.block_body()?;
        Ok(Statement::Block(statements))
    }

    /// Parse the body of a block (between braces)
    fn block_body(&mut self) -> Result<Vec<Statement>> {
        let mut statements = Vec::new();
        
        while !self.check(&TokenKind::RightBrace) && !self.is_at_end() {
            if self.match_token(&TokenKind::Newline) {
                continue;
            }
            statements.push(self.declaration()?);
        }
        
        self.consume(&TokenKind::RightBrace, "Expected '}' after block")?;
        Ok(statements)
    }

    /// Parse an expression statement
    fn expression_statement(&mut self) -> Result<Statement> {
        let expr = self.expression()?;
        
        // Check for assignment
        if let Expression::Variable(name) = &expr {
            if let Some(op) = self.assignment_operator() {
                let value = self.expression()?;
                self.consume_statement_terminator()?;
                return Ok(Statement::Assignment {
                    target: AssignmentTarget::Variable(name.clone()),
                    operator: op,
                    value,
                });
            }
        } else if let Expression::Property { object, property } = &expr {
            if let Some(op) = self.assignment_operator() {
                let value = self.expression()?;
                self.consume_statement_terminator()?;
                return Ok(Statement::Assignment {
                    target: AssignmentTarget::Property {
                        object: *object.clone(),
                        property: property.clone(),
                    },
                    operator: op,
                    value,
                });
            }
        } else if let Expression::Index { object, index } = &expr {
            if let Some(op) = self.assignment_operator() {
                let value = self.expression()?;
                self.consume_statement_terminator()?;
                return Ok(Statement::Assignment {
                    target: AssignmentTarget::Index {
                        object: *object.clone(),
                        index: *index.clone(),
                    },
                    operator: op,
                    value,
                });
            }
        }
        
        self.consume_statement_terminator()?;
        Ok(Statement::Expression(expr))
    }

    /// Check for assignment operators
    fn assignment_operator(&mut self) -> Option<AssignmentOperator> {
        if self.match_token(&TokenKind::Assign) {
            Some(AssignmentOperator::Assign)
        } else if self.match_token(&TokenKind::PlusAssign) {
            Some(AssignmentOperator::PlusAssign)
        } else if self.match_token(&TokenKind::MinusAssign) {
            Some(AssignmentOperator::MinusAssign)
        } else {
            None
        }
    }

    /// Parse an expression
    fn expression(&mut self) -> Result<Expression> {
        self.conditional()
    }

    /// Parse a conditional expression (ternary operator)
    fn conditional(&mut self) -> Result<Expression> {
        let expr = self.logical_or()?;
        
        if self.match_token(&TokenKind::Question) {
            let true_expr = self.expression()?;
            self.consume(&TokenKind::Colon, "Expected ':' after conditional true expression")?;
            let false_expr = self.expression()?;
            Ok(Expression::Conditional {
                condition: Box::new(expr),
                true_expr: Box::new(true_expr), 
                false_expr: Box::new(false_expr),
            })
        } else {
            Ok(expr)
        }
    }

    /// Parse logical OR expression
    fn logical_or(&mut self) -> Result<Expression> {
        let mut expr = self.logical_and()?;
        
        while self.match_token(&TokenKind::Or) {
            let right = self.logical_and()?;
            expr = Expression::Binary {
                left: Box::new(expr),
                operator: BinaryOperator::Or,
                right: Box::new(right),
            };
        }
        
        Ok(expr)
    }

    /// Parse logical AND expression
    fn logical_and(&mut self) -> Result<Expression> {
        let mut expr = self.equality()?;
        
        while self.match_token(&TokenKind::And) {
            let right = self.equality()?;
            expr = Expression::Binary {
                left: Box::new(expr),
                operator: BinaryOperator::And,
                right: Box::new(right),
            };
        }
        
        Ok(expr)
    }

    /// Parse equality expression
    fn equality(&mut self) -> Result<Expression> {
        let mut expr = self.comparison()?;
        
        while let Some(op) = self.match_equality_operator() {
            let right = self.comparison()?;
            expr = Expression::Binary {
                left: Box::new(expr),
                operator: op,
                right: Box::new(right),
            };
        }
        
        Ok(expr)
    }

    /// Match equality operators
    fn match_equality_operator(&mut self) -> Option<BinaryOperator> {
        if self.match_token(&TokenKind::Equal) {
            Some(BinaryOperator::Equal)
        } else if self.match_token(&TokenKind::NotEqual) {
            Some(BinaryOperator::NotEqual)
        } else {
            None
        }
    }

    /// Parse comparison expression
    fn comparison(&mut self) -> Result<Expression> {
        let mut expr = self.term()?;
        
        while let Some(op) = self.match_comparison_operator() {
            let right = self.term()?;
            expr = Expression::Binary {
                left: Box::new(expr),
                operator: op,
                right: Box::new(right),
            };
        }
        
        Ok(expr)
    }

    /// Match comparison operators
    fn match_comparison_operator(&mut self) -> Option<BinaryOperator> {
        if self.match_token(&TokenKind::Greater) {
            Some(BinaryOperator::Greater)
        } else if self.match_token(&TokenKind::GreaterEqual) {
            Some(BinaryOperator::GreaterEqual)
        } else if self.match_token(&TokenKind::Less) {
            Some(BinaryOperator::Less)
        } else if self.match_token(&TokenKind::LessEqual) {
            Some(BinaryOperator::LessEqual)
        } else {
            None
        }
    }

    /// Parse term expression (addition/subtraction)
    fn term(&mut self) -> Result<Expression> {
        let mut expr = self.factor()?;
        
        while let Some(op) = self.match_term_operator() {
            let right = self.factor()?;
            expr = Expression::Binary {
                left: Box::new(expr),
                operator: op,
                right: Box::new(right),
            };
        }
        
        Ok(expr)
    }

    /// Match term operators
    fn match_term_operator(&mut self) -> Option<BinaryOperator> {
        if self.match_token(&TokenKind::Minus) {
            Some(BinaryOperator::Subtract)
        } else if self.match_token(&TokenKind::Plus) {
            Some(BinaryOperator::Add)
        } else {
            None
        }
    }

    /// Parse factor expression (multiplication/division)
    fn factor(&mut self) -> Result<Expression> {
        let mut expr = self.unary()?;
        
        while let Some(op) = self.match_factor_operator() {
            let right = self.unary()?;
            expr = Expression::Binary {
                left: Box::new(expr),
                operator: op,
                right: Box::new(right),
            };
        }
        
        Ok(expr)
    }

    /// Match factor operators
    fn match_factor_operator(&mut self) -> Option<BinaryOperator> {
        if self.match_token(&TokenKind::Divide) {
            Some(BinaryOperator::Divide)
        } else if self.match_token(&TokenKind::Multiply) {
            Some(BinaryOperator::Multiply)
        } else if self.match_token(&TokenKind::Modulo) {
            Some(BinaryOperator::Modulo)
        } else {
            None
        }
    }

    /// Parse unary expression
    fn unary(&mut self) -> Result<Expression> {
        if let Some(op) = self.match_unary_operator() {
            let operand = self.unary()?;
            Ok(Expression::Unary {
                operator: op,
                operand: Box::new(operand),
            })
        } else {
            self.call()
        }
    }

    fn match_unary_operator(&mut self) -> Option<UnaryOperator> {
        if self.match_token(&TokenKind::Minus) {
            Some(UnaryOperator::Minus)
        } else if self.match_token(&TokenKind::Not) {
            Some(UnaryOperator::Not)
        } else if self.match_token(&TokenKind::Tilde) {
            Some(UnaryOperator::BitwiseNot)
        } else {
            None
        }
    }

    fn call(&mut self) -> Result<Expression> {
        let mut expr = self.primary()?;

        loop {
            if self.match_token(&TokenKind::LeftParen) {
                expr = self.finish_call(expr)?;
            } else if self.match_token(&TokenKind::Dot) {
                let property = self.consume_identifier("Expected property name after '.'")?;
                expr = Expression::Property {
                    object: Box::new(expr),
                    property,
                };
            } else if self.match_token(&TokenKind::LeftBracket) {
                let index = self.expression()?;
                self.consume(&TokenKind::RightBracket, "Expected ']' after index")?;
                expr = Expression::Index {
                    object: Box::new(expr),
                    index: Box::new(index),
                };
            } else {
                break;
            }
        }

        Ok(expr)
    }
    
    fn finish_call(&mut self, callee: Expression) -> Result<Expression> {
        let mut arguments = Vec::new();
        if !self.check(&TokenKind::RightParen) {
            loop {
                arguments.push(self.expression()?);
                if !self.match_token(&TokenKind::Comma) {
                    break;
                }
            }
        }
        self.consume(&TokenKind::RightParen, "Expected ')' after arguments")?;

        Ok(Expression::Call {
            callee: Box::new(callee),
            arguments,
        })
    }

    /// Parse primary expression (literals, grouping)
    fn primary(&mut self) -> Result<Expression> {
        let token = self.advance().clone();
        match &token.kind {
            TokenKind::Number(n) => Ok(Expression::Literal(Value::Number(*n))),
            TokenKind::String(s) => Ok(Expression::Literal(Value::String(s.clone()))),
            TokenKind::True => Ok(Expression::Literal(Value::Boolean(true))),
            TokenKind::False => Ok(Expression::Literal(Value::Boolean(false))),
            TokenKind::Null => Ok(Expression::Literal(Value::Null)),
            TokenKind::Identifier(name) => Ok(Expression::Variable(name.clone())),
            TokenKind::LeftParen => {
                let expr = self.expression()?;
                self.consume(&TokenKind::RightParen, "Expected ')' after expression")?;
                Ok(expr)
            }
            TokenKind::LeftBracket => self.array_literal(),
            TokenKind::LeftBrace => self.object_literal(),
            _ => Err(self.error_at_token(&token, "Expected expression")),
        }
    }

    fn array_literal(&mut self) -> Result<Expression> {
        let mut elements = Vec::new();
        if !self.check(&TokenKind::RightBracket) {
            loop {
                elements.push(self.expression()?);
                if !self.match_token(&TokenKind::Comma) {
                    break;
                }
            }
        }
        self.consume(&TokenKind::RightBracket, "Expected ']' after array elements")?;
        Ok(Expression::Array(elements))
    }

    fn object_literal(&mut self) -> Result<Expression> {
        let mut properties = HashMap::new();
        if !self.check(&TokenKind::RightBrace) {
            loop {
                let key = self.consume_identifier("Expected property name")?;
                self.consume(&TokenKind::Colon, "Expected ':' after property name")?;
                let value = self.expression()?;
                properties.insert(key, value);
                if !self.match_token(&TokenKind::Comma) {
                    break;
                }
            }
        }
        self.consume(&TokenKind::RightBrace, "Expected '}' after object properties")?;
        Ok(Expression::Object(properties))
    }

    // Helper functions
    
    fn consume_identifier(&mut self, message: &str) -> Result<String> {
        if let TokenKind::Identifier(name) = &self.peek().kind {
            let name = name.clone();
            self.advance();
            Ok(name)
        } else {
            Err(self.error(message))
        }
    }

    fn consume_statement_terminator(&mut self) -> Result<()> {
        if self.match_token(&TokenKind::Semicolon) || self.match_token(&TokenKind::Newline) || self.is_at_end() {
            Ok(())
        } else {
            Err(self.error("Expected newline or ';' after statement"))
        }
    }

    /// Match a token of a given kind
    fn match_token(&mut self, kind: &TokenKind) -> bool {
        if self.check(kind) {
            self.advance();
            true
        } else {
            false
        }
    }

    /// Consume a token or return an error
    fn consume(&mut self, kind: &TokenKind, message: &str) -> Result<&Token> {
        if self.check(kind) {
            Ok(self.advance())
        } else {
            Err(self.error(message))
        }
    }

    /// Check if the current token is of a given kind
    fn check(&self, kind: &TokenKind) -> bool {
        if self.is_at_end() {
            return false;
        }
        &self.peek().kind == kind
    }

    /// Advance to the next token
    fn advance(&mut self) -> &Token {
        if !self.is_at_end() {
            self.current += 1;
        }
        self.previous()
    }

    /// Check if we are at the end of the token stream
    fn is_at_end(&self) -> bool {
        self.peek().kind == TokenKind::Eof
    }

    /// Get the current token
    fn peek(&self) -> &Token {
        &self.tokens[self.current]
    }

    /// Get the previous token
    fn previous(&self) -> &Token {
        &self.tokens[self.current - 1]
    }

    /// Create an error at the current token
    fn error(&self, message: &str) -> Error {
        self.error_at_token(self.peek(), message)
    }

    /// Create an error at a specific token
    fn error_at_token(&self, token: &Token, message: &str) -> Error {
        Error::parse_error(token.line, message.to_string())
    }
}