├── .gitignore ├── ci └── verify-check-cfg │ ├── .gitignore │ ├── Cargo.toml │ ├── src │ └── main.rs │ └── build.rs ├── examples ├── versions.rs ├── integers.rs ├── nightly.rs ├── paths.rs └── traits.rs ├── tests ├── wrap_ignored ├── support │ └── mod.rs ├── no_std.rs ├── rustflags.rs ├── wrappers.rs └── tests.rs ├── Cargo.toml ├── LICENSE-MIT ├── src ├── tests.rs ├── error.rs ├── version.rs ├── rustc.rs └── lib.rs ├── .github └── workflows │ └── ci.yaml ├── README.md └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target 3 | **/*.rs.bk 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /ci/verify-check-cfg/.gitignore: -------------------------------------------------------------------------------- 1 | # Rust 2 | /target 3 | /Cargo.lock 4 | -------------------------------------------------------------------------------- /examples/versions.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | fn main() { 4 | // Normally, cargo will set `OUT_DIR` for build scripts. 5 | let ac = autocfg::AutoCfg::with_dir("target").unwrap(); 6 | for i in 0..100 { 7 | ac.emit_rustc_version(1, i); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /examples/integers.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | fn main() { 4 | // Normally, cargo will set `OUT_DIR` for build scripts. 5 | let ac = autocfg::AutoCfg::with_dir("target").unwrap(); 6 | for i in 3..8 { 7 | ac.emit_has_type(&format!("i{}", 1 << i)); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tests/wrap_ignored: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | for arg in "$@"; do 4 | case "$arg" in 5 | # Add our own version so we can check that the wrapper is used for that. 6 | "--version") echo "release: 12345.6789.0" ;; 7 | # Read all input so the writer doesn't get EPIPE when we exit. 8 | "-") read -d "" PROBE ;; 9 | esac 10 | done 11 | 12 | exit 0 13 | -------------------------------------------------------------------------------- /ci/verify-check-cfg/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | # NOTE: Cannot be in workspace because of rustc 1.0 support 3 | name = "autocfg-verify-check-cfg" 4 | description = "A dummy crate to verify autocfg is emitting check-cfg directives" 5 | version = "0.1.0" 6 | edition = "2015" 7 | # only for testing 8 | publish = false 9 | 10 | build = "build.rs" 11 | 12 | [build-dependencies] 13 | autocfg = { path = "../.." } 14 | 15 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "autocfg" 3 | version = "1.5.0" 4 | authors = ["Josh Stone "] 5 | license = "Apache-2.0 OR MIT" 6 | repository = "https://github.com/cuviper/autocfg" 7 | documentation = "https://docs.rs/autocfg/" 8 | description = "Automatic cfg for Rust compiler features" 9 | readme = "README.md" 10 | keywords = ["rustc", "build", "autoconf"] 11 | categories = ["development-tools::build-utils"] 12 | exclude = ["/.github/**"] 13 | rust-version = "1.0" 14 | 15 | [dependencies] 16 | -------------------------------------------------------------------------------- /examples/nightly.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | fn main() { 4 | // Normally, cargo will set `OUT_DIR` for build scripts. 5 | let ac = autocfg::AutoCfg::with_dir("target").unwrap(); 6 | 7 | // When this feature was stabilized, it also renamed the method to 8 | // `chunk_by`, so it's important to *use* the feature in your probe. 9 | let code = r#" 10 | #![feature(slice_group_by)] 11 | pub fn probe(slice: &[i32]) -> impl Iterator { 12 | slice.group_by(|a, b| a == b) 13 | } 14 | "#; 15 | if ac.probe_raw(code).is_ok() { 16 | autocfg::emit("has_slice_group_by"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tests/support/mod.rs: -------------------------------------------------------------------------------- 1 | use std::borrow::Cow; 2 | use std::env; 3 | use std::path::{Path, PathBuf}; 4 | 5 | /// The directory containing this test binary. 6 | pub fn exe_dir() -> PathBuf { 7 | let exe = env::current_exe().unwrap(); 8 | exe.parent().unwrap().to_path_buf() 9 | } 10 | 11 | /// The directory to use for test probes. 12 | pub fn out_dir() -> Cow<'static, Path> { 13 | if let Some(tmpdir) = option_env!("CARGO_TARGET_TMPDIR") { 14 | Cow::Borrowed(tmpdir.as_ref()) 15 | } else if let Some(tmpdir) = env::var_os("TESTS_TARGET_DIR") { 16 | Cow::Owned(tmpdir.into()) 17 | } else { 18 | // Use the same path as this test binary. 19 | Cow::Owned(exe_dir()) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /examples/paths.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | fn main() { 4 | // Normally, cargo will set `OUT_DIR` for build scripts. 5 | let ac = autocfg::AutoCfg::with_dir("target").unwrap(); 6 | 7 | // since ancient times... 8 | ac.emit_has_path("std::vec::Vec"); 9 | ac.emit_path_cfg("std::vec::Vec", "has_vec"); 10 | 11 | // rustc 1.10.0 12 | ac.emit_has_path("std::panic::PanicInfo"); 13 | ac.emit_path_cfg("std::panic::PanicInfo", "has_panic_info"); 14 | 15 | // rustc 1.20.0 16 | ac.emit_has_path("std::mem::ManuallyDrop"); 17 | ac.emit_path_cfg("std::mem::ManuallyDrop", "has_manually_drop"); 18 | 19 | // rustc 1.25.0 20 | ac.emit_has_path("std::ptr::NonNull"); 21 | ac.emit_path_cfg("std::ptr::NonNull", "has_non_null"); 22 | } 23 | -------------------------------------------------------------------------------- /tests/no_std.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | use std::env; 4 | 5 | mod support; 6 | 7 | /// Tests that we can control the use of `#![no_std]`. 8 | #[test] 9 | fn no_std() { 10 | // Clear the CI `TARGET`, if any, so we're just dealing with the 11 | // host target which always has `std` available. 12 | env::remove_var("TARGET"); 13 | 14 | // Use the same path as this test binary. 15 | let out = support::out_dir(); 16 | 17 | let mut ac = autocfg::AutoCfg::with_dir(out.as_ref()).unwrap(); 18 | assert!(!ac.no_std()); 19 | assert!(ac.probe_path("std::mem")); 20 | 21 | // `#![no_std]` was stabilized in Rust 1.6 22 | if ac.probe_rustc_version(1, 6) { 23 | ac.set_no_std(true); 24 | assert!(ac.no_std()); 25 | assert!(!ac.probe_path("std::mem")); 26 | assert!(ac.probe_path("core::mem")); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /examples/traits.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | fn main() { 4 | // Normally, cargo will set `OUT_DIR` for build scripts. 5 | let ac = autocfg::AutoCfg::with_dir("target").unwrap(); 6 | 7 | // since ancient times... 8 | ac.emit_has_trait("std::ops::Add"); 9 | ac.emit_trait_cfg("std::ops::Add", "has_ops"); 10 | 11 | // trait parameters have to be provided 12 | ac.emit_has_trait("std::borrow::Borrow"); 13 | ac.emit_trait_cfg("std::borrow::Borrow", "has_borrow"); 14 | 15 | // rustc 1.8.0 16 | ac.emit_has_trait("std::ops::AddAssign"); 17 | ac.emit_trait_cfg("std::ops::AddAssign", "has_assign_ops"); 18 | 19 | // rustc 1.12.0 20 | ac.emit_has_trait("std::iter::Sum"); 21 | ac.emit_trait_cfg("std::iter::Sum", "has_sum"); 22 | 23 | // rustc 1.28.0 24 | ac.emit_has_trait("std::alloc::GlobalAlloc"); 25 | ac.emit_trait_cfg("std::alloc::GlobalAlloc", "has_global_alloc"); 26 | } 27 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 Josh Stone 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /ci/verify-check-cfg/src/main.rs: -------------------------------------------------------------------------------- 1 | #![allow(unknown_lints)] 2 | #![deny(unexpected_cfgs)] 3 | 4 | macro_rules! test_cfgs { 5 | ($($cfg:ident,)*) => {$({ 6 | let cfg_desc = format!("cfg!({})", stringify!($cfg)); 7 | if cfg!($cfg) { 8 | println!("Enabled: {}", cfg_desc); 9 | } else { 10 | println!("Disabled: {}", cfg_desc); 11 | } 12 | })*}; 13 | 14 | } 15 | 16 | pub fn main() { 17 | test_cfgs!( 18 | // emit_rustc_version 19 | rustc_1_0, 20 | rustc_7_4294967295, 21 | // emit_has_path, emit_path_cfg 22 | has_std__vec__Vec, 23 | has_path_std_vec, 24 | has_dummy__DummyPath, 25 | has_path_dummy, 26 | // emit_has_trait, emit_trait_cfg 27 | has_std__ops__Add, 28 | has_trait_add, 29 | has_dummy__DummyTrait, 30 | has_trait_dummy, 31 | // emit_has_type, has_type_i32 32 | has_i32, 33 | has_type_i32, 34 | has_i7billion, 35 | has_type_i7billion, 36 | // emit_expression_cfg 37 | has_working_addition, 38 | has_working_5xor, 39 | // emit_constant_cfg 40 | has_const_7, 41 | has_const_file_open, 42 | ); 43 | } 44 | -------------------------------------------------------------------------------- /tests/rustflags.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | use std::env; 4 | 5 | mod support; 6 | 7 | /// Tests that autocfg uses the RUSTFLAGS or CARGO_ENCODED_RUSTFLAGS 8 | /// environment variables when running rustc. 9 | #[test] 10 | fn test_with_sysroot() { 11 | let dir = support::exe_dir(); 12 | let out = support::out_dir(); 13 | 14 | // If we have encoded rustflags, they take precedence, even if empty. 15 | env::set_var("CARGO_ENCODED_RUSTFLAGS", ""); 16 | env::set_var("RUSTFLAGS", &format!("-L {}", dir.display())); 17 | let ac = autocfg::AutoCfg::with_dir(out.as_ref()).unwrap(); 18 | assert!(ac.probe_sysroot_crate("std")); 19 | assert!(!ac.probe_sysroot_crate("autocfg")); 20 | 21 | // Now try again with useful encoded args. 22 | env::set_var( 23 | "CARGO_ENCODED_RUSTFLAGS", 24 | &format!("-L\x1f{}", dir.display()), 25 | ); 26 | let ac = autocfg::AutoCfg::with_dir(out.as_ref()).unwrap(); 27 | assert!(ac.probe_sysroot_crate("autocfg")); 28 | 29 | // Try the old-style RUSTFLAGS, ensuring HOST != TARGET. 30 | env::remove_var("CARGO_ENCODED_RUSTFLAGS"); 31 | env::set_var("HOST", "lol"); 32 | let ac = autocfg::AutoCfg::with_dir(out.as_ref()).unwrap(); 33 | assert!(ac.probe_sysroot_crate("autocfg")); 34 | } 35 | -------------------------------------------------------------------------------- /ci/verify-check-cfg/build.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | pub fn main() { 4 | let cfg = autocfg::AutoCfg::new().unwrap(); 5 | 6 | // 7 | // tests 8 | // 9 | 10 | // always true 11 | cfg.emit_rustc_version(1, 0); 12 | // should always be false 13 | cfg.emit_rustc_version(7, std::u32::MAX as usize); 14 | 15 | // always true 16 | cfg.emit_has_path("std::vec::Vec"); 17 | cfg.emit_path_cfg("std::vec::Vec", "has_path_std_vec"); 18 | // always false 19 | cfg.emit_has_path("dummy::DummyPath"); 20 | cfg.emit_path_cfg("dummy::DummyPath", "has_path_dummy"); 21 | 22 | // always true 23 | cfg.emit_has_trait("std::ops::Add"); 24 | cfg.emit_trait_cfg("std::ops::Add", "has_trait_add"); 25 | // always false 26 | cfg.emit_has_trait("dummy::DummyTrait"); 27 | cfg.emit_trait_cfg("dummy::DummyTrait", "has_trait_dummy"); 28 | 29 | // always true 30 | cfg.emit_has_type("i32"); 31 | cfg.emit_type_cfg("i32", "has_type_i32"); 32 | // always false 33 | cfg.emit_has_type("i7billion"); 34 | cfg.emit_type_cfg("i7billion", "has_type_i7billion"); 35 | 36 | // always true 37 | cfg.emit_expression_cfg("3 + 7", "has_working_addition"); 38 | // always false 39 | cfg.emit_expression_cfg("3 ^^^^^ 12", "has_working_5xor"); 40 | 41 | // always true 42 | cfg.emit_constant_cfg("7", "has_const_7"); 43 | // false - Opening file should never be `const` 44 | cfg.emit_constant_cfg("std::fs::File::open(\"foo.txt\")", "has_const_file_open"); 45 | } 46 | -------------------------------------------------------------------------------- /src/tests.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | 3 | #[test] 4 | fn version_cmp() { 5 | use super::version::Version; 6 | let v123 = Version::new(1, 2, 3); 7 | 8 | assert!(Version::new(1, 0, 0) < v123); 9 | assert!(Version::new(1, 2, 2) < v123); 10 | assert!(Version::new(1, 2, 3) == v123); 11 | assert!(Version::new(1, 2, 4) > v123); 12 | assert!(Version::new(1, 10, 0) > v123); 13 | assert!(Version::new(2, 0, 0) > v123); 14 | } 15 | 16 | #[test] 17 | fn dir_does_not_contain_target() { 18 | assert!(!super::dir_contains_target( 19 | &Some("x86_64-unknown-linux-gnu".into()), 20 | Path::new("/project/target/debug/build/project-ea75983148559682/out"), 21 | None, 22 | )); 23 | } 24 | 25 | #[test] 26 | fn dir_does_contain_target() { 27 | assert!(super::dir_contains_target( 28 | &Some("x86_64-unknown-linux-gnu".into()), 29 | Path::new( 30 | "/project/target/x86_64-unknown-linux-gnu/debug/build/project-0147aca016480b9d/out" 31 | ), 32 | None, 33 | )); 34 | } 35 | 36 | #[test] 37 | fn dir_does_not_contain_target_with_custom_target_dir() { 38 | assert!(!super::dir_contains_target( 39 | &Some("x86_64-unknown-linux-gnu".into()), 40 | Path::new("/project/custom/debug/build/project-ea75983148559682/out"), 41 | Some("custom".into()), 42 | )); 43 | } 44 | 45 | #[test] 46 | fn dir_does_contain_target_with_custom_target_dir() { 47 | assert!(super::dir_contains_target( 48 | &Some("x86_64-unknown-linux-gnu".into()), 49 | Path::new( 50 | "/project/custom/x86_64-unknown-linux-gnu/debug/build/project-0147aca016480b9d/out" 51 | ), 52 | Some("custom".into()), 53 | )); 54 | } 55 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use std::error; 2 | use std::fmt; 3 | use std::io; 4 | use std::num; 5 | use std::process; 6 | use std::str; 7 | 8 | /// A common error type for the `autocfg` crate. 9 | #[derive(Debug)] 10 | pub struct Error { 11 | kind: ErrorKind, 12 | } 13 | 14 | impl error::Error for Error { 15 | fn description(&self) -> &str { 16 | "AutoCfg error" 17 | } 18 | 19 | fn cause(&self) -> Option<&error::Error> { 20 | match self.kind { 21 | ErrorKind::Io(ref e) => Some(e), 22 | ErrorKind::Num(ref e) => Some(e), 23 | ErrorKind::Utf8(ref e) => Some(e), 24 | ErrorKind::Process(_) | ErrorKind::Other(_) => None, 25 | } 26 | } 27 | } 28 | 29 | impl fmt::Display for Error { 30 | fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { 31 | match self.kind { 32 | ErrorKind::Io(ref e) => e.fmt(f), 33 | ErrorKind::Num(ref e) => e.fmt(f), 34 | ErrorKind::Utf8(ref e) => e.fmt(f), 35 | ErrorKind::Process(ref status) => { 36 | // Same message as the newer `ExitStatusError` 37 | write!(f, "process exited unsuccessfully: {}", status) 38 | } 39 | ErrorKind::Other(s) => s.fmt(f), 40 | } 41 | } 42 | } 43 | 44 | #[derive(Debug)] 45 | enum ErrorKind { 46 | Io(io::Error), 47 | Num(num::ParseIntError), 48 | Process(process::ExitStatus), 49 | Utf8(str::Utf8Error), 50 | Other(&'static str), 51 | } 52 | 53 | pub fn from_exit(status: process::ExitStatus) -> Error { 54 | Error { 55 | kind: ErrorKind::Process(status), 56 | } 57 | } 58 | 59 | pub fn from_io(e: io::Error) -> Error { 60 | Error { 61 | kind: ErrorKind::Io(e), 62 | } 63 | } 64 | 65 | pub fn from_num(e: num::ParseIntError) -> Error { 66 | Error { 67 | kind: ErrorKind::Num(e), 68 | } 69 | } 70 | 71 | pub fn from_utf8(e: str::Utf8Error) -> Error { 72 | Error { 73 | kind: ErrorKind::Utf8(e), 74 | } 75 | } 76 | 77 | pub fn from_str(s: &'static str) -> Error { 78 | Error { 79 | kind: ErrorKind::Other(s), 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /tests/wrappers.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | use std::env; 4 | 5 | mod support; 6 | 7 | /// Tests that autocfg uses the RUSTC_WRAPPER and/or RUSTC_WORKSPACE_WRAPPER 8 | /// environment variables when running rustc. 9 | #[test] 10 | #[cfg(unix)] // we're using system binaries as wrappers 11 | fn test_wrappers() { 12 | fn set(name: &str, value: Option) { 13 | match value { 14 | Some(true) => env::set_var(name, "/usr/bin/env"), 15 | Some(false) => env::set_var(name, "/bin/false"), 16 | None => env::remove_var(name), 17 | } 18 | } 19 | 20 | let out = support::out_dir(); 21 | 22 | // This is used as a heuristic to detect rust-lang/cargo#9601. 23 | env::set_var("CARGO_ENCODED_RUSTFLAGS", ""); 24 | 25 | // No wrapper, a good pass-through wrapper, and a bad wrapper. 26 | let variants = [None, Some(true), Some(false)]; 27 | 28 | for &workspace in &variants { 29 | for &rustc in &variants { 30 | set("RUSTC_WRAPPER", rustc); 31 | set("RUSTC_WORKSPACE_WRAPPER", workspace); 32 | 33 | let ac = autocfg::AutoCfg::with_dir(out.as_ref()).unwrap(); 34 | if rustc == Some(false) || workspace == Some(false) { 35 | // Everything should fail with bad wrappers. 36 | assert!(!ac.probe_type("usize")); 37 | } else { 38 | // Try known good and bad types for the wrapped rustc. 39 | assert!(ac.probe_type("usize")); 40 | assert!(!ac.probe_type("mesize")); 41 | } 42 | // Either way, we should have found the inner rustc version. 43 | assert!(ac.probe_rustc_version(1, 0)); 44 | } 45 | } 46 | 47 | // Finally, make sure that `RUSTC_WRAPPER` is applied outermost 48 | // by using something that doesn't pass through at all. 49 | env::set_var("RUSTC_WRAPPER", "./tests/wrap_ignored"); 50 | env::set_var("RUSTC_WORKSPACE_WRAPPER", "/bin/false"); 51 | let ac = autocfg::AutoCfg::with_dir(out.as_ref()).unwrap(); 52 | assert!(ac.probe_type("mesize")); // anything goes! 53 | 54 | // Make sure we also got the version from that wrapper. 55 | assert!(ac.probe_rustc_version(12345, 6789)); 56 | } 57 | -------------------------------------------------------------------------------- /src/version.rs: -------------------------------------------------------------------------------- 1 | use std::process::Command; 2 | use std::str; 3 | 4 | use super::{error, Error}; 5 | 6 | /// A version structure for making relative comparisons. 7 | #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] 8 | pub struct Version { 9 | major: usize, 10 | minor: usize, 11 | patch: usize, 12 | } 13 | 14 | impl Version { 15 | /// Creates a `Version` instance for a specific `major.minor.patch` version. 16 | pub fn new(major: usize, minor: usize, patch: usize) -> Self { 17 | Version { 18 | major: major, 19 | minor: minor, 20 | patch: patch, 21 | } 22 | } 23 | 24 | pub fn from_command(command: &mut Command) -> Result { 25 | // Get rustc's verbose version 26 | let output = try!(command 27 | .args(&["--version", "--verbose"]) 28 | .output() 29 | .map_err(error::from_io)); 30 | if !output.status.success() { 31 | return Err(error::from_str("could not execute rustc")); 32 | } 33 | let output = try!(str::from_utf8(&output.stdout).map_err(error::from_utf8)); 34 | 35 | // Find the release line in the verbose version output. 36 | let release = match output.lines().find(|line| line.starts_with("release: ")) { 37 | Some(line) => &line["release: ".len()..], 38 | None => return Err(error::from_str("could not find rustc release")), 39 | }; 40 | 41 | // Strip off any extra channel info, e.g. "-beta.N", "-nightly" 42 | let version = match release.find('-') { 43 | Some(i) => &release[..i], 44 | None => release, 45 | }; 46 | 47 | // Split the version into semver components. 48 | let mut iter = version.splitn(3, '.'); 49 | let major = try!(iter 50 | .next() 51 | .ok_or_else(|| error::from_str("missing major version"))); 52 | let minor = try!(iter 53 | .next() 54 | .ok_or_else(|| error::from_str("missing minor version"))); 55 | let patch = try!(iter 56 | .next() 57 | .ok_or_else(|| error::from_str("missing patch version"))); 58 | 59 | Ok(Version::new( 60 | try!(major.parse().map_err(error::from_num)), 61 | try!(minor.parse().map_err(error::from_num)), 62 | try!(patch.parse().map_err(error::from_num)), 63 | )) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | 10 | test: 11 | name: Test 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | rust: [1.0.0, 1.5.0, 1.10.0, 1.15.0, 1.20.0, 1.25.0, 1.30.0, 1.35.0, 16 | 1.40.0, 1.45.0, 1.50.0, 1.55.0, 1.60.0, 1.65.0, 1.70.0, 1.75.0, 17 | 1.80.0, # first version with rustc-check-cfg 18 | 1.85.0, stable, beta, nightly] 19 | steps: 20 | - uses: actions/checkout@v4 21 | - uses: dtolnay/rust-toolchain@master 22 | with: 23 | toolchain: ${{ matrix.rust }} 24 | - run: cargo build --verbose 25 | - run: cargo test --verbose 26 | - run: cargo run 27 | working-directory: ./ci/verify-check-cfg 28 | 29 | # try probing a target that doesn't have std at all 30 | no_std: 31 | name: No Std 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v4 35 | - uses: dtolnay/rust-toolchain@stable 36 | with: 37 | target: thumbv6m-none-eabi 38 | - run: cargo test --verbose --lib 39 | env: 40 | TARGET: thumbv6m-none-eabi 41 | 42 | # we don't even need an installed target for version checks 43 | missing_target: 44 | name: Missing Target 45 | runs-on: ubuntu-latest 46 | steps: 47 | - uses: actions/checkout@v4 48 | - uses: dtolnay/rust-toolchain@stable 49 | - run: cargo test --verbose --lib -- version 50 | env: 51 | TARGET: thumbv6m-none-eabi 52 | 53 | fmt: 54 | name: Format 55 | runs-on: ubuntu-latest 56 | steps: 57 | - uses: actions/checkout@v4 58 | - uses: dtolnay/rust-toolchain@1.87.0 59 | with: 60 | components: rustfmt 61 | - run: cargo fmt --all --check 62 | 63 | # One job that "summarizes" the success state of this pipeline. This can then be added to branch 64 | # protection, rather than having to add each job separately. 65 | success: 66 | name: Success 67 | runs-on: ubuntu-latest 68 | needs: [test, no_std, missing_target, fmt] 69 | # Github branch protection is exceedingly silly and treats "jobs skipped because a dependency 70 | # failed" as success. So we have to do some contortions to ensure the job fails if any of its 71 | # dependencies fails. 72 | if: always() # make sure this is never "skipped" 73 | steps: 74 | # Manually check the status of all dependencies. `if: failure()` does not work. 75 | - name: check if any dependency failed 76 | run: jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}' 77 | -------------------------------------------------------------------------------- /src/rustc.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::ffi::OsString; 3 | use std::path::PathBuf; 4 | use std::process::Command; 5 | 6 | use super::error::Error; 7 | use super::version::Version; 8 | 9 | #[derive(Clone, Debug)] 10 | pub struct Rustc { 11 | rustc: PathBuf, 12 | rustc_wrapper: Option, 13 | rustc_workspace_wrapper: Option, 14 | } 15 | 16 | impl Rustc { 17 | pub fn new() -> Self { 18 | Rustc { 19 | rustc: env::var_os("RUSTC") 20 | .unwrap_or_else(|| "rustc".into()) 21 | .into(), 22 | rustc_wrapper: get_rustc_wrapper(false), 23 | rustc_workspace_wrapper: get_rustc_wrapper(true), 24 | } 25 | } 26 | 27 | /// Build the command with possible wrappers. 28 | pub fn command(&self) -> Command { 29 | let mut rustc = self 30 | .rustc_wrapper 31 | .iter() 32 | .chain(self.rustc_workspace_wrapper.iter()) 33 | .chain(Some(&self.rustc)); 34 | let mut command = Command::new(rustc.next().unwrap()); 35 | for arg in rustc { 36 | command.arg(arg); 37 | } 38 | command 39 | } 40 | 41 | /// Try to get the `rustc` version. 42 | pub fn version(&self) -> Result { 43 | // Some wrappers like clippy-driver don't pass through version commands, 44 | // so we try to fall back to combinations without each wrapper. 45 | macro_rules! try_version { 46 | ($command:expr) => { 47 | if let Ok(value) = Version::from_command($command) { 48 | return Ok(value); 49 | } 50 | }; 51 | } 52 | 53 | let rustc = &self.rustc; 54 | if let Some(ref rw) = self.rustc_wrapper { 55 | if let Some(ref rww) = self.rustc_workspace_wrapper { 56 | try_version!(Command::new(rw).args(&[rww, rustc])); 57 | } 58 | try_version!(Command::new(rw).arg(rustc)); 59 | } 60 | if let Some(ref rww) = self.rustc_workspace_wrapper { 61 | try_version!(Command::new(rww).arg(rustc)); 62 | } 63 | Version::from_command(&mut Command::new(rustc)) 64 | } 65 | } 66 | 67 | fn get_rustc_wrapper(workspace: bool) -> Option { 68 | // We didn't really know whether the workspace wrapper is applicable until Cargo started 69 | // deliberately setting or unsetting it in rust-lang/cargo#9601. We'll use the encoded 70 | // rustflags as a proxy for that change for now, but we could instead check version 1.55. 71 | if workspace && env::var_os("CARGO_ENCODED_RUSTFLAGS").is_none() { 72 | return None; 73 | } 74 | 75 | let name = if workspace { 76 | "RUSTC_WORKSPACE_WRAPPER" 77 | } else { 78 | "RUSTC_WRAPPER" 79 | }; 80 | 81 | if let Some(wrapper) = env::var_os(name) { 82 | // NB: `OsStr` didn't get `len` or `is_empty` until 1.9. 83 | if wrapper != OsString::new() { 84 | return Some(wrapper.into()); 85 | } 86 | } 87 | 88 | None 89 | } 90 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | autocfg 2 | ======= 3 | 4 | [![autocfg crate](https://img.shields.io/crates/v/autocfg.svg)](https://crates.io/crates/autocfg) 5 | [![autocfg documentation](https://docs.rs/autocfg/badge.svg)](https://docs.rs/autocfg) 6 | ![minimum rustc 1.0](https://img.shields.io/badge/rustc-1.0+-red.svg) 7 | ![build status](https://github.com/cuviper/autocfg/workflows/CI/badge.svg) 8 | 9 | A Rust library for build scripts to automatically configure code based on 10 | compiler support. Code snippets are dynamically tested to see if the `rustc` 11 | will accept them, rather than hard-coding specific version support. 12 | 13 | 14 | ## Usage 15 | 16 | Add this to your `Cargo.toml`: 17 | 18 | ```toml 19 | [build-dependencies] 20 | autocfg = "1" 21 | ``` 22 | 23 | Then use it in your `build.rs` script to detect compiler features. For 24 | example, to test for 128-bit integer support, it might look like: 25 | 26 | ```rust 27 | extern crate autocfg; 28 | 29 | fn main() { 30 | let ac = autocfg::new(); 31 | ac.emit_has_type("i128"); 32 | 33 | // (optional) We don't need to rerun for anything external. 34 | autocfg::rerun_path("build.rs"); 35 | } 36 | ``` 37 | 38 | If the type test succeeds, this will write a `cargo:rustc-cfg=has_i128` line 39 | for Cargo, which translates to Rust arguments `--cfg has_i128`. Then in the 40 | rest of your Rust code, you can add `#[cfg(has_i128)]` conditions on code that 41 | should only be used when the compiler supports it. 42 | 43 | 44 | ## Release Notes 45 | 46 | - 1.5.0 (2025-06-17) 47 | 48 | - Add `edition` and `set_edition` to control the Rust edition used in probes. 49 | - Remove probe result files so they don't pollute the output directory. 50 | 51 | - 1.4.0 (2024-09-26) 52 | 53 | - Add `emit_possibility` for Rust 1.80's [checked cfgs], and call that 54 | automatically for methods that conditionally `emit`, by @Techcable. 55 | 56 | [checked cfgs]: https://blog.rust-lang.org/2024/05/06/check-cfg.html 57 | 58 | - 1.3.0 (2024-05-03) 59 | 60 | - Add `probe_raw` for direct control of the code that will be test-compiled. 61 | - Use wrappers when querying the `rustc` version information too. 62 | 63 | - 1.2.0 (2024-03-25) 64 | 65 | - Add `no_std` and `set_no_std` to control the use of `#![no_std]` in probes. 66 | - Use `RUSTC_WRAPPER` and `RUSTC_WORKSPACE_WRAPPER` when they are set. 67 | 68 | - 1.1.0 (2022-02-07) 69 | - Use `CARGO_ENCODED_RUSTFLAGS` when it is set. 70 | 71 | - 1.0.1 (2020-08-20) 72 | - Apply `RUSTFLAGS` for more `--target` scenarios, by @adamreichold. 73 | 74 | - 1.0.0 (2020-01-08) 75 | - 🎉 Release 1.0! 🎉 (no breaking changes) 76 | - Add `probe_expression` and `emit_expression_cfg` to test arbitrary expressions. 77 | - Add `probe_constant` and `emit_constant_cfg` to test arbitrary constant expressions. 78 | 79 | - 0.1.7 (2019-10-20) 80 | - Apply `RUSTFLAGS` when probing `$TARGET != $HOST`, mainly for sysroot, by @roblabla. 81 | 82 | - 0.1.6 (2019-08-19) 83 | - Add `probe`/`emit_sysroot_crate`, by @leo60228. 84 | 85 | - 0.1.5 (2019-07-16) 86 | - Mask some warnings from newer rustc. 87 | 88 | - 0.1.4 (2019-05-22) 89 | - Relax `std`/`no_std` probing to a warning instead of an error. 90 | - Improve `rustc` bootstrap compatibility. 91 | 92 | - 0.1.3 (2019-05-21) 93 | - Auto-detects if `#![no_std]` is needed for the `$TARGET`. 94 | 95 | - 0.1.2 (2019-01-16) 96 | - Add `rerun_env(ENV)` to print `cargo:rerun-if-env-changed=ENV`. 97 | - Add `rerun_path(PATH)` to print `cargo:rerun-if-changed=PATH`. 98 | 99 | 100 | ## Minimum Rust version policy 101 | 102 | This crate's minimum supported `rustc` version is `1.0.0`. Compatibility is 103 | its entire reason for existence, so this crate will be extremely conservative 104 | about raising this requirement. If this is ever deemed necessary, it will be 105 | treated as a major breaking change for semver purposes. 106 | 107 | 108 | ## License 109 | 110 | This project is licensed under either of 111 | 112 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or 113 | https://www.apache.org/licenses/LICENSE-2.0) 114 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or 115 | https://opensource.org/licenses/MIT) 116 | 117 | at your option. 118 | -------------------------------------------------------------------------------- /tests/tests.rs: -------------------------------------------------------------------------------- 1 | extern crate autocfg; 2 | 3 | use autocfg::AutoCfg; 4 | 5 | mod support; 6 | 7 | fn core_std(ac: &AutoCfg, path: &str) -> String { 8 | let krate = if ac.no_std() { "core" } else { "std" }; 9 | format!("{}::{}", krate, path) 10 | } 11 | 12 | fn assert_std(ac: &AutoCfg, probe_result: bool) { 13 | assert_eq!(!ac.no_std(), probe_result); 14 | } 15 | 16 | fn assert_min(ac: &AutoCfg, major: usize, minor: usize, probe_result: bool) { 17 | assert_eq!(ac.probe_rustc_version(major, minor), probe_result); 18 | } 19 | 20 | fn autocfg_for_test() -> AutoCfg { 21 | AutoCfg::with_dir(support::out_dir().as_ref()).unwrap() 22 | } 23 | 24 | #[test] 25 | fn autocfg_version() { 26 | let ac = autocfg_for_test(); 27 | assert!(ac.probe_rustc_version(1, 0)); 28 | } 29 | 30 | #[test] 31 | fn probe_add() { 32 | let ac = autocfg_for_test(); 33 | let add = core_std(&ac, "ops::Add"); 34 | let add_rhs = add.clone() + ""; 35 | let add_rhs_output = add.clone() + ""; 36 | let dyn_add_rhs_output = "dyn ".to_string() + &*add_rhs_output; 37 | assert!(ac.probe_path(&add)); 38 | assert!(ac.probe_trait(&add)); 39 | assert!(ac.probe_trait(&add_rhs)); 40 | assert!(ac.probe_trait(&add_rhs_output)); 41 | assert_min(&ac, 1, 27, ac.probe_type(&dyn_add_rhs_output)); 42 | } 43 | 44 | #[test] 45 | fn probe_as_ref() { 46 | let ac = autocfg_for_test(); 47 | let as_ref = core_std(&ac, "convert::AsRef"); 48 | let as_ref_str = as_ref.clone() + ""; 49 | let dyn_as_ref_str = "dyn ".to_string() + &*as_ref_str; 50 | assert!(ac.probe_path(&as_ref)); 51 | assert!(ac.probe_trait(&as_ref_str)); 52 | assert!(ac.probe_type(&as_ref_str)); 53 | assert_min(&ac, 1, 27, ac.probe_type(&dyn_as_ref_str)); 54 | } 55 | 56 | #[test] 57 | fn probe_i128() { 58 | let ac = autocfg_for_test(); 59 | let i128_path = core_std(&ac, "i128"); 60 | assert_min(&ac, 1, 26, ac.probe_path(&i128_path)); 61 | assert_min(&ac, 1, 26, ac.probe_type("i128")); 62 | } 63 | 64 | #[test] 65 | fn probe_sum() { 66 | let ac = autocfg_for_test(); 67 | let sum = core_std(&ac, "iter::Sum"); 68 | let sum_i32 = sum.clone() + ""; 69 | let dyn_sum_i32 = "dyn ".to_string() + &*sum_i32; 70 | assert_min(&ac, 1, 12, ac.probe_path(&sum)); 71 | assert_min(&ac, 1, 12, ac.probe_trait(&sum)); 72 | assert_min(&ac, 1, 12, ac.probe_trait(&sum_i32)); 73 | assert_min(&ac, 1, 12, ac.probe_type(&sum_i32)); 74 | assert_min(&ac, 1, 27, ac.probe_type(&dyn_sum_i32)); 75 | } 76 | 77 | #[test] 78 | fn probe_std() { 79 | let ac = autocfg_for_test(); 80 | assert_std(&ac, ac.probe_sysroot_crate("std")); 81 | } 82 | 83 | #[test] 84 | fn probe_alloc() { 85 | let ac = autocfg_for_test(); 86 | assert_min(&ac, 1, 36, ac.probe_sysroot_crate("alloc")); 87 | } 88 | 89 | #[test] 90 | fn probe_bad_sysroot_crate() { 91 | let ac = autocfg_for_test(); 92 | assert!(!ac.probe_sysroot_crate("doesnt_exist")); 93 | } 94 | 95 | #[test] 96 | fn probe_no_std() { 97 | let ac = autocfg_for_test(); 98 | assert!(ac.probe_type("i32")); 99 | assert!(ac.probe_type("[i32]")); 100 | assert_std(&ac, ac.probe_type("Vec")); 101 | } 102 | 103 | #[test] 104 | fn probe_expression() { 105 | let ac = autocfg_for_test(); 106 | assert!(ac.probe_expression(r#""test".trim_left()"#)); 107 | assert_min(&ac, 1, 30, ac.probe_expression(r#""test".trim_start()"#)); 108 | assert_std(&ac, ac.probe_expression("[1, 2, 3].to_vec()")); 109 | } 110 | 111 | #[test] 112 | fn probe_constant() { 113 | let ac = autocfg_for_test(); 114 | assert!(ac.probe_constant("1 + 2 + 3")); 115 | assert_min( 116 | &ac, 117 | 1, 118 | 33, 119 | ac.probe_constant("{ let x = 1 + 2 + 3; x * x }"), 120 | ); 121 | assert_min(&ac, 1, 39, ac.probe_constant(r#""test".len()"#)); 122 | } 123 | 124 | #[test] 125 | fn probe_raw() { 126 | let ac = autocfg_for_test(); 127 | let prefix = if ac.no_std() { "#![no_std]\n" } else { "" }; 128 | let f = |s| format!("{}{}", prefix, s); 129 | 130 | // This attribute **must** be used at the crate level. 131 | assert!(ac.probe_raw(&f("#![no_builtins]")).is_ok()); 132 | 133 | assert!(ac.probe_raw(&f("#![deny(dead_code)] fn x() {}")).is_err()); 134 | assert!(ac.probe_raw(&f("#![allow(dead_code)] fn x() {}")).is_ok()); 135 | assert!(ac 136 | .probe_raw(&f("#![deny(dead_code)] pub fn x() {}")) 137 | .is_ok()); 138 | } 139 | 140 | #[test] 141 | fn probe_cleanup() { 142 | let dir = support::out_dir().join("autocfg_test_probe_cleanup"); 143 | std::fs::create_dir(&dir).unwrap(); 144 | 145 | let ac = AutoCfg::with_dir(&dir).unwrap(); 146 | assert!(ac.probe_type("i32")); 147 | 148 | // NB: this is not `remove_dir_all`, so it will only work if the directory 149 | // is empty -- i.e. the probe should have removed any output files. 150 | std::fs::remove_dir(&dir).unwrap(); 151 | } 152 | 153 | #[test] 154 | fn editions() { 155 | let mut ac = autocfg_for_test(); 156 | assert!(ac.edition().is_none()); 157 | assert!(ac.probe_raw("").is_ok()); 158 | 159 | for (edition, minor) in vec![(2015, 27), (2018, 31), (2021, 56), (2024, 85)] { 160 | let edition = edition.to_string(); 161 | ac.set_edition(Some(edition.clone())); 162 | assert_eq!(ac.edition(), Some(&*edition)); 163 | assert_min(&ac, 1, minor, ac.probe_raw("").is_ok()); 164 | } 165 | 166 | ac.set_edition(Some("invalid".into())); 167 | assert_eq!(ac.edition(), Some("invalid")); 168 | assert!(ac.probe_raw("").is_err()); 169 | 170 | ac.set_edition(None); 171 | assert!(ac.edition().is_none()); 172 | assert!(ac.probe_raw("").is_ok()); 173 | } 174 | 175 | #[test] 176 | fn edition_keyword_try() { 177 | let mut ac = autocfg_for_test(); 178 | 179 | if ac.probe_rustc_version(1, 27) { 180 | ac.set_edition(Some(2015.to_string())); 181 | } 182 | assert!(ac.probe_expression("{ let try = 0; try }")); 183 | 184 | if ac.probe_rustc_version(1, 31) { 185 | ac.set_edition(Some(2018.to_string())); 186 | assert!(!ac.probe_expression("{ let try = 0; try }")); 187 | assert!(ac.probe_expression("{ let r#try = 0; r#try }")); 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 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 | //! # let exe = std::env::current_exe().unwrap(); 24 | //! # std::env::set_var("OUT_DIR", exe.parent().unwrap()); 25 | //! let ac = autocfg::new(); 26 | //! ac.emit_has_type("i128"); 27 | //! 28 | //! // (optional) We don't need to rerun for anything external. 29 | //! autocfg::rerun_path("build.rs"); 30 | //! } 31 | //! ``` 32 | //! 33 | //! If the type test succeeds, this will write a `cargo:rustc-cfg=has_i128` line 34 | //! for Cargo, which translates to Rust arguments `--cfg has_i128`. Then in the 35 | //! rest of your Rust code, you can add `#[cfg(has_i128)]` conditions on code that 36 | //! should only be used when the compiler supports it. 37 | //! 38 | //! ## Caution 39 | //! 40 | //! Many of the probing methods of `AutoCfg` document the particular template they 41 | //! use, **subject to change**. The inputs are not validated to make sure they are 42 | //! semantically correct for their expected use, so it's _possible_ to escape and 43 | //! inject something unintended. However, such abuse is unsupported and will not 44 | //! be considered when making changes to the templates. 45 | 46 | #![deny(missing_debug_implementations)] 47 | #![deny(missing_docs)] 48 | // allow future warnings that can't be fixed while keeping 1.0 compatibility 49 | #![allow(unknown_lints)] 50 | #![allow(bare_trait_objects)] 51 | #![allow(ellipsis_inclusive_range_patterns)] 52 | 53 | /// Local macro to avoid `std::try!`, deprecated in Rust 1.39. 54 | macro_rules! try { 55 | ($result:expr) => { 56 | match $result { 57 | Ok(value) => value, 58 | Err(error) => return Err(error), 59 | } 60 | }; 61 | } 62 | 63 | use std::env; 64 | use std::ffi::OsString; 65 | use std::fmt::Arguments; 66 | use std::fs; 67 | use std::io::{stderr, Write}; 68 | use std::path::{Path, PathBuf}; 69 | use std::process::Stdio; 70 | #[allow(deprecated)] 71 | use std::sync::atomic::ATOMIC_USIZE_INIT; 72 | use std::sync::atomic::{AtomicUsize, Ordering}; 73 | 74 | mod error; 75 | pub use error::Error; 76 | 77 | mod rustc; 78 | use rustc::Rustc; 79 | 80 | mod version; 81 | use version::Version; 82 | 83 | #[cfg(test)] 84 | mod tests; 85 | 86 | /// Helper to detect compiler features for `cfg` output in build scripts. 87 | #[derive(Clone, Debug)] 88 | pub struct AutoCfg { 89 | out_dir: PathBuf, 90 | rustc: Rustc, 91 | rustc_version: Version, 92 | target: Option, 93 | no_std: bool, 94 | edition: Option, 95 | rustflags: Vec, 96 | uuid: u64, 97 | } 98 | 99 | /// Writes a config flag for rustc on standard out. 100 | /// 101 | /// This looks like: `cargo:rustc-cfg=CFG` 102 | /// 103 | /// Cargo will use this in arguments to rustc, like `--cfg CFG`. 104 | /// 105 | /// This does not automatically call [`emit_possibility`] 106 | /// so the compiler my generate an [`unexpected_cfgs` warning][check-cfg-flags]. 107 | /// However, all the builtin emit methods on [`AutoCfg`] call [`emit_possibility`] automatically. 108 | /// 109 | /// [check-cfg-flags]: https://blog.rust-lang.org/2024/05/06/check-cfg.html 110 | pub fn emit(cfg: &str) { 111 | println!("cargo:rustc-cfg={}", cfg); 112 | } 113 | 114 | /// Writes a line telling Cargo to rerun the build script if `path` changes. 115 | /// 116 | /// This looks like: `cargo:rerun-if-changed=PATH` 117 | /// 118 | /// This requires at least cargo 0.7.0, corresponding to rustc 1.6.0. Earlier 119 | /// versions of cargo will simply ignore the directive. 120 | pub fn rerun_path(path: &str) { 121 | println!("cargo:rerun-if-changed={}", path); 122 | } 123 | 124 | /// Writes a line telling Cargo to rerun the build script if the environment 125 | /// variable `var` changes. 126 | /// 127 | /// This looks like: `cargo:rerun-if-env-changed=VAR` 128 | /// 129 | /// This requires at least cargo 0.21.0, corresponding to rustc 1.20.0. Earlier 130 | /// versions of cargo will simply ignore the directive. 131 | pub fn rerun_env(var: &str) { 132 | println!("cargo:rerun-if-env-changed={}", var); 133 | } 134 | 135 | /// Indicates to rustc that a config flag should not generate an [`unexpected_cfgs` warning][check-cfg-flags] 136 | /// 137 | /// This looks like `cargo:rustc-check-cfg=cfg(VAR)` 138 | /// 139 | /// As of rust 1.80, the compiler does [automatic checking of cfgs at compile time][check-cfg-flags]. 140 | /// All custom configuration flags must be known to rustc, or they will generate a warning. 141 | /// This is done automatically when calling the builtin emit methods on [`AutoCfg`], 142 | /// but not when calling [`autocfg::emit`](crate::emit) directly. 143 | /// 144 | /// Versions before rust 1.80 will simply ignore this directive. 145 | /// 146 | /// This function indicates to the compiler that the config flag never has a value. 147 | /// If this is not desired, see [the blog post][check-cfg]. 148 | /// 149 | /// [check-cfg-flags]: https://blog.rust-lang.org/2024/05/06/check-cfg.html 150 | pub fn emit_possibility(cfg: &str) { 151 | println!("cargo:rustc-check-cfg=cfg({})", cfg); 152 | } 153 | 154 | /// Creates a new `AutoCfg` instance. 155 | /// 156 | /// # Panics 157 | /// 158 | /// Panics if `AutoCfg::new()` returns an error. 159 | pub fn new() -> AutoCfg { 160 | AutoCfg::new().unwrap() 161 | } 162 | 163 | impl AutoCfg { 164 | /// Creates a new `AutoCfg` instance. 165 | /// 166 | /// # Common errors 167 | /// 168 | /// - `rustc` can't be executed, from `RUSTC` or in the `PATH`. 169 | /// - The version output from `rustc` can't be parsed. 170 | /// - `OUT_DIR` is not set in the environment, or is not a writable directory. 171 | /// 172 | pub fn new() -> Result { 173 | match env::var_os("OUT_DIR") { 174 | Some(d) => Self::with_dir(d), 175 | None => Err(error::from_str("no OUT_DIR specified!")), 176 | } 177 | } 178 | 179 | /// Creates a new `AutoCfg` instance with the specified output directory. 180 | /// 181 | /// # Common errors 182 | /// 183 | /// - `rustc` can't be executed, from `RUSTC` or in the `PATH`. 184 | /// - The version output from `rustc` can't be parsed. 185 | /// - `dir` is not a writable directory. 186 | /// 187 | pub fn with_dir>(dir: T) -> Result { 188 | let rustc = Rustc::new(); 189 | let rustc_version = try!(rustc.version()); 190 | 191 | let target = env::var_os("TARGET"); 192 | 193 | // Sanity check the output directory 194 | let dir = dir.into(); 195 | let meta = try!(fs::metadata(&dir).map_err(error::from_io)); 196 | if !meta.is_dir() || meta.permissions().readonly() { 197 | return Err(error::from_str("output path is not a writable directory")); 198 | } 199 | 200 | let mut ac = AutoCfg { 201 | rustflags: rustflags(&target, &dir), 202 | out_dir: dir, 203 | rustc: rustc, 204 | rustc_version: rustc_version, 205 | target: target, 206 | no_std: false, 207 | edition: None, 208 | uuid: new_uuid(), 209 | }; 210 | 211 | // Sanity check with and without `std`. 212 | if ac.probe_raw("").is_err() { 213 | if ac.probe_raw("#![no_std]").is_ok() { 214 | ac.no_std = true; 215 | } else { 216 | // Neither worked, so assume nothing... 217 | let warning = b"warning: autocfg could not probe for `std`\n"; 218 | stderr().write_all(warning).ok(); 219 | } 220 | } 221 | Ok(ac) 222 | } 223 | 224 | /// Returns whether `AutoCfg` is using `#![no_std]` in its probes. 225 | /// 226 | /// This is automatically detected during construction -- if an empty probe 227 | /// fails while one with `#![no_std]` succeeds, then the attribute will be 228 | /// used for all further probes. This is usually only necessary when the 229 | /// `TARGET` lacks `std` altogether. If neither succeeds, `no_std` is not 230 | /// set, but that `AutoCfg` will probably only work for version checks. 231 | /// 232 | /// This attribute changes the implicit [prelude] from `std` to `core`, 233 | /// which may affect the paths you need to use in other probes. It also 234 | /// restricts some types that otherwise get additional methods in `std`, 235 | /// like floating-point trigonometry and slice sorting. 236 | /// 237 | /// See also [`set_no_std`](#method.set_no_std). 238 | /// 239 | /// [prelude]: https://doc.rust-lang.org/reference/names/preludes.html#the-no_std-attribute 240 | pub fn no_std(&self) -> bool { 241 | self.no_std 242 | } 243 | 244 | /// Sets whether `AutoCfg` should use `#![no_std]` in its probes. 245 | /// 246 | /// See also [`no_std`](#method.no_std). 247 | pub fn set_no_std(&mut self, no_std: bool) { 248 | self.no_std = no_std; 249 | } 250 | 251 | /// Returns the `--edition` string that is currently being passed to `rustc`, if any, 252 | /// as configured by the [`set_edition`][Self::set_edition] method. 253 | pub fn edition(&self) -> Option<&str> { 254 | match self.edition { 255 | Some(ref edition) => Some(&**edition), 256 | None => None, 257 | } 258 | } 259 | 260 | /// Sets the `--edition` string that will be passed to `rustc`, 261 | /// or `None` to leave the compiler at its default edition. 262 | /// 263 | /// See also [The Rust Edition Guide](https://doc.rust-lang.org/edition-guide/). 264 | /// 265 | /// **Warning:** Setting an unsupported edition will likely cause **all** subsequent probes to 266 | /// fail! As of this writing, the known editions and their minimum Rust versions are: 267 | /// 268 | /// | Edition | Version | 269 | /// | ------- | ---------- | 270 | /// | 2015 | 1.27.0[^1] | 271 | /// | 2018 | 1.31.0 | 272 | /// | 2021 | 1.56.0 | 273 | /// | 2024 | 1.85.0 | 274 | /// 275 | /// [^1]: Prior to 1.27.0, Rust was effectively 2015 Edition by default, but the concept hadn't 276 | /// been established yet, so the explicit `--edition` flag wasn't supported either. 277 | pub fn set_edition(&mut self, edition: Option) { 278 | self.edition = edition; 279 | } 280 | 281 | /// Tests whether the current `rustc` reports a version greater than 282 | /// or equal to "`major`.`minor`". 283 | pub fn probe_rustc_version(&self, major: usize, minor: usize) -> bool { 284 | self.rustc_version >= Version::new(major, minor, 0) 285 | } 286 | 287 | /// Sets a `cfg` value of the form `rustc_major_minor`, like `rustc_1_29`, 288 | /// if the current `rustc` is at least that version. 289 | pub fn emit_rustc_version(&self, major: usize, minor: usize) { 290 | let cfg_flag = format!("rustc_{}_{}", major, minor); 291 | emit_possibility(&cfg_flag); 292 | if self.probe_rustc_version(major, minor) { 293 | emit(&cfg_flag); 294 | } 295 | } 296 | 297 | /// Returns a new (hopefully unique) crate name for probes. 298 | fn new_crate_name(&self) -> String { 299 | #[allow(deprecated)] 300 | static ID: AtomicUsize = ATOMIC_USIZE_INIT; 301 | 302 | let id = ID.fetch_add(1, Ordering::Relaxed); 303 | format!("autocfg_{:016x}_{}", self.uuid, id) 304 | } 305 | 306 | fn probe_fmt<'a>(&self, source: Arguments<'a>) -> Result<(), Error> { 307 | let crate_name = self.new_crate_name(); 308 | let mut command = self.rustc.command(); 309 | command 310 | .arg("--crate-name") 311 | .arg(&crate_name) 312 | .arg("--crate-type=lib") 313 | .arg("--out-dir") 314 | .arg(&self.out_dir) 315 | .arg("--emit=llvm-ir"); 316 | 317 | if let Some(edition) = self.edition.as_ref() { 318 | command.arg("--edition").arg(edition); 319 | } 320 | 321 | if let Some(target) = self.target.as_ref() { 322 | command.arg("--target").arg(target); 323 | } 324 | 325 | command.args(&self.rustflags); 326 | 327 | command.arg("-").stdin(Stdio::piped()); 328 | let mut child = try!(command.spawn().map_err(error::from_io)); 329 | let mut stdin = child.stdin.take().expect("rustc stdin"); 330 | 331 | try!(stdin.write_fmt(source).map_err(error::from_io)); 332 | drop(stdin); 333 | 334 | match child.wait() { 335 | Ok(status) if status.success() => { 336 | // Try to remove the output file so it doesn't look like a build product for 337 | // systems like bazel -- but this is best-effort, so we can ignore failure. 338 | // The probe itself is already considered successful at this point. 339 | let mut file = self.out_dir.join(crate_name); 340 | file.set_extension("ll"); 341 | let _ = fs::remove_file(file); 342 | 343 | Ok(()) 344 | } 345 | Ok(status) => Err(error::from_exit(status)), 346 | Err(error) => Err(error::from_io(error)), 347 | } 348 | } 349 | 350 | fn probe<'a>(&self, code: Arguments<'a>) -> bool { 351 | let result = if self.no_std { 352 | self.probe_fmt(format_args!("#![no_std]\n{}", code)) 353 | } else { 354 | self.probe_fmt(code) 355 | }; 356 | result.is_ok() 357 | } 358 | 359 | /// Tests whether the given code can be compiled as a Rust library. 360 | /// 361 | /// This will only return `Ok` if the compiler ran and exited successfully, 362 | /// per `ExitStatus::success()`. 363 | /// The code is passed to the compiler exactly as-is, notably not even 364 | /// adding the [`#![no_std]`][Self::no_std] attribute like other probes. 365 | /// 366 | /// Raw probes are useful for testing functionality that's not yet covered 367 | /// by the rest of the `AutoCfg` API. For example, the following attribute 368 | /// **must** be used at the crate level, so it wouldn't work within the code 369 | /// templates used by other `probe_*` methods. 370 | /// 371 | /// ``` 372 | /// # extern crate autocfg; 373 | /// # // Normally, cargo will set `OUT_DIR` for build scripts. 374 | /// # let exe = std::env::current_exe().unwrap(); 375 | /// # std::env::set_var("OUT_DIR", exe.parent().unwrap()); 376 | /// let ac = autocfg::new(); 377 | /// assert!(ac.probe_raw("#![no_builtins]").is_ok()); 378 | /// ``` 379 | /// 380 | /// Rust nightly features could be tested as well -- ideally including a 381 | /// code sample to ensure the unstable feature still works as expected. 382 | /// For example, `slice::group_by` was renamed to `chunk_by` when it was 383 | /// stabilized, even though the feature name was unchanged, so testing the 384 | /// `#![feature(..)]` alone wouldn't reveal that. For larger snippets, 385 | /// [`include_str!`] may be useful to load them from separate files. 386 | /// 387 | /// ``` 388 | /// # extern crate autocfg; 389 | /// # // Normally, cargo will set `OUT_DIR` for build scripts. 390 | /// # let exe = std::env::current_exe().unwrap(); 391 | /// # std::env::set_var("OUT_DIR", exe.parent().unwrap()); 392 | /// let ac = autocfg::new(); 393 | /// let code = r#" 394 | /// #![feature(slice_group_by)] 395 | /// pub fn probe(slice: &[i32]) -> impl Iterator { 396 | /// slice.group_by(|a, b| a == b) 397 | /// } 398 | /// "#; 399 | /// if ac.probe_raw(code).is_ok() { 400 | /// autocfg::emit("has_slice_group_by"); 401 | /// } 402 | /// ``` 403 | pub fn probe_raw(&self, code: &str) -> Result<(), Error> { 404 | self.probe_fmt(format_args!("{}", code)) 405 | } 406 | 407 | /// Tests whether the given sysroot crate can be used. 408 | /// 409 | /// The test code is subject to change, but currently looks like: 410 | /// 411 | /// ```ignore 412 | /// extern crate CRATE as probe; 413 | /// ``` 414 | pub fn probe_sysroot_crate(&self, name: &str) -> bool { 415 | // Note: `as _` wasn't stabilized until Rust 1.33 416 | self.probe(format_args!("extern crate {} as probe;", name)) 417 | } 418 | 419 | /// Emits a config value `has_CRATE` if `probe_sysroot_crate` returns true. 420 | pub fn emit_sysroot_crate(&self, name: &str) { 421 | let cfg_flag = format!("has_{}", mangle(name)); 422 | emit_possibility(&cfg_flag); 423 | if self.probe_sysroot_crate(name) { 424 | emit(&cfg_flag); 425 | } 426 | } 427 | 428 | /// Tests whether the given path can be used. 429 | /// 430 | /// The test code is subject to change, but currently looks like: 431 | /// 432 | /// ```ignore 433 | /// pub use PATH; 434 | /// ``` 435 | pub fn probe_path(&self, path: &str) -> bool { 436 | self.probe(format_args!("pub use {};", path)) 437 | } 438 | 439 | /// Emits a config value `has_PATH` if `probe_path` returns true. 440 | /// 441 | /// Any non-identifier characters in the `path` will be replaced with 442 | /// `_` in the generated config value. 443 | pub fn emit_has_path(&self, path: &str) { 444 | self.emit_path_cfg(path, &format!("has_{}", mangle(path))); 445 | } 446 | 447 | /// Emits the given `cfg` value if `probe_path` returns true. 448 | pub fn emit_path_cfg(&self, path: &str, cfg: &str) { 449 | emit_possibility(cfg); 450 | if self.probe_path(path) { 451 | emit(cfg); 452 | } 453 | } 454 | 455 | /// Tests whether the given trait can be used. 456 | /// 457 | /// The test code is subject to change, but currently looks like: 458 | /// 459 | /// ```ignore 460 | /// pub trait Probe: TRAIT + Sized {} 461 | /// ``` 462 | pub fn probe_trait(&self, name: &str) -> bool { 463 | self.probe(format_args!("pub trait Probe: {} + Sized {{}}", name)) 464 | } 465 | 466 | /// Emits a config value `has_TRAIT` if `probe_trait` returns true. 467 | /// 468 | /// Any non-identifier characters in the trait `name` will be replaced with 469 | /// `_` in the generated config value. 470 | pub fn emit_has_trait(&self, name: &str) { 471 | self.emit_trait_cfg(name, &format!("has_{}", mangle(name))); 472 | } 473 | 474 | /// Emits the given `cfg` value if `probe_trait` returns true. 475 | pub fn emit_trait_cfg(&self, name: &str, cfg: &str) { 476 | emit_possibility(cfg); 477 | if self.probe_trait(name) { 478 | emit(cfg); 479 | } 480 | } 481 | 482 | /// Tests whether the given type can be used. 483 | /// 484 | /// The test code is subject to change, but currently looks like: 485 | /// 486 | /// ```ignore 487 | /// pub type Probe = TYPE; 488 | /// ``` 489 | pub fn probe_type(&self, name: &str) -> bool { 490 | self.probe(format_args!("pub type Probe = {};", name)) 491 | } 492 | 493 | /// Emits a config value `has_TYPE` if `probe_type` returns true. 494 | /// 495 | /// Any non-identifier characters in the type `name` will be replaced with 496 | /// `_` in the generated config value. 497 | pub fn emit_has_type(&self, name: &str) { 498 | self.emit_type_cfg(name, &format!("has_{}", mangle(name))); 499 | } 500 | 501 | /// Emits the given `cfg` value if `probe_type` returns true. 502 | pub fn emit_type_cfg(&self, name: &str, cfg: &str) { 503 | emit_possibility(cfg); 504 | if self.probe_type(name) { 505 | emit(cfg); 506 | } 507 | } 508 | 509 | /// Tests whether the given expression can be used. 510 | /// 511 | /// The test code is subject to change, but currently looks like: 512 | /// 513 | /// ```ignore 514 | /// pub fn probe() { let _ = EXPR; } 515 | /// ``` 516 | pub fn probe_expression(&self, expr: &str) -> bool { 517 | self.probe(format_args!("pub fn probe() {{ let _ = {}; }}", expr)) 518 | } 519 | 520 | /// Emits the given `cfg` value if `probe_expression` returns true. 521 | pub fn emit_expression_cfg(&self, expr: &str, cfg: &str) { 522 | emit_possibility(cfg); 523 | if self.probe_expression(expr) { 524 | emit(cfg); 525 | } 526 | } 527 | 528 | /// Tests whether the given constant expression can be used. 529 | /// 530 | /// The test code is subject to change, but currently looks like: 531 | /// 532 | /// ```ignore 533 | /// pub const PROBE: () = ((), EXPR).0; 534 | /// ``` 535 | pub fn probe_constant(&self, expr: &str) -> bool { 536 | self.probe(format_args!("pub const PROBE: () = ((), {}).0;", expr)) 537 | } 538 | 539 | /// Emits the given `cfg` value if `probe_constant` returns true. 540 | pub fn emit_constant_cfg(&self, expr: &str, cfg: &str) { 541 | emit_possibility(cfg); 542 | if self.probe_constant(expr) { 543 | emit(cfg); 544 | } 545 | } 546 | } 547 | 548 | fn mangle(s: &str) -> String { 549 | s.chars() 550 | .map(|c| match c { 551 | 'A'...'Z' | 'a'...'z' | '0'...'9' => c, 552 | _ => '_', 553 | }) 554 | .collect() 555 | } 556 | 557 | fn dir_contains_target( 558 | target: &Option, 559 | dir: &Path, 560 | cargo_target_dir: Option, 561 | ) -> bool { 562 | target 563 | .as_ref() 564 | .and_then(|target| { 565 | dir.to_str().and_then(|dir| { 566 | let mut cargo_target_dir = cargo_target_dir 567 | .map(PathBuf::from) 568 | .unwrap_or_else(|| PathBuf::from("target")); 569 | cargo_target_dir.push(target); 570 | 571 | cargo_target_dir 572 | .to_str() 573 | .map(|cargo_target_dir| dir.contains(cargo_target_dir)) 574 | }) 575 | }) 576 | .unwrap_or(false) 577 | } 578 | 579 | fn rustflags(target: &Option, dir: &Path) -> Vec { 580 | // Starting with rust-lang/cargo#9601, shipped in Rust 1.55, Cargo always sets 581 | // CARGO_ENCODED_RUSTFLAGS for any host/target build script invocation. This 582 | // includes any source of flags, whether from the environment, toml config, or 583 | // whatever may come in the future. The value is either an empty string, or a 584 | // list of arguments separated by the ASCII unit separator (US), 0x1f. 585 | if let Ok(a) = env::var("CARGO_ENCODED_RUSTFLAGS") { 586 | return if a.is_empty() { 587 | Vec::new() 588 | } else { 589 | a.split('\x1f').map(str::to_string).collect() 590 | }; 591 | } 592 | 593 | // Otherwise, we have to take a more heuristic approach, and we don't 594 | // support values from toml config at all. 595 | // 596 | // Cargo only applies RUSTFLAGS for building TARGET artifact in 597 | // cross-compilation environment. Sadly, we don't have a way to detect 598 | // when we're building HOST artifact in a cross-compilation environment, 599 | // so for now we only apply RUSTFLAGS when cross-compiling an artifact. 600 | // 601 | // See https://github.com/cuviper/autocfg/pull/10#issuecomment-527575030. 602 | if *target != env::var_os("HOST") 603 | || dir_contains_target(target, dir, env::var_os("CARGO_TARGET_DIR")) 604 | { 605 | if let Ok(rustflags) = env::var("RUSTFLAGS") { 606 | // This is meant to match how cargo handles the RUSTFLAGS environment variable. 607 | // See https://github.com/rust-lang/cargo/blob/69aea5b6f69add7c51cca939a79644080c0b0ba0/src/cargo/core/compiler/build_context/target_info.rs#L434-L441 608 | return rustflags 609 | .split(' ') 610 | .map(str::trim) 611 | .filter(|s| !s.is_empty()) 612 | .map(str::to_string) 613 | .collect(); 614 | } 615 | } 616 | 617 | Vec::new() 618 | } 619 | 620 | /// Generates a numeric ID to use in probe crate names. 621 | /// 622 | /// This attempts to be random, within the constraints of Rust 1.0 and no dependencies. 623 | fn new_uuid() -> u64 { 624 | const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; 625 | const FNV_PRIME: u64 = 0x100_0000_01b3; 626 | 627 | // This set should have an actual random hasher. 628 | let set: std::collections::HashSet = (0..256).collect(); 629 | 630 | // Feed the `HashSet`-shuffled order into FNV-1a. 631 | let mut hash: u64 = FNV_OFFSET_BASIS; 632 | for x in set { 633 | hash = (hash ^ x).wrapping_mul(FNV_PRIME); 634 | } 635 | hash 636 | } 637 | --------------------------------------------------------------------------------