about summary refs log tree commit diff
path: root/users/wpcarro/scratch/compiler/parser.ml
blob: dc66f2506ed3b1f9b5598149c91c9d504c6c70ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
(****************************************************************************** 
 * 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