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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
use anyhow::Result;
use rayon::prelude::*;
use std::collections::HashMap;

use crate::engine::audio::events::AudioEventList;
use crate::engine::events::EventHandler;
use crate::engine::events::EventRegistry;
use crate::engine::functions::FunctionRegistry;
use crate::language::syntax::ast::{Statement, StatementKind, Value};

use super::AudioInterpreter;

// Conditional logging macros for CLI feature
#[allow(unused_macros)]
#[cfg(feature = "cli")]
macro_rules! log_info {
    ($logger:expr, $($arg:tt)*) => {
        $logger.info(format!($($arg)*))
    };
}

#[allow(unused_macros)]
#[cfg(not(feature = "cli"))]
macro_rules! log_info {
    ($_logger:expr, $($arg:tt)*) => {
        let _ = ($($arg)*);
    };
}

#[cfg(feature = "cli")]
macro_rules! log_warn {
    ($logger:expr, $($arg:tt)*) => {
        $logger.warn(format!($($arg)*))
    };
}

#[allow(unused_macros)]
#[cfg(not(feature = "cli"))]
macro_rules! log_warn {
    ($_logger:expr, $($arg:tt)*) => {
        let _ = ($($arg)*);
    };
}

#[cfg(feature = "cli")]
macro_rules! log_error {
    ($logger:expr, $($arg:tt)*) => {
        $logger.error(format!($($arg)*))
    };
}

#[allow(unused_macros)]
#[cfg(not(feature = "cli"))]
macro_rules! log_error {
    ($_logger:expr, $($arg:tt)*) => {
        let _ = ($($arg)*);
    };
}

#[allow(unused_macros)]
#[cfg(feature = "cli")]
macro_rules! log_structured_error {
    ($logger:expr, $error:expr) => {
        $logger.log_structured_error(&$error)
    };
}

#[allow(unused_macros)]
#[cfg(not(feature = "cli"))]
macro_rules! log_structured_error {
    ($_logger:expr, $_error:expr) => {};
}

pub fn collect_events(interpreter: &mut AudioInterpreter, statements: &[Statement]) -> Result<()> {
    #[cfg(feature = "cli")]
    let logger = crate::tools::logger::Logger::new();
    #[cfg(not(feature = "cli"))]
    let _logger = ();
    // (content copied from top-level collector.rs)
    // Drain any background worker events first so they are available during collection
    if let Some(rx) = interpreter.background_event_rx.as_mut() {
        // Drain all pending lists
        loop {
            match rx.try_recv() {
                Ok(events) => {
                    // Debug info: show how many events are being merged from background workers
                    let _cnt = events.events.len();
                    // Consider both audio events and logged print messages when computing earliest time
                    let mut times: Vec<f32> = Vec::new();
                    for e in &events.events {
                        if let crate::engine::audio::events::AudioEvent::Note {
                            start_time, ..
                        } = e
                        {
                            times.push(*start_time);
                        } else if let crate::engine::audio::events::AudioEvent::Chord {
                            start_time,
                            ..
                        } = e
                        {
                            times.push(*start_time);
                        } else if let crate::engine::audio::events::AudioEvent::Sample {
                            start_time,
                            ..
                        } = e
                        {
                            times.push(*start_time);
                        }
                    }
                    for (t, _m) in &events.logs {
                        times.push(*t);
                    }
                    let earliest = times
                        .into_iter()
                        .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
                    let _ = earliest;
                    interpreter.events.merge(events);
                }
                Err(std::sync::mpsc::TryRecvError::Empty) => break,
                Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                    break;
                }
            }
        }
    }
    let (spawns, others): (Vec<_>, Vec<_>) = statements
        .iter()
        .partition(|stmt| matches!(stmt.kind, StatementKind::Spawn { .. }));

    // Iterate with index so we can inspect the remaining statements for global-automation span
    for idx in 0..others.len() {
        let stmt = &others[idx];
        interpreter.current_statement_location = Some((stmt.line, stmt.column));
        interpreter
            .special_vars
            .update_time(interpreter.cursor_time);

        match &stmt.kind {
            StatementKind::Function {
                name,
                parameters,
                body,
            } => {
                // Register function definition in variables so it can be called later
                let func_stmt = Statement {
                    kind: StatementKind::Function {
                        name: name.clone(),
                        parameters: parameters.clone(),
                        body: body.clone(),
                    },
                    value: stmt.value.clone(),
                    indent: stmt.indent,
                    line: stmt.line,
                    column: stmt.column,
                };
                interpreter
                    .variables
                    .insert(name.clone(), Value::Statement(Box::new(func_stmt)));
            }
            StatementKind::Let { name, value } => {
                if let Some(val) = value {
                    super::handler::handle_let(interpreter, name, val)?;
                }
            }
            StatementKind::Const { name, value } => {
                // Treat const like let at runtime: register the value in the interpreter variables.
                // Immutability is enforced at higher language layers; runtime simply stores the value.
                if let Some(val) = value {
                    super::handler::handle_let(interpreter, name, val)?;
                }
            }
            StatementKind::ArrowCall {
                target,
                method,
                args,
            } => {
                let chain = if let Value::Map(map) = &stmt.value {
                    map.get("chain").and_then(|v| {
                        if let Value::Array(arr) = v {
                            Some(arr.as_slice())
                        } else {
                            None
                        }
                    })
                } else {
                    None
                };

                let context =
                    crate::engine::audio::interpreter::statements::arrow_call::execute_arrow_call(
                        interpreter,
                        target,
                        method,
                        args,
                        chain,
                        interpreter.cursor_time,
                        interpreter.bpm,
                    )
                    .map_err(|e| {
                        #[cfg(feature = "wasm")]
                        {
                            use crate::web::registry::debug;
                            if debug::is_debug_errors_enabled() {
                                // wasm registry expects: message, line, column, error_type
                                debug::push_parse_error_from_parts(
                                    format!("{}", e),
                                    stmt.line,
                                    stmt.column,
                                    "RuntimeError".to_string(),
                                );
                            }
                        }
                        e
                    })?;

                super::extractor::extract_audio_event(interpreter, target, &context)?;
                interpreter.cursor_time += context.duration;
            }
            StatementKind::Tempo { value, body } => {
                let prev_bpm = interpreter.bpm;
                interpreter.set_bpm(*value);

                // If this is a block, execute its body with the new tempo
                if let Some(block_body) = body {
                    collect_events(interpreter, block_body)?;
                }

                // If body is None (simple tempo declaration), keep the new BPM
                // Otherwise, restore the previous BPM after the block completes
                if body.is_some() {
                    interpreter.bpm = prev_bpm;
                }
            }
            StatementKind::Sleep => {
                // Accept either a raw number (ms) or a Duration value (beats/fraction)
                match &stmt.value {
                    Value::Number(n) => {
                        interpreter.cursor_time += n / 1000.0;
                    }
                    Value::Duration(dv) => {
                        if let Ok(s) = interpreter.duration_to_seconds(dv) {
                            interpreter.cursor_time += s;
                        }
                    }
                    _ => {}
                }
            }
            StatementKind::Group {
                name,
                body,
                duration: _,
            } => {
                interpreter.groups.insert(name.clone(), body.clone());
            }
            StatementKind::Routing { body } => {
                // Process routing block - parse nodes, fx, routes, ducks, and sidechains
                for routing_stmt in body {
                    match &routing_stmt.kind {
                        StatementKind::RoutingNode { name, alias } => {
                            let config = super::RoutingNodeConfig {
                                name: name.clone(),
                                alias: alias.clone(),
                                effects: None,
                            };
                            interpreter.routing.nodes.insert(name.clone(), config);
                        }
                        StatementKind::RoutingFx { target, effects } => {
                            if let Some(node_config) = interpreter.routing.nodes.get_mut(target) {
                                node_config.effects = Some(effects.clone());
                            }
                        }
                        StatementKind::RoutingRoute {
                            source,
                            destination,
                            effects,
                        } => {
                            interpreter.routing.routes.push(super::RouteConfig {
                                source: source.clone(),
                                destination: destination.clone(),
                                effects: effects.clone(),
                            });
                        }
                        StatementKind::RoutingDuck {
                            source,
                            destination,
                            effect,
                        } => {
                            interpreter.routing.ducks.push(super::DuckConfig {
                                source: source.clone(),
                                destination: destination.clone(),
                                effect: effect.clone(),
                            });
                        }
                        StatementKind::RoutingSidechain {
                            source,
                            destination,
                            effect,
                        } => {
                            interpreter.routing.sidechains.push(super::SidechainConfig {
                                source: source.clone(),
                                destination: destination.clone(),
                                effect: effect.clone(),
                            });
                        }
                        _ => {}
                    }
                }

                // Build the audio graph from routing configuration
                interpreter.audio_graph =
                    crate::engine::audio::graph::AudioGraph::from_routing_setup(
                        &interpreter.routing,
                    );
            }
            StatementKind::Call { name, args } => {
                // If this call contains an inline pattern (parser stores it in stmt.value as a Map
                // with `inline_pattern = true`), register it as a Pattern statement in variables
                // so that handle_call can find and execute it targeting the correct bank.trigger.
                if let Value::Map(map) = &stmt.value {
                    if let Some(Value::Boolean(inline)) = map.get("inline_pattern") {
                        if *inline {
                            let target = map.get("target").and_then(|v| {
                                if let Value::String(s) = v {
                                    Some(s.clone())
                                } else {
                                    None
                                }
                            });

                            let pattern_stmt = Statement {
                                kind: StatementKind::Pattern {
                                    name: name.clone(),
                                    target: target.clone(),
                                },
                                value: stmt.value.clone(),
                                indent: stmt.indent,
                                line: stmt.line,
                                column: stmt.column,
                            };

                            interpreter
                                .variables
                                .insert(name.clone(), Value::Statement(Box::new(pattern_stmt)));
                        }
                    }
                }

                super::handler::handle_call(interpreter, name, args)?;
            }

            StatementKind::Automate { target } => {
                // Expect stmt.value to be a Map with keys: "mode" (optional) and "body" (raw string)
                if let Value::Map(map) = &stmt.value {
                    let mode = map
                        .get("mode")
                        .and_then(|v| {
                            if let Value::String(s) = v {
                                Some(s.clone())
                            } else {
                                None
                            }
                        })
                        .unwrap_or_else(|| "global".to_string());

                    if let Some(Value::String(raw_body)) = map.get("body") {
                        // Parse templates
                        let templates =
                            crate::engine::audio::automation::parse_param_templates_from_raw(
                                raw_body,
                            );

                        if mode == "note" {
                            // For note mode, we need to estimate the duration of the block
                            // so that per-note automations can calculate their progress properly
                            let remaining: Vec<crate::language::syntax::ast::Statement> =
                                others[idx + 1..].iter().map(|s| (*s).clone()).collect();

                            // Create a local interpreter snapshot to measure duration
                            let current_bpm = interpreter.bpm;
                            let groups_snapshot = interpreter.groups.clone();
                            let variables_snapshot = interpreter.variables.clone();
                            let special_vars_snapshot = interpreter.special_vars.clone();

                            let mut local_interpreter = AudioInterpreter {
                                sample_rate: interpreter.sample_rate,
                                bpm: current_bpm,
                                function_registry: FunctionRegistry::new(),
                                events: AudioEventList::new(),
                                variables: variables_snapshot.clone(),
                                groups: groups_snapshot.clone(),
                                banks: interpreter.banks.clone(),
                                automation_registry: interpreter.automation_registry.clone(),
                                note_automation_templates: interpreter
                                    .note_automation_templates
                                    .clone(),
                                cursor_time: 0.0,
                                special_vars: special_vars_snapshot.clone(),
                                event_registry: EventRegistry::new(),
                                #[cfg(feature = "cli")]
                                midi_manager: interpreter.midi_manager.clone(),
                                current_statement_location: None,
                                suppress_beat_emit: true,
                                suppress_print: true,
                                break_flag: false,
                                // Inherit background_event_tx from parent so spawned/child
                                // interpreters reuse the same Sender when running under
                                // live playback. This prevents child interpreters from
                                // creating their own private Receiver that would be
                                // dropped while background workers keep running.
                                background_event_tx: interpreter.background_event_tx.clone(),
                                background_event_rx: None,
                                background_workers: Vec::new(),
                                realtime_print_tx: None,
                                function_call_depth: 0,
                                returning_flag: false,
                                return_value: None,
                                routing: Default::default(),
                                audio_graph: crate::engine::audio::graph::AudioGraph::new(),
                                current_event_node: None,
                                schedule_deadline: None,
                            };

                            // Inherit synth definitions
                            local_interpreter.events.synths = interpreter.events.synths.clone();

                            // Simulate to measure duration
                            if !remaining.is_empty() {
                                let _ = collect_events(&mut local_interpreter, &remaining);
                            }

                            let end_time =
                                interpreter.cursor_time + local_interpreter.events.total_duration();

                            // Create context with timing information
                            let context = super::NoteAutomationContext {
                                templates,
                                start_time: interpreter.cursor_time,
                                end_time,
                            };

                            // Store context under target for per-note application
                            interpreter
                                .note_automation_templates
                                .insert(target.clone(), context);
                        } else {
                            // Global mode: determine a sensible total duration for the envelope.
                            // We'll estimate it by simulating the remaining statements in this block
                            // (i.e., the statements after this automate statement in the current list).
                            let remaining: Vec<crate::language::syntax::ast::Statement> =
                                others[idx + 1..].iter().map(|s| (*s).clone()).collect();

                            // Create a local interpreter snapshot to measure the total duration
                            let current_bpm = interpreter.bpm;
                            let groups_snapshot = interpreter.groups.clone();
                            let variables_snapshot = interpreter.variables.clone();
                            let special_vars_snapshot = interpreter.special_vars.clone();

                            let mut local_interpreter = AudioInterpreter {
                                sample_rate: interpreter.sample_rate,
                                bpm: current_bpm,
                                function_registry: FunctionRegistry::new(),
                                events: AudioEventList::new(),
                                variables: variables_snapshot.clone(),
                                groups: groups_snapshot.clone(),
                                banks: interpreter.banks.clone(),
                                automation_registry: interpreter.automation_registry.clone(),
                                note_automation_templates: interpreter
                                    .note_automation_templates
                                    .clone(),
                                cursor_time: 0.0,
                                special_vars: special_vars_snapshot.clone(),
                                event_registry: EventRegistry::new(),
                                #[cfg(feature = "cli")]
                                midi_manager: interpreter.midi_manager.clone(),
                                current_statement_location: None,
                                suppress_beat_emit: true,
                                suppress_print: true,
                                break_flag: false,
                                // Keep the same background sender as the parent interpreter
                                background_event_tx: interpreter.background_event_tx.clone(),
                                background_event_rx: None,
                                background_workers: Vec::new(),
                                realtime_print_tx: None,
                                function_call_depth: 0,
                                returning_flag: false,
                                return_value: None,
                                routing: Default::default(),
                                audio_graph: crate::engine::audio::graph::AudioGraph::new(),
                                current_event_node: None,
                                schedule_deadline: None,
                            };

                            // Inherit synth definitions so durations reflect real events
                            local_interpreter.events.synths = interpreter.events.synths.clone();

                            // Simulate collecting events for the remaining statements to estimate duration
                            if !remaining.is_empty() {
                                let _ = collect_events(&mut local_interpreter, &remaining);
                            }

                            let total_dur = local_interpreter.events.total_duration();
                            let start_time = interpreter.cursor_time;

                            let mut envelope =
                                crate::engine::audio::automation::AutomationEnvelope::new(
                                    target.clone(),
                                );

                            // For each template, create AutomationParam segments between adjacent points
                            for tpl in templates.iter() {
                                if tpl.points.len() >= 2 {
                                    for w in tpl.points.windows(2) {
                                        let (p0, v0) = w[0];
                                        let (p1, v1) = w[1];
                                        let seg_start = start_time + p0 * total_dur;
                                        let seg_dur = (p1 - p0) * total_dur;
                                        if seg_dur <= 0.0 {
                                            continue;
                                        }
                                        envelope.add_param(
                                            crate::engine::audio::automation::AutomationParam {
                                                param_name: tpl.param_name.clone(),
                                                from_value: v0,
                                                to_value: v1,
                                                start_time: seg_start,
                                                duration: seg_dur,
                                                curve: tpl.curve,
                                            },
                                        );
                                    }
                                } else if tpl.points.len() == 1 {
                                    // Single point - treat as immediate set at that fraction
                                    let (p, v) = tpl.points[0];
                                    let seg_start = start_time + p * total_dur;
                                    envelope.add_param(
                                        crate::engine::audio::automation::AutomationParam {
                                            param_name: tpl.param_name.clone(),
                                            from_value: v,
                                            to_value: v,
                                            start_time: seg_start,
                                            duration: 0.0,
                                            curve: tpl.curve,
                                        },
                                    );
                                }
                            }

                            // Register the automation envelope
                            interpreter.automation_registry.register(envelope);
                        }
                    }
                }
            }

            StatementKind::Spawn { .. } => {
                unreachable!("Spawn statements should be handled in parallel section");
            }
            StatementKind::Loop { count, body } => {
                interpreter.execute_loop(count, body)?;
            }
            StatementKind::For {
                variable,
                iterable,
                body,
            } => {
                interpreter.execute_for(variable, iterable, body)?;
            }
            StatementKind::Return { value } => {
                // Only allow 'return' inside a function call context
                if interpreter.function_call_depth == 0 {
                    return Err(anyhow::anyhow!(
                        "'return' used outside of a function at {}:{}",
                        stmt.line,
                        stmt.column
                    ));
                }

                // Resolve return value (if provided) and signal function return
                if let Some(vbox) = value.as_ref() {
                    let resolved = interpreter.resolve_value(vbox)?;
                    interpreter.return_value = Some(resolved);
                } else {
                    interpreter.return_value = Some(Value::Null);
                }
                interpreter.returning_flag = true;
                // Stop further execution of the current statement block
                return Ok(());
            }
            StatementKind::Break => {
                // Signal to enclosing loop/for that a break occurred
                interpreter.break_flag = true;
                // Stop processing this block so loop logic can handle the break
                return Ok(());
            }
            StatementKind::Print => {
                super::handler::execute_print(interpreter, &stmt.value)?;
            }
            StatementKind::If {
                condition,
                body,
                else_body,
            } => {
                super::handler::execute_if(interpreter, condition, body, else_body)?;
            }
            StatementKind::While { condition, body } => {
                super::handler::execute_while(interpreter, condition, body)?;
            }
            StatementKind::On { event, args, body } => {
                // Build handler: pick up once flag and keep args (intervals etc.)
                let once = args
                    .as_ref()
                    .and_then(|a| {
                        a.iter().find_map(|v| {
                            if let Value::String(s) = v {
                                Some(s == "once")
                            } else {
                                None
                            }
                        })
                    })
                    .unwrap_or(false);

                // Normalize event name (strip trailing ':' if present)
                let event_name = event.trim_end_matches(':').trim().to_string();
                let handler = EventHandler {
                    event_name: event_name.clone(),
                    body: body.clone(),
                    once,
                    args: args.clone(),
                };
                interpreter.event_registry.register_handler(handler);
            }
            StatementKind::Emit { event, payload } => {
                let data = if let Some(Value::Map(map)) = payload {
                    map.clone()
                } else {
                    HashMap::new()
                };
                interpreter
                    .event_registry
                    .emit(event.clone(), data, interpreter.cursor_time);
                super::handler::execute_event_handlers(interpreter, event)?;
            }
            StatementKind::Assign { target, property } => {
                super::handler::handle_assign(interpreter, target, property, &stmt.value)?;
            }
            StatementKind::Load { source, alias } => {
                super::handler::handle_load(interpreter, source, alias)?;
            }
            #[cfg(feature = "cli")]
            StatementKind::UsePlugin {
                author,
                name,
                alias,
            } => {
                let clean_alias = alias.trim_end_matches(';').to_string();
                super::handler::handle_use_plugin(interpreter, author, name, &clean_alias)?;
            }
            #[cfg(not(feature = "cli"))]
            StatementKind::UsePlugin { author, name, .. } => {
                eprintln!(
                    "⚠️  Plugin loading not supported in WASM mode: {}.{}",
                    author, name
                );
            }
            StatementKind::Pattern { name, target } => {
                let pattern_stmt = Statement {
                    kind: StatementKind::Pattern {
                        name: name.clone(),
                        target: target.clone(),
                    },
                    value: stmt.value.clone(),
                    indent: stmt.indent,
                    line: stmt.line,
                    column: stmt.column,
                };
                interpreter
                    .variables
                    .insert(name.clone(), Value::Statement(Box::new(pattern_stmt)));
            }
            StatementKind::Bank { name, alias } => {
                super::handler::handle_bank(interpreter, name, alias)?;
            }
            StatementKind::Bind { source, target } => {
                super::handler::handle_bind(interpreter, source, target, &stmt.value)?;
            }
            StatementKind::Import { names, source } => {
                let path = std::path::Path::new(&source);
                if path.exists() {
                    match crate::language::preprocessor::loader::load_module_exports(path) {
                        Ok(exports) => {
                            for name in names {
                                if let Some(val) = exports.variables.get(name) {
                                    interpreter.variables.insert(name.clone(), val.clone());
                                } else if let Some(group_body) = exports.groups.get(name) {
                                    interpreter.groups.insert(name.clone(), group_body.clone());
                                } else if let Some(pattern_stmt) = exports.patterns.get(name) {
                                    interpreter.variables.insert(
                                        name.clone(),
                                        Value::Statement(Box::new(pattern_stmt.clone())),
                                    );
                                } else {
                                    log_warn!(logger, "Import: '{}' not found in {}", name, source);
                                }
                            }
                        }
                        Err(e) => {
                            log_warn!(logger, "Failed to load module {}: {}", source, e);
                        }
                    }
                } else {
                    log_warn!(logger, "Import path not found: {}", source);
                }
            }
            StatementKind::Trigger {
                entity,
                duration: _,
                effects,
            } => {
                // Pass the effects associated with the trigger statement into the handler so
                // runtime scheduling can attach them to sample events.
                super::handler::handle_trigger(interpreter, entity, effects.as_ref())?;
            }
            StatementKind::Fade {
                direction,
                target,
                duration,
            } => {
                // Execute fade statement: automate a parameter in/out over duration
                super::handler::handle_fade(interpreter, direction, target, duration)?;
            }
            StatementKind::Section {
                name,
                duration,
                body,
            } => {
                // Execute section: store as a named group with duration
                // The section can be referenced later in timeline or schedule
                interpreter.groups.insert(name.clone(), body.clone());

                // If section has a duration specified, advance cursor by that duration
                // Otherwise, the duration will be auto-calculated when section is executed
                if let Some(dur) = duration {
                    if let Ok(sec) = interpreter.duration_to_seconds(dur) {
                        interpreter.cursor_time += sec;
                    }
                }
                // If duration is None, we let the execution of the body determine the timing
            }
            StatementKind::Timeline { sections } => {
                // Execute timeline: sequence sections in order
                for (section_name, opt_duration) in sections {
                    if let Some(body) = interpreter.groups.get(section_name).cloned() {
                        // Execute the section body
                        collect_events(interpreter, &body)?;

                        // If timeline specifies a duration override, use it; otherwise skip
                        if let Some(dur) = opt_duration {
                            interpreter.cursor_time += interpreter.duration_to_seconds(dur)?;
                        }
                    } else {
                        log_warn!(logger, "Section '{}' not found in timeline", section_name);
                    }
                }
            }
            StatementKind::Schedule { events } => {
                // Schedule is NON-BLOCKING: execute events at their specified times with deadlines
                // After executing all events, advance cursor to the end of the latest event

                let mut max_time = 0.0f32;

                // Execute each event with proper deadline.
                for (_idx, (start_dur, optional_dur, body)) in events.iter().enumerate() {
                    let start_time_secs = interpreter.duration_to_seconds(start_dur)?;
                    let opt_dur_secs = optional_dur
                        .as_ref()
                        .map(|dur| interpreter.duration_to_seconds(dur))
                        .transpose()?;

                    // Calculate deadline: either explicit duration or total_duration
                    // Events run in parallel, not sequentially, so each event runs until the end
                    // (or until explicit "during X" duration)
                    let deadline = if let Some(dur) = opt_dur_secs {
                        start_time_secs + dur
                    } else {
                        // Run until the end of the piece (respects stop all, etc.)
                        interpreter.special_vars.total_duration.max(1.0)
                    };

                    // Track the end time of this event
                    max_time = max_time.max(deadline);

                    // Execute event with cursor at its start time and deadline set
                    let saved_cursor = interpreter.cursor_time;
                    let saved_deadline = interpreter.schedule_deadline;

                    interpreter.cursor_time = start_time_secs;
                    interpreter.schedule_deadline = Some(deadline);

                    collect_events(interpreter, body)?;

                    interpreter.schedule_deadline = saved_deadline;
                    interpreter.cursor_time = saved_cursor;
                }

                // Advance cursor to the end of the latest scheduled event
                // so subsequent statements execute after all schedule events
                interpreter.cursor_time = max_time;
            }
            StatementKind::Stop { target, after } => {
                // Execute stop statement: silence audio playback
                // Stop is a global instruction that applies from the absolute start (time 0)
                // NOT relative to the current cursor_time
                let delay = after
                    .as_ref()
                    .map(|after_val| interpreter.duration_to_seconds(after_val))
                    .transpose()?
                    .unwrap_or(0.0);
                super::handler::handle_stop(interpreter, target.as_deref(), delay)?;
            }
            StatementKind::Unknown => {
                // Unknown statements are parser errors - log them with structured formatting
                if let Value::String(error_msg) = &stmt.value {
                    // Parse the structured error format: "MESSAGE|||FILE:LINE|||SUGGESTION"
                    let parts: Vec<&str> = error_msg.split("|||").collect();

                    let main_msg = parts
                        .get(0)
                        .map(|s| s.to_string())
                        .unwrap_or_else(|| error_msg.clone());
                    let file_location = parts.get(1).map(|s| s.to_string());
                    let suggestion_text = parts.get(2).and_then(|s| {
                        if s.is_empty() {
                            None
                        } else {
                            Some(format!("Did you mean '{}' ?", s))
                        }
                    });

                    // Create structured error with details
                    #[cfg(feature = "cli")]
                    {
                        let mut structured_err =
                            crate::tools::logger::StructuredError::new(&main_msg)
                                .with_location(stmt.line, stmt.column)
                                .with_type("UnknownStatement");

                        // Add file location if available
                        if let Some(file_loc) = file_location {
                            structured_err = structured_err.with_file(file_loc);
                        }

                        // Add suggestion if available
                        if let Some(suggest) = suggestion_text {
                            structured_err = structured_err.with_suggestion(suggest);
                        }

                        // Log the structured error
                        log_structured_error!(logger, structured_err);
                    }

                    #[cfg(not(feature = "cli"))]
                    {
                        let _ = (&main_msg, file_location, suggestion_text);
                    }

                    // Optionally push to WASM error registry
                    #[cfg(feature = "wasm")]
                    {
                        use crate::web::registry::debug;
                        if debug::is_debug_errors_enabled() {
                            debug::push_parse_error_from_parts(
                                error_msg.clone(),
                                stmt.line,
                                stmt.column,
                                "UnknownStatement".to_string(),
                            );
                        }
                    }
                }
            }
            _ => {}
        }
    }

    if !spawns.is_empty() {
        // ============================================================================
        // SPAWN EXECUTION (Parallel)
        // ============================================================================
        // Spawn accepts:
        // - Groups (defined with `group name:`)
        // - Patterns (defined with `pattern name with trigger = "x---"`)
        // - Samples (variables containing sample URIs)
        // - Bank properties (e.g., `spawn myBank.kick`)
        // ============================================================================

        // Executing spawns in parallel
        let current_time = interpreter.cursor_time;
        let current_bpm = interpreter.bpm;
        let groups_snapshot = interpreter.groups.clone();
        let variables_snapshot = interpreter.variables.clone();
        let special_vars_snapshot = interpreter.special_vars.clone();

        let spawn_results: Vec<Result<AudioEventList>> = spawns
            .par_iter()
            .map(|stmt| {
                if let StatementKind::Spawn { name, args: _ } = &stmt.kind {
                    let resolved_name = if name.starts_with('.') {
                        &name[1..]
                    } else {
                        name
                    };
                    if resolved_name.contains('.') {
                        let parts: Vec<&str> = resolved_name.split('.').collect();
                        if parts.len() == 2 {
                            let (var_name, property) = (parts[0], parts[1]);
                            if let Some(Value::Map(map)) = variables_snapshot.get(var_name) {
                                if let Some(Value::String(sample_uri)) = map.get(property) {
                                    // Spawn nested sample
                                    let mut event_list = AudioEventList::new();
                                    event_list.add_sample_event(
                                        sample_uri.trim_matches('"').trim_matches('\''),
                                        current_time,
                                        1.0,
                                    );
                                    return Ok(event_list);
                                }
                            }
                        }
                    }
                    if let Some(sample_value) = variables_snapshot.get(resolved_name) {
                        if let Value::String(sample_uri) = sample_value {
                            // Spawn sample
                            let mut event_list = AudioEventList::new();
                            event_list.add_sample_event(
                                sample_uri.trim_matches('"').trim_matches('\''),
                                current_time,
                                1.0,
                            );
                            return Ok(event_list);
                        }
                    }

                    let mut local_interpreter = AudioInterpreter {
                        sample_rate: interpreter.sample_rate,
                        bpm: current_bpm,
                        function_registry: FunctionRegistry::new(),
                        events: AudioEventList::new(),
                        variables: variables_snapshot.clone(),
                        groups: groups_snapshot.clone(),
                        banks: interpreter.banks.clone(),
                        automation_registry: interpreter.automation_registry.clone(),
                        note_automation_templates: interpreter.note_automation_templates.clone(),
                        cursor_time: current_time,
                        special_vars: special_vars_snapshot.clone(),
                        event_registry: EventRegistry::new(),
                        #[cfg(feature = "cli")]
                        midi_manager: interpreter.midi_manager.clone(),
                        current_statement_location: None,
                        suppress_beat_emit: interpreter.suppress_beat_emit,
                        suppress_print: interpreter.suppress_print,
                        break_flag: false,
                        // Ensure spawned local interpreters inherit the parent's
                        // background sender when present. This avoids creating
                        // ephemeral receivers that would be dropped and cause
                        // background workers to observe "receiver closed".
                        background_event_tx: interpreter.background_event_tx.clone(),
                        background_event_rx: None,
                        background_workers: Vec::new(),
                        realtime_print_tx: None,
                        function_call_depth: 0,
                        returning_flag: false,
                        return_value: None,
                        routing: Default::default(),
                        audio_graph: crate::engine::audio::graph::AudioGraph::new(),
                        current_event_node: interpreter.current_event_node.clone(),
                        schedule_deadline: None,
                    };

                    // Inherit synth definitions from parent so spawned groups can snapshot synths/plugins
                    local_interpreter.events.synths = interpreter.events.synths.clone();

                    // Try to spawn a group first
                    if let Some(body) = groups_snapshot.get(resolved_name) {
                        // Spawn group (parallel)
                        collect_events(&mut local_interpreter, body)?;
                        Ok(local_interpreter.events)
                    }
                    // Try to spawn a pattern
                    else if let Some(pattern_value) = variables_snapshot.get(resolved_name) {
                        if let Value::Statement(stmt_box) = pattern_value {
                            if let StatementKind::Pattern { target, .. } = &stmt_box.kind {
                                if let Some(tgt) = target.as_ref() {
                                    let (pattern_str, options) =
                                        local_interpreter.extract_pattern_data(&stmt_box.value);
                                    if let Some(pat) = pattern_str {
                                        // Execute pattern in spawned context
                                        local_interpreter.execute_pattern(
                                            tgt.as_str(),
                                            &pat,
                                            options,
                                        )?;
                                        return Ok(local_interpreter.events);
                                    }
                                }
                            }
                        }
                        // If not a pattern, warn
                        log_warn!(
                            logger,
                            "Spawn target '{}' is not a group or pattern",
                            resolved_name
                        );
                        Ok(AudioEventList::new())
                    } else {
                        log_warn!(
                            logger,
                            "Spawn target '{}' not found (neither sample, group, nor pattern)",
                            resolved_name
                        );
                        Ok(AudioEventList::new())
                    }
                } else {
                    Ok(AudioEventList::new())
                }
            })
            .collect();

        for result in spawn_results {
            match result {
                Ok(spawn_events) => {
                    interpreter.events.merge(spawn_events);
                }
                Err(e) => {
                    log_error!(logger, "Error in spawn execution: {}", e);
                }
            }
        }
    }

    // Emit some built-in beat events to trigger 'on beat' handlers.
    // Use the interpreter.special_vars.total_duration when available, but limit to a small number
    // of beats to avoid excessively long renders during tests.
    {
        // Emit beat events at exact beat grid (0, beat, 2*beat, ...) up to total duration.
        // We temporarily set interpreter.cursor_time and special_vars so handlers add events at
        // the correct beat timestamps, then we restore the original cursor_time afterwards.
        if !interpreter.suppress_beat_emit {
            let beat_duration =
                crate::engine::audio::duration::seconds_per_beat(interpreter.bpm).unwrap_or(0.0);

            // Determine total duration to cover. Prefer special_vars.total_duration if set.
            let total = if interpreter.special_vars.total_duration > 0.0 {
                interpreter.special_vars.total_duration
            } else {
                // Fallback: cover at least 4 beats
                beat_duration * 4.0
            };

            let max_beats = ((total / beat_duration).ceil() as usize).min(256).max(1);

            // Save previous state
            let prev_cursor = interpreter.cursor_time;
            let prev_time = interpreter.special_vars.current_time;
            let prev_beat = interpreter.special_vars.current_beat;

            for i in 0..max_beats {
                let beat_time = i as f32 * beat_duration;
                interpreter.cursor_time = beat_time;
                // Update special vars consistently (updates beat and bar)
                interpreter.special_vars.update_time(beat_time);

                // execute handlers for 'beat' but ensure handlers won't re-emit beats by setting the guard
                let prev = interpreter.suppress_beat_emit;
                interpreter.suppress_beat_emit = true;
                interpreter.execute_event_handlers("beat")?;
                // Also call 'bar' handlers at bar boundaries (every 4 beats)
                if (i % 4) == 0 {
                    interpreter.execute_event_handlers("bar")?;
                }
                interpreter.suppress_beat_emit = prev;
            }

            // Restore previous state
            interpreter.cursor_time = prev_cursor;
            interpreter.special_vars.current_time = prev_time;
            interpreter.special_vars.current_beat = prev_beat;
            // restore bar too
            interpreter.special_vars.current_bar = prev_beat / 4.0;
        }
    }

    // Do not perform a blocking drain here — background 'pass' workers will deliver
    // their events asynchronously. Blocking here caused noticeable latency before
    // playback in some offline render scenarios, so we avoid waiting and let the
    // normal event merge logic handle incoming background batches.

    Ok(())
}