Debian Codegraph @

helix-parsec/src/lib.rs

raw symbols SCIP
1 //! Parser-combinator functions
2 //!
3 //! This module provides parsers and parser combinators which can be used
4 //! together to build parsers by functional composition.
5
6 // This module implements parser combinators following https://bodil.lol/parser-combinators/.
7 // `sym` (trait implementation for `&'static str`), `map`, `pred` (filter), `one_or_more`,
8 // `zero_or_more`, as well as the `Parser` trait originate mostly from that post.
9 // The remaining parsers and parser combinators are either based on
10 // https://github.com/archseer/snippets.nvim/blob/a583da6ef130d2a4888510afd8c4e5ffd62d0dce/lua/snippet/parser.lua#L5-L138
11 // or are novel.
12
13 // When a parser matches the input successfully, it returns `Ok((next_input, some_value))`
14 // where the type of the returned value depends on the parser. If the parser fails to match,
15 // it returns `Err(input)`.
16 type ParseResult<'a, Output> = Result<(&'a str, Output), &'a str>;
17
18 /// A parser or parser-combinator.
19 ///
20 /// Parser-combinators compose multiple parsers together to parse input.
21 /// For example, two basic parsers (`&'static str`s) may be combined with
22 /// a parser-combinator like [or] to produce a new parser.
23 ///
24 /// ```
25 /// use helix_parsec::{or, Parser};
26 /// let foo = "foo"; // matches "foo" literally
27 /// let bar = "bar"; // matches "bar" literally
28 /// let foo_or_bar = or(foo, bar); // matches either "foo" or "bar"
29 /// assert_eq!(Ok(("", "foo")), foo_or_bar.parse("foo"));
30 /// assert_eq!(Ok(("", "bar")), foo_or_bar.parse("bar"));
31 /// assert_eq!(Err("baz"), foo_or_bar.parse("baz"));
32 /// ```
33 pub trait Parser<'a> {
34 type Output;
35
36 fn parse(&self, input: &'a str) -> ParseResult<'a, Self::Output>;
37 }
38
39 // Most parser-combinators are written as higher-order functions which take some
40 // parser(s) as input and return a new parser: a function that takes input and returns
41 // a parse result. The underlying implementation of [Parser::parse] for these functions
42 // is simply application.
43 #[doc(hidden)]
44 impl<'a, F, T> Parser<'a> for F
45 where
46 F: Fn(&'a str) -> ParseResult<'a, T>,
47 {
48 type Output = T;
49
50 fn parse(&self, input: &'a str) -> ParseResult<'a, Self::Output> {
51 self(input)
52 }
53 }
54
55 /// A parser which matches the string literal exactly.
56 ///
57 /// This parser succeeds if the next characters in the input are equal to the given
58 /// string literal.
59 ///
60 /// Note that [str::parse] interferes with calling [Parser::parse] on string literals
61 /// directly; this trait implementation works when used within any parser combinator
62 /// but does not work on its own. To call [Parser::parse] on a parser for a string
63 /// literal, use the [token] parser.
64 ///
65 /// # Examples
66 ///
67 /// ```
68 /// use helix_parsec::{or, Parser};
69 /// let parser = or("foo", "bar");
70 /// assert_eq!(Ok(("", "foo")), parser.parse("foo"));
71 /// assert_eq!(Ok(("", "bar")), parser.parse("bar"));
72 /// assert_eq!(Err("baz"), parser.parse("baz"));
73 /// ```
74 impl<'a> Parser<'a> for &'static str {
75 type Output = &'a str;
76
77 fn parse(&self, input: &'a str) -> ParseResult<'a, Self::Output> {
78 match input.get(0..self.len()) {
79 Some(actual) if actual == *self => Ok((&input[self.len()..], &input[0..self.len()])),
80 _ => Err(input),
81 }
82 }
83 }
84
85 // Parsers
86
87 /// A parser which matches the given string literally.
88 ///
89 /// This function is a convenience for interpreting string literals as parsers
90 /// and is only necessary to avoid conflict with [str::parse]. See the documentation
91 /// for the `&'static str` implementation of [Parser].
92 ///
93 /// # Examples
94 ///
95 /// ```
96 /// use helix_parsec::{token, Parser};
97 /// let parser = token("foo");
98 /// assert_eq!(Ok(("", "foo")), parser.parse("foo"));
99 /// assert_eq!(Err("bar"), parser.parse("bar"));
100 /// ```
101 pub fn token<'a>(literal: &'static str) -> impl Parser<'a, Output = &'a str> {
102 literal
103 }
104
105 /// A parser which matches all values until the specified pattern is found.
106 ///
107 /// If the pattern is not found, this parser does not match. The input up to the
108 /// character which returns `true` is returned but not that character itself.
109 ///
110 /// If the pattern function returns true on the first input character, this
111 /// parser fails.
112 ///
113 /// # Examples
114 ///
115 /// ```
116 /// use helix_parsec::{take_until, Parser};
117 /// let parser = take_until(|c| c == '.');
118 /// assert_eq!(Ok((".bar", "foo")), parser.parse("foo.bar"));
119 /// assert_eq!(Err(".foo"), parser.parse(".foo"));
120 /// assert_eq!(Err("foo"), parser.parse("foo"));
121 /// ```
122 pub fn take_until<'a, F>(pattern: F) -> impl Parser<'a, Output = &'a str>
123 where
124 F: Fn(char) -> bool,
125 {
126 move |input: &'a str| match input.find(&pattern) {
127 Some(index) if index != 0 => Ok((&input[index..], &input[0..index])),
128 _ => Err(input),
129 }
130 }
131
132 /// A parser which matches all values until the specified pattern no longer match.
133 ///
134 /// This parser only ever fails if the input has a length of zero.
135 ///
136 /// # Examples
137 ///
138 /// ```
139 /// use helix_parsec::{take_while, Parser};
140 /// let parser = take_while(|c| c == '1');
141 /// assert_eq!(Ok(("2", "11")), parser.parse("112"));
142 /// assert_eq!(Err("22"), parser.parse("22"));
143 /// ```
144 pub fn take_while<'a, F>(pattern: F) -> impl Parser<'a, Output = &'a str>
145 where
146 F: Fn(char) -> bool,
147 {
148 move |input: &'a str| match input
149 .char_indices()
150 .take_while(|(_p, c)| pattern(*c))
151 .last()
152 {
153 Some((index, c)) => {
154 let index = index + c.len_utf8();
155 Ok((&input[index..], &input[0..index]))
156 }
157 _ => Err(input),
158 }
159 }
160
161 // Variadic parser combinators
162
163 /// A parser combinator which matches a sequence of parsers in an all-or-nothing fashion.
164 ///
165 /// The returned value is a tuple containing the outputs of all parsers in order. Each
166 /// parser in the sequence may be typed differently.
167 ///
168 /// # Examples
169 ///
170 /// ```
171 /// use helix_parsec::{seq, Parser};
172 /// let parser = seq!("<", "a", ">");
173 /// assert_eq!(Ok(("", ("<", "a", ">"))), parser.parse("<a>"));
174 /// assert_eq!(Err("<b>"), parser.parse("<b>"));
175 /// ```
176 #[macro_export]
177 macro_rules! seq {
178 ($($parsers: expr),+ $(,)?) => {
179 ($($parsers),+)
180 }
181 }
182
183 // Seq is implemented using trait-implementations of Parser for various size tuples.
184 // This allows sequences to be typed heterogeneously.
185 macro_rules! seq_impl {
186 ($($parser:ident),+) => {
187 #[allow(non_snake_case)]
188 impl<'a, $($parser),+> Parser<'a> for ($($parser),+)
189 where
190 $($parser: Parser<'a>),+
191 {
192 type Output = ($($parser::Output),+);
193
194 fn parse(&self, input: &'a str) -> ParseResult<'a, Self::Output> {
195 let ($($parser),+) = self;
196 seq_body_impl!(input, input, $($parser),+ ; )
197 }
198 }
199 }
200 }
201
202 macro_rules! seq_body_impl {
203 ($input:expr, $next_input:expr, $head:ident, $($tail:ident),+ ; $(,)? $($acc:ident),*) => {
204 match $head.parse($next_input) {
205 Ok((next_input, $head)) => seq_body_impl!($input, next_input, $($tail),+ ; $($acc),*, $head),
206 Err(_) => Err($input),
207 }
208 };
209 ($input:expr, $next_input:expr, $last:ident ; $(,)? $($acc:ident),*) => {
210 match $last.parse($next_input) {
211 Ok((next_input, last)) => Ok((next_input, ($($acc),+, last))),
212 Err(_) => Err($input),
213 }
214 }
215 }
216
217 seq_impl!(A, B);
218 seq_impl!(A, B, C);
219 seq_impl!(A, B, C, D);
220 seq_impl!(A, B, C, D, E);
221 seq_impl!(A, B, C, D, E, F);
222 seq_impl!(A, B, C, D, E, F, G);
223 seq_impl!(A, B, C, D, E, F, G, H);
224 seq_impl!(A, B, C, D, E, F, G, H, I);
225 seq_impl!(A, B, C, D, E, F, G, H, I, J);
226
227 /// A parser combinator which chooses the first of the input parsers which matches
228 /// successfully.
229 ///
230 /// All input parsers must have the same output type. This is a variadic form for [or].
231 ///
232 /// # Examples
233 ///
234 /// ```
235 /// use helix_parsec::{choice, or, Parser};
236 /// let parser = choice!("foo", "bar", "baz");
237 /// assert_eq!(Ok(("", "foo")), parser.parse("foo"));
238 /// assert_eq!(Ok(("", "bar")), parser.parse("bar"));
239 /// assert_eq!(Err("quiz"), parser.parse("quiz"));
240 /// ```
241 #[macro_export]
242 macro_rules! choice {
243 ($parser: expr $(,)?) => {
244 $parser
245 };
246 ($parser: expr, $($rest: expr),+ $(,)?) => {
247 or($parser, choice!($($rest),+))
248 }
249 }
250
251 // Ordinary parser combinators
252
253 /// A parser combinator which takes a parser as input and maps the output using the
254 /// given transformation function.
255 ///
256 /// This corresponds to [Result::map]. The value is only mapped if the input parser
257 /// matches against input.
258 ///
259 /// # Examples
260 ///
261 /// ```
262 /// use helix_parsec::{map, Parser};
263 /// let parser = map("123", |s| s.parse::<i32>().unwrap());
264 /// assert_eq!(Ok(("", 123)), parser.parse("123"));
265 /// assert_eq!(Err("abc"), parser.parse("abc"));
266 /// ```
267 pub fn map<'a, P, F, T>(parser: P, map_fn: F) -> impl Parser<'a, Output = T>
268 where
269 P: Parser<'a>,
270 F: Fn(P::Output) -> T,
271 {
272 move |input| {
273 parser
274 .parse(input)
275 .map(|(next_input, result)| (next_input, map_fn(result)))
276 }
277 }
278
279 /// A parser combinator which succeeds if the given parser matches the input and
280 /// the given `filter_map_fn` returns `Some`.
281 ///
282 /// # Examples
283 ///
284 /// ```
285 /// use helix_parsec::{filter_map, take_until, Parser};
286 /// let parser = filter_map(take_until(|c| c == '.'), |s| s.parse::<i32>().ok());
287 /// assert_eq!(Ok((".456", 123)), parser.parse("123.456"));
288 /// assert_eq!(Err("abc.def"), parser.parse("abc.def"));
289 /// ```
290 pub fn filter_map<'a, P, F, T>(parser: P, filter_map_fn: F) -> impl Parser<'a, Output = T>
291 where
292 P: Parser<'a>,
293 F: Fn(P::Output) -> Option<T>,
294 {
295 move |input| match parser.parse(input) {
296 Ok((next_input, value)) => match filter_map_fn(value) {
297 Some(value) => Ok((next_input, value)),
298 None => Err(input),
299 },
300 Err(_) => Err(input),
301 }
302 }
303
304 /// A parser combinator which succeeds if the first given parser matches the input and
305 /// the second given parse also matches.
306 ///
307 /// # Examples
308 ///
309 /// ```
310 /// use helix_parsec::{reparse_as, take_until, one_or_more, Parser};
311 /// let parser = reparse_as(take_until(|c| c == '/'), one_or_more("a"));
312 /// assert_eq!(Ok(("/bb", vec!["a", "a"])), parser.parse("aa/bb"));
313 /// ```
314 pub fn reparse_as<'a, P1, P2, T>(parser1: P1, parser2: P2) -> impl Parser<'a, Output = T>
315 where
316 P1: Parser<'a, Output = &'a str>,
317 P2: Parser<'a, Output = T>,
318 {
319 filter_map(parser1, move |str| {
320 parser2.parse(str).map(|(_, value)| value).ok()
321 })
322 }
323
324 /// A parser combinator which only matches the input when the predicate function
325 /// returns true.
326 ///
327 /// # Examples
328 ///
329 /// ```
330 /// use helix_parsec::{filter, take_until, Parser};
331 /// let parser = filter(take_until(|c| c == '.'), |s| s == &"123");
332 /// assert_eq!(Ok((".456", "123")), parser.parse("123.456"));
333 /// assert_eq!(Err("456.123"), parser.parse("456.123"));
334 /// ```
335 pub fn filter<'a, P, F, T>(parser: P, pred_fn: F) -> impl Parser<'a, Output = T>
336 where
337 P: Parser<'a, Output = T>,
338 F: Fn(&P::Output) -> bool,
339 {
340 move |input| {
341 if let Ok((next_input, value)) = parser.parse(input) {
342 if pred_fn(&value) {
343 return Ok((next_input, value));
344 }
345 }
346 Err(input)
347 }
348 }
349
350 /// A parser combinator which matches either of the input parsers.
351 ///
352 /// Both parsers must have the same output type. For a variadic form which
353 /// can take any number of parsers, use `choice!`.
354 ///
355 /// # Examples
356 ///
357 /// ```
358 /// use helix_parsec::{or, Parser};
359 /// let parser = or("foo", "bar");
360 /// assert_eq!(Ok(("", "foo")), parser.parse("foo"));
361 /// assert_eq!(Ok(("", "bar")), parser.parse("bar"));
362 /// assert_eq!(Err("baz"), parser.parse("baz"));
363 /// ```
364 pub fn or<'a, P1, P2, T>(parser1: P1, parser2: P2) -> impl Parser<'a, Output = T>
365 where
366 P1: Parser<'a, Output = T>,
367 P2: Parser<'a, Output = T>,
368 {
369 move |input| match parser1.parse(input) {
370 ok @ Ok(_) => ok,
371 Err(_) => parser2.parse(input),
372 }
373 }
374
375 /// A parser combinator which attempts to match the given parser, returning a
376 /// `None` output value if the parser does not match.
377 ///
378 /// The parser produced with this combinator always succeeds. If the given parser
379 /// succeeds, `Some(value)` is returned where `value` is the output of the given
380 /// parser. Otherwise, `None`.
381 ///
382 /// # Examples
383 ///
384 /// ```
385 /// use helix_parsec::{optional, Parser};
386 /// let parser = optional("foo");
387 /// assert_eq!(Ok(("bar", Some("foo"))), parser.parse("foobar"));
388 /// assert_eq!(Ok(("bar", None)), parser.parse("bar"));
389 /// ```
390 pub fn optional<'a, P, T>(parser: P) -> impl Parser<'a, Output = Option<T>>
391 where
392 P: Parser<'a, Output = T>,
393 {
394 move |input| match parser.parse(input) {
395 Ok((next_input, value)) => Ok((next_input, Some(value))),
396 Err(_) => Ok((input, None)),
397 }
398 }
399
400 /// A parser combinator which runs the given parsers in sequence and returns the
401 /// value of `left` if both are matched.
402 ///
403 /// This is useful for two-element sequences in which you only want the output
404 /// value of the `left` parser.
405 ///
406 /// # Examples
407 ///
408 /// ```
409 /// use helix_parsec::{left, Parser};
410 /// let parser = left("foo", "bar");
411 /// assert_eq!(Ok(("", "foo")), parser.parse("foobar"));
412 /// ```
413 pub fn left<'a, L, R, T>(left: L, right: R) -> impl Parser<'a, Output = T>
414 where
415 L: Parser<'a, Output = T>,
416 R: Parser<'a>,
417 {
418 map(seq!(left, right), |(left_value, _)| left_value)
419 }
420
421 /// A parser combinator which runs the given parsers in sequence and returns the
422 /// value of `right` if both are matched.
423 ///
424 /// This is useful for two-element sequences in which you only want the output
425 /// value of the `right` parser.
426 ///
427 /// # Examples
428 ///
429 /// ```
430 /// use helix_parsec::{right, Parser};
431 /// let parser = right("foo", "bar");
432 /// assert_eq!(Ok(("", "bar")), parser.parse("foobar"));
433 /// ```
434 pub fn right<'a, L, R, T>(left: L, right: R) -> impl Parser<'a, Output = T>
435 where
436 L: Parser<'a>,
437 R: Parser<'a, Output = T>,
438 {
439 map(seq!(left, right), |(_, right_value)| right_value)
440 }
441
442 /// A parser combinator which matches the given parser against the input zero or
443 /// more times.
444 ///
445 /// This parser always succeeds and returns the empty Vec when it matched zero
446 /// times.
447 ///
448 /// # Examples
449 ///
450 /// ```
451 /// use helix_parsec::{zero_or_more, Parser};
452 /// let parser = zero_or_more("a");
453 /// assert_eq!(Ok(("", vec![])), parser.parse(""));
454 /// assert_eq!(Ok(("", vec!["a"])), parser.parse("a"));
455 /// assert_eq!(Ok(("", vec!["a", "a"])), parser.parse("aa"));
456 /// assert_eq!(Ok(("bb", vec![])), parser.parse("bb"));
457 /// ```
458 pub fn zero_or_more<'a, P, T>(parser: P) -> impl Parser<'a, Output = Vec<T>>
459 where
460 P: Parser<'a, Output = T>,
461 {
462 let parser = non_empty(parser);
463 move |mut input| {
464 let mut values = Vec::new();
465
466 while let Ok((next_input, value)) = parser.parse(input) {
467 input = next_input;
468 values.push(value);
469 }
470
471 Ok((input, values))
472 }
473 }
474
475 /// A parser combinator which matches the given parser against the input one or
476 /// more times.
477 ///
478 /// This parser combinator acts the same as [zero_or_more] but must match at
479 /// least once.
480 ///
481 /// # Examples
482 ///
483 /// ```
484 /// use helix_parsec::{one_or_more, Parser};
485 /// let parser = one_or_more("a");
486 /// assert_eq!(Err(""), parser.parse(""));
487 /// assert_eq!(Ok(("", vec!["a"])), parser.parse("a"));
488 /// assert_eq!(Ok(("", vec!["a", "a"])), parser.parse("aa"));
489 /// assert_eq!(Err("bb"), parser.parse("bb"));
490 /// ```
491 pub fn one_or_more<'a, P, T>(parser: P) -> impl Parser<'a, Output = Vec<T>>
492 where
493 P: Parser<'a, Output = T>,
494 {
495 let parser = non_empty(parser);
496 move |mut input| {
497 let mut values = Vec::new();
498
499 match parser.parse(input) {
500 Ok((next_input, value)) => {
501 input = next_input;
502 values.push(value);
503 }
504 Err(err) => return Err(err),
505 }
506
507 while let Ok((next_input, value)) = parser.parse(input) {
508 input = next_input;
509 values.push(value);
510 }
511
512 Ok((input, values))
513 }
514 }
515
516 /// A parser combinator which matches one or more instances of the given parser
517 /// interspersed with the separator parser.
518 ///
519 /// Output values of the separator parser are discarded.
520 ///
521 /// This is typically used to parse function arguments or list items.
522 ///
523 /// # Examples
524 ///
525 /// ```rust
526 /// use helix_parsec::{sep, Parser};
527 /// let parser = sep("a", ",");
528 /// assert_eq!(Ok(("", vec!["a", "a", "a"])), parser.parse("a,a,a"));
529 /// ```
530 pub fn sep<'a, P, S, T>(parser: P, separator: S) -> impl Parser<'a, Output = Vec<T>>
531 where
532 P: Parser<'a, Output = T>,
533 S: Parser<'a>,
534 {
535 move |mut input| {
536 let mut values = Vec::new();
537
538 match parser.parse(input) {
539 Ok((next_input, value)) => {
540 input = next_input;
541 values.push(value);
542 }
543 Err(err) => return Err(err),
544 }
545
546 loop {
547 match separator.parse(input) {
548 Ok((next_input, _)) => input = next_input,
549 Err(_) => break,
550 }
551
552 match parser.parse(input) {
553 Ok((next_input, value)) => {
554 input = next_input;
555 values.push(value);
556 }
557 Err(_) => break,
558 }
559 }
560
561 Ok((input, values))
562 }
563 }
564
565 pub fn non_empty<'a, T>(p: impl Parser<'a, Output = T>) -> impl Parser<'a, Output = T> {
566 move |input| {
567 let (new_input, res) = p.parse(input)?;
568 if new_input.len() == input.len() {
569 Err(input)
570 } else {
571 Ok((new_input, res))
572 }
573 }
574 }