|
| 1 | +//! Get the built-in cfg flags for the to be compile platform. |
| 2 | +
|
| 3 | +use anyhow::Context; |
| 4 | +use cfg::CfgAtom; |
| 5 | +use rustc_hash::FxHashMap; |
| 6 | +use toolchain::Tool; |
| 7 | + |
| 8 | +use crate::{toolchain_info::QueryConfig, utf8_stdout}; |
| 9 | + |
| 10 | +/// Uses `rustc --print cfg` to fetch the builtin cfgs. |
| 11 | +pub fn get( |
| 12 | + config: QueryConfig<'_>, |
| 13 | + target: Option<&str>, |
| 14 | + extra_env: &FxHashMap<String, String>, |
| 15 | +) -> Vec<CfgAtom> { |
| 16 | + let _p = tracing::info_span!("rustc_cfg::get").entered(); |
| 17 | + |
| 18 | + let rustc_cfgs = rustc_print_cfg(target, extra_env, config); |
| 19 | + let rustc_cfgs = match rustc_cfgs { |
| 20 | + Ok(cfgs) => cfgs, |
| 21 | + Err(e) => { |
| 22 | + tracing::error!(?e, "failed to get rustc cfgs"); |
| 23 | + return vec![]; |
| 24 | + } |
| 25 | + }; |
| 26 | + |
| 27 | + let rustc_cfgs = rustc_cfgs.lines().map(crate::parse_cfg).collect::<Result<Vec<_>, _>>(); |
| 28 | + match rustc_cfgs { |
| 29 | + Ok(rustc_cfgs) => { |
| 30 | + tracing::debug!(?rustc_cfgs, "rustc cfgs found"); |
| 31 | + rustc_cfgs |
| 32 | + } |
| 33 | + Err(e) => { |
| 34 | + tracing::error!(?e, "failed to parse rustc cfgs"); |
| 35 | + vec![] |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +fn rustc_print_cfg( |
| 41 | + target: Option<&str>, |
| 42 | + extra_env: &FxHashMap<String, String>, |
| 43 | + config: QueryConfig<'_>, |
| 44 | +) -> anyhow::Result<String> { |
| 45 | + const RUSTC_ARGS: [&str; 3] = ["--print", "cfg", "-O"]; |
| 46 | + let sysroot = match config { |
| 47 | + QueryConfig::Cargo(sysroot, cargo_toml) => { |
| 48 | + let mut cmd = sysroot.tool(Tool::Cargo); |
| 49 | + cmd.envs(extra_env); |
| 50 | + cmd.current_dir(cargo_toml.parent()).env("RUSTC_BOOTSTRAP", "1"); |
| 51 | + cmd.args(["rustc", "-Z", "unstable-options"]).args(RUSTC_ARGS); |
| 52 | + if let Some(target) = target { |
| 53 | + cmd.args(["--target", target]); |
| 54 | + } |
| 55 | + |
| 56 | + match utf8_stdout(&mut cmd) { |
| 57 | + Ok(it) => return Ok(it), |
| 58 | + Err(e) => { |
| 59 | + tracing::warn!( |
| 60 | + %e, |
| 61 | + "failed to run `{cmd:?}`, falling back to invoking rustc directly" |
| 62 | + ); |
| 63 | + sysroot |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + QueryConfig::Rustc(sysroot) => sysroot, |
| 68 | + }; |
| 69 | + |
| 70 | + let mut cmd = sysroot.tool(Tool::Rustc); |
| 71 | + cmd.envs(extra_env); |
| 72 | + cmd.args(RUSTC_ARGS); |
| 73 | + if let Some(target) = target { |
| 74 | + cmd.args(["--target", target]); |
| 75 | + } |
| 76 | + |
| 77 | + utf8_stdout(&mut cmd).with_context(|| format!("unable to fetch cfgs via `{cmd:?}`")) |
| 78 | +} |
0 commit comments