Skip to content

Commit 1e7a990

Browse files
committed
SI-8359 Adjust parameter order of accessor method in Delambdafy
Under `-Ydelambdafy:method`, a public, static accessor method is created to expose the private method containing the body of the lambda. Currently this accessor method has its parameters in the same order structure as those of the lambda body method. What is this order? There are three categories of parameters: 1. lambda parameters 2. captured parameters (added by lambdalift) 3. self parameters (added to lambda bodies that end up in trait impl classes by mixin, and added unconditionally to the static accessor method.) These are currently emitted in order #3, #1, #2. Here are examples of the current behaviour: BEFORE (trait): ``` % cat sandbox/test.scala && scalac-hash v2.11.5 -Ydelambdafy:method sandbox/test.scala && javap -private -classpath . 'Test$class' trait Member; class Capture; trait LambdaParam trait Test { def member: Member def foo { val local = new Capture (arg: LambdaParam) => "" + arg + member + local } } Compiled from "test.scala" public abstract class Test$class { public static void foo(Test); private static final java.lang.String $anonfun$1(Test, LambdaParam, Capture); public static void $init$(Test); public static final java.lang.String accessor$1(Test, LambdaParam, Capture); } ``` BEFORE (class): ``` % cat sandbox/test.scala && scalac-hash v2.11.5 -Ydelambdafy:method sandbox/test.scala && javap -private -classpath . Test trait Member; class Capture; trait LambdaParam abstract class Test { def member: Member def foo { val local = new Capture (arg: LambdaParam) => "" + arg + member + local } } Compiled from "test.scala" public abstract class Test { public abstract Member member(); public void foo(); private final java.lang.String $anonfun$1(LambdaParam, Capture); public Test(); public static final java.lang.String accessor$1(Test, LambdaParam, Capture); } ``` Contrasting the class case with Java: ``` % cat sandbox/Test.java && javac -d . sandbox/Test.java && javap -private -classpath . Test public abstract class Test { public static class Member {}; public static class Capture {}; public static class LambaParam {}; public static interface I { public abstract Object c(LambaParam arg); } public abstract Member member(); public void test() { Capture local = new Capture(); I i1 = (LambaParam arg) -> "" + member() + local; } } Compiled from "Test.java" public abstract class Test { public Test(); public abstract Test$Member member(); public void test(); private java.lang.Object lambda$test$0(Test$Capture, Test$LambaParam); } ``` We can see that in Java 8 lambda parameters come after captures. If we want to use Java's LambdaMetafactory to spin up our anoymous FunctionN subclasses on the fly, our ordering must change. I can see three options for change: 1. Adjust `LambdaLift` to always prepend captured parameters, rather than appending them. I think we could leave `Mixin` as it is, it already prepends the self parameter. This would result a parameter ordering, in terms of the list above: #3, #2, #1. 2. More conservatively, do this just for methods known to hold lambda bodies. This might avoid needlessly breaking code that has come to depend on our binary encoding. 3. Adjust the parameters of the accessor method only. The body of this method can permute params before calling the lambda body method. This commit implements option #2. In also prototyped #1, and found it worked so long as I limited it to non-constructors, to sidestep the need to make corresponding changes elsewhere in the compiler to avoid the crasher shown in the enclosed test case, which was minimized from a bootstrap failure from an earlier a version of this patch. We would need to defer option #1 to 2.12 in any case, as some of these lifted methods are publicied by the optimizer, and we must leave the signatures alone to comply with MiMa. I've included a test that shows this in all in action. However, that is currently disabled, as we don't have a partest category for tests that require Java 8.
1 parent d14e065 commit 1e7a990

File tree

5 files changed

+86
-3
lines changed

5 files changed

+86
-3
lines changed

src/compiler/scala/tools/nsc/transform/LambdaLift.scala

+11-3
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ abstract class LambdaLift extends InfoTransform {
367367

368368
private def addFreeArgs(pos: Position, sym: Symbol, args: List[Tree]) = {
369369
free get sym match {
370-
case Some(fvs) => args ++ (fvs.toList map (fv => atPos(pos)(proxyRef(fv))))
370+
case Some(fvs) => addFree(sym, free = fvs.toList map (fv => atPos(pos)(proxyRef(fv))), original = args)
371371
case _ => args
372372
}
373373
}
@@ -379,9 +379,9 @@ abstract class LambdaLift extends InfoTransform {
379379
case DefDef(_, _, _, vparams :: _, _, _) =>
380380
val addParams = cloneSymbols(ps).map(_.setFlag(PARAM))
381381
sym.updateInfo(
382-
lifted(MethodType(sym.info.params ::: addParams, sym.info.resultType)))
382+
lifted(MethodType(addFree(sym, free = addParams, original = sym.info.params), sym.info.resultType)))
383383

384-
copyDefDef(tree)(vparamss = List(vparams ++ freeParams))
384+
copyDefDef(tree)(vparamss = List(addFree(sym, free = freeParams, original = vparams)))
385385
case ClassDef(_, _, _, _) =>
386386
// SI-6231
387387
// Disabled attempt to to add getters to freeParams
@@ -562,4 +562,12 @@ abstract class LambdaLift extends InfoTransform {
562562
}
563563
} // class LambdaLifter
564564

565+
private def addFree[A](sym: Symbol, free: List[A], original: List[A]): List[A] = {
566+
val prependFree = (
567+
!sym.isConstructor // this condition is redundant for now. It will be needed if we remove the second condition in 2.12.x
568+
&& (settings.Ydelambdafy.value == "method" && sym.isDelambdafyTarget) // SI-8359 Makes the lambda body a viable as the target MethodHandle for a call to LambdaMetafactory
569+
)
570+
if (prependFree) free ::: original
571+
else original ::: free
572+
}
565573
}

src/reflect/scala/reflect/internal/Symbols.scala

+1
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,7 @@ trait Symbols extends api.Symbols { self: SymbolTable =>
789789

790790
final def isAnonymousFunction = isSynthetic && (name containsName tpnme.ANON_FUN_NAME)
791791
final def isDelambdafyFunction = isSynthetic && (name containsName tpnme.DELAMBDAFY_LAMBDA_CLASS_NAME)
792+
final def isDelambdafyTarget = isSynthetic && isMethod && (name containsName tpnme.ANON_FUN_NAME)
792793
final def isDefinedInPackage = effectiveOwner.isPackageClass
793794
final def needsFlatClasses = phase.flatClasses && rawowner != NoSymbol && !rawowner.isPackageClass
794795

Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
-optimize
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package test
2+
3+
// This is a minimization of code that crashed the compiler during bootstrapping
4+
// in the first iteration of https://github.com/scala/scala/pull/4373, the PR
5+
// that adjusted the order of free and declared params in LambdaLift.
6+
7+
// Was:
8+
// java.lang.AssertionError: assertion failed:
9+
// Record Record(<$anon: Function1>,Map(value a$1 -> Deref(LocalVar(value b)))) does not contain a field value b$1
10+
// at scala.tools.nsc.Global.assert(Global.scala:262)
11+
// at scala.tools.nsc.backend.icode.analysis.CopyPropagation$copyLattice$State.getFieldNonRecordValue(CopyPropagation.scala:113)
12+
// at scala.tools.nsc.backend.icode.analysis.CopyPropagation$copyLattice$State.getFieldNonRecordValue(CopyPropagation.scala:122)
13+
// at scala.tools.nsc.backend.opt.ClosureElimination$ClosureElim$$anonfun$analyzeMethod$1$$anonfun$apply$2.replaceFieldAccess$1(ClosureElimination.scala:124)
14+
class Typer {
15+
def bar(a: Boolean, b: Boolean): Unit = {
16+
@inline
17+
def baz(): Unit = {
18+
((_: Any) => (Typer.this, a, b)).apply("")
19+
}
20+
((_: Any) => baz()).apply("")
21+
}
22+
}
23+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
//
2+
// Tests that the static accessor method for lambda bodies
3+
// (generated under -Ydelambdafy:method) are compatible with
4+
// Java 8's LambdaMetafactory.
5+
//
6+
import java.lang.invoke._
7+
8+
class C {
9+
def test1: Unit = {
10+
(x: String) => x.reverse
11+
}
12+
def test2: Unit = {
13+
val capture1 = "capture1"
14+
(x: String) => capture1 + " " + x.reverse
15+
}
16+
def test3: Unit = {
17+
(x: String) => C.this + " " + x.reverse
18+
}
19+
}
20+
trait T {
21+
def test4: Unit = {
22+
(x: String) => x.reverse
23+
}
24+
}
25+
26+
// A functional interface. Function1 contains abstract methods that are filled in by mixin
27+
trait Function1ish[A, B] {
28+
def apply(a: A): B
29+
}
30+
31+
object Test {
32+
def lambdaFactory[A, B](hostClass: Class[_], instantiatedParam: Class[A], instantiatedRet: Class[B], accessorName: String,
33+
capturedParams: Array[(Class[_], AnyRef)] = Array()) = {
34+
val caller = MethodHandles.lookup
35+
val methodType = MethodType.methodType(classOf[AnyRef], Array[Class[_]](classOf[AnyRef]))
36+
val instantiatedMethodType = MethodType.methodType(instantiatedRet, Array[Class[_]](instantiatedParam))
37+
val (capturedParamTypes, captured) = capturedParams.unzip
38+
val targetMethodType = MethodType.methodType(instantiatedRet, capturedParamTypes :+ instantiatedParam)
39+
val invokedType = MethodType.methodType(classOf[Function1ish[_, _]], capturedParamTypes)
40+
val target = caller.findStatic(hostClass, accessorName, targetMethodType)
41+
val site = LambdaMetafactory.metafactory(caller, "apply", invokedType, methodType, target, instantiatedMethodType)
42+
site.getTarget.invokeWithArguments(captured: _*).asInstanceOf[Function1ish[A, B]]
43+
}
44+
def main(args: Array[String]) {
45+
println(lambdaFactory(classOf[C], classOf[String], classOf[String], "accessor$1").apply("abc"))
46+
println(lambdaFactory(classOf[C], classOf[String], classOf[String], "accessor$2", Array(classOf[String] -> "capture1")).apply("abc"))
47+
println(lambdaFactory(classOf[C], classOf[String], classOf[String], "accessor$3", Array(classOf[C] -> new C)).apply("abc"))
48+
println(lambdaFactory(Class.forName("T$class"), classOf[String], classOf[String], "accessor$4", Array(classOf[T] -> new T{})).apply("abc"))
49+
}
50+
}

0 commit comments

Comments
 (0)