Skip to main content

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#![expect(internal_features)]
12#![feature(iter_intersperse)]
13#![feature(rustc_attrs)]
14// tidy-alphabetical-end
15
16use std::path::{Path, PathBuf};
17
18pub mod asm;
19pub mod callconv;
20pub mod json;
21pub mod spec;
22pub mod target_features;
23
24#[cfg(test)]
25mod tests;
26
27/// The name of rustc's own place to organize libraries.
28///
29/// Used to be `rustc`, now the default is `rustlib`.
30const RUST_LIB_DIR: &str = "rustlib";
31
32/// Returns a `rustlib` path for this particular target, relative to the provided sysroot.
33///
34/// For example: `target_sysroot_path("/usr", "x86_64-unknown-linux-gnu")` =>
35/// `"lib*/rustlib/x86_64-unknown-linux-gnu"`.
36pub fn relative_target_rustlib_path(sysroot: &Path, target_triple: &str) -> PathBuf {
37    let libdir = find_relative_libdir(sysroot);
38    Path::new(libdir.as_ref()).join(RUST_LIB_DIR).join(target_triple)
39}
40
41/// The name of the directory rustc expects libraries to be located.
42fn find_relative_libdir(sysroot: &Path) -> std::borrow::Cow<'static, str> {
43    // FIXME: This is a quick hack to make the rustc binary able to locate
44    // Rust libraries in Linux environments where libraries might be installed
45    // to lib64/lib32. This would be more foolproof by basing the sysroot off
46    // of the directory where `librustc_driver` is located, rather than
47    // where the rustc binary is.
48    // If --libdir is set during configuration to the value other than
49    // "lib" (i.e., non-default), this value is used (see issue #16552).
50
51    #[cfg(target_pointer_width = "64")]
52    const PRIMARY_LIB_DIR: &str = "lib64";
53
54    #[cfg(target_pointer_width = "32")]
55    const PRIMARY_LIB_DIR: &str = "lib32";
56
57    const SECONDARY_LIB_DIR: &str = "lib";
58
59    match ::core::option::Option::Some("lib")option_env!("CFG_LIBDIR_RELATIVE") {
60        None | Some("lib") => {
61            if sysroot.join(PRIMARY_LIB_DIR).join(RUST_LIB_DIR).exists() {
62                PRIMARY_LIB_DIR.into()
63            } else {
64                SECONDARY_LIB_DIR.into()
65            }
66        }
67        Some(libdir) => libdir.into(),
68    }
69}
70
71macro_rules! target_spec_enum {
72    (
73        $( #[$attr:meta] )*
74        pub enum $Name:ident {
75            $(
76                $( #[$variant_attr:meta] )*
77                $Variant:ident = $string:literal $(,$alias:literal)* ,
78            )*
79        }
80        parse_error_type = $parse_error_type:literal;
81    ) => {
82        $( #[$attr] )*
83        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
84        #[derive(schemars::JsonSchema)]
85        pub enum $Name {
86            $(
87                $( #[$variant_attr] )*
88                #[serde(rename = $string)] // for JSON schema generation only
89                $( #[serde(alias = $alias)] )*
90                $Variant,
91            )*
92        }
93
94        impl FromStr for $Name {
95            type Err = String;
96
97            fn from_str(s: &str) -> Result<Self, Self::Err> {
98                Ok(match s {
99                    $(
100                        $string => Self::$Variant,
101                        $($alias => Self::$Variant,)*
102                    )*
103                    _ => {
104                        let all = [$( concat!("'", $string, "'") ),*].join(", ");
105                        return Err(format!("invalid {}: '{s}'. allowed values: {all}", $parse_error_type));
106                    }
107                })
108            }
109        }
110
111        impl $Name {
112            pub const ALL: &'static [$Name] = &[ $( $Name::$Variant, )* ];
113            pub fn desc(&self) -> &'static str {
114                match self {
115                    $( Self::$Variant => $string, )*
116                }
117            }
118        }
119
120        crate::target_spec_enum!(@common_impls $Name);
121    };
122
123    (
124        $( #[$attr:meta] )*
125        pub enum $Name:ident {
126            $(
127                $( #[$variant_attr:meta] )*
128                $Variant:ident = $string:literal $(,$alias:literal)* ,
129            )*
130        }
131        $( #[$other_variant_attr:meta] )*
132        other_variant = $OtherVariant:ident;
133    ) => {
134        $( #[$attr] )*
135        #[derive(Clone, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
136        pub enum $Name {
137            $(
138                $( #[$variant_attr:meta] )*
139                 $( #[serde(alias = $alias)] )*
140                $Variant,
141            )*
142            /// The vast majority of the time, the compiler deals with a fixed
143            /// set of values, so it is convenient for them to be represented in
144            /// an enum. However, it is possible to have arbitrary values in a
145            /// target JSON file (which can be parsed when `--target` is
146            /// specified). This might occur, for example, for an out-of-tree
147            /// codegen backend that supports a value (e.g. architecture or OS)
148            /// that rustc currently doesn't know about. This variant exists as
149            /// an escape hatch for such cases.
150            $( #[$other_variant_attr] )*
151            $OtherVariant(crate::spec::StaticCow<str>),
152        }
153
154        impl schemars::JsonSchema for $Name {
155            fn schema_name() -> std::borrow::Cow<'static, str> {
156                std::borrow::Cow::Borrowed(stringify!($Name))
157            }
158
159            fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
160                schemars::json_schema!({
161                    "type": "string"
162                })
163            }
164        }
165
166        impl FromStr for $Name {
167            type Err = core::convert::Infallible;
168
169            fn from_str(s: &str) -> Result<Self, Self::Err> {
170                Ok(match s {
171                    $(
172                        $string => Self::$Variant,
173                        $($alias => Self::$Variant,)*
174                    )*
175                    _ => Self::$OtherVariant(s.to_owned().into()),
176                })
177            }
178        }
179
180        impl $Name {
181            pub fn desc(&self) -> &str {
182                match self {
183                    $( Self::$Variant => $string, )*
184                    Self::$OtherVariant(name) => name.as_ref(),
185                }
186            }
187        }
188
189        crate::target_spec_enum!(@common_impls $Name);
190    };
191
192    (@common_impls $Name:ident) => {
193        impl crate::json::ToJson for $Name {
194            fn to_json(&self) -> crate::json::Json {
195                self.desc().to_json()
196            }
197        }
198
199        crate::json::serde_deserialize_from_str!($Name);
200
201
202        impl std::fmt::Display for $Name {
203            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204                f.write_str(self.desc())
205            }
206        }
207    };
208}
209use target_spec_enum;