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_rev_map_filter f l =
157 let rec aux a = function
160 begin match f hd with
162 | Some b -> aux (b :: a) tl
167 let list_rev_map_filter_fold f v l =
168 let rec aux v a = function
171 begin match f v hd with
172 | v, None -> aux v a tl
173 | v, Some b -> aux v (b :: a) tl
178 let list_concat ?(sep = []) =
182 | [ last ] -> List.flatten (List.rev (last :: acc))
183 | hd :: tl -> aux ([sep; hd] @ acc) tl
187 let rec list_findopt f l =
188 let rec aux = function
193 | Some _ as rc -> rc)
198 let rec aux acc n l =
200 | 0, _ -> List.rev acc, l
201 | n, [] -> raise (Failure "HExtlib.split_nth")
202 | n, hd :: tl -> aux (hd :: acc) (n - 1) tl in
206 let l = List.rev l in
207 try List.hd l with exn -> raise (Failure "HExtlib.list_last")
210 (** {2 File predicates} *)
214 (Unix.stat fname).Unix.st_kind = Unix.S_DIR
215 with Unix.Unix_error _ -> false
217 let writable_dir path =
219 let file = path ^ "/prova_matita" in
220 let oc = open_out file in
224 with Sys_error _ -> false
227 let is_regular fname =
229 (Unix.stat fname).Unix.st_kind = Unix.S_REG
230 with Unix.Unix_error _ -> false
232 let is_executable fname =
234 let stat = (Unix.stat fname) in
235 stat.Unix.st_kind = Unix.S_REG &&
236 (stat.Unix.st_perm land 0o001 > 0)
237 with Unix.Unix_error _ -> false
239 let chmod mode filename =
240 Unix.chmod filename mode
243 let components = split ~sep:'/' path in
244 let rec aux where = function
248 if where = "" then piece else where ^ "/" ^ piece in
250 Unix.mkdir path 0o755; chmod 0o2775 path
252 | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
253 | Unix.Unix_error (e,_,_) ->
256 ("Unix.mkdir " ^ path ^ " 0o2775 :" ^ (Unix.error_message e))));
259 let where = if path.[0] = '/' then "/" else "" in
262 (** {2 Filesystem} *)
264 let input_file fname =
265 let size = (Unix.stat fname).Unix.st_size in
266 let buf = Buffer.create size in
267 let ic = open_in fname in
268 Buffer.add_channel buf ic size;
274 let buf = Buffer.create size in
275 let s = String.create size in
278 let bytes = input ic s 0 size in
279 if bytes = 0 then raise End_of_file
280 else Buffer.add_substring buf s 0 bytes
282 with End_of_file -> ());
285 let output_file ~filename ~text =
286 let oc = open_out filename in
287 output_string oc text;
292 let len = String.length s in
293 let buf = Buffer.create 0 in
297 if Buffer.length buf > 0
298 then List.rev (Buffer.contents buf :: acc)
301 if is_blank s.[i] then
302 if Buffer.length buf > 0 then begin
303 let s = Buffer.contents buf in
305 aux (s :: acc) (i + 1)
309 Buffer.add_char buf s.[i];
316 (* Rules: * "~name" -> home dir of "name"
317 * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
319 let get_home login = (Unix.getpwnam login).Unix.pw_dir in
321 let len = String.length s in
322 if len > 0 && s.[0] = '~' then begin
323 let login_len = ref 1 in
324 while !login_len < len && is_alphanum (s.[!login_len]) do
327 let login = String.sub s 1 (!login_len - 1) in
331 try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
335 home ^ String.sub s !login_len (len - !login_len)
336 with Not_found | Invalid_argument _ -> s
340 String.concat " " (List.map expand_one (blank_split s))
342 let find ?(test = fun _ -> true) path =
343 let rec aux acc todo =
348 let handle = Unix.opendir path in
350 let matching_files = ref [] in
353 match Unix.readdir handle with
356 let qentry = path ^ "/" ^ entry in
358 if is_dir qentry then
359 dirs := qentry :: !dirs
360 else if test qentry then
361 matching_files := qentry :: !matching_files;
362 with Unix.Unix_error _ -> ())
364 with End_of_file -> Unix.closedir handle);
365 aux (!matching_files @ acc) (!dirs @ tl)
366 with Unix.Unix_error _ -> aux acc tl
370 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
374 let od = Unix.opendir d in
376 let name = Unix.readdir od in
377 if name <> "." && name <> ".." then false else aux () in
378 let res = try aux () with End_of_file -> true in
382 Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
384 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
386 let rec rmdir_descend d =
387 if is_dir_empty d then
390 rmdir_descend (Filename.dirname d)
394 (** {2 Exception handling} *)
396 let finally at_end f arg =
399 with exn -> at_end (); raise exn
404 (** {2 Localized exceptions } *)
406 exception Localized of Token.flocation * exn
408 let loc_of_floc = function
409 | { Lexing.pos_cnum = loc_begin }, { Lexing.pos_cnum = loc_end } ->
412 let floc_of_loc (loc_begin, loc_end) =
414 { Lexing.pos_fname = ""; Lexing.pos_lnum = -1; Lexing.pos_bol = -1;
415 Lexing.pos_cnum = loc_begin }
417 let floc_end = { floc_begin with Lexing.pos_cnum = loc_end } in
418 (floc_begin, floc_end)
420 let dummy_floc = floc_of_loc (-1, -1)
422 let raise_localized_exception ~offset floc exn =
423 let (x, y) = loc_of_floc floc in
424 let x = offset + x in
425 let y = offset + y in
426 let flocb,floce = floc in
428 { flocb with Lexing.pos_cnum = x }, { floce with Lexing.pos_cnum = y }
430 raise (Localized (floc, exn))
432 let estimate_size x =
433 4 * (String.length (Marshal.to_string x [])) / 1024