Parser for CARGO_ENCODED_RUSTFLAGS

Overview

Parser for CARGO_ENCODED_RUSTFLAGS

github crates.io docs.rs build status

CARGO_ENCODED_RUSTFLAGS is one of the environment variables provided by Cargo to build scripts. It synthesizes several sources of flags affecting Cargo's rustc invocations that build scripts might care about:

  • Flags passed via the RUSTFLAGS environment variable,
  • Cargo config entries under target.<triple>.rustflags and target.<cfg>.rustflags and build.rustflags, including from the project-specific Cargo config file and the Cargo config in the user's CARGO_HOME.

If a build script needs to make some rustc invocations, or needs to characterize aspects of the upcoming rustc invocation, it likely needs these flags.

[build-dependencies]
rustflags = "0.1"

Examples

This build script wants to know whether it is okay to enable #![feature(proc_macro_span)]. If the user is building with -Zallow-features with a feature list that does not include proc_macro_span, we need to not enable the feature or the build will fail.

// build.rs

use rustflags::Flag;

fn main() {
    if is_nightly() && feature_allowed("proc_macro_span") {
        println!("cargo:rustc-cfg=proc_macro_span");
    }
}

// Look for `-Z allow-features=feature1,feature2`
fn feature_allowed(feature: &str) -> bool {
    for flag in rustflags::from_env() {
        if let Flag::Z(option) = flag {
            if option.starts_with("allow-features=") {
                return option["allow-features=".len()..]
                    .split(',')
                    .any(|allowed| allowed == feature);
            }
        }
    }

    // No allow-features= flag, allowed by default.
    true
}

This build scripts wants to try compiling a source file to figure out whether an unstable API is supported in the expected form by the current toolchain.

// build.rs

use rustflags::Flag;
use std::env;
use std::fs;
use std::path::Path;
use std::process::{Command, ExitStatus, Stdio};

// This code exercises the surface area that we expect of the unstable
// feature. If the current toolchain is able to compile it, we go ahead and
// enable the feature.
const PROBE: &str = r#"
    #![feature(backtrace)]
    #![allow(dead_code)]

    use std::backtrace::{Backtrace, BacktraceStatus};

    fn probe() {
        let backtrace = Backtrace::capture();
        match backtrace.status() {
            BacktraceStatus::Captured | BacktraceStatus::Disabled | _ => {}
        }
    }
"#;

fn main() {
    match compile_probe() {
        Some(status) if status.success() => println!("cargo:rustc-cfg=backtrace"),
        _ => {}
    }
}

fn compile_probe() -> Option<ExitStatus> {
    let rustc = env::var_os("RUSTC")?;
    let out_dir = env::var_os("OUT_DIR")?;
    let probefile = Path::new(&out_dir).join("probe.rs");
    fs::write(&probefile, PROBE).ok()?;

    // Make sure to pick up Cargo rustc configuration.
    let mut cmd = if let Some(wrapper) = env::var_os("CARGO_RUSTC_WRAPPER") {
        let mut cmd = Command::new(wrapper);
        // The wrapper's first argument is supposed to be the path to rustc.
        cmd.arg(rustc);
        cmd
    } else {
        Command::new(rustc)
    };

    cmd.stderr(Stdio::null())
        .arg("--edition=2021")
        .arg("--crate-name=try_backtrace")
        .arg("--crate-type=lib")
        .arg("--emit=metadata")
        .arg("--out-dir")
        .arg(out_dir)
        .arg(probefile)
        .args(rustflags::from_env()
            .filter(|flag| matches!(flag, Flag::Cfg{..} | Flag::Z(_)))
            .flatten())
        .status()
        .ok()
}

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
You might also like...
Python wrapper for Rust's httparse HTTP parser

httparse Python wrapper for Rust's httparse. See this project on GitHub. Example from httparse import RequestParser parser = RequestParser() buff =

A parser and matcher for route patterns in Rust 🦀

Route Pattern A parser and matcher for a popular way to create route patterns. Patterns like these that include regular expressions, delimited in this

Alpha Hyprland/Hyprpaper/Hypr configuration file parser

Hyprland/Hyprpaper/Hypr configuration file parser [maintainer=@yavko]

Here we will show you how to build a simple parser.

A Rustic invitation to parsing: Calculator demo This is the code repository that accompanies the Rustic invitation to parsing blog post. It provides a

Rust parser/validator for Debian version strings

debian version handling in rust This simple crate provides a struct for parsing, validating, manipulating and comparing Debian version strings. It aim

SP3 Precise GNSS Orbit and Clock parser :artificial_satellite:

SP3 SP3 Precise GNSS Orbit files parser. SP3 is specifid by IGS. The parser only supports Revisions C & D at the moment and rejects revisions A & B. G

A SQL query parser written using nom.

sqlparser-nom A SQL query parser written using nom. Query Select From Where Order by Limit CTE Group by Having Aggregate Window Pratt Parsing Friendly

🔨 A JSON parser that will return span informations

Spanned Json Parser   This crate is a json parser that will return span information for values, which mean lines and column number. It is also compati

A parser combinator that is fully statically dispatched and supports both sync/async.

XParse A parser combinator that is fully statically dispatched and supports both sync & async parsing. How to use An example of a very simple JSON par

Releases(0.1.2)
Owner
David Tolnay
David Tolnay
A full featured, fast Command Line Argument Parser for Rust

clap Command Line Argument Parser for Rust It is a simple-to-use, efficient, and full-featured library for parsing command line arguments and subcomma

null 10.4k Jan 10, 2023
Docopt for Rust (command line argument parser).

THIS CRATE IS UNMAINTAINED This crate is unlikely to see significant future evolution. The primary reason to choose this crate for a new project is if

null 743 Jan 1, 2023
Pure-Rust rewrite of the Linux fontconfig library (no system dependencies) - using ttf-parser and allsorts

rust-fontconfig Pure-Rust rewrite of the Linux fontconfig library (no system dependencies) - using allsorts as a font parser in order to parse .woff,

Felix Schütt 28 Oct 29, 2022
A minimal argument parser

Pieces An argument parser built with control in mind. Parsing The results you get are dependent on what order you parse in. If you want to say only pa

ibx34 3 Sep 30, 2021
A full featured, fast Command Line Argument Parser for Rust

clap Command Line Argument Parser for Rust It is a simple-to-use, efficient, and full-featured library for parsing command line arguments and subcomma

Ed Page 0 Jun 16, 2022
Simple command line flag parser for rust.

easy_flag Simple command line flag parser for rust. use easy_flag::FlagSet; fn main() -> Result<(), String>{ let mut help = false; let mut my

BillyfBrain 3 Oct 20, 2021
Next-generation, type-safe CLI parser for Rust

Next-generation, type-safe CLI parser for Rust

0918nobita 19 Jul 20, 2022
lemmy-help is a emmylua parser as well as a CLI which takes that parsed tree and converts it into vim help docs.

lemmy-help is a emmylua parser as well as a CLI which takes that parsed tree and converts it into vim help docs.

Vikas Raj 117 Jan 3, 2023
A simple, lightweight and extensible command line argument parser for rust codebases

A simple, lightweight and extensible command line argument parser for rust codebases. This crate aims to provide you with an easy-to-use and extensibl

Victor Ndaba 20 Nov 12, 2022
A parser and evaluator of spreadsheet-like formulas

Formula A parser and evaluator of spreadsheet-like formulas Formula is in its early stages, so it's better to be used cautiously. So far we have the f

Omid Rad 5 Dec 18, 2022