Debian Codegraph @

third_party/rust/lalrpop-util/src/lib.rs

raw
1 #![cfg_attr(not(feature = "std"), no_std)]
2
3 extern crate alloc;
4
5 use alloc::{string::String, vec::Vec};
6 use core::fmt;
7 #[cfg(feature = "std")]
8 use std::error::Error;
9
10 #[cfg(feature = "lexer")]
11 pub mod lexer;
12 pub mod state_machine;
13
14 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
15 pub enum ParseError<L, T, E> {
16 /// Generated by the parser when it encounters a token (or EOF) it did not
17 /// expect.
18 InvalidToken { location: L },
19
20 /// Generated by the parser when it encounters an EOF it did not expect.
21 UnrecognizedEOF {
22 /// The end of the final token
23 location: L,
24
25 /// The set of expected tokens: these names are taken from the
26 /// grammar and hence may not necessarily be suitable for
27 /// presenting to the user.
28 expected: Vec<String>,
29 },
30
31 /// Generated by the parser when it encounters a token it did not expect.
32 UnrecognizedToken {
33 /// The unexpected token of type `T` with a span given by the two `L` values.
34 token: (L, T, L),
35
36 /// The set of expected tokens: these names are taken from the
37 /// grammar and hence may not necessarily be suitable for
38 /// presenting to the user.
39 expected: Vec<String>,
40 },
41
42 /// Generated by the parser when it encounters additional, unexpected tokens.
43 ExtraToken { token: (L, T, L) },
44
45 /// Custom error type.
46 User { error: E },
47 }
48
49 impl<L, T, E> ParseError<L, T, E> {
50 fn map_intern<LL, TT, EE>(
51 self,
52 mut loc_op: impl FnMut(L) -> LL,
53 tok_op: impl FnOnce(T) -> TT,
54 err_op: impl FnOnce(E) -> EE,
55 ) -> ParseError<LL, TT, EE> {
56 let maptok = |(s, t, e): (L, T, L)| (loc_op(s), tok_op(t), loc_op(e));
57 match self {
58 ParseError::InvalidToken { location } => ParseError::InvalidToken {
59 location: loc_op(location),
60 },
61 ParseError::UnrecognizedEOF { location, expected } => ParseError::UnrecognizedEOF {
62 location: loc_op(location),
63 expected,
64 },
65 ParseError::UnrecognizedToken { token, expected } => ParseError::UnrecognizedToken {
66 token: maptok(token),
67 expected,
68 },
69 ParseError::ExtraToken { token } => ParseError::ExtraToken {
70 token: maptok(token),
71 },
72 ParseError::User { error } => ParseError::User {
73 error: err_op(error),
74 },
75 }
76 }
77
78 pub fn map_location<LL>(self, op: impl FnMut(L) -> LL) -> ParseError<LL, T, E> {
79 self.map_intern(op, |x| x, |x| x)
80 }
81
82 pub fn map_token<TT>(self, op: impl FnOnce(T) -> TT) -> ParseError<L, TT, E> {
83 self.map_intern(|x| x, op, |x| x)
84 }
85
86 pub fn map_error<EE>(self, op: impl FnOnce(E) -> EE) -> ParseError<L, T, EE> {
87 self.map_intern(|x| x, |x| x, op)
88 }
89 }
90
91 /// Format a list of expected tokens.
92 fn fmt_expected(f: &mut fmt::Formatter<'_>, expected: &[String]) -> fmt::Result {
93 if !expected.is_empty() {
94 writeln!(f)?;
95 for (i, e) in expected.iter().enumerate() {
96 let sep = match i {
97 0 => "Expected one of",
98 _ if i < expected.len() - 1 => ",",
99 // Last expected message to be written
100 _ => " or",
101 };
102 write!(f, "{} {}", sep, e)?;
103 }
104 }
105 Ok(())
106 }
107
108 impl<L, T, E> fmt::Display for ParseError<L, T, E>
109 where
110 L: fmt::Display,
111 T: fmt::Display,
112 E: fmt::Display,
113 {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 use self::ParseError::*;
116 match *self {
117 User { ref error } => write!(f, "{}", error),
118 InvalidToken { ref location } => write!(f, "Invalid token at {}", location),
119 UnrecognizedEOF {
120 ref location,
121 ref expected,
122 } => {
123 write!(f, "Unrecognized EOF found at {}", location)?;
124 fmt_expected(f, expected)
125 }
126 UnrecognizedToken {
127 token: (ref start, ref token, ref end),
128 ref expected,
129 } => {
130 write!(
131 f,
132 "Unrecognized token `{}` found at {}:{}",
133 token, start, end
134 )?;
135 fmt_expected(f, expected)
136 }
137 ExtraToken {
138 token: (ref start, ref token, ref end),
139 } => write!(f, "Extra token {} found at {}:{}", token, start, end),
140 }
141 }
142 }
143
144 impl<L, T, E> From<E> for ParseError<L, T, E> {
145 fn from(error: E) -> Self {
146 ParseError::User { error }
147 }
148 }
149
150 #[cfg(feature = "std")]
151 impl<L, T, E> Error for ParseError<L, T, E>
152 where
153 L: fmt::Debug + fmt::Display,
154 T: fmt::Debug + fmt::Display,
155 E: fmt::Debug + fmt::Display,
156 {
157 fn description(&self) -> &str {
158 "parse error"
159 }
160 }
161
162 #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
163 pub struct ErrorRecovery<L, T, E> {
164 pub error: ParseError<L, T, E>,
165 pub dropped_tokens: Vec<(L, T, L)>,
166 }
167
168 /// Define a module using the generated parse from a `.lalrpop` file.
169 ///
170 /// You have to specify the name of the module and the path of the file
171 /// generated by LALRPOP. If the input is in the root directory, you can
172 /// omit it.
173 ///
174 /// # Example
175 /// ```ignore
176 /// // load parser in src/parser.lalrpop
177 /// lalrpop_mod!(parser);
178 ///
179 /// // load parser in src/lex/parser.lalrpop
180 /// lalrpop_mod!(parser, "/lex/parser.rs");
181 ///
182 /// // define a public module
183 /// lalrpop_mod!(pub parser);
184 /// ```
185
186 #[macro_export]
187 macro_rules! lalrpop_mod {
188 ($(#[$attr:meta])* $vis:vis $modname:ident) => {
189 lalrpop_mod!($(#[$attr])* $vis $modname, concat!("/", stringify!($modname), ".rs"));
190 };
191
192 ($(#[$attr:meta])* $vis:vis $modname:ident, $source:expr) => {
193 $(#[$attr])* $vis mod $modname { include!(concat!(env!("OUT_DIR"), $source)); }
194 };
195 }
196
197 #[cfg(test)]
198 mod tests {
199 use super::*;
200 use alloc::{format, vec, string::ToString};
201
202 #[test]
203 fn test() {
204 let err = ParseError::UnrecognizedToken::<i32, &str, &str> {
205 token: (1, "t0", 2),
206 expected: vec!["t1", "t2", "t3"]
207 .into_iter()
208 .map(|s| s.to_string())
209 .collect(),
210 };
211 assert_eq!(
212 format!("{}", err),
213 "Unrecognized token `t0` found at 1:2\n\
214 Expected one of t1, t2 or t3"
215 );
216 }
217 }