diff --git a/docs/studio/behaviour/map.md b/docs/studio/behaviour/map.md index 986c0661..d9111b71 100644 --- a/docs/studio/behaviour/map.md +++ b/docs/studio/behaviour/map.md @@ -55,7 +55,7 @@ A law with `backing: "check"` has a test that stands behind it; one with `"trust The map file itself needs no owner and no `ignored` entry: `check` and `touched` both place `system-map.json` as ignored, and an `ignored` pattern that is exactly `system-map.json` never fails for matching nothing. So a new repository's map passes before and after it is first tracked. -**The link check.** A part is **read** when a named extractor reads at least one file it owns that is not one of its test files: `rust-modules` reads Rust files, `cargo` `Cargo.toml` files, `typescript-imports` script files, `go-imports` Go files, `java-imports` Java files, `python-imports` Python files, `dart-imports` Dart files, `php-imports` PHP files and `dotnet-projects` project files (`.csproj`, `.fsproj`, `.vbproj`), so two parts inside one project stay unproven. Between two read parts: +**The link check.** A part is **read** when a named extractor reads at least one file it owns that is not one of its test files: `rust-modules` reads Rust files, `cargo` `Cargo.toml` files, `typescript-imports` script files, `go-imports` Go files, `java-imports` Java files, `python-imports` Python files, `dart-imports` Dart files, `php-imports` PHP files, `c-includes` C and C++ files and `dotnet-projects` project files (`.csproj`, `.fsproj`, `.vbproj`), so two parts inside one project stay unproven. Between two read parts: - an `import` link with no computed edge in its direction fails: a dead link, or a backwards one, whose problem says to turn it around; - a computed edge with no `import` link in its direction fails, whatever run-time links join the pair, so a run-time link never hides a new dependency. (Before spec #473 such an edge was only a `note:`.) @@ -78,7 +78,7 @@ An extractor reads which tracked file depends on which; the checker turns each p - **Text only.** It reads the repository's tracked files as text and runs no toolchain, so a check gives the same answer on any machine and in CI. The one exception is `cargo metadata`, which both Rust extractors run (`docs/adr/0002-extractors-read-text-only.md`). - **The core's rules.** The checker, not the extractor, drops a pair whose ends are not both tracked and a pair from a file to itself, and keeps a pair several extractors find once. It runs the extractors in the map's `extractors` order, so their problems print in that order. -- **Skipped files are its own.** An extractor names the files of its language that the build leaves out, most often its test files, or ones the build never compiles. A skipped file gives no pair and never makes its part read. `typescript-imports` skips its test files, `go-imports` its test files and the files no build compiles, `java-imports` the files outside production source roots, `python-imports` its test files, `dart-imports` the files under its test folders or of a fixture package and the ones whose header it cannot lex, `php-imports` its test folders, the files only a `classmap` reaches and the files it cannot lex, and `dotnet-projects` its test projects (their sections say which); `cargo` and `rust-modules` skip none: they leave dev-dependencies out but read files under `tests/` and `#[cfg(test)]` code. +- **Skipped files are its own.** An extractor names the files of its language that the build leaves out, most often its test files, or ones the build never compiles. A skipped file gives no pair and never makes its part read. `typescript-imports` skips its test files, `go-imports` its test files and the files no build compiles, `java-imports` the files outside production source roots, `python-imports` its test files, `dart-imports` the files under its test folders or of a fixture package and the ones whose header it cannot lex, `php-imports` its test folders, the files only a `classmap` reaches and the files it cannot lex, `c-includes` its test folders and test-named files, and `dotnet-projects` its test projects (their sections say which); `cargo` and `rust-modules` skip none: they leave dev-dependencies out but read files under `tests/` and `#[cfg(test)]` code. - **Over-counts are stated.** An edge the code may not really hold is allowed only where its section below says so, as the barrel over-counts of `typescript-imports` are. - **Invisible dependencies are listed.** A dependency the text shows no import for is a silent under-count, and its section lists it. @@ -185,6 +185,23 @@ An extractor reads which tracked file depends on which; the checker turns each p - **Under-counts:** transitive use (A's code using C through B with no reference from A to C); every reference of a skipped project, which the rules also take from a production project that sits under a test folder, carries a test name or holds a test marker, unless it says `false`; references written in `Directory.Build.props`, `Directory.Build.targets` or another imported file, which are not read; shared projects (`.projitems`); legacy `` with a `HintPath` into another project's build output; linked sources (``), which compile another project's file with no reference; a wrongly cased reference, which builds on Windows and macOS but names no tracked file; and a mis-cased `itemgroup` or `include=`. - **Unsure:** a path built from a property other than the two read, from an item list, or holding a wildcard. +- `c-includes` (`system-map/src/extract/c/`): each `#include` of a C or C++ file, paired with the tracked file it names (spec #806, whose research note is `docs/studio/research/c-cpp-extractor.md` and decision record `docs/adr/0004-c-includes-an-ignored-copy-keeps-an-include-unsure.md`). It reads tracked files as text, needs no config file (no `CMakeLists.txt`, `Makefile` or `compile_commands.json` is read) and runs no compiler (`docs/adr/0002-extractors-read-text-only.md`). + + - **What it reads.** A tracked file whose extension, in any case, is one of `.c .h .cc .cpp .cxx .c++ .hpp .hh .hxx .h++ .inl .ipp .tcc`, the thirteen the research scanned. `.m`, `.mm`, `.cu`, `.inc`, `.def` and `.rc` are not read. In commit mode it reads the commit's texts. + - **The lexer** walks each file once. It skips `//` and `/* */` comments (an unclosed block comment hides the rest of the file), string and character literals, and C++ raw strings (`R"delim(...)delim"`), so an include in them gives nothing. A `'` inside a number (`1'000`, `0xFF'FF`) is a digit separator and opens no character literal. A block comment counts as one space, so code after it is at a line's start only when the comment began at one. A backslash at a line's end joins it to the next line. A directive is a line whose first non-space character is `#`, then optional spaces or tabs, then `include`, then `"path"` or ``; its site is the line of the `#`. `#include` followed by anything else (a macro name), `#include_next`, `#import` and `__has_include` give nothing. Conditional blocks are not evaluated: includes in every branch are read, `#if 0` included. + - **Paths.** A path is used as written, case-sensitively, less its `.` segments. An empty path, an absolute one (starting with `/`) or one holding a backslash gives nothing. + - **Skipped files.** A file with a folder named, in any case, `test`, `tests`, `testing`, `unittest` or `fuzz`, or named `*_test.*`, `*_tests.*` or `test_*.*`, is skipped: it gives no pair, never makes its part read and is never an include's target. `bench/` and names such as `testutil.cc` are not skipped. The scan's own test rule is another one. + - **Resolution, per include.** Each include goes through these steps in order, the first that settles it wins: + 1. **Next to the file.** A quoted include whose path, joined to the including file's folder and cleaned (`..` climbs), names a tracked file pairs with it, as the compiler's first search step finds it; an ignored or skipped file there gives no pair, and the search stops either way, as the compiler stops, with no fall-through to a match elsewhere. + 2. **System names.** An angle-bracket include whose path is on the system-header list gives nothing. The list (`system-map/src/extract/c/system_headers.rs`) is the C and C++ standard headers, the POSIX headers, any path under `sys/`, `linux/`, `mach/`, `machine/`, `bits/`, `netinet/`, `arpa/` or `net/`, common platform headers (`byteswap.h`, `cpuid.h`, `intrin.h` and the like) and common Windows CRT and SDK headers; it never applies to a quoted include. Without it, bitcoin's `` would match `src/compat/cpuid.h`. + 3. **Path-ending match.** A path with a `..` segment that did not resolve in step 1 gives nothing. Otherwise the candidates are the tracked files whose path equals the include's path or ends with `/` and the path, less skipped files; ignored files stay candidates. None, or only ignored ones: no pair. One live one: a pair. Some but not all ignored: Unsure. Two or more, none ignored: step 4. + 4. **The folder tie-break.** A candidate's implied folder is its path less `/` and the include's path (`.` when equal). A folder's evidence is the number of include directives, across all read files that are neither skipped nor ignored, that reached step 3 and had exactly one candidate (ignored or not) whose implied folder it is. When exactly one candidate's folder has evidence of 5 or more, that candidate is the pair; otherwise the include is Unsure. The evidence is counted over the whole repository before any tie is settled, so file order changes nothing. + - **Unsure.** An include is Unsure for one of two reasons, `an ignored copy matches it` (step 3) or `several files match it` (step 4, with no tie-break beyond the evidence rule). The finding lists every candidate; the including file relaxes only its links to the candidates' parts, and `--json` lists it under `unsure`. + - **`ignored`.** An ignored copy stays a candidate and keeps an include Unsure, even when the tie-break would pick a live file: redis's `` means `deps/hiredis/sds.h` while `src/sds.h` is also tracked, so dropping the ignored copy would draw a wrong line. This differs from `java-imports` on purpose, which leaves an ignored file out of its type index (ADR 0004). Includes inside an ignored file are never resolved. + - **Under-counts:** includes reached through a build's `-I` folder that the path-ending match can't settle; macro includes, `#include_next`, `#import`; generated headers (`curl_config.h`, `bitcoin-build-config.h`); headers outside the repository; includes from skipped test files, and non-test code's includes of test helpers (bitcoin's `src/bench/`); `..` paths that don't resolve next to the file; ties whose folders have fewer than 5 matches of evidence. + - **Over-counts:** every `#if` branch, `#if 0` included; an angle-bracket include of an outside library's header whose name isn't on the system list matches whenever exactly one tracked file anywhere has that path ending, the common case a wrapper named after the library it wraps (curl's `lib/vtls/rustls.h` for ``); platform-only includes such as curl's VMS `curlmsg_vms.h`. + - **The trial set.** The research ran it on curl, leveldb, bitcoin and redis (`docs/studio/research/c-cpp-extractor.md`, rounds 1 to 4). It sets no group: each include names one file. + **Import sites** (spec #477, "What an import site is"). Each file pair keeps the lines of the importing file that make it, each line once, and the core joins the lines when several extractors, or one twice, find the pair. A site is always in the importing file: - `rust-modules`: a `use` line is one site at its `use`, however many names its group brings in and however many lines it spans; an inline path is a site at its first word, once per line however many times the line writes it; a `mod` line is a site at its `mod`. @@ -194,6 +211,7 @@ An extractor reads which tracked file depends on which; the checker turns each p - `python-imports`: an import statement is a site at the line where it starts, its `from`, `lazy` or `import`, however many names or lines it spans; `import a, b` is one site for each pair it makes. - `dart-imports`: an `import`, `export` or `part` directive is a site at the line of its keyword, however many lines its URIs, `if (…)` configurations and clauses span; each URI of a conditional directive makes its own pair with that one site. - `php-imports`: a class `use` item is a site at the line of its name, so a group `use` over several lines gives each item its own line; a `require` or `include` is a site at the line of its keyword, however many lines its path spans. +- `c-includes`: an `#include` directive is a site at the line of its `#`, however many lines a backslash continuation spans. - `dotnet-projects`: a `ProjectReference` is a site at the line of its `<`, the first line of a start tag over several lines. - `cargo`: `cargo metadata` gives no lines, so the site is the importing crate's `Cargo.toml` at the line of the dependency's key (its rename, when it has one), found by a text search: a line `key = …` or `key.… = …`, bare or quoted, in a table of normal or build dependencies (a target's too, never `dev-dependencies` or a root manifest's `[workspace.dependencies]`), or a header `[dependencies.key]`. When no line matches, as for a top-level inline table `dependencies = { … }`, the site has no line. diff --git a/system-map/src/extract/c/lexer.rs b/system-map/src/extract/c/lexer.rs new file mode 100644 index 00000000..5f48d132 --- /dev/null +++ b/system-map/src/extract/c/lexer.rs @@ -0,0 +1,210 @@ +//! The `#include` directives of a C or C++ file (spec #806, "Finding includes"), found without running the +//! preprocessor: comments, string and character literals and C++ raw strings are skipped, a backslash at a line's end +//! joins it to the next, and no `#if` is evaluated. + +/// One `#include "path"` or `#include ` directive. +#[derive(Debug, PartialEq)] +pub(super) struct Include { + pub(super) path: String, + /// Whether it is `"path"` and not ``. + pub(super) quoted: bool, + /// The raw line of the `#`. + pub(super) line: u32, +} + +/// The directives of `text`, in order. +pub(super) fn includes(text: &str) -> Vec { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); + let (spliced, splices) = splice(text.as_bytes()); + let mut found = Vec::new(); + // The line counter only moves forward: `line` is the raw line at offset `counted`. + let mut line = 1u32; + let mut counted = 0usize; + let mut next_splice = 0usize; + let mut at_line_start = true; + let mut i = 0; + while i < spliced.len() { + match spliced[i] { + b'\n' => { + at_line_start = true; + i += 1; + } + b' ' | b'\t' | b'\r' | 0x0b | 0x0c => i += 1, + b'/' if spliced.get(i + 1) == Some(&b'/') => { + i = spliced[i..] + .iter() + .position(|&b| b == b'\n') + .map_or(spliced.len(), |n| i + n); + } + b'/' if spliced.get(i + 1) == Some(&b'*') => { + // A comment is one space, so it leaves the next code at a line's start only if it began at one. + i = find(&spliced, i + 2, b"*/").map_or(spliced.len(), |n| n + 2); + } + b'#' if at_line_start => { + if let Some((path, quoted, end)) = directive(&spliced, i + 1) { + for &b in &spliced[counted..i] { + line += u32::from(b == b'\n'); + } + while next_splice < splices.len() && splices[next_splice] <= i { + line += 1; + next_splice += 1; + } + counted = i; + found.push(Include { path, quoted, line }); + i = end; + } else { + i += 1; + } + at_line_start = false; + } + b'"' => { + at_line_start = false; + i = match raw_string_open(&spliced, i) { + Some(delimiter) => skip_raw_string(&spliced, i, delimiter), + None => skip_quoted(&spliced, i, b'"'), + }; + } + b'0'..=b'9' if i == 0 || !is_identifier(spliced[i - 1]) => { + at_line_start = false; + i = skip_number(&spliced, i); + } + b'\'' => { + at_line_start = false; + i = skip_quoted(&spliced, i, b'\''); + } + _ => { + at_line_start = false; + i += 1; + } + } + } + found +} + +/// `text` with every backslash-newline removed, and the offsets in the result where one was. +fn splice(text: &[u8]) -> (Vec, Vec) { + let mut out = Vec::with_capacity(text.len()); + let mut splices = Vec::new(); + let mut i = 0; + while i < text.len() { + if text[i] == b'\\' { + let after = match (text.get(i + 1), text.get(i + 2)) { + (Some(b'\n'), _) => Some(i + 2), + (Some(b'\r'), Some(b'\n')) => Some(i + 3), + _ => None, + }; + if let Some(after) = after { + splices.push(out.len()); + i = after; + continue; + } + } + out.push(text[i]); + i += 1; + } + (out, splices) +} + +/// The offset of the first `needle` at or after `from`. +fn find(text: &[u8], from: usize, needle: &[u8]) -> Option { + text.get(from..)? + .windows(needle.len()) + .position(|w| w == needle) + .map(|n| from + n) +} + +/// The directive after a `#` at `i - 1`: `include`, then `"path"` or `` on the same line. Its path, whether +/// quoted, and the offset past it. +fn directive(text: &[u8], mut i: usize) -> Option<(String, bool, usize)> { + let blanks = |mut at: usize| { + while matches!(text.get(at), Some(b' ' | b'\t')) { + at += 1; + } + at + }; + i = blanks(i); + text.get(i..)?.strip_prefix(b"include")?; + i += "include".len(); + if text.get(i).is_some_and(|&b| is_identifier(b)) { + return None; + } + i = blanks(i); + let (close, quoted) = match text.get(i)? { + b'"' => (b'"', true), + b'<' => (b'>', false), + _ => return None, + }; + let start = i + 1; + let len = text[start..] + .iter() + .position(|&b| b == close || b == b'\n')?; + if text[start + len] != close { + return None; + } + let path = String::from_utf8_lossy(&text[start..start + len]).into_owned(); + Some((path, quoted, start + len + 1)) +} + +/// For the `"` at `i`: the delimiter of the raw string it opens (`R"delimiter(`), when the prefix before it is one of +/// `R`, `LR`, `uR`, `UR` and `u8R`. +fn raw_string_open(text: &[u8], i: usize) -> Option<&[u8]> { + let start = text[..i] + .iter() + .rposition(|&b| !is_identifier(b)) + .map_or(0, |n| n + 1); + if !matches!(&text[start..i], b"R" | b"LR" | b"uR" | b"UR" | b"u8R") { + return None; + } + let rest = &text[i + 1..]; + let open = rest.iter().position(|&b| b == b'(')?; + let delimiter = &rest[..open]; + let valid = delimiter.len() <= 16 + && !delimiter + .iter() + .any(|b| matches!(b, b' ' | b'"' | b')' | b'\\' | b'\t' | b'\n' | b'\r')); + valid.then_some(delimiter) +} + +/// The offset past the raw string whose opening `"` is at `i`; the end of the text when it never closes. +fn skip_raw_string(text: &[u8], i: usize, delimiter: &[u8]) -> usize { + let mut closing = vec![b')']; + closing.extend_from_slice(delimiter); + closing.push(b'"'); + find(text, i + 1 + delimiter.len(), &closing).map_or(text.len(), |n| n + closing.len()) +} + +fn is_identifier(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' +} + +/// The offset past the number that begins with the digit at `i`: a preprocessing number, whose `'` before a digit or +/// letter is a digit separator (`1'000`, `0xFF'FF`), not a character literal. +fn skip_number(text: &[u8], i: usize) -> usize { + let mut at = i + 1; + while let Some(&b) = text.get(at) { + let next = text.get(at + 1).copied(); + at += match b { + b'e' | b'E' | b'p' | b'P' if matches!(next, Some(b'+' | b'-')) => 2, + b'\'' if next.is_some_and(is_identifier) => 2, + _ if is_identifier(b) || b == b'.' => 1, + _ => break, + }; + } + at +} + +/// The offset past the string or character literal opened at `i` by `quote`: at its closing quote, or at the line's end +/// when it never closes there. +fn skip_quoted(text: &[u8], i: usize, quote: u8) -> usize { + let mut at = i + 1; + while let Some(&b) = text.get(at) { + match b { + b'\n' => return at, + // An escape takes the next byte, but never the line's end: a lone backslash left there ends the literal. + b'\\' if text.get(at + 1) != Some(&b'\n') => at += 2, + _ if b == quote => return at + 1, + _ => at += 1, + } + } + text.len() +} diff --git a/system-map/src/extract/c/mod.rs b/system-map/src/extract/c/mod.rs new file mode 100644 index 00000000..51ab62c0 --- /dev/null +++ b/system-map/src/extract/c/mod.rs @@ -0,0 +1,115 @@ +//! The `c-includes` extractor: the `#include` directives of C and C++ files, read as text with no compiler, `cmake` or +//! `make` run (ADR 0002), each resolved to a tracked file and paired with it, or left Unsure (spec #806, "Resolution, +//! per include"; ADR 0004). + +mod lexer; +mod resolve; +mod system_headers; + +use std::collections::BTreeMap; + +use super::{Extractor, Output, Pair, Repo, Unsure, folders}; + +use lexer::includes; +use resolve::Settled; + +pub(crate) struct CIncludes; + +/// The extensions the reader reads, in any case: the thirteen the research scanned (spec #806, "What it reads"). +const EXTENSIONS: [&str; 13] = [ + "c", "h", "cc", "cpp", "cxx", "c++", "hpp", "hh", "hxx", "h++", "inl", "ipp", "tcc", +]; + +impl Extractor for CIncludes { + fn name(&self) -> &'static str { + "c-includes" + } + + fn reads(&self, file: &str) -> bool { + let name = file.rsplit('/').next().unwrap_or(file); + name.rsplit_once('.') + .is_some_and(|(_, ext)| EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e))) + } + + fn skips(&self, _repo: &Repo, file: &str) -> bool { + is_test_file(file) + } + + fn extract(&self, repo: &Repo) -> Output { + // Every include is settled as far as the path-ending match first, so that the folder evidence is counted over + // the whole repository before any tie is settled. + let index = resolve::Index::new(repo); + let mut evidence = BTreeMap::new(); + let mut settled = Vec::new(); + for &file in repo.files() { + if repo.is_ignored(file) || !self.reads(file) || is_test_file(file) { + continue; + } + let Some(text) = repo.read(file) else { + continue; + }; + for include in includes(&text) { + let Some(path) = resolve::clean(&include.path) else { + continue; + }; + let found = resolve::settle(repo, &index, file, &include, &path, &mut evidence); + settled.push((file, include, path, found)); + } + } + let mut output = Output::default(); + for (file, include, path, found) in settled { + let (reason, candidates) = match found { + Settled::Nothing => continue, + Settled::File(to) => { + output.pairs.push(Pair::at(file, &to, include.line)); + continue; + } + Settled::Tie(candidates) => { + if let Some(to) = resolve::tie_break(&candidates, &path, &evidence) { + output.pairs.push(Pair::at(file, &to, include.line)); + continue; + } + ("several files match it", candidates) + } + Settled::IgnoredCopy(candidates) => ("an ignored copy matches it", candidates), + }; + output.unsure.push(Unsure { + file: file.to_string(), + name: include.path, + reason: reason.to_string(), + candidates: candidates.iter().map(ToString::to_string).collect(), + }); + } + output + } + + #[cfg(test)] + fn fixture(&self) -> super::contract::Fixture { + use super::contract::{Case, Fixture, MissingConfig}; + Fixture { + support: Vec::new(), + source: |name| format!("src/{name}.c"), + importing: |_, to| format!("#include \"{}\"\n", to.rsplit('/').next().unwrap_or(to)), + plain: |_| "int x;\n".to_string(), + missing_config: MissingConfig::None, + malformed_config: None, + test_file: Some(|name| format!("tests/{name}_test.c")), + skip: vec![(Case::MalformedConfig, "c-includes has no config file")], + } + } +} + +/// Whether `file` is a test file (spec #806, "Skipped files"): in a folder named `test`, `tests`, `testing`, `unittest` +/// or `fuzz` in any case, or named `*_test.*`, `*_tests.*` or `test_*.*`. The scan's own `is_test` is another rule. +fn is_test_file(file: &str) -> bool { + let (folders, name) = file.rsplit_once('/').unwrap_or(("", file)); + folders.split('/').any(|folder| { + ["test", "tests", "testing", "unittest", "fuzz"] + .iter() + .any(|t| folder.eq_ignore_ascii_case(t)) + }) || name.contains("_test.") + || name.contains("_tests.") + || name + .strip_prefix("test_") + .is_some_and(|rest| rest.contains('.')) +} diff --git a/system-map/src/extract/c/resolve.rs b/system-map/src/extract/c/resolve.rs new file mode 100644 index 00000000..02baf4d6 --- /dev/null +++ b/system-map/src/extract/c/resolve.rs @@ -0,0 +1,141 @@ +//! Resolving an include to a tracked file (spec #806, "Resolution, per include"; ADR 0004). +//! +//! Steps 1 and 2 need only the include and the file; steps 3 and 4 need the whole repository. So the reader first +//! settles each include as far as the path-ending match, counts the evidence for the folder tie-break over every +//! include, and only then settles the ties, which is why the result doesn't depend on file order. + +use std::collections::{BTreeMap, HashMap}; + +use super::lexer::Include; +use super::system_headers::is_system; +use super::{Repo, folders, is_test_file}; + +/// How many includes, each with one candidate, a folder needs for it to settle a tie (research, round 4, item 2). +const EVIDENCE: usize = 5; + +/// The tracked files, keyed by their last path segment, built once per run. +pub(super) struct Index<'a> { + by_name: HashMap<&'a str, Vec<&'a str>>, +} + +impl<'a> Index<'a> { + pub(super) fn new(repo: &Repo<'a>) -> Self { + let mut by_name: HashMap<&str, Vec<&str>> = HashMap::new(); + for &file in repo.files() { + by_name + .entry(file.rsplit('/').next().unwrap_or(file)) + .or_default() + .push(file); + } + Index { by_name } + } + + /// The tracked files equal to `path` or ending in `/` and `path`, less skipped files, sorted; ignored files stay. + fn candidates(&self, path: &str) -> Vec<&'a str> { + let name = path.rsplit('/').next().unwrap_or(path); + self.by_name + .get(name) + .into_iter() + .flatten() + .copied() + .filter(|file| ends_with_path(file, path) && !is_test_file(file)) + .collect() + } +} + +/// Whether `file` is `path` or ends in `/` followed by it. +fn ends_with_path(file: &str, path: &str) -> bool { + file.strip_suffix(path) + .is_some_and(|rest| rest.is_empty() || rest.ends_with('/')) +} + +/// The folder `file` implies for `path`: `file` less `/` and `path`, or `.` when they are equal. +fn implied_folder<'a>(file: &'a str, path: &str) -> &'a str { + file.len() + .checked_sub(path.len() + 1) + .map_or(".", |end| &file[..end]) +} + +/// What an include came to before the folder tie-break. +pub(super) enum Settled<'a> { + Nothing, + File(String), + /// Several candidates, none ignored, for the tie-break. + Tie(Vec<&'a str>), + /// Some but not all candidates are ignored. + IgnoredCopy(Vec<&'a str>), +} + +/// The path of `include` as written, less its `.` segments; none for an empty path, an absolute one or one with a +/// backslash (spec #806, "Paths"). +pub(super) fn clean(path: &str) -> Option { + if path.starts_with('/') || path.contains('\\') { + return None; + } + let kept: Vec<&str> = path.split('/').filter(|s| *s != ".").collect(); + let cleaned = kept.join("/"); + (!cleaned.is_empty()).then_some(cleaned) +} + +/// Steps 1 to 3 for one include of `from`, and `path` its cleaned path. A folder's evidence is added to `evidence` for +/// an include with exactly one candidate. +pub(super) fn settle<'a>( + repo: &Repo, + index: &Index<'a>, + from: &str, + include: &Include, + path: &str, + evidence: &mut BTreeMap, +) -> Settled<'a> { + // Step 1: next to the file. + if include.quoted + && let Some(near) = folders::join(folders::folder_of(from), path) + && repo.files().contains(near.as_str()) + { + return if repo.is_ignored(&near) || is_test_file(&near) { + Settled::Nothing + } else { + Settled::File(near) + }; + } + // Step 2: system names. + if !include.quoted && is_system(path) { + return Settled::Nothing; + } + // A `..` path is resolved only next to the file. + if path.split('/').any(|s| s == "..") { + return Settled::Nothing; + } + // Step 3: the path-ending match. + let candidates = index.candidates(path); + if let [only] = candidates[..] { + *evidence + .entry(implied_folder(only, path).to_string()) + .or_default() += 1; + } + let ignored = candidates.iter().filter(|c| repo.is_ignored(c)).count(); + match (candidates.len(), ignored) { + (0, _) => Settled::Nothing, + (n, i) if i == n => Settled::Nothing, + (1, _) => Settled::File(candidates[0].to_string()), + (_, 0) => Settled::Tie(candidates), + _ => Settled::IgnoredCopy(candidates), + } +} + +/// Step 4: the one candidate whose implied folder has evidence of 5 or more, when exactly one has. +pub(super) fn tie_break( + candidates: &[&str], + path: &str, + evidence: &BTreeMap, +) -> Option { + let mut backed = candidates.iter().filter(|c| { + evidence + .get(implied_folder(c, path)) + .is_some_and(|n| *n >= EVIDENCE) + }); + match (backed.next(), backed.next()) { + (Some(one), None) => Some(one.to_string()), + _ => None, + } +} diff --git a/system-map/src/extract/c/system_headers.rs b/system-map/src/extract/c/system_headers.rs new file mode 100644 index 00000000..c1fee414 --- /dev/null +++ b/system-map/src/extract/c/system_headers.rs @@ -0,0 +1,54 @@ +//! The system-header list: the names an angle-bracket include gives nothing for, so that a tracked file sharing a +//! system header's name (bitcoin's `src/util/string.h`) never catches `` (spec #806, "The system-header +//! list"). It holds exactly the lists the research measured with (`docs/studio/research/c-cpp-extractor.md`, "Round 2 +//! method": `STD`, `PLATFORM`, `SYS_PREFIX`; "Round 4 method": `WIN`), so the trials' zero wrong lines carry over. + +/// The C (C23) and C++ standard headers and the POSIX headers, whitespace-separated. Sources: cppreference, "C Standard +/// Library header files" (https://en.cppreference.com/w/c/header) and "C++ Standard Library headers" +/// (https://en.cppreference.com/w/cpp/header), with the `c`-prefixed compatibility headers; the POSIX.1-2024 "Headers" +/// index (https://pubs.opengroup.org/onlinepubs/9799919799/idx/head.html). +const STD: &str = "assert.h complex.h ctype.h errno.h fenv.h float.h inttypes.h iso646.h limits.h +locale.h math.h setjmp.h signal.h stdalign.h stdarg.h stdatomic.h stdbit.h stdbool.h stdckdint.h +stddef.h stdint.h stdio.h stdlib.h stdnoreturn.h string.h tgmath.h threads.h time.h uchar.h +wchar.h wctype.h aio.h arpa/inet.h cpio.h devctl.h dirent.h dlfcn.h endian.h fcntl.h fmtmsg.h +fnmatch.h ftw.h glob.h grp.h iconv.h langinfo.h libintl.h libgen.h monetary.h mqueue.h ndbm.h +net/if.h netdb.h netinet/in.h netinet/tcp.h nl_types.h poll.h pthread.h pwd.h regex.h sched.h +search.h semaphore.h spawn.h strings.h syslog.h tar.h termios.h unistd.h utmpx.h wordexp.h +algorithm any array atomic barrier bit bitset cassert ccomplex cctype cerrno cfenv cfloat charconv +chrono cinttypes ciso646 climits clocale cmath codecvt compare complex concepts condition_variable +contracts coroutine csetjmp csignal cstdalign cstdarg cstdbool cstddef cstdint cstdio cstdlib +cstring ctgmath ctime cuchar cwchar cwctype debugging deque exception execution expected +filesystem flat_map flat_set format forward_list fstream functional future generator +hazard_pointer hive initializer_list inplace_vector iomanip ios iosfwd iostream istream iterator +latch limits linalg list locale map mdspan memory memory_resource meta mutex new numbers numeric +optional ostream print queue random ranges ratio rcu regex scoped_allocator semaphore set +shared_mutex simd source_location span spanstream sstream stack stacktrace stdexcept stdfloat +stop_token streambuf string string_view strstream syncstream system_error text_encoding thread +tuple type_traits typeindex typeinfo unordered_map unordered_set utility valarray variant vector +version"; + +/// Common platform headers outside those standards: the glibc manual (`byteswap.h`, `malloc.h`, `alloca.h`, +/// `execinfo.h`, `features.h`), GCC's and Arm's intrinsics documentation (`cpuid.h`, `intrin.h`, `immintrin.h`, +/// `x86intrin.h`, `emmintrin.h`, `arm_neon.h`) and Microsoft Learn (`windows.h`, `winsock2.h`, `ws2tcpip.h`, `io.h`). +const PLATFORM: &str = + "byteswap.h malloc.h alloca.h execinfo.h features.h cpuid.h windows.h winsock2.h +ws2tcpip.h io.h intrin.h immintrin.h x86intrin.h emmintrin.h arm_neon.h"; + +/// Paths starting with these name a system folder's headers (glibc and the BSD and Darwin systems). +const SYS_PREFIX: [&str; 8] = [ + "sys/", "linux/", "mach/", "machine/", "bits/", "netinet/", "arpa/", "net/", +]; + +/// Windows CRT and SDK headers, plus `memory.h`: Microsoft Learn, "C runtime library reference" and the Windows SDK +/// headers. +const WIN: &str = + "process.h schannel.h windows.h winsock2.h ws2tcpip.h io.h direct.h malloc.h conio.h +tchar.h memory.h"; + +/// Whether `path`, written in angle brackets, is a system header. +pub(super) fn is_system(path: &str) -> bool { + SYS_PREFIX.iter().any(|p| path.starts_with(p)) + || [STD, PLATFORM, WIN] + .iter() + .any(|list| list.split_whitespace().any(|name| name == path)) +} diff --git a/system-map/src/extract/mod.rs b/system-map/src/extract/mod.rs index ddaecf21..2686bf52 100644 --- a/system-map/src/extract/mod.rs +++ b/system-map/src/extract/mod.rs @@ -2,6 +2,7 @@ //! depends on which (spec #529, "The contract"). Each is one module behind [`Extractor`], registered in //! [`registry::EXTRACTORS`]; the core here runs the ones a map names and holds their output to the contract. +mod c; mod cargo; #[cfg(test)] mod contract; diff --git a/system-map/src/extract/registry.rs b/system-map/src/extract/registry.rs index 8e8232b5..de4f9f7f 100644 --- a/system-map/src/extract/registry.rs +++ b/system-map/src/extract/registry.rs @@ -1,9 +1,9 @@ //! The extractors a map may name, one line each. Registering an extractor here also runs the contract cases on it. use super::{ - Extractor, cargo::Cargo, dart::DartImports, dotnet::DotnetProjects, go::GoImports, - java::JavaImports, php::PhpImports, python::PythonImports, rust_modules::RustModules, - typescript::TypescriptImports, + Extractor, c::CIncludes, cargo::Cargo, dart::DartImports, dotnet::DotnetProjects, + go::GoImports, java::JavaImports, php::PhpImports, python::PythonImports, + rust_modules::RustModules, typescript::TypescriptImports, }; pub(crate) const EXTRACTORS: &[&dyn Extractor] = &[ @@ -16,4 +16,5 @@ pub(crate) const EXTRACTORS: &[&dyn Extractor] = &[ &DartImports, &PhpImports, &DotnetProjects, + &CIncludes, ]; diff --git a/system-map/src/scan.rs b/system-map/src/scan.rs index bb105fd0..010badd2 100644 --- a/system-map/src/scan.rs +++ b/system-map/src/scan.rs @@ -79,6 +79,14 @@ const LANGUAGES: &[(&str, &str)] = &[ ("cpp", "C++"), ("cc", "C++"), ("hpp", "C++"), + ("cxx", "C++"), + ("c++", "C++"), + ("hh", "C++"), + ("hxx", "C++"), + ("h++", "C++"), + ("inl", "C++"), + ("ipp", "C++"), + ("tcc", "C++"), ("sql", "SQL"), ("sh", "Shell"), ("proto", "Protobuf"), diff --git a/system-map/tests/c.rs b/system-map/tests/c.rs new file mode 100644 index 00000000..6d8119f7 --- /dev/null +++ b/system-map/tests/c.rs @@ -0,0 +1,619 @@ +//! `c-includes`: C and C++ repositories in temporary folders, read through `check` (spec #806, "Testing Decisions"): +//! the reader's lexing, the thirteen extensions, the includes next to the including file, skipped files and detection. + +use serde_json::{Value, json}; + +use crate::common::{ + assert_only_candidate_links_relaxed, extractor_map, pairs, repo, report, run, sites, write, +}; + +/// A map naming `c-includes` that gives every tracked file but `ignored` ones its own part, so that a file pair is a +/// pair of parts and shows in the pairs, and with no link. +fn per_file(files: &[(&str, &str)], ignored: &[&str]) -> Value { + let owned: Vec = files + .iter() + .map(|(f, _)| f.to_string()) + .filter(|f| !ignored.iter().any(|i| f.starts_with(i))) + .collect(); + let ids: Vec = (0..owned.len()).map(|i| format!("p{i}")).collect(); + let parts: Vec<(&str, Vec<&str>)> = ids + .iter() + .zip(&owned) + .map(|(id, f)| (id.as_str(), vec![f.as_str()])) + .collect(); + let parts: Vec<(&str, &[&str])> = parts.iter().map(|(id, p)| (*id, p.as_slice())).collect(); + extractor_map("c-includes", &parts, &[], ignored) +} + +/// The file pairs `files` give, with the folders `ignored` ignored. +fn c_pairs(files: &[(&str, &str)], ignored: &[&str]) -> Vec { + let (_dir, root) = repo(&per_file(files, ignored), files); + pairs(&report(&root)) +} + +const A_TO_X: &str = "src/a.c>src/x.h"; + +#[test] +fn the_thirteen_extensions_are_read_in_any_case_and_no_others() { + let read = [ + "c", "h", "cc", "cpp", "cxx", "c++", "hpp", "hh", "hxx", "h++", "inl", "ipp", "tcc", "C", + "HPP", "Cc", + ]; + for ext in read { + let from = format!("src/a.{ext}"); + let found = c_pairs(&[(&from, "#include \"x.h\"\n"), ("src/x.h", "")], &[]); + assert_eq!(found, [format!("{from}>src/x.h")], ".{ext}"); + } + for ext in ["m", "mm", "cu", "inc", "def", "rc", "txt"] { + let from = format!("src/a.{ext}"); + let found = c_pairs(&[(&from, "#include \"x.h\"\n"), ("src/x.h", "")], &[]); + assert_eq!(found, Vec::::new(), ".{ext}"); + } +} + +#[test] +fn a_quoted_include_pairs_with_a_file_next_to_the_including_file() { + let from_main = |to: &[&str]| { + to.iter() + .map(|t| format!("src/a.c>{t}")) + .collect::>() + }; + for (text, expected) in [ + ("#include \"x.h\"\n", from_main(&["src/x.h"])), + ("#include \"./x.h\"\n", from_main(&["src/x.h"])), + ("#include \"sub/../x.h\"\n", from_main(&["src/x.h"])), + ("#include \"../top.h\"\n", from_main(&["top.h"])), + ( + "#include \"x.h\"\n#include \"../top.h\"\n", + from_main(&["src/x.h", "top.h"]), + ), + // Not next to the file: the path-ending match settles an angle bracket and a root-relative path. + ("#include \n", from_main(&["src/x.h"])), + ("#include \"src/x.h\"\n", from_main(&["src/x.h"])), + ("#include \n", from_main(&["src/x.h"])), + // A path naming no tracked file, and a climb above the root. + ("#include \"gone.h\"\n", vec![]), + ("#include \"../../top.h\"\n", vec![]), + // A `..` path that does not resolve next to the file never reaches the path-ending match. + ("#include \"../x.h\"\n", vec![]), + ("#include <../x.h>\n", vec![]), + ("#include \"sub/../../x.h\"\n", vec![]), + // An empty, absolute or backslashed path. + ("#include \"\"\n", vec![]), + ("#include \"/src/x.h\"\n", vec![]), + ("#include \"sub\\\\..\\\\x.h\"\n", vec![]), + ("#include \"\\\\x.h\"\n", vec![]), + ("#include \".\"\n", vec![]), + ("#include <>\n", vec![]), + ] { + let files = [("src/a.c", text), ("src/x.h", ""), ("top.h", "")]; + let (_dir, root) = repo(&per_file(&files, &[]), &files); + let found = report(&root); + assert_eq!(pairs(&found), expected, "{text}"); + // An include that pairs with nothing is no problem either. + if expected.is_empty() { + assert_eq!(found.problems, Vec::::new(), "{text}"); + } + } +} + +#[test] +fn the_pair_carries_the_line_of_the_directive() { + let (_dir, root) = repo( + &per_file(&[("src/a.c", ""), ("src/x.h", "")], &[]), + &[("src/a.c", "int a;\n\n#include \"x.h\"\n"), ("src/x.h", "")], + ); + assert_eq!(sites(&root, &[]), ["src/a.c>src/x.h src/a.c:3"]); +} + +#[test] +fn an_ignored_or_skipped_file_gives_no_pair_and_an_adjacent_one_stops_the_search() { + let text = "#include \"x.h\"\n"; + // The files, the ignored folders, and whether `src/a.c` is Unsure. + for (files, ignored, unsure) in [ + // An ignored copy elsewhere, which keeps the include Unsure. + ( + vec![("src/a.c", text), ("src/gen/x.h", ""), ("x.h", "")], + vec!["src/gen/"], + true, + ), + // An ignored sibling stops the search before a live copy elsewhere. + ( + vec![("src/a.c", text), ("src/x.h", ""), ("lib/x.h", "")], + vec!["src/x.h"], + false, + ), + // A skipped sibling: `test_x.h` is named like a test file. + ( + vec![("src/a.c", "#include \"test_x.h\"\n"), ("src/test_x.h", "")], + vec![], + false, + ), + // An including file the map ignores. + ( + vec![("gen/a.c", text), ("gen/x.h", ""), ("b.c", "")], + vec!["gen/"], + false, + ), + ] { + let ignored: Vec<&str> = ignored; + let (_dir, root) = repo(&per_file(&files, &ignored), &files); + let found = report(&root); + assert_eq!(pairs(&found), Vec::::new(), "{files:?}"); + assert_eq!(!found.unsure.is_empty(), unsure, "{files:?}"); + } + // The ignored sibling itself. + let found = c_pairs( + &[ + ("src/a.c", text), + ("src/x.h", ""), + ("gen/b.c", "#include \"x.h\"\n"), + ("gen/x.h", ""), + ], + &["gen/"], + ); + assert_eq!(found, [A_TO_X]); +} + +#[test] +fn the_lexer_reads_what_the_preprocessor_reads() { + // The lines of `src/a.c` that pair with `src/x.h`, for the text of `src/a.c`. + let cases: [(&str, &str, &[u32]); 35] = [ + ("a line comment", "// #include \"x.h\"\n", &[]), + ("a block comment", "/* \n#include \"x.h\"\n*/\n", &[]), + ( + "a block comment, then code", + "/* c */\n#include \"x.h\"\n", + &[2], + ), + ("an unclosed block comment", "/* \n#include \"x.h\"\n", &[]), + ( + "a string", + "const char *s = \"\n#include \\\"x.h\\\"\n\";\n", + &[], + ), + ( + "a string with an include inside", + "char *s = \"#include \\\"x.h\\\"\";\n", + &[], + ), + ( + "a raw string", + "const char *s = R\"d(\n#include \"x.h\"\n)d\";\n", + &[], + ), + ( + "code after a raw string", + "const char *s = R\"d(x)d\";\n#include \"x.h\"\n", + &[2], + ), + ("a char literal", "char c = '\"';\n#include \"x.h\"\n", &[2]), + ( + "a comment opener inside a string", + "const char *s = \"/*\";\n#include \"x.h\"\n", + &[2], + ), + ( + "a backslash before a line's end in a character literal", + "#error don't \\\\\n\n#include \"x.h\"\n", + &[3], + ), + ("spaces after the hash", "# include \"x.h\"\n", &[1]), + ("a space before the hash", " # include \"x.h\"\n", &[1]), + ("tabs", "#\tinclude\t\"x.h\"\n", &[1]), + ("a backslash continuation", "#include \\\n \"x.h\"\n", &[1]), + ( + "a continuation moves the later lines", + "#define A \\\n 1\n#include \"x.h\"\n", + &[3], + ), + ("a macro", "#include MACRO\n", &[]), + ("include_next", "#include_next \"x.h\"\n", &[]), + ("import", "#import \"x.h\"\n", &[]), + ("has_include", "#if __has_include(\"x.h\")\n#endif\n", &[]), + ("the word is not a directive", "#includes \"x.h\"\n", &[]), + ( + "both branches", + "#if A\n#include \"x.h\"\n#else\n#include \"x.h\"\n#endif\n", + &[2, 4], + ), + ("if zero", "#if 0\n#include \"x.h\"\n#endif\n", &[2]), + ("not at a line start", "int a; #include \"x.h\"\n", &[]), + ( + "a comment before the hash", + "/* c */ #include \"x.h\"\n", + &[1], + ), + ("a closing quote missing", "#include \"x.h\n", &[]), + ( + "a comment spanning lines after code", + "int a; /* c\n c */ #include \"x.h\"\n", + &[], + ), + // A `'` inside a number is a digit separator, not a character literal. + ( + "a digit separator", + "int a = 1'000; /* c\n#include \"x.h\"\n*/\n", + &[], + ), + ( + "a digit separator before a raw string", + "int a = 1'0 + R\"(\n#include \"x.h\"\n)\";\n", + &[], + ), + ( + "a hex digit separator", + "int a = 0xFF'FF; /* c\n#include \"x.h\"\n*/\n", + &[], + ), + ( + "a binary digit separator", + "int a = 0b1'0; /* c\n#include \"x.h\"\n*/\n", + &[], + ), + // A prefixed character literal still opens one, so the `/*` inside it opens no comment. + ( + "a u8 char literal", + "char c = u8'/*';\n#include \"x.h\"\n", + &[2], + ), + ( + "an L char literal", + "char c = L'/*';\n#include \"x.h\"\n", + &[2], + ), + ( + "a u char literal", + "char c = u'/*';\n#include \"x.h\"\n", + &[2], + ), + ( + "a U char literal", + "char c = U'/*';\n#include \"x.h\"\n", + &[2], + ), + ]; + for (name, text, lines) in cases { + let (_dir, root) = repo( + &per_file(&[("src/a.c", ""), ("src/x.h", "")], &[]), + &[("src/a.c", text), ("src/x.h", "")], + ); + let expected: Vec = lines + .iter() + .map(|l| format!("src/a.c>src/x.h src/a.c:{l}")) + .collect(); + assert_eq!(sites(&root, &[]), expected, "{name}"); + } +} + +#[test] +fn a_test_file_makes_no_pair_and_does_not_make_its_part_read() { + let skipped = [ + "tests/a.c", + "src/Test/a.c", + "fuzz/a.c", + "src/testing/a.c", + "src/unittest/a.c", + "src/a_test.cc", + "src/a_tests.cc", + "src/test_a.c", + ]; + let read = ["src/testutil.cc", "bench/a.cc", "src/attest.c", "src/a.c"]; + // Each file includes its sibling `sib.h`, and its part `t` links to `lib`, which it does not include. + let text = "#include \"sib.h\"\n"; + for (file, is_read) in skipped + .iter() + .map(|f| (f, false)) + .chain(read.iter().map(|f| (f, true))) + { + let to = "lib/x.h"; + let from_dir = file.rsplit_once('/').unwrap().0; + let files = [ + (*file, text), + (&format!("{from_dir}/sib.h")[..], ""), + (to, ""), + ]; + let mut map = extractor_map( + "c-includes", + &[ + ("t", &[*file]), + ("lib", &["lib/"]), + ("sib", &[&format!("{from_dir}/sib.h")]), + ], + &[("t", "lib")], + &[], + ); + map["ignored"] = json!(["system-map.json"]); + let (_dir, root) = repo(&map, &files); + let found = report(&root); + let edges = pairs(&found); + let sib_pairs = edges.iter().any(|p| p.starts_with(file)); + let link_fails = found + .problems + .iter() + .any(|p| p.contains("runs from \"t\" to \"lib\"")); + assert_eq!(sib_pairs, is_read, "{file}: {edges:?}"); + // A read part's link without a dependency fails; an unread part's link passes as unproven. + assert_eq!(link_fails, is_read, "{file}: {:?}", found.problems); + } +} + +#[test] +fn check_suggests_c_includes_only_for_a_repository_with_a_production_c_file_the_map_does_not_ignore() + { + let note = "note: c-includes could read this repository; add it to extractors\n"; + let mut ignoring = extractor_map("c-includes", &[("a", &["**"])], &[], &["gen/"]); + ignoring["extractors"] = json!([]); + for (files, expected) in [ + (&[("src/a.c", "")][..], note), + (&[("src/a.HPP", "")], note), + ( + &[("tests/a.c", ""), ("fuzz/b.c", ""), ("src/a_test.cc", "")], + "", + ), + (&[("gen/a.c", "")], ""), + (&[("src/a.m", "")], ""), + (&[("tests/a.c", ""), ("src/b.c", "")], note), + ] { + let (_dir, root) = repo(&ignoring, files); + let out = run(&root, "check", &[]); + assert_eq!(String::from_utf8_lossy(&out.stderr), expected, "{files:?}"); + } +} + +#[test] +fn commit_mode_gives_the_pairs_of_the_working_tree() { + let files = [ + ("a/a.c", "#include \"../b/b.h\"\n"), + ("b/b.h", "#include \"../a/a.h\"\n"), + ("a/a.h", ""), + ]; + let (dir, root) = repo( + &extractor_map( + "c-includes", + &[("a", &["a/"]), ("b", &["b/"])], + &[("a", "b"), ("b", "a")], + &[], + ), + &files, + ); + let tree = run(&root, "check", &["--json"]); + let commit = run(&root, "check", &["--json", "--commit", "HEAD"]); + assert_eq!( + String::from_utf8_lossy(&commit.stdout), + String::from_utf8_lossy(&tree.stdout) + ); + assert_eq!( + sites(&root, &["--commit", "HEAD"]), + ["a/a.c>b/b.h a/a.c:1", "b/b.h>a/a.h b/b.h:1"] + ); + // An edit not committed changes nothing at the commit. + write(dir.path(), "a/a.c", "int a;\n"); + assert_eq!( + sites(&root, &["--commit", "HEAD"]), + ["a/a.c>b/b.h a/a.c:1", "b/b.h>a/a.h b/b.h:1"] + ); +} + +/// The files that make `n` unique includes of `<{tag}{i}.h>`, each header in `folder` and each included from a source +/// of its own. +fn evidence(folder: &str, tag: &str, n: usize) -> Vec<(String, String)> { + (0..n) + .flat_map(|i| { + [ + (format!("m/{tag}e{i}.c"), format!("#include <{tag}{i}.h>\n")), + (format!("{folder}{tag}{i}.h"), String::new()), + ] + }) + .collect() +} + +fn owned(files: &[(String, String)]) -> Vec<(&str, &str)> { + files + .iter() + .map(|(a, b)| (a.as_str(), b.as_str())) + .collect() +} + +#[test] +fn a_system_name_gives_nothing_for_an_angle_bracket_include_only() { + for (include, tracked) in [ + ("", "util/string.h"), + ("", "compat/sys/time.h"), + ("", "win/windows.h"), + ("", "compat/cpuid.h"), + ("", "util/vector"), + ("", "compat/linux/x.h"), + ("", "compat/arpa/inet.h"), + ("", "util/memory.h"), + ("", "util/direct.h"), + ] { + let text = format!("#include {include}\n"); + let found = c_pairs(&[("src/a.c", &text), (tracked, "")], &[]); + assert_eq!(found, Vec::::new(), "{include}"); + } + // A name not on the list matches, and a quoted include of a listed name does too, elsewhere or next to the file. + for (include, tracked) in [ + ("", "util/mystring.h"), + ("\"string.h\"", "util/string.h"), + ("\"string.h\"", "src/string.h"), + ] { + let text = format!("#include {include}\n"); + let found = c_pairs(&[("src/a.c", &text), (tracked, "")], &[]); + assert_eq!(found, [format!("src/a.c>{tracked}")], "{include}"); + } +} + +#[test] +fn candidates_are_files_whose_path_ends_with_the_include_after_a_slash() { + for (text, files, expected) in [ + // The path ends the candidate's path only at a folder boundary. + ("#include \n", vec![("lib/ax.h", "")], vec![]), + ("#include \n", vec![("lib/ab/x.h", "")], vec![]), + ( + "#include \n", + vec![("lib/a/b/x.h", "")], + vec!["lib/a/b/x.h"], + ), + ("#include \n", vec![("x.h", "")], vec!["x.h"]), + // A skipped file is not a candidate, so the other file is the only one. + ( + "#include \n", + vec![("lib/x.h", ""), ("tests/x.h", "")], + vec!["lib/x.h"], + ), + ("#include \n", vec![("tests/x.h", "")], vec![]), + // A tie between a production header and test ones is the production one. + ( + "#include \n", + vec![("src/x.h", ""), ("tests/x.h", ""), ("fuzz/x.h", "")], + vec!["src/x.h"], + ), + // A sibling wins over a root-relative match elsewhere. + ( + "#include \"db/x.h\"\n", + vec![("src/db/x.h", ""), ("db/x.h", "")], + vec!["src/db/x.h"], + ), + // An angle bracket skips the including file's folder: with its sibling and another copy it is Unsure. + ( + "#include \n", + vec![("src/x.h", ""), ("lib/x.h", "")], + vec![], + ), + ] { + let mut all = vec![("src/a.c", text)]; + all.extend(files); + let found = c_pairs(&all, &[]); + let expected: Vec = expected.iter().map(|t| format!("src/a.c>{t}")).collect(); + assert_eq!(found, expected, "{text} {all:?}"); + } +} + +#[test] +fn a_tie_is_settled_by_the_folder_five_unique_matches_use() { + for (name, ev, extra, expected) in [ + ("five settle it", 5, 0, Some("src/chain.h")), + ("four do not", 4, 0, None), + ("two folders with five each stay unsure", 5, 5, None), + ] { + let mut files = evidence("src/", "a", ev); + files.extend(evidence("src/kernel/", "b", extra)); + files.push(("src/chain.h".into(), String::new())); + files.push(("src/kernel/chain.h".into(), String::new())); + files.push(("src/kernel/c.cc".into(), "#include \n".into())); + let found: Vec = c_pairs(&owned(&files), &[]) + .into_iter() + .filter(|p| p.starts_with("src/kernel/c.cc")) + .collect(); + let expected: Vec = expected + .iter() + .map(|t| format!("src/kernel/c.cc>{t}")) + .collect(); + assert_eq!(found, expected, "{name}"); + } +} + +#[test] +fn evidence_does_not_depend_on_file_order() { + // The includes that are the evidence sort after the tie's file, and before it. + for prefix in ["a", "z"] { + let mut files: Vec<(String, String)> = (0..5) + .flat_map(|i| { + [ + (format!("{prefix}/e{i}.c"), format!("#include \n")), + (format!("lib/u{i}.h"), String::new()), + ] + }) + .collect(); + files.push(("lib/chain.h".into(), String::new())); + files.push(("lib/kernel/chain.h".into(), String::new())); + files.push(("m/c.cc".into(), "#include \n".into())); + let found: Vec = c_pairs(&owned(&files), &[]) + .into_iter() + .filter(|p| p.starts_with("m/c.cc")) + .collect(); + assert_eq!(found, ["m/c.cc>lib/chain.h"], "{prefix}"); + } +} + +#[test] +fn an_ignored_copy_keeps_the_include_unsure_even_with_evidence_for_the_live_one() { + let mut files = evidence("src/", "a", 5); + files.push(("src/sds.h".into(), String::new())); + files.push(("deps/hiredis/sds.h".into(), String::new())); + files.push(("src/cli.c".into(), "#include \n".into())); + let files = owned(&files); + let found = c_pairs(&files, &["deps/"]); + assert!( + !found.iter().any(|p| p.starts_with("src/cli.c")), + "{found:?}" + ); + let (_dir, root) = repo(&per_file(&files, &["deps/"]), &files); + let value: Value = serde_json::from_slice(&run(&root, "check", &["--json"]).stdout).unwrap(); + assert_eq!( + value["unsure"], + json!([{ + "file": "src/cli.c", + "name": "sds.h", + "reason": "an ignored copy matches it", + "candidates": ["src/sds.h"] + }]) + ); +} + +#[test] +fn an_include_matching_only_an_ignored_file_gives_nothing_and_no_unsure() { + let files = [("src/a.c", "#include \n"), ("deps/sds.h", "")]; + assert_eq!(c_pairs(&files, &["deps/"]), Vec::::new()); + let (_dir, root) = repo(&per_file(&files, &["deps/"]), &files); + let value: Value = serde_json::from_slice(&run(&root, "check", &["--json"]).stdout).unwrap(); + assert!(value["unsure"].is_null(), "{value}"); +} + +/// A repository where `app` includes ``, which two other parts hold, and a third part `other` holds a file `app` +/// also links to. +fn two_x() -> (tempfile::TempDir, String) { + let files = [ + ("app/a.c", "#include \n"), + ("xa/x.h", ""), + ("xb/x.h", ""), + ("other/o.h", ""), + ]; + repo( + &extractor_map( + "c-includes", + &[ + ("app", &["app/"]), + ("xa", &["xa/"]), + ("xb", &["xb/"]), + ("other", &["other/"]), + ], + &[("app", "xa"), ("app", "xb"), ("app", "other")], + &[], + ), + &files, + ) +} + +#[test] +fn several_matches_make_the_importer_unsure_and_relax_only_the_candidates_links() { + let (_dir, root) = two_x(); + assert_only_candidate_links_relaxed( + &root, + "note: app/a.c is unsure of x.h; its links to xa, xb pass as unproven\n", + "app", + "other", + ); + let value: Value = serde_json::from_slice(&run(&root, "check", &["--json"]).stdout).unwrap(); + assert_eq!( + value["unsure"], + json!([{ + "file": "app/a.c", + "name": "x.h", + "reason": "several files match it", + "candidates": ["xa/x.h", "xb/x.h"] + }]) + ); + assert_eq!(value["edges"], json!([])); +} diff --git a/system-map/tests/main.rs b/system-map/tests/main.rs index 28177871..bef241e5 100644 --- a/system-map/tests/main.rs +++ b/system-map/tests/main.rs @@ -1,6 +1,7 @@ //! The crate's one test binary: each file beside this one is a module of it. mod binary; +mod c; mod common; mod dart; mod dotnet; diff --git a/system-map/tests/scan.rs b/system-map/tests/scan.rs index f95eb349..0512089a 100644 --- a/system-map/tests/scan.rs +++ b/system-map/tests/scan.rs @@ -423,13 +423,55 @@ fn parts_with_the_same_last_folder_take_their_parents_into_the_id() { #[test] fn a_language_no_extractor_reads_is_detected_and_named() { - let mut tree = files(&[code("src", 1)]); - tree.push(("src/Main.kt".into(), "x\n")); - tree.push(("src/main.go".into(), "package main\n")); - let f = found(&tree); - assert_eq!(f.read, ["Go", "TypeScript"]); - assert_eq!(f.unread, ["Kotlin"]); - assert_eq!(f.extractors, ["typescript-imports"]); + // (name, files, read languages, unread languages, detected extractors) + type Case = ( + &'static str, + Vec<(String, &'static str)>, + Vec<&'static str>, + Vec<&'static str>, + Vec<&'static str>, + ); + let mut unread = files(&[code("src", 1)]); + unread.push(("src/Main.kt".into(), "x\n")); + unread.push(("src/main.go".into(), "package main\n")); + let mut cases: Vec = vec![ + ( + "a language no extractor reads", + unread, + vec!["Go", "TypeScript"], + vec!["Kotlin"], + vec!["typescript-imports"], + ), + ( + "C and every C++ extension the reader reads", + vec![ + ("src/a.c".to_string(), "int a;\n"), + ("src/b.cxx".to_string(), "int b;\n"), + ("src/c.hh".to_string(), "int c;\n"), + ], + vec!["C", "C++"], + vec![], + vec!["c-includes"], + ), + ]; + // Each C++ extension alone, so a missing one shows. + for ext in [ + "cc", "cpp", "cxx", "c++", "hpp", "hh", "hxx", "h++", "inl", "ipp", "tcc", + ] { + cases.push(( + ext, + vec![(format!("src/a.{ext}"), "int a;\n")], + vec!["C++"], + vec![], + vec!["c-includes"], + )); + } + for (name, tree, read, unread, extractors) in cases { + let f = found(&tree); + assert_eq!(strings(&f.read), read, "{name}"); + assert_eq!(strings(&f.unread), unread, "{name}"); + assert_eq!(strings(&f.extractors), extractors, "{name}"); + } } #[test]