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
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
use crate::engine::audio::events::AudioEventList;
use crate::engine::audio::events::SynthDefinition;
#[cfg(feature = "cli")]
use crate::engine::audio::midi_native::MidiManager;
use crate::engine::events::EventRegistry;
use crate::engine::functions::FunctionRegistry;
use crate::engine::special_vars::{SpecialVarContext, is_special_var, resolve_special_var};
#[cfg(feature = "cli")]
use crate::language::addons::registry::BankRegistry;
use crate::language::syntax::ast::{Statement, Value};
/// Routing configuration for a node
#[derive(Debug, Clone)]
pub struct RoutingNodeConfig {
pub name: String,
pub alias: Option<String>,
pub effects: Option<Value>, // FX chain for this node
}
/// Route configuration
#[derive(Debug, Clone)]
pub struct RouteConfig {
pub source: String,
pub destination: String,
pub effects: Option<Value>,
}
/// Duck configuration (sidechain-like compression)
#[derive(Debug, Clone)]
pub struct DuckConfig {
pub source: String,
pub destination: String,
pub effect: Value,
}
/// Sidechain configuration
#[derive(Debug, Clone)]
pub struct SidechainConfig {
pub source: String,
pub destination: String,
pub effect: Value,
}
/// Full routing setup
#[derive(Debug, Clone)]
pub struct RoutingSetup {
pub nodes: HashMap<String, RoutingNodeConfig>,
pub routes: Vec<RouteConfig>,
pub ducks: Vec<DuckConfig>,
pub sidechains: Vec<SidechainConfig>,
}
impl Default for RoutingSetup {
fn default() -> Self {
Self {
nodes: HashMap::new(),
routes: Vec::new(),
ducks: Vec::new(),
sidechains: Vec::new(),
}
}
}
#[cfg(not(feature = "cli"))]
#[allow(dead_code)]
#[derive(Clone)]
pub struct BankRegistry;
#[cfg(not(feature = "cli"))]
impl BankRegistry {
pub fn new() -> Self {
BankRegistry
}
pub fn list_banks(&self) -> Vec<(String, StubBank)> {
Vec::new()
}
pub fn resolve_trigger(&self, _var: &str, _prop: &str) -> Option<std::path::PathBuf> {
None
}
pub fn register_bank(
&self,
_alias: String,
_name: &str,
_cwd: &std::path::Path,
_cwd2: &std::path::Path,
) -> Result<(), anyhow::Error> {
Ok(())
}
}
#[cfg(not(feature = "cli"))]
#[allow(dead_code)]
#[derive(Clone)]
pub struct StubBank;
#[cfg(not(feature = "cli"))]
impl StubBank {
pub fn list_triggers(&self) -> Vec<String> {
Vec::new()
}
}
/// Context for note-mode automations: contains templates and their temporal bounds
#[derive(Clone, Debug)]
pub struct NoteAutomationContext {
pub templates: Vec<crate::engine::audio::automation::AutomationParamTemplate>,
pub start_time: f32,
pub end_time: f32,
}
impl NoteAutomationContext {
/// Calculate the total duration of this automation block
pub fn duration(&self) -> f32 {
(self.end_time - self.start_time).max(0.001) // Avoid division by zero
}
/// Calculate global progress (0.0 to 1.0) for a given time point within this block
pub fn progress_at_time(&self, time: f32) -> f32 {
((time - self.start_time) / self.duration()).clamp(0.0, 1.0)
}
}
/// Audio interpreter driver - main execution loop
use anyhow::Result;
use std::collections::HashMap;
pub mod collector;
pub mod extractor;
pub mod handler;
pub mod patterns;
pub mod renderer;
pub mod renderer_graph;
pub struct AudioInterpreter {
pub sample_rate: u32,
pub bpm: f32,
pub function_registry: FunctionRegistry,
pub events: AudioEventList,
pub variables: HashMap<String, Value>,
pub groups: HashMap<String, Vec<Statement>>,
pub banks: BankRegistry,
/// Registered global automations
pub automation_registry: crate::engine::audio::automation::AutomationRegistry,
/// Per-target note-mode automation contexts (including templates and timing info)
pub note_automation_templates: std::collections::HashMap<String, NoteAutomationContext>,
pub cursor_time: f32,
pub special_vars: SpecialVarContext,
pub event_registry: EventRegistry,
#[cfg(feature = "cli")]
pub midi_manager: Option<std::sync::Arc<std::sync::Mutex<MidiManager>>>,
/// Track current statement location for better error reporting
current_statement_location: Option<(usize, usize)>, // (line, column)
/// Internal guard to avoid re-entrant beat emission during handler execution
pub suppress_beat_emit: bool,
/// Internal guard to suppress printing during simulated/local interpreter runs
pub suppress_print: bool,
/// Flag used by 'break' statement to request breaking out of loops
pub break_flag: bool,
/// Background worker channel sender/receiver (threads send AudioEventList here)
pub background_event_tx:
Option<std::sync::mpsc::Sender<crate::engine::audio::events::AudioEventList>>,
pub background_event_rx:
Option<std::sync::mpsc::Receiver<crate::engine::audio::events::AudioEventList>>,
/// Holds join handles for background workers (optional, can be left running)
pub background_workers: Vec<std::thread::JoinHandle<()>>,
/// Optional channel used to replay prints in realtime during offline rendering.
pub realtime_print_tx: Option<std::sync::mpsc::Sender<(f32, String)>>,
/// Depth of active function calls. Used to validate 'return' usage (only valid inside functions).
pub function_call_depth: usize,
/// Function return state: when executing a function, a `return` statement sets
/// this flag and stores the returned value here so callers can inspect it.
pub returning_flag: bool,
pub return_value: Option<Value>,
/// Audio routing configuration
pub routing: RoutingSetup,
/// Audio graph (built from routing configuration)
pub audio_graph: crate::engine::audio::graph::AudioGraph,
/// Current graph node target while collecting a routed group/pattern.
pub current_event_node: Option<String>,
/// Optional deadline for schedule "during" clause (cutoff time for parent loop)
pub schedule_deadline: Option<f32>,
}
impl AudioInterpreter {
pub fn new(sample_rate: u32) -> Self {
Self {
sample_rate,
bpm: 120.0,
function_registry: FunctionRegistry::new(),
events: AudioEventList::new(),
variables: HashMap::new(),
groups: HashMap::new(),
banks: BankRegistry::new(),
automation_registry: crate::engine::audio::automation::AutomationRegistry::new(),
note_automation_templates: std::collections::HashMap::new(),
cursor_time: 0.0,
special_vars: SpecialVarContext::new(120.0, sample_rate),
event_registry: EventRegistry::new(),
#[cfg(feature = "cli")]
midi_manager: None,
current_statement_location: None,
suppress_beat_emit: false,
suppress_print: false,
break_flag: false,
background_event_tx: None,
background_event_rx: None,
background_workers: Vec::new(),
realtime_print_tx: None,
function_call_depth: 0,
returning_flag: false,
return_value: None,
routing: RoutingSetup::default(),
audio_graph: crate::engine::audio::graph::AudioGraph::new(),
current_event_node: None,
schedule_deadline: None,
}
}
/// Handle a trigger statement (e.g., .kit.kick or kit.kick)
fn handle_trigger(&mut self, entity: &str) -> Result<()> {
// Delegate detailed trigger handling to the handler module
handler::handle_trigger(self, entity, None)
}
/// Helper to print banks and triggers for debugging
fn debug_list_banks(&self) {
// helper intentionally silent in production builds
}
pub fn interpret(&mut self, statements: &[Statement]) -> Result<Vec<f32>> {
// Initialize special vars context
let total_duration = self.calculate_total_duration(statements)?;
self.special_vars.total_duration = total_duration;
self.special_vars.update_bpm(self.bpm);
// Phase 1: Collect events
self.collect_events(statements)?;
// If background 'pass' workers were spawned, drain their produced batches
// until we've received events covering the estimated total duration. This
// ensures offline/non-live renders include asynchronous loop-pass events
// (which are produced by background workers) before rendering audio.
if let Some(rx) = self.background_event_rx.as_mut() {
use std::sync::mpsc::RecvTimeoutError;
use std::time::{Duration, Instant};
let start = Instant::now();
// Hard cap to avoid waiting forever: allow up to total_duration + 5s
let hard_limit = Duration::from_secs_f32(total_duration + 5.0);
loop {
match rx.recv_timeout(Duration::from_millis(200)) {
Ok(events) => {
self.events.merge(events);
}
Err(RecvTimeoutError::Timeout) => {
// If we've already got events extending to the target duration, stop draining
if self.events.total_duration() >= (total_duration - 0.001) {
break;
}
if start.elapsed() > hard_limit {
// give up after hard limit
break;
}
// else continue waiting
}
Err(RecvTimeoutError::Disconnected) => {
// Sender(s) dropped; nothing more will arrive
break;
}
}
}
}
// Phase 2: Render audio
// Phase 2: Render audio
self.render_audio()
}
/// Get reference to collected audio events (for MIDI export)
pub fn events(&self) -> &AudioEventList {
&self.events
}
/// Get current statement location for error reporting
pub fn current_statement_location(&self) -> Option<(usize, usize)> {
self.current_statement_location
}
/// Calculate approximate total duration by scanning statements
pub fn calculate_total_duration(&self, _statements: &[Statement]) -> Result<f32> {
// For now, return a default duration (will be updated during collect_events)
Ok(60.0) // Default 60 seconds
}
pub fn collect_events(&mut self, statements: &[Statement]) -> Result<()> {
// Delegate to the collector child module
collector::collect_events(self, statements)
}
pub fn handle_let(&mut self, name: &str, value: &Value) -> Result<()> {
handler::handle_let(self, name, value)
}
pub fn extract_audio_event(
&mut self,
target: &str,
context: &crate::engine::functions::FunctionContext,
) -> Result<()> {
// Delegate to extractor child module
extractor::extract_audio_event(self, target, context)
}
pub fn render_audio(&self) -> Result<Vec<f32>> {
// Delegate to renderer child module
renderer::render_audio(self)
}
pub fn set_bpm(&mut self, bpm: f32) {
self.bpm = bpm.max(1.0).min(999.0);
// Keep special vars in sync so $beat/$bar calculations use the updated BPM
self.special_vars.update_bpm(self.bpm);
}
pub fn samples_per_beat(&self) -> usize {
((60.0 / self.bpm) * self.sample_rate as f32) as usize
}
/// Get duration of one beat in seconds
pub fn beat_duration(&self) -> f32 {
60.0 / self.bpm
}
/// Execute print statement with variable interpolation
/// Supports {variable_name} syntax
pub fn execute_print(&mut self, value: &Value) -> Result<()> {
handler::execute_print(self, value)
}
/// Interpolate variables in a string
/// Replaces {variable_name} with the variable's value
pub fn interpolate_string(&self, template: &str) -> String {
let mut result = template.to_string();
// Find all {variable} patterns
let Ok(re) = regex::Regex::new(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}") else {
return result;
};
for cap in re.captures_iter(template) {
let full_match = &cap[0]; // {variable_name}
let var_name = &cap[1]; // variable_name
if let Some(value) = self.variables.get(var_name) {
let replacement = self.value_to_string(value);
result = result.replace(full_match, &replacement);
} else {
// Variable not found, leave placeholder or show error
result = result.replace(full_match, &format!("<undefined:{}>", var_name));
}
}
result
}
/// Convert a Value to a displayable string
fn value_to_string(&self, value: &Value) -> String {
match value {
Value::String(s) => {
// Remove surrounding quotes if present
s.trim_matches('"').trim_matches('\'').to_string()
}
Value::Number(n) => {
// Format nicely: remove trailing zeros
if n.fract() == 0.0 {
format!("{:.0}", n)
} else {
format!("{}", n)
}
}
Value::Boolean(b) => b.to_string(),
Value::Array(arr) => {
let items: Vec<String> = arr.iter().map(|v| self.value_to_string(v)).collect();
format!("[{}]", items.join(", "))
}
Value::Identifier(id) => id.clone(),
_ => format!("{:?}", value),
}
}
/// Execute if statement with condition evaluation
pub fn execute_if(
&mut self,
condition: &Value,
body: &[Statement],
else_body: &Option<Vec<Statement>>,
) -> Result<()> {
handler::execute_if(self, condition, body, else_body)
}
/// Evaluate a condition to a boolean
/// Supports: ==, !=, <, >, <=, >=
pub fn evaluate_condition(&mut self, condition: &Value) -> Result<bool> {
// Condition is stored as a Map with operator and operands
if let Value::Map(map) = condition {
let operator = map
.get("operator")
.and_then(|v| {
if let Value::String(s) = v {
Some(s.as_str())
} else {
None
}
})
.unwrap_or("==");
// Handle logical operators first (highest priority)
match operator {
"&&" => {
let left = map
.get("left")
.ok_or_else(|| anyhow::anyhow!("Missing left operand for &&"))?;
let right = map
.get("right")
.ok_or_else(|| anyhow::anyhow!("Missing right operand for &&"))?;
let left_result = self.evaluate_condition(left)?;
let right_result = self.evaluate_condition(right)?;
return Ok(left_result && right_result);
}
"||" => {
let left = map
.get("left")
.ok_or_else(|| anyhow::anyhow!("Missing left operand for ||"))?;
let right = map
.get("right")
.ok_or_else(|| anyhow::anyhow!("Missing right operand for ||"))?;
let left_result = self.evaluate_condition(left)?;
let right_result = self.evaluate_condition(right)?;
return Ok(left_result || right_result);
}
"!" => {
let operand = map
.get("operand")
.ok_or_else(|| anyhow::anyhow!("Missing operand for !"))?;
let operand_result = self.evaluate_condition(operand)?;
return Ok(!operand_result);
}
_ => {}
}
// Handle comparison operators
let left = map
.get("left")
.ok_or_else(|| anyhow::anyhow!("Missing left operand"))?;
let right = map
.get("right")
.ok_or_else(|| anyhow::anyhow!("Missing right operand"))?;
// Resolve values (replace identifiers with their values)
let left_val = self.resolve_value(left)?;
let right_val = self.resolve_value(right)?;
// Compare based on operator
match operator {
"==" => Ok(self.values_equal(&left_val, &right_val)),
"!=" => Ok(!self.values_equal(&left_val, &right_val)),
"<" => self.compare_values(&left_val, &right_val, std::cmp::Ordering::Less),
">" => self.compare_values(&left_val, &right_val, std::cmp::Ordering::Greater),
"<=" => {
let less =
self.compare_values(&left_val, &right_val, std::cmp::Ordering::Less)?;
let equal = self.values_equal(&left_val, &right_val);
Ok(less || equal)
}
">=" => {
let greater =
self.compare_values(&left_val, &right_val, std::cmp::Ordering::Greater)?;
let equal = self.values_equal(&left_val, &right_val);
Ok(greater || equal)
}
_ => Err(anyhow::anyhow!("Unknown operator: {}", operator)),
}
} else {
// Direct boolean value or identifier: resolve identifiers first
let resolved = self.resolve_value(condition)?;
match resolved {
Value::Boolean(b) => Ok(b),
Value::Number(n) => Ok(n != 0.0),
Value::String(s) => Ok(!s.is_empty()),
Value::Identifier(id) => {
// Resolve further if needed (shouldn't usually happen)
let further = self.resolve_value(&Value::Identifier(id))?;
match further {
Value::Boolean(b2) => Ok(b2),
Value::Number(n2) => Ok(n2 != 0.0),
Value::String(s2) => Ok(!s2.is_empty()),
_ => Ok(false),
}
}
_ => Ok(false),
}
}
}
/// Resolve a value (replace identifiers with their values from variables)
pub fn resolve_value(&mut self, value: &Value) -> Result<Value> {
match value {
Value::Identifier(name) => {
// Check if it's a special variable
if is_special_var(name) {
if let Some(special_val) = resolve_special_var(name, &self.special_vars) {
return Ok(special_val);
}
}
// Support combined property/index access like `obj.prop` and `arr[0]` or mixed `arr[0].prop`
if name.contains('.') || name.contains('[') {
// parse segments: start with initial identifier, then .prop or [index]
let mut chars = name.chars().peekable();
// read initial identifier
let mut ident = String::new();
while let Some(&c) = chars.peek() {
if c == '.' || c == '[' {
break;
}
ident.push(c);
chars.next();
}
let mut current: Option<Value> = if ident.is_empty() {
None
} else if is_special_var(&ident) {
resolve_special_var(&ident, &self.special_vars)
} else {
self.variables.get(&ident).cloned()
};
if current.is_none() {
return Ok(Value::Null);
}
// iterate segments
while let Some(&c) = chars.peek() {
if c == '.' {
// consume '.'
chars.next();
// read property name
let mut prop = String::new();
while let Some(&nc) = chars.peek() {
if nc == '.' || nc == '[' {
break;
}
prop.push(nc);
chars.next();
}
// descend into map
match current {
Some(Value::Map(ref map)) => {
current = map.get(&prop).cloned();
}
_ => {
return Ok(Value::Null);
}
}
if current.is_none() {
return Ok(Value::Null);
}
} else if c == '[' {
// consume '['
chars.next();
// read until ']'
let mut idx_tok = String::new();
while let Some(&nc) = chars.peek() {
if nc == ']' {
break;
}
idx_tok.push(nc);
chars.next();
}
// consume ']'
if let Some(&nc) = chars.peek() {
if nc == ']' {
chars.next();
} else {
return Ok(Value::Null); // malformed
}
} else {
return Ok(Value::Null); // malformed
}
let idx_tok_trim = idx_tok.trim();
// resolve index token: it can be a number or identifier
let index_value = if let Ok(n) = idx_tok_trim.parse::<usize>() {
Value::Number(n as f32)
} else {
Value::Identifier(idx_tok_trim.to_string())
};
// apply index to current
match current {
Some(Value::Array(ref arr)) => {
// resolve index value to number. Support simple expressions like
// `i + 1` and post-increment `i++` (treated as i+1 without mutation).
// Evaluate index token. Support mutation for `i++` (post-increment):
// When encountering `ident++`, mutate the variable in-place and use the old value.
let resolved_idx = if idx_tok_trim.ends_with("++") {
// post-increment: mutate var and return old value
let varname = idx_tok_trim[..idx_tok_trim.len() - 2].trim();
let cur = match self.resolve_value(&Value::Identifier(
varname.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
};
self.variables.insert(
varname.to_string(),
Value::Number((cur + 1) as f32),
);
cur
} else if idx_tok_trim.ends_with("--") {
// post-decrement: mutate var and return old value
let varname = idx_tok_trim[..idx_tok_trim.len() - 2].trim();
let cur = match self.resolve_value(&Value::Identifier(
varname.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
};
self.variables.insert(
varname.to_string(),
Value::Number((cur - 1) as f32),
);
cur
} else if idx_tok_trim.contains('+') {
let parts: Vec<&str> =
idx_tok_trim.splitn(2, '+').collect();
let left = parts[0].trim();
let right = parts[1].trim();
let left_val = if let Ok(n) = left.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
left.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
let right_val = if let Ok(n) = right.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
right.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
left_val + right_val
} else if idx_tok_trim.contains('*') {
let parts: Vec<&str> =
idx_tok_trim.splitn(2, '*').collect();
let left = parts[0].trim();
let right = parts[1].trim();
let left_val = if let Ok(n) = left.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
left.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
let right_val = if let Ok(n) = right.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
right.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
left_val * right_val
} else if idx_tok_trim.contains('/') {
let parts: Vec<&str> =
idx_tok_trim.splitn(2, '/').collect();
let left = parts[0].trim();
let right = parts[1].trim();
let left_val = if let Ok(n) = left.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
left.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
let right_val = if let Ok(n) = right.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
right.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
if right_val == 0 {
return Err(anyhow::anyhow!(
"Division by zero in index expression"
));
}
left_val / right_val
} else if idx_tok_trim.contains('%') {
let parts: Vec<&str> =
idx_tok_trim.splitn(2, '%').collect();
let left = parts[0].trim();
let right = parts[1].trim();
let left_val = if let Ok(n) = left.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
left.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
let right_val = if let Ok(n) = right.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
right.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
if right_val == 0 {
return Err(anyhow::anyhow!(
"Modulo by zero in index expression"
));
}
left_val % right_val
} else if idx_tok_trim.contains('-') {
let parts: Vec<&str> =
idx_tok_trim.splitn(2, '-').collect();
let left = parts[0].trim();
let right = parts[1].trim();
let left_val = if let Ok(n) = left.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
left.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
let right_val = if let Ok(n) = right.parse::<isize>() {
n
} else {
match self.resolve_value(&Value::Identifier(
right.to_string(),
))? {
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
}
};
left_val - right_val
} else {
match index_value {
Value::Number(n) => n as isize,
Value::Identifier(ref id) => match self
.resolve_value(&Value::Identifier(id.clone()))?
{
Value::Number(n2) => n2 as isize,
_ => return Ok(Value::Null),
},
_ => return Ok(Value::Null),
}
};
if resolved_idx < 0 {
return Ok(Value::Null);
}
let ui = resolved_idx as usize;
if ui < arr.len() {
let mut elem = arr[ui].clone();
// If the element is a bare Identifier (like C4) and there is no
// variable with that name, treat it as a String token for convenience
if let Value::Identifier(ref id) = elem {
if !is_special_var(id)
&& self.variables.get(id).is_none()
{
elem = Value::String(id.clone());
}
}
// If the element is a Map with a 'value' key, unwrap it so
// myArray[0] returns the inner value directly and so that
// chained access like myArray[2].volume works (we operate on
// the inner value map)
if let Value::Map(ref m) = elem {
if let Some(inner) = m.get("value") {
current = Some(inner.clone());
} else {
current = Some(elem);
}
} else {
current = Some(elem);
}
} else {
return Err(anyhow::anyhow!(
"Index out of range: {} (len={})",
ui,
arr.len()
));
}
}
Some(Value::Map(ref map)) => {
// use index token as key
let key = idx_tok_trim.trim_matches('"').trim_matches('\'');
current = map.get(key).cloned();
if current.is_none() {
return Ok(Value::Null);
}
}
_ => {
return Ok(Value::Null);
}
}
} else {
// unexpected char
break;
}
}
return Ok(current.unwrap_or(Value::Null));
}
// Otherwise, look in variables; if not found, treat bare identifier as a string token
return Ok(self
.variables
.get(name)
.cloned()
.unwrap_or(Value::String(name.clone())));
}
Value::Call { name, args } => {
// Evaluate call expression: resolve args then execute function/group/pattern
// Resolve each arg
let mut resolved_args: Vec<Value> = Vec::new();
for a in args.iter() {
let rv = self.resolve_value(a)?;
resolved_args.push(rv);
}
// Delegate to handler to execute call and return a Value
let res = super::handler::call_function(self, name, &resolved_args)?;
return Ok(res);
}
_ => return Ok(value.clone()),
}
}
/// Execute event handlers matching the event name
pub fn execute_event_handlers(&mut self, event_name: &str) -> Result<()> {
handler::execute_event_handlers(self, event_name)
}
/// Check if two values are equal
pub fn values_equal(&self, left: &Value, right: &Value) -> bool {
match (left, right) {
(Value::Number(a), Value::Number(b)) => (a - b).abs() < 0.0001,
(Value::String(a), Value::String(b)) => a == b,
(Value::Boolean(a), Value::Boolean(b)) => a == b,
(Value::Null, Value::Null) => true,
_ => false,
}
}
/// Compare two values
pub fn compare_values(
&self,
left: &Value,
right: &Value,
ordering: std::cmp::Ordering,
) -> Result<bool> {
match (left, right) {
(Value::Number(a), Value::Number(b)) => {
Ok(a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal) == ordering)
}
(Value::String(a), Value::String(b)) => Ok(a.cmp(b) == ordering),
_ => Err(anyhow::anyhow!("Cannot compare {:?} and {:?}", left, right)),
}
}
/// Handle property assignment: target.property = value
pub fn handle_assign(&mut self, target: &str, property: &str, value: &Value) -> Result<()> {
handler::handle_assign(self, target, property, value)
}
/// Extract synth definition from a map
pub fn extract_synth_def_from_map(
&self,
map: &HashMap<String, Value>,
) -> Result<SynthDefinition> {
handler::extract_synth_def_from_map(self, map)
}
/// Handle MIDI file loading: @load "path.mid" as alias
pub fn handle_load(&mut self, source: &str, alias: &str) -> Result<()> {
handler::handle_load(self, source, alias)
}
/// Handle MIDI binding: bind source -> target { options }
pub fn handle_bind(&mut self, source: &str, target: &str, options: &Value) -> Result<()> {
handler::handle_bind(self, source, target, options)
}
/// Extract pattern string and options from pattern value
pub fn extract_pattern_data(
&self,
value: &Value,
) -> (Option<String>, Option<HashMap<String, f32>>) {
patterns::extract_pattern_data(self, value)
}
/// Execute a pattern with given target and pattern string
pub fn execute_pattern(
&mut self,
target: &str,
pattern: &str,
options: Option<HashMap<String, f32>>,
) -> Result<()> {
patterns::execute_pattern(self, target, pattern, options)
}
/// Execute a pattern with source tracking for routing
pub fn execute_pattern_with_source(
&mut self,
target: &str,
pattern: &str,
options: Option<HashMap<String, f32>>,
source: Option<&str>,
) -> Result<()> {
patterns::execute_pattern_with_source(self, target, pattern, options, source)
}
/// Resolve sample URI from bank.trigger notation (e.g., myBank.kick -> devalang://bank/devalang.808/kick)
pub fn resolve_sample_uri(&self, target: &str) -> String {
patterns::resolve_sample_uri(self, target)
}
/// Convert a DurationValue to seconds based on current BPM
pub fn duration_to_seconds(
&self,
duration: &crate::language::syntax::ast::DurationValue,
) -> Result<f32> {
crate::engine::audio::duration::duration_to_seconds(duration, self.bpm)
}
/// Resolve the graph node for an event while collecting it.
pub fn resolve_event_node_id(&self, source: &str) -> Option<String> {
if let Some(node_id) = &self.current_event_node {
return Some(node_id.clone());
}
let source = crate::engine::audio::graph::canonicalize_node_id(source);
for (node_name, config) in &self.routing.nodes {
let node_id = crate::engine::audio::graph::canonicalize_node_id(node_name);
if node_id == source
|| config.name == source
|| config
.alias
.as_ref()
.map(|alias| crate::engine::audio::graph::canonicalize_node_id(alias) == source)
.unwrap_or(false)
{
return Some(node_id);
}
}
Some(self.audio_graph.master.clone())
}
/// Execute a body with a temporary routed graph node context.
pub fn collect_with_event_node(
&mut self,
node_id: Option<String>,
body: &[Statement],
) -> Result<()> {
let previous = self.current_event_node.clone();
self.current_event_node = node_id.or(previous.clone());
let result = collector::collect_events(self, body);
self.current_event_node = previous;
result
}
/// Resolve a group or pattern name to a declared routing node alias.
pub fn routed_node_for_alias(&self, alias: &str) -> Option<String> {
self.routing.nodes.iter().find_map(|(node_name, config)| {
if config.alias.as_deref() == Some(alias) || node_name == alias {
Some(crate::engine::audio::graph::canonicalize_node_id(node_name))
} else {
None
}
})
}
}
#[cfg(test)]
#[path = "test_arrays.rs"]
mod tests_arrays;
#[cfg(test)]
#[path = "test_print.rs"]
mod tests_print;
#[cfg(test)]
#[path = "test_functions.rs"]
mod tests_functions;
#[cfg(test)]
#[path = "test_control_flow.rs"]
mod tests_control_flow;
#[cfg(test)]
mod phase_2_routing_tests {
use super::*;
use crate::engine::audio::events::{AudioEvent, SynthDefinition};
use crate::engine::functions::FunctionContext;
use crate::language::syntax::ast::Value;
fn route_pattern_to_bus(interpreter: &mut AudioInterpreter) {
interpreter.routing.nodes.insert(
"drums_bus".to_string(),
RoutingNodeConfig {
name: "drums_bus".to_string(),
alias: Some("kickPattern".to_string()),
effects: None,
},
);
interpreter.audio_graph =
crate::engine::audio::graph::AudioGraph::from_routing_setup(&interpreter.routing);
}
#[test]
fn note_event_node_id_is_resolved_during_collection() {
let mut interpreter = AudioInterpreter::new(44_100);
interpreter.routing.nodes.insert(
"lead_bus".to_string(),
RoutingNodeConfig {
name: "lead_bus".to_string(),
alias: Some("lead".to_string()),
effects: None,
},
);
interpreter.audio_graph =
crate::engine::audio::graph::AudioGraph::from_routing_setup(&interpreter.routing);
interpreter
.events
.add_synth("lead".to_string(), SynthDefinition::default());
let mut context = FunctionContext::new("lead".to_string(), 0.0, interpreter.bpm);
context.set("note", Value::String("C4".to_string()));
context.set("duration", Value::Number(250.0));
interpreter.extract_audio_event("lead", &context).unwrap();
match interpreter.events.events.last().unwrap() {
AudioEvent::Note { node_id, .. } => {
assert_eq!(node_id.as_deref(), Some("lead_bus"));
}
other => panic!("expected note event, got {:?}", other),
}
}
#[test]
fn sample_event_node_id_is_resolved_from_pattern_source() {
let mut interpreter = AudioInterpreter::new(44_100);
route_pattern_to_bus(&mut interpreter);
interpreter
.execute_pattern_with_source("kit.kick", "x---", None, Some("kickPattern"))
.unwrap();
match interpreter.events.events.first().unwrap() {
AudioEvent::Sample {
node_id, source, ..
} => {
assert_eq!(source.as_deref(), Some("kickPattern"));
assert_eq!(node_id.as_deref(), Some("drums_bus"));
}
other => panic!("expected sample event, got {:?}", other),
}
}
#[test]
fn unrouted_event_falls_back_to_master_node() {
let interpreter = AudioInterpreter::new(44_100);
assert_eq!(
interpreter.resolve_event_node_id("missing").as_deref(),
Some("master")
);
}
}