Skip to content

Commit 5196efd

Browse files
committed
Change the implementation of context bound expansion for poly functions to reuse some of the existing context bound expansion
1 parent 64bd03e commit 5196efd

File tree

3 files changed

+68
-51
lines changed

3 files changed

+68
-51
lines changed

compiler/src/dotty/tools/dotc/ast/Desugar.scala

+23-35
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ object desugar {
5252
*/
5353
val ContextBoundParam: Property.Key[Unit] = Property.StickyKey()
5454

55+
/** An attachment key to indicate that a DefDef is a poly function apply
56+
* method definition.
57+
*/
58+
val PolyFunctionApply: Property.Key[Unit] = Property.StickyKey()
59+
5560
/** What static check should be applied to a Match? */
5661
enum MatchCheck {
5762
case None, Exhaustive, IrrefutablePatDef, IrrefutableGenFrom
@@ -337,7 +342,8 @@ object desugar {
337342
cpy.DefDef(meth)(
338343
name = normalizeName(meth, tpt).asTermName,
339344
paramss = paramssNoContextBounds),
340-
evidenceParamBuf.toList)
345+
evidenceParamBuf.toList
346+
)
341347
end elimContextBounds
342348

343349
def addDefaultGetters(meth: DefDef)(using Context): Tree =
@@ -508,7 +514,19 @@ object desugar {
508514
case Nil =>
509515
params :: Nil
510516

511-
cpy.DefDef(meth)(paramss = recur(meth.paramss))
517+
if meth.hasAttachment(PolyFunctionApply) then
518+
meth.removeAttachment(PolyFunctionApply)
519+
val paramTpts = params.map(_.tpt)
520+
val paramNames = params.map(_.name)
521+
val paramsErased = params.map(_.mods.flags.is(Erased))
522+
if ctx.mode.is(Mode.Type) then
523+
val ctxFunction = makeContextualFunction(paramTpts, paramNames, meth.tpt, paramsErased)
524+
cpy.DefDef(meth)(tpt = ctxFunction)
525+
else
526+
val ctxFunction = makeContextualFunction(paramTpts, paramNames, meth.rhs, paramsErased)
527+
cpy.DefDef(meth)(rhs = ctxFunction)
528+
else
529+
cpy.DefDef(meth)(paramss = recur(meth.paramss))
512530
end addEvidenceParams
513531

514532
/** The parameters generated from the contextual bounds of `meth`, as generated by `desugar.defDef` */
@@ -1221,38 +1239,6 @@ object desugar {
12211239
case _ => body
12221240
cpy.PolyFunction(tree)(tree.targs, stripped(tree.body)).asInstanceOf[PolyFunction]
12231241

1224-
/** Desugar [T_1 : B_1, ..., T_N : B_N] => (P_1, ..., P_M) => R
1225-
* Into [T_1, ..., T_N] => (P_1, ..., P_M) => (B_1, ..., B_N) ?=> R
1226-
*/
1227-
def expandPolyFunctionContextBounds(tree: PolyFunction)(using Context): PolyFunction =
1228-
val PolyFunction(tparams: List[untpd.TypeDef] @unchecked, fun @ Function(vparamTypes, res)) = tree: @unchecked
1229-
val newTParams = tparams.mapConserve {
1230-
case td @ TypeDef(name, cb @ ContextBounds(bounds, ctxBounds)) =>
1231-
cpy.TypeDef(td)(name, bounds)
1232-
case t => t
1233-
}
1234-
var idx = 0
1235-
val collectedContextBounds = tparams.collect {
1236-
case td @ TypeDef(name, cb @ ContextBounds(bounds, ctxBounds)) if ctxBounds.nonEmpty =>
1237-
name -> ctxBounds
1238-
}.flatMap { case (name, ctxBounds) =>
1239-
ctxBounds.map { ctxBound =>
1240-
val ContextBoundTypeTree(tycon, paramName, ownName) = ctxBound: @unchecked
1241-
if tree.isTerm then
1242-
ValDef(ownName, ctxBound, EmptyTree).withFlags(TermParam | Given)
1243-
else
1244-
ContextBoundTypeTree(tycon, paramName, EmptyTermName) // this has to be handled in Typer#typedFunctionType
1245-
}
1246-
}
1247-
val contextFunctionResult =
1248-
if collectedContextBounds.isEmpty then fun
1249-
else
1250-
val mods = EmptyModifiers.withFlags(Given)
1251-
val erasedParams = collectedContextBounds.map(_ => false)
1252-
Function(vparamTypes, FunctionWithMods(collectedContextBounds, res, mods, erasedParams)).withSpan(fun.span)
1253-
if collectedContextBounds.isEmpty then tree
1254-
else PolyFunction(newTParams, contextFunctionResult).withSpan(tree.span)
1255-
12561242
/** Desugar [T_1, ..., T_M] => (P_1, ..., P_N) => R
12571243
* Into scala.PolyFunction { def apply[T_1, ..., T_M](x$1: P_1, ..., x$N: P_N): R }
12581244
*/
@@ -1275,7 +1261,9 @@ object desugar {
12751261
}.toList
12761262

12771263
RefinedTypeTree(ref(defn.PolyFunctionType), List(
1278-
DefDef(nme.apply, tparams :: vparams :: Nil, res, EmptyTree).withFlags(Synthetic)
1264+
DefDef(nme.apply, tparams :: vparams :: Nil, res, EmptyTree)
1265+
.withFlags(Synthetic)
1266+
.withAttachment(PolyFunctionApply, ())
12791267
)).withSpan(tree.span)
12801268
end makePolyFunctionType
12811269

compiler/src/dotty/tools/dotc/typer/Typer.scala

+18-16
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ import annotation.tailrec
4040
import Implicits.*
4141
import util.Stats.record
4242
import config.Printers.{gadts, typr}
43-
import config.Feature, Feature.{migrateTo3, sourceVersion, warnOnMigration}
43+
import config.Feature, Feature.{migrateTo3, modularity, sourceVersion, warnOnMigration}
4444
import config.SourceVersion.*
4545
import rewrites.Rewrites, Rewrites.patch
4646
import staging.StagingLevel
@@ -53,6 +53,7 @@ import config.MigrationVersion
5353
import transform.CheckUnused.OriginalName
5454

5555
import scala.annotation.constructorOnly
56+
import dotty.tools.dotc.ast.desugar.PolyFunctionApply
5657

5758
object Typer {
5859

@@ -1145,7 +1146,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
11451146
if templ1.parents.isEmpty
11461147
&& isFullyDefined(pt, ForceDegree.flipBottom)
11471148
&& isSkolemFree(pt)
1148-
&& isEligible(pt.underlyingClassRef(refinementOK = Feature.enabled(Feature.modularity)))
1149+
&& isEligible(pt.underlyingClassRef(refinementOK = Feature.enabled(modularity)))
11491150
then
11501151
templ1 = cpy.Template(templ)(parents = untpd.TypeTree(pt) :: Nil)
11511152
for case parent: RefTree <- templ1.parents do
@@ -1720,11 +1721,11 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
17201721
typedFunctionType(desugar.makeFunctionWithValDefs(tree, pt), pt)
17211722
else
17221723
val funSym = defn.FunctionSymbol(numArgs, isContextual, isImpure)
1723-
val args1 = args.mapConserve {
1724-
case cb: untpd.ContextBoundTypeTree => typed(cb)
1725-
case t => t
1726-
}
1727-
val result = typed(cpy.AppliedTypeTree(tree)(untpd.TypeTree(funSym.typeRef), args1 :+ body), pt)
1724+
// val args1 = args.mapConserve {
1725+
// case cb: untpd.ContextBoundTypeTree => typed(cb)
1726+
// case t => t
1727+
// }
1728+
val result = typed(cpy.AppliedTypeTree(tree)(untpd.TypeTree(funSym.typeRef), args :+ body), pt)
17281729
// if there are any erased classes, we need to re-do the typecheck.
17291730
result match
17301731
case r: AppliedTypeTree if r.args.exists(_.tpe.isErasedClass) =>
@@ -1923,10 +1924,8 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
19231924

19241925
def typedPolyFunction(tree: untpd.PolyFunction, pt: Type)(using Context): Tree =
19251926
val tree1 = desugar.normalizePolyFunction(tree)
1926-
val tree2 = if Feature.enabled(Feature.modularity) then desugar.expandPolyFunctionContextBounds(tree1)
1927-
else tree1
1928-
if (ctx.mode is Mode.Type) typed(desugar.makePolyFunctionType(tree2), pt)
1929-
else typedPolyFunctionValue(tree2, pt)
1927+
if (ctx.mode is Mode.Type) typed(desugar.makePolyFunctionType(tree1), pt)
1928+
else typedPolyFunctionValue(tree1, pt)
19301929

19311930
def typedPolyFunctionValue(tree: untpd.PolyFunction, pt: Type)(using Context): Tree =
19321931
val untpd.PolyFunction(tparams: List[untpd.TypeDef] @unchecked, fun) = tree: @unchecked
@@ -1951,15 +1950,17 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
19511950
val resultTpt =
19521951
untpd.InLambdaTypeTree(isResult = true, (tsyms, vsyms) =>
19531952
mt.resultType.substParams(mt, vsyms.map(_.termRef)).substParams(poly, tsyms.map(_.typeRef)))
1954-
val desugared = desugar.makeClosure(tparams, inferredVParams, body, resultTpt, tree.span)
1953+
val desugared @ Block(List(defdef), _) = desugar.makeClosure(tparams, inferredVParams, body, resultTpt, tree.span)
1954+
defdef.putAttachment(PolyFunctionApply, ())
19551955
typed(desugared, pt)
19561956
else
19571957
val msg =
19581958
em"""|Provided polymorphic function value doesn't match the expected type $dpt.
19591959
|Expected type should be a polymorphic function with the same number of type and value parameters."""
19601960
errorTree(EmptyTree, msg, tree.srcPos)
19611961
case _ =>
1962-
val desugared = desugar.makeClosure(tparams, vparams, body, untpd.TypeTree(), tree.span)
1962+
val desugared @ Block(List(defdef), _) = desugar.makeClosure(tparams, vparams, body, untpd.TypeTree(), tree.span)
1963+
defdef.putAttachment(PolyFunctionApply, ())
19631964
typed(desugared, pt)
19641965
end typedPolyFunctionValue
19651966

@@ -2456,12 +2457,12 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
24562457
if tycon.tpe.typeParams.nonEmpty then
24572458
val tycon0 = tycon.withType(tycon.tpe.etaCollapse)
24582459
typed(untpd.AppliedTypeTree(spliced(tycon0), tparam :: Nil))
2459-
else if Feature.enabled(Feature.modularity) && tycon.tpe.member(tpnme.Self).symbol.isAbstractOrParamType then
2460+
else if Feature.enabled(modularity) && tycon.tpe.member(tpnme.Self).symbol.isAbstractOrParamType then
24602461
val tparamSplice = untpd.TypedSplice(typedExpr(tparam))
24612462
typed(untpd.RefinedTypeTree(spliced(tycon), List(untpd.TypeDef(tpnme.Self, tparamSplice))))
24622463
else
24632464
def selfNote =
2464-
if Feature.enabled(Feature.modularity) then
2465+
if Feature.enabled(modularity) then
24652466
" and\ndoes not have an abstract type member named `Self` either"
24662467
else ""
24672468
errorTree(tree,
@@ -3610,6 +3611,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
36103611

36113612
protected def makeContextualFunction(tree: untpd.Tree, pt: Type)(using Context): Tree = {
36123613
val defn.FunctionOf(formals, _, true) = pt.dropDependentRefinement: @unchecked
3614+
println(i"make contextual function $tree / $pt")
36133615
val paramNamesOrNil = pt match
36143616
case RefinedType(_, _, rinfo: MethodType) => rinfo.paramNames
36153617
case _ => Nil
@@ -4710,7 +4712,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
47104712
cpy.Ident(qual)(qual.symbol.name.sourceModuleName.toTypeName)
47114713
case _ =>
47124714
errorTree(tree, em"cannot convert from $tree to an instance creation expression")
4713-
val tycon = ctorResultType.underlyingClassRef(refinementOK = Feature.enabled(Feature.modularity))
4715+
val tycon = ctorResultType.underlyingClassRef(refinementOK = Feature.enabled(modularity))
47144716
typed(
47154717
untpd.Select(
47164718
untpd.New(untpd.TypedSplice(tpt.withType(tycon))),

tests/pos/contextbounds-for-poly-functions.scala

+27
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,18 @@ trait Ord[X]:
77
trait Show[X]:
88
def show(x: X): String
99

10+
val less0: [X: Ord] => (X, X) => Boolean = ???
11+
1012
val less1 = [X: Ord] => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
1113

14+
val less1_type_test: [X: Ord] => (X, X) => Boolean =
15+
[X: Ord] => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
16+
1217
val less2 = [X: Ord as ord] => (x: X, y: X) => ord.compare(x, y) < 0
1318

19+
val less2_type_test: [X: Ord as ord] => (X, X) => Boolean =
20+
[X: Ord as ord] => (x: X, y: X) => ord.compare(x, y) < 0
21+
1422
type CtxFunctionRef = Ord[Int] ?=> Boolean
1523
type ComparerRef = [X] => (x: X, y: X) => Ord[X] ?=> Boolean
1624
type Comparer = [X: Ord] => (x: X, y: X) => Boolean
@@ -20,12 +28,31 @@ val less3: Comparer = [X: Ord as ord] => (x: X, y: X) => ord.compare(x, y) < 0
2028
// type Comparer2 = [X: Ord] => Cmp[X]
2129
// val less4: Comparer2 = [X: Ord] => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
2230

31+
// type CmpWeak[X] = (x: X, y: X) => Boolean
32+
// type Comparer2Weak = [X: Ord] => (x: X) => CmpWeak[X]
33+
// val less4: Comparer2Weak = [X: Ord] => (x: X) => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
34+
2335
val less5 = [X: [X] =>> Ord[X]] => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
2436

37+
val less5_type_test: [X: [X] =>> Ord[X]] => (X, X) => Boolean =
38+
[X: [X] =>> Ord[X]] => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
39+
2540
val less6 = [X: {Ord, Show}] => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
2641

42+
val less6_type_test: [X: {Ord, Show}] => (X, X) => Boolean =
43+
[X: {Ord, Show}] => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
44+
2745
val less7 = [X: {Ord as ord, Show}] => (x: X, y: X) => ord.compare(x, y) < 0
2846

47+
val less7_type_test: [X: {Ord as ord, Show}] => (X, X) => Boolean =
48+
[X: {Ord as ord, Show}] => (x: X, y: X) => ord.compare(x, y) < 0
49+
2950
val less8 = [X: {Ord, Show as show}] => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
3051

52+
val less8_type_test: [X: {Ord, Show as show}] => (X, X) => Boolean =
53+
[X: {Ord, Show as show}] => (x: X, y: X) => summon[Ord[X]].compare(x, y) < 0
54+
3155
val less9 = [X: {Ord as ord, Show as show}] => (x: X, y: X) => ord.compare(x, y) < 0
56+
57+
val less9_type_test: [X: {Ord as ord, Show as show}] => (X, X) => Boolean =
58+
[X: {Ord as ord, Show as show}] => (x: X, y: X) => ord.compare(x, y) < 0

0 commit comments

Comments
 (0)