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