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