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;
pub const FILE: &str = ".clang-tidy";
pub const MARKER: &str =
"# Generated by cuno from [lint] in cuno.toml, and overwritten: edit cuno.toml instead.";
const RECOMMENDED: &[&str] = &[
"bugprone-*",
"-bugprone-easily-swappable-parameters",
"-bugprone-throwing-static-initialization",
"clang-analyzer-*",
"performance-*",
"modernize-use-nullptr",
"modernize-use-override",
"modernize-make-unique",
"modernize-use-emplace",
"readability-isolate-declaration",
];
const STRICT: &[&str] = &[
"readability-*",
"cppcoreguidelines-*",
"modernize-*",
"-modernize-use-trailing-return-type",
"-readability-identifier-length",
];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TidyConfig {
pub checks: Vec<String>,
pub warnings_as_errors: Vec<String>,
}
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('-'));
#[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,
}
}
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(","),
)
}
pub fn any_check(config: &TidyConfig) -> bool {
config.checks.iter().any(|glob| !glob.starts_with('-'))
}
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 {
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
}
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())
}
pub struct ClangTidy<'a> {
pub program: &'a Path,
pub config: &'a Path,
pub root: &'a Path,
pub env: &'a Env,
pub jobs: usize,
pub fix: bool,
pub scratch: &'a Path,
}
#[derive(Debug, Default)]
pub struct Linted {
pub shown: Vec<u8>,
pub warnings: usize,
pub errors: usize,
pub fixed: usize,
pub failed: Vec<(PathBuf, String)>,
pub not_fixed: Vec<(PathBuf, PathBuf)>,
}
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) = run.foreign {
linted.not_fixed.push((source.clone(), foreign));
}
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);
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);
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);
}
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
}
struct Run {
output: std::io::Result<cuno_toolchain::Output>,
foreign: Option<PathBuf>,
}
#[derive(Clone, Copy)]
enum Mode<'a> {
Show,
Export(&'a Path),
Fix,
}
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);
if let Some(foreign) = targets.iter().find(|t| !ours(&tool.root.join(t))) {
return Run {
output: looked,
foreign: Some(foreign.clone()),
};
}
if targets.is_empty() {
return Run {
output: looked,
foreign: None,
};
}
Run {
output: run_one(source, tool, Mode::Fix, runner),
foreign: None,
}
}
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()
}
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());
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)
}
struct Finding {
path: PathBuf,
error: bool,
check: String,
text: Vec<u8>,
}
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
}
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
}
fn summary(line: &str) -> bool {
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
}
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).
";
#[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);
}
#[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);
}
#[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")
]
);
}
#[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");
}
#[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-*")]
);
}
#[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(""))));
}
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
}
fn judge(config: &TidyConfig, check: &str) -> (bool, bool) {
let on = last_match(&config.checks, check);
(on, on && last_match(&config.warnings_as_errors, check))
}
#[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),
("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}");
}
}
#[test]
fn allow_warn_deny_follow_the_spec_s_precedence() {
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",
));
assert_eq!(judge(&c, "bugprone-use-after-move"), (true, false));
assert_eq!(judge(&c, "bugprone-macro-parentheses"), (true, true));
assert_eq!(judge(&c, "x-a"), (true, true));
assert_eq!(judge(&c, "y-b"), (true, false));
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));
}
#[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)
);
}
#[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: ''");
}
}