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