tvl-depot/users/wpcarro/scratch/compiler/parser.ml
William Carroll bd0bf6ea7d feat(wpcarro/compiler): Support Vector type
Support an array that dynamically resizes itself, and replace usages of `List`,
`Array`, and `Queue` with `Vec`.

Change-Id: I910b140b7c1bdddae40e08f8191986dccbc6fddf
Reviewed-on: https://cl.tvl.fyi/c/depot/+/7080
Tested-by: BuildkiteCI
Reviewed-by: wpcarro <wpcarro@gmail.com>
2022-10-25 04:32:59 +00:00

47 lines
1.2 KiB
OCaml

(******************************************************************************
* Defines a generic parser class.
******************************************************************************)
open Vec
exception ParseError of string
type token = string
type state = { i : int; tokens : token vec }
class parser (tokens : token vec) =
object (self)
val mutable tokens = tokens
val mutable i = ref 0
method advance = i := !i + 1
method prev : token option = Vec.get (!i - 1) tokens
method curr : token option = Vec.get !i tokens
method next : token option = Vec.get (!i + 1) tokens
method consume : token option =
match self#curr with
| None -> None
| Some x as res ->
self#advance;
res
method expect (x : token) =
match self#curr with
| Some y when x = y -> self#advance
| _ -> raise (ParseError (Printf.sprintf "Expected %s" x))
method matches (x : token) : bool =
match self#curr with
| None -> false
| Some y ->
if x = y then
begin
self#advance;
true
end
else false
method exhausted : bool = !i >= Vec.length tokens
method state : state = { i = !i; tokens }
end