1#![deny(unused_extern_crates)]
4#![deny(clippy::missing_docs_in_private_items)]
5#![allow(deprecated)]
6
7use std::str::FromStr;
8use std::{fmt, io};
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
12#[repr(transparent)]
13pub struct RustTarget(Version);
14
15impl RustTarget {
16 pub fn stable(minor: u64, patch: u64) -> Result<Self, InvalidRustTarget> {
18 let target = Self(Version::Stable(minor, patch));
19
20 if target < EARLIEST_STABLE_RUST {
21 return Err(InvalidRustTarget::TooEarly);
22 }
23
24 Ok(target)
25 }
26
27 const fn minor(&self) -> Option<u64> {
28 match self.0 {
29 Version::Nightly => None,
30 Version::Stable(minor, _) => Some(minor),
31 }
32 }
33
34 const fn is_compatible(&self, other: &Self) -> bool {
35 match (self.0, other.0) {
36 (Version::Stable(minor, _), Version::Stable(other_minor, _)) => {
37 minor >= other_minor
40 }
41 (Version::Nightly, _) => true,
43 (Version::Stable { .. }, Version::Nightly) => false,
45 }
46 }
47}
48
49impl Default for RustTarget {
50 fn default() -> Self {
51 #[cfg(not(feature = "__cli"))]
54 {
55 use std::env;
56 use std::iter;
57 use std::process::Command;
58 use std::sync::OnceLock;
59
60 static CURRENT_RUST: OnceLock<Option<RustTarget>> = OnceLock::new();
61
62 if let Some(current_rust) = *CURRENT_RUST.get_or_init(|| {
63 let is_build_script =
64 env::var_os("CARGO_CFG_TARGET_ARCH").is_some();
65 if !is_build_script {
66 return None;
67 }
68
69 let rustc = env::var_os("RUSTC")?;
70 let rustc_wrapper = env::var_os("RUSTC_WRAPPER")
71 .filter(|wrapper| !wrapper.is_empty());
72 let wrapped_rustc =
73 rustc_wrapper.iter().chain(iter::once(&rustc));
74
75 let mut is_clippy_driver = false;
76 loop {
77 let mut wrapped_rustc = wrapped_rustc.clone();
78 let mut command =
79 Command::new(wrapped_rustc.next().unwrap());
80 command.args(wrapped_rustc);
81 if is_clippy_driver {
82 command.arg("--rustc");
83 }
84 command.arg("--version");
85
86 let output = command.output().ok()?;
87 let string = String::from_utf8(output.stdout).ok()?;
88
89 let last_line = string.lines().last().unwrap_or(&string);
91 let (program, rest) = last_line.trim().split_once(' ')?;
92 if program != "rustc" {
93 if program.starts_with("clippy") && !is_clippy_driver {
94 is_clippy_driver = true;
95 continue;
96 }
97 return None;
98 }
99
100 let number = rest.split([' ', '-', '+']).next()?;
101 break RustTarget::from_str(number).ok();
102 }
103 }) {
104 return current_rust;
105 }
106 }
107
108 LATEST_STABLE_RUST
112 }
113}
114
115impl fmt::Display for RustTarget {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 match self.0 {
118 Version::Stable(minor, patch) => write!(f, "1.{minor}.{patch}"),
119 Version::Nightly => "nightly".fmt(f),
120 }
121 }
122}
123
124#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
125enum Version {
126 Stable(u64, u64),
127 Nightly,
128}
129
130#[derive(Debug, PartialEq, Eq, Hash)]
131pub enum InvalidRustTarget {
132 TooEarly,
133}
134
135impl fmt::Display for InvalidRustTarget {
136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 match self {
138 Self::TooEarly => write!(f, "the earliest Rust version supported by bindgen is {EARLIEST_STABLE_RUST}"),
139 }
140 }
141}
142
143macro_rules! define_rust_editions {
145 ($($variant:ident($value:literal) => $minor:literal,)*) => {
146 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
147 #[doc = "Represents Rust Edition for the generated bindings"]
148 pub enum RustEdition {
149 $(
150 #[doc = concat!("The ", stringify!($value), " edition of Rust.")]
151 $variant,
152 )*
153 }
154
155 impl FromStr for RustEdition {
156 type Err = InvalidRustEdition;
157
158 fn from_str(s: &str) -> Result<Self, Self::Err> {
159 match s {
160 $(stringify!($value) => Ok(Self::$variant),)*
161 _ => Err(InvalidRustEdition(s.to_owned())),
162 }
163 }
164 }
165
166 impl fmt::Display for RustEdition {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 match self {
169 $(Self::$variant => stringify!($value).fmt(f),)*
170 }
171 }
172 }
173
174 impl RustEdition {
175 pub(crate) const ALL: [Self; [$($value,)*].len()] = [$(Self::$variant,)*];
176
177 pub(crate) fn is_available(self, target: RustTarget) -> bool {
178 let Some(minor) = target.minor() else {
179 return true;
180 };
181
182 match self {
183 $(Self::$variant => $minor <= minor,)*
184 }
185 }
186 }
187 }
188}
189
190#[derive(Debug)]
191pub struct InvalidRustEdition(String);
192
193impl fmt::Display for InvalidRustEdition {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 write!(f, "\"{}\" is not a valid Rust edition", self.0)
196 }
197}
198
199impl std::error::Error for InvalidRustEdition {}
200
201define_rust_editions! {
202 Edition2018(2018) => 31,
203 Edition2021(2021) => 56,
204 Edition2024(2024) => 85,
205}
206
207impl RustTarget {
208 pub(crate) fn latest_edition(self) -> RustEdition {
210 RustEdition::ALL
211 .iter()
212 .rev()
213 .find(|edition| edition.is_available(self))
214 .copied()
215 .expect("bindgen should always support at least one edition")
216 }
217}
218
219impl Default for RustEdition {
220 fn default() -> Self {
221 RustTarget::default().latest_edition()
222 }
223}
224
225macro_rules! define_rust_targets {
227 (
228 Nightly => {$($nightly_feature:ident $(($nightly_edition:literal))|* $(: #$issue:literal)?),* $(,)?} $(,)?
229 $(
230 $variant:ident($minor:literal) => {$($feature:ident $(($edition:literal))|* $(: #$pull:literal)?),* $(,)?},
231 )*
232 $(,)?
233 ) => {
234
235 impl RustTarget {
236 $(#[doc = concat!(
238 "- [`", stringify!($nightly_feature), "`]",
239 "(", $("https://github.com/rust-lang/rust/pull/", stringify!($issue),)* ")",
240 )])*
241 #[deprecated = "The use of this constant is deprecated, please use `RustTarget::nightly` instead."]
242 pub const Nightly: Self = Self::nightly();
243
244 $(#[doc = concat!(
246 "- [`", stringify!($nightly_feature), "`]",
247 "(", $("https://github.com/rust-lang/rust/pull/", stringify!($issue),)* ")",
248 )])*
249 pub const fn nightly() -> Self {
250 Self(Version::Nightly)
251 }
252
253 $(
254 #[doc = concat!("Version 1.", stringify!($minor), " of Rust, which introduced the following features:")]
255 $(#[doc = concat!(
256 "- [`", stringify!($feature), "`]",
257 "(", $("https://github.com/rust-lang/rust/pull/", stringify!($pull),)* ")",
258 )])*
259 #[deprecated = "The use of this constant is deprecated, please use `RustTarget::stable` instead."]
260 pub const $variant: Self = Self(Version::Stable($minor, 0));
261 )*
262
263 const fn stable_releases() -> [(Self, u64); [$($minor,)*].len()] {
264 [$((Self::$variant, $minor),)*]
265 }
266 }
267
268 #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
269 pub(crate) struct RustFeatures {
270 $($(pub(crate) $feature: bool,)*)*
271 $(pub(crate) $nightly_feature: bool,)*
272 }
273
274 impl RustFeatures {
275 pub(crate) fn new(target: RustTarget, edition: RustEdition) -> Self {
277 let mut features = Self {
278 $($($feature: false,)*)*
279 $($nightly_feature: false,)*
280 };
281
282 if target.is_compatible(&RustTarget::nightly()) {
283 $(
284 let editions: &[RustEdition] = &[$(stringify!($nightly_edition).parse::<RustEdition>().ok().expect("invalid edition"),)*];
285
286 if editions.is_empty() || editions.contains(&edition) {
287 features.$nightly_feature = true;
288 }
289 )*
290 }
291
292 $(
293 if target.is_compatible(&RustTarget::$variant) {
294 $(
295 let editions: &[RustEdition] = &[$(stringify!($edition).parse::<RustEdition>().ok().expect("invalid edition"),)*];
296
297 if editions.is_empty() || editions.contains(&edition) {
298 features.$feature = true;
299 }
300 )*
301 }
302 )*
303
304 features
305 }
306 }
307 };
308}
309
310define_rust_targets! {
314 Nightly => {
315 vectorcall_abi: #124485,
316 ptr_metadata: #81513,
317 layout_for_ptr: #69835,
318 },
319 Stable_1_82(82) => {
320 unsafe_extern_blocks: #127921,
321 },
322 Stable_1_77(77) => {
323 offset_of: #106655,
324 literal_cstr(2021)|(2024): #117472,
325 },
326 Stable_1_73(73) => { thiscall_abi: #42202 },
327 Stable_1_71(71) => { c_unwind_abi: #106075 },
328 Stable_1_68(68) => { abi_efiapi: #105795 },
329 Stable_1_64(64) => { core_ffi_c: #94503 },
330 Stable_1_51(51) => {
331 raw_ref_macros: #80886,
332 min_const_generics: #74878,
333 },
334 Stable_1_59(59) => { const_cstr: #54745 },
335 Stable_1_47(47) => { larger_arrays: #74060 },
336 Stable_1_43(43) => { associated_constants: #68952 },
337 Stable_1_40(40) => { non_exhaustive: #44109 },
338 Stable_1_36(36) => { maybe_uninit: #60445 },
339 Stable_1_33(33) => { repr_packed_n: #57049 },
340}
341
342pub const LATEST_STABLE_RUST: RustTarget = {
344 let targets = RustTarget::stable_releases();
354
355 let mut i = 0;
356 let mut latest_target = None;
357 let mut latest_minor = 0;
358
359 while i < targets.len() {
360 let (target, minor) = targets[i];
361
362 if latest_minor < minor {
363 latest_minor = minor;
364 latest_target = Some(target);
365 }
366
367 i += 1;
368 }
369
370 match latest_target {
371 Some(target) => target,
372 None => unreachable!(),
373 }
374};
375
376pub const EARLIEST_STABLE_RUST: RustTarget = {
378 let targets = RustTarget::stable_releases();
388
389 let mut i = 0;
390 let mut earliest_target = None;
391 let Some(mut earliest_minor) = LATEST_STABLE_RUST.minor() else {
392 unreachable!()
393 };
394
395 while i < targets.len() {
396 let (target, minor) = targets[i];
397
398 if earliest_minor > minor {
399 earliest_minor = minor;
400 earliest_target = Some(target);
401 }
402
403 i += 1;
404 }
405
406 match earliest_target {
407 Some(target) => target,
408 None => unreachable!(),
409 }
410};
411
412fn invalid_input(input: &str, msg: impl fmt::Display) -> io::Error {
413 io::Error::new(
414 io::ErrorKind::InvalidInput,
415 format!("\"{input}\" is not a valid Rust target, {msg}"),
416 )
417}
418
419impl FromStr for RustTarget {
420 type Err = io::Error;
421
422 fn from_str(input: &str) -> Result<Self, Self::Err> {
423 if input == "nightly" {
424 return Ok(Self::Nightly);
425 }
426
427 let Some((major_str, tail)) = input.split_once('.') else {
428 return Err(invalid_input(input, "accepted values are of the form \"1.71\", \"1.71.1\" or \"nightly\"." ) );
429 };
430
431 if major_str != "1" {
432 return Err(invalid_input(
433 input,
434 "The largest major version of Rust released is \"1\"",
435 ));
436 }
437
438 let (minor, patch) = if let Some((minor_str, patch_str)) =
439 tail.split_once('.')
440 {
441 let Ok(minor) = minor_str.parse::<u64>() else {
442 return Err(invalid_input(input, "the minor version number must be an unsigned 64-bit integer"));
443 };
444 let Ok(patch) = patch_str.parse::<u64>() else {
445 return Err(invalid_input(input, "the patch version number must be an unsigned 64-bit integer"));
446 };
447 (minor, patch)
448 } else {
449 let Ok(minor) = tail.parse::<u64>() else {
450 return Err(invalid_input(input, "the minor version number must be an unsigned 64-bit integer"));
451 };
452 (minor, 0)
453 };
454
455 Self::stable(minor, patch).map_err(|err| invalid_input(input, err))
456 }
457}
458
459impl RustFeatures {
460 pub(crate) fn new_with_latest_edition(target: RustTarget) -> Self {
463 Self::new(target, target.latest_edition())
464 }
465}
466
467impl Default for RustFeatures {
468 fn default() -> Self {
469 Self::new_with_latest_edition(RustTarget::default())
470 }
471}
472
473#[cfg(test)]
474mod test {
475 use super::*;
476
477 #[test]
478 fn release_versions_for_editions() {
479 assert_eq!(
480 "1.33".parse::<RustTarget>().unwrap().latest_edition(),
481 RustEdition::Edition2018
482 );
483 assert_eq!(
484 "1.56".parse::<RustTarget>().unwrap().latest_edition(),
485 RustEdition::Edition2021
486 );
487 assert_eq!(
488 "1.85".parse::<RustTarget>().unwrap().latest_edition(),
489 RustEdition::Edition2024
490 );
491 assert_eq!(
492 "nightly".parse::<RustTarget>().unwrap().latest_edition(),
493 RustEdition::Edition2024
494 );
495 }
496
497 #[test]
498 fn target_features() {
499 let features =
500 RustFeatures::new_with_latest_edition(RustTarget::Stable_1_71);
501 assert!(
502 features.c_unwind_abi &&
503 features.abi_efiapi &&
504 !features.thiscall_abi
505 );
506
507 let features = RustFeatures::new(
508 RustTarget::Stable_1_77,
509 RustEdition::Edition2018,
510 );
511 assert!(!features.literal_cstr);
512
513 let features =
514 RustFeatures::new_with_latest_edition(RustTarget::Stable_1_77);
515 assert!(features.literal_cstr);
516
517 let f_nightly =
518 RustFeatures::new_with_latest_edition(RustTarget::Nightly);
519 assert!(
520 f_nightly.vectorcall_abi &&
521 f_nightly.ptr_metadata &&
522 f_nightly.layout_for_ptr
523 );
524 }
525
526 fn test_target(input: &str, expected: RustTarget) {
527 let expected = RustFeatures::new_with_latest_edition(expected);
529 let found = RustFeatures::new_with_latest_edition(
530 input.parse::<RustTarget>().unwrap(),
531 );
532 assert_eq!(
533 expected,
534 found,
535 "target {input} enables features:\n{found:#?}\nand should enable features:\n{expected:#?}"
536 );
537 }
538
539 fn test_invalid_target(input: &str) {
540 assert!(
541 input.parse::<RustTarget>().is_err(),
542 "{input} should be an invalid target"
543 );
544 }
545
546 #[test]
547 fn valid_targets() {
548 test_target("1.71", RustTarget::Stable_1_71);
549 test_target("1.71.0", RustTarget::Stable_1_71);
550 test_target("1.71.1", RustTarget::Stable_1_71);
551 test_target("1.72", RustTarget::Stable_1_71);
552 test_target("1.73", RustTarget::Stable_1_73);
553 test_target("1.18446744073709551615", LATEST_STABLE_RUST);
554 test_target("nightly", RustTarget::Nightly);
555 }
556
557 #[test]
558 fn invalid_targets() {
559 test_invalid_target("2.0");
560 test_invalid_target("1.cat");
561 test_invalid_target("1.0.cat");
562 test_invalid_target("1.18446744073709551616");
563 test_invalid_target("1.0.18446744073709551616");
564 test_invalid_target("1.-1.0");
565 test_invalid_target("1.0.-1");
566 test_invalid_target("beta");
567 test_invalid_target("1.0.0");
568 test_invalid_target("1.32.0");
569 }
570}