]> matita.cs.unibo.it Git - helm.git/blob - components/extlib/hExtlib.ml
2fba7f651497a532af8db1445cdc12d25dcea302
[helm.git] / 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 writable_dir path =
218   try
219     let file = path ^ "/prova_matita" in
220     let oc = open_out file in
221     close_out oc;
222     Sys.remove file;
223     true
224   with Sys_error _ -> false
225
226
227 let is_regular fname =
228   try
229     (Unix.stat fname).Unix.st_kind = Unix.S_REG
230   with Unix.Unix_error _ -> false
231
232 let is_executable fname =
233   try
234     let stat = (Unix.stat fname) in
235     stat.Unix.st_kind = Unix.S_REG &&
236     (stat.Unix.st_perm land 0o001 > 0)
237   with Unix.Unix_error _ -> false
238
239 let chmod mode filename =
240    Unix.chmod filename mode
241
242 let mkdir path =
243   let components = split ~sep:'/' path in
244   let rec aux where = function
245     | [] -> ()
246     | piece::tl -> 
247         let path =
248           if where = "" then piece else where ^ "/" ^ piece in
249         (try
250           Unix.mkdir path 0o755; chmod 0o2775 path 
251         with 
252         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
253         | Unix.Unix_error (e,_,_) -> 
254             raise 
255               (Failure 
256                 ("Unix.mkdir " ^ path ^ " 0o2775 :" ^ (Unix.error_message e))));
257         aux path tl
258   in
259   let where = if path.[0] = '/' then "/" else "" in
260   aux where components
261
262 (** {2 Filesystem} *)
263
264 let input_file fname =
265   let size = (Unix.stat fname).Unix.st_size in
266   let buf = Buffer.create size in
267   let ic = open_in fname in
268   Buffer.add_channel buf ic size;
269   close_in ic;
270   Buffer.contents buf
271
272 let input_all ic =
273   let size = 10240 in
274   let buf = Buffer.create size in
275   let s = String.create size in
276   (try
277     while true do
278       let bytes = input ic s 0 size in
279       if bytes = 0 then raise End_of_file
280       else Buffer.add_substring buf s 0 bytes
281     done
282   with End_of_file -> ());
283   Buffer.contents buf
284
285 let output_file ~filename ~text = 
286   let oc = open_out filename in
287   output_string oc text;
288   close_out oc;
289   chmod 0o664 filename
290
291 let blank_split s =
292   let len = String.length s in
293   let buf = Buffer.create 0 in
294   let rec aux acc i =
295     if i >= len
296     then begin
297       if Buffer.length buf > 0
298       then List.rev (Buffer.contents buf :: acc)
299       else List.rev acc
300     end else begin
301       if is_blank s.[i] then
302         if Buffer.length buf > 0 then begin
303           let s = Buffer.contents buf in
304           Buffer.clear buf;
305           aux (s :: acc) (i + 1)
306         end else
307           aux acc (i + 1)
308       else begin
309         Buffer.add_char buf s.[i];
310         aux acc (i + 1)
311       end
312     end
313   in
314   aux [] 0
315
316   (* Rules: * "~name" -> home dir of "name"
317    * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
318 let tilde_expand s =
319   let get_home login = (Unix.getpwnam login).Unix.pw_dir in
320   let expand_one s =
321     let len = String.length s in
322     if len > 0 && s.[0] = '~' then begin
323       let login_len = ref 1 in
324       while !login_len < len && is_alphanum (s.[!login_len]) do
325         incr login_len
326       done;
327       let login = String.sub s 1 (!login_len - 1) in
328       try
329         let home =
330           if login = "" then
331             try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
332           else
333             get_home login
334         in
335         home ^ String.sub s !login_len (len - !login_len)
336       with Not_found | Invalid_argument _ -> s
337     end else
338       s
339   in
340   String.concat " " (List.map expand_one (blank_split s))
341   
342 let find ?(test = fun _ -> true) path = 
343   let rec aux acc todo = 
344     match todo with
345     | [] -> acc
346     | path :: tl ->
347         try
348           let handle = Unix.opendir path in
349           let dirs = ref [] in
350           let matching_files = ref [] in 
351           (try 
352             while true do 
353               match Unix.readdir handle with
354               | "." | ".." -> ()
355               | entry ->
356                   let qentry = path ^ "/" ^ entry in
357                   (try
358                     if is_dir qentry then
359                       dirs := qentry :: !dirs
360                     else if test qentry then
361                       matching_files := qentry :: !matching_files;
362                   with Unix.Unix_error _ -> ())
363             done
364           with End_of_file -> Unix.closedir handle);
365           aux (!matching_files @ acc) (!dirs @ tl)
366         with Unix.Unix_error _ -> aux acc tl
367   in
368   aux [] [path]
369
370 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
371
372 let is_dir_empty d =
373  try
374   let od = Unix.opendir d in
375   let rec aux () =
376    let name = Unix.readdir od in
377    if name <> "." && name <> ".." then false else aux () in
378   let res = try aux () with End_of_file -> true in
379    Unix.closedir od;
380    res
381  with
382   Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
383
384 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
385
386 let rec rmdir_descend d = 
387   if is_dir_empty d then
388     begin
389       safe_rmdir d;
390       rmdir_descend (Filename.dirname d)
391     end
392
393
394 (** {2 Exception handling} *)
395
396 let finally at_end f arg =
397   let res =
398     try f arg
399     with exn -> at_end (); raise exn
400   in
401   at_end ();
402   res
403
404 (** {2 Localized exceptions } *)
405
406 exception Localized of Stdpp.location * exn
407
408 let loc_of_floc floc = Stdpp.first_pos floc, Stdpp.last_pos floc;;
409
410 let floc_of_loc (loc_begin, loc_end) =
411  Stdpp.make_loc (loc_begin, loc_end)
412
413 let dummy_floc = floc_of_loc (-1, -1)
414
415 let raise_localized_exception ~offset floc exn =
416  let x, y = loc_of_floc floc in
417  let x = offset + x in
418  let y = offset + y in
419  let floc = floc_of_loc (x,y) in
420   raise (Localized (floc, exn))
421
422 let estimate_size x = 
423   4 * (String.length (Marshal.to_string x [])) / 1024
424
425 let normalize_path s = 
426   let s = Str.global_replace (Str.regexp "//") "/" s in
427   let l = Str.split (Str.regexp "/") s in
428   let rec aux = function
429     | [] -> []
430     | he::".."::tl -> aux tl
431     | he::"."::tl -> aux (he::tl)
432     | he::tl -> he :: aux tl
433   in
434   (if Str.string_match (Str.regexp "^/") s 0 then "/" else "") ^
435   String.concat "/" (aux l)
436   ^ (if Str.string_match (Str.regexp "/$") s 0 then "/" else "")
437 ;;
438
439 let find_in paths path =
440    let rec aux = function
441    | [] -> raise (Failure "not found")
442    | p :: tl ->
443       let path = normalize_path (p ^ "/" ^ path) in
444        try
445          if (Unix.stat path).Unix.st_kind = Unix.S_REG then path
446          else aux tl
447        with Unix.Unix_error _ -> aux tl
448    in
449    try
450      aux paths
451    with Unix.Unix_error _ | Failure _ -> 
452      raise 
453        (Failure ("File " ^ path ^ " not found (or not readable) in: " ^
454          String.concat ":" paths))
455 ;;
456