]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/extlib/hExtlib.ml
added estimate_size
[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 = 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 rec list_uniq ?(eq=(=)) = function 
139   | [] -> []
140   | h::[] -> [h]
141   | h1::h2::tl when eq h1 h2 -> list_uniq ~eq (h2 :: tl) 
142   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq ~eq tl
143
144 let rec filter_map f =
145   function
146   | [] -> []
147   | hd :: tl ->
148       (match f hd with
149       | None -> filter_map f tl
150       | Some v -> v :: filter_map f tl)
151
152 let list_concat ?(sep = []) =
153   let rec aux acc =
154     function
155     | [] -> []
156     | [ last ] -> List.flatten (List.rev (last :: acc))
157     | hd :: tl -> aux ([sep; hd] @ acc) tl
158   in
159   aux []
160   
161 let rec list_findopt f l = 
162   let rec aux = function 
163     | [] -> None 
164     | x::tl -> 
165         (match f x with
166         | None -> aux tl
167         | Some _ as rc -> rc)
168   in
169   aux l
170
171 (** {2 File predicates} *)
172
173 let is_dir fname =
174   try
175     (Unix.stat fname).Unix.st_kind = Unix.S_DIR
176   with Unix.Unix_error _ -> false
177
178 let is_regular fname =
179   try
180     (Unix.stat fname).Unix.st_kind = Unix.S_REG
181   with Unix.Unix_error _ -> false
182
183 let mkdir path =
184   let components = split ~sep:'/' path in
185   let rec aux where = function
186     | [] -> ()
187     | piece::tl -> 
188         let path =
189           if where = "" then piece else where ^ "/" ^ piece in
190         (try
191           Unix.mkdir path 0o755
192         with 
193         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
194         | Unix.Unix_error (e,_,_) -> 
195             raise 
196               (Failure 
197                 ("Unix.mkdir " ^ path ^ " 0o755 :" ^ (Unix.error_message e))));
198         aux path tl
199   in
200   let where = if path.[0] = '/' then "/" else "" in
201   aux where components
202
203 (** {2 Filesystem} *)
204
205 let input_file fname =
206   let size = (Unix.stat fname).Unix.st_size in
207   let buf = Buffer.create size in
208   let ic = open_in fname in
209   Buffer.add_channel buf ic size;
210   close_in ic;
211   Buffer.contents buf
212
213 let input_all ic =
214   let size = 10240 in
215   let buf = Buffer.create size in
216   let s = String.create size in
217   (try
218     while true do
219       let bytes = input ic s 0 size in
220       if bytes = 0 then raise End_of_file
221       else Buffer.add_substring buf s 0 bytes
222     done
223   with End_of_file -> ());
224   Buffer.contents buf
225
226 let output_file ~filename ~text = 
227   let oc = open_out filename in
228   output_string oc text;
229   close_out oc
230
231 let blank_split s =
232   let len = String.length s in
233   let buf = Buffer.create 0 in
234   let rec aux acc i =
235     if i >= len
236     then begin
237       if Buffer.length buf > 0
238       then List.rev (Buffer.contents buf :: acc)
239       else List.rev acc
240     end else begin
241       if is_blank s.[i] then
242         if Buffer.length buf > 0 then begin
243           let s = Buffer.contents buf in
244           Buffer.clear buf;
245           aux (s :: acc) (i + 1)
246         end else
247           aux acc (i + 1)
248       else begin
249         Buffer.add_char buf s.[i];
250         aux acc (i + 1)
251       end
252     end
253   in
254   aux [] 0
255
256   (* Rules: * "~name" -> home dir of "name"
257    * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
258 let tilde_expand s =
259   let get_home login = (Unix.getpwnam login).Unix.pw_dir in
260   let expand_one s =
261     let len = String.length s in
262     if len > 0 && s.[0] = '~' then begin
263       let login_len = ref 1 in
264       while !login_len < len && is_alphanum (s.[!login_len]) do
265         incr login_len
266       done;
267       let login = String.sub s 1 (!login_len - 1) in
268       try
269         let home =
270           if login = "" then
271             try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
272           else
273             get_home login
274         in
275         home ^ String.sub s !login_len (len - !login_len)
276       with Not_found | Invalid_argument _ -> s
277     end else
278       s
279   in
280   String.concat " " (List.map expand_one (blank_split s))
281   
282 let find ?(test = fun _ -> true) path = 
283   let rec aux acc todo = 
284     match todo with
285     | [] -> acc
286     | path :: tl ->
287         try
288           let handle = Unix.opendir path in
289           let dirs = ref [] in
290           let matching_files = ref [] in 
291           (try 
292             while true do 
293               match Unix.readdir handle with
294               | "." | ".." -> ()
295               | entry ->
296                   let qentry = path ^ "/" ^ entry in
297                   (try
298                     if is_dir qentry then
299                       dirs := qentry :: !dirs
300                     else if test qentry then
301                       matching_files := qentry :: !matching_files;
302                   with Unix.Unix_error _ -> ())
303             done
304           with End_of_file -> Unix.closedir handle);
305           aux (!matching_files @ acc) (!dirs @ tl)
306         with Unix.Unix_error _ -> aux acc tl
307   in
308   aux [] [path]
309
310 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
311
312 let is_dir_empty d =
313  let od = Unix.opendir d in
314  let rec aux () =
315   let name = Unix.readdir od in
316   if name <> "." && name <> ".." then false else aux () in
317  let res = try aux () with End_of_file -> true in
318   Unix.closedir od;
319   res
320
321 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
322
323 let rec rmdir_descend d = 
324   if is_dir_empty d then
325     begin
326       safe_rmdir d;
327       rmdir_descend (Filename.dirname d)
328     end
329
330
331 (** {2 Exception handling} *)
332
333 let finally at_end f arg =
334   let res =
335     try f arg
336     with exn -> at_end (); raise exn
337   in
338   at_end ();
339   res
340
341 (** {2 Localized exceptions } *)
342
343 exception Localized of Token.flocation * exn
344
345 let loc_of_floc = function
346   | { Lexing.pos_cnum = loc_begin }, { Lexing.pos_cnum = loc_end } ->
347       (loc_begin, loc_end)
348
349 let floc_of_loc (loc_begin, loc_end) =
350   let floc_begin =
351     { Lexing.pos_fname = ""; Lexing.pos_lnum = -1; Lexing.pos_bol = -1;
352       Lexing.pos_cnum = loc_begin }
353   in
354   let floc_end = { floc_begin with Lexing.pos_cnum = loc_end } in
355   (floc_begin, floc_end)
356
357 let dummy_floc = floc_of_loc (-1, -1)
358
359 let raise_localized_exception ~offset floc exn =
360  let (x, y) = loc_of_floc floc in
361  let x = offset + x in
362  let y = offset + y in
363  let flocb,floce = floc in
364  let floc =
365    { flocb with Lexing.pos_cnum = x }, { floce with Lexing.pos_cnum = y }
366  in
367   raise (Localized (floc, exn))
368
369 let estimate_size x = 
370   4 * (String.length (Marshal.to_string x [])) / 1024
371