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