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    // small epsilon to avoid floating-point rounding making exact boundaries fall
90    // just below an integer (e.g., 0.9999999) which would incorrectly floor to previous
91    // bar. Use a tiny epsilon when applying floor for bar calculations.
92    let eps = 1e-6_f32;
93
94    match name {
95        // Time variables
96        "$time" => Some(Value::Number(context.current_time)),
97        "$beat" => Some(Value::Number(context.current_beat)),
98        // Return 1-based bar number (integers) so scripts can compare with ==
99        // e.g., at time 0 the first bar is 1
100        "$bar" => Some(Value::Number((context.current_bar + eps).floor() + 1.0)),
101        "$currentTime" => Some(Value::Number(context.current_time)),
102        "$currentBeat" => Some(Value::Number(context.current_beat)),
103        "$currentBar" => Some(Value::Number((context.current_bar + eps).floor() + 1.0)),
104
105        // Music variables
106        "$bpm" => Some(Value::Number(context.bpm)),
107        "$tempo" => Some(Value::Number(context.bpm)),
108        "$duration" => Some(Value::Number(context.duration)),
109
110        // Position variables
111        "$position" => Some(Value::Number(context.position)),
112        "$progress" => Some(Value::Number(context.position)),
113
114        // System variables
115        "$sampleRate" => Some(Value::Number(context.sample_rate as f32)),
116        "$channels" => Some(Value::Number(context.channels as f32)),
117
118        // Random variables (computed on-demand)
119        #[cfg(any(feature = "cli", feature = "wasm"))]
120        "$random" | "$random.float" => Some(Value::Number(rand::random::<f32>())),
121        #[cfg(any(feature = "cli", feature = "wasm"))]
122        "$random.noise" => Some(Value::Number(rand::random::<f32>() * 2.0 - 1.0)), // -1.0 to 1.0
123        #[cfg(any(feature = "cli", feature = "wasm"))]
124        "$random.int" => Some(Value::Number((rand::random::<u32>() % 100) as f32)),
125        #[cfg(any(feature = "cli", feature = "wasm"))]
126        "$random.bool" => Some(Value::Boolean(rand::random::<bool>())),
127
128        // Nested random with ranges
129        #[cfg(any(feature = "cli", feature = "wasm"))]
130        _ if name.starts_with("$random.range(") => {
131            // Parse $random.range(min, max)
132            parse_random_range(name)
133        }
134
135        _ => None,
136    }
137}
138
139/// Parse $random.range(min, max) syntax
140#[cfg(any(feature = "cli", feature = "wasm"))]
141fn parse_random_range(name: &str) -> Option<Value> {
142    // Extract content between parentheses
143    let start = name.find('(')?;
144    let end = name.rfind(')')?;
145    let content = &name[start + 1..end];
146
147    // Split by comma
148    let parts: Vec<&str> = content.split(',').map(|s| s.trim()).collect();
149    if parts.len() != 2 {
150        return None;
151    }
152
153    // Parse min and max
154    let min: f32 = parts[0].parse().ok()?;
155    let max: f32 = parts[1].parse().ok()?;
156
157    // Generate random value in range
158    let value = min + rand::random::<f32>() * (max - min);
159    Some(Value::Number(value))
160}
161
162/// Get all available special variables as a map
163pub fn get_all_special_vars(context: &SpecialVarContext) -> HashMap<String, Value> {
164    let mut vars = HashMap::new();
165
166    // small epsilon to avoid floating-point rounding issues at exact boundaries
167    let eps = 1e-6_f32;
168
169    // Time
170    vars.insert("$time".to_string(), Value::Number(context.current_time));
171    vars.insert("$beat".to_string(), Value::Number(context.current_beat));
172    // Expose bar as 1-based integer (users expect $bar == 1 for first bar)
173    vars.insert(
174        "$bar".to_string(),
175        Value::Number((context.current_bar + eps).floor() + 1.0),
176    );
177    vars.insert(
178        "$currentTime".to_string(),
179        Value::Number(context.current_time),
180    );
181    vars.insert(
182        "$currentBeat".to_string(),
183        Value::Number(context.current_beat),
184    );
185    vars.insert(
186        "$currentBar".to_string(),
187        Value::Number((context.current_bar + eps).floor() + 1.0),
188    );
189
190    // Music
191    vars.insert("$bpm".to_string(), Value::Number(context.bpm));
192    vars.insert("$tempo".to_string(), Value::Number(context.bpm));
193    vars.insert("$duration".to_string(), Value::Number(context.duration));
194
195    // Position
196    vars.insert("$position".to_string(), Value::Number(context.position));
197    vars.insert("$progress".to_string(), Value::Number(context.position));
198
199    // System
200    vars.insert(
201        "$sampleRate".to_string(),
202        Value::Number(context.sample_rate as f32),
203    );
204    vars.insert(
205        "$channels".to_string(),
206        Value::Number(context.channels as f32),
207    );
208
209    vars
210}
211
212/// List all special variable categories with examples
213pub fn list_special_vars() -> HashMap<&'static str, Vec<(&'static str, &'static str)>> {
214    let mut categories = HashMap::new();
215
216    categories.insert(
217        "Time",
218        vec![
219            ("$time", "Current time in seconds"),
220            ("$beat", "Current beat position"),
221            ("$bar", "Current bar position"),
222            ("$currentTime", "Alias for $time"),
223            ("$currentBeat", "Alias for $beat"),
224            ("$currentBar", "Alias for $bar"),
225        ],
226    );
227
228    categories.insert(
229        "Music",
230        vec![
231            ("$bpm", "Current BPM"),
232            ("$tempo", "Alias for $bpm"),
233            ("$duration", "Beat duration in seconds"),
234        ],
235    );
236
237    categories.insert(
238        "Position",
239        vec![
240            ("$position", "Normalized position (0.0-1.0)"),
241            ("$progress", "Alias for $position"),
242        ],
243    );
244
245    categories.insert(
246        "Random",
247        vec![
248            ("$random", "Random float 0.0-1.0"),
249            ("$random.float", "Random float 0.0-1.0"),
250            ("$random.noise", "Random float -1.0 to 1.0"),
251            ("$random.int", "Random integer 0-99"),
252            ("$random.bool", "Random boolean"),
253            ("$random.range(min, max)", "Random float in range"),
254        ],
255    );
256
257    categories.insert(
258        "System",
259        vec![
260            ("$sampleRate", "Sample rate in Hz"),
261            ("$channels", "Number of audio channels"),
262        ],
263    );
264
265    categories
266}
267
268#[cfg(test)]
269#[path = "test_special_vars.rs"]
270mod tests;