]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/extlib/hExtlib.ml
BIG FAT COMMIT REGARDING COERCIONS:
[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 = 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     let before = Unix.gettimeofday () in
56     try
57      incr calls;
58      let res = f x in
59      let after = Unix.gettimeofday () in
60      let delta = after -. before in
61       total := !total +. delta;
62       if delta > !max then max := delta;
63       res
64     with
65      exc ->
66       let after = Unix.gettimeofday () in
67       let delta = after -. before in
68        total := !total +. delta;
69        if delta > !max then max := delta;
70        raise exc
71    in
72    at_exit
73     (fun () ->
74       if !profiling_printings s && !calls <> 0 then
75        begin
76         something_profiled := true;
77         prerr_endline
78          (Printf.sprintf "!! %-39s %10d %9.4f %9.4f %9.4f" 
79          s !calls !total !max (!total /. (float_of_int !calls)))
80        end);
81    { profile = profile }
82  else
83    { profile = fun f x -> f x }
84
85 (** {2 Optional values} *)
86
87 let map_option f = function None -> None | Some v -> Some (f v)
88 let iter_option f = function None -> () | Some v -> f v
89 let unopt = function None -> failwith "unopt: None" | Some v -> v
90
91 (** {2 String processing} *)
92
93 let split ?(sep = ' ') s =
94   let pieces = ref [] in
95   let rec aux idx =
96     match (try Some (String.index_from s idx sep) with Not_found -> None) with
97     | Some pos ->
98         pieces := String.sub s idx (pos - idx) :: !pieces;
99         aux (pos + 1)
100     | None -> pieces := String.sub s idx (String.length s - idx) :: !pieces
101   in
102   aux 0;
103   List.rev !pieces
104
105 let trim_blanks s =
106   let rec find_left idx =
107     match s.[idx] with
108     | ' ' | '\t' | '\r' | '\n' -> find_left (idx + 1)
109     | _ -> idx
110   in
111   let rec find_right idx =
112     match s.[idx] with
113     | ' ' | '\t' | '\r' | '\n' -> find_right (idx - 1)
114     | _ -> idx
115   in
116   let s_len = String.length s in
117   let left, right = find_left 0, find_right (s_len - 1) in
118   String.sub s left (right - left + 1)
119
120 (** {2 Char processing} *)
121
122 let is_alpha c =
123   let code = Char.code c in 
124   (code >= 65 && code <= 90) || (code >= 97 && code <= 122)
125
126 let is_digit c =
127   let code = Char.code c in 
128   code >= 48 && code <= 57
129
130 let is_blank c =
131   let code = Char.code c in 
132   code = 9 || code = 10 || code = 13 || code = 32
133
134 let is_alphanum c = is_alpha c || is_digit c
135
136 (** {2 List processing} *)
137
138 let flatten_map f l =
139   List.flatten (List.map f l)
140 ;;
141
142 let rec list_uniq ?(eq=(=)) = function 
143   | [] -> []
144   | h::[] -> [h]
145   | h1::h2::tl when eq h1 h2 -> list_uniq ~eq (h2 :: tl) 
146   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq ~eq tl
147
148 let rec filter_map f =
149   function
150   | [] -> []
151   | hd :: tl ->
152       (match f hd with
153       | None -> filter_map f tl
154       | Some v -> v :: filter_map f tl)
155
156 let list_concat ?(sep = []) =
157   let rec aux acc =
158     function
159     | [] -> []
160     | [ last ] -> List.flatten (List.rev (last :: acc))
161     | hd :: tl -> aux ([sep; hd] @ acc) tl
162   in
163   aux []
164   
165 let rec list_findopt f l = 
166   let rec aux = function 
167     | [] -> None 
168     | x::tl -> 
169         (match f x with
170         | None -> aux tl
171         | Some _ as rc -> rc)
172   in
173   aux l
174
175 let split_nth n l =
176   let rec aux acc n l =
177     match n, l with
178     | 0, _ -> List.rev acc, l
179     | n, [] -> raise (Failure "HExtlib.split_nth")
180     | n, hd :: tl -> aux (hd :: acc) (n - 1) tl in
181   aux [] n l
182
183 let list_last l =
184   let l = List.rev l in 
185   try List.hd l with exn -> raise (Failure "HExtlib.list_last")
186 ;;
187   
188 (** {2 File predicates} *)
189
190 let is_dir fname =
191   try
192     (Unix.stat fname).Unix.st_kind = Unix.S_DIR
193   with Unix.Unix_error _ -> false
194
195 let is_regular fname =
196   try
197     (Unix.stat fname).Unix.st_kind = Unix.S_REG
198   with Unix.Unix_error _ -> false
199
200 let mkdir path =
201   let components = split ~sep:'/' path in
202   let rec aux where = function
203     | [] -> ()
204     | piece::tl -> 
205         let path =
206           if where = "" then piece else where ^ "/" ^ piece in
207         (try
208           Unix.mkdir path 0o755
209         with 
210         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
211         | Unix.Unix_error (e,_,_) -> 
212             raise 
213               (Failure 
214                 ("Unix.mkdir " ^ path ^ " 0o755 :" ^ (Unix.error_message e))));
215         aux path tl
216   in
217   let where = if path.[0] = '/' then "/" else "" in
218   aux where components
219
220 (** {2 Filesystem} *)
221
222 let input_file fname =
223   let size = (Unix.stat fname).Unix.st_size in
224   let buf = Buffer.create size in
225   let ic = open_in fname in
226   Buffer.add_channel buf ic size;
227   close_in ic;
228   Buffer.contents buf
229
230 let input_all ic =
231   let size = 10240 in
232   let buf = Buffer.create size in
233   let s = String.create size in
234   (try
235     while true do
236       let bytes = input ic s 0 size in
237       if bytes = 0 then raise End_of_file
238       else Buffer.add_substring buf s 0 bytes
239     done
240   with End_of_file -> ());
241   Buffer.contents buf
242
243 let output_file ~filename ~text = 
244   let oc = open_out filename in
245   output_string oc text;
246   close_out oc
247
248 let blank_split s =
249   let len = String.length s in
250   let buf = Buffer.create 0 in
251   let rec aux acc i =
252     if i >= len
253     then begin
254       if Buffer.length buf > 0
255       then List.rev (Buffer.contents buf :: acc)
256       else List.rev acc
257     end else begin
258       if is_blank s.[i] then
259         if Buffer.length buf > 0 then begin
260           let s = Buffer.contents buf in
261           Buffer.clear buf;
262           aux (s :: acc) (i + 1)
263         end else
264           aux acc (i + 1)
265       else begin
266         Buffer.add_char buf s.[i];
267         aux acc (i + 1)
268       end
269     end
270   in
271   aux [] 0
272
273   (* Rules: * "~name" -> home dir of "name"
274    * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
275 let tilde_expand s =
276   let get_home login = (Unix.getpwnam login).Unix.pw_dir in
277   let expand_one s =
278     let len = String.length s in
279     if len > 0 && s.[0] = '~' then begin
280       let login_len = ref 1 in
281       while !login_len < len && is_alphanum (s.[!login_len]) do
282         incr login_len
283       done;
284       let login = String.sub s 1 (!login_len - 1) in
285       try
286         let home =
287           if login = "" then
288             try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
289           else
290             get_home login
291         in
292         home ^ String.sub s !login_len (len - !login_len)
293       with Not_found | Invalid_argument _ -> s
294     end else
295       s
296   in
297   String.concat " " (List.map expand_one (blank_split s))
298   
299 let find ?(test = fun _ -> true) path = 
300   let rec aux acc todo = 
301     match todo with
302     | [] -> acc
303     | path :: tl ->
304         try
305           let handle = Unix.opendir path in
306           let dirs = ref [] in
307           let matching_files = ref [] in 
308           (try 
309             while true do 
310               match Unix.readdir handle with
311               | "." | ".." -> ()
312               | entry ->
313                   let qentry = path ^ "/" ^ entry in
314                   (try
315                     if is_dir qentry then
316                       dirs := qentry :: !dirs
317                     else if test qentry then
318                       matching_files := qentry :: !matching_files;
319                   with Unix.Unix_error _ -> ())
320             done
321           with End_of_file -> Unix.closedir handle);
322           aux (!matching_files @ acc) (!dirs @ tl)
323         with Unix.Unix_error _ -> aux acc tl
324   in
325   aux [] [path]
326
327 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
328
329 let is_dir_empty d =
330  try
331   let od = Unix.opendir d in
332   let rec aux () =
333    let name = Unix.readdir od in
334    if name <> "." && name <> ".." then false else aux () in
335   let res = try aux () with End_of_file -> true in
336    Unix.closedir od;
337    res
338  with
339   Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
340
341 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
342
343 let rec rmdir_descend d = 
344   if is_dir_empty d then
345     begin
346       safe_rmdir d;
347       rmdir_descend (Filename.dirname d)
348     end
349
350
351 (** {2 Exception handling} *)
352
353 let finally at_end f arg =
354   let res =
355     try f arg
356     with exn -> at_end (); raise exn
357   in
358   at_end ();
359   res
360
361 (** {2 Localized exceptions } *)
362
363 exception Localized of Token.flocation * exn
364
365 let loc_of_floc = function
366   | { Lexing.pos_cnum = loc_begin }, { Lexing.pos_cnum = loc_end } ->
367       (loc_begin, loc_end)
368
369 let floc_of_loc (loc_begin, loc_end) =
370   let floc_begin =
371     { Lexing.pos_fname = ""; Lexing.pos_lnum = -1; Lexing.pos_bol = -1;
372       Lexing.pos_cnum = loc_begin }
373   in
374   let floc_end = { floc_begin with Lexing.pos_cnum = loc_end } in
375   (floc_begin, floc_end)
376
377 let dummy_floc = floc_of_loc (-1, -1)
378
379 let raise_localized_exception ~offset floc exn =
380  let (x, y) = loc_of_floc floc in
381  let x = offset + x in
382  let y = offset + y in
383  let flocb,floce = floc in
384  let floc =
385    { flocb with Lexing.pos_cnum = x }, { floce with Lexing.pos_cnum = y }
386  in
387   raise (Localized (floc, exn))
388
389 let estimate_size x = 
390   4 * (String.length (Marshal.to_string x [])) / 1024
391