]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/extlib/hExtlib.ml
Preparing for 0.5.9 release.
[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 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
219     | he::tl ->
220         let acc, he1 = f acc he in
221         he1 :: aux (b && he1 == he) acc tl
222   in
223   let l1 = aux true acc l in
224   !final_acc, if !unchanged then l else l1
225 ;;
226
227 let rec list_uniq ?(eq=(=)) = function 
228   | [] -> []
229   | h::[] -> [h]
230   | h1::h2::tl when eq h1 h2 -> list_uniq ~eq (h2 :: tl) 
231   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq ~eq tl
232
233 let rec filter_map f =
234   function
235   | [] -> []
236   | hd :: tl ->
237       (match f hd with
238       | None -> filter_map f tl
239       | Some v -> v :: filter_map f tl)
240
241 let filter_map_acc f acc l =
242   let acc, res = 
243    List.fold_left
244     (fun (acc, res) t ->
245        match f acc t with
246        | None -> acc, res
247        | Some (acc, x) -> acc, x::res)
248     (acc,[]) l
249   in
250    acc, List.rev res
251 ;;
252
253 let filter_map_monad f acc l =
254   let acc, res = 
255    List.fold_left
256     (fun (acc, res) t ->
257        match f acc t with
258        | acc, None -> acc, res
259        | acc, Some x -> acc, x::res)
260     (acc,[]) l
261   in
262    acc, List.rev res
263 ;;
264
265 let list_rev_map_filter f l =
266    let rec aux a = function
267       | []       -> a
268       | hd :: tl -> 
269          begin match f hd with
270             | None   -> aux a tl
271             | Some b -> aux (b :: a) tl 
272          end
273    in 
274    aux [] l
275
276 let list_rev_map_filter_fold f v l =
277    let rec aux v a = function
278       | []       -> v, a
279       | hd :: tl -> 
280          begin match f v hd with
281             | v, None   -> aux v a tl
282             | v, Some b -> aux v (b :: a) tl 
283          end
284    in 
285    aux v [] l
286
287 let list_concat ?(sep = []) =
288   let rec aux acc =
289     function
290     | [] -> []
291     | [ last ] -> List.flatten (List.rev (last :: acc))
292     | hd :: tl -> aux ([sep; hd] @ acc) tl
293   in
294   aux []
295   
296 let list_iter_sep ~sep f =
297   let rec aux =
298     function
299     | [] -> ()
300     | [ last ] -> f last
301     | hd :: tl -> f hd; sep (); aux tl
302   in
303   aux
304   
305 let rec list_findopt f l = 
306   let rec aux k = function 
307     | [] -> None 
308     | x::tl -> 
309         (match f x k with
310         | None -> aux (succ k) tl
311         | Some _ as rc -> rc)
312   in
313   aux 0 l
314
315 let split_nth n l =
316   let rec aux acc n l =
317     match n, l with
318     | 0, _ -> List.rev acc, l
319     | n, [] -> raise (Failure "HExtlib.split_nth")
320     | n, hd :: tl -> aux (hd :: acc) (n - 1) tl in
321   aux [] n l
322
323 let list_last l =
324   let l = List.rev l in 
325   try List.hd l with exn -> raise (Failure "HExtlib.list_last")
326 ;;
327
328 let rec list_assoc_all a = function
329    | []                      -> []
330    | (x, y) :: tl when x = a -> y :: list_assoc_all a tl
331    | _ :: tl                 -> list_assoc_all a tl
332 ;;
333
334 let rec rm_assoc_option n = function
335   | [] -> None,[]
336   | (x,i)::tl when n=x -> Some i,tl
337   | p::tl -> let i,tl = rm_assoc_option n tl in i,p::tl
338 ;;
339
340 let rm_assoc_assert n l =
341   match rm_assoc_option n l with
342   | None,_ -> assert false
343   | Some i,l -> i,l
344 ;;
345
346 (* naif implementation of the union-find merge operation
347    canonicals maps elements to canonicals
348    elements maps canonicals to the classes *)
349 let merge canonicals elements extern n m =
350   let cn,canonicals = rm_assoc_option n canonicals in
351   let cm,canonicals = rm_assoc_option m canonicals in
352     match cn,cm with
353       | None, None -> canonicals, elements, extern
354       | None, Some c
355       | Some c, None -> 
356           let l,elements = rm_assoc_assert c elements in
357           let canonicals = 
358             List.filter (fun (_,xc) -> not (xc = c)) canonicals 
359           in
360             canonicals,elements,l@extern
361       | Some cn, Some cm when cn=cm ->
362           (n,cm)::(m,cm)::canonicals, elements, extern
363       | Some cn, Some cm ->
364           let ln,elements = rm_assoc_assert cn elements in
365           let lm,elements = rm_assoc_assert cm elements in
366           let canonicals = 
367             (n,cm)::(m,cm)::List.map 
368               (fun ((x,xc) as p)  -> 
369                  if xc = cn then (x,cm) else p) canonicals
370           in 
371           let elements = (cm,ln@lm)::elements 
372           in
373             canonicals,elements,extern
374 ;;
375
376 (* f x gives the direct dependencies of x.
377    x must not belong to (f x). 
378    All elements not in l are merged into a single extern class *)
379 let clusters f l =
380   let canonicals = List.map (fun x -> (x,x)) l in
381   let elements = List.map (fun x -> (x,[x])) l in
382   let extern = [] in
383   let _,elements,extern = 
384     List.fold_left 
385      (fun (canonicals,elements,extern) x ->
386        let dep = f x in
387          List.fold_left 
388            (fun (canonicals,elements,extern) d ->
389               merge canonicals elements extern d x) 
390            (canonicals,elements,extern) dep)
391      (canonicals,elements,extern) l
392   in
393   let c = (List.map snd elements) in
394   if extern = [] then c else extern::c
395 ;;
396
397 (** {2 File predicates} *)
398
399 let is_dir fname =
400   try
401     (Unix.stat fname).Unix.st_kind = Unix.S_DIR
402   with Unix.Unix_error _ -> false
403
404 let writable_dir path =
405   try
406     let file = path ^ "/prova_matita" in
407     let oc = open_out file in
408     close_out oc;
409     Sys.remove file;
410     true
411   with Sys_error _ -> false
412
413
414 let is_regular fname =
415   try
416     (Unix.stat fname).Unix.st_kind = Unix.S_REG
417   with Unix.Unix_error _ -> false
418
419 let is_executable fname =
420   try
421     let stat = (Unix.stat fname) in
422     stat.Unix.st_kind = Unix.S_REG &&
423     (stat.Unix.st_perm land 0o001 > 0)
424   with Unix.Unix_error _ -> false
425
426 let chmod mode filename =
427    Unix.chmod filename mode
428
429 let mkdir path =
430   let components = split ~sep:'/' path in
431   let rec aux where = function
432     | [] -> ()
433     | piece::tl -> 
434         let path =
435           if where = "" then piece else where ^ "/" ^ piece in
436         (try
437           Unix.mkdir path 0o755; chmod 0o2775 path 
438         with 
439         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
440         | Unix.Unix_error (e,_,_) -> 
441             raise 
442               (Failure 
443                 ("Unix.mkdir " ^ path ^ " 0o2775 :" ^ (Unix.error_message e))));
444         aux path tl
445   in
446   let where = if path.[0] = '/' then "/" else "" in
447   aux where components
448
449 (** {2 Filesystem} *)
450
451 let input_file fname =
452   let size = (Unix.stat fname).Unix.st_size in
453   let buf = Buffer.create size in
454   let ic = open_in fname in
455   Buffer.add_channel buf ic size;
456   close_in ic;
457   Buffer.contents buf
458
459 let input_all ic =
460   let size = 10240 in
461   let buf = Buffer.create size in
462   let s = String.create size in
463   (try
464     while true do
465       let bytes = input ic s 0 size in
466       if bytes = 0 then raise End_of_file
467       else Buffer.add_substring buf s 0 bytes
468     done
469   with End_of_file -> ());
470   Buffer.contents buf
471
472 let output_file ~filename ~text = 
473   let oc = open_out filename in
474   output_string oc text;
475   close_out oc;
476   chmod 0o664 filename
477
478 let blank_split s =
479   let len = String.length s in
480   let buf = Buffer.create 0 in
481   let rec aux acc i =
482     if i >= len
483     then begin
484       if Buffer.length buf > 0
485       then List.rev (Buffer.contents buf :: acc)
486       else List.rev acc
487     end else begin
488       if is_blank s.[i] then
489         if Buffer.length buf > 0 then begin
490           let s = Buffer.contents buf in
491           Buffer.clear buf;
492           aux (s :: acc) (i + 1)
493         end else
494           aux acc (i + 1)
495       else begin
496         Buffer.add_char buf s.[i];
497         aux acc (i + 1)
498       end
499     end
500   in
501   aux [] 0
502
503   (* Rules: * "~name" -> home dir of "name"
504    * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
505 let tilde_expand s =
506   let get_home login = (Unix.getpwnam login).Unix.pw_dir in
507   let expand_one s =
508     let len = String.length s in
509     if len > 0 && s.[0] = '~' then begin
510       let login_len = ref 1 in
511       while !login_len < len && is_alphanum (s.[!login_len]) do
512         incr login_len
513       done;
514       let login = String.sub s 1 (!login_len - 1) in
515       try
516         let home =
517           if login = "" then
518             try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
519           else
520             get_home login
521         in
522         home ^ String.sub s !login_len (len - !login_len)
523       with Not_found | Invalid_argument _ -> s
524     end else
525       s
526   in
527   String.concat " " (List.map expand_one (blank_split s))
528   
529 let find ?(test = fun _ -> true) path = 
530   let rec aux acc todo = 
531     match todo with
532     | [] -> acc
533     | path :: tl ->
534         try
535           let handle = Unix.opendir path in
536           let dirs = ref [] in
537           let matching_files = ref [] in 
538           (try 
539             while true do 
540               match Unix.readdir handle with
541               | "." | ".." -> ()
542               | entry ->
543                   let qentry = path ^ "/" ^ entry in
544                   (try
545                     if is_dir qentry then
546                       dirs := qentry :: !dirs
547                     else if test qentry then
548                       matching_files := qentry :: !matching_files;
549                   with Unix.Unix_error _ -> ())
550             done
551           with End_of_file -> Unix.closedir handle);
552           aux (!matching_files @ acc) (!dirs @ tl)
553         with Unix.Unix_error _ -> aux acc tl
554   in
555   aux [] [path]
556
557 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
558
559 let is_dir_empty d =
560  try
561   let od = Unix.opendir d in
562   let rec aux () =
563    let name = Unix.readdir od in
564    if name <> "." && name <> ".." then false else aux () in
565   let res = try aux () with End_of_file -> true in
566    Unix.closedir od;
567    res
568  with
569   Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
570
571 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
572
573 let rec rmdir_descend d = 
574   if is_dir_empty d then
575     begin
576       safe_rmdir d;
577       rmdir_descend (Filename.dirname d)
578     end
579
580
581 (** {2 Exception handling} *)
582
583 let finally at_end f arg =
584   let res =
585     try f arg
586     with exn -> at_end (); raise exn
587   in
588   at_end ();
589   res
590
591 (** {2 Localized exceptions } *)
592
593 exception Localized of Stdpp.location * exn
594
595 let loc_of_floc floc = Stdpp.first_pos floc, Stdpp.last_pos floc;;
596
597 let floc_of_loc (loc_begin, loc_end) =
598  Stdpp.make_loc (loc_begin, loc_end)
599
600 let dummy_floc = floc_of_loc (0, 0)
601
602 let raise_localized_exception ~offset floc exn =
603  let x, y = loc_of_floc floc in
604  let x = offset + x in
605  let y = offset + y in
606  let floc = floc_of_loc (x,y) in
607   raise (Localized (floc, exn))
608
609 let estimate_size x = 
610   4 * (String.length (Marshal.to_string x [])) / 1024
611
612 let normalize_path s = 
613   let s = Str.global_replace (Str.regexp "//") "/" s in
614   let l = Str.split (Str.regexp "/") s in
615   let rec aux acc = function
616     | [] -> acc
617     | he::"."::tl -> aux acc (he::tl)
618     | he::".."::tl when he <> ".." -> aux [] (acc @ tl)
619     | he::tl -> aux (acc@[he]) tl
620   in
621   (if Str.string_match (Str.regexp "^/") s 0 then "/" else "") ^
622   String.concat "/" (aux [] l)
623   ^ (if Str.string_match (Str.regexp "/$") s 0 then "/" else "")
624 ;;
625
626 let find_in paths path =
627    let rec aux = function
628    | [] -> raise (Failure "find_in")
629    | p :: tl ->
630       let path = normalize_path (p ^ "/" ^ path) in
631        try
632          if (Unix.stat path).Unix.st_kind = Unix.S_REG then path
633          else aux tl
634        with Unix.Unix_error _ -> 
635                aux tl
636    in
637    try
638      aux paths
639    with Unix.Unix_error _ | Failure _ -> 
640      raise 
641        (Failure "find_in")
642 ;;
643
644 let is_prefix_of_aux d1 d2 = 
645   let len1 = String.length d1 in
646   let len2 = String.length d2 in
647   if len2 < len1 then 
648     false, len1, len2
649   else
650     let pref = String.sub d2 0 len1 in
651     pref = d1 && (len1 = len2 || d1.[len1-1] = '/' || d2.[len1] = '/'), len1, len2
652
653 let is_prefix_of d1 d2 =
654   let b,_,_ = is_prefix_of_aux d1 d2 in b
655 ;;
656
657 let chop_prefix prefix s =
658   let b,lp,ls = is_prefix_of_aux prefix s in
659   if b then
660     String.sub s lp (ls - lp)
661   else 
662     s
663 ;;
664
665 let touch s =
666   try close_out(open_out s) with Sys_error _ -> ()
667 ;;
668
669 let rec mk_list x = function
670   | 0 -> []
671   | n -> x :: mk_list x (n-1)
672 ;;
673
674 let list_seq start stop =
675   if start > stop then [] else
676   let rec aux pos =
677     if pos = stop then []
678     else pos :: (aux (pos+1))
679   in
680     aux start
681 ;;
682
683 let rec list_skip n l =
684   match n,l with
685   | 0,_ -> l
686   | n,_::l -> list_skip (n-1) l
687   | _, [] -> assert false
688 ;;
689