1 (* Copyright (C) 2005, HELM Team.
3 * This file is part of HELM, an Hypertextual, Electronic
4 * Library of Mathematics, developed at the Computer Science
5 * Department, University of Bologna, Italy.
7 * HELM is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * HELM is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with HELM; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22 * For details, see the HELM World-Wide-Web page,
23 * http://cs.unibo.it/helm/.
30 let profiling_enabled = false ;; (* ComponentsConf.profiling *)
32 let something_profiled = ref false
35 if !something_profiled then
39 (Printf.sprintf "!! %39s ---------- --------- --------- ---------"
40 (String.make 39 '-'));
42 (Printf.sprintf "!! %-39s %10s %9s %9s %9s"
43 "function" "#calls" "total" "max" "average"))
45 let profiling_printings = ref (fun _ -> true)
46 let set_profiling_printings f = profiling_printings := f
48 type profiler = { profile : 'a 'b. ('a -> 'b) -> 'a -> 'b }
49 let profile ?(enable = true) s =
50 if profiling_enabled && enable then
51 let total = ref 0.0 in
55 let before = Unix.gettimeofday () in
59 let after = Unix.gettimeofday () in
60 let delta = after -. before in
61 total := !total +. delta;
62 if delta > !max then max := delta;
66 let after = Unix.gettimeofday () in
67 let delta = after -. before in
68 total := !total +. delta;
69 if delta > !max then max := delta;
74 if !profiling_printings s && !calls <> 0 then
76 something_profiled := true;
78 (Printf.sprintf "!! %-39s %10d %9.4f %9.4f %9.4f"
79 s !calls !total !max (!total /. (float_of_int !calls)))
83 { profile = fun f x -> f x }
85 (** {2 Optional values} *)
87 let map_option f = function None -> None | Some v -> Some (f v)
88 let iter_option f = function None -> () | Some v -> f v
89 let unopt = function None -> failwith "unopt: None" | Some v -> v
91 (** {2 String processing} *)
93 let split ?(sep = ' ') s =
94 let pieces = ref [] in
96 match (try Some (String.index_from s idx sep) with Not_found -> None) with
98 pieces := String.sub s idx (pos - idx) :: !pieces;
100 | None -> pieces := String.sub s idx (String.length s - idx) :: !pieces
106 let rec find_left idx =
108 | ' ' | '\t' | '\r' | '\n' -> find_left (idx + 1)
111 let rec find_right idx =
113 | ' ' | '\t' | '\r' | '\n' -> find_right (idx - 1)
116 let s_len = String.length s in
117 let left, right = find_left 0, find_right (s_len - 1) in
118 String.sub s left (right - left + 1)
120 (** {2 Char processing} *)
123 let code = Char.code c in
124 (code >= 65 && code <= 90) || (code >= 97 && code <= 122)
127 let code = Char.code c in
128 code >= 48 && code <= 57
131 let code = Char.code c in
132 code = 9 || code = 10 || code = 13 || code = 32
134 let is_alphanum c = is_alpha c || is_digit c
136 (** {2 List processing} *)
138 let flatten_map f l =
139 List.flatten (List.map f l)
142 let rec list_uniq ?(eq=(=)) = function
145 | h1::h2::tl when eq h1 h2 -> list_uniq ~eq (h2 :: tl)
146 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq ~eq tl
148 let rec filter_map f =
153 | None -> filter_map f tl
154 | Some v -> v :: filter_map f tl)
156 let list_concat ?(sep = []) =
160 | [ last ] -> List.flatten (List.rev (last :: acc))
161 | hd :: tl -> aux ([sep; hd] @ acc) tl
165 let rec list_findopt f l =
166 let rec aux = function
171 | Some _ as rc -> rc)
176 let rec aux acc n l =
178 | 0, _ -> List.rev acc, l
179 | n, [] -> raise (Failure "HExtlib.split_nth")
180 | n, hd :: tl -> aux (hd :: acc) (n - 1) tl in
183 (** {2 File predicates} *)
187 (Unix.stat fname).Unix.st_kind = Unix.S_DIR
188 with Unix.Unix_error _ -> false
190 let is_regular fname =
192 (Unix.stat fname).Unix.st_kind = Unix.S_REG
193 with Unix.Unix_error _ -> false
196 let components = split ~sep:'/' path in
197 let rec aux where = function
201 if where = "" then piece else where ^ "/" ^ piece in
203 Unix.mkdir path 0o755
205 | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
206 | Unix.Unix_error (e,_,_) ->
209 ("Unix.mkdir " ^ path ^ " 0o755 :" ^ (Unix.error_message e))));
212 let where = if path.[0] = '/' then "/" else "" in
215 (** {2 Filesystem} *)
217 let input_file fname =
218 let size = (Unix.stat fname).Unix.st_size in
219 let buf = Buffer.create size in
220 let ic = open_in fname in
221 Buffer.add_channel buf ic size;
227 let buf = Buffer.create size in
228 let s = String.create size in
231 let bytes = input ic s 0 size in
232 if bytes = 0 then raise End_of_file
233 else Buffer.add_substring buf s 0 bytes
235 with End_of_file -> ());
238 let output_file ~filename ~text =
239 let oc = open_out filename in
240 output_string oc text;
244 let len = String.length s in
245 let buf = Buffer.create 0 in
249 if Buffer.length buf > 0
250 then List.rev (Buffer.contents buf :: acc)
253 if is_blank s.[i] then
254 if Buffer.length buf > 0 then begin
255 let s = Buffer.contents buf in
257 aux (s :: acc) (i + 1)
261 Buffer.add_char buf s.[i];
268 (* Rules: * "~name" -> home dir of "name"
269 * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
271 let get_home login = (Unix.getpwnam login).Unix.pw_dir in
273 let len = String.length s in
274 if len > 0 && s.[0] = '~' then begin
275 let login_len = ref 1 in
276 while !login_len < len && is_alphanum (s.[!login_len]) do
279 let login = String.sub s 1 (!login_len - 1) in
283 try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
287 home ^ String.sub s !login_len (len - !login_len)
288 with Not_found | Invalid_argument _ -> s
292 String.concat " " (List.map expand_one (blank_split s))
294 let find ?(test = fun _ -> true) path =
295 let rec aux acc todo =
300 let handle = Unix.opendir path in
302 let matching_files = ref [] in
305 match Unix.readdir handle with
308 let qentry = path ^ "/" ^ entry in
310 if is_dir qentry then
311 dirs := qentry :: !dirs
312 else if test qentry then
313 matching_files := qentry :: !matching_files;
314 with Unix.Unix_error _ -> ())
316 with End_of_file -> Unix.closedir handle);
317 aux (!matching_files @ acc) (!dirs @ tl)
318 with Unix.Unix_error _ -> aux acc tl
322 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
326 let od = Unix.opendir d in
328 let name = Unix.readdir od in
329 if name <> "." && name <> ".." then false else aux () in
330 let res = try aux () with End_of_file -> true in
334 Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
336 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
338 let rec rmdir_descend d =
339 if is_dir_empty d then
342 rmdir_descend (Filename.dirname d)
346 (** {2 Exception handling} *)
348 let finally at_end f arg =
351 with exn -> at_end (); raise exn
356 (** {2 Localized exceptions } *)
358 exception Localized of Token.flocation * exn
360 let loc_of_floc = function
361 | { Lexing.pos_cnum = loc_begin }, { Lexing.pos_cnum = loc_end } ->
364 let floc_of_loc (loc_begin, loc_end) =
366 { Lexing.pos_fname = ""; Lexing.pos_lnum = -1; Lexing.pos_bol = -1;
367 Lexing.pos_cnum = loc_begin }
369 let floc_end = { floc_begin with Lexing.pos_cnum = loc_end } in
370 (floc_begin, floc_end)
372 let dummy_floc = floc_of_loc (-1, -1)
374 let raise_localized_exception ~offset floc exn =
375 let (x, y) = loc_of_floc floc in
376 let x = offset + x in
377 let y = offset + y in
378 let flocb,floce = floc in
380 { flocb with Lexing.pos_cnum = x }, { floce with Lexing.pos_cnum = y }
382 raise (Localized (floc, exn))
384 let estimate_size x =
385 4 * (String.length (Marshal.to_string x [])) / 1024