]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/extlib/hExtlib.ml
99e6609ec27efed198c8ba68bfa34f0f6b069199
[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
27 (** PROFILING *)
28
29 (* we should use a key in te registry, but we can't see the registry.. *)
30 let profiling_enabled = true
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 () 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 = where ^ "/" ^ piece in
166         (try
167           Unix.mkdir path 0o755
168         with 
169         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
170         | Unix.Unix_error (e,_,_) -> 
171             raise 
172               (Failure 
173                 ("Unix.mkdir " ^ path ^ " 0o755 :" ^ (Unix.error_message e))));
174         aux path tl
175   in
176   aux "" components
177
178 (** {2 Filesystem} *)
179
180 let input_file fname =
181   let size = (Unix.stat fname).Unix.st_size in
182   let buf = Buffer.create size in
183   let ic = open_in fname in
184   Buffer.add_channel buf ic size;
185   close_in ic;
186   Buffer.contents buf
187
188 let input_all ic =
189   let size = 10240 in
190   let buf = Buffer.create size in
191   let s = String.create size in
192   (try
193     while true do
194       let bytes = input ic s 0 size in
195       if bytes = 0 then raise End_of_file
196       else Buffer.add_substring buf s 0 bytes
197     done
198   with End_of_file -> ());
199   Buffer.contents buf
200
201 let output_file ~filename ~text = 
202   let oc = open_out filename in
203   output_string oc text;
204   close_out oc
205
206 let blank_split s =
207   let len = String.length s in
208   let buf = Buffer.create 0 in
209   let rec aux acc i =
210     if i >= len
211     then begin
212       if Buffer.length buf > 0
213       then List.rev (Buffer.contents buf :: acc)
214       else List.rev acc
215     end else begin
216       if is_blank s.[i] then
217         if Buffer.length buf > 0 then begin
218           let s = Buffer.contents buf in
219           Buffer.clear buf;
220           aux (s :: acc) (i + 1)
221         end else
222           aux acc (i + 1)
223       else begin
224         Buffer.add_char buf s.[i];
225         aux acc (i + 1)
226       end
227     end
228   in
229   aux [] 0
230
231   (* Rules: * "~name" -> home dir of "name"
232    * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
233 let tilde_expand s =
234   let get_home login = (Unix.getpwnam login).Unix.pw_dir in
235   let expand_one s =
236     let len = String.length s in
237     if len > 0 && s.[0] = '~' then begin
238       let login_len = ref 1 in
239       while !login_len < len && is_alphanum (s.[!login_len]) do
240         incr login_len
241       done;
242       let login = String.sub s 1 (!login_len - 1) in
243       try
244         let home =
245           if login = "" then
246             try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
247           else
248             get_home login
249         in
250         home ^ String.sub s !login_len (len - !login_len)
251       with Not_found | Invalid_argument _ -> s
252     end else
253       s
254   in
255   String.concat " " (List.map expand_one (blank_split s))
256   
257 let find ?(test = fun _ -> true) path = 
258   let rec aux acc todo = 
259     match todo with
260     | [] -> acc
261     | path :: tl ->
262         try
263           let handle = Unix.opendir path in
264           let dirs = ref [] in
265           let matching_files = ref [] in 
266           (try 
267             while true do 
268               match Unix.readdir handle with
269               | "." | ".." -> ()
270               | entry ->
271                   let qentry = path ^ "/" ^ entry in
272                   (try
273                     if is_dir qentry then
274                       dirs := qentry :: !dirs
275                     else if test qentry then
276                       matching_files := qentry :: !matching_files;
277                   with Unix.Unix_error _ -> ())
278             done
279           with End_of_file -> Unix.closedir handle);
280           aux (!matching_files @ acc) (!dirs @ tl)
281         with Unix.Unix_error _ -> aux acc tl
282   in
283   aux [] [path]
284
285 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
286
287 let is_dir_empty d =
288  let od = Unix.opendir d in
289  let rec aux () =
290   let name = Unix.readdir od in
291   if name <> "." && name <> ".." then false else aux () in
292  let res = try aux () with End_of_file -> true in
293   Unix.closedir od;
294   res
295
296 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
297
298 let rec rmdir_descend d = 
299   if is_dir_empty d then
300     begin
301       safe_rmdir d;
302       rmdir_descend (Filename.dirname d)
303     end
304
305
306 (** {2 Exception handling} *)
307
308 let finally at_end f arg =
309   let res =
310     try f arg
311     with exn -> at_end (); raise exn
312   in
313   at_end ();
314   res
315
316 (** {2 Localized exceptions } *)
317
318 exception Localized of Token.flocation * exn
319
320 let loc_of_floc = function
321   | { Lexing.pos_cnum = loc_begin }, { Lexing.pos_cnum = loc_end } ->
322       (loc_begin, loc_end)
323
324 let raise_localized_exception ~offset floc exn =
325  let (x, y) = loc_of_floc floc in
326  let x = offset + x in
327  let y = offset + y in
328  let flocb,floce = floc in
329  let floc =
330    { flocb with Lexing.pos_cnum = x }, { floce with Lexing.pos_cnum = y }
331  in
332   raise (Localized (floc, exn))