windjammer 0.48.0

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

use crate::lexer::Token;
use crate::parser::ast::*;
use crate::parser_impl::Parser;

impl Parser {
    pub(crate) fn parse_block_statements(
        &mut self,
    ) -> Result<Vec<&'static Statement<'static>>, String> {
        let mut statements = Vec::new();

        while self.current_token() != &Token::RBrace && self.current_token() != &Token::Eof {
            statements.push(self.parse_statement()?);
        }

        Ok(statements)
    }

    pub(crate) fn parse_statement(&mut self) -> Result<&'static Statement<'static>, String> {
        match self.current_token() {
            Token::Let => self.parse_let(),
            Token::Const => self.parse_const_statement(),
            Token::Static => self.parse_static_statement(),
            Token::Return => self.parse_return(),
            Token::If => self.parse_if(),
            Token::Match => self.parse_match(),
            Token::For => self.parse_for(),
            Token::Loop => self.parse_loop(),
            Token::While => self.parse_while(),
            Token::Thread => {
                // Check if this is a thread block or a module path (thread::...)
                if self.peek(1) == Some(&Token::LBrace) {
                    self.parse_thread()
                } else {
                    // It's an expression like thread::spawn() or thread::sleep()
                    let expr = self.parse_expression()?;
                    if self.current_token() == &Token::Semicolon {
                        self.advance();
                    }
                    Ok(self.alloc_stmt(Statement::Expression {
                        expr,
                        location: self.current_location(),
                    }))
                }
            }
            Token::Async => {
                // Check if this is an async block or a module path (async::...)
                if self.peek(1) == Some(&Token::LBrace) {
                    self.parse_async()
                } else {
                    // It's an expression like async::something()
                    let expr = self.parse_expression()?;
                    if self.current_token() == &Token::Semicolon {
                        self.advance();
                    }
                    Ok(self.alloc_stmt(Statement::Expression {
                        expr,
                        location: self.current_location(),
                    }))
                }
            }
            Token::Defer => self.parse_defer(),
            Token::Break => {
                self.advance();
                let stmt = self.alloc_stmt(Statement::Break {
                    location: self.current_location(),
                });
                // Consume trailing semicolon if present
                if self.current_token() == &Token::Semicolon {
                    self.advance();
                }
                Ok(stmt)
            }
            Token::Continue => {
                self.advance();
                let stmt = self.alloc_stmt(Statement::Continue {
                    location: self.current_location(),
                });
                // Consume trailing semicolon if present
                if self.current_token() == &Token::Semicolon {
                    self.advance();
                }
                Ok(stmt)
            }
            Token::Use => {
                self.advance(); // consume 'use'
                let (path, alias) = self.parse_use()?;
                Ok(self.alloc_stmt(Statement::Use {
                    path,
                    alias,
                    is_pub: false, // Statements are never pub
                    location: self.current_location(),
                }))
            }
            _ => {
                // Try to parse as expression first
                let expr = self.parse_expression()?;

                // Check if this is an assignment (expr = value) or compound assignment (expr += value)
                match self.current_token() {
                    Token::Assign => {
                        self.advance(); // consume '='
                        let value = self.parse_expression()?;

                        // Optionally consume semicolon
                        if self.current_token() == &Token::Semicolon {
                            self.advance();
                        }

                        Ok(self.alloc_stmt(Statement::Assignment {
                            target: expr,
                            value,
                            compound_op: None,
                            location: self.current_location(),
                        }))
                    }
                    Token::PlusAssign
                    | Token::MinusAssign
                    | Token::StarAssign
                    | Token::SlashAssign
                    | Token::PercentAssign
                    | Token::AndAssign
                    | Token::OrAssign
                    | Token::XorAssign
                    | Token::ShlAssign
                    | Token::ShrAssign => {
                        let op_token = self.current_token().clone();
                        self.advance(); // consume compound operator

                        let rhs = self.parse_expression()?;

                        // PRESERVE compound operator for idiomatic Rust output
                        // Map token to CompoundOp
                        let compound_op = match op_token {
                            Token::PlusAssign => CompoundOp::Add,
                            Token::MinusAssign => CompoundOp::Sub,
                            Token::StarAssign => CompoundOp::Mul,
                            Token::SlashAssign => CompoundOp::Div,
                            Token::PercentAssign => CompoundOp::Mod,
                            Token::AndAssign => CompoundOp::BitAnd,
                            Token::OrAssign => CompoundOp::BitOr,
                            Token::XorAssign => CompoundOp::BitXor,
                            Token::ShlAssign => CompoundOp::Shl,
                            Token::ShrAssign => CompoundOp::Shr,
                            _ => unreachable!(),
                        };

                        // Optionally consume semicolon
                        if self.current_token() == &Token::Semicolon {
                            self.advance();
                        }

                        Ok(self.alloc_stmt(Statement::Assignment {
                            target: expr,
                            value: rhs, // Just the RHS, not expanded binary expression
                            compound_op: Some(compound_op),
                            location: self.current_location(),
                        }))
                    }
                    _ => {
                        // Optionally consume semicolon after expression statement
                        if self.current_token() == &Token::Semicolon {
                            self.advance();
                        }
                        Ok(self.alloc_stmt(Statement::Expression {
                            expr,
                            location: self.current_location(),
                        }))
                    }
                }
            }
        }
    }

    fn parse_const_statement(&mut self) -> Result<&'static Statement<'static>, String> {
        self.advance(); // consume 'const'
        let (name, type_, value) = self.parse_const_or_static()?;
        Ok(self.alloc_stmt(Statement::Const {
            name,
            type_,
            value,
            location: self.current_location(),
        }))
    }

    fn parse_static_statement(&mut self) -> Result<&'static Statement<'static>, String> {
        self.advance(); // consume 'static'
        let mutable = if self.current_token() == &Token::Mut {
            self.advance();
            true
        } else {
            false
        };
        let (name, type_, value) = self.parse_const_or_static()?;
        Ok(self.alloc_stmt(Statement::Static {
            name,
            mutable,
            type_,
            value,
            location: self.current_location(),
        }))
    }

    fn parse_for(&mut self) -> Result<&'static Statement<'static>, String> {
        self.expect(Token::For)?;

        // Parse for-loop pattern: use the general pattern parser which handles all cases:
        // - Identifier: for x in ...
        // - Wildcard: for _ in ...
        // - Tuple: for (i, item) in ...
        // - Reference: for &x in ...
        // TDD FIX: Previously only handled Ident, LParen, and Ampersand explicitly,
        // missing Token::Underscore (wildcard patterns like `for _ in 0..3`).
        let pattern = if self.current_token() == &Token::Ampersand {
            // Reference pattern: &x — handle separately because parse_pattern
            // doesn't know about reference patterns in for-loops
            self.advance(); // consume &
            if let Token::Ident(name) = self.current_token() {
                let name = name.clone();
                self.advance();
                Pattern::Reference(self.alloc_pattern(Pattern::Identifier(name)))
            } else {
                return Err("Expected identifier after & in for loop pattern".to_string());
            }
        } else {
            // Use general pattern parser for all other cases (identifier, wildcard, tuple, etc.)
            self.parse_pattern()?
        };

        self.expect(Token::In)?;
        let iterable = self.parse_expression()?;

        self.expect(Token::LBrace)?;
        let body = self.parse_block_statements()?;
        self.expect(Token::RBrace)?;

        Ok(self.alloc_stmt(Statement::For {
            pattern,
            iterable,
            body,
            location: self.current_location(),
        }))
    }

    fn parse_thread(&mut self) -> Result<&'static Statement<'static>, String> {
        self.expect(Token::Thread)?;
        self.expect(Token::LBrace)?;
        let body = self.parse_block_statements()?;
        self.expect(Token::RBrace)?;

        Ok(self.alloc_stmt(Statement::Thread {
            body,
            location: self.current_location(),
        }))
    }

    fn parse_async(&mut self) -> Result<&'static Statement<'static>, String> {
        self.expect(Token::Async)?;
        self.expect(Token::LBrace)?;
        let body = self.parse_block_statements()?;
        self.expect(Token::RBrace)?;

        Ok(self.alloc_stmt(Statement::Async {
            body,
            location: self.current_location(),
        }))
    }

    fn parse_defer(&mut self) -> Result<&'static Statement<'static>, String> {
        self.expect(Token::Defer)?;
        let stmt = self.parse_statement()?;

        Ok(self.alloc_stmt(Statement::Defer {
            statement: stmt,
            location: self.current_location(),
        }))
    }

    fn parse_let(&mut self) -> Result<&'static Statement<'static>, String> {
        self.expect(Token::Let)?;

        let mutable = if self.current_token() == &Token::Mut {
            self.advance();
            true
        } else {
            false
        };

        // Parse pattern - always use parse_pattern() to handle all cases
        let pattern = self.parse_pattern()?;

        // Check if the pattern is refutable (can fail to match)
        let is_refutable = Self::is_pattern_refutable(&pattern);

        let type_ = if self.current_token() == &Token::Colon {
            self.advance();
            Some(self.parse_type()?)
        } else {
            None
        };

        self.expect(Token::Assign)?;
        let value = self.parse_expression()?;

        // Check for `else` block (required for refutable patterns)
        let else_block = if self.current_token() == &Token::Else {
            self.advance();
            // Parse the else block (must be a block, not an expression)
            self.expect(Token::LBrace)?;
            let block = self.parse_block_statements()?;
            self.expect(Token::RBrace)?;
            Some(block)
        } else {
            None
        };

        // Refutable patterns require an else block (let-else syntax)
        if is_refutable && else_block.is_none() {
            return Err(format!(
                "Refutable pattern in `let` binding requires an `else` block. Use `let {} = value else {{ ... }}`",
                Self::pattern_to_string(&pattern)
            ));
        }

        // Optionally consume semicolon (semicolons are optional in Windjammer)
        if self.current_token() == &Token::Semicolon {
            self.advance();
        }

        Ok(self.alloc_stmt(Statement::Let {
            pattern,
            mutable,
            type_,
            value,
            else_block,
            location: self.current_location(),
        }))
    }

    fn parse_return(&mut self) -> Result<&'static Statement<'static>, String> {
        self.advance();

        // TDD FIX: Check for Comma too! Match arms can have: None => return,
        // The comma indicates end of return statement (no value to return)
        let stmt = if matches!(
            self.current_token(),
            Token::RBrace | Token::Semicolon | Token::Comma
        ) {
            self.alloc_stmt(Statement::Return {
                value: None,
                location: self.current_location(),
            })
        } else {
            let value = self.parse_expression()?;
            self.alloc_stmt(Statement::Return {
                value: Some(value),
                location: self.current_location(),
            })
        };

        // Consume trailing semicolon if present
        if self.current_token() == &Token::Semicolon {
            self.advance();
        }

        Ok(stmt)
    }

    pub(crate) fn parse_if(&mut self) -> Result<&'static Statement<'static>, String> {
        self.expect(Token::If)?;

        // Check for `if let` pattern matching
        if self.current_token() == &Token::Let {
            self.advance(); // consume 'let'

            // Parse pattern
            let pattern = self.parse_pattern()?;

            self.expect(Token::Assign)?;

            // Parse value to match against
            let value = self.parse_expression()?;

            // Parse optional guard: `if let Some(x) = opt if x > 0 { ... }`
            let guard = if self.current_token() == &Token::If {
                self.advance(); // consume 'if' (the guard keyword)
                Some(self.parse_match_value()?)
            } else {
                None
            };

            self.expect(Token::LBrace)?;
            let then_block = self.parse_block_statements()?;
            self.expect(Token::RBrace)?;

            let else_block = if self.current_token() == &Token::Else {
                self.advance();
                // Check for else if
                if self.current_token() == &Token::If {
                    // else if - parse as nested if statement
                    let if_stmt = self.parse_if()?;
                    Some(vec![if_stmt])
                } else {
                    // else - parse block
                    self.expect(Token::LBrace)?;
                    let block = self.parse_block_statements()?;
                    self.expect(Token::RBrace)?;
                    Some(block)
                }
            } else {
                None
            };

            let then_body = self.alloc_expr(Expression::Block {
                statements: then_block,
                is_unsafe: false,
                location: self.current_location(),
            });

            let mut arms = vec![MatchArm {
                pattern,
                guard,
                body: then_body,
            }];

            // Add wildcard arm for else block (or empty block if no else)
            // This ensures exhaustive pattern matching in Rust
            let else_body = if let Some(else_stmts) = else_block {
                self.alloc_expr(Expression::Block {
                    statements: else_stmts,
                    is_unsafe: false,
                    location: self.current_location(),
                })
            } else {
                self.alloc_expr(Expression::Block {
                    statements: vec![],
                    is_unsafe: false,
                    location: self.current_location(),
                }) // Empty block if no else clause
            };

            arms.push(MatchArm {
                pattern: Pattern::Wildcard,
                guard: None,
                body: else_body,
            });

            Ok(self.alloc_stmt(Statement::Match {
                value,
                arms,
                location: self.current_location(),
            }))
        } else {
            // Regular if statement
            let condition = self.parse_expression()?;

            self.expect(Token::LBrace)?;
            let then_block = self.parse_block_statements()?;
            self.expect(Token::RBrace)?;

            let else_block = if self.current_token() == &Token::Else {
                self.advance();
                // Check for else if
                if self.current_token() == &Token::If {
                    // else if - parse as nested if statement
                    let if_stmt = self.parse_if()?;
                    Some(vec![if_stmt])
                } else {
                    // else - parse block
                    self.expect(Token::LBrace)?;
                    let block = self.parse_block_statements()?;
                    self.expect(Token::RBrace)?;
                    Some(block)
                }
            } else {
                None
            };

            Ok(self.alloc_stmt(Statement::If {
                condition,
                then_block,
                else_block,
                location: self.current_location(),
            }))
        }
    }

    fn parse_match(&mut self) -> Result<&'static Statement<'static>, String> {
        self.expect(Token::Match)?;

        let value = self.parse_match_value()?;

        self.expect(Token::LBrace)?;

        let mut arms = Vec::new();
        while self.current_token() != &Token::RBrace {
            let pattern = self.parse_pattern_with_or()?;

            // Parse optional guard: if condition
            let guard = if self.current_token() == &Token::If {
                self.advance();
                Some(self.parse_expression()?)
            } else {
                None
            };

            self.expect(Token::FatArrow)?;

            // TDD: Match arms can contain assignments (statements), not just expressions
            // Check if this is a block or a single statement/expression
            let (body, is_block) = if self.current_token() == &Token::LBrace {
                // Block expression: match x { Pattern => { ... } }
                self.advance();
                let statements = self.parse_block_statements()?;
                self.expect(Token::RBrace)?;
                let block = self.alloc_expr(Expression::Block {
                    statements,
                    is_unsafe: false,
                    location: self.current_location(),
                });
                (block, true)
            } else {
                // Try to parse as statement first (for assignments), then as expression
                let _checkpoint = self.position;

                // Peek ahead to see if this looks like an assignment
                let is_assignment = if let Token::Ident(_) = self.current_token() {
                    // Check for identifier followed by = (or .field = for field assignment)
                    let mut ahead = 1;
                    loop {
                        match self.peek(ahead) {
                            Some(Token::Assign) => break true,
                            Some(Token::Dot) | Some(Token::LBracket) => {
                                ahead += 1;
                                if let Some(Token::Ident(_)) = self.peek(ahead) {
                                    ahead += 1;
                                } else {
                                    break false;
                                }
                            }
                            _ => break false,
                        }
                    }
                } else {
                    false
                };

                // TDD: break/continue/return in match arm (e.g. None => break) must be parsed
                // as statements, not expressions. Expression parser doesn't handle them.
                let is_control_flow = matches!(
                    self.current_token(),
                    Token::Break | Token::Continue | Token::Return
                );

                if is_assignment || is_control_flow {
                    // Parse as statement (assignment or break/continue/return)
                    let stmt = self.parse_statement()?;
                    // Wrap in block expression
                    let block = self.alloc_expr(Expression::Block {
                        statements: vec![stmt],
                        is_unsafe: false,
                        location: self.current_location(),
                    });
                    (block, false)
                } else {
                    // Parse as expression
                    (self.parse_expression()?, false)
                }
            };

            arms.push(MatchArm {
                pattern,
                guard,
                body,
            });

            // TDD: Match arms must be comma-separated
            // Exception: Commas are optional after block expressions (Rust-style)
            if self.current_token() == &Token::Comma {
                self.advance();
                // Allow trailing comma before closing brace
                if self.current_token() == &Token::RBrace {
                    break;
                }
            } else if self.current_token() == &Token::RBrace {
                // End of match arms
                break;
            } else if !is_block {
                // No comma after a non-block expression (and not at end) - this is an error
                return Err(format!(
                    "Expected ',' or '}}' after match arm, got {:?}",
                    self.current_token()
                ));
            }
            // If is_block is true and no comma, continue to next arm (comma is optional)
        }

        self.expect(Token::RBrace)?;

        Ok(self.alloc_stmt(Statement::Match {
            value,
            arms,
            location: self.current_location(),
        }))
    }

    // ========================================================================
    // SECTION 6: PATTERN PARSING
    // ========================================================================

    fn parse_loop(&mut self) -> Result<&'static Statement<'static>, String> {
        self.expect(Token::Loop)?;
        self.expect(Token::LBrace)?;
        let body = self.parse_block_statements()?;
        self.expect(Token::RBrace)?;

        Ok(self.alloc_stmt(Statement::Loop {
            body,
            location: self.current_location(),
        }))
    }

    fn parse_while(&mut self) -> Result<&'static Statement<'static>, String> {
        self.expect(Token::While)?;

        // Check for `while let` pattern
        if self.peek(0) == Some(&Token::Let) {
            self.advance(); // consume 'let'

            // Parse pattern
            let pattern = self.parse_pattern()?;

            self.expect(Token::Assign)?; // '='

            // Parse the expression to match against
            let expr = self.parse_expression()?;

            self.expect(Token::LBrace)?;
            let body = self.parse_block_statements()?;
            self.expect(Token::RBrace)?;

            // Desugar `while let` into a loop with match
            // while let pattern = expr { body }
            // becomes:
            // loop {
            //     match expr {
            //         pattern => { body }
            //         _ => break
            //     }
            // }
            let body_block = self.alloc_expr(Expression::Block {
                statements: body.clone(),
                is_unsafe: false,
                location: self.current_location(),
            });

            let break_stmt = self.alloc_stmt(Statement::Break {
                location: self.current_location(),
            });

            let break_block = self.alloc_expr(Expression::Block {
                statements: vec![break_stmt],
                is_unsafe: false,
                location: self.current_location(),
            });

            let match_stmt = self.alloc_stmt(Statement::Match {
                value: expr,
                arms: vec![
                    MatchArm {
                        pattern,
                        guard: None,
                        body: body_block,
                    },
                    MatchArm {
                        pattern: Pattern::Wildcard,
                        guard: None,
                        body: break_block,
                    },
                ],
                location: self.current_location(),
            });

            Ok(self.alloc_stmt(Statement::Loop {
                body: vec![match_stmt],
                location: self.current_location(),
            }))
        } else {
            // Regular while loop
            let condition = self.parse_expression()?;

            self.expect(Token::LBrace)?;
            let body = self.parse_block_statements()?;
            self.expect(Token::RBrace)?;

            Ok(self.alloc_stmt(Statement::While {
                condition,
                body,
                location: self.current_location(),
            }))
        }
    }
}