Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve 1164 #1166

Merged
merged 5 commits into from Mar 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -327,6 +327,9 @@ object TypedExprNormalization {
}

f1 match {
// TODO: what if f1: Generic(_, AnnotatedLambda(_, _, _))
// we should still be able ton convert this to a let by
// instantiating to the right args
case AnnotatedLambda(lamArgs, expr, _) =>
// (y -> z)(x) = let y = x in z
val lets = lamArgs.zip(args).map { case ((n, ltpe), arg) =>
Expand Down
223 changes: 196 additions & 27 deletions core/src/main/scala/org/bykn/bosatsu/rankn/Infer.scala
Expand Up @@ -428,9 +428,7 @@ object Infer {

private val checkedKinds: Infer[Type => Option[Kind]] = {
val emptyRegion = Region(0, 0)
GetEnv.map { env =>
tpe => env.getKind(tpe, emptyRegion).toOption
}
GetEnv.map(env => tpe => env.getKind(tpe, emptyRegion).toOption)
}

// on t[a] we know t: k -> *, what is the variance
Expand Down Expand Up @@ -561,10 +559,10 @@ object Infer {
* with what they point to
*/
def zonkType(t: Type): Infer[Type] =
Type.zonkMeta(t)(zonk(_))
Type.zonkMeta(t)(zonk)

def zonkTypedExpr[A](e: TypedExpr[A]): Infer[TypedExpr[A]] =
TypedExpr.zonkMeta(e)(zonk(_))
TypedExpr.zonkMeta(e)(zonk)

val zonkTypeExprK
: FunctionK[TypedExpr.Rho, Lambda[x => Infer[TypedExpr[x]]]] =
Expand Down Expand Up @@ -1176,9 +1174,9 @@ object Infer {
left: Region,
right: Region
): Option[Infer[TypedExpr.Coerce]] =
inferred match {
(inferred match {
case Type.ForAll(vars, inT) =>
Type.instantiate(vars.iterator.toMap, inT, declared).map {
Type.instantiate(vars.iterator.toMap, inT, declared, Map.empty).map {
case (_, subs) =>
validateSubs(subs.toList, left, right)
.as {
Expand All @@ -1191,8 +1189,26 @@ object Infer {
}
}
}
case _ => None
}
case _ =>
None
}).orElse(declared match {
case Type.Exists(vars, inT) =>
Type.instantiate(vars.iterator.toMap, inT, inferred, Map.empty).map {
case (_, subs) =>
validateSubs(subs.toList, left, right)
.as {
new FunctionK[TypedExpr, TypedExpr] {
def apply[A](te: TypedExpr[A]): TypedExpr[A] =
// we apply the annotation here and let Normalization
// instantiate. We could explicitly have
// instantiation TypedExpr where you pass the variables to set
TypedExpr.Annotation(te, declared)
}
}
}
case _ =>
None
})
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should be able to match on any Quantification and instantiate it correctly. The existential and universal require instantiating two different directions to only one or the other is easy.

// note, this is identical to subsCheckRho when declared is a Rho type
def subsCheck(
inferred: Type,
Expand Down Expand Up @@ -1377,8 +1393,9 @@ object Infer {
if inT.length == args.length =>
// see if we can instantiate the result type
// if we can, we use that to fix the known parameters and continue
Type.instantiate(univ.iterator.toMap, outT, tpe).flatMap {
case (frees, inst) =>
Type
.instantiate(univ.iterator.toMap, outT, tpe, Map.empty)
.flatMap { case (frees, inst) =>
// if instantiate works, we know outT => tpe
if (inst.nonEmpty && frees.isEmpty) {
// we made some progress and there are no frees
Expand All @@ -1389,7 +1406,7 @@ object Infer {
// We learned nothing
None
}
}
}
case _ =>
None
}
Expand Down Expand Up @@ -1462,6 +1479,130 @@ object Infer {
}
}

// noshadow must include any free vars of args
def liftQuantification[A](
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should add direct tests of this in simple cases and possibly property checks. For instance, if there is a quantification on any arg, it should be lifted up. Or rather the result should not have quantification on any argument.

args: NonEmptyList[TypedExpr[A]],
noshadow: Set[Type.Var.Bound]
): (
Option[Type.Quantification],
NonEmptyList[TypedExpr[A]]
) = {

val htype = args.head.getType
val (oq, rest) = NonEmptyList.fromList(args.tail) match {
case Some(neTail) =>
val (oq, rest) = liftQuantification(neTail, noshadow)
(oq, rest.toList)
case None =>
(None, Nil)
}

htype match {
case Type.Quantified(q, rho) =>
oq match {
case Some(qtail) =>
// we have to unshadow with noshadow + all the vars in the tail
val (map, q1) =
q.unshadow(noshadow ++ qtail.vars.toList.iterator.map(_._1))
val rho1 = Type.substituteRhoVar(rho, map)
(
Some(q1.concat(qtail)),
NonEmptyList(TypedExpr.Annotation(args.head, rho1), rest)
)
case None =>
val (map, q1) = q.unshadow(noshadow)
val rho1 = Type.substituteRhoVar(rho, map)
(
Some(q1),
NonEmptyList(TypedExpr.Annotation(args.head, rho1), rest)
)
}

case _ =>
(oq, NonEmptyList(args.head, rest))
}
}

def applyViaInst[A: HasRegion](
fn: Expr[A],
args: NonEmptyList[Expr[A]],
tag: A
): Infer[Option[TypedExpr[A]]] =
(maybeSimple(fn), args.traverse(maybeSimple(_))).mapN {
(infFn, infArgs) =>
infFn.flatMap { fnTe =>
fnTe.getType match {
case Type.Fun.SimpleUniversal(us, argsT, resT)
if argsT.length == args.length =>
infArgs.sequence
.flatMap { argsTE =>
val argTypes = argsTE.map(_.getType)
// we can lift any quantification of the args
// outside of the function application
// We have to lift *before* substitution
val noshadows =
Type.freeBoundTyVars(resT :: argTypes.toList).toSet ++
us.iterator.map(_._1)
val (optQ, liftArgs) =
liftQuantification(argsTE, noshadows)

val liftArgTypes = liftArgs.map(_.getType)
Type.instantiate(
us.toList.toMap,
Type.Tuple(argsT.toList),
Type.Tuple(liftArgTypes.toList),
optQ.fold(Map.empty[Type.Var.Bound, Kind])(
_.vars.toList.toMap
)
) match {
case None =>
/*
println(s"can't instantiate: ${
Type.fullyResolvedDocument.document(fnTe.getType).render(80)
} to ${liftArgTypes.map(Type.fullyResolvedDocument.document(_).render(80))}")
*/
pureNone
case Some((frees, inst)) =>
if (frees.nonEmpty) {
// TODO maybe we could handle this, but not yet
// seems like if the free vars are set to the same
// variable, then we can just lift it into the
// quantification
/*
println(s"remaining frees in ${
Type.fullyResolvedDocument.document(fnTe.getType).render(80)
} to ${liftArgTypes.map(Type.fullyResolvedDocument.document(_).render(80))}: $frees")
*/
pureNone
} else {
val subMap =
inst.view.mapValues(_._2).toMap[Type.Var, Type]
val fnType0 = Type.Fun(liftArgTypes, resT)
val fnType1 = Type.substituteVar(fnType0, subMap)
val resType = Type.substituteVar(resT, subMap)

val resTe = TypedExpr.App(
TypedExpr.Annotation(fnTe, fnType1),
liftArgs,
resType,
tag
)

val maybeQuant = optQ match {
case Some(q) => TypedExpr.Generic(q, resTe)
case None => resTe
}

pure(Some(maybeQuant))
}
}
}
case _ =>
pureNone
}
}
}.flatSequence

def applyRhoExpect[A: HasRegion](
fn: Expr[A],
args: NonEmptyList[Expr[A]],
Expand Down Expand Up @@ -1518,20 +1659,44 @@ object Infer {
res <- zonkTypedExpr(TypedExpr.Global(pack, name, vSigma, tag))
} yield coerce(res)
case Annotation(App(fn, args, tag), resT, annTag) =>
(
checkApply(fn, args, tag, resT, region(annTag)),
instSigma(resT, expect, region(annTag))
)
.parFlatMapN { (typedTerm, coerce) =>
zonkTypedExpr(typedTerm).map(coerce(_))
applyViaInst(fn, args, tag)
.flatMap {
case Some(te) =>
for {
co1 <- subsCheck(
te.getType,
resT,
region(tag),
region(annTag)
)
co2 <- instSigma(resT, expect, region(annTag))
z <- zonkTypedExpr(te)
} yield co2(co1(z))
case None =>
(
checkApply(fn, args, tag, resT, region(annTag)),
instSigma(resT, expect, region(annTag))
)
.parFlatMapN { (typedTerm, coerce) =>
zonkTypedExpr(typedTerm).map(coerce(_))
}
}
case App(fn, args, tag) =>
expect match {
case Expected.Check((rho, reg)) =>
checkApply(fn, args, tag, rho, reg)
case inf =>
applyRhoExpect(fn, args, tag, inf)
}
applyViaInst(fn, args, tag)
.flatMap {
case Some(te) =>
for {
co <- instSigma(te.getType, expect, HasRegion.region(tag))
z <- zonkTypedExpr(te)
} yield co(z)
case None =>
expect match {
case Expected.Check((rho, reg)) =>
checkApply(fn, args, tag, rho, reg)
case inf @ Expected.Inf(_) =>
applyRhoExpect(fn, args, tag, inf)
}
}
case Generic(tpes, in) =>
for {
unSkol <- inferForAll(tpes, in)
Expand Down Expand Up @@ -1697,7 +1862,12 @@ object Infer {
simp.flatMap { te =>
te.getType match {
case Type.ForAll(fas, in) =>
Type.instantiate(fas.iterator.toMap, in, rho) match {
Type.instantiate(
fas.iterator.toMap,
in,
rho,
Map.empty
) match {
case Some((frees, subs)) if frees.isEmpty =>
// we know that substituting in gives rho
// check kinds
Expand Down Expand Up @@ -2249,8 +2419,7 @@ object Infer {

for {
_ <- init
rhoT <- inferRho(e)
(rho, expTyRho) = rhoT
(rho, expTyRho) <- inferRho(e)
q <- quantify(unifySelf(expTyRho), rho)
} yield q
}
Expand Down
62 changes: 58 additions & 4 deletions core/src/main/scala/org/bykn/bosatsu/rankn/Type.scala
Expand Up @@ -69,6 +69,46 @@ object Type {
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) },
Expand Down Expand Up @@ -503,7 +543,12 @@ object Type {
/** 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): Option[
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)]
Expand Down Expand Up @@ -540,17 +585,26 @@ object Type {
opt match {
case Unknown =>
to match {
case TyVar(toB: Var.Bound) =>
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 => 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 hasNoUnboundVars(to) =>
case _
if freeBoundTyVars(to :: Nil)
.filterNot(env.keySet)
.isEmpty =>
Some(state.updated(b, (kind, Fixed(to))))
case _ => None
}
Expand Down