Release coccinelle-0.2.3rc1
[bpt/coccinelle.git] / commons / common.ml
1 (* Yoann Padioleau
2 *
3 * Copyright (C) 2010 INRIA, University of Copenhagen DIKU
4 * Copyright (C) 1998-2009 Yoann Padioleau
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public License
8 * version 2.1 as published by the Free Software Foundation, with the
9 * special exception on linking described in file license.txt.
10 *
11 * This library is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the file
14 * license.txt for more details.
15 *)
16
17 (*****************************************************************************)
18 (* Notes *)
19 (*****************************************************************************)
20
21
22
23 (* ---------------------------------------------------------------------- *)
24 (* Maybe could split common.ml and use include tricks as in ofullcommon.ml or
25 * Jane Street core lib. But then harder to bundle simple scripts like my
26 * make_full_linux_kernel.ml because would then need to pass all the files
27 * either to ocamlc or either to some #load. Also as the code of many
28 * functions depends on other functions from this common, it would
29 * be tedious to add those dependencies. Here simpler (have just the
30 * pb of the Prelude, but it's a small problem).
31 *
32 * pixel means code from Pascal Rigaux
33 * julia means code from Julia Lawall
34 *)
35 (* ---------------------------------------------------------------------- *)
36
37 (*****************************************************************************)
38 (* We use *)
39 (*****************************************************************************)
40 (*
41 * modules:
42 * - Pervasives, of course
43 * - List
44 * - Str
45 * - Hashtbl
46 * - Format
47 * - Buffer
48 * - Unix and Sys
49 * - Arg
50 *
51 * functions:
52 * - =, <=, max min, abs, ...
53 * - List.rev, List.mem, List.partition,
54 * - List.fold*, List.concat, ...
55 * - Str.global_replace
56 * - Filename.is_relative
57 * - String.uppercase, String.lowercase
58 *
59 *
60 * The Format library allows to hide passing an indent_level variable.
61 * You use as usual the print_string function except that there is
62 * this automatic indent_level variable handled for you (and maybe
63 * more services). src: julia in coccinelle unparse_cocci.
64 *
65 * Extra packages
66 * - ocamlbdb
67 * - ocamlgtk, and gtksourceview
68 * - ocamlgl
69 * - ocamlpython
70 * - ocamlagrep
71 * - ocamlfuse
72 * - ocamlmpi
73 * - ocamlcalendar
74 *
75 * - pcre
76 * - sdl
77 *
78 * Many functions in this file were inspired by Haskell or Lisp librairies.
79 *)
80
81 (*****************************************************************************)
82 (* Prelude *)
83 (*****************************************************************************)
84
85 (* The following functions should be in their respective sections but
86 * because some functions in some sections use functions in other
87 * sections, and because I don't want to take care of the order of
88 * those sections, of those dependencies, I put the functions causing
89 * dependency problem here. C is better than caml on this with the
90 * ability to declare prototype, enabling some form of forward
91 * reference. *)
92
93 let (+>) o f = f o
94 let (++) = (@)
95
96 exception Timeout
97 exception UnixExit of int
98
99 let rec (do_n: int -> (unit -> unit) -> unit) = fun i f ->
100 if i = 0 then () else (f(); do_n (i-1) f)
101 let rec (foldn: ('a -> int -> 'a) -> 'a -> int -> 'a) = fun f acc i ->
102 if i = 0 then acc else foldn f (f acc i) (i-1)
103
104 let sum_int = List.fold_left (+) 0
105
106 (* could really call it 'for' :) *)
107 let fold_left_with_index f acc =
108 let rec fold_lwi_aux acc n = function
109 | [] -> acc
110 | x::xs -> fold_lwi_aux (f acc x n) (n+1) xs
111 in fold_lwi_aux acc 0
112
113
114 let rec drop n xs =
115 match (n,xs) with
116 | (0,_) -> xs
117 | (_,[]) -> failwith "drop: not enough"
118 | (n,x::xs) -> drop (n-1) xs
119
120 let rec enum_orig x n = if x = n then [n] else x::enum_orig (x+1) n
121
122 let enum x n =
123 if not(x <= n)
124 then failwith (Printf.sprintf "bad values in enum, expect %d <= %d" x n);
125 let rec enum_aux acc x n =
126 if x = n then n::acc else enum_aux (x::acc) (x+1) n
127 in
128 List.rev (enum_aux [] x n)
129
130 let rec take n xs =
131 match (n,xs) with
132 | (0,_) -> []
133 | (_,[]) -> failwith "take: not enough"
134 | (n,x::xs) -> x::take (n-1) xs
135
136
137 let last_n n l = List.rev (take n (List.rev l))
138 let last l = List.hd (last_n 1 l)
139
140
141 let (list_of_string: string -> char list) = function
142 "" -> []
143 | s -> (enum 0 ((String.length s) - 1) +> List.map (String.get s))
144
145 let (lines: string -> string list) = fun s ->
146 let rec lines_aux = function
147 | [] -> []
148 | [x] -> if x = "" then [] else [x]
149 | x::xs ->
150 x::lines_aux xs
151 in
152 Str.split_delim (Str.regexp "\n") s +> lines_aux
153
154
155 let push2 v l =
156 l := v :: !l
157
158 let null xs = match xs with [] -> true | _ -> false
159
160
161
162
163 let debugger = ref false
164
165 let unwind_protect f cleanup =
166 if !debugger then f() else
167 try f ()
168 with e -> begin cleanup e; raise e end
169
170 let finalize f cleanup =
171 if !debugger then f() else
172 try
173 let res = f () in
174 cleanup ();
175 res
176 with e ->
177 cleanup ();
178 raise e
179
180 let command2 s = ignore(Sys.command s)
181
182
183 let (matched: int -> string -> string) = fun i s ->
184 Str.matched_group i s
185
186 let matched1 = fun s -> matched 1 s
187 let matched2 = fun s -> (matched 1 s, matched 2 s)
188 let matched3 = fun s -> (matched 1 s, matched 2 s, matched 3 s)
189 let matched4 = fun s -> (matched 1 s, matched 2 s, matched 3 s, matched 4 s)
190 let matched5 = fun s -> (matched 1 s, matched 2 s, matched 3 s, matched 4 s, matched 5 s)
191 let matched6 = fun s -> (matched 1 s, matched 2 s, matched 3 s, matched 4 s, matched 5 s, matched 6 s)
192 let matched7 = fun s -> (matched 1 s, matched 2 s, matched 3 s, matched 4 s, matched 5 s, matched 6 s, matched 7 s)
193
194 let (with_open_stringbuf: (((string -> unit) * Buffer.t) -> unit) -> string) =
195 fun f ->
196 let buf = Buffer.create 1000 in
197 let pr s = Buffer.add_string buf (s ^ "\n") in
198 f (pr, buf);
199 Buffer.contents buf
200
201
202 let foldl1 p = function x::xs -> List.fold_left p x xs | _ -> failwith "foldl1"
203
204 (*****************************************************************************)
205 (* Debugging/logging *)
206 (*****************************************************************************)
207
208 (* I used this in coccinelle where the huge logging of stuff ask for
209 * a more organized solution that use more visual indentation hints.
210 *
211 * todo? could maybe use log4j instead ? or use Format module more
212 * consistently ?
213 *)
214
215 let _tab_level_print = ref 0
216 let _tab_indent = 5
217
218
219 let _prefix_pr = ref ""
220
221 let indent_do f =
222 _tab_level_print := !_tab_level_print + _tab_indent;
223 finalize f
224 (fun () -> _tab_level_print := !_tab_level_print - _tab_indent;)
225
226
227 let pr s =
228 print_string !_prefix_pr;
229 do_n !_tab_level_print (fun () -> print_string " ");
230 print_string s;
231 print_string "\n";
232 flush stdout
233
234 let pr_no_nl s =
235 print_string !_prefix_pr;
236 do_n !_tab_level_print (fun () -> print_string " ");
237 print_string s;
238 flush stdout
239
240
241
242
243
244
245 let _chan_pr2 = ref (None: out_channel option)
246
247 let out_chan_pr2 ?(newline=true) s =
248 match !_chan_pr2 with
249 | None -> ()
250 | Some chan ->
251 output_string chan (s ^ (if newline then "\n" else ""));
252 flush chan
253
254 let print_to_stderr = ref true
255
256 let pr2 s =
257 if !print_to_stderr
258 then
259 begin
260 prerr_string !_prefix_pr;
261 do_n !_tab_level_print (fun () -> prerr_string " ");
262 prerr_string s;
263 prerr_string "\n";
264 flush stderr;
265 out_chan_pr2 s;
266 ()
267 end
268
269 let pr2_no_nl s =
270 if !print_to_stderr
271 then
272 begin
273 prerr_string !_prefix_pr;
274 do_n !_tab_level_print (fun () -> prerr_string " ");
275 prerr_string s;
276 flush stderr;
277 out_chan_pr2 ~newline:false s;
278 ()
279 end
280
281
282 let pr_xxxxxxxxxxxxxxxxx () =
283 pr "-----------------------------------------------------------------------"
284
285 let pr2_xxxxxxxxxxxxxxxxx () =
286 pr2 "-----------------------------------------------------------------------"
287
288
289 let reset_pr_indent () =
290 _tab_level_print := 0
291
292 (* old:
293 * let pr s = (print_string s; print_string "\n"; flush stdout)
294 * let pr2 s = (prerr_string s; prerr_string "\n"; flush stderr)
295 *)
296
297 (* ---------------------------------------------------------------------- *)
298
299 (* I can not use the _xxx ref tech that I use for common_extra.ml here because
300 * ocaml don't like the polymorphism of Dumper mixed with refs.
301 *
302 * let (_dump_func : ('a -> string) ref) = ref
303 * (fun x -> failwith "no dump yet, have you included common_extra.cmo?")
304 * let (dump : 'a -> string) = fun x ->
305 * !_dump_func x
306 *
307 * So I have included directly dumper.ml in common.ml. It's more practical
308 * when want to give script that use my common.ml, I just have to give
309 * this file.
310 *)
311
312 (* start of dumper.ml *)
313
314 (* Dump an OCaml value into a printable string.
315 * By Richard W.M. Jones (rich@annexia.org).
316 * dumper.ml 1.2 2005/02/06 12:38:21 rich Exp
317 *)
318 open Printf
319 open Obj
320
321 let rec dump r =
322 if is_int r then
323 string_of_int (magic r : int)
324 else ( (* Block. *)
325 let rec get_fields acc = function
326 | 0 -> acc
327 | n -> let n = n-1 in get_fields (field r n :: acc) n
328 in
329 let rec is_list r =
330 if is_int r then (
331 if (magic r : int) = 0 then true (* [] *)
332 else false
333 ) else (
334 let s = size r and t = tag r in
335 if t = 0 && s = 2 then is_list (field r 1) (* h :: t *)
336 else false
337 )
338 in
339 let rec get_list r =
340 if is_int r then []
341 else let h = field r 0 and t = get_list (field r 1) in h :: t
342 in
343 let opaque name =
344 (* XXX In future, print the address of value 'r'. Not possible in
345 * pure OCaml at the moment.
346 *)
347 "<" ^ name ^ ">"
348 in
349
350 let s = size r and t = tag r in
351
352 (* From the tag, determine the type of block. *)
353 if is_list r then ( (* List. *)
354 let fields = get_list r in
355 "[" ^ String.concat "; " (List.map dump fields) ^ "]"
356 )
357 else if t = 0 then ( (* Tuple, array, record. *)
358 let fields = get_fields [] s in
359 "(" ^ String.concat ", " (List.map dump fields) ^ ")"
360 )
361
362 (* Note that [lazy_tag .. forward_tag] are < no_scan_tag. Not
363 * clear if very large constructed values could have the same
364 * tag. XXX *)
365 else if t = lazy_tag then opaque "lazy"
366 else if t = closure_tag then opaque "closure"
367 else if t = object_tag then ( (* Object. *)
368 let fields = get_fields [] s in
369 let clasz, id, slots =
370 match fields with h::h'::t -> h, h', t | _ -> assert false in
371 (* No information on decoding the class (first field). So just print
372 * out the ID and the slots.
373 *)
374 "Object #" ^ dump id ^
375 " (" ^ String.concat ", " (List.map dump slots) ^ ")"
376 )
377 else if t = infix_tag then opaque "infix"
378 else if t = forward_tag then opaque "forward"
379
380 else if t < no_scan_tag then ( (* Constructed value. *)
381 let fields = get_fields [] s in
382 "Tag" ^ string_of_int t ^
383 " (" ^ String.concat ", " (List.map dump fields) ^ ")"
384 )
385 else if t = string_tag then (
386 "\"" ^ String.escaped (magic r : string) ^ "\""
387 )
388 else if t = double_tag then (
389 string_of_float (magic r : float)
390 )
391 else if t = abstract_tag then opaque "abstract"
392 else if t = custom_tag then opaque "custom"
393 else if t = final_tag then opaque "final"
394 else failwith ("dump: impossible tag (" ^ string_of_int t ^ ")")
395 )
396
397 let dump v = dump (repr v)
398
399 (* end of dumper.ml *)
400
401 (*
402 let (dump : 'a -> string) = fun x ->
403 Dumper.dump x
404 *)
405
406
407 (* ---------------------------------------------------------------------- *)
408 let pr2_gen x = pr2 (dump x)
409
410
411
412 (* ---------------------------------------------------------------------- *)
413
414
415 let _already_printed = Hashtbl.create 101
416 let disable_pr2_once = ref false
417
418 let xxx_once f s =
419 if !disable_pr2_once then pr2 s
420 else
421 if not (Hashtbl.mem _already_printed s)
422 then begin
423 Hashtbl.add _already_printed s true;
424 f ("(ONCE) " ^ s);
425 end
426
427 let pr2_once s = xxx_once pr2 s
428
429 (* ---------------------------------------------------------------------- *)
430 let mk_pr2_wrappers aref =
431 let fpr2 s =
432 if !aref
433 then pr2 s
434 else
435 (* just to the log file *)
436 out_chan_pr2 s
437 in
438 let fpr2_once s =
439 if !aref
440 then pr2_once s
441 else
442 xxx_once out_chan_pr2 s
443 in
444 fpr2, fpr2_once
445
446 (* ---------------------------------------------------------------------- *)
447 (* could also be in File section *)
448
449 let redirect_stdout file f =
450 begin
451 let chan = open_out file in
452 let descr = Unix.descr_of_out_channel chan in
453
454 let saveout = Unix.dup Unix.stdout in
455 Unix.dup2 descr Unix.stdout;
456 flush stdout;
457 let res = f() in
458 flush stdout;
459 Unix.dup2 saveout Unix.stdout;
460 close_out chan;
461 res
462 end
463
464 let redirect_stdout_opt optfile f =
465 match optfile with
466 | None -> f()
467 | Some outfile -> redirect_stdout outfile f
468
469 let redirect_stdout_stderr file f =
470 begin
471 let chan = open_out file in
472 let descr = Unix.descr_of_out_channel chan in
473
474 let saveout = Unix.dup Unix.stdout in
475 let saveerr = Unix.dup Unix.stderr in
476 Unix.dup2 descr Unix.stdout;
477 Unix.dup2 descr Unix.stderr;
478 flush stdout; flush stderr;
479 f();
480 flush stdout; flush stderr;
481 Unix.dup2 saveout Unix.stdout;
482 Unix.dup2 saveerr Unix.stderr;
483 close_out chan;
484 end
485
486 let redirect_stdin file f =
487 begin
488 let chan = open_in file in
489 let descr = Unix.descr_of_in_channel chan in
490
491 let savein = Unix.dup Unix.stdin in
492 Unix.dup2 descr Unix.stdin;
493 f();
494 Unix.dup2 savein Unix.stdin;
495 close_in chan;
496 end
497
498 let redirect_stdin_opt optfile f =
499 match optfile with
500 | None -> f()
501 | Some infile -> redirect_stdin infile f
502
503
504 (* cf end
505 let with_pr2_to_string f =
506 *)
507
508
509 (* ---------------------------------------------------------------------- *)
510
511 include Printf
512
513 (* cf common.mli, fprintf, printf, eprintf, sprintf.
514 * also what is this ?
515 * val bprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a
516 * val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b
517 *)
518
519 (* ex of printf:
520 * printf "%02d" i
521 * for padding
522 *)
523
524 let spf = sprintf
525
526 (* ---------------------------------------------------------------------- *)
527
528 let _chan = ref stderr
529 let start_log_file () =
530 let filename = (spf "/tmp/debugml%d:%d" (Unix.getuid()) (Unix.getpid())) in
531 pr2 (spf "now using %s for logging" filename);
532 _chan := open_out filename
533
534
535 let dolog s = output_string !_chan (s ^ "\n"); flush !_chan
536
537 let verbose_level = ref 1
538 let log s = if !verbose_level >= 1 then dolog s
539 let log2 s = if !verbose_level >= 2 then dolog s
540 let log3 s = if !verbose_level >= 3 then dolog s
541 let log4 s = if !verbose_level >= 4 then dolog s
542
543 let if_log f = if !verbose_level >= 1 then f()
544 let if_log2 f = if !verbose_level >= 2 then f()
545 let if_log3 f = if !verbose_level >= 3 then f()
546 let if_log4 f = if !verbose_level >= 4 then f()
547
548 (* ---------------------------------------------------------------------- *)
549
550 let pause () = (pr2 "pause: type return"; ignore(read_line ()))
551
552 (* src: from getopt from frish *)
553 let bip () = Printf.printf "\007"; flush stdout
554 let wait () = Unix.sleep 1
555
556 (* was used by fix_caml *)
557 let _trace_var = ref 0
558 let add_var() = incr _trace_var
559 let dec_var() = decr _trace_var
560 let get_var() = !_trace_var
561
562 let (print_n: int -> string -> unit) = fun i s ->
563 do_n i (fun () -> print_string s)
564 let (printerr_n: int -> string -> unit) = fun i s ->
565 do_n i (fun () -> prerr_string s)
566
567 let _debug = ref true
568 let debugon () = _debug := true
569 let debugoff () = _debug := false
570 let debug f = if !_debug then f () else ()
571
572
573
574 (* now in prelude:
575 * let debugger = ref false
576 *)
577
578
579 (*****************************************************************************)
580 (* Profiling *)
581 (*****************************************************************************)
582
583 let get_mem() =
584 command2("grep VmData /proc/" ^ string_of_int (Unix.getpid()) ^ "/status")
585
586 let memory_stat () =
587 let stat = Gc.stat() in
588 let conv_mo x = x * 4 / 1000000 in
589 Printf.sprintf "maximal = %d Mo\n" (conv_mo stat.Gc.top_heap_words) ^
590 Printf.sprintf "current = %d Mo\n" (conv_mo stat.Gc.heap_words) ^
591 Printf.sprintf "lives = %d Mo\n" (conv_mo stat.Gc.live_words)
592 (* Printf.printf "fragments = %d Mo\n" (conv_mo stat.Gc.fragments); *)
593
594 let timenow () =
595 "sys:" ^ (string_of_float (Sys.time ())) ^ " seconds" ^
596 ":real:" ^
597 (let tm = Unix.time () +> Unix.gmtime in
598 tm.Unix.tm_min +> string_of_int ^ " min:" ^
599 tm.Unix.tm_sec +> string_of_int ^ ".00 seconds")
600
601 let _count1 = ref 0
602 let _count2 = ref 0
603 let _count3 = ref 0
604 let _count4 = ref 0
605 let _count5 = ref 0
606
607 let count1 () = incr _count1
608 let count2 () = incr _count2
609 let count3 () = incr _count3
610 let count4 () = incr _count4
611 let count5 () = incr _count5
612
613 let profile_diagnostic_basic () =
614 Printf.sprintf
615 "count1 = %d\ncount2 = %d\ncount3 = %d\ncount4 = %d\ncount5 = %d\n"
616 !_count1 !_count2 !_count3 !_count4 !_count5
617
618
619
620 let time_func f =
621 (* let _ = Timing () in *)
622 let x = f () in
623 (* let _ = Timing () in *)
624 x
625
626 (* ---------------------------------------------------------------------- *)
627
628 type prof = PALL | PNONE | PSOME of string list
629 let profile = ref PNONE
630 let show_trace_profile = ref false
631
632 let check_profile category =
633 match !profile with
634 PALL -> true
635 | PNONE -> false
636 | PSOME l -> List.mem category l
637
638 let _profile_table = ref (Hashtbl.create 100)
639
640 let adjust_profile_entry category difftime =
641 let (xtime, xcount) =
642 (try Hashtbl.find !_profile_table category
643 with Not_found ->
644 let xtime = ref 0.0 in
645 let xcount = ref 0 in
646 Hashtbl.add !_profile_table category (xtime, xcount);
647 (xtime, xcount)
648 ) in
649 xtime := !xtime +. difftime;
650 xcount := !xcount + 1;
651 ()
652
653 let profile_start category = failwith "todo"
654 let profile_end category = failwith "todo"
655
656
657 (* subtil: don't forget to give all argumens to f, otherwise partial app
658 * and will profile nothing.
659 *
660 * todo: try also detect when complexity augment each time, so can
661 * detect the situation for a function gets worse and worse ?
662 *)
663 let profile_code category f =
664 if not (check_profile category)
665 then f()
666 else begin
667 if !show_trace_profile then pr2 (spf "p: %s" category);
668 let t = Unix.gettimeofday () in
669 let res, prefix =
670 try Some (f ()), ""
671 with Timeout -> None, "*"
672 in
673 let category = prefix ^ category in (* add a '*' to indicate timeout func *)
674 let t' = Unix.gettimeofday () in
675
676 adjust_profile_entry category (t' -. t);
677 (match res with
678 | Some res -> res
679 | None -> raise Timeout
680 );
681 end
682
683
684 let _is_in_exclusif = ref (None: string option)
685
686 let profile_code_exclusif category f =
687 if not (check_profile category)
688 then f()
689 else begin
690
691 match !_is_in_exclusif with
692 | Some s ->
693 failwith (spf "profile_code_exclusif: %s but already in %s " category s);
694 | None ->
695 _is_in_exclusif := (Some category);
696 finalize
697 (fun () ->
698 profile_code category f
699 )
700 (fun () ->
701 _is_in_exclusif := None
702 )
703
704 end
705
706 let profile_code_inside_exclusif_ok category f =
707 failwith "Todo"
708
709
710 (* todo: also put % ? also add % to see if coherent numbers *)
711 let profile_diagnostic () =
712 if !profile = PNONE then "" else
713 let xs =
714 Hashtbl.fold (fun k v acc -> (k,v)::acc) !_profile_table []
715 +> List.sort (fun (k1, (t1,n1)) (k2, (t2,n2)) -> compare t2 t1)
716 in
717 with_open_stringbuf (fun (pr,_) ->
718 pr "---------------------";
719 pr "profiling result";
720 pr "---------------------";
721 xs +> List.iter (fun (k, (t,n)) ->
722 pr (sprintf "%-40s : %10.3f sec %10d count" k !t !n)
723 )
724 )
725
726
727
728 let report_if_take_time timethreshold s f =
729 let t = Unix.gettimeofday () in
730 let res = f () in
731 let t' = Unix.gettimeofday () in
732 if (t' -. t > float_of_int timethreshold)
733 then pr2 (sprintf "Note: processing took %7.1fs: %s" (t' -. t) s);
734 res
735
736 let profile_code2 category f =
737 profile_code category (fun () ->
738 if !profile = PALL
739 then pr2 ("starting: " ^ category);
740 let t = Unix.gettimeofday () in
741 let res = f () in
742 let t' = Unix.gettimeofday () in
743 if !profile = PALL
744 then pr2 (spf "ending: %s, %fs" category (t' -. t));
745 res
746 )
747
748
749 (*****************************************************************************)
750 (* Test *)
751 (*****************************************************************************)
752 let example b = assert b
753
754 let _ex1 = example (enum 1 4 = [1;2;3;4])
755
756 let assert_equal a b =
757 if not (a = b)
758 then failwith ("assert_equal: those 2 values are not equal:\n\t" ^
759 (dump a) ^ "\n\t" ^ (dump b) ^ "\n")
760
761 let (example2: string -> bool -> unit) = fun s b ->
762 try assert b with x -> failwith s
763
764 (*-------------------------------------------------------------------*)
765 let _list_bool = ref []
766
767 let (example3: string -> bool -> unit) = fun s b ->
768 _list_bool := (s,b)::(!_list_bool)
769
770 (* could introduce a fun () otherwise the calculus is made at compile time
771 * and this can be long. This would require to redefine test_all.
772 * let (example3: string -> (unit -> bool) -> unit) = fun s func ->
773 * _list_bool := (s,func):: (!_list_bool)
774 *
775 * I would like to do as a func that take 2 terms, and make an = over it
776 * avoid to add this ugly fun (), but pb of type, cant do that :(
777 *)
778
779
780 let (test_all: unit -> unit) = fun () ->
781 List.iter (fun (s, b) ->
782 Printf.printf "%s: %s\n" s (if b then "passed" else "failed")
783 ) !_list_bool
784
785 let (test: string -> unit) = fun s ->
786 Printf.printf "%s: %s\n" s
787 (if (List.assoc s (!_list_bool)) then "passed" else "failed")
788
789 let _ex = example3 "++" ([1;2]++[3;4;5] = [1;2;3;4;5])
790
791 (*-------------------------------------------------------------------*)
792 (* Regression testing *)
793 (*-------------------------------------------------------------------*)
794
795 (* cf end of file. It uses too many other common functions so I
796 * have put the code at the end of this file.
797 *)
798
799
800
801 (* todo? take code from julien signoles in calendar-2.0.2/tests *)
802 (*
803
804 (* Generic functions used in the tests. *)
805
806 val reset : unit -> unit
807 val nb_ok : unit -> int
808 val nb_bug : unit -> int
809 val test : bool -> string -> unit
810 val test_exn : 'a Lazy.t -> string -> unit
811
812
813 let ok_ref = ref 0
814 let ok () = incr ok_ref
815 let nb_ok () = !ok_ref
816
817 let bug_ref = ref 0
818 let bug () = incr bug_ref
819 let nb_bug () = !bug_ref
820
821 let reset () =
822 ok_ref := 0;
823 bug_ref := 0
824
825 let test x s =
826 if x then ok () else begin Printf.printf "%s\n" s; bug () end;;
827
828 let test_exn x s =
829 try
830 ignore (Lazy.force x);
831 Printf.printf "%s\n" s;
832 bug ()
833 with _ ->
834 ok ();;
835 *)
836
837
838 (*****************************************************************************)
839 (* Quickcheck like (sfl) *)
840 (*****************************************************************************)
841
842 (* Better than quickcheck, cos cant do a test_all_prop in haskell cos
843 * prop were functions, whereas here we have not prop_Unix x = ... but
844 * laws "unit" ...
845 *
846 * How to do without overloading ? objet ? can pass a generator as a
847 * parameter, mais lourd, prefer automatic inferring of the
848 * generator? But at the same time quickcheck does not do better cos
849 * we must explictly type the property. So between a
850 * prop_unit:: [Int] -> [Int] -> bool ...
851 * prop_unit x = reverse [x] == [x]
852 * and
853 * let _ = laws "unit" (fun x -> reverse [x] = [x]) (listg intg)
854 * there is no real differences.
855 *
856 * Yes I define typeg generator but quickcheck too, he must define
857 * class instance. I emulate the context Gen a => Gen [a] by making
858 * listg take as a param a type generator. Moreover I have not the pb of
859 * monad. I can do random independently, so my code is more simple
860 * I think than the haskell code of quickcheck.
861 *
862 * update: apparently Jane Street have copied some of my code for their
863 * Ounit_util.ml and quichcheck.ml in their Core library :)
864 *)
865
866 (*---------------------------------------------------------------------------*)
867 (* generators *)
868 (*---------------------------------------------------------------------------*)
869 type 'a gen = unit -> 'a
870
871 let (ig: int gen) = fun () ->
872 Random.int 10
873 let (lg: ('a gen) -> ('a list) gen) = fun gen () ->
874 foldn (fun acc i -> (gen ())::acc) [] (Random.int 10)
875 let (pg: ('a gen) -> ('b gen) -> ('a * 'b) gen) = fun gen1 gen2 () ->
876 (gen1 (), gen2 ())
877 let polyg = ig
878 let (ng: (string gen)) = fun () ->
879 "a" ^ (string_of_int (ig ()))
880
881 let (oneofl: ('a list) -> 'a gen) = fun xs () ->
882 List.nth xs (Random.int (List.length xs))
883 (* let oneofl l = oneof (List.map always l) *)
884
885 let (oneof: (('a gen) list) -> 'a gen) = fun xs ->
886 List.nth xs (Random.int (List.length xs))
887
888 let (always: 'a -> 'a gen) = fun e () -> e
889
890 let (frequency: ((int * ('a gen)) list) -> 'a gen) = fun xs ->
891 let sums = sum_int (List.map fst xs) in
892 let i = Random.int sums in
893 let rec freq_aux acc = function
894 | (x,g)::xs -> if i < acc+x then g else freq_aux (acc+x) xs
895 | _ -> failwith "frequency"
896 in
897 freq_aux 0 xs
898 let frequencyl l = frequency (List.map (fun (i,e) -> (i,always e)) l)
899
900 (*
901 let b = oneof [always true; always false] ()
902 let b = frequency [3, always true; 2, always false] ()
903 *)
904
905 (* cant do this:
906 * let rec (lg: ('a gen) -> ('a list) gen) = fun gen -> oneofl [[]; lg gen ()]
907 * nor
908 * let rec (lg: ('a gen) -> ('a list) gen) = fun gen -> oneof [always []; lg gen]
909 *
910 * because caml is not as lazy as haskell :( fix the pb by introducing a size
911 * limit. take the bounds/size as parameter. morover this is needed for
912 * more complex type.
913 *
914 * how make a bintreeg ?? we need recursion
915 *
916 * let rec (bintreeg: ('a gen) -> ('a bintree) gen) = fun gen () ->
917 * let rec aux n =
918 * if n = 0 then (Leaf (gen ()))
919 * else frequencyl [1, Leaf (gen ()); 4, Branch ((aux (n / 2)), aux (n / 2))]
920 * ()
921 * in aux 20
922 *
923 *)
924
925
926 (*---------------------------------------------------------------------------*)
927 (* property *)
928 (*---------------------------------------------------------------------------*)
929
930 (* todo: a test_all_laws, better syntax (done already a little with ig in
931 * place of intg. En cas d'erreur, print the arg that not respect
932 *
933 * todo: with monitoring, as in haskell, laws = laws2, no need for 2 func,
934 * but hard i found
935 *
936 * todo classify, collect, forall
937 *)
938
939
940 (* return None when good, and Just the_problematic_case when bad *)
941 let (laws: string -> ('a -> bool) -> ('a gen) -> 'a option) = fun s func gen ->
942 let res = foldn (fun acc i -> let n = gen() in (n, func n)::acc) [] 1000 in
943 let res = List.filter (fun (x,b) -> not b) res in
944 if res = [] then None else Some (fst (List.hd res))
945
946 let rec (statistic_number: ('a list) -> (int * 'a) list) = function
947 | [] -> []
948 | x::xs -> let (splitg, splitd) = List.partition (fun y -> y = x) xs in
949 (1+(List.length splitg), x)::(statistic_number splitd)
950
951 (* in pourcentage *)
952 let (statistic: ('a list) -> (int * 'a) list) = fun xs ->
953 let stat_num = statistic_number xs in
954 let totals = sum_int (List.map fst stat_num) in
955 List.map (fun (i, v) -> ((i * 100) / totals), v) stat_num
956
957 let (laws2:
958 string -> ('a -> (bool * 'b)) -> ('a gen) ->
959 ('a option * ((int * 'b) list ))) =
960 fun s func gen ->
961 let res = foldn (fun acc i -> let n = gen() in (n, func n)::acc) [] 1000 in
962 let stat = statistic (List.map (fun (x,(b,v)) -> v) res) in
963 let res = List.filter (fun (x,(b,v)) -> not b) res in
964 if res = [] then (None, stat) else (Some (fst (List.hd res)), stat)
965
966
967 (*
968 let b = laws "unit" (fun x -> reverse [x] = [x] )ig
969 let b = laws "app " (fun (xs,ys) -> reverse (xs++ys) = reverse ys++reverse xs)(pg (lg ig)(lg ig))
970 let b = laws "rev " (fun xs -> reverse (reverse xs) = xs )(lg ig)
971 let b = laws "appb" (fun (xs,ys) -> reverse (xs++ys) = reverse xs++reverse ys)(pg (lg ig)(lg ig))
972 let b = laws "max" (fun (x,y) -> x <= y ==> (max x y = y) )(pg ig ig)
973
974 let b = laws2 "max" (fun (x,y) -> ((x <= y ==> (max x y = y)), x <= y))(pg ig ig)
975 *)
976
977
978 (* todo, do with coarbitrary ?? idea is that given a 'a, generate a 'b
979 * depending of 'a and gen 'b, that is modify gen 'b, what is important is
980 * that each time given the same 'a, we must get the same 'b !!!
981 *)
982
983 (*
984 let (fg: ('a gen) -> ('b gen) -> ('a -> 'b) gen) = fun gen1 gen2 () ->
985 let b = laws "funs" (fun (f,g,h) -> x <= y ==> (max x y = y) )(pg ig ig)
986 *)
987
988 (*
989 let one_of xs = List.nth xs (Random.int (List.length xs))
990 let take_one xs =
991 if empty xs then failwith "Take_one: empty list"
992 else
993 let i = Random.int (List.length xs) in
994 List.nth xs i, filter_index (fun j _ -> i <> j) xs
995 *)
996
997 (*****************************************************************************)
998 (* Persistence *)
999 (*****************************************************************************)
1000
1001 let get_value filename =
1002 let chan = open_in filename in
1003 let x = input_value chan in (* <=> Marshal.from_channel *)
1004 (close_in chan; x)
1005
1006 let write_value valu filename =
1007 let chan = open_out filename in
1008 (output_value chan valu; (* <=> Marshal.to_channel *)
1009 (* Marshal.to_channel chan valu [Marshal.Closures]; *)
1010 close_out chan)
1011
1012 let write_back func filename =
1013 write_value (func (get_value filename)) filename
1014
1015
1016 let read_value f = get_value f
1017
1018
1019 let marshal__to_string2 v flags =
1020 Marshal.to_string v flags
1021 let marshal__to_string a b =
1022 profile_code "Marshalling" (fun () -> marshal__to_string2 a b)
1023
1024 let marshal__from_string2 v flags =
1025 Marshal.from_string v flags
1026 let marshal__from_string a b =
1027 profile_code "Marshalling" (fun () -> marshal__from_string2 a b)
1028
1029
1030
1031 (*****************************************************************************)
1032 (* Counter *)
1033 (*****************************************************************************)
1034 let _counter = ref 0
1035 let counter () = (_counter := !_counter +1; !_counter)
1036
1037 let _counter2 = ref 0
1038 let counter2 () = (_counter2 := !_counter2 +1; !_counter2)
1039
1040 let _counter3 = ref 0
1041 let counter3 () = (_counter3 := !_counter3 +1; !_counter3)
1042
1043 type timestamp = int
1044
1045 (*****************************************************************************)
1046 (* String_of *)
1047 (*****************************************************************************)
1048 (* To work with the macro system autogenerated string_of and print_ function
1049 (kind of deriving a la haskell) *)
1050
1051 (* int, bool, char, float, ref ?, string *)
1052
1053 let string_of_string s = "\"" ^ s "\""
1054
1055 let string_of_list f xs =
1056 "[" ^ (xs +> List.map f +> String.concat ";" ) ^ "]"
1057
1058 let string_of_unit () = "()"
1059
1060 let string_of_array f xs =
1061 "[|" ^ (xs +> Array.to_list +> List.map f +> String.concat ";") ^ "|]"
1062
1063 let string_of_option f = function
1064 | None -> "None "
1065 | Some x -> "Some " ^ (f x)
1066
1067
1068
1069
1070 let print_bool x = print_string (if x then "True" else "False")
1071
1072 let print_option pr = function
1073 | None -> print_string "None"
1074 | Some x -> print_string "Some ("; pr x; print_string ")"
1075
1076 let print_list pr xs =
1077 begin
1078 print_string "[";
1079 List.iter (fun x -> pr x; print_string ",") xs;
1080 print_string "]";
1081 end
1082
1083 (* specialised
1084 let (string_of_list: char list -> string) =
1085 List.fold_left (fun acc x -> acc^(Char.escaped x)) ""
1086 *)
1087
1088
1089 let rec print_between between fn = function
1090 | [] -> ()
1091 | [x] -> fn x
1092 | x::xs -> fn x; between(); print_between between fn xs
1093
1094
1095
1096
1097 let adjust_pp_with_indent f =
1098 Format.open_box !_tab_level_print;
1099 (*Format.force_newline();*)
1100 f();
1101 Format.close_box ();
1102 Format.print_newline()
1103
1104 let adjust_pp_with_indent_and_header s f =
1105 Format.open_box (!_tab_level_print + String.length s);
1106 do_n !_tab_level_print (fun () -> Format.print_string " ");
1107 Format.print_string s;
1108 f();
1109 Format.close_box ();
1110 Format.print_newline()
1111
1112
1113
1114 let pp_do_in_box f = Format.open_box 1; f(); Format.close_box ()
1115 let pp_do_in_zero_box f = Format.open_box 0; f(); Format.close_box ()
1116
1117 let pp_f_in_box f =
1118 Format.open_box 1;
1119 let res = f() in
1120 Format.close_box ();
1121 res
1122
1123 let pp s = Format.print_string s
1124
1125 let mk_str_func_of_assoc_conv xs =
1126 let swap (x,y) = (y,x) in
1127
1128 (fun s ->
1129 let xs' = List.map swap xs in
1130 List.assoc s xs'
1131 ),
1132 (fun a ->
1133 List.assoc a xs
1134 )
1135
1136
1137
1138 (* julia: convert something printed using format to print into a string *)
1139 (* now at bottom of file
1140 let format_to_string f =
1141 ...
1142 *)
1143
1144
1145
1146 (*****************************************************************************)
1147 (* Macro *)
1148 (*****************************************************************************)
1149
1150 (* put your macro in macro.ml4, and you can test it interactivly as in lisp *)
1151 let macro_expand s =
1152 let c = open_out "/tmp/ttttt.ml" in
1153 begin
1154 output_string c s; close_out c;
1155 command2 ("ocamlc -c -pp 'camlp4o pa_extend.cmo q_MLast.cmo -impl' " ^
1156 "-I +camlp4 -impl macro.ml4");
1157 command2 "camlp4o ./macro.cmo pr_o.cmo /tmp/ttttt.ml";
1158 command2 "rm -f /tmp/ttttt.ml";
1159 end
1160
1161 (*
1162 let t = macro_expand "{ x + y | (x,y) <- [(1,1);(2,2);(3,3)] and x>2 and y<3}"
1163 let x = { x + y | (x,y) <- [(1,1);(2,2);(3,3)] and x > 2 and y < 3}
1164 let t = macro_expand "{1 .. 10}"
1165 let x = {1 .. 10} +> List.map (fun i -> i)
1166 let t = macro_expand "[1;2] to append to [2;4]"
1167 let t = macro_expand "{x = 2; x = 3}"
1168
1169 let t = macro_expand "type 'a bintree = Leaf of 'a | Branch of ('a bintree * 'a bintree)"
1170 *)
1171
1172
1173
1174 (*****************************************************************************)
1175 (* Composition/Control *)
1176 (*****************************************************************************)
1177
1178 (* I like the obj.func object notation. In OCaml cant use '.' so I use +>
1179 *
1180 * update: it seems that F# agrees with me :) but they use |>
1181 *)
1182
1183 (* now in prelude:
1184 * let (+>) o f = f o
1185 *)
1186 let (+!>) refo f = refo := f !refo
1187 (* alternatives:
1188 * let ((@): 'a -> ('a -> 'b) -> 'b) = fun a b -> b a
1189 * let o f g x = f (g x)
1190 *)
1191
1192 let ($) f g x = g (f x)
1193 let compose f g x = f (g x)
1194 (* dont work :( let ( ° ) f g x = f(g(x)) *)
1195
1196 (* trick to have something similar to the 1 `max` 4 haskell infix notation.
1197 by Keisuke Nakano on the caml mailing list.
1198 > let ( /* ) x y = y x
1199 > and ( */ ) x y = x y
1200 or
1201 let ( <| ) x y = y x
1202 and ( |> ) x y = x y
1203
1204 > Then we can make an infix operator <| f |> for a binary function f.
1205 *)
1206
1207 let flip f = fun a b -> f b a
1208
1209 let curry f x y = f (x,y)
1210 let uncurry f (a,b) = f a b
1211
1212 let id = fun x -> x
1213
1214 let do_nothing () = ()
1215
1216 let rec applyn n f o = if n = 0 then o else applyn (n-1) f (f o)
1217
1218 let forever f =
1219 while true do
1220 f();
1221 done
1222
1223
1224 class ['a] shared_variable_hook (x:'a) =
1225 object(self)
1226 val mutable data = x
1227 val mutable registered = []
1228 method set x =
1229 begin
1230 data <- x;
1231 pr "refresh registered";
1232 registered +> List.iter (fun f -> f());
1233 end
1234 method get = data
1235 method modify f = self#set (f self#get)
1236 method register f =
1237 registered <- f :: registered
1238 end
1239
1240 (* src: from aop project. was called ptFix *)
1241 let rec fixpoint trans elem =
1242 let image = trans elem in
1243 if (image = elem)
1244 then elem (* point fixe *)
1245 else fixpoint trans image
1246
1247 (* le point fixe pour les objets. was called ptFixForObjetct *)
1248 let rec fixpoint_for_object trans elem =
1249 let image = trans elem in
1250 if (image#equal elem) then elem (* point fixe *)
1251 else fixpoint_for_object trans image
1252
1253 let (add_hook: ('a -> ('a -> 'b) -> 'b) ref -> ('a -> ('a -> 'b) -> 'b) -> unit) =
1254 fun var f ->
1255 let oldvar = !var in
1256 var := fun arg k -> f arg (fun x -> oldvar x k)
1257
1258 let (add_hook_action: ('a -> unit) -> ('a -> unit) list ref -> unit) =
1259 fun f hooks ->
1260 push2 f hooks
1261
1262 let (run_hooks_action: 'a -> ('a -> unit) list ref -> unit) =
1263 fun obj hooks ->
1264 !hooks +> List.iter (fun f -> try f obj with _ -> ())
1265
1266
1267 type 'a mylazy = (unit -> 'a)
1268
1269 (* a la emacs *)
1270 let save_excursion reference f =
1271 let old = !reference in
1272 let res = try f() with e -> reference := old; raise e in
1273 reference := old;
1274 res
1275
1276 let save_excursion_and_disable reference f =
1277 save_excursion reference (fun () ->
1278 reference := false;
1279 f ()
1280 )
1281
1282 let save_excursion_and_enable reference f =
1283 save_excursion reference (fun () ->
1284 reference := true;
1285 f ()
1286 )
1287
1288
1289 let memoized h k f =
1290 try Hashtbl.find h k
1291 with Not_found ->
1292 let v = f () in
1293 begin
1294 Hashtbl.add h k v;
1295 v
1296 end
1297
1298 let cache_in_ref myref f =
1299 match !myref with
1300 | Some e -> e
1301 | None ->
1302 let e = f () in
1303 myref := Some e;
1304 e
1305
1306 let once f =
1307 let already = ref false in
1308 (fun x ->
1309 if not !already
1310 then begin already := true; f x end
1311 )
1312
1313 (* cache_file, cf below *)
1314
1315 let before_leaving f x =
1316 f x;
1317 x
1318
1319 (* finalize, cf prelude *)
1320
1321
1322 (* cheat *)
1323 let rec y f = fun x -> f (y f) x
1324
1325 (*****************************************************************************)
1326 (* Concurrency *)
1327 (*****************************************************************************)
1328
1329 (* from http://en.wikipedia.org/wiki/File_locking
1330 *
1331 * "When using file locks, care must be taken to ensure that operations
1332 * are atomic. When creating the lock, the process must verify that it
1333 * does not exist and then create it, but without allowing another
1334 * process the opportunity to create it in the meantime. Various
1335 * schemes are used to implement this, such as taking advantage of
1336 * system calls designed for this purpose (but such system calls are
1337 * not usually available to shell scripts) or by creating the lock file
1338 * under a temporary name and then attempting to move it into place."
1339 *
1340 * => can't use 'if(not (file_exist xxx)) then create_file xxx' because
1341 * file_exist/create_file are not in atomic section (classic problem).
1342 *
1343 * from man open:
1344 *
1345 * "O_EXCL When used with O_CREAT, if the file already exists it
1346 * is an error and the open() will fail. In this context, a
1347 * symbolic link exists, regardless of where it points to.
1348 * O_EXCL is broken on NFS file systems; programs which
1349 * rely on it for performing locking tasks will contain a
1350 * race condition. The solution for performing atomic file
1351 * locking using a lockfile is to create a unique file on
1352 * the same file system (e.g., incorporating host- name and
1353 * pid), use link(2) to make a link to the lockfile. If
1354 * link(2) returns 0, the lock is successful. Otherwise,
1355 * use stat(2) on the unique file to check if its link
1356 * count has increased to 2, in which case the lock is also
1357 * successful."
1358
1359 *)
1360
1361 exception FileAlreadyLocked
1362
1363 (* Racy if lock file on NFS!!! But still racy with recent Linux ? *)
1364 let acquire_file_lock filename =
1365 pr2 ("Locking file: " ^ filename);
1366 try
1367 let _fd = Unix.openfile filename [Unix.O_CREAT;Unix.O_EXCL] 0o777 in
1368 ()
1369 with Unix.Unix_error (e, fm, argm) ->
1370 pr2 (spf "exn Unix_error: %s %s %s\n" (Unix.error_message e) fm argm);
1371 raise FileAlreadyLocked
1372
1373
1374 let release_file_lock filename =
1375 pr2 ("Releasing file: " ^ filename);
1376 Unix.unlink filename;
1377 ()
1378
1379
1380
1381 (*****************************************************************************)
1382 (* Error managment *)
1383 (*****************************************************************************)
1384
1385 exception Todo
1386 exception Impossible
1387 exception Here
1388 exception ReturnExn
1389
1390 exception Multi_found (* to be consistent with Not_found *)
1391
1392 exception WrongFormat of string
1393
1394 (* old: let _TODO () = failwith "TODO", now via fix_caml with raise Todo *)
1395
1396 let internal_error s = failwith ("internal error: "^s)
1397 let error_cant_have x = internal_error ("cant have this case: " ^(dump x))
1398 let myassert cond = if cond then () else failwith "assert error"
1399
1400
1401
1402 (* before warning I was forced to do stuff like this:
1403 *
1404 * let (fixed_int_to_posmap: fixed_int -> posmap) = fun fixed ->
1405 * let v = ((fix_to_i fixed) / (power 2 16)) in
1406 * let _ = Printf.printf "coord xy = %d\n" v in
1407 * v
1408 *
1409 * The need for printf make me force to name stuff :(
1410 * How avoid ? use 'it' special keyword ?
1411 * In fact dont have to name it, use +> (fun v -> ...) so when want
1412 * erase debug just have to erase one line.
1413 *)
1414 let warning s v = (pr2 ("Warning: " ^ s ^ "; value = " ^ (dump v)); v)
1415
1416
1417
1418
1419 let exn_to_s exn =
1420 Printexc.to_string exn
1421
1422 (* alias *)
1423 let string_of_exn exn = exn_to_s exn
1424
1425
1426 (* want or of merd, but cant cos cant put die ... in b (strict call) *)
1427 let (|||) a b = try a with _ -> b
1428
1429 (* emacs/lisp inspiration, (vouillon does that too in unison I think) *)
1430
1431 (* now in Prelude:
1432 * let unwind_protect f cleanup = ...
1433 * let finalize f cleanup = ...
1434 *)
1435
1436 type error = Error of string
1437
1438 (* sometimes to get help from ocaml compiler to tell me places where
1439 * I should update, we sometimes need to change some type from pair
1440 * to triple, hence this kind of fake type.
1441 *)
1442 type evotype = unit
1443 let evoval = ()
1444
1445 (*****************************************************************************)
1446 (* Environment *)
1447 (*****************************************************************************)
1448
1449 let check_stack = ref true
1450 let check_stack_size limit =
1451 if !check_stack then begin
1452 pr2 "checking stack size (do ulimit -s 50000 if problem)";
1453 let rec aux i =
1454 if i = limit
1455 then 0
1456 else 1 + aux (i + 1)
1457 in
1458 assert(aux 0 = limit);
1459 ()
1460 end
1461
1462 let test_check_stack_size limit =
1463 (* bytecode: 100000000 *)
1464 (* native: 10000000 *)
1465 check_stack_size (int_of_string limit)
1466
1467
1468 (* only relevant in bytecode, in native the stacklimit is the os stacklimit
1469 * (adjustable by ulimit -s)
1470 *)
1471 let _init_gc_stack =
1472 Gc.set {(Gc.get ()) with Gc.stack_limit = 100 * 1024 * 1024}
1473
1474
1475
1476
1477 (* if process a big set of files then dont want get overflow in the middle
1478 * so for this we are ready to spend some extra time at the beginning that
1479 * could save far more later.
1480 *)
1481 let check_stack_nbfiles nbfiles =
1482 if nbfiles > 200
1483 then check_stack_size 10000000
1484
1485 (*****************************************************************************)
1486 (* Arguments/options and command line (cocci and acomment) *)
1487 (*****************************************************************************)
1488
1489 (*
1490 * Why define wrappers ? Arg not good enough ? Well the Arg.Rest is not that
1491 * good and I need a way sometimes to get a list of argument.
1492 *
1493 * I could define maybe a new Arg.spec such as
1494 * | String_list of (string list -> unit), but the action may require
1495 * some flags to be set, so better to process this after all flags have
1496 * been set by parse_options. So have to split. Otherwise it would impose
1497 * an order of the options such as
1498 * -verbose_parsing -parse_c file1 file2. and I really like to use bash
1499 * history and add just at the end of my command a -profile for instance.
1500 *
1501 *
1502 * Why want a -action arg1 arg2 arg3 ? (which in turn requires this
1503 * convulated scheme ...) Why not use Arg.String action such as
1504 * "-parse_c", Arg.String (fun file -> ...) ?
1505 * I want something that looks like ocaml function but at the UNIX
1506 * command line level. So natural to have this scheme instead of
1507 * -taxo_file arg2 -sample_file arg3 -parse_c arg1.
1508 *
1509 *
1510 * Why not use the toplevel ?
1511 * - because to debug, ocamldebug is far superior to the toplevel
1512 * (can go back, can go directly to a specific point, etc).
1513 * I want a kind of testing at cmdline level.
1514 * - Also I don't have file completion when in the ocaml toplevel.
1515 * I have to type "/path/to/xxx" without help.
1516 *
1517 *
1518 * Why having variable flags ? Why use 'if !verbose_parsing then ...' ?
1519 * why not use strings and do stuff like the following
1520 * 'if (get_config "verbose_parsing") then ...'
1521 * Because I want to make the interface for flags easier for the code
1522 * that use it. The programmer should not be bothered wether this
1523 * flag is set via args cmd line or a config file, so I want to make it
1524 * as simple as possible, just use a global plain caml ref variable.
1525 *
1526 * Same spirit a little for the action. Instead of having function such as
1527 * test_parsing_c, I could do it only via string. But I still prefer
1528 * to have plain caml test functions. Also it makes it easier to call
1529 * those functions from a toplevel for people who prefer the toplevel.
1530 *
1531 *
1532 * So have flag_spec and action_spec. And in flag have debug_xxx flags,
1533 * verbose_xxx flags and other flags.
1534 *
1535 * I would like to not have to separate the -xxx actions spec from the
1536 * corresponding actions, but those actions may need more than one argument
1537 * and so have to wait for parse_options, which in turn need the options
1538 * spec, so circle.
1539 *
1540 * Also I dont want to mix code with data structures, so it's better that the
1541 * options variable contain just a few stuff and have no side effects except
1542 * setting global variables.
1543 *
1544 * Why not have a global variable such as Common.actions that
1545 * other modules modify ? No, I prefer to do less stuff behind programmer's
1546 * back so better to let the user merge the different options at call
1547 * site, but at least make it easier by providing shortcut for set of options.
1548 *
1549 *
1550 *
1551 *
1552 * todo? isn't unison or scott-mcpeak-lib-in-cil handles that kind of
1553 * stuff better ? That is the need to localize command line argument
1554 * while still being able to gathering them. Same for logging.
1555 * Similiar to the type prof = PALL | PNONE | PSOME of string list.
1556 * Same spirit of fine grain config in log4j ?
1557 *
1558 * todo? how mercurial/cvs/git manage command line options ? because they
1559 * all have a kind of DSL around arguments with some common options,
1560 * specific options, conventions, etc.
1561 *
1562 *
1563 * todo? generate the corresponding noxxx options ?
1564 * todo? generate list of options and show their value ?
1565 *
1566 * todo? make it possible to set this value via a config file ?
1567 *
1568 *
1569 *)
1570
1571 type arg_spec_full = Arg.key * Arg.spec * Arg.doc
1572 type cmdline_options = arg_spec_full list
1573
1574 (* the format is a list of triples:
1575 * (title of section * (optional) explanation of sections * options)
1576 *)
1577 type options_with_title = string * string * arg_spec_full list
1578 type cmdline_sections = options_with_title list
1579
1580
1581 (* ---------------------------------------------------------------------- *)
1582
1583 (* now I use argv as I like at the call sites to show that
1584 * this function internally use argv.
1585 *)
1586 let parse_options options usage_msg argv =
1587 let args = ref [] in
1588 (try
1589 Arg.parse_argv argv options (fun file -> args := file::!args) usage_msg;
1590 args := List.rev !args;
1591 !args
1592 with
1593 | Arg.Bad msg -> eprintf "%s" msg; exit 2
1594 | Arg.Help msg -> printf "%s" msg; exit 0
1595 )
1596
1597
1598
1599
1600 let usage usage_msg options =
1601 Arg.usage (Arg.align options) usage_msg
1602
1603
1604 (* for coccinelle *)
1605
1606 (* If you don't want the -help and --help that are appended by Arg.align *)
1607 let arg_align2 xs =
1608 Arg.align xs +> List.rev +> drop 2 +> List.rev
1609
1610
1611 let short_usage usage_msg ~short_opt =
1612 usage usage_msg short_opt
1613
1614 let long_usage usage_msg ~short_opt ~long_opt =
1615 pr usage_msg;
1616 pr "";
1617 let all_options_with_title =
1618 (("main options", "", short_opt)::long_opt) in
1619 all_options_with_title +> List.iter
1620 (fun (title, explanations, xs) ->
1621 pr title;
1622 pr_xxxxxxxxxxxxxxxxx();
1623 if explanations <> ""
1624 then begin pr explanations; pr "" end;
1625 arg_align2 xs +> List.iter (fun (key,action,s) ->
1626 pr (" " ^ key ^ s)
1627 );
1628 pr "";
1629 );
1630 ()
1631
1632
1633 (* copy paste of Arg.parse. Don't want the default -help msg *)
1634 let arg_parse2 l msg short_usage_fun =
1635 let args = ref [] in
1636 let f = (fun file -> args := file::!args) in
1637 let l = Arg.align l in
1638 (try begin
1639 Arg.parse_argv Sys.argv l f msg;
1640 args := List.rev !args;
1641 !args
1642 end
1643 with
1644 | Arg.Bad msg -> (* eprintf "%s" msg; exit 2; *)
1645 let xs = lines msg in
1646 (* take only head, it's where the error msg is *)
1647 pr2 (List.hd xs);
1648 short_usage_fun();
1649 raise (UnixExit (2))
1650 | Arg.Help msg -> (* printf "%s" msg; exit 0; *)
1651 raise Impossible (* -help is specified in speclist *)
1652 )
1653
1654
1655 (* ---------------------------------------------------------------------- *)
1656 (* kind of unit testing framework, or toplevel like functionnality
1657 * at shell command line. I realize than in fact It follows a current trend
1658 * to have a main cmdline program where can then select different actions,
1659 * as in cvs/hg/git where do hg <action> <arguments>, and the shell even
1660 * use a curried syntax :)
1661 *
1662 *
1663 * Not-perfect-but-basic-feels-right: an action
1664 * spec looks like this:
1665 *
1666 * let actions () = [
1667 * "-parse_taxo", " <file>",
1668 * Common.mk_action_1_arg test_parse_taxo;
1669 * ...
1670 * ]
1671 *
1672 * Not-perfect-but-basic-feels-right because for such functionality we
1673 * need a way to transform a string into a caml function and pass arguments
1674 * and the preceding design does exactly that, even if then the
1675 * functions that use this design are not so convenient to use (there
1676 * are 2 places where we need to pass those data, in the options and in the
1677 * main dispatcher).
1678 *
1679 * Also it's not too much intrusive. Still have an
1680 * action ref variable in the main.ml and can still use the previous
1681 * simpler way to do where the match args with in main.ml do the
1682 * dispatch.
1683 *
1684 * Use like this at option place:
1685 * (Common.options_of_actions actionref (Test_parsing_c.actions())) ++
1686 * Use like this at dispatch action place:
1687 * | xs when List.mem !action (Common.action_list all_actions) ->
1688 * Common.do_action !action xs all_actions
1689 *
1690 *)
1691
1692 type flag_spec = Arg.key * Arg.spec * Arg.doc
1693 type action_spec = Arg.key * Arg.doc * action_func
1694 and action_func = (string list -> unit)
1695
1696 type cmdline_actions = action_spec list
1697 exception WrongNumberOfArguments
1698
1699 let options_of_actions action_ref actions =
1700 actions +> List.map (fun (key, doc, _func) ->
1701 (key, (Arg.Unit (fun () -> action_ref := key)), doc)
1702 )
1703
1704 let (action_list: cmdline_actions -> Arg.key list) = fun xs ->
1705 List.map (fun (a,b,c) -> a) xs
1706
1707 let (do_action: Arg.key -> string list (* args *) -> cmdline_actions -> unit) =
1708 fun key args xs ->
1709 let assoc = xs +> List.map (fun (a,b,c) -> (a,c)) in
1710 let action_func = List.assoc key assoc in
1711 action_func args
1712
1713
1714 (* todo? if have a function with default argument ? would like a
1715 * mk_action_0_or_1_arg ?
1716 *)
1717
1718 let mk_action_0_arg f =
1719 (function
1720 | [] -> f ()
1721 | _ -> raise WrongNumberOfArguments
1722 )
1723
1724 let mk_action_1_arg f =
1725 (function
1726 | [file] -> f file
1727 | _ -> raise WrongNumberOfArguments
1728 )
1729
1730 let mk_action_2_arg f =
1731 (function
1732 | [file1;file2] -> f file1 file2
1733 | _ -> raise WrongNumberOfArguments
1734 )
1735
1736 let mk_action_3_arg f =
1737 (function
1738 | [file1;file2;file3] -> f file1 file2 file3
1739 | _ -> raise WrongNumberOfArguments
1740 )
1741
1742 let mk_action_n_arg f = f
1743
1744
1745 (*****************************************************************************)
1746 (* Equality *)
1747 (*****************************************************************************)
1748
1749 (* Using the generic (=) is tempting, but it backfires, so better avoid it *)
1750
1751 (* To infer all the code that use an equal, and that should be
1752 * transformed, is not that easy, because (=) is used by many
1753 * functions, such as List.find, List.mem, and so on. So the strategy
1754 * is to turn what you were previously using into a function, because
1755 * (=) return an exception when applied to a function. Then you simply
1756 * use ocamldebug to infer where the code has to be transformed.
1757 *)
1758
1759 (* src: caml mailing list ? *)
1760 let (=|=) : int -> int -> bool = (=)
1761 let (=<=) : char -> char -> bool = (=)
1762 let (=$=) : string -> string -> bool = (=)
1763 let (=:=) : bool -> bool -> bool = (=)
1764
1765 (* the evil generic (=). I define another symbol to more easily detect
1766 * it, cos the '=' sign is syntaxically overloaded in caml. It is also
1767 * used to define function.
1768 *)
1769 let (=*=) = (=)
1770
1771 (* if really want to forbid to use '='
1772 let (=) = (=|=)
1773 *)
1774 let (=) () () = false
1775
1776
1777
1778
1779
1780
1781
1782
1783 (*###########################################################################*)
1784 (* And now basic types *)
1785 (*###########################################################################*)
1786
1787
1788
1789 (*****************************************************************************)
1790 (* Bool *)
1791 (*****************************************************************************)
1792 let (==>) b1 b2 = if b1 then b2 else true (* could use too => *)
1793
1794 (* superseded by another <=> below
1795 let (<=>) a b = if a =*= b then 0 else if a < b then -1 else 1
1796 *)
1797
1798 let xor a b = not (a =*= b)
1799
1800
1801 (*****************************************************************************)
1802 (* Char *)
1803 (*****************************************************************************)
1804
1805 let string_of_char c = String.make 1 c
1806
1807 let is_single = String.contains ",;()[]{}_`"
1808 let is_symbol = String.contains "!@#$%&*+./<=>?\\^|:-~"
1809 let is_space = String.contains "\n\t "
1810 let cbetween min max c =
1811 (int_of_char c) <= (int_of_char max) &&
1812 (int_of_char c) >= (int_of_char min)
1813 let is_upper = cbetween 'A' 'Z'
1814 let is_lower = cbetween 'a' 'z'
1815 let is_alpha c = is_upper c || is_lower c
1816 let is_digit = cbetween '0' '9'
1817
1818 let string_of_chars cs = cs +> List.map (String.make 1) +> String.concat ""
1819
1820
1821
1822 (*****************************************************************************)
1823 (* Num *)
1824 (*****************************************************************************)
1825
1826 (* since 3.08, div by 0 raise Div_by_rezo, and not anymore a hardware trap :)*)
1827 let (/!) x y = if y =|= 0 then (log "common.ml: div by 0"; 0) else x / y
1828
1829 (* now in prelude
1830 * let rec (do_n: int -> (unit -> unit) -> unit) = fun i f ->
1831 * if i = 0 then () else (f(); do_n (i-1) f)
1832 *)
1833
1834 (* now in prelude
1835 * let rec (foldn: ('a -> int -> 'a) -> 'a -> int -> 'a) = fun f acc i ->
1836 * if i = 0 then acc else foldn f (f acc i) (i-1)
1837 *)
1838
1839 let sum_float = List.fold_left (+.) 0.0
1840 let sum_int = List.fold_left (+) 0
1841
1842 let pi = 3.14159265358979323846
1843 let pi2 = pi /. 2.0
1844 let pi4 = pi /. 4.0
1845
1846 (* 180 = pi *)
1847 let (deg_to_rad: float -> float) = fun deg ->
1848 (deg *. pi) /. 180.0
1849
1850 let clampf = function
1851 | n when n < 0.0 -> 0.0
1852 | n when n > 1.0 -> 1.0
1853 | n -> n
1854
1855 let square x = x *. x
1856
1857 let rec power x n = if n =|= 0 then 1 else x * power x (n-1)
1858
1859 let between i min max = i > min && i < max
1860
1861 let (between_strict: int -> int -> int -> bool) = fun a b c ->
1862 a < b && b < c
1863
1864
1865 let bitrange x p = let v = power 2 p in between x (-v) v
1866
1867 (* descendant *)
1868 let (prime1: int -> int option) = fun x ->
1869 let rec prime1_aux n =
1870 if n =|= 1 then None
1871 else
1872 if (x / n) * n =|= x then Some n else prime1_aux (n-1)
1873 in if x =|= 1 then None else if x < 0 then failwith "negative" else prime1_aux (x-1)
1874
1875 (* montant, better *)
1876 let (prime: int -> int option) = fun x ->
1877 let rec prime_aux n =
1878 if n =|= x then None
1879 else
1880 if (x / n) * n =|= x then Some n else prime_aux (n+1)
1881 in if x =|= 1 then None else if x < 0 then failwith "negative" else prime_aux 2
1882
1883 let sum xs = List.fold_left (+) 0 xs
1884 let product = List.fold_left ( * ) 1
1885
1886
1887 let decompose x =
1888 let rec decompose x =
1889 if x =|= 1 then []
1890 else
1891 (match prime x with
1892 | None -> [x]
1893 | Some n -> n::decompose (x / n)
1894 )
1895 in assert (product (decompose x) =|= x); decompose x
1896
1897 let mysquare x = x * x
1898 let sqr a = a *. a
1899
1900
1901 type compare = Equal | Inf | Sup
1902 let (<=>) a b = if a =*= b then Equal else if a < b then Inf else Sup
1903 let (<==>) a b = if a =*= b then 0 else if a < b then -1 else 1
1904
1905 type uint = int
1906
1907
1908 let int_of_stringchar s =
1909 fold_left_with_index (fun acc e i -> acc + (Char.code e*(power 8 i))) 0 (List.rev (list_of_string s))
1910
1911 let int_of_base s base =
1912 fold_left_with_index (fun acc e i ->
1913 let j = Char.code e - Char.code '0' in
1914 if j >= base then failwith "not in good base"
1915 else acc + (j*(power base i))
1916 )
1917 0 (List.rev (list_of_string s))
1918
1919 let int_of_stringbits s = int_of_base s 2
1920 let _ = example (int_of_stringbits "1011" =|= 1*8 + 1*2 + 1*1)
1921
1922 let int_of_octal s = int_of_base s 8
1923 let _ = example (int_of_octal "017" =|= 15)
1924
1925 (* let int_of_hex s = int_of_base s 16, NONONONO cos 'A' - '0' does not give 10 !! *)
1926
1927 let int_of_all s =
1928 if String.length s >= 2 && (String.get s 0 =<= '0') && is_digit (String.get s 1)
1929 then int_of_octal s else int_of_string s
1930
1931
1932 let (+=) ref v = ref := !ref + v
1933 let (-=) ref v = ref := !ref - v
1934
1935 let pourcent x total =
1936 (x * 100) / total
1937 let pourcent_float x total =
1938 ((float_of_int x) *. 100.0) /. (float_of_int total)
1939
1940 let pourcent_float_of_floats x total =
1941 (x *. 100.0) /. total
1942
1943
1944 let pourcent_good_bad good bad =
1945 (good * 100) / (good + bad)
1946
1947 let pourcent_good_bad_float good bad =
1948 (float_of_int good *. 100.0) /. (float_of_int good +. float_of_int bad)
1949
1950 type 'a max_with_elem = int ref * 'a ref
1951 let update_max_with_elem (aref, aelem) ~is_better (newv, newelem) =
1952 if is_better newv aref
1953 then begin
1954 aref := newv;
1955 aelem := newelem;
1956 end
1957
1958 (*****************************************************************************)
1959 (* Numeric/overloading *)
1960 (*****************************************************************************)
1961
1962 type 'a numdict =
1963 NumDict of (('a-> 'a -> 'a) *
1964 ('a-> 'a -> 'a) *
1965 ('a-> 'a -> 'a) *
1966 ('a -> 'a));;
1967
1968 let add (NumDict(a, m, d, n)) = a;;
1969 let mul (NumDict(a, m, d, n)) = m;;
1970 let div (NumDict(a, m, d, n)) = d;;
1971 let neg (NumDict(a, m, d, n)) = n;;
1972
1973 let numd_int = NumDict(( + ),( * ),( / ),( ~- ));;
1974 let numd_float = NumDict(( +. ),( *. ), ( /. ),( ~-. ));;
1975 let testd dict n =
1976 let ( * ) x y = mul dict x y in
1977 let ( / ) x y = div dict x y in
1978 let ( + ) x y = add dict x y in
1979 (* Now you can define all sorts of things in terms of *, /, + *)
1980 let f num = (num * num) / (num + num) in
1981 f n;;
1982
1983
1984
1985 module ArithFloatInfix = struct
1986 let (+..) = (+)
1987 let (-..) = (-)
1988 let (/..) = (/)
1989 let ( *.. ) = ( * )
1990
1991
1992 let (+) = (+.)
1993 let (-) = (-.)
1994 let (/) = (/.)
1995 let ( * ) = ( *. )
1996
1997 let (+=) ref v = ref := !ref + v
1998 let (-=) ref v = ref := !ref - v
1999
2000 end
2001
2002
2003
2004 (*****************************************************************************)
2005 (* Tuples *)
2006 (*****************************************************************************)
2007
2008 type 'a pair = 'a * 'a
2009 type 'a triple = 'a * 'a * 'a
2010
2011 let fst3 (x,_,_) = x
2012 let snd3 (_,y,_) = y
2013 let thd3 (_,_,z) = z
2014
2015 let sndthd (a,b,c) = (b,c)
2016
2017 let map_fst f (x, y) = f x, y
2018 let map_snd f (x, y) = x, f y
2019
2020 let pair f (x,y) = (f x, f y)
2021
2022 (* for my ocamlbeautify script *)
2023 let snd = snd
2024 let fst = fst
2025
2026 let double a = a,a
2027 let swap (x,y) = (y,x)
2028
2029
2030 let tuple_of_list1 = function [a] -> a | _ -> failwith "tuple_of_list1"
2031 let tuple_of_list2 = function [a;b] -> a,b | _ -> failwith "tuple_of_list2"
2032 let tuple_of_list3 = function [a;b;c] -> a,b,c | _ -> failwith "tuple_of_list3"
2033 let tuple_of_list4 = function [a;b;c;d] -> a,b,c,d | _ -> failwith "tuple_of_list4"
2034 let tuple_of_list5 = function [a;b;c;d;e] -> a,b,c,d,e | _ -> failwith "tuple_of_list5"
2035 let tuple_of_list6 = function [a;b;c;d;e;f] -> a,b,c,d,e,f | _ -> failwith "tuple_of_list6"
2036
2037
2038 (*****************************************************************************)
2039 (* Maybe *)
2040 (*****************************************************************************)
2041
2042 (* type 'a maybe = Just of 'a | None *)
2043
2044 type ('a,'b) either = Left of 'a | Right of 'b
2045 (* with sexp *)
2046 type ('a, 'b, 'c) either3 = Left3 of 'a | Middle3 of 'b | Right3 of 'c
2047 (* with sexp *)
2048
2049 let just = function
2050 | (Some x) -> x
2051 | _ -> failwith "just: pb"
2052
2053 let some = just
2054
2055
2056 let fmap f = function
2057 | None -> None
2058 | Some x -> Some (f x)
2059 let map_option = fmap
2060
2061 let do_option f = function
2062 | None -> ()
2063 | Some x -> f x
2064
2065 let optionise f =
2066 try Some (f ()) with Not_found -> None
2067
2068
2069
2070 (* pixel *)
2071 let some_or = function
2072 | None -> id
2073 | Some e -> fun _ -> e
2074
2075
2076 let partition_either f l =
2077 let rec part_either left right = function
2078 | [] -> (List.rev left, List.rev right)
2079 | x :: l ->
2080 (match f x with
2081 | Left e -> part_either (e :: left) right l
2082 | Right e -> part_either left (e :: right) l) in
2083 part_either [] [] l
2084
2085 let partition_either3 f l =
2086 let rec part_either left middle right = function
2087 | [] -> (List.rev left, List.rev middle, List.rev right)
2088 | x :: l ->
2089 (match f x with
2090 | Left3 e -> part_either (e :: left) middle right l
2091 | Middle3 e -> part_either left (e :: middle) right l
2092 | Right3 e -> part_either left middle (e :: right) l) in
2093 part_either [] [] [] l
2094
2095
2096 (* pixel *)
2097 let rec filter_some = function
2098 | [] -> []
2099 | None :: l -> filter_some l
2100 | Some e :: l -> e :: filter_some l
2101
2102 let map_filter f xs = xs +> List.map f +> filter_some
2103
2104 let rec find_some p = function
2105 | [] -> raise Not_found
2106 | x :: l ->
2107 match p x with
2108 | Some v -> v
2109 | None -> find_some p l
2110
2111 (* same
2112 let map_find f xs =
2113 xs +> List.map f +> List.find (function Some x -> true | None -> false)
2114 +> (function Some x -> x | None -> raise Impossible)
2115 *)
2116
2117
2118 let list_to_single_or_exn xs =
2119 match xs with
2120 | [] -> raise Not_found
2121 | x::y::zs -> raise Multi_found
2122 | [x] -> x
2123
2124 (*****************************************************************************)
2125 (* TriBool *)
2126 (*****************************************************************************)
2127
2128 type bool3 = True3 | False3 | TrueFalsePb3 of string
2129
2130
2131
2132 (*****************************************************************************)
2133 (* Regexp, can also use PCRE *)
2134 (*****************************************************************************)
2135
2136 (* Note: OCaml Str regexps are different from Perl regexp:
2137 * - The OCaml regexp must match the entire way.
2138 * So "testBee" =~ "Bee" is wrong
2139 * but "testBee" =~ ".*Bee" is right
2140 * Can have the perl behavior if use Str.search_forward instead of
2141 * Str.string_match.
2142 * - Must add some additional \ in front of some special char. So use
2143 * \\( \\| and also \\b
2144 * - It does not always handle newlines very well.
2145 * - \\b does consider _ but not numbers in indentifiers.
2146 *
2147 * Note: PCRE regexps are then different from Str regexps ...
2148 * - just use '(' ')' for grouping, not '\\)'
2149 * - still need \\b for word boundary, but this time it works ...
2150 * so can match some word that have some digits in them.
2151 *
2152 *)
2153
2154 (* put before String section because String section use some =~ *)
2155
2156 (* let gsubst = global_replace *)
2157
2158
2159 let (==~) s re = Str.string_match re s 0
2160
2161 let _memo_compiled_regexp = Hashtbl.create 101
2162 let candidate_match_func s re =
2163 (* old: Str.string_match (Str.regexp re) s 0 *)
2164 let compile_re =
2165 memoized _memo_compiled_regexp re (fun () -> Str.regexp re)
2166 in
2167 Str.string_match compile_re s 0
2168
2169 let match_func s re =
2170 profile_code "Common.=~" (fun () -> candidate_match_func s re)
2171
2172 let (=~) s re =
2173 match_func s re
2174
2175
2176
2177
2178
2179 let string_match_substring re s =
2180 try let _i = Str.search_forward re s 0 in true
2181 with Not_found -> false
2182
2183 let _ =
2184 example(string_match_substring (Str.regexp "foo") "a foo b")
2185 let _ =
2186 example(string_match_substring (Str.regexp "\\bfoo\\b") "a foo b")
2187 let _ =
2188 example(string_match_substring (Str.regexp "\\bfoo\\b") "a\n\nfoo b")
2189 let _ =
2190 example(string_match_substring (Str.regexp "\\bfoo_bar\\b") "a\n\nfoo_bar b")
2191 (* does not work :(
2192 let _ =
2193 example(string_match_substring (Str.regexp "\\bfoo_bar2\\b") "a\n\nfoo_bar2 b")
2194 *)
2195
2196
2197
2198 let (regexp_match: string -> string -> string) = fun s re ->
2199 assert(s =~ re);
2200 Str.matched_group 1 s
2201
2202 (* beurk, side effect code, but hey, it is convenient *)
2203 (* now in prelude
2204 * let (matched: int -> string -> string) = fun i s ->
2205 * Str.matched_group i s
2206 *
2207 * let matched1 = fun s -> matched 1 s
2208 * let matched2 = fun s -> (matched 1 s, matched 2 s)
2209 * let matched3 = fun s -> (matched 1 s, matched 2 s, matched 3 s)
2210 * let matched4 = fun s -> (matched 1 s, matched 2 s, matched 3 s, matched 4 s)
2211 * let matched5 = fun s -> (matched 1 s, matched 2 s, matched 3 s, matched 4 s, matched 5 s)
2212 * let matched6 = fun s -> (matched 1 s, matched 2 s, matched 3 s, matched 4 s, matched 5 s, matched 6 s)
2213 *)
2214
2215
2216
2217 let split sep s = Str.split (Str.regexp sep) s
2218 let _ = example (split "/" "" =*= [])
2219 let join sep xs = String.concat sep xs
2220 let _ = example (join "/" ["toto"; "titi"; "tata"] =$= "toto/titi/tata")
2221 (*
2222 let rec join str = function
2223 | [] -> ""
2224 | [x] -> x
2225 | x::xs -> x ^ str ^ (join str xs)
2226 *)
2227
2228
2229 let (split_list_regexp: string -> string list -> (string * string list) list) =
2230 fun re xs ->
2231 let rec split_lr_aux (heading, accu) = function
2232 | [] -> [(heading, List.rev accu)]
2233 | x::xs ->
2234 if x =~ re
2235 then (heading, List.rev accu)::split_lr_aux (x, []) xs
2236 else split_lr_aux (heading, x::accu) xs
2237 in
2238 split_lr_aux ("__noheading__", []) xs
2239 +> (fun xs -> if (List.hd xs) =*= ("__noheading__",[]) then List.tl xs else xs)
2240
2241
2242
2243 let regexp_alpha = Str.regexp
2244 "^[a-zA-Z_][A-Za-z_0-9]*$"
2245
2246
2247 let all_match re s =
2248 let regexp = Str.regexp re in
2249 let res = ref [] in
2250 let _ = Str.global_substitute regexp (fun _s ->
2251 let substr = Str.matched_string s in
2252 assert(substr ==~ regexp); (* @Effect: also use it's side effect *)
2253 let paren_matched = matched1 substr in
2254 push2 paren_matched res;
2255 "" (* @Dummy *)
2256 ) s in
2257 List.rev !res
2258
2259 let _ = example (all_match "\\(@[A-Za-z]+\\)" "ca va @Et toi @Comment"
2260 =*= ["@Et";"@Comment"])
2261
2262
2263 let global_replace_regexp re f_on_substr s =
2264 let regexp = Str.regexp re in
2265 Str.global_substitute regexp (fun _wholestr ->
2266
2267 let substr = Str.matched_string s in
2268 f_on_substr substr
2269 ) s
2270
2271
2272 let regexp_word_str =
2273 "\\([a-zA-Z_][A-Za-z_0-9]*\\)"
2274 let regexp_word = Str.regexp regexp_word_str
2275
2276 let regular_words s =
2277 all_match regexp_word_str s
2278
2279 let contain_regular_word s =
2280 let xs = regular_words s in
2281 List.length xs >= 1
2282
2283
2284
2285 (*****************************************************************************)
2286 (* Strings *)
2287 (*****************************************************************************)
2288
2289 let slength = String.length
2290 let concat = String.concat
2291
2292 (* ruby *)
2293 let i_to_s = string_of_int
2294 let s_to_i = int_of_string
2295
2296
2297 (* strings take space in memory. Better when can share the space used by
2298 similar strings *)
2299 let _shareds = Hashtbl.create 100
2300 let (shared_string: string -> string) = fun s ->
2301 try Hashtbl.find _shareds s
2302 with Not_found -> (Hashtbl.add _shareds s s; s)
2303
2304 let chop = function
2305 | "" -> ""
2306 | s -> String.sub s 0 (String.length s - 1)
2307
2308
2309 let chop_dirsymbol = function
2310 | s when s =~ "\\(.*\\)/$" -> matched1 s
2311 | s -> s
2312
2313
2314 let (<!!>) s (i,j) =
2315 String.sub s i (if j < 0 then String.length s - i + j + 1 else j - i)
2316 (* let _ = example ( "tototati"<!!>(3,-2) = "otat" ) *)
2317
2318 let (<!>) s i = String.get s i
2319
2320 (* pixel *)
2321 let rec split_on_char c s =
2322 try
2323 let sp = String.index s c in
2324 String.sub s 0 sp ::
2325 split_on_char c (String.sub s (sp+1) (String.length s - sp - 1))
2326 with Not_found -> [s]
2327
2328
2329 let lowercase = String.lowercase
2330
2331 let quote s = "\"" ^ s ^ "\""
2332
2333 (* easier to have this to be passed as hof, because ocaml dont have
2334 * haskell "section" operators
2335 *)
2336 let null_string s =
2337 s =$= ""
2338
2339 let is_blank_string s =
2340 s =~ "^\\([ \t]\\)*$"
2341
2342 (* src: lablgtk2/examples/entrycompletion.ml *)
2343 let is_string_prefix s1 s2 =
2344 (String.length s1 <= String.length s2) &&
2345 (String.sub s2 0 (String.length s1) =$= s1)
2346
2347 let plural i s =
2348 if i =|= 1
2349 then Printf.sprintf "%d %s" i s
2350 else Printf.sprintf "%d %ss" i s
2351
2352 let showCodeHex xs = List.iter (fun i -> printf "%02x" i) xs
2353
2354 let take_string n s =
2355 String.sub s 0 (n-1)
2356
2357 let take_string_safe n s =
2358 if n > String.length s
2359 then s
2360 else take_string n s
2361
2362
2363
2364 (* used by LFS *)
2365 let size_mo_ko i =
2366 let ko = (i / 1024) mod 1024 in
2367 let mo = (i / 1024) / 1024 in
2368 (if mo > 0
2369 then sprintf "%dMo%dKo" mo ko
2370 else sprintf "%dKo" ko
2371 )
2372
2373 let size_ko i =
2374 let ko = i / 1024 in
2375 sprintf "%dKo" ko
2376
2377
2378
2379
2380
2381
2382 (* done in summer 2007 for julia
2383 * Reference: P216 of gusfeld book
2384 * For two strings S1 and S2, D(i,j) is defined to be the edit distance of S1[1..i] to S2[1..j]
2385 * So edit distance of S1 (of length n) and S2 (of length m) is D(n,m)
2386 *
2387 * Dynamic programming technique
2388 * base:
2389 * D(i,0) = i for all i (cos to go from S1[1..i] to 0 characteres of S2 you have to delete all characters from S1[1..i]
2390 * D(0,j) = j for all j (cos j characters must be inserted)
2391 * recurrence:
2392 * D(i,j) = min([D(i-1, j)+1, D(i, j - 1 + 1), D(i-1, j-1) + t(i,j)])
2393 * where t(i,j) is equal to 1 if S1(i) != S2(j) and 0 if equal
2394 * intuition = there is 4 possible action = deletion, insertion, substitution, or match
2395 * so Lemma =
2396 *
2397 * D(i,j) must be one of the three
2398 * D(i, j-1) + 1
2399 * D(i-1, j)+1
2400 * D(i-1, j-1) +
2401 * t(i,j)
2402 *
2403 *
2404 *)
2405 let matrix_distance s1 s2 =
2406 let n = (String.length s1) in
2407 let m = (String.length s2) in
2408 let mat = Array.make_matrix (n+1) (m+1) 0 in
2409 let t i j =
2410 if String.get s1 (i-1) =<= String.get s2 (j-1)
2411 then 0
2412 else 1
2413 in
2414 let min3 a b c = min (min a b) c in
2415
2416 begin
2417 for i = 0 to n do
2418 mat.(i).(0) <- i
2419 done;
2420 for j = 0 to m do
2421 mat.(0).(j) <- j;
2422 done;
2423 for i = 1 to n do
2424 for j = 1 to m do
2425 mat.(i).(j) <-
2426 min3 (mat.(i).(j-1) + 1) (mat.(i-1).(j) + 1) (mat.(i-1).(j-1) + t i j)
2427 done
2428 done;
2429 mat
2430 end
2431 let edit_distance s1 s2 =
2432 (matrix_distance s1 s2).(String.length s1).(String.length s2)
2433
2434
2435 let test = edit_distance "vintner" "writers"
2436 let _ = assert (edit_distance "winter" "winter" =|= 0)
2437 let _ = assert (edit_distance "vintner" "writers" =|= 5)
2438
2439
2440 (*****************************************************************************)
2441 (* Filenames *)
2442 (*****************************************************************************)
2443
2444 let dirname = Filename.dirname
2445 let basename = Filename.basename
2446
2447 type filename = string (* TODO could check that exist :) type sux *)
2448 (* with sexp *)
2449 type dirname = string (* TODO could check that exist :) type sux *)
2450 (* with sexp *)
2451
2452 module BasicType = struct
2453 type filename = string
2454 end
2455
2456
2457 let (filesuffix: filename -> string) = fun s ->
2458 (try regexp_match s ".+\\.\\([a-zA-Z0-9_]+\\)$" with _ -> "NOEXT")
2459 let (fileprefix: filename -> string) = fun s ->
2460 (try regexp_match s "\\(.+\\)\\.\\([a-zA-Z0-9_]+\\)?$" with _ -> s)
2461
2462 let _ = example (filesuffix "toto.c" =$= "c")
2463 let _ = example (fileprefix "toto.c" =$= "toto")
2464
2465 (*
2466 assert (s = fileprefix s ^ filesuffix s)
2467
2468 let withoutExtension s = global_replace (regexp "\\..*$") "" s
2469 let () = example "without"
2470 (withoutExtension "toto.s.toto" = "toto")
2471 *)
2472
2473 let adjust_ext_if_needed filename ext =
2474 if String.get ext 0 <> '.'
2475 then failwith "I need an extension such as .c not just c";
2476
2477 if not (filename =~ (".*\\" ^ ext))
2478 then filename ^ ext
2479 else filename
2480
2481
2482
2483 let db_of_filename file =
2484 dirname file, basename file
2485
2486 let filename_of_db (basedir, file) =
2487 Filename.concat basedir file
2488
2489
2490
2491 let dbe_of_filename file =
2492 (* raise Invalid_argument if no ext, so safe to use later the unsafe
2493 * fileprefix and filesuffix functions.
2494 *)
2495 ignore(Filename.chop_extension file);
2496 Filename.dirname file,
2497 Filename.basename file +> fileprefix,
2498 Filename.basename file +> filesuffix
2499
2500 let filename_of_dbe (dir, base, ext) =
2501 Filename.concat dir (base ^ "." ^ ext)
2502
2503
2504 let dbe_of_filename_safe file =
2505 try Left (dbe_of_filename file)
2506 with Invalid_argument _ ->
2507 Right (Filename.dirname file, Filename.basename file)
2508
2509
2510 let dbe_of_filename_nodot file =
2511 let (d,b,e) = dbe_of_filename file in
2512 let d = if d =$= "." then "" else d in
2513 d,b,e
2514
2515
2516
2517
2518
2519 let replace_ext file oldext newext =
2520 let (d,b,e) = dbe_of_filename file in
2521 assert(e =$= oldext);
2522 filename_of_dbe (d,b,newext)
2523
2524
2525 let normalize_path file =
2526 let (dir, filename) = Filename.dirname file, Filename.basename file in
2527 let xs = split "/" dir in
2528 let rec aux acc = function
2529 | [] -> List.rev acc
2530 | x::xs ->
2531 (match x with
2532 | "." -> aux acc xs
2533 | ".." -> aux (List.tl acc) xs
2534 | x -> aux (x::acc) xs
2535 )
2536 in
2537 let xs' = aux [] xs in
2538 Filename.concat (join "/" xs') filename
2539
2540
2541
2542 (*
2543 let relative_to_absolute s =
2544 if Filename.is_relative s
2545 then
2546 begin
2547 let old = Sys.getcwd () in
2548 Sys.chdir s;
2549 let current = Sys.getcwd () in
2550 Sys.chdir old;
2551 s
2552 end
2553 else s
2554 *)
2555
2556 let relative_to_absolute s =
2557 if Filename.is_relative s
2558 then Sys.getcwd () ^ "/" ^ s
2559 else s
2560
2561 let is_relative s = Filename.is_relative s
2562 let is_absolute s = not (is_relative s)
2563
2564
2565 (* @Pre: prj_path must not contain regexp symbol *)
2566 let filename_without_leading_path prj_path s =
2567 let prj_path = chop_dirsymbol prj_path in
2568 if s =~ ("^" ^ prj_path ^ "/\\(.*\\)$")
2569 then matched1 s
2570 else
2571 failwith
2572 (spf "cant find filename_without_project_path: %s %s" prj_path s)
2573
2574
2575 (*****************************************************************************)
2576 (* i18n *)
2577 (*****************************************************************************)
2578 type langage =
2579 | English
2580 | Francais
2581 | Deutsch
2582
2583 (* gettext ? *)
2584
2585
2586 (*****************************************************************************)
2587 (* Dates *)
2588 (*****************************************************************************)
2589
2590 (* maybe I should use ocamlcalendar, but I don't like all those functors ... *)
2591
2592 type month =
2593 | Jan | Feb | Mar | Apr | May | Jun
2594 | Jul | Aug | Sep | Oct | Nov | Dec
2595 type year = Year of int
2596 type day = Day of int
2597 type wday = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday
2598
2599 type date_dmy = DMY of day * month * year
2600
2601 type hour = Hour of int
2602 type minute = Min of int
2603 type second = Sec of int
2604
2605 type time_hms = HMS of hour * minute * second
2606
2607 type full_date = date_dmy * time_hms
2608
2609
2610 (* intervalle *)
2611 type days = Days of int
2612
2613 type time_dmy = TimeDMY of day * month * year
2614
2615
2616 type float_time = float
2617
2618
2619
2620 let check_date_dmy (DMY (day, month, year)) =
2621 raise Todo
2622
2623 let check_time_dmy (TimeDMY (day, month, year)) =
2624 raise Todo
2625
2626 let check_time_hms (HMS (x,y,a)) =
2627 raise Todo
2628
2629
2630
2631 (* ---------------------------------------------------------------------- *)
2632
2633 (* older code *)
2634 let int_to_month i =
2635 assert (i <= 12 && i >= 1);
2636 match i with
2637
2638 | 1 -> "Jan"
2639 | 2 -> "Feb"
2640 | 3 -> "Mar"
2641 | 4 -> "Apr"
2642 | 5 -> "May"
2643 | 6 -> "Jun"
2644 | 7 -> "Jul"
2645 | 8 -> "Aug"
2646 | 9 -> "Sep"
2647 | 10 -> "Oct"
2648 | 11 -> "Nov"
2649 | 12 -> "Dec"
2650 (*
2651 | 1 -> "January"
2652 | 2 -> "February"
2653 | 3 -> "March"
2654 | 4 -> "April"
2655 | 5 -> "May"
2656 | 6 -> "June"
2657 | 7 -> "July"
2658 | 8 -> "August"
2659 | 9 -> "September"
2660 | 10 -> "October"
2661 | 11 -> "November"
2662 | 12 -> "December"
2663 *)
2664 | _ -> raise Impossible
2665
2666
2667 let month_info = [
2668 1 , Jan, "Jan", "January", 31;
2669 2 , Feb, "Feb", "February", 28;
2670 3 , Mar, "Mar", "March", 31;
2671 4 , Apr, "Apr", "April", 30;
2672 5 , May, "May", "May", 31;
2673 6 , Jun, "Jun", "June", 30;
2674 7 , Jul, "Jul", "July", 31;
2675 8 , Aug, "Aug", "August", 31;
2676 9 , Sep, "Sep", "September", 30;
2677 10 , Oct, "Oct", "October", 31;
2678 11 , Nov, "Nov", "November", 30;
2679 12 , Dec, "Dec", "December", 31;
2680 ]
2681
2682 let week_day_info = [
2683 0 , Sunday , "Sun" , "Dim" , "Sunday";
2684 1 , Monday , "Mon" , "Lun" , "Monday";
2685 2 , Tuesday , "Tue" , "Mar" , "Tuesday";
2686 3 , Wednesday , "Wed" , "Mer" , "Wednesday";
2687 4 , Thursday , "Thu" ,"Jeu" ,"Thursday";
2688 5 , Friday , "Fri" , "Ven" , "Friday";
2689 6 , Saturday , "Sat" ,"Sam" , "Saturday";
2690 ]
2691
2692 let i_to_month_h =
2693 month_info +> List.map (fun (i,month,monthstr,mlong,days) -> i, month)
2694 let s_to_month_h =
2695 month_info +> List.map (fun (i,month,monthstr,mlong,days) -> monthstr, month)
2696 let slong_to_month_h =
2697 month_info +> List.map (fun (i,month,monthstr,mlong,days) -> mlong, month)
2698 let month_to_s_h =
2699 month_info +> List.map (fun (i,month,monthstr,mlong,days) -> month, monthstr)
2700 let month_to_i_h =
2701 month_info +> List.map (fun (i,month,monthstr,mlong,days) -> month, i)
2702
2703 let i_to_wday_h =
2704 week_day_info +> List.map (fun (i,day,dayen,dayfr,daylong) -> i, day)
2705 let wday_to_en_h =
2706 week_day_info +> List.map (fun (i,day,dayen,dayfr,daylong) -> day, dayen)
2707 let wday_to_fr_h =
2708 week_day_info +> List.map (fun (i,day,dayen,dayfr,daylong) -> day, dayfr)
2709
2710 let month_of_string s =
2711 List.assoc s s_to_month_h
2712
2713 let month_of_string_long s =
2714 List.assoc s slong_to_month_h
2715
2716 let string_of_month s =
2717 List.assoc s month_to_s_h
2718
2719 let month_of_int i =
2720 List.assoc i i_to_month_h
2721
2722 let int_of_month m =
2723 List.assoc m month_to_i_h
2724
2725
2726 let wday_of_int i =
2727 List.assoc i i_to_wday_h
2728
2729 let string_en_of_wday wday =
2730 List.assoc wday wday_to_en_h
2731 let string_fr_of_wday wday =
2732 List.assoc wday wday_to_fr_h
2733
2734 (* ---------------------------------------------------------------------- *)
2735
2736 let wday_str_of_int ~langage i =
2737 let wday = wday_of_int i in
2738 match langage with
2739 | English -> string_en_of_wday wday
2740 | Francais -> string_fr_of_wday wday
2741 | Deutsch -> raise Todo
2742
2743
2744
2745 let string_of_date_dmy (DMY (Day n, month, Year y)) =
2746 (spf "%02d-%s-%d" n (string_of_month month) y)
2747
2748
2749 let string_of_unix_time ?(langage=English) tm =
2750 let y = tm.Unix.tm_year + 1900 in
2751 let mon = string_of_month (month_of_int (tm.Unix.tm_mon + 1)) in
2752 let d = tm.Unix.tm_mday in
2753 let h = tm.Unix.tm_hour in
2754 let min = tm.Unix.tm_min in
2755 let s = tm.Unix.tm_sec in
2756
2757 let wday = wday_str_of_int ~langage tm.Unix.tm_wday in
2758
2759 spf "%02d/%03s/%04d (%s) %02d:%02d:%02d" d mon y wday h min s
2760
2761 (* ex: 21/Jul/2008 (Lun) 21:25:12 *)
2762 let unix_time_of_string s =
2763 if s =~
2764 ("\\([0-9][0-9]\\)/\\(...\\)/\\([0-9][0-9][0-9][0-9]\\) " ^
2765 "\\(.*\\) \\([0-9][0-9]\\):\\([0-9][0-9]\\):\\([0-9][0-9]\\)")
2766 then
2767 let (sday, smonth, syear, _sday, shour, smin, ssec) = matched7 s in
2768
2769 let y = s_to_i syear - 1900 in
2770 let mon =
2771 smonth +> month_of_string +> int_of_month +> (fun i -> i -1)
2772 in
2773
2774 let tm = Unix.localtime (Unix.time ()) in
2775 { tm with
2776 Unix.tm_year = y;
2777 Unix.tm_mon = mon;
2778 Unix.tm_mday = s_to_i sday;
2779 Unix.tm_hour = s_to_i shour;
2780 Unix.tm_min = s_to_i smin;
2781 Unix.tm_sec = s_to_i ssec;
2782 }
2783 else failwith ("unix_time_of_string: " ^ s)
2784
2785
2786
2787 let short_string_of_unix_time ?(langage=English) tm =
2788 let y = tm.Unix.tm_year + 1900 in
2789 let mon = string_of_month (month_of_int (tm.Unix.tm_mon + 1)) in
2790 let d = tm.Unix.tm_mday in
2791 let _h = tm.Unix.tm_hour in
2792 let _min = tm.Unix.tm_min in
2793 let _s = tm.Unix.tm_sec in
2794
2795 let wday = wday_str_of_int ~langage tm.Unix.tm_wday in
2796
2797 spf "%02d/%03s/%04d (%s)" d mon y wday
2798
2799
2800 let string_of_unix_time_lfs time =
2801 spf "%02d--%s--%d"
2802 time.Unix.tm_mday
2803 (int_to_month (time.Unix.tm_mon + 1))
2804 (time.Unix.tm_year + 1900)
2805
2806
2807 (* ---------------------------------------------------------------------- *)
2808 let string_of_floattime ?langage i =
2809 let tm = Unix.localtime i in
2810 string_of_unix_time ?langage tm
2811
2812 let short_string_of_floattime ?langage i =
2813 let tm = Unix.localtime i in
2814 short_string_of_unix_time ?langage tm
2815
2816 let floattime_of_string s =
2817 let tm = unix_time_of_string s in
2818 let (sec,_tm) = Unix.mktime tm in
2819 sec
2820
2821
2822 (* ---------------------------------------------------------------------- *)
2823 let days_in_week_of_day day =
2824 let tm = Unix.localtime day in
2825
2826 let wday = tm.Unix.tm_wday in
2827 let wday = if wday =|= 0 then 6 else wday -1 in
2828
2829 let mday = tm.Unix.tm_mday in
2830
2831 let start_d = mday - wday in
2832 let end_d = mday + (6 - wday) in
2833
2834 enum start_d end_d +> List.map (fun mday ->
2835 Unix.mktime {tm with Unix.tm_mday = mday} +> fst
2836 )
2837
2838 let first_day_in_week_of_day day =
2839 List.hd (days_in_week_of_day day)
2840
2841 let last_day_in_week_of_day day =
2842 last (days_in_week_of_day day)
2843
2844
2845 (* ---------------------------------------------------------------------- *)
2846
2847 (* (modified) copy paste from ocamlcalendar/src/date.ml *)
2848 let days_month =
2849 [| 0; 31; 59; 90; 120; 151; 181; 212; 243; 273; 304; 334(*; 365*) |]
2850
2851
2852 let rough_days_since_jesus (DMY (Day nday, month, Year year)) =
2853 let n =
2854 nday +
2855 (days_month.(int_of_month month -1)) +
2856 year * 365
2857 in
2858 Days n
2859
2860
2861
2862 let is_more_recent d1 d2 =
2863 let (Days n1) = rough_days_since_jesus d1 in
2864 let (Days n2) = rough_days_since_jesus d2 in
2865 (n1 > n2)
2866
2867
2868 let max_dmy d1 d2 =
2869 if is_more_recent d1 d2
2870 then d1
2871 else d2
2872
2873 let min_dmy d1 d2 =
2874 if is_more_recent d1 d2
2875 then d2
2876 else d1
2877
2878
2879 let maximum_dmy ds =
2880 foldl1 max_dmy ds
2881
2882 let minimum_dmy ds =
2883 foldl1 min_dmy ds
2884
2885
2886
2887 let rough_days_between_dates d1 d2 =
2888 let (Days n1) = rough_days_since_jesus d1 in
2889 let (Days n2) = rough_days_since_jesus d2 in
2890 Days (n2 - n1)
2891
2892 let _ = example
2893 (rough_days_between_dates
2894 (DMY (Day 7, Jan, Year 1977))
2895 (DMY (Day 13, Jan, Year 1977)) =*= Days 6)
2896
2897 (* because of rough days, it is a bit buggy, here it should return 1 *)
2898 (*
2899 let _ = assert_equal
2900 (rough_days_between_dates
2901 (DMY (Day 29, Feb, Year 1977))
2902 (DMY (Day 1, Mar , Year 1977)))
2903 (Days 1)
2904 *)
2905
2906
2907 (* from julia, in gitsort.ml *)
2908
2909 (*
2910 let antimonths =
2911 [(1,31);(2,28);(3,31);(4,30);(5,31); (6,6);(7,7);(8,31);(9,30);(10,31);
2912 (11,30);(12,31);(0,31)]
2913
2914 let normalize (year,month,day,hour,minute,second) =
2915 if hour < 0
2916 then
2917 let (day,hour) = (day - 1,hour + 24) in
2918 if day = 0
2919 then
2920 let month = month - 1 in
2921 let day = List.assoc month antimonths in
2922 let day =
2923 if month = 2 && year / 4 * 4 = year && not (year / 100 * 100 = year)
2924 then 29
2925 else day in
2926 if month = 0
2927 then (year-1,12,day,hour,minute,second)
2928 else (year,month,day,hour,minute,second)
2929 else (year,month,day,hour,minute,second)
2930 else (year,month,day,hour,minute,second)
2931
2932 *)
2933
2934
2935 let mk_date_dmy day month year =
2936 let date = DMY (Day day, month_of_int month, Year year) in
2937 (* check_date_dmy date *)
2938 date
2939
2940
2941 (* ---------------------------------------------------------------------- *)
2942 (* conversion to unix.tm *)
2943
2944 let dmy_to_unixtime (DMY (Day n, month, Year year)) =
2945 let tm = {
2946 Unix.tm_sec = 0; (** Seconds 0..60 *)
2947 tm_min = 0; (** Minutes 0..59 *)
2948 tm_hour = 12; (** Hours 0..23 *)
2949 tm_mday = n; (** Day of month 1..31 *)
2950 tm_mon = (int_of_month month -1); (** Month of year 0..11 *)
2951 tm_year = year - 1900; (** Year - 1900 *)
2952 tm_wday = 0; (** Day of week (Sunday is 0) *)
2953 tm_yday = 0; (** Day of year 0..365 *)
2954 tm_isdst = false; (** Daylight time savings in effect *)
2955 } in
2956 Unix.mktime tm
2957
2958 let unixtime_to_dmy tm =
2959 let n = tm.Unix.tm_mday in
2960 let month = month_of_int (tm.Unix.tm_mon + 1) in
2961 let year = tm.Unix.tm_year + 1900 in
2962
2963 DMY (Day n, month, Year year)
2964
2965
2966 let unixtime_to_floattime tm =
2967 Unix.mktime tm +> fst
2968
2969 let floattime_to_unixtime sec =
2970 Unix.localtime sec
2971
2972
2973 let sec_to_days sec =
2974 let minfactor = 60 in
2975 let hourfactor = 60 * 60 in
2976 let dayfactor = 60 * 60 * 24 in
2977
2978 let days = sec / dayfactor in
2979 let hours = (sec mod dayfactor) / hourfactor in
2980 let mins = (sec mod hourfactor) / minfactor in
2981 let sec = (sec mod 60) in
2982 (* old: Printf.sprintf "%d days, %d hours, %d minutes" days hours mins *)
2983 (if days > 0 then plural days "day" ^ " " else "") ^
2984 (if hours > 0 then plural hours "hour" ^ " " else "") ^
2985 (if mins > 0 then plural mins "min" ^ " " else "") ^
2986 (spf "%dsec" sec)
2987
2988 let sec_to_hours sec =
2989 let minfactor = 60 in
2990 let hourfactor = 60 * 60 in
2991
2992 let hours = sec / hourfactor in
2993 let mins = (sec mod hourfactor) / minfactor in
2994 let sec = (sec mod 60) in
2995 (* old: Printf.sprintf "%d days, %d hours, %d minutes" days hours mins *)
2996 (if hours > 0 then plural hours "hour" ^ " " else "") ^
2997 (if mins > 0 then plural mins "min" ^ " " else "") ^
2998 (spf "%dsec" sec)
2999
3000
3001
3002 let test_date_1 () =
3003 let date = DMY (Day 17, Sep, Year 1991) in
3004 let float, tm = dmy_to_unixtime date in
3005 pr2 (spf "date: %.0f" float);
3006 ()
3007
3008
3009 (* src: ferre in logfun/.../date.ml *)
3010
3011 let day_secs : float = 86400.
3012
3013 let today : unit -> float = fun () -> (Unix.time () )
3014 let yesterday : unit -> float = fun () -> (Unix.time () -. day_secs)
3015 let tomorrow : unit -> float = fun () -> (Unix.time () +. day_secs)
3016
3017 let lastweek : unit -> float = fun () -> (Unix.time () -. (7.0 *. day_secs))
3018 let lastmonth : unit -> float = fun () -> (Unix.time () -. (30.0 *. day_secs))
3019
3020
3021 let week_before : float_time -> float_time = fun d ->
3022 (d -. (7.0 *. day_secs))
3023 let month_before : float_time -> float_time = fun d ->
3024 (d -. (30.0 *. day_secs))
3025
3026 let week_after : float_time -> float_time = fun d ->
3027 (d +. (7.0 *. day_secs))
3028
3029
3030
3031 (*****************************************************************************)
3032 (* Lines/words/strings *)
3033 (*****************************************************************************)
3034
3035 (* now in prelude:
3036 * let (list_of_string: string -> char list) = fun s ->
3037 * (enum 0 ((String.length s) - 1) +> List.map (String.get s))
3038 *)
3039
3040 let _ = example (list_of_string "abcd" =*= ['a';'b';'c';'d'])
3041
3042 (*
3043 let rec (list_of_stream: ('a Stream.t) -> 'a list) =
3044 parser
3045 | [< 'c ; stream >] -> c :: list_of_stream stream
3046 | [<>] -> []
3047
3048 let (list_of_string: string -> char list) =
3049 Stream.of_string $ list_of_stream
3050 *)
3051
3052 (* now in prelude:
3053 * let (lines: string -> string list) = fun s -> ...
3054 *)
3055
3056 let (lines_with_nl: string -> string list) = fun s ->
3057 let rec lines_aux = function
3058 | [] -> []
3059 | [x] -> if x =$= "" then [] else [x ^ "\n"] (* old: [x] *)
3060 | x::xs ->
3061 let e = x ^ "\n" in
3062 e::lines_aux xs
3063 in
3064 (time_func (fun () -> Str.split_delim (Str.regexp "\n") s)) +> lines_aux
3065
3066 (* in fact better make it return always complete lines, simplify *)
3067 (* Str.split, but lines "\n1\n2\n" dont return the \n and forget the first \n => split_delim better than split *)
3068 (* +> List.map (fun s -> s ^ "\n") but add an \n even at the end => lines_aux *)
3069 (* old: slow
3070 let chars = list_of_string s in
3071 chars +> List.fold_left (fun (acc, lines) char ->
3072 let newacc = acc ^ (String.make 1 char) in
3073 if char = '\n'
3074 then ("", newacc::lines)
3075 else (newacc, lines)
3076 ) ("", [])
3077 +> (fun (s, lines) -> List.rev (s::lines))
3078 *)
3079
3080 (* CHECK: unlines (lines x) = x *)
3081 let (unlines: string list -> string) = fun s ->
3082 (String.concat "\n" s) ^ "\n"
3083 let (words: string -> string list) = fun s ->
3084 Str.split (Str.regexp "[ \t()\";]+") s
3085 let (unwords: string list -> string) = fun s ->
3086 String.concat "" s
3087
3088 let (split_space: string -> string list) = fun s ->
3089 Str.split (Str.regexp "[ \t\n]+") s
3090
3091
3092 (* todo opti ? *)
3093 let nblines s =
3094 lines s +> List.length
3095 let _ = example (nblines "" =|= 0)
3096 let _ = example (nblines "toto" =|= 1)
3097 let _ = example (nblines "toto\n" =|= 1)
3098 let _ = example (nblines "toto\ntata" =|= 2)
3099 let _ = example (nblines "toto\ntata\n" =|= 2)
3100
3101 (*****************************************************************************)
3102 (* Process/Files *)
3103 (*****************************************************************************)
3104 let cat_orig file =
3105 let chan = open_in file in
3106 let rec cat_orig_aux () =
3107 try
3108 (* cant do input_line chan::aux() cos ocaml eval from right to left ! *)
3109 let l = input_line chan in
3110 l :: cat_orig_aux ()
3111 with End_of_file -> [] in
3112 cat_orig_aux()
3113
3114 (* tail recursive efficient version *)
3115 let cat file =
3116 let chan = open_in file in
3117 let rec cat_aux acc () =
3118 (* cant do input_line chan::aux() cos ocaml eval from right to left ! *)
3119 let (b, l) = try (true, input_line chan) with End_of_file -> (false, "") in
3120 if b
3121 then cat_aux (l::acc) ()
3122 else acc
3123 in
3124 cat_aux [] () +> List.rev +> (fun x -> close_in chan; x)
3125
3126 let cat_array file =
3127 (""::cat file) +> Array.of_list
3128
3129
3130 let interpolate str =
3131 begin
3132 command2 ("printf \"%s\\n\" " ^ str ^ ">/tmp/caml");
3133 cat "/tmp/caml"
3134 end
3135
3136 (* could do a print_string but printf dont like print_string *)
3137 let echo s = printf "%s" s; flush stdout; s
3138
3139 let usleep s = for i = 1 to s do () done
3140
3141 let sleep_little () =
3142 (*old: *)
3143 Unix.sleep 1
3144 (*ignore(Sys.command ("usleep " ^ !_sleep_time))*)
3145
3146
3147 (* now in prelude:
3148 * let command2 s = ignore(Sys.command s)
3149 *)
3150
3151 let do_in_fork f =
3152 let pid = Unix.fork () in
3153 if pid =|= 0
3154 then
3155 begin
3156 (* Unix.setsid(); *)
3157 Sys.set_signal Sys.sigint (Sys.Signal_handle (fun _ ->
3158 pr2 "being killed";
3159 Unix.kill 0 Sys.sigkill;
3160 ));
3161 f();
3162 exit 0;
3163 end
3164 else pid
3165
3166
3167 let process_output_to_list2 = fun command ->
3168 let chan = Unix.open_process_in command in
3169 let res = ref ([] : string list) in
3170 let rec process_otl_aux () =
3171 let e = input_line chan in
3172 res := e::!res;
3173 process_otl_aux() in
3174 try process_otl_aux ()
3175 with End_of_file ->
3176 let stat = Unix.close_process_in chan in (List.rev !res,stat)
3177 let cmd_to_list command =
3178 let (l,_) = process_output_to_list2 command in l
3179 let process_output_to_list = cmd_to_list
3180 let cmd_to_list_and_status = process_output_to_list2
3181
3182 (* now in prelude:
3183 * let command2 s = ignore(Sys.command s)
3184 *)
3185
3186
3187 let _batch_mode = ref false
3188 let command2_y_or_no cmd =
3189 if !_batch_mode then begin command2 cmd; true end
3190 else begin
3191
3192 pr2 (cmd ^ " [y/n] ?");
3193 match read_line () with
3194 | "y" | "yes" | "Y" -> command2 cmd; true
3195 | "n" | "no" | "N" -> false
3196 | _ -> failwith "answer by yes or no"
3197 end
3198
3199 let command2_y_or_no_exit_if_no cmd =
3200 let res = command2_y_or_no cmd in
3201 if res
3202 then ()
3203 else raise (UnixExit (1))
3204
3205
3206
3207
3208 let mkdir ?(mode=0o770) file =
3209 Unix.mkdir file mode
3210
3211 let read_file_orig file = cat file +> unlines
3212 let read_file file =
3213 let ic = open_in file in
3214 let size = in_channel_length ic in
3215 let buf = String.create size in
3216 really_input ic buf 0 size;
3217 close_in ic;
3218 buf
3219
3220
3221 let write_file ~file s =
3222 let chan = open_out file in
3223 (output_string chan s; close_out chan)
3224
3225 let filesize file =
3226 (Unix.stat file).Unix.st_size
3227
3228 let filemtime file =
3229 (Unix.stat file).Unix.st_mtime
3230
3231 (* opti? use wc -l ? *)
3232 let nblines_file file =
3233 cat file +> List.length
3234
3235 let lfile_exists filename =
3236 try
3237 (match (Unix.lstat filename).Unix.st_kind with
3238 | (Unix.S_REG | Unix.S_LNK) -> true
3239 | _ -> false
3240 )
3241 with
3242 Unix.Unix_error (Unix.ENOENT, _, _) -> false
3243 | Unix.Unix_error (Unix.ENOTDIR, _, _) -> false
3244 | Unix.Unix_error (error, _, fl) ->
3245 failwith
3246 (Printf.sprintf "unexpected error %s for file %s"
3247 (Unix.error_message error) fl)
3248
3249 let is_directory file =
3250 (Unix.stat file).Unix.st_kind =*= Unix.S_DIR
3251
3252
3253 (* src: from chailloux et al book *)
3254 let capsule_unix f args =
3255 try (f args)
3256 with Unix.Unix_error (e, fm, argm) ->
3257 log (Printf.sprintf "exn Unix_error: %s %s %s\n" (Unix.error_message e) fm argm)
3258
3259
3260 let (readdir_to_kind_list: string -> Unix.file_kind -> string list) =
3261 fun path kind ->
3262 Sys.readdir path
3263 +> Array.to_list
3264 +> List.filter (fun s ->
3265 try
3266 let stat = Unix.lstat (path ^ "/" ^ s) in
3267 stat.Unix.st_kind =*= kind
3268 with e ->
3269 pr2 ("EXN pb stating file: " ^ s);
3270 false
3271 )
3272
3273 let (readdir_to_dir_list: string -> string list) = fun path ->
3274 readdir_to_kind_list path Unix.S_DIR
3275
3276 let (readdir_to_file_list: string -> string list) = fun path ->
3277 readdir_to_kind_list path Unix.S_REG
3278
3279 let (readdir_to_link_list: string -> string list) = fun path ->
3280 readdir_to_kind_list path Unix.S_LNK
3281
3282
3283 let (readdir_to_dir_size_list: string -> (string * int) list) = fun path ->
3284 Sys.readdir path
3285 +> Array.to_list
3286 +> map_filter (fun s ->
3287 let stat = Unix.lstat (path ^ "/" ^ s) in
3288 if stat.Unix.st_kind =*= Unix.S_DIR
3289 then Some (s, stat.Unix.st_size)
3290 else None
3291 )
3292
3293 (* could be in control section too *)
3294
3295 (* Why a use_cache argument ? because sometimes want disable it but dont
3296 * want put the cache_computation funcall in comment, so just easier to
3297 * pass this extra option.
3298 *)
3299 let cache_computation2 ?(verbose=false) ?(use_cache=true) file ext_cache f =
3300 if not use_cache
3301 then f ()
3302 else begin
3303 if not (Sys.file_exists file)
3304 then failwith ("can't find: " ^ file);
3305 let file_cache = (file ^ ext_cache) in
3306 if Sys.file_exists file_cache &&
3307 filemtime file_cache >= filemtime file
3308 then begin
3309 if verbose then pr2 ("using cache: " ^ file_cache);
3310 get_value file_cache
3311 end
3312 else begin
3313 let res = f () in
3314 write_value res file_cache;
3315 res
3316 end
3317 end
3318 let cache_computation ?verbose ?use_cache a b c =
3319 profile_code "Common.cache_computation" (fun () ->
3320 cache_computation2 ?verbose ?use_cache a b c)
3321
3322
3323 let cache_computation_robust2
3324 file ext_cache
3325 (need_no_changed_files, need_no_changed_variables) ext_depend
3326 f =
3327 if not (Sys.file_exists file)
3328 then failwith ("can't find: " ^ file);
3329
3330 let file_cache = (file ^ ext_cache) in
3331 let dependencies_cache = (file ^ ext_depend) in
3332
3333 let dependencies =
3334 (* could do md5sum too *)
3335 ((file::need_no_changed_files) +> List.map (fun f -> f, filemtime f),
3336 need_no_changed_variables)
3337 in
3338
3339 if Sys.file_exists dependencies_cache &&
3340 get_value dependencies_cache =*= dependencies
3341 then get_value file_cache
3342 else begin
3343 pr2 ("cache computation recompute " ^ file);
3344 let res = f () in
3345 write_value dependencies dependencies_cache;
3346 write_value res file_cache;
3347 res
3348 end
3349
3350 let cache_computation_robust a b c d e =
3351 profile_code "Common.cache_computation_robust" (fun () ->
3352 cache_computation_robust2 a b c d e)
3353
3354
3355
3356
3357 (* dont forget that cmd_to_list call bash and so pattern may contain
3358 * '*' symbols that will be expanded, so can do glob "*.c"
3359 *)
3360 let glob pattern =
3361 cmd_to_list ("ls -1 " ^ pattern)
3362
3363
3364 (* update: have added the -type f, so normally need less the sanity_check_xxx
3365 * function below *)
3366 let files_of_dir_or_files ext xs =
3367 xs +> List.map (fun x ->
3368 if is_directory x
3369 then cmd_to_list ("find " ^ x ^" -noleaf -type f -name \"*." ^ext^"\"")
3370 else [x]
3371 ) +> List.concat
3372
3373
3374 let files_of_dir_or_files_no_vcs ext xs =
3375 xs +> List.map (fun x ->
3376 if is_directory x
3377 then
3378 cmd_to_list
3379 ("find " ^ x ^" -noleaf -type f -name \"*." ^ext^"\"" ^
3380 "| grep -v /.hg/ |grep -v /CVS/ | grep -v /.git/ |grep -v /_darcs/"
3381 )
3382 else [x]
3383 ) +> List.concat
3384
3385
3386 let files_of_dir_or_files_no_vcs_post_filter regex xs =
3387 xs +> List.map (fun x ->
3388 if is_directory x
3389 then
3390 cmd_to_list
3391 ("find " ^ x ^
3392 " -noleaf -type f | grep -v /.hg/ |grep -v /CVS/ | grep -v /.git/ |grep -v /_darcs/"
3393 )
3394 +> List.filter (fun s -> s =~ regex)
3395 else [x]
3396 ) +> List.concat
3397
3398
3399 let sanity_check_files_and_adjust ext files =
3400 let files = files +> List.filter (fun file ->
3401 if not (file =~ (".*\\."^ext))
3402 then begin
3403 pr2 ("warning: seems not a ."^ext^" file");
3404 false
3405 end
3406 else
3407 if is_directory file
3408 then begin
3409 pr2 (spf "warning: %s is a directory" file);
3410 false
3411 end
3412 else true
3413 ) in
3414 files
3415
3416
3417
3418
3419 (* taken from mlfuse, the predecessor of ocamlfuse *)
3420 type rwx = [`R|`W|`X] list
3421 let file_perm_of : u:rwx -> g:rwx -> o:rwx -> Unix.file_perm =
3422 fun ~u ~g ~o ->
3423 let to_oct l =
3424 List.fold_left (fun acc p -> acc lor ((function `R -> 4 | `W -> 2 | `X -> 1) p)) 0 l in
3425 let perm =
3426 ((to_oct u) lsl 6) lor
3427 ((to_oct g) lsl 3) lor
3428 (to_oct o)
3429 in
3430 perm
3431
3432
3433 (* pixel *)
3434 let has_env var =
3435 try
3436 let _ = Sys.getenv var in true
3437 with Not_found -> false
3438
3439 (* emacs/lisp inspiration (eric cooper and yaron minsky use that too) *)
3440 let (with_open_outfile: filename -> (((string -> unit) * out_channel) -> 'a) -> 'a) =
3441 fun file f ->
3442 let chan = open_out file in
3443 let pr s = output_string chan s in
3444 unwind_protect (fun () ->
3445 let res = f (pr, chan) in
3446 close_out chan;
3447 res)
3448 (fun e -> close_out chan)
3449
3450 let (with_open_infile: filename -> ((in_channel) -> 'a) -> 'a) = fun file f ->
3451 let chan = open_in file in
3452 unwind_protect (fun () ->
3453 let res = f chan in
3454 close_in chan;
3455 res)
3456 (fun e -> close_in chan)
3457
3458
3459 let (with_open_outfile_append: filename -> (((string -> unit) * out_channel) -> 'a) -> 'a) =
3460 fun file f ->
3461 let chan = open_out_gen [Open_creat;Open_append] 0o666 file in
3462 let pr s = output_string chan s in
3463 unwind_protect (fun () ->
3464 let res = f (pr, chan) in
3465 close_out chan;
3466 res)
3467 (fun e -> close_out chan)
3468
3469
3470 (* now in prelude:
3471 * exception Timeout
3472 *)
3473
3474 (* it seems that the toplevel block such signals, even with this explicit
3475 * command :(
3476 * let _ = Unix.sigprocmask Unix.SIG_UNBLOCK [Sys.sigalrm]
3477 *)
3478
3479 (* could be in Control section *)
3480
3481 (* subtil: have to make sure that timeout is not intercepted before here, so
3482 * avoid exn handle such as try (...) with _ -> cos timeout will not bubble up
3483 * enough. In such case, add a case before such as
3484 * with Timeout -> raise Timeout | _ -> ...
3485 *
3486 * question: can we have a signal and so exn when in a exn handler ?
3487 *)
3488
3489 let interval_timer = ref true
3490
3491 let timeout_function timeoutval = fun f ->
3492 try
3493 if !interval_timer
3494 then
3495 begin
3496 Sys.set_signal Sys.sigvtalrm
3497 (Sys.Signal_handle (fun _ -> raise Timeout));
3498 ignore
3499 (Unix.setitimer Unix.ITIMER_VIRTUAL
3500 {Unix.it_interval=float_of_int timeoutval;
3501 Unix.it_value =float_of_int timeoutval});
3502 let x = f() in
3503 ignore(Unix.alarm 0);
3504 x
3505 end
3506 else
3507 begin
3508 Sys.set_signal Sys.sigalrm
3509 (Sys.Signal_handle (fun _ -> raise Timeout ));
3510 ignore(Unix.alarm timeoutval);
3511 let x = f() in
3512 ignore(Unix.alarm 0);
3513 x
3514 end
3515 with Timeout ->
3516 begin
3517 log "timeout (we abort)";
3518 raise Timeout;
3519 end
3520 | e ->
3521 (* subtil: important to disable the alarm before relaunching the exn,
3522 * otherwise the alarm is still running.
3523 *
3524 * robust?: and if alarm launched after the log (...) ?
3525 * Maybe signals are disabled when process an exception handler ?
3526 *)
3527 begin
3528 ignore(Unix.alarm 0);
3529 (* log ("exn while in transaction (we abort too, even if ...) = " ^
3530 Printexc.to_string e);
3531 *)
3532 log "exn while in timeout_function";
3533 raise e
3534 end
3535
3536 let timeout_function_opt timeoutvalopt f =
3537 match timeoutvalopt with
3538 | None -> f()
3539 | Some x -> timeout_function x f
3540
3541
3542
3543 (* creation of tmp files, a la gcc *)
3544
3545 let _temp_files_created = ref ([] : filename list)
3546
3547 (* ex: new_temp_file "cocci" ".c" will give "/tmp/cocci-3252-434465.c" *)
3548 let new_temp_file prefix suffix =
3549 let processid = i_to_s (Unix.getpid ()) in
3550 let tmp_file = Filename.temp_file (prefix ^ "-" ^ processid ^ "-") suffix in
3551 push2 tmp_file _temp_files_created;
3552 tmp_file
3553
3554
3555 let save_tmp_files = ref false
3556 let erase_temp_files () =
3557 if not !save_tmp_files then begin
3558 !_temp_files_created +> List.iter (fun s ->
3559 (* pr2 ("erasing: " ^ s); *)
3560 command2 ("rm -f " ^ s)
3561 );
3562 _temp_files_created := []
3563 end
3564
3565 let erase_this_temp_file f =
3566 if not !save_tmp_files then begin
3567 _temp_files_created :=
3568 List.filter (function x -> not (x =$= f)) !_temp_files_created;
3569 command2 ("rm -f " ^ f)
3570 end
3571
3572
3573 (* now in prelude: exception UnixExit of int *)
3574 let exn_to_real_unixexit f =
3575 try f()
3576 with UnixExit x -> exit x
3577
3578
3579
3580
3581 let uncat xs file =
3582 with_open_outfile file (fun (pr,_chan) ->
3583 xs +> List.iter (fun s -> pr s; pr "\n");
3584
3585 )
3586
3587
3588
3589
3590
3591
3592 (*****************************************************************************)
3593 (* List *)
3594 (*****************************************************************************)
3595
3596 (* pixel *)
3597 let uncons l = (List.hd l, List.tl l)
3598
3599 (* pixel *)
3600 let safe_tl l = try List.tl l with _ -> []
3601
3602 let push l v =
3603 l := v :: !l
3604
3605 let rec zip xs ys =
3606 match (xs,ys) with
3607 | ([],[]) -> []
3608 | ([],_) -> failwith "zip: not same length"
3609 | (_,[]) -> failwith "zip: not same length"
3610 | (x::xs,y::ys) -> (x,y)::zip xs ys
3611
3612 let rec zip_safe xs ys =
3613 match (xs,ys) with
3614 | ([],_) -> []
3615 | (_,[]) -> []
3616 | (x::xs,y::ys) -> (x,y)::zip_safe xs ys
3617
3618 let rec unzip zs =
3619 List.fold_right (fun e (xs, ys) ->
3620 (fst e::xs), (snd e::ys)) zs ([],[])
3621
3622
3623 let map_withkeep f xs =
3624 xs +> List.map (fun x -> f x, x)
3625
3626 (* now in prelude
3627 * let rec take n xs =
3628 * match (n,xs) with
3629 * | (0,_) -> []
3630 * | (_,[]) -> failwith "take: not enough"
3631 * | (n,x::xs) -> x::take (n-1) xs
3632 *)
3633
3634 let rec take_safe n xs =
3635 match (n,xs) with
3636 | (0,_) -> []
3637 | (_,[]) -> []
3638 | (n,x::xs) -> x::take_safe (n-1) xs
3639
3640 let rec take_until p = function
3641 | [] -> []
3642 | x::xs -> if p x then [] else x::(take_until p xs)
3643
3644 let take_while p = take_until (p $ not)
3645
3646
3647 (* now in prelude: let rec drop n xs = ... *)
3648 let _ = example (drop 3 [1;2;3;4] =*= [4])
3649
3650 let rec drop_while p = function
3651 | [] -> []
3652 | x::xs -> if p x then drop_while p xs else x::xs
3653
3654
3655 let rec drop_until p xs =
3656 drop_while (fun x -> not (p x)) xs
3657 let _ = example (drop_until (fun x -> x =|= 3) [1;2;3;4;5] =*= [3;4;5])
3658
3659
3660 let span p xs = (take_while p xs, drop_while p xs)
3661
3662
3663 let rec (span: ('a -> bool) -> 'a list -> 'a list * 'a list) =
3664 fun p -> function
3665 | [] -> ([], [])
3666 | x::xs ->
3667 if p x then
3668 let (l1, l2) = span p xs in
3669 (x::l1, l2)
3670 else ([], x::xs)
3671 let _ = example ((span (fun x -> x <= 3) [1;2;3;4;1;2] =*= ([1;2;3],[4;1;2])))
3672
3673 let rec groupBy eq l =
3674 match l with
3675 | [] -> []
3676 | x::xs ->
3677 let (xs1,xs2) = List.partition (fun x' -> eq x x') xs in
3678 (x::xs1)::(groupBy eq xs2)
3679
3680 let rec group_by_mapped_key fkey l =
3681 match l with
3682 | [] -> []
3683 | x::xs ->
3684 let k = fkey x in
3685 let (xs1,xs2) = List.partition (fun x' -> let k2 = fkey x' in k=*=k2) xs
3686 in
3687 (k, (x::xs1))::(group_by_mapped_key fkey xs2)
3688
3689
3690
3691
3692 let (exclude_but_keep_attached: ('a -> bool) -> 'a list -> ('a * 'a list) list)=
3693 fun f xs ->
3694 let rec aux_filter acc = function
3695 | [] -> [] (* drop what was accumulated because nothing to attach to *)
3696 | x::xs ->
3697 if f x
3698 then aux_filter (x::acc) xs
3699 else (x, List.rev acc)::aux_filter [] xs
3700 in
3701 aux_filter [] xs
3702 let _ = example
3703 (exclude_but_keep_attached (fun x -> x =|= 3) [3;3;1;3;2;3;3;3] =*=
3704 [(1,[3;3]);(2,[3])])
3705
3706 let (group_by_post: ('a -> bool) -> 'a list -> ('a list * 'a) list * 'a list)=
3707 fun f xs ->
3708 let rec aux_filter grouped_acc acc = function
3709 | [] ->
3710 List.rev grouped_acc, List.rev acc
3711 | x::xs ->
3712 if f x
3713 then
3714 aux_filter ((List.rev acc,x)::grouped_acc) [] xs
3715 else
3716 aux_filter grouped_acc (x::acc) xs
3717 in
3718 aux_filter [] [] xs
3719
3720 let _ = example
3721 (group_by_post (fun x -> x =|= 3) [1;1;3;2;3;4;5;3;6;6;6] =*=
3722 ([([1;1],3);([2],3);[4;5],3], [6;6;6]))
3723
3724 let (group_by_pre: ('a -> bool) -> 'a list -> 'a list * ('a * 'a list) list)=
3725 fun f xs ->
3726 let xs' = List.rev xs in
3727 let (ys, unclassified) = group_by_post f xs' in
3728 List.rev unclassified,
3729 ys +> List.rev +> List.map (fun (xs, x) -> x, List.rev xs )
3730
3731 let _ = example
3732 (group_by_pre (fun x -> x =|= 3) [1;1;3;2;3;4;5;3;6;6;6] =*=
3733 ([1;1], [(3,[2]); (3,[4;5]); (3,[6;6;6])]))
3734
3735
3736 let rec (split_when: ('a -> bool) -> 'a list -> 'a list * 'a * 'a list) =
3737 fun p -> function
3738 | [] -> raise Not_found
3739 | x::xs ->
3740 if p x then
3741 [], x, xs
3742 else
3743 let (l1, a, l2) = split_when p xs in
3744 (x::l1, a, l2)
3745 let _ = example (split_when (fun x -> x =|= 3)
3746 [1;2;3;4;1;2] =*= ([1;2],3,[4;1;2]))
3747
3748
3749 (* not so easy to come up with ... used in aComment for split_paragraph *)
3750 let rec split_gen_when_aux f acc xs =
3751 match xs with
3752 | [] ->
3753 if null acc
3754 then []
3755 else [List.rev acc]
3756 | (x::xs) ->
3757 (match f (x::xs) with
3758 | None ->
3759 split_gen_when_aux f (x::acc) xs
3760 | Some (rest) ->
3761 let before = List.rev acc in
3762 if null before
3763 then split_gen_when_aux f [] rest
3764 else before::split_gen_when_aux f [] rest
3765 )
3766 (* could avoid introduce extra aux function by using ?(acc = []) *)
3767 let split_gen_when f xs =
3768 split_gen_when_aux f [] xs
3769
3770
3771
3772 (* generate exception (Failure "tl") if there is no element satisfying p *)
3773 let rec (skip_until: ('a list -> bool) -> 'a list -> 'a list) = fun p xs ->
3774 if p xs then xs else skip_until p (List.tl xs)
3775 let _ = example
3776 (skip_until (function 1::2::xs -> true | _ -> false)
3777 [1;3;4;1;2;4;5] =*= [1;2;4;5])
3778
3779 let rec skipfirst e = function
3780 | [] -> []
3781 | e'::l when e =*= e' -> skipfirst e l
3782 | l -> l
3783
3784
3785 (* now in prelude:
3786 * let rec enum x n = ...
3787 *)
3788
3789
3790 let index_list xs =
3791 if null xs then [] (* enum 0 (-1) generate an exception *)
3792 else zip xs (enum 0 ((List.length xs) -1))
3793
3794 let index_list_and_total xs =
3795 let total = List.length xs in
3796 if null xs then [] (* enum 0 (-1) generate an exception *)
3797 else zip xs (enum 0 ((List.length xs) -1))
3798 +> List.map (fun (a,b) -> (a,b,total))
3799
3800 let index_list_1 xs =
3801 xs +> index_list +> List.map (fun (x,i) -> x, i+1)
3802
3803 let or_list = List.fold_left (||) false
3804 let and_list = List.fold_left (&&) true
3805
3806 let avg_list xs =
3807 let sum = sum_int xs in
3808 (float_of_int sum) /. (float_of_int (List.length xs))
3809
3810 let snoc x xs = xs @ [x]
3811 let cons x xs = x::xs
3812
3813 let head_middle_tail xs =
3814 match xs with
3815 | x::y::xs ->
3816 let head = x in
3817 let reversed = List.rev (y::xs) in
3818 let tail = List.hd reversed in
3819 let middle = List.rev (List.tl reversed) in
3820 head, middle, tail
3821 | _ -> failwith "head_middle_tail, too small list"
3822
3823 let _ = assert_equal (head_middle_tail [1;2;3]) (1, [2], 3)
3824 let _ = assert_equal (head_middle_tail [1;3]) (1, [], 3)
3825
3826 (* now in prelude
3827 * let (++) = (@)
3828 *)
3829
3830 (* let (++) = (@), could do that, but if load many times the common, then pb *)
3831 (* let (++) l1 l2 = List.fold_right (fun x acc -> x::acc) l1 l2 *)
3832
3833 let remove x xs =
3834 let newxs = List.filter (fun y -> y <> x) xs in
3835 assert (List.length newxs =|= List.length xs - 1);
3836 newxs
3837
3838
3839 let exclude p xs =
3840 List.filter (fun x -> not (p x)) xs
3841
3842 (* now in prelude
3843 *)
3844
3845 let fold_k f lastk acc xs =
3846 let rec fold_k_aux acc = function
3847 | [] -> lastk acc
3848 | x::xs ->
3849 f acc x (fun acc -> fold_k_aux acc xs)
3850 in
3851 fold_k_aux acc xs
3852
3853
3854 let rec list_init = function
3855 | [] -> raise Not_found
3856 | [x] -> []
3857 | x::y::xs -> x::(list_init (y::xs))
3858
3859 let rec list_last = function
3860 | [] -> raise Not_found
3861 | [x] -> x
3862 | x::y::xs -> list_last (y::xs)
3863
3864 (* pixel *)
3865 (* now in prelude
3866 * let last_n n l = List.rev (take n (List.rev l))
3867 * let last l = List.hd (last_n 1 l)
3868 *)
3869
3870 let rec join_gen a = function
3871 | [] -> []
3872 | [x] -> [x]
3873 | x::xs -> x::a::(join_gen a xs)
3874
3875
3876 (* todo: foldl, foldr (a more consistent foldr) *)
3877
3878 (* start pixel *)
3879 let iter_index f l =
3880 let rec iter_ n = function
3881 | [] -> ()
3882 | e::l -> f e n ; iter_ (n+1) l
3883 in iter_ 0 l
3884
3885 let map_index f l =
3886 let rec map_ n = function
3887 | [] -> []
3888 | e::l -> f e n :: map_ (n+1) l
3889 in map_ 0 l
3890
3891
3892 (* pixel *)
3893 let filter_index f l =
3894 let rec filt i = function
3895 | [] -> []
3896 | e::l -> if f i e then e :: filt (i+1) l else filt (i+1) l
3897 in
3898 filt 0 l
3899
3900 (* pixel *)
3901 let do_withenv doit f env l =
3902 let r_env = ref env in
3903 let l' = doit (fun e ->
3904 let e', env' = f !r_env e in
3905 r_env := env' ; e'
3906 ) l in
3907 l', !r_env
3908
3909 (* now in prelude:
3910 * let fold_left_with_index f acc = ...
3911 *)
3912
3913 let map_withenv f env e = do_withenv List.map f env e
3914
3915 let rec collect_accu f accu = function
3916 | [] -> accu
3917 | e::l -> collect_accu f (List.rev_append (f e) accu) l
3918
3919 let collect f l = List.rev (collect_accu f [] l)
3920
3921 (* cf also List.partition *)
3922
3923 let rec fpartition p l =
3924 let rec part yes no = function
3925 | [] -> (List.rev yes, List.rev no)
3926 | x :: l ->
3927 (match p x with
3928 | None -> part yes (x :: no) l
3929 | Some v -> part (v :: yes) no l) in
3930 part [] [] l
3931
3932 (* end pixel *)
3933
3934 let rec removelast = function
3935 | [] -> failwith "removelast"
3936 | [_] -> []
3937 | e::l -> e :: removelast l
3938
3939 let remove x = List.filter (fun y -> y != x)
3940 let empty list = null list
3941
3942
3943 let rec inits = function
3944 | [] -> [[]]
3945 | e::l -> [] :: List.map (fun l -> e::l) (inits l)
3946
3947 let rec tails = function
3948 | [] -> [[]]
3949 | (_::xs) as xxs -> xxs :: tails xs
3950
3951
3952 let reverse = List.rev
3953 let rev = List.rev
3954
3955 let nth = List.nth
3956 let fold_left = List.fold_left
3957 let rev_map = List.rev_map
3958
3959 (* pixel *)
3960 let rec fold_right1 f = function
3961 | [] -> failwith "fold_right1"
3962 | [e] -> e
3963 | e::l -> f e (fold_right1 f l)
3964
3965 let maximum l = foldl1 max l
3966 let minimum l = foldl1 min l
3967
3968 (* do a map tail recursive, and result is reversed, it is a tail recursive map => efficient *)
3969 let map_eff_rev = fun f l ->
3970 let rec map_eff_aux acc =
3971 function
3972 | [] -> acc
3973 | x::xs -> map_eff_aux ((f x)::acc) xs
3974 in
3975 map_eff_aux [] l
3976
3977 let acc_map f l =
3978 let rec loop acc = function
3979 [] -> List.rev acc
3980 | x::xs -> loop ((f x)::acc) xs in
3981 loop [] l
3982
3983
3984 let rec (generate: int -> 'a -> 'a list) = fun i el ->
3985 if i =|= 0 then []
3986 else el::(generate (i-1) el)
3987
3988 let rec uniq = function
3989 | [] -> []
3990 | e::l -> if List.mem e l then uniq l else e :: uniq l
3991
3992 let has_no_duplicate xs =
3993 List.length xs =|= List.length (uniq xs)
3994 let is_set_as_list = has_no_duplicate
3995
3996
3997 let rec get_duplicates xs =
3998 match xs with
3999 | [] -> []
4000 | x::xs ->
4001 if List.mem x xs
4002 then x::get_duplicates xs (* todo? could x from xs to avoid double dups?*)
4003 else get_duplicates xs
4004
4005 let rec all_assoc e = function
4006 | [] -> []
4007 | (e',v) :: l when e=*=e' -> v :: all_assoc e l
4008 | _ :: l -> all_assoc e l
4009
4010 let prepare_want_all_assoc l =
4011 List.map (fun n -> n, uniq (all_assoc n l)) (uniq (List.map fst l))
4012
4013 let rotate list = List.tl list ++ [(List.hd list)]
4014
4015 let or_list = List.fold_left (||) false
4016 let and_list = List.fold_left (&&) true
4017
4018 let rec (return_when: ('a -> 'b option) -> 'a list -> 'b) = fun p -> function
4019 | [] -> raise Not_found
4020 | x::xs -> (match p x with None -> return_when p xs | Some b -> b)
4021
4022 let rec splitAt n xs =
4023 if n =|= 0 then ([],xs)
4024 else
4025 (match xs with
4026 | [] -> ([],[])
4027 | (x::xs) -> let (a,b) = splitAt (n-1) xs in (x::a, b)
4028 )
4029
4030 let pack n xs =
4031 let rec pack_aux l i = function
4032 | [] -> failwith "not on a boundary"
4033 | [x] -> if i =|= n then [l++[x]] else failwith "not on a boundary"
4034 | x::xs ->
4035 if i =|= n
4036 then (l++[x])::(pack_aux [] 1 xs)
4037 else pack_aux (l++[x]) (i+1) xs
4038 in
4039 pack_aux [] 1 xs
4040
4041 let min_with f = function
4042 | [] -> raise Not_found
4043 | e :: l ->
4044 let rec min_with_ min_val min_elt = function
4045 | [] -> min_elt
4046 | e::l ->
4047 let val_ = f e in
4048 if val_ < min_val
4049 then min_with_ val_ e l
4050 else min_with_ min_val min_elt l
4051 in min_with_ (f e) e l
4052
4053 let two_mins_with f = function
4054 | e1 :: e2 :: l ->
4055 let rec min_with_ min_val min_elt min_val2 min_elt2 = function
4056 | [] -> min_elt, min_elt2
4057 | e::l ->
4058 let val_ = f e in
4059 if val_ < min_val2
4060 then
4061 if val_ < min_val
4062 then min_with_ val_ e min_val min_elt l
4063 else min_with_ min_val min_elt val_ e l
4064 else min_with_ min_val min_elt min_val2 min_elt2 l
4065 in
4066 let v1 = f e1 in
4067 let v2 = f e2 in
4068 if v1 < v2 then min_with_ v1 e1 v2 e2 l else min_with_ v2 e2 v1 e1 l
4069 | _ -> raise Not_found
4070
4071 let grep_with_previous f = function
4072 | [] -> []
4073 | e::l ->
4074 let rec grep_with_previous_ previous = function
4075 | [] -> []
4076 | e::l -> if f previous e then e :: grep_with_previous_ e l else grep_with_previous_ previous l
4077 in e :: grep_with_previous_ e l
4078
4079 let iter_with_previous f = function
4080 | [] -> ()
4081 | e::l ->
4082 let rec iter_with_previous_ previous = function
4083 | [] -> ()
4084 | e::l -> f previous e ; iter_with_previous_ e l
4085 in iter_with_previous_ e l
4086
4087
4088 let iter_with_before_after f xs =
4089 let rec aux before_rev after =
4090 match after with
4091 | [] -> ()
4092 | x::xs ->
4093 f before_rev x xs;
4094 aux (x::before_rev) xs
4095 in
4096 aux [] xs
4097
4098
4099
4100 (* kind of cartesian product of x*x *)
4101 let rec (get_pair: ('a list) -> (('a * 'a) list)) = function
4102 | [] -> []
4103 | x::xs -> (List.map (fun y -> (x,y)) xs) ++ (get_pair xs)
4104
4105
4106 (* retourne le rang dans une liste d'un element *)
4107 let rang elem liste =
4108 let rec rang_rec elem accu = function
4109 | [] -> raise Not_found
4110 | a::l -> if a =*= elem then accu
4111 else rang_rec elem (accu+1) l in
4112 rang_rec elem 1 liste
4113
4114 (* retourne vrai si une liste contient des doubles *)
4115 let rec doublon = function
4116 | [] -> false
4117 | a::l -> if List.mem a l then true
4118 else doublon l
4119
4120 let rec (insert_in: 'a -> 'a list -> 'a list list) = fun x -> function
4121 | [] -> [[x]]
4122 | y::ys -> (x::y::ys) :: (List.map (fun xs -> y::xs) (insert_in x ys))
4123 (* insert_in 3 [1;2] = [[3; 1; 2]; [1; 3; 2]; [1; 2; 3]] *)
4124
4125 let rec (permutation: 'a list -> 'a list list) = function
4126 | [] -> []
4127 | [x] -> [[x]]
4128 | x::xs -> List.flatten (List.map (insert_in x) (permutation xs))
4129 (* permutation [1;2;3] =
4130 * [[1; 2; 3]; [2; 1; 3]; [2; 3; 1]; [1; 3; 2]; [3; 1; 2]; [3; 2; 1]]
4131 *)
4132
4133
4134 let rec remove_elem_pos pos xs =
4135 match (pos, xs) with
4136 | _, [] -> failwith "remove_elem_pos"
4137 | 0, x::xs -> xs
4138 | n, x::xs -> x::(remove_elem_pos (n-1) xs)
4139
4140 let rec insert_elem_pos (e, pos) xs =
4141 match (pos, xs) with
4142 | 0, xs -> e::xs
4143 | n, x::xs -> x::(insert_elem_pos (e, (n-1)) xs)
4144 | n, [] -> failwith "insert_elem_pos"
4145
4146 let rec uncons_permut xs =
4147 let indexed = index_list xs in
4148 indexed +> List.map (fun (x, pos) -> (x, pos), remove_elem_pos pos xs)
4149 let _ =
4150 example
4151 (uncons_permut ['a';'b';'c'] =*=
4152 [('a', 0), ['b';'c'];
4153 ('b', 1), ['a';'c'];
4154 ('c', 2), ['a';'b']
4155 ])
4156
4157 let rec uncons_permut_lazy xs =
4158 let indexed = index_list xs in
4159 indexed +> List.map (fun (x, pos) ->
4160 (x, pos),
4161 lazy (remove_elem_pos pos xs)
4162 )
4163
4164
4165
4166
4167 (* pixel *)
4168 let rec map_flatten f l =
4169 let rec map_flatten_aux accu = function
4170 | [] -> accu
4171 | e :: l -> map_flatten_aux (List.rev (f e) ++ accu) l
4172 in List.rev (map_flatten_aux [] l)
4173
4174
4175 let rec repeat e n =
4176 let rec repeat_aux acc = function
4177 | 0 -> acc
4178 | n when n < 0 -> failwith "repeat"
4179 | n -> repeat_aux (e::acc) (n-1) in
4180 repeat_aux [] n
4181
4182 let rec map2 f = function
4183 | [] -> []
4184 | x::xs -> let r = f x in r::map2 f xs
4185
4186 let rec map3 f l =
4187 let rec map3_aux acc = function
4188 | [] -> acc
4189 | x::xs -> map3_aux (f x::acc) xs in
4190 map3_aux [] l
4191
4192 (*
4193 let tails2 xs = map rev (inits (rev xs))
4194 let res = tails2 [1;2;3;4]
4195 let res = tails [1;2;3;4]
4196 let id x = x
4197 *)
4198
4199 let pack_sorted same xs =
4200 let rec pack_s_aux acc xs =
4201 match (acc,xs) with
4202 | ((cur,rest),[]) -> cur::rest
4203 | ((cur,rest), y::ys) ->
4204 if same (List.hd cur) y then pack_s_aux (y::cur, rest) ys
4205 else pack_s_aux ([y], cur::rest) ys
4206 in pack_s_aux ([List.hd xs],[]) (List.tl xs) +> List.rev
4207 let test = pack_sorted (=*=) [1;1;1;2;2;3;4]
4208
4209
4210 let rec keep_best f =
4211 let rec partition e = function
4212 | [] -> e, []
4213 | e' :: l ->
4214 match f(e,e') with
4215 | None -> let (e'', l') = partition e l in e'', e' :: l'
4216 | Some e'' -> partition e'' l
4217 in function
4218 | [] -> []
4219 | e::l ->
4220 let (e', l') = partition e l in
4221 e' :: keep_best f l'
4222
4223 let rec sorted_keep_best f = function
4224 | [] -> []
4225 | [a] -> [a]
4226 | a :: b :: l ->
4227 match f a b with
4228 | None -> a :: sorted_keep_best f (b :: l)
4229 | Some e -> sorted_keep_best f (e :: l)
4230
4231
4232
4233 let (cartesian_product: 'a list -> 'b list -> ('a * 'b) list) = fun xs ys ->
4234 xs +> List.map (fun x -> ys +> List.map (fun y -> (x,y)))
4235 +> List.flatten
4236
4237 let _ = assert_equal
4238 (cartesian_product [1;2] ["3";"4";"5"])
4239 [1,"3";1,"4";1,"5"; 2,"3";2,"4";2,"5"]
4240
4241 let sort_prof a b =
4242 profile_code "Common.sort_by_xxx" (fun () -> List.sort a b)
4243
4244 let sort_by_val_highfirst xs =
4245 sort_prof (fun (k1,v1) (k2,v2) -> compare v2 v1) xs
4246 let sort_by_val_lowfirst xs =
4247 sort_prof (fun (k1,v1) (k2,v2) -> compare v1 v2) xs
4248
4249 let sort_by_key_highfirst xs =
4250 sort_prof (fun (k1,v1) (k2,v2) -> compare k2 k1) xs
4251 let sort_by_key_lowfirst xs =
4252 sort_prof (fun (k1,v1) (k2,v2) -> compare k1 k2) xs
4253
4254 let _ = example (sort_by_key_lowfirst [4, (); 7,()] =*= [4,(); 7,()])
4255 let _ = example (sort_by_key_highfirst [4,(); 7,()] =*= [7,(); 4,()])
4256
4257
4258 let sortgen_by_key_highfirst xs =
4259 sort_prof (fun (k1,v1) (k2,v2) -> compare k2 k1) xs
4260 let sortgen_by_key_lowfirst xs =
4261 sort_prof (fun (k1,v1) (k2,v2) -> compare k1 k2) xs
4262
4263 (*----------------------------------*)
4264
4265 (* sur surEnsemble [p1;p2] [[p1;p2;p3] [p1;p2] ....] -> [[p1;p2;p3] ... *)
4266 (* mais pas p2;p3 *)
4267 (* (aop) *)
4268 let surEnsemble liste_el liste_liste_el =
4269 List.filter
4270 (function liste_elbis ->
4271 List.for_all (function el -> List.mem el liste_elbis) liste_el
4272 ) liste_liste_el;;
4273
4274
4275
4276 (*----------------------------------*)
4277 (* combinaison/product/.... (aop) *)
4278 (* 123 -> 123 12 13 23 1 2 3 *)
4279 let rec realCombinaison = function
4280 | [] -> []
4281 | [a] -> [[a]]
4282 | a::l ->
4283 let res = realCombinaison l in
4284 let res2 = List.map (function x -> a::x) res in
4285 res2 ++ res ++ [[a]]
4286
4287 (* genere toutes les combinaisons possible de paire *)
4288 (* par exemple combinaison [1;2;4] -> [1, 2; 1, 4; 2, 4] *)
4289 let rec combinaison = function
4290 | [] -> []
4291 | [a] -> []
4292 | [a;b] -> [(a, b)]
4293 | a::b::l -> (List.map (function elem -> (a, elem)) (b::l)) ++
4294 (combinaison (b::l))
4295
4296 (*----------------------------------*)
4297
4298 (* list of list(aop) *)
4299 (* insere elem dans la liste de liste (si elem est deja present dans une de *)
4300 (* ces listes, on ne fait rien *)
4301 let rec insere elem = function
4302 | [] -> [[elem]]
4303 | a::l ->
4304 if (List.mem elem a) then a::l
4305 else a::(insere elem l)
4306
4307 let rec insereListeContenant lis el = function
4308 | [] -> [el::lis]
4309 | a::l ->
4310 if List.mem el a then
4311 (List.append lis a)::l
4312 else a::(insereListeContenant lis el l)
4313
4314 (* fusionne les listes contenant et1 et et2 dans la liste de liste*)
4315 let rec fusionneListeContenant (et1, et2) = function
4316 | [] -> [[et1; et2]]
4317 | a::l ->
4318 (* si les deux sont deja dedans alors rien faire *)
4319 if List.mem et1 a then
4320 if List.mem et2 a then a::l
4321 else
4322 insereListeContenant a et2 l
4323 else if List.mem et2 a then
4324 insereListeContenant a et1 l
4325 else a::(fusionneListeContenant (et1, et2) l)
4326
4327 (*****************************************************************************)
4328 (* Arrays *)
4329 (*****************************************************************************)
4330
4331 (* do bound checking ? *)
4332 let array_find_index f a =
4333 let rec array_find_index_ i =
4334 if f i then i else array_find_index_ (i+1)
4335 in
4336 try array_find_index_ 0 with _ -> raise Not_found
4337
4338 let array_find_index_via_elem f a =
4339 let rec array_find_index_ i =
4340 if f a.(i) then i else array_find_index_ (i+1)
4341 in
4342 try array_find_index_ 0 with _ -> raise Not_found
4343
4344
4345
4346 type idx = Idx of int
4347 let next_idx (Idx i) = (Idx (i+1))
4348 let int_of_idx (Idx i) = i
4349
4350 let array_find_index_typed f a =
4351 let rec array_find_index_ i =
4352 if f i then i else array_find_index_ (next_idx i)
4353 in
4354 try array_find_index_ (Idx 0) with _ -> raise Not_found
4355
4356
4357
4358 (*****************************************************************************)
4359 (* Matrix *)
4360 (*****************************************************************************)
4361
4362 type 'a matrix = 'a array array
4363
4364 let map_matrix f mat =
4365 mat +> Array.map (fun arr -> arr +> Array.map f)
4366
4367 let (make_matrix_init:
4368 nrow:int -> ncolumn:int -> (int -> int -> 'a) -> 'a matrix) =
4369 fun ~nrow ~ncolumn f ->
4370 Array.init nrow (fun i ->
4371 Array.init ncolumn (fun j ->
4372 f i j
4373 )
4374 )
4375
4376 let iter_matrix f m =
4377 Array.iteri (fun i e ->
4378 Array.iteri (fun j x ->
4379 f i j x
4380 ) e
4381 ) m
4382
4383 let nb_rows_matrix m =
4384 Array.length m
4385
4386 let nb_columns_matrix m =
4387 assert(Array.length m > 0);
4388 Array.length m.(0)
4389
4390 (* check all nested arrays have the same size *)
4391 let invariant_matrix m =
4392 raise Todo
4393
4394 let (rows_of_matrix: 'a matrix -> 'a list list) = fun m ->
4395 Array.to_list m +> List.map Array.to_list
4396
4397 let (columns_of_matrix: 'a matrix -> 'a list list) = fun m ->
4398 let nbcols = nb_columns_matrix m in
4399 let nbrows = nb_rows_matrix m in
4400 (enum 0 (nbcols -1)) +> List.map (fun j ->
4401 (enum 0 (nbrows -1)) +> List.map (fun i ->
4402 m.(i).(j)
4403 ))
4404
4405
4406 let all_elems_matrix_by_row m =
4407 rows_of_matrix m +> List.flatten
4408
4409
4410 let ex_matrix1 =
4411 [|
4412 [|0;1;2|];
4413 [|3;4;5|];
4414 [|6;7;8|];
4415 |]
4416 let ex_rows1 =
4417 [
4418 [0;1;2];
4419 [3;4;5];
4420 [6;7;8];
4421 ]
4422 let ex_columns1 =
4423 [
4424 [0;3;6];
4425 [1;4;7];
4426 [2;5;8];
4427 ]
4428 let _ = example (rows_of_matrix ex_matrix1 =*= ex_rows1)
4429 let _ = example (columns_of_matrix ex_matrix1 =*= ex_columns1)
4430
4431
4432 (*****************************************************************************)
4433 (* Fast array *)
4434 (*****************************************************************************)
4435 (*
4436 module B_Array = Bigarray.Array2
4437 *)
4438
4439 (*
4440 open B_Array
4441 open Bigarray
4442 *)
4443
4444
4445 (* for the string_of auto generation of camlp4
4446 val b_array_string_of_t : 'a -> 'b -> string
4447 val bigarray_string_of_int16_unsigned_elt : 'a -> string
4448 val bigarray_string_of_c_layout : 'a -> string
4449 let b_array_string_of_t f a = "<>"
4450 let bigarray_string_of_int16_unsigned_elt a = "<>"
4451 let bigarray_string_of_c_layout a = "<>"
4452
4453 *)
4454
4455
4456 (*****************************************************************************)
4457 (* Set. Have a look too at set*.mli *)
4458 (*****************************************************************************)
4459 type 'a set = 'a list
4460 (* with sexp *)
4461
4462 let (empty_set: 'a set) = []
4463 let (insert_set: 'a -> 'a set -> 'a set) = fun x xs ->
4464 if List.mem x xs
4465 then (* let _ = print_string "warning insert: already exist" in *)
4466 xs
4467 else x::xs
4468
4469 let is_set xs =
4470 has_no_duplicate xs
4471
4472 let (single_set: 'a -> 'a set) = fun x -> insert_set x empty_set
4473 let (set: 'a list -> 'a set) = fun xs ->
4474 xs +> List.fold_left (flip insert_set) empty_set
4475
4476 let (exists_set: ('a -> bool) -> 'a set -> bool) = List.exists
4477 let (forall_set: ('a -> bool) -> 'a set -> bool) = List.for_all
4478 let (filter_set: ('a -> bool) -> 'a set -> 'a set) = List.filter
4479 let (fold_set: ('a -> 'b -> 'a) -> 'a -> 'b set -> 'a) = List.fold_left
4480 let (map_set: ('a -> 'b) -> 'a set -> 'b set) = List.map
4481 let (member_set: 'a -> 'a set -> bool) = List.mem
4482
4483 let find_set = List.find
4484 let sort_set = List.sort
4485 let iter_set = List.iter
4486
4487 let (top_set: 'a set -> 'a) = List.hd
4488
4489 let (inter_set: 'a set -> 'a set -> 'a set) = fun s1 s2 ->
4490 s1 +> fold_set (fun acc x -> if member_set x s2 then insert_set x acc else acc) empty_set
4491 let (union_set: 'a set -> 'a set -> 'a set) = fun s1 s2 ->
4492 s2 +> fold_set (fun acc x -> if member_set x s1 then acc else insert_set x acc) s1
4493 let (minus_set: 'a set -> 'a set -> 'a set) = fun s1 s2 ->
4494 s1 +> filter_set (fun x -> not (member_set x s2))
4495
4496
4497 let union_all l = List.fold_left union_set [] l
4498
4499 let big_union_set f xs = xs +> map_set f +> fold_set union_set empty_set
4500
4501 let (card_set: 'a set -> int) = List.length
4502
4503 let (include_set: 'a set -> 'a set -> bool) = fun s1 s2 ->
4504 (s1 +> forall_set (fun p -> member_set p s2))
4505
4506 let equal_set s1 s2 = include_set s1 s2 && include_set s2 s1
4507
4508 let (include_set_strict: 'a set -> 'a set -> bool) = fun s1 s2 ->
4509 (card_set s1 < card_set s2) && (include_set s1 s2)
4510
4511 let ($*$) = inter_set
4512 let ($+$) = union_set
4513 let ($-$) = minus_set
4514 let ($?$) a b = profile_code "$?$" (fun () -> member_set a b)
4515 let ($<$) = include_set_strict
4516 let ($<=$) = include_set
4517 let ($=$) = equal_set
4518
4519 (* as $+$ but do not check for memberness, allow to have set of func *)
4520 let ($@$) = fun a b -> a @ b
4521
4522 let rec nub = function
4523 [] -> []
4524 | x::xs -> if List.mem x xs then nub xs else x::(nub xs)
4525
4526 (*****************************************************************************)
4527 (* Set as normal list *)
4528 (*****************************************************************************)
4529 (*
4530 let (union: 'a list -> 'a list -> 'a list) = fun l1 l2 ->
4531 List.fold_left (fun acc x -> if List.mem x l1 then acc else x::acc) l1 l2
4532
4533 let insert_normal x xs = union xs [x]
4534
4535 (* retourne lis1 - lis2 *)
4536 let minus l1 l2 = List.filter (fun x -> not (List.mem x l2)) l1
4537
4538 let inter l1 l2 = List.fold_left (fun acc x -> if List.mem x l2 then x::acc else acc) [] l1
4539
4540 let union_list = List.fold_left union []
4541
4542 let uniq lis =
4543 List.fold_left (function acc -> function el -> union [el] acc) [] lis
4544
4545 (* pixel *)
4546 let rec non_uniq = function
4547 | [] -> []
4548 | e::l -> if mem e l then e :: non_uniq l else non_uniq l
4549
4550 let rec inclu lis1 lis2 =
4551 List.for_all (function el -> List.mem el lis2) lis1
4552
4553 let equivalent lis1 lis2 =
4554 (inclu lis1 lis2) && (inclu lis2 lis1)
4555
4556 *)
4557
4558
4559 (*****************************************************************************)
4560 (* Set as sorted list *)
4561 (*****************************************************************************)
4562 (* liste trie, cos we need to do intersection, and insertion (it is a set
4563 cos when introduce has, if we create a new has => must do a recurse_rep
4564 and another categ can have to this has => must do an union
4565 *)
4566 (*
4567 let rec insert x = function
4568 | [] -> [x]
4569 | y::ys ->
4570 if x = y then y::ys
4571 else (if x < y then x::y::ys else y::(insert x ys))
4572
4573 (* same, suppose sorted list *)
4574 let rec intersect x y =
4575 match(x,y) with
4576 | [], y -> []
4577 | x, [] -> []
4578 | x::xs, y::ys ->
4579 if x = y then x::(intersect xs ys)
4580 else
4581 (if x < y then intersect xs (y::ys)
4582 else intersect (x::xs) ys
4583 )
4584 (* intersect [1;3;7] [2;3;4;7;8];; *)
4585 *)
4586
4587 (*****************************************************************************)
4588 (* Assoc *)
4589 (*****************************************************************************)
4590 type ('a,'b) assoc = ('a * 'b) list
4591 (* with sexp *)
4592
4593
4594 let (assoc_to_function: ('a, 'b) assoc -> ('a -> 'b)) = fun xs ->
4595 xs +> List.fold_left (fun acc (k, v) ->
4596 (fun k' ->
4597 if k =*= k' then v else acc k'
4598 )) (fun k -> failwith "no key in this assoc")
4599 (* simpler:
4600 let (assoc_to_function: ('a, 'b) assoc -> ('a -> 'b)) = fun xs ->
4601 fun k -> List.assoc k xs
4602 *)
4603
4604 let (empty_assoc: ('a, 'b) assoc) = []
4605 let fold_assoc = List.fold_left
4606 let insert_assoc = fun x xs -> x::xs
4607 let map_assoc = List.map
4608 let filter_assoc = List.filter
4609
4610 let assoc = List.assoc
4611 let keys xs = List.map fst xs
4612
4613 let lookup = assoc
4614
4615 (* assert unique key ?*)
4616 let del_assoc key xs = xs +> List.filter (fun (k,v) -> k <> key)
4617 let replace_assoc (key, v) xs = insert_assoc (key, v) (del_assoc key xs)
4618
4619 let apply_assoc key f xs =
4620 let old = assoc key xs in
4621 replace_assoc (key, f old) xs
4622
4623 let big_union_assoc f xs = xs +> map_assoc f +> fold_assoc union_set empty_set
4624
4625 (* todo: pb normally can suppr fun l -> .... l but if do that, then strange type _a
4626 => assoc_map is strange too => equal dont work
4627 *)
4628 let (assoc_reverse: (('a * 'b) list) -> (('b * 'a) list)) = fun l ->
4629 List.map (fun(x,y) -> (y,x)) l
4630
4631 let (assoc_map: (('a * 'b) list) -> (('a * 'b) list) -> (('a * 'a) list)) =
4632 fun l1 l2 ->
4633 let (l1bis, l2bis) = (assoc_reverse l1, assoc_reverse l2) in
4634 List.map (fun (x,y) -> (y, List.assoc x l2bis )) l1bis
4635
4636 let rec (lookup_list: 'a -> ('a , 'b) assoc list -> 'b) = fun el -> function
4637 | [] -> raise Not_found
4638 | (xs::xxs) -> try List.assoc el xs with Not_found -> lookup_list el xxs
4639
4640 let (lookup_list2: 'a -> ('a , 'b) assoc list -> ('b * int)) = fun el xxs ->
4641 let rec lookup_l_aux i = function
4642 | [] -> raise Not_found
4643 | (xs::xxs) ->
4644 try let res = List.assoc el xs in (res,i)
4645 with Not_found -> lookup_l_aux (i+1) xxs
4646 in lookup_l_aux 0 xxs
4647
4648 let _ = example
4649 (lookup_list2 "c" [["a",1;"b",2];["a",1;"b",3];["a",1;"c",7]] =*= (7,2))
4650
4651
4652 let assoc_option k l =
4653 optionise (fun () -> List.assoc k l)
4654
4655 let assoc_with_err_msg k l =
4656 try List.assoc k l
4657 with Not_found ->
4658 pr2 (spf "pb assoc_with_err_msg: %s" (dump k));
4659 raise Not_found
4660
4661 (*****************************************************************************)
4662 (* Assoc int -> xxx with binary tree. Have a look too at Mapb.mli *)
4663 (*****************************************************************************)
4664
4665 (* ex: type robot_list = robot_info IntMap.t *)
4666 module IntMap = Map.Make
4667 (struct
4668 type t = int
4669 let compare = compare
4670 end)
4671 let intmap_to_list m = IntMap.fold (fun id v acc -> (id, v) :: acc) m []
4672 let intmap_string_of_t f a = "<Not Yet>"
4673
4674 module IntIntMap = Map.Make
4675 (struct
4676 type t = int * int
4677 let compare = compare
4678 end)
4679
4680 let intintmap_to_list m = IntIntMap.fold (fun id v acc -> (id, v) :: acc) m []
4681 let intintmap_string_of_t f a = "<Not Yet>"
4682
4683
4684 (*****************************************************************************)
4685 (* Hash *)
4686 (*****************************************************************************)
4687
4688 (* il parait que better when choose a prime *)
4689 let hcreate () = Hashtbl.create 401
4690 let hadd (k,v) h = Hashtbl.add h k v
4691 let hmem k h = Hashtbl.mem h k
4692 let hfind k h = Hashtbl.find h k
4693 let hreplace (k,v) h = Hashtbl.replace h k v
4694 let hiter = Hashtbl.iter
4695 let hfold = Hashtbl.fold
4696 let hremove k h = Hashtbl.remove h k
4697
4698
4699 let hash_to_list h =
4700 Hashtbl.fold (fun k v acc -> (k,v)::acc) h []
4701 +> List.sort compare
4702
4703 let hash_to_list_unsorted h =
4704 Hashtbl.fold (fun k v acc -> (k,v)::acc) h []
4705
4706 let hash_of_list xs =
4707 let h = Hashtbl.create 101 in
4708 begin
4709 xs +> List.iter (fun (k, v) -> Hashtbl.add h k v);
4710 h
4711 end
4712
4713 let _ =
4714 let h = Hashtbl.create 101 in
4715 Hashtbl.add h "toto" 1;
4716 Hashtbl.add h "toto" 1;
4717 assert(hash_to_list h =*= ["toto",1; "toto",1])
4718
4719
4720 let hfind_default key value_if_not_found h =
4721 try Hashtbl.find h key
4722 with Not_found ->
4723 (Hashtbl.add h key (value_if_not_found ()); Hashtbl.find h key)
4724
4725 (* not as easy as Perl $h->{key}++; but still possible *)
4726 let hupdate_default key op value_if_not_found h =
4727 let old = hfind_default key value_if_not_found h in
4728 Hashtbl.replace h key (op old)
4729
4730
4731 let hfind_option key h =
4732 optionise (fun () -> Hashtbl.find h key)
4733
4734
4735 (* see below: let hkeys h = ... *)
4736
4737
4738 (*****************************************************************************)
4739 (* Hash sets *)
4740 (*****************************************************************************)
4741
4742 type 'a hashset = ('a, bool) Hashtbl.t
4743 (* with sexp *)
4744
4745
4746 let hash_hashset_add k e h =
4747 match optionise (fun () -> Hashtbl.find h k) with
4748 | Some hset -> Hashtbl.replace hset e true
4749 | None ->
4750 let hset = Hashtbl.create 11 in
4751 begin
4752 Hashtbl.add h k hset;
4753 Hashtbl.replace hset e true;
4754 end
4755
4756 let hashset_to_set baseset h =
4757 h +> hash_to_list +> List.map fst +> (fun xs -> baseset#fromlist xs)
4758
4759 let hashset_to_list h = hash_to_list h +> List.map fst
4760
4761 let hashset_of_list xs =
4762 xs +> List.map (fun x -> x, true) +> hash_of_list
4763
4764
4765
4766 let hkeys h =
4767 let hkey = Hashtbl.create 101 in
4768 h +> Hashtbl.iter (fun k v -> Hashtbl.replace hkey k true);
4769 hashset_to_list hkey
4770
4771
4772
4773 let group_assoc_bykey_eff2 xs =
4774 let h = Hashtbl.create 101 in
4775 xs +> List.iter (fun (k, v) -> Hashtbl.add h k v);
4776 let keys = hkeys h in
4777 keys +> List.map (fun k -> k, Hashtbl.find_all h k)
4778
4779 let group_assoc_bykey_eff xs =
4780 profile_code2 "Common.group_assoc_bykey_eff" (fun () ->
4781 group_assoc_bykey_eff2 xs)
4782
4783
4784 let test_group_assoc () =
4785 let xs = enum 0 10000 +> List.map (fun i -> i_to_s i, i) in
4786 let xs = ("0", 2)::xs in
4787 (* let _ys = xs +> Common.groupBy (fun (a,resa) (b,resb) -> a =$= b) *)
4788 let ys = xs +> group_assoc_bykey_eff
4789 in
4790 pr2_gen ys
4791
4792
4793 let uniq_eff xs =
4794 let h = Hashtbl.create 101 in
4795 xs +> List.iter (fun k ->
4796 Hashtbl.add h k true
4797 );
4798 hkeys h
4799
4800
4801
4802 let diff_two_say_set_eff xs1 xs2 =
4803 let h1 = hashset_of_list xs1 in
4804 let h2 = hashset_of_list xs2 in
4805
4806 let hcommon = Hashtbl.create 101 in
4807 let honly_in_h1 = Hashtbl.create 101 in
4808 let honly_in_h2 = Hashtbl.create 101 in
4809
4810 h1 +> Hashtbl.iter (fun k _ ->
4811 if Hashtbl.mem h2 k
4812 then Hashtbl.replace hcommon k true
4813 else Hashtbl.add honly_in_h1 k true
4814 );
4815 h2 +> Hashtbl.iter (fun k _ ->
4816 if Hashtbl.mem h1 k
4817 then Hashtbl.replace hcommon k true
4818 else Hashtbl.add honly_in_h2 k true
4819 );
4820 hashset_to_list hcommon,
4821 hashset_to_list honly_in_h1,
4822 hashset_to_list honly_in_h2
4823
4824
4825 (*****************************************************************************)
4826 (* Stack *)
4827 (*****************************************************************************)
4828 type 'a stack = 'a list
4829 (* with sexp *)
4830
4831 let (empty_stack: 'a stack) = []
4832 let (push: 'a -> 'a stack -> 'a stack) = fun x xs -> x::xs
4833 let (top: 'a stack -> 'a) = List.hd
4834 let (pop: 'a stack -> 'a stack) = List.tl
4835
4836 let top_option = function
4837 | [] -> None
4838 | x::xs -> Some x
4839
4840
4841
4842
4843 (* now in prelude:
4844 * let push2 v l = l := v :: !l
4845 *)
4846
4847 let pop2 l =
4848 let v = List.hd !l in
4849 begin
4850 l := List.tl !l;
4851 v
4852 end
4853
4854
4855 (*****************************************************************************)
4856 (* Undoable Stack *)
4857 (*****************************************************************************)
4858
4859 (* Okasaki use such structure also for having efficient data structure
4860 * supporting fast append.
4861 *)
4862
4863 type 'a undo_stack = 'a list * 'a list (* redo *)
4864
4865 let (empty_undo_stack: 'a undo_stack) =
4866 [], []
4867
4868 (* push erase the possible redo *)
4869 let (push_undo: 'a -> 'a undo_stack -> 'a undo_stack) = fun x (undo,redo) ->
4870 x::undo, []
4871
4872 let (top_undo: 'a undo_stack -> 'a) = fun (undo, redo) ->
4873 List.hd undo
4874
4875 let (pop_undo: 'a undo_stack -> 'a undo_stack) = fun (undo, redo) ->
4876 match undo with
4877 | [] -> failwith "empty undo stack"
4878 | x::xs ->
4879 xs, x::redo
4880
4881 let (undo_pop: 'a undo_stack -> 'a undo_stack) = fun (undo, redo) ->
4882 match redo with
4883 | [] -> failwith "empty redo, nothing to redo"
4884 | x::xs ->
4885 x::undo, xs
4886
4887 let redo_undo x = undo_pop x
4888
4889
4890 let top_undo_option = fun (undo, redo) ->
4891 match undo with
4892 | [] -> None
4893 | x::xs -> Some x
4894
4895 (*****************************************************************************)
4896 (* Binary tree *)
4897 (*****************************************************************************)
4898 type 'a bintree = Leaf of 'a | Branch of ('a bintree * 'a bintree)
4899
4900
4901 (*****************************************************************************)
4902 (* N-ary tree *)
4903 (*****************************************************************************)
4904
4905 (* no empty tree, must have one root at list *)
4906 type 'a tree = Tree of 'a * ('a tree) list
4907
4908 let rec (tree_iter: ('a -> unit) -> 'a tree -> unit) = fun f tree ->
4909 match tree with
4910 | Tree (node, xs) ->
4911 f node;
4912 xs +> List.iter (tree_iter f)
4913
4914
4915 (*****************************************************************************)
4916 (* N-ary tree with updatable childrens *)
4917 (*****************************************************************************)
4918
4919 (* no empty tree, must have one root at list *)
4920
4921 type 'a treeref =
4922 | NodeRef of 'a * 'a treeref list ref
4923
4924 let treeref_children_ref tree =
4925 match tree with
4926 | NodeRef (n, x) -> x
4927
4928
4929
4930 let rec (treeref_node_iter:
4931 (* (('a * ('a, 'b) treeref list ref) -> unit) ->
4932 ('a, 'b) treeref -> unit
4933 *) 'a)
4934 =
4935 fun f tree ->
4936 match tree with
4937 (* | LeafRef _ -> ()*)
4938 | NodeRef (n, xs) ->
4939 f (n, xs);
4940 !xs +> List.iter (treeref_node_iter f)
4941
4942
4943 let find_treeref f tree =
4944 let res = ref [] in
4945
4946 tree +> treeref_node_iter (fun (n, xs) ->
4947 if f (n,xs)
4948 then push2 (n, xs) res;
4949 );
4950 match !res with
4951 | [n,xs] -> NodeRef (n, xs)
4952 | [] -> raise Not_found
4953 | x::y::zs -> raise Multi_found
4954
4955 let rec (treeref_node_iter_with_parents:
4956 (* (('a * ('a, 'b) treeref list ref) -> ('a list) -> unit) ->
4957 ('a, 'b) treeref -> unit)
4958 *) 'a)
4959 =
4960 fun f tree ->
4961 let rec aux acc tree =
4962 match tree with
4963 (* | LeafRef _ -> ()*)
4964 | NodeRef (n, xs) ->
4965 f (n, xs) acc ;
4966 !xs +> List.iter (aux (n::acc))
4967 in
4968 aux [] tree
4969
4970
4971 (* ---------------------------------------------------------------------- *)
4972 (* Leaf can seem redundant, but sometimes want to directly see if
4973 * a children is a leaf without looking if the list is empty.
4974 *)
4975 type ('a, 'b) treeref2 =
4976 | NodeRef2 of 'a * ('a, 'b) treeref2 list ref
4977 | LeafRef2 of 'b
4978
4979
4980 let treeref2_children_ref tree =
4981 match tree with
4982 | LeafRef2 _ -> failwith "treeref_tail: leaf"
4983 | NodeRef2 (n, x) -> x
4984
4985
4986
4987 let rec (treeref_node_iter2:
4988 (('a * ('a, 'b) treeref2 list ref) -> unit) ->
4989 ('a, 'b) treeref2 -> unit) =
4990 fun f tree ->
4991 match tree with
4992 | LeafRef2 _ -> ()
4993 | NodeRef2 (n, xs) ->
4994 f (n, xs);
4995 !xs +> List.iter (treeref_node_iter2 f)
4996
4997
4998 let find_treeref2 f tree =
4999 let res = ref [] in
5000
5001 tree +> treeref_node_iter2 (fun (n, xs) ->
5002 if f (n,xs)
5003 then push2 (n, xs) res;
5004 );
5005 match !res with
5006 | [n,xs] -> NodeRef2 (n, xs)
5007 | [] -> raise Not_found
5008 | x::y::zs -> raise Multi_found
5009
5010
5011
5012
5013 let rec (treeref_node_iter_with_parents2:
5014 (('a * ('a, 'b) treeref2 list ref) -> ('a list) -> unit) ->
5015 ('a, 'b) treeref2 -> unit) =
5016 fun f tree ->
5017 let rec aux acc tree =
5018 match tree with
5019 | LeafRef2 _ -> ()
5020 | NodeRef2 (n, xs) ->
5021 f (n, xs) acc ;
5022 !xs +> List.iter (aux (n::acc))
5023 in
5024 aux [] tree
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038 let find_treeref_with_parents_some f tree =
5039 let res = ref [] in
5040
5041 tree +> treeref_node_iter_with_parents (fun (n, xs) parents ->
5042 match f (n,xs) parents with
5043 | Some v -> push2 v res;
5044 | None -> ()
5045 );
5046 match !res with
5047 | [v] -> v
5048 | [] -> raise Not_found
5049 | x::y::zs -> raise Multi_found
5050
5051 let find_multi_treeref_with_parents_some f tree =
5052 let res = ref [] in
5053
5054 tree +> treeref_node_iter_with_parents (fun (n, xs) parents ->
5055 match f (n,xs) parents with
5056 | Some v -> push2 v res;
5057 | None -> ()
5058 );
5059 match !res with
5060 | [v] -> !res
5061 | [] -> raise Not_found
5062 | x::y::zs -> !res
5063
5064
5065 (*****************************************************************************)
5066 (* Graph. Have a look too at Ograph_*.mli *)
5067 (*****************************************************************************)
5068 (* todo: generalise to put in common (need 'edge (and 'c ?),
5069 * and take in param a display func, cos caml sux, no overloading of show :(
5070 * Simple impelemntation. Can do also matrix, or adjacent list, or pointer(ref)
5071 * todo: do some check (dont exist already, ...)
5072 *)
5073
5074 type 'node graph = ('node set) * (('node * 'node) set)
5075
5076 let (add_node: 'a -> 'a graph -> 'a graph) = fun node (nodes, arcs) ->
5077 (node::nodes, arcs)
5078
5079 let (del_node: 'a -> 'a graph -> 'a graph) = fun node (nodes, arcs) ->
5080 (nodes $-$ set [node], arcs)
5081 (* could do more job:
5082 let _ = assert (successors node (nodes, arcs) = empty) in
5083 +> List.filter (fun (src, dst) -> dst != node))
5084 *)
5085 let (add_arc: ('a * 'a) -> 'a graph -> 'a graph) = fun arc (nodes, arcs) ->
5086 (nodes, set [arc] $+$ arcs)
5087
5088 let (del_arc: ('a * 'a) -> 'a graph -> 'a graph) = fun arc (nodes, arcs) ->
5089 (nodes, arcs +> List.filter (fun a -> not (arc =*= a)))
5090
5091 let (successors: 'a -> 'a graph -> 'a set) = fun x (nodes, arcs) ->
5092 arcs +> List.filter (fun (src, dst) -> src =*= x) +> List.map snd
5093
5094 let (predecessors: 'a -> 'a graph -> 'a set) = fun x (nodes, arcs) ->
5095 arcs +> List.filter (fun (src, dst) -> dst =*= x) +> List.map fst
5096
5097 let (nodes: 'a graph -> 'a set) = fun (nodes, arcs) -> nodes
5098
5099 (* pre: no cycle *)
5100 let rec (fold_upward: ('b -> 'a -> 'b) -> 'a set -> 'b -> 'a graph -> 'b) =
5101 fun f xs acc graph ->
5102 match xs with
5103 | [] -> acc
5104 | x::xs -> (f acc x)
5105 +> (fun newacc -> fold_upward f (graph +> predecessors x) newacc graph)
5106 +> (fun newacc -> fold_upward f xs newacc graph)
5107 (* TODO avoid already visited *)
5108
5109 let empty_graph = ([], [])
5110
5111
5112
5113 (*
5114 let (add_arcs_toward: int -> (int list) -> 'a graph -> 'a graph) = fun i xs ->
5115 function
5116 (nodes, arcs) -> (nodes, (List.map (fun j -> (j,i) ) xs)++arcs)
5117 let (del_arcs_toward: int -> (int list) -> 'a graph -> 'a graph)= fun i xs g ->
5118 List.fold_left (fun acc el -> del_arc (el, i) acc) g xs
5119 let (add_arcs_from: int -> (int list) -> 'a graph -> 'a graph) = fun i xs ->
5120 function
5121 (nodes, arcs) -> (nodes, (List.map (fun j -> (i,j) ) xs)++arcs)
5122
5123
5124 let (del_node: (int * 'node) -> 'node graph -> 'node graph) = fun node ->
5125 function (nodes, arcs) ->
5126 let newnodes = List.filter (fun a -> not (node = a)) nodes in
5127 if newnodes = nodes then (raise Not_found) else (newnodes, arcs)
5128 let (replace_node: int -> 'node -> 'node graph -> 'node graph) = fun i n ->
5129 function (nodes, arcs) ->
5130 let newnodes = List.filter (fun (j,_) -> not (i = j)) nodes in
5131 ((i,n)::newnodes, arcs)
5132 let (get_node: int -> 'node graph -> 'node) = fun i -> function
5133 (nodes, arcs) -> List.assoc i nodes
5134
5135 let (get_free: 'a graph -> int) = function
5136 (nodes, arcs) -> (maximum (List.map fst nodes))+1
5137 (* require no cycle !!
5138 TODO if cycle check that we have already visited a node *)
5139 let rec (succ_all: int -> 'a graph -> (int list)) = fun i -> function
5140 (nodes, arcs) as g ->
5141 let direct = succ i g in
5142 union direct (union_list (List.map (fun i -> succ_all i g) direct))
5143 let rec (pred_all: int -> 'a graph -> (int list)) = fun i -> function
5144 (nodes, arcs) as g ->
5145 let direct = pred i g in
5146 union direct (union_list (List.map (fun i -> pred_all i g) direct))
5147 (* require that the nodes are different !! *)
5148 let rec (equal: 'a graph -> 'a graph -> bool) = fun g1 g2 ->
5149 let ((nodes1, arcs1),(nodes2, arcs2)) = (g1,g2) in
5150 try
5151 (* do 2 things, check same length and to assoc *)
5152 let conv = assoc_map nodes1 nodes2 in
5153 List.for_all (fun (i1,i2) ->
5154 List.mem (List.assoc i1 conv, List.assoc i2 conv) arcs2)
5155 arcs1
5156 && (List.length arcs1 = List.length arcs2)
5157 (* could think that only forall is needed, but need check same lenth too*)
5158 with _ -> false
5159
5160 let (display: 'a graph -> ('a -> unit) -> unit) = fun g display_func ->
5161 let rec aux depth i =
5162 print_n depth " ";
5163 print_int i; print_string "->"; display_func (get_node i g);
5164 print_string "\n";
5165 List.iter (aux (depth+2)) (succ i g)
5166 in aux 0 1
5167
5168 let (display_dot: 'a graph -> ('a -> string) -> unit)= fun (nodes,arcs) func ->
5169 let file = open_out "test.dot" in
5170 output_string file "digraph misc {\n" ;
5171 List.iter (fun (n, node) ->
5172 output_int file n; output_string file " [label=\"";
5173 output_string file (func node); output_string file " \"];\n"; ) nodes;
5174 List.iter (fun (i1,i2) -> output_int file i1 ; output_string file " -> " ;
5175 output_int file i2 ; output_string file " ;\n"; ) arcs;
5176 output_string file "}\n" ;
5177 close_out file;
5178 let status = Unix.system "viewdot test.dot" in
5179 ()
5180 (* todo: faire = graphe (int can change !!! => cant make simply =)
5181 reassign number first !!
5182 *)
5183
5184 (* todo: mettre diff(modulo = !!) en rouge *)
5185 let (display_dot2: 'a graph -> 'a graph -> ('a -> string) -> unit) =
5186 fun (nodes1, arcs1) (nodes2, arcs2) func ->
5187 let file = open_out "test.dot" in
5188 output_string file "digraph misc {\n" ;
5189 output_string file "rotate = 90;\n";
5190 List.iter (fun (n, node) ->
5191 output_string file "100"; output_int file n;
5192 output_string file " [label=\"";
5193 output_string file (func node); output_string file " \"];\n"; ) nodes1;
5194 List.iter (fun (n, node) ->
5195 output_string file "200"; output_int file n;
5196 output_string file " [label=\"";
5197 output_string file (func node); output_string file " \"];\n"; ) nodes2;
5198 List.iter (fun (i1,i2) ->
5199 output_string file "100"; output_int file i1 ; output_string file " -> " ;
5200 output_string file "100"; output_int file i2 ; output_string file " ;\n";
5201 )
5202 arcs1;
5203 List.iter (fun (i1,i2) ->
5204 output_string file "200"; output_int file i1 ; output_string file " -> " ;
5205 output_string file "200"; output_int file i2 ; output_string file " ;\n"; )
5206 arcs2;
5207 (* output_string file "500 -> 1001; 500 -> 2001}\n" ; *)
5208 output_string file "}\n" ;
5209 close_out file;
5210 let status = Unix.system "viewdot test.dot" in
5211 ()
5212
5213
5214 *)
5215 (*****************************************************************************)
5216 (* Generic op *)
5217 (*****************************************************************************)
5218 (* overloading *)
5219
5220 let map = List.map (* note: really really slow, use rev_map if possible *)
5221 let filter = List.filter
5222 let fold = List.fold_left
5223 let member = List.mem
5224 let iter = List.iter
5225 let find = List.find
5226 let exists = List.exists
5227 let forall = List.for_all
5228 let big_union f xs = xs +> map f +> fold union_set empty_set
5229 (* let empty = [] *)
5230 let empty_list = []
5231 let sort = List.sort
5232 let length = List.length
5233 (* in prelude now: let null xs = match xs with [] -> true | _ -> false *)
5234 let head = List.hd
5235 let tail = List.tl
5236 let is_singleton = fun xs -> List.length xs =|= 1
5237
5238 (*****************************************************************************)
5239 (* Geometry (raytracer) *)
5240 (*****************************************************************************)
5241
5242 type vector = (float * float * float)
5243 type point = vector
5244 type color = vector (* color(0-1) *)
5245
5246 (* todo: factorise *)
5247 let (dotproduct: vector * vector -> float) =
5248 fun ((x1,y1,z1),(x2,y2,z2)) -> (x1*.x2 +. y1*.y2 +. z1*.z2)
5249 let (vector_length: vector -> float) =
5250 fun (x,y,z) -> sqrt (square x +. square y +. square z)
5251 let (minus_point: point * point -> vector) =
5252 fun ((x1,y1,z1),(x2,y2,z2)) -> ((x1 -. x2),(y1 -. y2),(z1 -. z2))
5253 let (distance: point * point -> float) =
5254 fun (x1, x2) -> vector_length (minus_point (x2,x1))
5255 let (normalise: vector -> vector) =
5256 fun (x,y,z) ->
5257 let len = vector_length (x,y,z) in (x /. len, y /. len, z /. len)
5258 let (mult_coeff: vector -> float -> vector) =
5259 fun (x,y,z) c -> (x *. c, y *. c, z *. c)
5260 let (add_vector: vector -> vector -> vector) =
5261 fun v1 v2 -> let ((x1,y1,z1),(x2,y2,z2)) = (v1,v2) in
5262 (x1+.x2, y1+.y2, z1+.z2)
5263 let (mult_vector: vector -> vector -> vector) =
5264 fun v1 v2 -> let ((x1,y1,z1),(x2,y2,z2)) = (v1,v2) in
5265 (x1*.x2, y1*.y2, z1*.z2)
5266 let sum_vector = List.fold_left add_vector (0.0,0.0,0.0)
5267
5268 (*****************************************************************************)
5269 (* Pics (raytracer) *)
5270 (*****************************************************************************)
5271
5272 type pixel = (int * int * int) (* RGB *)
5273
5274 (* required pixel list in row major order, line after line *)
5275 let (write_ppm: int -> int -> (pixel list) -> string -> unit) = fun
5276 width height xs filename ->
5277 let chan = open_out filename in
5278 begin
5279 output_string chan "P6\n";
5280 output_string chan ((string_of_int width) ^ "\n");
5281 output_string chan ((string_of_int height) ^ "\n");
5282 output_string chan "255\n";
5283 List.iter (fun (r,g,b) ->
5284 List.iter (fun byt -> output_byte chan byt) [r;g;b]
5285 ) xs;
5286 close_out chan
5287 end
5288
5289 let test_ppm1 () = write_ppm 100 100
5290 ((generate (50*100) (1,45,100)) ++ (generate (50*100) (1,1,100)))
5291 "img.ppm"
5292
5293 (*****************************************************************************)
5294 (* Diff (lfs) *)
5295 (*****************************************************************************)
5296 type diff = Match | BnotinA | AnotinB
5297
5298 let (diff: (int -> int -> diff -> unit)-> (string list * string list) -> unit)=
5299 fun f (xs,ys) ->
5300 let file1 = "/tmp/diff1-" ^ (string_of_int (Unix.getuid ())) in
5301 let file2 = "/tmp/diff2-" ^ (string_of_int (Unix.getuid ())) in
5302 let fileresult = "/tmp/diffresult-" ^ (string_of_int (Unix.getuid ())) in
5303 write_file file1 (unwords xs);
5304 write_file file2 (unwords ys);
5305 command2
5306 ("diff --side-by-side -W 1 " ^ file1 ^ " " ^ file2 ^ " > " ^ fileresult);
5307 let res = cat fileresult in
5308 let a = ref 0 in
5309 let b = ref 0 in
5310 res +> List.iter (fun s ->
5311 match s with
5312 | ("" | " ") -> f !a !b Match; incr a; incr b;
5313 | ">" -> f !a !b BnotinA; incr b;
5314 | ("|" | "/" | "\\" ) ->
5315 f !a !b BnotinA; f !a !b AnotinB; incr a; incr b;
5316 | "<" -> f !a !b AnotinB; incr a;
5317 | _ -> raise Impossible
5318 )
5319 (*
5320 let _ =
5321 diff
5322 ["0";"a";"b";"c";"d"; "f";"g";"h";"j";"q"; "z"]
5323 [ "a";"b";"c";"d";"e";"f";"g";"i";"j";"k";"r";"x";"y";"z"]
5324 (fun x y -> pr "match")
5325 (fun x y -> pr "a_not_in_b")
5326 (fun x y -> pr "b_not_in_a")
5327 *)
5328
5329 let (diff2: (int -> int -> diff -> unit) -> (string * string) -> unit) =
5330 fun f (xstr,ystr) ->
5331 write_file "/tmp/diff1" xstr;
5332 write_file "/tmp/diff2" ystr;
5333 command2
5334 ("diff --side-by-side --left-column -W 1 " ^
5335 "/tmp/diff1 /tmp/diff2 > /tmp/diffresult");
5336 let res = cat "/tmp/diffresult" in
5337 let a = ref 0 in
5338 let b = ref 0 in
5339 res +> List.iter (fun s ->
5340 match s with
5341 | "(" -> f !a !b Match; incr a; incr b;
5342 | ">" -> f !a !b BnotinA; incr b;
5343 | "|" -> f !a !b BnotinA; f !a !b AnotinB; incr a; incr b;
5344 | "<" -> f !a !b AnotinB; incr a;
5345 | _ -> raise Impossible
5346 )
5347
5348
5349 (*****************************************************************************)
5350 (* Parsers (aop-colcombet) *)
5351 (*****************************************************************************)
5352
5353 let parserCommon lexbuf parserer lexer =
5354 try
5355 let result = parserer lexer lexbuf in
5356 result
5357 with Parsing.Parse_error ->
5358 print_string "buf: "; print_string lexbuf.Lexing.lex_buffer;
5359 print_string "\n";
5360 print_string "current: "; print_int lexbuf.Lexing.lex_curr_pos;
5361 print_string "\n";
5362 raise Parsing.Parse_error
5363
5364
5365 (* marche pas ca neuneu *)
5366 (*
5367 let getDoubleParser parserer lexer string =
5368 let lexbuf1 = Lexing.from_string string in
5369 let chan = open_in string in
5370 let lexbuf2 = Lexing.from_channel chan in
5371 (parserCommon lexbuf1 parserer lexer , parserCommon lexbuf2 parserer lexer )
5372 *)
5373
5374 let getDoubleParser parserer lexer =
5375 (
5376 (function string ->
5377 let lexbuf1 = Lexing.from_string string in
5378 parserCommon lexbuf1 parserer lexer
5379 ),
5380 (function string ->
5381 let chan = open_in string in
5382 let lexbuf2 = Lexing.from_channel chan in
5383 parserCommon lexbuf2 parserer lexer
5384 ))
5385
5386
5387 (*****************************************************************************)
5388 (* parser combinators *)
5389 (*****************************************************************************)
5390
5391 (* cf parser_combinators.ml
5392 *
5393 * Could also use ocaml stream. but not backtrack and forced to do LL,
5394 * so combinators are better.
5395 *
5396 *)
5397
5398
5399 (*****************************************************************************)
5400 (* Parser related (cocci) *)
5401 (*****************************************************************************)
5402
5403 type parse_info = {
5404 str: string;
5405 charpos: int;
5406
5407 line: int;
5408 column: int;
5409 file: filename;
5410 }
5411 (* with sexp *)
5412
5413 let fake_parse_info = {
5414 charpos = -1; str = "";
5415 line = -1; column = -1; file = "";
5416 }
5417
5418 let string_of_parse_info x =
5419 spf "%s at %s:%d:%d" x.str x.file x.line x.column
5420 let string_of_parse_info_bis x =
5421 spf "%s:%d:%d" x.file x.line x.column
5422
5423 let (info_from_charpos2: int -> filename -> (int * int * string)) =
5424 fun charpos filename ->
5425
5426 (* Currently lexing.ml does not handle the line number position.
5427 * Even if there is some fields in the lexing structure, they are not
5428 * maintained by the lexing engine :( So the following code does not work:
5429 * let pos = Lexing.lexeme_end_p lexbuf in
5430 * sprintf "at file %s, line %d, char %d" pos.pos_fname pos.pos_lnum
5431 * (pos.pos_cnum - pos.pos_bol) in
5432 * Hence this function to overcome the previous limitation.
5433 *)
5434 let chan = open_in filename in
5435 let linen = ref 0 in
5436 let posl = ref 0 in
5437 let rec charpos_to_pos_aux last_valid =
5438 let s =
5439 try Some (input_line chan)
5440 with End_of_file when charpos =|= last_valid -> None in
5441 incr linen;
5442 match s with
5443 Some s ->
5444 let s = s ^ "\n" in
5445 if (!posl + slength s > charpos)
5446 then begin
5447 close_in chan;
5448 (!linen, charpos - !posl, s)
5449 end
5450 else begin
5451 posl := !posl + slength s;
5452 charpos_to_pos_aux !posl;
5453 end
5454 | None -> (!linen, charpos - !posl, "\n")
5455 in
5456 let res = charpos_to_pos_aux 0 in
5457 close_in chan;
5458 res
5459
5460 let info_from_charpos a b =
5461 profile_code "Common.info_from_charpos" (fun () -> info_from_charpos2 a b)
5462
5463
5464
5465 let full_charpos_to_pos2 = fun filename ->
5466
5467 let size = (filesize filename + 2) in
5468
5469 let arr = Array.create size (0,0) in
5470
5471 let chan = open_in filename in
5472
5473 let charpos = ref 0 in
5474 let line = ref 0 in
5475
5476 let rec full_charpos_to_pos_aux () =
5477 try
5478 let s = (input_line chan) in
5479 incr line;
5480
5481 (* '... +1 do' cos input_line dont return the trailing \n *)
5482 for i = 0 to (slength s - 1) + 1 do
5483 arr.(!charpos + i) <- (!line, i);
5484 done;
5485 charpos := !charpos + slength s + 1;
5486 full_charpos_to_pos_aux();
5487
5488 with End_of_file ->
5489 for i = !charpos to Array.length arr - 1 do
5490 arr.(i) <- (!line, 0);
5491 done;
5492 ();
5493 in
5494 begin
5495 full_charpos_to_pos_aux ();
5496 close_in chan;
5497 arr
5498 end
5499 let full_charpos_to_pos a =
5500 profile_code "Common.full_charpos_to_pos" (fun () -> full_charpos_to_pos2 a)
5501
5502 let test_charpos file =
5503 full_charpos_to_pos file +> dump +> pr2
5504
5505
5506
5507 let complete_parse_info filename table x =
5508 { x with
5509 file = filename;
5510 line = fst (table.(x.charpos));
5511 column = snd (table.(x.charpos));
5512 }
5513
5514
5515
5516 let full_charpos_to_pos_large2 = fun filename ->
5517
5518 let size = (filesize filename + 2) in
5519
5520 (* old: let arr = Array.create size (0,0) in *)
5521 let arr1 = Bigarray.Array1.create
5522 Bigarray.int Bigarray.c_layout size in
5523 let arr2 = Bigarray.Array1.create
5524 Bigarray.int Bigarray.c_layout size in
5525 Bigarray.Array1.fill arr1 0;
5526 Bigarray.Array1.fill arr2 0;
5527
5528 let chan = open_in filename in
5529
5530 let charpos = ref 0 in
5531 let line = ref 0 in
5532
5533 let rec full_charpos_to_pos_aux () =
5534 let s = (input_line chan) in
5535 incr line;
5536
5537 (* '... +1 do' cos input_line dont return the trailing \n *)
5538 for i = 0 to (slength s - 1) + 1 do
5539 (* old: arr.(!charpos + i) <- (!line, i); *)
5540 arr1.{!charpos + i} <- (!line);
5541 arr2.{!charpos + i} <- i;
5542 done;
5543 charpos := !charpos + slength s + 1;
5544 full_charpos_to_pos_aux() in
5545 begin
5546 (try
5547 full_charpos_to_pos_aux ();
5548 with End_of_file ->
5549 for i = !charpos to (* old: Array.length arr *)
5550 Bigarray.Array1.dim arr1 - 1 do
5551 (* old: arr.(i) <- (!line, 0); *)
5552 arr1.{i} <- !line;
5553 arr2.{i} <- 0;
5554 done;
5555 ());
5556 close_in chan;
5557 (fun i -> arr1.{i}, arr2.{i})
5558 end
5559 let full_charpos_to_pos_large a =
5560 profile_code "Common.full_charpos_to_pos_large"
5561 (fun () -> full_charpos_to_pos_large2 a)
5562
5563
5564 let complete_parse_info_large filename table x =
5565 { x with
5566 file = filename;
5567 line = fst (table (x.charpos));
5568 column = snd (table (x.charpos));
5569 }
5570
5571 (*---------------------------------------------------------------------------*)
5572 (* Decalage is here to handle stuff such as cpp which include file and who
5573 * can make shift.
5574 *)
5575 let (error_messagebis: filename -> (string * int) -> int -> string)=
5576 fun filename (lexeme, lexstart) decalage ->
5577
5578 let charpos = lexstart + decalage in
5579 let tok = lexeme in
5580 let (line, pos, linecontent) = info_from_charpos charpos filename in
5581 sprintf "File \"%s\", line %d, column %d, charpos = %d
5582 around = '%s', whole content = %s"
5583 filename line pos charpos tok (chop linecontent)
5584
5585 let error_message = fun filename (lexeme, lexstart) ->
5586 try error_messagebis filename (lexeme, lexstart) 0
5587 with
5588 End_of_file ->
5589 ("PB in Common.error_message, position " ^ i_to_s lexstart ^
5590 " given out of file:" ^ filename)
5591
5592
5593
5594 let error_message_short = fun filename (lexeme, lexstart) ->
5595 try
5596 let charpos = lexstart in
5597 let (line, pos, linecontent) = info_from_charpos charpos filename in
5598 sprintf "File \"%s\", line %d" filename line
5599
5600 with End_of_file ->
5601 begin
5602 ("PB in Common.error_message, position " ^ i_to_s lexstart ^
5603 " given out of file:" ^ filename);
5604 end
5605
5606
5607
5608 (*****************************************************************************)
5609 (* Regression testing bis (cocci) *)
5610 (*****************************************************************************)
5611
5612 (* todo: keep also size of file, compute md5sum ? cos maybe the file
5613 * has changed!.
5614 *
5615 * todo: could also compute the date, or some version info of the program,
5616 * can record the first date when was found a OK, the last date where
5617 * was ok, and then first date when found fail. So the
5618 * Common.Ok would have more information that would be passed
5619 * to the Common.Pb of date * date * date * string peut etre.
5620 *
5621 * todo? maybe use plain text file instead of marshalling.
5622 *)
5623
5624 type score_result = Ok | Pb of string
5625 (* with sexp *)
5626 type score = (string (* usually a filename *), score_result) Hashtbl.t
5627 (* with sexp *)
5628 type score_list = (string (* usually a filename *) * score_result) list
5629 (* with sexp *)
5630
5631 let empty_score () = (Hashtbl.create 101 : score)
5632
5633
5634
5635 let regression_testing_vs newscore bestscore =
5636
5637 let newbestscore = empty_score () in
5638
5639 let allres =
5640 (hash_to_list newscore +> List.map fst)
5641 $+$
5642 (hash_to_list bestscore +> List.map fst)
5643 in
5644 begin
5645 allres +> List.iter (fun res ->
5646 match
5647 optionise (fun () -> Hashtbl.find newscore res),
5648 optionise (fun () -> Hashtbl.find bestscore res)
5649 with
5650 | None, None -> raise Impossible
5651 | Some x, None ->
5652 Printf.printf "new test file appeared: %s\n" res;
5653 Hashtbl.add newbestscore res x;
5654 | None, Some x ->
5655 Printf.printf "old test file disappeared: %s\n" res;
5656 | Some newone, Some bestone ->
5657 (match newone, bestone with
5658 | Ok, Ok ->
5659 Hashtbl.add newbestscore res Ok
5660 | Pb x, Ok ->
5661 Printf.printf
5662 "PBBBBBBBB: a test file does not work anymore!!! : %s\n" res;
5663 Printf.printf "Error : %s\n" x;
5664 Hashtbl.add newbestscore res Ok
5665 | Ok, Pb x ->
5666 Printf.printf "Great: a test file now works: %s\n" res;
5667 Hashtbl.add newbestscore res Ok
5668 | Pb x, Pb y ->
5669 Hashtbl.add newbestscore res (Pb x);
5670 if not (x =$= y)
5671 then begin
5672 Printf.printf
5673 "Semipb: still error but not same error : %s\n" res;
5674 Printf.printf "%s\n" (chop ("Old error: " ^ y));
5675 Printf.printf "New error: %s\n" x;
5676 end
5677 )
5678 );
5679 flush stdout; flush stderr;
5680 newbestscore
5681 end
5682
5683 let regression_testing newscore best_score_file =
5684
5685 pr2 ("regression file: "^ best_score_file);
5686 let (bestscore : score) =
5687 if not (Sys.file_exists best_score_file)
5688 then write_value (empty_score()) best_score_file;
5689 get_value best_score_file
5690 in
5691 let newbestscore = regression_testing_vs newscore bestscore in
5692 write_value newbestscore (best_score_file ^ ".old");
5693 write_value newbestscore best_score_file;
5694 ()
5695
5696
5697
5698
5699 let string_of_score_result v =
5700 match v with
5701 | Ok -> "Ok"
5702 | Pb s -> "Pb: " ^ s
5703
5704 let total_scores score =
5705 let total = hash_to_list score +> List.length in
5706 let good = hash_to_list score +> List.filter
5707 (fun (s, v) -> v =*= Ok) +> List.length in
5708 good, total
5709
5710
5711 let print_total_score score =
5712 pr2 "--------------------------------";
5713 pr2 "total score";
5714 pr2 "--------------------------------";
5715 let (good, total) = total_scores score in
5716 pr2 (sprintf "good = %d/%d" good total)
5717
5718 let print_score score =
5719 score +> hash_to_list +> List.iter (fun (k, v) ->
5720 pr2 (sprintf "% s --> %s" k (string_of_score_result v))
5721 );
5722 print_total_score score;
5723 ()
5724
5725
5726 (*****************************************************************************)
5727 (* Scope managment (cocci) *)
5728 (*****************************************************************************)
5729
5730 (* could also make a function Common.make_scope_functions that return
5731 * the new_scope, del_scope, do_in_scope, add_env. Kind of functor :)
5732 *)
5733
5734 type ('a, 'b) scoped_env = ('a, 'b) assoc list
5735
5736 (*
5737 let rec lookup_env f env =
5738 match env with
5739 | [] -> raise Not_found
5740 | []::zs -> lookup_env f zs
5741 | (x::xs)::zs ->
5742 match f x with
5743 | None -> lookup_env f (xs::zs)
5744 | Some y -> y
5745
5746 let member_env_key k env =
5747 try
5748 let _ = lookup_env (fun (k',v) -> if k = k' then Some v else None) env in
5749 true
5750 with Not_found -> false
5751
5752 *)
5753
5754 let rec lookup_env k env =
5755 match env with
5756 | [] -> raise Not_found
5757 | []::zs -> lookup_env k zs
5758 | ((k',v)::xs)::zs ->
5759 if k =*= k'
5760 then v
5761 else lookup_env k (xs::zs)
5762
5763 let member_env_key k env =
5764 match optionise (fun () -> lookup_env k env) with
5765 | None -> false
5766 | Some _ -> true
5767
5768
5769 let new_scope scoped_env = scoped_env := []::!scoped_env
5770 let del_scope scoped_env = scoped_env := List.tl !scoped_env
5771
5772 let do_in_new_scope scoped_env f =
5773 begin
5774 new_scope scoped_env;
5775 let res = f() in
5776 del_scope scoped_env;
5777 res
5778 end
5779
5780 let add_in_scope scoped_env def =
5781 let (current, older) = uncons !scoped_env in
5782 scoped_env := (def::current)::older
5783
5784
5785
5786
5787
5788 (* note that ocaml hashtbl store also old value of a binding when add
5789 * add a newbinding; that's why del_scope works
5790 *)
5791
5792 type ('a, 'b) scoped_h_env = {
5793 scoped_h : ('a, 'b) Hashtbl.t;
5794 scoped_list : ('a, 'b) assoc list;
5795 }
5796
5797 let empty_scoped_h_env () = {
5798 scoped_h = Hashtbl.create 101;
5799 scoped_list = [[]];
5800 }
5801 let clone_scoped_h_env x =
5802 { scoped_h = Hashtbl.copy x.scoped_h;
5803 scoped_list = x.scoped_list;
5804 }
5805
5806 let rec lookup_h_env k env =
5807 Hashtbl.find env.scoped_h k
5808
5809 let member_h_env_key k env =
5810 match optionise (fun () -> lookup_h_env k env) with
5811 | None -> false
5812 | Some _ -> true
5813
5814
5815 let new_scope_h scoped_env =
5816 scoped_env := {!scoped_env with scoped_list = []::!scoped_env.scoped_list}
5817 let del_scope_h scoped_env =
5818 begin
5819 List.hd !scoped_env.scoped_list +> List.iter (fun (k, v) ->
5820 Hashtbl.remove !scoped_env.scoped_h k
5821 );
5822 scoped_env := {!scoped_env with scoped_list =
5823 List.tl !scoped_env.scoped_list
5824 }
5825 end
5826
5827 let do_in_new_scope_h scoped_env f =
5828 begin
5829 new_scope_h scoped_env;
5830 let res = f() in
5831 del_scope_h scoped_env;
5832 res
5833 end
5834
5835 (*
5836 let add_in_scope scoped_env def =
5837 let (current, older) = uncons !scoped_env in
5838 scoped_env := (def::current)::older
5839 *)
5840
5841 let add_in_scope_h x (k,v) =
5842 begin
5843 Hashtbl.add !x.scoped_h k v;
5844 x := { !x with scoped_list =
5845 ((k,v)::(List.hd !x.scoped_list))::(List.tl !x.scoped_list);
5846 };
5847 end
5848
5849 (*****************************************************************************)
5850 (* Terminal *)
5851 (*****************************************************************************)
5852
5853 (* let ansi_terminal = ref true *)
5854
5855 let (_execute_and_show_progress_func: (int (* length *) -> ((unit -> unit) -> unit) -> unit) ref)
5856 = ref
5857 (fun a b ->
5858 failwith "no execute yet, have you included common_extra.cmo?"
5859 )
5860
5861
5862
5863 let execute_and_show_progress len f =
5864 !_execute_and_show_progress_func len f
5865
5866
5867 (* now in common_extra.ml:
5868 * let execute_and_show_progress len f = ...
5869 *)
5870
5871 (*****************************************************************************)
5872 (* Random *)
5873 (*****************************************************************************)
5874
5875 let _init_random = Random.self_init ()
5876 (*
5877 let random_insert i l =
5878 let p = Random.int (length l +1)
5879 in let rec insert i p l =
5880 if (p = 0) then i::l else (hd l)::insert i (p-1) (tl l)
5881 in insert i p l
5882
5883 let rec randomize_list = function
5884 [] -> []
5885 | a::l -> random_insert a (randomize_list l)
5886 *)
5887 let random_list xs =
5888 List.nth xs (Random.int (length xs))
5889
5890 (* todo_opti: use fisher/yates algorithm.
5891 * ref: http://en.wikipedia.org/wiki/Knuth_shuffle
5892 *
5893 * public static void shuffle (int[] array)
5894 * {
5895 * Random rng = new Random ();
5896 * int n = array.length;
5897 * while (--n > 0)
5898 * {
5899 * int k = rng.nextInt(n + 1); // 0 <= k <= n (!)
5900 * int temp = array[n];
5901 * array[n] = array[k];
5902 * array[k] = temp;
5903 * }
5904 * }
5905
5906 *)
5907 let randomize_list xs =
5908 let permut = permutation xs in
5909 random_list permut
5910
5911
5912
5913 let random_subset_of_list num xs =
5914 let array = Array.of_list xs in
5915 let len = Array.length array in
5916
5917 let h = Hashtbl.create 101 in
5918 let cnt = ref num in
5919 while !cnt > 0 do
5920 let x = Random.int len in
5921 if not (Hashtbl.mem h (array.(x))) (* bugfix2: not just x :) *)
5922 then begin
5923 Hashtbl.add h (array.(x)) true; (* bugfix1: not just x :) *)
5924 decr cnt;
5925 end
5926 done;
5927 let objs = hash_to_list h +> List.map fst in
5928 objs
5929
5930
5931
5932 (*****************************************************************************)
5933 (* Flags and actions *)
5934 (*****************************************************************************)
5935
5936 (* I put it inside a func as it can help to give a chance to
5937 * change the globals before getting the options as some
5938 * options sometimes may want to show the default value.
5939 *)
5940 let cmdline_flags_devel () =
5941 [
5942 "-debugger", Arg.Set debugger ,
5943 " option to set if launched inside ocamldebug";
5944 "-profile", Arg.Unit (fun () -> profile := PALL),
5945 " gather timing information about important functions";
5946 ]
5947 let cmdline_flags_verbose () =
5948 [
5949 "-verbose_level", Arg.Set_int verbose_level,
5950 " <int> guess what";
5951 "-disable_pr2_once", Arg.Set disable_pr2_once,
5952 " to print more messages";
5953 "-show_trace_profile", Arg.Set show_trace_profile,
5954 " show trace";
5955 ]
5956
5957 let cmdline_flags_other () =
5958 [
5959 "-nocheck_stack", Arg.Clear check_stack,
5960 " ";
5961 "-batch_mode", Arg.Set _batch_mode,
5962 " no interactivity"
5963 ]
5964
5965 (* potentially other common options but not yet integrated:
5966
5967 "-timeout", Arg.Set_int timeout,
5968 " <sec> interrupt LFS or buggy external plugins";
5969
5970 (* can't be factorized because of the $ cvs stuff, we want the date
5971 * of the main.ml file, not common.ml
5972 *)
5973 "-version", Arg.Unit (fun () ->
5974 pr2 "version: _dollar_Date: 2008/06/14 00:54:22 _dollar_";
5975 raise (Common.UnixExit 0)
5976 ),
5977 " guess what";
5978
5979 "-shorthelp", Arg.Unit (fun () ->
5980 !short_usage_func();
5981 raise (Common.UnixExit 0)
5982 ),
5983 " see short list of options";
5984 "-longhelp", Arg.Unit (fun () ->
5985 !long_usage_func();
5986 raise (Common.UnixExit 0)
5987 ),
5988 "-help", Arg.Unit (fun () ->
5989 !long_usage_func();
5990 raise (Common.UnixExit 0)
5991 ),
5992 " ";
5993 "--help", Arg.Unit (fun () ->
5994 !long_usage_func();
5995 raise (Common.UnixExit 0)
5996 ),
5997 " ";
5998
5999 *)
6000
6001 let cmdline_actions () =
6002 [
6003 "-test_check_stack", " <limit>",
6004 mk_action_1_arg test_check_stack_size;
6005 ]
6006
6007
6008 (*****************************************************************************)
6009 (* Postlude *)
6010 (*****************************************************************************)
6011 (* stuff put here cos of of forward definition limitation of ocaml *)
6012
6013
6014 (* Infix trick, seen in jane street lib and harrop's code, and maybe in GMP *)
6015 module Infix = struct
6016 let (+>) = (+>)
6017 let (==~) = (==~)
6018 let (=~) = (=~)
6019 end
6020
6021
6022 let main_boilerplate f =
6023 if not (!Sys.interactive) then
6024 exn_to_real_unixexit (fun () ->
6025
6026 Sys.set_signal Sys.sigint (Sys.Signal_handle (fun _ ->
6027 pr2 "C-c intercepted, will do some cleaning before exiting";
6028 (* But if do some try ... with e -> and if do not reraise the exn,
6029 * the bubble never goes at top and so I cant really C-c.
6030 *
6031 * A solution would be to not raise, but do the erase_temp_file in the
6032 * syshandler, here, and then exit.
6033 * The current solution is to not do some wild try ... with e
6034 * by having in the exn handler a case: UnixExit x -> raise ... | e ->
6035 *)
6036 Sys.set_signal Sys.sigint Sys.Signal_default;
6037 raise (UnixExit (-1))
6038 ));
6039
6040 (* The finalize below makes it tedious to go back to exn when use
6041 * 'back' in the debugger. Hence this special case. But the
6042 * Common.debugger will be set in main(), so too late, so
6043 * have to be quicker
6044 *)
6045 if Sys.argv +> Array.to_list +> List.exists (fun x -> x =$= "-debugger")
6046 then debugger := true;
6047
6048 finalize (fun ()->
6049 pp_do_in_zero_box (fun () ->
6050 f(); (* <---- here it is *)
6051 ))
6052 (fun()->
6053 if !profile <> PNONE
6054 then pr2 (profile_diagnostic ());
6055 erase_temp_files ();
6056 )
6057 )
6058 (* let _ = if not !Sys.interactive then (main ()) *)
6059
6060
6061 (* based on code found in cameleon from maxence guesdon *)
6062 let md5sum_of_string s =
6063 let com = spf "echo %s | md5sum | cut -d\" \" -f 1"
6064 (Filename.quote s)
6065 in
6066 match cmd_to_list com with
6067 | [s] ->
6068 (*pr2 s;*)
6069 s
6070 | _ -> failwith "md5sum_of_string wrong output"
6071
6072
6073
6074 let with_pr2_to_string f =
6075 let file = new_temp_file "pr2" "out" in
6076 redirect_stdout_stderr file f;
6077 cat file
6078
6079 (* julia: convert something printed using format to print into a string *)
6080 let format_to_string f =
6081 let (nm,o) = Filename.open_temp_file "format_to_s" ".out" in
6082 Format.set_formatter_out_channel o;
6083 let _ = f() in
6084 Format.print_newline();
6085 Format.print_flush();
6086 Format.set_formatter_out_channel stdout;
6087 close_out o;
6088 let i = open_in nm in
6089 let lines = ref [] in
6090 let rec loop _ =
6091 let cur = input_line i in
6092 lines := cur :: !lines;
6093 loop() in
6094 (try loop() with End_of_file -> ());
6095 close_in i;
6096 command2 ("rm -f " ^ nm);
6097 String.concat "\n" (List.rev !lines)
6098
6099
6100
6101 (*****************************************************************************)
6102 (* Misc/test *)
6103 (*****************************************************************************)
6104
6105 let (generic_print: 'a -> string -> string) = fun v typ ->
6106 write_value v "/tmp/generic_print";
6107 command2
6108 ("printf 'let (v:" ^ typ ^ ")= Common.get_value \"/tmp/generic_print\" " ^
6109 " in v;;' " ^
6110 " | calc.top > /tmp/result_generic_print");
6111 cat "/tmp/result_generic_print"
6112 +> drop_while (fun e -> not (e =~ "^#.*")) +> tail
6113 +> unlines
6114 +> (fun s ->
6115 if (s =~ ".*= \\(.+\\)")
6116 then matched1 s
6117 else "error in generic_print, not good format:" ^ s)
6118
6119 (* let main () = pr (generic_print [1;2;3;4] "int list") *)
6120
6121 class ['a] olist (ys: 'a list) =
6122 object(o)
6123 val xs = ys
6124 method view = xs
6125 (* method fold f a = List.fold_left f a xs *)
6126 method fold : 'b. ('b -> 'a -> 'b) -> 'b -> 'b =
6127 fun f accu -> List.fold_left f accu xs
6128 end
6129
6130
6131 (* let _ = write_value ((new setb[])#add 1) "/tmp/test" *)
6132 let typing_sux_test () =
6133 let x = Obj.magic [1;2;3] in
6134 let f1 xs = List.iter print_int xs in
6135 let f2 xs = List.iter print_string xs in
6136 (f1 x; f2 x)
6137
6138 (* let (test: 'a osetb -> 'a ocollection) = fun o -> (o :> 'a ocollection) *)
6139 (* let _ = test (new osetb (Setb.empty)) *)