forked from Fundament-Software/Alicorn0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluator.lua
3364 lines (3109 loc) · 119 KB
/
evaluator.lua
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
local terms = require "./terms"
local metalanguage = require "./metalanguage"
local U = require "./alicorn-utils"
local runtime_context = terms.runtime_context
local s = require("./pretty-printer").s
--local new_typechecking_context = terms.typechecking_context
--local checkable_term = terms.checkable_term
--local inferrable_term = terms.inferrable_term
local typed_term = terms.typed_term
local free = terms.free
local visibility = terms.visibility
local purity = terms.purity
local result_info = terms.result_info
local value = terms.value
local neutral_value = terms.neutral_value
local host_syntax_type = terms.host_syntax_type
local host_environment_type = terms.host_environment_type
local host_typed_term_type = terms.host_typed_term_type
local host_goal_type = terms.host_goal_type
local host_inferrable_term_type = terms.host_inferrable_term_type
local gen = require "./terms-generators"
local map = gen.declare_map
local string_typed_map = map(gen.builtin_string, typed_term)
local string_value_map = map(gen.builtin_string, value)
local array = gen.declare_array
local typed_array = array(typed_term)
local value_array = array(value)
local host_array = array(gen.any_lua_type)
local usage_array = array(gen.builtin_number)
local string_array = array(gen.builtin_string)
local internals_interface = require "./internals-interface"
local param_info_explicit = value.param_info(value.visibility(visibility.explicit))
local result_info_pure = value.result_info(result_info(purity.pure))
--local derivers = require "./derivers"
--local traits = require "./traits"
local OMEGA = 10
local typechecker_state
local evaluate, infer, check, apply_value
local name_array = string_array
local typed = terms.typed_term
---@param luafunc function
---@param parameters ArrayValue -- example usage: name_array("#wrap-TODO1", "#wrap-TODO2")
---@return value
local function luatovalue(luafunc, parameters)
local len = parameters:len()
local new_body = typed_array()
for i = 1, len do
new_body:append(typed.bound_variable(i + 1))
end
return value.closure(
"#args",
typed.application(
typed.literal(value.host_value(luafunc)),
typed.tuple_elim(parameters, typed.bound_variable(1), len, typed.host_tuple_cons(new_body))
),
runtime_context()
)
end
---@param srel SubtypeRelation
---@return SubtypeRelation
local function FunctionRelation(srel)
return {
debug_name = "FunctionRelation(" .. srel.debug_name .. ")",
srel = srel,
Rel = luatovalue(function(a, b) end, name_array("a", "b")),
refl = luatovalue(function(a) end, name_array("a")),
antisym = luatovalue(function(a, b, r1, r2) end, name_array("a", "b", "r1", "r2")),
constrain = luatovalue(function(val, use)
local u = value.neutral(neutral_value.free(free.unique({})))
local applied_val = U.tag("apply_value", { val = val, use = use }, apply_value, val, u)
local applied_use = U.tag("apply_value", { val = val, use = use }, apply_value, use, u)
typechecker_state:queue_constrain(applied_val, srel, applied_use, "FunctionRelation inner")
end, name_array("val", "use")),
}
end
FunctionRelation = U.memoize(FunctionRelation)
---@type SubtypeRelation
local effect_row_srel
effect_row_srel = {
debug_name = "effect_row_srel",
Rel = luatovalue(function(a, b) end, name_array("a", "b")),
refl = luatovalue(function(a) end, name_array("a")),
antisym = luatovalue(function(a, b, r1, r2) end, name_array("a", "b", "r1", "r2")),
constrain = luatovalue(
---@param val value
---@param use value
function(val, use)
if val:is_effect_empty() then
return true
end
if val:is_effect_row() then
local val_components, val_rest = val:unwrap_effect_row()
if use:is_effect_empty() then
error "production has effect requirements that the consumption doesn't fulfill"
end
if not use:is_effect_row() then
error "consumption of effect row constraint isn't an effect row?"
end
local use_components, use_rest = use:unwrap_effect_row()
if not use_components:superset(val_components) then
error "consumption of effect row doesn't satisfy all components of production"
end
--TODO allow polymorphism
if val_rest:is_effect_empty() and use_rest:is_effect_empty() then
return true
end
error "NYI effect polymorphism"
end
end,
name_array("val", "use")
),
}
---@type SubtypeRelation
local UniverseOmegaRelation
---@param onto ArrayValue
---@param with ArrayValue
local function add_arrays(onto, with)
local olen = #onto
for i, n in ipairs(with) do
local x
if i > olen then
x = 0
else
x = onto[i]
end
onto[i] = x + n
end
end
---make an alicorn function that returns the specified values
---@param v value
---@return value
local function const_combinator(v)
return value.closure("#CONST_PARAM", typed_term.bound_variable(1), runtime_context():append(v))
end
---@param t value
---@return integer
local function get_level(t)
-- TODO: this
-- TODO: typecheck
return 0
end
---@param val value an alicorn value
---@param mappings {[integer]: typed} the placeholder we are trying to get rid of by substituting
---@param context_len integer number of bindings in the runtime context already used - needed for closures
---@return typed a typed term
local function substitute_inner(val, mappings, context_len)
if val:is_visibility_type() then
return typed_term.literal(val)
elseif val:is_visibility() then
return typed_term.literal(val)
elseif val:is_param_info_type() then
return typed_term.literal(val)
elseif val:is_param_info() then
-- local visibility = val:unwrap_param_info()
-- TODO: this needs to be evaluated properly because it contains a value
return typed_term.literal(val)
elseif val:is_result_info_type() then
return typed_term.literal(val)
elseif val:is_result_info() then
return typed_term.literal(val)
elseif val:is_pi() then
local param_type, param_info, result_type, result_info = val:unwrap_pi()
local param_type = substitute_inner(param_type, mappings, context_len)
local param_info = substitute_inner(param_info, mappings, context_len)
local result_type = substitute_inner(result_type, mappings, context_len)
local result_info = substitute_inner(result_info, mappings, context_len)
return typed_term.pi(param_type, param_info, result_type, result_info)
elseif val:is_closure() then
local param_name, code, capture = val:unwrap_closure()
local unique = {}
local arg = value.neutral(neutral_value.free(free.unique(unique)))
val = apply_value(val, arg)
--print("applied closure during substitution: (value term follows)")
--print(val)
-- Here we need to add the new arg placeholder to a map of things to substitute
-- otherwise it would be left as a free.unique in the result
mappings[unique] = typed_term.bound_variable(context_len + 1)
local val_typed = substitute_inner(val, mappings, context_len + 1)
-- FIXME: this results in more captures every time we substitute a closure ->
-- can cause non-obvious memory leaks
-- since we don't yet remove unused captures from closure value
return typed_term.lambda(param_name, val_typed)
elseif val:is_name_type() then
return typed_term.literal(val)
elseif val:is_name() then
return typed_term.literal(val)
elseif val:is_operative_value() then
local userdata = val:unwrap_operative_value()
local userdata = substitute_inner(userdata, mappings, context_len)
return typed_term.operative_cons(userdata)
elseif val:is_operative_type() then
local handler, userdata_type = val:unwrap_operative_type()
local typed_handler = substitute_inner(handler, mappings, context_len)
local typed_userdata_type = substitute_inner(userdata_type, mappings, context_len)
return typed_term.operative_type_cons(typed_handler, typed_userdata_type)
elseif val:is_tuple_value() then
local elems = val:unwrap_tuple_value()
local res = typed_array()
for _, v in ipairs(elems) do
res:append(substitute_inner(v, mappings, context_len))
end
return typed_term.tuple_cons(res)
elseif val:is_tuple_type() then
local desc = val:unwrap_tuple_type()
local desc = substitute_inner(desc, mappings, context_len)
return typed_term.tuple_type(desc)
elseif val:is_tuple_desc_type() then
return typed_term.literal(val)
elseif val:is_enum_value() then
local constructor, arg = val:unwrap_enum_value()
local arg = substitute_inner(arg, mappings, context_len)
return typed_term.enum_cons(constructor, arg)
elseif val:is_enum_type() then
local desc = val:unwrap_enum_type()
-- TODO: Handle desc properly, because it's a value.
return typed_term.literal(val)
elseif val:is_record_value() then
-- TODO: How to deal with a map?
error("Records not yet implemented")
elseif val:is_record_type() then
local desc = val:unwrap_record_type()
-- TODO: Handle desc properly, because it's a value.
error("Records not yet implemented")
elseif val:is_record_extend_stuck() then
-- Needs to handle the nuetral value and map of values
error("Records not yet implemented")
elseif val:is_object_value() then
return typed_term.literal(val)
elseif val:is_object_type() then
-- local desc = val:unwrap_object_type()
-- TODO: this needs to be evaluated properly because it contains a value
error("Not yet implemented")
elseif val:is_level_type() then
return typed_term.literal(val)
elseif val:is_number_type() then
return typed_term.literal(val)
elseif val:is_number() then
return typed_term.literal(val)
elseif val:is_level() then
return typed_term.literal(val)
elseif val:is_star() then
return typed_term.literal(val)
elseif val:is_prop() then
return typed_term.literal(val)
elseif val:is_neutral() then
local nval = val:unwrap_neutral()
if nval:is_free() then
local free = nval:unwrap_free()
local lookup
if free:is_placeholder() then
lookup = free:unwrap_placeholder()
elseif free:is_unique() then
lookup = free:unwrap_unique()
elseif free:is_metavariable() then
local mv = free:unwrap_metavariable()
if not (mv.block_level < typechecker_state.block_level) then
local above, below, reln = typechecker_state:slice_constraints_for(mv)
local above_acc, below_acc = typed_array(), typed_array()
for _, v in ipairs(above) do
local subject_term = substitute_inner(v, mappings, context_len)
above_acc:append(subject_term)
end
for _, v in ipairs(below) do
local subject_term = substitute_inner(v, mappings, context_len)
below_acc:append(subject_term)
end
return terms.typed_term.range(
below_acc,
above_acc,
terms.typed_term.literal(terms.value.host_value(reln))
)
else
lookup = free:unwrap_metavariable()
end
else
error("substitute_inner NYI free with kind " .. free.kind)
end
local mapping = mappings[lookup]
if mapping then
return mapping
end
return typed_term.literal(val)
end
if nval:is_tuple_element_access_stuck() then
local subject, index = nval:unwrap_tuple_element_access_stuck()
local subject_term = substitute_inner(value.neutral(subject), mappings, context_len)
return typed_term.tuple_element_access(subject_term, index)
end
if nval:is_host_unwrap_stuck() then
local boxed = nval:unwrap_host_unwrap_stuck()
return typed_term.host_unwrap(substitute_inner(value.neutral(boxed), mappings, context_len))
end
if nval:is_host_wrap_stuck() then
local to_wrap = nval:unwrap_host_wrap_stuck()
return typed_term.host_wrap(substitute_inner(value.neutral(to_wrap), mappings, context_len))
end
if nval:is_host_unwrap_stuck() then
local to_unwrap = nval:unwrap_host_unwrap_stuck()
return typed_term.host_unwrap(substitute_inner(value.neutral(to_unwrap), mappings, context_len))
end
if nval:is_host_application_stuck() then
local fn, arg = nval:unwrap_host_application_stuck()
return typed_term.application(
typed_term.literal(value.host_value(fn)),
substitute_inner(value.neutral(arg), mappings, context_len)
)
end
if nval:is_host_tuple_stuck() then
local leading, stuck, trailing = nval:unwrap_host_tuple_stuck()
local elems = typed_array()
-- leading is an array of unwrapped host_values and must already be unwrapped host values
for _, elem in ipairs(leading) do
local elem_value = typed_term.literal(value.host_value(elem))
elems:append(elem_value)
end
elems:append(substitute_inner(value.neutral(stuck), mappings, context_len))
for _, elem in ipairs(trailing) do
elems:append(substitute_inner(elem, mappings, context_len))
end
-- print("host_tuple_stuck nval", nval)
local result = typed_term.host_tuple_cons(elems)
-- print("host_tuple_stuck result", result)
return result
end
if nval:is_host_if_stuck() then
local subject, consequent, alternate = nval:unwrap_host_if_stuck()
local subject = substitute_inner(value.neutral(subject), mappings, context_len)
local consequent = substitute_inner(consequent, mappings, context_len)
local alternate = substitute_inner(alternate, mappings, context_len)
return typed_term.host_if(subject, consequent, alternate)
end
if nval:is_application_stuck() then
local fn, arg = nval:unwrap_application_stuck()
return typed_term.application(
substitute_inner(value.neutral(fn), mappings, context_len),
substitute_inner(arg, mappings, context_len)
)
end
-- TODO: deconstruct nuetral value or something
error("substitute_inner not implemented yet val:is_neutral - " .. tostring(nval))
elseif val:is_host_value() then
return typed_term.literal(val)
elseif val:is_host_type_type() then
return typed_term.literal(val)
elseif val:is_host_number_type() then
return typed_term.literal(val)
elseif val:is_host_bool_type() then
return typed_term.literal(val)
elseif val:is_host_string_type() then
return typed_term.literal(val)
elseif val:is_host_function_type() then
local param_type, result_type, resinfo = val:unwrap_host_function_type()
local param_type = substitute_inner(param_type, mappings, context_len)
local result_type = substitute_inner(result_type, mappings, context_len)
local resinfo = substitute_inner(resinfo, mappings, context_len)
return typed_term.host_function_type(param_type, result_type, resinfo)
elseif val:is_host_wrapped_type() then
local type = val:unwrap_host_wrapped_type()
local type = substitute_inner(type, mappings, context_len)
return typed_term.host_wrapped_type(type)
elseif val:is_host_user_defined_type() then
local id, family_args = val:unwrap_host_user_defined_type()
local res = typed_array()
for _, v in ipairs(family_args) do
res:append(substitute_inner(v, mappings, context_len))
end
return typed_term.host_user_defined_type_cons(id, res)
elseif val:is_host_nil_type() then
return typed_term.literal(val)
elseif val:is_host_tuple_value() then
return typed_term.literal(val)
elseif val:is_host_tuple_type() then
local desc = val:unwrap_host_tuple_type()
local desc = substitute_inner(desc, mappings, context_len)
return typed_term.host_tuple_type(desc)
elseif val:is_range() then
local lower_bounds, upper_bounds, relation = val:unwrap_range()
local sub_lower_bounds = typed_array()
local sub_upper_bounds = typed_array()
for _, v in ipairs(lower_bounds) do
local sub = substitute_inner(v, mappings, context_len)
sub_lower_bounds:append(sub)
end
for _, v in ipairs(upper_bounds) do
local sub = substitute_inner(v, mappings, context_len)
sub_upper_bounds:append(sub)
end
local sub_relation = substitute_inner(relation, mappings, context_len)
return typed_term.range(sub_lower_bounds, sub_upper_bounds, sub_relation)
else
error("Unhandled value kind in substitute_inner: " .. val.kind)
end
end
--for substituting a single var at index
---@param val value
---@param index integer
---@param param_name string?
---@param typechecking_context TypecheckingContext
---@return value
local function substitute_type_variables(val, index, param_name, typechecking_context)
param_name = param_name and "#sub-" .. param_name or "#sub-param"
--print("value before substituting (val): (value term follows)")
--print(val)
local substituted = substitute_inner(val, {
[index] = typed_term.bound_variable(1),
}, 1)
--print("typed term after substitution (substituted): (typed term follows)")
--print(substituted:pretty_print(typechecking_context))
return value.closure(param_name, substituted, runtime_context())
end
---@param val value
---@return boolean
local function is_type_of_types(val)
return val:is_star() or val:is_prop() or val:is_host_type_type()
end
local make_inner_context
local infer_tuple_type, infer_tuple_type_unwrapped
local make_inner_context2
local infer_tuple_type2, infer_tuple_type_unwrapped2
local check_concrete
-- indexed by kind x kind
local concrete_comparers = {}
---@alias value_comparer fun(a: value, b: value): boolean, (string|ConcreteFail)?
---@param ka string
---@param kb string
---@param comparer value_comparer
local function add_comparer(ka, kb, comparer)
concrete_comparers[ka] = concrete_comparers[ka] or {}
concrete_comparers[ka][kb] = comparer
end
---@class ConcreteFail
local concrete_fail_mt = {
__tostring = function(self)
local message = self.message
if type(message) == "table" then
message = table.concat(message, "")
end
if self.cause then
return message .. " because:\n" .. tostring(self.cause)
end
return message
end,
}
local function concrete_fail(message, cause)
if not cause and type(message) == "string" then
if not message then
error "missing error message for concrete_fail"
end
return message
end
return setmetatable({
message = message,
cause = cause,
}, concrete_fail_mt)
end
---@type value_comparer
local function always_fits_comparer(a, b)
return true
end
-- host types
for _, host_type in ipairs({
value.host_number_type,
value.host_string_type,
value.host_bool_type,
value.host_user_defined_type({ name = "" }, value_array()),
}) do
add_comparer(host_type.kind, host_type.kind, always_fits_comparer)
end
-- types of types
add_comparer(value.host_type_type.kind, value.host_type_type.kind, always_fits_comparer)
---@type value_comparer
local function tuple_compare(a, b)
-- fixme lol
local placeholder = value.neutral(neutral_value.free(free.unique({})))
local tuple_types_a, tuple_types_b, tuple_vals, n = infer_tuple_type_unwrapped2(a, b, placeholder)
for i = 1, n do
local ta, tb = tuple_types_a[i], tuple_types_b[i]
if ta ~= tb then
if tb:is_neutral() then
typechecker_state:queue_subtype(ta, tb, "Nuetral value in tuple_compare")
else
typechecker_state:queue_subtype(ta, tb, "tuple_compare")
end
end
end
return true
end
add_comparer("value.tuple_type", "value.tuple_type", tuple_compare)
add_comparer("value.host_tuple_type", "value.host_tuple_type", tuple_compare)
add_comparer("value.pi", "value.pi", function(a, b)
if a == b then
return true
end
local a_param_type, a_param_info, a_result_type, a_result_info = a:unwrap_pi()
local b_param_type, b_param_info, b_result_type, b_result_info = b:unwrap_pi()
local avis = a_param_info:unwrap_param_info():unwrap_visibility()
local bvis = b_param_info:unwrap_param_info():unwrap_visibility()
if avis ~= bvis and not avis:is_implicit() then
return false, concrete_fail("pi param_info")
end
local apurity = a_result_info:unwrap_result_info():unwrap_result_info()
local bpurity = b_result_info:unwrap_result_info():unwrap_result_info()
if apurity ~= bpurity then
return false, concrete_fail("pi result_info")
end
typechecker_state:queue_subtype(b_param_type, a_param_type, "pi function parameters")
--local unique_placeholder = terms.value.neutral(terms.neutral_value.free(terms.free.unique({})))
--local a_res = apply_value(a_result_type, unique_placeholder)
--local b_res = apply_value(b_result_type, unique_placeholder)
--typechecker_state:queue_constrain(a_res, FunctionRelation(UniverseOmegaRelation), b_res, "pi function results")
typechecker_state:queue_constrain(
a_result_type,
FunctionRelation(UniverseOmegaRelation),
b_result_type,
"pi function results"
)
return true
end)
add_comparer("value.host_function_type", "value.host_function_type", function(a, b)
if a == b then
return true
end
local a_param_type, a_result_type, a_result_info = a:unwrap_host_function_type()
local b_param_type, b_result_type, b_result_info = b:unwrap_host_function_type()
local apurity = a_result_info:unwrap_result_info():unwrap_result_info()
local bpurity = b_result_info:unwrap_result_info():unwrap_result_info()
if apurity ~= bpurity then
return false, concrete_fail("host function result_info")
end
typechecker_state:queue_subtype(b_param_type, a_param_type, "host function parameters")
--local unique_placeholder = terms.value.neutral(terms.neutral_value.free(terms.free.unique({})))
--local a_res = apply_value(a_result_type, unique_placeholder)
--local b_res = apply_value(b_result_type, unique_placeholder)
--typechecker_state:queue_constrain(b_res, FunctionRelation(UniverseOmegaRelation), a_res, "host function parameters")
typechecker_state:queue_constrain(
a_result_type,
FunctionRelation(UniverseOmegaRelation),
b_result_type,
"host function results"
)
return true
end)
for _, type_of_type in ipairs({
value.host_type_type,
}) do
add_comparer(type_of_type.kind, value.star(0).kind, always_fits_comparer)
end
add_comparer(value.star(0).kind, value.star(0).kind, function(a, b)
local alevel = a:unwrap_star()
local blevel = b:unwrap_star()
if alevel > blevel then
print("star-comparer error:")
print("a:", alevel)
print("b:", blevel)
return false, "a.level > b.level"
end
return true
end)
add_comparer("value.host_wrapped_type", "value.host_wrapped_type", function(a, b)
local ua, ub = a:unwrap_host_wrapped_type(), b:unwrap_host_wrapped_type()
typechecker_state:queue_subtype(ua, ub)
--U.tag("check_concrete", { ua, ub }, check_concrete, ua, ub)
return true
end)
add_comparer("value.singleton", "value.singleton", function(a, b)
local a_supertype, a_value = a:unwrap_singleton()
local b_supertype, b_value = b:unwrap_singleton()
typechecker_state:queue_subtype(a_supertype, b_supertype, "singleton supertypes")
if a_value == b_value then
return true
else
return false, "unequal singletons"
end
end)
add_comparer("value.tuple_desc_type", "value.tuple_desc_type", function(a, b)
local a_universe = a:unwrap_tuple_desc_type()
local b_universe = b:unwrap_tuple_desc_type()
typechecker_state:queue_subtype(a_universe, b_universe, "tuple_desc_type universes")
return true
end)
add_comparer("value.program_type", "value.program_type", function(a, b)
local a_eff, a_base = a:unwrap_program_type()
local b_eff, b_base = b:unwrap_program_type()
typechecker_state:queue_subtype(a_base, b_base, "program result")
typechecker_state:queue_constrain(a_eff, effect_row_srel, b_eff, "program effects")
return true
end)
add_comparer("value.effect_row_type", "value.effect_row_type", function(a, b)
return true
end)
add_comparer("value.effect_type", "value.effect_type", function(a, b)
return true
end)
-- Compares any non-metavariables, or defers any metavariable comparisons to the work queue
---@param val value
---@param use value
---@return boolean
---@return string?
function check_concrete(val, use)
assert(val and use, "nil value or usage passed into check_concrete!")
if val:is_neutral() and use:is_neutral() then
if val == use then
return true
end
return false, "both values are neutral, but they aren't equal: " .. tostring(val) .. " ~= " .. tostring(use)
end
if val:is_singleton() and not use:is_singleton() then
local val_supertype, _ = val:unwrap_singleton()
typechecker_state:queue_subtype(val_supertype, use, "singleton subtype")
return true
end
if not concrete_comparers[val.kind] then
error("No valid concrete type comparer found for value " .. val.kind .. ": " .. tostring(val))
end
local comparer = (concrete_comparers[val.kind] or {})[use.kind]
if not comparer then
return false,
"no valid concerete comparer between value " .. val.kind .. " and usage " .. use.kind .. ": " .. tostring(
val
) .. " compared against " .. tostring(use)
end
return comparer(val, use)
end
---@param enum_val value
---@param closures ArrayValue
---@return ArrayValue
local function extract_tuple_elem_type_closures(enum_val, closures)
local constructor, arg = enum_val:unwrap_enum_value()
local elements = arg:unwrap_tuple_value()
if constructor == terms.DescCons.empty then
if #elements ~= 0 then
error "enum_value with constructor empty should have no args"
end
return closures
end
if constructor == terms.DescCons.cons then
if #elements ~= 2 then
error "enum_value with constructor cons should have two args"
end
extract_tuple_elem_type_closures(elements[1], closures)
if not elements[2]:is_closure() then
error "second elem in tuple_type enum_value should be closure"
end
closures:append(elements[2])
return closures
end
error "unknown enum constructor for value.tuple_type's enum_value, should not be reachable"
end
---@param checkable_term checkable
---@param typechecking_context TypecheckingContext
---@param goal_type value
---@return ArrayValue, typed
function check(
checkable_term, -- constructed from checkable_term
typechecking_context, -- todo
goal_type
) -- must be unify with goal type (there is some way we can assign metavariables to make them equal)
-- -> usage counts, a typed term
if terms.checkable_term.value_check(checkable_term) ~= true then
error("check, checkable_term: expected a checkable term")
end
if terms.typechecking_context_type.value_check(typechecking_context) ~= true then
error("check, typechecking_context: expected a typechecking context")
end
if terms.value.value_check(goal_type) ~= true then
print("goal_type", goal_type)
error("check, goal_type: expected a goal type (as an alicorn value)")
end
if checkable_term:is_inferrable() then
local inferrable_term = checkable_term:unwrap_inferrable()
local inferred_type, inferred_usages, typed_term = infer(inferrable_term, typechecking_context)
-- TODO: unify!!!!
if inferred_type ~= goal_type then
-- FIXME: needs context to avoid bugs where inferred and goal are the same neutral structurally
-- but come from different context thus are different
-- but erroneously compare equal
typechecker_state:flow(inferred_type, typechecking_context, goal_type, typechecking_context)
end
return inferred_usages, typed_term
elseif checkable_term:is_tuple_cons() then
local elements = checkable_term:unwrap_tuple_cons()
local usages = usage_array()
local new_elements = typed_array()
local desc = terms.empty
for _, v in ipairs(elements) do
local el_type_metavar = typechecker_state:metavariable(typechecking_context)
local el_type = el_type_metavar:as_value()
local el_usages, el_term = check(v, typechecking_context, el_type)
add_arrays(usages, el_usages)
new_elements:append(el_term)
local el_val = evaluate(el_term, typechecking_context.runtime_context)
desc = terms.cons(
desc,
value.closure(
"#check-tuple-cons-param",
typed_term.literal(value.singleton(el_type, el_val)),
typechecking_context.runtime_context
)
)
end
typechecker_state:flow(
value.tuple_type(desc),
typechecking_context,
goal_type,
typechecking_context,
"checkable_term:is_tuple_cons"
)
return usages, typed_term.tuple_cons(new_elements)
elseif checkable_term:is_host_tuple_cons() then
local elements = checkable_term:unwrap_host_tuple_cons()
local usages = usage_array()
local new_elements = typed_array()
local desc = terms.empty
for _, v in ipairs(elements) do
local el_type_metavar = typechecker_state:metavariable(typechecking_context)
local el_type = el_type_metavar:as_value()
local el_usages, el_term = check(v, typechecking_context, el_type)
add_arrays(usages, el_usages)
new_elements:append(el_term)
local el_val = evaluate(el_term, typechecking_context.runtime_context)
desc = terms.cons(
desc,
value.closure(
"#check-tuple-cons-param",
typed_term.literal(value.singleton(el_type, el_val)),
typechecking_context.runtime_context
)
)
end
typechecker_state:flow(
value.host_tuple_type(desc),
typechecking_context,
goal_type,
typechecking_context,
"checkable_term:is_host_tuple_cons"
)
return usages, typed_term.host_tuple_cons(new_elements)
elseif checkable_term:is_lambda() then
local param_name, body = checkable_term:unwrap_lambda()
-- assert that goal_type is a pi type
-- TODO open says work on other things first they will be easier
error("nyi")
else
error("check: unknown kind: " .. checkable_term.kind)
end
error("unreachable!?")
end
---apply an alicorn function to an alicorn value
---@param f value
---@param arg value
---@return value
function apply_value(f, arg)
if terms.value.value_check(f) ~= true then
error("apply_value, f: expected an alicorn value")
end
if terms.value.value_check(arg) ~= true then
error("apply_value, arg: expected an alicorn value")
end
if f:is_closure() then
local param_name, code, capture = f:unwrap_closure()
return U.notail(U.tag("evaluate", { code = code }, evaluate, code, capture:append(arg)))
elseif f:is_neutral() then
return value.neutral(neutral_value.application_stuck(f:unwrap_neutral(), arg))
elseif f:is_host_value() then
local host_func_impl = f:unwrap_host_value()
if host_func_impl == nil then
error "expected to get a function but found nil, did you forget to return the function from an intrinsic"
end
if arg:is_host_tuple_value() then
local arg_elements = arg:unwrap_host_tuple_value()
return value.host_tuple_value(host_array(host_func_impl(arg_elements:unpack())))
elseif arg:is_neutral() then
return value.neutral(neutral_value.host_application_stuck(host_func_impl, arg:unwrap_neutral()))
else
error("apply_value, is_host_value, arg: expected a host tuple argument")
end
else
error("apply_value, f: expected a function/closure")
end
error("unreachable!?")
end
---@param subject value
---@param index integer
---@return value
local function index_tuple_value(subject, index)
if terms.value.value_check(subject) ~= true then
error("index_tuple_value, subject: expected an alicorn value")
end
if subject:is_tuple_value() then
local elems = subject:unwrap_tuple_value()
return elems[index]
elseif subject:is_host_tuple_value() then
local elems = subject:unwrap_host_tuple_value()
return value.host_value(elems[index])
elseif subject:is_neutral() then
local inner = subject:unwrap_neutral()
if inner:is_host_tuple_stuck() then
local leading, stuck_elem, trailing = inner:unwrap_host_tuple_stuck()
if #leading >= index then
return terms.value.host_value(leading[index])
elseif #leading + 1 == index then
return terms.value.neutral(stuck_elem)
elseif #leading + 1 + #trailing >= index then
return trailing[index - #leading - 1]
else
error "tuple index out of bounds"
end
end
return value.neutral(neutral_value.tuple_element_access_stuck(inner, index))
end
error("Should be unreachable???")
end
---@param subject_type value
---@param subject_value value
---@return value
---@return fun(i: any) : value
local function make_tuple_prefix(subject_type, subject_value)
local desc, make_prefix
if subject_type:is_tuple_type() then
desc = subject_type:unwrap_tuple_type()
if subject_value:is_tuple_value() then
local subject_elements = subject_value:unwrap_tuple_value()
function make_prefix(i)
return value.tuple_value(subject_elements:copy(1, i))
end
elseif subject_value:is_neutral() then
local subject_neutral = subject_value:unwrap_neutral()
function make_prefix(i)
local prefix_elements = value_array()
for x = 1, i do
prefix_elements:append(value.neutral(neutral_value.tuple_element_access_stuck(subject_neutral, x)))
end
return value.tuple_value(prefix_elements)
end
else
error("make_tuple_prefix, is_tuple_type, subject_value: expected a tuple")
end
elseif subject_type:is_host_tuple_type() then
desc = subject_type:unwrap_host_tuple_type()
if subject_value:is_host_tuple_value() then
local subject_elements = subject_value:unwrap_host_tuple_value()
local subject_value_elements = value_array()
for _, v in ipairs(subject_elements) do
subject_value_elements:append(value.host_value(v))
end
function make_prefix(i)
return value.tuple_value(subject_value_elements:copy(1, i))
end
elseif subject_value:is_neutral() then
-- yes, literally a copy-paste of the neutral case above
local subject_neutral = subject_value:unwrap_neutral()
function make_prefix(i)
local prefix_elements = value_array()
for x = 1, i do
prefix_elements:append(value.neutral(neutral_value.tuple_element_access_stuck(subject_neutral, x)))
end
return value.tuple_value(prefix_elements)
end
else
error("make_tuple_prefix, is_host_tuple_type, subject_value: expected a host tuple")
end
else
print(subject_type:pretty_print())
error("make_tuple_prefix, subject_type: expected a term with a tuple type, but got " .. subject_type.kind)
end
return desc, make_prefix
end
-- TODO: create a typechecking context append variant that merges two
---@param desc value
---@param make_prefix fun(i: integer): value
---@return value[]
---@return integer
---@return value[]
function make_inner_context(desc, make_prefix)
-- evaluate the type of the tuple
local constructor, arg = desc:unwrap_enum_value()
if constructor == terms.DescCons.empty then
return value_array(), 0, value_array()
elseif constructor == terms.DescCons.cons then
local details = arg:unwrap_tuple_value()
local tupletypes, n_elements, tuplevals = make_inner_context(details[1], make_prefix)
local f = details[2]
local element_type
if #tupletypes == #tuplevals then
local prefix = value.tuple_value(tuplevals)
element_type = apply_value(f, prefix)
if element_type:is_singleton() then
local _, val = element_type:unwrap_singleton()
tuplevals:append(val)
end
else
local prefix = make_prefix(n_elements)
element_type = apply_value(f, prefix)
end
tupletypes:append(element_type)
return tupletypes, n_elements + 1, tuplevals
else
error("infer: unknown tuple type data constructor")
end
end
---@param subject_type value
---@param subject_value value
---@return value[]
---@return integer