package containers

  1. Overview
  2. Docs

Very Simple Parser Combinators

Examples:

parse recursive structures
open Containers_string.Parse;;

type tree = L of int | N of tree * tree;;

let mk_leaf x = L x
let mk_node x y = N(x,y)

let ptree = fix @@ fun self ->
  skip_space *>
  ( (char '(' *> (pure mk_node <*> self <*> self) <* char ')')
    <|>
    (U.int >|= mk_leaf) )
;;

parse_string_exn "(1 (2 3))" ptree;;
parse_string_exn "((1 2) (3 (4 5)))" ptree;;
Parse a list of words
open Containers_string.Parse;;
let p = U.list ~sep:"," U.word;;
parse_string_exn "[abc , de, hello ,world  ]" p;;
  • since 0.11
type 'a or_error = [
  1. | `Ok of 'a
  2. | `Error of string
]
exception ParseError of int * string

position * message

Input

type input = {
  1. is_done : unit -> bool;
    (*

    End of input?

    *)
  2. cur : unit -> char;
    (*

    Current char

    *)
  3. next : unit -> char;
    (*

    if not is_done, move to next char

    *)
  4. pos : unit -> int;
    (*

    Current pos

    *)
  5. backtrack : int -> unit;
    (*

    Restore to previous pos

    *)
  6. sub : int -> int -> string;
    (*

    sub pos len extracts slice from pos with len

    *)
}
val input_of_string : string -> input

Combinators

type 'a t = input -> 'a
val return : 'a -> 'a t
val pure : 'a -> 'a t

synonym to return

val (>|=) : 'a t -> ('a -> 'b) -> 'b t

synonym to return

val (>>=) : 'a t -> ('a -> 'b t) -> 'b t
val (<*>) : ('a -> 'b) t -> 'a t -> 'b t
val (<*) : 'a t -> _ t -> 'a t
val (*>) : _ t -> 'a t -> 'a t
val fail : string -> 'a t
val eoi : unit t

end of string

val nop : unit t

end of string

do nothing

val char : char -> char t
val char_if : (char -> bool) -> char t
val chars_if : (char -> bool) -> string t
val chars1_if : (char -> bool) -> string t

non empty

val endline : char t

non empty

val space : char t

tab or space

val white : char t

tab or space

tab or space or newline

val skip_chars : (char -> bool) -> unit t

Skip 0 or more chars

val skip_space : unit t

Skip 0 or more chars

val skip_white : unit t
val is_alpha : char -> bool
val is_num : char -> bool
val is_alpha_num : char -> bool
val is_space : char -> bool
val (~~~) : (char -> bool) -> char -> bool
val (|||) : (char -> bool) -> (char -> bool) -> char -> bool
val (&&&) : (char -> bool) -> (char -> bool) -> char -> bool
val (<|>) : 'a t -> 'a t -> 'a t
val string : string -> string t
val many : 'a t -> 'a list t
val many1 : 'a t -> 'a list t

non empty

val skip : _ t -> unit t

non empty

val sep : by:_ t -> 'a t -> 'a list t
val sep1 : by:_ t -> 'a t -> 'a list t

non empty

val fix : ('a t -> 'a t) -> 'a t

Fixpoint combinator

Parse

val parse : input:input -> 'a t -> 'a or_error
val parse_exn : input:input -> 'a t -> 'a
val parse_string : string -> 'a t -> 'a or_error
val parse_string_exn : string -> 'a t -> 'a

Utils

module U : sig ... end
OCaml

Innovation. Community. Security.