Debian Codegraph @

.cargo/vendor/autocfg/src/lib.rs

raw
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::fmt::Arguments;
65 use std::fs;
66 use std::io::{stderr, Write};
67 use std::path::{Path, PathBuf};
68 use std::process::Stdio;
69 #[allow(deprecated)]
70 use std::sync::atomic::ATOMIC_USIZE_INIT;
71 use std::sync::atomic::{AtomicUsize, Ordering};
72
73 mod error;
74 pub use error::Error;
75
76 mod rustc;
77 use rustc::Rustc;
78
79 mod version;
80 use version::Version;
81
82 #[cfg(test)]
83 mod tests;
84
85 /// Helper to detect compiler features for `cfg` output in build scripts.
86 #[derive(Clone, Debug)]
87 pub struct AutoCfg {
88 out_dir: PathBuf,
89 rustc: Rustc,
90 rustc_version: Version,
91 target: Option<OsString>,
92 no_std: bool,
93 rustflags: Vec<String>,
94 }
95
96 /// Writes a config flag for rustc on standard out.
97 ///
98 /// This looks like: `cargo:rustc-cfg=CFG`
99 ///
100 /// Cargo will use this in arguments to rustc, like `--cfg CFG`.
101 pub fn emit(cfg: &str) {
102 println!("cargo:rustc-cfg={}", cfg);
103 }
104
105 /// Writes a line telling Cargo to rerun the build script if `path` changes.
106 ///
107 /// This looks like: `cargo:rerun-if-changed=PATH`
108 ///
109 /// This requires at least cargo 0.7.0, corresponding to rustc 1.6.0. Earlier
110 /// versions of cargo will simply ignore the directive.
111 pub fn rerun_path(path: &str) {
112 println!("cargo:rerun-if-changed={}", path);
113 }
114
115 /// Writes a line telling Cargo to rerun the build script if the environment
116 /// variable `var` changes.
117 ///
118 /// This looks like: `cargo:rerun-if-env-changed=VAR`
119 ///
120 /// This requires at least cargo 0.21.0, corresponding to rustc 1.20.0. Earlier
121 /// versions of cargo will simply ignore the directive.
122 pub fn rerun_env(var: &str) {
123 println!("cargo:rerun-if-env-changed={}", var);
124 }
125
126 /// Creates a new `AutoCfg` instance.
127 ///
128 /// # Panics
129 ///
130 /// Panics if `AutoCfg::new()` returns an error.
131 pub fn new() -> AutoCfg {
132 AutoCfg::new().unwrap()
133 }
134
135 impl AutoCfg {
136 /// Creates a new `AutoCfg` instance.
137 ///
138 /// # Common errors
139 ///
140 /// - `rustc` can't be executed, from `RUSTC` or in the `PATH`.
141 /// - The version output from `rustc` can't be parsed.
142 /// - `OUT_DIR` is not set in the environment, or is not a writable directory.
143 ///
144 pub fn new() -> Result<Self, Error> {
145 match env::var_os("OUT_DIR") {
146 Some(d) => Self::with_dir(d),
147 None => Err(error::from_str("no OUT_DIR specified!")),
148 }
149 }
150
151 /// Creates a new `AutoCfg` instance with the specified output directory.
152 ///
153 /// # Common errors
154 ///
155 /// - `rustc` can't be executed, from `RUSTC` or in the `PATH`.
156 /// - The version output from `rustc` can't be parsed.
157 /// - `dir` is not a writable directory.
158 ///
159 pub fn with_dir<T: Into<PathBuf>>(dir: T) -> Result<Self, Error> {
160 let rustc = Rustc::new();
161 let rustc_version = try!(rustc.version());
162
163 let target = env::var_os("TARGET");
164
165 // Sanity check the output directory
166 let dir = dir.into();
167 let meta = try!(fs::metadata(&dir).map_err(error::from_io));
168 if !meta.is_dir() || meta.permissions().readonly() {
169 return Err(error::from_str("output path is not a writable directory"));
170 }
171
172 let mut ac = AutoCfg {
173 rustflags: rustflags(&target, &dir),
174 out_dir: dir,
175 rustc: rustc,
176 rustc_version: rustc_version,
177 target: target,
178 no_std: false,
179 };
180
181 // Sanity check with and without `std`.
182 if !ac.probe_raw("").is_ok() {
183 if ac.probe_raw("#![no_std]").is_ok() {
184 ac.no_std = true;
185 } else {
186 // Neither worked, so assume nothing...
187 let warning = b"warning: autocfg could not probe for `std`\n";
188 stderr().write_all(warning).ok();
189 }
190 }
191 Ok(ac)
192 }
193
194 /// Returns whether `AutoCfg` is using `#![no_std]` in its probes.
195 ///
196 /// This is automatically detected during construction -- if an empty probe
197 /// fails while one with `#![no_std]` succeeds, then the attribute will be
198 /// used for all further probes. This is usually only necessary when the
199 /// `TARGET` lacks `std` altogether. If neither succeeds, `no_std` is not
200 /// set, but that `AutoCfg` will probably only work for version checks.
201 ///
202 /// This attribute changes the implicit [prelude] from `std` to `core`,
203 /// which may affect the paths you need to use in other probes. It also
204 /// restricts some types that otherwise get additional methods in `std`,
205 /// like floating-point trigonometry and slice sorting.
206 ///
207 /// See also [`set_no_std`](#method.set_no_std).
208 ///
209 /// [prelude]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute
210 pub fn no_std(&self) -> bool {
211 self.no_std
212 }
213
214 /// Sets whether `AutoCfg` should use `#![no_std]` in its probes.
215 ///
216 /// See also [`no_std`](#method.no_std).
217 pub fn set_no_std(&mut self, no_std: bool) {
218 self.no_std = no_std;
219 }
220
221 /// Tests whether the current `rustc` reports a version greater than
222 /// or equal to "`major`.`minor`".
223 pub fn probe_rustc_version(&self, major: usize, minor: usize) -> bool {
224 self.rustc_version >= Version::new(major, minor, 0)
225 }
226
227 /// Sets a `cfg` value of the form `rustc_major_minor`, like `rustc_1_29`,
228 /// if the current `rustc` is at least that version.
229 pub fn emit_rustc_version(&self, major: usize, minor: usize) {
230 if self.probe_rustc_version(major, minor) {
231 emit(&format!("rustc_{}_{}", major, minor));
232 }
233 }
234
235 fn probe_fmt<'a>(&self, source: Arguments<'a>) -> Result<(), Error> {
236 #[allow(deprecated)]
237 static ID: AtomicUsize = ATOMIC_USIZE_INIT;
238
239 let id = ID.fetch_add(1, Ordering::Relaxed);
240
241 let mut command = self.rustc.command();
242 command
243 .arg("--crate-name")
244 .arg(format!("probe{}", id))
245 .arg("--crate-type=lib")
246 .arg("--out-dir")
247 .arg(&self.out_dir)
248 .arg("--emit=llvm-ir");
249
250 if let Some(target) = self.target.as_ref() {
251 command.arg("--target").arg(target);
252 }
253
254 command.args(&self.rustflags);
255
256 command.arg("-").stdin(Stdio::piped());
257 let mut child = try!(command.spawn().map_err(error::from_io));
258 let mut stdin = child.stdin.take().expect("rustc stdin");
259
260 try!(stdin.write_fmt(source).map_err(error::from_io));
261 drop(stdin);
262
263 match child.wait() {
264 Ok(status) if status.success() => Ok(()),
265 Ok(status) => Err(error::from_exit(status)),
266 Err(error) => Err(error::from_io(error)),
267 }
268 }
269
270 fn probe<'a>(&self, code: Arguments<'a>) -> bool {
271 let result = if self.no_std {
272 self.probe_fmt(format_args!("#![no_std]\n{}", code))
273 } else {
274 self.probe_fmt(code)
275 };
276 result.is_ok()
277 }
278
279 /// Tests whether the given code can be compiled as a Rust library.
280 ///
281 /// This will only return `Ok` if the compiler ran and exited successfully,
282 /// per `ExitStatus::success()`.
283 /// The code is passed to the compiler exactly as-is, notably not even
284 /// adding the [`#![no_std]`][Self::no_std] attribute like other probes.
285 ///
286 /// Raw probes are useful for testing functionality that's not yet covered
287 /// by the rest of the `AutoCfg` API. For example, the following attribute
288 /// **must** be used at the crate level, so it wouldn't work within the code
289 /// templates used by other `probe_*` methods.
290 ///
291 /// ```
292 /// # extern crate autocfg;
293 /// # // Normally, cargo will set `OUT_DIR` for build scripts.
294 /// # std::env::set_var("OUT_DIR", "target");
295 /// let ac = autocfg::new();
296 /// assert!(ac.probe_raw("#![no_builtins]").is_ok());
297 /// ```
298 ///
299 /// Rust nightly features could be tested as well -- ideally including a
300 /// code sample to ensure the unstable feature still works as expected.
301 /// For example, `slice::group_by` was renamed to `chunk_by` when it was
302 /// stabilized, even though the feature name was unchanged, so testing the
303 /// `#![feature(..)]` alone wouldn't reveal that. For larger snippets,
304 /// [`include_str!`] may be useful to load them from separate files.
305 ///
306 /// ```
307 /// # extern crate autocfg;
308 /// # // Normally, cargo will set `OUT_DIR` for build scripts.
309 /// # std::env::set_var("OUT_DIR", "target");
310 /// let ac = autocfg::new();
311 /// let code = r#"
312 /// #![feature(slice_group_by)]
313 /// pub fn probe(slice: &[i32]) -> impl Iterator<Item = &[i32]> {
314 /// slice.group_by(|a, b| a == b)
315 /// }
316 /// "#;
317 /// if ac.probe_raw(code).is_ok() {
318 /// autocfg::emit("has_slice_group_by");
319 /// }
320 /// ```
321 pub fn probe_raw(&self, code: &str) -> Result<(), Error> {
322 self.probe_fmt(format_args!("{}", code))
323 }
324
325 /// Tests whether the given sysroot crate can be used.
326 ///
327 /// The test code is subject to change, but currently looks like:
328 ///
329 /// ```ignore
330 /// extern crate CRATE as probe;
331 /// ```
332 pub fn probe_sysroot_crate(&self, name: &str) -> bool {
333 // Note: `as _` wasn't stabilized until Rust 1.33
334 self.probe(format_args!("extern crate {} as probe;", name))
335 }
336
337 /// Emits a config value `has_CRATE` if `probe_sysroot_crate` returns true.
338 pub fn emit_sysroot_crate(&self, name: &str) {
339 if self.probe_sysroot_crate(name) {
340 emit(&format!("has_{}", mangle(name)));
341 }
342 }
343
344 /// Tests whether the given path can be used.
345 ///
346 /// The test code is subject to change, but currently looks like:
347 ///
348 /// ```ignore
349 /// pub use PATH;
350 /// ```
351 pub fn probe_path(&self, path: &str) -> bool {
352 self.probe(format_args!("pub use {};", path))
353 }
354
355 /// Emits a config value `has_PATH` if `probe_path` returns true.
356 ///
357 /// Any non-identifier characters in the `path` will be replaced with
358 /// `_` in the generated config value.
359 pub fn emit_has_path(&self, path: &str) {
360 if self.probe_path(path) {
361 emit(&format!("has_{}", mangle(path)));
362 }
363 }
364
365 /// Emits the given `cfg` value if `probe_path` returns true.
366 pub fn emit_path_cfg(&self, path: &str, cfg: &str) {
367 if self.probe_path(path) {
368 emit(cfg);
369 }
370 }
371
372 /// Tests whether the given trait can be used.
373 ///
374 /// The test code is subject to change, but currently looks like:
375 ///
376 /// ```ignore
377 /// pub trait Probe: TRAIT + Sized {}
378 /// ```
379 pub fn probe_trait(&self, name: &str) -> bool {
380 self.probe(format_args!("pub trait Probe: {} + Sized {{}}", name))
381 }
382
383 /// Emits a config value `has_TRAIT` if `probe_trait` returns true.
384 ///
385 /// Any non-identifier characters in the trait `name` will be replaced with
386 /// `_` in the generated config value.
387 pub fn emit_has_trait(&self, name: &str) {
388 if self.probe_trait(name) {
389 emit(&format!("has_{}", mangle(name)));
390 }
391 }
392
393 /// Emits the given `cfg` value if `probe_trait` returns true.
394 pub fn emit_trait_cfg(&self, name: &str, cfg: &str) {
395 if self.probe_trait(name) {
396 emit(cfg);
397 }
398 }
399
400 /// Tests whether the given type can be used.
401 ///
402 /// The test code is subject to change, but currently looks like:
403 ///
404 /// ```ignore
405 /// pub type Probe = TYPE;
406 /// ```
407 pub fn probe_type(&self, name: &str) -> bool {
408 self.probe(format_args!("pub type Probe = {};", name))
409 }
410
411 /// Emits a config value `has_TYPE` if `probe_type` returns true.
412 ///
413 /// Any non-identifier characters in the type `name` will be replaced with
414 /// `_` in the generated config value.
415 pub fn emit_has_type(&self, name: &str) {
416 if self.probe_type(name) {
417 emit(&format!("has_{}", mangle(name)));
418 }
419 }
420
421 /// Emits the given `cfg` value if `probe_type` returns true.
422 pub fn emit_type_cfg(&self, name: &str, cfg: &str) {
423 if self.probe_type(name) {
424 emit(cfg);
425 }
426 }
427
428 /// Tests whether the given expression can be used.
429 ///
430 /// The test code is subject to change, but currently looks like:
431 ///
432 /// ```ignore
433 /// pub fn probe() { let _ = EXPR; }
434 /// ```
435 pub fn probe_expression(&self, expr: &str) -> bool {
436 self.probe(format_args!("pub fn probe() {{ let _ = {}; }}", expr))
437 }
438
439 /// Emits the given `cfg` value if `probe_expression` returns true.
440 pub fn emit_expression_cfg(&self, expr: &str, cfg: &str) {
441 if self.probe_expression(expr) {
442 emit(cfg);
443 }
444 }
445
446 /// Tests whether the given constant expression can be used.
447 ///
448 /// The test code is subject to change, but currently looks like:
449 ///
450 /// ```ignore
451 /// pub const PROBE: () = ((), EXPR).0;
452 /// ```
453 pub fn probe_constant(&self, expr: &str) -> bool {
454 self.probe(format_args!("pub const PROBE: () = ((), {}).0;", expr))
455 }
456
457 /// Emits the given `cfg` value if `probe_constant` returns true.
458 pub fn emit_constant_cfg(&self, expr: &str, cfg: &str) {
459 if self.probe_constant(expr) {
460 emit(cfg);
461 }
462 }
463 }
464
465 fn mangle(s: &str) -> String {
466 s.chars()
467 .map(|c| match c {
468 'A'...'Z' | 'a'...'z' | '0'...'9' => c,
469 _ => '_',
470 })
471 .collect()
472 }
473
474 fn dir_contains_target(
475 target: &Option<OsString>,
476 dir: &Path,
477 cargo_target_dir: Option<OsString>,
478 ) -> bool {
479 target
480 .as_ref()
481 .and_then(|target| {
482 dir.to_str().and_then(|dir| {
483 let mut cargo_target_dir = cargo_target_dir
484 .map(PathBuf::from)
485 .unwrap_or_else(|| PathBuf::from("target"));
486 cargo_target_dir.push(target);
487
488 cargo_target_dir
489 .to_str()
490 .map(|cargo_target_dir| dir.contains(cargo_target_dir))
491 })
492 })
493 .unwrap_or(false)
494 }
495
496 fn rustflags(target: &Option<OsString>, dir: &Path) -> Vec<String> {
497 // Starting with rust-lang/cargo#9601, shipped in Rust 1.55, Cargo always sets
498 // CARGO_ENCODED_RUSTFLAGS for any host/target build script invocation. This
499 // includes any source of flags, whether from the environment, toml config, or
500 // whatever may come in the future. The value is either an empty string, or a
501 // list of arguments separated by the ASCII unit separator (US), 0x1f.
502 if let Ok(a) = env::var("CARGO_ENCODED_RUSTFLAGS") {
503 return if a.is_empty() {
504 Vec::new()
505 } else {
506 a.split('\x1f').map(str::to_string).collect()
507 };
508 }
509
510 // Otherwise, we have to take a more heuristic approach, and we don't
511 // support values from toml config at all.
512 //
513 // Cargo only applies RUSTFLAGS for building TARGET artifact in
514 // cross-compilation environment. Sadly, we don't have a way to detect
515 // when we're building HOST artifact in a cross-compilation environment,
516 // so for now we only apply RUSTFLAGS when cross-compiling an artifact.
517 //
518 // See https://github.com/cuviper/autocfg/pull/10#issuecomment-527575030.
519 if *target != env::var_os("HOST")
520 || dir_contains_target(target, dir, env::var_os("CARGO_TARGET_DIR"))
521 {
522 if let Ok(rustflags) = env::var("RUSTFLAGS") {
523 // This is meant to match how cargo handles the RUSTFLAGS environment variable.
524 // See https://github.com/rust-lang/cargo/blob/69aea5b6f69add7c51cca939a79644080c0b0ba0/src/cargo/core/compiler/build_context/target_info.rs#L434-L441
525 return rustflags
526 .split(' ')
527 .map(str::trim)
528 .filter(|s| !s.is_empty())
529 .map(str::to_string)
530 .collect();
531 }
532 }
533
534 Vec::new()
535 }