| 1 |
//! A Rust library for build scripts to automatically configure code based on |
| 2 |
//! compiler support. Code snippets are dynamically tested to see if the `rustc` |
| 3 |
//! will accept them, rather than hard-coding specific version support. |
| 4 |
//! |
| 5 |
//! |
| 6 |
//! ## Usage |
| 7 |
//! |
| 8 |
//! Add this to your `Cargo.toml`: |
| 9 |
//! |
| 10 |
//! ```toml |
| 11 |
//! [build-dependencies] |
| 12 |
//! autocfg = "1" |
| 13 |
//! ``` |
| 14 |
//! |
| 15 |
//! Then use it in your `build.rs` script to detect compiler features. For |
| 16 |
//! example, to test for 128-bit integer support, it might look like: |
| 17 |
//! |
| 18 |
//! ```rust |
| 19 |
//! extern crate autocfg; |
| 20 |
//! |
| 21 |
//! fn main() { |
| 22 |
//! # // Normally, cargo will set `OUT_DIR` for build scripts. |
| 23 |
//! # std::env::set_var("OUT_DIR", "target"); |
| 24 |
//! let ac = autocfg::new(); |
| 25 |
//! ac.emit_has_type("i128"); |
| 26 |
//! |
| 27 |
//! // (optional) We don't need to rerun for anything external. |
| 28 |
//! autocfg::rerun_path("build.rs"); |
| 29 |
//! } |
| 30 |
//! ``` |
| 31 |
//! |
| 32 |
//! If the type test succeeds, this will write a `cargo:rustc-cfg=has_i128` line |
| 33 |
//! for Cargo, which translates to Rust arguments `--cfg has_i128`. Then in the |
| 34 |
//! rest of your Rust code, you can add `#[cfg(has_i128)]` conditions on code that |
| 35 |
//! should only be used when the compiler supports it. |
| 36 |
//! |
| 37 |
//! ## Caution |
| 38 |
//! |
| 39 |
//! Many of the probing methods of `AutoCfg` document the particular template they |
| 40 |
//! use, **subject to change**. The inputs are not validated to make sure they are |
| 41 |
//! semantically correct for their expected use, so it's _possible_ to escape and |
| 42 |
//! inject something unintended. However, such abuse is unsupported and will not |
| 43 |
//! be considered when making changes to the templates. |
| 44 |
|
| 45 |
#![deny(missing_debug_implementations)] |
| 46 |
#![deny(missing_docs)] |
| 47 |
// allow future warnings that can't be fixed while keeping 1.0 compatibility |
| 48 |
#![allow(unknown_lints)] |
| 49 |
#![allow(bare_trait_objects)] |
| 50 |
#![allow(ellipsis_inclusive_range_patterns)] |
| 51 |
|
| 52 |
/// Local macro to avoid `std::try!`, deprecated in Rust 1.39. |
| 53 |
macro_rules! try { |
| 54 |
($result:expr) => { |
| 55 |
match $result { |
| 56 |
Ok(value) => value, |
| 57 |
Err(error) => return Err(error), |
| 58 |
} |
| 59 |
}; |
| 60 |
} |
| 61 |
|
| 62 |
use std::env; |
| 63 |
use std::ffi::OsString; |
| 64 |
use std::fs; |
| 65 |
use std::io::{stderr, Write}; |
| 66 |
use std::path::{Path, PathBuf}; |
| 67 |
use std::process::{Command, Stdio}; |
| 68 |
#[allow(deprecated)] |
| 69 |
use std::sync::atomic::ATOMIC_USIZE_INIT; |
| 70 |
use std::sync::atomic::{AtomicUsize, Ordering}; |
| 71 |
|
| 72 |
mod error; |
| 73 |
pub use error::Error; |
| 74 |
|
| 75 |
mod version; |
| 76 |
use version::Version; |
| 77 |
|
| 78 |
#[cfg(test)] |
| 79 |
mod tests; |
| 80 |
|
| 81 |
/// Helper to detect compiler features for `cfg` output in build scripts. |
| 82 |
#[derive(Clone, Debug)] |
| 83 |
pub struct AutoCfg { |
| 84 |
out_dir: PathBuf, |
| 85 |
rustc: PathBuf, |
| 86 |
rustc_version: Version, |
| 87 |
target: Option<OsString>, |
| 88 |
no_std: bool, |
| 89 |
rustflags: Vec<String>, |
| 90 |
} |
| 91 |
|
| 92 |
/// Writes a config flag for rustc on standard out. |
| 93 |
/// |
| 94 |
/// This looks like: `cargo:rustc-cfg=CFG` |
| 95 |
/// |
| 96 |
/// Cargo will use this in arguments to rustc, like `--cfg CFG`. |
| 97 |
pub fn emit(cfg: &str) { |
| 98 |
println!("cargo:rustc-cfg={}", cfg); |
| 99 |
} |
| 100 |
|
| 101 |
/// Writes a line telling Cargo to rerun the build script if `path` changes. |
| 102 |
/// |
| 103 |
/// This looks like: `cargo:rerun-if-changed=PATH` |
| 104 |
/// |
| 105 |
/// This requires at least cargo 0.7.0, corresponding to rustc 1.6.0. Earlier |
| 106 |
/// versions of cargo will simply ignore the directive. |
| 107 |
pub fn rerun_path(path: &str) { |
| 108 |
println!("cargo:rerun-if-changed={}", path); |
| 109 |
} |
| 110 |
|
| 111 |
/// Writes a line telling Cargo to rerun the build script if the environment |
| 112 |
/// variable `var` changes. |
| 113 |
/// |
| 114 |
/// This looks like: `cargo:rerun-if-env-changed=VAR` |
| 115 |
/// |
| 116 |
/// This requires at least cargo 0.21.0, corresponding to rustc 1.20.0. Earlier |
| 117 |
/// versions of cargo will simply ignore the directive. |
| 118 |
pub fn rerun_env(var: &str) { |
| 119 |
println!("cargo:rerun-if-env-changed={}", var); |
| 120 |
} |
| 121 |
|
| 122 |
/// Create a new `AutoCfg` instance. |
| 123 |
/// |
| 124 |
/// # Panics |
| 125 |
/// |
| 126 |
/// Panics if `AutoCfg::new()` returns an error. |
| 127 |
pub fn new() -> AutoCfg { |
| 128 |
AutoCfg::new().unwrap() |
| 129 |
} |
| 130 |
|
| 131 |
impl AutoCfg { |
| 132 |
/// Create a new `AutoCfg` instance. |
| 133 |
/// |
| 134 |
/// # Common errors |
| 135 |
/// |
| 136 |
/// - `rustc` can't be executed, from `RUSTC` or in the `PATH`. |
| 137 |
/// - The version output from `rustc` can't be parsed. |
| 138 |
/// - `OUT_DIR` is not set in the environment, or is not a writable directory. |
| 139 |
/// |
| 140 |
pub fn new() -> Result<Self, Error> { |
| 141 |
match env::var_os("OUT_DIR") { |
| 142 |
Some(d) => Self::with_dir(d), |
| 143 |
None => Err(error::from_str("no OUT_DIR specified!")), |
| 144 |
} |
| 145 |
} |
| 146 |
|
| 147 |
/// Create a new `AutoCfg` instance with the specified output directory. |
| 148 |
/// |
| 149 |
/// # Common errors |
| 150 |
/// |
| 151 |
/// - `rustc` can't be executed, from `RUSTC` or in the `PATH`. |
| 152 |
/// - The version output from `rustc` can't be parsed. |
| 153 |
/// - `dir` is not a writable directory. |
| 154 |
/// |
| 155 |
pub fn with_dir<T: Into<PathBuf>>(dir: T) -> Result<Self, Error> { |
| 156 |
let rustc = env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); |
| 157 |
let rustc: PathBuf = rustc.into(); |
| 158 |
let rustc_version = try!(Version::from_rustc(&rustc)); |
| 159 |
|
| 160 |
let target = env::var_os("TARGET"); |
| 161 |
|
| 162 |
// Sanity check the output directory |
| 163 |
let dir = dir.into(); |
| 164 |
let meta = try!(fs::metadata(&dir).map_err(error::from_io)); |
| 165 |
if !meta.is_dir() || meta.permissions().readonly() { |
| 166 |
return Err(error::from_str("output path is not a writable directory")); |
| 167 |
} |
| 168 |
|
| 169 |
let mut ac = AutoCfg { |
| 170 |
rustflags: rustflags(&target, &dir), |
| 171 |
out_dir: dir, |
| 172 |
rustc: rustc, |
| 173 |
rustc_version: rustc_version, |
| 174 |
target: target, |
| 175 |
no_std: false, |
| 176 |
}; |
| 177 |
|
| 178 |
// Sanity check with and without `std`. |
| 179 |
if !ac.probe("").unwrap_or(false) { |
| 180 |
ac.no_std = true; |
| 181 |
if !ac.probe("").unwrap_or(false) { |
| 182 |
// Neither worked, so assume nothing... |
| 183 |
ac.no_std = false; |
| 184 |
let warning = b"warning: autocfg could not probe for `std`\n"; |
| 185 |
stderr().write_all(warning).ok(); |
| 186 |
} |
| 187 |
} |
| 188 |
Ok(ac) |
| 189 |
} |
| 190 |
|
| 191 |
/// Test whether the current `rustc` reports a version greater than |
| 192 |
/// or equal to "`major`.`minor`". |
| 193 |
pub fn probe_rustc_version(&self, major: usize, minor: usize) -> bool { |
| 194 |
self.rustc_version >= Version::new(major, minor, 0) |
| 195 |
} |
| 196 |
|
| 197 |
/// Sets a `cfg` value of the form `rustc_major_minor`, like `rustc_1_29`, |
| 198 |
/// if the current `rustc` is at least that version. |
| 199 |
pub fn emit_rustc_version(&self, major: usize, minor: usize) { |
| 200 |
if self.probe_rustc_version(major, minor) { |
| 201 |
emit(&format!("rustc_{}_{}", major, minor)); |
| 202 |
} |
| 203 |
} |
| 204 |
|
| 205 |
fn probe<T: AsRef<[u8]>>(&self, code: T) -> Result<bool, Error> { |
| 206 |
#[allow(deprecated)] |
| 207 |
static ID: AtomicUsize = ATOMIC_USIZE_INIT; |
| 208 |
|
| 209 |
let id = ID.fetch_add(1, Ordering::Relaxed); |
| 210 |
let mut command = Command::new(&self.rustc); |
| 211 |
command |
| 212 |
.arg("--crate-name") |
| 213 |
.arg(format!("probe{}", id)) |
| 214 |
.arg("--crate-type=lib") |
| 215 |
.arg("--out-dir") |
| 216 |
.arg(&self.out_dir) |
| 217 |
.arg("--emit=llvm-ir"); |
| 218 |
|
| 219 |
if let Some(target) = self.target.as_ref() { |
| 220 |
command.arg("--target").arg(target); |
| 221 |
} |
| 222 |
|
| 223 |
command.args(&self.rustflags); |
| 224 |
|
| 225 |
// Mozilla-local change: throw away stderr output. |
| 226 |
// |
| 227 |
// Mozilla's build system runs cargo with `-v -v` to help diagnose rustc |
| 228 |
// selection problems. Without the change below, that causes error |
| 229 |
// messages from autocfg compiler invocations (which simply indicate |
| 230 |
// that the feature autocfg was checking for isn't available, and are |
| 231 |
// not actual build errors) to show up in the build output stream, where |
| 232 |
// they confuse other parts of Mozilla's build system that try to |
| 233 |
// highlight and track errors. |
| 234 |
// |
| 235 |
// See: https://github.com/cuviper/autocfg/issues/30 |
| 236 |
command.arg("-").stdin(Stdio::piped()).stderr(Stdio::null()); |
| 237 |
let mut child = try!(command.spawn().map_err(error::from_io)); |
| 238 |
let mut stdin = child.stdin.take().expect("rustc stdin"); |
| 239 |
|
| 240 |
if self.no_std { |
| 241 |
try!(stdin.write_all(b"#![no_std]\n").map_err(error::from_io)); |
| 242 |
} |
| 243 |
try!(stdin.write_all(code.as_ref()).map_err(error::from_io)); |
| 244 |
drop(stdin); |
| 245 |
|
| 246 |
let status = try!(child.wait().map_err(error::from_io)); |
| 247 |
Ok(status.success()) |
| 248 |
} |
| 249 |
|
| 250 |
/// Tests whether the given sysroot crate can be used. |
| 251 |
/// |
| 252 |
/// The test code is subject to change, but currently looks like: |
| 253 |
/// |
| 254 |
/// ```ignore |
| 255 |
/// extern crate CRATE as probe; |
| 256 |
/// ``` |
| 257 |
pub fn probe_sysroot_crate(&self, name: &str) -> bool { |
| 258 |
self.probe(format!("extern crate {} as probe;", name)) // `as _` wasn't stabilized until Rust 1.33 |
| 259 |
.unwrap_or(false) |
| 260 |
} |
| 261 |
|
| 262 |
/// Emits a config value `has_CRATE` if `probe_sysroot_crate` returns true. |
| 263 |
pub fn emit_sysroot_crate(&self, name: &str) { |
| 264 |
if self.probe_sysroot_crate(name) { |
| 265 |
emit(&format!("has_{}", mangle(name))); |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
/// Tests whether the given path can be used. |
| 270 |
/// |
| 271 |
/// The test code is subject to change, but currently looks like: |
| 272 |
/// |
| 273 |
/// ```ignore |
| 274 |
/// pub use PATH; |
| 275 |
/// ``` |
| 276 |
pub fn probe_path(&self, path: &str) -> bool { |
| 277 |
self.probe(format!("pub use {};", path)).unwrap_or(false) |
| 278 |
} |
| 279 |
|
| 280 |
/// Emits a config value `has_PATH` if `probe_path` returns true. |
| 281 |
/// |
| 282 |
/// Any non-identifier characters in the `path` will be replaced with |
| 283 |
/// `_` in the generated config value. |
| 284 |
pub fn emit_has_path(&self, path: &str) { |
| 285 |
if self.probe_path(path) { |
| 286 |
emit(&format!("has_{}", mangle(path))); |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
/// Emits the given `cfg` value if `probe_path` returns true. |
| 291 |
pub fn emit_path_cfg(&self, path: &str, cfg: &str) { |
| 292 |
if self.probe_path(path) { |
| 293 |
emit(cfg); |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
/// Tests whether the given trait can be used. |
| 298 |
/// |
| 299 |
/// The test code is subject to change, but currently looks like: |
| 300 |
/// |
| 301 |
/// ```ignore |
| 302 |
/// pub trait Probe: TRAIT + Sized {} |
| 303 |
/// ``` |
| 304 |
pub fn probe_trait(&self, name: &str) -> bool { |
| 305 |
self.probe(format!("pub trait Probe: {} + Sized {{}}", name)) |
| 306 |
.unwrap_or(false) |
| 307 |
} |
| 308 |
|
| 309 |
/// Emits a config value `has_TRAIT` if `probe_trait` returns true. |
| 310 |
/// |
| 311 |
/// Any non-identifier characters in the trait `name` will be replaced with |
| 312 |
/// `_` in the generated config value. |
| 313 |
pub fn emit_has_trait(&self, name: &str) { |
| 314 |
if self.probe_trait(name) { |
| 315 |
emit(&format!("has_{}", mangle(name))); |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
/// Emits the given `cfg` value if `probe_trait` returns true. |
| 320 |
pub fn emit_trait_cfg(&self, name: &str, cfg: &str) { |
| 321 |
if self.probe_trait(name) { |
| 322 |
emit(cfg); |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
/// Tests whether the given type can be used. |
| 327 |
/// |
| 328 |
/// The test code is subject to change, but currently looks like: |
| 329 |
/// |
| 330 |
/// ```ignore |
| 331 |
/// pub type Probe = TYPE; |
| 332 |
/// ``` |
| 333 |
pub fn probe_type(&self, name: &str) -> bool { |
| 334 |
self.probe(format!("pub type Probe = {};", name)) |
| 335 |
.unwrap_or(false) |
| 336 |
} |
| 337 |
|
| 338 |
/// Emits a config value `has_TYPE` if `probe_type` returns true. |
| 339 |
/// |
| 340 |
/// Any non-identifier characters in the type `name` will be replaced with |
| 341 |
/// `_` in the generated config value. |
| 342 |
pub fn emit_has_type(&self, name: &str) { |
| 343 |
if self.probe_type(name) { |
| 344 |
emit(&format!("has_{}", mangle(name))); |
| 345 |
} |
| 346 |
} |
| 347 |
|
| 348 |
/// Emits the given `cfg` value if `probe_type` returns true. |
| 349 |
pub fn emit_type_cfg(&self, name: &str, cfg: &str) { |
| 350 |
if self.probe_type(name) { |
| 351 |
emit(cfg); |
| 352 |
} |
| 353 |
} |
| 354 |
|
| 355 |
/// Tests whether the given expression can be used. |
| 356 |
/// |
| 357 |
/// The test code is subject to change, but currently looks like: |
| 358 |
/// |
| 359 |
/// ```ignore |
| 360 |
/// pub fn probe() { let _ = EXPR; } |
| 361 |
/// ``` |
| 362 |
pub fn probe_expression(&self, expr: &str) -> bool { |
| 363 |
self.probe(format!("pub fn probe() {{ let _ = {}; }}", expr)) |
| 364 |
.unwrap_or(false) |
| 365 |
} |
| 366 |
|
| 367 |
/// Emits the given `cfg` value if `probe_expression` returns true. |
| 368 |
pub fn emit_expression_cfg(&self, expr: &str, cfg: &str) { |
| 369 |
if self.probe_expression(expr) { |
| 370 |
emit(cfg); |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
/// Tests whether the given constant expression can be used. |
| 375 |
/// |
| 376 |
/// The test code is subject to change, but currently looks like: |
| 377 |
/// |
| 378 |
/// ```ignore |
| 379 |
/// pub const PROBE: () = ((), EXPR).0; |
| 380 |
/// ``` |
| 381 |
pub fn probe_constant(&self, expr: &str) -> bool { |
| 382 |
self.probe(format!("pub const PROBE: () = ((), {}).0;", expr)) |
| 383 |
.unwrap_or(false) |
| 384 |
} |
| 385 |
|
| 386 |
/// Emits the given `cfg` value if `probe_constant` returns true. |
| 387 |
pub fn emit_constant_cfg(&self, expr: &str, cfg: &str) { |
| 388 |
if self.probe_constant(expr) { |
| 389 |
emit(cfg); |
| 390 |
} |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
fn mangle(s: &str) -> String { |
| 395 |
s.chars() |
| 396 |
.map(|c| match c { |
| 397 |
'A'...'Z' | 'a'...'z' | '0'...'9' => c, |
| 398 |
_ => '_', |
| 399 |
}) |
| 400 |
.collect() |
| 401 |
} |
| 402 |
|
| 403 |
fn dir_contains_target( |
| 404 |
target: &Option<OsString>, |
| 405 |
dir: &Path, |
| 406 |
cargo_target_dir: Option<OsString>, |
| 407 |
) -> bool { |
| 408 |
target |
| 409 |
.as_ref() |
| 410 |
.and_then(|target| { |
| 411 |
dir.to_str().and_then(|dir| { |
| 412 |
let mut cargo_target_dir = cargo_target_dir |
| 413 |
.map(PathBuf::from) |
| 414 |
.unwrap_or_else(|| PathBuf::from("target")); |
| 415 |
cargo_target_dir.push(target); |
| 416 |
|
| 417 |
cargo_target_dir |
| 418 |
.to_str() |
| 419 |
.map(|cargo_target_dir| dir.contains(&cargo_target_dir)) |
| 420 |
}) |
| 421 |
}) |
| 422 |
.unwrap_or(false) |
| 423 |
} |
| 424 |
|
| 425 |
fn rustflags(target: &Option<OsString>, dir: &Path) -> Vec<String> { |
| 426 |
// Starting with rust-lang/cargo#9601, shipped in Rust 1.55, Cargo always sets |
| 427 |
// CARGO_ENCODED_RUSTFLAGS for any host/target build script invocation. This |
| 428 |
// includes any source of flags, whether from the environment, toml config, or |
| 429 |
// whatever may come in the future. The value is either an empty string, or a |
| 430 |
// list of arguments separated by the ASCII unit separator (US), 0x1f. |
| 431 |
if let Ok(a) = env::var("CARGO_ENCODED_RUSTFLAGS") { |
| 432 |
return if a.is_empty() { |
| 433 |
Vec::new() |
| 434 |
} else { |
| 435 |
a.split('\x1f').map(str::to_string).collect() |
| 436 |
}; |
| 437 |
} |
| 438 |
|
| 439 |
// Otherwise, we have to take a more heuristic approach, and we don't |
| 440 |
// support values from toml config at all. |
| 441 |
// |
| 442 |
// Cargo only applies RUSTFLAGS for building TARGET artifact in |
| 443 |
// cross-compilation environment. Sadly, we don't have a way to detect |
| 444 |
// when we're building HOST artifact in a cross-compilation environment, |
| 445 |
// so for now we only apply RUSTFLAGS when cross-compiling an artifact. |
| 446 |
// |
| 447 |
// See https://github.com/cuviper/autocfg/pull/10#issuecomment-527575030. |
| 448 |
if *target != env::var_os("HOST") |
| 449 |
|| dir_contains_target(target, dir, env::var_os("CARGO_TARGET_DIR")) |
| 450 |
{ |
| 451 |
if let Ok(rustflags) = env::var("RUSTFLAGS") { |
| 452 |
// This is meant to match how cargo handles the RUSTFLAGS environment variable. |
| 453 |
// See https://github.com/rust-lang/cargo/blob/69aea5b6f69add7c51cca939a79644080c0b0ba0/src/cargo/core/compiler/build_context/target_info.rs#L434-L441 |
| 454 |
return rustflags |
| 455 |
.split(' ') |
| 456 |
.map(str::trim) |
| 457 |
.filter(|s| !s.is_empty()) |
| 458 |
.map(str::to_string) |
| 459 |
.collect(); |
| 460 |
} |
| 461 |
} |
| 462 |
|
| 463 |
Vec::new() |
| 464 |
} |