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