cobble-lang 0.6.3

A modern, Python-like language for creating Minecraft Data Packs
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
use super::tokenizer::{tokenize, Token};
use crate::ast::*;
use chumsky::prelude::*;

/// Token parser using chumsky
pub fn token_parser<'a>(
) -> impl Parser<'a, &'a [Token], Program, extra::Err<Rich<'a, Token>>> + Clone {
    recursive(|stmt| {
        // Expression parser
        let expr = recursive(|expr| {
            let array_literal = just(&Token::LBracket)
                .ignore_then(
                    expr.clone()
                        .separated_by(just(&Token::Comma))
                        .allow_trailing()
                        .collect(),
                )
                .then_ignore(just(&Token::RBracket))
                .map(Expression::Array);

            let map_entry = choice((
                select_ref! { Token::String(s) => s.clone() },
                select_ref! { Token::Ident(s) => s.clone() },
            ))
            .then_ignore(just(&Token::Colon))
            .then(expr.clone());

            let map_literal = just(&Token::LBrace)
                .ignore_then(
                    map_entry
                        .separated_by(just(&Token::Comma))
                        .allow_trailing()
                        .collect(),
                )
                .then_ignore(just(&Token::RBrace))
                .map(Expression::Map);

            let atom = choice((
                select_ref! {
                    Token::Number(n) => Expression::Number(n.parse().unwrap_or(0.0)),
                    Token::String(s) => Expression::String(s.clone()),
                    Token::True_ => Expression::Boolean(true),
                    Token::False_ => Expression::Boolean(false),
                    Token::None_ => Expression::None,
                    Token::Ident(s) => Expression::Identifier(s.clone()),
                },
                array_literal,
                map_literal,
                // Parenthesized expression
                just(&Token::LParen)
                    .ignore_then(expr.clone())
                    .then_ignore(just(&Token::RParen)),
            ));

            // Attribute access (e.g., stdlib.event)
            let postfix = atom.foldl(
                choice((
                    just(&Token::Dot)
                        .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
                        .map(|attr| (true, Expression::Identifier(attr))), // true = dot access
                    just(&Token::LBracket)
                        .ignore_then(expr.clone())
                        .then_ignore(just(&Token::RBracket))
                        .map(|index| (false, index)), // false = bracket access
                ))
                .repeated(),
                |base, (is_dot, accessor)| {
                    if is_dot {
                        if let Expression::Identifier(attr) = accessor {
                            Expression::Attribute(Box::new(base), attr)
                        } else {
                            unreachable!()
                        }
                    } else {
                        Expression::Subscript(Box::new(base), Box::new(accessor))
                    }
                },
            );

            // Function call
            let call = postfix
                .then(
                    just(&Token::LParen)
                        .ignore_then(
                            expr.clone()
                                .separated_by(just(&Token::Comma))
                                .allow_trailing()
                                .collect(),
                        )
                        .then_ignore(just(&Token::RParen))
                        .or_not(),
                )
                .map(|(func, args)| {
                    if let Some(args) = args {
                        Expression::Call(Box::new(func), args)
                    } else {
                        func
                    }
                });

            // Binary operations with proper precedence
            // Unary +/- (high precedence, but lower than call, higher than power)
            // Allow unary operators before any atom/call/parenthesized expression
            let unary = recursive(|unary_rec| {
                choice((
                    just(&Token::Minus).to(UnaryOp::Neg),
                    just(&Token::Plus).to(UnaryOp::Pos),
                ))
                .then(unary_rec.clone())
                .map(|(op, expr)| Expression::Unary(op, Box::new(expr)))
                .or(call.clone())
            });

            // Highest precedence: ^ (power) - right-associative
            // Power operator is right-associative: 2^3^2 = 2^(3^2) = 512
            // We parse left-to-right but fold right-to-left for right-associativity
            let power = unary
                .clone()
                .then(
                    just(&Token::Caret)
                        .to(BinaryOp::Pow)
                        .then(unary.clone())
                        .repeated()
                        .collect::<Vec<_>>(),
                )
                .map(|(first, rest)| {
                    if rest.is_empty() {
                        first
                    } else {
                        // Collect all operands: [first, second, third, ...]
                        let mut all_operands = vec![first];
                        for (_, operand) in &rest {
                            all_operands.push(operand.clone());
                        }

                        // Build right-associative tree by folding from right to left
                        // For [a, b, c]: a ^ (b ^ c)
                        let mut result = all_operands.pop().unwrap();
                        while let Some(operand) = all_operands.pop() {
                            result = Expression::Binary(
                                Box::new(operand),
                                BinaryOp::Pow,
                                Box::new(result),
                            );
                        }
                        result
                    }
                });

            // Second highest: *, /, %
            let mul_div_mod = power.clone().foldl(
                choice((
                    just(&Token::Star).to(BinaryOp::Mul),
                    just(&Token::Slash).to(BinaryOp::Div),
                    just(&Token::Percent).to(BinaryOp::Mod),
                ))
                .then(power.clone())
                .repeated(),
                |left, (op, right)| Expression::Binary(Box::new(left), op, Box::new(right)),
            );

            // Middle precedence: + -
            let add_sub = mul_div_mod.clone().foldl(
                choice((
                    just(&Token::Plus).to(BinaryOp::Add),
                    just(&Token::Minus).to(BinaryOp::Sub),
                ))
                .then(mul_div_mod.clone())
                .repeated(),
                |left, (op, right)| Expression::Binary(Box::new(left), op, Box::new(right)),
            );

            // Comparisons
            let comparison = add_sub.clone().foldl(
                choice((
                    just(&Token::EqEq).to(BinaryOp::Eq),
                    just(&Token::NotEq).to(BinaryOp::NotEq),
                    just(&Token::GtEq).to(BinaryOp::GtEq),
                    just(&Token::LtEq).to(BinaryOp::LtEq),
                    just(&Token::Gt).to(BinaryOp::Gt),
                    just(&Token::Lt).to(BinaryOp::Lt),
                ))
                .then(add_sub.clone())
                .repeated(),
                |left, (op, right)| Expression::Binary(Box::new(left), op, Box::new(right)),
            );

            // Not (unary)
            let not_expr = just(&Token::Not)
                .repeated()
                .foldr(comparison.clone(), |_op, expr| {
                    Expression::Unary(UnaryOp::Not, Box::new(expr))
                })
                .or(comparison.clone());

            // And
            let and_expr = not_expr.clone().foldl(
                just(&Token::And)
                    .to(BinaryOp::And)
                    .then(not_expr.clone())
                    .repeated(),
                |left, (op, right)| Expression::Binary(Box::new(left), op, Box::new(right)),
            );

            // Or (lowest precedence)
            and_expr.clone().foldl(
                just(&Token::Or)
                    .to(BinaryOp::Or)
                    .then(and_expr.clone())
                    .repeated(),
                |left, (op, right)| Expression::Binary(Box::new(left), op, Box::new(right)),
            )
        });

        // Block: INDENT statements DEDENT
        let block = just(&Token::Indent)
            .ignore_then(stmt.clone().repeated().collect())
            .then_ignore(just(&Token::Dedent));

        // Minecraft command
        let minecraft_cmd = select_ref! {
            Token::MinecraftCommand(s) => Statement::MinecraftCommand(format!("/{}", s))
        };

        // Import
        let import = choice((
            just(&Token::Import)
                .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
                .map(|module| {
                    Statement::Import(Import {
                        module,
                        items: vec![],
                    })
                }),
            just(&Token::From)
                .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
                .then_ignore(just(&Token::Import))
                .then(
                    select_ref! { Token::Ident(s) => s.clone() }
                        .separated_by(just(&Token::Comma))
                        .allow_trailing()
                        .collect(),
                )
                .map(|(module, items)| Statement::Import(Import { module, items })),
        ));

        // Global
        let global = just(&Token::Global)
            .ignore_then(
                select_ref! { Token::Ident(s) => s.clone() }
                    .separated_by(just(&Token::Comma))
                    .allow_trailing()
                    .collect(),
            )
            .map(Statement::Global);

        // Assignment
        let assignment = select_ref! { Token::Ident(s) => s.clone() }
            .then_ignore(just(&Token::Equals))
            .then(expr.clone())
            .map(|(target, value)| Statement::Assignment(Assignment { target, value }));

        // Const assignment
        let const_assignment = just(&Token::Const)
            .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
            .then_ignore(just(&Token::Equals))
            .then(expr.clone())
            .map(|(target, value)| Statement::ConstAssignment(ConstAssignment { target, value }));

        // Selector definition: @Name = @selector[...]
        let selector_def = select_ref! { Token::Ident(s) if s.starts_with('@') => s.clone() }
            .then_ignore(just(&Token::Equals))
            .then(select_ref! { Token::Ident(s) if s.starts_with('@') => s.clone() })
            .map(|(name_with_at, selector)| {
                // Strip @ from name (e.g., "@Player" -> "Player")
                let name = name_with_at
                    .strip_prefix('@')
                    .unwrap_or(&name_with_at)
                    .to_string();
                Statement::SelectorDef(SelectorDef { name, selector })
            });

        // Entity definition: define @Name = @Selector create { ... } end
        let entity_def = just(&Token::Define)
            .ignore_then(select_ref! { Token::Ident(s) if s.starts_with('@') => s.clone() })
            .then_ignore(just(&Token::Equals))
            .then(select_ref! { Token::Ident(s) if s.starts_with('@') => s.clone() })
            .then_ignore(just(&Token::Newline).or_not())
            .then_ignore(just(&Token::Create))
            .then(expr.clone())
            .then_ignore(just(&Token::Newline).or_not())
            .then_ignore(just(&Token::End))
            .map(|((name_with_at, selector), nbt)| {
                // Strip @ from name (e.g., "@Player" -> "Player")
                let name = name_with_at
                    .strip_prefix('@')
                    .unwrap_or(&name_with_at)
                    .to_string();
                Statement::EntityDef(EntityDef {
                    name,
                    selector,
                    nbt,
                })
            });

        // Create entity statement: create @Name
        let create_entity = just(&Token::Create)
            .ignore_then(select_ref! { Token::Ident(s) if s.starts_with('@') => s.clone() })
            .map(|name_with_at| {
                let name = name_with_at
                    .strip_prefix('@')
                    .unwrap_or(&name_with_at)
                    .to_string();
                Statement::CreateEntity(name)
            });

        // Pass
        let pass = just(&Token::Pass).to(Statement::Pass);

        // Return
        let return_stmt = just(&Token::Return)
            .ignore_then(expr.clone().or_not())
            .map(Statement::Return);

        // Docstring (string literal as statement)
        let docstring = select_ref! {
            Token::String(_s) => Statement::Pass  // Ignore docstrings
        };

        // Function definition
        let function = just(&Token::Def)
            .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
            .then(
                just(&Token::LParen)
                    .ignore_then(
                        select_ref! { Token::Ident(s) => s.clone() }
                            .separated_by(just(&Token::Comma))
                            .allow_trailing()
                            .collect::<Vec<String>>(),
                    )
                    .then_ignore(just(&Token::RParen)),
            )
            .then_ignore(just(&Token::Colon))
            .then_ignore(just(&Token::Newline).or_not())
            .then(block.clone())
            .map(|((name, params), body)| {
                Statement::FunctionDef(FunctionDef {
                    name,
                    params: params
                        .into_iter()
                        .map(|p| Parameter {
                            name: p,
                            default: None,
                        })
                        .collect(),
                    body,
                    decorators: vec![],
                })
            });

        // If/elif/else
        let if_stmt = just(&Token::If)
            .ignore_then(expr.clone())
            .then_ignore(just(&Token::Colon))
            .then_ignore(just(&Token::Newline).or_not())
            .then(block.clone())
            .then(
                just(&Token::Elif)
                    .ignore_then(expr.clone())
                    .then_ignore(just(&Token::Colon))
                    .then_ignore(just(&Token::Newline).or_not())
                    .then(block.clone())
                    .repeated()
                    .collect(),
            )
            .then(
                just(&Token::Else)
                    .ignore_then(just(&Token::Colon))
                    .then_ignore(just(&Token::Newline).or_not())
                    .ignore_then(block.clone())
                    .or_not(),
            )
            .map(|(((condition, then_branch), elif_branches), else_branch)| {
                Statement::If(IfStatement {
                    condition,
                    then_branch,
                    elif_branches,
                    else_branch,
                })
            });

        // For loop
        let for_loop = just(&Token::For)
            .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
            .then_ignore(just(&Token::In))
            .then(expr.clone())
            .then(just(&Token::By).ignore_then(expr.clone()).or_not())
            .then_ignore(just(&Token::Colon))
            .then_ignore(just(&Token::Newline).or_not())
            .then(block.clone())
            .map(|(((target, iter), step), body)| {
                Statement::For(ForLoop {
                    target,
                    iter,
                    step,
                    body,
                })
            });

        // While loop
        let while_loop = just(&Token::While)
            .ignore_then(expr.clone())
            .then_ignore(just(&Token::Colon))
            .then_ignore(just(&Token::Newline).or_not())
            .then(block.clone())
            .map(|(condition, body)| Statement::While(WhileLoop { condition, body }));

        // Match pattern
        let match_pattern = choice((
            // Wildcard: _
            just(&Token::Underscore).to(MatchPattern::Wildcard),
            // Range: expr to expr
            select_ref! { Token::Number(n) => n.parse::<i32>().unwrap() }
                .then(
                    just(&Token::To)
                        .ignore_then(select_ref! { Token::Number(n) => n.parse::<i32>().unwrap() })
                        .or_not(),
                )
                .map(|(start, end)| {
                    if let Some(end) = end {
                        MatchPattern::Range(start, end)
                    } else {
                        MatchPattern::Literal(start)
                    }
                }),
        ));

        // Match case
        let match_case = just(&Token::Case)
            .ignore_then(match_pattern)
            .then_ignore(just(&Token::Colon))
            .then_ignore(just(&Token::Newline).or_not())
            .then(block.clone())
            .map(|(pattern, body)| MatchCase { pattern, body });

        // Match statement
        let match_stmt = just(&Token::Match)
            .ignore_then(expr.clone())
            .then_ignore(just(&Token::Colon))
            .then_ignore(just(&Token::Newline))
            .then_ignore(just(&Token::Indent))
            .then(match_case.repeated().at_least(1).collect())
            .then_ignore(just(&Token::Dedent))
            .map(|(value, cases)| Statement::Match(MatchStatement { value, cases }));

        // Execute block modifiers
        // Helper to parse execute condition (for if/unless modifiers)
        let exec_condition = any()
            .filter(|t: &Token| !matches!(t, Token::Colon | Token::Newline | Token::As | Token::At))
            .repeated()
            .at_least(1)
            .collect::<Vec<Token>>()
            .map(|tokens| {
                // Convert tokens to string, but be smart about spacing
                let mut result = String::new();
                let mut prev_token: Option<&Token> = None;

                for (i, token) in tokens.iter().enumerate() {
                    let token_str = format!("{}", token);

                    // Determine if we need a space before this token
                    let need_space = if i == 0 {
                        false
                    } else if let Some(prev) = prev_token {
                        match (prev, token) {
                            // No space between dots (for "..")
                            (Token::Dot, Token::Dot) => false,
                            // No space after dot if followed by number (for "..10")
                            (Token::Dot, Token::Number(_)) => false,
                            // Space after dot for other cases like "1.. if"
                            (Token::Dot, _) => true,
                            // No space before dots
                            (_, Token::Dot) => false,
                            // No space between minus and number when it's a negative number
                            (Token::Minus, Token::Number(_)) => false,
                            // Default: add space
                            _ => true,
                        }
                    } else {
                        true
                    };

                    if need_space {
                        result.push(' ');
                    }
                    result.push_str(&token_str);
                    prev_token = Some(token);
                }
                result
            });

        // Helper: parse either an identifier or a macro parameter {name}
        let selector_or_macro = choice((
            select_ref! { Token::Ident(s) => s.clone() },
            just(&Token::LBrace)
                .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
                .then_ignore(just(&Token::RBrace))
                .map(|name| format!("{{{}}}", name)),
        ));

        let execute_modifier = choice((
            just(&Token::As)
                .ignore_then(selector_or_macro)
                .map(ExecuteModifier::As),
            just(&Token::At)
                .ignore_then(selector_or_macro)
                .map(ExecuteModifier::At),
            // if/unless in execute blocks:
            // For now, keep as raw and let transpiler determine if it's Python expression
            just(&Token::If)
                .ignore_then(exec_condition)
                .map(ExecuteModifier::IfRaw),
            just(&Token::Unless)
                .ignore_then(exec_condition)
                .map(ExecuteModifier::UnlessRaw),
            // positioned <coords>
            select_ref! { Token::Ident(s) if s == "positioned" => s.clone() }
                .ignore_then(exec_condition)
                .map(ExecuteModifier::Positioned),
            // rotated <rotation>
            select_ref! { Token::Ident(s) if s == "rotated" => s.clone() }
                .ignore_then(exec_condition)
                .map(ExecuteModifier::Rotated),
            // in <dimension>
            just(&Token::In)
                .ignore_then(exec_condition)
                .map(ExecuteModifier::In),
            // anchored <eyes|feet>
            select_ref! { Token::Ident(s) if s == "anchored" => s.clone() }
                .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
                .map(ExecuteModifier::Anchored),
            // align <axes>
            select_ref! { Token::Ident(s) if s == "align" => s.clone() }
                .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
                .map(ExecuteModifier::Align),
            // store result/success ...
            select_ref! { Token::Ident(s) if s == "store" => s.clone() }
                .ignore_then(exec_condition)
                .map(ExecuteModifier::Store),
        ));

        // Execute block - support all execute modifiers
        let execute_block = choice((
            // asat @s: -> as @s at @s:
            just(&Token::Asat)
                .ignore_then(select_ref! { Token::Ident(s) => s.clone() })
                .try_map(|s, span| {
                    if s.starts_with('@') {
                        Ok(s)
                    } else {
                        Err(Rich::custom(
                            span,
                            format!("Expected selector starting with '@', got '{}'", s),
                        ))
                    }
                })
                .then_ignore(just(&Token::Colon))
                .then_ignore(just(&Token::Newline).or_not())
                .then(block.clone())
                .map(|(selector, body)| {
                    Statement::Execute(ExecuteBlock {
                        modifiers: vec![
                            ExecuteModifier::As(selector),
                            ExecuteModifier::At("@s".to_string()),
                        ],
                        body,
                    })
                }),
            // Any execute modifier(s) followed by colon - supports positioned, in, etc. as first modifier
            execute_modifier
                .then(
                    execute_modifier
                        .repeated()
                        .collect::<Vec<ExecuteModifier>>(),
                )
                .then_ignore(just(&Token::Colon))
                .then_ignore(just(&Token::Newline).or_not())
                .then(block.clone())
                .map(|((first, rest), body)| {
                    let mut modifiers = vec![first];
                    modifiers.extend(rest);
                    Statement::Execute(ExecuteBlock { modifiers, body })
                }),
        ));

        // Expression statement (for function calls)
        let expr_stmt = expr.clone().map(Statement::Expression);

        // Simple statement (ends with newline)
        let simple_stmt = choice((
            docstring,
            minecraft_cmd,
            import,
            global,
            return_stmt,
            pass,
            selector_def,
            entity_def,
            create_entity,
            const_assignment,
            assignment,
            expr_stmt,
        ))
        .then_ignore(just(&Token::Newline).or_not());

        // Compound statement (has block)
        let compound_stmt = choice((
            function,
            if_stmt,
            for_loop,
            while_loop,
            match_stmt,
            execute_block,
        ));

        choice((compound_stmt, simple_stmt))
    })
    .repeated()
    .collect()
    .then_ignore(just(&Token::Eof))
    .map(|statements: Vec<Statement>| Program {
        imports: statements
            .iter()
            .filter_map(|s| {
                if let Statement::Import(imp) = s {
                    Some(imp.clone())
                } else {
                    None
                }
            })
            .collect(),
        statements: statements
            .into_iter()
            .filter(|s| !matches!(s, Statement::Import(_)))
            .collect(),
    })
}

/// Parse source code into AST
pub fn parse(source: &str) -> Result<Program, Vec<String>> {
    let tokens = tokenize(source).map_err(|e| vec![e])?;

    let result = token_parser().parse(&tokens);

    match result.into_result() {
        Ok(program) => Ok(program),
        Err(errors) => Err(errors
            .into_iter()
            .map(|e| format!("{}", e.reason()))
            .collect()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_function() {
        let source = r#"
def test():
    x = 10
    /say Hello
"#;
        let result = parse(source);
        assert!(result.is_ok(), "Parse failed: {:?}", result.err());
        let program = result.unwrap();
        assert_eq!(program.statements.len(), 1);
    }

    #[test]
    fn test_if_statement() {
        let source = r#"
def test():
    x = 5
    if x == 5:
        /say equal
"#;
        let result = parse(source);
        assert!(result.is_ok(), "Parse failed: {:?}", result.err());
    }

    #[test]
    fn test_for_loop() {
        let source = r#"
def test():
    for i in range(5):
        /say hello
"#;
        let result = parse(source);
        assert!(result.is_ok(), "Parse failed: {:?}", result.err());
    }

    #[test]
    fn test_execute_block() {
        let source = r#"
def test():
    as @a at @s:
        /particle flame ~ ~ ~
"#;
        let result = parse(source);
        assert!(result.is_ok(), "Parse failed: {:?}", result.err());
    }

    #[test]
    fn test_asat() {
        let source = r#"
def test():
    asat @s:
        /say Hello
"#;
        let result = parse(source);
        assert!(result.is_ok(), "Parse failed: {:?}", result.err());
    }

    #[test]
    fn test_global() {
        let source = r#"
def test():
    global score
    score = 10
"#;
        let result = parse(source);
        assert!(result.is_ok(), "Parse failed: {:?}", result.err());
    }

    #[test]
    fn test_import() {
        let source = r#"
import stdlib
from stdlib import event
"#;
        let result = parse(source);
        assert!(result.is_ok(), "Parse failed: {:?}", result.err());
        let program = result.unwrap();
        assert_eq!(program.imports.len(), 2);
    }
}