-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
subtype.clj
1615 lines (1442 loc) · 61 KB
/
subtype.clj
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
;; Copyright (c) Ambrose Bonnaire-Sergeant, Rich Hickey & contributors.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^:skip-wiki clojure.core.typed.checker.jvm.subtype
(:require [clojure.core.typed.current-impl :as impl]
[clojure.core.typed.checker.type-rep :as r]
[clojure.core.typed.checker.type-ctors :as c]
[clojure.core.typed.checker.utils :as u]
[clojure.core.typed.coerce-utils :as coerce]
[clojure.core.typed.errors :as err]
[clojure.core.typed.checker.jvm.parse-unparse :as prs]
[clojure.core.typed.checker.filter-rep :as fr]
[clojure.core.typed.checker.filter-ops :as fops]
[clojure.core.typed.checker.object-rep :as orep]
[clojure.core.typed.checker.frees :as frees]
[clojure.core.typed.checker.free-ops :as free-ops]
[clojure.core.typed.checker.datatype-ancestor-env :as ancest]
[clojure.core.typed.checker.path-rep :as pth-rep]
[clojure.core.typed.checker.indirect-ops :as ind]
[clojure.core.typed.checker.indirect-utils :as ind-u]
[clojure.core.typed.checker.jvm.assoc-utils :as assoc-u]
[clojure.set :as set])
(:import (clojure.lang ASeq)))
(defn ^:private gen-repeat [times repeated]
(reduce (fn [acc cur]
(concat acc cur))
[]
(repeat times repeated)))
;(defalias Seen Any)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Subtype
(defmacro handle-failure [& body]
`(u/handle-subtype-failure ~@body))
;[Type Type -> Nothing]
(defn fail! [s t]
(throw u/subtype-exn))
;keeps track of currently seen subtype relations for recursive types.
;(Set [Type Type])
(defonce ^:dynamic *sub-current-seen* #{})
(defn currently-subtyping? []
(boolean (seq *sub-current-seen*)))
(declare subtypes*-varargs subtype?)
;[(t/Seqable Type) (t/Seqable Type) Type -> Boolean]
(defn subtypes-varargs?
"True if argtys are under dom"
[argtys dom rst kws]
(handle-failure
(subtypes*-varargs #{} argtys dom rst kws)
true))
(defn subtypes-prest? [argtys dom prest]
"True if argtys are under dom and prest"
(let [dom-count (count dom)
[argtys-dom argtys-rest] (split-at dom-count argtys)]
(handle-failure
(subtypes*-varargs #{} argtys-dom dom nil nil)
(subtype? (r/-hvec (vec argtys-rest)) prest))))
;subtype and subtype? use *sub-current-seen* for remembering types (for Rec)
;subtypeA* takes an extra argument (the current-seen subtypes), called by subtype
;
; In short, only call subtype (or subtype?)
(declare subtype)
(defonce subtype-cache (atom {}))
; (ann reset-subtype-cache [-> nil])
(defn reset-subtype-cache []
(reset! subtype-cache {})
nil)
;[Type Type -> Boolean]
(defn subtype? [s t]
{:post [(boolean? %)]}
(letfn [(do-subtype []
(boolean
(handle-failure
(subtype s t))))]
(if-let [[_ res] (find @subtype-cache [s t])]
res
(let [res (do-subtype)]
(when-not (currently-subtyping?)
(swap! subtype-cache assoc [s t] res))
res))))
(declare subtypeA*)
;[(t/Set '[Type Type]) Type Type -> Boolean]
(defn subtypeA*? [A s t]
(handle-failure
(subtypeA* A s t)))
(declare supertype-of-one-arr)
;[(Map Symbol Bounds) (Map Symbol Bounds) (t/Seqable Type) (t/Seqable Type)
; -> Boolean]
(defn unify [X Y S T R]
(boolean
(u/handle-cs-gen-failure
(ind/infer X Y S T R))))
(declare protocol-extenders subtype-TypeFn-rands?
subtype-datatypes-or-records subtype-Result subtype-PrimitiveArray
subtype-CountRange subtype-TypeFn subtype-RClass
subtype-datatype-and-protocol subtype-rclass-protocol
boxed-primitives subtype-datatype-rclass subtype-TApp)
(defn subtype-HSet [s t]
{:pre [(r/HSet? s)
(r/HSet? t)]}
(if (and (= (:fixed s) (:fixed t))
(:complete? s)
(:complete? t))
*sub-current-seen*
(fail! s t)))
(defn simplify-In [t]
{:pre [(r/Intersection? t)]}
(let [mi (apply c/In (:types t))]
(if (r/Intersection? mi)
(:types mi)
[mi])))
;TODO replace hardcoding cases for unfolding Mu? etc. with a single case for unresolved types.
;[(t/Set '[Type Type]) Type Type -> (t/Set '[Type Type])]
(defn subtypeA* [A s t]
{:pre [(r/AnyType? s)
(r/AnyType? t)]
:post [(set? %)]}
;(prn "subtypeA*" s t)
(if (or (contains? A [s t])
(= s t)
; FIXME TypeFn's probably are not between Top/Bottom
(r/Top? t)
(r/Bottom? s)
;; Unchecked is both bottom and top
(r/Unchecked? s)
(r/Unchecked? t)
;TCError is top and bottom
(some r/TCError? [s t]))
A
(binding [*sub-current-seen* (conj A [s t])]
(cond
(or (r/TCResult? s)
(r/TCResult? t))
(assert nil "Cannot give TCResult to subtype")
; use bounds to determine subtyping between frees and types
; 2 frees of the same name are handled in the (= s t) case.
(and (r/F? s)
(let [{:keys [upper-bound lower-bound] :as bnd} (free-ops/free-with-name-bnds (:name s))]
(if-not bnd
(do #_(err/int-error (str "No bounds for " (:name s)))
nil)
(and (subtype? upper-bound t)
(subtype? lower-bound t)))))
*sub-current-seen*
(and (r/F? t)
(let [{:keys [upper-bound lower-bound] :as bnd} (free-ops/free-with-name-bnds (:name t))]
(if-not bnd
(do #_(err/int-error (str "No bounds for " (:name t)))
nil)
(and (subtype? s upper-bound)
(subtype? s lower-bound)))))
*sub-current-seen*
(r/TypeOf? s)
(subtypeA* *sub-current-seen* (c/resolve-TypeOf s) t)
(r/TypeOf? t)
(subtypeA* *sub-current-seen* s (c/resolve-TypeOf t))
(and (r/Value? s)
(r/Value? t))
;already (not= s t)
(fail! s t)
(and (r/Poly? s)
(r/Poly? t)
(= (:nbound s) (:nbound t)))
(let [;instantiate both sides with the same fresh variables
names (repeatedly (:nbound s) gensym)
bbnds1 (c/Poly-bbnds* names s)
bbnds2 (c/Poly-bbnds* names t)
b1 (c/Poly-body* names s)
b2 (c/Poly-body* names t)]
(if (and (= bbnds1 bbnds2)
(free-ops/with-bounded-frees (zipmap (map r/F-maker names) bbnds1)
(subtype? b1 b2)))
*sub-current-seen*
(fail! s t)))
;use unification to see if we can use the Poly type here
(and (r/Poly? s)
(let [names (c/Poly-fresh-symbols* s)
bnds (c/Poly-bbnds* names s)
b1 (c/Poly-body* names s)
;_ (prn "try unify on left")
u (unify (zipmap names bnds) {} [b1] [t] r/-any)]
;(prn "unified on left")
u))
*sub-current-seen*
(and (r/PolyDots? s)
(let [names (c/PolyDots-fresh-symbols* s)
bnds (c/PolyDots-bbnds* names s)
b1 (c/PolyDots-body* names s)
;_ (prn "try PolyDots unify on left")
u (unify (zipmap (butlast names) (butlast bnds)) {(last names) (last bnds)}
[b1] [t] r/-any)]
;(prn "unified on left" u)
u))
*sub-current-seen*
(and (r/Poly? t)
(let [names (c/Poly-fresh-symbols* t)
b (c/Poly-body* names t)]
(empty? (frees/fv t))))
(let [names (c/Poly-fresh-symbols* t)
b (c/Poly-body* names t)]
(if (subtype? s b)
*sub-current-seen*
(fail! s t)))
(r/Name? s)
(subtypeA* *sub-current-seen* (c/resolve-Name s) t)
(r/Name? t)
(subtypeA* *sub-current-seen* s (c/resolve-Name t))
(r/Mu? s)
(subtype (c/unfold s) t)
(r/Mu? t)
(subtype s (c/unfold t))
(r/App? s)
(subtypeA* *sub-current-seen* (c/resolve-App s) t)
(r/App? t)
(subtypeA* *sub-current-seen* s (c/resolve-App t))
(r/Bottom? t)
(fail! s t)
(and (r/TApp? s)
(r/TApp? t)
(= (c/fully-resolve-type (:rator s))
(c/fully-resolve-type (:rator t))))
(subtype-TApp s t)
(and (r/TApp? s)
(r/TypeFn? (c/fully-resolve-type (:rator s))))
(let [{:keys [rands]} s
rator (c/fully-resolve-type (:rator s))]
(cond
(r/F? rator) (fail! s t)
(r/TypeFn? rator)
(let [names (c/TypeFn-fresh-symbols* rator)
bbnds (c/TypeFn-bbnds* names rator)
res (c/instantiate-typefn rator rands :names names)]
(if (subtypeA*? (conj *sub-current-seen* [s t]) res t)
*sub-current-seen*
(fail! s t)))
:else (err/int-error (str "First argument to TApp must be TFn, actual: " (prs/unparse-type rator)))))
(and (r/TApp? t)
(r/TypeFn? (c/fully-resolve-type (:rator t))))
(let [{:keys [rands]} t
rator (c/fully-resolve-type (:rator t))]
(cond
(r/F? rator) (fail! s t)
(r/TypeFn? rator)
(let [names (c/TypeFn-fresh-symbols* rator)
res (c/instantiate-typefn rator rands :names names)]
(if (subtypeA*? (conj *sub-current-seen* [s t]) s res)
*sub-current-seen*
(fail! s t)))
:else (err/int-error (str "First argument to TApp must be TFn, actual: " (prs/unparse-type rator)))))
(r/Union? s)
;use subtypeA*, throws error
(if (every? (fn union-left [s] (subtypeA* *sub-current-seen* s t)) (:types s))
*sub-current-seen*
(fail! s t))
;use subtypeA*?, boolean result
(r/Union? t)
(if (some (fn union-right [t] (subtypeA*? *sub-current-seen* s t)) (:types t))
*sub-current-seen*
(fail! s t))
(and (r/FnIntersection? s)
(r/FnIntersection? t))
(loop [A* *sub-current-seen*
arr2 (:types t)]
(let [arr1 (:types s)]
(if (empty? arr2)
A*
(if-let [A (supertype-of-one-arr A* (first arr2) arr1)]
(recur A (next arr2))
(fail! s t)))))
;does it matter what order the Intersection cases are?
(r/Intersection? t)
(let [ts (simplify-In t)]
(if (every? #(subtype? s %) ts)
*sub-current-seen*
(fail! s t)))
(r/Intersection? s)
(let [ss (simplify-In s)]
(if (some #(subtype? % t) ss)
*sub-current-seen*
(fail! s t)))
(and (r/Extends? s)
(r/Extends? t))
(if (and ;all positive information matches.
; Each t should occur in at least one s.
(every? (fn extends-t [t*]
(some #(subtype? % t*) (:extends s)))
(:extends t))
;lhs does not explicitly implement any forbidden types.
; No negative t should be a supertype of a positive s
(not-any? (fn extends-not-t [not-t*]
(some #(subtype? % not-t*) (:extends s)))
(:without t))
;lhs explicitly disallows same types as rhs
; Each negative t should be a supertype of some negative s
(every? (fn extends-without-t [not-t*]
(some #(subtype? % not-t*) (:without s)))
(:without t)))
*sub-current-seen*
(fail! s t))
(r/Extends? s)
(if (and (some #(subtype? % t) (:extends s))
(not-any? #(subtype? % t) (:without s)))
*sub-current-seen*
(fail! s t))
(r/Extends? t)
(if (and (every? identity
(doall
(for [e (:extends t)]
(subtype? s e))))
(not-any? #(subtype? s %) (:without t)))
*sub-current-seen*
(fail! s t))
(and (r/TopFunction? t)
(r/FnIntersection? s))
*sub-current-seen*
; B <: A
;_______________________________
; (Not A) <: (Not B)
(every? r/NotType? [s t])
(if (subtype? (:type t) (:type s))
*sub-current-seen*
(fail! s t))
; A <!: B A is not free B is not free
;________________________________________
; A <: (Not B)
; Should this also require (fv s) U (fv t) to be empty?
(r/NotType? t)
(if (and (not-any? (some-fn r/B? r/F?) [s (:type t)])
(not (subtype? s (:type t))))
*sub-current-seen*
(fail! s t))
; delegate to NotType
(r/DifferenceType? s)
(subtype (apply c/In (:type s) (map r/NotType-maker (:without s)))
t)
(r/DifferenceType? t)
(subtype s
(apply c/In (:type t) (map r/NotType-maker (:without t))))
(and (r/GetType? s)
(not (r/F? (:target s))))
(subtype (c/-resolve s) t)
(and (r/GetType? t)
(not (r/F? (:target t))))
(subtype s (c/-resolve t))
(and (r/AssocType? s)
(r/RClass? t)
; (Map xx yy)
(= 'clojure.lang.IPersistentMap (:the-class t)))
(let [{:keys [target entries dentries]} s
{:keys [poly? the-class]} t
; _ (when-not (nil? dentries) (err/nyi-error (pr-str "NYI subtype of dentries AssocType " s)))
; we assume its all right
entries-keys (map first entries)
entries-vals (map second entries)]
(if (and (subtype? target t)
(every? identity (map subtype? entries-keys (repeat (first poly?))))
(every? identity (map subtype? entries-vals (repeat (second poly?)))))
*sub-current-seen*
(fail! s t)))
(and (r/AssocType? s)
(r/AssocType? t)
(r/F? (:target s))
(r/F? (:target t))
(not-any? :dentries [s t]))
(if (and (= (:target s) (:target t))
(subtype? (apply assoc-u/assoc-pairs-noret (c/-complete-hmap {}) (:entries s))
(apply assoc-u/assoc-pairs-noret (c/-complete-hmap {}) (:entries t))))
*sub-current-seen*
(fail! s t))
(and (r/AssocType? s)
(r/F? (:target s))
(not (r/AssocType? t)))
(let [bnds (free-ops/free-with-name-bnds (-> s :target :name))
_ (assert bnds
(str "Bounds not found for free variable: " (-> s :target :name)))]
(if (and (subtype? (:upper-bound bnds) t)
(subtype? (apply assoc-u/assoc-pairs-noret (c/-complete-hmap {}) (:entries s))
t))
*sub-current-seen*
(fail! s t)))
; avoids infinite expansion because associng an F is a fixed point
(and (r/AssocType? s)
(not (r/F? (:target s))))
(let [s-or-n (apply assoc-u/assoc-pairs-noret (:target s) (:entries s))]
(if (and s-or-n (subtype? s-or-n t))
*sub-current-seen*
(fail! s t)))
; avoids infinite expansion because associng an F is a fixed point
(and (r/AssocType? t)
(not (r/F? (:target t))))
(let [t-or-n (apply assoc-u/assoc-pairs-noret (:target t) (:entries t))]
(if (and t-or-n (subtype? s t-or-n))
*sub-current-seen*
(fail! s t)))
(and (r/HSequential? s)
(r/HSequential? t)
(r/compatible-HSequential-kind? (:kind s) (:kind t)))
(if (and (cond
; simple case, no rest, drest, repeat types
(and (not-any? :rest [s t])
(not-any? :drest [s t])
(not-any? :repeat [s t]))
(let []
(and (= (count (:types s))
(count (:types t)))
(every? identity (map subtype? (:types s) (:types t)))))
; repeat on left
(and (:repeat s)
(not (:drest t)))
(let [s-types (:types s)
t-types (:types t)
s-types-count (count s-types)
t-types-count (count t-types)]
(cond
(:rest t)
(and (= 1 s-types-count)
(every? identity (map subtype?
(repeat (first s-types))
t-types))
(subtype? (first s-types) (:rest t)))
; both s & t have :repeat
(:repeat t)
(if (and (<= t-types-count
s-types-count)
(zero? (rem s-types-count
t-types-count)))
(every? identity (map subtype?
s-types
(gen-repeat (/ (count s-types)
(count t-types)) t-types)))
false)
; nothing on right
:else
false))
; repeat on right
(and (:repeat t)
(not (:drest s)))
(let [s-types (:types s)
t-types (:types t)
s-types-count (count s-types)
t-types-count (count t-types)]
(if (:rest s)
(and (= 1 t-types-count)
(every? identity (map subtype?
s-types
(repeat (first t-types))))
(subtype? (:rest s) (first t-types)))
; nothing on left
(and (or (zero? s-types-count)
(<= t-types-count
s-types-count))
(if (zero? (rem s-types-count
t-types-count))
(every? identity (map subtype?
s-types
(gen-repeat (/ s-types-count
t-types-count) t-types)))
false))))
; rest on right
(and (:rest t)
(not ((some-fn :drest :repeat) s)))
(and (>= (count (:types s))
(count (:types t)))
(if (:rest s)
(subtype? (:rest s) (:rest t))
true)
;pad t to the right
(every? identity (map subtype?
(:types s)
(concat (:types t)
(repeat (- (count (:types s)) (count (:types t)))
(:rest t))))))
(and (:drest s)
(:rest t))
(and
(every? identity (map subtype?
(:types s)
(concat (:types t)
(repeat (- (count (:types s)) (count (:types t)))
(:rest t)))))
(r/Top? (:rest t)))
;TODO other cases
:else nil
)
; ignore interesting results
(every? (fn hvec1 [[f1 f2]] (or (= (fops/-FS fr/-top fr/-top) f2)
(= f1 f2)))
(map vector (:fs s) (:fs t)))
; ignore interesting results
(every? (fn hvec2 [[o1 o2]] (or (orep/EmptyObject? o2)
(= o1 o2)))
(map vector (:objects s) (:objects t))))
*sub-current-seen*
(fail! s t))
; repeat Heterogeneous* can always accept nil
(and (r/Nil? s)
(r/HSequential? t)
(:repeat t))
*sub-current-seen*
;every rtype entry must be in ltypes
;eg. {:a 1, :b 2, :c 3} <: {:a 1, :b 2}
(and (r/HeterogeneousMap? s)
(r/HeterogeneousMap? t))
(let [; convention: prefix things on left with l, right with r
{ltypes :types labsent :absent-keys :as s} s
{rtypes :types rabsent :absent-keys :as t} t]
(if (and ; if t is complete, s must be complete ..
(if (c/complete-hmap? t)
(if (c/complete-hmap? s)
; mandatory keys on the right must appear as
; mandatory on the left, but extra keys may appear
; on the left
(and (let [right-mkeys (set (keys rtypes))
left-mkeys (set (keys ltypes))]
(set/subset? right-mkeys
left-mkeys))
; extra mandatory keys on the left must appear
; as optional on the right
(let [left-extra-mkeys (set/difference (set (keys ltypes))
(set (keys rtypes)))
right-optional-keys (set (keys (:optional t)))]
(set/subset? left-extra-mkeys
right-optional-keys)))
;Note:
; optional key keys on t must be optional or mandatory or absent in s,
; which is always the case so we don't need to check.
false)
true)
; all absent keys in t should be absent in s
(every? identity
(for [rabsent-key rabsent]
; Subtyping is good if rabsent-key is:
; 1. Absent in s
; 2. Not present in s, but s is complete
(or ((set labsent) rabsent-key)
(when (c/complete-hmap? s)
(not ((set (keys ltypes)) rabsent-key))))))
; all present keys in t should be present in s
(every? identity
(map (fn [[k v]]
(when-let [t (get ltypes k)]
(subtype? t v)))
rtypes))
; all optional keys in t should match optional/mandatory entries in s
(every? identity
(map (fn [[k v]]
(let [matches-entry?
(if-let [actual-v
((merge-with c/In
(:types s)
(:optional s))
k)]
(subtype? actual-v v)
(c/complete-hmap? s))]
(cond
(c/partial-hmap? s)
(or (contains? (:absent-keys s) k)
matches-entry?)
:else matches-entry?)))
(:optional t)))
)
*sub-current-seen*
(fail! s t)))
(r/HeterogeneousMap? s)
(subtype (c/upcast-hmap s) t)
;; JSObj is covariant, taking after TypeScript & Google Closure. Obviously unsound.
(and (r/JSObj? s)
(r/JSObj? t))
(let [; convention: prefix things on left with l, right with r
{ltypes :types} s
{rtypes :types} t]
(if (every? (fn [[k rt]]
(let [lt (get ltypes k)]
(when lt
(subtype? lt rt))))
rtypes)
*sub-current-seen*
(fail! s t)))
(and (r/HSet? s)
(r/HSet? t))
(subtype-HSet s t)
(r/HSet? s)
(subtype (c/upcast-hset s) t)
(r/KwArgsSeq? s)
(let [ss (if (:complete? s)
(apply c/Un
(concat
(apply concat (:mandatory s))
(apply concat (:optional s))))
r/-any)
min-count (* 2 (count (:mandatory s)))
max-count (when (:complete? s)
(+ min-count
(* 2 (count (:optional s)))))]
(subtype (apply c/Un
(concat
(when (and (:nilable-non-empty? s)
(not (zero? min-count)))
[r/-nil])
[(c/In (r/make-CountRange
(max (if (:nilable-non-empty? s)
2
0)
min-count)
max-count)
(impl/impl-case
:clojure (c/RClass-of ASeq [ss])
:cljs (c/Protocol-of 'cljs.core/ISeq [ss])))]))
t))
; TODO add repeat support
(r/HSequential? s)
(subtype (c/upcast-HSequential s) t)
; The order of checking protocols and datatypes is subtle.
; It is easier to calculate the ancestors of a datatype than
; the descendants of a protocol, so Datatype <: Any comes
; before Protocol <: Any.
(and (r/Protocol? s)
(r/Protocol? t))
(let [{var1 :the-var variances* :variances poly1 :poly?} s
{var2 :the-var poly2 :poly?} t]
;(prn "protocols subtype" s t)
(if (and (= var1 var2)
(every? (fn prcol-variance [[v l r]]
(case v
:covariant (subtypeA* *sub-current-seen* l r)
:contravariant (subtypeA* *sub-current-seen* r l)
:invariant (and (subtypeA* *sub-current-seen* l r)
(subtypeA* *sub-current-seen* r l))))
(map vector variances* poly1 poly2)))
*sub-current-seen*
(fail! s t)))
(and (r/DataType? s)
(r/DataType? t))
(subtype-datatypes-or-records s t)
(and (r/DataType? s)
(r/Protocol? t))
(if (subtype-datatype-and-protocol s t)
*sub-current-seen*
(fail! s t))
(and (r/RClass? s)
(r/Protocol? t))
(subtype-rclass-protocol s t)
(and (r/Nil? s)
(r/Protocol? t)
(impl/checking-clojure?))
(if (contains? (c/Protocol-normal-extenders t) nil)
*sub-current-seen*
(fail! s t))
((some-fn r/JSNull? r/JSUndefined?) s)
(subtypeA* *sub-current-seen* r/-nil t)
;values are subtypes of their classes
(r/Value? s)
(let [sval (:val s)]
(impl/impl-case
:clojure (cond
; this is after the nil <: Protocol case, so we fail
(nil? sval) (fail! s t)
; this is a faster path than the final case
(r/RClass? t) (let [cls (let [cls (coerce/symbol->Class (:the-class t))]
(or (boxed-primitives cls)
cls))]
(cond
(#{Integer Long} cls) (if (or (instance? Integer sval)
(instance? Long sval))
*sub-current-seen*
(fail! s t))
;handle string-as-seqable
(string? sval) (if (subtype? (c/RClass-of String) t)
*sub-current-seen*
(fail! s t))
:else (if (instance? cls sval)
*sub-current-seen*
(fail! s t))))
:else (subtype (apply c/In (c/RClass-of (class sval))
(cond
;keyword values are functions
(keyword? sval) [(c/keyword->Fn sval)]
;strings have a known length as a seqable
(string? sval) [(r/make-ExactCountRange (count sval))]))
t))
:cljs (cond
(integer? sval) (subtype (r/CLJSInteger-maker) t)
(number? sval) (subtype (r/JSNumber-maker) t)
(string? sval) (subtype (r/JSString-maker) t)
(boolean? sval) (subtype (r/JSBoolean-maker) t)
(symbol? sval) (subtype (c/DataType-of 'cljs.core/Symbol) t)
(keyword? sval) (subtype (c/DataType-of 'cljs.core/Keyword) t)
:else (fail! s t))))
(and (r/Result? s)
(r/Result? t))
(subtype-Result s t)
(and (r/PrimitiveArray? s)
(r/PrimitiveArray? t))
(subtype-PrimitiveArray s t)
(r/PrimitiveArray? s)
(subtype (r/PrimitiveArray-maker Object r/-any r/-any) t)
(and (r/TypeFn? s)
(r/TypeFn? t))
(subtype-TypeFn s t)
(and (r/RClass? s)
(r/RClass? t))
(subtype-RClass s t)
(and (r/DataType? s)
(r/RClass? t))
(subtype-datatype-rclass s t)
; handles classes with FnIntersection ancestors
(and (r/RClass? s)
(r/FnIntersection? t))
(cond
; Var doesn't actually have an FnIntersection ancestor,
; but this case simulates it.
(#{'clojure.lang.Var} (:the-class s))
(let [[_ read-type :as poly] (:poly? s)
_ (when-not (#{2} (count (:poly? s)))
(err/int-error
(str "Assuming Var takes 2 arguments, "
"given " (count (:poly? s)))))]
(if (subtype? read-type t)
*sub-current-seen*
(fail! s t)))
:else (if (some #(when (r/FnIntersection? %)
(subtype? % t))
(map c/fully-resolve-type (c/RClass-supers* s)))
*sub-current-seen*
(fail! s t)))
; handles classes with heterogeneous vector ancestors (eg. IMapEntry)
(and (r/RClass? s)
(r/HSequential? t))
(if (some #(when (r/HSequential? %)
(subtype? % t))
(map c/fully-resolve-type (c/RClass-supers* s)))
*sub-current-seen*
(fail! s t))
; hack for FnIntersection <: clojure.lang.IFn
(when (r/FnIntersection? s)
(subtype? (c/RClass-of clojure.lang.IFn) t))
*sub-current-seen*
(and (r/CountRange? s)
(r/CountRange? t))
(subtype-CountRange s t)
; CLJS special types
(and (r/CLJSInteger? s)
(r/JSNumber? t))
*sub-current-seen*
(and (r/PolyDots? s)
(r/PolyDots? t)
(= (:nbound s) (:nbound t)))
(let [;instantiate both sides with the same fresh variables
names (repeatedly (:nbound s) gensym)
bbnds1 (c/PolyDots-bbnds* names s)
bbnds2 (c/PolyDots-bbnds* names t)
b1 (c/PolyDots-body* names s)
b2 (c/PolyDots-body* names t)]
(if (and (= bbnds1 bbnds2)
(free-ops/with-bounded-frees (zipmap (map r/F-maker names) bbnds1)
(subtype? b1 b2)))
*sub-current-seen*
(fail! s t)))
; TODO if s is (All [r x ...] [x ... x -> r]) and t is (All [r x] [x * -> r]) then we should say yes?
:else (fail! s t)))))
(let [analyze-qualified-symbol (delay (impl/dynaload 'clojure.core.typed.checker.jvm.analyze-cljs/analyze-qualified-symbol))]
(defn resolve-JS-reference [sym]
(impl/assert-cljs)
(cond
(= "js" (namespace sym)) (c/JSNominal-with-unknown-params sym)
:else (let [{{:keys [protocol-symbol name]} :info} (@analyze-qualified-symbol sym)]
(if protocol-symbol
(c/Protocol-with-unknown-params name)
(c/DataType-with-unknown-params name))))))
(let [cljs-extenders (delay (impl/dynaload 'clojure.core.typed.checker.jvm.analyze-cljs/extenders))]
(defn protocol-extenders [p]
{:pre [(r/Protocol? p)]
:post [(every? r/Type? %)]}
(impl/impl-case
:clojure (let [exts (c/Protocol-normal-extenders p)]
(for [ext exts]
(cond
(class? ext) (c/RClass-of-with-unknown-params ext)
(nil? ext) r/-nil
:else (throw (Exception. (str "What is this?" ext))))))
:cljs (let [exts (@cljs-extenders (:the-var p))]
(for [ext exts]
(cond
(symbol? ext) (resolve-JS-reference ext)
(nil? ext) r/-nil
:else (throw (Exception. (str "What is this?" ext)))))))))
;[Type Type -> (IPersistentSet '[Type Type])]
(defn- subtype [s t]
{:post [(set? %)]}
#_(prn "subtype")
; (if-let [hit (@subtype-cache (set [s t]))]
; (do #_(prn "subtype hit")
; hit)
(let [res (subtypeA* *sub-current-seen* s t)]
;(swap! subtype-cache assoc (set [s t]) res)
res))
;[(IPersistentSet '[Type Type]) (t/Seqable Type) (t/Seqable Type) (Option Type)
; -> (IPersistentSet '[Type Type])]
(defn subtypes*-varargs [A0 argtys dom rst kws]
{:pre [((some-fn nil? r/Type?) rst)
((some-fn nil? r/KwArgs?) kws)]}
(letfn [(all-mandatory-kws? [found-kws]
{:pre [(set? found-kws)]}
(empty? (set/difference (set (keys (:mandatory kws)))
found-kws)))]
(loop [dom dom
argtys argtys
A A0
found-kws #{}]
(cond
(and (empty? dom) (empty? argtys))
(if (all-mandatory-kws? found-kws)
A
(fail! argtys dom))
(empty? argtys) (fail! argtys dom)
(and (empty? dom) rst)
(if-let [A (subtypeA* A (first argtys) rst)]
(recur dom (next argtys) A found-kws)
(fail! (first argtys) rst))
(and (empty? dom) (<= 2 (count argtys)) kws)
(let [kw (c/fully-resolve-type (first argtys))
val (second argtys)
expected-val ((some-fn (:mandatory kws) (:optional kws))
kw)]
(if (and expected-val (subtype? val expected-val))
(recur dom (drop 2 argtys) A (conj found-kws kw))
(fail! (take 2 argtys) kws)))
(empty? dom) (fail! argtys dom)
:else
(if-let [A (subtypeA* A0 (first argtys) (first dom))]
(recur (next dom) (next argtys) A found-kws)
(fail! (first argtys) (first dom)))))))
;FIXME
(defn subtype-kwargs* [s t]
{:pre [((some-fn r/KwArgs? nil?) s)
((some-fn r/KwArgs? nil?) t)]}
(if (= s t)
*sub-current-seen*
(err/nyi-error "subtype kwargs")))
;; simple co/contra-variance for ->
;[(IPersistentSet '[Type Type]) Function Function -> (IPersistentSet '[Type Type])]
(defn arr-subtype [A0 s t]
{:pre [(r/Function? s)
(r/Function? t)]}
;; top for functions is above everything
(cond
;; top for functions is above everything
(r/TopFunction? t) A0
;; the really simple case
(and (not ((some-fn :rest :drest :kws :prest) s))
(not ((some-fn :rest :drest :kws :prest) t)))
(do
(when-not (= (count (:dom s))
(count (:dom t)))
(fail! s t))
(-> *sub-current-seen*
((fn [A0]
(reduce (fn [A* [s t]]
(subtypeA* A* s t))
A0
(map vector (:dom t) (:dom s)))))
(subtypeA* (:rng s) (:rng t))))
(and (:prest s)
(:prest t))
(if (and (= (count (:dom s))
(count (:dom t)))
(-> *sub-current-seen*
((fn [A0]
(reduce (fn [A* [s t]]
(subtypeA* A* s t))
A0
(map vector (:dom t) (:dom s)))))
(subtypeA* (:rng s) (:rng t)))
(subtype (:prest s) (:prest t)))
*sub-current-seen*
(fail! s t))
(and (:rest s)
(:prest t))