/
parser.rs
111 lines (93 loc) · 2.65 KB
/
parser.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//! Parsing flags from text.
//!
//! `bitflags` defines the following whitespace-insensitive grammar for flags formatted
//! as text:
//!
//! - _Flags:_ (_Flag_)`|`*
//! - _Flag:_ _Identifier_ | _HexNumber_
//! - _Identifier:_ Any Rust identifier
//! - _HexNumber_: `0x`([0-9a-zA-Z])*
//!
//! As an example, this is how `Flags::A | Flags::B | 0x0c` can be represented as text:
//!
//! ```text
//! A | B | 0x0c
//! ```
#![allow(clippy::let_unit_value)]
use core::fmt;
/// An error encountered while parsing flags from text.
#[derive(Debug)]
pub struct ParseError(ParseErrorKind);
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
enum ParseErrorKind {
EmptyFlag,
InvalidNamedFlag {
#[cfg(not(feature = "std"))]
got: (),
#[cfg(feature = "std")]
got: String,
},
InvalidHexFlag {
#[cfg(not(feature = "std"))]
got: (),
#[cfg(feature = "std")]
got: String,
},
}
impl ParseError {
/// An invalid hex flag was encountered.
pub fn invalid_hex_flag(flag: impl fmt::Display) -> Self {
let _flag = flag;
let got = {
#[cfg(feature = "std")]
{
_flag.to_string()
}
};
ParseError(ParseErrorKind::InvalidHexFlag { got })
}
/// A named flag that doesn't correspond to any on the flags type was encountered.
pub fn invalid_named_flag(flag: impl fmt::Display) -> Self {
let _flag = flag;
let got = {
#[cfg(feature = "std")]
{
_flag.to_string()
}
};
ParseError(ParseErrorKind::InvalidNamedFlag { got })
}
/// A hex or named flag wasn't found between separators.
pub fn empty_flag() -> Self {
ParseError(ParseErrorKind::EmptyFlag)
}
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.0 {
ParseErrorKind::InvalidNamedFlag { got } => {
let _got = got;
write!(f, "unrecognized named flag")?;
#[cfg(feature = "std")]
{
write!(f, " `{}`", _got)?;
}
}
ParseErrorKind::InvalidHexFlag { got } => {
let _got = got;
write!(f, "invalid hex flag")?;
#[cfg(feature = "std")]
{
write!(f, " `{}`", _got)?;
}
}
ParseErrorKind::EmptyFlag => {
write!(f, "encountered empty flag")?;
}
}
Ok(())
}
}
#[cfg(feature = "std")]
impl std::error::Error for ParseError {}