Skip to content

Decouple ImplicitFunctionN from FunctionN. #2008

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 9 additions & 20 deletions compiler/src/dotty/tools/dotc/core/Definitions.scala
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ class Definitions {
*
* ImplicitFunctionN traits follow this template:
*
* trait ImplicitFunctionN[T0,...,T{N-1}, R] extends Object with FunctionN[T0,...,T{N-1}, R] {
* trait ImplicitFunctionN[T0,...,T{N-1}, R] extends Object {
* def apply(implicit $x0: T0, ..., $x{N_1}: T{N-1}): R
* }
*/
Expand All @@ -113,27 +113,16 @@ class Definitions {
def complete(denot: SymDenotation)(implicit ctx: Context): Unit = {
val cls = denot.asClass.classSymbol
val decls = newScope
val arity = name.functionArity
val argParams =
for (i <- List.range(0, arity)) yield
enterTypeParam(cls, name ++ "$T" ++ i.toString, Contravariant, decls)
val resParam = enterTypeParam(cls, name ++ "$R", Covariant, decls)
val (methodType, parentTraits) =
if (name.startsWith(tpnme.ImplicitFunction)) {
val superTrait =
FunctionType(arity).appliedTo(argParams.map(_.typeRef) ::: resParam.typeRef :: Nil)
(ImplicitMethodType, ctx.normalizeToClassRefs(superTrait :: Nil, cls, decls))
}
else (MethodType, Nil)
val applyMeth =
decls.enter(
newMethod(cls, nme.apply,
methodType(argParams.map(_.typeRef), resParam.typeRef), Deferred))
denot.info =
ClassInfo(ScalaPackageClass.thisType, cls, ObjectType :: parentTraits, decls)
for (i <- List.range(0, name.functionArity)) yield
enterTypeParam(cls, name ++ "$T" ++ i.toString, Contravariant, decls).typeRef
val resParam = enterTypeParam(cls, name ++ "$R", Covariant, decls).typeRef
val methodType = if (name.isImplicitFunction) ImplicitMethodType else MethodType
decls.enter(newMethod(cls, nme.apply, methodType(argParams, resParam), Deferred))
denot.info = ClassInfo(ScalaPackageClass.thisType, cls, ObjectType :: Nil, decls)
}
}
newClassSymbol(ScalaPackageClass, name, Trait | NoInits, completer)
newClassSymbol(ScalaPackageClass, name, NoInitsTrait, completer)
}

private def newMethod(cls: ClassSymbol, name: TermName, info: Type, flags: FlagSet = EmptyFlags): TermSymbol =
Expand Down Expand Up @@ -822,7 +811,7 @@ class Definitions {
* trait gets screwed up. Therefore, it is mandatory that FunctionXXL
* is treated as a NoInit trait.
*/
lazy val NoInitClasses = PhantomClasses + FunctionXXLClass
def isNoInitClass(cls: Symbol) = PhantomClasses.contains(cls) || (cls eq FunctionXXLClass) || isFunctionClass(cls)

def isPolymorphicAfterErasure(sym: Symbol) =
(sym eq Any_isInstanceOf) || (sym eq Any_asInstanceOf)
Expand Down
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/transform/Mixin.scala
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ class Mixin extends MiniPhaseTransform with SymTransformer { thisTransform =>
case Some(call) =>
if (defn.PhantomClasses.contains(baseCls)) Nil else call :: Nil
case None =>
if (baseCls.is(NoInitsTrait) || defn.NoInitClasses.contains(baseCls)) Nil
if (baseCls.is(NoInitsTrait) || defn.isNoInitClass(baseCls)) Nil
else {
//println(i"synth super call ${baseCls.primaryConstructor}: ${baseCls.primaryConstructor.info}")
transformFollowingDeep(superRef(baseCls.primaryConstructor).appliedToNone) :: Nil
Expand Down
35 changes: 22 additions & 13 deletions compiler/src/dotty/tools/dotc/typer/Typer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2003,20 +2003,29 @@ class Typer extends Namer with TypeAssigner with Applications with Implicits wit
// local adaptation makes sure every adapted tree conforms to its pt
// so will take the code path that decides on inlining
return tpd.Block(adapt(tree, WildcardType) :: Nil, Literal(Constant(())))
// convert function literal to SAM closure
tree match {
case Closure(Nil, id @ Ident(nme.ANON_FUN), _)
if defn.isFunctionType(wtp) && !defn.isFunctionType(pt) =>
pt match {
case SAMType(meth)
if wtp <:< meth.info.toFunctionType() =>
// was ... && isFullyDefined(pt, ForceDegree.noBottom)
// but this prevents case blocks from implementing polymorphic partial functions,
// since we do not know the result parameter a priori. Have to wait until the
// body is typechecked.
return cpy.Closure(tree)(Nil, id, TypeTree(pt)).withType(pt)
case _ =>
}
case Closure(Nil, id @ Ident(nme.ANON_FUN), _) =>
val adaptToPrototype =
if (defn.isFunctionType(pt)) {
// convert implicit function to function
Copy link
Contributor

@odersky odersky Feb 21, 2017

Choose a reason for hiding this comment

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

Not sure about the change in this logic. Questions:

  • Do we want to convert implicit functions to functions, or to other SAM types? Does this case even arise? I was assuming that an implicit function is always immediately applied.
  • What would happen if we kept the previous code here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It is from implicit function to function, previously this worked because implicit functions where a subtype of functions.

A concrete case that fails without this change is

-- [E007] Type Mismatch Error: /Users/nicolasstucki/GitHub/dotty/tests/partest-generated/run/implicitFuns.scala --------
148 |        println(if (thisTransaction.isAborted) "aborted" else s"result: $res")
    |                                                                              ^
    |                                                                        found:    implicit Transaction => Unit
    |                                                                        required: Transaction => Any

where

  def transaction[T](op: Transaction => T) = {
    ...
  }

  def main(args: Array[String]) = {
    transaction {
      implicit thisTransaction =>
        val res = f1(args.length)
        println(if (thisTransaction.isAborted) "aborted" else s"result: $res")
    }
  }

Is there a better way to implement this coercion from implicit function to function?

!defn.isImplicitFunctionType(pt) && defn.isImplicitFunctionType(wtp)
} else {
// convert function literal to SAM closure
defn.isFunctionType(wtp) && {
pt match {
case SAMType(meth)
if wtp <:< meth.info.toFunctionType() =>
// was ... && isFullyDefined(pt, ForceDegree.noBottom)
// but this prevents case blocks from implementing polymorphic partial functions,
// since we do not know the result parameter a priori. Have to wait until the
// body is typechecked.
true
case _ => false
}
}
}
if (adaptToPrototype)
return cpy.Closure(tree)(Nil, id, TypeTree(pt)).withType(pt)
case _ =>
}
// try an implicit conversion
Expand Down
1 change: 1 addition & 0 deletions tests/run/implicitFunctionImpl.check
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
42
10 changes: 10 additions & 0 deletions tests/run/implicitFunctionImpl.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

object Test {
def main(args: Array[String]): Unit = {
println(new Fun().apply(42))
}
}

class Fun extends ImplicitFunction1[Int, Int] {
def apply(implicit v1: Int): Int = v1
}