package parseff

  1. Overview
  2. Docs

Combinators

Combinators compose simple parsers into more complex ones. They handle alternation, error labeling, lookahead, and recursion.

Alternation

or_

Parseff.or_ tries the left parser. If it fails, backtracks (resets the cursor) and tries the right parser.

val or_ : (unit -> 'a) -> (unit -> 'a) -> unit -> 'a
let bool_parser () =
  Parseff.or_
    (fun () ->
      let _ = Parseff.consume "true" in
      true)
    (fun () ->
      let _ = Parseff.consume "false" in
      false)
    ()
(* "true"  -> Ok true  *)
(* "false" -> Ok false *)
(* "maybe" -> Error: expected "false" or "true", found 'maybe' *)

On "maybe", both branches fail at the same position (position 0). Parseff merges what each branch expected into one sorted list: expected "false" or "true". The order of the branches does not change the message.

If the branches fail at different positions, the parse reports the failure that reached the furthest position. On "tr" the left branch fails at the end of the input, which is further than the mismatch of the right branch, so the error says expected "ue", found end of input at position 2.

A failure is recorded when it happens, not when the parse gives up. A branch that fails and is abandoned still counts if it went further than anything else, even when a later alternative succeeds.

or_ is ideal for two alternatives. When you have more, use Parseff.one_of, which takes a list and avoids nested or_ calls:

let keyword_with_or () =
  Parseff.or_
    (fun () -> Parseff.consume "let")
    (fun () ->
      Parseff.or_
        (fun () -> Parseff.consume "const")
        (fun () -> Parseff.consume "var")
        ())
    ()

let keyword_with_one_of () =
  Parseff.one_of
    [
      (fun () -> Parseff.consume "let");
      (fun () -> Parseff.consume "const");
      (fun () -> Parseff.consume "var");
    ]
    ()

one_of

Parseff.one_of tries each parser in order until one succeeds. Equivalent to chaining or_, but cleaner for more than two alternatives.

val one_of : (unit -> 'a) list -> unit -> 'a
let json_value () =
  Parseff.one_of
    [
      null_parser;
      bool_parser;
      number_parser;
      string_parser;
      array_parser;
      object_parser;
    ]
    ()

Error composition follows the same rules as or_: if all parsers fail at the same position, what they expected is merged into one sorted list without duplicates: expected "else", "if", or "while". With three or more items the list ends with ", or". If they fail at different positions, the failure that progressed furthest wins.

one_of_labeled

Parseff.one_of_labeled is like Parseff.one_of, but each parser has a label. On failure, the error message reports all labels, sorted:

val one_of_labeled : (string * (unit -> 'a)) list -> unit -> 'a
let literal () =
  Parseff.one_of_labeled
    [
      ("number", fun () -> Number (Parseff.digit ()));
      ("string", string_parser);
      ("boolean", bool_parser);
    ]
    ()
(* On failure: "expected boolean, number, or string" *)

This gives users a clear picture of what was expected at a given position, without exposing internal parser details.

Each branch is wrapped by expect: only failures at the position where one_of_labeled started are replaced by the label. If a branch fails further in, for example an unterminated string, its own message is kept, because it describes the problem better than "string".

optional

Parseff.optional tries the parser. Returns Some result on success, None on failure (without consuming input).

val optional : (unit -> 'a) -> unit -> 'a option
let signed_number () =
  let sign = Parseff.optional (fun () -> Parseff.char '-') () in
  let n = number () in
  match sign with
  | Some _ -> -n
  | None -> n
(* "42"  -> 42  *)
(* "-42" -> -42 *)

Lookahead

look_ahead

Parseff.look_ahead runs a parser without consuming input. The cursor stays where it was before the call. Fails if the parser fails.

val look_ahead : (unit -> 'a) -> 'a
let peek_open_paren () =
  let _ = Parseff.look_ahead (fun () -> Parseff.char '(') in
  (* cursor hasn't moved, '(' is still the next character *)
  parse_parenthesized_expr ()

Useful for context-sensitive decisions: peek at what's coming, then choose which parser to run.

Error labeling

expect

Parseff.expect runs a parser and relabels its failure with a clearer message. The error reads expected <description>.

val expect : string -> (unit -> 'a) -> 'a
let dot () =
  Parseff.expect "a dot separator" (fun () -> Parseff.char '.')

let digit_val () = Parseff.expect "a digit (0-9)" Parseff.digit

Use expect at grammar boundaries where user-facing wording is better than raw token names:

let ip_address () =
  let a = number () in
  let _ = Parseff.expect "a dot separator" (fun () -> Parseff.char '.') in
  let b = number () in
  let _ = Parseff.expect "a dot separator" (fun () -> Parseff.char '.') in
  let c = number () in
  let _ = Parseff.expect "a dot separator" (fun () -> Parseff.char '.') in
  let d = number () in
  (a, b, c, d)

Without expect, a failed char '.' reports expected '.'. With expect, it reports expected a dot separator.

expect relabels only failures at the position where the parser started. In expect "key" (fun () -> consume "id:"; digit ()), the input "foo" reports expected key, but "id:x" reports expected digit at offset 3, because the parser got past "id:" and the digit message is more precise.

Naming constructs

context

Parseff.context runs a parser inside a named construct. The name does not change what the parser accepts. A failure that happens inside it remembers which constructs were open, outermost first, so an error report can say "while parsing array".

val context : ?delimited:bool -> string -> (unit -> 'a) -> 'a
let array_parser value () =
  Parseff.context ~delimited:true "array" (fun () ->
      let _ = Parseff.char '[' in
      let xs =
        Parseff.sep_by value
          (fun () ->
            Parseff.skip_whitespace ();
            Parseff.char ',')
          ()
      in
      Parseff.skip_whitespace ();
      let _ = Parseff.char ']' in
      xs)

Use ~delimited:true for constructs that have an opening token, such as an array or a block. A parser that never calls context pays nothing for it. Each call costs about 100 instructions, so name constructs, not single tokens.

A construct is reported only when the failure is strictly past the place where it started. An alternative that fails at its first byte, such as an array tried where there is no opening bracket, does not appear in the list.

If two failures tie at the furthest position, the construct list of the first one is kept.

cut

Parseff.cut declares that the construct that is running is decided. Parseff.commit seals the nearest frame only. cut seals every or_, one_of, many, sep_by, optional and fold_* frame that was opened since the innermost enclosing context. It stops at Parseff.look_ahead.

val cut : unit -> unit

If the enclosing context then fails, the frames outside it are sealed too, so an enclosing or_, many or sep_by cannot swallow the failure:

let statement () =
  Parseff.context "statement" (fun () ->
      Parseff.or_
        (fun () ->
          let _ = Parseff.consume "let" in
          Parseff.cut ();
          Parseff.skip_whitespace ();
          let _ = Parseff.take_while ~at_least:1 ~label:"name" (fun c -> c >= 'a' && c <= 'z') in
          Parseff.skip_whitespace ();
          let _ = Parseff.char '=' in
          Parseff.skip_whitespace ();
          let _ = Parseff.take_while ~at_least:1 ~label:"expression" (fun c -> c >= '0' && c <= '9') in
          Parseff.char ';')
        (fun () ->
          let _ = Parseff.take_while ~at_least:1 (fun c -> c >= '0' && c <= '9') in
          Parseff.char ';')
        ())

let statements () = Parseff.many (fun () -> Parseff.skip_whitespace (); statement ()) ()
(* "let x = 1; 2;"  -> Ok [';'; ';'] *)
(* "let x = ;"      -> Error at 8: expected expression *)

With commit () in place of cut (), only the or_ is sealed, many stops and statements returns [] without reading the rest of the input. With cut (), the failure of let x = ; is the error of the parse.

cut also helps streaming: sealed frames no longer pin buffered input. See streaming.

Recursion

rec_

Parseff.rec_ marks a recursive entry point for depth tracking. Wrap the body of recursive parsers with rec_ so that Parseff.parse can enforce max_depth and fail cleanly instead of overflowing the stack.

val rec_ : (unit -> 'a) -> 'a
let rec json () =
  Parseff.rec_ (fun () ->
    Parseff.skip_whitespace ();
    Parseff.one_of
      [
        array_parser;
        object_parser;
        null_parser;
        bool_parser;
        number_parser;
        string_parser;
      ]
      ()
  )

and array_parser () =
  let _ = Parseff.consume "[" in
  (* ... calls json () recursively ... *)
  let _ = Parseff.consume "]" in
  Array elements

The ~max_depth parameter on Parseff.parse controls the limit (default: 128):

(* Reject inputs nested deeper than 64 levels *)
Parseff.parse ~max_depth:64 input json

When the limit is exceeded, parsing fails with "maximum nesting depth N exceeded" rather than a stack overflow.

Tip: Only wrap the top-level recursive entry point with rec_. You don't need it on every mutually recursive function, just the one that represents "entering a new nesting level".