3 releases

0.1.2 Feb 4, 2023
0.1.1 Feb 4, 2023
0.1.0 Feb 4, 2023

#723 in Programming languages

Download history 17/week @ 2024-01-04 41/week @ 2024-01-11 12/week @ 2024-01-18 16/week @ 2024-01-25 40/week @ 2024-02-01 33/week @ 2024-02-08 58/week @ 2024-02-15 143/week @ 2024-02-22 132/week @ 2024-02-29 144/week @ 2024-03-07 44/week @ 2024-03-14 53/week @ 2024-03-21 107/week @ 2024-03-28 64/week @ 2024-04-04 50/week @ 2024-04-11 36/week @ 2024-04-18

688 downloads per month
Used in 12 crates (2 directly)

MIT license

22KB
541 lines

Higher Order Parser

HOP is a lightweight, higher-order parser in Rust.

Hi-Parser provides a more Haskell-like parser style, and explores the ? syntax of Result to have a do-block-like monadic notation. This isn't as good as a proper do notation, but avoids identation hell. For example, a lambda, in a functional language, can be parsed as:

// Parses a λ-term in the syntax: `λx => body`
pub fn parse_lam(state: parser::State) -> parser::Answer<Option<Box<Term>>> {
  let (state, _)    = parser::there_take_exact("λ")?;
  let (state, name) = parser::there_nonempty_name(state)?;
  let (state, _)    = parser::there_take_exact("=>")?;
  let (state, body) = parse_term(state)?;
  Ok((state, Box::new(Term::Lam { name, body })))
}

A Parser is defined simply as:

Answer<A> = Result<(State, A), String>
Parser<A> = Fn(State) -> Answer<A>>

That is, a Parser is a function that receives a State and returns an Answer. That answer is either an updated state, and the parse result (if it succeeds), or an error message, as a simple string, if it fails. Note that there are two ways to fail:

1. Recoverable. Return an Ok with a Bool, or an Option:

- Ok((new_state, Some(result))) if it succeeds
- Ok((old_state, None))         if it fails

This backtracks, and can be used to implement alternatives. For example, if you're parsing an AST, "Animal", with 2 constructors, dog and cat, then you could implement:

parse_dog    : Parser<Option<Animal>>
parse_cat    : Parser<Option<Animal>>
parse_animal : Parser<Animal>

2. Irrecoverable. Return an Err with a message:

- Err(error_message)

This will abort the entire parser, like a "throw", and return the error message. Use this when you know that only one parsing branch can reach this location, yet the source is wrong.


This parser is used by HVM.

Note: this parser is in very early stage and provides very few features.

TODO: add examples, improve documentation.

Dependencies

~16KB