/
Type.scala
1513 lines (1350 loc) · 47.4 KB
/
Type.scala
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
package org.bykn.bosatsu.rankn
import cats.data.NonEmptyList
import cats.parse.{Parser => P, Numbers}
import cats.{Applicative, Monad, Order}
import org.typelevel.paiges.{Doc, Document}
import org.bykn.bosatsu.{
Kind,
PackageName,
Lit,
TypeName,
Identifier,
Parser,
TypeParser
}
import org.bykn.bosatsu.graph.Memoize.memoizeDagHashedConcurrent
import scala.collection.immutable.{SortedSet, SortedMap}
import cats.implicits._
sealed abstract class Type {
def sameAs(that: Type): Boolean = Type.sameType(this, that)
def normalize: Type
}
object Type {
/** A type with no top level quantification
*/
sealed abstract class Rho extends Type {
override def normalize: Rho
}
object Rho {
implicit val orderRho: Order[Rho] =
new Order[Rho] {
def compare(a: Rho, b: Rho): Int =
(a, b) match {
case (TyConst(a), TyConst(b)) =>
Ordering[Const].compare(a, b)
case (TyConst(_), _) => -1
case (TyVar(v0), TyVar(v1)) =>
Ordering[Var].compare(v0, v1)
case (TyVar(_), TyConst(_)) => 1
case (TyVar(_), _) => -1
case (TyMeta(m0), TyMeta(m1)) =>
Meta.orderingMeta.compare(m0, m1)
case (TyMeta(_), TyApply(_, _)) => -1
case (TyMeta(_), _) => 1
case (TyApply(a0, b0), TyApply(a1, b1)) =>
val c = Type.typeOrder.compare(a0, a1)
if (c == 0) Type.typeOrder.compare(b0, b1) else c
case (TyApply(_, _), _) => 1
}
}
implicit val orderingRho: Ordering[Rho] = orderRho.toOrdering
}
sealed abstract class Leaf extends Rho {
override def normalize: Leaf = this
}
type Tau = Rho // no forall or exists anywhere
sealed abstract class Quantification {
def vars: NonEmptyList[(Var.Bound, Kind)]
def existList: List[(Var.Bound, Kind)]
def forallList: List[(Var.Bound, Kind)]
def concat(that: Quantification): Quantification
// Return this quantification, where the vars avoid otherVars
def unshadow(
otherVars: Set[Var.Bound]
): (Map[Var, TyVar], Quantification) = {
def unshadowNel(
nel: NonEmptyList[(Var.Bound, Kind)]
): (Map[Var, TyVar], NonEmptyList[(Var.Bound, Kind)]) = {
val remap: Map[Var, Var.Bound] = {
val collisions = nel.toList.filter { case (b, _) => otherVars(b) }
val nonCollisions = nel.iterator.filterNot { case (b, _) =>
otherVars(b)
}
val colMap =
alignBinders(collisions, otherVars ++ nonCollisions.map(_._1))
colMap.iterator.map { case ((b, _), b1) => (b, b1) }.toMap
}
val nel1 = nel.map { case bk @ (b, k) =>
remap.get(b) match {
case None => bk
case Some(b1) => (b1, k)
}
}
(remap.view.mapValues(TyVar(_)).toMap, nel1)
}
if (vars.exists { case (b, _) => otherVars(b) }) {
this match {
case Quantification.Dual(foralls, exists) =>
val (mfa, fa) = unshadowNel(foralls)
val (mex, ex) = unshadowNel(exists)
(mfa ++ mex, Quantification.Dual(fa, ex))
case Quantification.ForAll(forAll) =>
unshadowNel(forAll).map(Quantification.ForAll(_))
case Quantification.Exists(exists) =>
unshadowNel(exists).map(Quantification.Exists(_))
}
} else (Map.empty, this)
}
def filter(fn: Var.Bound => Boolean): Option[Quantification] =
Quantification.fromLists(
forallList.filter { case (b, _) => fn(b) },
existList.filter { case (b, _) => fn(b) }
)
def existsQuant(fn: ((Var.Bound, Kind)) => Boolean): Boolean
}
object Quantification {
case class ForAll(vars: NonEmptyList[(Var.Bound, Kind)])
extends Quantification {
def existList: List[(Var.Bound, Kind)] = Nil
def forallList: List[(Var.Bound, Kind)] = vars.toList
def concat(that: Quantification): Quantification =
that match {
case ForAll(vars1) => ForAll(vars ::: vars1)
case Exists(evars) => Dual(vars, evars)
case Dual(f, e) => Dual(vars ::: f, e)
}
def existsQuant(fn: ((Var.Bound, Kind)) => Boolean): Boolean =
vars.exists(fn)
}
case class Exists(vars: NonEmptyList[(Var.Bound, Kind)])
extends Quantification {
def existList: List[(Var.Bound, Kind)] = vars.toList
def forallList: List[(Var.Bound, Kind)] = Nil
def concat(that: Quantification): Quantification =
that match {
case ForAll(vars1) => Dual(vars1, vars)
case Exists(evars) => Exists(vars ::: evars)
case Dual(f, e) => Dual(f, vars ::: e)
}
def existsQuant(fn: ((Var.Bound, Kind)) => Boolean): Boolean =
vars.exists(fn)
}
case class Dual(
foralls: NonEmptyList[(Var.Bound, Kind)],
exists: NonEmptyList[(Var.Bound, Kind)]
) extends Quantification {
lazy val vars = foralls ::: exists
def existList: List[(Var.Bound, Kind)] = exists.toList
def forallList: List[(Var.Bound, Kind)] = foralls.toList
def concat(that: Quantification): Quantification =
that match {
case ForAll(vars1) => Dual(foralls ::: vars1, exists)
case Exists(evars) => Dual(foralls, exists ::: evars)
case Dual(f, e) => Dual(foralls ::: f, exists ::: e)
}
def existsQuant(fn: ((Var.Bound, Kind)) => Boolean): Boolean =
foralls.exists(fn) || exists.exists(fn)
}
implicit val quantificationOrder: Order[Quantification] =
new Order[Quantification] {
val nelist = Order[NonEmptyList[(Var.Bound, Kind)]]
def compare(a: Quantification, b: Quantification): Int =
(a, b) match {
case (ForAll(v0), ForAll(v1)) => nelist.compare(v0, v1)
case (ForAll(_), _) => -1
case (Exists(_), ForAll(_)) => 1
case (Exists(v0), Exists(v1)) => nelist.compare(v0, v1)
case (Exists(_), _) => -1
case (Dual(fa0, ex0), Dual(fa1, ex1)) =>
val c1 = nelist.compare(fa0, fa1)
if (c1 != 0) c1
else nelist.compare(ex0, ex1)
case (Dual(_, _), _) => 1
}
}
def fromLists(
forallList: List[(Var.Bound, Kind)],
existList: List[(Var.Bound, Kind)]
): Option[Quantification] =
forallList match {
case Nil =>
NonEmptyList.fromList(existList).map(Exists(_))
case head :: tail =>
Some(existList match {
case Nil => ForAll(NonEmptyList(head, tail))
case eh :: et =>
Dual(NonEmptyList(head, tail), NonEmptyList(eh, et))
})
}
}
case class Quantified(quant: Quantification, in: Rho) extends Type {
def vars: NonEmptyList[(Var.Bound, Kind)] = quant.vars
def existList: List[(Var.Bound, Kind)] = quant.existList
def forallList: List[(Var.Bound, Kind)] = quant.forallList
lazy val normalize: Type = Type.runNormalize(this)
}
object Quantified {
implicit val quantifiedOrder: Order[Quantified] =
new Order[Quantified] {
def compare(a: Quantified, b: Quantified): Int = {
val c = Order[Quantification].compare(a.quant, b.quant)
if (c == 0) Order[Rho].compare(a.in, b.in)
else c
}
}
}
case class TyApply(on: Rho, arg: Type) extends Rho {
lazy val normalize: Rho = TyApply(on.normalize, arg.normalize)
}
case class TyConst(tpe: Const) extends Leaf
case class TyVar(toVar: Var) extends Leaf
case class TyMeta(toMeta: Meta) extends Leaf
def sameType(left: Type, right: Type): Boolean =
left match {
case leftLeaf: Leaf =>
// a Leaf is never equal to TyApply
right match {
case rightLeaf: Leaf => leftLeaf == rightLeaf
case _: TyApply => false
case q: Quantified => leftLeaf == normalize(q)
}
case _: TyApply if right.isInstanceOf[Leaf] => false
case _ =>
// at least one is quantified or both are TyApply
normalize(left) == normalize(right)
}
implicit val typeOrder: Order[Type] =
new Order[Type] {
def compare(a: Type, b: Type): Int =
(a, b) match {
case (arho: Rho, brho: Rho) =>
Rho.orderRho.compare(arho, brho)
case (_: Rho, _) => -1
case (aq: Quantified, bq: Quantified) =>
Quantified.quantifiedOrder.compare(aq, bq)
case (_: Quantified, _) => 1
}
}
implicit val typeOrdering: Ordering[Type] = typeOrder.toOrdering
@annotation.tailrec
def applyAllRho(rho: Rho, args: List[Type]): Rho =
args match {
case Nil => rho
case a :: as => applyAllRho(TyApply(rho, a), as)
}
def apply1(fn: Type, arg: Type): Type =
fn match {
case rho: Rho => TyApply(rho, arg)
case q => applyAll(q, arg :: Nil)
}
def applyAll(fn: Type, args: List[Type]): Type =
fn match {
case rho: Rho => applyAllRho(rho, args)
case Quantified(q, rho) =>
val freeBound = freeBoundTyVars(fn :: args)
if (freeBound.isEmpty) {
Quantified(q, applyAllRho(rho, args))
} else {
val freeBoundSet: Set[Var.Bound] = freeBound.toSet
val collisions = q.existsQuant { case (b, _) => freeBoundSet(b) }
if (!collisions) {
// we don't need to rename the vars
Quantified(q, applyAllRho(rho, args))
} else {
// we have to to rename the collisions so the free set
// is unchanged
val fa1 = alignBinders(q.forallList, freeBoundSet)
val ex1 = alignBinders(q.existList, freeBoundSet ++ fa1.map(_._2))
val subMap = (fa1.iterator ++ ex1.iterator)
.map { case ((b0, _), b1) =>
(b0, TyVar(b1))
}
.toMap[Var, Rho]
val rho1 = substituteRhoVar(rho, subMap)
val q1 = Quantification
.fromLists(
forallList = fa1.map { case ((_, k), b) => (b, k) },
existList = ex1.map { case ((_, k), b) => (b, k) }
)
.get // this Option must be defined because we started with a defined q
Quantified(q1, applyAllRho(rho1, args))
}
}
}
def unapplyAll(fn: Type): (Type, List[Type]) = {
@annotation.tailrec
def loop(fn: Type, acc: List[Type]): (Type, List[Type]) =
fn match {
case TyApply(fn, a) => loop(fn, a :: acc)
case notApply => (notApply, acc)
}
loop(fn, Nil)
}
object ForAll {
def unapply(t: Type): Option[(NonEmptyList[(Type.Var.Bound, Kind)], Type)] =
t match {
case _: Rho => None
case q: Quantified =>
q.quant match {
case Quantification.ForAll(vars) => Some((vars, q.in))
case Quantification.Dual(foralls, existsNel) =>
Some((foralls, exists(existsNel, q.in)))
case _ => None
}
}
}
object Exists {
def unapply(t: Type): Option[(NonEmptyList[(Type.Var.Bound, Kind)], Type)] =
t match {
case _: Rho => None
case q: Quantified =>
q.quant match {
case Quantification.Exists(vars) => Some((vars, q.in))
case Quantification.Dual(foralls, existsNel) =>
Some((existsNel, forAll(foralls, q.in)))
case _ => None
}
}
}
def constantsOf(t: Type): List[Const] =
t match {
case Quantified(_, t) => constantsOf(t)
case TyApply(on, arg) => constantsOf(on) ::: constantsOf(arg)
case TyConst(c) => c :: Nil
case TyVar(_) | TyMeta(_) => Nil
}
def hasNoVars(t: Type): Boolean =
t match {
case TyConst(_) => true
case TyVar(_) | TyMeta(_) => false
case TyApply(on, arg) => hasNoVars(on) && hasNoVars(arg)
case q: Quantified => freeTyVars(q :: Nil).isEmpty
}
def hasNoUnboundVars(t: Type): Boolean = {
def loop(t: Type, bound: Set[Var.Bound]): Boolean =
t match {
case TyVar(b: Var.Bound) => bound(b)
case _: Leaf => true
case TyApply(on, arg) => loop(on, bound) && loop(arg, bound)
case q: Quantified =>
loop(q.in, bound ++ q.vars.iterator.map(_._1))
}
loop(t, Set.empty)
}
final def forAll(vars: List[(Var.Bound, Kind)], in: Type): Type =
NonEmptyList.fromList(vars) match {
case None => in
case Some(ne) => forAll(ne, in)
}
final def forAll(
vars: NonEmptyList[(Var.Bound, Kind)],
in: Type
): Type.Quantified =
in match {
case rho: Rho =>
Quantified(Quantification.ForAll(vars), rho)
case q: Quantified =>
q.quant match {
case Quantification.ForAll(ne1) =>
Quantified(Quantification.ForAll(vars ::: ne1), q.in)
case Quantification.Exists(ne1) =>
Quantified(Quantification.Dual(foralls = vars, exists = ne1), q.in)
case Quantification.Dual(fa0, e) =>
Quantified(
Quantification.Dual(foralls = vars ::: fa0, exists = e),
q.in
)
}
}
final def exists(
vars: NonEmptyList[(Var.Bound, Kind)],
in: Type
): Type.Quantified =
in match {
case rho: Rho =>
Quantified(Quantification.Exists(vars), rho)
case q: Quantified =>
q.quant match {
case Quantification.Exists(ne1) =>
Quantified(Quantification.Exists(vars ::: ne1), q.in)
case Quantification.ForAll(ne1) =>
Quantified(Quantification.Dual(foralls = ne1, exists = vars), q.in)
case Quantification.Dual(fa0, e) =>
Quantified(
Quantification.Dual(foralls = fa0, exists = vars ::: e),
q.in
)
}
}
final def exists(vars: List[(Var.Bound, Kind)], in: Type): Type =
vars match {
case h :: t => exists(NonEmptyList(h, t), in)
case Nil => in
}
final def quantify(
forallList: List[(Var.Bound, Kind)],
existList: List[(Var.Bound, Kind)],
in: Type
): Type =
Quantification.fromLists(
forallList = forallList,
existList = existList
) match {
case Some(q) => quantify(q, in)
case None => in
}
final def quantify(
quantification: Quantification,
tpe: Type
): Type.Quantified =
quantification match {
case Quantification.ForAll(vars) => forAll(vars, tpe)
case Quantification.Exists(vars) => exists(vars, tpe)
case Quantification.Dual(fa, ex) => forAll(fa, exists(ex, tpe))
}
def getTypeOf(lit: Lit): Type =
lit match {
case Lit.Integer(_) => Type.IntType
case Lit.Str(_) => Type.StrType
case Lit.Chr(_) => Type.CharType
}
/** types are var, meta, or const, or applied or forall on one of those. This
* returns the Type.TyConst found by recursing
*/
@annotation.tailrec
final def rootConst(t: Type): Option[Type.TyConst] =
t match {
case tyc @ TyConst(_) => Some(tyc)
case TyVar(_) | TyMeta(_) => None
case TyApply(left, _) => rootConst(left)
case q: Quantified => rootConst(q.in)
}
def allConsts(ts: List[Type]): List[TyConst] = {
@annotation.tailrec
def loop(ts: List[Type], acc: List[TyConst]): List[TyConst] =
ts match {
case (tyc @ TyConst(_)) :: tail =>
loop(tail, tyc :: acc)
case (TyVar(_) | TyMeta(_)) :: tail =>
loop(tail, acc)
case TyApply(left, right) :: tail =>
loop(left :: right :: tail, acc)
case (q: Quantified) :: tail =>
loop(q.in :: tail, acc)
case Nil =>
acc.reverse.distinct
}
loop(ts, Nil)
}
object RootConst {
def unapply(t: Type): Option[Type.TyConst] =
rootConst(t)
}
/** This form is often useful in Infer
*/
def substTy(
keys: NonEmptyList[Var],
vals: NonEmptyList[Type]
): Type => Type = {
val env = keys.iterator.zip(vals.iterator).toMap
{ t => substituteVar(t, env) }
}
def substituteVar(t: Type, env: Map[Type.Var, Type]): Type =
if (env.isEmpty) t
else
(t match {
case TyApply(on, arg) =>
apply1(substituteVar(on, env), substituteVar(arg, env))
case v @ TyVar(n) =>
env.get(n) match {
case Some(rho) => rho
case None => v
}
case m @ TyMeta(_) => m
case c @ TyConst(_) => c
case q: Quantified =>
val boundSet = q.vars.iterator.map(_._1).toSet[Type.Var]
val env1 = env.iterator.filter { case (v, _) => !boundSet(v) }.toMap
val subin = substituteVar(q.in, env1)
quantify(q.quant, subin)
})
def substituteRhoVar(t: Type.Rho, env: Map[Type.Var, Type.Rho]): Type.Rho =
t match {
case TyApply(on, arg) =>
TyApply(substituteRhoVar(on, env), substituteVar(arg, env))
case v @ TyVar(n) =>
env.get(n) match {
case Some(rho) => rho
case None => v
}
case m @ TyMeta(_) => m
case c @ TyConst(_) => c
}
/** Kind of the opposite of substitute: given a Map of vars, can we set those
* vars to some Type and get from to match to exactly
*/
def instantiate(
vars: Map[Var.Bound, Kind],
from: Type,
to: Type,
env: Map[Var.Bound, Kind]
): Option[
(
SortedMap[Var.Bound, (Kind, Var.Bound)],
SortedMap[Var.Bound, (Kind, Type)]
)
] = {
sealed abstract class BoundState
case object Unknown extends BoundState
case class Fixed(tpe: Type) extends BoundState
case class Free(rightName: Var.Bound) extends BoundState
case class State(
fixed: Map[Var.Bound, (Kind, BoundState)],
rightFrees: Map[Var.Bound, Kind]
) {
def get(b: Var.Bound): Option[(Kind, BoundState)] = fixed.get(b)
def updated(b: Var.Bound, kindBound: (Kind, BoundState)): State =
copy(fixed = fixed.updated(b, kindBound))
def --(keys: IterableOnce[Var.Bound]): State =
copy(fixed = fixed -- keys)
def ++(keys: IterableOnce[(Var.Bound, (Kind, BoundState))]): State =
copy(fixed = fixed ++ keys)
}
def loop(from: Type, to: Type, state: State): Option[State] =
from match {
case TyVar(b: Var.Bound) =>
state.get(b) match {
case Some((kind, opt)) =>
opt match {
case Unknown =>
to match {
case tv @ TyVar(toB: Var.Bound) =>
state.rightFrees.get(toB) match {
case Some(toBKind) =>
if (Kind.leftSubsumesRight(kind, toBKind)) {
Some(state.updated(b, (toBKind, Free(toB))))
} else None
case None =>
env.get(toB) match {
case Some(toBKind)
if (Kind.leftSubsumesRight(kind, toBKind)) =>
Some(state.updated(b, (toBKind, Fixed(tv))))
case _ => None
}
// don't set to vars to non-free bound variables
// this shouldn't happen in real inference
}
case _
if freeBoundTyVars(to :: Nil)
.filterNot(env.keySet)
.isEmpty =>
Some(state.updated(b, (kind, Fixed(to))))
case _ => None
}
case Fixed(set) =>
if (set.sameAs(to)) Some(state)
else None
case Free(rightName) =>
to match {
case TyVar(toB) if rightName == toB => Some(state)
case _ => None
}
}
case None =>
// not a variable, we can use, but also not the same as the right
None
}
case TyApply(a, b) =>
to match {
case TyApply(ta, tb) =>
loop(a, ta, state).flatMap { s1 =>
loop(b, tb, s1)
}
case ForAll(rightFrees, rightT) =>
// TODO handle shadowing
if (
rightFrees.exists { case (b, _) =>
state.rightFrees.contains(b)
}
) {
None
} else {
loop(
from,
rightT,
state.copy(rightFrees =
state.rightFrees ++ rightFrees.iterator
)
)
.map { s1 =>
s1.copy(rightFrees = state.rightFrees)
}
}
case _ => None
}
case ForAll(shadows, from1) =>
val noShadow = state -- shadows.iterator.map(_._1)
loop(from1, to, noShadow).map { s1 =>
s1 ++ shadows.iterator.flatMap { case (v, _) =>
state.get(v).map(v -> _)
}
}
case _ =>
// We can't use sameAt to compare Var.Bound since we know the variances
// there
if (from.sameAs(to)) Some(state)
else None
}
val initState = State(
vars.iterator.map { case (v, a) => (v, (a, Unknown)) }.toMap,
Map.empty
)
loop(from, to, initState)
.map { state =>
(
state.fixed.iterator
.collect {
case (t, (k, Free(t1))) => (t, (k, t1))
case (t, (k, Unknown)) => (t, (k, t))
}
.to(SortedMap),
state.fixed.iterator
.collect { case (t, (k, Fixed(f))) =>
(t, (k, f))
}
.to(SortedMap)
)
}
}
/** Return the Bound and Skolem variables that are free in the given list of
* types
*/
def freeTyVars(ts: List[Type]): List[Type.Var] = {
// usually we can recurse in a loop, but sometimes not
def cheat(
ts: List[Type],
bound: Set[Type.Var.Bound],
acc: List[Type.Var]
): List[Type.Var] =
go(ts, bound, acc)
@annotation.tailrec
def go(
ts: List[Type],
bound: Set[Type.Var.Bound],
acc: List[Type.Var]
): List[Type.Var] =
ts match {
case Nil => acc
case Type.TyVar(tv) :: rest =>
// we only check here, we don't add
val isBound =
tv match {
case b @ Type.Var.Bound(_) => bound(b)
case _: Type.Var.Skolem => false
}
if (isBound) go(rest, bound, acc)
else go(rest, bound, tv :: acc)
case Type.TyApply(a, b) :: rest => go(a :: b :: rest, bound, acc)
case (Type.TyMeta(_) | Type.TyConst(_)) :: rest => go(rest, bound, acc)
case (q: Quantified) :: rest =>
val acc1 =
cheat(q.in :: Nil, bound ++ q.vars.toList.iterator.map(_._1), acc)
// note, q.vars ARE NOT bound in rest
go(rest, bound, acc1)
}
go(ts, Set.empty, Nil).reverse.distinct
}
/** Return the Bound variables that are free in the given list of types
*/
def freeBoundTyVars(ts: List[Type]): List[Type.Var.Bound] =
freeTyVars(ts).collect { case b @ Type.Var.Bound(_) => b }
@inline final def normalize(tpe: Type): Type = tpe.normalize
private def runNormalize(tpe: Type): Type =
tpe match {
case q: Quantified =>
@inline def removeDups[A, B](lst: List[(A, B)]): List[(A, B)] = {
def loop(lst: List[(A, B)]): (List[(A, B)], Set[A]) =
lst match {
case (pair @ (b, _)) :: rest =>
val res @ (r1, back) = loop(rest)
if (back(b)) res
else {
val b1 = back + b
// if rest eq r1, then pair :: rest == lst
if (r1 eq rest) (lst, b1)
else (pair :: r1, b1)
}
case Nil => (Nil, Set.empty)
}
loop(lst)._1
}
val foralls = removeDups(q.forallList)
val exists = removeDups(q.existList)
val in = q.in
val inFree = freeBoundTyVars(in :: Nil)
// sort the quantification by the order of appearance
val order = inFree.iterator.zipWithIndex.toMap
val inFreeSet = inFree.toSet
val ex1 = exists
.filter { case (b, _) => inFreeSet(b) }
.sortBy { case (b, _) => order(b) }
val inFreeFa = inFreeSet -- ex1.iterator.map(_._1)
val fa1 = foralls
.filter { case (b, _) => inFreeFa(b) }
.sortBy { case (b, _) => order(b) }
val frees = inFreeFa -- fa1.iterator.map(_._1)
val bs = alignBinders(fa1 ::: ex1, frees)
if (bs.nonEmpty) {
val subMap =
bs.iterator
.map { case ((bold, _), bnew) =>
bold -> TyVar(bnew)
}
.toMap[Type.Var, Type.Rho]
val newVars = bs.map { case ((_, k), b) => (b, k) }
// subMap is nonEmpty, so this is a new type so runNormalize
val normin = runNormalize(substituteRhoVar(in, subMap))
val forAllSize = fa1.size
val (normfas, normexs) = newVars.splitAt(forAllSize)
quantify(forallList = normfas, existList = normexs, normin)
} else {
// there is nothing to substitute, so we have nothing
// to quantify
in.normalize
}
case ta @ TyApply(_, _) => ta.normalize
case _ => tpe
}
def kindOfOption(
cons: TyConst => Option[Kind]
): Type => Option[Kind] = {
val unknown: Either[Unit, Kind] = Left(())
val consE = (tc: TyConst) => cons(tc).fold(unknown)(Right(_))
val fn = kindOf[Unit](_ => (), _ => (), (_, _, _) => (), consE)
fn.andThen {
case Right(kind) => Some(kind)
case Left(_) => None
}
}
def kindOf[A](
unknownVar: Var.Bound => A,
invalidApply: TyApply => A,
kindSubsumeError: (TyApply, Kind.Cons, Kind) => A,
cons: TyConst => Either[A, Kind]
): Type => Either[A, Kind] = {
val fn = memoizeDagHashedConcurrent[(Type, Map[Var.Bound, Kind]), Either[
A,
Kind
]] { case ((tpe, locals), rec) =>
tpe match {
case Type.TyVar(b @ Type.Var.Bound(_)) =>
locals.get(b) match {
case Some(k) => Right(k)
// $COVERAGE-OFF$ this should be unreachable because all vars should have a known kind
case None => Left(unknownVar(b))
// $COVERAGE-ON$ this should be unreachable
}
case Type.TyVar(Type.Var.Skolem(_, kind, _, _)) => Right(kind)
case Type.TyMeta(Type.Meta(kind, _, _, _)) => Right(kind)
case tc @ Type.TyConst(_) => cons(tc)
case ap @ Type.TyApply(left, right) =>
rec((left, locals))
.product(rec((right, locals)))
.flatMap { case (leftKind, rhs) =>
Kind.validApply[A](leftKind, rhs, invalidApply(ap))(
kindSubsumeError(ap, _, rhs)
)
}
case q: Quantified =>
val varList = q.vars.toList
rec((q.in, locals ++ varList))
}
}
{ t => fn((t, Map.empty)) }
}
/** These are upper-case to leverage scala's pattern matching on upper-cased
* vals
*/
val BoolType: Type.TyConst = TyConst(Const.predef("Bool"))
val DictType: Type.TyConst = TyConst(Const.predef("Dict"))
object FnType {
final val MaxSize = 32
private def predefFn(n: Int) = TyConst(Const.predef(s"Fn$n"))
private val tpes = (1 to MaxSize).map(predefFn)
private val fnMap: Map[TyConst, (TyConst, Int)] =
(1 to MaxSize).iterator.map { idx =>
val tyconst = tpes(idx - 1)
tyconst -> (tyconst, idx)
}.toMap
object ValidArity {
def unapply(n: Int): Boolean =
(1 <= n) && (n <= MaxSize)
}
def apply(n: Int): Type.TyConst =
if (ValidArity.unapply(n)) tpes(n - 1)
else {
throw new IllegalArgumentException(
s"invalid FnType arity = $n, must be 0 < n <= $MaxSize"
)
}
def maybeFakeName(n: Int): Type.TyConst =
if (n <= MaxSize) apply(n)
else {
// This type doesn't exist but we will catch it in typechecking etc...
predefFn(n)
}
def unapply(tpe: Type): Option[(Type.TyConst, Int)] =
tpe match {
case tyConst @ Type.TyConst(_) => fnMap.get(tyConst)
case _ => None
}
// FnType -> Kind(Kind.Type.contra, Kind.Type.co),
val FnKinds: List[(Type.TyConst, Kind)] = {
// -* -> -* ... -> +* -> *
def kindSize(n: Int): Kind =
Kind((Vector.fill(n)(Kind.Type.contra) :+ Kind.Type.co): _*)
tpes.iterator.zipWithIndex.map { case (t, n1) =>
(t, kindSize(n1 + 1))
}.toList
}
}
val IntType: Type.TyConst = TyConst(Const.predef("Int"))
val ListType: Type.TyConst = TyConst(Const.predef("List"))
val OptionType: Type.TyConst = TyConst(Const.predef("Option"))
val StrType: Type.TyConst = TyConst(Const.predef("String"))
val CharType: Type.TyConst = TyConst(Const.predef("Char"))
val TestType: Type.TyConst = TyConst(Const.predef("Test"))
val UnitType: Type.TyConst = TyConst(Type.Const.predef("Unit"))
def const(pn: PackageName, name: TypeName): Type.Rho =
TyConst(Type.Const.Defined(pn, name))
object Fun {
def ifValid(from: NonEmptyList[Type], to: Type): Option[Type.Rho] = {
val len = from.length
if (len <= FnType.MaxSize)
Some(apply(from, to))
else None
}
def unapply(t: Type): Option[(NonEmptyList[Type], Type)] = {
def check(
n: Int,
t: Type,
applied: List[Type],
last: Type
): Option[(NonEmptyList[Type], Type)] =
t match {
case TyApply(inner, arg) =>
check(n + 1, inner, arg :: applied, last)
case FnType((_, arity)) if n == (arity + 1) =>
// we need arity types and 1 result type
// we know applied has length == n and arity in [1, MaxSize]
val args = NonEmptyList.fromListUnsafe(applied)
Some((args, last))
case _ => None
}
t match {
case TyApply(inner, last) =>
check(1, inner, Nil, last)
case _ => None
}
}
/** Match if a type is a simple universal function, which is to say forall
* a, b. C -> D where the result type is a Rho type.
*/
object SimpleUniversal {
def unapply(t: Type): Option[
(NonEmptyList[(Type.Var.Bound, Kind)], NonEmptyList[Type], Type)
] =
t match {
case ForAll(univ, Fun(args, resT)) =>
resT match {
case ForAll(univR, res) =>
// we need to relabel univR if it intersects univ
val firstSet = univ.iterator.map(_._1).toSet
val intersects = univR.filter { case (b, _) => firstSet(b) }
NonEmptyList.fromList(intersects) match {
case None =>
Some((univ ::: univR, args, res))
case Some(interNel) =>
val good = univR.collect {
case pair @ (b, _) if !firstSet(b) => pair
}
val avoid = firstSet ++ good.iterator.map(_._1)
val rename = alignBinders(interNel, avoid)
val subMap =
rename.iterator
.map { case ((oldB, _), newB) =>
(oldB, Type.TyVar(newB))
}
.toMap[Type.Var, Type.Rho]
val bounds = univ.concat(good) ::: rename.map {
case ((_, k), b) => (b, k)
}
val newRes = Type.substituteVar(res, subMap)
Some((bounds, args, newRes))
}
case res => Some((univ, args, res))
}
case _ => None
}
}
def apply(from: NonEmptyList[Type], to: Type): Type.Rho = {
val arityFn = FnType.maybeFakeName(from.length)
val withArgs = from.foldLeft(arityFn: Type.Rho)(TyApply(_, _))
TyApply(withArgs, to)
}
def apply(from: Type, to: Type): Type.Rho =
apply(NonEmptyList.one(from), to)