Repository navigation
GROOVY-12836: native lambdas and method references for functional targets (GEP-34) - #3364
Open
paulk-asert wants to merge 10 commits into
Open
paulk-asert wants to merge 10 commits into
paulk-asert wants to merge 10 commits into
Conversation
…od references for its functional interface Under @CompileStatic, Supplier<String> s = flag ? () -> 'a' : () -> 'b' compiled and then failed with a GroovyCastException: the lambda could not be cast to Closure. The type checker types the conditional expression as the interface and gives each lambda the interface, so each lambda is compiled as an instance of it, but the class generator took the common type of the branches from their inferred types, Closure for a lambda, and cast each branch to it. The same held for a conditional expression returned or assigned to a subscript, property, field or list element, for method reference branches and for a lambda with a closure. StaticTypesTypeChooser now resolves a lambda or method reference that has a functional interface as its parameter type, which is what the lambda and method reference writers compile it to, to that interface. Assigned to a subscript, a conditional expression with a branch of the interface type and a lambda or method reference, such as map['k'] = flag ? f : (String s) -> s.trim(), did not compile: the type checker visits the value of a subscript assignment before the assignment, where the lambda got no target type, and putAt was checked with Object, the common type of the interface and Closure. That visit now takes the subscript's type as the target type, and a method reference branch, like a lambda, takes the interface as its type.
…onditional argument or a named argument the parameter types of its functional interface
A closure passed as an argument, or assigned to a variable or property of
a functional interface type, takes the types of its parameters from the
interface. Written in three other places it did not, so
it.toUpperCase() was rejected with "Cannot find matching method
java.lang.Object#toUpperCase()":
- as the operand of an operator method, such as
sink << { it.toUpperCase() } for leftShift(Function<String, String>);
- as a branch of a conditional expression passed as an argument, such as
apply(flag ? { it.toUpperCase() } : { it.trim() });
- as a named argument of a constructor call, such as
new Bean(value: { it.toUpperCase() }) for a Function<String, String>
property.
The same held for a lambda with an untyped parameter. In each place the
type checker visited the closure before it knew the operator method, the
method or the property.
The right operand of an operator now takes, before it is visited, the
interface that the operator method found for a closure declares its
parameter with, and the value of a named argument the interface the
property is declared with, as an assignment does. Either applies only
where the closure has parameters to type, an implicit one for a method of
one parameter or as many as the method with one untyped, so a closure
that minus(List, Iterable) also accepts keeps its checks. A conditional
expression whose branches are closures or lambdas is, as an argument,
visited once the method is chosen, as a closure is, and its branches
take the parameter's interface.
…lement the interface it is bound to Under @CompileStatic, a closure literal written for a slot declared with a type parameter that the call binds to a functional interface, as an argument, a return value, or a value assigned to a subscript or property, is compiled as a closure class that also implements that interface, so a statically compiled read through the interface works, and dynamic code can call the interface's methods on it. Untyped parameters take their types from the interface, also for an operand or a conditional argument. A closure for a sealed, trait or inaccessible interface, one whose parameters do not fit the interface method, and one for an interface with a default method Closure would replace are kept as they are; a value stored as a plain closure gets a warning. Squashed from the commits of apache#3090 and apache#3340, with the merge resolutions against apache#3338 and master. The GROOVY-10979 commits are those of apache#3089, which master has as ad1832f; here they keep only what differs from it. caab236 GROOVY-10979: Convert a closure passed for a type parameter to the interface the call binds it to 1727d5a GROOVY-12561: Convert a closure assigned to a subscript or property to its interface f6f5515 GROOVY-10979: Convert a closure returned by a generic method for a type parameter ca144e6 GROOVY-10979: Test closures passed for one type parameter and for one with several bounds e608a44 GROOVY-12561: Move the test of a closure assigned to a subscript or property ahead of the last test 8b73244 GROOVY-12561: Test a Callable or Runnable target and a value that is not a closure 3fff2f4 GROOVY-10979: Resolve a type-parameter slot only for a lambda or method reference under static compilation 06937ac GROOVY-10979: Document a lambda or method reference passed for a type parameter 6294e2d GROOVY-12561: Make a closure literal written for a type parameter implement the interface it is bound to 849e9da GROOVY-12561: Keep a closure for a sealed, trait or inaccessible interface as it is fba3a94 GROOVY-12561: Do not warn of a lambda or method reference assigned to a subscript or property 7867abf GROOVY-12561: Remove the fixed case from RegressionTest 0939f36 GROOVY-12561: Implement an interface with wildcard type arguments by the types they stand for 4731d3b GROOVY-12561: Pass a closure whose parameters are not the interface method's as it is cc72e80 GROOVY-12561: Keep a closure as it is for an interface with a default method Closure would replace 86cbfc2 GROOVY-12561: Call a default method of the implemented interface on a closure from dynamic code d5cbedc GROOVY-12561: Warn only of a value that is stored as a plain closure 76b60e2 GROOVY-12561: Document which closures get parameter types from the interface, and the new exceptions e056216 GROOVY-12561: Warn of a method pointer passed for a type parameter that is stored as it is 749f0c1 GROOVY-12561: Give a closure written for a type parameter as an operand or a conditional argument the interface's parameter types
…t as a closure that implements the interface
Under @CompileStatic, a lambda written for a slot declared with a type
parameter that the call binds to a functional interface, such as E of
List.add(E), is compiled as a closure class that also implements the
interface, as a closure literal there is. The value stays a Closure, so
dynamic code reads it as before, and a statically compiled read through
the interface works. Untyped parameters take their types from the
interface at arguments, operands, conditional and named arguments.
A literal whose class cannot implement the interface, and a value of
type Closure, are stored as they are, with a LIKELY_ERRORS warning that
a statically compiled read through the interface will fail.
The incubating groovy.target.lambda.typearg option and the method
reference operand path are removed: a method reference argument is still
compiled for the interface, and a method reference operand stays a
method closure, with the warning.
A composed, curried, writable, memoized or trampoline closure keeps the
closure it wraps as its owner, or in a field, so a dynamic call of the
interface method on the wrapper fell through to the wrapped closure:
f.andThen(up).apply(x) ran only f, and b.curry('x', 'y').apply(p, q)
dropped the curried arguments. The wrapper now answers the abstract
method by calling itself; the interface's default methods are not
answered.
The method a closure class declares for the interface has the body of
the compile-time adapter (GROOVY-12492): the closure is called with its
arguments converted and its exceptions translated, as "closure as F"
calls it, so a wrong argument through a raw view of the interface is a
MissingMethodException, as in Groovy 6.
@PackedClosures cannot pack such a closure; the decline reason names
the interface, and under mode = STRICT the error suggests LENIENT or
WARN, since such code compiled with STRICT before.
This implements GEP-33.
…ype the call is assigned, returned or cast to Under @CompileStatic, Function<String, String> f = id(String::trim) for <T> T id(T t) did not compile: "Argument is a method reference, but parameter type 'T' is not a functional interface". Since GROOVY-12727 the type a call's value is assigned, returned or cast to gives a type parameter that the arguments leave open when the argument is a lambda or a closure, but the functional interface of a method reference passed for a type parameter was taken from the arguments only. When no argument is a witness for the type parameter, the type the call is assigned, returned or cast to now gives it, within its bounds, as for a lambda, so a method reference or constructor reference is compiled for that interface. A call whose value has no such target still rejects it.
…s itself an argument from the enclosing parameter Under @CompileStatic, take(id(String::trim)) for <T> T id(T t) and take(Function<String, String>) did not compile: "Argument is a method reference, but parameter type 'T' is not a functional interface". The parameter of take gives T, as javac infers it, but the type checker visits id(String::trim) before it chooses take, so nothing gave T when it checked the method reference. A method reference whose type parameter a call that is itself an argument leaves open is now resolved once the enclosing call's method is chosen: the parameter it is passed for is then the call's target type, as an assignment's is since GROOVY-12823. When that parameter is a type parameter of the enclosing call, its target type gives it in turn, so take(wrap(id(String::trim))) and an assigned wrap(id(String::trim)) compile as well. If nothing gives the type parameter, the method reference is rejected as before.
… variable
A closure literal, lambda or Closure value passed where the call binds a
type parameter to a type variable of the enclosing method or class, such
as l.add { .. } for a List<T> in
<T extends Function<String, String>> void fill(List<T> l), is stored as
a plain closure: it is neither a T nor the bound, and a statically
compiled read through either fails far from the cause. The type checker
now warns at LIKELY_ERRORS when the type variable has a functional
interface as its bound. Implementing the bound would not help, since T
may be a subinterface of it.
The warning for a value of type Closure also no longer fires for a call
whose method reference is still to be resolved from the enclosing call
(GROOVY-12825), as in Function<String, String> f = wrap(id(String::trim)).
Dynamic code can now call a native lambda or method reference (an instance of a class LambdaMetafactory creates) and a Groovy coercion proxy (a Proxy whose handler is Groovy's conversion handler, checked per instance) with f(args) or f.call(args): the call invokes the abstract method of the value's functional interface. No other object becomes callable; a List, a Thread, an InputStream or a user class implementing a functional interface still throws MissingMethodException. The rule runs only after everything the MOP already tries, as a last resort before MissingMethodException, so categories, methodMissing, invokeMethod and a call property keep their precedence. A call through a property, obj.f(x), is not affected. The invokedynamic Selector binds the call at the call site, so a hot f(x) costs about as much as f.apply(x). This implements GEP-35.
Compares dynamic f(x) and f.apply(x) on a native lambda, a closure call, a coercion proxy, and the meta-class path without the call-site binding.
… target as native lambdas Under @CompileStatic, a lambda or method reference whose target is a functional interface is now a native lambda, as in Java: at type-parameter slots (list.add(s -> s.trim()), list << String::trim, map.put(k, s -> s.trim())), in conditional arguments, in list and map literals (List<F> l = [s -> s.trim()]), and as an argument of a generic call such as Optional.of(String::trim) or Arrays.asList(..). GEP-33 compiled the lambdas at type-parameter slots as closures that implement the interface; closure literals keep that representation. A lambda for list += stays a compile error. The target of a generic call can come from its context: the type it is assigned, returned or cast to, or the parameter of an enclosing call. One mechanism does this for lambdas and method references alike: the call waits for its target type and is then resumed, so type-checking extensions see it once. It replaces the deferred method references of GROOVY-12823 and GROOVY-12825. @TypeChecked code accepts the same literals. A closure or lambda there is a closure that implements the interface; a method reference at an operand, a subscript or a conditional branch is a method closure, with GEP-33's warning, as before. A lambda for a slot whose type is a type variable is an error, as in javac ("T is not a functional interface"); a closure literal there keeps GEP-33's warning, now also at operands. Closure literals at declared targets (F f = { .. }, take { .. }) stay coercion proxies; GEP-34 defers implementing closures there. The incubating groovy.target.functional.report system property makes the type checker warn of each literal that is now a native lambda where it was a closure, a method closure or a proxy, and of each call whose type arguments come from its context, without changing the code. Also fixes the lambda writer for a parameter declared with a superinterface of the interface method's parameter type, which failed with "The inferred type[String] is not compatible with the parameter type[CharSequence]", also in 6.0.0. This implements GEP-34.
✅ All tests passed ✅🏷️ Commit: bb79875 Learn more about TestLens at testlens.app/docs. |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
JIRA: GROOVY-12836
The implementation of GEP-34: Native Functional Values (version 2).
This PR is stacked. It contains #3362 (GEP-33) and #3363 (GEP-35, GROOVY-12835), which it needs, and adds one commit: the last,
GROOVY-12836: .... Review that commit; the others are reviewed on their own PRs. The only conflict in stacking them is one hunk ofFunctionalTypeArgumentTest, where #3362's side is kept. Once #3362 and #3363 are merged, this branch will be rebased to the one commit.What changes
Under
@CompileStatic, a lambda or method reference whose target is a functional interface is a native lambda, as in Java, at sites where Groovy 6 stored a closure or rejected it:@CompileStaticsitelist.add(λ),map.put(k, λ),list << λlist << String::trimcond ? λ1 : λ2as an argumentOptional.of(String::trim),Arrays.asList(λ),List.of(λ)F f = id(id(λ)),pick(fv, String::strip)List<F> l = [λ],Map<String, F> m = [k: λ]@TypeCheckedaccepts the same literals. A closure or lambda there is a closure that implements the interface; a method reference at an operand, a subscript or a conditional branch stays a method closure with GEP-33's warning, andlist.add(String::trim)stays an error, as in Groovy 6.F f = { .. },take { .. }) stay coercion proxies, as GEP-34 v2 defers implementing closures there.groovy.target.functional.report=truemakes the type checker warn of each literal that is now a native lambda where Groovy 6 had a closure, a method closure or a proxy, and of each call whose type arguments come from its context. It does not change the generated code (tested).Function<String, ..>with(CharSequence s) -> ..) failed with "The inferred type[String] is not compatible with the parameter type[CharSequence]", also in 6.0.0.Compatibility
These are breaking changes for statically compiled code that hands such values to dynamic code; GEP-34's "Breaking changes" section lists them with what still works. In short: a native lambda is not a
Closure, soinstanceof Closure,curry,>>,delegate,Closure-only DGM methods and serialization (unless the target isSerializable) stop working on it from dynamic code, andgrepandswitchsilently stop matching it. Call syntax keeps working through GEP-35 (#3363). A lambda that calls a method of an enclosing closure's delegate, a lambda whose parameters do not fit the interface, and a lambda for a type variable become compile errors, as in javac. The report mode finds affected code.Not in this PR
list += λon aList<F>is still a compile error; the GEP's table lists it as native.GenericsJavaCompatibilityTest, and a Groovy 7 compatibility entry.Testing
FunctionalContextInferenceTest; updatedFunctionalLiteralSiteTest,FunctionalTypeArgumentTest,CoercionTestandRegressionTest.:testpasses (22628 tests, 0 failures, 332 skipped), as docheckstyleGate,codenarcGateand:tests-native:checkNativeMetadata.