]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/extlib/hExtlib.ml
49d28bbb91733a50e785d3c17388a58cb7c7b32a
[helm.git] / helm / software / components / extlib / hExtlib.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
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.
6  * 
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.
11  * 
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.
16  *
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,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 (* $Id$ *)
27
28 (** PROFILING *)
29
30 let profiling_enabled = ref false ;; (* ComponentsConf.profiling *)
31
32 let something_profiled = ref false
33
34 let _ = 
35   if !something_profiled then
36     at_exit 
37       (fun _ -> 
38         prerr_endline 
39          (Printf.sprintf "!! %39s ---------- --------- --------- ---------" 
40            (String.make 39 '-'));
41         prerr_endline 
42          (Printf.sprintf "!! %-39s %10s %9s %9s %9s" 
43            "function" "#calls" "total" "max" "average"))
44
45 let profiling_printings = ref (fun _ -> true)
46 let set_profiling_printings f = profiling_printings := f
47
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
52    let calls = ref 0 in
53    let max = ref 0.0 in
54    let profile f x =
55     if not !profiling_enabled then f x else
56     let before = Unix.gettimeofday () in
57     try
58      incr calls;
59      let res = f x in
60      let after = Unix.gettimeofday () in
61      let delta = after -. before in
62       total := !total +. delta;
63       if delta > !max then max := delta;
64       res
65     with
66      exc ->
67       let after = Unix.gettimeofday () in
68       let delta = after -. before in
69        total := !total +. delta;
70        if delta > !max then max := delta;
71        raise exc
72    in
73    at_exit
74     (fun () ->
75       if !profiling_printings s && !calls <> 0 then
76        begin
77         something_profiled := true;
78         prerr_endline
79          (Printf.sprintf "!! %-39s %10d %9.4f %9.4f %9.4f" 
80          s !calls !total !max (!total /. (float_of_int !calls)))
81        end);
82    { profile = profile }
83  else
84    { profile = fun f x -> f x }
85
86 (** {2 Optional values} *)
87
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
91
92 (** {2 String processing} *)
93
94 let split ?(sep = ' ') s =
95   let pieces = ref [] in
96   let rec aux idx =
97     match (try Some (String.index_from s idx sep) with Not_found -> None) with
98     | Some pos ->
99         pieces := String.sub s idx (pos - idx) :: !pieces;
100         aux (pos + 1)
101     | None -> pieces := String.sub s idx (String.length s - idx) :: !pieces
102   in
103   aux 0;
104   List.rev !pieces
105
106 let trim_blanks s =
107   let rec find_left idx =
108     match s.[idx] with
109     | ' ' | '\t' | '\r' | '\n' -> find_left (idx + 1)
110     | _ -> idx
111   in
112   let rec find_right idx =
113     match s.[idx] with
114     | ' ' | '\t' | '\r' | '\n' -> find_right (idx - 1)
115     | _ -> idx
116   in
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)
120
121 (** {2 Char processing} *)
122
123 let is_alpha c =
124   let code = Char.code c in 
125   (code >= 65 && code <= 90) || (code >= 97 && code <= 122)
126
127 let is_digit c =
128   let code = Char.code c in 
129   code >= 48 && code <= 57
130
131 let is_blank c =
132   let code = Char.code c in 
133   code = 9 || code = 10 || code = 13 || code = 32
134
135 let is_alphanum c = is_alpha c || is_digit c
136
137 (** {2 List processing} *)
138
139 let flatten_map f l =
140   List.flatten (List.map f l)
141 ;;
142
143 let list_mapi f l =
144   let rec aux k = function
145     | [] -> []
146     | h::tl -> f h k :: aux (k+1) tl
147   in
148      aux 0 l
149 ;;
150
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
155   in
156    aux 0 a [] l
157 ;;
158
159 let list_index p =
160  let rec aux n =
161   function
162      [] -> None
163    | he::_ when p he -> Some (n,he)
164    | _::tl -> aux (n + 1) tl
165  in
166   aux 0
167 ;;
168
169 let rec list_iter_default2 f l1 def l2 = 
170   match l1,l2 with
171     | [], _ -> ()
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 [] 
174 ;;
175
176 let rec list_forall_default3 f l1 l2 def l3 = 
177   match l1,l2,l3 with
178     | [], [], _ -> true
179     | [], _, _
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 [] 
183 ;;
184
185 exception FailureAt of int;;
186
187 let list_forall_default3_var f l1 l2 def l3 = 
188   let rec aux f l1 l2 def l3 i =
189     match l1,l2,l3 with
190       | [], [], _ -> true
191       | [], _, _
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
200 ;;
201
202 let sharing_map f l =
203   let unchanged = ref true in
204   let rec aux b = function
205     | [] as t -> unchanged := b; t
206     | he::tl ->
207         let he1 = f he in
208         he1 :: aux (b && he1 == he) tl
209   in
210   let l1 = aux true l in
211   if !unchanged then l else l1
212 ;;
213         
214 let rec list_uniq ?(eq=(=)) = function 
215   | [] -> []
216   | h::[] -> [h]
217   | h1::h2::tl when eq h1 h2 -> list_uniq ~eq (h2 :: tl) 
218   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq ~eq tl
219
220 let rec filter_map f =
221   function
222   | [] -> []
223   | hd :: tl ->
224       (match f hd with
225       | None -> filter_map f tl
226       | Some v -> v :: filter_map f tl)
227
228 let filter_map_acc f acc l =
229   let acc, res = 
230    List.fold_left
231     (fun (acc, res) t ->
232        match f acc t with
233        | None -> acc, res
234        | Some (acc, x) -> acc, x::res)
235     (acc,[]) l
236   in
237    acc, List.rev res
238 ;;
239
240 let list_rev_map_filter f l =
241    let rec aux a = function
242       | []       -> a
243       | hd :: tl -> 
244          begin match f hd with
245             | None   -> aux a tl
246             | Some b -> aux (b :: a) tl 
247          end
248    in 
249    aux [] l
250
251 let list_rev_map_filter_fold f v l =
252    let rec aux v a = function
253       | []       -> v, a
254       | hd :: tl -> 
255          begin match f v hd with
256             | v, None   -> aux v a tl
257             | v, Some b -> aux v (b :: a) tl 
258          end
259    in 
260    aux v [] l
261
262 let list_concat ?(sep = []) =
263   let rec aux acc =
264     function
265     | [] -> []
266     | [ last ] -> List.flatten (List.rev (last :: acc))
267     | hd :: tl -> aux ([sep; hd] @ acc) tl
268   in
269   aux []
270   
271 let list_iter_sep ~sep f =
272   let rec aux =
273     function
274     | [] -> ()
275     | [ last ] -> f last
276     | hd :: tl -> f hd; sep (); aux tl
277   in
278   aux
279   
280 let rec list_findopt f l = 
281   let rec aux k = function 
282     | [] -> None 
283     | x::tl -> 
284         (match f x k with
285         | None -> aux (succ k) tl
286         | Some _ as rc -> rc)
287   in
288   aux 0 l
289
290 let split_nth n l =
291   let rec aux acc n l =
292     match n, l with
293     | 0, _ -> List.rev acc, l
294     | n, [] -> raise (Failure "HExtlib.split_nth")
295     | n, hd :: tl -> aux (hd :: acc) (n - 1) tl in
296   aux [] n l
297
298 let list_last l =
299   let l = List.rev l in 
300   try List.hd l with exn -> raise (Failure "HExtlib.list_last")
301 ;;
302
303 let rec list_assoc_all a = function
304    | []                      -> []
305    | (x, y) :: tl when x = a -> y :: list_assoc_all a tl
306    | _ :: tl                 -> list_assoc_all a tl
307 ;;
308
309 (** {2 File predicates} *)
310
311 let is_dir fname =
312   try
313     (Unix.stat fname).Unix.st_kind = Unix.S_DIR
314   with Unix.Unix_error _ -> false
315
316 let writable_dir path =
317   try
318     let file = path ^ "/prova_matita" in
319     let oc = open_out file in
320     close_out oc;
321     Sys.remove file;
322     true
323   with Sys_error _ -> false
324
325
326 let is_regular fname =
327   try
328     (Unix.stat fname).Unix.st_kind = Unix.S_REG
329   with Unix.Unix_error _ -> false
330
331 let is_executable fname =
332   try
333     let stat = (Unix.stat fname) in
334     stat.Unix.st_kind = Unix.S_REG &&
335     (stat.Unix.st_perm land 0o001 > 0)
336   with Unix.Unix_error _ -> false
337
338 let chmod mode filename =
339    Unix.chmod filename mode
340
341 let mkdir path =
342   let components = split ~sep:'/' path in
343   let rec aux where = function
344     | [] -> ()
345     | piece::tl -> 
346         let path =
347           if where = "" then piece else where ^ "/" ^ piece in
348         (try
349           Unix.mkdir path 0o755; chmod 0o2775 path 
350         with 
351         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
352         | Unix.Unix_error (e,_,_) -> 
353             raise 
354               (Failure 
355                 ("Unix.mkdir " ^ path ^ " 0o2775 :" ^ (Unix.error_message e))));
356         aux path tl
357   in
358   let where = if path.[0] = '/' then "/" else "" in
359   aux where components
360
361 (** {2 Filesystem} *)
362
363 let input_file fname =
364   let size = (Unix.stat fname).Unix.st_size in
365   let buf = Buffer.create size in
366   let ic = open_in fname in
367   Buffer.add_channel buf ic size;
368   close_in ic;
369   Buffer.contents buf
370
371 let input_all ic =
372   let size = 10240 in
373   let buf = Buffer.create size in
374   let s = String.create size in
375   (try
376     while true do
377       let bytes = input ic s 0 size in
378       if bytes = 0 then raise End_of_file
379       else Buffer.add_substring buf s 0 bytes
380     done
381   with End_of_file -> ());
382   Buffer.contents buf
383
384 let output_file ~filename ~text = 
385   let oc = open_out filename in
386   output_string oc text;
387   close_out oc;
388   chmod 0o664 filename
389
390 let blank_split s =
391   let len = String.length s in
392   let buf = Buffer.create 0 in
393   let rec aux acc i =
394     if i >= len
395     then begin
396       if Buffer.length buf > 0
397       then List.rev (Buffer.contents buf :: acc)
398       else List.rev acc
399     end else begin
400       if is_blank s.[i] then
401         if Buffer.length buf > 0 then begin
402           let s = Buffer.contents buf in
403           Buffer.clear buf;
404           aux (s :: acc) (i + 1)
405         end else
406           aux acc (i + 1)
407       else begin
408         Buffer.add_char buf s.[i];
409         aux acc (i + 1)
410       end
411     end
412   in
413   aux [] 0
414
415   (* Rules: * "~name" -> home dir of "name"
416    * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
417 let tilde_expand s =
418   let get_home login = (Unix.getpwnam login).Unix.pw_dir in
419   let expand_one s =
420     let len = String.length s in
421     if len > 0 && s.[0] = '~' then begin
422       let login_len = ref 1 in
423       while !login_len < len && is_alphanum (s.[!login_len]) do
424         incr login_len
425       done;
426       let login = String.sub s 1 (!login_len - 1) in
427       try
428         let home =
429           if login = "" then
430             try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
431           else
432             get_home login
433         in
434         home ^ String.sub s !login_len (len - !login_len)
435       with Not_found | Invalid_argument _ -> s
436     end else
437       s
438   in
439   String.concat " " (List.map expand_one (blank_split s))
440   
441 let find ?(test = fun _ -> true) path = 
442   let rec aux acc todo = 
443     match todo with
444     | [] -> acc
445     | path :: tl ->
446         try
447           let handle = Unix.opendir path in
448           let dirs = ref [] in
449           let matching_files = ref [] in 
450           (try 
451             while true do 
452               match Unix.readdir handle with
453               | "." | ".." -> ()
454               | entry ->
455                   let qentry = path ^ "/" ^ entry in
456                   (try
457                     if is_dir qentry then
458                       dirs := qentry :: !dirs
459                     else if test qentry then
460                       matching_files := qentry :: !matching_files;
461                   with Unix.Unix_error _ -> ())
462             done
463           with End_of_file -> Unix.closedir handle);
464           aux (!matching_files @ acc) (!dirs @ tl)
465         with Unix.Unix_error _ -> aux acc tl
466   in
467   aux [] [path]
468
469 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
470
471 let is_dir_empty d =
472  try
473   let od = Unix.opendir d in
474   let rec aux () =
475    let name = Unix.readdir od in
476    if name <> "." && name <> ".." then false else aux () in
477   let res = try aux () with End_of_file -> true in
478    Unix.closedir od;
479    res
480  with
481   Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
482
483 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
484
485 let rec rmdir_descend d = 
486   if is_dir_empty d then
487     begin
488       safe_rmdir d;
489       rmdir_descend (Filename.dirname d)
490     end
491
492
493 (** {2 Exception handling} *)
494
495 let finally at_end f arg =
496   let res =
497     try f arg
498     with exn -> at_end (); raise exn
499   in
500   at_end ();
501   res
502
503 (** {2 Localized exceptions } *)
504
505 exception Localized of Stdpp.location * exn
506
507 let loc_of_floc floc = Stdpp.first_pos floc, Stdpp.last_pos floc;;
508
509 let floc_of_loc (loc_begin, loc_end) =
510  Stdpp.make_loc (loc_begin, loc_end)
511
512 let dummy_floc = floc_of_loc (0, 0)
513
514 let raise_localized_exception ~offset floc exn =
515  let x, y = loc_of_floc floc in
516  let x = offset + x in
517  let y = offset + y in
518  let floc = floc_of_loc (x,y) in
519   raise (Localized (floc, exn))
520
521 let estimate_size x = 
522   4 * (String.length (Marshal.to_string x [])) / 1024
523
524 let normalize_path s = 
525   let s = Str.global_replace (Str.regexp "//") "/" s in
526   let l = Str.split (Str.regexp "/") s in
527   let rec aux acc = function
528     | [] -> acc
529     | he::"."::tl -> aux acc (he::tl)
530     | he::".."::tl when he <> ".." -> aux [] (acc @ tl)
531     | he::tl -> aux (acc@[he]) tl
532   in
533   (if Str.string_match (Str.regexp "^/") s 0 then "/" else "") ^
534   String.concat "/" (aux [] l)
535   ^ (if Str.string_match (Str.regexp "/$") s 0 then "/" else "")
536 ;;
537
538 let find_in paths path =
539    let rec aux = function
540    | [] -> raise (Failure "find_in")
541    | p :: tl ->
542       let path = normalize_path (p ^ "/" ^ path) in
543        try
544          if (Unix.stat path).Unix.st_kind = Unix.S_REG then path
545          else aux tl
546        with Unix.Unix_error _ -> 
547                aux tl
548    in
549    try
550      aux paths
551    with Unix.Unix_error _ | Failure _ -> 
552      raise 
553        (Failure "find_in")
554 ;;
555
556 let is_prefix_of_aux d1 d2 = 
557   let len1 = String.length d1 in
558   let len2 = String.length d2 in
559   if len2 < len1 then 
560     false, len1, len2
561   else
562     let pref = String.sub d2 0 len1 in
563     pref = d1 && (len1 = len2 || d1.[len1-1] = '/' || d2.[len1] = '/'), len1, len2
564
565 let is_prefix_of d1 d2 =
566   let b,_,_ = is_prefix_of_aux d1 d2 in b
567 ;;
568
569 let chop_prefix prefix s =
570   let b,lp,ls = is_prefix_of_aux prefix s in
571   if b then
572     String.sub s lp (ls - lp)
573   else 
574     s
575 ;;
576
577 let touch s =
578   try close_out(open_out s) with Sys_error _ -> ()
579 ;;
580
581 let rec mk_list x = function
582   | 0 -> []
583   | n -> x :: mk_list x (n-1)
584 ;;
585
586 let list_seq start stop =
587   if start > stop then [] else
588   let rec aux pos =
589     if pos = stop then []
590     else pos :: (aux (pos+1))
591   in
592     aux start
593 ;;
594
595 let rec list_skip n l =
596   match n,l with
597   | 0,_ -> l
598   | n,_::l -> list_skip (n-1) l
599   | _, [] -> assert false
600 ;;
601