Skip to main content

project_model/toolchain_info/
target_data.rs

1//! Runs `rustc --print target-spec-json` to get the target_data_layout.
2
3use anyhow::Context;
4use base_db::target;
5use rustc_hash::FxHashMap;
6use serde_derive::Deserialize;
7use toolchain::Tool;
8
9use crate::{Sysroot, toolchain_info::QueryConfig, utf8_stdout};
10
11#[derive(Debug, Deserialize)]
12#[serde(rename_all = "kebab-case")]
13pub enum Arch {
14    Wasm32,
15    Wasm64,
16    #[serde(other)]
17    Other,
18}
19
20impl From<Arch> for target::Arch {
21    fn from(value: Arch) -> Self {
22        match value {
23            Arch::Wasm32 => target::Arch::Wasm32,
24            Arch::Wasm64 => target::Arch::Wasm64,
25            Arch::Other => target::Arch::Other,
26        }
27    }
28}
29
30#[derive(Debug, Deserialize)]
31#[serde(rename_all = "kebab-case")]
32pub struct TargetSpec {
33    pub data_layout: String,
34    pub arch: Arch,
35}
36
37/// Uses `rustc --print target-spec-json`.
38pub fn get(
39    config: QueryConfig<'_>,
40    target: Option<&str>,
41    extra_env: &FxHashMap<String, Option<String>>,
42    version: Option<&semver::Version>,
43) -> anyhow::Result<target::TargetData> {
44    const RUSTC_ARGS: [&str; 2] = ["--print", "target-spec-json"];
45    let process = |output: String| {
46        let target_spec = serde_json::from_str::<TargetSpec>(&output).map_err(|_| {
47            anyhow::format_err!("could not parse target-spec-json from command output")
48        })?;
49        Ok(target::TargetData {
50            arch: target_spec.arch.into(),
51            data_layout: target_spec.data_layout.into_boxed_str(),
52        })
53    };
54    let (sysroot, current_dir) = match config {
55        QueryConfig::Cargo(sysroot, cargo_toml, _) => {
56            let mut cmd = sysroot.tool(Tool::Cargo, cargo_toml.parent(), extra_env);
57            cmd.env("RUSTC_BOOTSTRAP", "1");
58            cmd.args(["rustc", "-Z", "unstable-options"]).args(RUSTC_ARGS);
59            toolchain::cargo_use_targets(version, &mut cmd, target.as_slice());
60            cmd.args(["--", "-Z", "unstable-options"]);
61            match utf8_stdout(&mut cmd) {
62                Ok(output) => return process(output),
63                Err(e) => {
64                    tracing::warn!(%e, "failed to run `{cmd:?}`, falling back to invoking rustc directly");
65                    (sysroot, cargo_toml.parent().as_ref())
66                }
67            }
68        }
69        QueryConfig::Rustc(sysroot, current_dir) => (sysroot, current_dir),
70    };
71
72    let mut cmd = Sysroot::tool(sysroot, Tool::Rustc, current_dir, extra_env);
73    cmd.env("RUSTC_BOOTSTRAP", "1").args(["-Z", "unstable-options"]).args(RUSTC_ARGS);
74    if let Some(target) = target {
75        cmd.args(["--target", target]);
76    }
77    utf8_stdout(&mut cmd)
78        .with_context(|| format!("unable to fetch target-data-layout via `{cmd:?}`"))
79        .and_then(process)
80}
81
82#[cfg(test)]
83mod tests {
84    use paths::{AbsPathBuf, Utf8PathBuf};
85
86    use crate::{ManifestPath, Sysroot};
87
88    use super::*;
89
90    #[test]
91    fn cargo() {
92        let manifest_path = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");
93        let sysroot = Sysroot::empty();
94        let manifest_path =
95            ManifestPath::try_from(AbsPathBuf::assert(Utf8PathBuf::from(manifest_path))).unwrap();
96        let cfg = QueryConfig::Cargo(&sysroot, &manifest_path, &None);
97        let extra_env = &FxHashMap::default();
98        let Ok(version) = super::super::version::get(cfg, extra_env) else { return };
99        assert!(get(cfg, None, extra_env, version.as_ref()).is_ok());
100    }
101
102    #[test]
103    fn rustc() {
104        let sysroot = Sysroot::empty();
105        let cfg = QueryConfig::Rustc(&sysroot, env!("CARGO_MANIFEST_DIR").as_ref());
106        let extra_env = &FxHashMap::default();
107        let Ok(version) = super::super::version::get(cfg, extra_env) else { return };
108        assert!(get(cfg, None, extra_env, version.as_ref()).is_ok());
109    }
110}