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
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
pub mod directive;
pub mod duration;
pub mod effects;
pub mod helpers;
pub mod preprocessing;
pub mod routing;
pub mod statements;
pub mod trigger;
// Re-export statement-level parsers so they are available at driver root
use crate::language::syntax::ast::nodes::{Statement, StatementKind, Value};
use anyhow::{Result, anyhow};
pub use statements::*;
use std::path::{Path, PathBuf};

/// Find the closest keyword suggestion using Levenshtein distance
/// Returns the suggestion if distance is <= 2 (typo-like)
fn find_keyword_suggestion(input: &str, keywords: &[&str]) -> Option<String> {
    // Calculate Levenshtein distance between two strings
    fn levenshtein(s1: &str, s2: &str) -> usize {
        let len1 = s1.len();
        let len2 = s2.len();
        let mut matrix = vec![vec![0; len2 + 1]; len1 + 1];

        for i in 0..=len1 {
            matrix[i][0] = i;
        }
        for j in 0..=len2 {
            matrix[0][j] = j;
        }

        for (i, c1) in s1.chars().enumerate() {
            for (j, c2) in s2.chars().enumerate() {
                let cost = if c1 == c2 { 0 } else { 1 };
                matrix[i + 1][j + 1] = std::cmp::min(
                    std::cmp::min(
                        matrix[i][j + 1] + 1, // deletion
                        matrix[i + 1][j] + 1, // insertion
                    ),
                    matrix[i][j] + cost, // substitution
                );
            }
        }
        matrix[len1][len2]
    }

    let mut best = (usize::MAX, "");
    for &keyword in keywords {
        let distance = levenshtein(input, keyword);
        if distance < best.0 && distance <= 2 {
            best = (distance, keyword);
        }
    }

    if best.0 <= 2 {
        Some(best.1.to_string())
    } else {
        None
    }
}

/// Entry point: parse source into a list of Statements
pub fn parse(source: &str, path: PathBuf) -> Result<Vec<Statement>> {
    // Pre-process: merge ALL multiline statements with braces
    let braces_pre = preprocessing::preprocess_multiline_braces(source);

    // Then merge multiline brackets (for timeline, etc.)
    let brackets_pre = preprocessing::preprocess_multiline_brackets(&braces_pre);

    // Then merge multiline arrow calls (without braces)
    let preprocessed = preprocessing::preprocess_multiline_arrow_calls(&brackets_pre);

    let lines: Vec<_> = preprocessed.lines().collect();
    parse_lines(&lines, 0, lines.len(), 0, &path)
}

/// Parse a range of lines into statements, handling indentation for blocks.
fn parse_lines(
    lines: &Vec<&str>,
    start: usize,
    end: usize,
    indent: usize,
    path: &Path,
) -> Result<Vec<Statement>> {
    use crate::language::syntax::ast::nodes::StatementKind;

    let mut i = start;
    let mut statements: Vec<Statement> = Vec::new();

    while i < end {
        let raw = lines[i];
        let trimmed = raw.trim();

        if trimmed.is_empty() || is_comment_line(trimmed) {
            i += 1;
            continue;
        }

        let current_indent = raw.len() - raw.trim_start().len();
        if current_indent < indent {
            break;
        }

        // parse header line
        let mut statement = parse_line(trimmed, i + 1, path)?;
        statement.indent = current_indent;
        statement.line = i + 1;

        // determine body range for block statements
        let body_start = i + 1;
        let mut body_end = body_start;
        while body_end < end {
            let l = lines[body_end];
            if l.trim().is_empty() || is_comment_line(l.trim()) {
                body_end += 1;
                continue;
            }
            let indent_l = l.len() - l.trim_start().len();
            if indent_l <= current_indent {
                break;
            }
            body_end += 1;
        }

        // If we found a body, parse it and attach appropriately based on kind
        if body_end > body_start {
            let body = parse_lines(lines, body_start, body_end, current_indent + 1, path)?;

            // To avoid borrowing `statement.kind` and then assigning to it
            // (which the borrow checker forbids), take ownership of the kind
            // temporarily and then replace it with the updated version.
            let orig_kind = std::mem::replace(&mut statement.kind, StatementKind::Unknown);
            match orig_kind {
                StatementKind::If { condition, .. } => {
                    // Keep If simple here; attach else/else-if later in post-processing
                    statement.kind = StatementKind::If {
                        condition,
                        body: body.clone(),
                        else_body: None,
                    };
                }
                StatementKind::While { condition, .. } => {
                    // Attach body to While
                    statement.kind = StatementKind::While {
                        condition,
                        body: body.clone(),
                    };
                }
                StatementKind::For {
                    variable, iterable, ..
                } => {
                    statement.kind = StatementKind::For {
                        variable,
                        iterable,
                        body: body.clone(),
                    };
                }
                StatementKind::Loop { count, .. } => {
                    statement.kind = StatementKind::Loop {
                        count,
                        body: body.clone(),
                    };
                }
                StatementKind::On { event, args, .. } => {
                    statement.kind = StatementKind::On {
                        event,
                        args,
                        body: body.clone(),
                    };
                }
                StatementKind::Automate { target } => {
                    statement.kind = StatementKind::Automate { target };
                    // store raw body as value map if needed elsewhere
                    let raw_lines: Vec<String> = lines[body_start..body_end]
                        .iter()
                        .map(|s| s.to_string())
                        .collect();
                    let raw_body = raw_lines.join("\n");
                    let mut map = std::collections::HashMap::new();
                    map.insert("body".to_string(), Value::String(raw_body));
                    statement.value = Value::Map(map);
                }
                StatementKind::Function {
                    name, parameters, ..
                } => {
                    statement.kind = StatementKind::Function {
                        name: name.clone(),
                        parameters,
                        body: body.clone(),
                    };
                    statement.value = Value::Identifier(name.clone());
                }
                StatementKind::Group { duration, .. } => {
                    // attach body for groups, keep name in value if present
                    let group_name = match &statement.value {
                        Value::Identifier(s) => s.clone(),
                        _ => "".to_string(),
                    };
                    statement.kind = StatementKind::Group {
                        name: group_name,
                        body: body.clone(),
                        duration,
                    };
                }
                StatementKind::Routing { .. } => {
                    // Parse routing body statements
                    statement.kind = StatementKind::Routing { body: body.clone() };
                }
                StatementKind::Section { name, duration, .. } => {
                    statement.kind = StatementKind::Section {
                        name,
                        duration,
                        body: body.clone(),
                    };
                }
                StatementKind::Schedule { .. } => {
                    // Parse schedule events: each "at <time>:" line with following body
                    let mut events = Vec::new();
                    let mut i_local = body_start;
                    while i_local < body_end {
                        let line = lines[i_local].trim();

                        // Skip empty lines and comments
                        if line.is_empty() || is_comment_line(line) {
                            i_local += 1;
                            continue;
                        }

                        // Check if this is an "at" event header
                        if line.starts_with("at ") {
                            if let Ok((time, optional_duration)) =
                                statements::extended::parse_schedule_event_header(lines[i_local])
                            {
                                // Find the body for this event
                                let event_body_start = i_local + 1;
                                let mut event_body_end = event_body_start;

                                while event_body_end < body_end {
                                    let l = lines[event_body_end];
                                    if l.trim().is_empty() || is_comment_line(l.trim()) {
                                        event_body_end += 1;
                                        continue;
                                    }

                                    let indent_l = l.len() - l.trim_start().len();
                                    let event_indent =
                                        lines[i_local].len() - lines[i_local].trim_start().len();

                                    // Check if it's another "at" line at same level
                                    if l.trim().starts_with("at ") && indent_l == event_indent {
                                        break;
                                    }

                                    if indent_l <= event_indent {
                                        break;
                                    }

                                    event_body_end += 1;
                                }

                                // Parse the event body
                                if event_body_end > event_body_start {
                                    if let Ok(event_stmts) = parse_lines(
                                        lines,
                                        event_body_start,
                                        event_body_end,
                                        current_indent + 1,
                                        path,
                                    ) {
                                        events.push((time, optional_duration, event_stmts));
                                    }
                                }

                                i_local = event_body_end;
                            } else {
                                i_local += 1;
                            }
                        } else {
                            i_local += 1;
                        }
                    }

                    statement.kind = StatementKind::Schedule { events };
                }
                StatementKind::Tempo {
                    value,
                    body: Some(_),
                } => {
                    // Attach body to tempo block
                    statement.kind = StatementKind::Tempo {
                        value,
                        body: Some(body.clone()),
                    };
                }

                other => {
                    // keep original kind for other statements
                    statement.kind = other;
                }
            }

            // If this statement was a plain 'else' marker (Comment with value "else"),
            // the parsed body was not attached to the marker (we intentionally
            // keep the marker lightweight). We must append the parsed body
            // statements into the parent statements vector so the post-process
            // pass can collect them and attach to the previous If.
            i = body_end;
            statements.push(statement);

            if let Some(last_statement) = statements.last() {
                if let StatementKind::Comment = &last_statement.kind {
                    if let Value::String(s) = &last_statement.value {
                        if s == "else" {
                            // append the body statements after the marker
                            for stmt in body.into_iter() {
                                statements.push(stmt);
                            }
                        }
                    }
                }
            }
            continue;
        }

        // No body found
        statements.push(statement);
        i += 1;
    }

    // Post-process to attach else/else-if blocks
    fn attach_else_blocks(statements: &mut Vec<Statement>) {
        use crate::language::syntax::ast::StatementKind;

        // Helper: attach a new else-body (Vec<Statement>) to an existing If Statement.
        // If the If already has a nested else-if chain (encoded as a single If in
        // its else_body vector), descend into that chain and attach to the deepest
        // nested If instead of overwriting the entire else_body.
        fn attach_else_to_if_statement(target: Statement, new_else: Vec<Statement>) -> Statement {
            use crate::language::syntax::ast::StatementKind;

            match target.kind {
                StatementKind::If {
                    condition,
                    body,
                    else_body,
                } => {
                    match else_body {
                        None => Statement::new(
                            StatementKind::If {
                                condition,
                                body,
                                else_body: Some(new_else),
                            },
                            target.value,
                            target.indent,
                            target.line,
                            target.column,
                        ),
                        Some(mut eb) => {
                            if eb.len() == 1 {
                                let inner = eb.remove(0);
                                // If inner is an If, recurse into it
                                if let StatementKind::If { .. } = inner.kind {
                                    let updated_inner =
                                        attach_else_to_if_statement(inner, new_else);
                                    Statement::new(
                                        StatementKind::If {
                                            condition,
                                            body,
                                            else_body: Some(vec![updated_inner]),
                                        },
                                        target.value,
                                        target.indent,
                                        target.line,
                                        target.column,
                                    )
                                } else {
                                    // Not an If inside else_body; overwrite
                                    Statement::new(
                                        StatementKind::If {
                                            condition,
                                            body,
                                            else_body: Some(new_else),
                                        },
                                        target.value,
                                        target.indent,
                                        target.line,
                                        target.column,
                                    )
                                }
                            } else {
                                // Multiple statements in existing else_body; overwrite for now
                                Statement::new(
                                    StatementKind::If {
                                        condition,
                                        body,
                                        else_body: Some(new_else),
                                    },
                                    target.value,
                                    target.indent,
                                    target.line,
                                    target.column,
                                )
                            }
                        }
                    }
                }
                _ => target,
            }
        }

        let mut idx = 0;
        while idx < statements.len() {
            // Handle plain 'else' marker: Comment with value "else"
            if let StatementKind::Comment = &statements[idx].kind {
                if let Value::String(s) = &statements[idx].value {
                    if s == "else" {
                        let else_indent = statements[idx].indent;

                        // Collect following statements that are part of the else body
                        let mut body: Vec<Statement> = Vec::new();
                        let j = idx + 1;
                        while j < statements.len() && statements[j].indent > else_indent {
                            body.push(statements.remove(j));
                        }

                        // Remove the 'else' marker itself
                        statements.remove(idx);

                        // Find previous If to attach to (search backwards) and attach
                        // the parsed else body to the deepest nested If in the chain.
                        let mut k = idx as isize - 1;
                        while k >= 0 {
                            if let StatementKind::If { .. } = &statements[k as usize].kind {
                                // Take ownership of the previous If statement, attach into it,
                                // then put back the updated statement.
                                let prev = std::mem::replace(
                                    &mut statements[k as usize],
                                    Statement::new(StatementKind::Unknown, Value::Null, 0, 0, 1),
                                );
                                let updated = attach_else_to_if_statement(prev, body);
                                statements[k as usize] = updated;
                                break;
                            }
                            k -= 1;
                        }

                        continue;
                    }
                }
            }

            // Handle 'else if' which was parsed as an If with value == "else-if"
            if let StatementKind::If { .. } = &statements[idx].kind {
                if let Value::String(s) = &statements[idx].value {
                    if s == "else-if" {
                        // Remove this else-if statement and attach it as the
                        // else_body (single-statement vector) of the previous If.
                        let else_if_stmt = statements.remove(idx);

                        // find previous If and attach this else-if into its nested chain
                        let mut k = idx as isize - 1;
                        while k >= 0 {
                            if let StatementKind::If { .. } = &statements[k as usize].kind {
                                let prev = std::mem::replace(
                                    &mut statements[k as usize],
                                    Statement::new(StatementKind::Unknown, Value::Null, 0, 0, 1),
                                );
                                let updated = attach_else_to_if_statement(prev, vec![else_if_stmt]);
                                statements[k as usize] = updated;
                                break;
                            }
                            k -= 1;
                        }

                        continue;
                    }
                }
            }

            idx += 1;
        }
    }

    attach_else_blocks(&mut statements);

    Ok(statements)
}

fn parse_line(line: &str, line_number: usize, path: &Path) -> Result<Statement> {
    use crate::language::syntax::parser::driver::statements::*;

    if line.starts_with('.') {
        return trigger::parse_trigger_line(line, line_number);
    }

    let mut parts = line.split_whitespace();
    // Extract first token as keyword and strip a trailing ':' if present
    let first_token = parts
        .next()
        .ok_or_else(|| anyhow!("empty line"))?
        .to_string();
    let keyword = first_token.trim_end_matches(':').to_lowercase();

    // Check for routing statements (node, fx, route, duck, sidechain)
    let routing_keywords = ["node", "fx", "route", "duck", "sidechain"];
    if routing_keywords.contains(&keyword.as_str()) {
        return crate::language::syntax::parser::driver::routing::parse_routing_statement(
            line,
            line_number,
        );
    }

    if let Some(statement) = statements::structure::parse_pattern_shorthand(line, line_number)? {
        return Ok(statement);
    }

    // Check if this is a property assignment first: target.property = value
    if line.contains('=') && keyword.contains('.') {
        return parse_assign(line, line_number);
    }

    // Check if this looks like a trigger (contains a dot like "drums.kick")
    if keyword.contains('.') && !keyword.contains('(') {
        // Reconstruct the line and parse as trigger
        return trigger::parse_trigger_line(line, line_number);
    }

    // Check if this is a bind statement first (before arrow call)
    if keyword == "bind" && line.contains("->") {
        return parse_bind(line, line_number);
    }

    // If this line contains an arrow call, parse it as an ArrowCall, UNLESS the
    // statement starts with a reserved keyword that must be handled (let/var/const/etc.).
    // This ensures constructs like `let name = .bank.kick -> reverse(...)` are
    // parsed by `parse_let` rather than being mis-parsed as an ArrowCall.
    let reserved_keywords = [
        "bpm", "tempo", "print", "sleep", "rest", "wait", "pattern", "bank", "let", "const", "for",
        "foreach", "loop", "if", "while", "else", "group", "automate", "call", "spawn", "sequence",
        "layer", "on", "emit", "routing", "return", "break", "import", "export", "use", "load",
        "fade", "section", "timeline", "schedule", "stop", "silence", "mute",
    ];
    if line.contains("->") && !reserved_keywords.contains(&keyword.as_str()) {
        return statements::parse_arrow_call(line, line_number);
    }

    return match keyword.as_str() {
        "bpm" | "tempo" => statements::core::parse_tempo(line, line_number),
        "print" => statements::core::parse_print(line, line_number),
        "sleep" | "rest" | "wait" => statements::core::parse_sleep(parts, line_number),
        "trigger" => Err(anyhow!(
            "keyword 'trigger' is deprecated; use dot notation like '.alias' instead"
        )),
        "pattern" => parse_pattern(parts, line_number),
        "bank" => parse_bank(parts, line_number),
        "let" => parse_let(line, parts, line_number),
        "const" => parse_const(line, parts, line_number),
        "for" | "foreach" => parse_for(parts, line_number),
        "loop" => parse_loop(parts, line_number),
        "if" => statements::structure::parse_if(parts, line_number),
        "while" => statements::structure::parse_while(parts, line_number),
        "else" => statements::structure::parse_else(line, line_number),
        "group" => statements::structure::parse_group(parts, line_number),
        "automate" => {
            crate::language::syntax::parser::driver::statements::structure::parse_automate(
                parts,
                line_number,
            )
        }
        "call" | "sequence" => parse_call(line, parts, line_number),
        "break" => statements::structure::parse_break(parts, line_number),
        "function" => statements::structure::parse_function(line, line_number),
        "spawn" | "layer" => parse_spawn(parts, line_number),
        "on" => parse_on(parts, line_number),
        "emit" => parse_emit(line, parts, line_number),
        "fade" => statements::extended::parse_fade(line, line_number),
        "section" => statements::extended::parse_section(parts, line_number),
        "timeline" => statements::extended::parse_timeline(line, line_number),
        "schedule" => statements::extended::parse_schedule(line, line_number),
        "stop" | "silence" | "mute" => statements::extended::parse_stop(line, line_number),
        "return" => statements::core::parse_return(line, line_number),
        "routing" => {
            crate::language::syntax::parser::driver::routing::parse_routing_command(line_number)
        }
        "import" => directive::parse_directive_keyword(line, "import", line_number, path),
        "export" => directive::parse_directive_keyword(line, "export", line_number, path),
        "use" => directive::parse_directive_keyword(line, "use", line_number, path),
        "load" => directive::parse_directive_keyword(line, "load", line_number, path),
        _ => {
            // Provide helpful suggestions for common typos FIRST
            let suggestion = find_keyword_suggestion(&keyword, &reserved_keywords);

            // If we found a suggestion, it's likely a typo, not a trigger call
            if let Some(suggestion_str) = suggestion {
                // Store message in a structured format: "MESSAGE|||FILE:LINE|||SUGGESTION"
                // This allows the collector to parse it and build a StructuredError
                let error_msg = format!(
                    "Unknown statement '{}' at {}:{}|||{}|||{}",
                    keyword,
                    path.display(),
                    line_number,
                    path.display(),
                    suggestion_str
                );

                // Push structured error to WASM registry if available
                #[cfg(feature = "wasm")]
                {
                    use crate::web::registry::debug;
                    if debug::is_debug_errors_enabled() {
                        debug::push_parse_error_from_parts(
                            format!(
                                "Unknown statement '{}'. Did you mean '{}' ?",
                                keyword, suggestion_str
                            ),
                            line_number,
                            1,
                            "UnknownStatement".to_string(),
                        );
                    }
                }

                return Ok(Statement::new(
                    StatementKind::Unknown,
                    Value::String(error_msg),
                    0,
                    line_number,
                    1,
                ));
            }

            // Check if this looks like a potential trigger identifier (single word, no special chars except dots)
            // This handles cases like variable references: let kick = drums.kick; kick
            if keyword
                .chars()
                .all(|c| c.is_alphanumeric() || c == '_' || c == '.')
            {
                // Parse as trigger
                return trigger::parse_trigger_line(line, line_number);
            }

            // Generic error for truly unknown statements
            // Format: "MESSAGE|||FILE:LINE|||NO_SUGGESTION"
            let error_msg = format!(
                "Unknown statement '{}' at {}:{}|||{}|||",
                keyword,
                path.display(),
                line_number,
                path.display()
            );

            // Push structured error to WASM registry if available
            #[cfg(feature = "wasm")]
            {
                use crate::web::registry::debug;
                if debug::is_debug_errors_enabled() {
                    debug::push_parse_error_from_parts(
                        format!("Unknown statement '{}'", keyword),
                        line_number,
                        1,
                        "UnknownStatement".to_string(),
                    );
                }
            }

            return Ok(Statement::new(
                StatementKind::Unknown,
                Value::String(error_msg),
                0,
                line_number,
                1,
            ));
        }
    };
}

fn is_comment_line(line: &str) -> bool {
    line.starts_with('#') || line.starts_with("//")
}

pub use duration::parse_duration_token;
/// Re-export helper parsing functions from helpers.rs so other modules can call them
pub use helpers::{
    parse_array_value, parse_condition, parse_function_args, parse_map_value, parse_single_arg,
    parse_synth_definition,
};

/// SimpleParser is a small wrapper used by other modules/tests in the crate.
/// It forwards to the top-level parse implementation above.
pub struct SimpleParser;

impl SimpleParser {
    pub fn parse(source: &str, path: PathBuf) -> Result<Vec<Statement>> {
        crate::language::syntax::parser::driver::parse(source, path)
    }

    pub fn parse_file<P: AsRef<Path>>(path: P) -> Result<Vec<Statement>> {
        let buf = std::path::PathBuf::from(path.as_ref());
        let s = std::fs::read_to_string(&buf)?;
        let s = s.strip_prefix('\u{feff}').unwrap_or(&s);
        Self::parse(&s, buf)
    }
}

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

    #[test]
    fn test_unknown_statement_with_suggestion_is_structured() {
        let statements = parse("pritn hello", PathBuf::from("test.deva")).unwrap();

        assert_eq!(statements.len(), 1);
        assert!(matches!(statements[0].kind, StatementKind::Unknown));
        match &statements[0].value {
            Value::String(message) => {
                assert!(message.contains("Unknown statement 'pritn'"));
                assert!(message.ends_with("|||print"));
            }
            other => panic!("expected structured unknown message, got {:?}", other),
        }
    }

    #[test]
    fn test_else_body_is_attached_to_previous_if() {
        let source = "if true:\n  print yes\nelse:\n  print no";
        let statements = parse(source, PathBuf::from("test.deva")).unwrap();

        assert_eq!(statements.len(), 1);
        match &statements[0].kind {
            StatementKind::If {
                body, else_body, ..
            } => {
                assert_eq!(body.len(), 1);
                let else_body = else_body.as_ref().expect("else body should be attached");
                assert_eq!(else_body.len(), 1);
                assert!(matches!(else_body[0].kind, StatementKind::Print));
            }
            other => panic!("expected if statement, got {:?}", other),
        }
    }

    #[test]
    fn test_bare_synth_chained_waveform_and_preset() {
        let source = r#"let bass = synth -> waveform("saw") -> preset("bass")"#;
        let statements = parse(source, PathBuf::from("test.deva")).unwrap();

        assert_eq!(statements.len(), 1);
        match &statements[0].kind {
            StatementKind::Let {
                value: Some(Value::Map(map)),
                ..
            } => {
                assert!(matches!(
                    map.get("type"),
                    Some(Value::String(kind)) if kind == "synth"
                ));
                assert!(matches!(
                    map.get("waveform"),
                    Some(Value::String(waveform)) if waveform == "saw"
                ));
                assert!(matches!(
                    map.get("synth_type"),
                    Some(Value::String(preset)) if preset == "bass"
                ));
            }
            other => panic!("expected synth let statement, got {:?}", other),
        }
    }

    #[test]
    fn test_livecoding_synth_aliases_parse_to_canonical_map() {
        let source = r#"let bass = synth -> wave("saw") -> preset("bass") -> voices(2) -> env({ attack: 0.01, release: 0.08 })"#;
        let statements = parse(source, PathBuf::from("test.deva")).unwrap();

        assert_eq!(statements.len(), 1);
        match &statements[0].kind {
            StatementKind::Let {
                value: Some(Value::Map(map)),
                ..
            } => {
                assert!(matches!(
                    map.get("waveform"),
                    Some(Value::String(waveform)) if waveform == "saw"
                ));
                assert!(matches!(
                    map.get("synth_type"),
                    Some(Value::String(preset)) if preset == "bass"
                ));
                assert!(
                    matches!(map.get("attack"), Some(Value::Number(n)) if (*n - 0.01).abs() < f32::EPSILON)
                );
                assert!(
                    matches!(map.get("release"), Some(Value::Number(n)) if (*n - 0.08).abs() < f32::EPSILON)
                );
                assert!(
                    matches!(map.get("voices"), Some(Value::Number(n)) if (*n - 2.0).abs() < f32::EPSILON)
                );
            }
            other => panic!("expected synth let statement, got {:?}", other),
        }
    }

    #[test]
    fn test_pattern_shorthand_without_options() {
        let source = r#"kick: drums.kick = "x--- x---""#;
        let statements = parse(source, PathBuf::from("test.deva")).unwrap();

        assert_eq!(statements.len(), 1);
        match &statements[0].kind {
            StatementKind::Pattern { name, target } => {
                assert_eq!(name, "kick");
                assert_eq!(target.as_deref(), Some("drums.kick"));
                assert!(
                    matches!(&statements[0].value, Value::String(pattern) if pattern == "x--- x---")
                );
            }
            other => panic!("expected pattern shorthand, got {:?}", other),
        }
    }

    #[test]
    fn test_pattern_shorthand_with_arrow_options() {
        let source = r#"hat: drums.hat -> swing(0.08) -> velocity(0.7) = "x-x-""#;
        let statements = parse(source, PathBuf::from("test.deva")).unwrap();

        assert_eq!(statements.len(), 1);
        match &statements[0].kind {
            StatementKind::Pattern { name, target } => {
                assert_eq!(name, "hat");
                assert_eq!(target.as_deref(), Some("drums.hat"));
            }
            other => panic!("expected pattern shorthand, got {:?}", other),
        }

        match &statements[0].value {
            Value::Map(map) => {
                assert!(
                    matches!(map.get("pattern"), Some(Value::String(pattern)) if pattern == "x-x-")
                );
                assert!(
                    matches!(map.get("swing"), Some(Value::Number(n)) if (*n - 0.08).abs() < f32::EPSILON)
                );
                assert!(
                    matches!(map.get("velocity"), Some(Value::Number(n)) if (*n - 0.7).abs() < f32::EPSILON)
                );
            }
            other => panic!("expected pattern options map, got {:?}", other),
        }
    }
}