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::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: Option<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`.
emit(cfg: &str)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.
rerun_path(path: &str)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.
rerun_env(var: &str)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.
new() -> AutoCfg127 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     ///
new() -> Result<Self, Error>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     ///
with_dir<T: Into<PathBuf>>(dir: T) -> Result<Self, Error>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         // Sanity check the output directory
161         let dir = dir.into();
162         let meta = try!(fs::metadata(&dir).map_err(error::from_io));
163         if !meta.is_dir() || meta.permissions().readonly() {
164             return Err(error::from_str("output path is not a writable directory"));
165         }
166 
167         // Cargo only applies RUSTFLAGS for building TARGET artifact in
168         // cross-compilation environment. Sadly, we don't have a way to detect
169         // when we're building HOST artifact in a cross-compilation environment,
170         // so for now we only apply RUSTFLAGS when cross-compiling an artifact.
171         //
172         // See https://github.com/cuviper/autocfg/pull/10#issuecomment-527575030.
173         let rustflags = if env::var_os("TARGET") != env::var_os("HOST") {
174             env::var("RUSTFLAGS").ok().map(|rustflags| {
175                 // This is meant to match how cargo handles the RUSTFLAG environment
176                 // variable.
177                 // See https://github.com/rust-lang/cargo/blob/69aea5b6f69add7c51cca939a79644080c0b0ba0/src/cargo/core/compiler/build_context/target_info.rs#L434-L441
178                 rustflags
179                     .split(' ')
180                     .map(str::trim)
181                     .filter(|s| !s.is_empty())
182                     .map(str::to_string)
183                     .collect::<Vec<String>>()
184             })
185         } else {
186             None
187         };
188 
189         let mut ac = AutoCfg {
190             out_dir: dir,
191             rustc: rustc,
192             rustc_version: rustc_version,
193             target: env::var_os("TARGET"),
194             no_std: false,
195             rustflags: rustflags,
196         };
197 
198         // Sanity check with and without `std`.
199         if !ac.probe("").unwrap_or(false) {
200             ac.no_std = true;
201             if !ac.probe("").unwrap_or(false) {
202                 // Neither worked, so assume nothing...
203                 ac.no_std = false;
204                 let warning = b"warning: autocfg could not probe for `std`\n";
205                 stderr().write_all(warning).ok();
206             }
207         }
208         Ok(ac)
209     }
210 
211     /// Test whether the current `rustc` reports a version greater than
212     /// or equal to "`major`.`minor`".
probe_rustc_version(&self, major: usize, minor: usize) -> bool213     pub fn probe_rustc_version(&self, major: usize, minor: usize) -> bool {
214         self.rustc_version >= Version::new(major, minor, 0)
215     }
216 
217     /// Sets a `cfg` value of the form `rustc_major_minor`, like `rustc_1_29`,
218     /// if the current `rustc` is at least that version.
emit_rustc_version(&self, major: usize, minor: usize)219     pub fn emit_rustc_version(&self, major: usize, minor: usize) {
220         if self.probe_rustc_version(major, minor) {
221             emit(&format!("rustc_{}_{}", major, minor));
222         }
223     }
224 
probe<T: AsRef<[u8]>>(&self, code: T) -> Result<bool, Error>225     fn probe<T: AsRef<[u8]>>(&self, code: T) -> Result<bool, Error> {
226         #[allow(deprecated)]
227         static ID: AtomicUsize = ATOMIC_USIZE_INIT;
228 
229         let id = ID.fetch_add(1, Ordering::Relaxed);
230         let mut command = Command::new(&self.rustc);
231         command
232             .arg("--crate-name")
233             .arg(format!("probe{}", id))
234             .arg("--crate-type=lib")
235             .arg("--out-dir")
236             .arg(&self.out_dir)
237             .arg("--emit=llvm-ir");
238 
239         if let &Some(ref rustflags) = &self.rustflags {
240             command.args(rustflags);
241         }
242 
243         if let Some(target) = self.target.as_ref() {
244             command.arg("--target").arg(target);
245         }
246 
247         command.arg("-").stdin(Stdio::piped());
248         let mut child = try!(command.spawn().map_err(error::from_io));
249         let mut stdin = child.stdin.take().expect("rustc stdin");
250 
251         if self.no_std {
252             try!(stdin.write_all(b"#![no_std]\n").map_err(error::from_io));
253         }
254         try!(stdin.write_all(code.as_ref()).map_err(error::from_io));
255         drop(stdin);
256 
257         let status = try!(child.wait().map_err(error::from_io));
258         Ok(status.success())
259     }
260 
261     /// Tests whether the given sysroot crate can be used.
262     ///
263     /// The test code is subject to change, but currently looks like:
264     ///
265     /// ```ignore
266     /// extern crate CRATE as probe;
267     /// ```
probe_sysroot_crate(&self, name: &str) -> bool268     pub fn probe_sysroot_crate(&self, name: &str) -> bool {
269         self.probe(format!("extern crate {} as probe;", name)) // `as _` wasn't stabilized until Rust 1.33
270             .unwrap_or(false)
271     }
272 
273     /// Emits a config value `has_CRATE` if `probe_sysroot_crate` returns true.
emit_sysroot_crate(&self, name: &str)274     pub fn emit_sysroot_crate(&self, name: &str) {
275         if self.probe_sysroot_crate(name) {
276             emit(&format!("has_{}", mangle(name)));
277         }
278     }
279 
280     /// Tests whether the given path can be used.
281     ///
282     /// The test code is subject to change, but currently looks like:
283     ///
284     /// ```ignore
285     /// pub use PATH;
286     /// ```
probe_path(&self, path: &str) -> bool287     pub fn probe_path(&self, path: &str) -> bool {
288         self.probe(format!("pub use {};", path)).unwrap_or(false)
289     }
290 
291     /// Emits a config value `has_PATH` if `probe_path` returns true.
292     ///
293     /// Any non-identifier characters in the `path` will be replaced with
294     /// `_` in the generated config value.
emit_has_path(&self, path: &str)295     pub fn emit_has_path(&self, path: &str) {
296         if self.probe_path(path) {
297             emit(&format!("has_{}", mangle(path)));
298         }
299     }
300 
301     /// Emits the given `cfg` value if `probe_path` returns true.
emit_path_cfg(&self, path: &str, cfg: &str)302     pub fn emit_path_cfg(&self, path: &str, cfg: &str) {
303         if self.probe_path(path) {
304             emit(cfg);
305         }
306     }
307 
308     /// Tests whether the given trait can be used.
309     ///
310     /// The test code is subject to change, but currently looks like:
311     ///
312     /// ```ignore
313     /// pub trait Probe: TRAIT + Sized {}
314     /// ```
probe_trait(&self, name: &str) -> bool315     pub fn probe_trait(&self, name: &str) -> bool {
316         self.probe(format!("pub trait Probe: {} + Sized {{}}", name))
317             .unwrap_or(false)
318     }
319 
320     /// Emits a config value `has_TRAIT` if `probe_trait` returns true.
321     ///
322     /// Any non-identifier characters in the trait `name` will be replaced with
323     /// `_` in the generated config value.
emit_has_trait(&self, name: &str)324     pub fn emit_has_trait(&self, name: &str) {
325         if self.probe_trait(name) {
326             emit(&format!("has_{}", mangle(name)));
327         }
328     }
329 
330     /// Emits the given `cfg` value if `probe_trait` returns true.
emit_trait_cfg(&self, name: &str, cfg: &str)331     pub fn emit_trait_cfg(&self, name: &str, cfg: &str) {
332         if self.probe_trait(name) {
333             emit(cfg);
334         }
335     }
336 
337     /// Tests whether the given type can be used.
338     ///
339     /// The test code is subject to change, but currently looks like:
340     ///
341     /// ```ignore
342     /// pub type Probe = TYPE;
343     /// ```
probe_type(&self, name: &str) -> bool344     pub fn probe_type(&self, name: &str) -> bool {
345         self.probe(format!("pub type Probe = {};", name))
346             .unwrap_or(false)
347     }
348 
349     /// Emits a config value `has_TYPE` if `probe_type` returns true.
350     ///
351     /// Any non-identifier characters in the type `name` will be replaced with
352     /// `_` in the generated config value.
emit_has_type(&self, name: &str)353     pub fn emit_has_type(&self, name: &str) {
354         if self.probe_type(name) {
355             emit(&format!("has_{}", mangle(name)));
356         }
357     }
358 
359     /// Emits the given `cfg` value if `probe_type` returns true.
emit_type_cfg(&self, name: &str, cfg: &str)360     pub fn emit_type_cfg(&self, name: &str, cfg: &str) {
361         if self.probe_type(name) {
362             emit(cfg);
363         }
364     }
365 
366     /// Tests whether the given expression can be used.
367     ///
368     /// The test code is subject to change, but currently looks like:
369     ///
370     /// ```ignore
371     /// pub fn probe() { let _ = EXPR; }
372     /// ```
probe_expression(&self, expr: &str) -> bool373     pub fn probe_expression(&self, expr: &str) -> bool {
374         self.probe(format!("pub fn probe() {{ let _ = {}; }}", expr))
375             .unwrap_or(false)
376     }
377 
378     /// Emits the given `cfg` value if `probe_expression` returns true.
emit_expression_cfg(&self, expr: &str, cfg: &str)379     pub fn emit_expression_cfg(&self, expr: &str, cfg: &str) {
380         if self.probe_expression(expr) {
381             emit(cfg);
382         }
383     }
384 
385     /// Tests whether the given constant expression can be used.
386     ///
387     /// The test code is subject to change, but currently looks like:
388     ///
389     /// ```ignore
390     /// pub const PROBE: () = ((), EXPR).0;
391     /// ```
probe_constant(&self, expr: &str) -> bool392     pub fn probe_constant(&self, expr: &str) -> bool {
393         self.probe(format!("pub const PROBE: () = ((), {}).0;", expr))
394             .unwrap_or(false)
395     }
396 
397     /// Emits the given `cfg` value if `probe_constant` returns true.
emit_constant_cfg(&self, expr: &str, cfg: &str)398     pub fn emit_constant_cfg(&self, expr: &str, cfg: &str) {
399         if self.probe_constant(expr) {
400             emit(cfg);
401         }
402     }
403 }
404 
mangle(s: &str) -> String405 fn mangle(s: &str) -> String {
406     s.chars()
407         .map(|c| match c {
408             'A'...'Z' | 'a'...'z' | '0'...'9' => c,
409             _ => '_',
410         })
411         .collect()
412 }
413