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