cuno-tools 0.2.1

cuno fmt and cuno lint (clang-format / clang-tidy).
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
//! clang-tidy's configuration from `[lint]`
//! (`docs/en/specs/dev-tools.md`, "`[lint]`").

use std::collections::HashSet;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};

use cuno_core::Env;
use cuno_manifest::{Lint, LintPreset};
use cuno_toolchain::Runner;

/// The file editors read, at the project root.
pub const FILE: &str = ".clang-tidy";

/// The first line of every `.clang-tidy` cuno writes: a file that does not
/// start with it is the user's, and is not overwritten
/// (`docs/en/specs/dev-tools.md`, "Configuration").
pub const MARKER: &str =
    "# Generated by cuno from [lint] in Cuno.toml, and overwritten: edit Cuno.toml instead.";

/// `recommended` (`dev-tools.md`, "Contents of the presets").
const RECOMMENDED: &[&str] = &[
    "bugprone-*",
    "-bugprone-easily-swappable-parameters",
    // Every C++ test suite is a static object built from a lambda, which
    // this check reads through.
    "-bugprone-throwing-static-initialization",
    // With exceptions on (the default), any `main` that prints is a finding:
    // the stream may throw. An exception that escapes stops the program
    // loudly; `warn` puts the check back (`dev-tools.md`, "Contents of the
    // presets").
    "-bugprone-exception-escape",
    "clang-analyzer-*",
    "performance-*",
    "modernize-use-nullptr",
    "modernize-use-override",
    "modernize-make-unique",
    "modernize-use-emplace",
    "readability-isolate-declaration",
];

/// What `strict` adds to `recommended`.
const STRICT: &[&str] = &[
    "readability-*",
    "cppcoreguidelines-*",
    "modernize-*",
    "-modernize-use-trailing-return-type",
    "-readability-identifier-length",
];

/// clang-tidy's `Checks` and `WarningsAsErrors` for `lint`, each a list of globs that clang-tidy applies in order, the last
/// that matches a check deciding it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TidyConfig {
    /// Which checks run.
    pub checks: Vec<String>,
    /// Which of those are errors.
    pub warnings_as_errors: Vec<String>,
}

/// The configuration for `lint` (`dev-tools.md`, "allow / warn / deny"),
/// ordered so that clang-tidy's last-match-wins gives the spec's
/// precedence: the preset's checks; the user's wildcards, broadest first;
/// the preset's exclusions, which only a name brings back; the user's
/// names. At each rank `allow`, then `warn`, then `deny`, so the stronger
/// wins. C++-only checks in a C package are left to clang-tidy, which does
/// not run them on C.
pub fn clang_tidy_config(lint: &Lint) -> TidyConfig {
    let preset: Vec<&str> = match lint.preset {
        LintPreset::None => Vec::new(),
        LintPreset::Recommended => RECOMMENDED.to_vec(),
        LintPreset::Strict => RECOMMENDED.iter().chain(STRICT).copied().collect(),
    };
    let (excluded, enabled): (Vec<&str>, Vec<&str>) =
        preset.into_iter().partition(|g| g.starts_with('-'));

    // Every user pattern with its rank: wildcards by the length before `*`
    // (narrower later), names last; then allow < warn < deny.
    #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
    enum List {
        Allow,
        Warn,
        Deny,
    }
    let mut written: Vec<(usize, List, &str)> = Vec::new();
    for (list, patterns) in [
        (List::Allow, &lint.allow),
        (List::Warn, &lint.warn),
        (List::Deny, &lint.deny),
    ] {
        for pattern in patterns {
            let rank = pattern.find('*').unwrap_or(usize::MAX);
            written.push((rank, list, pattern));
        }
    }
    written.sort_by_key(|(rank, list, _)| (*rank, *list));
    let (wildcards, names): (Vec<_>, Vec<_>) = written
        .into_iter()
        .partition(|(rank, _, _)| *rank != usize::MAX);

    let mut checks: Vec<String> = vec!["-*".to_owned()];
    checks.extend(enabled.iter().map(|g| (*g).to_owned()));
    let mut errors: Vec<String> = Vec::new();
    let mut add = |checks: &mut Vec<String>, (_, list, pattern): (usize, List, &str)| {
        match list {
            List::Allow => checks.push(format!("-{pattern}")),
            List::Warn | List::Deny => checks.push(pattern.to_owned()),
        }
        match list {
            List::Allow | List::Warn => errors.push(format!("-{pattern}")),
            List::Deny => errors.push(pattern.to_owned()),
        }
    };
    for w in wildcards {
        add(&mut checks, w);
    }
    checks.extend(excluded.iter().map(|g| (*g).to_owned()));
    for n in names {
        add(&mut checks, n);
    }
    TidyConfig {
        checks,
        warnings_as_errors: errors,
    }
}

/// `.clang-tidy` for `lint`. With an empty
/// `HeaderFilterRegex`, clang-tidy reports no header's findings unless
/// asked on its command line: `cuno lint` asks, and keeps the package's.
pub fn clang_tidy_file(lint: &Lint) -> String {
    let config = clang_tidy_config(lint);
    format!(
        "{MARKER}\nChecks: '{}'\nWarningsAsErrors: '{}'\nHeaderFilterRegex: ''\nFormatStyle: file\n",
        config.checks.join(","),
        config.warnings_as_errors.join(","),
    )
}

/// Whether `config` turns any check on; clang-tidy refuses to run with
/// none (`docs/en/specs/commands.md`, "`cuno lint`").
pub fn any_check(config: &TidyConfig) -> bool {
    config.checks.iter().any(|glob| !glob.starts_with('-'))
}

/// The names in `lint`'s lists that match no check in `known`, with the
/// list each is in: a misspelt `deny` would otherwise do nothing, silently.
pub fn unknown_names<'a>(lint: &'a Lint, known: &[String]) -> Vec<(&'static str, &'a str)> {
    let mut unknown = Vec::new();
    for (list, names) in [
        ("lint.allow", &lint.allow),
        ("lint.warn", &lint.warn),
        ("lint.deny", &lint.deny),
    ] {
        for name in names {
            // The compiler's own warnings, which `--list-checks` does not
            // list, are checks all the same.
            if name.starts_with("clang-diagnostic-") {
                continue;
            }
            let found = match name.find('*') {
                Some(star) => {
                    let (before, after) = (&name[..star], &name[star + 1..]);
                    known.iter().any(|check| {
                        check.len() >= before.len() + after.len()
                            && check.starts_with(before)
                            && check.ends_with(after)
                    })
                }
                None => known.iter().any(|check| check == name),
            };
            if !found {
                unknown.push((list, name.as_str()));
            }
        }
    }
    unknown
}

/// The checks `program` has, from `--list-checks --checks=*`.
pub fn known_checks(
    program: &Path,
    env: &Env,
    runner: &dyn Runner,
) -> std::io::Result<Vec<String>> {
    let args: [&OsStr; 2] = ["--list-checks".as_ref(), "--checks=*".as_ref()];
    let output = runner.run(program, &args, env)?;
    if !output.success {
        return Err(std::io::Error::other("clang-tidy did not list its checks"));
    }
    Ok(String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.ends_with(':'))
        .map(str::to_owned)
        .collect())
}

/// clang-tidy, and what it is run with.
pub struct ClangTidy<'a> {
    /// The executable selection chose.
    pub program: &'a Path,
    /// The `.clang-tidy` to analyse with, whatever is at the root.
    pub config: &'a Path,
    /// The directory holding compile_commands.json; clang-tidy runs there.
    pub root: &'a Path,
    /// The compiler's environment.
    pub env: &'a Env,
    /// How many sources at once (one under `fix`).
    pub jobs: usize,
    /// `--fix`: fix the sources themselves, headers left alone.
    pub fix: bool,
    /// Where `--fix` writes the fixes it looks at first.
    pub scratch: &'a Path,
}

/// What analysing found.
#[derive(Debug, Default)]
pub struct Linted {
    /// The findings to show, each once, as clang-tidy printed them, source
    /// by source in the order given.
    pub shown: Vec<u8>,
    /// How many of those are warnings.
    pub warnings: usize,
    /// How many are errors (`deny`, or a compile error).
    pub errors: usize,
    /// How many `--fix` fixed; neither warnings nor errors any more.
    pub fixed: usize,
    /// Sources clang-tidy could not analyse, with why.
    pub failed: Vec<(PathBuf, String)>,
    /// Under `--fix`, sources left unfixed because a fix would change the
    /// file given, which cuno may not write, and why
    /// ([`crate::write::Refusal`]).
    pub not_fixed: Vec<(PathBuf, PathBuf, String)>,
}

/// Analyses `sources` with `tool`, keeping only the findings in files
/// `ours` accepts (the package's, not excluded), each once
/// (`docs/en/specs/commands.md`, "`cuno lint`").
pub fn lint(
    sources: &[PathBuf],
    tool: &ClangTidy<'_>,
    ours: &(dyn Fn(&Path) -> bool + Sync),
    runner: &(dyn Runner + Sync),
) -> Linted {
    let next = AtomicUsize::new(0);
    let runs: Mutex<Vec<(usize, Run)>> = Mutex::new(Vec::new());
    let jobs = if tool.fix { 1 } else { tool.jobs };
    std::thread::scope(|scope| {
        for _ in 0..jobs.clamp(1, sources.len().max(1)) {
            scope.spawn(|| {
                loop {
                    let i = next.fetch_add(1, Ordering::SeqCst);
                    let Some(source) = sources.get(i) else { break };
                    let run = if tool.fix {
                        fix_one(i, source, tool, ours, runner)
                    } else {
                        Run {
                            output: run_one(source, tool, Mode::Show, runner),
                            foreign: None,
                        }
                    };
                    runs.lock().unwrap().push((i, run));
                }
            });
        }
    });
    let mut runs = runs.into_inner().unwrap();
    runs.sort_by_key(|(i, _)| *i);
    let mut linted = Linted::default();
    let mut seen: HashSet<Vec<u8>> = HashSet::new();
    for (i, run) in runs {
        let source = &sources[i];
        if let Some((foreign, why)) = run.foreign {
            linted.not_fixed.push((source.clone(), foreign, why));
        }
        let output = match run.output {
            Ok(output) => output,
            Err(e) => {
                linted.failed.push((source.clone(), e.to_string()));
                continue;
            }
        };
        let stderr = String::from_utf8_lossy(&output.stderr);
        // A fix clang-tidy could not write is not a fix.
        let unwritten = stderr
            .lines()
            .find(|line| line.contains("unable to overwrite file"));
        if let Some(line) = unwritten {
            linted.failed.push((source.clone(), line.trim().to_owned()));
        }
        let mut explained = false;
        for finding in findings(&output.stdout) {
            let path = tool.root.join(&finding.path);
            // A compile error is shown wherever it is: the source could not
            // be analysed. Another file's other findings are not the
            // package's, though they may be why clang-tidy failed.
            let compile_error = finding.error && finding.check.contains("clang-diagnostic-");
            if !compile_error && !ours(&path) {
                explained |= finding.error;
                continue;
            }
            explained |= finding.error;
            if !seen.insert(finding.text.clone()) {
                continue;
            }
            let fixed = unwritten.is_none()
                && String::from_utf8_lossy(&finding.text).contains("FIX-IT applied");
            if fixed {
                linted.fixed += 1;
            } else if finding.error {
                linted.errors += 1;
            } else {
                linted.warnings += 1;
            }
            linted.shown.extend_from_slice(&finding.text);
        }
        // A failure no error finding explains is never a pass.
        if !output.success && !explained && unwritten.is_none() {
            let said = stderr
                .lines()
                .find(|line| !line.trim().is_empty())
                .unwrap_or("clang-tidy failed and said nothing");
            linted.failed.push((source.clone(), said.trim().to_owned()));
        }
    }
    linted
}

/// One source's analysis, and under `--fix` a file outside the package a
/// fix would have changed, when one did and nothing was fixed.
struct Run {
    output: std::io::Result<cuno_toolchain::Output>,
    foreign: Option<(PathBuf, String)>,
}

/// How clang-tidy is run on a source.
#[derive(Clone, Copy)]
enum Mode<'a> {
    /// Findings shown, headers' included.
    Show,
    /// The fixes written to the file given, nothing changed.
    Export(&'a Path),
    /// The fixes applied.
    Fix,
}

/// `--fix` for one source: the fixes clang-tidy would make are looked at
/// first, and applied only when every one is in the package's files; a fix
/// to a declaration in another package's header would otherwise rewrite
/// that header.
fn fix_one(
    i: usize,
    source: &Path,
    tool: &ClangTidy<'_>,
    ours: &(dyn Fn(&Path) -> bool + Sync),
    runner: &dyn Runner,
) -> Run {
    let exported = tool.scratch.join(format!("fixes-{i}.yaml"));
    let looked = run_one(source, tool, Mode::Export(&exported), runner);
    let targets = std::fs::read_to_string(&exported)
        .map(|text| fix_targets(&text))
        .unwrap_or_default();
    let _ = std::fs::remove_file(&exported);
    // Every file a fix would change must be one cuno may write: the
    // package's, a file, not a link (`write::code`); the first that is not
    // is named, with why.
    let refused = targets.iter().find_map(|t| {
        crate::write::code(&tool.root.join(t), ours)
            .err()
            .map(|why| (t.clone(), why.which()))
    });
    if let Some(foreign) = refused {
        return Run {
            output: looked,
            foreign: Some(foreign),
        };
    }
    if targets.is_empty() {
        return Run {
            output: looked,
            foreign: None,
        };
    }
    Run {
        output: run_one(source, tool, Mode::Fix, runner),
        foreign: None,
    }
}

/// The files the fixes in clang-tidy's exported YAML would change: every
/// replacement's `FilePath`.
fn fix_targets(yaml: &str) -> Vec<PathBuf> {
    yaml.lines()
        .filter_map(|line| line.trim_start().strip_prefix("- FilePath:"))
        .map(|value| PathBuf::from(unquote(value.trim())))
        .collect()
}

/// A YAML scalar as LLVM writes a path: plain, `'...'` with `''` for a
/// quote, or `"..."` with backslash escapes.
fn unquote(value: &str) -> String {
    if let Some(inner) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) {
        inner.replace("''", "'")
    } else if let Some(inner) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
        let mut out = String::new();
        let mut chars = inner.chars();
        while let Some(c) = chars.next() {
            if c == '\\' {
                out.extend(chars.next());
            } else {
                out.push(c);
            }
        }
        out
    } else {
        value.to_owned()
    }
}

fn run_one(
    source: &Path,
    tool: &ClangTidy<'_>,
    mode: Mode<'_>,
    runner: &dyn Runner,
) -> std::io::Result<cuno_toolchain::Output> {
    let config = format!("--config-file={}", tool.config.display());
    let database = format!("-p={}", tool.root.display());
    // Fixing, no header's finding is shown: headers are not fixed.
    let headers = match mode {
        Mode::Show => "--header-filter=.*",
        Mode::Export(_) | Mode::Fix => "--header-filter=^$",
    };
    let mut args: Vec<OsString> = vec![
        config.into(),
        database.into(),
        headers.into(),
        "--quiet".into(),
    ];
    match mode {
        Mode::Show => {}
        Mode::Export(file) => {
            let mut arg = OsString::from("--export-fixes=");
            arg.push(file);
            args.push(arg);
        }
        Mode::Fix => args.push("--fix".into()),
    }
    args.push(source.into());
    let args: Vec<&OsStr> = args.iter().map(OsString::as_os_str).collect();
    runner.run_in(tool.program, &args, tool.env, tool.root)
}

/// One finding as clang-tidy printed it: its first line and the lines
/// after it (the code, the caret, its notes) up to the next finding.
struct Finding {
    path: PathBuf,
    error: bool,
    /// The bracketed check names at the end of its first line.
    check: String,
    text: Vec<u8>,
}

/// The findings in clang-tidy's output; summary lines are not findings.
fn findings(stdout: &[u8]) -> Vec<Finding> {
    let mut found: Vec<Finding> = Vec::new();
    for line in stdout.split_inclusive(|b| *b == b'\n') {
        let text = String::from_utf8_lossy(line);
        if let Some((path, error)) = finding_head(&text) {
            let check = text
                .trim_end()
                .rsplit_once('[')
                .map(|(_, rest)| rest.trim_end_matches(']').to_owned())
                .unwrap_or_default();
            found.push(Finding {
                path,
                error,
                check,
                text: line.to_vec(),
            });
        } else if summary(&text) {
            continue;
        } else if let Some(last) = found.last_mut() {
            last.text.extend_from_slice(line);
        }
    }
    found
}

/// The path and severity of a line that starts a finding:
/// `path:line:column: warning: ...` or `... error: ...`, at the start of
/// the line: an excerpt of code, indented, never starts one.
fn finding_head(line: &str) -> Option<(PathBuf, bool)> {
    if line.starts_with(char::is_whitespace) {
        return None;
    }
    for (marker, error) in [(": warning: ", false), (": error: ", true)] {
        let Some(at) = line.find(marker) else {
            continue;
        };
        let mut parts = line[..at].rsplitn(3, ':');
        let column = parts.next()?;
        let row = parts.next()?;
        let path = parts.next()?;
        if column.parse::<u32>().is_ok() && row.parse::<u32>().is_ok() && !path.is_empty() {
            return Some((PathBuf::from(path), error));
        }
    }
    None
}

/// clang-tidy's tallies and advice, which `cuno lint` does not show.
fn summary(line: &str) -> bool {
    // clang-tidy prints these at the start of a line; an excerpt of code is
    // indented, whatever it says.
    if line.starts_with(char::is_whitespace) {
        return false;
    }
    let line = line.trim_end();
    line.ends_with(" generated.")
        || line.starts_with("Suppressed ")
        || line.starts_with("Use -header-filter")
        || line.starts_with("Found compiler error")
        || line.starts_with("Error while processing")
}

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

    fn lint(extra: &str) -> Lint {
        let toml = format!("[package]\nname = \"app\"\nversion = \"0.1.0\"\n{extra}");
        let root = std::path::Path::new("/p");
        cuno_manifest::parse_manifest(&toml, &root.join("Cuno.toml"), root)
            .unwrap()
            .value
            .lint
    }

    /// A clang-tidy that prints `stdout` and succeeds or not, whatever it is
    /// asked.
    struct Answers {
        stdout: &'static str,
        success: bool,
    }

    impl Runner for Answers {
        fn run(
            &self,
            _program: &Path,
            _args: &[&OsStr],
            _env: &Env,
        ) -> std::io::Result<cuno_toolchain::Output> {
            Ok(cuno_toolchain::Output {
                success: self.success,
                stdout: self.stdout.as_bytes().to_vec(),
                stderr: b"\nboom\n".to_vec(),
            })
        }
    }

    fn analyse(answers: &Answers, sources: &[&str]) -> Linted {
        let env = Env::from_pairs([], cuno_core::NameCase::Insensitive);
        let root = Path::new("/p");
        let tool = ClangTidy {
            program: Path::new("clang-tidy"),
            config: Path::new("c"),
            root,
            env: &env,
            jobs: 2,
            fix: false,
            scratch: Path::new("s"),
        };
        let sources: Vec<PathBuf> = sources.iter().map(|s| root.join(s)).collect();
        let ours = |p: &Path| !p.to_string_lossy().contains("vendor");
        super::lint(&sources, &tool, &ours, answers)
    }

    const OUTPUT: &str = "\
/p/src/a.cpp:3:14: warning: use nullptr [modernize-use-nullptr]
    3 |     int* p = 0;
      |              ^
1 warning generated.
/p/src/a.h:1:1: error: bad [bugprone-x,-warnings-as-errors]
/p/src/a.h:1:1: note: here
/p/vendor/v.h:2:2: warning: theirs [bugprone-y]
2 warnings generated.
Suppressed 4 warnings (4 in non-user code).
";

    /// Each finding is kept with its lines, counted by severity, shown once
    /// though two sources print it, and dropped outside the package;
    /// clang-tidy's tallies are not shown.
    ///
    /// Mutation: keep a summary line, keep another package's finding, show
    /// a repeat, or count an error as a warning; this test fails.
    #[test]
    fn findings_are_kept_once_and_only_the_package_s() {
        let linted = analyse(
            &Answers {
                stdout: OUTPUT,
                success: false,
            },
            &["src/a.cpp", "src/b.cpp"],
        );
        let shown = String::from_utf8(linted.shown).unwrap();
        assert_eq!(
            shown,
            "/p/src/a.cpp:3:14: warning: use nullptr [modernize-use-nullptr]\n    3 |     int* p = 0;\n      |              ^\n\
             /p/src/a.h:1:1: error: bad [bugprone-x,-warnings-as-errors]\n/p/src/a.h:1:1: note: here\n",
        );
        assert_eq!((linted.warnings, linted.errors), (1, 1));
        assert!(linted.failed.is_empty(), "{:?}", linted.failed);
    }

    /// A compile error is shown and counted in any file, the package's or
    /// not; another file's deny finding is not shown, but explains why
    /// clang-tidy failed; an indented excerpt that reads like a finding, or
    /// like a tally, is part of the finding above it.
    ///
    /// Mutation: drop a foreign compile error, let a dropped one explain a
    /// failure, take an indented line for a finding, or drop an indented
    /// line ending in "generated."; this test fails.
    #[test]
    fn compile_errors_count_anywhere_and_excerpts_stay_whole() {
        let linted = analyse(
            &Answers {
                stdout: "\
/p/vendor/v.h:1:10: error: 'nope.h' file not found [clang-diagnostic-error]
/p/src/a.cpp:2:5: warning: w [bugprone-x]
    2 |     puts(\"a.c:1:2: error: x\"); // all generated.
      |     ^
",
                success: false,
            },
            &["src/a.cpp"],
        );
        let shown = String::from_utf8(linted.shown).unwrap();
        assert!(
            shown.starts_with("/p/vendor/v.h:1:10: error: 'nope.h'"),
            "{shown}"
        );
        assert!(
            shown.contains("// all generated.\n      |     ^\n"),
            "{shown}"
        );
        assert_eq!((linted.warnings, linted.errors), (1, 1));
        assert!(linted.failed.is_empty(), "{:?}", linted.failed);

        let linted = analyse(
            &Answers {
                stdout: "/p/vendor/v.h:1:1: error: theirs [bugprone-y,-warnings-as-errors]\n",
                success: false,
            },
            &["src/a.cpp"],
        );
        assert!(linted.shown.is_empty());
        assert_eq!(linted.errors, 0);
        assert!(linted.failed.is_empty(), "{:?}", linted.failed);
    }

    /// The files exported fixes would change are every replacement's path,
    /// unquoted as LLVM writes it.
    ///
    /// Mutation: read the diagnostic's own path, or leave quotes in; this
    /// test fails.
    #[test]
    fn fix_targets_are_the_replacements_paths() {
        let yaml = "\
Diagnostics:
  - DiagnosticName:  x
    DiagnosticMessage:
      FilePath:        'C:\\p\\src\\a.cpp'
      Replacements:
        - FilePath:        'C:\\p\\src\\a.cpp'
          Offset:          1
        - FilePath:        'C:\\v\\it''s.h'
          Offset:          2
";
        assert_eq!(
            fix_targets(yaml),
            [
                PathBuf::from("C:\\p\\src\\a.cpp"),
                PathBuf::from("C:\\v\\it's.h")
            ]
        );
    }

    /// A clang-tidy that fails with no error finding to explain it is a
    /// failure of that source, never a pass.
    ///
    /// Mutation: treat a failure without findings as success; this test
    /// fails.
    #[test]
    fn an_unexplained_failure_is_reported() {
        let linted = analyse(
            &Answers {
                stdout: "",
                success: false,
            },
            &["src/a.cpp"],
        );
        assert_eq!(linted.failed.len(), 1);
        assert_eq!(linted.failed[0].1, "boom");
    }

    /// A name, or a wildcard, that matches no check clang-tidy has is
    /// reported with its list.
    ///
    /// Mutation: accept any wildcard, or match names by prefix; this test
    /// fails.
    #[test]
    fn unknown_names_are_found() {
        let known: Vec<String> = ["bugprone-use-after-move", "modernize-use-nullptr"]
            .map(str::to_owned)
            .to_vec();
        let l = lint(
            "[lint]\nallow = [\"modernize-*\", \"clang-diagnostic-unused-variable\"]\nwarn = [\"bugprone-use\"]\ndeny = [\"nope-*\", \"modernize-use-nullptr\"]\n",
        );
        assert_eq!(
            unknown_names(&l, &known),
            [("lint.warn", "bugprone-use"), ("lint.deny", "nope-*")]
        );
    }

    /// No check on is `preset = "none"` with nothing written.
    ///
    /// Mutation: count a negation as a check; this test fails.
    #[test]
    fn none_with_nothing_written_enables_nothing() {
        assert!(!any_check(&clang_tidy_config(&lint(
            "[lint]\npreset = \"none\"\n"
        ))));
        assert!(any_check(&clang_tidy_config(&lint(
            "[lint]\npreset = \"none\"\nwarn = [\"bugprone-*\"]\n"
        ))));
        assert!(any_check(&clang_tidy_config(&lint(""))));
    }

    /// clang-tidy's own rule: the last glob that matches decides.
    fn last_match(globs: &[String], check: &str) -> bool {
        let mut on = false;
        for glob in globs {
            let (negated, pattern) = match glob.strip_prefix('-') {
                Some(rest) => (true, rest),
                None => (false, glob.as_str()),
            };
            let matches = match pattern.strip_suffix('*') {
                Some(prefix) => check.starts_with(prefix),
                None => check == pattern,
            };
            if matches {
                on = !negated;
            }
        }
        on
    }

    /// Whether `check` runs, and whether it is an error.
    fn judge(config: &TidyConfig, check: &str) -> (bool, bool) {
        let on = last_match(&config.checks, check);
        (on, on && last_match(&config.warnings_as_errors, check))
    }

    /// Each preset turns on what the spec lists and leaves out its
    /// exclusions; `none` turns on nothing.
    ///
    /// Mutation: drop a glob or an exclusion from a preset; this test fails.
    #[test]
    fn presets_hold_what_the_spec_lists() {
        let none = clang_tidy_config(&lint("[lint]\npreset = \"none\"\n"));
        assert_eq!(none.checks, ["-*"]);
        let rec = clang_tidy_config(&lint(""));
        for (check, on) in [
            ("bugprone-use-after-move", true),
            ("bugprone-easily-swappable-parameters", false),
            ("bugprone-throwing-static-initialization", false),
            ("bugprone-exception-escape", false),
            ("clang-analyzer-core.NullDereference", true),
            ("performance-unnecessary-copy-initialization", true),
            ("modernize-use-nullptr", true),
            ("modernize-use-override", true),
            ("modernize-make-unique", true),
            ("modernize-use-emplace", true),
            ("modernize-use-auto", false),
            ("readability-isolate-declaration", true),
            ("readability-braces-around-statements", false),
        ] {
            assert_eq!(judge(&rec, check), (on, false), "recommended {check}");
        }
        let strict = clang_tidy_config(&lint("[lint]\npreset = \"strict\"\n"));
        for (check, on) in [
            ("readability-braces-around-statements", true),
            ("cppcoreguidelines-avoid-goto", true),
            ("modernize-use-auto", true),
            ("modernize-use-trailing-return-type", false),
            ("readability-identifier-length", false),
            ("bugprone-easily-swappable-parameters", false),
        ] {
            assert_eq!(judge(&strict, check), (on, false), "strict {check}");
        }
    }

    /// The spec's precedence, judged by clang-tidy's last-match-wins over
    /// what is emitted: a specific name beats a wildcard, and at the same
    /// specificity deny beats warn beats allow.
    ///
    /// Mutation: emit specific names before wildcards, or warn after deny,
    /// or allow after warn; this test fails.
    #[test]
    fn allow_warn_deny_follow_the_spec_s_precedence() {
        // The spec's own example.
        let c = clang_tidy_config(&lint(
            "[lint]\nwarn = [\"modernize-*\"]\nallow = [\"modernize-use-auto\"]\n",
        ));
        assert_eq!(judge(&c, "modernize-use-auto"), (false, false));
        assert_eq!(judge(&c, "modernize-loop-convert"), (true, false));

        let c = clang_tidy_config(&lint(
            "[lint]\ndeny = [\"bugprone-*\", \"x-a\"]\nwarn = [\"bugprone-use-after-move\", \"x-a\", \"y-*\"]\n\
                 allow = [\"bugprone-*\", \"y-*\", \"x-a\"]\n",
        ));
        // Specific warn over wildcard deny.
        assert_eq!(judge(&c, "bugprone-use-after-move"), (true, false));
        // Wildcard deny over wildcard allow.
        assert_eq!(judge(&c, "bugprone-macro-parentheses"), (true, true));
        // Same specificity: deny over warn over allow.
        assert_eq!(judge(&c, "x-a"), (true, true));
        assert_eq!(judge(&c, "y-b"), (true, false));

        // A specific allow beats a wildcard deny.
        let c = clang_tidy_config(&lint(
            "[lint]\ndeny = [\"performance-*\"]\nallow = [\"performance-noexcept-move-constructor\"]\n",
        ));
        assert_eq!(
            judge(&c, "performance-noexcept-move-constructor"),
            (false, false)
        );
        assert_eq!(judge(&c, "performance-for-range-copy"), (true, true));
    }

    /// Between wildcards the narrower wins, at any list; a check the preset
    /// excluded comes back only by its name, never by a wildcard
    /// (`dev-tools.md`, "allow / warn / deny").
    ///
    /// Mutation: rank wildcards equally, put the broader one last, or emit
    /// the preset's exclusions before the user's wildcards; this test fails.
    #[test]
    fn narrower_wildcards_win_and_exclusions_need_a_name() {
        let c = clang_tidy_config(&lint(
            "[lint]
preset = \"none\"
deny = [\"modernize-*\"]
allow = [\"modernize-use-*\"]
",
        ));
        assert_eq!(judge(&c, "modernize-use-nullptr"), (false, false));
        assert_eq!(judge(&c, "modernize-loop-convert"), (true, true));
        let c = clang_tidy_config(&lint(
            "[lint]
preset = \"none\"
allow = [\"clang-analyzer-*\"]
deny = [\"clang-analyzer-core.*\"]
",
        ));
        assert_eq!(
            judge(&c, "clang-analyzer-core.NullDereference"),
            (true, true)
        );
        assert_eq!(
            judge(&c, "clang-analyzer-cplusplus.NewDelete"),
            (false, false)
        );

        let c = clang_tidy_config(&lint(
            "[lint]
deny = [\"bugprone-*\"]
",
        ));
        assert_eq!(
            judge(&c, "bugprone-easily-swappable-parameters"),
            (false, false)
        );
        assert_eq!(judge(&c, "bugprone-use-after-move"), (true, true));
        let c = clang_tidy_config(&lint(
            "[lint]
warn = [\"bugprone-easily-swappable-parameters\"]
",
        ));
        assert_eq!(
            judge(&c, "bugprone-easily-swappable-parameters"),
            (true, false)
        );
    }

    /// The file carries the marker, both lists and no header filter.
    ///
    /// Mutation: drop the marker or a key; this test fails.
    #[test]
    fn the_file_holds_both_lists() {
        let text = clang_tidy_file(&lint("[lint]\ndeny = [\"bugprone-*\"]\n"));
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines[0], MARKER);
        assert!(lines[1].starts_with("Checks: '-*,bugprone-*,"), "{text}");
        assert_eq!(lines[2], "WarningsAsErrors: 'bugprone-*'");
        assert_eq!(lines[3], "HeaderFilterRegex: ''");
    }

    /// A runner whose clang-tidy exports one fix, to `file`, and finds
    /// nothing to show.
    struct Exports {
        file: String,
    }

    impl Runner for Exports {
        fn run(
            &self,
            _program: &Path,
            args: &[&OsStr],
            _env: &Env,
        ) -> std::io::Result<cuno_toolchain::Output> {
            for arg in args {
                if let Some(out) = arg.to_string_lossy().strip_prefix("--export-fixes=") {
                    std::fs::write(
                        out,
                        format!(
                            "Diagnostics:
  - Replacements:
      - FilePath: '{}'
",
                            self.file
                        ),
                    )?;
                }
            }
            Ok(cuno_toolchain::Output {
                success: true,
                stdout: Vec::new(),
                stderr: Vec::new(),
            })
        }
    }

    /// Under `--fix`, a source whose fix would change a file cuno may not
    /// write is left unfixed, and the reason given is the file's own: a
    /// link in the package is named as a link, a file outside it as not the
    /// package's (`commands.md`, "`cuno lint`").
    ///
    /// Mutation: ask only whether the file is the package's, or drop the
    /// reason; this test fails.
    #[cfg(windows)]
    #[test]
    fn a_fix_that_would_change_a_link_or_another_s_file_is_not_made() {
        let root = tempfile::tempdir().unwrap();
        let scratch = tempfile::tempdir().unwrap();
        let real = root.path().join("real");
        std::fs::create_dir(&real).unwrap();
        let link = root.path().join("inc");
        let made = std::process::Command::new("cmd")
            .args(["/C", "mklink", "/J"])
            .arg(&link)
            .arg(&real)
            .output()
            .unwrap();
        assert!(made.status.success(), "{made:?}");
        let source = root.path().join("a.cpp");
        std::fs::write(&source, "").unwrap();
        let env = Env::from_pairs([], cuno_core::NameCase::Insensitive);
        let tool = ClangTidy {
            program: Path::new("clang-tidy"),
            config: Path::new("c"),
            root: root.path(),
            env: &env,
            jobs: 1,
            fix: true,
            scratch: scratch.path(),
        };
        let ours = |p: &Path| p.starts_with(root.path());
        let fix = |file: &Path| {
            super::lint(
                std::slice::from_ref(&source),
                &tool,
                &ours,
                &Exports {
                    file: file.display().to_string(),
                },
            )
            .not_fixed
        };
        assert_eq!(
            fix(&link),
            [(
                source.clone(),
                link.clone(),
                "which is a link cuno does not write through".to_owned()
            )]
        );
        let outside = tempfile::tempdir().unwrap();
        let theirs = outside.path().join("v.h");
        std::fs::write(&theirs, "").unwrap();
        assert_eq!(
            fix(&theirs),
            [(
                source.clone(),
                theirs.clone(),
                "which is not the package's".to_owned()
            )]
        );
        std::fs::remove_dir(&link).unwrap();
    }
}