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