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 = ref 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 if not !profiling_enabled then f x else
56 let before = Unix.gettimeofday () in
60 let after = Unix.gettimeofday () in
61 let delta = after -. before in
62 total := !total +. delta;
63 if delta > !max then max := delta;
67 let after = Unix.gettimeofday () in
68 let delta = after -. before in
69 total := !total +. delta;
70 if delta > !max then max := delta;
75 if !profiling_printings s && !calls <> 0 then
77 something_profiled := true;
79 (Printf.sprintf "!! %-39s %10d %9.4f %9.4f %9.4f"
80 s !calls !total !max (!total /. (float_of_int !calls)))
84 { profile = fun f x -> f x }
86 (** {2 Optional values} *)
88 let map_option f = function None -> None | Some v -> Some (f v)
89 let iter_option f = function None -> () | Some v -> f v
90 let unopt = function None -> failwith "unopt: None" | Some v -> v
92 (** {2 String processing} *)
94 let split ?(sep = ' ') s =
95 let pieces = ref [] in
97 match (try Some (String.index_from s idx sep) with Not_found -> None) with
99 pieces := String.sub s idx (pos - idx) :: !pieces;
101 | None -> pieces := String.sub s idx (String.length s - idx) :: !pieces
107 let rec find_left idx =
109 | ' ' | '\t' | '\r' | '\n' -> find_left (idx + 1)
112 let rec find_right idx =
114 | ' ' | '\t' | '\r' | '\n' -> find_right (idx - 1)
117 let s_len = String.length s in
118 let left, right = find_left 0, find_right (s_len - 1) in
119 String.sub s left (right - left + 1)
121 (** {2 Char processing} *)
124 let code = Char.code c in
125 (code >= 65 && code <= 90) || (code >= 97 && code <= 122)
128 let code = Char.code c in
129 code >= 48 && code <= 57
132 let code = Char.code c in
133 code = 9 || code = 10 || code = 13 || code = 32
135 let is_alphanum c = is_alpha c || is_digit c
137 (** {2 List processing} *)
139 let flatten_map f l =
140 List.flatten (List.map f l)
143 let rec list_uniq ?(eq=(=)) = function
146 | h1::h2::tl when eq h1 h2 -> list_uniq ~eq (h2 :: tl)
147 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq ~eq tl
149 let rec filter_map f =
154 | None -> filter_map f tl
155 | Some v -> v :: filter_map f tl)
157 let list_rev_map_filter f l =
158 let rec aux a = function
161 begin match f hd with
163 | Some b -> aux (b :: a) tl
168 let list_rev_map_filter_fold f v l =
169 let rec aux v a = function
172 begin match f v hd with
173 | v, None -> aux v a tl
174 | v, Some b -> aux v (b :: a) tl
179 let list_concat ?(sep = []) =
183 | [ last ] -> List.flatten (List.rev (last :: acc))
184 | hd :: tl -> aux ([sep; hd] @ acc) tl
188 let rec list_findopt f l =
189 let rec aux = function
194 | Some _ as rc -> rc)
199 let rec aux acc n l =
201 | 0, _ -> List.rev acc, l
202 | n, [] -> raise (Failure "HExtlib.split_nth")
203 | n, hd :: tl -> aux (hd :: acc) (n - 1) tl in
207 let l = List.rev l in
208 try List.hd l with exn -> raise (Failure "HExtlib.list_last")
211 (** {2 File predicates} *)
215 (Unix.stat fname).Unix.st_kind = Unix.S_DIR
216 with Unix.Unix_error _ -> false
218 let writable_dir path =
220 let file = path ^ "/prova_matita" in
221 let oc = open_out file in
225 with Sys_error _ -> false
228 let is_regular fname =
230 (Unix.stat fname).Unix.st_kind = Unix.S_REG
231 with Unix.Unix_error _ -> false
233 let is_executable fname =
235 let stat = (Unix.stat fname) in
236 stat.Unix.st_kind = Unix.S_REG &&
237 (stat.Unix.st_perm land 0o001 > 0)
238 with Unix.Unix_error _ -> false
240 let chmod mode filename =
241 Unix.chmod filename mode
244 let components = split ~sep:'/' path in
245 let rec aux where = function
249 if where = "" then piece else where ^ "/" ^ piece in
251 Unix.mkdir path 0o755; chmod 0o2775 path
253 | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
254 | Unix.Unix_error (e,_,_) ->
257 ("Unix.mkdir " ^ path ^ " 0o2775 :" ^ (Unix.error_message e))));
260 let where = if path.[0] = '/' then "/" else "" in
263 (** {2 Filesystem} *)
265 let input_file fname =
266 let size = (Unix.stat fname).Unix.st_size in
267 let buf = Buffer.create size in
268 let ic = open_in fname in
269 Buffer.add_channel buf ic size;
275 let buf = Buffer.create size in
276 let s = String.create size in
279 let bytes = input ic s 0 size in
280 if bytes = 0 then raise End_of_file
281 else Buffer.add_substring buf s 0 bytes
283 with End_of_file -> ());
286 let output_file ~filename ~text =
287 let oc = open_out filename in
288 output_string oc text;
293 let len = String.length s in
294 let buf = Buffer.create 0 in
298 if Buffer.length buf > 0
299 then List.rev (Buffer.contents buf :: acc)
302 if is_blank s.[i] then
303 if Buffer.length buf > 0 then begin
304 let s = Buffer.contents buf in
306 aux (s :: acc) (i + 1)
310 Buffer.add_char buf s.[i];
317 (* Rules: * "~name" -> home dir of "name"
318 * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
320 let get_home login = (Unix.getpwnam login).Unix.pw_dir in
322 let len = String.length s in
323 if len > 0 && s.[0] = '~' then begin
324 let login_len = ref 1 in
325 while !login_len < len && is_alphanum (s.[!login_len]) do
328 let login = String.sub s 1 (!login_len - 1) in
332 try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
336 home ^ String.sub s !login_len (len - !login_len)
337 with Not_found | Invalid_argument _ -> s
341 String.concat " " (List.map expand_one (blank_split s))
343 let find ?(test = fun _ -> true) path =
344 let rec aux acc todo =
349 let handle = Unix.opendir path in
351 let matching_files = ref [] in
354 match Unix.readdir handle with
357 let qentry = path ^ "/" ^ entry in
359 if is_dir qentry then
360 dirs := qentry :: !dirs
361 else if test qentry then
362 matching_files := qentry :: !matching_files;
363 with Unix.Unix_error _ -> ())
365 with End_of_file -> Unix.closedir handle);
366 aux (!matching_files @ acc) (!dirs @ tl)
367 with Unix.Unix_error _ -> aux acc tl
371 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
375 let od = Unix.opendir d in
377 let name = Unix.readdir od in
378 if name <> "." && name <> ".." then false else aux () in
379 let res = try aux () with End_of_file -> true in
383 Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
385 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
387 let rec rmdir_descend d =
388 if is_dir_empty d then
391 rmdir_descend (Filename.dirname d)
395 (** {2 Exception handling} *)
397 let finally at_end f arg =
400 with exn -> at_end (); raise exn
405 (** {2 Localized exceptions } *)
407 exception Localized of Stdpp.location * exn
409 let loc_of_floc floc = Stdpp.first_pos floc, Stdpp.last_pos floc;;
411 let floc_of_loc (loc_begin, loc_end) =
412 Stdpp.make_loc (loc_begin, loc_end)
414 let dummy_floc = floc_of_loc (-1, -1)
416 let raise_localized_exception ~offset floc exn =
417 let x, y = loc_of_floc floc in
418 let x = offset + x in
419 let y = offset + y in
420 let floc = floc_of_loc (x,y) in
421 raise (Localized (floc, exn))
423 let estimate_size x =
424 4 * (String.length (Marshal.to_string x [])) / 1024
426 let normalize_path s =
427 let s = Str.global_replace (Str.regexp "//") "/" s in
428 let l = Str.split (Str.regexp "/") s in
429 let rec aux acc = function
431 | he::"."::tl -> aux acc (he::tl)
432 | he::".."::tl when he <> ".." -> aux [] (acc @ tl)
433 | he::tl -> aux (acc@[he]) tl
435 (if Str.string_match (Str.regexp "^/") s 0 then "/" else "") ^
436 String.concat "/" (aux [] l)
437 ^ (if Str.string_match (Str.regexp "/$") s 0 then "/" else "")
440 let find_in paths path =
441 let rec aux = function
442 | [] -> raise (Failure "find_in")
444 let path = normalize_path (p ^ "/" ^ path) in
446 if (Unix.stat path).Unix.st_kind = Unix.S_REG then path
448 with Unix.Unix_error _ ->
453 with Unix.Unix_error _ | Failure _ ->
458 let is_prefix_of_aux d1 d2 =
459 let len1 = String.length d1 in
460 let len2 = String.length d2 in
464 let pref = String.sub d2 0 len1 in
465 pref = d1 && (len1 = len2 || d1.[len1-1] = '/' || d2.[len1] = '/'), len1, len2
467 let is_prefix_of d1 d2 =
468 let b,_,_ = is_prefix_of_aux d1 d2 in b
471 let chop_prefix prefix s =
472 let b,lp,ls = is_prefix_of_aux prefix s in
474 String.sub s lp (ls - lp)
480 try close_out(open_out s) with Sys_error _ -> ()