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