aboutsummaryrefslogtreecommitdiff
path: root/src/dotty/tools/dotc/transform/FunctionalInterfaces.scala
blob: 5f433d28d66fdf3851e25fe903264063a44d8f8b (plain) (blame)
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
package dotty.tools.dotc
package transform

import TreeTransforms._
import core.DenotTransformers._
import core.Symbols._
import core.Contexts._
import core.Types._
import core.Flags._
import core.Decorators._
import core.SymDenotations._
import core.StdNames.nme
import core.Names._
import core.NameOps._
import ast.Trees._
import SymUtils._
import dotty.tools.dotc.ast.tpd
import collection.{ mutable, immutable }
import collection.mutable.{ LinkedHashMap, LinkedHashSet, TreeSet }

/**
 *  Rewires closures to implement more specific types of Functions.
 */
class FunctionalInterfaces extends MiniPhaseTransform {
  import tpd._

  def phaseName: String = "functionalInterfaces"

  var allowedReturnTypes: Set[Symbol] = _ // moved here to make it explicit what specializations are generated
  var allowedArgumentTypes: Set[Symbol] = _
  val maxArgsCount = 2

  def shouldSpecialize(m: MethodType)(implicit ctx: Context) =
    (m.paramTypes.size <= maxArgsCount) &&
      m.paramTypes.forall(x => allowedArgumentTypes.contains(x.typeSymbol)) &&
      allowedReturnTypes.contains(m.resultType.typeSymbol)

  val functionName = "JFunction".toTermName
  val functionPackage = "scala.compat.java8.".toTermName

  override def prepareForUnit(tree: tpd.Tree)(implicit ctx: Context): TreeTransform = {
    allowedReturnTypes   = defn.ScalaNumericValueClasses
    allowedArgumentTypes = defn.ScalaNumericValueClasses + defn.BooleanClass
    this
  }

  override def transformClosure(tree: Closure)(implicit ctx: Context, info: TransformerInfo): Tree = {
    tree.tpt match {
      case EmptyTree =>
        val m = tree.meth.tpe.widen.asInstanceOf[MethodType]

        if (shouldSpecialize(m)) {
          val interfaceName = (functionName ++ m.paramTypes.length.toString).specializedFor(m.resultType, m.paramTypes)
          // symbols loaded from classpath aren't defined in periods earlier than when they where loaded
          val interface = ctx.withPhase(ctx.typerPhase).requiredClass(functionPackage ++ interfaceName)
          val tpt = tpd.TypeTree(interface.asType.typeRef)
          tpd.Closure(tree.env, tree.meth, tpt)
        } else tree
      case _ =>
        tree
    }
  }
}