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
use crate::language::syntax::ast::DurationValue;
use anyhow::{Result, anyhow};

pub fn parse_duration_token(token: &str) -> Result<DurationValue> {
    let token = token.trim();
    if token.eq_ignore_ascii_case("auto") {
        return Ok(DurationValue::Auto);
    }

    // Check for milliseconds suffix (e.g., "500ms")
    if let Some(value) = token.strip_suffix("ms") {
        let ms: f32 = value
            .parse()
            .map_err(|_| anyhow!("invalid milliseconds duration: '{}'", token))?;
        return Ok(DurationValue::Milliseconds(ms));
    }

    // Check for bar/beat/measure suffixes (e.g., "1 bar", "2 beat", "3 measure")
    if let Some(result) = parse_temporal_duration(token) {
        return Ok(result);
    }

    // Check for fraction (e.g., "1/4", "1/8")
    if let Some(fraction) = parse_fraction(token) {
        return Ok(DurationValue::Beats(fraction));
    }

    // Try to parse as plain number (milliseconds)
    if let Ok(number) = token.parse::<f32>() {
        return Ok(DurationValue::Milliseconds(number));
    }

    // Fall back to identifier (variable reference)
    Ok(DurationValue::Identifier(token.to_string()))
}

/// Parse temporal duration formats like "1 bar", "2 beat", "3 measure"
/// Also supports: "1bar", "2beats", "1beat", "3 measures", etc.
/// Returns millisecond-based duration proportional to BPM
fn parse_temporal_duration(token: &str) -> Option<DurationValue> {
    // Try parsing with spaces first (e.g., "1 bar", "2 beats")
    let parts_with_space: Vec<&str> = token.split_whitespace().collect();
    if parts_with_space.len() == 2 {
        if let Some(result) = try_parse_temporal(parts_with_space[0], parts_with_space[1]) {
            return Some(result);
        }
    }

    // Try parsing without space (e.g., "1bar", "2beats")
    // Find where the unit starts (first alphabetic character)
    let split_pos = token.chars().position(|c| c.is_alphabetic())?;
    if split_pos == 0 {
        return None; // No number part
    }

    let num_str = &token[..split_pos];
    let unit_str = &token[split_pos..];

    try_parse_temporal(num_str, unit_str)
}

/// Helper function to parse temporal duration once we have number and unit separated
fn try_parse_temporal(num_str: &str, unit_str: &str) -> Option<DurationValue> {
    let count: f32 = num_str.trim().parse().ok()?;
    let unit = unit_str.trim().to_lowercase();

    // Remove trailing 's' if present (e.g., "beats" -> "beat", "bars" -> "bar")
    let unit_singular = if unit.ends_with('s') && unit.len() > 1 {
        &unit[..unit.len() - 1]
    } else {
        &unit
    };

    // 1 bar = 4 beats (at 4/4 time)
    // 1 beat at 120 BPM = 500ms (60000ms / 120 BPM)
    // 1 measure = 4 beats (same as bar)
    // 1 step = 1/4 beat (subdivision of a beat, e.g., 16th note at 4/4 time)
    let multiplier = match unit_singular {
        "step" => 0.25,
        "beat" => 1.0,
        "bar" => 4.0,
        "measure" => 4.0,
        _ => return None,
    };

    // We return Identifier with a special format to be resolved at runtime
    // Format: "__temporal__<beats>_beat" (always in beats, normalized)
    let beat_count = count * multiplier;
    let identifier = format!("__temporal__{}_beat", beat_count);
    Some(DurationValue::Identifier(identifier))
}

fn parse_fraction(token: &str) -> Option<f32> {
    let mut split = token.split('/');
    let numerator: f32 = split.next()?.trim().parse().ok()?;
    let denominator: f32 = split.next()?.trim().parse().ok()?;
    if denominator.abs() < f32::EPSILON {
        return None;
    }
    Some(numerator / denominator)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_duration_auto() {
        assert!(matches!(
            parse_duration_token("auto"),
            Ok(DurationValue::Auto)
        ));
        assert!(matches!(
            parse_duration_token("AUTO"),
            Ok(DurationValue::Auto)
        ));
    }

    #[test]
    fn test_duration_milliseconds() {
        // Plain number
        match parse_duration_token("500") {
            Ok(DurationValue::Milliseconds(ms)) => assert_eq!(ms, 500.0),
            _ => panic!("Expected milliseconds"),
        }

        // With ms suffix
        match parse_duration_token("500ms") {
            Ok(DurationValue::Milliseconds(ms)) => assert_eq!(ms, 500.0),
            _ => panic!("Expected milliseconds"),
        }

        match parse_duration_token("1000ms") {
            Ok(DurationValue::Milliseconds(ms)) => assert_eq!(ms, 1000.0),
            _ => panic!("Expected milliseconds"),
        }
    }

    #[test]
    fn test_duration_fractions() {
        // Quarter note
        match parse_duration_token("1/4") {
            Ok(DurationValue::Beats(b)) => assert_eq!(b, 0.25),
            _ => panic!("Expected beats"),
        }

        // Half note
        match parse_duration_token("1/2") {
            Ok(DurationValue::Beats(b)) => assert_eq!(b, 0.5),
            _ => panic!("Expected beats"),
        }

        // Full note
        match parse_duration_token("1/1") {
            Ok(DurationValue::Beats(b)) => assert_eq!(b, 1.0),
            _ => panic!("Expected beats"),
        }
    }

    #[test]
    fn test_temporal_beat_with_space() {
        // "1 beat"
        match parse_duration_token("1 beat") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__1_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "2 beat"
        match parse_duration_token("2 beat") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__2_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "1 beats" (plural)
        match parse_duration_token("1 beats") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__1_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "3 beats" (plural)
        match parse_duration_token("3 beats") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__3_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_temporal_beat_without_space() {
        // "1beat"
        match parse_duration_token("1beat") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__1_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "2beat"
        match parse_duration_token("2beat") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__2_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "1beats" (without space, with 's')
        match parse_duration_token("1beats") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__1_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "3beats" (without space, with 's')
        match parse_duration_token("3beats") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__3_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_temporal_bar_with_space() {
        // "1 bar" -> 1 * 4 beats = 4
        match parse_duration_token("1 bar") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "2 bar"
        match parse_duration_token("2 bar") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__8_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "1 bars" (plural)
        match parse_duration_token("1 bars") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "3 bars" (plural)
        match parse_duration_token("3 bars") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__12_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_temporal_bar_without_space() {
        // "1bar" -> 4 beats
        match parse_duration_token("1bar") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "2bar"
        match parse_duration_token("2bar") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__8_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "1bars" (without space, with 's')
        match parse_duration_token("1bars") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "3bars" (without space, with 's')
        match parse_duration_token("3bars") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__12_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_temporal_measure_with_space() {
        // "1 measure" (same as bar: 4 beats)
        match parse_duration_token("1 measure") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "2 measure"
        match parse_duration_token("2 measure") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__8_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "1 measures" (plural)
        match parse_duration_token("1 measures") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "3 measures" (plural)
        match parse_duration_token("3 measures") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__12_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_temporal_measure_without_space() {
        // "1measure" -> 4 beats
        match parse_duration_token("1measure") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "2measure"
        match parse_duration_token("2measure") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__8_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "1measures" (without space, with 's')
        match parse_duration_token("1measures") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "3measures" (without space, with 's')
        match parse_duration_token("3measures") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__12_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_temporal_step_with_space() {
        // "1 step" -> 1 * 0.25 beats = 0.25
        match parse_duration_token("1 step") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__0.25_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "4 step"
        match parse_duration_token("4 step") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__1_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "1 steps" (plural)
        match parse_duration_token("1 steps") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__0.25_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "16 steps" (plural)
        match parse_duration_token("16 steps") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_temporal_step_without_space() {
        // "1step" -> 0.25 beats
        match parse_duration_token("1step") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__0.25_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "4step"
        match parse_duration_token("4step") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__1_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "1steps" (without space, with 's')
        match parse_duration_token("1steps") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__0.25_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // "16steps" (without space, with 's')
        match parse_duration_token("16steps") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_mixed_case() {
        // Case insensitive
        match parse_duration_token("1 BEAT") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__1_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        match parse_duration_token("2 Bar") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__8_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        match parse_duration_token("1MEASURE") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__4_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }

    #[test]
    fn test_float_values() {
        // Float beat values
        match parse_duration_token("0.5 beat") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__0.5_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // Float bar values
        match parse_duration_token("1.5bar") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__6_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }

        // Float measure values
        match parse_duration_token("2.5 measures") {
            Ok(DurationValue::Identifier(id)) => assert_eq!(id, "__temporal__10_beat"),
            other => panic!("Unexpected result: {:?}", other),
        }
    }
}