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)
144 let rec aux k = function
146 | h::tl -> f h k :: aux (k+1) tl
151 let list_mapi_acc f a l =
152 let rec aux k a res = function
153 | [] -> a, List.rev res
154 | h::tl -> let a,h = f h k a in aux (k+1) a (h::res) tl
163 | he::_ when p he -> Some (n,he)
164 | _::tl -> aux (n + 1) tl
169 let rec list_iter_default2 f l1 def l2 =
172 | a::ta, b::tb -> f a b; list_iter_default2 f ta def tb
173 | a::ta, [] -> f a def; list_iter_default2 f ta def []
176 let rec list_forall_default3 f l1 l2 def l3 =
180 | _, [], _ -> raise (Invalid_argument "list_forall_default3")
181 | a::ta, b::tb, c::tc -> f a b c && list_forall_default3 f ta tb def tc
182 | a::ta, b::tb, [] -> f a b def && list_forall_default3 f ta tb def []
185 exception FailureAt of int;;
187 let list_forall_default3_var f l1 l2 def l3 =
188 let rec aux f l1 l2 def l3 i =
192 | _, [], _ -> raise (Invalid_argument "list_forall_default3")
193 | a::ta, b::tb, c::tc ->
194 if f a b c then aux f ta tb def tc (i+1)
195 else raise (FailureAt i)
196 | a::ta, b::tb, [] ->
197 if f a b def then aux f ta tb def [] (i+1)
198 else raise (FailureAt i)
199 in aux f l1 l2 def l3 0
202 let sharing_map f l =
203 let unchanged = ref true in
204 let rec aux b = function
205 | [] as t -> unchanged := b; t
208 he1 :: aux (b && he1 == he) tl
210 let l1 = aux true l in
211 if !unchanged then l else l1
214 let sharing_map_acc f acc l =
215 let unchanged = ref true in
216 let final_acc = ref acc in
217 let rec aux b acc = function
218 | [] as t -> unchanged := b; final_acc := acc; t
220 let acc, he1 = f acc he in
221 he1 :: aux (b && he1 == he) acc tl
223 let l1 = aux true acc l in
224 !final_acc, if !unchanged then l else l1
227 (* expects the list to be sorted *)
228 let rec list_uniq ?(eq=(=)) = function
231 | h1::h2::tl when eq h1 h2 -> list_uniq ~eq (h2 :: tl)
232 | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq ~eq tl
234 let rec filter_map f =
239 | None -> filter_map f tl
240 | Some v -> v :: filter_map f tl)
242 let filter_map_acc f acc l =
248 | Some (acc, x) -> acc, x::res)
254 let filter_map_monad f acc l =
259 | acc, None -> acc, res
260 | acc, Some x -> acc, x::res)
266 let list_rev_map_filter f l =
267 let rec aux a = function
270 begin match f hd with
272 | Some b -> aux (b :: a) tl
277 let list_rev_map_filter_fold f v l =
278 let rec aux v a = function
281 begin match f v hd with
282 | v, None -> aux v a tl
283 | v, Some b -> aux v (b :: a) tl
288 let list_concat ?(sep = []) =
292 | [ last ] -> List.flatten (List.rev (last :: acc))
293 | hd :: tl -> aux ([sep; hd] @ acc) tl
297 let list_iter_sep ~sep f =
302 | hd :: tl -> f hd; sep (); aux tl
306 let rec list_findopt f l =
307 let rec aux k = function
311 | None -> aux (succ k) tl
312 | Some _ as rc -> rc)
317 let rec aux acc n l =
319 | 0, _ -> List.rev acc, l
320 | n, [] -> raise (Failure "HExtlib.split_nth")
321 | n, hd :: tl -> aux (hd :: acc) (n - 1) tl in
325 let l = List.rev l in
326 try List.hd l with exn -> raise (Failure "HExtlib.list_last")
329 let rec list_assoc_all a = function
331 | (x, y) :: tl when x = a -> y :: list_assoc_all a tl
332 | _ :: tl -> list_assoc_all a tl
335 let rec rm_assoc_option n = function
337 | (x,i)::tl when n=x -> Some i,tl
338 | p::tl -> let i,tl = rm_assoc_option n tl in i,p::tl
341 let rm_assoc_assert n l =
342 match rm_assoc_option n l with
343 | None,_ -> assert false
347 (* naif implementation of the union-find merge operation
348 canonicals maps elements to canonicals
349 elements maps canonicals to the classes *)
350 let merge canonicals elements extern n m =
351 let cn,canonicals = rm_assoc_option n canonicals in
352 let cm,canonicals = rm_assoc_option m canonicals in
354 | None, None -> canonicals, elements, extern
357 let l,elements = rm_assoc_assert c elements in
359 List.filter (fun (_,xc) -> not (xc = c)) canonicals
361 canonicals,elements,l@extern
362 | Some cn, Some cm when cn=cm ->
363 (n,cm)::(m,cm)::canonicals, elements, extern
364 | Some cn, Some cm ->
365 let ln,elements = rm_assoc_assert cn elements in
366 let lm,elements = rm_assoc_assert cm elements in
368 (n,cm)::(m,cm)::List.map
369 (fun ((x,xc) as p) ->
370 if xc = cn then (x,cm) else p) canonicals
372 let elements = (cm,ln@lm)::elements
374 canonicals,elements,extern
377 (* f x gives the direct dependencies of x.
378 x must not belong to (f x).
379 All elements not in l are merged into a single extern class *)
381 let canonicals = List.map (fun x -> (x,x)) l in
382 let elements = List.map (fun x -> (x,[x])) l in
384 let _,elements,extern =
386 (fun (canonicals,elements,extern) x ->
389 (fun (canonicals,elements,extern) d ->
390 merge canonicals elements extern d x)
391 (canonicals,elements,extern) dep)
392 (canonicals,elements,extern) l
394 let c = (List.map snd elements) in
395 if extern = [] then c else extern::c
398 (** {2 File predicates} *)
402 (Unix.stat fname).Unix.st_kind = Unix.S_DIR
403 with Unix.Unix_error _ -> false
405 let writable_dir path =
407 let file = path ^ "/prova_matita" in
408 let oc = open_out file in
412 with Sys_error _ -> false
415 let is_regular fname =
417 (Unix.stat fname).Unix.st_kind = Unix.S_REG
418 with Unix.Unix_error _ -> false
420 let is_executable fname =
422 let stat = (Unix.stat fname) in
423 stat.Unix.st_kind = Unix.S_REG &&
424 (stat.Unix.st_perm land 0o001 > 0)
425 with Unix.Unix_error _ -> false
427 let chmod mode filename =
428 Unix.chmod filename mode
431 let components = split ~sep:'/' path in
432 let rec aux where = function
436 if where = "" then piece else where ^ "/" ^ piece in
438 Unix.mkdir path 0o755; chmod 0o2775 path
440 | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
441 | Unix.Unix_error (e,_,_) ->
444 ("Unix.mkdir " ^ path ^ " 0o2775 :" ^ (Unix.error_message e))));
447 let where = if path.[0] = '/' then "/" else "" in
450 (** {2 Filesystem} *)
452 let input_file fname =
453 let size = (Unix.stat fname).Unix.st_size in
454 let buf = Buffer.create size in
455 let ic = open_in fname in
456 Buffer.add_channel buf ic size;
462 let buf = Buffer.create size in
463 let s = String.create size in
466 let bytes = input ic s 0 size in
467 if bytes = 0 then raise End_of_file
468 else Buffer.add_substring buf s 0 bytes
470 with End_of_file -> ());
473 let output_file ~filename ~text =
474 let oc = open_out filename in
475 output_string oc text;
480 let len = String.length s in
481 let buf = Buffer.create 0 in
485 if Buffer.length buf > 0
486 then List.rev (Buffer.contents buf :: acc)
489 if is_blank s.[i] then
490 if Buffer.length buf > 0 then begin
491 let s = Buffer.contents buf in
493 aux (s :: acc) (i + 1)
497 Buffer.add_char buf s.[i];
504 (* Rules: * "~name" -> home dir of "name"
505 * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
507 let get_home login = (Unix.getpwnam login).Unix.pw_dir in
509 let len = String.length s in
510 if len > 0 && s.[0] = '~' then begin
511 let login_len = ref 1 in
512 while !login_len < len && is_alphanum (s.[!login_len]) do
515 let login = String.sub s 1 (!login_len - 1) in
519 try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
523 home ^ String.sub s !login_len (len - !login_len)
524 with Not_found | Invalid_argument _ -> s
528 String.concat " " (List.map expand_one (blank_split s))
530 let find ?(test = fun _ -> true) path =
531 let rec aux acc todo =
536 let handle = Unix.opendir path in
538 let matching_files = ref [] in
541 match Unix.readdir handle with
544 let qentry = path ^ "/" ^ entry in
546 if is_dir qentry then
547 dirs := qentry :: !dirs
548 else if test qentry then
549 matching_files := qentry :: !matching_files;
550 with Unix.Unix_error _ -> ())
552 with End_of_file -> Unix.closedir handle);
553 aux (!matching_files @ acc) (!dirs @ tl)
554 with Unix.Unix_error _ -> aux acc tl
558 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
562 let od = Unix.opendir d in
564 let name = Unix.readdir od in
565 if name <> "." && name <> ".." then false else aux () in
566 let res = try aux () with End_of_file -> true in
570 Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
572 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
574 let rec rmdir_descend d =
575 if is_dir_empty d then
578 rmdir_descend (Filename.dirname d)
582 (** {2 Exception handling} *)
584 let finally at_end f arg =
587 with exn -> at_end (); raise exn
592 (** {2 Localized exceptions } *)
594 exception Localized of Stdpp.location * exn
596 let loc_of_floc floc = Stdpp.first_pos floc, Stdpp.last_pos floc;;
598 let floc_of_loc (loc_begin, loc_end) =
599 Stdpp.make_loc (loc_begin, loc_end)
601 let dummy_floc = floc_of_loc (0, 0)
603 let raise_localized_exception ~offset floc exn =
604 let x, y = loc_of_floc floc in
605 let x = offset + x in
606 let y = offset + y in
607 let floc = floc_of_loc (x,y) in
608 raise (Localized (floc, exn))
610 let estimate_size x =
611 4 * (String.length (Marshal.to_string x [])) / 1024
613 let normalize_path s =
614 let s = Str.global_replace (Str.regexp "//") "/" s in
615 let l = Str.split (Str.regexp "/") s in
616 let rec aux acc = function
618 | he::"."::tl -> aux acc (he::tl)
619 | he::".."::tl when he <> ".." -> aux [] (acc @ tl)
620 | he::tl -> aux (acc@[he]) tl
622 (if Str.string_match (Str.regexp "^/") s 0 then "/" else "") ^
623 String.concat "/" (aux [] l)
624 ^ (if Str.string_match (Str.regexp "/$") s 0 then "/" else "")
627 let find_in paths path =
628 let rec aux = function
629 | [] -> raise (Failure "find_in")
631 let path = normalize_path (p ^ "/" ^ path) in
633 if (Unix.stat path).Unix.st_kind = Unix.S_REG then path
635 with Unix.Unix_error _ ->
640 with Unix.Unix_error _ | Failure _ ->
645 let is_prefix_of_aux d1 d2 =
646 let len1 = String.length d1 in
647 let len2 = String.length d2 in
651 let pref = String.sub d2 0 len1 in
652 pref = d1 && (len1 = len2 || d1.[len1-1] = '/' || d2.[len1] = '/'), len1, len2
654 let is_prefix_of d1 d2 =
655 let b,_,_ = is_prefix_of_aux d1 d2 in b
658 let chop_prefix prefix s =
659 let b,lp,ls = is_prefix_of_aux prefix s in
661 String.sub s lp (ls - lp)
667 try close_out(open_out s) with Sys_error _ -> ()
670 let rec mk_list x = function
672 | n -> x :: mk_list x (n-1)
675 let list_seq start stop =
676 if start > stop then [] else
678 if pos = stop then []
679 else pos :: (aux (pos+1))
684 let rec list_skip n l =
687 | n,_::l -> list_skip (n-1) l
688 | _, [] -> assert false
691 let utf8_parsed_text s floc =
692 let start, stop = loc_of_floc floc in
693 let len = stop - start in
694 let res = Netconversion.ustring_sub `Enc_utf8 start len s in
695 res, String.length res