]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/extlib/hExtlib.ml
- hExtlib: new function "list_assoc_all"
[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_index p =
152  let rec aux n =
153   function
154      [] -> None
155    | he::_ when p he -> Some (n,he)
156    | _::tl -> aux (n + 1) tl
157  in
158   aux 0
159 ;;
160
161 let rec list_iter_default2 f l1 def l2 = 
162   match l1,l2 with
163     | [], _ -> ()
164     | a::ta, b::tb -> f a b; list_iter_default2 f ta def tb 
165     | a::ta, [] -> f a def; list_iter_default2 f ta def [] 
166 ;;
167
168 let rec list_forall_default3 f l1 l2 def l3 = 
169   match l1,l2,l3 with
170     | [], [], _ -> true
171     | [], _, _
172     | _, [], _ -> raise (Invalid_argument "list_forall_default3")
173     | a::ta, b::tb, c::tc -> f a b c && list_forall_default3 f ta tb def tc
174     | a::ta, b::tb, [] -> f a b def && list_forall_default3 f ta tb def [] 
175 ;;
176
177 exception FailureAt of int;;
178
179 let list_forall_default3_var f l1 l2 def l3 = 
180   let rec aux f l1 l2 def l3 i =
181     match l1,l2,l3 with
182       | [], [], _ -> true
183       | [], _, _
184       | _, [], _ -> raise (Invalid_argument "list_forall_default3")
185       | a::ta, b::tb, c::tc -> 
186           if f a b c then aux f ta tb def tc (i+1)
187           else raise (FailureAt i)
188       | a::ta, b::tb, [] ->
189           if f a b def then aux f ta tb def [] (i+1)
190           else raise (FailureAt i)
191   in aux f l1 l2 def l3 0
192 ;;
193
194 let sharing_map f l =
195   let unchanged = ref true in
196   let rec aux b = function
197     | [] as t -> unchanged := b; t
198     | he::tl ->
199         let he1 = f he in
200         he1 :: aux (b && he1 == he) tl
201   in
202   let l1 = aux true l in
203   if !unchanged then l else l1
204 ;;
205         
206 let rec list_uniq ?(eq=(=)) = function 
207   | [] -> []
208   | h::[] -> [h]
209   | h1::h2::tl when eq h1 h2 -> list_uniq ~eq (h2 :: tl) 
210   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq ~eq tl
211
212 let rec filter_map f =
213   function
214   | [] -> []
215   | hd :: tl ->
216       (match f hd with
217       | None -> filter_map f tl
218       | Some v -> v :: filter_map f tl)
219
220 let list_rev_map_filter f l =
221    let rec aux a = function
222       | []       -> a
223       | hd :: tl -> 
224          begin match f hd with
225             | None   -> aux a tl
226             | Some b -> aux (b :: a) tl 
227          end
228    in 
229    aux [] l
230
231 let list_rev_map_filter_fold f v l =
232    let rec aux v a = function
233       | []       -> v, a
234       | hd :: tl -> 
235          begin match f v hd with
236             | v, None   -> aux v a tl
237             | v, Some b -> aux v (b :: a) tl 
238          end
239    in 
240    aux v [] l
241
242 let list_concat ?(sep = []) =
243   let rec aux acc =
244     function
245     | [] -> []
246     | [ last ] -> List.flatten (List.rev (last :: acc))
247     | hd :: tl -> aux ([sep; hd] @ acc) tl
248   in
249   aux []
250   
251 let rec list_findopt f l = 
252   let rec aux k = function 
253     | [] -> None 
254     | x::tl -> 
255         (match f x k with
256         | None -> aux (succ k) tl
257         | Some _ as rc -> rc)
258   in
259   aux 0 l
260
261 let split_nth n l =
262   let rec aux acc n l =
263     match n, l with
264     | 0, _ -> List.rev acc, l
265     | n, [] -> raise (Failure "HExtlib.split_nth")
266     | n, hd :: tl -> aux (hd :: acc) (n - 1) tl in
267   aux [] n l
268
269 let list_last l =
270   let l = List.rev l in 
271   try List.hd l with exn -> raise (Failure "HExtlib.list_last")
272 ;;
273
274 let rec list_assoc_all a = function
275    | []                      -> []
276    | (x, y) :: tl when x = a -> y :: list_assoc_all a tl
277    | _ :: tl                 -> list_assoc_all a tl
278 ;;
279
280 (** {2 File predicates} *)
281
282 let is_dir fname =
283   try
284     (Unix.stat fname).Unix.st_kind = Unix.S_DIR
285   with Unix.Unix_error _ -> false
286
287 let writable_dir path =
288   try
289     let file = path ^ "/prova_matita" in
290     let oc = open_out file in
291     close_out oc;
292     Sys.remove file;
293     true
294   with Sys_error _ -> false
295
296
297 let is_regular fname =
298   try
299     (Unix.stat fname).Unix.st_kind = Unix.S_REG
300   with Unix.Unix_error _ -> false
301
302 let is_executable fname =
303   try
304     let stat = (Unix.stat fname) in
305     stat.Unix.st_kind = Unix.S_REG &&
306     (stat.Unix.st_perm land 0o001 > 0)
307   with Unix.Unix_error _ -> false
308
309 let chmod mode filename =
310    Unix.chmod filename mode
311
312 let mkdir path =
313   let components = split ~sep:'/' path in
314   let rec aux where = function
315     | [] -> ()
316     | piece::tl -> 
317         let path =
318           if where = "" then piece else where ^ "/" ^ piece in
319         (try
320           Unix.mkdir path 0o755; chmod 0o2775 path 
321         with 
322         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
323         | Unix.Unix_error (e,_,_) -> 
324             raise 
325               (Failure 
326                 ("Unix.mkdir " ^ path ^ " 0o2775 :" ^ (Unix.error_message e))));
327         aux path tl
328   in
329   let where = if path.[0] = '/' then "/" else "" in
330   aux where components
331
332 (** {2 Filesystem} *)
333
334 let input_file fname =
335   let size = (Unix.stat fname).Unix.st_size in
336   let buf = Buffer.create size in
337   let ic = open_in fname in
338   Buffer.add_channel buf ic size;
339   close_in ic;
340   Buffer.contents buf
341
342 let input_all ic =
343   let size = 10240 in
344   let buf = Buffer.create size in
345   let s = String.create size in
346   (try
347     while true do
348       let bytes = input ic s 0 size in
349       if bytes = 0 then raise End_of_file
350       else Buffer.add_substring buf s 0 bytes
351     done
352   with End_of_file -> ());
353   Buffer.contents buf
354
355 let output_file ~filename ~text = 
356   let oc = open_out filename in
357   output_string oc text;
358   close_out oc;
359   chmod 0o664 filename
360
361 let blank_split s =
362   let len = String.length s in
363   let buf = Buffer.create 0 in
364   let rec aux acc i =
365     if i >= len
366     then begin
367       if Buffer.length buf > 0
368       then List.rev (Buffer.contents buf :: acc)
369       else List.rev acc
370     end else begin
371       if is_blank s.[i] then
372         if Buffer.length buf > 0 then begin
373           let s = Buffer.contents buf in
374           Buffer.clear buf;
375           aux (s :: acc) (i + 1)
376         end else
377           aux acc (i + 1)
378       else begin
379         Buffer.add_char buf s.[i];
380         aux acc (i + 1)
381       end
382     end
383   in
384   aux [] 0
385
386   (* Rules: * "~name" -> home dir of "name"
387    * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
388 let tilde_expand s =
389   let get_home login = (Unix.getpwnam login).Unix.pw_dir in
390   let expand_one s =
391     let len = String.length s in
392     if len > 0 && s.[0] = '~' then begin
393       let login_len = ref 1 in
394       while !login_len < len && is_alphanum (s.[!login_len]) do
395         incr login_len
396       done;
397       let login = String.sub s 1 (!login_len - 1) in
398       try
399         let home =
400           if login = "" then
401             try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
402           else
403             get_home login
404         in
405         home ^ String.sub s !login_len (len - !login_len)
406       with Not_found | Invalid_argument _ -> s
407     end else
408       s
409   in
410   String.concat " " (List.map expand_one (blank_split s))
411   
412 let find ?(test = fun _ -> true) path = 
413   let rec aux acc todo = 
414     match todo with
415     | [] -> acc
416     | path :: tl ->
417         try
418           let handle = Unix.opendir path in
419           let dirs = ref [] in
420           let matching_files = ref [] in 
421           (try 
422             while true do 
423               match Unix.readdir handle with
424               | "." | ".." -> ()
425               | entry ->
426                   let qentry = path ^ "/" ^ entry in
427                   (try
428                     if is_dir qentry then
429                       dirs := qentry :: !dirs
430                     else if test qentry then
431                       matching_files := qentry :: !matching_files;
432                   with Unix.Unix_error _ -> ())
433             done
434           with End_of_file -> Unix.closedir handle);
435           aux (!matching_files @ acc) (!dirs @ tl)
436         with Unix.Unix_error _ -> aux acc tl
437   in
438   aux [] [path]
439
440 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
441
442 let is_dir_empty d =
443  try
444   let od = Unix.opendir d in
445   let rec aux () =
446    let name = Unix.readdir od in
447    if name <> "." && name <> ".." then false else aux () in
448   let res = try aux () with End_of_file -> true in
449    Unix.closedir od;
450    res
451  with
452   Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
453
454 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
455
456 let rec rmdir_descend d = 
457   if is_dir_empty d then
458     begin
459       safe_rmdir d;
460       rmdir_descend (Filename.dirname d)
461     end
462
463
464 (** {2 Exception handling} *)
465
466 let finally at_end f arg =
467   let res =
468     try f arg
469     with exn -> at_end (); raise exn
470   in
471   at_end ();
472   res
473
474 (** {2 Localized exceptions } *)
475
476 exception Localized of Stdpp.location * exn
477
478 let loc_of_floc floc = Stdpp.first_pos floc, Stdpp.last_pos floc;;
479
480 let floc_of_loc (loc_begin, loc_end) =
481  Stdpp.make_loc (loc_begin, loc_end)
482
483 let dummy_floc = floc_of_loc (0, 0)
484
485 let raise_localized_exception ~offset floc exn =
486  let x, y = loc_of_floc floc in
487  let x = offset + x in
488  let y = offset + y in
489  let floc = floc_of_loc (x,y) in
490   raise (Localized (floc, exn))
491
492 let estimate_size x = 
493   4 * (String.length (Marshal.to_string x [])) / 1024
494
495 let normalize_path s = 
496   let s = Str.global_replace (Str.regexp "//") "/" s in
497   let l = Str.split (Str.regexp "/") s in
498   let rec aux acc = function
499     | [] -> acc
500     | he::"."::tl -> aux acc (he::tl)
501     | he::".."::tl when he <> ".." -> aux [] (acc @ tl)
502     | he::tl -> aux (acc@[he]) tl
503   in
504   (if Str.string_match (Str.regexp "^/") s 0 then "/" else "") ^
505   String.concat "/" (aux [] l)
506   ^ (if Str.string_match (Str.regexp "/$") s 0 then "/" else "")
507 ;;
508
509 let find_in paths path =
510    let rec aux = function
511    | [] -> raise (Failure "find_in")
512    | p :: tl ->
513       let path = normalize_path (p ^ "/" ^ path) in
514        try
515          if (Unix.stat path).Unix.st_kind = Unix.S_REG then path
516          else aux tl
517        with Unix.Unix_error _ -> 
518                aux tl
519    in
520    try
521      aux paths
522    with Unix.Unix_error _ | Failure _ -> 
523      raise 
524        (Failure "find_in")
525 ;;
526
527 let is_prefix_of_aux d1 d2 = 
528   let len1 = String.length d1 in
529   let len2 = String.length d2 in
530   if len2 < len1 then 
531     false, len1, len2
532   else
533     let pref = String.sub d2 0 len1 in
534     pref = d1 && (len1 = len2 || d1.[len1-1] = '/' || d2.[len1] = '/'), len1, len2
535
536 let is_prefix_of d1 d2 =
537   let b,_,_ = is_prefix_of_aux d1 d2 in b
538 ;;
539
540 let chop_prefix prefix s =
541   let b,lp,ls = is_prefix_of_aux prefix s in
542   if b then
543     String.sub s lp (ls - lp)
544   else 
545     s
546 ;;
547
548 let touch s =
549   try close_out(open_out s) with Sys_error _ -> ()
550 ;;
551
552 let rec mk_list x = function
553   | 0 -> []
554   | n -> x :: mk_list x (n-1)
555 ;;
556
557 let list_seq start stop =
558   if start > stop then [] else
559   let rec aux pos =
560     if pos = stop then []
561     else pos :: (aux (pos+1))
562   in
563     aux start
564 ;;
565
566 let rec list_skip n l =
567   match n,l with
568   | 0,_ -> l
569   | n,_::l -> list_skip (n-1) l
570   | _, [] -> assert false
571 ;;
572