package parseff

All checked builds pass
  1. Overview
  2. Docs
Direct-style parser combinator library for OCaml 5 with zero-copy spans

Install

dune-project
 Dependency

Authors

Maintainers

Sources

parseff-0.5.0.tbz
sha256=dad671e98bdf1816c76a5e61da157bf38a986057ed2f9416573143bb8f1afcce
sha512=2ac03f296c73611ff6905e29c6c7df5bc3319933dbe3525a165d28f1dd56d4af4db5a0093b0d805064dc310322cef4e8b03ba1b2faf8890af2f202552e8ed2d7

doc/errors.html

Error handling

Parseff exposes four main APIs for error handling:

Built-in errors and custom errors

A parse fails with one of two sorts of error.

Built-in errors come from Parseff itself: a primitive such as Parseff.char does not match, Parseff.fail stops with a message, or a limit such as max_depth is reached. Their kind is Expected, Failure, Depth_limit_exceeded or Backtrack_window_exceeded. You do not declare them, and Parseff.render_error prints them with a full message.

Custom errors are cases you add to Parseff.custom_error. You raise them with Parseff.error and get them back in kind as Custom. Use them when the input has the right shape but a wrong value, such as a number out of range, and the caller must handle that case in code, not only print it. Give Parseff.render_error a ~custom printer to print them.

type Parseff.custom_error += Out_of_range of int

let rating () =
  let n = Parseff.digit () in
  if n < 1 || n > 5 then Parseff.error (Out_of_range n) else n

let () =
  match Parseff.parse "7" rating with
  | Ok n -> Printf.printf "Got %d\n" n
  | Error { kind = Custom (Out_of_range n); _ } ->
      Printf.printf "%d is out of range\n" n
  | Error e -> prerr_endline (Parseff.render_error e)

fail

Abort parsing with a message. The message is returned as Error { kind = Failure msg; ... }.

val fail : ?from:int -> ?notes:note list -> string -> 'a
let byte () =
  let n =
    int_of_string
      (Parseff.take_while ~at_least:1
         (fun c -> c >= '0' && c <= '9')
         ~label:"digit")
  in
  if n >= 0 && n <= 255 then n
  else Parseff.fail "number must be between 0 and 255"

let () =
  match Parseff.parse "300" byte with
  | Error { kind = Failure msg; range; _ } ->
      (* range.start = 3, msg = "number must be between 0 and 255" *)
      Printf.printf "Error at %d: %s\n" range.start msg
  | Ok n -> Printf.printf "Got: %d\n" n
  | Error _ -> ()

Use this when a human-readable string is enough.

~from makes the error cover the bytes from from to the current position instead of a single position, so the rendered error underlines the whole value. ~notes attaches annotations: a note with a range is underlined in the source excerpt with its text, a note without one is printed as a * note: line.

let octet () =
  let start = Parseff.position () in
  let n =
    int_of_string
      (Parseff.take_while ~at_least:1 (fun c -> c >= '0' && c <= '9')
         ~label:"digit")
  in
  if n <= 255 then n
  else
    Parseff.fail ~from:start
      ~notes:[ { Parseff.at = None; text = "octets go from 0 to 255" } ]
      "octet out of range"

let () =
  match Parseff.parse "10.300" (fun () ->
      let a = octet () in
      let _ = Parseff.char '.' in
      (a, octet ()))
  with
  | Error e -> print_endline (Parseff.render_error ~name:"address" e)
  | Ok _ -> ()

which prints:

address:1:4: [error] octet out of range
1 | 10.300
  |    ^^^
  * note: octets go from 0 to 255

error

Abort parsing with a custom error value. Parseff.custom_error is an extensible variant: declare your own cases and match them in kind.

val error : ?from:int -> ?notes:note list -> custom_error -> 'a
type Parseff.custom_error += Too_large of int | Negative of int

let number () =
  let s =
    Parseff.take_while ~at_least:1 (fun c -> c >= '0' && c <= '9') ~label:"digit"
  in
  let n = int_of_string s in
  if n > 255 then Parseff.error (Too_large n)
  else if n < 0 then Parseff.error (Negative n)
  else n

let () =
  match Parseff.parse "300" number with
  | Error { kind = Custom (Too_large n); range; _ } ->
      Printf.printf "Number %d too large at position %d\n" n range.start
  | Error { kind = Custom (Negative n); range; _ } ->
      Printf.printf "Negative number %d at position %d\n" n range.start
  | Error _ -> Printf.printf "Other error\n"
  | Ok n -> Printf.printf "Got %d\n" n

Use this when callers need to pattern match on specific failure cases. ~from and ~notes work as in fail.

A typed error behaves like any other failure for backtracking: Parseff.or_ and the repetition combinators absorb it and try something else. If the parse then fails and the typed error is at the furthest failure position, it is the error that parse returns. At the same position a typed error wins over an Expected error, and the first of two typed errors wins.

A case without a payload works too:

type Parseff.custom_error += Too_large_quick | Negative_quick

let number_quick () =
  let s =
    Parseff.take_while ~at_least:1 (fun c -> c >= '0' && c <= '9') ~label:"digit"
  in
  let n = int_of_string s in
  if n > 255 then Parseff.error Too_large_quick
  else if n < 0 then Parseff.error Negative_quick
  else n

expect

Run a parser and replace its failure message with a clearer description. The error reads expected <description>.

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

let number () =
  let s =
    Parseff.take_while ~at_least:1 (fun c -> c >= '0' && c <= '9') ~label:"digit"
  in
  int_of_string s

let ip_address () =
  let a = number () in
  let _ = dot () in
  let b = number () in
  let _ = dot () in
  let c = number () in
  let _ = dot () 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 replaces only what the parser expected at the position where it started. If the parser got further before it failed, its own message stays, because it is more precise. See combinators.

context and cut

Parseff.context names a construct, for example "array". A failure inside it remembers the constructs that were open, outermost first. Parseff.cut says that the construct is decided: after cut, a failure inside the construct is not retried by an enclosing or_, many or sep_by. Use cut after the token that identifies the construct, such as let in a let statement. See combinators.

Which error a parse reports

When a parse fails, Parseff reports the furthest failure: the failure of any primitive that happened at the highest input position, also inside branches that or_, many, sep_by, optional or fold_left abandoned. Everything that was expected at that position is merged into one message, sorted and without duplicates:

(* "x" with one_of [consume "if"; consume "else"; consume "while"] *)
(* expected "else", "if", or "while", found 'x' *)

This also explains errors after a loop. With sep_by (fun () -> consume "ab") (fun () -> char ',') followed by end_of_input, the input "ab,ab,ax" reports expected "b" at offset 7. The loop stopped because "ax" is not "ab", and that is further than the end_of_input failure at offset 5.

A failure at the end of the input keeps what was expected. On "[1, 2" the error says expected ',' or ']', found end of input.

consume fails at the first byte that differs from the literal and expects the rest of it. Parseff.commit forgets the failures at or beyond its position, so a committed branch reports only what it expected itself.

The error value

A failed parse returns Error e, where e is a Parseff.error:

type error = {
  kind : error_kind;
  range : range;  (** the bytes the error is about, empty at the end of the input *)
  location : location option;
      (** line and column of [range.start], [None] when the line is not known; [col] counts bytes, the column [render_error] prints counts Unicode characters *)
  contexts : context list;  (** open constructs, outermost first *)
  notes : note list;
  excerpt : excerpt;
}

error and the types it holds are private: you can read and match them, not build them. Parseff.note and Parseff.range stay buildable, for ~notes of Parseff.fail.

kind says what happened:

  • Expected { items; found; more }: a primitive failed. items is everything that was expected at the furthest failure position, sorted and without duplicates: Char, Literal, Label or End_of_input. found is Text with the text at that position, End at the end of the input, Short n when a read of a fixed number of bytes, such as take, found only n bytes before the end of the input, or Value with the integer read in the same width when BE.int16 and its relatives do not match. Characters print as 'x', literals as "abc" and labels as written. items holds at most 64 items; more counts the alternatives past that, 0 otherwise.
  • Failure msg: a failure raised with Parseff.fail, or "no alternative matched" when one_of [] is the only failure at the furthest position. Failures of primitives are always Expected, so they merge with the other alternatives that were expected at the same position. Unlike Expected, fail is not caught by backtracking combinators (Parseff.or_, Parseff.many, etc.) or relabeling combinators (Parseff.expect, Parseff.one_of_labeled).
  • Custom e: a value given to Parseff.error.
  • Depth_limit_exceeded { limit }: a Parseff.rec_ call exceeded the ~max_depth limit.
  • Backtrack_window_exceeded { limit; oldest }: a streaming parser needed more rewind history than ~backtrack_window allows.

The match on kind is exhaustive: the compiler tells you when a case is missing. Custom holds an Parseff.custom_error, which is extensible, so match it with a final _ case.

match Parseff.parse input parser with
| Ok value -> value
| Error { kind = Custom (Too_large n); _ } -> handle_too_large n
| Error e -> prerr_endline (Parseff.render_error ~name:"input" e); exit 1

Rendering errors

Parseff.render_error prints an error with its source line, a caret under the failure and what the parser was doing:

input.json:4:5: [error] expected ',' or '}', found '"'
2 |     "config": {
  | ╭─────────────╯
3 | │     "a": 1
4 | │     "b": 2
  | ╰─────^
  * while parsing object, from 2:13
  * while parsing object, from 1:1
  • The header is name:line:col: [error] message. Without ~name it starts at line:col.
  • The message is expected A, B, or C, found X. A message lists at most 8 expected items, then , or N more alternatives. found X is a quoted identifier-like run (up to 32 bytes, found 'abc'... when it is cut) or one code point, with control bytes, non-breaking spaces and other invisible code points escaped as \x1B or \u{00A0}, or end of input. A take that finds too few bytes says found only 3 (end of input), and a binary integer that differs says expected int16be 0x0001, found 0x0002.
  • When the line of the error is not known, which happens in streaming when the position is older than the buffered input, the header is input.json: byte N: [error] message and there is no excerpt. The * lines are then indented by two spaces.
  • Carets cover the range, one per code point. Tabs in the line are kept, so the caret lines up for any tab width. Control bytes, invalid UTF-8 bytes and C1 control characters in the line print as the escapes of the message, such as \x1B, and the carets cover the whole escape.
  • * while parsing name, from line:col lines come from Parseff.context, innermost first, at most five; when only one more is hidden it is printed too. A construct made with ~delimited:true that started on an earlier line is shown as a bar that joins its opening token to the caret: ╭─╯ under the opener, │ on the lines in between and ╰──^ at the failure. A single hidden line between the opener and the failure is shown, longer gaps become a ... row in the gutter.
  • Notes print as * note: lines, or as a - underline on their line when they have a range.
  • A Parseff.rec_ nested deeper than ~max_depth and a streaming parse that exceeds ~backtrack_window keep the * while parsing lines that were open, and end with * help: raise ~max_depth or * help: call commit or cut earlier, or raise ~backtrack_window.
  • ~custom is a printer custom_error -> string for Custom errors. Without it, the message is custom error (no ~custom printer given).
  • The rows the renderer adds never end with a space. Source text is printed byte for byte, so a source line with trailing spaces keeps them.

~source gives the input to read the lines from. Without it the lines kept inside the error are used: the error line, the line before it and the line of the opener, each cut to 240 bytes around the failure. That is enough for in-memory and streaming parses; with a streaming source the old lines may be gone and the context line then says from byte N. Parseff.error_message returns only the one-line message.

The columns of the header and of the * while parsing lines count Unicode characters (code points), like the carets, while location.col counts bytes (see the UTF-8 page of the API documentation). When streaming has dropped the start of a line and ~source is not given, the character column is not known: the header is input.json: byte N: [error] ..., the excerpt of the error line is still printed and cut on the left with ..., and the context line says from byte N.

input.json:1:6: [error] expected ',' or ']', found '"'
1 | ["é" "b"]
  |      ^

Migrating from 0.4

Error { pos; error } with built-in polymorphic variants became Error e with a record. The common migration is one line:

(* before *)
| Error { pos; error = `Expected msg } -> Printf.printf "%d: %s\n" pos msg
(* after *)
| Error e -> prerr_endline (Parseff.render_error ~name:"input" e)

Custom errors move from the variant row into kind, with type Parseff.custom_error += Too_large of int. The built-in cases become cases of kind too:

(* before *)
| Error { error = `Too_large n; _ } -> ...
| Error { error = `Failure msg; _ } -> ...
| Error { error = `Unexpected_end_of_input; _ } -> ...
(* after *)
| Error { kind = Custom (Too_large n); _ } -> ...
| Error { kind = Failure msg; _ } -> ...
| Error { kind = Expected { found = End; _ }; _ } -> ...

The 0.4 messages of primitives that were not expectations (invalid UTF-8, failed regex, mismatched BE.int16) are now Expected items: valid UTF-8, text matching the pattern and int16be 0xFFFE. An error at the end of the input now says what was expected. The position is e.range.start.