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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
/// This module contains the Parser and Error types which /// contain the minimal logic for implementing the atomic /// parser combinators. /// Required modules and traits from core use core::fmt; use core::ops::Bound::*; use core::ops::{BitAnd, BitOr, Mul, Not, RangeBounds, Shl, Shr, Sub}; use alloc::string::{String, ToString}; use alloc::sync::Arc; /// We need alloc! use alloc::vec::Vec; /// This struct is the Err result when parsing. /// It contains a string representing: /// The actual input received /// The expected input /// And the remaining, unparsed input #[derive(Clone, PartialEq)] pub struct Error { actual: String, expected: String, remaining_input: String, } impl Error { pub fn new<T>( actual: impl ToString, expected: impl ToString, remaining_input: impl ToString, ) -> Result<T, Self> { Err(Self { actual: actual.to_string(), expected: expected.to_string(), remaining_input: remaining_input.to_string(), }) } } /// Needed for assertions and general debugging impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( f, "Expected `{}` but found `{}` when parsing `{}`", self.expected, self.actual, self.remaining_input.replace("\n", "") ) } } /// The Output type represents the output of a parser. /// Ok(T, String) result represents successfully parsed & lexed input. /// The T type represents the consumed and lexed input, /// and the String represents the remaining input. pub type Output<T> = Result<(T, String), Error>; /// A Parser has a function that consumes input /// and returns an object of type Output. #[derive(Clone)] pub struct Parser<T> { parser: Arc<dyn Fn(&str) -> Output<T>>, } impl<T> Parser<T> where T: 'static + Clone, { /// Create a new parser from a function that returns an Output. /// This is mainly used to define the atomic combinators pub fn new(parser: impl Fn(&str) -> Output<T> + 'static) -> Self { Self { parser: Arc::new(parser), } } /// This parses a string using this combinator, and returns /// a result containing either the successfully lexed and parsed /// data, or an error containing info about the failure. pub fn parse(&self, input: &str) -> Result<T, Error> { match self.parse_internal(input) { Ok(t) => Ok(t.0), Err(e) => Err(e), } } /// This is used by the atomic combinators for things like /// control flow and passing the output of one parser into another. pub fn parse_internal(&self, input: &str) -> Output<T> { (self.parser)(input) } /// This maps takes a function that takes the output of this Parser, /// and converts it to the output of another data type. /// This allows us to lex our input as we parse it. pub fn map<O>(self, map_fn: fn(T) -> O) -> Parser<O> where O: 'static + Clone, { Parser::new(move |s: &str| match self.parse_internal(s) { Ok((first_out, input)) => Ok((map_fn(first_out), input)), Err(e) => Err(e), }) } /// This parser "prefixes" another. /// When the returned parser is used, it will require this parser and /// the operand parser to succeed, and return the result of the second. pub fn prefixes<O>(self, operand: Parser<O>) -> Parser<O> where O: 'static + Clone, { Parser::new(move |s: &str| { // Get the remaining input from ourselves // and discard consumed input let (_, remaining) = self.parse_internal(s)?; // Get the consumed input and remaining input from operand let (consumed, remaining) = operand.parse_internal(&remaining)?; // Return result Ok((consumed, remaining)) }) } /// This parser will use the operand as a "suffix". /// The parser will only succeed if the "suffix" parser succeeds afterwards, /// but the input of the "suffix" parser will be discarded. pub fn suffix<O>(self, operand: Parser<O>) -> Parser<T> where O: 'static + Clone, { Parser::new(move |s: &str| { // Get consumed input and remaining input from ourselves let (consumed, remaining) = self.parse_internal(s)?; // Consume the input from the remaining, // but discard the consumed result. let (_, remaining) = operand.parse_internal(&remaining)?; // Return result Ok((consumed, remaining)) }) } /// This method returns a parser that does not consume input, /// but succeeds if this parser succeeds. This can be used to /// make assertions for our input. pub fn is(self) -> Parser<()> { Parser::new(move |s: &str| match self.parse_internal(s) { // If this parser succeeds, consume nothing and continue Ok(_) => Ok(((), s.to_string())), // If this parser fails, throw an error Err(_) => Error::new(s, format!("Not {}", s), s), }) } /// This method returns a parser that does not consume input, /// but succeeds if this parser does not succeed. This can be /// used to make assertions for our input. pub fn isnt(self) -> Parser<()> { Parser::new(move |s: &str| match self.parse_internal(s) { // If this parser succeeds, throw an error Ok(_) => Error::new(s, format!("Not {}", s), s), // If this parser fails, consume nothing and continue Err(_) => Ok(((), s.to_string())), }) } /// Combine two parsers into one, and combine their consumed /// inputs into a tuple. /// Parser<A> & Parser<B> -> Parser<A, B>. /// The resulting parser will only succeed if BOTH sub-parsers succeed. pub fn and<O>(self, operand: Parser<O>) -> Parser<(T, O)> where O: 'static + Clone, { Parser::new(move |s: &str| { // Get the first consumed and remaining let (first_consumed, remaining) = self.parse_internal(s)?; // Get the second consumed and remaining let (second_consumed, remaining) = operand.parse_internal(&remaining)?; // Return a tuple of first and second Ok(((first_consumed, second_consumed), remaining)) }) } /// If this parser does not succeed, try this other parser pub fn or(self, operand: Self) -> Self { Parser::new(move |s: &str| match self.parse_internal(s) { // If we succeed, return OUR result Ok(t) => Ok(t), // If we don't succeed, return the other parser's result // We can safely discard OUR error here because we expect failure. Err(_) => operand.parse_internal(s), }) } /// Repeat this parser N..M times /// This can also be repeated ..N times, N.. times, or even .. times pub fn repeat(self, range: impl RangeBounds<usize>) -> Parser<Vec<T>> { // Get the upper bound let upper_bound: usize = match range.end_bound() { Unbounded => core::usize::MAX, Excluded(n) => *n, Included(n) => *n, }; // Get the lower bound let lower_bound: usize = match range.start_bound() { Unbounded => 0, Excluded(n) => *n, Included(n) => *n, }; Parser::new(move |s: &str| { // The string containing the remaining input let mut remaining_input = s.to_string(); // This accumulates all the consumed and lexed outputs // from all the successfully parsed inputs let mut accum = vec![]; for n in 0..upper_bound { match self.parse_internal(&remaining_input) { Ok((consumed, unconsumed)) => { accum.push(consumed); remaining_input = unconsumed; } Err(e) => { // If we did not consume enough data, we failed. // If consumed greater than the lower bound, we succeeded! if n < lower_bound { return Err(e); } else { return Ok((accum, remaining_input)); } } } } // Return the vector of consumed inputs Ok((accum, remaining_input)) }) } } /// The | operator can be used as an alternative to the `.or` method impl<T: 'static + Clone> BitOr for Parser<T> { type Output = Parser<T>; fn bitor(self, rhs: Self) -> Self::Output { self.or(rhs) } } /// The & operator can be used as an alternative to the `.and` method impl<A: 'static + Clone, B: 'static + Clone> BitAnd<Parser<B>> for Parser<A> { type Output = Parser<(A, B)>; fn bitand(self, rhs: Parser<B>) -> Self::Output { self.and(rhs) } } /// The ! operator can be used as an alternative to the `.not` method impl<T: 'static + Clone> Not for Parser<T> { type Output = Parser<()>; fn not(self) -> Self::Output { self.isnt() } } /// Discard the consumed data of the RHS impl<A: 'static + Clone, B: 'static + Clone> Shl<Parser<B>> for Parser<A> { type Output = Parser<A>; fn shl(self, rhs: Parser<B>) -> Self::Output { self.suffix(rhs) } } /// Discard the consumed data of the LHS impl<A: 'static + Clone, B: 'static + Clone> Shr<Parser<B>> for Parser<A> { type Output = Parser<B>; fn shr(self, rhs: Parser<B>) -> Self::Output { self.prefixes(rhs) } } /// A parser can be multiplied by a range as an alternative to `.repeat`. /// Here's an example: `sym('a') * (..7)` impl<T: 'static + Clone, R: RangeBounds<usize>> Mul<R> for Parser<T> { type Output = Parser<Vec<T>>; fn mul(self, rhs: R) -> Self::Output { self.repeat(rhs) } } /// The - operator is used as an alternative to the `.map` method. impl<O, T> Sub<fn(T) -> O> for Parser<T> where O: 'static + Clone, T: 'static + Clone, { type Output = Parser<O>; fn sub(self, rhs: fn(T) -> O) -> Self::Output { self.map(rhs) } }