rsconstruct 0.9.168

Rust based fast build system
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! C/C++ dependency analyzer for scanning header files.
//!
//! Scans source files for #include directives and adds header dependencies
//! to products in the build graph.

use anyhow::Result;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;

use crate::config::CppAnalyzerConfig;
use crate::file_index::FileIndex;
use crate::graph::Product;
use crate::processor::{check_command_output, format_command, run_command_capture};

use super::{DepAnalyzer, ScanResult, is_cpp_source};

/// C/C++ dependency analyzer that scans source files for #include directives.
pub struct CppDepAnalyzer {
    config: CppAnalyzerConfig,
    verbose: bool,
    /// Cached canonical project root path (for stripping absolute prefixes from compiler output)
    canonical_root: OnceLock<PathBuf>,
    /// Cached include paths from pkg-config
    pkg_config_include_paths: OnceLock<Vec<PathBuf>>,
    /// Cached include paths from `include_path_commands`
    command_include_paths: OnceLock<Vec<PathBuf>>,
}

impl CppDepAnalyzer {
    pub const fn new(config: CppAnalyzerConfig, verbose: bool) -> Self {
        Self {
            config,
            verbose,
            canonical_root: OnceLock::new(),
            pkg_config_include_paths: OnceLock::new(),
            command_include_paths: OnceLock::new(),
        }
    }

    /// Get the canonical project root path (lazily computed).
    fn canonical_root(&self) -> &Path {
        self.canonical_root.get_or_init(|| {
            Path::new(".")
                .canonicalize()
                .unwrap_or_else(|_| PathBuf::from("."))
        })
    }

    /// Query pkg-config for include paths (lazy, cached).
    fn get_pkg_config_include_paths(
        &self,
        ctx: &crate::build_context::BuildContext,
    ) -> Result<&[PathBuf]> {
        super::cached_include_paths(&self.pkg_config_include_paths, || {
            super::query_pkg_config_include_paths(ctx, "cpp", &self.config.pkg_config, self.verbose)
        })
    }

    /// Run configured `include_path_commands` to get additional include paths (lazy, cached).
    fn get_command_include_paths(
        &self,
        ctx: &crate::build_context::BuildContext,
    ) -> Result<&[PathBuf]> {
        super::cached_include_paths(&self.command_include_paths, || {
            super::run_include_path_commands(
                ctx,
                "cpp",
                &self.config.include_path_commands,
                self.verbose,
            )
        })
    }

    /// Check if a path is within the project root (not a system header).
    /// A path that cannot be canonicalized is assumed not project-local.
    fn is_project_local(&self, path: &Path) -> bool {
        path.canonicalize()
            .is_ok_and(|canonical| canonical.starts_with(self.canonical_root()))
    }

    /// Check if a source path matches any of the configured exclude-dir segments.
    fn is_excluded(&self, path: &Path) -> bool {
        let path_str = path.to_string_lossy();
        self.config
            .src_exclude_dirs
            .iter()
            .any(|seg| path_str.contains(seg))
    }

    /// Run gcc/g++ -MM to scan dependencies for a source file.
    fn scan_dependencies_compiler(
        &self,
        ctx: &crate::build_context::BuildContext,
        source: &Path,
        is_cpp: bool,
    ) -> Result<Vec<PathBuf>> {
        let compiler = if is_cpp {
            &self.config.cxx
        } else {
            &self.config.cc
        };

        let mut cmd = Command::new(compiler);
        cmd.arg("-MM");

        // Add include paths
        for inc in &self.config.include_paths {
            cmd.arg(format!("-I{inc}"));
        }

        // Add pkg-config include paths
        for inc in self.get_pkg_config_include_paths(ctx)? {
            cmd.arg(format!("-I{}", inc.display()));
        }

        // Add include paths from commands
        for inc in self.get_command_include_paths(ctx)? {
            cmd.arg(format!("-I{}", inc.display()));
        }

        // Add compile flags
        let flags = if is_cpp {
            &self.config.cxxflags
        } else {
            &self.config.cflags
        };
        for flag in flags {
            cmd.arg(flag);
        }

        cmd.arg(source);

        if self.verbose {
            eprintln!("[cpp] {}", format_command(&cmd));
        }

        let output = run_command_capture(ctx, &cmd)?;
        check_command_output(
            &output,
            format_args!("Dependency scan of {}", source.display()),
        )?;

        let content = String::from_utf8_lossy(&output.stdout).to_string();
        Ok(self.parse_dep_file(&content))
    }

    /// Parse a Makefile-style dependency file (.d) produced by gcc -MM.
    /// Format: target.o: source.c header1.h header2.h \
    ///           header3.h
    /// Returns the list of header files (excludes the source file itself and system headers).
    fn parse_dep_file(&self, content: &str) -> Vec<PathBuf> {
        // Join continuation lines (backslash-newline)
        let joined = content.replace("\\\n", " ");

        // Find the colon separating target from dependencies
        let deps_part = match joined.find(':') {
            Some(pos) => &joined[pos + 1..],
            None => return Vec::new(),
        };

        // Split by whitespace, skip the first token (the source file itself)
        let tokens: Vec<&str> = deps_part.split_whitespace().collect();
        if tokens.is_empty() {
            return Vec::new();
        }

        // First token is the source file; remaining are headers
        let canonical_root = self.canonical_root();
        tokens[1..]
            .iter()
            .filter_map(|token| {
                let path = PathBuf::from(token);

                // For absolute paths, check if they're within the project
                if path.is_absolute() {
                    if self.is_project_local(&path) {
                        // Convert to relative path
                        if let Ok(rel) = path.strip_prefix(canonical_root) {
                            Some(rel.to_path_buf())
                        } else if let Ok(canonical) = path.canonicalize() {
                            canonical
                                .strip_prefix(canonical_root)
                                .ok()
                                .map(std::path::Path::to_path_buf)
                        } else {
                            None
                        }
                    } else {
                        // System header, skip it
                        None
                    }
                } else {
                    // Relative paths are assumed to be project-local. gcc
                    // prints them as it built them (`src/../gen/x.h`).
                    Some(super::lexical_normalize(&path))
                }
            })
            .collect()
    }

    /// The directories the compiler searches for a quoted include in
    /// `source`, in order: the source's own directory, then the `-I` paths
    /// in the order `scan_dependencies_compiler` passes them.
    fn search_dirs(
        &self,
        ctx: &crate::build_context::BuildContext,
        source: &Path,
    ) -> Result<Vec<PathBuf>> {
        Ok(
            std::iter::once(crate::processor::parent_dir_or_empty(source).to_path_buf())
                .chain(self.config.include_paths.iter().map(PathBuf::from))
                .chain(self.get_pkg_config_include_paths(ctx)?.iter().cloned())
                .chain(self.get_command_include_paths(ctx)?.iter().cloned())
                .map(|dir| without_cur_dir(&dir))
                .collect(),
        )
    }

    /// Scan dependencies using compiler -MM method.
    fn scan_dependencies(
        &self,
        ctx: &crate::build_context::BuildContext,
        source: &Path,
        is_cpp: bool,
    ) -> Result<Vec<PathBuf>> {
        self.scan_dependencies_compiler(ctx, source, is_cpp)
    }
}

impl DepAnalyzer for CppDepAnalyzer {
    fn description(&self) -> &'static str {
        "Scan C/C++ source files for #include dependencies"
    }

    fn enabled(&self) -> bool {
        self.config.enabled
    }

    fn auto_detect(&self, file_index: &FileIndex) -> bool {
        // Check if there are any C/C++ source files
        let extensions = [".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".hxx"];
        for ext in extensions {
            if file_index.has_extension(ext) {
                return true;
            }
        }
        false
    }

    fn match_product(&self, p: &Product) -> Option<PathBuf> {
        self.match_sources(p).into_iter().next()
    }

    /// Every C/C++ source among the product's inputs, wherever it sits: a
    /// compiler product has its source first, but a `cc.yaml` or
    /// `linux-module.yaml` product has the manifest first and the sources
    /// it lists after it.
    fn match_sources(&self, p: &Product) -> Vec<PathBuf> {
        p.inputs
            .iter()
            .filter(|input| is_cpp_source(input) && !self.is_excluded(input))
            .cloned()
            .collect()
    }

    fn scan(
        &self,
        ctx: &crate::build_context::BuildContext,
        source: &Path,
        _file_index: &FileIndex,
    ) -> Result<ScanResult> {
        let ext = source.extension().and_then(|s| s.to_str()).unwrap_or("");
        let is_cpp = ext == "cc" || ext == "cpp" || ext == "cxx";
        let deps = self.scan_dependencies(ctx, source, is_cpp)?;
        let absent = shadow_probes(&self.search_dirs(ctx, source)?, &deps);
        Ok(ScanResult::deps(deps, absent))
    }

    /// Resolves pkg-config and the include-path commands, so a failure in
    /// either stops the build before any file is scanned.
    fn fingerprint_parts(&self, ctx: &crate::build_context::BuildContext) -> Result<Vec<String>> {
        let mut parts = super::config_fingerprint(&self.config)?;
        parts.extend(
            self.get_pkg_config_include_paths(ctx)?
                .iter()
                .chain(self.get_command_include_paths(ctx)?)
                .map(|p| p.display().to_string()),
        );
        Ok(parts)
    }
}

/// The paths the compiler probed, and found empty, before each of `deps`.
///
/// `-MM` names the header it found, not how it was spelled in the
/// `#include`, so the spelling is reconstructed: for every search directory
/// a header lies under, its path relative to that directory is a possible
/// spelling, and that spelling under each directory searched *earlier* is a
/// probe that came up empty — a file appearing there would now be found
/// instead. Covering every possible spelling over-approximates (a
/// superfluous probe can only cause a needless rescan), and the includer's
/// own directory is approximated by the source's. Paths that exist are left
/// out: they were not what the compiler found, so they were never probed.
fn shadow_probes(search_dirs: &[PathBuf], deps: &[PathBuf]) -> Vec<PathBuf> {
    let mut probes: Vec<PathBuf> = Vec::new();
    for dep in deps {
        for (found_at, dir) in search_dirs.iter().enumerate() {
            let Ok(spelling) = dep.strip_prefix(dir) else {
                continue;
            };
            for earlier in &search_dirs[..found_at] {
                let probe = earlier.join(spelling);
                if !probe.exists() && !probes.contains(&probe) {
                    probes.push(probe);
                }
            }
        }
    }
    probes
}

/// `dir` without `./` components, so `./include` and `include` both prefix
/// the relative paths `-MM` reports.
fn without_cur_dir(dir: &Path) -> PathBuf {
    dir.components()
        .filter(|c| !matches!(c, std::path::Component::CurDir))
        .collect()
}

inventory::submit! {
    crate::registries::AnalyzerPlugin {
        name: "cpp",
        description: "Scan C/C++ source files for #include dependencies (using compiler -MM)",
        is_builtin: false,
        create: |toml_value, verbose| {
            let cfg: CppAnalyzerConfig = toml::from_str(&toml::to_string(toml_value)?)?;
            Ok(Box::new(CppDepAnalyzer::new(cfg, verbose)))
        },
        defconfig_toml: || {
            toml::to_string_pretty(&crate::config::CppAnalyzerConfig::default()).ok()
        },
        known_fields: crate::registries::typed_known_fields::<crate::config::CppAnalyzerConfig>,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `include/x.h` found through `-Iinclude` was spelled `x.h`, so the
    /// compiler first tried `src/x.h`; spelled `include/x.h` it would be
    /// found from the source directory first, which probes nothing. Both
    /// spellings are covered. Paths that exist are never probes.
    #[test]
    fn shadow_probes_cover_every_spelling_before_the_hit() {
        let tmp = tempfile::TempDir::new().unwrap();
        let src = tmp.path().join("src");
        let include = tmp.path().join("include");
        let other = tmp.path().join("other");
        fs_create(&[&src, &include, &other]);
        let header = include.join("x.h");
        std::fs::write(&header, "").unwrap();
        std::fs::write(other.join("x.h"), "").unwrap();

        let dirs = vec![src.clone(), include, other];
        let probes = shadow_probes(&dirs, &[header]);
        assert_eq!(probes, vec![src.join("x.h")]);
    }

    fn product(inputs: &[&str]) -> Product {
        Product::new(
            inputs.iter().map(PathBuf::from).collect(),
            vec![],
            "x",
            0,
            None,
        )
    }

    /// A `cc.yaml` product carries the manifest first and the sources it
    /// lists after it; every one of those sources is scanned, and the
    /// manifest and headers are not. A plain compiler product still scans
    /// exactly its primary input.
    #[test]
    fn cpp_match_sources_finds_every_source_behind_a_manifest() {
        let analyzer = CppDepAnalyzer::new(CppAnalyzerConfig::default(), false);
        let manifest = product(&["cc.yaml", "src/a.c", "include/x.h", "src/b.cpp"]);
        assert_eq!(
            analyzer.match_sources(&manifest),
            vec![PathBuf::from("src/a.c"), PathBuf::from("src/b.cpp")]
        );
        assert_eq!(
            analyzer.match_product(&manifest),
            Some(PathBuf::from("src/a.c"))
        );

        let single = product(&["src/main.c"]);
        assert_eq!(
            analyzer.match_sources(&single),
            vec![PathBuf::from("src/main.c")]
        );
        assert_eq!(
            analyzer.match_sources(&product(&["cc.yaml"])),
            Vec::<PathBuf>::new()
        );
        assert_eq!(analyzer.match_product(&product(&["doc.md"])), None);
    }

    /// `src_exclude_dirs` applies per source, not per product.
    #[test]
    fn cpp_match_sources_excludes_per_source() {
        let config = CppAnalyzerConfig {
            src_exclude_dirs: vec!["/vendor/".to_string()],
            ..CppAnalyzerConfig::default()
        };
        let analyzer = CppDepAnalyzer::new(config, false);
        let p = product(&["cc.yaml", "src/vendor/v.c", "src/a.c"]);
        assert_eq!(analyzer.match_sources(&p), vec![PathBuf::from("src/a.c")]);
    }

    #[test]
    fn without_cur_dir_strips_dot_components() {
        assert_eq!(
            without_cur_dir(Path::new("./include")),
            PathBuf::from("include")
        );
        assert_eq!(without_cur_dir(Path::new(".")), PathBuf::new());
    }

    fn fs_create(dirs: &[&Path]) {
        for dir in dirs {
            std::fs::create_dir_all(dir).unwrap();
        }
    }
}