devalang_wasm/engine/special_vars/
mod.rs

1/// Special variables system for Devalang
2/// Provides runtime-computed variables like $beat, $time, $random, etc.
3use crate::language::syntax::ast::Value;
4use std::collections::HashMap;
5
6/// Special variable prefix
7pub const SPECIAL_VAR_PREFIX: char = '$';
8
9/// Special variable categories
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum SpecialVarCategory {
12    Time,     // $time, $beat, $bar
13    Random,   // $random.noise, $random.float, $random.int
14    Music,    // $bpm, $tempo, $duration
15    Position, // $position, $progress
16    Midi,     // $midi.note, $midi.velocity
17    System,   // $sampleRate, $channels
18}
19
20/// Special variable context - holds runtime state
21#[derive(Debug, Clone)]
22pub struct SpecialVarContext {
23    pub current_time: f32,   // Current playback time in seconds
24    pub current_beat: f32,   // Current beat position
25    pub current_bar: f32,    // Current bar position
26    pub bpm: f32,            // Current BPM
27    pub duration: f32,       // Beat duration in seconds
28    pub sample_rate: u32,    // Sample rate
29    pub channels: usize,     // Number of channels
30    pub position: f32,       // Normalized position (0.0-1.0)
31    pub total_duration: f32, // Total duration in seconds
32}
33
34impl Default for SpecialVarContext {
35    fn default() -> Self {
36        Self {
37            current_time: 0.0,
38            current_beat: 0.0,
39            current_bar: 0.0,
40            bpm: 120.0,
41            duration: 0.5,
42            sample_rate: 44100,
43            channels: 2,
44            position: 0.0,
45            total_duration: 0.0,
46        }
47    }
48}
49
50impl SpecialVarContext {
51    pub fn new(bpm: f32, sample_rate: u32) -> Self {
52        Self {
53            bpm,
54            duration: 60.0 / bpm,
55            sample_rate,
56            ..Default::default()
57        }
58    }
59
60    /// Update time-based variables
61    pub fn update_time(&mut self, time: f32) {
62        self.current_time = time;
63        self.current_beat = time / self.duration;
64        self.current_bar = self.current_beat / 4.0;
65
66        if self.total_duration > 0.0 {
67            self.position = (time / self.total_duration).clamp(0.0, 1.0);
68        }
69    }
70
71    /// Update BPM
72    pub fn update_bpm(&mut self, bpm: f32) {
73        self.bpm = bpm;
74        self.duration = 60.0 / bpm;
75    }
76}
77
78/// Check if a variable name is a special variable
79pub fn is_special_var(name: &str) -> bool {
80    name.starts_with(SPECIAL_VAR_PREFIX)
81}
82
83/// Resolve a special variable to its current value
84pub fn resolve_special_var(name: &str, context: &SpecialVarContext) -> Option<Value> {
85    if !is_special_var(name) {
86        return None;
87    }
88
89    match name {
90        // Time variables
91        "$time" => Some(Value::Number(context.current_time)),
92        "$beat" => Some(Value::Number(context.current_beat)),
93        "$bar" => Some(Value::Number(context.current_bar)),
94        "$currentTime" => Some(Value::Number(context.current_time)),
95        "$currentBeat" => Some(Value::Number(context.current_beat)),
96        "$currentBar" => Some(Value::Number(context.current_bar)),
97
98        // Music variables
99        "$bpm" => Some(Value::Number(context.bpm)),
100        "$tempo" => Some(Value::Number(context.bpm)),
101        "$duration" => Some(Value::Number(context.duration)),
102
103        // Position variables
104        "$position" => Some(Value::Number(context.position)),
105        "$progress" => Some(Value::Number(context.position)),
106
107        // System variables
108        "$sampleRate" => Some(Value::Number(context.sample_rate as f32)),
109        "$channels" => Some(Value::Number(context.channels as f32)),
110
111        // Random variables (computed on-demand)
112        "$random" | "$random.float" => Some(Value::Number(rand::random::<f32>())),
113        "$random.noise" => Some(Value::Number(rand::random::<f32>() * 2.0 - 1.0)), // -1.0 to 1.0
114        "$random.int" => Some(Value::Number((rand::random::<u32>() % 100) as f32)),
115        "$random.bool" => Some(Value::Boolean(rand::random::<bool>())),
116
117        // Nested random with ranges
118        _ if name.starts_with("$random.range(") => {
119            // Parse $random.range(min, max)
120            parse_random_range(name)
121        }
122
123        _ => None,
124    }
125}
126
127/// Parse $random.range(min, max) syntax
128fn parse_random_range(name: &str) -> Option<Value> {
129    // Extract content between parentheses
130    let start = name.find('(')?;
131    let end = name.rfind(')')?;
132    let content = &name[start + 1..end];
133
134    // Split by comma
135    let parts: Vec<&str> = content.split(',').map(|s| s.trim()).collect();
136    if parts.len() != 2 {
137        return None;
138    }
139
140    // Parse min and max
141    let min: f32 = parts[0].parse().ok()?;
142    let max: f32 = parts[1].parse().ok()?;
143
144    // Generate random value in range
145    let value = min + rand::random::<f32>() * (max - min);
146    Some(Value::Number(value))
147}
148
149/// Get all available special variables as a map
150pub fn get_all_special_vars(context: &SpecialVarContext) -> HashMap<String, Value> {
151    let mut vars = HashMap::new();
152
153    // Time
154    vars.insert("$time".to_string(), Value::Number(context.current_time));
155    vars.insert("$beat".to_string(), Value::Number(context.current_beat));
156    vars.insert("$bar".to_string(), Value::Number(context.current_bar));
157    vars.insert(
158        "$currentTime".to_string(),
159        Value::Number(context.current_time),
160    );
161    vars.insert(
162        "$currentBeat".to_string(),
163        Value::Number(context.current_beat),
164    );
165    vars.insert(
166        "$currentBar".to_string(),
167        Value::Number(context.current_bar),
168    );
169
170    // Music
171    vars.insert("$bpm".to_string(), Value::Number(context.bpm));
172    vars.insert("$tempo".to_string(), Value::Number(context.bpm));
173    vars.insert("$duration".to_string(), Value::Number(context.duration));
174
175    // Position
176    vars.insert("$position".to_string(), Value::Number(context.position));
177    vars.insert("$progress".to_string(), Value::Number(context.position));
178
179    // System
180    vars.insert(
181        "$sampleRate".to_string(),
182        Value::Number(context.sample_rate as f32),
183    );
184    vars.insert(
185        "$channels".to_string(),
186        Value::Number(context.channels as f32),
187    );
188
189    vars
190}
191
192/// List all special variable categories with examples
193pub fn list_special_vars() -> HashMap<&'static str, Vec<(&'static str, &'static str)>> {
194    let mut categories = HashMap::new();
195
196    categories.insert(
197        "Time",
198        vec![
199            ("$time", "Current time in seconds"),
200            ("$beat", "Current beat position"),
201            ("$bar", "Current bar position"),
202            ("$currentTime", "Alias for $time"),
203            ("$currentBeat", "Alias for $beat"),
204            ("$currentBar", "Alias for $bar"),
205        ],
206    );
207
208    categories.insert(
209        "Music",
210        vec![
211            ("$bpm", "Current BPM"),
212            ("$tempo", "Alias for $bpm"),
213            ("$duration", "Beat duration in seconds"),
214        ],
215    );
216
217    categories.insert(
218        "Position",
219        vec![
220            ("$position", "Normalized position (0.0-1.0)"),
221            ("$progress", "Alias for $position"),
222        ],
223    );
224
225    categories.insert(
226        "Random",
227        vec![
228            ("$random", "Random float 0.0-1.0"),
229            ("$random.float", "Random float 0.0-1.0"),
230            ("$random.noise", "Random float -1.0 to 1.0"),
231            ("$random.int", "Random integer 0-99"),
232            ("$random.bool", "Random boolean"),
233            ("$random.range(min, max)", "Random float in range"),
234        ],
235    );
236
237    categories.insert(
238        "System",
239        vec![
240            ("$sampleRate", "Sample rate in Hz"),
241            ("$channels", "Number of audio channels"),
242        ],
243    );
244
245    categories
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn test_is_special_var() {
254        assert!(is_special_var("$time"));
255        assert!(is_special_var("$beat"));
256        assert!(is_special_var("$random"));
257        assert!(!is_special_var("time"));
258        assert!(!is_special_var("myVar"));
259    }
260
261    #[test]
262    fn test_resolve_time_vars() {
263        let mut context = SpecialVarContext::default();
264        context.update_time(2.0);
265
266        let time = resolve_special_var("$time", &context);
267        assert_eq!(time, Some(Value::Number(2.0)));
268
269        let beat = resolve_special_var("$beat", &context);
270        assert!(matches!(beat, Some(Value::Number(_))));
271    }
272
273    #[test]
274    fn test_resolve_random_vars() {
275        let context = SpecialVarContext::default();
276
277        let rand1 = resolve_special_var("$random", &context);
278        assert!(matches!(rand1, Some(Value::Number(_))));
279
280        let rand2 = resolve_special_var("$random.noise", &context);
281        assert!(matches!(rand2, Some(Value::Number(_))));
282    }
283
284    #[test]
285    fn test_context_update_time() {
286        let mut context = SpecialVarContext::new(120.0, 44100);
287        context.update_time(1.0);
288
289        assert_eq!(context.current_time, 1.0);
290        assert!(context.current_beat > 0.0);
291    }
292
293    #[test]
294    fn test_parse_random_range() {
295        let result = parse_random_range("$random.range(0, 10)");
296        assert!(result.is_some());
297
298        if let Some(Value::Number(n)) = result {
299            assert!(n >= 0.0 && n <= 10.0);
300        }
301    }
302}