Skip to main content

cuno_tools/
tidy.rs

1//! clang-tidy's configuration from `[lint]`
2//! (`docs/en/specs/dev-tools.md`, "`[lint]`").
3
4use std::collections::HashSet;
5use std::ffi::{OsStr, OsString};
6use std::path::{Path, PathBuf};
7use std::sync::Mutex;
8use std::sync::atomic::{AtomicUsize, Ordering};
9
10use cuno_core::Env;
11use cuno_manifest::{Lint, LintPreset};
12use cuno_toolchain::Runner;
13
14/// The file editors read, at the project root.
15pub const FILE: &str = ".clang-tidy";
16
17/// The first line of every `.clang-tidy` cuno writes: a file that does not
18/// start with it is the user's, and is not overwritten
19/// (`docs/en/specs/dev-tools.md`, "Configuration").
20pub const MARKER: &str =
21    "# Generated by cuno from [lint] in Cuno.toml, and overwritten: edit Cuno.toml instead.";
22
23/// `recommended` (`dev-tools.md`, "Contents of the presets").
24const RECOMMENDED: &[&str] = &[
25    "bugprone-*",
26    "-bugprone-easily-swappable-parameters",
27    // Every C++ test suite is a static object built from a lambda, which
28    // this check reads through.
29    "-bugprone-throwing-static-initialization",
30    // With exceptions on (the default), any `main` that prints is a finding:
31    // the stream may throw. An exception that escapes stops the program
32    // loudly; `warn` puts the check back (`dev-tools.md`, "Contents of the
33    // presets").
34    "-bugprone-exception-escape",
35    "clang-analyzer-*",
36    "performance-*",
37    "modernize-use-nullptr",
38    "modernize-use-override",
39    "modernize-make-unique",
40    "modernize-use-emplace",
41    "readability-isolate-declaration",
42];
43
44/// What `strict` adds to `recommended`.
45const STRICT: &[&str] = &[
46    "readability-*",
47    "cppcoreguidelines-*",
48    "modernize-*",
49    "-modernize-use-trailing-return-type",
50    "-readability-identifier-length",
51];
52
53/// clang-tidy's `Checks` and `WarningsAsErrors` for `lint`, each a list of globs that clang-tidy applies in order, the last
54/// that matches a check deciding it.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct TidyConfig {
57    /// Which checks run.
58    pub checks: Vec<String>,
59    /// Which of those are errors.
60    pub warnings_as_errors: Vec<String>,
61}
62
63/// The configuration for `lint` (`dev-tools.md`, "allow / warn / deny"),
64/// ordered so that clang-tidy's last-match-wins gives the spec's
65/// precedence: the preset's checks; the user's wildcards, broadest first;
66/// the preset's exclusions, which only a name brings back; the user's
67/// names. At each rank `allow`, then `warn`, then `deny`, so the stronger
68/// wins. C++-only checks in a C package are left to clang-tidy, which does
69/// not run them on C.
70pub fn clang_tidy_config(lint: &Lint) -> TidyConfig {
71    let preset: Vec<&str> = match lint.preset {
72        LintPreset::None => Vec::new(),
73        LintPreset::Recommended => RECOMMENDED.to_vec(),
74        LintPreset::Strict => RECOMMENDED.iter().chain(STRICT).copied().collect(),
75    };
76    let (excluded, enabled): (Vec<&str>, Vec<&str>) =
77        preset.into_iter().partition(|g| g.starts_with('-'));
78
79    // Every user pattern with its rank: wildcards by the length before `*`
80    // (narrower later), names last; then allow < warn < deny.
81    #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
82    enum List {
83        Allow,
84        Warn,
85        Deny,
86    }
87    let mut written: Vec<(usize, List, &str)> = Vec::new();
88    for (list, patterns) in [
89        (List::Allow, &lint.allow),
90        (List::Warn, &lint.warn),
91        (List::Deny, &lint.deny),
92    ] {
93        for pattern in patterns {
94            let rank = pattern.find('*').unwrap_or(usize::MAX);
95            written.push((rank, list, pattern));
96        }
97    }
98    written.sort_by_key(|(rank, list, _)| (*rank, *list));
99    let (wildcards, names): (Vec<_>, Vec<_>) = written
100        .into_iter()
101        .partition(|(rank, _, _)| *rank != usize::MAX);
102
103    let mut checks: Vec<String> = vec!["-*".to_owned()];
104    checks.extend(enabled.iter().map(|g| (*g).to_owned()));
105    let mut errors: Vec<String> = Vec::new();
106    let mut add = |checks: &mut Vec<String>, (_, list, pattern): (usize, List, &str)| {
107        match list {
108            List::Allow => checks.push(format!("-{pattern}")),
109            List::Warn | List::Deny => checks.push(pattern.to_owned()),
110        }
111        match list {
112            List::Allow | List::Warn => errors.push(format!("-{pattern}")),
113            List::Deny => errors.push(pattern.to_owned()),
114        }
115    };
116    for w in wildcards {
117        add(&mut checks, w);
118    }
119    checks.extend(excluded.iter().map(|g| (*g).to_owned()));
120    for n in names {
121        add(&mut checks, n);
122    }
123    TidyConfig {
124        checks,
125        warnings_as_errors: errors,
126    }
127}
128
129/// `.clang-tidy` for `lint`. With an empty
130/// `HeaderFilterRegex`, clang-tidy reports no header's findings unless
131/// asked on its command line: `cuno lint` asks, and keeps the package's.
132pub fn clang_tidy_file(lint: &Lint) -> String {
133    let config = clang_tidy_config(lint);
134    format!(
135        "{MARKER}\nChecks: '{}'\nWarningsAsErrors: '{}'\nHeaderFilterRegex: ''\nFormatStyle: file\n",
136        config.checks.join(","),
137        config.warnings_as_errors.join(","),
138    )
139}
140
141/// Whether `config` turns any check on; clang-tidy refuses to run with
142/// none (`docs/en/specs/commands.md`, "`cuno lint`").
143pub fn any_check(config: &TidyConfig) -> bool {
144    config.checks.iter().any(|glob| !glob.starts_with('-'))
145}
146
147/// The names in `lint`'s lists that match no check in `known`, with the
148/// list each is in: a misspelt `deny` would otherwise do nothing, silently.
149pub fn unknown_names<'a>(lint: &'a Lint, known: &[String]) -> Vec<(&'static str, &'a str)> {
150    let mut unknown = Vec::new();
151    for (list, names) in [
152        ("lint.allow", &lint.allow),
153        ("lint.warn", &lint.warn),
154        ("lint.deny", &lint.deny),
155    ] {
156        for name in names {
157            // The compiler's own warnings, which `--list-checks` does not
158            // list, are checks all the same.
159            if name.starts_with("clang-diagnostic-") {
160                continue;
161            }
162            let found = match name.find('*') {
163                Some(star) => {
164                    let (before, after) = (&name[..star], &name[star + 1..]);
165                    known.iter().any(|check| {
166                        check.len() >= before.len() + after.len()
167                            && check.starts_with(before)
168                            && check.ends_with(after)
169                    })
170                }
171                None => known.iter().any(|check| check == name),
172            };
173            if !found {
174                unknown.push((list, name.as_str()));
175            }
176        }
177    }
178    unknown
179}
180
181/// The checks `program` has, from `--list-checks --checks=*`.
182pub fn known_checks(
183    program: &Path,
184    env: &Env,
185    runner: &dyn Runner,
186) -> std::io::Result<Vec<String>> {
187    let args: [&OsStr; 2] = ["--list-checks".as_ref(), "--checks=*".as_ref()];
188    let output = runner.run(program, &args, env)?;
189    if !output.success {
190        return Err(std::io::Error::other("clang-tidy did not list its checks"));
191    }
192    Ok(String::from_utf8_lossy(&output.stdout)
193        .lines()
194        .map(str::trim)
195        .filter(|line| !line.is_empty() && !line.ends_with(':'))
196        .map(str::to_owned)
197        .collect())
198}
199
200/// clang-tidy, and what it is run with.
201pub struct ClangTidy<'a> {
202    /// The executable selection chose.
203    pub program: &'a Path,
204    /// The `.clang-tidy` to analyse with, whatever is at the root.
205    pub config: &'a Path,
206    /// The directory holding compile_commands.json; clang-tidy runs there.
207    pub root: &'a Path,
208    /// The compiler's environment.
209    pub env: &'a Env,
210    /// How many sources at once (one under `fix`).
211    pub jobs: usize,
212    /// `--fix`: fix the sources themselves, headers left alone.
213    pub fix: bool,
214    /// Where `--fix` writes the fixes it looks at first.
215    pub scratch: &'a Path,
216}
217
218/// What analysing found.
219#[derive(Debug, Default)]
220pub struct Linted {
221    /// The findings to show, each once, as clang-tidy printed them, source
222    /// by source in the order given.
223    pub shown: Vec<u8>,
224    /// How many of those are warnings.
225    pub warnings: usize,
226    /// How many are errors (`deny`, or a compile error).
227    pub errors: usize,
228    /// How many `--fix` fixed; neither warnings nor errors any more.
229    pub fixed: usize,
230    /// Sources clang-tidy could not analyse, with why.
231    pub failed: Vec<(PathBuf, String)>,
232    /// Under `--fix`, sources left unfixed because a fix would change the
233    /// file given, which cuno may not write, and why
234    /// ([`crate::write::Refusal`]).
235    pub not_fixed: Vec<(PathBuf, PathBuf, String)>,
236}
237
238/// Analyses `sources` with `tool`, keeping only the findings in files
239/// `ours` accepts (the package's, not excluded), each once
240/// (`docs/en/specs/commands.md`, "`cuno lint`").
241pub fn lint(
242    sources: &[PathBuf],
243    tool: &ClangTidy<'_>,
244    ours: &(dyn Fn(&Path) -> bool + Sync),
245    runner: &(dyn Runner + Sync),
246) -> Linted {
247    let next = AtomicUsize::new(0);
248    let runs: Mutex<Vec<(usize, Run)>> = Mutex::new(Vec::new());
249    let jobs = if tool.fix { 1 } else { tool.jobs };
250    std::thread::scope(|scope| {
251        for _ in 0..jobs.clamp(1, sources.len().max(1)) {
252            scope.spawn(|| {
253                loop {
254                    let i = next.fetch_add(1, Ordering::SeqCst);
255                    let Some(source) = sources.get(i) else { break };
256                    let run = if tool.fix {
257                        fix_one(i, source, tool, ours, runner)
258                    } else {
259                        Run {
260                            output: run_one(source, tool, Mode::Show, runner),
261                            foreign: None,
262                        }
263                    };
264                    runs.lock().unwrap().push((i, run));
265                }
266            });
267        }
268    });
269    let mut runs = runs.into_inner().unwrap();
270    runs.sort_by_key(|(i, _)| *i);
271    let mut linted = Linted::default();
272    let mut seen: HashSet<Vec<u8>> = HashSet::new();
273    for (i, run) in runs {
274        let source = &sources[i];
275        if let Some((foreign, why)) = run.foreign {
276            linted.not_fixed.push((source.clone(), foreign, why));
277        }
278        let output = match run.output {
279            Ok(output) => output,
280            Err(e) => {
281                linted.failed.push((source.clone(), e.to_string()));
282                continue;
283            }
284        };
285        let stderr = String::from_utf8_lossy(&output.stderr);
286        // A fix clang-tidy could not write is not a fix.
287        let unwritten = stderr
288            .lines()
289            .find(|line| line.contains("unable to overwrite file"));
290        if let Some(line) = unwritten {
291            linted.failed.push((source.clone(), line.trim().to_owned()));
292        }
293        let mut explained = false;
294        for finding in findings(&output.stdout) {
295            let path = tool.root.join(&finding.path);
296            // A compile error is shown wherever it is: the source could not
297            // be analysed. Another file's other findings are not the
298            // package's, though they may be why clang-tidy failed.
299            let compile_error = finding.error && finding.check.contains("clang-diagnostic-");
300            if !compile_error && !ours(&path) {
301                explained |= finding.error;
302                continue;
303            }
304            explained |= finding.error;
305            if !seen.insert(finding.text.clone()) {
306                continue;
307            }
308            let fixed = unwritten.is_none()
309                && String::from_utf8_lossy(&finding.text).contains("FIX-IT applied");
310            if fixed {
311                linted.fixed += 1;
312            } else if finding.error {
313                linted.errors += 1;
314            } else {
315                linted.warnings += 1;
316            }
317            linted.shown.extend_from_slice(&finding.text);
318        }
319        // A failure no error finding explains is never a pass.
320        if !output.success && !explained && unwritten.is_none() {
321            let said = stderr
322                .lines()
323                .find(|line| !line.trim().is_empty())
324                .unwrap_or("clang-tidy failed and said nothing");
325            linted.failed.push((source.clone(), said.trim().to_owned()));
326        }
327    }
328    linted
329}
330
331/// One source's analysis, and under `--fix` a file outside the package a
332/// fix would have changed, when one did and nothing was fixed.
333struct Run {
334    output: std::io::Result<cuno_toolchain::Output>,
335    foreign: Option<(PathBuf, String)>,
336}
337
338/// How clang-tidy is run on a source.
339#[derive(Clone, Copy)]
340enum Mode<'a> {
341    /// Findings shown, headers' included.
342    Show,
343    /// The fixes written to the file given, nothing changed.
344    Export(&'a Path),
345    /// The fixes applied.
346    Fix,
347}
348
349/// `--fix` for one source: the fixes clang-tidy would make are looked at
350/// first, and applied only when every one is in the package's files; a fix
351/// to a declaration in another package's header would otherwise rewrite
352/// that header.
353fn fix_one(
354    i: usize,
355    source: &Path,
356    tool: &ClangTidy<'_>,
357    ours: &(dyn Fn(&Path) -> bool + Sync),
358    runner: &dyn Runner,
359) -> Run {
360    let exported = tool.scratch.join(format!("fixes-{i}.yaml"));
361    let looked = run_one(source, tool, Mode::Export(&exported), runner);
362    let targets = std::fs::read_to_string(&exported)
363        .map(|text| fix_targets(&text))
364        .unwrap_or_default();
365    let _ = std::fs::remove_file(&exported);
366    // Every file a fix would change must be one cuno may write: the
367    // package's, a file, not a link (`write::code`); the first that is not
368    // is named, with why.
369    let refused = targets.iter().find_map(|t| {
370        crate::write::code(&tool.root.join(t), ours)
371            .err()
372            .map(|why| (t.clone(), why.which()))
373    });
374    if let Some(foreign) = refused {
375        return Run {
376            output: looked,
377            foreign: Some(foreign),
378        };
379    }
380    if targets.is_empty() {
381        return Run {
382            output: looked,
383            foreign: None,
384        };
385    }
386    Run {
387        output: run_one(source, tool, Mode::Fix, runner),
388        foreign: None,
389    }
390}
391
392/// The files the fixes in clang-tidy's exported YAML would change: every
393/// replacement's `FilePath`.
394fn fix_targets(yaml: &str) -> Vec<PathBuf> {
395    yaml.lines()
396        .filter_map(|line| line.trim_start().strip_prefix("- FilePath:"))
397        .map(|value| PathBuf::from(unquote(value.trim())))
398        .collect()
399}
400
401/// A YAML scalar as LLVM writes a path: plain, `'...'` with `''` for a
402/// quote, or `"..."` with backslash escapes.
403fn unquote(value: &str) -> String {
404    if let Some(inner) = value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')) {
405        inner.replace("''", "'")
406    } else if let Some(inner) = value.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
407        let mut out = String::new();
408        let mut chars = inner.chars();
409        while let Some(c) = chars.next() {
410            if c == '\\' {
411                out.extend(chars.next());
412            } else {
413                out.push(c);
414            }
415        }
416        out
417    } else {
418        value.to_owned()
419    }
420}
421
422fn run_one(
423    source: &Path,
424    tool: &ClangTidy<'_>,
425    mode: Mode<'_>,
426    runner: &dyn Runner,
427) -> std::io::Result<cuno_toolchain::Output> {
428    let config = format!("--config-file={}", tool.config.display());
429    let database = format!("-p={}", tool.root.display());
430    // Fixing, no header's finding is shown: headers are not fixed.
431    let headers = match mode {
432        Mode::Show => "--header-filter=.*",
433        Mode::Export(_) | Mode::Fix => "--header-filter=^$",
434    };
435    let mut args: Vec<OsString> = vec![
436        config.into(),
437        database.into(),
438        headers.into(),
439        "--quiet".into(),
440    ];
441    match mode {
442        Mode::Show => {}
443        Mode::Export(file) => {
444            let mut arg = OsString::from("--export-fixes=");
445            arg.push(file);
446            args.push(arg);
447        }
448        Mode::Fix => args.push("--fix".into()),
449    }
450    args.push(source.into());
451    let args: Vec<&OsStr> = args.iter().map(OsString::as_os_str).collect();
452    runner.run_in(tool.program, &args, tool.env, tool.root)
453}
454
455/// One finding as clang-tidy printed it: its first line and the lines
456/// after it (the code, the caret, its notes) up to the next finding.
457struct Finding {
458    path: PathBuf,
459    error: bool,
460    /// The bracketed check names at the end of its first line.
461    check: String,
462    text: Vec<u8>,
463}
464
465/// The findings in clang-tidy's output; summary lines are not findings.
466fn findings(stdout: &[u8]) -> Vec<Finding> {
467    let mut found: Vec<Finding> = Vec::new();
468    for line in stdout.split_inclusive(|b| *b == b'\n') {
469        let text = String::from_utf8_lossy(line);
470        if let Some((path, error)) = finding_head(&text) {
471            let check = text
472                .trim_end()
473                .rsplit_once('[')
474                .map(|(_, rest)| rest.trim_end_matches(']').to_owned())
475                .unwrap_or_default();
476            found.push(Finding {
477                path,
478                error,
479                check,
480                text: line.to_vec(),
481            });
482        } else if summary(&text) {
483            continue;
484        } else if let Some(last) = found.last_mut() {
485            last.text.extend_from_slice(line);
486        }
487    }
488    found
489}
490
491/// The path and severity of a line that starts a finding:
492/// `path:line:column: warning: ...` or `... error: ...`, at the start of
493/// the line: an excerpt of code, indented, never starts one.
494fn finding_head(line: &str) -> Option<(PathBuf, bool)> {
495    if line.starts_with(char::is_whitespace) {
496        return None;
497    }
498    for (marker, error) in [(": warning: ", false), (": error: ", true)] {
499        let Some(at) = line.find(marker) else {
500            continue;
501        };
502        let mut parts = line[..at].rsplitn(3, ':');
503        let column = parts.next()?;
504        let row = parts.next()?;
505        let path = parts.next()?;
506        if column.parse::<u32>().is_ok() && row.parse::<u32>().is_ok() && !path.is_empty() {
507            return Some((PathBuf::from(path), error));
508        }
509    }
510    None
511}
512
513/// clang-tidy's tallies and advice, which `cuno lint` does not show.
514fn summary(line: &str) -> bool {
515    // clang-tidy prints these at the start of a line; an excerpt of code is
516    // indented, whatever it says.
517    if line.starts_with(char::is_whitespace) {
518        return false;
519    }
520    let line = line.trim_end();
521    line.ends_with(" generated.")
522        || line.starts_with("Suppressed ")
523        || line.starts_with("Use -header-filter")
524        || line.starts_with("Found compiler error")
525        || line.starts_with("Error while processing")
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531
532    fn lint(extra: &str) -> Lint {
533        let toml = format!("[package]\nname = \"app\"\nversion = \"0.1.0\"\n{extra}");
534        let root = std::path::Path::new("/p");
535        cuno_manifest::parse_manifest(&toml, &root.join("Cuno.toml"), root)
536            .unwrap()
537            .value
538            .lint
539    }
540
541    /// A clang-tidy that prints `stdout` and succeeds or not, whatever it is
542    /// asked.
543    struct Answers {
544        stdout: &'static str,
545        success: bool,
546    }
547
548    impl Runner for Answers {
549        fn run(
550            &self,
551            _program: &Path,
552            _args: &[&OsStr],
553            _env: &Env,
554        ) -> std::io::Result<cuno_toolchain::Output> {
555            Ok(cuno_toolchain::Output {
556                success: self.success,
557                stdout: self.stdout.as_bytes().to_vec(),
558                stderr: b"\nboom\n".to_vec(),
559            })
560        }
561    }
562
563    fn analyse(answers: &Answers, sources: &[&str]) -> Linted {
564        let env = Env::from_pairs([], cuno_core::NameCase::Insensitive);
565        let root = Path::new("/p");
566        let tool = ClangTidy {
567            program: Path::new("clang-tidy"),
568            config: Path::new("c"),
569            root,
570            env: &env,
571            jobs: 2,
572            fix: false,
573            scratch: Path::new("s"),
574        };
575        let sources: Vec<PathBuf> = sources.iter().map(|s| root.join(s)).collect();
576        let ours = |p: &Path| !p.to_string_lossy().contains("vendor");
577        super::lint(&sources, &tool, &ours, answers)
578    }
579
580    const OUTPUT: &str = "\
581/p/src/a.cpp:3:14: warning: use nullptr [modernize-use-nullptr]
582    3 |     int* p = 0;
583      |              ^
5841 warning generated.
585/p/src/a.h:1:1: error: bad [bugprone-x,-warnings-as-errors]
586/p/src/a.h:1:1: note: here
587/p/vendor/v.h:2:2: warning: theirs [bugprone-y]
5882 warnings generated.
589Suppressed 4 warnings (4 in non-user code).
590";
591
592    /// Each finding is kept with its lines, counted by severity, shown once
593    /// though two sources print it, and dropped outside the package;
594    /// clang-tidy's tallies are not shown.
595    ///
596    /// Mutation: keep a summary line, keep another package's finding, show
597    /// a repeat, or count an error as a warning; this test fails.
598    #[test]
599    fn findings_are_kept_once_and_only_the_package_s() {
600        let linted = analyse(
601            &Answers {
602                stdout: OUTPUT,
603                success: false,
604            },
605            &["src/a.cpp", "src/b.cpp"],
606        );
607        let shown = String::from_utf8(linted.shown).unwrap();
608        assert_eq!(
609            shown,
610            "/p/src/a.cpp:3:14: warning: use nullptr [modernize-use-nullptr]\n    3 |     int* p = 0;\n      |              ^\n\
611             /p/src/a.h:1:1: error: bad [bugprone-x,-warnings-as-errors]\n/p/src/a.h:1:1: note: here\n",
612        );
613        assert_eq!((linted.warnings, linted.errors), (1, 1));
614        assert!(linted.failed.is_empty(), "{:?}", linted.failed);
615    }
616
617    /// A compile error is shown and counted in any file, the package's or
618    /// not; another file's deny finding is not shown, but explains why
619    /// clang-tidy failed; an indented excerpt that reads like a finding, or
620    /// like a tally, is part of the finding above it.
621    ///
622    /// Mutation: drop a foreign compile error, let a dropped one explain a
623    /// failure, take an indented line for a finding, or drop an indented
624    /// line ending in "generated."; this test fails.
625    #[test]
626    fn compile_errors_count_anywhere_and_excerpts_stay_whole() {
627        let linted = analyse(
628            &Answers {
629                stdout: "\
630/p/vendor/v.h:1:10: error: 'nope.h' file not found [clang-diagnostic-error]
631/p/src/a.cpp:2:5: warning: w [bugprone-x]
632    2 |     puts(\"a.c:1:2: error: x\"); // all generated.
633      |     ^
634",
635                success: false,
636            },
637            &["src/a.cpp"],
638        );
639        let shown = String::from_utf8(linted.shown).unwrap();
640        assert!(
641            shown.starts_with("/p/vendor/v.h:1:10: error: 'nope.h'"),
642            "{shown}"
643        );
644        assert!(
645            shown.contains("// all generated.\n      |     ^\n"),
646            "{shown}"
647        );
648        assert_eq!((linted.warnings, linted.errors), (1, 1));
649        assert!(linted.failed.is_empty(), "{:?}", linted.failed);
650
651        let linted = analyse(
652            &Answers {
653                stdout: "/p/vendor/v.h:1:1: error: theirs [bugprone-y,-warnings-as-errors]\n",
654                success: false,
655            },
656            &["src/a.cpp"],
657        );
658        assert!(linted.shown.is_empty());
659        assert_eq!(linted.errors, 0);
660        assert!(linted.failed.is_empty(), "{:?}", linted.failed);
661    }
662
663    /// The files exported fixes would change are every replacement's path,
664    /// unquoted as LLVM writes it.
665    ///
666    /// Mutation: read the diagnostic's own path, or leave quotes in; this
667    /// test fails.
668    #[test]
669    fn fix_targets_are_the_replacements_paths() {
670        let yaml = "\
671Diagnostics:
672  - DiagnosticName:  x
673    DiagnosticMessage:
674      FilePath:        'C:\\p\\src\\a.cpp'
675      Replacements:
676        - FilePath:        'C:\\p\\src\\a.cpp'
677          Offset:          1
678        - FilePath:        'C:\\v\\it''s.h'
679          Offset:          2
680";
681        assert_eq!(
682            fix_targets(yaml),
683            [
684                PathBuf::from("C:\\p\\src\\a.cpp"),
685                PathBuf::from("C:\\v\\it's.h")
686            ]
687        );
688    }
689
690    /// A clang-tidy that fails with no error finding to explain it is a
691    /// failure of that source, never a pass.
692    ///
693    /// Mutation: treat a failure without findings as success; this test
694    /// fails.
695    #[test]
696    fn an_unexplained_failure_is_reported() {
697        let linted = analyse(
698            &Answers {
699                stdout: "",
700                success: false,
701            },
702            &["src/a.cpp"],
703        );
704        assert_eq!(linted.failed.len(), 1);
705        assert_eq!(linted.failed[0].1, "boom");
706    }
707
708    /// A name, or a wildcard, that matches no check clang-tidy has is
709    /// reported with its list.
710    ///
711    /// Mutation: accept any wildcard, or match names by prefix; this test
712    /// fails.
713    #[test]
714    fn unknown_names_are_found() {
715        let known: Vec<String> = ["bugprone-use-after-move", "modernize-use-nullptr"]
716            .map(str::to_owned)
717            .to_vec();
718        let l = lint(
719            "[lint]\nallow = [\"modernize-*\", \"clang-diagnostic-unused-variable\"]\nwarn = [\"bugprone-use\"]\ndeny = [\"nope-*\", \"modernize-use-nullptr\"]\n",
720        );
721        assert_eq!(
722            unknown_names(&l, &known),
723            [("lint.warn", "bugprone-use"), ("lint.deny", "nope-*")]
724        );
725    }
726
727    /// No check on is `preset = "none"` with nothing written.
728    ///
729    /// Mutation: count a negation as a check; this test fails.
730    #[test]
731    fn none_with_nothing_written_enables_nothing() {
732        assert!(!any_check(&clang_tidy_config(&lint(
733            "[lint]\npreset = \"none\"\n"
734        ))));
735        assert!(any_check(&clang_tidy_config(&lint(
736            "[lint]\npreset = \"none\"\nwarn = [\"bugprone-*\"]\n"
737        ))));
738        assert!(any_check(&clang_tidy_config(&lint(""))));
739    }
740
741    /// clang-tidy's own rule: the last glob that matches decides.
742    fn last_match(globs: &[String], check: &str) -> bool {
743        let mut on = false;
744        for glob in globs {
745            let (negated, pattern) = match glob.strip_prefix('-') {
746                Some(rest) => (true, rest),
747                None => (false, glob.as_str()),
748            };
749            let matches = match pattern.strip_suffix('*') {
750                Some(prefix) => check.starts_with(prefix),
751                None => check == pattern,
752            };
753            if matches {
754                on = !negated;
755            }
756        }
757        on
758    }
759
760    /// Whether `check` runs, and whether it is an error.
761    fn judge(config: &TidyConfig, check: &str) -> (bool, bool) {
762        let on = last_match(&config.checks, check);
763        (on, on && last_match(&config.warnings_as_errors, check))
764    }
765
766    /// Each preset turns on what the spec lists and leaves out its
767    /// exclusions; `none` turns on nothing.
768    ///
769    /// Mutation: drop a glob or an exclusion from a preset; this test fails.
770    #[test]
771    fn presets_hold_what_the_spec_lists() {
772        let none = clang_tidy_config(&lint("[lint]\npreset = \"none\"\n"));
773        assert_eq!(none.checks, ["-*"]);
774        let rec = clang_tidy_config(&lint(""));
775        for (check, on) in [
776            ("bugprone-use-after-move", true),
777            ("bugprone-easily-swappable-parameters", false),
778            ("bugprone-throwing-static-initialization", false),
779            ("bugprone-exception-escape", false),
780            ("clang-analyzer-core.NullDereference", true),
781            ("performance-unnecessary-copy-initialization", true),
782            ("modernize-use-nullptr", true),
783            ("modernize-use-override", true),
784            ("modernize-make-unique", true),
785            ("modernize-use-emplace", true),
786            ("modernize-use-auto", false),
787            ("readability-isolate-declaration", true),
788            ("readability-braces-around-statements", false),
789        ] {
790            assert_eq!(judge(&rec, check), (on, false), "recommended {check}");
791        }
792        let strict = clang_tidy_config(&lint("[lint]\npreset = \"strict\"\n"));
793        for (check, on) in [
794            ("readability-braces-around-statements", true),
795            ("cppcoreguidelines-avoid-goto", true),
796            ("modernize-use-auto", true),
797            ("modernize-use-trailing-return-type", false),
798            ("readability-identifier-length", false),
799            ("bugprone-easily-swappable-parameters", false),
800        ] {
801            assert_eq!(judge(&strict, check), (on, false), "strict {check}");
802        }
803    }
804
805    /// The spec's precedence, judged by clang-tidy's last-match-wins over
806    /// what is emitted: a specific name beats a wildcard, and at the same
807    /// specificity deny beats warn beats allow.
808    ///
809    /// Mutation: emit specific names before wildcards, or warn after deny,
810    /// or allow after warn; this test fails.
811    #[test]
812    fn allow_warn_deny_follow_the_spec_s_precedence() {
813        // The spec's own example.
814        let c = clang_tidy_config(&lint(
815            "[lint]\nwarn = [\"modernize-*\"]\nallow = [\"modernize-use-auto\"]\n",
816        ));
817        assert_eq!(judge(&c, "modernize-use-auto"), (false, false));
818        assert_eq!(judge(&c, "modernize-loop-convert"), (true, false));
819
820        let c = clang_tidy_config(&lint(
821            "[lint]\ndeny = [\"bugprone-*\", \"x-a\"]\nwarn = [\"bugprone-use-after-move\", \"x-a\", \"y-*\"]\n\
822                 allow = [\"bugprone-*\", \"y-*\", \"x-a\"]\n",
823        ));
824        // Specific warn over wildcard deny.
825        assert_eq!(judge(&c, "bugprone-use-after-move"), (true, false));
826        // Wildcard deny over wildcard allow.
827        assert_eq!(judge(&c, "bugprone-macro-parentheses"), (true, true));
828        // Same specificity: deny over warn over allow.
829        assert_eq!(judge(&c, "x-a"), (true, true));
830        assert_eq!(judge(&c, "y-b"), (true, false));
831
832        // A specific allow beats a wildcard deny.
833        let c = clang_tidy_config(&lint(
834            "[lint]\ndeny = [\"performance-*\"]\nallow = [\"performance-noexcept-move-constructor\"]\n",
835        ));
836        assert_eq!(
837            judge(&c, "performance-noexcept-move-constructor"),
838            (false, false)
839        );
840        assert_eq!(judge(&c, "performance-for-range-copy"), (true, true));
841    }
842
843    /// Between wildcards the narrower wins, at any list; a check the preset
844    /// excluded comes back only by its name, never by a wildcard
845    /// (`dev-tools.md`, "allow / warn / deny").
846    ///
847    /// Mutation: rank wildcards equally, put the broader one last, or emit
848    /// the preset's exclusions before the user's wildcards; this test fails.
849    #[test]
850    fn narrower_wildcards_win_and_exclusions_need_a_name() {
851        let c = clang_tidy_config(&lint(
852            "[lint]
853preset = \"none\"
854deny = [\"modernize-*\"]
855allow = [\"modernize-use-*\"]
856",
857        ));
858        assert_eq!(judge(&c, "modernize-use-nullptr"), (false, false));
859        assert_eq!(judge(&c, "modernize-loop-convert"), (true, true));
860        let c = clang_tidy_config(&lint(
861            "[lint]
862preset = \"none\"
863allow = [\"clang-analyzer-*\"]
864deny = [\"clang-analyzer-core.*\"]
865",
866        ));
867        assert_eq!(
868            judge(&c, "clang-analyzer-core.NullDereference"),
869            (true, true)
870        );
871        assert_eq!(
872            judge(&c, "clang-analyzer-cplusplus.NewDelete"),
873            (false, false)
874        );
875
876        let c = clang_tidy_config(&lint(
877            "[lint]
878deny = [\"bugprone-*\"]
879",
880        ));
881        assert_eq!(
882            judge(&c, "bugprone-easily-swappable-parameters"),
883            (false, false)
884        );
885        assert_eq!(judge(&c, "bugprone-use-after-move"), (true, true));
886        let c = clang_tidy_config(&lint(
887            "[lint]
888warn = [\"bugprone-easily-swappable-parameters\"]
889",
890        ));
891        assert_eq!(
892            judge(&c, "bugprone-easily-swappable-parameters"),
893            (true, false)
894        );
895    }
896
897    /// The file carries the marker, both lists and no header filter.
898    ///
899    /// Mutation: drop the marker or a key; this test fails.
900    #[test]
901    fn the_file_holds_both_lists() {
902        let text = clang_tidy_file(&lint("[lint]\ndeny = [\"bugprone-*\"]\n"));
903        let lines: Vec<&str> = text.lines().collect();
904        assert_eq!(lines[0], MARKER);
905        assert!(lines[1].starts_with("Checks: '-*,bugprone-*,"), "{text}");
906        assert_eq!(lines[2], "WarningsAsErrors: 'bugprone-*'");
907        assert_eq!(lines[3], "HeaderFilterRegex: ''");
908    }
909
910    /// A runner whose clang-tidy exports one fix, to `file`, and finds
911    /// nothing to show.
912    struct Exports {
913        file: String,
914    }
915
916    impl Runner for Exports {
917        fn run(
918            &self,
919            _program: &Path,
920            args: &[&OsStr],
921            _env: &Env,
922        ) -> std::io::Result<cuno_toolchain::Output> {
923            for arg in args {
924                if let Some(out) = arg.to_string_lossy().strip_prefix("--export-fixes=") {
925                    std::fs::write(
926                        out,
927                        format!(
928                            "Diagnostics:
929  - Replacements:
930      - FilePath: '{}'
931",
932                            self.file
933                        ),
934                    )?;
935                }
936            }
937            Ok(cuno_toolchain::Output {
938                success: true,
939                stdout: Vec::new(),
940                stderr: Vec::new(),
941            })
942        }
943    }
944
945    /// Under `--fix`, a source whose fix would change a file cuno may not
946    /// write is left unfixed, and the reason given is the file's own: a
947    /// link in the package is named as a link, a file outside it as not the
948    /// package's (`commands.md`, "`cuno lint`").
949    ///
950    /// Mutation: ask only whether the file is the package's, or drop the
951    /// reason; this test fails.
952    #[cfg(windows)]
953    #[test]
954    fn a_fix_that_would_change_a_link_or_another_s_file_is_not_made() {
955        let root = tempfile::tempdir().unwrap();
956        let scratch = tempfile::tempdir().unwrap();
957        let real = root.path().join("real");
958        std::fs::create_dir(&real).unwrap();
959        let link = root.path().join("inc");
960        let made = std::process::Command::new("cmd")
961            .args(["/C", "mklink", "/J"])
962            .arg(&link)
963            .arg(&real)
964            .output()
965            .unwrap();
966        assert!(made.status.success(), "{made:?}");
967        let source = root.path().join("a.cpp");
968        std::fs::write(&source, "").unwrap();
969        let env = Env::from_pairs([], cuno_core::NameCase::Insensitive);
970        let tool = ClangTidy {
971            program: Path::new("clang-tidy"),
972            config: Path::new("c"),
973            root: root.path(),
974            env: &env,
975            jobs: 1,
976            fix: true,
977            scratch: scratch.path(),
978        };
979        let ours = |p: &Path| p.starts_with(root.path());
980        let fix = |file: &Path| {
981            super::lint(
982                std::slice::from_ref(&source),
983                &tool,
984                &ours,
985                &Exports {
986                    file: file.display().to_string(),
987                },
988            )
989            .not_fixed
990        };
991        assert_eq!(
992            fix(&link),
993            [(
994                source.clone(),
995                link.clone(),
996                "which is a link cuno does not write through".to_owned()
997            )]
998        );
999        let outside = tempfile::tempdir().unwrap();
1000        let theirs = outside.path().join("v.h");
1001        std::fs::write(&theirs, "").unwrap();
1002        assert_eq!(
1003            fix(&theirs),
1004            [(
1005                source.clone(),
1006                theirs.clone(),
1007                "which is not the package's".to_owned()
1008            )]
1009        );
1010        std::fs::remove_dir(&link).unwrap();
1011    }
1012}