/
Infer.scala
2588 lines (2410 loc) · 91.1 KB
/
Infer.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.{Functor, Monad}
import cats.arrow.FunctionK
import cats.data.{Chain, NonEmptyChain, NonEmptyList}
import cats.syntax.all._
import org.bykn.bosatsu.{
Expr,
HasRegion,
Identifier,
Kind,
ListUtil,
PackageName,
ParallelViaProduct,
Pattern => GenPattern,
Region,
RecursionKind,
TypedExpr,
Variance
}
import scala.collection.immutable.SortedSet
import HasRegion.region
import Identifier.{Bindable, Constructor}
import scala.collection.immutable.SortedMap
sealed abstract class Infer[+A] {
import Infer.Error
def run(env: Infer.Env): RefSpace[Either[Error, A]]
final def flatMap[B](fn: A => Infer[B]): Infer[B] =
Infer.Impl.FlatMap(this, fn)
// Run but don't change any state
def peek: Infer[Either[Error, A]] =
Infer.Impl.Peek(this)
final def mapEither[B](fn: A => Either[Error, B]): Infer[B] =
Infer.Impl.MapEither(this, fn)
final def runVar(
v: Map[Infer.Name, Type],
tpes: Map[(PackageName, Constructor), Infer.Cons],
kinds: Map[Type.Const.Defined, Kind]
): RefSpace[Either[Error, A]] =
Infer.Env.init(v, tpes, kinds).flatMap(run(_))
final def runFully(
v: Map[Infer.Name, Type],
tpes: Map[(PackageName, Constructor), Infer.Cons],
kinds: Map[Type.Const.Defined, Kind]
): Either[Error, A] =
runVar(v, tpes, kinds).run.value
}
object Infer {
type Pattern = GenPattern[(PackageName, Constructor), Type]
// Import our private implementation functions
import Impl._
implicit val inferMonad: Monad[Infer] =
new Monad[Infer] {
def pure[A](a: A) = Infer.pure(a)
def flatMap[A, B](fa: Infer[A])(fn: A => Infer[B]): Infer[B] =
fa.flatMap(fn)
def tailRecM[A, B](a: A)(fn: A => Infer[Either[A, B]]): Infer[B] =
TailRecM(a, fn)
}
implicit val inferParallel: cats.Parallel[Infer] =
new ParallelViaProduct[Infer] {
def monad = inferMonad
def parallelProduct[A, B](fa: Infer[A], fb: Infer[B]): Infer[(A, B)] =
ParallelProduct(fa, fb)
}
/** The first element of the tuple are the the bound type vars for this type.
* the next are the types of the args of the constructor the final is the
* defined type this creates
*/
type Cons = (List[(Type.Var.Bound, Kind.Arg)], List[Type], Type.Const.Defined)
type Name = (Option[PackageName], Identifier)
class Env(
val uniq: Ref[Long],
val vars: Map[Name, Type],
val typeCons: Map[(PackageName, Constructor), Cons],
val variances: Map[Type.Const.Defined, Kind]
) {
def addVars(vt: NonEmptyList[(Name, Type)]): Env =
new Env(uniq, vars = (vars + vt.head) ++ vt.tail, typeCons, variances)
private[this] val kindCache: Type => Either[Region => Error, Kind] =
Type.kindOf[Region => Error](
b => { region =>
Error.UnknownKindOfVar(Type.TyVar(b), region, s"unbound var: $b")
},
ap => { region =>
Error.KindCannotTyApply(ap, region)
},
(ap, cons, rhs) => { region =>
Error.KindInvalidApply(ap, cons, rhs, region)
},
{ case Type.TyConst(const) =>
val d = const.toDefined
// some tests rely on syntax without importing
// TODO remove this
variances.get(d).orElse(Type.builtInKinds.get(d)) match {
case Some(ks) => Right(ks)
case None => Left({ region => Error.UnknownDefined(d, region) })
}
}
)
def getKindOpt(t: Type): Option[Kind] =
kindCache(t).toOption
def getKind(t: Type, region: Region): Either[Error, Kind] =
kindCache(t).leftMap { err =>
err(region)
}
}
object Env {
def init(
vars: Map[Name, Type],
tpes: Map[(PackageName, Constructor), Cons],
kinds: Map[Type.Const.Defined, Kind]
): RefSpace[Env] =
RefSpace.newRef(0L).map(new Env(_, vars, tpes, kinds))
}
def getEnv: Infer[Map[Name, Type]] = GetEnv.map(_.vars)
def lift[A](rs: RefSpace[A]): Infer[A] =
Lift(rs.map(Right(_)))
def fail(err: Error): Infer[Nothing] =
Lift(RefSpace.pure(Left(err)))
def pure[A](a: A): Infer[A] =
Lift(RefSpace.pure(Right(a)))
val unit: Infer[Unit] = pure(())
// Fails if v is not in the env
def lookupVarType(v: Name, reg: Region): Infer[Type] =
getEnv.flatMap { env =>
env.get(v) match {
case None => fail(Error.VarNotInScope(v, env, reg))
case Some(t) => pure(t)
}
}
sealed abstract class Error
object Error {
sealed abstract class Single extends Error
/** These are errors in the ability to type the code Generally these cannot
* be caught by other phases
*/
sealed abstract class TypeError extends Single
case class NotUnifiable(
left: Type,
right: Type,
leftRegion: Region,
rightRegion: Region
) extends TypeError
case class KindInvalidApply(
typeApply: Type.TyApply,
leftK: Kind.Cons,
rightK: Kind,
region: Region
) extends TypeError
case class KindMismatch(
target: Type,
targetKind: Kind,
source: Type,
sourceKind: Kind,
targetRegion: Region,
sourceRegion: Region
) extends TypeError
case class KindCannotTyApply(ap: Type.TyApply, region: Region)
extends TypeError
case class UnknownDefined(tpe: Type.Const.Defined, region: Region)
extends TypeError
case class NotPolymorphicEnough(
tpe: Type,
in: Expr[_],
badTvs: NonEmptyList[Type],
reg: Region
) extends TypeError
case class SubsumptionCheckFailure(
inferred: Type,
declared: Type,
infRegion: Region,
decRegion: Region,
badTvs: NonEmptyList[Type]
) extends TypeError
// this sounds internal but can be due to an infinite type attempted to be defined
case class UnexpectedMeta(
m: Type.Meta,
in: Type,
left: Region,
right: Region
) extends TypeError
case class ArityMismatch(
leftArity: Int,
leftRegion: Region,
rightArity: Int,
rightRegion: Region
) extends TypeError
case class ArityTooLarge(arity: Int, maxArity: Int, region: Region)
extends TypeError
/** These are errors that prevent typing due to unknown names, They could be
* caught in a phase that collects all the naming errors
*/
sealed abstract class NameError extends Single
// This could be a user error if we don't check scoping before typing
case class VarNotInScope(
varName: Name,
vars: Map[Name, Type],
region: Region
) extends NameError
// This could be a user error if we don't check scoping before typing
case class UnexpectedBound(
v: Type.Var.Bound,
in: Type,
rb: Region,
rt: Region
) extends NameError
case class UnknownConstructor(
name: (PackageName, Constructor),
region: Region,
env: Env
) extends NameError {
def knownConstructors: List[(PackageName, Constructor)] =
env.typeCons.keys.toList.sorted
}
case class UnionPatternBindMismatch(
pattern: Pattern,
names: NonEmptyList[List[Identifier.Bindable]],
region: Region
) extends NameError
/** These can only happen if the compiler has bugs at some point
*/
sealed abstract class InternalError extends Single {
def message: String
def region: Region
}
// This is a logic error which should never happen
case class InferIncomplete(term: Expr[_], region: Region)
extends InternalError {
// $COVERAGE-OFF$ we don't test these messages, maybe they should be removed
def message = s"inferRho not complete for $term"
// $COVERAGE-ON$ we don't test these messages, maybe they should be removed
}
case class ExpectedRho(tpe: Type, context: String, region: Region)
extends InternalError {
// $COVERAGE-OFF$ we don't test these messages, maybe they should be removed
def message = s"expected $tpe to be a Type.Rho, at $context"
// $COVERAGE-ON$ we don't test these messages, maybe they should be removed
}
case class UnknownKindOfVar(tpe: Type, region: Region, mess: String)
extends InternalError {
// $COVERAGE-OFF$ we don't test these messages, maybe they should be removed
def message = s"unknown var in $tpe: $mess at $region"
// $COVERAGE-ON$ we don't test these messages, maybe they should be removed
}
// here is when we have more than one error
case class Combine(left: Error, right: Error) extends Error {
private def flatten(
errs: NonEmptyList[Error],
inAcc: Set[Single],
acc: Chain[Single]
): NonEmptyChain[Single] =
errs match {
case NonEmptyList(s: Single, tail) =>
tail match {
case Nil =>
if (inAcc(s)) {
// we know s is in acc, so Chain must not be empty
NonEmptyChain.fromChainUnsafe(acc)
} else {
NonEmptyChain.fromChainAppend(acc, s)
}
case h :: t =>
if (inAcc(s)) {
flatten(NonEmptyList(h, t), inAcc, acc)
} else {
flatten(NonEmptyList(h, t), inAcc + s, acc :+ s)
}
}
case NonEmptyList(Combine(a, b), tail) =>
flatten(NonEmptyList(a, b :: tail), inAcc, acc)
}
lazy val flatten: NonEmptyChain[Single] =
flatten(NonEmptyList(left, right :: Nil), Set.empty, Chain.empty)
}
}
/** This is where the internal implementation goes. It is here to make it easy
* to make one block private and not do so on every little helper function
*/
private object Impl {
sealed abstract class Expected[A]
object Expected {
case class Inf[A](ref: Ref[Either[Error.InferIncomplete, A]])
extends Expected[A] {
def set(a: A): Infer[Unit] =
Infer.lift(ref.set(Right(a)))
}
case class Check[A](value: A) extends Expected[A]
}
case class FlatMap[A, B](fa: Infer[A], fn: A => Infer[B]) extends Infer[B] {
def run(env: Env) =
fa.run(env).flatMap {
case Right(a) => fn(a).run(env)
case left @ Left(_) => RefSpace.pure(left.rightCast)
}
}
case class ParallelProduct[A, B](fa: Infer[A], fb: Infer[B])
extends Infer[(A, B)] {
def run(env: Env) =
fa.run(env).flatMap {
case Right(a) =>
fb.run(env).map {
case Right(b) => Right((a, b))
case left @ Left(_) => left.rightCast
}
case left @ Left(errA) =>
fb.run(env).map {
case Right(_) => left.rightCast
case Left(errB) => Left(Error.Combine(errA, errB))
}
}
}
case class Peek[A](fa: Infer[A]) extends Infer[Either[Error, A]] {
def run(env: Env) =
fa.run(env).resetOnLeft(Left[Either[Error, A], Nothing](_)).map {
case Left(res) => Right(res)
// $COVERAGE-OFF$ this should be unreachable
case Right(unreach) => unreach
// $COVERAGE-ON$ this should be unreachable
}
}
case class MapEither[A, B](fa: Infer[A], fn: A => Either[Error, B])
extends Infer[B] {
def run(env: Env) =
fa.run(env).flatMap {
case Right(a) => RefSpace.pure(fn(a))
case left @ Left(_) => RefSpace.pure(left.rightCast)
}
}
// $COVERAGE-OFF$ needed for Monad, but not actually used
case class TailRecM[A, B](init: A, fn: A => Infer[Either[A, B]])
extends Infer[B] {
def run(env: Env) = {
// RefSpace uses Eval so this is fine, if not maybe the fastest thing ever
def loop(a: A): RefSpace[Either[Error, B]] =
fn(a).run(env).flatMap {
case Left(err) => RefSpace.pure(Left(err))
case Right(Left(a)) => loop(a)
case Right(Right(b)) => RefSpace.pure(Right(b))
}
loop(init)
}
}
// $COVERAGE-ON$
case object GetEnv extends Infer[Env] {
def run(env: Env): RefSpace[Either[Error, Env]] =
RefSpace.pure(Right(env))
}
def GetDataCons(fqn: (PackageName, Constructor), reg: Region): Infer[Cons] =
GetEnv.mapEither { env =>
env.typeCons.get(fqn) match {
case Some(res) => Right(res)
case None =>
Left(Error.UnknownConstructor(fqn, reg, env))
}
}
case class ExtendEnvs[A](vt: NonEmptyList[(Name, Type)], in: Infer[A])
extends Infer[A] {
def run(env: Env) = in.run(env.addVars(vt))
}
case class Lift[A](res: RefSpace[Either[Error, A]]) extends Infer[A] {
def run(env: Env) = res
}
val nextId: Infer[Long] =
GetEnv.flatMap { env =>
Lift(
for {
thisId <- env.uniq.get
_ <- env.uniq.set(thisId + 1L)
} yield Right(thisId)
)
}
def kindOf(t: Type, r: Region): Infer[Kind] =
GetEnv.mapEither { env =>
env.getKind(t, r)
}
private val checkedKinds: Infer[Type => Option[Kind]] = {
val emptyRegion = Region(0, 0)
GetEnv.map(env => tpe => env.getKind(tpe, emptyRegion).toOption)
}
// on t[a] we know t: k -> *, what is the variance
// in the arg a
def varianceOfCons(ta: Type.TyApply, region: Region): Infer[Variance] =
kindOf(ta.on, region)
.flatMap(varianceOfConsKind(ta, _, region))
def varianceOfConsKind(
ta: Type.TyApply,
k: Kind,
region: Region
): Infer[Variance] =
k match {
case Kind.Cons(Kind.Arg(v, _), _) => pure(v)
case Kind.Type =>
fail(Error.KindCannotTyApply(ta, region))
}
/** Skolemize on a function just recurses on the result type.
*
* Skolemize replaces ForAll parameters with skolem variables and then
* skolemizes recurses on the substituted value
*
* otherwise we return the type.
*
* The returned type is in weak-prenex form: all ForAlls have been floated
* up over covariant parameters
*
* see: https://www.csd.uwo.ca/~lkari/prenex.pdf It seems that if C[x] is
* covariant, then C[forall x. D[x]] == forall x. C[D[x]]
*
* this is always true for existential quantification I think, but for
* universal, we need that C is covariant which roughtly means C[x] either
* has x in a return position of a function, or not at all, which then
* gives us that (forall x. (A(x) u B(x))) == (forall x A(x)) u (forall x
* B(x)) where A(x) and B(x) represent the union branches of the type C
*/
private def skolemize(
t: Type,
region: Region
): Infer[(List[Type.Var.Skolem], List[Type.TyMeta], Type.Rho)] = {
// Invariant: if t is Rho, then result._3 is Rho
def loop(
t: Type,
path: Variance
): Infer[(List[Type.Var.Skolem], List[Type.TyMeta], Type)] =
t match {
case q: Type.Quantified =>
if (path == Variance.co) {
val univ = q.forallList
val exists = q.existList
val ty = q.in
// Rule PRPOLY
for {
sks1 <- univ.traverse { case (b, k) =>
newSkolemTyVar(b, k, existential = false)
}
ms <- exists.traverse { case (_, k) => newExistential(k) }
sksT = sks1.map(Type.TyVar(_))
ty1 = Type.substituteRhoVar(
ty,
(exists.map(_._1).iterator.zip(ms) ++
univ.map(_._1).iterator.zip(sksT.iterator)).toMap
)
(sks2, ms2, ty) <- loop(ty1, path)
} yield (sks1 ::: sks2, ms ::: ms2, ty)
} else pure((Nil, Nil, t))
case ta @ Type.TyApply(left, right) =>
// Rule PRFUN
// we know the kind of left is k -> x, and right has kind k
// since left: Rho, we know loop(left, path)._3 is Rho
(varianceOfCons(ta, region), loop(left, path))
.flatMapN { case (consVar, (sksl, el, ltpe0)) =>
// due to loop invariant
val ltpe: Type.Rho = ltpe0.asInstanceOf[Type.Rho]
val rightPath = consVar * path
loop(right, rightPath)
.map { case (sksr, er, rtpe) =>
(sksl ::: sksr, el ::: er, Type.TyApply(ltpe, rtpe))
}
}
case other: Type.Rho =>
// Rule PRMONO
pure((Nil, Nil, other))
}
loop(t, Variance.co).map {
case (skols, metas, rho: Type.Rho) =>
(skols, metas, rho)
// $COVERAGE-OFF$ this should be unreachable
// because we only return ForAll on paths nested inside noncovariant path in TyApply
case (sks, metas, notRho) =>
sys.error(s"type = $t, sks = $sks, metas = $metas notRho = $notRho")
// $COVERAGE-ON$ this should be unreachable
}
}
def getFreeTyVars(ts: List[Type]): Infer[Set[Type.Var]] =
ts.traverse(zonkType).map(Type.freeTyVars(_).toSet)
def getExistentialMetas(ts: List[Type]): Infer[Set[Type.Meta]] = {
val pureEmpty = pure(SortedSet.empty[Type.Meta])
def existentialsOf(tm: Type.Meta): Infer[Set[Type.Meta]] = {
val parents = readMeta(tm).flatMap {
case Some(Type.TyMeta(m2)) => existentialsOf(m2)
case _ => pureEmpty
}
if (tm.existential) parents.map(_ + tm)
else parents
}
for {
zonked <- ts.traverse(zonkType)
metas = Type.metaTvs(zonked)
metaSet <- metas.toList.traverse(existentialsOf)
} yield metaSet.foldLeft(Set.empty[Type.Meta])(_ | _)
}
val zonk: Type.Meta => Infer[Option[Type.Rho]] =
Type.zonk[Infer](SortedSet.empty, readMeta _, writeMeta _)
/** This fills in any meta vars that have been quantified and replaces them
* with what they point to
*/
def zonkType(t: Type): Infer[Type] =
Type.zonkMeta(t)(zonk)
def zonkTypedExpr[A](e: TypedExpr[A]): Infer[TypedExpr[A]] =
TypedExpr.zonkMeta(e)(zonk)
val zonkTypeExprK
: FunctionK[TypedExpr.Rho, Lambda[x => Infer[TypedExpr[x]]]] =
new FunctionK[TypedExpr.Rho, Lambda[x => Infer[TypedExpr[x]]]] {
def apply[A](fa: TypedExpr[A]): Infer[TypedExpr[A]] = zonkTypedExpr(fa)
}
def initRef[E: HasRegion, A](
t: Expr[E]
): Infer[Ref[Either[Error.InferIncomplete, A]]] =
lift(
RefSpace.newRef[Either[Error.InferIncomplete, A]](
Left(Error.InferIncomplete(t, region(t)))
)
)
def substTyRho(
keys: NonEmptyList[Type.Var],
vals: NonEmptyList[Type.Rho]
): Type.Rho => Type.Rho = {
val env = keys.toList.iterator.zip(vals.toList.iterator).toMap
{ t => Type.substituteRhoVar(t, env) }
}
def substTyExpr[A](
keys: NonEmptyList[Type.Var],
vals: NonEmptyList[Type.Rho],
expr: TypedExpr[A]
): TypedExpr[A] = {
val fn = Type.substTy(keys, vals)
expr.traverseType[cats.Id](fn)
}
/*
* This asserts that a given Type must be a Rho. We have some
* invariants we can't track with the type system, so we dynamically
* check those here
*
* An alternative to calling this method is instantiate, which assigns
* new meta variables for each bound variable in ForAll or skolemize
* which replaces the ForAll variables with skolem variables
*/
def assertRho(
t: Type,
context: => String,
region: Region
): Infer[Type.Rho] =
t match {
case r: Type.Rho => pure(r)
// $COVERAGE-OFF$ this should be unreachable
case _ => fail(Error.ExpectedRho(t, context, region))
// $COVERAGE-ON$ this should be unreachable
}
/*
* Return a Rho type (not a Forall), by assigning
* new meta variables for each of the outer ForAll variables
*/
def instantiate(t: Type): Infer[(List[Type.Var.Skolem], Type.Rho)] =
t match {
case q: Type.Quantified =>
// TODO: it may be possible to improve type checking
// by pushing foralls into covariant constructors
// but it's not trivial
val univs = q.forallList
val rho = q.in
val univRho =
NonEmptyList.fromList(univs) match {
case Some(vars) =>
vars
.traverse { case (_, k) => newMetaType(k) }
.map { vars1T =>
substTyRho(vars.map(_._1), vars1T)(rho)
}
case None => pure(rho)
}
univRho.flatMap { rho =>
val exists = q.existList
for {
skols <- exists.traverse { case (b, k) =>
newSkolemTyVar(b, k, existential = true)
}
env = exists.iterator
.map(_._1)
.zip(skols.iterator.map(Type.TyVar))
.toMap[Type.Var, Type.TyVar]
rho1 = Type.substituteRhoVar(rho, env)
} yield (skols, rho1)
}
case rho: Type.Rho => pure((Nil, rho))
}
/*
* Invariant: r2 needs to be in weak prenex form
*/
def subsCheckFn(
a1s: NonEmptyList[Type],
r1: Type,
a2s: NonEmptyList[Type],
r2: Type.Rho,
left: Region,
right: Region
): Infer[TypedExpr.Coerce] =
// note due to contravariance in input, we reverse the order there
for {
// we know that they have the same length because we have already called unifyFnRho
coarg <- a2s.zip(a1s).parTraverse { case (a2, a1) =>
subsCheck(a2, a1, right, left)
}
// r2 is already in weak-prenex form
cores <- subsCheckRho(r1, r2, left, right)
ks <- checkedKinds
} yield TypedExpr.coerceFn(a1s, r2, coarg, cores, ks)
/*
* If t <:< rho then coerce to rho
* invariant: second argument is in weak prenex form, which means that all
* the covariant positions have lifted the ForAlls out, e.g.
* forall a. a -> (forall b. b -> b)
* was rewritten to:
* forall a, b. a -> (b -> b)
*/
def subsCheckRho(
t: Type,
rho: Type.Rho,
left: Region,
right: Region
): Infer[TypedExpr.Coerce] =
(t, rho) match {
case (fa: Type.Quantified, rho) =>
subsInstantiate(fa, rho, left, right) match {
case Some(inf) => inf
case None =>
// Rule SPEC
for {
(exSkols, faRho) <- instantiate(fa)
unskol = unskolemizeExists(exSkols)
coerce <- subsCheckRho2(faRho, rho, left, right)
} yield coerce.andThen(unskol)
}
// for existential lower bounds, we skolemize the existentials
// then verify they don't escape after inference and unskolemize
// them (if they are free in the resulting type)
case (rhot: Type.Rho, rho) =>
subsCheckRho2(rhot, rho, left, right)
}
private val idCoerce = pure(FunctionK.id[TypedExpr])
// if t <:< rho, then coerce to rho
def subsCheckRho2(
t: Type.Rho,
rho: Type.Rho,
left: Region,
right: Region
): Infer[TypedExpr.Coerce] =
if (t == rho) idCoerce
else
(t, rho) match {
case (rho1, Type.Fun(a2, r2)) =>
// Rule FUN
for {
(a1, r1) <- unifyFnRho(a2.length, rho1, left, right)
// since rho is in weak prenex form, and Fun is covariant on r2, we know
// r2 is in weak-prenex form and a rho type
rhor2 <- assertRho(
r2,
s"subsCheckRho2($t, $rho, $left, $right), line 619",
right
)
coerce <- subsCheckFn(a1, r1, a2, rhor2, left, right)
} yield coerce
case (Type.Fun(a1, r1), rho2) =>
// Rule FUN
for {
(a2, r2) <- unifyFnRho(a1.length, rho2, right, left)
// since rho is in weak prenex form, and Fun is covariant on r2, we know
// r2 is in weak-prenex form
rhor2 <- assertRho(
r2,
s"subsCheckRho2($t, $rho, $left, $right), line 628",
right
)
coerce <- subsCheckFn(a1, r1, a2, rhor2, left, right)
} yield coerce
case (rho1, ta @ Type.TyApply(l2, r2)) =>
for {
(kl, kr) <- validateKinds(ta, right)
(l1, r1) <- unifyTyApp(rho1, kl, kr, left, right)
// Check from right to left
_ <- subsCheckRho2(l1, l2, left, right)
_ <- varianceOfConsKind(ta, kl, right).flatMap {
case Variance.Covariant =>
subsCheck(r1, r2, left, right)
case Variance.Contravariant =>
subsCheck(r2, r1, right, left)
case Variance.Phantom =>
// this doesn't matter
unit
case Variance.Invariant =>
unifyType(r1, r2, left, right)
}
ks <- checkedKinds
} yield TypedExpr.coerceRho(ta, ks)
case (ta @ Type.TyApply(l1, r1), rho2) =>
// here we know that rho2 != TyApply
for {
(kl, kr) <- validateKinds(ta, left)
// here we set the kinds of l2: kl and r2: k2
// so the kinds definitely match
(l2, r2) <- unifyTyApp(rho2, kl, kr, right, left)
// Check from right to left
_ <- subsCheckRho2(l1, l2, left, right)
// we know that l2 has kind kl
_ <- varianceOfConsKind(Type.TyApply(l2, r2), kl, right).flatMap {
case Variance.Covariant =>
subsCheck(r1, r2, left, right)
case Variance.Contravariant =>
subsCheck(r2, r1, right, left)
case Variance.Phantom =>
// this doesn't matter
unit
case Variance.Invariant =>
unifyType(r1, r2, left, right)
}
ks <- checkedKinds
} yield TypedExpr.coerceRho(rho2, ks)
case (t1, t2) =>
// rule: MONO
for {
_ <- unify(t1, t2, left, right)
ck <- checkedKinds
} yield TypedExpr.coerceRho(
t1,
ck
) // TODO this coerce seems right, since we have unified
}
/*
* Invariant: if the second argument is (Check rho) then rho is in weak prenex form
*/
def instSigma(
sigma: Type,
expect: Expected[(Type.Rho, Region)],
r: Region
): Infer[TypedExpr.Coerce] =
expect match {
case Expected.Check((t, tr)) =>
// note t is in weak-prenex form
subsCheckRho(sigma, t, r, tr)
case infer @ Expected.Inf(_) =>
for {
(exSkols, rho) <- instantiate(sigma)
_ <- infer.set((rho, r))
ks <- checkedKinds
coerce = TypedExpr.coerceRho(rho, ks)
} yield coerce.andThen(unskolemizeExists(exSkols))
}
def unifyFnRho(
arity: Int,
fnType: Type.Rho,
fnRegion: Region,
evidenceRegion: Region
): Infer[(NonEmptyList[Type], Type)] =
fnType match {
case Type.Fun(arg, res) =>
val fnArity = arg.length
if (fnArity == arity) pure((arg, res))
else
fail(Error.ArityMismatch(fnArity, fnRegion, arity, evidenceRegion))
case tau =>
if (Type.FnType.ValidArity.unapply(arity)) {
val sized = NonEmptyList.fromListUnsafe((1 to arity).toList)
for {
argT <- sized.traverse(_ => newMeta)
resT <- newMeta
_ <- unify(tau, Type.Fun(argT, resT), fnRegion, evidenceRegion)
} yield (argT, resT)
} else {
fail(
Error.ArityTooLarge(arity, Type.FnType.MaxSize, evidenceRegion)
)
}
}
def validateKinds(ta: Type.TyApply, region: Region): Infer[(Kind, Kind)] =
kindOf(ta.on, region)
.parProduct(kindOf(ta.arg, region))
.flatMap { case tup @ (lKind, rKind) =>
Kind.validApply[Error](
lKind,
rKind,
Error.KindCannotTyApply(ta, region)
) { cons =>
Error.KindInvalidApply(ta, cons, rKind, region)
} match {
case Right(_) => pure(tup)
case Left(err) => fail(err)
}
}
// destructure apType in left[right]
// invariant apType is being checked against some rho with validated kind: lKind[rKind]
def unifyTyApp(
apType: Type.Rho,
lKind: Kind,
rKind: Kind,
apRegion: Region,
evidenceRegion: Region
): Infer[(Type.Rho, Type)] =
apType match {
case ta @ Type.TyApply(left, right) =>
// this branch only happens when checking ta <:< (rho: lKind[rKind]) or >:> (rho)
// TODO: what validates that ta has compatible kinds with lKind and rKind
// since we could be doing subtyping or supertyping here we would need
// to pass in some directionality
validateKinds(ta, apRegion).as((left, right))
case notApply =>
for {
leftT <- newMetaType(lKind)
rightT <- newMetaType(rKind)
ap = Type.TyApply(leftT, rightT)
_ <- unify(notApply, ap, apRegion, evidenceRegion)
} yield (leftT, rightT)
}
// invariant the flexible type variable ty1 is not bound
def unifyUnboundVar(
ty1: Type.TyMeta,
ty2: Type.Tau,
left: Region,
right: Region
): Infer[Unit] =
ty2 match {
case meta2 @ Type.TyMeta(m2) =>
val m = ty1.toMeta
// we have to check that the kind matches before writing to a meta
if (m.kind == m2.kind) {
val cmp = Ordering[Type.Meta].compare(m, m2)
if (cmp == 0) unit
else
(readMeta(m2).flatMap {
case Some(ty2) =>
// we know that m2 is set, but m is not because ty1 is unbound
if (m.existential == m2.existential) {
// we unify here because ty2 could possibly be ty1
unify(ty1, ty2, left, right)
} else if (m.existential) {
// m2.existential == false
// we need to point m2 at m
writeMeta(m, ty2) *> writeMeta(m2, ty1)
} else {
// m.existential == false && m2.existential == true
// we need to point m at m2
writeMeta(m, meta2)
}
case None =>
// Both m and m2 are not set. We just point one at the other
// by convention point to the smaller item which
// definitely prevents cycles.
if (cmp > 0) writeMeta(m, meta2)
else {
// since we checked above we know that
// m.id != m2.id, so it is safe to write without
// creating a self-loop here
writeMeta(m2, ty1)
}
})
} else {
fail(
Error.KindMismatch(
ty1,
ty1.toMeta.kind,
meta2,
m2.kind,
left,
right
)
)
}
case nonMeta =>
// we have a non-meta, but inside of it (TyApply) we may have
// metas. Let's go ahead and zonk them now to minimize nesting
// metas inside metas.
zonkType(nonMeta)
.flatMap { nm2 =>
val m = ty1.toMeta
val tvs2 = Type.metaTvs(nm2 :: Nil)
if (tvs2(m)) fail(Error.UnexpectedMeta(m, nonMeta, left, right))
else {
kindOf(nonMeta, right)
.flatMap { nmk =>
if (Kind.leftSubsumesRight(m.kind, nmk)) {
// we have to check that the kind matches before writing to a meta
// TODO: this seems a bit fishy since we are unifying here.
// but maybe it is okay, since widening into an unknown meta
// variable seems like it should always be okay?
// I can't seem to find a way to exploit this to produce
// a forall a. a value.
writeMeta(m, nonMeta)
} else {
fail(
Error.KindMismatch(
ty1,
m.kind,
nonMeta,
nmk,
left,
right
)
)
}
}
}
}
}
def unifyVar(
tv: Type.TyMeta,
t: Type.Tau,
left: Region,
right: Region
): Infer[Unit] =
readMeta(tv.toMeta).flatMap {
case None => unifyUnboundVar(tv, t, left, right)
case Some(ty1) => unify(ty1, t, left, right)
}
def show(t: Type): String =
Type.fullyResolvedDocument.document(t).render(80)
def unify(t1: Type.Tau, t2: Type.Tau, r1: Region, r2: Region): Infer[Unit] =
(t1, t2) match {