meow-meow-script 0.6.0

A host-neutral parser, runtime, and evaluator for Meow Meow Script
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
use crate::ast::{
    AssignmentStatement, BinOpKind, BlockStatement, CallExpression, ComponentExpression,
    ConstructorCall, ElseBranch, Expression, Ident, IfStatement, ImportItem, ReturnStatement, Span,
    Statement, TableFieldValue, UnaryOpKind,
};
use crate::token::{Token, TokenKind};
use std::collections::HashSet;

#[derive(Debug, Clone, PartialEq)]
pub struct ParseError {
    pub message: String,
    pub token_index: usize,
    pub span: Span,
}

pub struct MeowMeowParser {
    tokens: Vec<Token>,
    pos: usize,
    component_names: Option<HashSet<String>>,
}

impl MeowMeowParser {
    pub fn new(tokens: Vec<Token>) -> Self {
        Self { tokens, pos: 0, component_names: None }
    }

    /// Construct a parser whose component-expression disambiguation is driven
    /// by a runtime catalog. Names are matched case-insensitively.
    pub fn with_component_names(
        tokens: Vec<Token>,
        names: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            tokens,
            pos: 0,
            component_names: Some(
                names
                    .into_iter()
                    .map(|name| name.into().to_lowercase())
                    .collect(),
            ),
        }
    }

    fn is_component_name(&self, name: &str) -> bool {
        self.component_names.as_ref().map_or_else(
            || name.chars().next().is_some_and(char::is_uppercase),
            |names| names.contains(&name.to_lowercase()),
        )
    }

    pub fn parse_program(mut self) -> Result<Vec<Statement>, ParseError> {
        let mut statements = Vec::new();
        while !self.is_eof() {
            if self.try_consume(&TokenKind::Semicolon) {
                continue;
            }
            statements.push(self.parse_statement()?);
        }
        Ok(statements)
    }

    fn parse_statement(&mut self) -> Result<Statement, ParseError> {
        match self.peek_kind() {
            TokenKind::Let => {
                self.consume(&TokenKind::Let)?;
                let name = self.expect_ident()?;
                self.consume(&TokenKind::Eq)?;
                let value = self.parse_expression()?;
                self.try_consume(&TokenKind::Semicolon);
                Ok(Statement::Assignment(AssignmentStatement {
                    name,
                    value,
                    exported: false,
                }))
            }
            TokenKind::Fn => {
                self.bump(); // consume `fn`
                // `fn name(params) { body }` — named function sugar for `let name = fn(params) { body }`
                if matches!(self.peek_kind(), TokenKind::Ident(_)) {
                    let name = self.expect_ident()?;
                    let func = self.parse_fn_body()?;
                    self.try_consume(&TokenKind::Semicolon);
                    Ok(Statement::Assignment(AssignmentStatement {
                        name,
                        value: func,
                        exported: false,
                    }))
                } else {
                    // anonymous fn in statement position — unusual but valid
                    let func = self.parse_fn_body()?;
                    self.try_consume(&TokenKind::Semicolon);
                    Ok(Statement::Expression(func))
                }
            }
            TokenKind::Export => {
                self.bump(); // consume 'export'
                let exported = true;
                match self.peek_kind() {
                    TokenKind::Let => {
                        self.bump();
                        let name = self.expect_ident()?;
                        self.consume(&TokenKind::Eq)?;
                        let value = self.parse_expression()?;
                        self.try_consume(&TokenKind::Semicolon);
                        Ok(Statement::Assignment(AssignmentStatement {
                            name,
                            value,
                            exported,
                        }))
                    }
                    TokenKind::Fn => {
                        self.bump();
                        let name = self.expect_ident()?;
                        let func = self.parse_fn_body()?;
                        self.try_consume(&TokenKind::Semicolon);
                        Ok(Statement::Assignment(AssignmentStatement {
                            name,
                            value: func,
                            exported,
                        }))
                    }
                    _ => Err(self.err("Expected 'let' or 'fn' after 'export'")),
                }
            }
            TokenKind::Import => {
                self.bump(); // consume 'import'
                self.consume(&TokenKind::LBrace)?;
                let mut items = Vec::new();
                if !self.try_consume(&TokenKind::RBrace) {
                    loop {
                        match self.peek_kind().clone() {
                            TokenKind::Number(n) => {
                                self.bump();
                                let index = n as usize;
                                self.consume(&TokenKind::As)?;
                                let alias = self.expect_ident()?;
                                items.push(ImportItem::PositionalAlias { index, alias });
                            }
                            TokenKind::Ident(_) => {
                                let name = self.expect_ident()?;
                                if self.try_consume(&TokenKind::As) {
                                    let alias = self.expect_ident()?;
                                    items.push(ImportItem::NamedAlias { name, alias });
                                } else {
                                    items.push(ImportItem::Named(name));
                                }
                            }
                            _ => {
                                return Err(
                                    self.err("Expected identifier or number in import list")
                                );
                            }
                        }
                        if !self.try_consume(&TokenKind::Comma) {
                            break;
                        }
                        if matches!(self.peek_kind(), TokenKind::RBrace) {
                            break; // trailing comma
                        }
                    }
                    self.consume(&TokenKind::RBrace)?;
                }
                self.consume(&TokenKind::From)?;
                let path = match self.peek_kind().clone() {
                    TokenKind::String(s) => {
                        self.bump();
                        s
                    }
                    _ => return Err(self.err("Expected string path after 'from'")),
                };
                self.try_consume(&TokenKind::Semicolon);
                Ok(Statement::Import { items, path })
            }
            TokenKind::Return => {
                self.consume(&TokenKind::Return)?;
                if matches!(self.peek_kind(), TokenKind::Semicolon | TokenKind::RBrace) {
                    self.try_consume(&TokenKind::Semicolon);
                    return Ok(Statement::Return(ReturnStatement { value: None }));
                }
                let value = self.parse_expression()?;
                self.try_consume(&TokenKind::Semicolon);
                Ok(Statement::Return(ReturnStatement { value: Some(value) }))
            }
            TokenKind::If => Ok(Statement::If(self.parse_if_statement()?)),
            TokenKind::For => {
                self.consume(&TokenKind::For)?;
                let binding = self.expect_ident()?;
                self.consume(&TokenKind::In)?;
                let iterable = self.parse_expression()?;
                let body = self.parse_block_statement()?;
                Ok(Statement::ForIn {
                    binding,
                    iterable,
                    body,
                })
            }
            TokenKind::While => {
                self.consume(&TokenKind::While)?;
                let condition = self.parse_expression()?;
                let body = self.parse_block_statement()?;
                Ok(Statement::While { condition, body })
            }
            TokenKind::Break => {
                self.bump();
                self.try_consume(&TokenKind::Semicolon);
                Ok(Statement::Break)
            }
            TokenKind::Continue => {
                self.bump();
                self.try_consume(&TokenKind::Semicolon);
                Ok(Statement::Continue)
            }
            TokenKind::LBrace => Ok(Statement::Block(self.parse_block_statement()?)),
            _ => {
                let expr = self.parse_expression()?;
                if self.try_consume(&TokenKind::Eq) {
                    if !is_assignable_target(&expr) {
                        return Err(self.err("invalid reassignment target"));
                    }
                    let value = self.parse_expression()?;
                    self.try_consume(&TokenKind::Semicolon);
                    return Ok(Statement::Reassign {
                        target: expr,
                        value,
                    });
                }
                self.try_consume(&TokenKind::Semicolon);
                Ok(Statement::Expression(expr))
            }
        }
    }

    fn parse_block_statement(&mut self) -> Result<BlockStatement, ParseError> {
        self.consume(&TokenKind::LBrace)?;
        let mut statements = Vec::new();
        while !self.try_consume(&TokenKind::RBrace) {
            if self.is_eof() {
                return Err(self.err("Unterminated block"));
            }
            if self.try_consume(&TokenKind::Semicolon) {
                continue;
            }
            statements.push(self.parse_statement()?);
        }
        Ok(BlockStatement { statements })
    }

    fn parse_if_statement(&mut self) -> Result<IfStatement, ParseError> {
        self.consume(&TokenKind::If)?;
        // No parentheses: `if condition { }` — condition is everything up to `{`
        let condition = self.parse_expression()?;
        let then_branch = self.parse_block_statement()?;
        let else_branch = if self.try_consume(&TokenKind::Else) {
            if matches!(self.peek_kind(), TokenKind::If) {
                Some(ElseBranch::If(Box::new(self.parse_if_statement()?)))
            } else {
                Some(ElseBranch::Block(self.parse_block_statement()?))
            }
        } else {
            None
        };
        Ok(IfStatement {
            condition,
            then_branch,
            else_branch,
        })
    }

    /// Pratt parser entry point.
    fn parse_expression(&mut self) -> Result<Expression, ParseError> {
        self.parse_expr_bp(0)
    }

    /// Pratt/precedence-climbing expression parser.
    /// `min_bp`: minimum binding power for the left side of the next infix op.
    fn parse_expr_bp(&mut self, min_bp: u8) -> Result<Expression, ParseError> {
        let mut lhs = self.parse_prefix()?;

        loop {
            if self.try_consume(&TokenKind::LBracket) {
                let index = self.parse_expression()?;
                self.consume(&TokenKind::RBracket)?;
                lhs = Expression::Index {
                    base: Box::new(lhs),
                    index: Box::new(index),
                };
                continue;
            }

            if self.try_consume(&TokenKind::Dot) {
                let member = self.expect_ident()?;
                let dot_expr = Expression::BinaryOp {
                    op: BinOpKind::Dot,
                    lhs: Box::new(lhs),
                    rhs: Box::new(Expression::Identifier(member)),
                };
                lhs = if self.try_consume(&TokenKind::LParen) {
                    Expression::Call(CallExpression {
                        callee: Box::new(dot_expr),
                        args: self.parse_call_args()?,
                    })
                } else {
                    dot_expr
                };
                continue;
            }

            let Some((l_bp, r_bp, op)) = self.peek_infix_op() else {
                break;
            };
            if l_bp < min_bp {
                break;
            }
            self.bump(); // consume the operator token
            let rhs = self.parse_expr_bp(r_bp)?;
            lhs = Expression::BinaryOp {
                op,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
            };
        }

        Ok(lhs)
    }

    /// Binding powers for infix operators. Returns (left_bp, right_bp, op).
    /// Left-associative: l_bp == r_bp - 1.
    fn peek_infix_op(&self) -> Option<(u8, u8, BinOpKind)> {
        match self.peek_kind() {
            TokenKind::Arrow => Some((0, 1, BinOpKind::Query)),
            TokenKind::PipeGt => Some((2, 3, BinOpKind::Pipe)),
            TokenKind::PipePipe => Some((4, 5, BinOpKind::Or)),
            TokenKind::AmpAmp => Some((6, 7, BinOpKind::And)),
            TokenKind::EqEq => Some((8, 9, BinOpKind::Eq)),
            TokenKind::BangEq => Some((8, 9, BinOpKind::NotEq)),
            TokenKind::Lt => Some((10, 11, BinOpKind::Lt)),
            TokenKind::Gt => Some((10, 11, BinOpKind::Gt)),
            TokenKind::LtEq => Some((10, 11, BinOpKind::LtEq)),
            TokenKind::GtEq => Some((10, 11, BinOpKind::GtEq)),
            TokenKind::Plus => Some((12, 13, BinOpKind::Add)),
            TokenKind::Minus => Some((12, 13, BinOpKind::Sub)),
            TokenKind::Star => Some((14, 15, BinOpKind::Mul)),
            TokenKind::Slash => Some((14, 15, BinOpKind::Div)),
            TokenKind::Percent => Some((14, 15, BinOpKind::Rem)),
            _ => None,
        }
    }

    /// Parse prefix / atom expressions (nud).
    fn parse_prefix(&mut self) -> Result<Expression, ParseError> {
        match self.peek_kind() {
            // Unary minus
            TokenKind::Minus => {
                self.bump();
                let operand = self.parse_expr_bp(17)?;
                Ok(Expression::UnaryOp {
                    op: UnaryOpKind::Neg,
                    operand: Box::new(operand),
                })
            }
            // Logical not
            TokenKind::Bang => {
                self.bump();
                let operand = self.parse_expr_bp(17)?;
                Ok(Expression::UnaryOp {
                    op: UnaryOpKind::Not,
                    operand: Box::new(operand),
                })
            }
            // Grouped expression
            TokenKind::LParen => {
                self.bump();
                let inner = self.parse_expr_bp(0)?;
                self.consume(&TokenKind::RParen)?;
                Ok(inner)
            }
            // Function expression
            TokenKind::Fn => {
                self.bump();
                self.parse_fn_body()
            }
            // Literals
            TokenKind::String(_) => {
                if let TokenKind::String(s) = self.bump().kind {
                    Ok(Expression::String(s))
                } else {
                    unreachable!()
                }
            }
            TokenKind::Number(_) => {
                if let TokenKind::Number(n) = self.bump().kind {
                    Ok(Expression::Number(n))
                } else {
                    unreachable!()
                }
            }
            TokenKind::Dimension(_, _) => {
                if let TokenKind::Dimension(n, unit) = self.bump().kind {
                    Ok(Expression::Dimension(n, unit))
                } else {
                    unreachable!()
                }
            }
            TokenKind::True => {
                self.bump();
                Ok(Expression::Bool(true))
            }
            TokenKind::False => {
                self.bump();
                Ok(Expression::Bool(false))
            }
            TokenKind::Null => {
                self.bump();
                Ok(Expression::Null)
            }
            TokenKind::LBrace => self.parse_table(),
            TokenKind::LBracket => self.parse_array(),
            TokenKind::Ident(_) => self.parse_ident_leading_expression(),
            _ => Err(self.err("Unexpected token in expression")),
        }
    }

    /// Parse `(params) { body }` — the part of a function after the `fn` keyword (and optional name).
    fn parse_fn_body(&mut self) -> Result<Expression, ParseError> {
        self.consume(&TokenKind::LParen)?;
        let mut params = Vec::new();
        if !matches!(self.peek_kind(), TokenKind::RParen) {
            loop {
                params.push(self.expect_ident()?);
                if !self.try_consume(&TokenKind::Comma) {
                    break;
                }
                if matches!(self.peek_kind(), TokenKind::RParen) {
                    break;
                }
            }
        }
        self.consume(&TokenKind::RParen)?;
        let body = self.parse_block_statement()?;
        Ok(Expression::Function { params, body })
    }

    fn parse_array(&mut self) -> Result<Expression, ParseError> {
        self.consume(&TokenKind::LBracket)?;
        let mut items = Vec::new();
        if self.try_consume(&TokenKind::RBracket) {
            return Ok(Expression::Array(items));
        }
        loop {
            items.push(self.parse_expression()?);
            if self.try_consume(&TokenKind::Comma) {
                if self.try_consume(&TokenKind::RBracket) {
                    break;
                }
                continue;
            }
            self.consume(&TokenKind::RBracket)?;
            break;
        }
        Ok(Expression::Array(items))
    }

    fn parse_table(&mut self) -> Result<Expression, ParseError> {
        self.consume(&TokenKind::LBrace)?;
        let mut fields = Vec::new();
        if self.try_consume(&TokenKind::RBrace) {
            return Ok(Expression::Table(fields));
        }
        loop {
            let name = self.expect_ident()?;
            self.consume(&TokenKind::Eq)?;
            let value = self.parse_expression()?;
            fields.push(TableFieldValue { name, value });

            if self.try_consume(&TokenKind::Comma) {
                if self.try_consume(&TokenKind::RBrace) {
                    break;
                }
                continue;
            }
            if self.try_consume(&TokenKind::RBrace) {
                break;
            }
        }
        Ok(Expression::Table(fields))
    }

    /// Parse an expression that starts with an identifier.
    ///
    /// Disambiguates:
    /// - Uppercase `Type.method(args)[.method2(args2)...] [{body}]` → ComponentExpression
    /// - `ident(args)`                                              → free CallExpression
    /// - `UpperType { body }`                                       → ComponentExpression, no ctor
    /// - `ident`                                                    → bare Identifier
    fn parse_ident_leading_expression(&mut self) -> Result<Expression, ParseError> {
        let ident = self.expect_ident()?;
        let is_builtin_table = matches!(ident.0.as_str(), "Math" | "MusicNote");
        let is_component_type = self.is_component_name(&ident.0);

        if !is_builtin_table && is_component_type && self.try_consume(&TokenKind::Dot) {
            let method = self.expect_ident()?;
            self.consume(&TokenKind::LParen)?;
            let args = self.parse_call_args()?;

            // `Type.method(args)[.chain(args)...] [{body}]` → ComponentExpression
            let mut constructors = vec![ConstructorCall { method, args }];
            while self.try_consume(&TokenKind::Dot) {
                let chained = self.expect_ident()?;
                self.consume(&TokenKind::LParen)?;
                let chained_args = self.parse_call_args()?;
                constructors.push(ConstructorCall {
                    method: chained,
                    args: chained_args,
                });
            }
            let body = if matches!(self.peek_kind(), TokenKind::LBrace) {
                self.parse_block_statement()?
            } else {
                BlockStatement { statements: vec![] }
            };
            return Ok(Expression::Component(ComponentExpression {
                component_type: ident,
                constructors,
                body,
            }));
        }

        // `ident(args)` → free call expression
        if self.try_consume(&TokenKind::LParen) {
            let args = self.parse_call_args()?;
            return Ok(Expression::Call(CallExpression {
                callee: Box::new(Expression::Identifier(ident)),
                args,
            }));
        }

        // `ident { body }` → component expression, no constructor.
        // Convention: component type names always start uppercase; lowercase = variable.
        // This prevents `if flag { ... }` from consuming `flag {` as a component expression.
        let is_component_type = self.is_component_name(&ident.0);
        if !is_builtin_table && is_component_type && matches!(self.peek_kind(), TokenKind::LBrace) {
            let body = self.parse_block_statement()?;
            return Ok(Expression::Component(ComponentExpression {
                component_type: ident,
                constructors: vec![],
                body,
            }));
        }

        // bare identifier
        Ok(Expression::Identifier(ident))
    }

    fn parse_call_args(&mut self) -> Result<Vec<Expression>, ParseError> {
        let mut args = Vec::new();
        if self.try_consume(&TokenKind::RParen) {
            return Ok(args);
        }
        loop {
            args.push(self.parse_expression()?);
            if self.try_consume(&TokenKind::Comma) {
                if self.try_consume(&TokenKind::RParen) {
                    break;
                }
                continue;
            }
            self.consume(&TokenKind::RParen)?;
            break;
        }
        Ok(args)
    }

    fn expect_ident(&mut self) -> Result<Ident, ParseError> {
        match self.bump().kind {
            TokenKind::Ident(s) => Ok(Ident(s)),
            _ => Err(self.err("Expected identifier")),
        }
    }

    fn consume(&mut self, kind: &TokenKind) -> Result<(), ParseError> {
        if self.try_consume(kind) {
            Ok(())
        } else {
            Err(self.err(&format!("Expected {:?}", kind)))
        }
    }

    fn try_consume(&mut self, kind: &TokenKind) -> bool {
        if std::mem::discriminant(self.peek_kind()) == std::mem::discriminant(kind) {
            self.pos += 1;
            true
        } else {
            false
        }
    }

    fn bump(&mut self) -> Token {
        let t = self.tokens.get(self.pos).cloned().unwrap_or(Token {
            kind: TokenKind::Eof,
            span: crate::ast::Span::new(0, 0),
        });
        self.pos += 1;
        t
    }

    fn peek_kind(&self) -> &TokenKind {
        self.tokens
            .get(self.pos)
            .map(|t| &t.kind)
            .unwrap_or(&TokenKind::Eof)
    }

    fn is_eof(&self) -> bool {
        matches!(self.peek_kind(), TokenKind::Eof)
    }

    fn err(&self, message: &str) -> ParseError {
        let span = self
            .tokens
            .get(self.pos)
            .map(|t| t.span.clone())
            .unwrap_or(Span::new(0, 0));
        ParseError {
            message: message.to_string(),
            token_index: self.pos,
            span,
        }
    }
}

fn is_assignable_target(expr: &Expression) -> bool {
    match expr {
        Expression::Identifier(_) => true,
        Expression::Index { base, .. } => is_assignable_target(base),
        Expression::BinaryOp {
            op: crate::ast::BinOpKind::Dot,
            lhs,
            rhs,
        } => is_assignable_target(lhs) && matches!(rhs.as_ref(), Expression::Identifier(_)),
        _ => false,
    }
}