### Example: emit_has_path and emit_path_cfg Source: https://docs.rs/autocfg/latest/autocfg/struct.AutoCfg.html Example from examples/paths.rs showing how to emit cfg flags for the presence of various standard library paths. ```rust fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); // since ancient times... ac.emit_has_path("std::vec::Vec"); ac.emit_path_cfg("std::vec::Vec", "has_vec"); // rustc 1.10.0 ac.emit_has_path("std::panic::PanicInfo"); ac.emit_path_cfg("std::panic::PanicInfo", "has_panic_info"); // rustc 1.20.0 ac.emit_has_path("std::mem::ManuallyDrop"); ac.emit_path_cfg("std::mem::ManuallyDrop", "has_manually_drop"); // rustc 1.25.0 ac.emit_has_path("std::ptr::NonNull"); ac.emit_path_cfg("std::ptr::NonNull", "has_non_null"); } ``` -------------------------------- ### Example: emit_has_type with with_dir Source: https://docs.rs/autocfg/latest/autocfg/struct.AutoCfg.html Example from examples/integers.rs showing how to emit cfg flags for integer types of various sizes. ```rust fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); for i in 3..8 { ac.emit_has_type(&format!("i{}", 1 << i)); } } ``` -------------------------------- ### Example: emit_has_trait and emit_trait_cfg Source: https://docs.rs/autocfg/latest/autocfg/struct.AutoCfg.html Example from examples/traits.rs showing how to emit cfg flags for the presence of various standard library traits. ```rust fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); // since ancient times... ac.emit_has_trait("std::ops::Add"); ac.emit_trait_cfg("std::ops::Add", "has_ops"); // trait parameters have to be provided ac.emit_has_trait("std::borrow::Borrow"); ac.emit_trait_cfg("std::borrow::Borrow", "has_borrow"); // rustc 1.8.0 ac.emit_has_trait("std::ops::AddAssign"); ac.emit_trait_cfg("std::ops::AddAssign", "has_assign_ops"); // rustc 1.12.0 ac.emit_has_trait("std::iter::Sum"); ac.emit_trait_cfg("std::iter::Sum", "has_sum"); // rustc 1.28.0 ac.emit_has_trait("std::alloc::GlobalAlloc"); ac.emit_trait_cfg("std::alloc::GlobalAlloc", "has_global_alloc"); } ``` -------------------------------- ### Example: emit_rustc_version with with_dir Source: https://docs.rs/autocfg/latest/autocfg/struct.AutoCfg.html Example from examples/versions.rs showing how to create an AutoCfg instance with a custom output directory and emit rustc version checks. ```rust fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); for i in 0..100 { ac.emit_rustc_version(1, i); } } ``` -------------------------------- ### Call a_func from example in examples/ex.rs Source: https://docs.rs/autocfg/latest/scrape-examples-help.html Example file that calls the public function a_func from the crate. This code snippet will be included in the documentation for a_func. ```rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Example: Using autocfg::emit in nightly.rs Source: https://docs.rs/autocfg/latest/autocfg/fn.emit.html Example from `examples/nightly.rs` (line 16) showing how to use `autocfg::emit` to emit a config flag after a successful probe. It creates an `AutoCfg` instance, defines a code snippet to probe for the `slice_group_by` feature, and calls `emit` with the flag name if the probe succeeds. ```rust fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); // When this feature was stabilized, it also renamed the method to // `chunk_by`, so it's important to *use* the feature in your probe. let code = r#" #![feature(slice_group_by)] pub fn probe(slice: &[i32]) -> impl Iterator { slice.group_by(|a, b| a == b) } "#; if ac.probe_raw(code).is_ok() { autocfg::emit("has_slice_group_by"); } } ``` -------------------------------- ### Rustc struct and implementation for rustc.rs Source: https://docs.rs/autocfg/latest/src/autocfg/rustc.rs.html Defines the Rustc struct with fields for the rustc path and optional wrappers. The new() constructor reads environment variables RUSTC, RUSTC_WRAPPER, and RUSTC_WORKSPACE_WRAPPER. The command() method builds a Command that chains wrappers and the rustc executable. The version() method attempts to get the rustc version, trying combinations with and without wrappers to handle wrappers like clippy-driver that don't pass through version commands. The get_rustc_wrapper() helper returns the wrapper path if set and non-empty, with special handling for the workspace wrapper based on CARGO_ENCODED_RUSTFLAGS. ```rust use std::env; use std::ffi::OsString; use std::path::PathBuf; use std::process::Command; use super::error::Error; use super::version::Version; #[derive(Clone, Debug)] pub struct Rustc { rustc: PathBuf, rustc_wrapper: Option, rustc_workspace_wrapper: Option, } impl Rustc { pub fn new() -> Self { Rustc { rustc: env::var_os("RUSTC") .unwrap_or_else(|| "rustc".into()) .into(), rustc_wrapper: get_rustc_wrapper(false), rustc_workspace_wrapper: get_rustc_wrapper(true), } } /// Build the command with possible wrappers. pub fn command(&self) -> Command { let mut rustc = self .rustc_wrapper .iter() .chain(self.rustc_workspace_wrapper.iter()) .chain(Some(&self.rustc)); let mut command = Command::new(rustc.next().unwrap()); for arg in rustc { command.arg(arg); } command } /// Try to get the `rustc` version. pub fn version(&self) -> Result { // Some wrappers like clippy-driver don't pass through version commands, // so we try to fall back to combinations without each wrapper. macro_rules! try_version { ($command:expr) => { if let Ok(value) = Version::from_command($command) { return Ok(value); } }; } let rustc = &self.rustc; if let Some(ref rw) = self.rustc_wrapper { if let Some(ref rww) = self.rustc_workspace_wrapper { try_version!(Command::new(rw).args(&[rww, rustc])); } try_version!(Command::new(rw).arg(rustc)); } if let Some(ref rww) = self.rustc_workspace_wrapper { try_version!(Command::new(rww).arg(rustc)); } Version::from_command(&mut Command::new(rustc)) } } fn get_rustc_wrapper(workspace: bool) -> Option { // We didn't really know whether the workspace wrapper is applicable until Cargo started // deliberately setting or unsetting it in rust-lang/cargo#9601. We'll use the encoded // rustflags as a proxy for that change for now, but we could instead check version 1.55. if workspace && env::var_os("CARGO_ENCODED_RUSTFLAGS").is_none() { return None; } let name = if workspace { "RUSTC_WORKSPACE_WRAPPER" } else { "RUSTC_WRAPPER" }; if let Some(wrapper) = env::var_os(name) { // NB: `OsStr` didn't get `len` or `is_empty` until 1.9. if wrapper != OsString::new() { return Some(wrapper.into()); } } None } ``` -------------------------------- ### probe_raw example: testing slice_group_by feature Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Uses autocfg::new() and probe_raw to test a raw code snippet for the slice_group_by feature, emitting 'has_slice_group_by' if successful. The example sets OUT_DIR to the current executable's parent directory for testing outside a build script. ```rust # extern crate autocfg; # // Normally, cargo will set `OUT_DIR` for build scripts. # let exe = std::env::current_exe().unwrap(); # std::env::set_var("OUT_DIR", exe.parent().unwrap()); let ac = autocfg::new(); let code = r#" #![feature(slice_group_by)] pub fn probe(slice: &[i32]) -> impl Iterator { slice.group_by(|a, b| a == b) } "#; if ac.probe_raw(code).is_ok() { autocfg::emit("has_slice_group_by"); } ``` -------------------------------- ### autocfg build script: emit_has_path and emit_path_cfg for std paths Source: https://docs.rs/autocfg/latest/src/paths/paths.rs.html Example build script for the autocfg crate. It creates an AutoCfg instance using the "target" directory (normally cargo sets OUT_DIR for build scripts) and emits cfg flags for the presence of several std paths, each with a corresponding emit_path_cfg call. The comments note the rustc versions that introduced each path: std::vec::Vec (ancient), std::panic::PanicInfo (1.10.0), std::mem::ManuallyDrop (1.20.0), and std::ptr::NonNull (1.25.0). ```rust extern crate autocfg; fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); // since ancient times... ac.emit_has_path("std::vec::Vec"); ac.emit_path_cfg("std::vec::Vec", "has_vec"); // rustc 1.10.0 ac.emit_has_path("std::panic::PanicInfo"); ac.emit_path_cfg("std::panic::PanicInfo", "has_panic_info"); // rustc 1.20.0 ac.emit_has_path("std::mem::ManuallyDrop"); ac.emit_path_cfg("std::mem::ManuallyDrop", "has_manually_drop"); // rustc 1.25.0 ac.emit_has_path("std::ptr::NonNull"); ac.emit_path_cfg("std::ptr::NonNull", "has_non_null"); } ``` -------------------------------- ### Rust: Detect 128-bit integer support in build.rs Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Example build.rs script that uses autocfg to test for 128-bit integer support. It emits a cargo:rustc-cfg=has_i128 line if the type test succeeds, which translates to --cfg has_i128 for rustc. The example also shows how to rerun the build script when build.rs changes. ```rust extern crate autocfg; fn main() { # // Normally, cargo will set `OUT_DIR` for build scripts. # let exe = std::env::current_exe().unwrap(); # std::env::set_var("OUT_DIR", exe.parent().unwrap()); let ac = autocfg::new(); ac.emit_has_type("i128"); // (optional) We don't need to rerun for anything external. autocfg::rerun_path("build.rs"); } ``` -------------------------------- ### Emit rustc version checks with autocfg Source: https://docs.rs/autocfg/latest/src/versions/versions.rs.html Shows how to use autocfg to emit rustc version checks for versions 1.0 through 1.99. The example uses `AutoCfg::with_dir("target")` to specify the output directory, noting that normally cargo sets `OUT_DIR` for build scripts. ```rust extern crate autocfg; fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); for i in 0..100 { ac.emit_rustc_version(1, i); } } ``` -------------------------------- ### Add autocfg as a build dependency in Cargo.toml Source: https://docs.rs/autocfg/latest/index.html Adds autocfg version 1 to the build-dependencies section of Cargo.toml. This is the required setup before using the library in a build script. ```toml [build-dependencies] autocfg = "1" ``` -------------------------------- ### Detect i128 support in build.rs using autocfg Source: https://docs.rs/autocfg/latest/index.html Example build.rs script that creates an AutoCfg instance and emits a cfg flag for i128 type support. Optionally calls rerun_path to avoid rerunning for external changes. On success, it writes cargo:rustc-cfg=has_i128, enabling #[cfg(has_i128)] conditions in the code. ```rust extern crate autocfg; fn main() { let ac = autocfg::new(); ac.emit_has_type("i128"); // (optional) We don't need to rerun for anything external. autocfg::rerun_path("build.rs"); } ``` -------------------------------- ### Raw probe with #![no_builtins] attribute Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Tests raw code compilation using probe_raw, which passes code exactly as-is without adding #![no_std]. Useful for crate-level attributes that must appear at the top of the file. The example asserts that probing #![no_builtins] succeeds. ```rust /// ``` /// # extern crate autocfg; /// # // Normally, cargo will set `OUT_DIR` for build scripts. /// # let exe = std::env::current_exe().unwrap(); /// # std::env::set_var("OUT_DIR", exe.parent().unwrap()); /// let ac = autocfg::new(); /// assert!(ac.probe_raw("#![no_builtins]").is_ok()); /// ``` ``` -------------------------------- ### Define public function a_func in src/lib.rs Source: https://docs.rs/autocfg/latest/scrape-examples-help.html Defines a public function in the library source that will be documented. Rustdoc scrapes examples of this item from the project's source code. ```rust // src/lib.rs pub fn a_func() {} ``` -------------------------------- ### new (free function) Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Creates a new `AutoCfg` instance, panicking if `AutoCfg::new()` returns an error. ```APIDOC ## new (free function) ### Description Creates a new `AutoCfg` instance, panicking if `AutoCfg::new()` returns an error. ### Function Signature `pub fn new() -> AutoCfg` ### Panics Panics if `AutoCfg::new()` returns an error. ``` -------------------------------- ### Version struct and from_command implementation Source: https://docs.rs/autocfg/latest/src/autocfg/version.rs.html Defines the Version struct with major, minor, and patch fields, and provides a new constructor and a from_command method that parses rustc's verbose version output. The from_command method runs rustc with --version --verbose, extracts the release line, strips channel info, and parses semver components, returning errors for missing or invalid parts. ```rust use std::process::Command; use std::str; use super::{error, Error}; /// A version structure for making relative comparisons. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Version { major: usize, minor: usize, patch: usize, } impl Version { /// Creates a `Version` instance for a specific `major.minor.patch` version. pub fn new(major: usize, minor: usize, patch: usize) -> Self { Version { major: major, minor: minor, patch: patch, } } pub fn from_command(command: &mut Command) -> Result { // Get rustc's verbose version let output = try!(command .args(&["--version", "--verbose"]) .output() .map_err(error::from_io)); if !output.status.success() { return Err(error::from_str("could not execute rustc")); } let output = try!(str::from_utf8(&output.stdout).map_err(error::from_utf8)); // Find the release line in the verbose version output. let release = match output.lines().find(|line| line.starts_with("release: ")) { Some(line) => &line["release: ".len()..], None => return Err(error::from_str("could not find rustc release")), }; // Strip off any extra channel info, e.g. "-beta.N", "-nightly" let version = match release.find('-') { Some(i) => &release[..i], None => release, }; // Split the version into semver components. let mut iter = version.splitn(3, '.'); let major = try!(iter .next() .ok_or_else(|| error::from_str("missing major version"))); let minor = try!(iter .next() .ok_or_else(|| error::from_str("missing minor version"))); let patch = try!(iter .next() .ok_or_else(|| error::from_str("missing patch version"))); Ok(Version::new( try!(major.parse().map_err(error::from_num)), try!(minor.parse().map_err(error::from_num)), try!(patch.parse().map_err(error::from_num)), )) } } ``` -------------------------------- ### pub fn new() -> AutoCfg Source: https://docs.rs/autocfg/latest/autocfg/fn.new.html Creates a new `AutoCfg` instance. This function panics if `AutoCfg::new()` returns an error. ```APIDOC ## pub fn new() -> AutoCfg ### Description Creates a new `AutoCfg` instance. This function panics if `AutoCfg::new()` returns an error. ### Function Signature ```rust pub fn new() -> AutoCfg ``` ### Panics Panics if `AutoCfg::new()` returns an error. ### Returns - `AutoCfg` - A new `AutoCfg` instance. ``` -------------------------------- ### rerun_env Source: https://docs.rs/autocfg/latest/autocfg/fn.rerun_env.html Documentation for the `rerun_env` function from the `autocfg` crate. ```APIDOC ## rerun_env ### Description Writes a line telling Cargo to rerun the build script if the environment variable `var` changes. This looks like: `cargo:rerun-if-env-changed=VAR`. This requires at least cargo 0.21.0, corresponding to rustc 1.20.0. Earlier versions of cargo will simply ignore the directive. ### Function Signature `pub fn rerun_env(var: &str)` ### Parameters - **var** (`&str`) - The name of the environment variable to watch for changes. ### Behavior - Emits a Cargo directive `cargo:rerun-if-env-changed=VAR` to the build script output. - Requires Cargo 0.21.0 or later (rustc 1.20.0 or later). - Earlier Cargo versions ignore the directive. ``` -------------------------------- ### Version::new Source: https://docs.rs/autocfg/latest/src/autocfg/version.rs.html Constructs a Version instance from explicit major, minor, and patch numbers. ```APIDOC ## Version::new ### Description Creates a `Version` instance for a specific `major.minor.patch` version. ### Method `pub fn new(major: usize, minor: usize, patch: usize) -> Self` ### Parameters - **major** (usize) - Required - The major version number. - **minor** (usize) - Required - The minor version number. - **patch** (usize) - Required - The patch version number. ### Returns - **Self** - A new `Version` instance with the given components. ### Example ```rust let version = Version::new(1, 5, 1); ``` ``` -------------------------------- ### AutoCfg::with_dir Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Creates a new `AutoCfg` instance with the specified output directory. Returns an error if `rustc` cannot be executed, its version cannot be parsed, or the directory is not writable. ```APIDOC ## AutoCfg::with_dir ### Description Creates a new `AutoCfg` instance with the specified output directory. Returns an error if `rustc` cannot be executed, its version cannot be parsed, or the directory is not writable. ### Method Signature `pub fn with_dir>(dir: T) -> Result` ### Parameters - **dir** (`T: Into`) - The output directory to use. ### Common Errors - `rustc` can't be executed, from `RUSTC` or in the `PATH`. - The version output from `rustc` can't be parsed. - `dir` is not a writable directory. ``` -------------------------------- ### AutoCfg::new Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Creates a new `AutoCfg` instance using the `OUT_DIR` environment variable. Returns an error if `rustc` cannot be executed, its version cannot be parsed, or `OUT_DIR` is not set or not writable. ```APIDOC ## AutoCfg::new ### Description Creates a new `AutoCfg` instance using the `OUT_DIR` environment variable. Returns an error if `rustc` cannot be executed, its version cannot be parsed, or `OUT_DIR` is not set or not writable. ### Method Signature `pub fn new() -> Result` ### Common Errors - `rustc` can't be executed, from `RUSTC` or in the `PATH`. - The version output from `rustc` can't be parsed. - `OUT_DIR` is not set in the environment, or is not a writable directory. ``` -------------------------------- ### AutoCfg::with_dir Source: https://docs.rs/autocfg/latest/autocfg/struct.AutoCfg.html Creates a new `AutoCfg` instance with a specified output directory, useful when `OUT_DIR` is not set. ```APIDOC ## AutoCfg::with_dir ### Description Creates a new `AutoCfg` instance with the specified output directory. This is useful when `OUT_DIR` is not set or you want to use a custom directory. ### Method with_dir ### Signature `pub fn with_dir>(dir: T) -> Result` ### Parameters - **dir** (`T: Into`) - Required - The output directory to use for the `AutoCfg` instance. ### Return Value - `Result` - A new `AutoCfg` instance, or an error if `rustc` cannot be executed, the version output cannot be parsed, or `dir` is not a writable directory. ### Errors - `rustc` cannot be executed, from `RUSTC` or in the `PATH`. - The version output from `rustc` cannot be parsed. - `dir` is not a writable directory. ### Example ```rust let ac = autocfg::AutoCfg::with_dir("target").unwrap(); ``` ``` -------------------------------- ### Version::from_command Source: https://docs.rs/autocfg/latest/src/autocfg/version.rs.html Parses a Version from the output of a rustc command, extracting the release line and splitting it into major, minor, and patch components. ```APIDOC ## Version::from_command ### Description Creates a `Version` instance by parsing the output of a `rustc --version --verbose` command. The command is executed and its output is parsed to extract the release version. ### Method `pub fn from_command(command: &mut Command) -> Result` ### Parameters - **command** (&mut Command) - Required - A mutable reference to a `std::process::Command` that will be executed with `--version --verbose` arguments. ### Returns - **Result** - On success, a `Version` instance parsed from the command output. On failure, an `Error` describing the problem (e.g., command execution failure, invalid UTF-8, missing release line, or malformed version components). ### Errors - Returns an error if the command fails to execute or exits with a non-success status. - Returns an error if the output is not valid UTF-8. - Returns an error if the output does not contain a line starting with `release: `. - Returns an error if the version string is missing major, minor, or patch components, or if any component fails to parse as a number. ### Example ```rust use std::process::Command; let mut cmd = Command::new("rustc"); let version = Version::from_command(&mut cmd)?; ``` ``` -------------------------------- ### emit(cfg: &str) Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Writes a config flag for rustc on standard out. This looks like `cargo:rustc-cfg=CFG`. Cargo will use this in arguments to rustc, like `--cfg CFG`. ```APIDOC ## emit(cfg: &str) ### Description Writes a config flag for rustc on standard out. This looks like `cargo:rustc-cfg=CFG`. Cargo will use this in arguments to rustc, like `--cfg CFG`. ### Parameters - `cfg` (string) - Required - The config flag to emit. ### Behavior This does not automatically call `emit_possibility` so the compiler may generate an `unexpected_cfgs` warning. However, all the builtin emit methods on `AutoCfg` call `emit_possibility` automatically. ``` -------------------------------- ### autocfg::emit Source: https://docs.rs/autocfg/latest/index.html Writes a config flag for rustc on standard out. ```APIDOC ## Function: emit ### Description Writes a config flag for rustc on standard out. ### Signature `pub fn emit(cfg: &str)` ### Parameters - **cfg** (&str) - Required - The config flag to emit. ### Usage Example ```rust autocfg::emit("has_i128"); ``` ``` -------------------------------- ### autocfg::new Source: https://docs.rs/autocfg/latest/index.html Creates a new AutoCfg instance for detecting compiler features in build scripts. ```APIDOC ## Function: new ### Description Creates a new `AutoCfg` instance. ### Signature `pub fn new() -> AutoCfg` ### Returns - **AutoCfg** - A new instance for probing compiler features. ### Usage Example ```rust extern crate autocfg; fn main() { let ac = autocfg::new(); ac.emit_has_type("i128"); } ``` ``` -------------------------------- ### set_edition Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Sets the Rust edition to use for probes. The edition must be supported by the current rustc, otherwise probes will fail. ```APIDOC ## set_edition ### Description Sets the Rust edition to use for probes. The edition must be supported by the current rustc, otherwise probes will fail. ### Method set_edition ### Signature pub fn set_edition(&mut self, edition: Option) ### Parameters - **edition** (Option) - Required - The edition to set, e.g., "2015", "2018", "2021", "2024". ### Notes Known editions and their minimum Rust versions: - 2015: 1.27.0 - 2018: 1.31.0 - 2021: 1.56.0 - 2024: 1.85.0 ``` -------------------------------- ### Function signature: pub fn emit(cfg: &str) Source: https://docs.rs/autocfg/latest/autocfg/fn.emit.html Signature of the `emit` function. It takes a `&str` representing the config flag name and writes it to standard output. ```rust pub fn emit(cfg: &str) ``` -------------------------------- ### emit_rustc_version Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Sets a cfg value of the form rustc_major_minor (e.g., rustc_1_29) if the current rustc is at least that version. ```APIDOC ## emit_rustc_version ### Description Sets a cfg value of the form rustc_major_minor (e.g., rustc_1_29) if the current rustc is at least that version. ### Method emit_rustc_version ### Signature pub fn emit_rustc_version(&self, major: usize, minor: usize) ### Parameters - **major** (usize) - Required - The major version number. - **minor** (usize) - Required - The minor version number. ### Behavior Emits a cfg flag like `rustc_1_29` if the current rustc version is >= major.minor. ``` -------------------------------- ### probe_raw with slice_group_by feature Source: https://docs.rs/autocfg/latest/autocfg/struct.AutoCfg.html Shows a raw probe testing the unstable slice_group_by feature. The code is passed exactly as-is, and the feature is used to ensure it works. If the probe succeeds, emits the has_slice_group_by cfg. ```rust let ac = autocfg::new(); let code = r#" #![feature(slice_group_by)] pub fn probe(slice: &[i32]) -> impl Iterator { slice.group_by(|a, b| a == b) } "#; if ac.probe_raw(code).is_ok() { autocfg::emit("has_slice_group_by"); } ``` -------------------------------- ### emit_sysroot_crate Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Emits a config value `has_CRATE` if `probe_sysroot_crate` returns true. ```APIDOC ## emit_sysroot_crate ### Description Emits a config value `has_CRATE` if `probe_sysroot_crate` returns true. ### Method emit_sysroot_crate(&self, name: &str) ### Parameters - **name** (string) - Required - The name of the sysroot crate to test and emit config for. ### Behavior - Emits a config value `has_CRATE` if the crate can be used. ``` -------------------------------- ### probe_path Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Tests whether the given path can be used. The test code is subject to change, but currently looks like `pub use PATH;`. ```APIDOC ## probe_path ### Description Tests whether the given path can be used. The test code is subject to change, but currently looks like `pub use PATH;`. ### Method probe_path(&self, path: &str) -> bool ### Parameters - **path** (string) - Required - The path to test. ### Returns - **bool** - true if the path can be used, false otherwise. ``` -------------------------------- ### Probe slice_group_by feature with autocfg::probe_raw Source: https://docs.rs/autocfg/latest/src/nightly/nightly.rs.html Use `autocfg::AutoCfg::with_dir` to create a probe context, then call `probe_raw` with a code snippet that uses the `slice_group_by` feature. If the probe succeeds, emit the `has_slice_group_by` flag. The comment notes that the feature was later renamed to `chunk_by`, so the probe must actually use the feature to detect the correct API. ```rust extern crate autocfg; fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); // When this feature was stabilized, it also renamed the method to // `chunk_by`, so it's important to *use* the feature in your probe. let code = r#" #![feature(slice_group_by)] pub fn probe(slice: &[i32]) -> impl Iterator { slice.group_by(|a, b| a == b) } "#; if ac.probe_raw(code).is_ok() { autocfg::emit("has_slice_group_by"); } } ``` -------------------------------- ### probe_raw Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Tests whether the given code can be compiled as a Rust library. The code is passed to the compiler exactly as-is, without adding the #![no_std] attribute. ```APIDOC ## probe_raw ### Description Tests whether the given code can be compiled as a Rust library. The code is passed to the compiler exactly as-is, without adding the #![no_std] attribute. ### Method probe_raw ### Signature pub fn probe_raw(&self, code: &str) -> Result<(), Error> ### Parameters - **code** (&str) - Required - The Rust code to compile as a probe. ### Returns - **Result<(), Error>** - `Ok(())` if the compiler ran and exited successfully, otherwise an error. ### Example ```rust let ac = autocfg::new(); assert!(ac.probe_raw("#![no_builtins]").is_ok()); ``` ``` -------------------------------- ### rerun_env(var: &str) Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Writes a line telling Cargo to rerun the build script if the environment variable `var` changes. This looks like `cargo:rerun-if-env-changed=VAR`. ```APIDOC ## rerun_env(var: &str) ### Description Writes a line telling Cargo to rerun the build script if the environment variable `var` changes. This looks like `cargo:rerun-if-env-changed=VAR`. ### Parameters - `var` (string) - Required - The environment variable to watch for changes. ### Requirements This requires at least cargo 0.21.0, corresponding to rustc 1.20.0. Earlier versions of cargo will simply ignore the directive. ``` -------------------------------- ### Probe constant and emit cfg Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Probes whether a given constant expression can be used and emits the corresponding cfg value if the probe succeeds. The probe code is constructed with the expression inserted into a constant definition. ```rust pub const PROBE: () = ((), EXPR).0; ``` ```rust pub fn probe_constant(&self, expr: &str) -> bool { self.probe(format_args!("pub const PROBE: () = ((), {}).0;", expr)) } ``` ```rust pub fn emit_constant_cfg(&self, expr: &str, cfg: &str) { emit_possibility(cfg); if self.probe_constant(expr) { emit(cfg); } } ``` -------------------------------- ### probe_raw Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Tests whether the given Rust code can be compiled with the current compiler. Useful for probing feature gates or larger code snippets. ```APIDOC ## probe_raw ### Description Tests whether the given Rust code can be compiled with the current compiler. Useful for probing feature gates or larger code snippets. ### Method probe_raw(&self, code: &str) -> Result<(), Error> ### Parameters - **code** (string) - Required - The Rust code to test compilation. ### Returns - **Result<(), Error>** - Ok(()) if the code compiles, otherwise an error. ### Example ```rust let ac = autocfg::new(); let code = r#" #![feature(slice_group_by)] pub fn probe(slice: &[i32]) -> impl Iterator { slice.group_by(|a, b| a == b) } "#; if ac.probe_raw(code).is_ok() { autocfg::emit("has_slice_group_by"); } ``` ``` -------------------------------- ### probe_sysroot_crate Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Tests whether the given sysroot crate can be used. The test code is subject to change, but currently looks like `extern crate CRATE as probe;`. ```APIDOC ## probe_sysroot_crate ### Description Tests whether the given sysroot crate can be used. The test code is subject to change, but currently looks like `extern crate CRATE as probe;`. ### Method probe_sysroot_crate(&self, name: &str) -> bool ### Parameters - **name** (string) - Required - The name of the sysroot crate to test. ### Returns - **bool** - true if the crate can be used, false otherwise. ``` -------------------------------- ### AutoCfg Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Helper to detect compiler features for cfg output in build scripts. Provides methods to probe compiler support and emit configuration flags. ```APIDOC ## AutoCfg ### Description Helper to detect compiler features for `cfg` output in build scripts. Provides methods to probe compiler support and emit configuration flags. ### Methods - `new()` - Creates a new AutoCfg instance. - `emit_has_type(type_name)` - Emits a config flag if the given type is supported by the compiler. - `emit_possibility(cfg)` - Emits a config flag indicating that a cfg possibility exists. ### Usage Example ```rust let ac = autocfg::new(); ac.emit_has_type("i128"); ``` ``` -------------------------------- ### autocfg::rerun_env Source: https://docs.rs/autocfg/latest/index.html Writes a line telling Cargo to rerun the build script if the environment variable changes. ```APIDOC ## Function: rerun_env ### Description Writes a line telling Cargo to rerun the build script if the environment variable `var` changes. ### Signature `pub fn rerun_env(var: &str)` ### Parameters - **var** (&str) - Required - The environment variable name to monitor. ### Usage Example ```rust autocfg::rerun_env("DEP_FOO_VERSION"); ``` ``` -------------------------------- ### probe_rustc_version Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Tests whether the current rustc reports a version greater than or equal to the given major.minor version. ```APIDOC ## probe_rustc_version ### Description Tests whether the current rustc reports a version greater than or equal to the given major.minor version. ### Method probe_rustc_version ### Signature pub fn probe_rustc_version(&self, major: usize, minor: usize) -> bool ### Parameters - **major** (usize) - Required - The major version number. - **minor** (usize) - Required - The minor version number. ### Returns - **bool** - `true` if the current rustc version is >= major.minor, otherwise `false`. ``` -------------------------------- ### autocfg trait detection build script Source: https://docs.rs/autocfg/latest/src/traits/traits.rs.html Uses autocfg::AutoCfg::with_dir to create a config, then emits has_trait and trait_cfg flags for traits like std::ops::Add, std::borrow::Borrow, std::ops::AddAssign, std::iter::Sum, and std::alloc::GlobalAlloc. The comments note the Rust versions when each trait was introduced. ```rust extern crate autocfg; fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); // since ancient times... ac.emit_has_trait("std::ops::Add"); ac.emit_trait_cfg("std::ops::Add", "has_ops"); // trait parameters have to be provided ac.emit_has_trait("std::borrow::Borrow"); ac.emit_trait_cfg("std::borrow::Borrow", "has_borrow"); // rustc 1.8.0 ac.emit_has_trait("std::ops::AddAssign"); ac.emit_trait_cfg("std::ops::AddAssign", "has_assign_ops"); // rustc 1.12.0 ac.emit_has_trait("std::iter::Sum"); ac.emit_trait_cfg("std::iter::Sum", "has_sum"); // rustc 1.28.0 ac.emit_has_trait("std::alloc::GlobalAlloc"); ac.emit_trait_cfg("std::alloc::GlobalAlloc", "has_global_alloc"); } ``` -------------------------------- ### rerun_path Source: https://docs.rs/autocfg/latest/autocfg/fn.rerun_path.html Writes a line telling Cargo to rerun the build script if the given path changes. The directive is formatted as 'cargo:rerun-if-changed=PATH'. ```APIDOC ## rerun_path ### Description Writes a line telling Cargo to rerun the build script if `path` changes. The directive is formatted as `cargo:rerun-if-changed=PATH`. ### Function Signature ```rust pub fn rerun_path(path: &str) ``` ### Parameters - **path** (`&str`) - Required - The path that, when changed, should trigger a rerun of the build script. ### Behavior - Emits a Cargo directive: `cargo:rerun-if-changed=PATH`. - Requires Cargo 0.7.0 or later (rustc 1.6.0+). Earlier versions of Cargo will ignore the directive. ``` -------------------------------- ### Probe expression and emit cfg Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Probes whether a given expression can be used and emits the corresponding cfg value if the probe succeeds. The probe code is constructed with the expression inserted into a function body. ```rust self.probe(format_args!("pub fn probe() {{ let _ = {}; }}", expr)) ``` ```rust pub fn emit_expression_cfg(&self, expr: &str, cfg: &str) { emit_possibility(cfg); if self.probe_expression(expr) { emit(cfg); } } ``` -------------------------------- ### emit_path_cfg Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Emits the given `cfg` value if `probe_path` returns true. ```APIDOC ## emit_path_cfg ### Description Emits the given `cfg` value if `probe_path` returns true. ### Method emit_path_cfg(&self, path: &str, cfg: &str) ### Parameters - **path** (string) - Required - The path to test. - **cfg** (string) - Required - The config value to emit if the path can be used. ### Behavior - Emits the given `cfg` value if the path can be used. ``` -------------------------------- ### probe_expression Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Tests whether the given expression can be used. The test code is subject to change, but currently looks like `pub fn probe() { let _ = EXPR; }`. ```APIDOC ## probe_expression ### Description Tests whether the given expression can be used. The test code is subject to change, but currently looks like `pub fn probe() { let _ = EXPR; }`. ### Method probe_expression(&self, expr: &str) -> bool ### Parameters - **expr** (string) - Required - The expression to test. ### Returns - **bool** - true if the expression can be used, false otherwise. ``` -------------------------------- ### AutoCfg::edition Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Returns the `--edition` string that is currently being passed to `rustc`, if any, as configured by the `set_edition` method. ```APIDOC ## AutoCfg::edition ### Description Returns the `--edition` string that is currently being passed to `rustc`, if any, as configured by the `set_edition` method. ### Method Signature `pub fn edition(&self) -> Option<&str>` ### Returns - `Option<&str>` - The edition string if set, `None` otherwise. ``` -------------------------------- ### emit_has_path Source: https://docs.rs/autocfg/latest/src/autocfg/lib.rs.html Emits a config value `has_PATH` if `probe_path` returns true. Any non-identifier characters in the `path` will be replaced with `_` in the generated config value. ```APIDOC ## emit_has_path ### Description Emits a config value `has_PATH` if `probe_path` returns true. Any non-identifier characters in the `path` will be replaced with `_` in the generated config value. ### Method emit_has_path(&self, path: &str) ### Parameters - **path** (string) - Required - The path to test and emit config for. ### Behavior - Emits a config value `has_PATH` if the path can be used. ``` -------------------------------- ### Emit cfg flags for integer types with autocfg Source: https://docs.rs/autocfg/latest/src/integers/integers.rs.html Use in a build script to emit cfg flags for integer types i8 through i128. It creates an AutoCfg instance with the target directory and calls emit_has_type for each type name generated by the loop. ```rust extern crate autocfg; fn main() { // Normally, cargo will set `OUT_DIR` for build scripts. let ac = autocfg::AutoCfg::with_dir("target").unwrap(); for i in 3..8 { ac.emit_has_type(&format!("i{}", 1 << i)); } } ``` -------------------------------- ### pub fn emit_possibility(cfg: &str) Source: https://docs.rs/autocfg/latest/autocfg/fn.emit_possibility.html Indicates to rustc that a config flag should not generate an unexpected_cfgs warning. This is equivalent to emitting `cargo:rustc-check-cfg=cfg(VAR)` and is ignored by Rust versions before 1.80. ```APIDOC ## pub fn emit_possibility(cfg: &str) ### Description Indicates to rustc that a config flag should not generate an `unexpected_cfgs` warning. This is equivalent to emitting `cargo:rustc-check-cfg=cfg(VAR)`. As of Rust 1.80, the compiler performs automatic checking of cfgs at compile time, and all custom configuration flags must be known to rustc to avoid warnings. This function is useful when calling `autocfg::emit` directly, as the built-in emit methods on `AutoCfg` handle this automatically. Versions before Rust 1.80 will simply ignore this directive. ### Parameters #### Parameters - **cfg** (`&str`) - Required - The config flag to indicate as known to rustc. ### Notes - This function indicates that the config flag never has a value. If value-bearing flags are needed, refer to the linked blog post on check-cfg. ### Example ```rust // Example usage (not provided in source) ``` ``` -------------------------------- ### emit_path_cfg Source: https://docs.rs/autocfg/latest/autocfg/struct.AutoCfg.html Emits a given cfg value if the specified path can be used. This is useful for conditionally enabling features based on the availability of a path. ```APIDOC ## emit_path_cfg ### Description Emits the given `cfg` value if `probe_path` returns true. ### Method pub fn emit_path_cfg(&self, path: &str, cfg: &str) ### Parameters - **path** (&str) - The path to probe. - **cfg** (&str) - The cfg value to emit if the path is available. ### Example ```rust ac.emit_path_cfg("std::vec::Vec", "has_vec"); ``` ```