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