diff --git a/CHANGELOG.md b/CHANGELOG.md index 457a959a..40b4bb09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,26 @@ All notable changes to `trace` are documented in this file. ## Unreleased +### Cover standard headers behind external headers in the canonical prelude + +The canonical preamble scan read only project sources and headers. A standard +header reached through an external SDK header (for example `` +through a vendored ``) therefore stayed uncovered; because canonical +indexing keeps `separate_system_headers` off, its whole compiler-root closure +was inlined into every project header and translation unit that included the +SDK header, greatly enlarging their expansion text and line maps. The scan now +follows project and external includes transitively, including quoted +spellings that resolve into the compiler roots, with the run's own search +paths, and admits the compiler-default angle spellings they reach, so those +headers become prelude entries covered by the closure. A quoted spelling adds +no preamble line itself, the C++ standard-library tree is not raw-walked, +`# include` with a separating space is recognized, and transitively reached +spellings are appended after the project's own angle spellings to preserve +the baseline include order. Each distinct spelling's search-list result is +memoized, so the scan walks the include directories once per spelling rather +than once per occurrence. See +[Canonical system-header prelude](docs/CANONICAL_SYSTEM_PRELUDE.md). + ### Track nested container elements Callback and pointer values stored in nested modeled containers now reach diff --git a/crates/trace-parse/src/lower.rs b/crates/trace-parse/src/lower.rs index fa32ff96..56b599e3 100644 --- a/crates/trace-parse/src/lower.rs +++ b/crates/trace-parse/src/lower.rs @@ -26,7 +26,7 @@ use rayon::prelude::*; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; use std::borrow::Cow; use std::cell::{Cell, RefCell}; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::io::Write; use std::path::{Path, PathBuf}; use std::sync::{Arc, Condvar, Mutex}; @@ -977,9 +977,14 @@ fn build_program_inner( // mock of a standard spelling nor an explicit system tree enters // the shared declarations or the macro closure. let roots = inline.compiler_system_include_paths.clone(); - let Some((preamble, scratch)) = - canonical_system_preamble(&include_graph, &sources, &roots, language) - else { + let Some((preamble, scratch)) = canonical_system_preamble( + &include_graph, + &sources, + &roots, + language, + &inline, + &files, + ) else { continue; }; inline.include_paths.clear(); @@ -3232,16 +3237,123 @@ fn project_preprocess_opts( eff } -fn angle_includes(text: &str) -> impl Iterator { +/// `#include` spellings in raw text, with whether the spelling was quoted. +/// This is the preamble scan's over-approximation: it reads lines before +/// preprocessing, so includes in inactive arms and comments count too. +fn raw_includes(text: &str) -> impl Iterator { text.lines().filter_map(|line| { let line = line.trim_start(); - let rest = line.strip_prefix("#include")?.trim_start(); - let inner = rest.strip_prefix('<')?; - let end = inner.find('>')?; - Some(inner[..end].trim()) + let rest = line.strip_prefix('#')?.trim_start(); + let rest = rest.strip_prefix("include")?.trim_start(); + if let Some(inner) = rest.strip_prefix('<') { + let end = inner.find('>')?; + Some((false, inner[..end].trim())) + } else { + let inner = rest.strip_prefix('"')?; + let end = inner.find('"')?; + Some((true, &inner[..end])) + } }) } +/// Whether the preamble scan's include search finds `path`, on disk or among +/// the caller's virtual headers. +fn scan_include_exists(search: &PreprocessOptions, path: &Path) -> bool { + trace_ir::is_file_cached(path) + || search + .source_cache + .as_ref() + .is_some_and(|cache| cache.is_virtual(path)) +} + +fn scan_include_exists_in(search: &PreprocessOptions, dir: &Path, spelling: &str) -> bool { + trace_ir::is_file_in(dir, Path::new(spelling)) + || search + .source_cache + .as_ref() + .is_some_and(|cache| cache.is_virtual(&dir.join(spelling))) +} + +/// Search-list results shared by every include occurrence of one spelling in +/// one language/configuration, like the preprocessor's own include-search +/// memo. The including file's directory is still probed first per occurrence. +type ScannedIncludeMemo = HashMap<(String, bool, bool), Option>; + +/// Resolve a raw include spelling the way the preprocessor will, so the +/// preamble scan can follow project and external headers to the standard +/// headers they include. Only the result feeds the scan: the preamble itself +/// still admits compiler-default spellings alone. The order mirrors +/// `Preprocessor::resolve_include` / `search_include_dirs` in +/// `trace-preproc/src/preprocessor.rs`, the authority for include resolution. +fn resolve_scanned_include( + search: &PreprocessOptions, + from: &Path, + spelling: &str, + quoted: bool, + memo: &mut ScannedIncludeMemo, +) -> Option { + let spelling_path = Path::new(spelling); + if spelling_path.is_absolute() { + return scan_include_exists(search, spelling_path) + .then(|| trace_ir::canonicalize(spelling_path)); + } + let local = from.parent().map(|parent| parent.join(spelling_path)); + if (quoted || !search.strict_include_search) + && local + .as_deref() + .is_some_and(|candidate| scan_include_exists(search, candidate)) + { + return local.map(|candidate| trace_ir::canonicalize(&candidate)); + } + let from_is_test = search + .inference_root + .as_ref() + .is_none_or(|root| trace_ir::is_test_path(root, from, &search.test_partition)); + let key = (spelling.to_string(), quoted, from_is_test); + if let Some(found) = memo.get(&key) { + return found.clone(); + } + let admits = |path: &Path| { + from_is_test + || search + .inference_root + .as_ref() + .is_none_or(|root| !trace_ir::is_test_path(root, path, &search.test_partition)) + }; + let mut search_dirs = search + .quote_include_paths + .iter() + .filter(|_| quoted) + .chain(&search.include_paths) + .chain(&search.system_include_paths) + .chain(&search.compiler_system_include_paths) + .chain(&search.after_include_paths); + let mut found = search_dirs + .find(|dir| scan_include_exists_in(search, dir, spelling)) + .map(|dir| trace_ir::canonicalize(&dir.join(spelling))); + if found.is_none() { + found = search.inferred_include_paths.iter().find_map(|dir| { + let candidate = dir.join(spelling_path); + (scan_include_exists(search, &candidate) && admits(&candidate)) + .then(|| trace_ir::canonicalize(&candidate)) + }); + } + if found.is_none() && !search.strict_include_search { + if let Some(index) = &search.basename_index { + if let Some(name) = spelling_path.file_name().and_then(|name| name.to_str()) { + if let Some(matches) = index.get(name) { + let mut admitted = matches.iter().filter(|path| admits(path)); + if let (Some(only), None) = (admitted.next(), admitted.next()) { + found = Some(trace_ir::canonicalize(only)); + } + } + } + } + } + memo.insert(key, found.clone()); + found +} + /// The translation units and headers of each language present, as the /// indexer will preprocess them: a header in every language whose units reach /// it (C++ for C++ header spellings). A header the static include graph does @@ -3319,12 +3431,52 @@ fn canonical_prelude_identity(roots: &[PathBuf], language: Language) -> PathBuf .join(name) } +/// Whether `spelling` names a compiler-default header the prelude can admit. +/// Only a plain relative spelling whose first match stays inside its root +/// qualifies: `<../project/own.h>` or an absolute spelling can reach a project +/// file, whose bodies a symbols-only prelude drops. C's standard and platform +/// headers are all `.h`; an extensionless or other spelling under a shared +/// root is a C++ library header that a C prelude must not read (a raw scan +/// also sees `#ifdef __cplusplus` arms). +fn compiler_default_spelling(roots: &[PathBuf], language: Language, spelling: &str) -> bool { + let path = Path::new(spelling); + if language == Language::C + && !path + .extension() + .is_some_and(|extension| extension.eq_ignore_ascii_case("h")) + { + return false; + } + path.components() + .all(|component| matches!(component, std::path::Component::Normal(_))) + && roots + .iter() + .find(|root| trace_ir::is_file_in(root, path)) + .is_some_and(|root| trace_ir::canonicalize(&root.join(path)).starts_with(root)) +} + +/// Whether `path` is inside a C++ standard-library tree (`include/c++/...`, +/// including multiarch spellings such as `x86_64-linux-gnu/c++/`). Its +/// headers select many configuration branches, so the raw scan does not walk +/// them; project angle spellings still enter the preamble normally. +fn is_cxx_library_path(path: &Path) -> bool { + path.components().any(|component| { + component + .as_os_str() + .to_str() + .is_some_and(|name| name.starts_with("c++")) + }) +} + fn canonical_system_preamble( graph: &IncludeGraph, sources: &[PathBuf], roots: &[PathBuf], language: Language, + search: &PreprocessOptions, + files: &[PathBuf], ) -> Option<(PathBuf, tempfile::NamedTempFile)> { + let translation_units: HashSet = files.iter().cloned().collect(); let roots: Vec = roots .iter() .map(|path| trace_ir::canonicalize(path)) @@ -3333,52 +3485,111 @@ fn canonical_system_preamble( return None; } let mut spellings: BTreeSet = BTreeSet::new(); - for file in sources { - let canonical = graph.intern_path(file); - let text = match graph.source_cache.get(&canonical) { + // Spellings discovered only through a followed include are appended after + // the project's own angle spellings. That keeps the baseline include order + // (and therefore the macro state the baseline standard headers see) while + // still covering the newly reached headers. + let mut deferred: BTreeSet = BTreeSet::new(); + // Raw-scan the project files and, transitively, every external header + // they reach. An SDK header is not itself a standard header, but it can + // include compiler-default ones (`` under a vendored `uv.h`); + // without this walk those were neither prelude spellings nor covered, so + // canonical indexing inlined their whole closure into every consumer. + let mut initial_sources: Vec = + sources.iter().map(|file| graph.intern_path(file)).collect(); + initial_sources.sort(); + initial_sources.dedup(); + let initial: HashSet = initial_sources.iter().cloned().collect(); + let mut visited: HashSet = HashSet::default(); + let mut pending: VecDeque = initial_sources.into_iter().collect(); + let mut admitted: HashMap = HashMap::default(); + let mut resolve_memo: ScannedIncludeMemo = HashMap::default(); + while let Some(file) = pending.pop_front() { + if !visited.insert(file.clone()) { + continue; + } + let deferred_file = !initial.contains(&file); + let text = match graph.source_cache.get(&file) { Some(text) => Arc::clone(text), - None => match std::fs::read_to_string(file) { - Ok(text) => Arc::from(text), - Err(_) => continue, - }, + None => { + // The scan reads this file only as metadata; still report it + // as an input under `--require-local-inputs`. + if let Some(boundary) = &search.input_boundary { + boundary.record(&file); + } + match std::fs::read_to_string(&file) { + Ok(text) => Arc::from(text), + Err(_) => continue, + } + } }; - for spelling in angle_includes(&text) { - if !spelling.is_empty() { - spellings.insert(spelling.to_string()); + for (quoted, spelling) in raw_includes(&text) { + if spelling.is_empty() { + continue; + } + if !quoted { + if deferred_file { + deferred.insert(spelling.to_string()); + } else { + spellings.insert(spelling.to_string()); + } + let admissible = match admitted.get(spelling) { + Some(value) => *value, + None => { + let value = compiler_default_spelling(&roots, language, spelling); + admitted.insert(spelling.to_string(), value); + value + } + }; + // A compiler-default header enters the preamble through its + // angle spelling; the prelude run then follows its nested + // includes. Reading it here as well would repeat that whole + // closure. + if admissible { + continue; + } + } + let Some(resolved) = + resolve_scanned_include(search, &file, spelling, quoted, &mut resolve_memo) + else { + continue; + }; + // A quoted include that resolves into a compiler root is still + // followed from a header: the file itself stays inline, but the + // standard headers it includes must become preamble entries. A + // translation unit's own quoted compiler header is expanded once + // for that unit rather than shared through project-header cache + // entries, and a fallback spelling there can be accidental (a + // Linux-target file reaching the host's `"p2p.h"`); globalizing + // its platform closure would change every unit. The C++ + // library tree is skipped because a raw scan would over-approximate + // its configuration branches wholesale; a project angle spelling + // still reaches it through `compiler_default_spelling`. + if is_cxx_library_path(&resolved) { + continue; + } + if roots.iter().any(|root| resolved.starts_with(root)) + && translation_units.contains(&file) + { + continue; } + pending.push_back(resolved); } } // Probe each distinct spelling once, including misses. Large trees repeat // the same standard includes in thousands of files; probing while scanning - // made this serial phase scale with occurrences times search roots. Only - // a plain relative spelling whose first match stays inside its root - // names a compiler header: `<../project/own.h>` or an absolute spelling - // can reach a project file, whose bodies a symbols-only prelude drops. - spellings.retain(|spelling| { - let path = Path::new(spelling); - // C's standard and platform headers are all `.h`; an extensionless - // or other spelling under a shared root is a C++ library header that - // a C prelude must not read (a raw scan also sees `#ifdef - // __cplusplus` arms). - if language == Language::C - && !path - .extension() - .is_some_and(|extension| extension.eq_ignore_ascii_case("h")) - { - return false; - } - path.components() - .all(|component| matches!(component, std::path::Component::Normal(_))) - && roots - .iter() - .find(|root| trace_ir::is_file_in(root, path)) - .is_some_and(|root| trace_ir::canonicalize(&root.join(path)).starts_with(root)) - }); - if spellings.is_empty() { + // made this serial phase scale with occurrences times search roots. + spellings.retain(|spelling| admitted.get(spelling).copied().unwrap_or(false)); + deferred.retain(|spelling| admitted.get(spelling).copied().unwrap_or(false)); + if spellings.is_empty() && deferred.is_empty() { return None; } let mut text = String::new(); - for spelling in &spellings { + for spelling in spellings.iter().chain( + deferred + .iter() + .filter(|spelling| !spellings.contains(*spelling)), + ) { text.push_str("#include <"); text.push_str(spelling); text.push_str(">\n"); @@ -36540,10 +36751,24 @@ mod canonical_system_tests { let files = vec![source]; let graph = IncludeGraph::build(&root, &files, &[]); let roots = vec![system]; - let (first, first_guard) = - canonical_system_preamble(&graph, &files, &roots, Language::Cpp).unwrap(); - let (second, second_guard) = - canonical_system_preamble(&graph, &files, &roots, Language::Cpp).unwrap(); + let (first, first_guard) = canonical_system_preamble( + &graph, + &files, + &roots, + Language::Cpp, + &PreprocessOptions::new(), + &files, + ) + .unwrap(); + let (second, second_guard) = canonical_system_preamble( + &graph, + &files, + &roots, + Language::Cpp, + &PreprocessOptions::new(), + &files, + ) + .unwrap(); assert_ne!(first, second); assert!(!first.starts_with(trace_ir::canonicalize(&root))); assert!(!second.starts_with(trace_ir::canonicalize(&root))); @@ -36584,6 +36809,218 @@ mod canonical_system_tests { assert_eq!(entries, [".trace-canonical-std.tmp", "main.cpp"]); } + /// An external SDK header is not a standard header, but the standard + /// headers it includes must still enter the prelude. Otherwise canonical + /// indexing inlines their whole closure at every consumer, which is how + /// a vendored `uv.h` pulled `windows.h` into project cache entries. + #[test] + fn canonical_preamble_covers_standard_headers_reached_through_external_headers() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("project"); + let sdk = dir.path().join("sdk"); + let sys = dir.path().join("sys"); + for path in [&root, &sdk.join("native/nested"), &sdk.join("other"), &sys] { + std::fs::create_dir_all(path).unwrap(); + } + std::fs::write( + sys.join("winapi.h"), + "#pragma once\n#define WINAPI_MARKER 1\nint WinApi(void);\n", + ) + .unwrap(); + std::fs::write(sys.join("winapi2.h"), "#pragma once\nint WinApi2(void);\n").unwrap(); + std::fs::write( + sdk.join("native/api.h"), + "#pragma once\n#include \"nested/leaf.h\"\nint SdkApi(void);\n", + ) + .unwrap(); + std::fs::write( + sdk.join("native/nested/leaf.h"), + "#pragma once\n# include \nint LeafApi(void);\n", + ) + .unwrap(); + std::fs::write( + sdk.join("other/extra.h"), + "#pragma once\n#include \nint ExtraApi(void);\n", + ) + .unwrap(); + std::fs::write( + root.join("own.h"), + "#pragma once\n#include \n#include \"other/extra.h\"\n\ + int UseApi(void) { return WinApi() + WinApi2(); }\n", + ) + .unwrap(); + std::fs::write(root.join("main.cpp"), "#include \"own.h\"\n").unwrap(); + let files = vec![trace_ir::canonicalize(&root.join("main.cpp"))]; + let headers = vec![trace_ir::canonicalize(&root.join("own.h"))]; + let graph = IncludeGraph::build(&root, &files, &headers); + let mut search = PreprocessOptions::new().with_include(sdk); + let roots = vec![sys]; + let sources = canonical_prelude_sources(&graph, &files, &headers, None); + let (preamble, _guard) = canonical_system_preamble( + &graph, + &sources[0].1, + &roots, + Language::Cpp, + &search, + &files, + ) + .unwrap(); + assert_eq!( + std::fs::read_to_string(preamble).unwrap(), + "#include \n#include \n" + ); + + search.compiler_system_include_paths = roots; + search.canonical_system_headers = true; + let program = build_program_with_jobs(&root, &search, 1).unwrap(); + let calls: Vec<_> = program + .symbols + .call_sites + .iter() + .filter(|site| program.symbols.function(site.caller).name == "UseApi") + .map(|site| site.callee_name.to_string()) + .collect(); + for callee in ["WinApi", "WinApi2"] { + assert!(calls.contains(&callee.to_string()), "{calls:?}"); + } + } + + /// Spellings found only through a followed include are appended after the + /// project's own angle spellings, so adding coverage does not reorder the + /// baseline prelude and change the macros an earlier standard header sees. + #[test] + fn canonical_preamble_appends_transitively_reached_spellings() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("project"); + let sdk = dir.path().join("sdk"); + let sys = dir.path().join("sys"); + for path in [&root, &sdk, &sys] { + std::fs::create_dir_all(path).unwrap(); + } + std::fs::write(sys.join("zeta.h"), "#pragma once\nint Zeta(void);\n").unwrap(); + std::fs::write(sys.join("alpha.h"), "#pragma once\nint Alpha(void);\n").unwrap(); + std::fs::write( + sdk.join("sdk.h"), + "#pragma once\n#include \nint Sdk(void);\n", + ) + .unwrap(); + std::fs::write( + root.join("own.h"), + "#pragma once\n#include \n#include \n", + ) + .unwrap(); + std::fs::write(root.join("main.cpp"), "#include \"own.h\"\n").unwrap(); + let files = vec![trace_ir::canonicalize(&root.join("main.cpp"))]; + let headers = vec![trace_ir::canonicalize(&root.join("own.h"))]; + let graph = IncludeGraph::build(&root, &files, &headers); + let search = PreprocessOptions::new().with_include(sdk); + let sources = canonical_prelude_sources(&graph, &files, &headers, None); + let (preamble, _guard) = canonical_system_preamble( + &graph, + &sources[0].1, + std::slice::from_ref(&sys), + Language::Cpp, + &search, + &files, + ) + .unwrap(); + assert_eq!( + std::fs::read_to_string(preamble).unwrap(), + "#include \n#include \n" + ); + } + + /// A quoted project spelling can resolve into the compiler roots by + /// accident (a platform `"p2p.h"`). The file itself stays an ordinary + /// inline include, but the standard headers it includes still enter the + /// preamble when the quoting file is a header, where the expansion is + /// shared. The `# include` spelling with a separating space counts. + #[test] + fn canonical_preamble_follows_quoted_compiler_headers_to_their_standard_includes() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("project"); + let sys = dir.path().join("sys"); + std::fs::create_dir(&root).unwrap(); + std::fs::create_dir(&sys).unwrap(); + std::fs::write( + sys.join("platform.h"), + "#pragma once\n# include \nint Platform(void);\n", + ) + .unwrap(); + std::fs::write(sys.join("nested.h"), "#pragma once\nint Nested(void);\n").unwrap(); + std::fs::write( + root.join("own.h"), + "#pragma once\n#include \"platform.h\"\nint PlatformUser(void);\n", + ) + .unwrap(); + std::fs::write( + root.join("main.cpp"), + "#include \"own.h\"\nint Run(void) { return Platform(); }\n", + ) + .unwrap(); + let files = vec![trace_ir::canonicalize(&root.join("main.cpp"))]; + let headers = vec![trace_ir::canonicalize(&root.join("own.h"))]; + let graph = IncludeGraph::build(&root, &files, &headers); + let search = PreprocessOptions::new().with_compiler_system_include(&sys); + let (preamble, _guard) = canonical_system_preamble( + &graph, + &files, + std::slice::from_ref(&sys), + Language::Cpp, + &search, + &files, + ) + .unwrap(); + assert_eq!( + std::fs::read_to_string(preamble).unwrap(), + "#include \n" + ); + } + + /// The C++ standard-library tree is not raw-walked even when a quoted + /// include resolves into it; its configuration branches would flood the + /// preamble. + #[test] + fn canonical_preamble_skips_quoted_libstdcxx_headers() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("project"); + let sys = dir.path().join("sys"); + let lib = sys.join("include/c++/15"); + std::fs::create_dir_all(&lib).unwrap(); + std::fs::create_dir(&root).unwrap(); + std::fs::write( + lib.join("vector"), + "#pragma once\n#include \nint Vector(void);\n", + ) + .unwrap(); + std::fs::write(sys.join("leaked.h"), "#pragma once\nint Leaked(void);\n").unwrap(); + std::fs::write( + root.join("own.h"), + "#pragma once\n#include \"vector\"\nint VectorUser(void);\n", + ) + .unwrap(); + std::fs::write( + root.join("main.cpp"), + "#include \"own.h\"\nint Run(void) { return Vector(); }\n", + ) + .unwrap(); + let files = vec![trace_ir::canonicalize(&root.join("main.cpp"))]; + let headers = vec![trace_ir::canonicalize(&root.join("own.h"))]; + let graph = IncludeGraph::build(&root, &files, &headers); + let search = PreprocessOptions::new() + .with_compiler_system_include(&lib) + .with_compiler_system_include(&sys); + assert!(canonical_system_preamble( + &graph, + &files, + &[lib, sys], + Language::Cpp, + &search, + &files, + ) + .is_none()); + } + #[cfg(unix)] #[test] fn canonical_preamble_does_not_follow_legacy_symlinks() { @@ -36598,9 +37035,15 @@ mod canonical_system_tests { std::os::unix::fs::symlink(&victim, &legacy).unwrap(); let files = vec![source]; let graph = IncludeGraph::build(dir.path(), &files, &[]); - let (_, guard) = - canonical_system_preamble(&graph, &files, &[dir.path().to_path_buf()], Language::Cpp) - .unwrap(); + let (_, guard) = canonical_system_preamble( + &graph, + &files, + &[dir.path().to_path_buf()], + Language::Cpp, + &PreprocessOptions::new(), + &files, + ) + .unwrap(); drop(guard); assert!(legacy.is_symlink()); assert_eq!( @@ -36745,9 +37188,15 @@ mod canonical_system_tests { .unwrap(); let files = vec![trace_ir::canonicalize(&root.join("main.cpp"))]; let graph = IncludeGraph::build(&root, &files, &[]); - let (preamble, _guard) = - canonical_system_preamble(&graph, &files, std::slice::from_ref(&sys), Language::Cpp) - .unwrap(); + let (preamble, _guard) = canonical_system_preamble( + &graph, + &files, + std::slice::from_ref(&sys), + Language::Cpp, + &PreprocessOptions::new(), + &files, + ) + .unwrap(); assert_eq!( std::fs::read_to_string(preamble).unwrap(), "#include \n" @@ -36992,10 +37441,19 @@ mod canonical_system_tests { ] ); let roots = vec![sys.clone()]; + let search = PreprocessOptions::new(); let (c_preamble, _c) = - canonical_system_preamble(&graph, &sources[0].1, &roots, Language::C).unwrap(); - let (cpp_preamble, _cpp) = - canonical_system_preamble(&graph, &sources[1].1, &roots, Language::Cpp).unwrap(); + canonical_system_preamble(&graph, &sources[0].1, &roots, Language::C, &search, &files) + .unwrap(); + let (cpp_preamble, _cpp) = canonical_system_preamble( + &graph, + &sources[1].1, + &roots, + Language::Cpp, + &search, + &files, + ) + .unwrap(); assert_eq!( std::fs::read_to_string(c_preamble).unwrap(), "#include \n" diff --git a/docs/CANONICAL_SYSTEM_PRELUDE.md b/docs/CANONICAL_SYSTEM_PRELUDE.md index e6dfed14..ff1b2bd9 100644 --- a/docs/CANONICAL_SYSTEM_PRELUDE.md +++ b/docs/CANONICAL_SYSTEM_PRELUDE.md @@ -73,6 +73,25 @@ identities, the two languages' preludes are distinct units, and the identity has the dependency ownership of the headers it stands for. Each distinct spelling is probed once through the shared directory-listing cache. +The scan also follows includes into the non-project `#include`s those files +reach: an external SDK header (`uv.h`, `napi/native_api.h`) is not a standard +header itself, but it can include compiler-default ones (``, +``) through quoted local headers and angle spellings. Those headers +are scanned transitively with the run's project, explicit system, inferred +and compiler search paths; only their angle spellings that resolve inside a +compiler-default root enter the preamble. A quoted spelling that resolves +into a compiler-default root is followed for its nested includes but adds no +preamble line itself, and the C++ standard-library tree is not raw-walked +because its configuration branches would over-approximate wholesale. A +spelling discovered only through a followed include is appended after the +project's own angle spellings, so the baseline include order and the macro +state the baseline headers see stay unchanged. Each distinct spelling's +search-list result is memoized, as in the preprocessor, so the scan probes +the include directories once per spelling rather than once per occurrence. +Without this walk the standard headers +behind an external header were neither prelude entries nor covered, so +canonical indexing inlined their whole expansion into every consumer. + The scan reads raw lines, before preprocessing, so it over-approximates: an include in an inactive `#if` arm, in a block comment or in a configuration the tree never builds still enters the preamble. The prelude then lowers diff --git a/docs/PREPROCESSOR.md b/docs/PREPROCESSOR.md index 4e93461a..0c2948e2 100644 --- a/docs/PREPROCESSOR.md +++ b/docs/PREPROCESSOR.md @@ -834,12 +834,23 @@ one shared prelude per language: in the system temporary directory (never into the analyzed tree) holding each `#include <...>` spelling of that language's units and the headers they reach that exists under its compiler-default roots, and preprocesses - it inline once. That run searches only those roots: no project, explicit - system, inferred or basename paths and no forced includes, so neither a - project mock of a standard spelling nor an explicit system tree can enter - the shared state. The lowered prelude is identified as - `.trace-canonical-std-c.prelude` or `.trace-canonical-std-cpp.prelude` under - the language's first compiler-default root. + it inline once. Those units and headers are raw-scanned transitively + through their includes outside the compiler-default roots and through + quoted spellings that resolve inside them, so standard headers reached + only through an SDK header enter the preamble too. A quoted spelling adds + no preamble line itself, the C++ standard-library tree is not raw-walked, + and `# include` with a separating space counts. Spellings found only + through a followed include are appended after the project's own angle + spellings, preserving the baseline order for the headers the project names + directly. A spelling's search-list result is memoized, so the scan walks + the include directories once per spelling, not once per occurrence. That + run searches + only those roots: no project, explicit system, inferred or basename paths + and no forced includes, so neither a project mock of a standard spelling + nor an explicit system tree can enter the shared state. The lowered + prelude is identified as `.trace-canonical-std-c.prelude` or + `.trace-canonical-std-cpp.prelude` under the language's first + compiler-default root. 2. The run records its executed directives (`PreprocessOptions::record_macro_ops`). Compacted to each name's last directive, they are the *closure*; the files it read are the *covered*