Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add backtrack parser. #220

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/angstrom.ml
Original file line number Diff line number Diff line change
Expand Up @@ -741,3 +741,9 @@ let parse_string ~consume p s =
let bs = Bigstringaf.create len in
Bigstringaf.unsafe_blit_from_string s ~src_off:0 bs ~dst_off:0 ~len;
parse_bigstring ~consume p bs

let backtrack n =
{ run = fun input pos more fail succ ->
if pos - n < Input.(parser_committed_bytes input)
then fail input pos more [] "not enough uncommited bytes to backtrack"
else succ input (pos - n) more () }
1 change: 1 addition & 0 deletions lib/angstrom.mli
Original file line number Diff line number Diff line change
Expand Up @@ -686,3 +686,4 @@ end

val pos : int t
val available : int t
val backtrack : int -> unit t
36 changes: 36 additions & 0 deletions lib_test/test_angstrom.ml
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,41 @@ let consume =
]
;;

let backtrack =
let parse name p res =
let open Angstrom in
Alcotest.(check (result (string) string))
name
(parse_string ~consume:Prefix p "abcdef")
res
in
[ "backtrack 0 is nop", `Quick, begin fun () ->
parse
"backtracking works"
(char 'a' *> char 'b' *> backtrack 0 *> take 3)
(Ok "cde")
end;
"backtracking works", `Quick, begin fun () ->
parse
"backtracking works"
(char 'a' *> char 'b' *> backtrack 2 *> take 3)
(Ok "abc")
end;
"backtracking past beginning fails", `Quick, begin fun () ->
parse
"backtracking works"
(char 'a' *> char 'b' *> backtrack 3 *> take 3)
(Error ": not enough uncommited bytes to backtrack")
end;
"backtracking past commit point fails", `Quick, begin fun () ->
parse
"backtracking works"
(char 'a' *> commit *> char 'b' *> backtrack 2 *> take 3)
(Error ": not enough uncommited bytes to backtrack")
end
]
;;

let () =
Alcotest.run "test suite"
[ "basic constructors" , basic_constructors
Expand All @@ -446,4 +481,5 @@ let () =
; "choice and commit" , choice_commit
; "input" , input
; "consume" , consume
; "backtrack" , backtrack
]