devalang 0.2.0

Write music with code. Devalang is a domain-specific language (DSL) for sound designers and music hackers. Compose, automate, and control sound — in plain text.
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
use super::super::helpers::{parse_array_value, parse_condition};
use crate::language::syntax::ast::{Statement, StatementKind, Value};
/// Structure statement parsing: group, pattern, loop, for, if, on, emit, call, spawn
use anyhow::{Result, anyhow};
use std::collections::HashMap;
use std::iter::Iterator;

/// Parse pattern statement
/// Supports:
/// - pattern name with target = "pattern"
/// - pattern name with target { options } = "pattern"
pub fn parse_pattern(
    mut parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    let name = parts
        .next()
        .ok_or_else(|| anyhow!("pattern requires a name"))?
        .as_ref()
        .to_string();

    let mut target = None;
    let mut pattern_str = None;
    let mut options: HashMap<String, Value> = HashMap::new();

    // Check for "with" keyword
    if let Some(word) = parts.next() {
        if word.as_ref() == "with" {
            // Next is the target
            target = parts.next().map(|v| v.as_ref().to_string());

            // Collect remaining parts to check for options block or pattern
            let rest: Vec<String> = parts.map(|s| s.as_ref().to_string()).collect();
            let joined = rest.join(" ");

            // Check if there's an options block: { key: value, key: value }
            if let Some(brace_start) = joined.find('{') {
                if let Some(brace_end) = joined.rfind('}') {
                    // Extract options block
                    let options_str = &joined[brace_start + 1..brace_end];

                    // Parse options (key: value pairs)
                    for pair in options_str.split(',') {
                        let parts: Vec<&str> = pair.split(':').collect();
                        if parts.len() == 2 {
                            let key = parts[0].trim().to_string();
                            let value_str = parts[1].trim();

                            // Parse value
                            let value = if let Ok(num) = value_str.parse::<f32>() {
                                Value::Number(num)
                            } else if value_str == "true" {
                                Value::Boolean(true)
                            } else if value_str == "false" {
                                Value::Boolean(false)
                            } else if value_str.starts_with('"') && value_str.ends_with('"') {
                                Value::String(value_str.trim_matches('"').to_string())
                            } else {
                                Value::Identifier(value_str.to_string())
                            };

                            options.insert(key, value);
                        }
                    }

                    // Check for "=" and pattern after the brace
                    let after_brace = joined[brace_end + 1..].trim();
                    if let Some(eq_pos) = after_brace.find('=') {
                        let pattern_part = after_brace[eq_pos + 1..].trim();
                        pattern_str = Some(pattern_part.trim_matches('"').to_string());
                    }
                } else {
                    return Err(anyhow!("Unclosed brace in pattern options"));
                }
            } else {
                // No options block, check for "=" and pattern directly
                if let Some(eq_pos) = joined.find('=') {
                    let pattern_part = joined[eq_pos + 1..].trim();
                    pattern_str = Some(pattern_part.trim_matches('"').to_string());
                }
            }
        }
    }

    // Store pattern string and options in value
    let value = if !options.is_empty() {
        let mut map = options;
        if let Some(pat) = pattern_str {
            map.insert("pattern".to_string(), Value::String(pat));
        }
        Value::Map(map)
    } else {
        pattern_str.map(Value::String).unwrap_or(Value::Null)
    };

    Ok(Statement::new(
        StatementKind::Pattern { name, target },
        value,
        0,
        line_number,
        1,
    ))
}

/// Parse compact pattern shorthand:
///   kick: drums.kick = "x---"
///   hat: drums.hat -> swing(0.08) = "x-x-"
pub fn parse_pattern_shorthand(line: &str, line_number: usize) -> Result<Option<Statement>> {
    let Some(colon_idx) = line.find(':') else {
        return Ok(None);
    };
    let Some(eq_idx) = line.find('=') else {
        return Ok(None);
    };
    if colon_idx > eq_idx {
        return Ok(None);
    }

    let name = line[..colon_idx].trim();
    if name.is_empty()
        || name.contains(char::is_whitespace)
        || !name.chars().all(|c| c.is_alphanumeric() || c == '_')
    {
        return Ok(None);
    }

    let target_expr = line[colon_idx + 1..eq_idx].trim();
    let pattern_part = line[eq_idx + 1..].trim();
    if target_expr.is_empty()
        || !(pattern_part.starts_with('"')
            && pattern_part.ends_with('"')
            && pattern_part.len() >= 2)
    {
        return Ok(None);
    }

    let mut target = target_expr.to_string();
    let mut options: HashMap<String, Value> = HashMap::new();

    fn insert_option(options: &mut HashMap<String, Value>, method: &str, args: &[Value]) {
        if let Some(first) = args.first() {
            match first {
                Value::Number(_) => {
                    options.insert(method.to_string(), first.clone());
                }
                Value::Map(map) => {
                    for (key, value) in map.iter() {
                        if matches!(value, Value::Number(_)) {
                            options.insert(key.clone(), value.clone());
                        }
                    }
                }
                _ => {}
            }
        }
    }

    if target_expr.contains("->") {
        let stmt =
            crate::language::syntax::parser::driver::parse_arrow_call(target_expr, line_number)?;
        if let Value::Map(chain_container) = stmt.value {
            if let Some(Value::String(parsed_target)) = chain_container.get("target") {
                target = parsed_target.clone();
            }

            if let Some(Value::String(method)) = chain_container.get("method") {
                if let Some(Value::Array(args)) = chain_container.get("args") {
                    insert_option(&mut options, method, args);
                }
            }

            if let Some(Value::Array(chain)) = chain_container.get("chain") {
                for item in chain {
                    if let Value::Map(call_map) = item {
                        if let (Some(Value::String(method)), Some(Value::Array(args))) =
                            (call_map.get("method"), call_map.get("args"))
                        {
                            insert_option(&mut options, method, args);
                        }
                    }
                }
            }
        }
    }

    let pattern = pattern_part.trim_matches('"').to_string();
    let value = if options.is_empty() {
        Value::String(pattern)
    } else {
        options.insert("pattern".to_string(), Value::String(pattern));
        Value::Map(options)
    };

    Ok(Some(Statement::new(
        StatementKind::Pattern {
            name: name.to_string(),
            target: Some(target),
        },
        value,
        0,
        line_number,
        1,
    )))
}

/// Parse group statement: group <name>: or group <name> during <duration>:
/// Example: group verse: or group verse during 16 bars:
pub fn parse_group(
    mut parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    let name = parts
        .next()
        .ok_or_else(|| anyhow!("group requires a name"))?
        .as_ref()
        .trim_end_matches(':')
        .to_string();

    // Check for "during" keyword for optional duration
    let next = parts.next();
    let duration = if next.as_ref().map(|w| w.as_ref()) == Some("during") {
        // Parse duration (everything after 'during')
        let duration_str = parts
            .map(|p| p.as_ref().to_string())
            .collect::<Vec<_>>()
            .join(" ")
            .trim_end_matches(':')
            .to_string();

        Some(super::super::duration::parse_duration_token(&duration_str)?)
    } else {
        None
    };

    Ok(Statement::new(
        StatementKind::Group {
            name: name.clone(),
            body: Vec::new(),
            duration,
        },
        Value::Identifier(name),
        0,
        line_number,
        1,
    ))
}

/// Parse automate statement: automate <target> [mode <note|global>]:
pub fn parse_automate(
    mut parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    // First part is the target
    let target = parts
        .next()
        .ok_or_else(|| anyhow!("automate requires a target"))?
        .as_ref()
        .trim_end_matches(':')
        .to_string();

    // Optional mode: 'mode note' or 'mode global'
    let mut mode: Option<String> = None;
    if let Some(word) = parts.next() {
        if word.as_ref() == "mode" {
            if let Some(m) = parts.next() {
                mode = Some(m.as_ref().trim_end_matches(':').to_string());
            }
        }
    }

    let mut map = HashMap::new();
    if let Some(m) = mode {
        map.insert("mode".to_string(), Value::String(m));
    }

    Ok(Statement::new(
        StatementKind::Automate { target },
        Value::Map(map),
        0,
        line_number,
        1,
    ))
}

/// Parse loop statement
pub fn parse_loop(
    parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    // Parse: loop <count>:  OR plain `loop:` (no count)
    // If no count is provided we store Value::Null to indicate an unbounded loop
    // Special case: loop pass(<duration>): - pass with explicit duration

    // First, collect all parts and rejoin them to handle durations with spaces
    let all_parts: Vec<String> = parts.map(|p| p.as_ref().to_string()).collect();

    let count = if all_parts.is_empty() {
        // No explicit count -> mark as Null (infinite/indefinite)
        Value::Null
    } else {
        // Join all remaining parts to handle things like "pass(1 bar)"
        let count_str = all_parts.join(" ").trim_end_matches(':').to_string();

        // Support forms:
        // - loop pass:
        // - loop pass():
        // - loop pass(500):
        // - loop pass(1 bar):
        // - loop pass(2.5 bars):
        // - loop 4:
        if let Ok(num) = count_str.parse::<f32>() {
            Value::Number(num)
        } else if count_str.contains('(') && count_str.ends_with(')') {
            // Parse as a call-like value (e.g., pass(500) or pass(1 bar))
            if let Some(open_idx) = count_str.find('(') {
                let name = count_str[..open_idx].to_string();
                let inside = &count_str[open_idx + 1..count_str.len() - 1];

                // Special case: if it's "pass" with a duration argument, parse as duration
                if name == "pass" && !inside.trim().is_empty() {
                    // Try to parse as duration first
                    if let Ok(duration) =
                        crate::language::syntax::parser::driver::parse_duration_token(inside.trim())
                    {
                        Value::Duration(duration)
                    } else {
                        // Fall back to call parsing
                        let args = if inside.trim().is_empty() {
                            Vec::new()
                        } else {
                            crate::language::syntax::parser::driver::parse_function_args(inside)?
                        };
                        Value::Call { name, args }
                    }
                } else {
                    // Regular call parsing
                    let args = if inside.trim().is_empty() {
                        Vec::new()
                    } else {
                        crate::language::syntax::parser::driver::parse_function_args(inside)?
                    };
                    Value::Call { name, args }
                }
            } else {
                Value::Identifier(count_str.to_string())
            }
        } else {
            Value::Identifier(count_str)
        }
    };

    Ok(Statement::new(
        StatementKind::Loop {
            count,
            body: Vec::new(), // Will be filled during indentation parsing
        },
        Value::Null,
        0,
        line_number,
        1,
    ))
}

/// Parse for statement
pub fn parse_for(
    parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    // Parse: for <var> in <iterable>:
    let parts_vec: Vec<String> = parts.map(|s| s.as_ref().to_string()).collect();

    if parts_vec.is_empty() {
        return Err(anyhow!("for loop requires a variable name"));
    }

    let variable = parts_vec[0].clone();

    // Expect "in"
    if parts_vec.len() < 2 || parts_vec[1] != "in" {
        return Err(anyhow!("Expected 'in' after variable in for loop"));
    }

    // Parse iterable (array or identifier)
    let iterable_str = parts_vec[2..].join(" ");
    let iterable_str = iterable_str.trim_end_matches(':').trim();

    let iterable = if iterable_str.starts_with('[') && iterable_str.ends_with(']') {
        // Parse as array: [1, 2, 3] or range: [1..10]
        parse_array_value(iterable_str)?
    } else {
        // Parse as identifier or number
        if let Ok(num) = iterable_str.parse::<f32>() {
            Value::Number(num)
        } else {
            Value::Identifier(iterable_str.to_string())
        }
    };

    Ok(Statement::new(
        StatementKind::For {
            variable,
            iterable,
            body: Vec::new(), // Will be filled during indentation parsing
        },
        Value::Null,
        0,
        line_number,
        1,
    ))
}

/// Parse function statement: function name(arg1, arg2, ...):
pub fn parse_function(line: &str, line_number: usize) -> Result<Statement> {
    // Expect form: function <name>(arg1, arg2, ...):
    let after_kw = line
        .trim()
        .strip_prefix("function")
        .ok_or_else(|| anyhow!("function parsing error"))?
        .trim();

    // Find name and args parentheses
    if let Some(paren_idx) = after_kw.find('(') {
        let name = after_kw[..paren_idx].trim().to_string();
        if let Some(close_idx) = after_kw.rfind(')') {
            let args_str = &after_kw[paren_idx + 1..close_idx];
            // Parse parameter names: split by ',' and trim
            let params: Vec<String> = if args_str.trim().is_empty() {
                Vec::new()
            } else {
                args_str
                    .split(',')
                    .map(|s| s.trim().trim_end_matches(':').to_string())
                    .filter(|s| !s.is_empty())
                    .collect()
            };

            return Ok(Statement::new(
                StatementKind::Function {
                    name: name.clone(),
                    parameters: params,
                    body: Vec::new(),
                },
                Value::Identifier(name),
                0,
                line_number,
                1,
            ));
        }
    }

    Err(anyhow!("Invalid function declaration"))
}

/// Parse if statement
pub fn parse_if(
    parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    // Parse: if <condition>:
    let condition_str = parts
        .map(|s| s.as_ref().to_string())
        .collect::<Vec<_>>()
        .join(" ");
    let condition_str = condition_str.trim_end_matches(':').trim();

    // Parse condition (for now, simple comparison)
    let condition = parse_condition(condition_str)?;

    Ok(Statement::new(
        StatementKind::If {
            condition,
            body: Vec::new(), // Will be filled during indentation parsing
            else_body: None,
        },
        Value::Null,
        0,
        line_number,
        1,
    ))
}

/// Parse while statement
/// Syntax: while <condition>:
pub fn parse_while(
    parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    // Parse: while <condition>:
    let condition_str = parts
        .map(|s| s.as_ref().to_string())
        .collect::<Vec<_>>()
        .join(" ");
    let condition_str = condition_str.trim_end_matches(':').trim();

    // Parse condition
    let condition = parse_condition(condition_str)?;

    Ok(Statement::new(
        StatementKind::While {
            condition,
            body: Vec::new(), // Will be filled during indentation parsing
        },
        Value::Null,
        0,
        line_number,
        1,
    ))
}

/// Parse else statement (can be "else if" or just "else")
pub fn parse_else(line: &str, line_number: usize) -> Result<Statement> {
    // Check if this is "else if" or just "else"
    if line.trim().starts_with("else if") {
        // Parse as "else if <condition>:"
        let Some(condition_str) = line.trim().strip_prefix("else if") else {
            return Err(anyhow::anyhow!(
                "Invalid else-if statement at line {}",
                line_number
            ));
        };
        let condition_str = condition_str.trim();
        let condition_str = condition_str.trim_end_matches(':').trim();
        let condition = parse_condition(condition_str)?;

        // Mark this If as originating from an 'else if' so the outer parser
        // post-process can attach it as an else-branch to the previous If.
        Ok(Statement::new(
            StatementKind::If {
                condition,
                body: Vec::new(), // Will be filled during indentation parsing
                else_body: None,
            },
            Value::String("else-if".to_string()),
            0,
            line_number,
            1,
        ))
    } else {
        // Just "else:"
        // Return a lightweight marker (Comment with value "else") so the
        // outer parser can detect and attach the following indented block
        // as the else-body of the preceding If.
        Ok(Statement::new(
            StatementKind::Comment, // We'll handle this specially during body parsing
            Value::String("else".to_string()),
            0,
            line_number,
            1,
        ))
    }
}

/// Parse call statement
/// Supports:
/// - call groupName
/// - call target = "pattern" (inline pattern assignment)
pub fn parse_call(
    line: &str,
    mut parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    // Determine the call name. If the call uses parentheses (call name(arg1, arg2))
    // extract the name from the text before the first '(', otherwise fall back to
    // the whitespace-split first token.
    let first_token = parts
        .next()
        .ok_or_else(|| anyhow!("call requires a target"))?
        .as_ref()
        .to_string();
    let mut call_name = first_token.clone();
    if line.find('(').is_some() {
        // Extract the substring between 'call' and the first '(' as the name
        if let Some(after_call) = line.trim().strip_prefix("call") {
            let snippet = after_call.trim();
            if let Some(pidx) = snippet.find('(') {
                call_name = snippet[..pidx].trim().to_string();
            }
        }
    }

    // Check if this is an inline pattern assignment: call target = "pattern"
    if line.contains('=') {
        // Split by = to get target and pattern
        let eq_parts: Vec<&str> = line.splitn(2, '=').collect();
        if eq_parts.len() == 2 {
            // Extract target (remove "call " prefix)
            let target = eq_parts[0]
                .trim()
                .strip_prefix("call")
                .unwrap_or(eq_parts[0])
                .trim()
                .to_string();
            let pattern = eq_parts[1].trim().trim_matches('"').to_string();

            // Create an inline pattern statement
            // Store pattern data in the Call's value field
            let mut map = HashMap::new();
            map.insert("inline_pattern".to_string(), Value::Boolean(true));
            map.insert("target".to_string(), Value::String(target.clone()));
            map.insert("pattern".to_string(), Value::String(pattern));

            return Ok(Statement::new(
                StatementKind::Call {
                    name: target,
                    args: Vec::new(),
                },
                Value::Map(map),
                0,
                line_number,
                1,
            ));
        }
    }

    // Regular call statement (call groupName or call patternName)
    // Support call with arguments: call name(arg1, arg2)
    if let Some(paren_idx) = line.find('(') {
        if let Some(close_idx) = line.rfind(')') {
            let args_str = &line[paren_idx + 1..close_idx];
            let args = if args_str.trim().is_empty() {
                Vec::new()
            } else {
                // Reuse parse_function_args from parent module
                crate::language::syntax::parser::driver::parse_function_args(args_str)?
            };

            return Ok(Statement::new(
                StatementKind::Call {
                    name: call_name,
                    args,
                },
                Value::Null,
                0,
                line_number,
                1,
            ));
        }
    }

    Ok(Statement::new(
        StatementKind::Call {
            name: call_name,
            args: Vec::new(),
        },
        Value::Null,
        0,
        line_number,
        1,
    ))
}

/// Parse break statement
pub fn parse_break(
    _parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    Ok(Statement::new(
        StatementKind::Break,
        Value::Null,
        0,
        line_number,
        1,
    ))
}

/// Parse spawn statement
pub fn parse_spawn(
    mut parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    let name = parts
        .next()
        .ok_or_else(|| anyhow!("spawn requires a target"))?
        .as_ref()
        .to_string();

    Ok(Statement::new(
        StatementKind::Spawn {
            name,
            args: Vec::new(),
        },
        Value::Null,
        0,
        line_number,
        1,
    ))
}

/// Parse on statement (event handler)
pub fn parse_on(
    mut parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    // Parse: on eventName: or on eventName once:
    // Accept forms like: on beat: | on beat once: | on beat(4): | on beat(4) once:
    let raw = parts
        .next()
        .ok_or_else(|| anyhow!("on statement requires an event name"))?
        .as_ref()
        .to_string();

    // Parse optional interval within parentheses, e.g. beat(4)
    let mut event_name = raw.clone();
    let mut args_vec: Vec<Value> = Vec::new();
    if let Some(open_idx) = raw.find('(') {
        if raw.ends_with(')') {
            let base = raw[..open_idx].to_string();
            let inside = &raw[open_idx + 1..raw.len() - 1];
            if let Ok(n) = inside.trim().parse::<f32>() {
                args_vec.push(Value::Number(n));
            }
            event_name = base;
        }
    }

    // Check for "once" keyword as next token
    let next_word = parts.next();
    let once = next_word.map(|w| w.as_ref() == "once").unwrap_or(false);
    if once {
        args_vec.push(Value::String("once".to_string()));
    }

    let args = if !args_vec.is_empty() {
        Some(args_vec)
    } else {
        None
    };

    Ok(Statement::new(
        StatementKind::On {
            event: event_name,
            args,
            body: Vec::new(), // Will be filled during indentation parsing
        },
        Value::Null,
        0,
        line_number,
        1,
    ))
}

/// Parse emit statement (event emission)
pub fn parse_emit(
    line: &str,
    mut parts: impl Iterator<Item = impl AsRef<str>>,
    line_number: usize,
) -> Result<Statement> {
    // Parse: emit eventName { key: value, key: value }
    let event_name = parts
        .next()
        .ok_or_else(|| anyhow!("emit statement requires an event name"))?
        .as_ref()
        .to_string();

    // Parse payload if present
    let remainder = line.splitn(2, &event_name).nth(1).unwrap_or("").trim();

    let payload = if remainder.starts_with('{') && remainder.ends_with('}') {
        // Parse as map: { key: value, key: value }
        let inner = &remainder[1..remainder.len() - 1];
        let mut map = HashMap::new();

        // Split by comma and parse key-value pairs
        for pair in inner.split(',') {
            let parts: Vec<&str> = pair.split(':').collect();
            if parts.len() == 2 {
                let key = parts[0].trim().to_string();
                let value_str = parts[1].trim();

                // Parse value
                let value = if value_str.starts_with('"') && value_str.ends_with('"') {
                    Value::String(value_str.trim_matches('"').to_string())
                } else if let Ok(num) = value_str.parse::<f32>() {
                    Value::Number(num)
                } else {
                    Value::Identifier(value_str.to_string())
                };

                map.insert(key, value);
            }
        }

        Some(Value::Map(map))
    } else {
        None
    };

    Ok(Statement::new(
        StatementKind::Emit {
            event: event_name,
            payload,
        },
        Value::Null,
        0,
        line_number,
        1,
    ))
}