sva-cli 0.7.16

The command-line front end for SVA
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
// Concern: what a composition can be told about itself without rendering a sample | Non-concern: rendering, or judging how it sounds | IO: (dir[, target]) -> Vec<Finding> or CliError

use std::path::Path;

use sva_ast::parse_doc_comment;
use sva_ast::{Graph, Source, ref_spans};
use sva_core::{CliError, Job, LintCode, LintViolation, Severity, lint_diagnostic};
use sva_core::{Diagnostic, prepared, refuse_unresolved_bars, settled};

/// These ride a `success` envelope; a refusal raises [`sva_core::CliError::LintRefused`].
pub struct Finding {
    pub code: LintCode,
    pub severity: Severity,
    pub subject: String,
    pub message: String,
    /// The 1-based line the check found it on, where it knows one.
    pub line: Option<usize>,
}

impl Finding {
    pub fn diagnostic(&self) -> Diagnostic {
        lint_diagnostic(
            self.code,
            &self.subject,
            &self.message,
            self.severity,
            self.line,
        )
    }
}

pub struct LintReport {
    pub nodes: usize,
    pub findings: Vec<Finding>,
    /// The seconds a render of the target reads.
    pub interval: Option<(f64, f64)>,
}

/// With no target, every file's own rules and every entry point's types; with one, those of
/// each file it reaches and the interval a render of it reads.
pub fn lint(dir: &Path, target: Option<&str>) -> Result<LintReport, CliError> {
    let source = sva_ast::Dir::at(dir);
    match target {
        None => lint_files(&source, prepared(&source)?),
        Some(target) => lint_reaching(&source, target),
    }
}

/// Every entry point is typed, which types every file it reaches; one that no render can take
/// whole is left to the render that refuses it. A lint violation refuses before a type does.
fn lint_files(source: &dyn Source, graph: Graph) -> Result<LintReport, CliError> {
    refuse_unresolved_bars(&graph)?;
    let violations = lint_violations(source, &graph);
    if violations.is_empty() {
        for root in crate::trace::entry_points(&graph) {
            sva_core::types(&Job::over(source, &format!("@{root}")))?;
        }
    }
    verdict(graph.paths().count(), violations, per_file(&graph), None)
}

/// The findings no file's neighbours change.
fn per_file(graph: &Graph) -> Vec<Finding> {
    let mut findings = grid_row_counts(graph);
    findings.extend(crate::variables::key_findings(graph));
    findings.extend(crate::bare::bare_findings(graph));
    findings
}

/// The status is the verdict; `data.diagnostics[]` carries everything the scan found.
fn verdict(
    nodes: usize,
    violations: Vec<LintViolation>,
    findings: Vec<Finding>,
    interval: Option<(f64, f64)>,
) -> Result<LintReport, CliError> {
    if violations.is_empty() {
        return Ok(LintReport {
            nodes,
            findings,
            interval,
        });
    }
    let mut every = violations;
    every.extend(findings.into_iter().map(|f| LintViolation {
        code: f.code,
        severity: f.severity,
        subject: f.subject,
        message: f.message,
        line: f.line,
    }));
    Err(CliError::LintRefused(every))
}

/// The files the target reaches, each under its own rules, then what a render of it decides:
/// a lint violation refuses before a structural one.
fn lint_reaching(source: &dyn Source, target: &str) -> Result<LintReport, CliError> {
    let expr = sva_core::target(target)?.expr;
    let held = sva_core::roots_of(source, &expr)?;
    let roots: Vec<&str> = held.iter().map(String::as_str).collect();
    let graph = settled(sva_ast::load_reaching(source, &roots))?;
    refuse_unresolved_bars(&graph)?;
    let violations = lint_violations(source, &graph);
    let mut interval = None;
    if violations.is_empty() {
        let job = Job::over(source, target);
        let render = sva_core::plan(&job)?;
        let rate = f64::from(render.config.rate);
        interval = render
            .range
            .map(|r| (r.start_secs(render.config.rate), r.end as f64 / rate));
    }
    verdict(
        graph.paths().count(),
        violations,
        per_file(&graph),
        interval,
    )
}

/// A row count tiles a span as a subdivision of a bar or as whole bars; both count.
fn grid_row_counts(graph: &Graph) -> Vec<Finding> {
    let mut findings = Vec::new();
    for path in graph.paths() {
        let Some(grid) = graph.grid(path) else {
            continue;
        };
        let Some(bars) = grid.bar_span.filter(|b| *b > 0.0) else {
            continue;
        };
        let rows_per_bar = grid.row_count as f64 / bars;
        let bars_per_row = bars / grid.row_count as f64;
        let whole = |v: f64| (v - v.round()).abs() <= 1e-9;
        if !whole(rows_per_bar) && !whole(bars_per_row) {
            findings.push(Finding {
                code: LintCode::GridRowsPerBar,
                severity: Severity::Warning,
                subject: path.to_string(),
                message: format!(
                    "`{path}` has {} rows over {bars} bar(s), {rows_per_bar:.4} rows/bar and \
                     {bars_per_row:.4} bars/row — neither a whole subdivision of a bar nor a \
                     whole number of bars a row, likely a stray or missing row",
                    grid.row_count
                ),
                line: None,
            });
        }
    }
    findings
}

/// Refuses with every violation found, not just the first: a tree-wide scan, unlike
/// `check_arity`/`check_feedback`'s single graph evaluation.
fn lint_violations(source: &dyn Source, graph: &Graph) -> Vec<LintViolation> {
    let mut violations = Vec::new();
    violations.extend(doc_comment_violations(source, graph));
    violations.extend(long_comment_block_violations(source, graph));
    violations.extend(long_expression_body_violations(source, graph));
    violations.extend(crate::rates::rate_violations(graph));
    violations.extend(crate::arity::arity_violations(graph));
    violations
}

/// Even a justified multi-line block stays under this.
const LONG_COMMENT_BLOCK_CHARS: usize = 1000;

/// The line-1 doc-comment's own run is excluded from the count.
fn long_comment_block_violations(source: &dyn Source, graph: &Graph) -> Vec<LintViolation> {
    let mut violations = Vec::new();
    for path in graph.paths() {
        let Ok(Some(text)) = source.get(path) else {
            continue;
        };
        // start line, running char total, first line's own char length.
        let mut run: Option<(usize, usize, usize)> = None;
        for (idx, line) in text.lines().enumerate() {
            if line.trim_start().starts_with(';') {
                let line_chars = line.chars().count();
                run = Some(match run {
                    Some((start, chars, first)) => (start, chars + line_chars, first),
                    None => (idx + 1, line_chars, line_chars),
                });
            } else {
                flush_comment_run(run.take(), path, &mut violations);
            }
        }
        flush_comment_run(run, path, &mut violations);
    }
    violations
}

/// Drops the header line's own char count (not a flat `1`) when the run starts at line 1.
fn flush_comment_run(
    run: Option<(usize, usize, usize)>,
    path: &str,
    violations: &mut Vec<LintViolation>,
) {
    let Some((start, chars, first)) = run else {
        return;
    };
    let chars = if start == 1 {
        chars.saturating_sub(first)
    } else {
        chars
    };
    if chars > LONG_COMMENT_BLOCK_CHARS {
        violations.push(LintViolation {
            code: LintCode::LongCommentBlock,
            severity: Severity::Error,
            subject: path.to_string(),
            message: format!(
                "`{path}` has a {chars}-character comment block, over the \
                 {LONG_COMMENT_BLOCK_CHARS}-character threshold — split it or trim it"
            ),
            line: Some(start),
        });
    }
}

/// Exactly one doc-comment line at the top, or `lint` refuses it. Only the leading run is
/// judged — a grid's own inline `; lane` comments stay out of scope.
fn doc_comment_violations(source: &dyn Source, graph: &Graph) -> Vec<LintViolation> {
    let mut violations = Vec::new();
    for path in graph.paths() {
        let Ok(Some(text)) = source.get(path) else {
            continue;
        };
        let header: Vec<&str> = text
            .lines()
            .take_while(|line| line.trim_start().starts_with(';'))
            .collect();
        match header.len() {
            0 => violations.push(LintViolation {
                code: LintCode::MissingComment,
                severity: Severity::Error,
                subject: path.to_string(),
                message: format!(
                    "`{path}` has no `;`-comment — every composition node must carry one `; \
                     Models: ... | Neglects: ... | IO: ... -> ... | Tags: ...` line \
                     documenting it"
                ),
                line: None,
            }),
            1 => {
                if let Err(reason) = parse_doc_comment(header[0]) {
                    violations.push(LintViolation {
                        code: LintCode::MalformedComment,
                        severity: Severity::Error,
                        subject: path.to_string(),
                        message: format!(
                            "`{path}`'s comment does not match `Models: ... | Neglects: ... \
                             | IO: ... -> ... | Tags: ...` ({reason})"
                        ),
                        line: None,
                    });
                }
            }
            n => violations.push(LintViolation {
                code: LintCode::MultilineComment,
                severity: Severity::Error,
                subject: path.to_string(),
                message: format!(
                    "`{path}` has {n} `;`-comment lines — exactly one is required, written \
                     denser instead of split across lines"
                ),
                line: None,
            }),
        }
    }
    violations
}

/// Generous on purpose: today's longest real body is ~5000 chars — a backstop against
/// runaway generation, not a tight budget on complex physical models.
const EXPRESSION_BODY_CHARS: usize = 10_000;

/// A verbose local `@ref` name is a naming choice, not equation complexity.
const REF_PLACEHOLDER: &str = "@x";

/// Excludes the leading `;`-comment run. A node over budget on the raw count gets one more,
/// cheap recount with ref names collapsed, so a verbose `@ref` name alone cannot trip the cap.
fn long_expression_body_violations(source: &dyn Source, graph: &Graph) -> Vec<LintViolation> {
    let mut violations = Vec::new();
    for path in graph.paths() {
        let Ok(Some(text)) = source.get(path) else {
            continue;
        };
        let body: String = text
            .lines()
            .skip_while(|line| line.trim_start().starts_with(';'))
            .collect::<Vec<_>>()
            .join("\n");
        let chars = body.chars().count();
        if chars <= EXPRESSION_BODY_CHARS {
            continue;
        }
        let (chars, has_refs) = ref_stripped_char_count(&body);
        if chars > EXPRESSION_BODY_CHARS {
            let message = if has_refs {
                format!(
                    "`{path}` has a {chars}-character expression body even with every `@ref` \
                     name collapsed to `{REF_PLACEHOLDER}`, over the \
                     {EXPRESSION_BODY_CHARS}-character threshold — decompose it into sub-nodes"
                )
            } else {
                format!(
                    "`{path}` has a {chars}-character expression body, over the \
                     {EXPRESSION_BODY_CHARS}-character threshold — decompose it into sub-nodes"
                )
            };
            violations.push(LintViolation {
                code: LintCode::LongExpressionBody,
                severity: Severity::Error,
                subject: path.to_string(),
                message,
                line: None,
            });
        }
    }
    violations
}

/// Only reached once the raw count already exceeds the cap. Collapses each `@ref`'s `@path`
/// head to a placeholder; a trailing `(...)` invocation stays, being real expression content.
/// The `bool` says whether any ref was actually collapsed, so the error message can be worded
/// accurately for a body already over budget on pure literal content.
fn ref_stripped_char_count(body: &str) -> (usize, bool) {
    let spans = ref_spans(body);
    let has_refs = !spans.is_empty();
    let mut reduced = String::with_capacity(body.len());
    let mut cursor = 0;
    for span in spans {
        reduced.push_str(&body[cursor..span.start]);
        reduced.push_str(REF_PLACEHOLDER);
        cursor = span.end;
    }
    reduced.push_str(&body[cursor..]);
    (reduced.chars().count(), has_refs)
}

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

    fn dir_of(name: &str, files: &[(&str, &str)]) -> std::path::PathBuf {
        let dir =
            std::env::temp_dir().join(format!("sva-cli-lint-{name}-{:x}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        for (rel, content) in files {
            let path = dir.join(rel);
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(path, content).unwrap();
        }
        dir
    }

    /// A well-formed doc comment, for a fixture node the test isn't about.
    fn doc(models: &str) -> String {
        format!(
            "; Models: {models} | Neglects: nothing, it's a fixture | IO: t -> mix | Tags: \
             fixture\n"
        )
    }

    /// Both response paths are one external contract: a reader branches on `severity`, and
    /// gets the same object shape whether `lint` succeeded or refused.
    #[test]
    fn both_lint_response_paths_answer_the_same_diagnostic_shape() {
        let dir = dir_of(
            "one-envelope",
            &[
                ("master", &(doc("the mix") + "@kick*0.5\n")),
                ("kick", &(doc("a thump") + "sin(2*pi*50*t)\n")),
                ("variables/key", &(doc("the key") + "sin(t)\n")),
            ],
        );
        let report = lint(&dir, None).expect("a documented composition lints clean");
        let found: Vec<Diagnostic> = report.findings.iter().map(Finding::diagnostic).collect();
        let json = sva_core::success_envelope(
            &crate::output::lint_data(&dir.display().to_string(), None, report.nodes, None),
            &found,
        );
        assert!(json.contains("\"diagnostics\""), "{json}");
        assert!(
            json.contains("\"code\": \"lint.key_is_not_a_pitch\""),
            "{json}"
        );
        assert!(json.contains("\"severity\": \"warning\""), "{json}");
        assert!(
            json.contains("\"location\": { \"file\": \"variables/key\", \"span\": null, \"start\": null, \"end\": null }"),
            "{json}"
        );
        assert!(json.contains("\"help\""), "{json}");

        let undocumented = dir_of(
            "one-envelope-refused",
            &[("master", "@kick*0.5\n"), ("kick", "sin(t)\n")],
        );
        let Err(err) = lint(&undocumented, None) else {
            panic!("an undocumented node must refuse");
        };
        let refused = sva_core::error_envelope(err.code(), &err.message(), &err.diagnostics());
        assert!(refused.contains("\"diagnostics\""), "{refused}");
        assert!(
            refused.contains("\"code\": \"lint.missing_comment\""),
            "{refused}"
        );
        assert!(refused.contains("\"severity\": \"error\""), "{refused}");
        assert!(
            refused
                .contains("\"location\": { \"file\": \"kick\", \"span\": null, \"start\": null, \"end\": null }"),
            "{refused}"
        );
        assert!(refused.contains("\"help\""), "{refused}");

        let _ = fs::remove_dir_all(&dir);
        let _ = fs::remove_dir_all(&undocumented);
    }

    fn assert_refused(result: Result<LintReport, CliError>, code: LintCode, subject: &str) {
        match result {
            Ok(report) => panic!(
                "expected a `{code:?}` refusal for `{subject}`, got a clean report: {:?}",
                report.findings.iter().map(|f| &f.code).collect::<Vec<_>>()
            ),
            Err(CliError::LintRefused(violations)) => assert!(
                violations
                    .iter()
                    .any(|v| v.code == code && v.subject == subject),
                "expected a `{code:?}` refusal for `{subject}`, got: {:?}",
                violations
                    .iter()
                    .map(|v| (v.code, &v.subject))
                    .collect::<Vec<_>>()
            ),
            Err(other) => panic!("expected a `{code:?}` refusal, got a different error: {other:?}"),
        }
    }

    #[test]
    fn a_loop_the_engine_can_schedule_lints_clean() {
        let dir = dir_of(
            "long-loop",
            &[
                (
                    "a",
                    &(doc("a fixture signal") + "sin(t) + @b(t - 0.01s)*0.5\n"),
                ),
                ("b", &(doc("a fixture signal") + "@a(t - 0.01s)*0.5\n")),
                ("master", &(doc("a fixture signal") + "@a\n")),
            ],
        );
        assert!(
            lint(&dir, None).is_ok(),
            "a schedulable loop is not a finding"
        );
    }

    /// Plain lint types every entry point, so it refuses what a lint of that target does.
    #[test]
    fn plain_lint_refuses_the_type_refusal_a_targeted_lint_does() {
        let body = "crop(self(t - 1sp) + sample(sin(2*pi*100*t))*1sp, 0s, 1s)\n";
        let dir = dir_of("typed", &[("master", &(doc("a discrete loop") + body))]);
        for target in [None, Some("@master")] {
            let Err(err) = lint(&dir, target) else {
                panic!("{target:?}: `self(t - d)` in a discrete loop must refuse");
            };
            let codes: Vec<String> = err.diagnostics().into_iter().map(|d| d.code).collect();
            assert!(
                codes.iter().any(|c| c == "type.discrete_self_at_time"),
                "{target:?}: {codes:?}"
            );
        }
        let _ = fs::remove_dir_all(&dir);
    }

    /// The dogfooding bug: a trailing blank row makes 33, and 33/4 is not a whole subdivision —
    /// yet every intended note is still there, which is why counting notes alone missed it.
    #[test]
    fn a_grid_with_a_trailing_blank_row_over_its_bar_span_is_flagged() {
        let dir = dir_of(
            "trailing-blank-row",
            &[
                ("kick", &(doc("a fixture kick") + "sin(2*pi*50*t)\n")),
                (
                    "pattern-4b",
                    &(doc("a fixture pattern") + &("@kick\n".repeat(32) + "\n")),
                ),
                ("master", &(doc("a fixture signal") + "@pattern-4b\n")),
            ],
        );
        let whole = lint(&dir, None).unwrap();
        assert!(
            whole
                .findings
                .iter()
                .any(|f| f.code == LintCode::GridRowsPerBar && f.subject == "pattern-4b"),
            "33 rows over 4 bars must be flagged: {:?}",
            whole.findings.iter().map(|f| &f.code).collect::<Vec<_>>()
        );

        let targeted = lint(&dir, Some("@master([0, 1s])")).unwrap();
        assert!(
            targeted
                .findings
                .iter()
                .any(|f| f.code == LintCode::GridRowsPerBar),
            "the target-scoped path must run this check too"
        );
    }

    #[test]
    fn a_grid_whose_rows_tile_its_bar_span_evenly_is_clean() {
        let dir = dir_of(
            "clean-grid",
            &[
                ("kick", &(doc("a fixture kick") + "sin(2*pi*50*t)\n")),
                (
                    "pattern-4b",
                    &(doc("a fixture pattern") + &"@kick\n".repeat(32)),
                ),
                ("master", &(doc("a fixture signal") + "@pattern-4b\n")),
            ],
        );
        assert!(
            !lint(&dir, None)
                .unwrap()
                .findings
                .iter()
                .any(|f| f.code == LintCode::GridRowsPerBar),
            "32 rows over 4 bars is an exact subdivision"
        );
        assert!(
            !lint(&dir, Some("@master([0, 1s])"))
                .unwrap()
                .findings
                .iter()
                .any(|f| f.code == LintCode::GridRowsPerBar)
        );
    }

    #[test]
    fn a_grid_spanned_in_seconds_has_no_bar_count_to_check() {
        let dir = dir_of(
            "seconds-spanned",
            &[
                ("kick", &(doc("a fixture kick") + "sin(2*pi*50*t)\n")),
                (
                    "pattern-2s",
                    &(doc("a fixture pattern") + &("@kick\n".repeat(33) + "\n")),
                ),
                ("master", &(doc("a fixture signal") + "@pattern-2s\n")),
            ],
        );
        assert!(
            !lint(&dir, None)
                .unwrap()
                .findings
                .iter()
                .any(|f| f.code == LintCode::GridRowsPerBar),
            "a `-Ns` grid declares no bars, so there is nothing to divide"
        );
    }

    type ThresholdCase = (&'static str, std::path::PathBuf, Box<dyn Fn()>);

    #[test]
    fn every_length_threshold_sits_at_its_boundary_and_trips_one_char_over() {
        let cases: Vec<ThresholdCase> = vec![
            (
                "long-comment-block, 1000 chars",
                dir_of(
                    "boundary-comment",
                    &[(
                        "master",
                        &(doc("a fixture signal")
                            + "sin(t)\n"
                            + &format!(";{}", "x".repeat(999))
                            + "\n"),
                    )],
                ),
                Box::new(|| {
                    let trailing = format!(";{}", "x".repeat(1000));
                    let dir = dir_of(
                        "long-comment",
                        &[
                            (
                                "long",
                                &(doc("a fixture signal") + "sin(t)\n" + &trailing + "\n"),
                            ),
                            ("master", &(doc("a fixture signal") + "@long\n")),
                        ],
                    );
                    assert_refused(lint(&dir, None), LintCode::LongCommentBlock, "long");
                    assert_refused(
                        lint(&dir, Some("@master([0, 1s])")),
                        LintCode::LongCommentBlock,
                        "long",
                    );
                }) as Box<dyn Fn()>,
            ),
            (
                "long-expression-body, 10000 chars",
                dir_of(
                    "boundary-expression-body",
                    &[(
                        "drone",
                        &(String::from(
                            "; Models: a sustained drone | Neglects: envelope, detune | IO: t -> \
                             amplitude | Tags: drone\n",
                        ) + &"0".repeat(10_000)
                            + "\n"),
                    )],
                ),
                Box::new(|| {
                    let body = "0".repeat(10_001);
                    let dir = dir_of(
                        "long-expression-body",
                        &[
                            (
                                "drone",
                                &(String::from(
                                    "; Models: a sustained drone | Neglects: envelope, detune | \
                                     IO: t -> amplitude | Tags: drone\n",
                                ) + &body
                                    + "\n"),
                            ),
                            (
                                "master",
                                &(String::from(WELL_FORMED_MASTER_COMMENT) + "@drone\n"),
                            ),
                        ],
                    );
                    assert_refused(lint(&dir, None), LintCode::LongExpressionBody, "drone");
                    assert_refused(
                        lint(&dir, Some("@master([0, 1s])")),
                        LintCode::LongExpressionBody,
                        "drone",
                    );
                }),
            ),
        ];
        for (label, at, over) in cases {
            assert!(
                lint(&at, None).is_ok(),
                "{label}: exactly at the threshold, not over it"
            );
            over();
        }
    }

    /// Line 1's own run is exempt from this budget, however long its one required line is.
    #[test]
    fn a_long_but_well_formed_leading_doc_comment_is_not_a_long_comment_block() {
        let filler = "x".repeat(2000);
        let header = format!(
            "; Models: {filler} | Neglects: nothing, it's a fixture | IO: t -> mix | Tags: \
             fixture\n"
        );
        let dir = dir_of("long-header-exempt", &[("master", &(header + "sin(t)\n"))]);
        assert!(
            lint(&dir, None).is_ok(),
            "a single well-formed doc-comment line is exempt from the long-comment-block \
             budget regardless of its own length"
        );
    }

    /// A 2-line run is also `multiline-comment`; `.any()` isolates the arithmetic under test.
    #[test]
    fn the_line_one_header_annotation_is_excluded_from_its_run() {
        let header = ";header"; // 7 chars
        let boundary_line = format!(";{}", "x".repeat(999)); // 1000 chars
        let over_line = format!(";{}", "x".repeat(1000)); // 1001 chars

        let under = dir_of(
            "header-excluded-under",
            &[("master", &format!("{header}\n{boundary_line}\nsin(t)\n"))],
        );
        let Err(CliError::LintRefused(violations)) = lint(&under, None) else {
            panic!("a 2-line leading run is also multiline-comment, so this must still refuse")
        };
        assert!(
            !violations
                .iter()
                .any(|v| v.code == LintCode::LongCommentBlock),
            "1007 chars from line 1 is 1000 once the header is excluded: {:?}",
            violations.iter().map(|v| &v.code).collect::<Vec<_>>()
        );

        let over = dir_of(
            "header-excluded-over",
            &[("master", &format!("{header}\n{over_line}\nsin(t)\n"))],
        );
        assert_refused(lint(&over, None), LintCode::LongCommentBlock, "master");
    }

    /// Well-formed, so it never adds noise to a scenario testing some other node's comment.
    const WELL_FORMED_MASTER_COMMENT: &str = "; Models: a test harness's master node | Neglects: nothing, it's a fixture | IO: t -> mix | Tags: fixture\n";

    #[test]
    fn a_node_with_no_comment_at_all_is_missing_comment_in_both_modes() {
        let dir = dir_of(
            "missing-comment",
            &[
                ("plucked", "sin(t)\n"),
                (
                    "master",
                    &(String::from(WELL_FORMED_MASTER_COMMENT) + "@plucked\n"),
                ),
            ],
        );
        assert_refused(lint(&dir, None), LintCode::MissingComment, "plucked");
        assert_refused(
            lint(&dir, Some("@master([0, 1s])")),
            LintCode::MissingComment,
            "plucked",
        );
    }

    #[test]
    fn two_contiguous_comment_lines_are_multiline_comment_in_both_modes() {
        let dir = dir_of(
            "multiline-comment",
            &[
                (
                    "stacked",
                    "; Models: a thing\n; Neglects: nothing | IO: t -> out\nsin(t)\n",
                ),
                (
                    "master",
                    &(String::from(WELL_FORMED_MASTER_COMMENT) + "@stacked\n"),
                ),
            ],
        );
        assert_refused(lint(&dir, None), LintCode::MultilineComment, "stacked");
        assert_refused(
            lint(&dir, Some("@master([0, 1s])")),
            LintCode::MultilineComment,
            "stacked",
        );
    }

    #[test]
    fn one_correctly_shaped_comment_line_under_the_length_threshold_is_clean() {
        let dir = dir_of(
            "well-formed-comment",
            &[
                (
                    "plucked",
                    "; Models: a plucked string's fundamental decay | Neglects: pick-position \
                     comb, body coupling | IO: note -> supersaw base | Tags: pluck\nsin(t)\n",
                ),
                (
                    "master",
                    &(String::from(WELL_FORMED_MASTER_COMMENT) + "@plucked\n"),
                ),
            ],
        );
        assert!(
            lint(&dir, None).is_ok(),
            "a single well-formed, short comment must not refuse"
        );
        assert!(
            lint(&dir, Some("@master([0, 1s])")).is_ok(),
            "a single well-formed, short comment must not refuse"
        );
    }

    #[test]
    fn a_single_free_text_comment_line_is_malformed_comment_in_both_modes() {
        let dir = dir_of(
            "malformed-comment",
            &[
                (
                    "plucked",
                    "; a plucked string, decays over time, no body resonance modeled\nsin(t)\n",
                ),
                (
                    "master",
                    &(String::from(WELL_FORMED_MASTER_COMMENT) + "@plucked\n"),
                ),
            ],
        );
        assert_refused(lint(&dir, None), LintCode::MalformedComment, "plucked");
        assert_refused(
            lint(&dir, Some("@master([0, 1s])")),
            LintCode::MalformedComment,
            "plucked",
        );
    }

    /// `; lane`-style inline comments inside a TSV grid, well below the header, are a
    /// separate, already-legitimate feature (`sva-ast`'s `code_rows`) — not a second doc
    /// comment competing with the header for "exactly one".
    #[test]
    fn a_grids_own_inline_comment_below_a_well_formed_header_is_not_multiline_comment() {
        let dir = dir_of(
            "grid-inline-comment",
            &[
                ("kick", &(doc("a fixture kick") + "sin(2*pi*50*t)\n")),
                (
                    "pattern-1b",
                    "; Models: a kick pattern | Neglects: dynamics, humanization | \
                     IO: (t) -> amplitude | Tags: kick\n@kick\n; lane\n@kick\n",
                ),
                (
                    "master",
                    &(String::from(WELL_FORMED_MASTER_COMMENT) + "@pattern-1b\n"),
                ),
            ],
        );
        assert!(
            lint(&dir, None).is_ok(),
            "a grid's own inline comment must not be mistaken for a second doc comment"
        );
    }

    /// A well-formed header plus a body just under the cap must not refuse, even though
    /// their combined length exceeds it.
    #[test]
    fn the_leading_doc_comment_is_excluded_from_the_expression_body_count() {
        let body = "0".repeat(9_999);
        let dir = dir_of(
            "doc-comment-excluded",
            &[(
                "drone",
                &(String::from(
                    "; Models: a sustained drone with a longer than usual doc comment header \
                     | Neglects: envelope, detune | IO: t -> amplitude | Tags: drone\n",
                ) + &body
                    + "\n"),
            )],
        );
        assert!(
            lint(&dir, None).is_ok(),
            "the doc comment header must not count toward the body length"
        );
    }

    /// Raw count is over budget only because the author picked a verbose local `@ref` name;
    /// once every occurrence collapses to `@x` the equation itself is nowhere near the cap.
    #[test]
    fn a_body_over_budget_only_from_verbose_ref_names_is_clean_once_they_collapse() {
        let long_name = "a".repeat(50);
        let n = 200; // (1 + 50) chars per `@<name>` occurrence, joined by " + " (3 chars).
        let refs: Vec<String> = std::iter::repeat_n(format!("@{long_name}"), n).collect();
        let body = refs.join(" + ");
        let raw = body.chars().count();
        assert!(
            raw > EXPRESSION_BODY_CHARS,
            "raw count must be over budget: {raw}"
        );

        let reduced: usize = n * REF_PLACEHOLDER.chars().count() + (n - 1) * 3;
        assert!(
            reduced <= EXPRESSION_BODY_CHARS,
            "reduced count must be under budget: {reduced}"
        );

        let dir = dir_of(
            "ref-collapse-clean",
            &[
                (&long_name, &(doc("a fixture ref target") + "sin(t)\n")),
                (
                    "drone",
                    &(String::from(
                        "; Models: a sustained drone | Neglects: envelope, detune | IO: t -> \
                         amplitude | Tags: drone\n",
                    ) + &body
                        + "\n"),
                ),
                (
                    "master",
                    &(String::from(WELL_FORMED_MASTER_COMMENT) + "@drone\n"),
                ),
            ],
        );
        assert!(
            lint(&dir, None).is_ok(),
            "a body over budget only from a verbose ref name must clear once ref names collapse"
        );
    }

    /// Even with ref names collapsed, enough literal filler keeps the reduced count over budget.
    #[test]
    fn a_body_still_over_budget_after_ref_collapse_is_still_flagged() {
        let long_name = "b".repeat(50);
        let filler = "0".repeat(10_500);
        let body = format!("@{long_name} + @{long_name} + {filler}");
        let raw = body.chars().count();
        assert!(
            raw > EXPRESSION_BODY_CHARS,
            "raw count must be over budget: {raw}"
        );
        let reduced = 2 * REF_PLACEHOLDER.chars().count() + 2 * 3 + filler.chars().count();
        assert!(
            reduced > EXPRESSION_BODY_CHARS,
            "reduced count must still be over budget: {reduced}"
        );

        let dir = dir_of(
            "ref-collapse-still-over",
            &[
                (&long_name, &(doc("a fixture ref target") + "sin(t)\n")),
                (
                    "drone",
                    &(String::from(
                        "; Models: a sustained drone | Neglects: envelope, detune | IO: t -> \
                         amplitude | Tags: drone\n",
                    ) + &body
                        + "\n"),
                ),
                (
                    "master",
                    &(String::from(WELL_FORMED_MASTER_COMMENT) + "@drone\n"),
                ),
            ],
        );
        assert_refused(lint(&dir, None), LintCode::LongExpressionBody, "drone");
    }

    /// A body with `@ref`s well under the raw cap is clean — refs or not, staying under
    /// budget never depends on collapsing them.
    #[test]
    fn a_body_with_refs_under_the_raw_cap_is_clean() {
        let dir = dir_of(
            "under-budget-with-refs",
            &[
                ("kick", &(doc("a fixture kick") + "sin(t)\n")),
                (
                    "drone",
                    &(String::from(
                        "; Models: a sustained drone | Neglects: envelope, detune | IO: t -> \
                         amplitude | Tags: drone\n",
                    ) + &"@kick + ".repeat(20)
                        + "0.5\n"),
                ),
                (
                    "master",
                    &(String::from(WELL_FORMED_MASTER_COMMENT) + "@drone\n"),
                ),
            ],
        );
        assert!(
            lint(&dir, None).is_ok(),
            "this body is well under the raw cap"
        );
    }

    /// A well-formed doc comment with a caller-chosen `Tags:` value, for tests exercising
    /// `Tags:` validation specifically.
    fn doc_with_tags(tags: &str) -> String {
        format!(
            "; Models: a fixture signal | Neglects: nothing, it's a fixture | IO: t -> mix | \
             Tags: {tags}\n"
        )
    }

    #[test]
    fn a_comment_with_the_old_three_fields_and_no_tags_is_refused_as_missing_a_fourth_field() {
        let dir = dir_of(
            "old-three-field-comment",
            &[(
                "master",
                "; Models: a fixture signal | Neglects: nothing, it's a fixture | IO: t -> \
                 mix\nsin(t)\n",
            )],
        );
        let Err(CliError::LintRefused(violations)) = lint(&dir, None) else {
            panic!("a comment with no `Tags:` field must refuse")
        };
        let violation = violations
            .iter()
            .find(|v| v.code == LintCode::MalformedComment && v.subject == "master")
            .unwrap_or_else(|| {
                panic!(
                    "expected a malformed-comment refusal, got: {:?}",
                    violations.iter().map(|v| v.code).collect::<Vec<_>>()
                )
            });
        assert!(
            violation.message.contains("four"),
            "expected the refusal to name the missing fourth field: {}",
            violation.message
        );
    }

    #[test]
    fn a_tags_field_with_no_tags_is_refused() {
        let dir = dir_of(
            "empty-tags-field",
            &[("master", &(doc_with_tags("") + "sin(t)\n"))],
        );
        assert_refused(lint(&dir, None), LintCode::MalformedComment, "master");
    }

    #[test]
    fn an_empty_tag_between_commas_is_refused() {
        let dir = dir_of(
            "empty-tag-between-commas",
            &[("master", &(doc_with_tags("piano,,pad") + "sin(t)\n"))],
        );
        assert_refused(lint(&dir, None), LintCode::MalformedComment, "master");
    }

    #[test]
    fn a_single_valid_tag_is_clean() {
        let dir = dir_of(
            "one-valid-tag",
            &[("master", &(doc_with_tags("piano") + "sin(t)\n"))],
        );
        assert!(
            lint(&dir, None).is_ok(),
            "a single valid tag is not a finding"
        );
    }

    #[test]
    fn three_valid_comma_separated_tags_are_clean() {
        let dir = dir_of(
            "three-valid-tags",
            &[(
                "master",
                &(doc_with_tags("piano, sustained-pad, mellow") + "sin(t)\n"),
            )],
        );
        assert!(
            lint(&dir, None).is_ok(),
            "three valid comma-separated tags are not a finding"
        );
    }

    /// A well-formed 4-field header (valid `Tags:` included) ahead of a separate, non-leading
    /// comment block must not shield that block from `LONG_COMMENT_BLOCK_CHARS` — the two
    /// checks stay independent even once the header carries a fourth field.
    #[test]
    fn a_well_formed_tagged_header_does_not_exempt_a_later_long_comment_block() {
        let trailing = format!(";{}", "x".repeat(1000)); // 1001 chars
        let dir = dir_of(
            "tagged-header-long-block",
            &[
                (
                    "long",
                    &(doc_with_tags("fixture") + "sin(t)\n" + &trailing + "\n"),
                ),
                ("master", &(doc_with_tags("fixture") + "@long\n")),
            ],
        );
        assert_refused(lint(&dir, None), LintCode::LongCommentBlock, "long");
    }
}