Source file reason_multi_parser.ml

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
48
49
50
51
52
53
54
55
56
module S = Reason_single_parser

type 'a parser = 'a S.parser list

let initial entry_point position = [ S.initial entry_point position ]

type 'a step =
  | Intermediate of 'a parser
  | Success of 'a * Reason_lexer.invalid_docstrings
  | Error

let rec fork token = function
  | [] -> []
  | x :: xs ->
    (match S.step x token with
    | S.Intermediate x' -> x :: x' :: fork token xs
    | _ -> x :: fork token xs)

let rec progress_successful token acc = function
  | [] -> Intermediate (List.rev acc)
  | x :: xs ->
    (match S.step x token with
    | S.Intermediate p -> progress_successful token (p :: acc) xs
    | S.Error -> progress_successful token acc xs
    | S.Success (result, ds) -> Success (result, ds))

let step parsers token =
  match token with
  | Reason_parser.ES6_FUN, _, _ ->
    (* Fork case *)
    Intermediate (fork token parsers)
  | _ ->
    (* Regular case *)
    (match parsers with
    | [ x ] ->
      (* Fast-path: One parser *)
      (match S.step x token with
      | S.Intermediate parser -> Intermediate [ parser ]
      | S.Success (result, ds) -> Success (result, ds)
      | S.Error -> Error)
    (* Parallel parsing case *)
    | x :: xs ->
      (match S.step x token with
      | S.Intermediate p -> progress_successful token [ p ] xs
      | S.Success (result, ds) -> Success (result, ds)
      | S.Error ->
        (match progress_successful token [] xs with
        | Intermediate [] -> Error
        | result -> result))
    (* Impossible case *)
    | [] -> assert false)

(* Interface for recovery *)

let recover cp ds = [ S.recover cp ds ]
let recovery_env = function [] -> assert false | x :: _xs -> S.recovery_env x