Source file common.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
open Pp
open Util
open Names
open ModPath
open Namegen
open Nameops
open Table
open Miniml
open Mlutil
let ascii_of_id id =
let s = Id.to_string id in
for i = 0 to String.length s - 2 do
if s.[i] == '_' && s.[i+1] == '_' then warning_id s
done;
Unicode.ascii_of_ident s
let is_mp_bound = function MPbound _ -> true | _ -> false
let pp_par par st = if par then str "(" ++ st ++ str ")" else st
(** [pp_apply] : a head part applied to arguments, possibly with parenthesis *)
let pp_apply st par args = match args with
| [] -> st
| _ -> hov 2 (pp_par par (st ++ spc () ++ prlist_with_sep spc identity args))
(** Same as [pp_apply], but with also protection of the head by parenthesis *)
let pp_apply2 st par args =
let par' = not (List.is_empty args) || par in
pp_apply (pp_par par' st) par args
let pr_binding = function
| [] -> mt ()
| l -> str " " ++ prlist_with_sep (fun () -> str " ") Id.print l
let pp_tuple_light f = function
| [] -> mt ()
| [x] -> f true x
| l ->
pp_par true (prlist_with_sep (fun () -> str "," ++ spc ()) (f false) l)
let pp_tuple f = function
| [] -> mt ()
| [x] -> f x
| l -> pp_par true (prlist_with_sep (fun () -> str "," ++ spc ()) f l)
let pp_boxed_tuple f = function
| [] -> mt ()
| [x] -> f x
| l -> pp_par true (hov 0 (prlist_with_sep (fun () -> str "," ++ spc ()) f l))
let pp_array f = function
| [] -> mt ()
| [x] -> f x
| l -> pp_par true (prlist_with_sep (fun () -> str ";" ++ spc ()) f l)
(** By default, in module Format, you can do horizontal placing of blocks
even if they include newlines, as long as the number of chars in the
blocks is less that a line length. To avoid this awkward situation,
we attach a big virtual size to [fnl] newlines. *)
let fnl () = fnl ()
let fnl2 () = fnl () ++ fnl ()
let space_if = function true -> str " " | false -> mt ()
let begins_with s prefix =
let len = String.length prefix in
String.length s >= len && String.equal (String.sub s 0 len) prefix
let begins_with_CoqXX s =
let n = String.length s in
n >= 4 && s.[0] == 'C' && s.[1] == 'o' && s.[2] == 'q' &&
let i = ref 3 in
try while !i < n do
match s.[!i] with
| '_' -> i:=n
| '0'..'9' -> incr i
| _ -> raise Not_found
done; true
with Not_found -> false
let unquote s =
if lang () != Scheme then s
else String.map (fun c -> if c == '\'' then '~' else c) s
let rec qualify delim = function
| [] -> assert false
| [s] -> s
| ""::l -> qualify delim l
| s::l -> s^delim^(qualify delim l)
let dottify = qualify "."
let pseudo_qualify = qualify "__"
let is_upper s = match s.[0] with 'A' .. 'Z' -> true | _ -> false
let is_lower s = match s.[0] with 'a' .. 'z' | '_' -> true | _ -> false
let lowercase_id id = Id.of_string (String.uncapitalize_ascii (ascii_of_id id))
let uppercase_id id =
let s = ascii_of_id id in
assert (not (String.is_empty s));
if s.[0] == '_' then Id.of_string ("Coq_"^s)
else Id.of_string (String.capitalize_ascii s)
type kind = Term | Type | Cons | Mod
module KOrd =
struct
type t = kind * string
let compare (k1, s1) (k2, s2) =
let c = pervasives_compare k1 k2 in
if c = 0 then String.compare s1 s2
else c
end
module KMap = Map.Make(KOrd)
let upperkind = function
| Type -> lang () == Haskell
| Term -> false
| Cons | Mod -> true
let kindcase_id k id =
if upperkind k then uppercase_id id else lowercase_id id
type env = Id.t list * Id.Set.t
let rec rename_id id avoid =
if Id.Set.mem id avoid then rename_id (increment_subscript id) avoid else id
let rec rename_vars avoid = function
| [] ->
[], avoid
| id :: idl when id == dummy_name ->
let (idl', avoid') = rename_vars avoid idl in
(id :: idl', avoid')
| id :: idl ->
let (idl, avoid) = rename_vars avoid idl in
let id = rename_id (lowercase_id id) avoid in
(id :: idl, Id.Set.add id avoid)
let rename_tvars avoid l =
let rec rename avoid = function
| [] -> [],avoid
| id :: idl ->
let id = rename_id (lowercase_id id) avoid in
let idl, avoid = rename (Id.Set.add id avoid) idl in
(id :: idl, avoid) in
fst (rename avoid l)
let push_vars ids (db,avoid) =
let ids',avoid' = rename_vars avoid ids in
ids', (ids' @ db, avoid')
let get_db_name n (db,_) = List.nth db (pred n)
let register_cleanup, do_cleanup =
let funs = ref [] in
(fun f -> funs:=f::!funs), (fun () -> List.iter (fun f -> f ()) !funs)
type phase = Pre | Impl | Intf
let set_phase, get_phase =
let ph = ref Impl in ((:=) ph), (fun () -> !ph)
let set_keywords, get_keywords =
let k = ref Id.Set.empty in
((:=) k), (fun () -> !k)
let add_global_ids, get_global_ids =
let ids = ref Id.Set.empty in
register_cleanup (fun () -> ids := get_keywords ());
let add s = ids := Id.Set.add s !ids
and get () = !ids
in (add,get)
let empty_env () = [], get_global_ids ()
let mktable_id autoclean =
let m = ref Id.Map.empty in
let clear () = m := Id.Map.empty in
if autoclean then register_cleanup clear;
(fun r v -> m := Id.Map.add r v !m), (fun r -> Id.Map.find r !m), clear
let mktable_ref autoclean =
let m = ref Refmap'.empty in
let clear () = m := Refmap'.empty in
if autoclean then register_cleanup clear;
(fun r v -> m := Refmap'.add r v !m), (fun r -> Refmap'.find r !m), clear
let mktable_modpath autoclean =
let m = ref MPmap.empty in
let clear () = m := MPmap.empty in
if autoclean then register_cleanup clear;
(fun r v -> m := MPmap.add r v !m), (fun r -> MPmap.find r !m), clear
let add_mpfiles_content,get_mpfiles_content,clear_mpfiles_content =
mktable_modpath false
let get_mpfiles_content mp =
try get_mpfiles_content mp
with Not_found -> failwith "get_mpfiles_content"
let mpfiles_add, mpfiles_mem, mpfiles_list, mpfiles_clear =
let m = ref MPset.empty in
let add mp = m:=MPset.add mp !m
and mem mp = MPset.mem mp !m
and list () = MPset.elements !m
and clear () = m:=MPset.empty
in
register_cleanup clear;
(add,mem,list,clear)
let params_ren_add, params_ren_mem =
let m = ref MPset.empty in
let add mp = m:=MPset.add mp !m
and mem mp = MPset.mem mp !m
and clear () = m:=MPset.empty
in
register_cleanup clear;
(add,mem)
type visible_layer = { mp : ModPath.t;
params : ModPath.t list;
mutable content : Label.t KMap.t; }
let pop_visible, push_visible, get_visible =
let vis = ref [] in
register_cleanup (fun () -> vis := []);
let pop () =
match !vis with
| [] -> assert false
| v :: vl ->
vis := vl;
if get_phase () == Impl && modular () && is_modfile v.mp
then add_mpfiles_content v.mp v.content
and push mp mps =
vis := { mp = mp; params = mps; content = KMap.empty } :: !vis
and get () = !vis
in (pop,push,get)
let get_visible_mps () = List.map (function v -> v.mp) (get_visible ())
let top_visible () = match get_visible () with [] -> assert false | v::_ -> v
let top_visible_mp () = (top_visible ()).mp
let add_visible ks l =
let visible = top_visible () in
visible.content <- KMap.add ks l visible.content
module DupOrd =
struct
type t = ModPath.t * Label.t
let compare (mp1, l1) (mp2, l2) =
let c = Label.compare l1 l2 in
if Int.equal c 0 then ModPath.compare mp1 mp2 else c
end
module DupMap = Map.Make(DupOrd)
let add_duplicate, get_duplicate =
let index = ref 0 and dups = ref DupMap.empty in
register_cleanup (fun () -> index := 0; dups := DupMap.empty);
let add mp l =
incr index;
let ren = "Coq__" ^ string_of_int !index in
dups := DupMap.add (mp,l) ren !dups
and get mp l =
try Some (DupMap.find (mp, l) !dups) with Not_found -> None
in (add,get)
type reset_kind = AllButExternal | Everything
let reset_renaming_tables flag =
do_cleanup ();
if flag == Everything then clear_mpfiles_content ()
let modular_rename k id =
let s = ascii_of_id id in
let prefix,is_ok = if upperkind k then "Coq_",is_upper else "coq_",is_lower
in
if not (is_ok s) || Id.Set.mem id (get_keywords ()) || begins_with s prefix
then prefix ^ s
else s
let modfstlev_rename =
let add_index,get_index,_ = mktable_id true in
fun l ->
let id = Label.to_id l in
try
let n = get_index id in
add_index id (n+1);
let s = if n == 0 then "" else string_of_int (n-1) in
"Coq"^s^"_"^(ascii_of_id id)
with Not_found ->
let s = ascii_of_id id in
if is_lower s || begins_with_CoqXX s then
(add_index id 1; "Coq_"^s)
else
(add_index id 0; s)
let rec mp_renaming_fun mp = match mp with
| _ when not (modular ()) && at_toplevel mp -> [""]
| MPdot (mp,l) ->
let lmp = mp_renaming mp in
let mp = match lmp with
| [""] -> modfstlev_rename l
| _ -> modular_rename Mod (Label.to_id l)
in
mp ::lmp
| MPbound mbid ->
let s = modular_rename Mod (MBId.to_id mbid) in
if not (params_ren_mem mp) then [s]
else let i,_,_ = MBId.repr mbid in [s^"__"^string_of_int i]
| MPfile _ ->
assert (modular ());
assert (get_phase () == Pre);
let current_mpfile = (List.last (get_visible ())).mp in
if not (ModPath.equal mp current_mpfile) then mpfiles_add mp;
[string_of_modfile mp]
and mp_renaming =
let add,get,_ = mktable_modpath true in
fun x ->
try if is_mp_bound (base_mp x) then raise Not_found; get x
with Not_found -> let y = mp_renaming_fun x in add x y; y
let ref_renaming_fun (k,r) =
let mp = modpath_of_r r in
let l = mp_renaming mp in
let l = if lang () != Ocaml && not (modular ()) then [""] else l in
let s =
let idg = safe_basename_of_global r in
match l with
| [""] ->
let globs = get_global_ids () in
let id = next_ident_away (kindcase_id k idg) globs in
Id.to_string id
| _ -> modular_rename k idg
in
add_global_ids (Id.of_string s);
s::l
let ref_renaming =
let add,get,_ = mktable_ref true in
fun ((k,r) as x) ->
try if is_mp_bound (base_mp (modpath_of_r r)) then raise Not_found; get r
with Not_found -> let y = ref_renaming_fun x in add r y; y
let rec clash mem mp0 ks = function
| [] -> false
| mp :: _ when ModPath.equal mp mp0 -> false
| mp :: _ when mem mp ks -> true
| _ :: mpl -> clash mem mp0 ks mpl
let mpfiles_clash mp0 ks =
clash (fun mp k -> KMap.mem k (get_mpfiles_content mp)) mp0 ks
(List.rev (mpfiles_list ()))
let rec params_lookup mp0 ks = function
| [] -> false
| param :: _ when ModPath.equal mp0 param -> true
| param :: params ->
let () = match ks with
| (Mod, mp) when String.equal (List.hd (mp_renaming param)) mp -> params_ren_add param
| _ -> ()
in
params_lookup mp0 ks params
let visible_clash mp0 ks =
let rec clash = function
| [] -> false
| v :: _ when ModPath.equal v.mp mp0 -> false
| v :: vis ->
let b = KMap.mem ks v.content in
if b && not (is_mp_bound mp0) then true
else begin
if b then params_ren_add mp0;
if params_lookup mp0 ks v.params then false
else clash vis
end
in clash (get_visible ())
let visible_clash_dbg mp0 ks =
let rec clash = function
| [] -> None
| v :: _ when ModPath.equal v.mp mp0 -> None
| v :: vis ->
try Some (v.mp,KMap.find ks v.content)
with Not_found ->
if params_lookup mp0 ks v.params then None
else clash vis
in clash (get_visible ())
let opened_libraries () =
if not (modular ()) then []
else
let used_files = mpfiles_list () in
let used_ks = List.map (fun mp -> Mod,string_of_modfile mp) used_files in
let to_open =
List.filter
(fun mp ->
not (List.exists (fun k -> KMap.mem k (get_mpfiles_content mp)) used_ks))
used_files
in
mpfiles_clear ();
List.iter mpfiles_add to_open;
mpfiles_list ()
let pp_duplicate k' prefix mp rls olab =
let rls', lbl =
if k' != Mod then
rls, Option.get olab
else
List.tl rls, get_nth_label_mp (mp_length mp - mp_length prefix) mp
in
match get_duplicate prefix lbl with
| Some ren -> dottify (ren :: rls')
| None ->
assert (get_phase () == Pre);
add_duplicate prefix lbl; dottify rls
let fstlev_ks k = function
| [] -> assert false
| [s] -> k,s
| s::_ -> Mod,s
let pp_ocaml_local k prefix mp rls olab =
assert (k != Mod || not (ModPath.equal mp prefix));
let rls' = List.skipn (mp_length prefix) rls in
let k's = fstlev_ks k rls' in
if not (visible_clash prefix k's) then dottify rls'
else pp_duplicate (fst k's) prefix mp rls' olab
let pp_ocaml_bound base rls =
if get_phase () == Pre then ignore (visible_clash base (Mod,List.hd rls));
dottify rls
let pp_ocaml_extern k base rls = match rls with
| [] -> assert false
| base_s :: rls' ->
if (not (modular ()))
|| (List.is_empty rls')
|| (not (mpfiles_mem base))
|| (mpfiles_clash base (fstlev_ks k rls'))
|| (visible_clash base (fstlev_ks k rls'))
then
match visible_clash_dbg base (Mod,base_s) with
| None -> dottify rls
| Some (mp,l) -> error_module_clash base (MPdot (mp,l))
else
dottify rls'
let pp_ocaml_gen k mp rls olab =
match common_prefix_from_list mp (get_visible_mps ()) with
| Some prefix -> pp_ocaml_local k prefix mp rls olab
| None ->
let base = base_mp mp in
if is_mp_bound base then pp_ocaml_bound base rls
else pp_ocaml_extern k base rls
let pp_haskell_gen k mp rls = match rls with
| [] -> assert false
| s::rls' ->
let str = pseudo_qualify rls' in
let str = if is_upper str && not (upperkind k) then ("_"^str) else str in
if ModPath.equal (base_mp mp) (top_visible_mp ()) then str else s^"."^str
let pp_global_with_key k key r =
let ls = ref_renaming (k,r) in
assert (List.length ls > 1);
let s = List.hd ls in
let mp,l = KerName.repr key in
if ModPath.equal mp (top_visible_mp ()) then
(add_visible (k,s) l; unquote s)
else
let rls = List.rev ls in
match lang () with
| Scheme -> unquote s
| JSON -> dottify (List.map unquote rls)
| Haskell -> if modular () then pp_haskell_gen k mp rls else s
| Ocaml -> pp_ocaml_gen k mp rls (Some l)
let pp_global k r =
pp_global_with_key k (repr_of_r r) r
let pp_global_name k r =
let ls = ref_renaming (k,r) in
assert (List.length ls > 1);
List.hd ls
let pp_module mp =
let ls = mp_renaming mp in
match mp with
| MPdot (mp0,l) when ModPath.equal mp0 (top_visible_mp ()) ->
let s = List.hd ls in
add_visible (Mod,s) l; s
| _ -> pp_ocaml_gen Mod mp (List.rev ls) None
(** Special hack for constants of type Ascii.ascii : if an
[Extract Inductive ascii => char] has been declared, then
the constants are directly turned into chars *)
let ascii_type_name = "core.ascii.type"
let ascii_constructor_name = "core.ascii.ascii"
let is_ascii_registered () =
Coqlib.has_ref ascii_type_name
&& Coqlib.has_ref ascii_constructor_name
let ascii_type_ref () = Coqlib.lib_ref ascii_type_name
let ascii_constructor_ref () = Coqlib.lib_ref ascii_constructor_name
let () =
try
let char_type = match lang () with
| Ocaml -> "char"
| Haskell -> "Prelude.Char"
| _ -> raise Not_found
in
String.equal (find_custom @@ ascii_type_ref ()) (char_type)
with Not_found -> false
let is_list_cons l =
List.for_all (function MLcons (_,GlobRef.ConstructRef(_,_),[]) -> true | _ -> false) l
let is_native_char = function
| MLcons(_,gr,l) ->
is_ascii_registered ()
&& GlobRef.CanOrd.equal gr (ascii_constructor_ref ())
&& check_extract_ascii ()
&& is_list_cons l
| _ -> false
let get_native_char c =
let rec cumul = function
| [] -> 0
| MLcons(_,GlobRef.ConstructRef(_,j),[])::l -> (2-j) + 2 * (cumul l)
| _ -> assert false
in
let l = match c with MLcons(_,_,l) -> l | _ -> assert false in
Char.chr (cumul l)
let pp_native_char c = str ("'"^Char.escaped (get_native_char c)^"'")
(** Special hack for constants of type String.string : if an
[Extract Inductive string => string] has been declared, then
the constants are directly turned into string literals *)
let string_type_name = "core.string.type"
let empty_string_name = "core.string.empty"
let string_constructor_name = "core.string.string"
let is_string_registered () =
Coqlib.has_ref string_type_name
&& Coqlib.has_ref empty_string_name
&& Coqlib.has_ref string_constructor_name
let string_type_ref () = Coqlib.lib_ref string_type_name
let empty_string_ref () = Coqlib.lib_ref empty_string_name
let string_constructor_ref () = Coqlib.lib_ref string_constructor_name
let () =
try
let string_type = match lang () with
| Ocaml -> "string"
| Haskell -> "Prelude.String"
| _ -> raise Not_found
in
String.equal (find_custom @@ string_type_ref ()) string_type
with Not_found -> false
let rec is_native_string_rec empty_string_ref string_constructor_ref = function
| MLcons(_, gr, []) -> GlobRef.CanOrd.equal gr empty_string_ref
| MLcons(_, gr, [hd; tl]) ->
GlobRef.CanOrd.equal gr string_constructor_ref
&& is_native_char hd
&& is_native_string_rec empty_string_ref string_constructor_ref tl
| _ -> false
let is_native_string c =
match c with
| MLcons(_, GlobRef.ConstructRef(ind, j), l) ->
is_string_registered ()
&& GlobRef.CanOrd.equal (GlobRef.IndRef ind) (string_type_ref ())
&& check_extract_string ()
&& is_native_string_rec (empty_string_ref ()) (string_constructor_ref ()) c
| _ -> false
let get_native_string c =
let buf = Buffer.create 64 in
let rec get = function
| MLcons(_, gr, []) when GlobRef.CanOrd.equal gr (empty_string_ref ()) ->
Buffer.contents buf
| MLcons(_, gr, [hd; tl]) when GlobRef.CanOrd.equal gr (string_constructor_ref ()) ->
Buffer.add_char buf (get_native_char hd);
get tl
| _ -> assert false
in get c
let pp_native_string c =
str ("\"" ^ String.escaped (get_native_string c) ^ "\"")
let sig_type_ref () = Coqlib.lib_ref "core.sig.type"