diff --git a/benchmark/benchmark.nu b/benchmark/benchmark.nu index 93d80f72..eb1ad3ce 100644 --- a/benchmark/benchmark.nu +++ b/benchmark/benchmark.nu @@ -115,12 +115,15 @@ export def run-hyperfine [ rust_bin: string, # path to rust binary of cpp-linter (v2.x) prev_rust_bin?: string, # path to previous commit's release build of rust binary (v2.x) ] { + # `--prepare` empties the clang-tidy result cache, so every run measures clang-tidy. + # It runs nushell's `rm`, since Windows has no `rm` command. mut hyperfine_args = [ --shell none --output pipe --export-json ../benchmark.json --export-markdown ../benchmark.md --warmup 1 + --prepare "nu --no-config-file --commands 'rm --recursive --force .cpp-linter-cache/tidy'" --style color --runs ] diff --git a/cpp-linter/src/clang_tools/clang_tidy/cache.rs b/cpp-linter/src/clang_tools/clang_tidy/cache.rs new file mode 100644 index 00000000..690dbea4 --- /dev/null +++ b/cpp-linter/src/clang_tools/clang_tidy/cache.rs @@ -0,0 +1,1374 @@ +//! A cache of clang-tidy results. +//! +//! clang-tidy is slow, and most runs check files that did not change since the last +//! run. So the results of each run are kept in the cache directory +//! ([`ClangParams::CACHE_DIR`]), one entry per checked file. The next run reuses an +//! entry if nothing that could change clang-tidy's results has changed. Like the +//! direct mode of ccache, this is checked in two steps: +//! +//! 1. The entry's key is a hash of the clang-tidy version, the clang-tidy arguments +//! (including `--line-filter`), the compilation database, the `.clang-tidy` and +//! `.clang-format` files that apply to the checked file, and the checked file +//! itself. +//! 2. The entry also lists every header that the checked file opened in the last run +//! (as printed by `--extra-arg=-H`). The entry is only used if none of these +//! headers changed either. +//! +//! The cache is skipped (but clang-tidy still runs) when the clang-tidy version is +//! unknown, the compilation database uses the MSVC driver (which has no `-H`), or a +//! header is forced in with `-include` or `-imacros` without a precompiled header +//! (`-H` does not list the headers that such a header includes). +//! +//! Known limits: a new header that shadows another one in the include path (or that +//! `__has_include` looked for), and changes to environment variables, do not +//! invalidate an entry. + +use std::{ + collections::{HashMap, HashSet}, + fs, + path::{Component, Path, PathBuf}, + process::Command, + sync::{Arc, LazyLock, Mutex}, + time::SystemTime, +}; + +use clang_tools_manager::utils::normalize_path; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use super::CompilationUnit; +use crate::{cli::ClangParams, common_fs::FileObj}; + +/// Bump this to discard every entry written by an older cpp-linter. +const FORMAT: u32 = 1; + +/// The clang-tidy argument that lists the opened headers on stderr. +pub(super) const LIST_HEADERS_ARG: &str = "--extra-arg=-H"; + +/// The name of the folder (in [`ClangParams::CACHE_DIR`]) for clang-tidy results. +const TIDY_DIR: &str = "tidy"; + +/// The output of a clang-tidy run, fresh or from the cache. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub(super) struct TidyRun { + pub stdout: Vec, + /// clang-tidy's stderr, without the list of headers. + pub stderr: String, + pub success: bool, + /// The exported fixes (YAML), if clang-tidy exported any. + pub fixes: Option, +} + +/// A cache entry, as stored in a JSON file. +#[derive(Debug, Serialize, Deserialize)] +struct Entry { + format: u32, + key: String, + headers: Vec
, + stdout: String, + stderr: String, + success: bool, + fixes: Option, +} + +/// A header opened by the checked file, and the hash of its content. +#[derive(Debug, Serialize, Deserialize)] +struct Header { + path: PathBuf, + hash: String, +} + +/// The cache entry for one checked file. +#[derive(Debug)] +pub(super) struct TidyCache { + /// The entry's JSON file. + path: PathBuf, + /// The hash of everything (except headers) that the results depend on. + key: String, + /// The folders that relative header paths may be relative to. + bases: Vec, + /// The absolute path of the checked file. + target: PathBuf, + /// The files (besides the checked file) whose content is in the key. + inputs: Vec, +} + +impl TidyCache { + /// Prepare the cache entry for running `cmd` on `file`. + /// + /// `cmd` is the clang-tidy command, without [`LIST_HEADERS_ARG`]. + /// `content` is the content of the checked file. + /// + /// Returns [`None`] if the results of `cmd` should not be cached. + pub(super) fn new( + file: &FileObj, + clang_params: &ClangParams, + cmd: &Command, + content: &[u8], + ) -> Option { + let version = tool_version(Path::new(cmd.get_program()))?; + let working_dir = std::path::absolute(&clang_params.repo_root).ok()?; + let target = normalize_path(&working_dir.join(&file.name)); + if clang_params + .extra_args + .iter() + .any(|arg| is_msvc_arg(&arg.to_lowercase())) + { + return None; + } + + let mut key = KeyHasher::default(); + key.add(FORMAT.to_string()); + key.add(env!("CARGO_PKG_VERSION")); + key.add(&version); + key.add(working_dir.as_os_str().as_encoded_bytes()); + let mut skip_next = false; + for arg in cmd.get_args() { + if std::mem::take(&mut skip_next) { + continue; + } + if arg == "--export-fixes" { + // The path of the exported fixes does not change the results. + skip_next = true; + continue; + } + key.add(arg.as_encoded_bytes()); + } + key.add(file.name.as_os_str().as_encoded_bytes()); + key.add(content); + + // The compilation database, as clang-tidy would find it. + let databases = match &clang_params.database { + Some(db) => { + let db = working_dir.join(db); + if db.is_dir() { + vec![ + db.join("compile_commands.json"), + db.join("compile_flags.txt"), + ] + } else { + vec![db] + } + } + None => target + .ancestors() + .skip(1) + .flat_map(|dir| { + [ + dir.join("compile_commands.json"), + dir.join("compile_flags.txt"), + ] + }) + .collect(), + }; + // Relative header paths are relative to the compilation unit's directory. + let mut bases = units_of(&target, &clang_params.database_json); + bases.push(working_dir.clone()); + + // Files that the compile commands read, but `-H` does not list. + let mut side_inputs = vec![]; + let mut inputs = vec![]; + for db in databases { + if let Some(hash) = file_hash(&db) { + if uses_msvc(&db, &hash) { + return None; + } + key.add(db.as_os_str().as_encoded_bytes()); + key.add(&hash); + side_inputs.extend(db_side_inputs(&db, &hash, &target)); + inputs.push(db); + } + } + for base in &bases { + side_inputs.extend(side_inputs_of(&clang_params.extra_args, base)); + } + let mut side_files = vec![]; + side_input_files(&side_inputs, 0, &mut side_files)?; + for input in side_files { + key.add(input.as_os_str().as_encoded_bytes()); + // An empty hash means that the file does not exist. + key.add(file_hash(&input).unwrap_or_default()); + inputs.push(input); + } + // The config files that apply to the checked file. + for dir in target.ancestors().skip(1) { + for name in [".clang-tidy", ".clang-format", "_clang-format"] { + let config = dir.join(name); + if let Some(hash) = file_hash(&config) { + key.add(config.as_os_str().as_encoded_bytes()); + key.add(hash); + inputs.push(config); + } + } + } + + let path = clang_params + .repo_root + .join(ClangParams::CACHE_DIR) + .join(TIDY_DIR) + .join(format!( + "{}.json", + &hex(Sha256::digest(file.name.as_os_str().as_encoded_bytes()))[..32] + )); + Some(Self { + path, + key: key.finish(), + bases, + target, + inputs, + }) + } + + /// Get the cached results, if they are still valid. + pub(super) fn load(&self) -> Option { + let json = fs::read(&self.path).ok()?; + let entry: Entry = serde_json::from_slice(&json).ok()?; + if entry.format != FORMAT || entry.key != self.key { + return None; + } + for header in &entry.headers { + // An empty hash means that the file did not exist. + if file_hash(&header.path).unwrap_or_default() != header.hash { + return None; + } + } + Some(TidyRun { + stdout: entry.stdout.into_bytes(), + stderr: entry.stderr, + success: entry.success, + fixes: entry.fixes, + }) + } + + /// Store the results of a fresh run. + /// + /// `raw_stderr` is clang-tidy's stderr, including the list of opened headers. + /// `started` is a time before the checked file was read and clang-tidy started. + pub(super) fn store( + &self, + run: &TidyRun, + raw_stderr: &str, + started: SystemTime, + ) -> Result<(), String> { + let stdout = String::from_utf8(run.stdout.clone()) + .map_err(|_| String::from("clang-tidy's output is not UTF-8"))?; + // A file changed while clang-tidy ran would be stored with its new hash (or + // key) but the results of its old content. + let changed = |path: &Path| { + fs::metadata(path) + .and_then(|meta| meta.modified()) + .is_ok_and(|modified| modified >= started) + }; + if changed(&self.target) { + return Err(String::from("the file changed while clang-tidy ran")); + } + if let Some(input) = self.inputs.iter().find(|input| changed(input)) { + return Err(format!("{} changed while clang-tidy ran", input.display())); + } + let mut headers: Vec
= vec![]; + let mut seen = HashSet::new(); + for listed in listed_headers(raw_stderr) { + let paths = self.resolve(listed); + if paths.is_empty() { + return Err(format!("could not find the header {listed}")); + } + for path in paths { + if !seen.insert(fs::canonicalize(&path).unwrap_or_else(|_| path.clone())) { + continue; + } + let hash = (!changed(&path)) + .then(|| file_hash(&path)) + .flatten() + .filter(|_| !changed(&path)) + .ok_or_else(|| format!("{listed} changed while clang-tidy ran"))?; + headers.push(Header { path, hash }); + } + } + headers.extend(self.header_configs(&headers)); + let entry = Entry { + format: FORMAT, + key: self.key.clone(), + headers, + stdout, + stderr: run.stderr.clone(), + success: run.success, + fixes: run.fixes.clone(), + }; + let json = serde_json::to_vec(&entry).map_err(|e| e.to_string())?; + let dir = self + .path + .parent() + .ok_or_else(|| String::from("unknown cache folder"))?; + fs::create_dir_all(dir).map_err(|e| e.to_string())?; + // Write a temporary file first, so a reader never sees a partial entry. + let mut tmp = self.path.clone().into_os_string(); + tmp.push(format!(".{}.tmp", std::process::id())); + fs::write(&tmp, json).map_err(|e| e.to_string())?; + fs::rename(&tmp, &self.path).map_err(|e| { + let _ = fs::remove_file(&tmp); + e.to_string() + }) + } + + /// Get the absolute paths that a header listed by clang-tidy may be. + /// + /// A relative path may be relative to any of the compilation units' folders (when + /// the file has more than one unit), so every existing match is returned. Extra + /// matches only make the entry stricter. + /// + /// `..` is left for the OS to resolve: a lexical `..` is wrong after a symbolic link, + /// eg. `/../lib/gcc/x86_64-linux-gnu/13/../../../../include` is `/usr/include` if + /// `/lib` links to `/usr/lib`. clang lists such paths when the compiler in the + /// compilation database has no folder (like `c++` in Meson's databases). + fn resolve(&self, listed: &str) -> Vec { + let listed = Path::new(listed); + if listed.is_absolute() { + let path = without_cur_dirs(listed); + return if path.is_file() { vec![path] } else { vec![] }; + } + let mut found: Vec = vec![]; + for base in &self.bases { + let path = without_cur_dirs(&base.join(listed)); + if path.is_file() && !found.contains(&path) { + found.push(path); + } + } + found + } + + /// The `.clang-tidy` files that could apply to the headers in the repository. + /// + /// Some checks (eg. readability-identifier-naming) use the configuration of the + /// header's folder for code in that header. Missing files are listed with an empty + /// hash, so that adding one later is noticed. The folders that contain the checked + /// file are left out, since their configuration is in the key. + fn header_configs(&self, headers: &[Header]) -> Vec
{ + let Some(working_dir) = self.bases.last() else { + return vec![]; + }; + let mut seen = HashSet::new(); + let mut configs = vec![]; + for header in headers { + if !header.path.starts_with(working_dir) { + continue; + } + for dir in header.path.ancestors().skip(1) { + if self.target.starts_with(dir) || !seen.insert(dir.to_path_buf()) { + break; + } + let path = dir.join(".clang-tidy"); + let hash = file_hash(&path).unwrap_or_default(); + configs.push(Header { path, hash }); + } + } + configs + } +} + +/// Remove the `.` components of a path (but not `..`, see [`TidyCache::resolve`]). +fn without_cur_dirs(path: &Path) -> PathBuf { + path.components() + .filter(|part| *part != Component::CurDir) + .collect() +} + +/// A file that a compile command reads, but `-H` does not list. +#[derive(Debug, Clone, PartialEq, Eq)] +enum SideInput { + /// A response file (`@file`) and the folder that its relative paths start from. + Response(PathBuf, PathBuf), + /// A forced include (`-include`, `-imacros` or `-include-pch`). + Forced(PathBuf), + /// A forced include (not a precompiled header) whose own includes are unknown: + /// `-H` does not list them. + Untracked, +} + +/// Get the response files and forced includes in `args`. +/// +/// Relative paths are resolved from `dir`, the folder that the command runs in. +fn side_inputs_of(args: &[String], dir: &Path) -> Vec { + const FORCED: [&str; 3] = ["-include", "-imacros", "-include-pch"]; + // `--include` is the same as `-include`. + let option = |opt: &str| { + let opt = opt + .strip_prefix('-') + .filter(|o| o.starts_with('-')) + .unwrap_or(opt); + FORCED.iter().find(|forced| **forced == opt).copied() + }; + let mut found = vec![]; + let (mut has_pch, mut has_header) = (false, false); + // `-Xclang` passes the next argument to the compiler itself. CMake uses it for + // precompiled headers: `-Xclang -include-pch -Xclang -Xclang -include ...`. + let mut args = args.iter().filter(|arg| *arg != "-Xclang"); + while let Some(arg) = args.next() { + if let Some(file) = arg.strip_prefix('@') { + found.push(SideInput::Response(dir.join(file), dir.to_path_buf())); + continue; + } + let forced = if let Some(opt) = option(arg) { + args.next().map(|file| (opt, file.as_str())) + } else if let Some((opt, value)) = arg.split_once('=') + && let Some(opt) = option(opt) + { + Some((opt, value)) + } else { + FORCED.iter().find_map(|opt| { + arg.strip_prefix(opt) + .filter(|rest| !rest.is_empty() && !rest.starts_with('-')) + .map(|rest| (*opt, rest)) + }) + }; + if let Some((opt, file)) = forced { + if opt == "-include-pch" { + has_pch = true; + } else { + has_header = true; + } + found.push(SideInput::Forced(dir.join(file))); + } + } + // With a precompiled header (like CMake's), the forced header is the one that the + // precompiled header was made from: its includes are in the precompiled header. + if has_header && !has_pch { + found.push(SideInput::Untracked); + } + found +} + +/// Get the side inputs of the commands for `target` in a compilation database. +/// +/// If no command is for `target`, clang-tidy borrows the command of a similar file, so +/// the side inputs of every command are returned. `hash` is the hash of the database's +/// content. +fn db_side_inputs(db: &Path, hash: &str, target: &Path) -> Vec { + // The side inputs of each command, by the absolute path of the command's file. + type Commands = Vec<(PathBuf, Vec)>; + type Seen = HashMap<(PathBuf, String), Arc>; + static SEEN: LazyLock> = LazyLock::new(Mutex::default); + let id = (db.to_path_buf(), hash.to_string()); + let cached = SEEN.lock().ok().and_then(|seen| seen.get(&id).cloned()); + let commands = cached.unwrap_or_else(|| { + let commands = Arc::new(db_commands(db)); + if let Ok(mut seen) = SEEN.lock() { + seen.insert(id, commands.clone()); + } + commands + }); + let mut found = vec![]; + let mut add = |inputs: &[SideInput]| { + for input in inputs { + if !found.contains(input) { + found.push(input.clone()); + } + } + }; + let mut matched = false; + for (file, inputs) in commands.iter() { + if file == target { + matched = true; + add(inputs); + } + } + if !matched { + for (_, inputs) in commands.iter() { + add(inputs); + } + } + found +} + +/// Get the side inputs of each command in a compilation database, by the absolute path +/// of the command's file. The commands of `compile_flags.txt` are for any file. +fn db_commands(db: &Path) -> Vec<(PathBuf, Vec)> { + let content = fs::read_to_string(db).unwrap_or_default(); + if db + .file_name() + .is_some_and(|name| name == "compile_flags.txt") + { + let args: Vec = content.lines().map(String::from).collect(); + let dir = db.parent().unwrap_or(Path::new("")); + return vec![(PathBuf::new(), side_inputs_of(&args, dir))]; + } + let Ok(units) = serde_json::from_str::>(&content) else { + return vec![]; + }; + let mut commands = vec![]; + for unit in units { + let text = |name: &str| { + unit.get(name) + .and_then(|value| value.as_str()) + .unwrap_or("") + }; + let dir = Path::new(text("directory")); + let args = match unit.get("arguments").and_then(|args| args.as_array()) { + Some(args) => args + .iter() + .filter_map(|arg| arg.as_str().map(String::from)) + .collect(), + None => split_command(text("command")), + }; + let file = normalize_path(&dir.join(text("file"))); + commands.push((file, side_inputs_of(&args, dir))); + } + commands +} + +/// Get the files to add to the key for `inputs`, following nested response files. +/// +/// Returns [`None`] if a forced include does not exist where it is named: clang would +/// search the include path for it, so its changes could not be noticed. +fn side_input_files(inputs: &[SideInput], depth: u8, files: &mut Vec) -> Option<()> { + for input in inputs { + match input { + SideInput::Untracked => return None, + SideInput::Forced(path) => { + if !path.is_file() { + return None; + } + files.push(path.clone()); + } + SideInput::Response(path, dir) => { + files.push(path.clone()); + if depth < 8 { + side_input_files(&response_inputs(path, dir), depth + 1, files)?; + } + } + } + } + Some(()) +} + +/// Get the side inputs of the arguments in a response file. +/// +/// The result is remembered for the file's content, since many commands may use the +/// same response file. +fn response_inputs(path: &Path, dir: &Path) -> Arc> { + type Seen = HashMap<(PathBuf, PathBuf, String), Arc>>; + static SEEN: LazyLock> = LazyLock::new(Mutex::default); + let Some(hash) = file_hash(path) else { + return Arc::default(); + }; + let id = (path.to_path_buf(), dir.to_path_buf(), hash); + if let Some(found) = SEEN.lock().ok().and_then(|seen| seen.get(&id).cloned()) { + return found; + } + let content = fs::read_to_string(path).unwrap_or_default(); + let found = Arc::new(side_inputs_of(&split_command(&content), dir)); + if let Ok(mut seen) = SEEN.lock() { + seen.insert(id, found.clone()); + } + found +} + +/// Split a command line into arguments, like clang does for a compilation database. +/// +/// Quotes group words. A backslash escapes the next character, except on Windows, +/// where it only escapes a quote (so `C:\path` stays as it is). +fn split_command(command: &str) -> Vec { + let mut args = vec![]; + let mut arg = String::new(); + let mut in_arg = false; + let mut quote = None; + let mut chars = command.chars().peekable(); + while let Some(c) = chars.next() { + match (quote, c) { + (Some(q), c) if c == q => quote = None, + (Some('"') | None, '\\') if !cfg!(windows) || chars.peek() == Some(&'"') => { + if let Some(next) = chars.next() { + arg.push(next); + } + in_arg = true; + } + (Some(_), c) => arg.push(c), + (None, '"' | '\'') => { + quote = Some(c); + in_arg = true; + } + (None, c) if c.is_whitespace() => { + if in_arg { + args.push(std::mem::take(&mut arg)); + in_arg = false; + } + } + (None, c) => { + arg.push(c); + in_arg = true; + } + } + } + if in_arg { + args.push(arg); + } + args +} + +/// Remove the list of opened headers (from [`LIST_HEADERS_ARG`]) from clang-tidy's stderr. +pub(super) fn strip_header_list(stderr: &str) -> String { + let mut out = String::with_capacity(stderr.len()); + for line in stderr.split_inclusive('\n') { + if header_line(line).is_none() { + out.push_str(line); + } + } + out +} + +/// Get the header path from a line of `-H` output (eg. `.. /usr/include/stdio.h`). +fn header_line(line: &str) -> Option<&str> { + let rest = line.trim_start_matches('.'); + if rest.len() == line.len() { + return None; + } + let path = rest.strip_prefix(' ')?.trim_end_matches(['\r', '\n']); + (!path.is_empty()).then_some(path) +} + +/// Get the paths of the headers listed in clang-tidy's stderr. +fn listed_headers(stderr: &str) -> impl Iterator { + stderr.lines().filter_map(header_line) +} + +/// Get the build directories of the compilation units for `target`. +fn units_of(target: &Path, database_json: &Option>) -> Vec { + let Some(units) = database_json else { + return vec![]; + }; + let mut dirs = vec![]; + for unit in units { + let dir = PathBuf::from(&unit.directory); + if normalize_path(&dir.join(&unit.file)) == target && !dirs.contains(&dir) { + dirs.push(dir); + } + } + if dirs.is_empty() { + // clang-tidy borrows the command of a similar unit for a file that is not in the + // database (eg. a header), and runs it in that unit's folder. That folder is + // only known for sure if every unit uses the same one. + let mut all = units.iter().map(|unit| PathBuf::from(&unit.directory)); + if let Some(first) = all.next() + && all.all(|dir| dir == first) + { + dirs.push(first); + } + } + dirs +} + +/// Does this (lower case) compiler argument select the MSVC driver? +fn is_msvc_arg(arg: &str) -> bool { + arg.contains("--driver-mode=cl") +} + +/// Does this compilation database use the MSVC driver (clang-cl or cl.exe)? +/// +/// The MSVC driver has no `-H` option, so the opened headers could not be listed. +/// `hash` is the hash of the database's content. +fn uses_msvc(db: &Path, hash: &str) -> bool { + static SEEN: LazyLock>> = LazyLock::new(Mutex::default); + let id = (db.to_path_buf(), hash.to_string()); + if let Some(found) = SEEN.lock().ok().and_then(|seen| seen.get(&id).copied()) { + return found; + } + let found = fs::read(db).is_ok_and(|content| { + let content = String::from_utf8_lossy(&content).to_lowercase(); + is_msvc_arg(&content) || content.contains("clang-cl") || content.contains("cl.exe") + }); + if let Ok(mut seen) = SEEN.lock() { + seen.insert(id, found); + } + found +} + +/// Get the output of `clang-tidy --version`, if it ran successfully. +fn tool_version(program: &Path) -> Option { + static VERSIONS: LazyLock>>> = + LazyLock::new(Mutex::default); + if let Some(version) = VERSIONS + .lock() + .ok() + .and_then(|versions| versions.get(program).cloned()) + { + return version; + } + let version = Command::new(program) + .arg("--version") + .output() + .ok() + .filter(|out| out.status.success()) + .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string()) + .filter(|version| !version.is_empty()); + if let Ok(mut versions) = VERSIONS.lock() { + versions.insert(program.to_path_buf(), version.clone()); + } + version +} + +/// Get the hash of a file's content, or [`None`] if it is not a readable file. +/// +/// Many checked files open the same headers, so hashes are reused while the file's +/// size and modification time stay the same. +fn file_hash(path: &Path) -> Option { + type Stamp = (u64, Option); + static HASHES: LazyLock>> = + LazyLock::new(Mutex::default); + let meta = fs::metadata(path).ok().filter(|meta| meta.is_file())?; + let stamp = (meta.len(), meta.modified().ok()); + if let Some(hash) = HASHES.lock().ok().and_then(|hashes| { + hashes + .get(path) + .filter(|(known, _)| stamp.1.is_some() && *known == stamp) + .map(|(_, hash)| hash.clone()) + }) { + return Some(hash); + } + let hash = hex(Sha256::digest(fs::read(path).ok()?)); + if let Ok(mut hashes) = HASHES.lock() { + hashes.insert(path.to_path_buf(), (stamp, hash.clone())); + } + Some(hash) +} + +/// Format bytes as lower case hexadecimal. +fn hex(bytes: impl AsRef<[u8]>) -> String { + bytes.as_ref().iter().map(|b| format!("{b:02x}")).collect() +} + +/// Hashes a list of values, so that no two lists give the same input to the hash. +#[derive(Default)] +struct KeyHasher(Sha256); + +impl KeyHasher { + fn add(&mut self, value: impl AsRef<[u8]>) { + let value = value.as_ref(); + self.0.update((value.len() as u64).to_le_bytes()); + self.0.update(value); + } + + fn finish(self) -> String { + hex(self.0.finalize()) + } +} + +#[cfg(test)] +mod test { + #![allow(clippy::unwrap_used, clippy::expect_used)] + + use std::{ + fs, + path::{Path, PathBuf}, + process::Command, + str::FromStr, + sync::Mutex, + time::{Duration, SystemTime}, + }; + + use clang_tools_manager::RequestedVersion; + + use super::{ + CompilationUnit, TidyCache, TidyRun, header_line, split_command, strip_header_list, + }; + use crate::{ + clang_tools::{ClangTool, clang_tidy::run_clang_tidy}, + cli::ClangParams, + common_fs::FileObj, + }; + + fn tidy_exe() -> PathBuf { + ClangTool::ClangTidy + .get_exe_path( + &RequestedVersion::from_str(&std::env::var("CLANG_VERSION").unwrap_or_default()) + .unwrap(), + ) + .unwrap() + } + + fn make_params(repo_root: &Path) -> ClangParams { + ClangParams { + tidy_checks: "-*,readability-braces-around-statements".to_string(), + clang_tidy_command: Some(tidy_exe()), + repo_root: repo_root.to_path_buf(), + gen_patch: true, + ..Default::default() + } + } + + /// Run clang-tidy on demo/demo.cpp; returns the logs, the notes and the patched file. + fn run(params: &ClangParams) -> (String, String, Vec) { + let file = Mutex::new(FileObj::new(PathBuf::from("demo/demo.cpp"))); + let mut file = file.lock().unwrap(); + let (logs, _) = run_clang_tidy(&mut file, params).unwrap(); + let logs = logs + .into_iter() + .map(|(_, msg)| msg) + .collect::>() + .join("\n"); + let notes = format!("{:?}", file.tidy_advice.as_ref().unwrap().notes); + let patched = fs::read(file.patched_path.as_ref().unwrap()).unwrap(); + (logs, notes, patched) + } + + /// A start time after every file was written. + fn later() -> SystemTime { + SystemTime::now() + Duration::from_secs(3600) + } + + fn cache_for(params: &ClangParams, content: &[u8]) -> Option { + let file = FileObj::new(PathBuf::from("demo/demo.cpp")); + let cmd = Command::new(params.clang_tidy_command.as_ref().unwrap()); + TidyCache::new(&file, params, &cmd, content) + } + + #[test] + fn results_reused_until_something_changes() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = make_params(tmp.path()); + + let (logs, notes, patched) = run(¶ms); + assert!(logs.contains("Running \"")); + assert!(logs.contains(super::LIST_HEADERS_ARG)); + assert!(notes.contains("readability-braces-around-statements")); + // the list of headers is not shown as clang-tidy's summary + assert!(!logs.contains("demo.hpp\n")); + + // nothing changed + let (logs, cached_notes, cached_patch) = run(¶ms); + assert!(logs.contains("Using cached clang-tidy results for demo/demo.cpp")); + assert!(!logs.contains("Running \""), "{logs}"); + assert_eq!(cached_notes, notes); + assert_eq!(cached_patch, patched); + + // a header changed + let header = tmp.path().join("demo/demo.hpp"); + let mut content = fs::read_to_string(&header).unwrap(); + content.push_str("\n// changed\n"); + fs::write(&header, content).unwrap(); + let (logs, ..) = run(¶ms); + assert!(logs.contains("Running \"")); + let (logs, ..) = run(¶ms); + assert!(logs.contains("Using cached")); + + // a config file changed + fs::write(tmp.path().join(".clang-tidy"), "Checks: '-*'\n").unwrap(); + let (logs, ..) = run(¶ms); + assert!(logs.contains("Running \"")); + + // the arguments changed + let params = ClangParams { + tidy_checks: "-*,readability-*".to_string(), + ..params + }; + let (logs, ..) = run(¶ms); + assert!(logs.contains("Running \"")); + let (logs, ..) = run(¶ms); + assert!(logs.contains("Using cached")); + } + + #[test] + fn missing_header_not_cached() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = make_params(tmp.path()); + fs::write( + tmp.path().join("demo/demo.cpp"), + "#include \"generated.h\"\nint main() { for (;;) break; }\n", + ) + .unwrap(); + let (logs, notes, _) = run(¶ms); + assert!(notes.contains("clang-diagnostic-error"), "{notes}"); + let (logs2, ..) = run(¶ms); + assert!(logs2.contains("Running \""), "{logs}\n{logs2}"); + // the header is generated: the results change + fs::write(tmp.path().join("demo/generated.h"), "#pragma once\n").unwrap(); + let (_, notes, _) = run(¶ms); + assert!(!notes.contains("clang-diagnostic-error"), "{notes}"); + assert!(notes.contains("readability-braces-around-statements")); + } + + #[test] + fn header_changed_while_running() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = make_params(tmp.path()); + let header = tmp.path().join("demo/demo.hpp"); + let cache = cache_for(¶ms, b"content").unwrap(); + let started = SystemTime::now(); + std::thread::sleep(Duration::from_millis(20)); + fs::write(&header, "// edited\n").unwrap(); + let stderr = format!(". {}\n", header.display()); + let err = cache + .store(&TidyRun::default(), &stderr, started) + .unwrap_err(); + assert!(err.contains("changed while clang-tidy ran"), "{err}"); + cache.store(&TidyRun::default(), &stderr, later()).unwrap(); + assert!(cache.load().is_some()); + } + + #[test] + fn config_of_header_folder() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = make_params(tmp.path()); + let inc = std::path::absolute(tmp.path()).unwrap().join("inc"); + fs::create_dir(&inc).unwrap(); + fs::write(inc.join("h.hpp"), "#pragma once\n").unwrap(); + let cache = cache_for(¶ms, b"content").unwrap(); + let stderr = format!(". {}\n", inc.join("h.hpp").display()); + cache.store(&TidyRun::default(), &stderr, later()).unwrap(); + assert!(cache.load().is_some()); + // a new config file for the header's folder + fs::write(inc.join(".clang-tidy"), "Checks: '-*'\n").unwrap(); + assert!(cache.load().is_none()); + cache.store(&TidyRun::default(), &stderr, later()).unwrap(); + assert!(cache.load().is_some()); + // the config file changed + fs::write(inc.join(".clang-tidy"), "Checks: '*'\n").unwrap(); + assert!(cache.load().is_none()); + } + + #[cfg(unix)] + #[test] + fn dot_dot_after_symlink() { + // like `/../lib/gcc/x86_64-linux-gnu/13/../../../../include/c++/13/vector` + // where `/lib` links to `/usr/lib` + let tmp = crate::test_common::setup_tmp_workspace(); + let root = std::path::absolute(tmp.path()).unwrap(); + fs::create_dir_all(root.join("usr/lib/gcc/13")).unwrap(); + fs::create_dir_all(root.join("usr/include")).unwrap(); + fs::write(root.join("usr/include/vector"), "").unwrap(); + std::os::unix::fs::symlink(root.join("usr/lib"), root.join("lib")).unwrap(); + let cache = cache_for(&make_params(tmp.path()), b"content").unwrap(); + let listed = root.join("lib/gcc/13/../../../include/vector"); + assert_eq!( + cache.resolve(&listed.to_string_lossy()), + vec![listed.clone()] + ); + } + + #[test] + fn invalid_entries_are_not_used() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = make_params(tmp.path()); + let header = tmp.path().join("demo/demo.hpp"); + let cache = cache_for(¶ms, b"content").unwrap(); + let tidy_run = TidyRun { + stdout: b"out".to_vec(), + stderr: String::from("summary\n"), + success: true, + fixes: None, + }; + + // nothing stored yet + assert_eq!(cache.load(), None); + // a corrupt entry + fs::create_dir_all(cache.path.parent().unwrap()).unwrap(); + fs::write(&cache.path, "{").unwrap(); + assert_eq!(cache.load(), None); + + let stderr = format!(". {}\n.. ./demo/demo.hpp\nsummary\n", header.display()); + cache.store(&tidy_run, &stderr, later()).unwrap(); + assert_eq!(cache.load(), Some(tidy_run.clone())); + let json = fs::read_to_string(&cache.path).unwrap(); + // the same header listed twice (absolute and relative) is stored once + assert_eq!(json.matches("demo.hpp").count(), 1); + + // another key + let other = cache_for(¶ms, b"other content").unwrap(); + assert_eq!(other.path, cache.path); + assert_eq!(other.load(), None); + + // a header changed or is gone + fs::write(&header, "changed").unwrap(); + assert_eq!(cache.load(), None); + fs::remove_file(&header).unwrap(); + assert_eq!(cache.load(), None); + } + + #[test] + fn some_results_are_not_stored() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = make_params(tmp.path()); + let cache = cache_for(¶ms, b"content").unwrap(); + let mut tidy_run = TidyRun { + stdout: vec![0xff], + ..Default::default() + }; + assert!( + cache + .store(&tidy_run, "", later()) + .unwrap_err() + .contains("UTF-8") + ); + tidy_run.stdout.clear(); + let err = cache + .store(&tidy_run, ". missing.h\n", later()) + .unwrap_err(); + assert!(err.contains("missing.h")); + assert!(!cache.path.exists()); + // the entry can't replace a folder + fs::create_dir_all(cache.path.join("sub")).unwrap(); + assert!(cache.store(&tidy_run, "", later()).is_err()); + assert_eq!( + fs::read_dir(cache.path.parent().unwrap()).unwrap().count(), + 1 + ); + // the cache folder can't be made + fs::remove_dir_all(tmp.path().join(ClangParams::CACHE_DIR)).unwrap(); + fs::write(tmp.path().join(ClangParams::CACHE_DIR), "").unwrap(); + assert!(cache.store(&tidy_run, "", later()).is_err()); + } + + #[test] + fn results_used_even_if_not_stored() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = make_params(tmp.path()); + // a file where the cache folder should be + let tidy_dir = tmp + .path() + .join(ClangParams::CACHE_DIR) + .join(super::TIDY_DIR); + fs::create_dir_all(tidy_dir.parent().unwrap()).unwrap(); + fs::write(&tidy_dir, "").unwrap(); + let (logs, notes, _) = run(¶ms); + assert!(logs.contains("Did not cache the clang-tidy results for demo/demo.cpp")); + assert!(notes.contains("readability-braces-around-statements")); + } + + #[test] + fn relative_headers_from_build_dir() { + let tmp = crate::test_common::setup_tmp_workspace(); + let root = std::path::absolute(tmp.path()).unwrap(); + let build = root.join("build"); + fs::create_dir(&build).unwrap(); + let params = ClangParams { + database_json: Some(vec![ + CompilationUnit { + directory: build.to_string_lossy().to_string(), + file: String::from("../demo/demo.cpp"), + }, + CompilationUnit { + directory: build.to_string_lossy().to_string(), + file: String::from("../demo/other.cpp"), + }, + ]), + ..make_params(tmp.path()) + }; + let cache = cache_for(¶ms, b"").unwrap(); + assert_eq!(cache.bases, vec![build.clone(), root.clone()]); + // a file that is not in the database (eg. a header) borrows a unit's command + let header = FileObj::new(PathBuf::from("demo/demo.hpp")); + let cmd = Command::new(params.clang_tidy_command.as_ref().unwrap()); + let cache = TidyCache::new(&header, ¶ms, &cmd, b"").unwrap(); + assert_eq!(cache.bases, vec![build.clone(), root.clone()]); + // unless the units use different folders + let mut two_dirs = params.clone(); + if let Some(units) = two_dirs.database_json.as_mut() { + units[1].directory = root.to_string_lossy().to_string(); + } + let cache = TidyCache::new(&header, &two_dirs, &cmd, b"").unwrap(); + assert_eq!(cache.bases, vec![root.clone()]); + let cache = cache_for(¶ms, b"").unwrap(); + assert_eq!( + cache.resolve("../demo/demo.hpp"), + vec![build.join("../demo/demo.hpp")] + ); + assert_eq!( + cache.resolve("demo/demo.hpp"), + vec![root.join("demo/demo.hpp")] + ); + assert!(cache.resolve("missing.hpp").is_empty()); + // every folder's copy may be read + fs::write(build.join("config.h"), "").unwrap(); + fs::write(root.join("config.h"), "").unwrap(); + assert_eq!( + cache.resolve("./config.h"), + vec![build.join("config.h"), root.join("config.h")] + ); + } + + #[test] + fn file_changed_while_running() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = make_params(tmp.path()); + let cache = cache_for(¶ms, b"content").unwrap(); + let started = SystemTime::now(); + std::thread::sleep(Duration::from_millis(20)); + fs::write(tmp.path().join("demo/demo.cpp"), "// edited\n").unwrap(); + let err = cache.store(&TidyRun::default(), "", started).unwrap_err(); + assert!(err.contains("the file changed"), "{err}"); + } + + #[test] + fn file_changed_while_running_in_key() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = make_params(tmp.path()); + let config = tmp.path().join(".clang-tidy"); + fs::write(&config, "Checks: '-*'\n").unwrap(); + let cache = cache_for(¶ms, b"content").unwrap(); + let started = SystemTime::now(); + std::thread::sleep(Duration::from_millis(20)); + fs::write(&config, "Checks: '*'\n").unwrap(); + let err = cache.store(&TidyRun::default(), "", started).unwrap_err(); + assert!(err.contains(".clang-tidy changed"), "{err}"); + } + + #[test] + fn forced_includes_and_response_files_in_key() { + let tmp = crate::test_common::setup_tmp_workspace(); + let root = std::path::absolute(tmp.path()).unwrap(); + let build = root.join("build"); + fs::create_dir(&build).unwrap(); + fs::write(build.join("forced.h"), "#define A 0\n").unwrap(); + fs::write(build.join("forced.h.pch"), "").unwrap(); + fs::write(build.join("flags.rsp"), "-DX @more.rsp").unwrap(); + fs::write( + build.join("more.rsp"), + "-include-pch forced.h.pch -include forced.h", + ) + .unwrap(); + let db = build.join("compile_commands.json"); + let entry = |command: &str| { + serde_json::json!([{ + "directory": build.to_string_lossy(), + "command": command, + "file": "../demo/demo.cpp", + }]) + .to_string() + }; + fs::write(&db, entry("clang++ @flags.rsp -c ../demo/demo.cpp")).unwrap(); + let params = ClangParams { + database: Some(build.clone()), + ..make_params(tmp.path()) + }; + let key = cache_for(¶ms, b"").unwrap().key; + // a forced include changed (found through nested response files) + fs::write(build.join("forced.h"), "#define A 1\n").unwrap(); + let key2 = cache_for(¶ms, b"").unwrap().key; + assert_ne!(key2, key); + // the precompiled header changed + fs::write(build.join("forced.h.pch"), "1").unwrap(); + let key3 = cache_for(¶ms, b"").unwrap().key; + assert_ne!(key3, key2); + // a response file changed + fs::write( + build.join("more.rsp"), + "-include-pch forced.h.pch -include forced.h -DY", + ) + .unwrap(); + assert_ne!(cache_for(¶ms, b"").unwrap().key, key3); + // a forced include without a precompiled header: its includes are unknown + fs::write(build.join("more.rsp"), "-include forced.h").unwrap(); + assert!(cache_for(¶ms, b"").is_none()); + + // a precompiled header that can't be found without the include path + fs::write( + &db, + entry("clang++ -include-pch not-here.pch -c ../demo/demo.cpp"), + ) + .unwrap(); + assert!(cache_for(¶ms, b"").is_none()); + + // `arguments` instead of `command`, and the other spellings + for args in [ + vec!["--include=forced.h", "-include-pch", "forced.h.pch"], + vec!["-includeforced.h", "--include-pch=forced.h.pch"], + vec!["-imacros=forced.h", "-include-pch../build/forced.h.pch"], + // CMake's precompiled headers + vec![ + "-Xclang", + "-include-pch", + "-Xclang", + "forced.h.pch", + "-Xclang", + "-include", + "-Xclang", + "forced.h", + ], + ] { + let arg = args.join(" "); + let mut arguments = vec!["clang++"]; + arguments.extend(args.iter()); + arguments.extend(["-c", "../demo/demo.cpp"]); + let json = serde_json::json!([{ + "directory": build.to_string_lossy(), + "arguments": arguments, + "file": "../demo/demo.cpp", + }]); + fs::write(&db, json.to_string()).unwrap(); + let key = cache_for(¶ms, b"").unwrap().key; + fs::write(build.join("forced.h"), format!("// {arg}\n")).unwrap(); + assert_ne!(cache_for(¶ms, b"").unwrap().key, key, "{arg}"); + } + // forced includes without a precompiled header: their includes are unknown + for args in [ + vec!["-imacros", "forced.h"], + vec!["-Xclang", "-include", "-Xclang", "forced.h"], + ] { + let mut arguments = vec!["clang++"]; + arguments.extend(args.iter()); + arguments.extend(["-c", "../demo/demo.cpp"]); + let json = serde_json::json!([{ + "directory": build.to_string_lossy(), + "arguments": arguments, + "file": "../demo/demo.cpp", + }]); + fs::write(&db, json.to_string()).unwrap(); + assert!(cache_for(¶ms, b"").is_none(), "{}", args.join(" ")); + } + + // only the commands for the checked file count, if it has any + let json = serde_json::json!([ + { + "directory": build.to_string_lossy(), + "command": "clang++ -include forced.h -c other.cpp", + "file": "other.cpp", + }, + { + "directory": build.to_string_lossy(), + "command": "clang++ @flags.rsp -c ../demo/demo.cpp", + "file": "../demo/demo.cpp", + }, + ]); + fs::write(&db, json.to_string()).unwrap(); + fs::write(build.join("more.rsp"), "-DZ").unwrap(); + assert!(cache_for(¶ms, b"").is_some()); + let json = serde_json::json!([{ + "directory": build.to_string_lossy(), + "command": "clang++ -include forced.h -c other.cpp", + "file": "other.cpp", + }]); + fs::write(&db, json.to_string()).unwrap(); + assert!(cache_for(¶ms, b"").is_none()); + + // compile_flags.txt and extra arguments + let params = ClangParams { + database: None, + extra_args: vec![String::from("-include"), String::from("forced.h")], + ..params + }; + fs::remove_file(&db).unwrap(); + fs::write(root.join("forced.h"), "").unwrap(); + fs::write( + root.join("demo/compile_flags.txt"), + "-include-pch\n../pch\n", + ) + .unwrap(); + // a forced include without a precompiled header in the same arguments + fs::write(root.join("pch"), "").unwrap(); + assert!(cache_for(¶ms, b"").is_none()); + let params = ClangParams { + extra_args: vec![String::from("-include-pch"), String::from("pch")], + ..params + }; + let key = cache_for(¶ms, b"").unwrap().key; + fs::write(root.join("pch"), "// changed\n").unwrap(); + assert_ne!(cache_for(¶ms, b"").unwrap().key, key); + fs::remove_file(root.join("pch")).unwrap(); + assert!(cache_for(¶ms, b"").is_none()); + } + + #[test] + fn split_commands() { + let expected: &[&str] = if cfg!(windows) { + &["cc", "-DA=b c", "d e", "f\\", "g", "@x.rsp"] + } else { + &["cc", "-DA=b c", "d e", "f g", "@x.rsp"] + }; + assert_eq!( + split_command(r#"cc -DA="b c" 'd e' f\ g @x.rsp"#), + expected + ); + assert_eq!(split_command(r#"a "q\"q""#), ["a", r#"q"q"#]); + if cfg!(windows) { + assert_eq!( + split_command(r"-include C:\x\f.h"), + ["-include", r"C:\x\f.h"] + ); + } + assert!(split_command(" ").is_empty()); + } + + #[test] + fn compile_database_in_key() { + let tmp = crate::test_common::setup_tmp_workspace(); + let build = tmp.path().join("build"); + fs::create_dir(&build).unwrap(); + let db = build.join("compile_commands.json"); + fs::write(&db, "[]").unwrap(); + let params = ClangParams { + database: Some(build.clone()), + ..make_params(tmp.path()) + }; + let key = cache_for(¶ms, b"").unwrap().key; + fs::write(&db, "[ ]").unwrap(); + assert_ne!(cache_for(¶ms, b"").unwrap().key, key); + + // the database file itself + let params = ClangParams { + database: Some(db.clone()), + ..params + }; + assert!(cache_for(¶ms, b"").is_some()); + + // found in a parent folder of the checked file + let params = ClangParams { + database: None, + ..params + }; + let key = cache_for(¶ms, b"").unwrap().key; + fs::write(tmp.path().join("compile_flags.txt"), "-Wall").unwrap(); + assert_ne!(cache_for(¶ms, b"").unwrap().key, key); + } + + #[test] + fn msvc_driver_not_cached() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = ClangParams { + extra_args: vec![String::from("--driver-mode=cl")], + ..make_params(tmp.path()) + }; + assert!(cache_for(¶ms, b"").is_none()); + + let build = tmp.path().join("build"); + fs::create_dir(&build).unwrap(); + fs::write( + build.join("compile_commands.json"), + r#"[{"directory": ".", "command": "C:/LLVM/bin/clang-cl.exe /c demo.cpp", "file": "demo.cpp"}]"#, + ) + .unwrap(); + let params = ClangParams { + extra_args: vec![], + database: Some(build), + ..params + }; + assert!(cache_for(¶ms, b"").is_none()); + // the answer is reused + assert!(cache_for(¶ms, b"").is_none()); + } + + #[test] + fn unknown_tool_version_not_cached() { + let tmp = crate::test_common::setup_tmp_workspace(); + let params = ClangParams { + clang_tidy_command: Some(tmp.path().join("not-a-clang-tidy")), + ..make_params(tmp.path()) + }; + assert!(cache_for(¶ms, b"").is_none()); + // the answer is reused + assert!(cache_for(¶ms, b"").is_none()); + } + + #[test] + fn header_list_lines() { + assert_eq!( + header_line(". /usr/include/stdio.h\n"), + Some("/usr/include/stdio.h") + ); + assert_eq!(header_line("... a b.h\r\n"), Some("a b.h")); + assert_eq!(header_line("1 warning generated."), None); + assert_eq!(header_line(".hidden"), None); + assert_eq!(header_line(". "), None); + assert_eq!( + strip_header_list(". a.h\n.. b.h\n1 warning generated.\n"), + "1 warning generated.\n" + ); + } +} diff --git a/cpp-linter/src/clang_tools/clang_tidy/mod.rs b/cpp-linter/src/clang_tools/clang_tidy/mod.rs index da47f0b5..1588f667 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/mod.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/mod.rs @@ -24,7 +24,9 @@ use crate::{ markdown::{self, Status}, }; +mod cache; pub mod other_files; +use cache::{TidyCache, TidyRun}; use other_files::{OtherFileFix, Replacement, TidyFixes}; /// Used to deserialize a json compilation database's translation unit. @@ -685,10 +687,14 @@ pub(super) fn write_cache( /// Build the clang-tidy command that analyzes the given `file`. /// /// clang-tidy exports its fixes to `fixes_path` instead of applying them. +/// +/// If `list_headers` is true, clang-tidy also lists the opened headers on stderr +/// (see [`cache::LIST_HEADERS_ARG`]). fn build_tidy_command( file: &FileObj, clang_params: &ClangParams, fixes_path: &Path, + list_headers: bool, ) -> Result { let cmd_path = clang_params .clang_tidy_command @@ -723,6 +729,9 @@ fn build_tidy_command( ); cmd.args(["--line-filter", filter.as_str()]); } + if list_headers { + cmd.arg(cache::LIST_HEADERS_ARG); + } cmd.arg("--export-fixes"); cmd.arg(fixes_path); cmd.arg(tool_file_arg(&file.name)); @@ -745,23 +754,31 @@ fn remove_file_if_exists(path: &Path) -> Result<(), ClangCaptureError> { /// Read (and then remove) the fixes that clang-tidy exported to `fixes_path`. /// /// clang-tidy does not write the file if there was nothing to report. -fn read_exported_fixes(fixes_path: &Path) -> Result { - let file_name = fixes_path.to_string_lossy().to_string(); +fn read_exported_fixes(fixes_path: &Path) -> Result, ClangCaptureError> { let yml = match fs::read_to_string(fixes_path) { Ok(yml) => yml, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - return Ok(ExportedFixes::default()); - } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(e) => { return Err(ClangCaptureError::ReadFileFailed { - file_name, + file_name: fixes_path.to_string_lossy().to_string(), source: e, }); } }; remove_file_if_exists(fixes_path)?; - serde_saphyr::from_str(&yml).map_err(|e| ClangCaptureError::ParseFixesFailed { - file_name, + Ok(Some(yml)) +} + +/// Parse the fixes that clang-tidy exported to `fixes_path` (if any). +fn parse_exported_fixes( + yml: Option<&str>, + fixes_path: &Path, +) -> Result { + let Some(yml) = yml else { + return Ok(ExportedFixes::default()); + }; + serde_saphyr::from_str(yml).map_err(|e| ClangCaptureError::ParseFixesFailed { + file_name: fixes_path.to_string_lossy().to_string(), source: Box::new(e), }) } @@ -812,6 +829,53 @@ pub(crate) fn tidy_failure( }) } +/// Run clang-tidy on `file`. +/// +/// Returns the run's results and clang-tidy's whole stderr (which lists the opened +/// headers if `list_headers` is true). +fn run_tidy_command( + file: &FileObj, + clang_params: &ClangParams, + fixes_path: &Path, + list_headers: bool, + logs: &mut Vec<(log::Level, String)>, +) -> Result<(TidyRun, String), ClangCaptureError> { + let file_name = file.name.to_string_lossy(); + let mut cmd = build_tidy_command(file, clang_params, fixes_path, list_headers)?; + logs.push(( + log::Level::Info, + format!( + "Running \"{} {}\"", + cmd.get_program().to_string_lossy(), + cmd.get_args() + .map(|x| x.to_string_lossy()) + .collect::>() + .join(" ") + ), + )); + let output = cmd + .output() + .map_err(|e| ClangCaptureError::FailedToRunCommand { + task: format!("execute clang-tidy on file {file_name}"), + source: e, + })?; + // Read (and remove) the exported fixes even if clang-tidy failed. + let fixes = read_exported_fixes(fixes_path)?; + let raw_stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + let stderr = if list_headers { + cache::strip_header_list(&raw_stderr) + } else { + raw_stderr.clone() + }; + let run = TidyRun { + stdout: output.stdout, + stderr, + success: output.status.success(), + fixes, + }; + Ok((run, raw_stderr)) +} + /// Run clang-tidy, then parse and return it's output. /// /// clang-tidy is not allowed to modify any files. @@ -823,6 +887,9 @@ pub fn run_clang_tidy( clang_params: &ClangParams, ) -> Result<(Vec<(log::Level, String)>, TidyFixes), ClangCaptureError> { let file_name = file.name.to_string_lossy().to_string(); + // Taken before the file is read, so that the cache can tell if the file changed + // while it was checked. + let started = std::time::SystemTime::now(); let repo_file_path = clang_params.repo_root.join(&file.name); let original_content = fs::read(&repo_file_path).map_err(|e| ClangCaptureError::ReadFileFailed { @@ -840,63 +907,63 @@ pub fn run_clang_tidy( let mut fixes_path = std::path::absolute(&cache_patch_path) .map_err(ClangCaptureError::UnknownWorkingDirectory)? .into_os_string(); - fixes_path.push(".fixes.yml"); + // Another cpp-linter process may check the same file at the same time (eg. a git hook + // and an editor); a shared fixes file would let one process read (and remove) the + // other's fixes, and the cache would keep the wrong result. + fixes_path.push(format!(".{}.fixes.yml", std::process::id())); let fixes_path = PathBuf::from(fixes_path); // Don't let a stale file from a previous run get used. remove_file_if_exists(&fixes_path)?; - let mut cmd = build_tidy_command(file, clang_params, &fixes_path)?; - let mut logs = vec![( - log::Level::Info, - format!( - "Running \"{} {}\"", - cmd.get_program().to_string_lossy(), - cmd.get_args() - .map(|x| x.to_string_lossy()) - .collect::>() - .join(" ") - ), - )]; - let output = cmd - .output() - .map_err(|e| ClangCaptureError::FailedToRunCommand { - task: format!("execute clang-tidy on file {file_name}"), - source: e, - })?; + let cache = TidyCache::new( + file, + clang_params, + &build_tidy_command(file, clang_params, &fixes_path, false)?, + &original_content, + ); + let mut logs = vec![]; + let mut fresh = None; + let run = match cache.as_ref().and_then(TidyCache::load) { + Some(run) => { + logs.push(( + log::Level::Info, + format!("Using cached clang-tidy results for {file_name}"), + )); + run + } + None => { + let (run, raw_stderr) = + run_tidy_command(file, clang_params, &fixes_path, cache.is_some(), &mut logs)?; + fresh = Some((raw_stderr, started)); + run + } + }; logs.push(( log::Level::Debug, format!( "Output from clang-tidy:\n{}", - String::from_utf8_lossy(&output.stdout) + String::from_utf8_lossy(&run.stdout) ), )); - if !output.stderr.is_empty() { + if !run.stderr.is_empty() { logs.push(( log::Level::Debug, - format!( - "clang-tidy made the following summary:\n{}", - String::from_utf8_lossy(&output.stderr) - ), + format!("clang-tidy made the following summary:\n{}", run.stderr), )); } let mut notes = parse_tidy_output( - &output.stdout, + &run.stdout, &clang_params.database_json, &clang_params.repo_root, )?; - if let Some(reason) = tidy_failure( - output.status.success(), - &String::from_utf8_lossy(&output.stderr), - ¬es, - ) { + if let Some(reason) = tidy_failure(run.success, &run.stderr, ¬es) { logs.push(( log::Level::Warn, format!( "clang-tidy did not analyze {file_name}; counting it as a failed check:\n{reason}" ), )); - remove_file_if_exists(&fixes_path)?; file.tidy_advice = Some(TidyAdvice { failed: true, ..Default::default() @@ -904,7 +971,21 @@ pub fn run_clang_tidy( return Ok((logs, TidyFixes::default())); } - let fixes = read_exported_fixes(&fixes_path)?; + let fixes = parse_exported_fixes(run.fixes.as_deref(), &fixes_path)?; + // A missing file (eg. a header that is not generated yet) is not in the list of + // opened headers, so these results could not be checked later. + let missing_file = notes.iter().any(|note| { + note.diagnostic == "clang-diagnostic-error" && note.rationale.ends_with("not found") + }); + if let (Some(cache), Some((raw_stderr, started))) = (&cache, fresh) + && !missing_file + && let Err(reason) = cache.store(&run, &raw_stderr, started) + { + logs.push(( + log::Level::Debug, + format!("Did not cache the clang-tidy results for {file_name}: {reason}"), + )); + } let working_dir = std::path::absolute(&clang_params.repo_root) .map_err(ClangCaptureError::UnknownWorkingDirectory)?; let target = normalize_path(&working_dir.join(&file.name)); diff --git a/cpp-linter/src/clang_tools/clang_tidy/test.rs b/cpp-linter/src/clang_tools/clang_tidy/test.rs index c54e112e..06157d61 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/test.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/test.rs @@ -816,7 +816,7 @@ fn tidy_stale_fixes_not_removable() { fs::create_dir_all( clang_params .get_cache_path() - .join("demo/demo.cpp.fixes.yml"), + .join(format!("demo/demo.cpp.{}.fixes.yml", std::process::id())), ) .unwrap(); let file = Mutex::new(FileObj::new(PathBuf::from("demo/demo.cpp"))); diff --git a/cspell.config.yml b/cspell.config.yml index c7fe0906..4dc4c86a 100644 --- a/cspell.config.yml +++ b/cspell.config.yml @@ -51,7 +51,9 @@ words: - gnueabihf - htmltitle - hustcer + - imacros - imara + - includeforced - inlinehilite - interner - iomanip @@ -143,6 +145,7 @@ words: - venv - Werror - winget + - Xclang - Xianpeng - yarnrc - zigbuild diff --git a/docs/docs/migration.md b/docs/docs/migration.md index 8d85034d..db6a2972 100644 --- a/docs/docs/migration.md +++ b/docs/docs/migration.md @@ -171,12 +171,29 @@ the current working directory, not against [`--repo-root`][repo-root]. With the default `--repo-root` of `.`, nothing changes. +## clang-tidy results are cached + +v2 keeps each file's clang-tidy results in `.cpp-linter-cache/tidy/`, in the +[`--repo-root`][repo-root] folder. The next run reuses them if nothing that could change them has +changed: the clang-tidy version, its arguments (including the changed lines), the compilation +database, the `.clang-tidy` and `.clang-format` files, the file itself and every header it +includes. Only the other files run clang-tidy again, so a second run is much faster. + +To reuse the results in CI, keep the `.cpp-linter-cache` folder between runs, for example with +the CI's cache feature. Delete the folder to start over. + +The cache is not used if the compilation database uses the MSVC driver (`clang-cl` or `cl.exe`), +or forces a header in with `-include` or `-imacros` without a precompiled header. +A new header that hides another one on the include path or that `__has_include` looked for, and +changed environment variables, are not noticed. + ## New in v2 - [`--sarif-file`][sarif-file] writes clang-tidy diagnostics as a SARIF 2.1.0 file, for example to upload to GitHub code scanning. - [`--code-quality-file`][code-quality-file] writes clang-format and clang-tidy findings as a GitLab Code Quality report, to show them in GitLab merge requests. +- clang-tidy results are cached, described above. - [`--gen-patch`][gen-patch] and [`--gen-patch-path`][gen-patch-path] produce one patch of the clang-format and clang-tidy fixes, described above. - [`--mod-sys`][mod-sys] and [`--no-mod-sys`][no-mod-sys] control whether system package managers