| @@ -0,0 +1,535 @@ |
| 1 | +//! Turning generated C into an executable: write it with `tilrt.h`, |
| 2 | +//! compile it, build the packages' native dependencies (C sources, Rust |
| 3 | +//! crates, `pkg-config` libraries; ADR 0005), and link them with |
| 4 | +//! `libtilrt.a`. |
| 5 | +//! |
| 6 | +//! `tilc_codegen_c` produces the C; this crate runs the tools. It is the |
| 7 | +//! only part of the back end that knows about packages (`tilc_db`'s |
| 8 | +//! manifests), processes and the file system. |
| 9 | + |
| 10 | +use std::hash::{Hash, Hasher}; |
| 11 | +use std::path::{Path, PathBuf}; |
| 12 | +use std::process::Command; |
| 13 | + |
| 14 | +use tilc_db::manifest::{NativeDep, NativeKind}; |
| 15 | +use tilc_span::timings::Timings; |
| 16 | + |
| 17 | +/// The runtime header, embedded so `tilc` works from any directory. |
| 18 | +const HEADER: &str = include_str!("../../../runtime/tilrt/include/tilrt.h"); |
| 19 | + |
| 20 | +/// Libraries a Rust static library needs on Linux |
| 21 | +/// (`rustc --print native-static-libs`). |
| 22 | +const SYSTEM_LIBS: &[&str] = &[ |
| 23 | + "-lgcc_s", |
| 24 | + "-lutil", |
| 25 | + "-lrt", |
| 26 | + "-lpthread", |
| 27 | + "-lm", |
| 28 | + "-ldl", |
| 29 | + "-lc", |
| 30 | +]; |
| 31 | + |
| 32 | +/// How to invoke the C compiler. |
| 33 | +#[derive(Clone, Debug, Default)] |
| 34 | +pub struct CcOptions { |
| 35 | + /// The compiler (default: `$TILC_CC`, else the first of `clang`, `cc` |
| 36 | + /// and `gcc` that supports `musttail`: clang 13 or later, GCC 15 or |
| 37 | + /// later). |
| 38 | + pub cc: Option<String>, |
| 39 | + /// Extra flags (default: `$TILC_CFLAGS`, e.g. sanitizers). |
| 40 | + pub flags: Vec<String>, |
| 41 | + /// The directory holding `libtilrt.a` (default: `$TILRT_LIB_DIR`, else |
| 42 | + /// next to the running executable or its parent, as in Cargo's target |
| 43 | + /// directory). |
| 44 | + pub lib_dir: Option<PathBuf>, |
| 45 | + /// Optimise (`-O2`) instead of debugging (`-O0 -g`). |
| 46 | + pub release: bool, |
| 47 | + /// Native dependencies to build and link (from the packages' |
| 48 | + /// manifests, ADR 0005). |
| 49 | + pub natives: Vec<NativeDep>, |
| 50 | +} |
| 51 | + |
| 52 | +#[derive(Debug)] |
| 53 | +pub enum BuildError { |
| 54 | + /// `libtilrt.a` was not found. |
| 55 | + NoRuntime(String), |
| 56 | + Io(std::io::Error), |
| 57 | + /// The C compiler failed (its output). |
| 58 | + Cc(String), |
| 59 | +} |
| 60 | + |
| 61 | +impl std::fmt::Display for BuildError { |
| 62 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 63 | + match self { |
| 64 | + BuildError::NoRuntime(searched) => write!( |
| 65 | + f, |
| 66 | + "cannot find the runtime library libtilrt.a (searched {searched}); build it with `cargo build -p tilrt` or set TILRT_LIB_DIR" |
| 67 | + ), |
| 68 | + BuildError::Io(e) => write!(f, "{e}"), |
| 69 | + BuildError::Cc(out) => write!(f, "the C compiler failed:\n{out}"), |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +impl From<std::io::Error> for BuildError { |
| 75 | + fn from(e: std::io::Error) -> Self { |
| 76 | + BuildError::Io(e) |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +fn runtime_dir(opts: &CcOptions) -> Result<PathBuf, BuildError> { |
| 81 | + let mut candidates = Vec::new(); |
| 82 | + if let Some(d) = &opts.lib_dir { |
| 83 | + candidates.push(d.clone()); |
| 84 | + } else if let Some(d) = std::env::var_os("TILRT_LIB_DIR") { |
| 85 | + candidates.push(PathBuf::from(d)); |
| 86 | + } else if let Ok(exe) = std::env::current_exe() { |
| 87 | + // target/<profile>/tilc, or target/<profile>/deps/<test binary>. |
| 88 | + for dir in exe.ancestors().skip(1).take(2) { |
| 89 | + candidates.push(dir.to_path_buf()); |
| 90 | + } |
| 91 | + } |
| 92 | + candidates |
| 93 | + .iter() |
| 94 | + .find(|d| d.join("libtilrt.a").is_file()) |
| 95 | + .cloned() |
| 96 | + .ok_or_else(|| { |
| 97 | + BuildError::NoRuntime( |
| 98 | + candidates |
| 99 | + .iter() |
| 100 | + .map(|d| d.display().to_string()) |
| 101 | + .collect::<Vec<_>>() |
| 102 | + .join(", "), |
| 103 | + ) |
| 104 | + }) |
| 105 | +} |
| 106 | + |
| 107 | +/// The first of `clang`, `cc`, `gcc` that supports `musttail` (clang 13+, |
| 108 | +/// GCC 15+), found once per process. clang comes first: on generated C it |
| 109 | +/// compiled 3 times faster than GCC 16 at `-O2`, and its code ran 0-25% |
| 110 | +/// faster on `tests/bench` (issue #61). |
| 111 | +fn default_cc() -> Result<String, BuildError> { |
| 112 | + static FOUND: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new(); |
| 113 | + FOUND |
| 114 | + .get_or_init(|| { |
| 115 | + // The probe goes through stdin to /dev/null: no files to clean |
| 116 | + // up (a probe directory per process used to be left in /tmp |
| 117 | + // when a build was interrupted). |
| 118 | + const PROBE: &str = "static int g(int x) { return x; }\nint f(int x) { __attribute__((musttail)) return g(x); }\n"; |
| 119 | + ["clang", "cc", "gcc"] |
| 120 | + .into_iter() |
| 121 | + .find(|cc| { |
| 122 | + use std::io::Write; |
| 123 | + let child = Command::new(cc) |
| 124 | + .args(["-x", "c", "-c", "-o", "/dev/null", "-"]) |
| 125 | + .stdin(std::process::Stdio::piped()) |
| 126 | + .stdout(std::process::Stdio::null()) |
| 127 | + .stderr(std::process::Stdio::null()) |
| 128 | + .spawn(); |
| 129 | + let Ok(mut child) = child else { |
| 130 | + return false; |
| 131 | + }; |
| 132 | + let written = child |
| 133 | + .stdin |
| 134 | + .take() |
| 135 | + .is_some_and(|mut stdin| stdin.write_all(PROBE.as_bytes()).is_ok()); |
| 136 | + child.wait().is_ok_and(|s| s.success()) && written |
| 137 | + }) |
| 138 | + .map(str::to_owned) |
| 139 | + }) |
| 140 | + .clone() |
| 141 | + .ok_or_else(|| { |
| 142 | + BuildError::Cc( |
| 143 | + "no C compiler supporting `musttail` was found (tried clang, cc, gcc): install clang 13+ or GCC 15+, or set TILC_CC" |
| 144 | + .into(), |
| 145 | + ) |
| 146 | + }) |
| 147 | +} |
| 148 | + |
| 149 | +/// Compile `c_source` into the executable `output`. The C file and the |
| 150 | +/// runtime header are written next to it (`output.c`, `tilrt.h`). |
| 151 | +pub fn build_executable(c_source: &str, output: &Path, opts: &CcOptions) -> Result<(), BuildError> { |
| 152 | + build_executable_timed(&[c_source], output, opts, &mut Timings::default()) |
| 153 | +} |
| 154 | + |
| 155 | +/// [`build_executable`] for a program in one or more C translation units |
| 156 | +/// (`generate_units`), recording the time of compiling the C and of |
| 157 | +/// linking. The units are written next to the executable (`output.c`, |
| 158 | +/// then `output.1.c`, ...) and compiled in parallel. |
| 159 | +/// |
| 160 | +/// Each object is kept in `.tilcayo-cache/` next to the executable, with |
| 161 | +/// a hash of everything that produced it (the compiler, its flags, the C |
| 162 | +/// and the header). A rebuild with the same hash reuses the kept object |
| 163 | +/// instead of compiling again (`compile_cached`). |
| 164 | +pub fn build_executable_timed( |
| 165 | + units: &[&str], |
| 166 | + output: &Path, |
| 167 | + opts: &CcOptions, |
| 168 | + timings: &mut Timings, |
| 169 | +) -> Result<(), BuildError> { |
| 170 | + let lib_dir = runtime_dir(opts)?; |
| 171 | + let dir = output.parent().unwrap_or(Path::new(".")); |
| 172 | + let cache = dir.join(".tilcayo-cache"); |
| 173 | + std::fs::create_dir_all(&cache)?; |
| 174 | + write_if_changed(&dir.join("tilrt.h"), HEADER)?; |
| 175 | + // Finding the compiler runs it once (`default_cc`). |
| 176 | + let (cc, flags) = timings.time("C compile", || compiler(opts))?; |
| 177 | + let mut link = Vec::new(); |
| 178 | + if !opts.natives.is_empty() { |
| 179 | + timings.time("natives", || -> Result<(), BuildError> { |
| 180 | + for dep in &opts.natives { |
| 181 | + link.extend(build_native(dep, dir, &cc, &flags)?); |
| 182 | + } |
| 183 | + Ok(()) |
| 184 | + })?; |
| 185 | + } |
| 186 | + let name = output.file_name().unwrap_or("main".as_ref()); |
| 187 | + let mut jobs = Vec::new(); |
| 188 | + for (i, unit) in units.iter().enumerate() { |
| 189 | + let (c_file, object) = match i { |
| 190 | + 0 => ( |
| 191 | + output.with_extension("c"), |
| 192 | + cache.join(name).with_extension("o"), |
| 193 | + ), |
| 194 | + _ => ( |
| 195 | + output.with_extension(format!("{i}.c")), |
| 196 | + cache.join(name).with_extension(format!("{i}.o")), |
| 197 | + ), |
| 198 | + }; |
| 199 | + std::fs::write(&c_file, unit)?; |
| 200 | + let mut compile = Command::new(&cc); |
| 201 | + compile |
| 202 | + .arg("-std=gnu11") |
| 203 | + .args(if opts.release { |
| 204 | + &["-O2"][..] |
| 205 | + } else { |
| 206 | + &["-O0", "-g"][..] |
| 207 | + }) |
| 208 | + .arg("-w") |
| 209 | + .arg("-I") |
| 210 | + .arg(dir) |
| 211 | + .args(&flags) |
| 212 | + .arg("-c") |
| 213 | + .arg(&c_file) |
| 214 | + .arg("-o") |
| 215 | + .arg(&object); |
| 216 | + jobs.push((compile, object)); |
| 217 | + } |
| 218 | + let objects = timings.time("C compile", || { |
| 219 | + in_parallel(jobs, |(mut compile, object)| { |
| 220 | + compile_cached(&mut compile, &object, run_cc).map(|()| object) |
| 221 | + }) |
| 222 | + .into_iter() |
| 223 | + .collect::<Result<Vec<_>, _>>() |
| 224 | + })?; |
| 225 | + let mut cmd = Command::new(&cc); |
| 226 | + cmd.args(&flags) |
| 227 | + .args(&objects) |
| 228 | + .args(&link) |
| 229 | + .arg(lib_dir.join("libtilrt.a")) |
| 230 | + .args(SYSTEM_LIBS) |
| 231 | + .arg("-o") |
| 232 | + .arg(output); |
| 233 | + timings.time("link", || run_cc(&mut cmd)) |
| 234 | +} |
| 235 | + |
| 236 | +/// How many C translation units to split a program into |
| 237 | +/// (`generate_units`): `$TILC_C_UNITS` if set; else one per core, up to |
| 238 | +/// 8, for a debug build; one for a release build. |
| 239 | +/// |
| 240 | +/// Release builds stay in one unit because calls between units cannot be |
| 241 | +/// inlined: on `tests/bench` split in 4 units, `arith` ran 30% more |
| 242 | +/// cycles, `effects` 9% and `dict` 7% (issue #61). Debug builds (`-O0`) |
| 243 | +/// inline nothing, so splitting them costs nothing at run time. |
| 244 | +pub fn default_units(release: bool) -> usize { |
| 245 | + if let Some(n) = std::env::var("TILC_C_UNITS") |
| 246 | + .ok() |
| 247 | + .and_then(|n| n.parse().ok()) |
| 248 | + { |
| 249 | + return n; |
| 250 | + } |
| 251 | + if release { |
| 252 | + return 1; |
| 253 | + } |
| 254 | + std::thread::available_parallelism().map_or(1, |n| n.get().min(8)) |
| 255 | +} |
| 256 | + |
| 257 | +/// The C compiler and the extra flags to give it. |
| 258 | +fn compiler(opts: &CcOptions) -> Result<(String, Vec<String>), BuildError> { |
| 259 | + let cc = match opts.cc.clone().or_else(|| std::env::var("TILC_CC").ok()) { |
| 260 | + Some(cc) => cc, |
| 261 | + None => default_cc()?, |
| 262 | + }; |
| 263 | + let mut flags = opts.flags.clone(); |
| 264 | + if flags.is_empty() |
| 265 | + && let Ok(env) = std::env::var("TILC_CFLAGS") |
| 266 | + { |
| 267 | + flags.extend(env.split_whitespace().map(str::to_owned)); |
| 268 | + } |
| 269 | + Ok((cc, flags)) |
| 270 | +} |
| 271 | + |
| 272 | +/// Run `compile`, which writes `object`, with `runner`, unless `object` |
| 273 | +/// is up to date: the same command made it from files with the same |
| 274 | +/// contents (the C file and the headers it included, from the compiler's |
| 275 | +/// dependency list, `object.d`). The key, a hash of both, is kept in |
| 276 | +/// `object.key`. |
| 277 | +fn compile_cached( |
| 278 | + compile: &mut Command, |
| 279 | + object: &Path, |
| 280 | + runner: fn(&mut Command) -> Result<(), BuildError>, |
| 281 | +) -> Result<(), BuildError> { |
| 282 | + let deps = object.with_extension("d"); |
| 283 | + let key_file = object.with_extension("key"); |
| 284 | + compile.arg("-MMD").arg("-MF").arg(&deps); |
| 285 | + if object.is_file() |
| 286 | + && let Some(key) = cache_key(compile, &deps) |
| 287 | + && std::fs::read_to_string(&key_file).is_ok_and(|k| k == key) |
| 288 | + { |
| 289 | + return Ok(()); |
| 290 | + } |
| 291 | + // No key while the object may be stale or half-written. |
| 292 | + let _ = std::fs::remove_file(&key_file); |
| 293 | + runner(compile)?; |
| 294 | + if let Some(key) = cache_key(compile, &deps) { |
| 295 | + std::fs::write(&key_file, key)?; |
| 296 | + } |
| 297 | + Ok(()) |
| 298 | +} |
| 299 | + |
| 300 | +/// A hash of `compile` and of the contents of the files listed in the |
| 301 | +/// dependency file `deps`; none if one cannot be read. |
| 302 | +fn cache_key(compile: &Command, deps: &Path) -> Option<String> { |
| 303 | + let mut h = std::collections::hash_map::DefaultHasher::new(); |
| 304 | + format!("{compile:?}").hash(&mut h); |
| 305 | + for file in parse_deps(&std::fs::read_to_string(deps).ok()?) { |
| 306 | + file.hash(&mut h); |
| 307 | + std::fs::read(&file).ok()?.hash(&mut h); |
| 308 | + } |
| 309 | + Some(format!("{:016x}\n", h.finish())) |
| 310 | +} |
| 311 | + |
| 312 | +/// The prerequisites in a Make rule written by `-MMD` |
| 313 | +/// (`target: a.c b.h \<newline> c.h`); `\ ` escapes a space in a path. |
| 314 | +fn parse_deps(rule: &str) -> Vec<String> { |
| 315 | + let Some((_, prereqs)) = rule.split_once(": ") else { |
| 316 | + return Vec::new(); |
| 317 | + }; |
| 318 | + let mut files = Vec::new(); |
| 319 | + let mut current = String::new(); |
| 320 | + let mut chars = prereqs.chars().peekable(); |
| 321 | + while let Some(c) = chars.next() { |
| 322 | + match c { |
| 323 | + '\\' if chars.peek() == Some(&' ') => { |
| 324 | + current.push(' '); |
| 325 | + chars.next(); |
| 326 | + } |
| 327 | + '\\' if chars.peek() == Some(&'\n') => {} |
| 328 | + c if c.is_whitespace() => { |
| 329 | + if !current.is_empty() { |
| 330 | + files.push(std::mem::take(&mut current)); |
| 331 | + } |
| 332 | + } |
| 333 | + c => current.push(c), |
| 334 | + } |
| 335 | + } |
| 336 | + if !current.is_empty() { |
| 337 | + files.push(current); |
| 338 | + } |
| 339 | + files |
| 340 | +} |
| 341 | + |
| 342 | +/// Write `contents` unless the file already has them (keeping its |
| 343 | +/// modification time for tools that look at it). |
| 344 | +fn write_if_changed(path: &Path, contents: &str) -> std::io::Result<()> { |
| 345 | + if std::fs::read(path).is_ok_and(|old| old == contents.as_bytes()) { |
| 346 | + return Ok(()); |
| 347 | + } |
| 348 | + std::fs::write(path, contents) |
| 349 | +} |
| 350 | + |
| 351 | +/// `f` of each job, in order, running up to one job per core at a time. |
| 352 | +fn in_parallel<J: Send, R: Send>(jobs: Vec<J>, f: impl Fn(J) -> R + Sync) -> Vec<R> { |
| 353 | + let width = std::thread::available_parallelism().map_or(1, |n| n.get()); |
| 354 | + let mut results = Vec::with_capacity(jobs.len()); |
| 355 | + let mut jobs = jobs.into_iter().peekable(); |
| 356 | + while jobs.peek().is_some() { |
| 357 | + let batch: Vec<J> = jobs.by_ref().take(width).collect(); |
| 358 | + std::thread::scope(|scope| { |
| 359 | + let running: Vec<_> = batch.into_iter().map(|j| scope.spawn(|| f(j))).collect(); |
| 360 | + results.extend( |
| 361 | + running |
| 362 | + .into_iter() |
| 363 | + .map(|r| r.join().expect("a compiler thread panicked")), |
| 364 | + ); |
| 365 | + }); |
| 366 | + } |
| 367 | + results |
| 368 | +} |
| 369 | + |
| 370 | +/// Run the C compiler or linker; on failure, its output. |
| 371 | +fn run_cc(cmd: &mut Command) -> Result<(), BuildError> { |
| 372 | + let result = cmd.output()?; |
| 373 | + if !result.status.success() { |
| 374 | + return Err(BuildError::Cc(format!( |
| 375 | + "{}{}", |
| 376 | + String::from_utf8_lossy(&result.stdout), |
| 377 | + String::from_utf8_lossy(&result.stderr) |
| 378 | + ))); |
| 379 | + } |
| 380 | + Ok(()) |
| 381 | +} |
| 382 | + |
| 383 | +fn run(cmd: &mut Command) -> Result<String, BuildError> { |
| 384 | + let result = cmd.output()?; |
| 385 | + if !result.status.success() { |
| 386 | + return Err(BuildError::Cc(format!( |
| 387 | + "{:?}\n{}{}", |
| 388 | + cmd, |
| 389 | + String::from_utf8_lossy(&result.stdout), |
| 390 | + String::from_utf8_lossy(&result.stderr) |
| 391 | + ))); |
| 392 | + } |
| 393 | + Ok(String::from_utf8_lossy(&result.stdout).into_owned()) |
| 394 | +} |
| 395 | + |
| 396 | +/// Build one native dependency next to the program (`dir`); returns what |
| 397 | +/// to add to the link command. |
| 398 | +fn build_native( |
| 399 | + dep: &NativeDep, |
| 400 | + dir: &Path, |
| 401 | + cc: &str, |
| 402 | + flags: &[String], |
| 403 | +) -> Result<Vec<String>, BuildError> { |
| 404 | + let work = dir.join(".tilcayo-native").join(&dep.name); |
| 405 | + std::fs::create_dir_all(&work)?; |
| 406 | + match &dep.kind { |
| 407 | + NativeKind::C { |
| 408 | + sources, |
| 409 | + include, |
| 410 | + cflags, |
| 411 | + } => { |
| 412 | + let jobs = sources.iter().map(|src| { |
| 413 | + let stem = src |
| 414 | + .file_stem() |
| 415 | + .map_or("src".into(), |s| s.to_string_lossy().into_owned()); |
| 416 | + // Distinct sources with the same name get distinct objects. |
| 417 | + let obj = work.join(format!("{stem}-{:x}.o", hash(&src.display().to_string()))); |
| 418 | + let mut cmd = Command::new(cc); |
| 419 | + cmd.args(["-std=gnu11", "-O2", "-w", "-c", "-I"]) |
| 420 | + .arg(dir) |
| 421 | + .args( |
| 422 | + include |
| 423 | + .iter() |
| 424 | + .flat_map(|i| [PathBuf::from("-I"), i.clone()]), |
| 425 | + ) |
| 426 | + .args(cflags) |
| 427 | + .args(flags) |
| 428 | + .arg(src) |
| 429 | + .arg("-o") |
| 430 | + .arg(&obj); |
| 431 | + (cmd, obj) |
| 432 | + }); |
| 433 | + in_parallel(jobs.collect(), |(mut cmd, obj)| { |
| 434 | + compile_cached(&mut cmd, &obj, |c| run(c).map(drop))?; |
| 435 | + Ok(obj.display().to_string()) |
| 436 | + }) |
| 437 | + .into_iter() |
| 438 | + .collect() |
| 439 | + } |
| 440 | + NativeKind::Static { lib } => Ok(vec![lib.display().to_string()]), |
| 441 | + NativeKind::PkgConfig { name } => { |
| 442 | + let out = run(Command::new("pkg-config").args(["--cflags", "--libs", name]))?; |
| 443 | + Ok(out.split_whitespace().map(str::to_owned).collect()) |
| 444 | + } |
| 445 | + NativeKind::Cargo { path } => { |
| 446 | + let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()); |
| 447 | + let target = work.join("target"); |
| 448 | + run(Command::new(cargo) |
| 449 | + .args(["build", "--quiet", "--release", "--manifest-path"]) |
| 450 | + .arg(path.join("Cargo.toml")) |
| 451 | + .arg("--target-dir") |
| 452 | + .arg(&target))?; |
| 453 | + let manifest = std::fs::read_to_string(path.join("Cargo.toml"))?; |
| 454 | + let value: toml::Table = manifest |
| 455 | + .parse() |
| 456 | + .map_err(|e| BuildError::Cc(format!("{}: {e}", path.display())))?; |
| 457 | + let name = value |
| 458 | + .get("lib") |
| 459 | + .and_then(|l| l.get("name")) |
| 460 | + .or_else(|| value.get("package").and_then(|p| p.get("name"))) |
| 461 | + .and_then(|n| n.as_str()) |
| 462 | + .unwrap_or("native") |
| 463 | + .replace('-', "_"); |
| 464 | + // A Rust static library carries its own copy of Rust's standard |
| 465 | + // library, as does libtilrt.a: let the linker keep one. |
| 466 | + Ok(vec![ |
| 467 | + target |
| 468 | + .join("release") |
| 469 | + .join(format!("lib{name}.a")) |
| 470 | + .display() |
| 471 | + .to_string(), |
| 472 | + "-Wl,--allow-multiple-definition".into(), |
| 473 | + ]) |
| 474 | + } |
| 475 | + } |
| 476 | +} |
| 477 | + |
| 478 | +fn hash(s: &str) -> u64 { |
| 479 | + s.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| { |
| 480 | + (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) |
| 481 | + }) |
| 482 | +} |
| 483 | + |
| 484 | +#[cfg(test)] |
| 485 | +mod tests { |
| 486 | + use super::*; |
| 487 | + use std::sync::atomic::{AtomicUsize, Ordering}; |
| 488 | + |
| 489 | + #[test] |
| 490 | + fn dependency_lists_are_parsed() { |
| 491 | + let rule = "out/a.o: src/a.c src/my\\ dir/b.h \\\n /usr/include/c.h\n"; |
| 492 | + assert_eq!( |
| 493 | + parse_deps(rule), |
| 494 | + ["src/a.c", "src/my dir/b.h", "/usr/include/c.h"] |
| 495 | + ); |
| 496 | + } |
| 497 | + |
| 498 | + /// Compiler runs, counted by `counted`. |
| 499 | + static RUNS: AtomicUsize = AtomicUsize::new(0); |
| 500 | + |
| 501 | + fn counted(cmd: &mut Command) -> Result<(), BuildError> { |
| 502 | + RUNS.fetch_add(1, Ordering::SeqCst); |
| 503 | + run_cc(cmd) |
| 504 | + } |
| 505 | + |
| 506 | + #[test] |
| 507 | + fn objects_are_rebuilt_only_when_an_input_changes() { |
| 508 | + let (cc, _) = compiler(&CcOptions::default()).expect("a C compiler"); |
| 509 | + let dir = std::env::temp_dir().join(format!("tilc-cache-test-{}", std::process::id())); |
| 510 | + std::fs::create_dir_all(&dir).unwrap(); |
| 511 | + std::fs::write( |
| 512 | + dir.join("a.c"), |
| 513 | + "#include \"b.h\"\nint f(void) { return B; }\n", |
| 514 | + ) |
| 515 | + .unwrap(); |
| 516 | + std::fs::write(dir.join("b.h"), "#define B 1\n").unwrap(); |
| 517 | + let object = dir.join("a.o"); |
| 518 | + let build = |flag: &str| { |
| 519 | + let mut cmd = Command::new(&cc); |
| 520 | + cmd.arg(flag) |
| 521 | + .arg("-c") |
| 522 | + .arg(dir.join("a.c")) |
| 523 | + .arg("-o") |
| 524 | + .arg(&object); |
| 525 | + compile_cached(&mut cmd, &object, counted).unwrap(); |
| 526 | + RUNS.load(Ordering::SeqCst) |
| 527 | + }; |
| 528 | + assert_eq!(build("-O0"), 1); |
| 529 | + assert_eq!(build("-O0"), 1, "unchanged: the object is kept"); |
| 530 | + std::fs::write(dir.join("b.h"), "#define B 2\n").unwrap(); |
| 531 | + assert_eq!(build("-O0"), 2, "an included header changed"); |
| 532 | + assert_eq!(build("-O1"), 3, "the flags changed"); |
| 533 | + let _ = std::fs::remove_dir_all(&dir); |
| 534 | + } |
| 535 | +} |