-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathmlfe_typer.erl
3927 lines (3698 loc) · 157 KB
/
mlfe_typer.erl
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
%%% -*- mode: erlang;erlang-indent-level: 4;indent-tabs-mode: nil -*-
%%% ex: ft=erlang ts=4 sw=4 et
%%%
%%% Copyright 2016 Jeremy Pierre
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%% http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%% #mlfe_typer.erl
%%%
%%% This is based off of the sound and eager type inferencer in
%%% http://okmij.org/ftp/ML/generalization.html with some influence
%%% from https://github.com/tomprimozic/type-systems/blob/master/algorithm_w
%%% where the arrow type and instantiation are concerned.
%%%
%%% I still often use proplists in this module, mostly because dialyzer doesn't
%%% yet type maps correctly (Erlang 18.1).
-module(mlfe_typer).
-dialyzer({nowarn_function, dump_env/1}).
-dialyzer({nowarn_function, dump_term/1}).
-include("mlfe_ast.hrl").
-include("builtin_types.hrl").
%%% API
-export([type_modules/1]).
-export_type([t_cell/0]).
%%% Internal
-export([cell/1]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
%%% ##Data Structures
%%%
%%% ###Reference Cells
%%%
%%% Reference cells make unification much simpler (linking is a mutation)
%%% but we also need a simple way to make complete copies of cells so that
%%% each expression being typed can refer to its own copies of items from
%%% the environment and not _globally_ unify another function's types with
%%% its own, preventing others from doing the same (see Types And Programming
%%% Languages (Pierce), chapter 22).
%%% A t_cell is just a reference cell for a type.
-type t_cell() :: pid().
%%% A cell can be sent the message `'stop'` to let the reference cell halt
%%% and be deallocated.
cell(TypVal) ->
receive
{get, Pid} ->
Pid ! TypVal,
cell(TypVal);
{set, NewVal} ->
cell(NewVal);
stop ->
ok
end.
-spec new_cell(typ()) -> pid().
new_cell(Typ) ->
Pid = spawn_link(?MODULE, cell, [Typ]),
Pid.
-spec get_cell(t_cell()|typ()) -> typ().
get_cell(Cell) when is_pid(Cell) ->
Cell ! {get, self()},
receive
Val -> Val
end;
get_cell(NotACell) ->
NotACell.
set_cell(Cell, Val) ->
Cell ! {set, Val},
ok.
%%% The `map` is a map of `unbound type variable name` to a `t_cell()`.
%%% It's used to ensure that each reference or link to a single type
%%% variable actually points to a single canonical reference cell for that
%%% variable. Failing to do so causes problems with unification since
%%% unifying one variable with another type should impact all occurrences
%%% of that variable.
-spec copy_cell(t_cell(), map()) -> {t_cell(), map()}.
copy_cell(Cell, RefMap) ->
case get_cell(Cell) of
{link, C} when is_pid(C) ->
{NC, NewMap} = copy_cell(C, RefMap),
{new_cell({link, NC}), NewMap};
{t_arrow, Args, Ret} ->
%% there's some commonality below with copy_type_list/2
%% that can probably be exploited in future:
Folder = fun(A, {L, RM}) ->
{V, NM} = copy_cell(A, RM),
{[V|L], NM}
end,
{NewArgs, Map2} = lists:foldl(Folder, {[], RefMap}, Args),
{NewRet, Map3} = copy_cell(Ret, Map2),
{new_cell({t_arrow, lists:reverse(NewArgs), NewRet}), Map3};
{unbound, Name, _Lvl} = V ->
case maps:get(Name, RefMap, undefined) of
undefined ->
NC = new_cell(V),
{NC, maps:put(Name, NC, RefMap)};
Existing ->
{Existing, RefMap}
end;
{t_tuple, Members} ->
F = fun(M, {RM, Memo}) ->
{M2, RM2} = copy_cell(M, RM),
{RM2, [M2|Memo]}
end,
{RefMap2, Members2} = lists:foldl(F, {RefMap, []}, Members),
{{t_tuple, lists:reverse(Members2)}, RefMap2};
{t_list, C} ->
{C2, Map2} = copy_cell(C, RefMap),
{new_cell({t_list, C2}), Map2};
{t_map, K, V} ->
{K2, Map2} = copy_cell(K, RefMap),
{V2, Map3} = copy_cell(V, Map2),
{new_cell({t_map, K2, V2}), Map3};
#adt{vars=TypeVars, members=Members}=ADT ->
%% copy the type variables:
Folder = fun({TN, C}, {L, RM}) ->
{C2, NM} = copy_cell(C, RM),
{[{TN, C2}|L], NM}
end,
{NewTypeVars, Map2} = lists:foldl(Folder, {[], RefMap}, TypeVars),
%% and then copy the members:
F2 = fun(M, {L, RM}) ->
{M2, NM} = copy_cell(M, RM),
{[M2|L], NM}
end,
{NewMembers, Map3} = lists:foldl(F2, {[], Map2}, Members),
{new_cell(ADT#adt{vars=lists:reverse(NewTypeVars),
members=lists:reverse(NewMembers)}), Map3};
{t_adt_cons, _}=Constructor ->
{Constructor, RefMap};
P when is_pid(P) ->
copy_cell(P, RefMap);
V ->
{new_cell(V), RefMap}
end.
%%% ###Environments
%%%
%%% Environments track the following:
%%%
%%% 1. A counter for naming new type variables
%%% 2. The modules entered so far while checking the types of functions called
%%% in other modules that have not yet been typed. This is used in a crude
%%% form of detecting mutual recursion between/across modules.
%%% 3. The current module being checked.
%%% 4. The types available to the current module, eventually including
%%% imported types. This is used to find union types.
%%% 5. A proplist from type constructor name to the constructor AST node.
%%% 6. A proplist from type name to its instantiated ADT record.
%%% 7. A proplist of {expression name, expression type} for the types
%%% of values and functions so far inferred/checked.
%%% 8. The set of modules included in type checking.
%%%
%%% I'm including the modules in the typing environment so that when a call
%%% crosses a module boundary into a module not yet checked, we can add the
%%% bindings the other function expects. An example:
%%%
%%% Function `A.f` (f in module A) calls function `B.g` (g in module B). `B.g`
%%% calls an unexported function `B.h`. If the module B has not been checked
%%% before we check `A.f`, we have to check `B.g` in order to determine `A.f`'s
%%% type. In order to check `B.g`, `B.h` must be in the enviroment to also be
%%% checked.
%%%
-record(env, {
next_var=0 :: integer(),
entered_modules=[] :: list(atom()),
current_module=none :: none | mlfe_module(),
current_types=[] :: list(mlfe_type()),
type_constructors=[] :: list({string(), mlfe_constructor()}),
type_bindings=[] :: list({string(), t_adt()}),
bindings=[] :: list({term(), typ()|t_cell()}),
modules=[] :: list(mlfe_module())
}).
-type env() :: #env{}.
new_env(Mods) ->
#env{bindings=[celled_binding(Typ)||Typ <- ?all_bifs],
modules=Mods}.
%%% We need to build a proplist of type constructor name to the actual type
%%% constructor's AST node and associated type.
-spec constructors(list(mlfe_type())) -> list({string(), mlfe_constructor()}).
constructors(Types) ->
MemberFolder =
fun(#mlfe_constructor{name={type_constructor, _, N}}=C, {Type, Acc}) ->
WithType = C#mlfe_constructor{type=Type},
{Type, [{N, WithType}|Acc]};
(_, Acc) ->
Acc
end,
TypesFolder = fun(#mlfe_type{members=Ms}=Typ, Acc) ->
{_, Cs} = lists:foldl(MemberFolder, {Typ, []}, Ms),
[Cs|Acc]
end,
lists:flatten(lists:foldl(TypesFolder, [], Types)).
%% Given a presumed newly-typed module, replace its untyped occurence within
%% the supplied environment. If the module does *not* exist in the environment,
%% it will be added.
replace_env_module(#env{modules=Ms}=E, #mlfe_module{name=N}=M) ->
E#env{modules = [M | [X || #mlfe_module{name=XN}=X <- Ms, XN /= N]]}.
celled_binding({Name, {t_arrow, Args, Ret}}) ->
{Name, {t_arrow, [new_cell(A) || A <- Args], new_cell(Ret)}}.
update_binding(Name, Typ, #env{bindings=Bs} = Env) ->
Env#env{bindings=[{Name, Typ}|[{N, T} || {N, T} <- Bs, N =/= Name]]}.
update_counter(VarNum, Env) ->
Env#env{next_var=VarNum}.
%% Used by deep_copy_type for a set of function arguments or
%% list elements.
copy_type_list(TL, RefMap) ->
Folder = fun(A, {L, RM}) ->
{V, NM} = copy_type(A, RM),
{[V|L], NM}
end,
{NewList, Map2} = lists:foldl(Folder, {[], RefMap}, TL),
{lists:reverse(NewList), Map2}.
%%% As referenced in several places, this is, after a fashion, following
%%% Pierce's advice in chapter 22 of Types and Programming Languages.
%%% We make a deep copy of the chain of reference cells so that we can
%%% unify a polymorphic function with some other types from a function
%%% application without _permanently_ unifying the types for everyone else
%%% and thus possibly blocking a legitimate use of said polymorphic function
%%% in another location.
deep_copy_type({t_arrow, A, B}, RefMap) ->
{NewArgs, Map2} = copy_type_list(A, RefMap),
{NewRet, Map3} = copy_type(B, Map2),
{{t_arrow, NewArgs, NewRet}, Map3};
deep_copy_type({t_list, A}, RefMap) ->
{NewList, Map} = copy_type_list(A, RefMap),
{{t_list, NewList}, Map};
deep_copy_type({t_map, K, V}, RefMap) ->
{NewK, Map2} = copy_type(K, RefMap),
{NewV, Map3} = copy_type(V, Map2),
{{t_map, NewK, NewV}, Map3};
deep_copy_type({t_receiver, A, B}, RefMap) ->
%% Here we're copying the body of the receiver first and then the
%% receiver type itself, explicitly with a method that pulls existing
%% reference cells for named type variables from the map returned by
%% the body's deep copy operation. This ensures that when the same
%% type variable occurs in body the body and receive types we use the
%% same reference cell.
{B2, M2} = deep_copy_type(B, RefMap),
{A2, M3} = copy_type(A, M2),
{{t_receiver, A2, B2}, M3};
deep_copy_type(T, M) ->
{T, M}.
copy_type(P, RefMap) when is_pid(P) ->
copy_cell(P, RefMap);
copy_type({t_arrow, _, _}=A, M) ->
deep_copy_type(A, M);
copy_type({unbound, _, _}=U, M) ->
copy_type(new_cell(U), M);
copy_type(T, M) ->
{new_cell(T), M}.
%%% ## Type Inferencer
occurs(Label, Level, P) when is_pid(P) ->
occurs(Label, Level, get_cell(P));
occurs(Label, _Level, {unbound, Label, _}) ->
{error_circular, Label};
occurs(Label, Level, {link, Ty}) ->
occurs(Label, Level, Ty);
occurs(_Label, Level, {unbound, N, Lvl}) ->
{unbound, N, min(Level, Lvl)};
occurs(Label, Level, {t_arrow, Params, RetTyp}) ->
{t_arrow,
lists:map(fun(T) -> occurs(Label, Level, T) end, Params),
occurs(Label, Level, RetTyp)};
occurs(_L, _Lvl, T) ->
T.
unwrap_cell(C) when is_pid(C) ->
unwrap_cell(get_cell(C));
unwrap_cell(Typ) ->
Typ.
%% Get the name of the current module out of the environment. Useful for
%% error generation.
module_name(#env{current_module=#mlfe_module{name=N}}) ->
N;
module_name(_) ->
undefined.
-type unification_error() ::
{error, {cannot_unify, atom(), integer(), typ(), typ()}}.
%% I make unification error tuples everywhere, just standardizing their
%% construction here:
-spec unify_error(Env::env(), Line::integer(), typ(), typ()) ->
unification_error().
unify_error(Env, Line, Typ1, Typ2) ->
{error, {cannot_unify, module_name(Env), Line, Typ1, Typ2}}.
%%% Unify now requires the environment not in order to make changes to it but
%%% so that it can look up potential type unions when faced with unification
%%% errors.
%%%
%%% For the purposes of record unification, T1 is considered to be the lower
%%% bound for unification. Example:
%%%
%%% a: {x: int, y: int} -- a row variable `A` is implied.
%%% f: {x: int|F} -> (int, {x: int|F})
%%%
%%% Calling f(a) given the above poses no problem. The two `x` members unify
%%% and the `F` in f's type unifies with `y: int|A`. But:
%%%
%%% b: {x: int} - a row variable `B` is implied.
%%% f: {x: int, y: int|F} -> (int, {x: int, y: int|F})
%%%
%%% Here `f` is more specific than `b` and _requires_ a `y: int` member. Its
%%% type must serve as a lower bound for unification, we don't want `f(b)` to
%%% succeed if the implied row variable `B` does not contain a `y: int`.
%%%
%%% Some of the packing into and unpacking from row variables is likely to get
%%% a little hairy in the first implementation here.
-spec unify(typ(), typ(), env(), integer()) -> ok | {error, term()}.
unify(T1, T2, Env, Line) ->
case {unwrap_cell(T1), unwrap_cell(T2)} of
{T, T} ->
ok;
%% only one instance of a type variable is permitted:
{{unbound, N, _}, {unbound, N, _}} -> unify_error(Env, Line, T1, T2);
{{link, Ty}, _} ->
unify(Ty, T2, Env, Line);
{_, {link, Ty}} ->
unify(T1, Ty, Env, Line);
{t_rec, _} ->
set_cell(T1, {link, T2}),
ok;
{_, t_rec} ->
set_cell(T2, {link, T1}),
ok;
%% Definitely room for cleanup in the next two cases:
{{unbound, N, Lvl}, Ty} ->
case occurs(N, Lvl, Ty) of
{unbound, _, _} = T ->
set_cell(T2, T),
set_cell(T1, {link, T2});
{error, _} = E ->
E;
_Other ->
set_cell(T1, {link, T2})
end,
ok;
{Ty, {unbound, N, Lvl}} ->
case occurs(N, Lvl, Ty) of
{unbound, _, _} = T ->
set_cell(T1, T), % level adjustment
set_cell(T2, {link, T1});
{error, _} = E ->
E;
_Other ->
set_cell(T2, {link, T1})
end,
set_cell(T2, {link, T1}),
ok;
%%% This section creeps me right out at the moment. This is where some
%%% other operator that moves the receiver to the outside should be.
%%% Smells like a functor or monad to me.
{{t_arrow, _, A2}, {t_arrow, _, B2}} ->
ArrowArgCells = fun(C) when is_pid(C) ->
{t_arrow, Xs, _}=get_cell(C),
Xs;
({t_arrow, Xs, _}) -> Xs
end,
case unify_list(ArrowArgCells(T1), ArrowArgCells(T2), Env, Line) of
{error, _} = E -> E;
_ ->
%% Unwrap cells and links down to the first non-cell level.
%% Super gross.
F = fun(C) when is_pid(C) ->
case get_cell(C) of
{t_receiver, _, _}=R ->
R;
{link, CC} when is_pid(CC) ->
case get_cell(CC) of
{t_receiver, _, _}=R2 -> R2;
_ -> none
end;
{link, {t_receiver, _, _}=R2} -> R2;
_ -> none
end;
({link, CC}) when is_pid(CC) ->
case get_cell(CC) of
{t_receiver, _, _}=R2 -> R2;
_ -> none
end;
({t_receiver, _, _}=X) -> X;
(_) -> none
end,
AArgs = case T1 of
_ when is_pid(T1) ->
{t_arrow, Xs, _}=get_cell(T1),
Xs;
_ ->
{t_arrow, Xs, _}=T1,
Xs
end,
StripCell = fun(C) when is_pid(C) -> get_cell(C);
({link, C}) when is_pid(C) -> get_cell(C);
({link, X}) -> X;
(X) -> X
end,
NoCellArgs = lists:map(StripCell, lists:map(StripCell, AArgs)),
RR = [Receiver||{t_receiver, _, _}=Receiver
<- lists:map(F, NoCellArgs)],
%% Any argument to a function application that is a receiver
%% makes the entire expression a receiver.
case RR of
[] ->
unify(A2, B2, Env, Line);
%% The received types for each receiver must unify in
%% order for the process to be typed correctly.
[{t_receiver, H, _}|Tail] ->
Unify = fun(_, {error, _}=Err) -> Err;
({t_receiver, T, _}, Acc) ->
case unify(T, Acc, Env, Line) of
{error, _}=Err -> Err;
ok -> T
end;
(_Other, Acc) ->
Acc
end,
case lists:foldl(Unify, H, Tail) of
{error, _}=Err -> Err;
_ ->
case unify(A2, B2, Env, Line) of
{error, _}=Err -> Err;
ok ->
%% Re-wrapping with fresh cells
%% because I was running into
%% cycles. This entire block of
%% arrow unification needs to be
%% rewritten.
Receiver = {t_receiver,
new_cell(unwrap(H)),
new_cell(unwrap(A2))},
set_cell(A2, Receiver),
set_cell(B2, {link, A2}),
ok
end
end
end
end;
{{t_tuple, A}, {t_tuple, B}} when length(A) =:= length(B) ->
case unify_list(A, B, Env, Line) of
{error, _} = Err -> Err;
_ -> ok
end;
{{t_list, _}, t_nil} ->
set_cell(T2, {link, T1}),
ok;
{t_nil, {t_list, _}} ->
set_cell(T1, {link, T2}),
ok;
{{t_list, A}, {t_list, B}} ->
unify(A, B, Env, Line);
{{t_map, A1, B1}, {t_map, A2, B2}} ->
case unify(A1, A2, Env, Line) of
{error, _}=Err -> Err;
ok ->
case unify(B1, B2, Env, Line) of
{error, _}=Err -> Err;
ok -> ok
end
end;
{#t_record{}=LowerBound, #t_record{}=Target} ->
unify_records(LowerBound, Target, Env, Line);
{#adt{}=A, B} -> unify_adt(T1, T2, A, B, Env, Line);
{A, #adt{}=B} -> unify_adt(T2, T1, B, A, Env, Line);
{{t_pid, _}, {t_pid, _}} ->
{t_pid, AC} = get_cell(T1),
{t_pid, BC} = get_cell(T2),
case unify(AC, BC, Env, Line) of
{error, _}=Err -> Err;
ok ->
set_cell(T1, new_cell({t_pid, AC})),
set_cell(T2, {link, T1}),
ok
end;
%%% Receivers unify with each other or in the case of a receiver and
%%% something else, the receiver unifies its result type with the other
%%% expression and both become receivers.
{{t_receiver, _, _}, {t_receiver, _, _}} ->
RecvRes = fun(C) when is_pid(C) ->
{t_receiver, _, X} = get_cell(C),
X;
({t_receiver, _, X}) ->
X
end,
RecvR = fun(C) when is_pid(C) ->
{t_receiver, X, _} = get_cell(C),
X;
({t_receiver, X, _}) ->
X
end,
case unify(RecvR(T1), RecvR(T2), Env, Line) of
{error, _}=Err -> Err;
ok -> case unify(RecvRes(T1), RecvRes(T2), Env, Line) of
{error, _}=Err -> Err;
ok ->
set_cell(T2, {link, T1}),
ok
end
end;
{{t_receiver, Recv, ResA}, {t_arrow, Args, ResB}} ->
case unify(ResA, ResB, Env, Line) of
{error, _}=Err -> Err;
ok ->
NewTyp = {t_receiver, Recv, {t_arrow, Args, ResA}},
set_cell(T1, NewTyp),
set_cell(T2, {link, T1}),
ok
end;
{{t_arrow, _, _}, {t_receiver, _, _}} ->
unify(T2, T1, Env, Line);
{{t_receiver, _Recv, ResA}, B} ->
case unify(ResA, new_cell(B), Env, Line) of
{error, _}=Err -> Err;
ok ->
set_cell(T2, {link, T1}),
ok
end;
{_A, {t_receiver, _Recv, _ResB}} ->
unify(T2, T1, Env, Line);
{_T1, _T2} ->
io:format("Find covering for ~w ~w~n", [T1, T2]),
case find_covering_type(_T1, _T2, Env, Line) of
{error, _}=Err ->
io:format("UNIFY FAIL: ~w AND ~w~n",
[unwrap(T1), unwrap(T2)]),
io:format("LINE ~w~n", [Line]),
Err;
{ok, _EnvOut, Union} ->
io:format("UNIFIED ~w AND ~w on ~w~n",
[unwrap(_T1), unwrap(_T2), unwrap(Union)]),
set_cell(T1, Union),
set_cell(T2, Union),
%% TODO: output environment.
ok
end
end.
%%% Here we're checking for membership of one party in another or for an
%%% exact match.
-spec unify_adt(t_cell(), t_cell(), t_adt(), typ(), env(), Line::integer()) ->
ok |
{error, {cannot_unify, typ(), typ()}}.
unify_adt(C1, C2, #adt{name=N, vars=AVars}=A,
#adt{name=N, vars=BVars}, Env, L) ->
%% Don't unify the keys _and_ vars:
case unify_list([V||{_, V} <- AVars], [V||{_, V} <- BVars], Env, L) of
{error, _}=Err -> Err;
_ ->
set_cell(C1, A),
set_cell(C2, {link, C1}),
ok
end;
unify_adt(C1, C2, #adt{vars=Vs, members=Ms}=A, AtomTyp, Env, L)
when is_atom(AtomTyp) ->
case [M||M <- Ms, unwrap(M) =:= AtomTyp] of
[_] ->
set_cell(C1, A),
set_cell(C2, {link, C1}),
ok;
[] ->
VFolder = fun(_, ok) -> ok;
({_, V}, Res) ->
case lists:member(V, Ms) of
true -> unify(AtomTyp, V, Env, L);
false -> Res
end
end,
lists:foldl(VFolder, unify_error(Env, L, A, AtomTyp), Vs)
end;
%% If an ADTs members are empty, it's a reference to an ADT that should
%% be instantiated in the environment. Replace it with the instantiated
%% version before proceeding. Having separate cases for A and B is
%% bothering me.
unify_adt(C1, C2, #adt{name=NA, members=[]}, B, Env, L) ->
case proplists:get_value(NA, Env#env.type_bindings) of
undefined -> {error, {no_type_for_name, NA}};
ADT -> unify_adt(C1, C2, ADT, B, Env, L)
end;
unify_adt(_C1, _C2,
#adt{name=NA, vars=VarsA, members=MA}=A,
#adt{name=NB, vars=VarsB, members=MB}=B, Env, L) ->
MemberFilter = fun(N) -> fun(#adt{name=AN}) when N =:= AN -> true;
(_) -> false
end
end,
case lists:filter(MemberFilter(NB), MA) of
[#adt{vars=ToCheck}] ->
UnifyFun = fun(_, {error, _}=Err) -> Err;
({{_, X}, {_, Y}}, ok) -> unify(L, X, Y, Env)
end,
lists:foldl(UnifyFun, ok, lists:zip(VarsB, ToCheck));
_ ->
case lists:filter(MemberFilter(NA), MB) of
[#adt{vars=ToCheck}] ->
UnifyFun = fun(_, {error, _}=Err) -> Err;
({{_, X}, {_, Y}}, ok) -> unify(L, X, Y, Env)
end,
lists:foldl(UnifyFun, ok, lists:zip(VarsA, ToCheck));
_ -> unify_error(Env, L, A, B)
end
end;
unify_adt(C1, C2, #adt{}=A, {t_tuple, _}=ToCheck, Env, L) ->
unify_adt_and_poly(C1, C2, A, ToCheck, Env, L);
unify_adt(C1, C2, #adt{}=A, {t_list, _LType}=ToCheck, Env, L) ->
unify_adt_and_poly(C1, C2, A, ToCheck, Env, L);
unify_adt(C1, C2, #adt{}=A, {t_map, _, _}=ToCheck, Env, L) ->
unify_adt_and_poly(C1, C2, A, ToCheck, Env, L);
unify_adt(C1, C2, #adt{}=A, #t_record{}=ToCheck, Env, L) ->
unify_adt_and_poly(C1, C2, A, ToCheck, Env, L);
unify_adt(_, _, A, B, Env, L) ->
unify_error(Env, L, A, B).
unify_adt_and_poly(C1, C2, #adt{members=Ms}=A, ToCheck, Env, L) when is_pid(ToCheck) ->
%% Try to find an ADT member that will unify with the passed in
%% polymorphic type:
F = fun(_, ok) -> ok;
(T, Res) ->
case unify(ToCheck, T, Env, L) of
ok ->
set_cell(C2, {link, C1}),
ok;
_ ->
Res
end
end,
Seed = unify_error(Env, L, A, ToCheck),
lists:foldl(F, Seed, Ms);
%% ToCheck needs to be in a reference cell for unification and we're not
%% worried about losing the cell at this level since C1 and C2 are what
%% will actually be manipulated.
unify_adt_and_poly(C1, C2, #adt{members=Ms}=A, ToCheck, Env, L) ->
unify_adt_and_poly(C1, C2, A, new_cell(ToCheck), Env, L).
%%% Given two different types, find a type in the set of currently available
%%% types that can unify them or fail.
-spec find_covering_type(
T1::typ(),
T2::typ(),
env(),
integer()) -> {ok, typ(), env()} |
{error,
{cannot_unify, atom(), integer(), typ(), typ()} |
{bad_variable, integer(), mlfe_type_var()}}.
find_covering_type(T1, T2, #env{current_types=Ts}=EnvIn, L) ->
%% Convert all the available types to actual ADT types with
%% which to attempt unions:
TypeFolder = fun(_ ,{error, _}=Err) ->
Err;
(Typ, {ADTs, E}) ->
case inst_type(Typ, E) of
{error, _}=Err -> Err;
{ok, E2, ADT, Ms} -> {[{ADT, Ms}|ADTs], E2}
end
end,
%% We remove all of the types from the environment because we don't want
%% to reinstantiate them again on unification failure when it's trying
%% to unify the two types with the instantiated member types.
%%
%% For example, if `T1` is `t_int` and the first member of a type we're
%% checking for valid union is anything _other_ that `t_int`, the call
%% to `unify` in `try_types` will cause `unify` to call this method
%% (`find_covering_type`) again, leading to instantiating all of the
%% types all over again and eventually leading to a spawn limit error.
%% By simply removing the types from the environment before proceeding,
%% we avoid this cycle.
case lists:foldl(TypeFolder, {[], EnvIn#env{current_types=[]}}, Ts) of
{error, _}=Err -> Err;
{ADTs, EnvOut} ->
ReturnEnv = EnvOut#env{current_types=EnvIn#env.current_types},
%% each type, filter to types that are T1 or T2, if the list
%% contains both, it's a match.
F = fun(_, {ok, _}=Res) ->
Res;
({ADT, Ms}, Acc) ->
case try_types(T1, T2, Ms, EnvOut, L, {none, none}) of
{ok, ok} -> {ok, ReturnEnv, ADT};
_ -> Acc
end
end,
Default = unify_error(EnvIn, L, T1, T2),
lists:foldl(F, Default, lists:reverse(ADTs))
end.
%%% try_types/5 attempts to unify the two given types with each ADT available
%%% to the module until one is found that covers both types or we run out of
%%% available types, yielding `'no_match'`.
try_types(_, _, _, _, _, {ok, ok}=Memo) ->
Memo;
try_types(T1, T2, [Candidate|Tail], Env, L, {none, none}) ->
case unify(T1, Candidate, Env, L) of
ok -> try_types(T1, T2, Tail, Env, L, {ok, none});
_ -> case unify(T2, Candidate, Env, L) of
ok -> try_types(T1, T2, Tail, Env, L, {none, ok});
_ -> try_types(T1, T2, Tail, Env, L, {none, none})
end
end;
try_types(T1, T2, [Candidate|Tail], Env, L, {none, M2}=Memo) ->
case unify(T1, Candidate, Env, L) of
ok -> try_types(T1, T2, Tail, Env, L, {ok, M2});
_ -> try_types(T1, T2, Tail, Env, L, Memo)
end;
try_types(T1, T2, [Candidate|Tail], Env, L, {M1, none}=Memo) ->
case unify(T2, Candidate, Env, L) of
ok -> try_types(T1, T2, Tail, Env, L, {M1, ok});
_ -> try_types(T1, T2, Tail, Env, L, Memo)
end;
try_types(_, _, [], _, _, _) ->
no_match.
unify_records(LowerBound, Target, Env, Line) ->
%% unify each member of the lower bound with the others
#t_record{members=LowerM, row_var=LowerRow} = flatten_record(LowerBound),
#t_record{members=TargetM, row_var=TargetRow} = flatten_record(Target),
%% we operate on the target's members so that if the unification
%% with the lower bound's members succeeds, we have a list of exactly
%% what needs to unify with the lower's row variable.
KeyedTarget = lists:map(fun(#t_record_member{name=X}=TRM) -> {X, TRM} end, TargetM),
RemainingTarget = unify_record_members(LowerM, KeyedTarget, Env, Line),
%% unify the row variables
case RemainingTarget of
[] ->
unify(LowerRow, TargetRow, Env, Line);
_ ->
NewTarget = new_cell(#t_record{members=RemainingTarget, row_var=TargetRow}),
unify(LowerRow, NewTarget, Env, Line)
end.
unify_record_members([], TargetRem, Env, Line) ->
lists:map(fun({_, X}) -> X end, TargetRem);
unify_record_members([LowerBound|Rem], TargetRem, Env, Line) ->
#t_record_member{name=N, type=T} = LowerBound,
case proplists:get_value(N, TargetRem) of
undefined ->
erlang:error({missing_record_field, Line, N});
#t_record_member{type=T2} ->
case unify(T, T2, Env, Line) of
{error, _}=Err ->
erlang:error(Err);
ok ->
NewTargetRem = proplists:delete(N, TargetRem),
unify_record_members(Rem, NewTargetRem, Env, Line)
end
end.
%% Record types are basically linked lists where the `row_var` portion
%% could be either an unbound type variable or another record type. We
%% need to unpack these row variables to unify records predictably and
%% also upon completion of typing. Problems could occur when unifying the
%% following:
%%
%% #t_record{members={x, t_int}, row_var=#t_record{members={y, t_int}}, ...}
%% #t_record{members={y, t_int}, row_var=#t_record{members={x, t_int}}, ...}
%%
%% Because the members that need unifying (coming from either record to the
%% other) are effectively hidden in their respective row variables,
%% unify_record_members won't see them directly.
flatten_record(#t_record{members=Ms, row_var=#t_record{}=Inner}) ->
#t_record{members=InnerMs, row_var=InnerRow} = Inner,
flatten_record(#t_record{members=Ms ++ InnerMs, row_var=InnerRow});
flatten_record(#t_record{row_var=P}=R) when is_pid(P) ->
case get_cell(P) of
#t_record{}=Inner -> flatten_record(R#t_record{row_var=Inner});
{link, L}=Link -> flatten_record(R#t_record{row_var=L});
_ -> R
end;
flatten_record(#t_record{}=R) ->
R.
%%% To search for a potential union, a type's variables all need to be
%%% instantiated and its members that are other types need to use the
%%% same variables wherever referenced. The successful returned elements
%%% (not including `'ok'`) include:
%%%
%%% - the instantiated type as an `#adt{}` record, with real type variable
%%% cells.
%%% - a list of all members that are _types_, so type variables, tuples, and
%%% other types but _not_ ADT constructors.
%%%
%%% Any members that are polymorphic types (AKA "generics") must reference
%%% only the containing type's variables or an error will result.
%%%
%%% In the `VarFolder` function you'll see that I always use a level of `0`
%%% for type variables. My thinking here is that since types are only
%%% defined at the top level, their variables are always created at the
%%% highest level. I might be wrong here and need to include the typing
%%% level as passed to inst/3 as well.
-spec inst_type(mlfe_type(), EnvIn::env()) ->
{ok, env(), typ(), list(typ())} |
{error, {bad_variable, integer(), mlfe_type_var()}}.
inst_type(Typ, EnvIn) ->
#mlfe_type{name={type_name, _, N}, vars=Vs, members=Ms} = Typ,
VarFolder = fun({type_var, _, VN}, {Vars, E}) ->
{TVar, E2} = new_var(0, E),
{[{VN, TVar}|Vars], E2}
end,
{Vars, Env} = lists:foldl(VarFolder, {[], EnvIn}, Vs),
ParentADT = #adt{name=N, vars=lists:reverse(Vars)},
inst_type_members(ParentADT, Ms, Env, []).
inst_type_members(ParentADT, [], Env, FinishedMembers) ->
{ok,
Env,
new_cell(ParentADT#adt{members=FinishedMembers}),
lists:reverse(FinishedMembers)};
%% single atom types are passed unchanged (built-in types):
inst_type_members(ParentADT, [H|T], Env, Memo) when is_atom(H) ->
inst_type_members(ParentADT, T, Env, [new_cell(H)|Memo]);
inst_type_members(ADT, [{mlfe_list, TExp}|Rem], Env, Memo) ->
case inst_type_members(ADT, [TExp], Env, []) of
{error, _}=Err -> Err;
{ok, Env2, _, [InstMem]} ->
inst_type_members(ADT, Rem, Env2,
[new_cell({t_list, InstMem})|Memo])
end;
inst_type_members(ADT, [{mlfe_map, KExp, VExp}|Rem], Env, Memo) ->
case inst_type_members(ADT, [KExp], Env, []) of
{error, _}=Err -> Err;
{ok, Env2, _, [InstK]} ->
case inst_type_members(ADT, [VExp], Env2, []) of
{error, _}=Err -> Err;
{ok, Env3, _, [InstV]} ->
NewT = new_cell({t_map, InstK, InstV}),
inst_type_members(ADT, Rem, Env3, [NewT|Memo])
end
end;
inst_type_members(ADT, [#t_record{}=R|Rem], Env, Memo) ->
#t_record{members=Ms, row_var=RV} = R,
{RVC, Env2} = case RV of
undefined ->
{V, E} = new_var(0, Env),
{new_cell(V), E};
{unbound, _, _}=V ->
{new_cell(V), Env};
_ ->
{RV, Env}
end,
F = fun(#t_record_member{type=T}=M, {NewMems, E}) ->
case inst_type_members(ADT, [T], Env, []) of
{error, _}=Err ->
erlang:error(Err);
{ok, E2, _, [InstT]} ->
{[M#t_record_member{type=InstT}|NewMems], E2}
end
end,
{NewMems, Env3} = lists:foldl(F, {[], Env2}, Ms),
NewT = new_cell(#t_record{members=lists:reverse(NewMems), row_var=RVC}),
inst_type_members(ADT, Rem, Env3, [NewT|Memo]);
inst_type_members(ADT, [{mlfe_pid, TExp}|Rem], Env, Memo) ->
case inst_type_members(ADT, [TExp], Env, []) of
{error, _}=Err ->
Err;
{ok, Env2, _, [InstMem]} ->
inst_type_members(ADT, Rem, Env2,
[new_cell({t_pid, InstMem})|Memo])
end;
inst_type_members(#adt{vars=Vs}=ADT, [{type_var, L, N}|T], Env, Memo) ->
Default = {error, {bad_variable, L, N}},
case proplists:get_value(N, Vs, Default) of
{error, _}=Err -> Err;
Typ -> inst_type_members(ADT, T, Env, [Typ|Memo])
end;
inst_type_members(ADT, [#mlfe_type_tuple{members=Ms}|T], Env, Memo) ->
case inst_type_members(ADT, Ms, Env, []) of
{error, _}=Err ->
Err;
{ok, Env2, _, InstMembers} ->
inst_type_members(ADT, T, Env2,
[new_cell({t_tuple, InstMembers})|Memo])
end;
inst_type_members(ADT,
[#mlfe_type{name={type_name, _, N}, vars=Vs, members=[]}|T],
Env,
Memo) ->
case inst_type_members(ADT, Vs, Env, []) of
{error, _}=Err -> Err;
{ok, Env2, _, Members} ->
Names = [VN || {type_var, _, VN} <- Vs],
NewMember = #adt{name=N, vars=lists:zip(Names, Members)},
inst_type_members(ADT, T, Env2, [NewMember|Memo])
end;
inst_type_members(ADT, [#mlfe_constructor{name={_, _, N}}|T], Env, Memo) ->
inst_type_members(ADT, T, Env, [{t_adt_cons, N}|Memo]);
%% Everything else gets discared. Type constructors are not types in their
%% own right and thus not eligible for unification so we just discard them here:
inst_type_members(ADT, [_|T], Env, Memo) ->
inst_type_members(ADT, T, Env, Memo).
%%% When the typer encounters the application of a type constructor, we can
%%% treat it somewhat like a typ arrow vs a normal function arrow (see
%%% `typ_apply/5`). The difference is that the arity is always `1` and the
%%% result type may contain numerous type variables rather than the single
%%% type variable in a normal arrow. Example:
%%%
%%% type t 'x 'y = A 'x | B 'y
%%%
%%% f z = A (z + 1)
%%%
%%% We need a way to unify the constructor application with a type constructor
%%% arrow that will yield something matching the following:
%%%
%%% #adt{name="t", vars=[t_int, {unbound, _, _}]
%%%
%%% To do this, `inst_type_arrow` builds a type arrow that uses the same type
%%% variable cells in the argument as in the return type, which is of course
%%% an instantiated instance of the ADT. If the "type arrow" unifies with
%%% the argument in the actual constructor application, the return of the type
%%% arrow will have the correct variables instantiated.
-spec inst_type_arrow(Env::env(), Name::mlfe_constructor_name()) ->
{ok, env(), {typ_arrow, typ(), t_adt()}} |
{error, {bad_constructor, integer(), string()}} |
{error, {unknown_type, string()}} |
{error, {bad_constructor_arg,term()}}.
inst_type_arrow(EnvIn, {type_constructor, Line, Name}) ->
%% 20160603: I have an awful lot of case ... of all over this
%% codebase, trying a lineup of functions specific to this
%% task here instead. Sort of want Scala's `Try`.
ADT_f = fun({error, _}=Err) ->
Err;
(#mlfe_constructor{type=#mlfe_type{}=T}=C) ->
{C, inst_type(T, EnvIn)}
end,
Cons_f = fun({_, {error, _}=Err}) ->Err;
({C, {ok, Env, ADT, _}}) ->
#adt{vars=Vs} = get_cell(ADT),
#mlfe_constructor{arg=Arg} = C,
Types = EnvIn#env.current_types,
Arrow = {type_arrow, inst_constructor_arg(Arg, Vs, Types), ADT},
{Env, Arrow}
end,
Default = {error, {bad_constructor, Line, Name}},
C = proplists:get_value(Name, EnvIn#env.type_constructors, Default),
try Cons_f(ADT_f(C))
catch
throw:{error, _}=Error -> Error
end.
inst_constructor_arg(none, _, _) ->
t_unit;
inst_constructor_arg(AtomType, _, _) when is_atom(AtomType) ->
AtomType;
inst_constructor_arg({type_var, _, N}, Vs, _) ->
proplists:get_value(N, Vs);