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