misc.ml 9.53 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
(******************************************************************************)
(*                                                                            *)
(*                                   Menhir                                   *)
(*                                                                            *)
(*                       François Pottier, Inria Paris                        *)
(*              Yann Régis-Gianas, PPS, Université Paris Diderot              *)
(*                                                                            *)
(*  Copyright Inria. All rights reserved. This file is distributed under the  *)
(*  terms of the GNU General Public License version 2, as described in the    *)
(*  file LICENSE.                                                             *)
(*                                                                            *)
(******************************************************************************)
13 14 15 16

let ( $$ ) x f = f x

let unSome = function
POTTIER Francois's avatar
POTTIER Francois committed
17
    None -> assert false
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
  | Some x -> x

let o2s o f =
  match o with
  | None ->
      ""
  | Some x ->
      f x

let single = function
  | [ x ] ->
      x
  | _ ->
      assert false

let rec mapd f = function
  | [] ->
      []
  | x :: xs ->
      let y1, y2 = f x in
      y1 :: y2 :: mapd f xs

let tabulate n f =
  let a = Array.init n f in
  Array.get a

let tabulateb n f =
  let a = Array.init n f in
  Array.get a,
  Array.fold_left (fun count element ->
    if element then count + 1 else count
  ) 0 a

let tabulatef number fold n dummy f =
52
  let a = Array.make n dummy in
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
  let () = fold (fun () element ->
    a.(number element) <- f element
  ) () in
  let get element =
    a.(number element)
  in
  get

let tabulateo number fold n f =
  let c = ref 0 in
  let get =
    tabulatef number fold n None (fun element ->
      let image = f element in
      begin match image with
      | Some _ ->
68
          incr c
69
      | None ->
70
          ()
71 72 73 74 75 76
      end;
      image
    )
  in
  get, !c

77
module IntSet = Set.Make (struct
78 79 80
                            type t = int
                            let compare = ( - )
                          end)
81

82 83
type 'a iter = ('a -> unit) -> unit

84
let separated_iter_to_string printer separator iter =
85 86 87 88 89 90 91 92 93 94 95 96 97 98
  let b = Buffer.create 32 in
  let first = ref true in
  iter (fun x ->
    if !first then begin
      Buffer.add_string b (printer x);
      first := false
    end
    else begin
      Buffer.add_string b separator;
      Buffer.add_string b (printer x)
    end
  );
  Buffer.contents b

99
let separated_list_to_string printer separator xs =
100 101 102 103 104 105 106 107 108 109 110 111
  separated_iter_to_string printer separator (fun f -> List.iter f xs)

let terminated_iter_to_string printer terminator iter =
  let b = Buffer.create 32 in
  iter (fun x ->
    Buffer.add_string b (printer x);
    Buffer.add_string b terminator
  );
  Buffer.contents b

let terminated_list_to_string printer terminator xs =
  terminated_iter_to_string printer terminator (fun f -> List.iter f xs)
112

113
let index_map string_map =
114
  let n = StringMap.cardinal string_map in
115
  let a = Array.make n None in
116
  let conv, _ = StringMap.fold
117 118 119
    (fun k v (conv, idx) ->
       a.(idx) <- Some (k, v);
       StringMap.add k idx conv, idx + 1)
120
    string_map (StringMap.empty, 0)
121 122 123 124
  in
    ((fun n -> snd (unSome a.(n))),
     (fun k -> StringMap.find k conv),
     (fun n -> fst (unSome a.(n))))
125

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
let support_assoc l x =
  try
    List.assoc x l
  with Not_found -> x

let index (strings : string list) : int * string array * int StringMap.t =
  let name = Array.of_list strings
  and n, map = List.fold_left (fun (n, map) s ->
    n+1, StringMap.add s n map
  ) (0, StringMap.empty) strings in
  n, name, map

(* Turning an implicit list, stored using pointers through a hash
   table, into an explicit list. The head of the implicit list is
   not included in the explicit list. *)

let materialize (table : ('a, 'a option) Hashtbl.t) (x : 'a) : 'a list =
  let rec loop x =
    match Hashtbl.find table x with
    | None ->
146
        []
147
    | Some x ->
148
        x :: loop x
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
  in
  loop x

(* [iteri] implements a [for] loop over integers, from 0 to
   [n-1]. *)

let iteri n f =
  for i = 0 to n - 1 do
    f i
  done

(* [foldi] implements a [for] loop over integers, from 0 to [n-1],
   with an accumulator. [foldij] implements a [for] loop over
   integers, from [start] to [n-1], with an accumulator. *)

let foldij start n f accu =
  let rec loop i accu =
    if i = n then
      accu
    else
      loop (i+1) (f i accu)
  in
  loop start accu

let foldi n f accu =
  foldij 0 n f accu

POTTIER Francois's avatar
POTTIER Francois committed
176
(* [mapij start n f] produces the list [ f start; ... f (n-1) ]. *)
177

POTTIER Francois's avatar
POTTIER Francois committed
178
let mapij start n f =
179
  List.rev (
POTTIER Francois's avatar
POTTIER Francois committed
180
    foldij start n (fun i accu ->
181 182 183 184
      f i :: accu
    ) []
  )

POTTIER Francois's avatar
POTTIER Francois committed
185 186 187 188 189
(* [mapi n f] produces the list [ f 0; ... f (n-1) ]. *)

let mapi n f =
  mapij 0 n f

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
(* [qfold f accu q] repeatedly takes an element [x] off the queue [q]
   and applies [f] to the accumulator and to [x], until [q] becomes
   empty. Of course, [f] can add elements to [q] as a side-effect.

   We allocate an option to ensure that [qfold] is tail-recursive. *)

let rec qfold f accu q =
  match
    try
      Some (Queue.take q)
    with Queue.Empty ->
      None
  with
  | Some x ->
      qfold f (f accu x) q
  | None ->
      accu

(* [qiter f q] repeatedly takes an element [x] off the queue [q] and
   applies [f] to [x], until [q] becomes empty. Of course, [f] can add
   elements to [q] as a side-effect. *)

let qiter f q =
  try
    while true do
      f (Queue.take q)
    done
  with Queue.Empty ->
    ()

let rec smap f = function
  | [] ->
      []
  | (x :: xs) as l ->
      let x' = f x
      and xs' = smap f xs in
      if x == x' && xs == xs' then
227
        l
228
      else
229
        x' :: xs'
230 231 232 233 234 235 236 237 238

let rec smapa f accu = function
  | [] ->
      accu, []
  | (x :: xs) as l ->
      let accu, x' = f accu x in
      let accu, xs' = smapa f accu xs in
      accu,
      if x == x' && xs == xs' then
239
        l
240
      else
241
        x' :: xs'
242 243

let normalize s =
POTTIER Francois's avatar
POTTIER Francois committed
244
  let s = Bytes.of_string s in
POTTIER Francois's avatar
POTTIER Francois committed
245
  let n = Bytes.length s in
246
  for i = 0 to n - 1 do
POTTIER Francois's avatar
POTTIER Francois committed
247
    match Bytes.get s i with
248 249 250
    | '('
    | ')'
    | ',' ->
251
        Bytes.set s i '_'
252
    | _ ->
253
        ()
254
  done;
POTTIER Francois's avatar
POTTIER Francois committed
255
  Bytes.unsafe_to_string s
256 257 258 259 260 261 262 263

(* [postincrement r] increments [r] and returns its original value. *)

let postincrement r =
  let x = !r in
  r := x + 1;
  x

264
(* [map_opt f l] returns the list of [y]s such that [f x = Some y] where [x]
265
   is in [l], preserving the order of elements of [l]. *)
266 267 268 269 270 271
let map_opt f l =
  List.(rev (fold_left (fun ys x ->
    match f x with
      | None -> ys
      | Some y -> y :: ys
  ) [] l))
272

273
let new_intern capacity =
274
  (* Set up a a hash table, mapping strings to unique integers. *)
275 276 277 278 279 280
  let module H = Hashtbl.Make(struct
    type t = string
    let equal = (=)
    let hash = Hashtbl.hash
  end) in
  let table = H.create capacity in
281
  (* This counts the calls to [intern]. *)
POTTIER Francois's avatar
POTTIER Francois committed
282
  let c = ref 0 in
283
  (* A string is mapped to a unique string, as follows. *)
284 285
  let intern s =
    c := !c + 1;
286 287 288 289 290
    try
      H.find table s
    with Not_found ->
      H.add table s s;
      s
291 292 293
  and verbose () =
    Printf.fprintf stderr
      "%d calls to intern; %d unique strings.\n%!"
POTTIER Francois's avatar
POTTIER Francois committed
294
      !c (H.length table)
295 296
  in
  intern, verbose
297

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
let new_encode_decode capacity =
  (* Set up a a hash table, mapping strings to unique integers. *)
  let module H = Hashtbl.Make(struct
    type t = string
    let equal = (=)
    let hash = Hashtbl.hash
  end) in
  let table = H.create capacity in
  (* Set up a resizable array, mapping integers to strings. *)
  let text = MenhirLib.InfiniteArray.make "" in
  (* This counts the calls to [encode]. *)
  let c = ref 0 in
  (* A string is mapped to a unique integer, as follows. *)
  let encode (s : string) : int =
    c := !c + 1;
    try
      H.find table s
    with Not_found ->
      (* The number of elements in the hash table is the next available
         unique integer code. *)
      let i = H.length table in
      H.add table s i;
      MenhirLib.InfiniteArray.set text i s;
      i
  (* An integer code can be mapped back to a string, as follows. *)
  and decode (i : int) : string =
    MenhirLib.InfiniteArray.get text i
  and verbose () =
    Printf.fprintf stderr
      "%d calls to intern; %d unique strings.\n%!"
      !c (H.length table)
  in
  encode, decode, verbose

POTTIER Francois's avatar
POTTIER Francois committed
332 333 334
let rec best (preferable : 'a -> 'a -> bool) (xs : 'a list) : 'a option =
  match xs with
  | [] ->
335 336 337
      (* Special case: no elements at all, so no best element. This case
         does not participate in the recursion. *)
      None
POTTIER Francois's avatar
POTTIER Francois committed
338 339 340 341 342 343 344 345
  | [x] ->
      Some x
  | x :: xs ->
      (* If [x] is preferable to every element of [xs], then it is the
         best element of [x :: xs]. *)
      if List.for_all (preferable x) xs then
        Some x
      else
346
        (* [xs] is nonempty, so the recursive call is permitted. *)
POTTIER Francois's avatar
POTTIER Francois committed
347 348 349 350 351 352 353 354 355 356 357 358
        match best preferable xs with
        | Some y ->
            if preferable y x then
              (* If [y] is the best element of [xs] and [y] is preferable to
                 [x], then [y] is the best element of [x :: xs]. *)
              Some y
            else
              (* There is no best element. *)
              None
        | None ->
            (* There is no best element. *)
            None
POTTIER Francois's avatar
POTTIER Francois committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377

let rec levels1 cmp x1 xs =
  match xs with
  | [] ->
      [x1], []
  | x2 :: xs ->
      let ys1, yss = levels1 cmp x2 xs in
      if cmp x1 x2 = 0 then
        x1 :: ys1, yss
      else
        [x1], ys1 :: yss

let levels cmp xs =
  match xs with
  | [] ->
      []
  | x1 :: xs ->
      let ys1, yss = levels1 cmp x1 xs in
      ys1 :: yss
POTTIER Francois's avatar
POTTIER Francois committed
378 379 380 381 382 383 384

let once x y =
  let s = ref x in
  fun () ->
    let result = !s in
    s := y;
    result