Source file Solver.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
open Signatures
module Make
(X : TEVAR)
(S : HSTRUCTURE)
(O : OUTPUT with type 'a structure = 'a S.structure)
= struct
type tevar =
X.t
type tevars =
tevar list
module TeVarMap =
Hashtbl.Make(X)
type variable =
int
type variables =
variable list
let fresh : unit -> variable =
Utils.gensym()
module VarTable = Hashtbl
type range =
Lexing.position * Lexing.position
type shallow_ty =
variable O.structure
type tyvars =
O.tyvar list
type tys =
O.ty list
type scheme =
tyvars * O.ty
type schemes =
scheme list
(**A constraint of type ['a co] is a constraint whose resolution, if
successful, produces a value of type ['a]. The ability for the
resolution process to produce a result can be used to express
elaboration in an elegant way. *)
type _ co =
| CRange : range * 'a co -> 'a co
(**The constraint [CRange (range, c)] is equivalent to the constraint [c],
and is annotated with [range], a range of positions in some piece of
source code. *)
| CTrue : unit co
(**The trivial constraint [CTrue] is always true. *)
| CMap : 'a co * ('a -> 'b) -> 'b co
(**The constraint [CMap (c, f)] is equivalent to the constraint [c]. The
transformation function [f] is used to postprocess the result of solving
this constraint. *)
| CPure : 'a -> 'a co
(**The constraint [CPure x] is always true, and produces the value [x].
It is equivalent to [CMap (CTrue, fun () -> x)]. *)
| CConj : 'a co * 'b co -> ('a * 'b) co
(**[CConj (c1, c2)] is the conjunction of the constraints [c1] and [c2]. *)
| CEq : variable * variable -> unit co
(**[CEq (v1, v2)] is an equality constraint between the type variables [v1]
and [v2]. *)
| CExist : variable * variable S.structure option * 'a co -> 'a co
(**An existential quantification [CExist (v, so, c)] binds the type
variable [v] in the constraint [c]. This type variable carries an
optional equality constraint [so] whose right-hand side is a shallow
term. *)
| CDecode : variable -> O.ty co
(**The constraint [CDecode v] is logically equivalent to
a [true] constraint, so it is always satisfied. Its result is
a decoded type which represents the value assigned to the
type variable [v] at the end of the resolution process. *)
| CInstance : tevar * variable -> tys co
(**An instantiation constraint [CInstance (x, v)] requires the type
variable [v] to be an instance of the type scheme denoted by the
term variable [x]. Its result is a list of types that indicates
how the type scheme was instantiated. *)
| CDef : tevar * variable * 'a co -> 'a co
(**The constraint [CDef (x, v, c)] binds the term variable [x] to
the trivial (monomorphic) type scheme [v] in the constraint [c]. *)
| CLet :
variables * tevars * variables * 'a co * 'b co ->
(tyvars * schemes * 'a * 'b) co
(**The constraint [CLet rs xs vs c1 c2] is solved as follows:
- First, the constraint [∀rs.∃vs.c1] is solved.
- Then, for each pair [(x, v)] drawn from the lists [xs] and [vs]
(which must have the same length), the term variable [x] is
bound to the constraint abstraction [λv.∃rs.∃(vs\v).c1].
- Finally, under these bindings, the constraint [c2] is solved.
Thus, the variables [rs] are initially regarded as rigid while [c1]
is solved and simplified; but, once this is done, their rigid
nature disappears and they become flexible before generalization
is performed. The scheme associated with the term variable [x]
has the corresponding type variable [v] as its root.
The semantic value of this constraint is a tuple of:
- a list [γs] of decoded type variables that may appear in the semantic
value [v1].
- a list of decoded schemes, in correspondence with the list [xs].
- the semantic value [v1] of the constraint [c1].
- the semantic value [v2] of the constraint [c2]. *)
exception Unbound of range * tevar
exception Unify of range * O.ty * O.ty
exception Cycle of range * O.ty
exception VariableScopeEscape of range
module Printer = struct
[@@@warning "-4"]
open PPrint
let string_of_var v =
string_of_int v
let var v =
string (string_of_var v)
let tevar x =
string (X.to_string x)
let annot (x, v) =
tevar x ^^ string " = " ^^ var v
let shallow_equality s =
string " = " ^^ S.pprint var s
let rec entry : type a . a co -> document = fun c ->
binders c
and binders : type a . a co -> document = fun c ->
let next = conj in
let self = binders in
group @@ match c with
| CRange (_, c) ->
self c
| CMap (c, _) ->
self c
| CExist (v, so, c) ->
string "exi " ^^
var v ^^
optional shallow_equality so ^^
string " in" ^/^
self c
| CDef (x, v, c) ->
string "def " ^^
annot (x, v) ^^
string " in" ^/^
self c
| CLet (rs, xs, vs, c1, c2) ->
assert (List.length xs = List.length vs);
let xvs = List.combine xs vs in
string "let" ^^
(if rs = [] then empty else brackets (separate_map space var rs)) ^^
separate_map (string " and ") annot xvs ^^
string " where" ^^ group (nest 2 (break 1 ^^
next c1 ^^
string " in")) ^/^
self c2
| _ ->
next c
and conj : type a . a co -> document = fun c ->
let self = conj in
let next = simple in
group @@ match c with
| CRange (_, c) ->
self c
| CMap (c, _) ->
self c
| CConj (c1, c2) ->
self c1 ^^ string " *" ^/^ self c2
| _ ->
next c
and simple : type a . a co -> document = fun c ->
let self = simple in
group @@ match c with
| CRange (_, c) ->
self c
| CMap (c, _) ->
self c
| CTrue | CPure _ ->
string "True"
| CDecode v ->
separate space [string "wit"; var v]
| CEq (v1, v2) ->
separate space [var v1; string "="; var v2]
| CInstance (x, v) ->
tevar x ^^ utf8string " ≤ " ^^ var v
| CExist _
| CDef _
| CLet _
| CConj _
->
surround 2 0 lparen (entry c) rparen
end
let pprint =
Printer.entry
module Solve (C : sig
(**The flag [rectypes] indicates whether equirecursive types are permitted. *)
val rectypes: bool
end) = struct
open C
module OS = Structure.Option(S)
module G = Generalization.Make(OS)
module U = G.U
module Env = struct
let table =
TeVarMap.create 8
let lookup range x =
try
TeVarMap.find table x
with Not_found ->
raise (Unbound (range, x))
let bind x s =
TeVarMap.add table x s
let unbind x =
TeVarMap.remove table x
end
module UVar = struct
let table =
VarTable.create 8
let uvar (v : variable) : U.variable =
try
VarTable.find table v
with Not_found ->
Printf.ksprintf failwith "Unbound variable %d" v
let flexible (v : variable) so =
assert (not (VarTable.mem table v));
let uv = G.flexible (OS.map uvar so) in
VarTable.add table v uv;
uv
let rigid (v : variable) =
assert (not (VarTable.mem table v));
let uv = G.rigid() in
VarTable.add table v uv;
uv
let uunbind v =
VarTable.remove table v
end
module D =
Decoder.Make (G.Data) (U) (struct
include O
let structure (s : O.ty U.structure) : O.ty =
O.structure (OS.project_nonleaf (G.Data.project s))
end)
let unify range v1 v2 =
try
U.unify v1 v2
with
| U.Unify (v1, v2) ->
let decode = D.new_cyclic_decoder() in
raise (Unify (range, decode v1, decode v2))
| G.VariableScopeEscape ->
raise (VariableScopeEscape range)
let exit range ~rectypes vs =
try
G.exit ~rectypes vs
with
| G.Cycle v ->
let decode = D.new_cyclic_decoder() in
raise (Cycle (range, decode v))
| G.VariableScopeEscape ->
raise (VariableScopeEscape range)
let decode : U.variable -> O.ty =
if rectypes then D.new_cyclic_decoder() else D.new_acyclic_decoder()
let decode_scheme (s : G.scheme) : scheme =
List.map D.decode_variable (G.quantifiers s),
decode (G.body s)
let rec ok : type a . a co -> bool =
function
| CRange (_, c) ->
ok c
| CTrue | CPure _ ->
true
| CMap (c, _) ->
ok c
| CLet (_rs, _xs, _vs, _c1, c2) ->
ok c2
| CConj (c1, c2) ->
ok c1 && ok c2
| CEq _
| CExist _
| CDecode _
| CInstance _
| CDef _ ->
false
type 'a on_sol =
On_sol of (unit -> 'a) [@@unboxed]
open UVar
let rec solve : type a . range -> a co -> a on_sol =
fun range c -> match c with
| CRange (range, c) ->
solve range c
| CTrue ->
On_sol (fun () -> ())
| CPure x ->
On_sol (fun () -> x)
| CMap (c, f) ->
let (On_sol r) = solve range c in
On_sol (fun () -> f (r ()))
| CConj (c1, c2) ->
let (On_sol r1) = solve range c1 in
let (On_sol r2) = solve range c2 in
On_sol (fun () ->
let a1 = r1() in
let a2 = r2() in
a1, a2
)
| CEq (v, w) ->
unify range (uvar v) (uvar w);
On_sol (fun () -> ())
| CExist (v, s, c) ->
ignore (flexible v s);
let result = solve range c in
uunbind v;
result
| CDecode v ->
let uv = uvar v in
On_sol (fun () -> decode uv)
| CInstance (x, w) ->
let s = Env.lookup range x in
let witnesses, v = G.instantiate s in
unify range v (uvar w);
On_sol (fun () -> List.map decode witnesses)
| CDef (x, v, c) ->
Env.bind x (G.trivial (uvar v));
let a = solve range c in
Env.unbind x;
a
| CLet (rs, xs, vs, c1, c2) ->
G.enter();
let urs = List.map (fun v -> rigid v) rs in
let uvs = List.map (fun v -> flexible v None) vs in
let (On_sol r1) = solve range c1 in
let gammas, ss = exit range ~rectypes uvs in
assert (urs |> List.for_all (fun r -> List.mem r gammas));
List.iter uunbind vs;
List.iter2 Env.bind xs ss;
let (On_sol r2) = solve range c2 in
List.iter Env.unbind xs;
On_sol (fun () ->
List.map D.decode_variable gammas,
List.map decode_scheme ss,
r1(),
r2()
)
let main (type a) (c : a co) : a =
if not (ok c) then
invalid_arg "solve: ill-formed toplevel constraint";
let range = Lexing.(dummy_pos, dummy_pos) in
let (On_sol r) = solve range c in
r()
end
let solve ~rectypes c =
let module S = Solve(struct let rectypes = rectypes end) in
S.main c
let pure x =
CPure x
let (let+) c f = CMap(c, f)
let (and+) c1 c2 = CConj(c1, c2)
let _map f c =
let+ x = c in
f x
let _conjunction c1 c2 =
let+ x1 = c1
and+ x2 = c2
in (x1, x2)
type ('var, 'a) binder =
('var -> 'a co) -> 'a co
let (let@) m f =
m f
let decode v =
CDecode v
let exist_aux t f =
let v = fresh () in
let c = f v in
CExist (v, t, c)
let exist f =
exist_aux None f
let shallow t f =
exist_aux (Some t) f
let lift f v1 t2 =
shallow t2 (fun v2 ->
f v1 v2
)
type deep_ty =
| DeepVar of variable
| DeepStructure of deep_ty S.structure
let deep dty f =
let vs = ref [] in
let rec convert dty =
match dty with
| DeepVar v ->
v
| DeepStructure s ->
let v = fresh () in
let s =
S.map convert s in
vs := (v, s) :: !vs;
v
in
let c = f (convert dty) in
List.fold_left (fun rc (v, s) -> CExist (v, Some s, rc)) c !vs
let (--) v1 v2 =
CEq (v1, v2)
let (---) v t =
lift (--) v t
let _other_lift f v1 t2 =
exist (fun v2 ->
let+ () = v2 --- t2
and+ v = f v1 v2
in v
)
let _shallow (t : variable O.structure) : (variable, 'a) binder =
fun f ->
let@ v = exist in
let+ () = v --- t
and+ y = f v in
y
let instance x v =
CInstance (x, v)
let def x v c =
CDef (x, v, c)
let single xs =
match xs with
| [ x ] ->
x
| _ ->
assert false
let letrn k xs f1 c2 =
let rs = List.init k (fun _ -> fresh()) in
let vs = List.map (fun _ -> fresh()) xs in
let c1 = f1 rs vs in
CLet (rs, xs, vs, c1, c2)
let letr1 k x f1 c2 =
let+ gammas, ss, v1, v2 = letrn k [x] (fun rs vs -> f1 rs (single vs)) c2
in gammas, single ss, v1, v2
let letn xs f1 c2 =
letrn 0 xs (fun _rs vs -> f1 vs) c2
let let1 x f1 c2 =
let+ gammas, ss, v1, v2 = letn [x] (fun vs -> f1 (single vs)) c2
in gammas, single ss, v1, v2
let let0 c1 =
let+ gammas, _, v1, () = letn [] (fun _ -> c1) CTrue
in gammas, v1
let correlate range c =
CRange (range, c)
end