]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/extlib/hExtlib.ml
according to camlp5 sources, the dummy loc should be 0,0 and not -1,-1
[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 = ref 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     if not !profiling_enabled then f x else
56     let before = Unix.gettimeofday () in
57     try
58      incr calls;
59      let res = f x in
60      let after = Unix.gettimeofday () in
61      let delta = after -. before in
62       total := !total +. delta;
63       if delta > !max then max := delta;
64       res
65     with
66      exc ->
67       let after = Unix.gettimeofday () in
68       let delta = after -. before in
69        total := !total +. delta;
70        if delta > !max then max := delta;
71        raise exc
72    in
73    at_exit
74     (fun () ->
75       if !profiling_printings s && !calls <> 0 then
76        begin
77         something_profiled := true;
78         prerr_endline
79          (Printf.sprintf "!! %-39s %10d %9.4f %9.4f %9.4f" 
80          s !calls !total !max (!total /. (float_of_int !calls)))
81        end);
82    { profile = profile }
83  else
84    { profile = fun f x -> f x }
85
86 (** {2 Optional values} *)
87
88 let map_option f = function None -> None | Some v -> Some (f v)
89 let iter_option f = function None -> () | Some v -> f v
90 let unopt = function None -> failwith "unopt: None" | Some v -> v
91
92 (** {2 String processing} *)
93
94 let split ?(sep = ' ') s =
95   let pieces = ref [] in
96   let rec aux idx =
97     match (try Some (String.index_from s idx sep) with Not_found -> None) with
98     | Some pos ->
99         pieces := String.sub s idx (pos - idx) :: !pieces;
100         aux (pos + 1)
101     | None -> pieces := String.sub s idx (String.length s - idx) :: !pieces
102   in
103   aux 0;
104   List.rev !pieces
105
106 let trim_blanks s =
107   let rec find_left idx =
108     match s.[idx] with
109     | ' ' | '\t' | '\r' | '\n' -> find_left (idx + 1)
110     | _ -> idx
111   in
112   let rec find_right idx =
113     match s.[idx] with
114     | ' ' | '\t' | '\r' | '\n' -> find_right (idx - 1)
115     | _ -> idx
116   in
117   let s_len = String.length s in
118   let left, right = find_left 0, find_right (s_len - 1) in
119   String.sub s left (right - left + 1)
120
121 (** {2 Char processing} *)
122
123 let is_alpha c =
124   let code = Char.code c in 
125   (code >= 65 && code <= 90) || (code >= 97 && code <= 122)
126
127 let is_digit c =
128   let code = Char.code c in 
129   code >= 48 && code <= 57
130
131 let is_blank c =
132   let code = Char.code c in 
133   code = 9 || code = 10 || code = 13 || code = 32
134
135 let is_alphanum c = is_alpha c || is_digit c
136
137 (** {2 List processing} *)
138
139 let flatten_map f l =
140   List.flatten (List.map f l)
141 ;;
142
143 let list_mapi f l =
144   let rec aux k = function
145     | [] -> []
146     | h::tl -> f h k :: aux (k+1) tl
147   in
148      aux 0 l
149 ;;
150
151 let rec list_iter_default2 f l1 def l2 = 
152   match l1,l2 with
153     | [], _ -> ()
154     | a::ta, b::tb -> f a b; list_iter_default2 f ta def tb 
155     | a::ta, [] -> f a def; list_iter_default2 f ta def [] 
156 ;;
157
158 let rec list_forall_default3 f l1 l2 def l3 = 
159   match l1,l2,l3 with
160     | [], [], _ -> true
161     | [], _, _
162     | _, [], _ -> raise (Invalid_argument "list_forall_default3")
163     | a::ta, b::tb, c::tc -> f a b c && list_forall_default3 f ta tb def tc
164     | a::ta, b::tb, [] -> f a b def && list_forall_default3 f ta tb def [] 
165 ;;
166
167 exception FailureAt of int;;
168
169 let list_forall_default3_var f l1 l2 def l3 = 
170   let rec aux f l1 l2 def l3 i =
171     match l1,l2,l3 with
172       | [], [], _ -> true
173       | [], _, _
174       | _, [], _ -> raise (Invalid_argument "list_forall_default3")
175       | a::ta, b::tb, c::tc -> 
176           if f a b c then aux f ta tb def tc (i+1)
177           else raise (FailureAt i)
178       | a::ta, b::tb, [] ->
179           if f a b def then aux f ta tb def [] (i+1)
180           else raise (FailureAt i)
181   in aux f l1 l2 def l3 0
182 ;;
183
184 let sharing_map f l =
185   let unchanged = ref true in
186   let rec aux b = function
187     | [] as t -> unchanged := b; t
188     | he::tl ->
189         let he1 = f he in
190         he1 :: aux (b && he1 == he) tl
191   in
192   let l1 = aux true l in
193   if !unchanged then l else l1
194 ;;
195         
196 let rec list_uniq ?(eq=(=)) = function 
197   | [] -> []
198   | h::[] -> [h]
199   | h1::h2::tl when eq h1 h2 -> list_uniq ~eq (h2 :: tl) 
200   | h1::tl (* when h1 <> h2 *) -> h1 :: list_uniq ~eq tl
201
202 let rec filter_map f =
203   function
204   | [] -> []
205   | hd :: tl ->
206       (match f hd with
207       | None -> filter_map f tl
208       | Some v -> v :: filter_map f tl)
209
210 let list_rev_map_filter f l =
211    let rec aux a = function
212       | []       -> a
213       | hd :: tl -> 
214          begin match f hd with
215             | None   -> aux a tl
216             | Some b -> aux (b :: a) tl 
217          end
218    in 
219    aux [] l
220
221 let list_rev_map_filter_fold f v l =
222    let rec aux v a = function
223       | []       -> v, a
224       | hd :: tl -> 
225          begin match f v hd with
226             | v, None   -> aux v a tl
227             | v, Some b -> aux v (b :: a) tl 
228          end
229    in 
230    aux v [] l
231
232 let list_concat ?(sep = []) =
233   let rec aux acc =
234     function
235     | [] -> []
236     | [ last ] -> List.flatten (List.rev (last :: acc))
237     | hd :: tl -> aux ([sep; hd] @ acc) tl
238   in
239   aux []
240   
241 let rec list_findopt f l = 
242   let rec aux = function 
243     | [] -> None 
244     | x::tl -> 
245         (match f x with
246         | None -> aux tl
247         | Some _ as rc -> rc)
248   in
249   aux l
250
251 let split_nth n l =
252   let rec aux acc n l =
253     match n, l with
254     | 0, _ -> List.rev acc, l
255     | n, [] -> raise (Failure "HExtlib.split_nth")
256     | n, hd :: tl -> aux (hd :: acc) (n - 1) tl in
257   aux [] n l
258
259 let list_last l =
260   let l = List.rev l in 
261   try List.hd l with exn -> raise (Failure "HExtlib.list_last")
262 ;;
263   
264 (** {2 File predicates} *)
265
266 let is_dir fname =
267   try
268     (Unix.stat fname).Unix.st_kind = Unix.S_DIR
269   with Unix.Unix_error _ -> false
270
271 let writable_dir path =
272   try
273     let file = path ^ "/prova_matita" in
274     let oc = open_out file in
275     close_out oc;
276     Sys.remove file;
277     true
278   with Sys_error _ -> false
279
280
281 let is_regular fname =
282   try
283     (Unix.stat fname).Unix.st_kind = Unix.S_REG
284   with Unix.Unix_error _ -> false
285
286 let is_executable fname =
287   try
288     let stat = (Unix.stat fname) in
289     stat.Unix.st_kind = Unix.S_REG &&
290     (stat.Unix.st_perm land 0o001 > 0)
291   with Unix.Unix_error _ -> false
292
293 let chmod mode filename =
294    Unix.chmod filename mode
295
296 let mkdir path =
297   let components = split ~sep:'/' path in
298   let rec aux where = function
299     | [] -> ()
300     | piece::tl -> 
301         let path =
302           if where = "" then piece else where ^ "/" ^ piece in
303         (try
304           Unix.mkdir path 0o755; chmod 0o2775 path 
305         with 
306         | Unix.Unix_error (Unix.EEXIST,_,_) -> ()
307         | Unix.Unix_error (e,_,_) -> 
308             raise 
309               (Failure 
310                 ("Unix.mkdir " ^ path ^ " 0o2775 :" ^ (Unix.error_message e))));
311         aux path tl
312   in
313   let where = if path.[0] = '/' then "/" else "" in
314   aux where components
315
316 (** {2 Filesystem} *)
317
318 let input_file fname =
319   let size = (Unix.stat fname).Unix.st_size in
320   let buf = Buffer.create size in
321   let ic = open_in fname in
322   Buffer.add_channel buf ic size;
323   close_in ic;
324   Buffer.contents buf
325
326 let input_all ic =
327   let size = 10240 in
328   let buf = Buffer.create size in
329   let s = String.create size in
330   (try
331     while true do
332       let bytes = input ic s 0 size in
333       if bytes = 0 then raise End_of_file
334       else Buffer.add_substring buf s 0 bytes
335     done
336   with End_of_file -> ());
337   Buffer.contents buf
338
339 let output_file ~filename ~text = 
340   let oc = open_out filename in
341   output_string oc text;
342   close_out oc;
343   chmod 0o664 filename
344
345 let blank_split s =
346   let len = String.length s in
347   let buf = Buffer.create 0 in
348   let rec aux acc i =
349     if i >= len
350     then begin
351       if Buffer.length buf > 0
352       then List.rev (Buffer.contents buf :: acc)
353       else List.rev acc
354     end else begin
355       if is_blank s.[i] then
356         if Buffer.length buf > 0 then begin
357           let s = Buffer.contents buf in
358           Buffer.clear buf;
359           aux (s :: acc) (i + 1)
360         end else
361           aux acc (i + 1)
362       else begin
363         Buffer.add_char buf s.[i];
364         aux acc (i + 1)
365       end
366     end
367   in
368   aux [] 0
369
370   (* Rules: * "~name" -> home dir of "name"
371    * "~" -> value of $HOME if defined, home dir of the current user otherwise *)
372 let tilde_expand s =
373   let get_home login = (Unix.getpwnam login).Unix.pw_dir in
374   let expand_one s =
375     let len = String.length s in
376     if len > 0 && s.[0] = '~' then begin
377       let login_len = ref 1 in
378       while !login_len < len && is_alphanum (s.[!login_len]) do
379         incr login_len
380       done;
381       let login = String.sub s 1 (!login_len - 1) in
382       try
383         let home =
384           if login = "" then
385             try Sys.getenv "HOME" with Not_found -> get_home (Unix.getlogin ())
386           else
387             get_home login
388         in
389         home ^ String.sub s !login_len (len - !login_len)
390       with Not_found | Invalid_argument _ -> s
391     end else
392       s
393   in
394   String.concat " " (List.map expand_one (blank_split s))
395   
396 let find ?(test = fun _ -> true) path = 
397   let rec aux acc todo = 
398     match todo with
399     | [] -> acc
400     | path :: tl ->
401         try
402           let handle = Unix.opendir path in
403           let dirs = ref [] in
404           let matching_files = ref [] in 
405           (try 
406             while true do 
407               match Unix.readdir handle with
408               | "." | ".." -> ()
409               | entry ->
410                   let qentry = path ^ "/" ^ entry in
411                   (try
412                     if is_dir qentry then
413                       dirs := qentry :: !dirs
414                     else if test qentry then
415                       matching_files := qentry :: !matching_files;
416                   with Unix.Unix_error _ -> ())
417             done
418           with End_of_file -> Unix.closedir handle);
419           aux (!matching_files @ acc) (!dirs @ tl)
420         with Unix.Unix_error _ -> aux acc tl
421   in
422   aux [] [path]
423
424 let safe_remove fname = if Sys.file_exists fname then Sys.remove fname
425
426 let is_dir_empty d =
427  try
428   let od = Unix.opendir d in
429   let rec aux () =
430    let name = Unix.readdir od in
431    if name <> "." && name <> ".." then false else aux () in
432   let res = try aux () with End_of_file -> true in
433    Unix.closedir od;
434    res
435  with
436   Unix.Unix_error _ -> true (* raised by Unix.opendir, we hope :-) *)
437
438 let safe_rmdir d = try Unix.rmdir d with Unix.Unix_error _ -> ()
439
440 let rec rmdir_descend d = 
441   if is_dir_empty d then
442     begin
443       safe_rmdir d;
444       rmdir_descend (Filename.dirname d)
445     end
446
447
448 (** {2 Exception handling} *)
449
450 let finally at_end f arg =
451   let res =
452     try f arg
453     with exn -> at_end (); raise exn
454   in
455   at_end ();
456   res
457
458 (** {2 Localized exceptions } *)
459
460 exception Localized of Stdpp.location * exn
461
462 let loc_of_floc floc = Stdpp.first_pos floc, Stdpp.last_pos floc;;
463
464 let floc_of_loc (loc_begin, loc_end) =
465  Stdpp.make_loc (loc_begin, loc_end)
466
467 let dummy_floc = floc_of_loc (0, 0)
468
469 let raise_localized_exception ~offset floc exn =
470  let x, y = loc_of_floc floc in
471  let x = offset + x in
472  let y = offset + y in
473  let floc = floc_of_loc (x,y) in
474   raise (Localized (floc, exn))
475
476 let estimate_size x = 
477   4 * (String.length (Marshal.to_string x [])) / 1024
478
479 let normalize_path s = 
480   let s = Str.global_replace (Str.regexp "//") "/" s in
481   let l = Str.split (Str.regexp "/") s in
482   let rec aux acc = function
483     | [] -> acc
484     | he::"."::tl -> aux acc (he::tl)
485     | he::".."::tl when he <> ".." -> aux [] (acc @ tl)
486     | he::tl -> aux (acc@[he]) tl
487   in
488   (if Str.string_match (Str.regexp "^/") s 0 then "/" else "") ^
489   String.concat "/" (aux [] l)
490   ^ (if Str.string_match (Str.regexp "/$") s 0 then "/" else "")
491 ;;
492
493 let find_in paths path =
494    let rec aux = function
495    | [] -> raise (Failure "find_in")
496    | p :: tl ->
497       let path = normalize_path (p ^ "/" ^ path) in
498        try
499          if (Unix.stat path).Unix.st_kind = Unix.S_REG then path
500          else aux tl
501        with Unix.Unix_error _ -> 
502                aux tl
503    in
504    try
505      aux paths
506    with Unix.Unix_error _ | Failure _ -> 
507      raise 
508        (Failure "find_in")
509 ;;
510
511 let is_prefix_of_aux d1 d2 = 
512   let len1 = String.length d1 in
513   let len2 = String.length d2 in
514   if len2 < len1 then 
515     false, len1, len2
516   else
517     let pref = String.sub d2 0 len1 in
518     pref = d1 && (len1 = len2 || d1.[len1-1] = '/' || d2.[len1] = '/'), len1, len2
519
520 let is_prefix_of d1 d2 =
521   let b,_,_ = is_prefix_of_aux d1 d2 in b
522 ;;
523
524 let chop_prefix prefix s =
525   let b,lp,ls = is_prefix_of_aux prefix s in
526   if b then
527     String.sub s lp (ls - lp)
528   else 
529     s
530 ;;
531
532 let touch s =
533   try close_out(open_out s) with Sys_error _ -> ()
534 ;;
535
536 let rec mk_list x = function
537   | 0 -> []
538   | n -> x :: mk_list x (n-1)
539 ;;
540
541 let list_seq start stop =
542   if start > stop then [] else
543   let rec aux pos =
544     if pos = stop then []
545     else pos :: (aux (pos+1))
546   in
547     aux start
548 ;;
549
550 let rec list_skip n l =
551   match n,l with
552   | 0,_ -> l
553   | n,_::l -> list_skip (n-1) l
554   | _, [] -> assert false
555 ;;
556