Debian Codegraph @

vendor/re/src/group.ml

raw
1 (* Result of a successful match. *)
2 type t =
3 { (* Input string. Matched strings are substrings of s *)
4 s : string
5 (* Mapping from group indices to positions in gpos. group i has positions 2*i
6 - 1, 2*i + 1 in gpos. If the group wasn't matched, then its corresponding
7 values in marks will be -1,-1 *)
8 ; marks : Mark_infos.t
9 ; (* Marks positions. i.e. those marks created with Re.marks *)
10 pmarks : Pmark.Set.t
11 ; (* Group positions. Adjacent elements are (start, stop) of group match.
12 indexed by the values in marks. So group i in an re would be the substring:
13
14 start = t.gpos.(marks.(2*i)) - 1
15 stop = t.gpos.(marks.(2*i + 1)) - 1 *)
16 gpos : int array
17 ; (* Number of groups the regular expression contains. Matched or not *)
18 gcount : int
19 }
20
21 let create s ~gcount ~gpos marks pmarks = { s; gcount; gpos; marks; pmarks }
22
23 let offset_opt t i =
24 Mark_infos.offset t.marks i
25 |> Option.map (fun (start, stop) -> t.gpos.(start), t.gpos.(stop))
26 ;;
27
28 let or_not_found = function
29 | None -> raise Not_found
30 | Some s -> s
31 ;;
32
33 let offset t i = offset_opt t i |> or_not_found
34
35 let get_opt t i =
36 offset_opt t i |> Option.map (fun (p1, p2) -> String.sub t.s p1 (p2 - p1))
37 ;;
38
39 let pmarks t = t.pmarks
40 let get t i = get_opt t i |> or_not_found
41 let start_opt subs i = offset_opt subs i |> Option.map fst
42 let start subs i = start_opt subs i |> or_not_found
43 let stop_opt subs i = offset_opt subs i |> Option.map snd
44 let stop subs i = stop_opt subs i |> or_not_found
45 let test t i = Mark_infos.test t.marks i
46 let get_opt t i = if test t i then Some (get t i) else None
47 let dummy_offset = -1, -1
48
49 let all_offset t =
50 let res = Array.make t.gcount dummy_offset in
51 Mark_infos.iteri t.marks ~f:(fun i start stop ->
52 let p1 = t.gpos.(start) in
53 let p2 = t.gpos.(stop) in
54 res.(i) <- p1, p2);
55 res
56 ;;
57
58 let dummy_string = ""
59
60 let all t =
61 let res = Array.make t.gcount dummy_string in
62 Mark_infos.iteri t.marks ~f:(fun i start stop ->
63 let p1 = t.gpos.(start) in
64 let p2 = t.gpos.(stop) in
65 res.(i) <- String.sub t.s p1 (p2 - p1));
66 res
67 ;;
68
69 let pp fmt t =
70 let matches =
71 let offsets = all_offset t in
72 let strs = all t in
73 Array.to_list (Array.init (Array.length strs) (fun i -> strs.(i), offsets.(i)))
74 in
75 let open Format in
76 let open Fmt in
77 let pp_match fmt (str, (start, stop)) = fprintf fmt "@[(%s (%d %d))@]" str start stop in
78 sexp fmt "Group" (list pp_match) matches
79 ;;
80
81 let nb_groups t = t.gcount