aboutsummaryrefslogtreecommitdiff
path: root/crates/project_model/src/rustc_cfg.rs
blob: 012eab256ab4b76fa81a09d222033f7b8d572733 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//! Runs `rustc --print cfg` to get built-in cfg flags.

use std::process::Command;

use anyhow::Result;
use paths::AbsPath;

use crate::{cfg_flag::CfgFlag, utf8_stdout};

pub(crate) fn get(cargo_toml: Option<&AbsPath>, target: Option<&str>) -> Vec<CfgFlag> {
    let _p = profile::span("rustc_cfg::get");
    let mut res = Vec::with_capacity(6 * 2 + 1);

    // Some nightly-only cfgs, which are required for stdlib
    res.push(CfgFlag::Atom("target_thread_local".into()));
    for &ty in ["8", "16", "32", "64", "cas", "ptr"].iter() {
        for &key in ["target_has_atomic", "target_has_atomic_load_store"].iter() {
            res.push(CfgFlag::KeyValue { key: key.to_string(), value: ty.into() });
        }
    }

    match get_rust_cfgs(cargo_toml, target) {
        Ok(rustc_cfgs) => res.extend(rustc_cfgs.lines().map(|it| it.parse().unwrap())),
        Err(e) => log::error!("failed to get rustc cfgs: {:#}", e),
    }

    res
}

fn get_rust_cfgs(cargo_toml: Option<&AbsPath>, target: Option<&str>) -> Result<String> {
    let cargo_rust_cfgs = match cargo_toml {
        Some(cargo_toml) => {
            let mut cargo_config = Command::new(toolchain::cargo());
            cargo_config
                .current_dir(cargo_toml.parent().unwrap())
                .args(&["-Z", "unstable-options", "rustc", "--print", "cfg"])
                .env("RUSTC_BOOTSTRAP", "1");
            if let Some(target) = target {
                cargo_config.args(&["--target", target]);
            }
            utf8_stdout(cargo_config).ok()
        }
        None => None,
    };
    match cargo_rust_cfgs {
        Some(stdout) => Ok(stdout),
        None => {
            // using unstable cargo features failed, fall back to using plain rustc
            let mut cmd = Command::new(toolchain::rustc());
            cmd.args(&["--print", "cfg", "-O"]);
            if let Some(target) = target {
                cmd.args(&["--target", target]);
            }
            utf8_stdout(cmd)
        }
    }
}