Skip to main content

ra_ap_edition/
lib.rs

1//! The edition of the Rust language used in a crate.
2// This should live in a separate crate because we use it in both actual code and codegen.
3use std::fmt;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
6#[repr(u8)]
7pub enum Edition {
8    // The syntax context stuff needs the discriminants to start from 0 and be consecutive.
9    Edition2015 = 0,
10    Edition2018,
11    Edition2021,
12    Edition2024,
13}
14
15impl Edition {
16    pub const DEFAULT: Edition = Edition::Edition2015;
17    pub const LATEST: Edition = Edition::Edition2024;
18    pub const CURRENT: Edition = Edition::Edition2024;
19
20    pub fn from_u32(u32: u32) -> Edition {
21        match u32 {
22            0 => Edition::Edition2015,
23            1 => Edition::Edition2018,
24            2 => Edition::Edition2021,
25            3 => Edition::Edition2024,
26            _ => panic!("invalid edition"),
27        }
28    }
29
30    pub fn at_least_2024(self) -> bool {
31        self >= Edition::Edition2024
32    }
33
34    pub fn at_least_2021(self) -> bool {
35        self >= Edition::Edition2021
36    }
37
38    pub fn at_least_2018(self) -> bool {
39        self >= Edition::Edition2018
40    }
41
42    pub fn number(&self) -> usize {
43        match self {
44            Edition::Edition2015 => 2015,
45            Edition::Edition2018 => 2018,
46            Edition::Edition2021 => 2021,
47            Edition::Edition2024 => 2024,
48        }
49    }
50
51    pub fn iter() -> impl Iterator<Item = Edition> {
52        [Edition::Edition2015, Edition::Edition2018, Edition::Edition2021, Edition::Edition2024]
53            .iter()
54            .copied()
55    }
56}
57
58#[derive(Debug)]
59pub struct ParseEditionError {
60    invalid_input: String,
61}
62
63impl std::error::Error for ParseEditionError {}
64impl fmt::Display for ParseEditionError {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        write!(f, "invalid edition: {:?}", self.invalid_input)
67    }
68}
69
70impl std::str::FromStr for Edition {
71    type Err = ParseEditionError;
72
73    fn from_str(s: &str) -> Result<Self, Self::Err> {
74        let res = match s {
75            "2015" => Edition::Edition2015,
76            "2018" => Edition::Edition2018,
77            "2021" => Edition::Edition2021,
78            "2024" => Edition::Edition2024,
79            _ => return Err(ParseEditionError { invalid_input: s.to_owned() }),
80        };
81        Ok(res)
82    }
83}
84
85impl fmt::Display for Edition {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        f.write_str(match self {
88            Edition::Edition2015 => "2015",
89            Edition::Edition2018 => "2018",
90            Edition::Edition2021 => "2021",
91            Edition::Edition2024 => "2024",
92        })
93    }
94}