project_model/toolchain_info/
target_data.rs1use 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
37pub fn get(
39 config: QueryConfig<'_>,
40 target: Option<&str>,
41 extra_env: &FxHashMap<String, Option<String>>,
42) -> anyhow::Result<target::TargetData> {
43 const RUSTC_ARGS: [&str; 2] = ["--print", "target-spec-json"];
44 let process = |output: String| {
45 let target_spec = serde_json::from_str::<TargetSpec>(&output).map_err(|_| {
46 anyhow::format_err!("could not parse target-spec-json from command output")
47 })?;
48 Ok(target::TargetData {
49 arch: target_spec.arch.into(),
50 data_layout: target_spec.data_layout.into_boxed_str(),
51 })
52 };
53 let (sysroot, current_dir) = match config {
54 QueryConfig::Cargo(sysroot, cargo_toml, _) => {
55 let mut cmd = sysroot.tool(Tool::Cargo, cargo_toml.parent(), extra_env);
56 cmd.env("RUSTC_BOOTSTRAP", "1");
57 cmd.args(["rustc", "-Z", "unstable-options"]).args(RUSTC_ARGS);
58 if let Some(target) = target {
59 cmd.args(["--target", target]);
60 }
61 cmd.args(["--", "-Z", "unstable-options"]);
62 match utf8_stdout(&mut cmd) {
63 Ok(output) => return process(output),
64 Err(e) => {
65 tracing::warn!(%e, "failed to run `{cmd:?}`, falling back to invoking rustc directly");
66 (sysroot, cargo_toml.parent().as_ref())
67 }
68 }
69 }
70 QueryConfig::Rustc(sysroot, current_dir) => (sysroot, current_dir),
71 };
72
73 let mut cmd = Sysroot::tool(sysroot, Tool::Rustc, current_dir, extra_env);
74 cmd.env("RUSTC_BOOTSTRAP", "1").args(["-Z", "unstable-options"]).args(RUSTC_ARGS);
75 if let Some(target) = target {
76 cmd.args(["--target", target]);
77 }
78 utf8_stdout(&mut cmd)
79 .with_context(|| format!("unable to fetch target-data-layout via `{cmd:?}`"))
80 .and_then(process)
81}
82
83#[cfg(test)]
84mod tests {
85 use paths::{AbsPathBuf, Utf8PathBuf};
86
87 use crate::{ManifestPath, Sysroot};
88
89 use super::*;
90
91 #[test]
92 fn cargo() {
93 let manifest_path = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");
94 let sysroot = Sysroot::empty();
95 let manifest_path =
96 ManifestPath::try_from(AbsPathBuf::assert(Utf8PathBuf::from(manifest_path))).unwrap();
97 let cfg = QueryConfig::Cargo(&sysroot, &manifest_path, &None);
98 assert!(get(cfg, None, &FxHashMap::default()).is_ok());
99 }
100
101 #[test]
102 fn rustc() {
103 let sysroot = Sysroot::empty();
104 let cfg = QueryConfig::Rustc(&sysroot, env!("CARGO_MANIFEST_DIR").as_ref());
105 assert!(get(cfg, None, &FxHashMap::default()).is_ok());
106 }
107}