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