-
Notifications
You must be signed in to change notification settings - Fork 27
/
tcheck.ml
2464 lines (2210 loc) · 109 KB
/
tcheck.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
(****************************************************************
* ASL typechecker
*
* Copyright Arm Limited (c) 2017-2019
* SPDX-Licence-Identifier: BSD-3-Clause
****************************************************************)
(** Type inference and checker for ASL language *)
module PE = PPrintEngine
module PC = PPrintCombinators
module PP = Asl_parser_pp
module AST = Asl_ast
module Visitor = Asl_visitor
open PE
open AST
open Utils
open Asl_utils
open Printf
let verbose = false
(****************************************************************)
(** {3 Exceptions thrown by typechecker} *)
(****************************************************************)
exception UnknownObject of (l * string * string)
exception DoesNotMatch of (l * string * string * string)
exception IsNotA of (l * string * string)
exception Ambiguous of (l * string * string)
exception TypeError of (l * string)
exception InternalError of (string) (* internal invariants have been broken *)
(****************************************************************)
(** {3 AST construction utilities} *)
(****************************************************************)
(* todo: given the function/procedure distinction, it is not clear
* that we need type_unit
*)
let type_unit = Type_Tuple([])
let type_integer = Type_Constructor(Ident "integer")
let type_bool = Type_Constructor(Ident "boolean")
let type_real = Type_Constructor(Ident "real")
let type_string = Type_Constructor(Ident "string")
let type_bits (n: expr) = Type_Bits(n)
let type_exn = Type_Constructor(Ident "__Exception")
let type_bitsK (k: intLit): AST.ty = type_bits(Expr_LitInt(k))
(** Construct expression "eq_int(x, y)" *)
let mk_eq_int (x: AST.expr) (y: AST.expr): AST.expr =
Expr_TApply (FIdent ("eq_int",0), [], [x; y])
(** Construct expression "add_int(x, y)" *)
let mk_add_int (x: AST.expr) (y: AST.expr): AST.expr =
Expr_TApply (FIdent ("add_int",0), [], [x; y])
(** Construct expression "sub_int(x, y)" *)
let mk_sub_int (x: AST.expr) (y: AST.expr): AST.expr =
Expr_TApply (FIdent ("sub_int",0), [], [x; y])
(** Construct expression "(0 + x1) + ... + xn" *)
let mk_add_ints (xs: AST.expr list): AST.expr =
List.fold_left mk_add_int (Expr_LitInt "0") xs
let mk_concat_ty (x: AST.ty) (y: AST.ty): AST.ty =
(match (x, y) with
| (Type_Bits(e1), Type_Bits(e2)) ->
type_bits (mk_add_int e1 e2)
| _ ->
Printf.printf "Can't concatenate types %s and %s\n" (pp_type x) (pp_type y);
raise (InternalError "mk_concat_ty")
)
let mk_concat_tys (xs: AST.ty list): AST.ty =
List.fold_left mk_concat_ty (type_bitsK "0") xs
let slice_width (x: AST.slice): AST.expr =
(match x with
| Slice_Single(e) -> Expr_LitInt "1"
| Slice_HiLo(hi, lo) -> mk_add_int (mk_sub_int hi lo) (Expr_LitInt "1")
| Slice_LoWd(lo, wd) -> wd
)
let slices_width (xs: AST.slice list): AST.expr =
mk_add_ints (List.map slice_width xs)
let ixtype_basetype (ty: AST.ixtype): AST.ty =
(match ty with
| Index_Enum tc -> Type_Constructor tc
| Index_Range _ -> type_integer
)
(****************************************************************)
(** {3 Prettyprinting support} *)
(****************************************************************)
(** Table of binary operators used for resugaring expressions when printing
error messages.
*)
let binop_table : AST.binop Bindings.t ref = ref Bindings.empty
let add_binop (op: binop) (x: ident): unit =
binop_table := Bindings.add x op !binop_table
(** Very pretty print expression (resugaring expressions) *)
let ppp_expr (x: expr): string =
pp_expr (resugar_expr !binop_table x)
(** Very pretty print type (resugaring expressions) *)
let ppp_type (x: AST.ty): string =
pp_type (resugar_type !binop_table x)
(****************************************************************)
(** {2 Environment representing global and local objects} *)
(****************************************************************)
type typedef
= Type_Builtin of ident
| Type_Forward
| Type_Record of (ty * ident) list
| Type_Enumeration of ident list
| Type_Abbreviation of ty
let pp_typedef (x: typedef): string =
(match x with
| Type_Builtin t -> "builtin " ^ pprint_ident t
| Type_Forward -> "forward"
| Type_Record fs -> "record { " ^ String.concat "; " (List.map (fun (ty, f) -> pp_type ty ^" "^ pprint_ident f) fs) ^ "}"
| Type_Enumeration es -> "enumeration {" ^ String.concat ", " (List.map pprint_ident es) ^ "}"
| Type_Abbreviation ty -> pp_type ty
)
type funtype = (AST.ident * bool * AST.ident list * AST.expr list * (AST.ty * AST.ident) list * AST.ty)
let ft_id ((f, _, _, _, _, _): funtype): AST.ident = f
let pp_funtype ((f, isArr, tvs, cs, atys, rty): funtype): document =
PP.pp_ident f
^^ string " :: " ^^
(if tvs = [] then
string ""
else
(string "∀ " ^^ (PC.separate (string ", ") (List.map PP.pp_ident tvs))
^^ string " . ")
)
^^
(if cs = [] then
string ""
else
((PC.separate (string ", ") (List.map PP.pp_expr cs))
^^ string " => "
)
)
^^ (if isArr then PC.brackets else PC.parens)
(PC.separate (string ", ") (List.map PP.pp_formal atys))
^^ string " -> "
^^ PP.pp_ty rty
let fv_funtype ((_, _, tvs, _, atys, rty): funtype): IdentSet.t =
(* todo: should final tvs list we generate exclude any variable names mentioned in atys?
* This would let us think of the tvs as being implicit parameters that are
* added by the type inference process and would mean that there would be no
* possible way that the value parameter "N" and a type parameter "N" could
* be different from each other.
* This would be different from archex and would break down a bit the distinction
* between type variables and value variables.
*)
IdentSet.union (IdentSet.of_list tvs) (IdentSet.union (fv_args atys) (fv_type rty))
(* type of setter function *)
type sfuntype = (AST.ident * AST.ident list * AST.expr list * AST.sformal list * AST.ty)
let sft_id ((f, _, _, _, _): sfuntype): AST.ident = f
let pp_sfuntype ((f, tvs, cs, atys, vty): sfuntype): document =
PP.pp_ident f
^^ string " :: " ^^
(if tvs = [] then
string ""
else
(string "∀ " ^^ (PC.separate (string ", ") (List.map PP.pp_ident tvs))
^^ string " . ")
)
^^
(if cs = [] then
string ""
else
((PC.separate (string ", ") (List.map PP.pp_expr cs))
^^ string " => "
)
)
^^ PC.parens (PC.separate (string ", ") (List.map PP.pp_sformal atys))
^^ string " <- "
^^ PP.pp_ty vty
let sformal_var (x: sformal): AST.ident =
( match x with
| Formal_In (_, v) -> v
| Formal_InOut (_, v) -> v
)
let sformal_type (x: sformal): AST.ty =
( match x with
| Formal_In (ty, _) -> ty
| Formal_InOut (ty, _) -> ty
)
let formal_of_sformal (x: AST.sformal): (AST.ty * AST.ident) =
( match x with
| Formal_In (ty, v) -> (ty, v)
| Formal_InOut (ty, v) -> (ty, v)
)
let funtype_of_sfuntype ((f, tvs, cs, atys, vty): sfuntype): funtype =
(f, true, tvs, cs, List.map formal_of_sformal atys, vty)
module Operator1 = struct
type t = AST.unop
let compare x y = Stdlib.compare x y
end
module Operators1 = Map.Make(Operator1)
module Operator2 = struct
type t = AST.binop
let compare x y = Stdlib.compare x y
end
module Operators2 = Map.Make(Operator2)
(****************************************************************)
(** {3 Global Environment (aka the Global Symbol Table)} *)
(****************************************************************)
module GlobalEnv : sig
type t
val mkempty : unit -> t
val addType : t -> AST.l -> AST.ident -> typedef -> unit
val getType : t -> AST.ident -> typedef option
val isType : t -> AST.ident -> bool
val isTycon : t -> AST.ident -> bool
val isEnum : t -> AST.ident -> bool
val addFuns : t -> AST.l -> AST.ident -> funtype list -> unit
val getFuns : t -> AST.ident -> funtype list
val addSetterFuns : t -> AST.ident -> sfuntype list -> unit
val getSetterFun : t -> AST.ident -> sfuntype list
val addOperators1 : t -> AST.l -> AST.unop -> funtype list -> unit
val getOperators1 : t -> AST.l -> AST.unop -> funtype list
val addOperators2 : t -> AST.l -> AST.binop -> funtype list -> unit
val getOperators2 : t -> AST.l -> AST.binop -> funtype list
val addEncoding : t -> AST.ident -> unit
val isEncoding : t -> AST.ident -> bool
val addGlobalVar : t -> AST.l -> AST.ident -> AST.ty -> bool -> unit
val getGlobalVar : t -> AST.ident -> AST.ty option
end = struct
type t = {
mutable types : typedef Bindings.t;
mutable functions : (funtype list) Bindings.t;
mutable setters : (sfuntype list) Bindings.t;
mutable operators1 : (funtype list) Operators1.t;
mutable operators2 : (funtype list) Operators2.t;
mutable encodings : IdentSet.t;
mutable globals : AST.ty Bindings.t;
}
let mkempty _: t = {
types = Bindings.empty;
functions = Bindings.empty;
setters = Bindings.empty;
operators1 = Operators1.empty;
operators2 = Operators2.empty;
encodings = IdentSet.empty;
globals = Bindings.empty;
}
let addType (env: t) (loc: AST.l) (qid: AST.ident) (t: typedef): unit =
(* Printf.printf "New type %s at %s\n" qid (pp_loc loc); *)
let t' = (match (Bindings.find_opt qid env.types, t) with
| (None, _) -> t
| (Some Type_Forward, _) -> t
| (Some p, Type_Forward) -> p
| (Some p, _) when p <> t ->
raise (DoesNotMatch (loc, "type definition", pp_typedef t, pp_typedef p))
| _ -> t
) in
env.types <- Bindings.add qid t' env.types
let getType (env: t) (qid: AST.ident): typedef option =
Bindings.find_opt qid env.types
let isType (env: t) (qid: AST.ident): bool = true (* todo *)
let isTycon (env: t) (qid: AST.ident): bool = true (* todo *)
let isEnum (env: t) (qid: AST.ident): bool = true (* todo *)
let addFuns (env: t) (loc: AST.l) (qid: AST.ident) (ftys: funtype list): unit =
env.functions <- Bindings.add qid ftys env.functions
let getFuns (env: t) (qid: AST.ident): funtype list =
(match Bindings.find_opt qid env.functions with
| None -> []
| Some tys -> tys
)
let addSetterFuns (env: t) (qid: AST.ident) (ftys: sfuntype list): unit =
env.setters <- Bindings.add qid ftys env.setters
let getSetterFun (env: t) (qid: AST.ident): sfuntype list =
(match Bindings.find_opt qid env.setters with
| None -> []
| Some tys -> tys
)
let addOperators1 (env: t) (loc: AST.l) (op: AST.unop) (funs: funtype list): unit =
env.operators1 <- Operators1.update op (fun ov ->
let old = from_option ov (fun _ -> []) in
Some (List.append funs old)
) env.operators1
let getOperators1 (env: t) (loc: AST.l) (op: AST.unop): funtype list =
from_option (Operators1.find_opt op (env.operators1)) (fun _ -> [])
let addOperators2 (env: t) (loc: AST.l) (op: AST.binop) (funs: funtype list): unit =
List.iter (function fty -> add_binop op (ft_id fty)) funs;
env.operators2 <- Operators2.update op (fun ov ->
let old = from_option ov (fun _ -> []) in
Some (List.append funs old)
) env.operators2
let getOperators2 (env: t) (loc: AST.l) (op: AST.binop): funtype list =
from_option (Operators2.find_opt op (env.operators2)) (fun _ -> [])
let addEncoding (env: t) (qid: AST.ident): unit =
env.encodings <- IdentSet.add qid env.encodings
let isEncoding (env: t) (qid: AST.ident): bool =
IdentSet.mem qid env.encodings
let addGlobalVar (env: t) (loc: AST.l) (qid: AST.ident) (ty: AST.ty) (isConstant: bool): unit =
(* Printf.printf "New %s %s at %s\n" (if isConstant then "constant" else "variable") qid (pp_loc loc); *)
env.globals <- Bindings.add qid ty env.globals
let getGlobalVar (env: t) (v: AST.ident): AST.ty option =
(* Printf.printf "Looking for global variable %s\n" (pprint_ident v); *)
Bindings.find_opt v env.globals
end
(** dereference typedef *)
let rec derefType (env: GlobalEnv.t) (ty: AST.ty): AST.ty =
(match ty with
| Type_Constructor tc
| Type_App (tc, _) ->
(match GlobalEnv.getType env tc with
(* todo: instantiate with type parameters? *)
| Some (Type_Abbreviation ty') -> derefType env ty'
| _ -> ty
)
| _ -> ty
)
(** compare index types *)
let cmp_ixtype (ty1: AST.ixtype) (ty2: AST.ixtype): bool =
(match (ty1, ty2) with
| (Index_Enum tc1, Index_Enum tc2) -> tc1 = tc2
| (Index_Range _, Index_Range _) -> true
| _ -> false
)
(** structural match on two types - ignoring the dependent type part *)
(* todo: does not handle register<->bits coercions *)
let rec cmp_type (env: GlobalEnv.t) (ty1: AST.ty) (ty2: AST.ty): bool =
(match (derefType env ty1, derefType env ty2) with
| (Type_Constructor c1, Type_Constructor c2) -> c1 = c2
| (Type_Bits(e1), Type_Bits(e2)) -> true
| (Type_App (c1, es1), Type_App (c2, es2)) -> c1 = c2
| (Type_OfExpr e1, Type_OfExpr e2) -> raise (InternalError "cmp_type: typeof")
(* todo: this is equating the types, not subtyping them *)
| (Type_Bits(e1), Type_Register (w2, _)) -> true
| (Type_Register (w1, _), Type_Bits(e2)) -> true
| (Type_Register (w1, _), Type_Register (w2, _)) -> true
| (Type_Array (ixty1, elty1), Type_Array (ixty2, elty2)) -> cmp_ixtype ixty1 ixty2 && cmp_type env elty1 elty2
| (Type_Tuple tys1, Type_Tuple tys2) ->
(List.length tys1 = List.length tys2) && List.for_all2 (cmp_type env) tys1 tys2
| _ -> false
)
(****************************************************************)
(** {3 Field typechecking support} *)
(****************************************************************)
(** Field accesses can be either record fields or fields of registers
This type captures the information needed to typecheck either of these
- a list of fieldname/type pairs for records
- a list of fieldname/slice pairs for registers
*)
type fieldtypes
= FT_Record of (ty * ident) list
| FT_Register of (AST.slice list * ident) list
(** Get fieldtype information for a record/register type *)
let rec typeFields (env: GlobalEnv.t) (loc: AST.l) (x: ty): fieldtypes =
(match derefType env x with
| Type_Constructor tc
| Type_App (tc, _) ->
(match GlobalEnv.getType env tc with
| Some(Type_Record fs) -> FT_Record fs
| Some(Type_Abbreviation ty') -> typeFields env loc ty'
| _ -> raise (IsNotA(loc, "record", pprint_ident tc))
)
| Type_Register (wd, fs) -> FT_Register fs
| Type_OfExpr(e) -> raise (InternalError ("typeFields: Type_OfExpr " ^ ppp_expr e))
| _ -> raise (IsNotA(loc, "record/register", pp_type x))
)
(** Get fieldtype information for a named field of a record *)
let get_recordfield (loc: AST.l) (rfs: (ty * ident) list) (f: ident): AST.ty =
(match List.filter (fun (_, fnm) -> fnm = f) rfs with
| [(fty, _)] -> fty
| [] -> raise (UnknownObject(loc, "field", pprint_ident f))
| fs -> raise (Ambiguous (loc, "field", pprint_ident f))
)
(** Get fieldtype information for a named field of a slice *)
let get_regfield_info (loc: AST.l) (rfs: (AST.slice list * ident) list) (f: ident): AST.slice list =
(match List.filter (fun (_, fnm) -> fnm = f) rfs with
| [(ss, _)] -> ss
| [] -> raise (UnknownObject(loc, "field", pprint_ident f))
| fs -> raise (Ambiguous (loc, "field", pprint_ident f))
)
(** Get named field of a register and calculate type *)
let get_regfield (loc: AST.l) (rfs: (AST.slice list * ident) list) (f: ident): (AST.slice list * AST.ty) =
let ss = get_regfield_info loc rfs f in
(ss, type_bits (slices_width ss))
(** Get named fields of a register and calculate type of concatenating them *)
let get_regfields (loc: AST.l) (rfs: (AST.slice list * ident) list) (fs: ident list): (AST.slice list * AST.ty) =
let ss = List.flatten (List.map (get_regfield_info loc rfs) fs) in
(ss, type_bits (slices_width ss))
(****************************************************************)
(** {3 Environment (aka the Local+Global Symbol Table)} *)
(****************************************************************)
(* The handling of implicitly declared variables is complex.
*
* The typechecker inserts a variable declaration for any variable
* that is assigned to for which there is no explicit declaration.
*
* To match the way that ASL is written, the declaration doesn't
* always go in the current (i.e., innermost) scope because
* a lot of ASL code requires that the variable should still
* exist after the current scope has ended.
*
* At the same time, the declaration must:
* - be legal: any variables used in the type of the declaration
* must be in scope
* - mean the same: any variables used in the type of the declaration
* must have the same values
* - be unique: there must be at most one declaration of each variable
* name (implicit or explicit) within a function
* (Note that this also means that we cannot explicitly declare two
* variables with the same name in different scopes - even if they have
* the same type.)
*
* So the rule for deciding where to put an implicit variable declaration is:
* - it must occur before the initial assignment(s)
* - there must be no assignment to any dependent variables between
* the declaration and the initial assignment(s)
*
* To implement this, the environment tracks:
* - the set of all local variables (implicit or explicit) in this function
* - the set of variables assigned to so far in each scope
* - the list of pending implicit declarations waiting to be emitted
* (this is a list to make it easier to emit declarations in order)
* And we maintain the invariant that none of the pending implicit declarations
* have dependencies that are modified in the current (innermost) scope.
*
* New variables (both implicitly declared and explicitly declared) are
* checked against the set of all local variables for conflicts.
*
* New implicitly declared variables either:
* - have declarations inserted immediately before their assignment
* (if their type depends on variables modified in the current scope)
* or
* - are added to the list of implicit declarations
*
* On leaving scope I for scope O:
* - explicit declarations are inserted for any pending implicit declarations that
* depend on variables modified in scope O
*)
type implicitVars = (AST.ident * AST.ty) list
let declare_implicits (loc: AST.l) (imps: implicitVars): AST.stmt list =
List.map (fun (v, ty) -> Stmt_VarDeclsNoInit(ty, [v], loc)) imps
module Env : sig
type t
val mkEnv : GlobalEnv.t -> t
val globals : t -> GlobalEnv.t
val nest : (t -> 'a) -> (t -> 'a)
val nest_with_bindings : (t -> 'a) -> (t -> ('a * (AST.ident * AST.ty) list))
val addLocalVar : t -> AST.l -> AST.ident -> AST.ty -> unit
val addLocalImplicitVar : t -> AST.l -> AST.ident -> AST.ty -> unit
val getAllImplicits : t -> implicitVars
val getImplicits : t -> implicitVars
val getVar : t -> AST.ident -> (AST.ident * AST.ty) option
val markModified : t -> AST.ident -> unit
val addConstraint : t -> AST.l -> AST.expr -> unit
val getConstraints : t -> AST.expr list
val setReturnType : t -> AST.ty -> unit
val getReturnType : t -> AST.ty option
end = struct
type t = {
globals : GlobalEnv.t;
mutable rty : AST.ty option;
(* a stack of nested scopes representing the local type environment *)
(* Invariant: the stack is never empty *)
mutable locals : AST.ty Bindings.t list;
mutable modified : IdentSet.t;
mutable implicits : AST.ty Bindings.t ref;
(* constraints collected while typechecking current expression/assignment *)
mutable constraints : AST.expr list;
}
let mkEnv (globalEnv: GlobalEnv.t) = {
globals = globalEnv;
rty = None;
locals = [Bindings.empty];
modified = IdentSet.empty;
implicits = ref Bindings.empty;
constraints = [];
}
(* todo: would it be better to make Env a subclass of GlobalEnv
* Doing that would eliminate many, many calls to this function
*)
let globals (env: t): GlobalEnv.t =
env.globals
let nest (k: t -> 'a) (parent: t): 'a =
let child = {
globals = parent.globals;
rty = parent.rty;
locals = Bindings.empty :: parent.locals;
modified = IdentSet.empty;
implicits = parent.implicits;
constraints = parent.constraints;
} in
let r = k child in
parent.modified <- IdentSet.union parent.modified child.modified;
r
let nest_with_bindings (k: t -> 'a) (parent: t): ('a * (AST.ident * AST.ty) list) =
let child = {
globals = parent.globals;
rty = parent.rty;
locals = Bindings.empty :: parent.locals;
modified = IdentSet.empty;
implicits = parent.implicits;
constraints = parent.constraints;
} in
let r = k child in
parent.modified <- IdentSet.union parent.modified child.modified;
let locals = Bindings.bindings (List.hd child.locals) in
(r, locals)
let addLocalVar (env: t) (loc: AST.l) (v: AST.ident) (ty: AST.ty): unit =
(* Printf.printf "New local var %s : %s at %s\n" (pprint_ident v) (ppp_type ty) (pp_loc loc); *)
(match env.locals with
| (bs :: bss) -> env.locals <- (Bindings.add v ty bs) :: bss
| [] -> raise (InternalError "addLocalVar")
);
env.modified <- IdentSet.add v env.modified
let addLocalImplicitVar (env: t) (loc: AST.l) (v: AST.ident) (ty: AST.ty): unit =
(* Printf.printf "New implicit: %s : %s\n" (pprint_ident v) (ppp_type ty); *)
env.implicits := Bindings.add v ty !(env.implicits);
env.modified <- IdentSet.add v env.modified
let getAllImplicits (env: t): implicitVars =
let imps = !(env.implicits) in
env.implicits := Bindings.empty;
Bindings.bindings imps
let getImplicits (env: t): implicitVars =
let unconflicted _ (ty: AST.ty): bool =
let deps = fv_type ty in
IdentSet.disjoint deps env.modified
in
let (good, conflicts) = Bindings.partition unconflicted !(env.implicits) in
env.implicits := good;
Bindings.bindings conflicts
let getVar (env: t) (v: AST.ident): (AST.ident * AST.ty) option =
(* Printf.printf "Looking for variable %s\n" (pprint_ident v); *)
let rec search (bss : AST.ty Bindings.t list): AST.ty option =
(match bss with
| (bs :: bss') ->
orelse_option (Bindings.find_opt v bs) (fun _ ->
search bss')
| [] ->
orelse_option (Bindings.find_opt v !(env.implicits)) (fun _ ->
GlobalEnv.getGlobalVar env.globals v)
)
in
map_option (fun ty -> (v, ty)) (search env.locals)
let markModified (env: t) (v: AST.ident): unit =
env.modified <- IdentSet.add v env.modified
let addConstraint (env: t) (loc: AST.l) (c: AST.expr): unit =
env.constraints <- c :: env.constraints
let getConstraints (env: t): AST.expr list =
env.constraints
let setReturnType (env: t) (ty: AST.ty): unit =
env.rty <- Some ty
let getReturnType (env: t): AST.ty option =
env.rty
end
(****************************************************************)
(** {2 Unification} *)
(****************************************************************)
(****************************************************************)
(** {3 Expression simplification} *)
(****************************************************************)
(** Perform simple constant folding of expression
It's primary role is to enable the 'DIV' hacks in
z3_of_expr which rely on shallow syntactic transforms.
It has a secondary benefit of sometimes causing constraints
to become so trivial that we don't even need to invoke Z3
which gives a performance benefit.
*)
let rec simplify_expr (x: AST.expr): AST.expr =
let eval (x: AST.expr): Big_int.big_int option =
(match x with
| Expr_LitInt x' -> Some (Big_int.big_int_of_string x')
| _ -> None
)
in
let to_expr (x: Big_int.big_int): AST.expr =
Expr_LitInt (Big_int.string_of_big_int x)
in
(match x with
| Expr_TApply (f, tes, es) ->
let es' = List.map simplify_expr es in
(match (f, flatten_map_option eval es') with
| (FIdent ("add_int",_), Some [a; b]) -> to_expr (Big_int.add_big_int a b)
| (FIdent ("sub_int",_), Some [a; b]) -> to_expr (Big_int.sub_big_int a b)
| (FIdent ("mul_int",_), Some [a; b]) -> to_expr (Big_int.mult_big_int a b)
| _ -> Expr_TApply (f, tes, es')
)
| _ -> x
)
(** Perform simple constant folding of expressions within a type *)
let simplify_type (x: AST.ty): AST.ty =
let repl = new replaceExprClass (fun e -> Some (simplify_expr e)) in
Asl_visitor.visit_type repl x
(****************************************************************)
(** {3 Z3 support code} *)
(****************************************************************)
(** Convert ASL expression to Z3 expression.
This only copes with a limited set of operations: ==, +, -, * and DIV.
(It is possible that we will need to extend this list in the future but
it is sufficient for the current ASL specifications.)
The support for DIV is not sound - it is a hack needed to cope with
the way ASL code is written and generally needs a side condition
that the division is exact (no remainder).
ufs is a mutable list of conversions used to handle subexpressions
that cannot be translated. We treat such subexpressions as
uninterpreted functions and add them to the 'ufs' list so that
we can reason that "F(x) == F(x)" without knowing "F".
*)
let rec z3_of_expr (ctx: Z3.context) (ufs: (AST.expr * Z3.Expr.expr) list ref) (x: AST.expr): Z3.Expr.expr =
(match x with
| Expr_Var(v) ->
let intsort = Z3.Arithmetic.Integer.mk_sort ctx in
Z3.Expr.mk_const_s ctx (pprint_ident v) intsort
| Expr_Parens y -> z3_of_expr ctx ufs y
| Expr_LitInt i -> Z3.Arithmetic.Integer.mk_numeral_s ctx i
(* todo: the following lines involving DIV are not sound *)
| Expr_TApply (FIdent ("mul_int",_), [], [Expr_TApply (FIdent ("fdiv_int",_), [], [a; b]); c]) when b = c -> z3_of_expr ctx ufs a
| Expr_TApply (FIdent ("mul_int",_), [], [a; Expr_TApply (FIdent ("fdiv_int",_), [], [b; c])]) when a = c -> z3_of_expr ctx ufs b
| Expr_TApply (FIdent ("add_int",_), [], [Expr_TApply (FIdent ("fdiv_int",_), [], [a1; b1]);
Expr_TApply (FIdent ("fdiv_int",_), [], [a2; b2])])
when a1 = a2 && b1 = b2 && b1 = Expr_LitInt "2"
-> z3_of_expr ctx ufs a1
| Expr_TApply (FIdent ("eq_int",_), [], [a; Expr_TApply (FIdent ("fdiv_int",_), [], [b; c])]) ->
Z3.Boolean.mk_eq ctx
(Z3.Arithmetic.mk_mul ctx [z3_of_expr ctx ufs c; z3_of_expr ctx ufs a])
(z3_of_expr ctx ufs b)
| Expr_TApply (FIdent ("add_int",_), [], xs) -> Z3.Arithmetic.mk_add ctx (List.map (z3_of_expr ctx ufs) xs)
| Expr_TApply (FIdent ("sub_int",_), [], xs) -> Z3.Arithmetic.mk_sub ctx (List.map (z3_of_expr ctx ufs) xs)
| Expr_TApply (FIdent ("mul_int",_), [], xs) -> Z3.Arithmetic.mk_mul ctx (List.map (z3_of_expr ctx ufs) xs)
| Expr_TApply (FIdent ("fdiv_int",_), [], [a;b]) -> Z3.Arithmetic.mk_div ctx (z3_of_expr ctx ufs a) (z3_of_expr ctx ufs b)
| Expr_TApply (FIdent ("eq_int",_), [], [a;b]) -> Z3.Boolean.mk_eq ctx (z3_of_expr ctx ufs a) (z3_of_expr ctx ufs b)
| _ ->
if verbose then Printf.printf " Unable to translate %s - using as uninterpreted function\n" (pp_expr x);
let intsort = Z3.Arithmetic.Integer.mk_sort ctx in
(match List.assoc_opt x !ufs with
| None ->
let uf = Z3.Expr.mk_fresh_const ctx "UNINTERPRETED" intsort in
ufs := (x, uf) :: !ufs;
uf
| Some uf ->
uf
)
)
(** check that bs => cs *)
let check_constraints (bs: expr list) (cs: expr list): bool =
(* note that we rebuild the Z3 context each time.
* It is possible to share them across all invocations to save
* about 10% of execution time.
*)
let z3_ctx = Z3.mk_context [] in
let solver = Z3.Solver.mk_simple_solver z3_ctx in
let ufs = ref [] in (* uninterpreted function list *)
let bs' = List.map (z3_of_expr z3_ctx ufs) bs in
let cs' = List.map (z3_of_expr z3_ctx ufs) cs in
let p = Z3.Boolean.mk_implies z3_ctx (Z3.Boolean.mk_and z3_ctx bs') (Z3.Boolean.mk_and z3_ctx cs') in
if verbose then Printf.printf " - Checking %s\n" (Z3.Expr.to_string p);
Z3.Solver.add solver [Z3.Boolean.mk_not z3_ctx p];
let q = Z3.Solver.check solver [] in
if q = SATISFIABLE then Printf.printf "Failed property %s\n" (Z3.Expr.to_string p);
q = UNSATISFIABLE
(****************************************************************)
(** {3 Unification support code} *)
(****************************************************************)
(** Unifier
This class supports collecting all the constraints introduced while
typechecking an expression, checking those constraints
and synthesizing a solution.
This is the most complex part of the entire typechecker.
Most of that complexity is the result of having to support
code like
bits(64) x = ZeroExtend(R[i]);
where the width of the ZeroExtend call is determined by
the context that it occurs in.
*)
class unifier (loc: AST.l) (assumptions: expr list) = object (self)
(* unification results in bindings of the form "$i == $j".
* We use a renaming structure to track equivalence classes
* and to pick a canonical member of each equivalence class
*)
val mutable renamings = new equivalences
val mutable bindings : AST.expr Bindings.t = Bindings.empty
val mutable constraints : AST.expr list = []
val mutable next = 0
method fresh: ident =
let v = genericTyvar next in
ignore (renamings#canonicalize v); (* add v to rename table *)
next <- next + 1;
v
method isFresh (x: ident): bool =
isGenericTyvar x
method addEquality (x: AST.expr) (y: AST.expr): unit =
(match (x, y) with
| (Expr_Var v, Expr_Var w) when self#isFresh v && self#isFresh w ->
renamings#merge v w
| (Expr_Var v, _) when self#isFresh v && not (Bindings.mem v bindings) ->
bindings <- Bindings.add v y bindings
| (_, Expr_Var w) when self#isFresh w && not (Bindings.mem w bindings) ->
bindings <- Bindings.add w x bindings
| _ ->
constraints <- mk_eq_int x y :: constraints
)
method addEqualities (xs: AST.expr list) (ys: AST.expr list) =
if List.length xs = List.length ys then
List.iter2 self#addEquality xs ys
method checkConstraints: expr Bindings.t = begin
(* Plan:
* - Generate renaming that maps each fresh var to canonical
* representative of equivalence class.
* - Collect all the bindings associated with each equivalence class.
* - For each equivalence class, check that there is at least
* one closed binding for that equivalence class and
* add all the others as constraints.
* (A "closed binding" is a binding that does not contain any fresh
* variables - construct it by substituting other closed bindings
* into a binding.)
* - If any equivalence class has no closed bindings, report an error.
*)
let rns = renamings#mapping in
let classes = renamings#classes in
(* map each canonical representative to set of bindings *)
let binds = Bindings.map (fun vs -> flatmap_option (fun v -> Bindings.find_opt v bindings) (IdentSet.elements vs)) classes in
if verbose then begin
Printf.printf " - Checking Constraints at %s\n" (pp_loc loc);
Bindings.iter (fun v e -> Printf.printf " Old Bind: %s -> %s\n" (pprint_ident v) (ppp_expr e)) bindings;
Bindings.iter (fun v es -> List.iter (fun e -> Printf.printf " binds: %s -> %s\n" (pprint_ident v) (ppp_expr e)) es) binds;
renamings#pp " Renaming: ";
Bindings.iter (fun v w -> Printf.printf " - renaming: %s -> %s\n" (pprint_ident v) (pprint_ident w)) rns
end;
let isClosed (x: expr): bool =
IdentSet.is_empty (IdentSet.filter self#isFresh (fv_expr x))
in
(* todo: memoize close_ident to improve performance - should probably profile first *)
(* search for a closed binding for a variable x by testing whether any of the available bindings can be closed *)
let rec close_ident (x: ident): expr =
let x' = renamings#canonicalize x in
(match bind_option (Bindings.find_opt x' binds) (fun es -> first_option close_expr es) with
| Some e -> e
| None ->
Printf.printf "Type Error at %s\n" (pp_loc loc);
if verbose then begin
List.iter (fun v -> Printf.printf " Related to: %s\n" (pprint_ident v)) (IdentSet.elements (Bindings.find x' classes));
List.iter (fun e -> Printf.printf " Candidate: %s\n" (pp_expr e)) (Bindings.find x' binds);
renamings#pp " Renaming: ";
Bindings.iter (fun v e -> Printf.printf " Bind: %s -> %s\n" (pprint_ident v) (ppp_expr e)) bindings
end;
raise (TypeError (loc, "Unable to infer value of type parameter "^ pprint_ident x'))
)
(* attempt to close an expression by replacing all fresh vars with a closed expression *)
and close_expr (x: expr): expr option =
let subst = new substFunClass (fun x -> if self#isFresh x then Some (close_ident x) else None) in
let x' = Asl_visitor.visit_expr subst x in
if isClosed x' then
Some x'
else
None
in
(* map of each canonical member to a closed expression *)
let pre_closed = Bindings.mapi (fun k _ -> close_ident k) classes in
(* extend map to all type variables *)
let closed = Bindings.map (fun v -> Bindings.find v pre_closed) rns in
if verbose then begin
Bindings.iter (fun v e -> Printf.printf " PreClosed Bind: %s -> %s\n" (pprint_ident v) (ppp_expr e)) pre_closed;
Bindings.iter (fun v e -> Printf.printf " Closed Bind: %s -> %s\n" (pprint_ident v) (ppp_expr e)) closed
end;
constraints <- List.map (subst_expr closed) constraints;
(* turn all old bindings into constraints *)
let new_constraints = List.map (fun (v, e) -> mk_eq_int (Bindings.find v closed) (subst_expr closed e)) (Bindings.bindings bindings) in
constraints <- new_constraints @ constraints;
bindings <- closed;
if verbose then begin
List.iter (fun c -> Printf.printf " OldConstraint: %s\n" (ppp_expr c)) constraints;
List.iter (fun c -> Printf.printf " NewConstraint: %s\n" (ppp_expr c)) new_constraints;
List.iter (fun c -> Printf.printf " Constraint: %s\n" (ppp_expr c)) constraints
end;
constraints <- List.map simplify_expr constraints;
(* as a minor optimisation and also to declutter error messages, delete equalities that are obviously satisfied *)
constraints <- List.filter (function Expr_TApply(FIdent ("eq_int",_), [], [x; y]) -> x <> y | _ -> true) constraints;
(* The optimisation of not invoking solver if there are no constraints
* improves runtime by a factor of 6x
*)
if constraints <> [] && not (check_constraints assumptions constraints) then begin
Printf.printf "Type Error at %s\n" (pp_loc loc);
if verbose then begin
renamings#pp " Renaming: ";
Bindings.iter (fun v e -> Printf.printf " Bind: %s -> %s\n" (pprint_ident v) (ppp_expr e)) bindings
end;
List.iter (fun c -> Printf.printf " Constraint: %s\n" (ppp_expr c)) constraints;
flush stdout;
raise (TypeError (loc, "Type mismatch"))
end;
bindings
end
end
(** Create a fresh unifier, invoke a function that uses the unifier and check
that the constraints are satisfied.
Returns the synthesized bindings and result of function
*)
let with_unify (env: Env.t) (loc: AST.l) (f: unifier -> 'a): (expr Bindings.t * 'a) =
let u = new unifier loc (Env.getConstraints env) in
let r = f u in
let bs = u#checkConstraints in
(bs, r)
(****************************************************************)
(** {3 Type Unification} *)
(****************************************************************)
(** Notes on how type inference works:
- we use structural matching (ignoring the dependent type)
to disambiguate each binop/unop/function/procedure call/getter/setter
- as we construct each TApply node,
- we insert fresh type variables $0, $1, ... for each of the type arguments
(these are things we are going to solve for)
- unification generates two kinds of constraints:
1. bindings for type variables whenever unification requires "$i == e" or "e == $i"
for some type variable $i
2. constraints where there are multiple bindings for a single variable
3. constraints on type variables whenever unification requires "e1 == e2"
where e1 is not a variable
- after scanning an entire assignment/expression, we check:
1. do we have at least one binding for each variable?
2. are the bindings consistent with the constraints?
Note that we could potentially give better (more localized) type errors if
we check for consistency as we go along and if we check that a variable
is bound as soon as the result type could not possibly involve the variable.
(e.g., when checking "(e1 == e2 && Q) || R", any type variables associated
with the equality check do not impact the && or || because "boolean" does
not have any type parameters.)
Note that there is a choice of what type arguments to add to a function
bits(N) ZeroExtend(bits(M) x, integer N)
We can either:
- add only the missing information "M"
In effect, we are saying that missing type parameters are implicit parameters that are
added by the type inference process and that the "type parameters" are basically just
value expressions that are added by type inference.
- add type arguments for both "M" and "N".
In effect we are saying that type parameters are distinct from value parameters
and we are in the strange situation that a function could have both a value
parameter M and a type parameter N and they might be bound to different (but
equivalent) arguments.
This is what archex does.
*)
(** Unify two index types *)
let unify_ixtype (u: unifier) (ty1: AST.ixtype) (ty2: AST.ixtype): unit =
(match (ty1, ty2) with
| (Index_Enum tc1, Index_Enum tc2) -> ()
| (Index_Range (lo1, hi1), Index_Range (lo2, hi2)) ->
u#addEquality lo1 lo2;
u#addEquality hi1 hi2
| _ -> ()
)
(** Unify two types
This performs a structural match on two types - ignoring the dependent type part
*)
(* todo: does not handle register<->bits coercions *)
let rec unify_type (env: GlobalEnv.t) (u: unifier) (ty1: AST.ty) (ty2: AST.ty): unit =
(match (derefType env ty1, derefType env ty2) with
| (Type_Constructor c1, Type_Constructor c2) -> ()