| 1 | //! Building blocks for a recursive descent LL(1) parsing method. |
| 2 | //! |
| 3 | //! The general idea is that a grammar (without left recursion) is translated to a series of |
| 4 | //! conditional and unconditional 'acceptance' methods. |
| 5 | //! |
| 6 | //! For example, assuming we have a parser for integers: |
| 7 | //! |
| 8 | //! sum = integer | integer + sum |
| 9 | //! |
| 10 | //! Can get translated as: (representing a sum as `LinkedList<u32>`): |
| 11 | //! |
| 12 | //! ```ignore |
| 13 | //! impl<T: Parse> Parse for LinkedList<T> { |
| 14 | //! fn parse(stream: &mut CharStream) -> Parsed<LinkedList<T>> { |
| 15 | //! let x = try_nonterminal(stream)?; |
| 16 | //! let mut tail = if is_syntax('+', stream)? { |
| 17 | //! expect_nonterminal(stream)? |
| 18 | //! } else { |
| 19 | //! LinkedList::new() |
| 20 | //! }; |
| 21 | //! tail.push_front(x); |
| 22 | //! |
| 23 | //! make(tail) |
| 24 | //! } |
| 25 | //! } |
| 26 | //! ``` |
| 27 | |
| 28 | /// Type holding a parsed object (or error information if parsing failed) |
| 29 | pub type Parsed<T> = Result<T, Status>; |
| 30 | |
| 31 | #[derive(Copy, Clone, PartialEq)] |
| 32 | #[cfg_attr(test, derive(Debug, Eq))] |
| 33 | pub struct Span { |
| 34 | pub start: (usize, usize), |
| 35 | pub end: (usize, usize), |
| 36 | } |
| 37 | |
| 38 | #[cfg_attr(test, derive(Debug, PartialEq))] |
| 39 | pub enum Status { |
| 40 | Fatal(Span, String), // not recoverable; stream in inconsistent state |
| 41 | Reject, // parsing failed by no input consumed |
| 42 | } |
| 43 | |
| 44 | pub fn make<T>(value: T) -> Parsed<T> { |
| 45 | Ok(value) |
| 46 | } |
| 47 | |
| 48 | pub fn reject<T>() -> Parsed<T> { |
| 49 | Err(Status::Reject) |
| 50 | } |
| 51 | |
| 52 | macro_rules! unrecoverable { |
| 53 | (pos=$pos:expr, $stream:ident, $($str:expr),*) => { |
| 54 | return Err(crate::sudoers::basic_parser::Status::Fatal(Span { start: $pos, end: CharStream::get_pos($stream)}, format![$($str),*])) |
| 55 | }; |
| 56 | ($stream:ident, $($str:expr),*) => {{ |
| 57 | let pos = CharStream::get_pos($stream); |
| 58 | return Err(crate::sudoers::basic_parser::Status::Fatal(Span { start: pos, end: pos }, format![$($str),*])) |
| 59 | }}; |
| 60 | ($($str:expr),*) => { |
| 61 | return Err(crate::basic_parser::Status::Fatal(Default::default(), format![$($str),*])) |
| 62 | }; |
| 63 | } |
| 64 | |
| 65 | pub(super) use unrecoverable; |
| 66 | |
| 67 | /// This recovers from a failed parsing. |
| 68 | pub fn maybe<T>(status: Parsed<T>) -> Parsed<Option<T>> { |
| 69 | match status { |
| 70 | Ok(x) => Ok(Some(x)), |
| 71 | Err(Status::Reject) => Ok(None), |
| 72 | Err(err) => Err(err), |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | pub use super::char_stream::CharStream; |
| 77 | |
| 78 | /// All implementations of the Parse trait must satisfy this contract: |
| 79 | /// If the `parse` method of this trait returns None, the iterator is not advanced; otherwise it is |
| 80 | /// advanced beyond the accepted part of the input. i.e. if some input is consumed the method |
| 81 | /// *MUST* be producing a `Some` value. |
| 82 | pub trait Parse { |
| 83 | fn parse(stream: &mut CharStream) -> Parsed<Self> |
| 84 | where |
| 85 | Self: Sized; |
| 86 | } |
| 87 | |
| 88 | /// Structures representing whitespace (trailing whitespace can contain comments) |
| 89 | #[cfg_attr(test, derive(PartialEq, Eq))] |
| 90 | struct LeadingWhitespace; |
| 91 | |
| 92 | #[cfg_attr(test, derive(PartialEq, Eq))] |
| 93 | struct TrailingWhitespace; |
| 94 | |
| 95 | #[cfg_attr(test, derive(Debug, PartialEq, Eq))] |
| 96 | struct Comment; |
| 97 | |
| 98 | /// Accept zero or more whitespace characters; fails if the whitespace is not "leading" to something |
| 99 | /// (which can be used to detect end-of-input). |
| 100 | impl Parse for LeadingWhitespace { |
| 101 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 102 | let eat_space = |stream: &mut CharStream| stream.next_if(|c| "\t ".contains(c)); |
| 103 | while eat_space(stream).is_some() {} |
| 104 | |
| 105 | if stream.peek().is_some() { |
| 106 | make(LeadingWhitespace {}) |
| 107 | } else { |
| 108 | unrecoverable!(stream, "superfluous whitespace") |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// Accept zero or more whitespace characters; since this accepts zero characters, it |
| 114 | /// always succeeds (unless some serious error occurs). This parser also accepts comments, |
| 115 | /// since those can form part of trailing white space. |
| 116 | impl Parse for TrailingWhitespace { |
| 117 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 118 | loop { |
| 119 | let _ = LeadingWhitespace::parse(stream); // don't propagate any errors |
| 120 | |
| 121 | // line continuations |
| 122 | if stream.eat_char('\\') { |
| 123 | // do the equivalent of expect_syntax('\n', stream)?, without recursion |
| 124 | if !stream.eat_char('\n') { |
| 125 | unrecoverable!(stream, "stray escape sequence") |
| 126 | } |
| 127 | } else { |
| 128 | break; |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | make(TrailingWhitespace {}) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /// Parses a comment |
| 137 | impl Parse for Comment { |
| 138 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 139 | if !stream.eat_char('#') { |
| 140 | return Err(Status::Reject); |
| 141 | } |
| 142 | stream.skip_to_newline(); |
| 143 | make(Comment {}) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | pub(super) fn skip_trailing_whitespace(stream: &mut CharStream) -> Parsed<()> { |
| 148 | TrailingWhitespace::parse(stream)?; |
| 149 | make(()) |
| 150 | } |
| 151 | |
| 152 | /// Adheres to the contract of the [Parse] trait, accepts one character and consumes trailing whitespace. |
| 153 | pub fn try_syntax(syntax: char, stream: &mut CharStream) -> Parsed<()> { |
| 154 | if !stream.eat_char(syntax) { |
| 155 | return Err(Status::Reject); |
| 156 | } |
| 157 | skip_trailing_whitespace(stream)?; |
| 158 | make(()) |
| 159 | } |
| 160 | |
| 161 | /// Similar to [try_syntax], but aborts parsing if the expected character is not found. |
| 162 | pub fn expect_syntax(syntax: char, stream: &mut CharStream) -> Parsed<()> { |
| 163 | if try_syntax(syntax, stream).is_err() { |
| 164 | let str = if let Some(c) = stream.peek() { |
| 165 | c.to_string() |
| 166 | } else { |
| 167 | "EOF".to_string() |
| 168 | }; |
| 169 | unrecoverable!(stream, "expecting '{syntax}' but found '{str}'") |
| 170 | } |
| 171 | make(()) |
| 172 | } |
| 173 | |
| 174 | /// Convenience function: usually try_syntax is called as a test criterion; if this returns true, the input was consumed. |
| 175 | pub fn is_syntax(syntax: char, stream: &mut CharStream) -> Parsed<bool> { |
| 176 | let result = maybe(try_syntax(syntax, stream))?; |
| 177 | make(result.is_some()) |
| 178 | } |
| 179 | |
| 180 | /// Interface for working with types that implement the [Parse] trait; this allows parsing to use |
| 181 | /// type inference. Use this instead of calling [Parse::parse] directly. |
| 182 | pub fn try_nonterminal<T: Parse>(stream: &mut CharStream) -> Parsed<T> { |
| 183 | let result = T::parse(stream)?; |
| 184 | skip_trailing_whitespace(stream)?; |
| 185 | make(result) |
| 186 | } |
| 187 | |
| 188 | /// Interface for working with types that implement the [Parse] trait; this expects to parse |
| 189 | /// the given type or gives a fatal parse error if this did not succeed. |
| 190 | use super::ast_names::UserFriendly; |
| 191 | |
| 192 | pub fn expect_nonterminal<T: Parse + UserFriendly>(stream: &mut CharStream) -> Parsed<T> { |
| 193 | let begin_pos = stream.get_pos(); |
| 194 | match try_nonterminal(stream) { |
| 195 | Err(Status::Reject) => { |
| 196 | unrecoverable!(pos = begin_pos, stream, "expected {}", T::DESCRIPTION) |
| 197 | } |
| 198 | result => result, |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | /// Something that implements the Token trait is a token (i.e. a string of characters defined by a |
| 203 | /// maximum length, character classes, and possible escaping). The class for the first character of |
| 204 | /// the token can be different than that of the rest. |
| 205 | pub trait Token: Sized { |
| 206 | const MAX_LEN: usize = 255; |
| 207 | |
| 208 | fn construct(s: String) -> Result<Self, String>; |
| 209 | |
| 210 | fn accept(c: char) -> bool; |
| 211 | fn accept_1st(c: char) -> bool { |
| 212 | Self::accept(c) |
| 213 | } |
| 214 | |
| 215 | const ALLOW_ESCAPE: bool = false; |
| 216 | fn escaped(_: char) -> bool { |
| 217 | false |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | /// Implementation of the [Parse] trait for anything that implements [Token] |
| 222 | impl<T: Token> Parse for T { |
| 223 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 224 | fn accept_escaped<T: Token>( |
| 225 | pred: fn(char) -> bool, |
| 226 | stream: &mut CharStream, |
| 227 | ) -> Parsed<char> { |
| 228 | const ESCAPE: char = '\\'; |
| 229 | if T::ALLOW_ESCAPE && stream.eat_char(ESCAPE) { |
| 230 | if let Some(c) = stream.next_if(T::escaped) { |
| 231 | Ok(c) |
| 232 | } else if pred(ESCAPE) { |
| 233 | Ok(ESCAPE) |
| 234 | } else if stream.eat_char('\n') { |
| 235 | if pred(' ') { |
| 236 | // escape + newline = line continuation (whitespace) |
| 237 | Ok(' ') |
| 238 | } else { |
| 239 | reject() |
| 240 | } |
| 241 | } else { |
| 242 | unrecoverable!(stream, "illegal escape sequence") |
| 243 | } |
| 244 | } else if let Some(c) = stream.next_if(pred) { |
| 245 | Ok(c) |
| 246 | } else { |
| 247 | reject() |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | let start_pos = stream.get_pos(); |
| 252 | let mut str = accept_escaped::<T>(T::accept_1st, stream)?.to_string(); |
| 253 | while let Some(c) = maybe(accept_escaped::<T>(T::accept, stream))? { |
| 254 | if str.len() >= T::MAX_LEN { |
| 255 | unrecoverable!(stream, "token exceeds maximum length") |
| 256 | } |
| 257 | str.push(c) |
| 258 | } |
| 259 | |
| 260 | match T::construct(str) { |
| 261 | Ok(result) => make(result), |
| 262 | Err(msg) => unrecoverable!(pos = start_pos, stream, "{msg}"), |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | /// Parser for `Option<T>` (this can be used to make the code more readable) |
| 268 | impl<T: Parse> Parse for Option<T> { |
| 269 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 270 | maybe(T::parse(stream)) |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | /// Parsing method for lists of items separated by a given character; this adheres to the contract of the [Parse] trait. |
| 275 | pub(super) fn parse_list<T: Parse + UserFriendly>( |
| 276 | sep_by: char, |
| 277 | max: usize, |
| 278 | stream: &mut CharStream, |
| 279 | ) -> Parsed<Vec<T>> { |
| 280 | let mut elems = Vec::new(); |
| 281 | elems.push(try_nonterminal(stream)?); |
| 282 | while maybe(try_syntax(sep_by, stream))?.is_some() { |
| 283 | if elems.len() >= max { |
| 284 | unrecoverable!(stream, "too many items in list") |
| 285 | } |
| 286 | elems.push(expect_nonterminal(stream)?); |
| 287 | } |
| 288 | |
| 289 | make(elems) |
| 290 | } |
| 291 | |
| 292 | /// Types that implement the Many trait can be parsed multiple tokens into a `Vec<T>`; they are |
| 293 | /// separated by `SEP`. There should also be a limit on the number of items. |
| 294 | pub trait Many { |
| 295 | const SEP: char = ','; |
| 296 | const LIMIT: usize = 127; |
| 297 | } |
| 298 | |
| 299 | /// Generic implementation for parsing multiple items of a type `T` that implements the [Parse] and |
| 300 | /// [Many] traits. |
| 301 | impl<T: Parse + Many + UserFriendly> Parse for Vec<T> { |
| 302 | fn parse(stream: &mut CharStream) -> Parsed<Self> { |
| 303 | parse_list(T::SEP, T::LIMIT, stream) |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | /// Entry point utility function; parse a `Vec<T>` but with fatal error recovery per line |
| 308 | pub fn parse_lines<T>(stream: &mut CharStream) -> Vec<Parsed<T>> |
| 309 | where |
| 310 | T: Parse + UserFriendly, |
| 311 | { |
| 312 | let mut result = Vec::new(); |
| 313 | |
| 314 | // this will terminate; if the inner accept_if is an error, either a character will be consumed |
| 315 | // by the second accept_if (making progress), or the end of the stream will have been reacherd |
| 316 | // (which will cause the next iteration to fall through) |
| 317 | |
| 318 | while LeadingWhitespace::parse(stream).is_ok() { |
| 319 | let item = expect_nonterminal(stream); |
| 320 | let parsed_item_ok = item.is_ok(); |
| 321 | result.push(item); |
| 322 | |
| 323 | let _ = maybe(Comment::parse(stream)); |
| 324 | if !stream.eat_char('\n') { |
| 325 | if parsed_item_ok { |
| 326 | let msg = if stream.peek().is_none() { |
| 327 | "missing line terminator at end of file" |
| 328 | } else { |
| 329 | "garbage at end of line" |
| 330 | }; |
| 331 | let error = |stream: &mut CharStream| unrecoverable!(stream, "{msg}"); |
| 332 | result.push(error(stream)); |
| 333 | } |
| 334 | stream.skip_to_newline(); |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | result |
| 339 | } |
| 340 | |
| 341 | #[cfg(test)] |
| 342 | fn expect_complete<T: Parse>(stream: &mut CharStream) -> Parsed<T> { |
| 343 | let result = expect_nonterminal(stream)?; |
| 344 | if let Some(c) = stream.peek() { |
| 345 | unrecoverable!(stream, "garbage at end of line: {c}") |
| 346 | } |
| 347 | make(result) |
| 348 | } |
| 349 | |
| 350 | /// Convenience function (especially useful for writing test cases, to avoid having to write out the |
| 351 | /// AST constructors by hand. |
| 352 | #[cfg(test)] |
| 353 | pub fn parse_string<T: Parse>(text: &str) -> Parsed<T> { |
| 354 | expect_complete(&mut CharStream::new(text)) |
| 355 | } |
| 356 | |
| 357 | #[cfg(test)] |
| 358 | pub fn parse_eval<T: Parse>(text: &str) -> T { |
| 359 | parse_string(text).unwrap() |
| 360 | } |
| 361 | |
| 362 | #[cfg(test)] |
| 363 | mod test { |
| 364 | use super::*; |
| 365 | |
| 366 | impl Token for String { |
| 367 | fn construct(val: String) -> Result<Self, String> { |
| 368 | Ok(val) |
| 369 | } |
| 370 | |
| 371 | fn accept(c: char) -> bool { |
| 372 | c.is_ascii_alphanumeric() |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | impl Many for String {} |
| 377 | |
| 378 | #[test] |
| 379 | fn comment_test() { |
| 380 | assert_eq!(parse_eval::<Comment>("# hello"), Comment); |
| 381 | } |
| 382 | #[test] |
| 383 | #[should_panic] |
| 384 | fn comment_test_fail() { |
| 385 | assert_eq!(parse_eval::<Comment>("# hello\nsomething"), Comment); |
| 386 | } |
| 387 | |
| 388 | #[test] |
| 389 | fn lines_test() { |
| 390 | let input = |text: &str| parse_lines(&mut CharStream::new(text)); |
| 391 | |
| 392 | let s = |text: &str| Ok(text.to_string()); |
| 393 | assert_eq!(input("hello\nworld\n"), vec![s("hello"), s("world")]); |
| 394 | assert_eq!(input(" hello\nworld\n"), vec![s("hello"), s("world")]); |
| 395 | assert_eq!(input("hello \nworld\n"), vec![s("hello"), s("world")]); |
| 396 | assert_eq!(input("hello\n world\n"), vec![s("hello"), s("world")]); |
| 397 | assert_eq!(input("hello\nworld \n"), vec![s("hello"), s("world")]); |
| 398 | assert_eq!(input("hello\nworld")[0..2], vec![s("hello"), s("world")]); |
| 399 | let Err(_) = input("hello\nworld")[2] else { |
| 400 | panic!() |
| 401 | }; |
| 402 | let Err(_) = input("hello\nworld:\n")[2] else { |
| 403 | panic!() |
| 404 | }; |
| 405 | } |
| 406 | #[test] |
| 407 | fn whitespace_test() { |
| 408 | assert_eq!( |
| 409 | parse_eval::<Vec<String>>("hello,something"), |
| 410 | vec!["hello", "something"] |
| 411 | ); |
| 412 | assert_eq!( |
| 413 | parse_eval::<Vec<String>>("hello , something"), |
| 414 | vec!["hello", "something"] |
| 415 | ); |
| 416 | assert_eq!( |
| 417 | parse_eval::<Vec<String>>("hello, something"), |
| 418 | vec!["hello", "something"] |
| 419 | ); |
| 420 | assert_eq!( |
| 421 | parse_eval::<Vec<String>>("hello ,something"), |
| 422 | vec!["hello", "something"] |
| 423 | ); |
| 424 | assert_eq!( |
| 425 | parse_eval::<Vec<String>>("hello\\\n,something"), |
| 426 | vec!["hello", "something"] |
| 427 | ); |
| 428 | } |
| 429 | } |