Unnamed repository; edit this file 'description' to name the repository.
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
//! Functionality to discover the current build target(s).
use std::path::Path;

use anyhow::Context;
use rustc_hash::FxHashMap;
use toolchain::Tool;

use crate::{
    Sysroot, cargo_config_file::CargoConfigFile, toolchain_info::QueryConfig, utf8_stdout,
};

/// For cargo, runs `cargo -Zunstable-options config get build.target` to get the configured project target(s).
/// For rustc, runs `rustc --print -vV` to get the host target.
pub fn get(
    config: QueryConfig<'_>,
    target: Option<&str>,
    extra_env: &FxHashMap<String, Option<String>>,
) -> anyhow::Result<Vec<String>> {
    let _p = tracing::info_span!("target_tuple::get").entered();
    if let Some(target) = target {
        return Ok(vec![target.to_owned()]);
    }

    let (sysroot, current_dir) = match config {
        QueryConfig::Cargo(sysroot, cargo_toml, config_file) => {
            match config_file.as_ref().and_then(cargo_config_build_target) {
                Some(it) => return Ok(it),
                None => (sysroot, cargo_toml.parent().as_ref()),
            }
        }
        QueryConfig::Rustc(sysroot, current_dir) => (sysroot, current_dir),
    };
    rustc_discover_host_tuple(extra_env, sysroot, current_dir).map(|it| vec![it])
}

fn rustc_discover_host_tuple(
    extra_env: &FxHashMap<String, Option<String>>,
    sysroot: &Sysroot,
    current_dir: &Path,
) -> anyhow::Result<String> {
    let mut cmd = sysroot.tool(Tool::Rustc, current_dir, extra_env);
    cmd.arg("-vV");
    let stdout = utf8_stdout(&mut cmd)
        .with_context(|| format!("unable to discover host platform via `{cmd:?}`"))?;
    let field = "host: ";
    let target = stdout.lines().find_map(|l| l.strip_prefix(field));
    if let Some(target) = target {
        Ok(target.to_owned())
    } else {
        // If we fail to resolve the host platform, it's not the end of the world.
        Err(anyhow::format_err!("rustc -vV did not report host platform, got:\n{}", stdout))
    }
}

fn cargo_config_build_target(config: &CargoConfigFile) -> Option<Vec<String>> {
    match parse_toml_cargo_config_build_target(config) {
        Ok(v) => v,
        Err(e) => {
            tracing::debug!("Failed to discover cargo config build target {e:?}");
            None
        }
    }
}

// Parses `"build.target = [target-tuple, target-tuple, ...]"` or `"build.target = "target-tuple"`
fn parse_toml_cargo_config_build_target(
    config: &CargoConfigFile,
) -> anyhow::Result<Option<Vec<String>>> {
    let Some(config_reader) = config.read() else {
        return Ok(None);
    };
    let Some(target) = config_reader.get_spanned(["build", "target"]) else {
        return Ok(None);
    };

    // if the target ends with `.json`, join it to the config file's parent dir.
    // See https://github.com/rust-lang/cargo/blob/f7acf448fc127df9a77c52cc2bba027790ac4931/src/cargo/core/compiler/compile_kind.rs#L171-L192
    let join_to_origin_if_json_path = |s: &str, spanned: &toml::Spanned<toml::de::DeValue<'_>>| {
        if s.ends_with(".json") {
            config_reader
                .get_origin_root(spanned)
                .map(|p| p.join(s).to_string())
                .unwrap_or_else(|| s.to_owned())
        } else {
            s.to_owned()
        }
    };

    let parse_err = "Failed to parse `build.target` as an array of target";

    match target.as_ref() {
        toml::de::DeValue::String(s) => {
            Ok(Some(vec![join_to_origin_if_json_path(s.as_ref(), target)]))
        }
        toml::de::DeValue::Array(arr) => arr
            .iter()
            .map(|v| {
                let s = v.as_ref().as_str().context(parse_err)?;
                Ok(join_to_origin_if_json_path(s, v))
            })
            .collect::<anyhow::Result<_>>()
            .map(Option::Some),
        _ => Err(anyhow::anyhow!(parse_err)),
    }
}

#[cfg(test)]
mod tests {
    use paths::{AbsPathBuf, Utf8PathBuf};

    use crate::{ManifestPath, Sysroot};

    use super::*;

    #[test]
    fn cargo() {
        let manifest_path = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");
        let sysroot = Sysroot::empty();
        let manifest_path =
            ManifestPath::try_from(AbsPathBuf::assert(Utf8PathBuf::from(manifest_path))).unwrap();
        let cfg = QueryConfig::Cargo(&sysroot, &manifest_path, &None);
        assert!(get(cfg, None, &FxHashMap::default()).is_ok());
    }

    #[test]
    fn rustc() {
        let sysroot = Sysroot::empty();
        let cfg = QueryConfig::Rustc(&sysroot, env!("CARGO_MANIFEST_DIR").as_ref());
        assert!(get(cfg, None, &FxHashMap::default()).is_ok());
    }
}
SyntaxToken, } impl std::fmt::Display for Byte { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for Byte { fn can_cast(kind: SyntaxKind) -> bool { kind == BYTE } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for Byte { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Byte").field("syntax", &self.syntax).finish() } } impl Clone for Byte { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for Byte { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for Byte {} impl PartialEq for Byte { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } } pub struct ByteString { pub(crate) syntax: SyntaxToken, } impl std::fmt::Display for ByteString { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for ByteString { fn can_cast(kind: SyntaxKind) -> bool { kind == BYTE_STRING } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for ByteString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ByteString").field("syntax", &self.syntax).finish() } } impl Clone for ByteString { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for ByteString { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for ByteString {} impl PartialEq for ByteString { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } } pub struct CString { pub(crate) syntax: SyntaxToken, } impl std::fmt::Display for CString { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for CString { fn can_cast(kind: SyntaxKind) -> bool { kind == C_STRING } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for CString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("CString").field("syntax", &self.syntax).finish() } } impl Clone for CString { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for CString { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for CString {} impl PartialEq for CString { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } } pub struct Char { pub(crate) syntax: SyntaxToken, } impl std::fmt::Display for Char { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for Char { fn can_cast(kind: SyntaxKind) -> bool { kind == CHAR } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for Char { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Char").field("syntax", &self.syntax).finish() } } impl Clone for Char { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for Char { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for Char {} impl PartialEq for Char { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } } pub struct Comment { pub(crate) syntax: SyntaxToken, } impl std::fmt::Display for Comment { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for Comment { fn can_cast(kind: SyntaxKind) -> bool { kind == COMMENT } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for Comment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Comment").field("syntax", &self.syntax).finish() } } impl Clone for Comment { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for Comment { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for Comment {} impl PartialEq for Comment { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } } pub struct FloatNumber { pub(crate) syntax: SyntaxToken, } impl std::fmt::Display for FloatNumber { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for FloatNumber { fn can_cast(kind: SyntaxKind) -> bool { kind == FLOAT_NUMBER } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for FloatNumber { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FloatNumber").field("syntax", &self.syntax).finish() } } impl Clone for FloatNumber { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for FloatNumber { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for FloatNumber {} impl PartialEq for FloatNumber { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } } pub struct Ident { pub(crate) syntax: SyntaxToken, } impl std::fmt::Display for Ident { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for Ident { fn can_cast(kind: SyntaxKind) -> bool { kind == IDENT } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for Ident { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Ident").field("syntax", &self.syntax).finish() } } impl Clone for Ident { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for Ident { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for Ident {} impl PartialEq for Ident { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } } pub struct IntNumber { pub(crate) syntax: SyntaxToken, } impl std::fmt::Display for IntNumber { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for IntNumber { fn can_cast(kind: SyntaxKind) -> bool { kind == INT_NUMBER } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for IntNumber { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("IntNumber").field("syntax", &self.syntax).finish() } } impl Clone for IntNumber { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for IntNumber { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for IntNumber {} impl PartialEq for IntNumber { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } } pub struct String { pub(crate) syntax: SyntaxToken, } impl std::fmt::Display for String { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for String { fn can_cast(kind: SyntaxKind) -> bool { kind == STRING } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for String { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("String").field("syntax", &self.syntax).finish() } } impl Clone for String { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for String { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for String {} impl PartialEq for String { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } } pub struct Whitespace { pub(crate) syntax: SyntaxToken, } impl std::fmt::Display for Whitespace { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.syntax, f) } } impl AstToken for Whitespace { fn can_cast(kind: SyntaxKind) -> bool { kind == WHITESPACE } fn cast(syntax: SyntaxToken) -> Option<Self> { if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None } } fn syntax(&self) -> &SyntaxToken { &self.syntax } } impl fmt::Debug for Whitespace { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Whitespace").field("syntax", &self.syntax).finish() } } impl Clone for Whitespace { fn clone(&self) -> Self { Self { syntax: self.syntax.clone() } } } impl hash::Hash for Whitespace { fn hash<H: hash::Hasher>(&self, state: &mut H) { self.syntax.hash(state); } } impl Eq for Whitespace {} impl PartialEq for Whitespace { fn eq(&self, other: &Self) -> bool { self.syntax == other.syntax } }