forked from rems-project/sail
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonomorphise.ml
4122 lines (3880 loc) · 175 KB
/
monomorphise.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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(**************************************************************************)
(* Sail *)
(* *)
(* Copyright (c) 2013-2017 *)
(* Kathyrn Gray *)
(* Shaked Flur *)
(* Stephen Kell *)
(* Gabriel Kerneis *)
(* Robert Norton-Wright *)
(* Christopher Pulte *)
(* Peter Sewell *)
(* Alasdair Armstrong *)
(* Brian Campbell *)
(* Thomas Bauereiss *)
(* Anthony Fox *)
(* Jon French *)
(* Dominic Mulligan *)
(* Stephen Kell *)
(* Mark Wassell *)
(* *)
(* All rights reserved. *)
(* *)
(* This software was developed by the University of Cambridge Computer *)
(* Laboratory as part of the Rigorous Engineering of Mainstream Systems *)
(* (REMS) project, funded by EPSRC grant EP/K008528/1. *)
(* *)
(* Redistribution and use in source and binary forms, with or without *)
(* modification, are permitted provided that the following conditions *)
(* are met: *)
(* 1. Redistributions of source code must retain the above copyright *)
(* notice, this list of conditions and the following disclaimer. *)
(* 2. Redistributions in binary form must reproduce the above copyright *)
(* notice, this list of conditions and the following disclaimer in *)
(* the documentation and/or other materials provided with the *)
(* distribution. *)
(* *)
(* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' *)
(* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *)
(* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A *)
(* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR *)
(* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, *)
(* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *)
(* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF *)
(* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND *)
(* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, *)
(* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT *)
(* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF *)
(* SUCH DAMAGE. *)
(**************************************************************************)
(* Could fix list:
- Can probably trigger non-termination in the analysis or constant
propagation with carefully constructed recursive (or mutually
recursive) functions
*)
open Parse_ast
open Ast
open Ast_util
module Big_int = Nat_big_num
open Type_check
let size_set_limit = 64
let optmap v f =
match v with
| None -> None
| Some v -> Some (f v)
let kbindings_from_list = List.fold_left (fun s (v,i) -> KBindings.add v i s) KBindings.empty
let bindings_from_list = List.fold_left (fun s (v,i) -> Bindings.add v i s) Bindings.empty
(* union was introduced in 4.03.0, a bit too recently *)
let bindings_union s1 s2 =
Bindings.merge (fun _ x y -> match x,y with
| _, (Some x) -> Some x
| (Some x), _ -> Some x
| _, _ -> None) s1 s2
let kbindings_union s1 s2 =
KBindings.merge (fun _ x y -> match x,y with
| _, (Some x) -> Some x
| (Some x), _ -> Some x
| _, _ -> None) s1 s2
let ids_in_exp exp =
let open Rewriter in
fold_exp {
(pure_exp_alg IdSet.empty IdSet.union) with
e_id = IdSet.singleton;
lEXP_id = IdSet.singleton;
lEXP_memory = (fun (id,s) -> List.fold_left IdSet.union (IdSet.singleton id) s);
lEXP_cast = (fun (_,id) -> IdSet.singleton id)
} exp
let make_vector_lit sz i =
let f j = if Big_int.equal (Big_int.modulus (Big_int.shift_right i (sz-j-1)) (Big_int.of_int 2)) Big_int.zero then '0' else '1' in
let s = String.init sz f in
L_aux (L_bin s,Generated Unknown)
let tabulate f n =
let rec aux acc n =
let acc' = f n::acc in
if Big_int.equal n Big_int.zero then acc' else aux acc' (Big_int.sub n (Big_int.of_int 1))
in if Big_int.equal n Big_int.zero then [] else aux [] (Big_int.sub n (Big_int.of_int 1))
let make_vectors sz =
tabulate (make_vector_lit sz) (Big_int.shift_left (Big_int.of_int 1) sz)
let is_inc_vec typ =
try
let (_, ord, _) = vector_typ_args_of typ in
is_order_inc ord
with _ -> false
let rec cross = function
| [] -> failwith "cross"
| [(x,l)] -> List.map (fun y -> [(x,y)]) l
| (x,l)::t ->
let t' = cross t in
List.concat (List.map (fun y -> List.map (fun l' -> (x,y)::l') t') l)
let rec cross' = function
| [] -> [[]]
| (h::t) ->
let t' = cross' t in
List.concat (List.map (fun x -> List.map (fun l -> x::l) t') h)
let rec cross'' = function
| [] -> [[]]
| (k,None)::t -> List.map (fun l -> (k,None)::l) (cross'' t)
| (k,Some h)::t ->
let t' = cross'' t in
List.concat (List.map (fun x -> List.map (fun l -> (k,Some x)::l) t') h)
let kidset_bigunion = function
| [] -> KidSet.empty
| h::t -> List.fold_left KidSet.union h t
(* TODO: deal with non-set constraints, intersections, etc somehow *)
let extract_set_nc env l var nc =
let vars = Spec_analysis.equal_kids_ncs var [nc] in
let rec aux_or (NC_aux (nc,l)) =
match nc with
| NC_equal (Nexp_aux (Nexp_var id,_), Nexp_aux (Nexp_constant n,_))
when KidSet.mem id vars ->
Some [n]
| NC_or (nc1,nc2) ->
(match aux_or nc1, aux_or nc2 with
| Some l1, Some l2 -> Some (l1 @ l2)
| _, _ -> None)
| _ -> None
in
(* Lazily expand constraints to keep close to the original form *)
let rec aux expanded (NC_aux (nc,l) as nc_full) =
let re nc = NC_aux (nc,l) in
match nc with
| NC_set (id,is) when KidSet.mem id vars -> Some (is,re NC_true)
| NC_equal (Nexp_aux (Nexp_var id,_), Nexp_aux (Nexp_constant n,_))
when KidSet.mem id vars ->
Some ([n], re NC_true)
(* Turn (i <= 'v & 'v <= j & ...) into set constraint ('v in {i..j}) *)
| NC_and (NC_aux (NC_bounded_le (Nexp_aux (Nexp_constant n, _), Nexp_aux (Nexp_var kid, _)), _) as nc1, nc2)
when KidSet.mem kid vars ->
let aux2 () = match aux expanded nc2 with
| Some (is, nc2') -> Some (is, re (NC_and (nc1, nc2')))
| None -> None
in
begin match constraint_conj nc2 with
| NC_aux (NC_bounded_le (Nexp_aux (Nexp_var kid', _), Nexp_aux (Nexp_constant n', _)), _) :: ncs
when KidSet.mem kid' vars ->
let len = Big_int.succ (Big_int.sub n' n) in
if Big_int.less_equal Big_int.zero len && Big_int.less_equal len (Big_int.of_int size_set_limit) then
let elem i = Big_int.add n (Big_int.of_int i) in
let is = List.init (Big_int.to_int len) elem in
if aux expanded (List.fold_left nc_and nc_true ncs) <> None then
raise (Reporting.err_general l ("Multiple set constraints for " ^ string_of_kid var))
else Some (is, nc_full)
else aux2 ()
| _ -> aux2 ()
end
| NC_and (nc1,nc2) ->
(match aux expanded nc1, aux expanded nc2 with
| None, None -> None
| None, Some (is,nc2') -> Some (is, re (NC_and (nc1,nc2')))
| Some (is,nc1'), None -> Some (is, re (NC_and (nc1',nc2)))
| Some _, Some _ ->
raise (Reporting.err_general l ("Multiple set constraints for " ^ string_of_kid var)))
| NC_or _ ->
(match aux_or nc_full with
| Some is -> Some (is, re NC_true)
| None -> None)
| _ -> if expanded then None else aux true (Env.expand_constraint_synonyms env nc_full)
in match aux false nc with
| Some is -> is
| None ->
raise (Reporting.err_general l ("No set constraint for " ^ string_of_kid var ^
" in " ^ string_of_n_constraint nc))
let rec peel = function
| [], l -> ([], l)
| h1::t1, h2::t2 -> let (l1,l2) = peel (t1, t2) in ((h1,h2)::l1,l2)
| _,_ -> assert false
let rec split_insts = function
| [] -> [],[]
| (k,None)::t -> let l1,l2 = split_insts t in l1,k::l2
| (k,Some v)::t -> let l1,l2 = split_insts t in (k,v)::l1,l2
let apply_kid_insts kid_insts nc t =
let kid_insts, kids' = split_insts kid_insts in
let kid_insts = List.map
(fun (v,i) -> (kopt_kid v,Nexp_aux (Nexp_constant i,Generated Unknown)))
kid_insts in
let subst = kbindings_from_list kid_insts in
kids', subst_kids_nc subst nc, subst_kids_typ subst t
let rec inst_src_type insts (Typ_aux (ty,l) as typ) =
match ty with
| Typ_id _
| Typ_var _
-> insts,typ
| Typ_fn _ ->
raise (Reporting.err_general l "Function type in constructor")
| Typ_bidir _ ->
raise (Reporting.err_general l "Mapping type in constructor")
| Typ_tup ts ->
let insts,ts =
List.fold_right
(fun typ (insts,ts) -> let insts,typ = inst_src_type insts typ in insts,typ::ts)
ts (insts,[])
in insts, Typ_aux (Typ_tup ts,l)
| Typ_app (id,args) ->
let insts,ts =
List.fold_right
(fun arg (insts,args) -> let insts,arg = inst_src_typ_arg insts arg in insts,arg::args)
args (insts,[])
in insts, Typ_aux (Typ_app (id,ts),l)
| Typ_exist (kopts, nc, t) -> begin
let kid_insts, insts' = peel (kopts,insts) in
let kopts', nc', t' = apply_kid_insts kid_insts nc t in
match kopts' with
| [] -> insts', t'
| _ -> insts', Typ_aux (Typ_exist (kopts', nc', t'), l)
end
| Typ_internal_unknown -> Reporting.unreachable l __POS__ "escaped Typ_internal_unknown"
and inst_src_typ_arg insts (A_aux (ta,l) as tyarg) =
match ta with
| A_nexp _
| A_order _
| A_bool _
-> insts, tyarg
| A_typ typ ->
let insts', typ' = inst_src_type insts typ in
insts', A_aux (A_typ typ',l)
let rec contains_exist (Typ_aux (ty,l)) =
match ty with
| Typ_id _
| Typ_var _
-> false
| Typ_fn (t1,t2,_) -> List.exists contains_exist t1 || contains_exist t2
| Typ_bidir (t1, t2, _) -> contains_exist t1 || contains_exist t2
| Typ_tup ts -> List.exists contains_exist ts
| Typ_app (_,args) -> List.exists contains_exist_arg args
| Typ_exist _ -> true
| Typ_internal_unknown -> Reporting.unreachable l __POS__ "escaped Typ_internal_unknown"
and contains_exist_arg (A_aux (arg,_)) =
match arg with
| A_nexp _
| A_order _
| A_bool _
-> false
| A_typ typ -> contains_exist typ
let is_number typ = match destruct_numeric typ with
| Some _ -> true
| None -> false
let rec size_nvars_nexp (Nexp_aux (ne,_)) =
match ne with
| Nexp_var v -> [v]
| Nexp_id _
| Nexp_constant _
-> []
| Nexp_times (n1,n2)
| Nexp_sum (n1,n2)
| Nexp_minus (n1,n2)
-> size_nvars_nexp n1 @ size_nvars_nexp n2
| Nexp_exp n
| Nexp_neg n
-> size_nvars_nexp n
| Nexp_app (_,args) -> List.concat (List.map size_nvars_nexp args)
(* Given a type for a constructor, work out which refinements we ought to produce *)
(* TODO collision avoidance *)
let split_src_type all_errors env id ty (TypQ_aux (q,ql)) =
let cannot l msg default =
let open Reporting in
match all_errors with
| None -> raise (err_general l msg)
| Some flag -> begin
flag := false;
print_err l "Error" msg;
default
end
in
let i = string_of_id id in
(* This was originally written for the general case, but I cut it down to the
more manageable prenex-form below *)
let rec size_nvars_ty typ =
let Typ_aux (ty,l) = Env.expand_synonyms env typ in
match ty with
| Typ_id _
| Typ_var _
-> (KidSet.empty,[[],typ])
| Typ_fn _ ->
cannot l ("Function type in constructor " ^ i) (KidSet.empty,[[],typ])
| Typ_bidir _ ->
cannot l ("Mapping type in constructor " ^ i) (KidSet.empty,[[],typ])
| Typ_tup ts ->
let (vars,tys) = List.split (List.map size_nvars_ty ts) in
let insttys = List.map (fun x -> let (insts,tys) = List.split x in
List.concat insts, Typ_aux (Typ_tup tys,l)) (cross' tys) in
(kidset_bigunion vars, insttys)
| Typ_app (Id_aux (Id "bitvector",_),
[A_aux (A_nexp sz,_);_]) ->
(KidSet.of_list (size_nvars_nexp sz), [[],typ])
| Typ_app (_, tas) ->
(KidSet.empty,[[],typ]) (* We only support sizes for bitvectors mentioned explicitly, not any buried
inside another type *)
| Typ_exist (kopts, nc, t) ->
let (vars,tys) = size_nvars_ty t in
let find_insts k (insts,nc) =
let inst,nc' =
if KidSet.mem (kopt_kid k) vars then
let is,nc' = extract_set_nc env l (kopt_kid k) nc in
Some is,nc'
else None,nc
in (k,inst)::insts,nc'
in
let (insts,nc') = List.fold_right find_insts kopts ([],nc) in
let insts = cross'' insts in
let ty_and_inst (inst0,ty) inst =
let kopts, nc', ty = apply_kid_insts inst nc' ty in
let ty =
(* Typ_exist is not allowed an empty list of kids *)
match kopts with
| [] -> ty
| _ -> Typ_aux (Typ_exist (kopts, nc', ty),l)
in inst@inst0, ty
in
let tys = List.concat (List.map (fun instty -> List.map (ty_and_inst instty) insts) tys) in
let free = List.fold_left (fun vars k -> KidSet.remove (kopt_kid k) vars) vars kopts in
(free,tys)
| Typ_internal_unknown -> Reporting.unreachable l __POS__ "escaped Typ_internal_unknown"
in
let size_nvars_ty (Typ_aux (ty,l) as typ) =
match ty with
| Typ_exist (kids,_,t) ->
begin
match snd (size_nvars_ty typ) with
| [] -> []
| [[],_] -> []
| tys ->
if contains_exist t then
cannot l "Only prenex types in unions are supported by monomorphisation" []
else tys
end
| _ -> []
in
(* TODO: reject universally quantification or monomorphise it *)
let variants = size_nvars_ty ty in
match variants with
| [] -> None
| [l,_] when List.for_all (function (_,None) -> true | _ -> false) l -> None
| sample::_ ->
if List.length variants > size_set_limit then
cannot ql
(string_of_int (List.length variants) ^ "variants for constructor " ^ i ^
"bigger than limit " ^ string_of_int size_set_limit) None
else
let wrap = match id with
| Id_aux (Id i,l) -> (fun f -> Id_aux (Id (f i),Generated l))
| Id_aux (Operator i,l) -> (fun f -> Id_aux (Operator (f i),l))
in
let name_seg = function
| (_,None) -> ""
| (k,Some i) -> "#" ^ string_of_kid (kopt_kid k) ^ Big_int.to_string i
in
let name l i = String.concat "" (i::(List.map name_seg l)) in
Some (List.map (fun (l,ty) -> (l, wrap (name l),ty)) variants)
let reduce_nexp subst ne =
let rec eval (Nexp_aux (ne,_) as nexp) =
match ne with
| Nexp_constant i -> i
| Nexp_sum (n1,n2) -> Big_int.add (eval n1) (eval n2)
| Nexp_minus (n1,n2) -> Big_int.sub (eval n1) (eval n2)
| Nexp_times (n1,n2) -> Big_int.mul (eval n1) (eval n2)
| Nexp_exp n -> Big_int.shift_left (eval n) 1
| Nexp_neg n -> Big_int.negate (eval n)
| _ ->
raise (Reporting.err_general Unknown ("Couldn't turn nexp " ^
string_of_nexp nexp ^ " into concrete value"))
in eval ne
let typ_of_args args =
match args with
| [(E_aux (E_tuple args, (_, tannot)) as exp)] ->
begin match destruct_tannot tannot with
| Some (_,Typ_aux (Typ_exist _,_),_) ->
let tys = List.map Type_check.typ_of args in
Typ_aux (Typ_tup tys,Unknown)
| _ -> Type_check.typ_of exp
end
| [exp] ->
Type_check.typ_of exp
| _ ->
let tys = List.map Type_check.typ_of args in
Typ_aux (Typ_tup tys,Unknown)
(* Check to see if we need to monomorphise a use of a constructor. Currently
assumes that bitvector sizes are always given as a variable; don't yet handle
more general cases (e.g., 8 * var) *)
let refine_constructor refinements l env id args =
match List.find (fun (id',_) -> Id.compare id id' = 0) refinements with
| (_,irefinements) -> begin
let (_,constr_ty) = Env.get_union_id id env in
match constr_ty with
(* A constructor should always have a single argument. *)
| Typ_aux (Typ_fn ([constr_ty],_,_),_) -> begin
let arg_ty = typ_of_args args in
match Type_check.destruct_exist (Type_check.Env.expand_synonyms env constr_ty) with
| None -> None
| Some (kopts,nc,constr_ty) ->
(* Remove existentials in argument types to prevent unification failures *)
let unwrap (Typ_aux (t,_) as typ) = match t with
| Typ_exist (_,_,typ) -> typ
| _ -> typ
in
let arg_ty = match arg_ty with
| Typ_aux (Typ_tup ts,annot) -> Typ_aux (Typ_tup (List.map unwrap ts),annot)
| _ -> arg_ty
in
let bindings = Type_check.unify l env (tyvars_of_typ constr_ty) constr_ty arg_ty in
let find_kopt kopt = try Some (KBindings.find (kopt_kid kopt) bindings) with Not_found -> None in
let bindings = List.map find_kopt kopts in
let matches_refinement (mapping,_,_) =
List.for_all2
(fun v (_,w) ->
match v,w with
| _,None -> true
| Some (A_aux (A_nexp (Nexp_aux (Nexp_constant n, _)), _)),Some m -> Big_int.equal n m
| _,_ -> false) bindings mapping
in
match List.find matches_refinement irefinements with
| (_,new_id,_) -> Some (E_app (new_id,args))
| exception Not_found ->
let print_map kopt = function
| None -> string_of_kid (kopt_kid kopt) ^ " -> _"
| Some ta -> string_of_kid (kopt_kid kopt) ^ " -> " ^ string_of_typ_arg ta
in
(Reporting.print_err l "Monomorphisation"
("Unable to refine constructor " ^ string_of_id id ^ " using mapping " ^ String.concat "," (List.map2 print_map kopts bindings));
None)
end
| _ -> None
end
| exception Not_found -> None
type pat_choice = Parse_ast.l * (int * int * (id * tannot exp) list)
(* We may need to split up a pattern match if (1) we've been told to case split
on a variable by the user or analysis, or (2) we monomorphised a constructor that's used
in the pattern. *)
type split =
| NoSplit
| VarSplit of (tannot pat * (* pattern for this case *)
(id * tannot Ast.exp) list * (* substitutions for arguments *)
pat_choice list * (* optional locations of constraints/case expressions to reduce *)
nexp KBindings.t) (* substitutions for type variables *)
list
| ConstrSplit of (tannot pat * nexp KBindings.t) list
let isubst_minus subst subst' =
Bindings.merge (fun _ x y -> match x,y with (Some a), None -> Some a | _, _ -> None) subst subst'
let freshen_id =
let counter = ref 0 in
fun id ->
let n = !counter in
let () = counter := n + 1 in
match id with
| Id_aux (Id x, l) -> Id_aux (Id (x ^ "#m" ^ string_of_int n),Generated l)
| Id_aux (Operator x, l) -> Id_aux (Operator (x ^ "#m" ^ string_of_int n),Generated l)
(* TODO: only freshen bindings that might be shadowed *)
let rec freshen_pat_bindings p =
let rec aux (P_aux (p,(l,annot)) as pat) =
let mkp p = P_aux (p,(Generated l, annot)) in
match p with
| P_lit _
| P_wild -> pat, []
| P_or (p1, p2) ->
let (r1, vs1) = aux p1 in
let (r2, vs2) = aux p2 in
(mkp (P_or (r1, r2)), vs1 @ vs2)
| P_not p ->
let (r, vs) = aux p in
(mkp (P_not r), vs)
| P_as (p,_) -> aux p
| P_typ (typ,p) -> let p',vs = aux p in mkp (P_typ (typ,p')),vs
| P_id id -> let id' = freshen_id id in mkp (P_id id'),[id,E_aux (E_id id',(Generated Unknown,empty_tannot))]
| P_var (p,_) -> aux p
| P_app (id,args) ->
let args',vs = List.split (List.map aux args) in
mkp (P_app (id,args')),List.concat vs
| P_vector ps ->
let ps,vs = List.split (List.map aux ps) in
mkp (P_vector ps),List.concat vs
| P_vector_concat ps ->
let ps,vs = List.split (List.map aux ps) in
mkp (P_vector_concat ps),List.concat vs
| P_string_append ps ->
let ps,vs = List.split (List.map aux ps) in
mkp (P_string_append ps),List.concat vs
| P_tup ps ->
let ps,vs = List.split (List.map aux ps) in
mkp (P_tup ps),List.concat vs
| P_list ps ->
let ps,vs = List.split (List.map aux ps) in
mkp (P_list ps),List.concat vs
| P_cons (p1,p2) ->
let p1,vs1 = aux p1 in
let p2,vs2 = aux p2 in
mkp (P_cons (p1, p2)), vs1@vs2
in aux p
(* This cuts off function bodies at false assertions that we may have produced
in a wildcard pattern match. It should handle the same assertions that
find_set_assertions does. *)
let stop_at_false_assertions e =
let dummy_value_of_typ typ =
let l = Generated Unknown in
E_aux (E_exit (E_aux (E_lit (L_aux (L_unit,l)),(l,empty_tannot))),(l,empty_tannot))
in
let rec nc_false (NC_aux (nc,_)) =
match nc with
| NC_false -> true
| NC_and (nc1,nc2) -> nc_false nc1 || nc_false nc2
| _ -> false
in
let rec exp_false (E_aux (e,_)) =
match e with
| E_constraint nc -> nc_false nc
| E_lit (L_aux (L_false,_)) -> true
| E_app (Id_aux (Id "and_bool",_),[e1;e2]) ->
exp_false e1 || exp_false e2
| _ -> false
in
let rec exp (E_aux (e,ann) as ea) =
match e with
| E_block es ->
let rec aux = function
| [] -> [], None
| e::es -> let e,stop = exp e in
match stop with
| Some _ -> [e],stop
| None ->
let es',stop = aux es in
e::es',stop
in let es,stop = aux es in begin
match stop with
| None -> E_aux (E_block es,ann), stop
| Some typ ->
let typ' = typ_of_annot ann in
if Type_check.alpha_equivalent (env_of_annot ann) typ typ'
then E_aux (E_block es,ann), stop
else E_aux (E_block (es@[dummy_value_of_typ typ']),ann), Some typ'
end
| E_cast (typ,e) -> let e,stop = exp e in
let stop = match stop with Some _ -> Some typ | None -> None in
E_aux (E_cast (typ,e),ann),stop
| E_let (LB_aux (LB_val (p,e1),lbann),e2) ->
let e1,stop = exp e1 in begin
match stop with
| Some _ -> e1,stop
| None ->
let e2,stop = exp e2 in
E_aux (E_let (LB_aux (LB_val (p,e1),lbann),e2),ann), stop
end
| E_assert (e1,_) when exp_false e1 ->
ea, Some (typ_of_annot ann)
| E_throw e ->
ea, Some (typ_of_annot ann)
| _ -> ea, None
in fst (exp e)
(* Use the location pairs in choices to reduce case expressions at the first
location to the given case at the second. *)
let apply_pat_choices choices =
let rec rewrite_ncs (NC_aux (nc,l) as nconstr) =
match nc with
| NC_set _
| NC_or _ -> begin
match List.assoc l choices with
| choice,max,_ ->
NC_aux ((if choice < max then NC_true else NC_false), Generated l)
| exception Not_found -> nconstr
end
| NC_and (nc1,nc2) -> begin
match rewrite_ncs nc1, rewrite_ncs nc2 with
| NC_aux (NC_false,l), _
| _, NC_aux (NC_false,l) -> NC_aux (NC_false,l)
| nc1,nc2 -> NC_aux (NC_and (nc1,nc2),l)
end
| _ -> nconstr
in
let rec rewrite_assert_cond (E_aux (e,(l,ann)) as exp) =
match List.assoc l choices with
| choice,max,_ ->
E_aux (E_lit (L_aux ((if choice < max then L_true else L_false (* wildcard *)),
Generated l)),(Generated l,ann))
| exception Not_found ->
match e with
| E_constraint nc -> E_aux (E_constraint (rewrite_ncs nc),(l,ann))
| E_app (Id_aux (Id "and_bool",andl), [e1;e2]) ->
E_aux (E_app (Id_aux (Id "and_bool",andl),
[rewrite_assert_cond e1;
rewrite_assert_cond e2]),(l,ann))
| _ -> exp
in
let rewrite_assert (e1,e2) =
E_assert (rewrite_assert_cond e1, e2)
in
let rewrite_case (e,cases) =
match List.assoc (exp_loc e) choices with
| choice,max,subst ->
(match List.nth cases choice with
| Pat_aux (Pat_exp (p,E_aux (e,_)),_) ->
let dummyannot = (Generated Unknown,empty_tannot) in
(* TODO: use a proper substitution *)
List.fold_left (fun e (id,e') ->
E_let (LB_aux (LB_val (P_aux (P_id id, dummyannot),e'),dummyannot),E_aux (e,dummyannot))) e subst
| Pat_aux (Pat_when _,(l,_)) ->
raise (Reporting.err_unreachable l __POS__
"Pattern acquired a guard after analysis!")
| exception Not_found ->
raise (Reporting.err_unreachable (exp_loc e) __POS__
"Unable to find case I found earlier!"))
| exception Not_found -> E_case (e,cases)
in
let open Rewriter in
fold_exp { id_exp_alg with
e_assert = rewrite_assert;
e_case = rewrite_case }
let split_defs target all_errors splits env defs =
let no_errors_happened = ref true in
let error_opt = if all_errors then Some no_errors_happened else None in
let split_constructors (Defs defs) =
let sc_type_union q (Tu_aux (Tu_ty_id (ty, id), l)) =
match split_src_type error_opt env id ty q with
| None -> ([],[Tu_aux (Tu_ty_id (ty,id),l)])
| Some variants ->
([(id,variants)],
List.map (fun (insts, id', ty) -> Tu_aux (Tu_ty_id (ty,id'),Generated l)) variants)
in
let sc_type_def ((TD_aux (tda,annot)) as td) =
match tda with
| TD_variant (id,quant,tus,flag) ->
let (refinements, tus') = List.split (List.map (sc_type_union quant) tus) in
(List.concat refinements, TD_aux (TD_variant (id,quant,List.concat tus',flag),annot))
| _ -> ([],td)
in
let sc_def d =
match d with
| DEF_type td -> let (refinements,td') = sc_type_def td in (refinements, DEF_type td')
| _ -> ([], d)
in
let (refinements, defs') = List.split (List.map sc_def defs)
in (List.concat refinements, Defs defs')
in
let (refinements, defs') = split_constructors defs in
let subst_exp ref_vars substs ksubsts exp =
let substs = bindings_from_list substs, ksubsts in
fst (Constant_propagation.const_prop target defs ref_vars substs Bindings.empty exp)
in
(* Split a variable pattern into every possible value *)
let split var pat_l annot =
let v = string_of_id var in
let env = Type_check.env_of_annot (pat_l, annot) in
let typ = Type_check.typ_of_annot (pat_l, annot) in
let typ = Env.expand_synonyms env typ in
let Typ_aux (ty,l) = typ in
let new_l = Generated l in
let renew_id (Id_aux (id,l)) = Id_aux (id,new_l) in
let cannot msg =
let open Reporting in
let error_msg = "Cannot split type " ^ string_of_typ typ ^ " for variable " ^ v ^ ": " ^ msg in
if all_errors
then (no_errors_happened := false;
print_err pat_l "" error_msg;
[P_aux (P_id var,(pat_l,annot)),[],[],KBindings.empty])
else raise (err_general pat_l error_msg)
in
match ty with
| Typ_id (Id_aux (Id "bool",_)) | Typ_app (Id_aux (Id "atom_bool", _), [_]) ->
[P_aux (P_lit (L_aux (L_true,new_l)),(l,annot)),[var, E_aux (E_lit (L_aux (L_true,new_l)),(new_l,annot))],[],KBindings.empty;
P_aux (P_lit (L_aux (L_false,new_l)),(l,annot)),[var, E_aux (E_lit (L_aux (L_false,new_l)),(new_l,annot))],[],KBindings.empty]
| Typ_id id ->
(try
(* enumerations *)
let ns = Env.get_enum id env in
List.map (fun n -> (P_aux (P_id (renew_id n),(l,annot)),
[var,E_aux (E_id (renew_id n),(new_l,annot))],[],KBindings.empty)) ns
with Type_error _ ->
match id with
| Id_aux (Id "bit",_) ->
List.map (fun b ->
P_aux (P_lit (L_aux (b,new_l)),(l,annot)),
[var,E_aux (E_lit (L_aux (b,new_l)),(new_l, annot))],[],KBindings.empty)
[L_zero; L_one]
| _ -> cannot ("don't know about type " ^ string_of_id id))
| Typ_app (Id_aux (Id "bitvector",_), [A_aux (A_nexp len,_);_]) ->
(match len with
| Nexp_aux (Nexp_constant sz,_) when Big_int.greater_equal sz Big_int.zero ->
let sz = Big_int.to_int sz in
let num_lits = Big_int.pow_int (Big_int.of_int 2) sz in
(* Check that split size is within limits before generating the list of literals *)
if (Big_int.less_equal num_lits (Big_int.of_int size_set_limit)) then
let lits = make_vectors sz in
List.map (fun lit ->
P_aux (P_lit lit,(l,annot)),
[var,E_aux (E_lit lit,(new_l,annot))],[],KBindings.empty) lits
else
cannot ("bitvector length outside limit, " ^ string_of_nexp len)
| _ ->
cannot ("length not constant and positive, " ^ string_of_nexp len)
)
(* set constrained numbers *)
| Typ_app (Id_aux (Id "atom",_), [A_aux (A_nexp (Nexp_aux (value,_) as nexp),_)]) ->
begin
let mk_lit kid i =
let lit = L_aux (L_num i,new_l) in
P_aux (P_lit lit,(l,annot)),
[var,E_aux (E_lit lit,(new_l,annot))],[],
match kid with None -> KBindings.empty
| Some k -> KBindings.singleton k (nconstant i)
in
match value with
| Nexp_constant i -> [mk_lit None i]
| Nexp_var kvar ->
let ncs = Env.get_constraints env in
let nc = List.fold_left nc_and nc_true ncs in
(match extract_set_nc env l kvar nc with
| (is,_) -> List.map (mk_lit (Some kvar)) is
| exception Reporting.Fatal_error (Reporting.Err_general (_,msg)) -> cannot msg)
| _ -> cannot ("unsupport atom nexp " ^ string_of_nexp nexp)
end
| _ -> cannot ("unsupported type " ^ string_of_typ typ)
in
(* Split variable patterns at the given locations *)
let map_locs ls (Defs defs) =
let rec match_l = function
| Unknown -> []
| Unique (_, l) -> match_l l
| Generated l -> [] (* Could do match_l l, but only want to split user-written patterns *)
| Documented (_,l) -> match_l l
| Range (p,q) ->
let matches =
List.filter (fun ((filename,line),_,_) ->
p.Lexing.pos_fname = filename &&
p.Lexing.pos_lnum <= line && line <= q.Lexing.pos_lnum) ls
in List.map (fun (_,var,optpats) -> (var,optpats)) matches
in
let split_pat vars p =
let id_match = function
| Id_aux (Id x,_) -> (try Some (List.assoc x vars) with Not_found -> None)
| Id_aux (Operator x,_) -> (try Some (List.assoc x vars) with Not_found -> None)
in
let rec list f = function
| [] -> None
| h::t ->
let t' =
match list f t with
| None -> [t,[],[],KBindings.empty]
| Some t' -> t'
in
let h' =
match f h with
| None -> [h,[],[],KBindings.empty]
| Some ps -> ps
in
let merge (h,hsubs,hpchoices,hksubs) (t,tsubs,tpchoices,tksubs) =
if KBindings.for_all (fun kid nexp ->
match KBindings.find_opt kid tksubs with
| None -> true
| Some nexp' -> Nexp.compare nexp nexp' == 0) hksubs
then Some (h::t, hsubs@tsubs, hpchoices@tpchoices,
KBindings.union (fun k a _ -> Some a) hksubs tksubs)
else None
in
Some (List.concat
(List.map (fun h -> Util.map_filter (merge h) t') h'))
in
let rec spl (P_aux (p,(l,annot))) =
let relist f ctx ps =
optmap (list f ps)
(fun ps ->
List.map (fun (ps,sub,pchoices,ksub) -> P_aux (ctx ps,(l,annot)),sub,pchoices,ksub) ps)
in
let re f p =
optmap (spl p)
(fun ps -> List.map (fun (p,sub,pchoices,ksub) -> (P_aux (f p,(l,annot)), sub, pchoices, ksub)) ps)
in
let re2 f ctx p1 p2 =
(* Todo: I am not proud of this abuse of relist - but creating a special
* version of re just for two entries did not seem worth it
*)
relist f (function [p1'; p2'] -> ctx p1' p2' | _ -> assert false) [p1; p2]
in
match p with
| P_lit _
| P_wild
-> None
| P_or (p1, p2) ->
re2 spl (fun p1' p2' -> P_or (p1', p2')) p1 p2
| P_not p ->
(* todo: not sure that I can't split - but can't figure out how at
* the moment *)
raise (Reporting.err_general l
("Cannot split on 'not' pattern"))
| P_as (p',id) when id_match id <> None ->
raise (Reporting.err_general l
("Cannot split " ^ string_of_id id ^ " on 'as' pattern"))
| P_as (p',id) ->
re (fun p -> P_as (p,id)) p'
| P_typ (t,p') -> re (fun p -> P_typ (t,p)) p'
| P_var (p', (TP_aux (TP_var kid,_) as tp)) ->
(match spl p' with
| None -> None
| Some ps ->
let kids = Spec_analysis.equal_kids (env_of_pat p') kid in
Some (List.map (fun (p,sub,pchoices,ksub) ->
P_aux (P_var (p,tp),(l,annot)), sub, pchoices,
match List.find_opt (fun k -> KBindings.mem k ksub) (KidSet.elements kids) with
| None -> ksub
| Some k -> KBindings.add kid (KBindings.find k ksub) ksub
) ps))
| P_var (p',tp) -> re (fun p -> P_var (p,tp)) p'
| P_id id ->
(match id_match id with
| None -> None
(* Total case split *)
| Some None -> Some (split id l annot)
(* Where the analysis proposed a specific case split, propagate a
literal as normal, but perform a more careful transformation
otherwise *)
| Some (Some (pats,l)) ->
let max = List.length pats - 1 in
let lit_like = function
| P_lit _ -> true
| P_vector ps -> List.for_all (function P_aux (P_lit _,_) -> true | _ -> false) ps
| _ -> false
in
let rec to_exp = function
| P_aux (P_lit lit,(l,ann)) -> E_aux (E_lit lit,(Generated l,ann))
| P_aux (P_vector ps,(l,ann)) -> E_aux (E_vector (List.map to_exp ps),(Generated l,ann))
| _ -> assert false
in
Some (List.mapi (fun i p ->
match p with
| P_aux (P_lit (L_aux (L_num j,_) as lit),(pl,pannot)) ->
let orig_typ = Env.base_typ_of (env_of_annot (l,annot)) (typ_of_annot (l,annot)) in
let kid_subst = match orig_typ with
| Typ_aux
(Typ_app (Id_aux (Id "atom",_),
[A_aux (A_nexp
(Nexp_aux (Nexp_var var,_)),_)]),_) ->
KBindings.singleton var (nconstant j)
| _ -> KBindings.empty
in
p,[id,E_aux (E_lit lit,(Generated pl,pannot))],[l,(i,max,[])],kid_subst
| P_aux (p',(pl,pannot)) when lit_like p' ->
p,[id,to_exp p],[l,(i,max,[])],KBindings.empty
| _ ->
let p',subst = freshen_pat_bindings p in
match p' with
| P_aux (P_wild,_) ->
P_aux (P_id id,(l,annot)),[],[l,(i,max,subst)],KBindings.empty
| _ ->
P_aux (P_as (p',id),(l,annot)),[],[l,(i,max,subst)],KBindings.empty)
pats)
)
| P_app (id,ps) ->
relist spl (fun ps -> P_app (id,ps)) ps
| P_vector ps ->
relist spl (fun ps -> P_vector ps) ps
| P_vector_concat ps ->
relist spl (fun ps -> P_vector_concat ps) ps
| P_string_append ps ->
relist spl (fun ps -> P_string_append ps) ps
| P_tup ps ->
relist spl (fun ps -> P_tup ps) ps
| P_list ps ->
relist spl (fun ps -> P_list ps) ps
| P_cons (p1,p2) ->
re2 spl (fun p1' p2' -> P_cons (p1', p2')) p1 p2
in spl p
in
let map_pat_by_loc (P_aux (p,(l,_)) as pat) =
match match_l l with
| [] -> None
| vars -> split_pat vars pat
in
let map_pat (P_aux (p,(l,tannot)) as pat) =
let try_by_location () =
match map_pat_by_loc pat with
| Some l -> VarSplit l
| None -> NoSplit
in
match p with
| P_app (id,args) ->
begin
match List.find (fun (id',_) -> Id.compare id id' = 0) refinements with
| (_,variants) ->
(* TODO: at changes to the pattern and what substitutions do we need in general?
let kid,kid_annot =
match args with
| [P_aux (P_var (_, TP_aux (TP_var kid, _)),ann)] -> kid,ann
| _ ->
raise (Reporting.err_general l
("Pattern match not currently supported by monomorphisation: "
^ string_of_pat pat))
in
let map_inst (insts,id',_) =
let insts =
match insts with [(v,Some i)] -> [(kid,Nexp_aux (Nexp_constant i, Generated l))]
| _ -> assert false
in
(*
let insts,_ = split_insts insts in
let insts = List.map (fun (v,i) ->
(??,
Nexp_aux (Nexp_constant i,Generated l)))
insts in
P_aux (app (id',args),(Generated l,tannot)),
*)
P_aux (P_app (id',[P_aux (P_id (id_of_kid kid),kid_annot)]),(Generated l,tannot)),
kbindings_from_list insts
in
*)
let map_inst (insts,id',_) =
P_aux (P_app (id',args),(Generated l,tannot)),
KBindings.empty
in
ConstrSplit (List.map map_inst variants)
| exception Not_found -> try_by_location ()
end
| _ -> try_by_location ()
in
let check_single_pat (P_aux (_,(l,annot)) as p) =
match match_l l with
| [] -> p
| lvs ->
let pvs = Spec_analysis.bindings_from_pat p in
let pvs = List.map string_of_id pvs in
let overlap = List.exists (fun (v,_) -> List.mem v pvs) lvs in
let () =
if overlap then
Reporting.print_err l "Monomorphisation"
"Splitting a singleton pattern is not possible"
in p
in
let check_split_size lst l =
let size = List.length lst in
if size > size_set_limit then
let open Reporting in
let error_msg = "Case split is too large (" ^ string_of_int size ^ " > limit " ^ string_of_int size_set_limit ^ ")" in
if all_errors
then (no_errors_happened := false;
print_err l "" error_msg; false)
else raise (err_general l error_msg)