package containers
Install
Dune Dependency
Authors
Maintainers
Sources
md5=efc44e54af764ddb969ec823b7539a3e
sha512=df7c147233f13490710e81279a365290c85d4a00280d56a5bd2a74c579568abbe08c04a60c80f2936d7c15194b58b54b112b974eb8a0d28e131bae5ef38ac10d
doc/containers/CCParse/index.html
Module CCParse
Source
Very Simple Parser Combinators
open CCParse;;
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 *>
( (try_ (char '(') *> (pure mk_node <*> self <*> self) <* char ')')
<|>
(U.int >|= mk_leaf) )
;;
parse_string_exn ptree "(1 (2 3))" ;;
parse_string_exn ptree "((1 2) (3 (4 5)))" ;;
Parse a list of words
open Containers.Parse;;
let p = U.list ~sep:"," U.word;;
parse_string_exn p "[abc , de, hello ,world ]";;
Stress Test
This makes a list of 100_000 integers, prints it and parses it back.
let p = CCParse.(U.list ~sep:"," U.int);;
let l = CCList.(1 -- 100_000);;
let l_printed =
CCFormat.(to_string (within "[" "]" (list ~sep:(return ",@,") int))) l;;
let l' = CCParse.parse_string_exn p l_printed;;
assert (l=l');;
parsing branch * message.
Input
Combinators
Takes the input and two continuations:
ok
to call with the result when it's doneerr
to call when the parser met an error
Monadic bind. p >>= f
results in a new parser which behaves as p
then, in case of success, applies f
to the result.
a <* b
parses a
into x
, parses b
and ignores its result, and returns x
.
a *> b
parses a
, then parses b
into x
, and returns x
. The results of a
is ignored.
parsing s p
behaves the same as p
, with the information that we are parsing s
, if p
fails.
Is the char a letter?
Is the char a digit?
Is the char a letter or a digit?
True on ' ' and '\t'.
True on ' ' and '\t' and '\n'.
a <?> msg
behaves like a
, but if a
fails without consuming any input, it fails with msg
instead. Useful as the last choice in a series of <|>
: a <|> b <|> c <?> "expected a|b|c"
.
try_ p
tries to parse like p
, but backtracks if p
fails. Useful in combination with <|>
.
suspend f
is the same as f ()
, but evaluates f ()
only when needed.
sep1 ~by p
parses a non empty list of p
, separated by by
.
Memoize the parser. memo p
will behave like p
, but when called in a state (read: position in input) it has already processed, memo p
returns a result directly. The implementation uses an underlying hashtable. This can be costly in memory, but improve the run time a lot if there is a lot of backtracking involving p
.
This function is not thread-safe.
Parse
Those functions have a label ~p
on the parser, since 0.14.
parse p st
applies p
on the input, and returns Ok x
if p
succeeds with x
, or Error s
otherwise.
parse_file p file
parses file
with p
by opening the file and reading it whole.
Infix
Utils
This is useful to parse OCaml-like values in a simple way.