Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 1 addition & 9 deletions cpp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,7 @@
//! Behind the scene, it uses the `cc` crate.
//!
//! `cpp_build` tells cargo to rerun the build script when one of the Rust source files it
//! parses changes. It doesn't track C++ headers included from `cpp!` macros, or files added
//! with `cpp_build::Config::file`, so print `cargo:rerun-if-changed` for those yourself:
//!
//! ```no_run
//! fn main() {
//! cpp_build::build("src/lib.rs");
//! println!("cargo:rerun-if-changed=src/header.h");
//! }
//! ```
//! parses changes. It also tracks the C++ sources it compiles and the headers they include.
//!
//! ## Using external libraries
//!
Expand Down
2 changes: 1 addition & 1 deletion cpp_build/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ docs-only = []
parallel = ["cc/parallel"]

[dependencies]
cc = "1.0.38"
cc = "1.6"
cpp_common = { path = "../cpp_common", version = "=0.5.12" }
syn = { version = "2.0", features=["full", "visit"] }
proc-macro2 = "1.0"
Expand Down
194 changes: 192 additions & 2 deletions cpp_build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ mod strnom;

use cpp_common::*;
use std::collections::hash_map::{Entry, HashMap};
use std::collections::HashSet;
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{create_dir, remove_dir_all, File};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -688,13 +690,201 @@ In order to provide a better error message, the build script will exit successfu
// to the proc-macro.
self.cc.flag_if_supported("-fno-lto");

// Build the C++ library
if let Err(e) = self.cc.file(filename).try_compile(LIB_NAME) {
// Have GCC and Clang list each source's headers in a `.d` file next to its object
let tool = if self.cargo_metadata { self.cc.try_get_compiler().ok() } else { None };
if tool.as_ref().is_some_and(|tool| !tool.is_like_msvc()) {
self.cc.flag("-MMD").flag("-MT").flag(DEPS_TARGET);
}

// Build the C++ library, keeping the objects to find their `.d` files
let objects = self.cc.file(&filename).try_compile_intermediates().and_then(|objects| {
let library = self.cc.try_create_archive(LIB_NAME, &objects)?;
cc::try_emit_link_directives(&self.cc, library)?;
Ok(objects)
});
let objects = objects.unwrap_or_else(|e| {
let _ = writeln!(std::io::stderr(), "\n\nerror occurred: {}\n\n", e);
#[cfg(not(feature = "docs-only"))]
std::process::exit(1);
#[cfg(feature = "docs-only")]
Vec::new()
});

if let Some(tool) = tool {
self.print_cpp_dependencies(&tool, &objects);
}
}

/// Tell Cargo to rerun the build script when a C++ source or one of its headers changes.
fn print_cpp_dependencies(&self, tool: &cc::Tool, objects: &[PathBuf]) {
let current_dir = env::current_dir().unwrap_or_default();
let mut printed = HashSet::new();
let deps: Vec<PathBuf> = if tool.is_like_msvc() {
self.cc.get_files().flat_map(|source| msvc_dependencies(tool, source)).collect()
} else {
objects
.iter()
.flat_map(|object| make_dependencies(&object.with_extension("d")))
.collect()
};
for dep in deps {
let dep = current_dir.join(dep);
// Files in `OUT_DIR` are regenerated on every run, and a path that doesn't exist
// counts as changed, so either would make Cargo rerun the build script every time.
if dep.starts_with(out_dir()) || !dep.is_file() {
continue;
}
// Keep paths inside the package relative, so the build can be moved.
let dep = dep.strip_prefix(cargo_manifest_dir()).unwrap_or(&dep);
if printed.insert(dep.to_owned()) {
println!("cargo:rerun-if-changed={}", dep.display());
}
}
}
}

/// The make target name passed to the compiler with `-MT`.
const DEPS_TARGET: &str = "cpp_build_deps";

/// Read the files GCC or Clang listed in `depfile`.
fn make_dependencies(depfile: &Path) -> Vec<PathBuf> {
match std::fs::read(depfile) {
Ok(text) => {
let text = String::from_utf8_lossy(&text);
parse_make_deps(&text).into_iter().map(PathBuf::from).collect()
}
Err(_) => Vec::new(),
}
}

/// Ask cl.exe or clang-cl which files `source` reads, with `/Zs` so it only checks the syntax.
fn msvc_dependencies(tool: &cc::Tool, source: &Path) -> Vec<PathBuf> {
let mut command = tool.to_command();
// Keep the output in English on localized systems, as rustc and cc do.
command.env("VSLANG", "1033");
if tool.is_like_clang_cl() {
command.args(["/Zs", "/showIncludes:user", "--"]).arg(source);
} else {
command.args(["/Zs", "/showIncludes"]);
// cl.exe treats a file it doesn't recognise, like `.cc`, as an object unless given `-Tp`.
if source.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("c")) {
command.arg(source);
} else {
let mut arg = OsString::from("-Tp");
arg.push(source);
command.arg(arg);
}
}
// cl.exe doesn't support `/showIncludes:user`, so leave out system headers by skipping anything
// under the `INCLUDE` directories.
let include = command
.get_envs()
.find(|(key, _)| key.eq_ignore_ascii_case("INCLUDE"))
.map_or_else(|| env::var_os("INCLUDE"), |(_, value)| value.map(OsStr::to_owned))
.unwrap_or_default();
let system_dirs = split_include_dirs(&include);

let output = match command.output() {
Ok(output) if output.status.success() => output,
_ => return Vec::new(),
};
let text = String::from_utf8_lossy(&output.stdout);
let headers = parse_show_includes(&text).into_iter().map(PathBuf::from);
std::iter::once(source.to_owned())
.chain(headers.filter(|header| !system_dirs.iter().any(|dir| header.starts_with(dir))))
.collect()
}

/// Split an `INCLUDE` value into its directories, dropping empty entries such as the one after
/// a trailing `;`, because an empty path matches every header.
fn split_include_dirs(include: &OsStr) -> Vec<PathBuf> {
env::split_paths(include).filter(|dir| !dir.as_os_str().is_empty()).collect()
}

#[test]
fn test_split_include_dirs() {
assert!(split_include_dirs(OsStr::new("")).is_empty());
let include = env::join_paths(["inc", "", "sdk"]).unwrap();
assert_eq!(split_include_dirs(&include), [Path::new("inc"), Path::new("sdk")]);
}

/// Parse the files listed in `/showIncludes` output, where extra spaces show how deeply a header
/// is nested.
fn parse_show_includes(output: &str) -> Vec<&str> {
output
.lines()
.filter_map(|line| line.strip_prefix("Note: including file:"))
.map(str::trim)
.filter(|file| !file.is_empty())
.collect()
}

#[test]
fn test_parse_show_includes() {
let output = "cpp_closures.cpp\r\n\
Note: including file: D:\\crate\\src/header.h\r\n\
Note: including file: D:\\crate\\src\\nested.h\r\n\
Note: including file: ../vendor/include\\Dir With Space\\util.h\r\n\
cpp_closures.cpp(3): warning C4100: unreferenced parameter\r\n";
assert_eq!(
parse_show_includes(output),
[
"D:\\crate\\src/header.h",
"D:\\crate\\src\\nested.h",
"../vendor/include\\Dir With Space\\util.h",
]
);
assert!(parse_show_includes("cl : Command line warning D9002 : ignoring option").is_empty());
}

/// Parse the files listed in a `.d` file, which uses Makefile syntax.
fn parse_make_deps(output: &str) -> Vec<String> {
let Some(deps) =
output.trim_start().strip_prefix(DEPS_TARGET).and_then(|d| d.strip_prefix(':'))
else {
return Vec::new();
};
let mut files = Vec::new();
let mut file = String::new();
let mut chars = deps.chars().peekable();
while let Some(c) = chars.next() {
match c {
// An escaped space or `#` is part of the file name.
'\\' if matches!(chars.peek(), Some(' ' | '#')) => file.push(chars.next().unwrap()),
'\\' if matches!(chars.peek(), Some('\n' | '\r')) => {}
'$' if chars.peek() == Some(&'$') => {
chars.next();
file.push('$');
}
c if c.is_whitespace() => {
if !file.is_empty() {
files.push(std::mem::take(&mut file));
}
}
c => file.push(c),
}
}
if !file.is_empty() {
files.push(file);
}
files
}

#[test]
fn test_parse_make_deps() {
let output = "cpp_build_deps: /out/rust_cpp/cpp_closures.cpp src/header.h \\\n \
../vendor/my\\ lib.h C:\\include\\a.h dir/\\#odd$$name.h\r\n";
assert_eq!(
parse_make_deps(output),
[
"/out/rust_cpp/cpp_closures.cpp",
"src/header.h",
"../vendor/my lib.h",
"C:\\include\\a.h",
"dir/#odd$name.h",
]
);
assert!(parse_make_deps("something else: a.h").is_empty());
}

/// Run the `cpp` build process on the crate with a root at the given path.
Expand Down
25 changes: 25 additions & 0 deletions test/src/headers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use cpp::cpp;

cpp! {{
#include "src/headers/outer.h"
}}

#[test]
fn header_from_cpp_block() {
let value = unsafe { cpp!([] -> i32 as "int" { return outer_value(); }) };
assert_eq!(value, 3);
}

#[test]
#[cfg(not(target_env = "msvc"))]
fn headers_are_in_dependency_files() {
let mut deps = String::new();
for entry in std::fs::read_dir(env!("OUT_DIR")).unwrap().flatten() {
if entry.path().extension().is_some_and(|ext| ext == "d") {
deps += &std::fs::read_to_string(entry.path()).unwrap();
}
}
for header in ["src/headers/outer.h", "src/headers/inner.h"] {
assert!(deps.contains(header), "{header} isn't in the dependency files:\n{deps}");
}
}
6 changes: 6 additions & 0 deletions test/src/headers/inner.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#ifndef headers_inner_h__
#define headers_inner_h__

inline int inner_value() { return 2; }

#endif // defined(headers_inner_h__)
8 changes: 8 additions & 0 deletions test/src/headers/outer.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#ifndef headers_outer_h__
#define headers_outer_h__

#include "inner.h"

inline int outer_value() { return inner_value() + 1; }

#endif // defined(headers_outer_h__)
3 changes: 3 additions & 0 deletions test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ mod inner;
#[cfg(test)]
mod inner_sibling;

#[cfg(test)]
mod headers;

// Test that module resolution works correctly with inline modules.
#[cfg(test)]
mod nomod {
Expand Down
Loading