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
use crate::language::syntax::ast::Value;
/// Helper functions for parsing values, arguments, and complex structures
use anyhow::Result;
use std::collections::HashMap;

/// Parse function arguments from string
/// Supports: numbers, strings, identifiers, arrays, maps
pub fn parse_function_args(args_str: &str) -> Result<Vec<Value>> {
    let mut args = Vec::new();
    let mut current_arg = String::new();
    let mut depth = 0; // Track nested structures
    let mut in_string = false;

    for ch in args_str.chars() {
        match ch {
            '"' => {
                in_string = !in_string;
                current_arg.push(ch);
            }
            '[' | '{' if !in_string => {
                depth += 1;
                current_arg.push(ch);
            }
            ']' | '}' if !in_string => {
                depth -= 1;
                current_arg.push(ch);
            }
            ',' if depth == 0 && !in_string => {
                // End of argument
                if !current_arg.trim().is_empty() {
                    args.push(parse_single_arg(current_arg.trim())?);
                    current_arg.clear();
                }
            }
            _ => {
                current_arg.push(ch);
            }
        }
    }

    // Last argument
    if !current_arg.trim().is_empty() {
        args.push(parse_single_arg(current_arg.trim())?);
    }

    Ok(args)
}

/// Parse a single argument value
pub fn parse_single_arg(arg: &str) -> Result<Value> {
    let arg = arg.trim();

    // String literal
    if arg.starts_with('"') && arg.ends_with('"') {
        return Ok(Value::String(arg[1..arg.len() - 1].to_string()));
    }

    // Array
    if arg.starts_with('[') && arg.ends_with(']') {
        let inner = &arg[1..arg.len() - 1];
        let items = parse_function_args(inner)?;
        return Ok(Value::Array(items));
    }

    // Map/Object
    if arg.starts_with('{') && arg.ends_with('}') {
        let inner = &arg[1..arg.len() - 1];
        let mut map = HashMap::new();

        // Parse key: value pairs
        for pair in inner.split(',') {
            if let Some(colon_idx) = pair.find(':') {
                let key = pair[..colon_idx].trim().trim_matches('"');
                let value = parse_single_arg(pair[colon_idx + 1..].trim())?;
                map.insert(key.to_string(), value);
            }
        }

        return Ok(Value::Map(map));
    }

    // Number
    if let Ok(num) = arg.parse::<f32>() {
        return Ok(Value::Number(num));
    }

    // Function call expression: name(arg1, arg2)
    if let Some(open_paren) = arg.find('(') {
        if arg.ends_with(')') {
            let name = arg[..open_paren].trim().to_string();
            let args_str = &arg[open_paren + 1..arg.len() - 1];
            let parsed_args = if args_str.trim().is_empty() {
                Vec::new()
            } else {
                parse_function_args(args_str)?
            };
            return Ok(Value::Call {
                name,
                args: parsed_args,
            });
        }
    }

    // Boolean
    match arg.to_lowercase().as_str() {
        "true" => return Ok(Value::Boolean(true)),
        "false" => return Ok(Value::Boolean(false)),
        _ => {}
    }

    // Default to identifier
    Ok(Value::Identifier(arg.to_string()))
}

/// Parse synth definition: synth waveform { params } OR synth plugin.<name> { params }
/// Returns a Map with type="synth", waveform/plugin info, and parameters
///
/// Supported syntaxes:
/// - synth
/// - synth "sine" { attack: 0.1 }
/// - synth plugin.acid.synth { waveform: "sine" }
/// - synth { waveform: "sine", attack: 0.1 }  // waveform in params
pub fn parse_synth_definition(input: &str) -> Result<Value> {
    // Remove the `synth` prefix while also accepting bare `synth`.
    let input = input.trim();
    let input = if input == "synth" {
        ""
    } else {
        input.strip_prefix("synth ").map(str::trim).unwrap_or(input)
    };

    // Check if we have braces
    let (waveform_or_plugin, params_str) = if let Some(brace_idx) = input.find('{') {
        let before_brace = input[..brace_idx].trim();
        let params = &input[brace_idx..];
        (before_brace, params)
    } else {
        // No parameters, just waveform/plugin reference, or bare `synth`.
        return Ok(Value::Map({
            let mut map = HashMap::new();
            map.insert("type".to_string(), Value::String("synth".to_string()));

            if input.is_empty() {
                // Bare `synth` uses runtime defaults. v0.2 style config should be chained:
                // `synth -> waveform("saw") -> preset("bass")`.
            } else if input.starts_with("plugin.") {
                // Check if it's a plugin reference (plugin.author.name OR variable.export)
                let parts: Vec<&str> = input.split('.').collect();
                if parts.len() >= 3 {
                    map.insert(
                        "plugin_author".to_string(),
                        Value::String(parts[1].to_string()),
                    );
                    map.insert(
                        "plugin_name".to_string(),
                        Value::String(parts[2].to_string()),
                    );
                    if parts.len() >= 4 {
                        map.insert(
                            "plugin_export".to_string(),
                            Value::String(parts[3].to_string()),
                        );
                    }
                }
            } else if input.contains('.') {
                // Variable.property reference (e.g., acid.synth) - store for runtime resolution
                map.insert("_plugin_ref".to_string(), Value::String(input.to_string()));
            } else {
                // Simple waveform like "sine" or "square"
                // v0.2.0: synth <waveform> is deprecated shorthand
                // Add deprecation flag for runtime warning
                map.insert("_deprecated_shorthand".to_string(), Value::Boolean(true));
                map.insert("waveform".to_string(), Value::String(input.to_string()));
            }

            map
        }));
    };

    // Parse parameters from { key: value, ... }
    let params_str = params_str.trim_matches(|c| c == '{' || c == '}').trim();
    let mut params_map = HashMap::new();

    // Add type
    params_map.insert("type".to_string(), Value::String("synth".to_string()));

    // Handle waveform_or_plugin (what comes before the braces)
    if !waveform_or_plugin.is_empty() {
        // Check if it's a plugin reference (contains '.' → variable.property or plugin.author.name)
        if waveform_or_plugin.contains('.') {
            // Store plugin reference in internal field (will be resolved in interpreter)
            params_map.insert(
                "_plugin_ref".to_string(),
                Value::String(waveform_or_plugin.to_string()),
            );

            // Also check for explicit plugin.author.name format
            if waveform_or_plugin.starts_with("plugin.") {
                let parts: Vec<&str> = waveform_or_plugin.split('.').collect();
                if parts.len() >= 3 {
                    params_map.insert(
                        "plugin_author".to_string(),
                        Value::String(parts[1].to_string()),
                    );
                    params_map.insert(
                        "plugin_name".to_string(),
                        Value::String(parts[2].to_string()),
                    );
                    if parts.len() >= 4 {
                        params_map.insert(
                            "plugin_export".to_string(),
                            Value::String(parts[3].to_string()),
                        );
                    }
                }
            }
        } else {
            // It's a waveform string
            params_map.insert(
                "waveform".to_string(),
                Value::String(waveform_or_plugin.to_string()),
            );
        }
    }

    // Parse key: value pairs (support newlines by replacing them with commas)
    if !params_str.is_empty() {
        // First, remove inline comments (everything after //)
        let mut cleaned_lines = Vec::new();
        for line in params_str.lines() {
            if let Some(comment_pos) = line.find("//") {
                let clean_line = &line[..comment_pos];
                if !clean_line.trim().is_empty() {
                    cleaned_lines.push(clean_line);
                }
            } else if !line.trim().is_empty() {
                cleaned_lines.push(line);
            }
        }

        // Now join lines and split by comma and newline
        let cleaned = cleaned_lines.join("\n");
        let normalized = cleaned.replace('\n', ",").replace('\r', "");

        for pair in normalized.split(',') {
            let pair = pair.trim();
            if pair.is_empty() {
                continue;
            }

            let parts: Vec<&str> = pair.split(':').collect();
            if parts.len() >= 2 {
                let key = parts[0].trim().to_string();
                // Join back in case value contains ':'
                let value_part = parts[1..].join(":");
                let value_str = value_part.trim().trim_matches(',').trim_matches('"');

                // Parse arrays (for filters)
                if value_str.starts_with('[') {
                    if let Ok(array_val) = parse_array_value(value_str) {
                        params_map.insert(key, array_val);
                        continue;
                    }
                }

                // Try to parse as number
                if let Ok(num) = value_str.parse::<f32>() {
                    params_map.insert(key, Value::Number(num));
                } else {
                    // Store as string (override waveform if specified in params)
                    params_map.insert(key, Value::String(value_str.to_string()));
                }
            }
        }
    }

    Ok(Value::Map(params_map))
}

/// Parse array value like [{ key: val }, ...]
pub fn parse_array_value(input: &str) -> Result<Value> {
    let input = input.trim().trim_matches(|c| c == '[' || c == ']').trim();
    if input.is_empty() {
        return Ok(Value::Array(Vec::new()));
    }

    // Check for range pattern: "start..end"
    if input.contains("..") {
        let parts: Vec<&str> = input.split("..").collect();
        if parts.len() == 2 {
            let start_str = parts[0].trim();
            let end_str = parts[1].trim();

            // Try to parse as numbers
            if let (Ok(start), Ok(end)) = (start_str.parse::<f32>(), end_str.parse::<f32>()) {
                return Ok(Value::Range {
                    start: Box::new(Value::Number(start)),
                    end: Box::new(Value::Number(end)),
                });
            }
        }
    }

    let mut items = Vec::new();
    let mut depth = 0;
    let mut current = String::new();

    for ch in input.chars() {
        match ch {
            '{' => {
                depth += 1;
                current.push(ch);
            }
            '}' => {
                depth -= 1;
                current.push(ch);

                if depth == 0 && !current.trim().is_empty() {
                    // Parse this object
                    if let Ok(obj) = parse_map_value(&current) {
                        items.push(obj);
                    }
                    current.clear();
                }
            }
            ',' if depth == 0 => {
                // End of a top-level array element (not inside an object).
                let token = current.trim();
                if !token.is_empty() {
                    // Parse simple token (number, identifier, string, nested array/map)
                    if let Ok(val) = parse_single_arg(token) {
                        // If the parsed value is a Map, keep it. Otherwise, wrap into a Map
                        // with `index` and `value` keys so arrays of simple tokens become
                        // objects supporting property access (index, value).
                        if let Value::Map(_) = val {
                            items.push(val);
                        } else {
                            let mut map = HashMap::new();
                            let idx = items.len();
                            map.insert("index".to_string(), Value::Number(idx as f32));
                            map.insert("value".to_string(), val);
                            items.push(Value::Map(map));
                        }
                    }
                }
                current.clear();
                continue;
            }
            _ => {
                current.push(ch);
            }
        }
    }

    // If there is a trailing token after the loop, parse and push it
    if !current.trim().is_empty() {
        let token = current.trim();
        // If it's an object it should have been handled above; otherwise parse as single arg
        if !token.is_empty() {
            if let Ok(val) = parse_single_arg(token) {
                items.push(val);
            }
        }
    }

    Ok(Value::Array(items))
}

/// Parse map value like { key: val, key2: val2 }
pub fn parse_map_value(input: &str) -> Result<Value> {
    let input = input.trim().trim_matches(|c| c == '{' || c == '}').trim();
    let mut map = HashMap::new();

    for pair in input.split(',') {
        let pair = pair.trim();
        if pair.is_empty() {
            continue;
        }

        let parts: Vec<&str> = pair.split(':').collect();
        if parts.len() >= 2 {
            let key = parts[0].trim().to_string();
            // Join back in case value contains ':' (shouldn't happen but just in case)
            let value_part = parts[1..].join(":");

            // Remove inline comments (everything after //)
            let value_clean = if let Some(comment_pos) = value_part.find("//") {
                &value_part[..comment_pos]
            } else {
                &value_part
            };

            let value_str = value_clean.trim().trim_matches('"').trim_matches('\'');

            // Try to parse as number
            if let Ok(num) = value_str.parse::<f32>() {
                map.insert(key, Value::Number(num));
            } else {
                map.insert(key, Value::String(value_str.to_string()));
            }
        }
    }

    Ok(Value::Map(map))
}

/// Find a word boundary in a string (for keyword operators like "and", "or")
/// Returns the index where the word starts, or None if not found
fn find_word_boundary(text: &str, keyword: &str) -> Option<usize> {
    // Find rightmost occurrence (lowest precedence)
    text.rfind(keyword).and_then(|idx| {
        // Check that it's a word boundary (not part of an identifier)
        let before_ok =
            idx == 0 || !text[..idx].ends_with(|c: char| c.is_alphanumeric() || c == '_');
        let after_idx = idx + keyword.len();
        let after_ok = after_idx >= text.len()
            || !text[after_idx..].starts_with(|c: char| c.is_alphanumeric() || c == '_');

        if before_ok && after_ok {
            Some(idx)
        } else {
            None
        }
    })
}

/// Parse a condition string into a Value (for if statements)
/// Supports: var > value, var < value, var == value, var != value, var >= value, var <= value
/// Also supports logical operators: &&/and, ||/or, !/not
pub fn parse_condition(condition_str: &str) -> Result<Value> {
    let condition_str = condition_str.trim();

    // Handle OR operator (lowest precedence) - support both "||" and "or"
    if let Some(idx) = condition_str.rfind("||") {
        let left = parse_condition(&condition_str[..idx].trim())?;
        let right = parse_condition(&condition_str[idx + 2..].trim())?;

        let mut map = HashMap::new();
        map.insert("operator".to_string(), Value::String("||".to_string()));
        map.insert("left".to_string(), left);
        map.insert("right".to_string(), right);
        return Ok(Value::Map(map));
    }

    // Handle "or" keyword operator (support word-based OR)
    if let Some(idx) = find_word_boundary(condition_str, " or ") {
        let left = parse_condition(&condition_str[..idx].trim())?;
        let right = parse_condition(&condition_str[idx + 4..].trim())?;

        let mut map = HashMap::new();
        map.insert("operator".to_string(), Value::String("||".to_string()));
        map.insert("left".to_string(), left);
        map.insert("right".to_string(), right);
        return Ok(Value::Map(map));
    }

    // Handle AND operator (higher precedence than OR) - support both "&&" and "and"
    if let Some(idx) = condition_str.rfind("&&") {
        let left = parse_condition(&condition_str[..idx].trim())?;
        let right = parse_condition(&condition_str[idx + 2..].trim())?;

        let mut map = HashMap::new();
        map.insert("operator".to_string(), Value::String("&&".to_string()));
        map.insert("left".to_string(), left);
        map.insert("right".to_string(), right);
        return Ok(Value::Map(map));
    }

    // Handle "and" keyword operator (support word-based AND)
    if let Some(idx) = find_word_boundary(condition_str, " and ") {
        let left = parse_condition(&condition_str[..idx].trim())?;
        let right = parse_condition(&condition_str[idx + 5..].trim())?;

        let mut map = HashMap::new();
        map.insert("operator".to_string(), Value::String("&&".to_string()));
        map.insert("left".to_string(), left);
        map.insert("right".to_string(), right);
        return Ok(Value::Map(map));
    }

    // Handle NOT operator (highest precedence) - support "!"
    if condition_str.starts_with('!') {
        let inner = parse_condition(&condition_str[1..].trim())?;

        let mut map = HashMap::new();
        map.insert("operator".to_string(), Value::String("!".to_string()));
        map.insert("operand".to_string(), inner);
        return Ok(Value::Map(map));
    }

    // Handle "not" keyword operator (support word-based NOT)
    if condition_str.starts_with("not ") {
        let inner = parse_condition(&condition_str[4..].trim())?;

        let mut map = HashMap::new();
        map.insert("operator".to_string(), Value::String("!".to_string()));
        map.insert("operand".to_string(), inner);
        return Ok(Value::Map(map));
    }

    // Handle comparison operators
    let operators = vec![">=", "<=", "==", "!=", ">", "<"];
    for op in operators {
        if let Some(idx) = condition_str.find(op) {
            let left = condition_str[..idx].trim();
            let right = condition_str[idx + op.len()..].trim();

            // Create a map representing the condition
            let mut map = HashMap::new();
            map.insert("operator".to_string(), Value::String(op.to_string()));
            map.insert(
                "left".to_string(),
                if let Ok(num) = left.parse::<f32>() {
                    Value::Number(num)
                } else {
                    Value::Identifier(left.to_string())
                },
            );
            map.insert(
                "right".to_string(),
                if let Ok(num) = right.parse::<f32>() {
                    Value::Number(num)
                } else {
                    Value::Identifier(right.to_string())
                },
            );

            return Ok(Value::Map(map));
        }
    }

    // No operator found, treat as boolean identifier
    Ok(Value::Identifier(condition_str.to_string()))
}