rustc_target/
lib.rs

1//! Some stuff used by rustc that doesn't have many dependencies
2//!
3//! Originally extracted from rustc::back, which was nominally the
4//! compiler 'backend', though LLVM is rustc's backend, so rustc_target
5//! is really just odds-and-ends relating to code gen and linking.
6//! This crate mostly exists to make rustc smaller, so we might put
7//! more 'stuff' here in the future. It does not have a dependency on
8//! LLVM.
9
10// tidy-alphabetical-start
11#![allow(internal_features)]
12#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
13#![doc(rust_logo)]
14#![feature(debug_closure_helpers)]
15#![feature(iter_intersperse)]
16#![feature(rustdoc_internals)]
17// tidy-alphabetical-end
18
19use std::path::{Path, PathBuf};
20
21pub mod asm;
22pub mod callconv;
23pub mod json;
24pub mod spec;
25pub mod target_features;
26
27#[cfg(test)]
28mod tests;
29
30use rustc_abi::HashStableContext;
31
32/// The name of rustc's own place to organize libraries.
33///
34/// Used to be `rustc`, now the default is `rustlib`.
35const RUST_LIB_DIR: &str = "rustlib";
36
37/// Returns a `rustlib` path for this particular target, relative to the provided sysroot.
38///
39/// For example: `target_sysroot_path("/usr", "x86_64-unknown-linux-gnu")` =>
40/// `"lib*/rustlib/x86_64-unknown-linux-gnu"`.
41pub fn relative_target_rustlib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
42    let libdir = find_relative_libdir(sysroot);
43    Path::new(libdir.as_ref()).join(RUST_LIB_DIR).join(target_triple)
44}
45
46/// The name of the directory rustc expects libraries to be located.
47fn find_relative_libdir(sysroot: &Path) -> std::borrow::Cow<'static, str> {
48    // FIXME: This is a quick hack to make the rustc binary able to locate
49    // Rust libraries in Linux environments where libraries might be installed
50    // to lib64/lib32. This would be more foolproof by basing the sysroot off
51    // of the directory where `librustc_driver` is located, rather than
52    // where the rustc binary is.
53    // If --libdir is set during configuration to the value other than
54    // "lib" (i.e., non-default), this value is used (see issue #16552).
55
56    #[cfg(target_pointer_width = "64")]
57    const PRIMARY_LIB_DIR: &str = "lib64";
58
59    #[cfg(target_pointer_width = "32")]
60    const PRIMARY_LIB_DIR: &str = "lib32";
61
62    const SECONDARY_LIB_DIR: &str = "lib";
63
64    match option_env!("CFG_LIBDIR_RELATIVE") {
65        None | Some("lib") => {
66            if sysroot.join(PRIMARY_LIB_DIR).join(RUST_LIB_DIR).exists() {
67                PRIMARY_LIB_DIR.into()
68            } else {
69                SECONDARY_LIB_DIR.into()
70            }
71        }
72        Some(libdir) => libdir.into(),
73    }
74}
75
76macro_rules! target_spec_enum {
77    (
78        $( #[$attr:meta] )*
79        pub enum $name:ident {
80            $(
81                $( #[$variant_attr:meta] )*
82                $variant:ident = $string:literal,
83            )*
84        }
85        parse_error_type = $parse_error_type:literal;
86    ) => {
87        $( #[$attr] )*
88        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
89        #[derive(schemars::JsonSchema)]
90        pub enum $name {
91            $(
92                $( #[$variant_attr] )*
93                #[serde(rename = $string)] // for JSON schema generation only
94                $variant,
95            )*
96        }
97
98        impl FromStr for $name {
99            type Err = String;
100
101            fn from_str(s: &str) -> Result<Self, Self::Err> {
102                Ok(match s {
103                    $( $string => Self::$variant, )*
104                    _ => {
105                        let all = [$( concat!("'", $string, "'") ),*].join(", ");
106                        return Err(format!("invalid {}: '{s}'. allowed values: {all}", $parse_error_type));
107                    }
108                })
109            }
110        }
111
112        impl $name {
113            pub fn desc(&self) -> &'static str {
114                match self {
115                    $( Self::$variant => $string, )*
116                }
117            }
118        }
119
120        impl crate::json::ToJson for $name {
121            fn to_json(&self) -> crate::json::Json {
122                self.desc().to_json()
123            }
124        }
125
126        crate::json::serde_deserialize_from_str!($name);
127
128
129        impl std::fmt::Display for $name {
130            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131                f.write_str(self.desc())
132            }
133        }
134    };
135}
136use target_spec_enum;