Skip to content

GROOVY-12836: native lambdas and method references for functional targets (GEP-34) - #3364

Open
paulk-asert wants to merge 10 commits into
apache:masterfrom
paulk-asert:gep34
Open

paulk-asert wants to merge 10 commits into
apache:masterfrom
paulk-asert:gep34

Conversation

@paulk-asert

@paulk-asert paulk-asert commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

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 of FunctionalTypeArgumentTest, 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:

@CompileStatic site Groovy 6.0 GEP-33 (#3362) this PR
list.add(λ), map.put(k, λ), list << λ closure, read through F fails implementing closure native
list << String::trim method closure, read through F fails method closure, warning native
cond ? λ1 : λ2 as an argument closure, read through F fails implementing closure native
Optional.of(String::trim), Arrays.asList(λ), List.of(λ) compile error compile error native
F f = id(id(λ)), pick(fv, String::strip) compile error method references only native
List<F> l = [λ], Map<String, F> m = [k: λ] compile error compile error native
  • Inference from context. The target of a generic call can come from the type it is assigned, returned or cast to, or from the parameter of an enclosing call. One mechanism serves lambdas and method references: the call waits for its target type and is resumed, never checked twice, so type-checking extensions see it once (tested with the extension callbacks). It replaces the deferred method references of GROOVY-12823/12825 (GROOVY-12823: SC: take a method reference's type parameter from the type the call is assigned, returned or cast to #3337, GROOVY-12825: SC: resolve a method reference in a generic call that is itself an argument from the enclosing parameter #3339) that GROOVY-12561: functional literals for type-parameter slots (GEP-33) #3362 contains.
  • @TypeChecked 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 stays a method closure with GEP-33's warning, and list.add(String::trim) stays an error, as in Groovy 6.
  • Type-variable targets. A lambda for a slot whose type is a type variable is a compile error, as in javac: "The lambda is written for T, which is a type variable: T is not a functional interface; write a closure, or take the value as a parameter of type T". A closure literal there keeps GEP-33's warning, now also at operands.
  • Closure literals at declared targets (F f = { .. }, take { .. }) stay coercion proxies, as GEP-34 v2 defers implementing closures there.
  • Report mode. The incubating system property groovy.target.functional.report=true makes 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).
  • A lambda writer fix, also a 6.0.x candidate: a lambda parameter declared with a superinterface of the interface method's parameter type (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, so instanceof Closure, curry, >>, delegate, Closure-only DGM methods and serialization (unless the target is Serializable) stop working on it from dynamic code, and grep and switch silently 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 a List<F> is still a compile error; the GEP's table lists it as native.
  • The GEP's work items for benchmarks, cases checked against javac in GenericsJavaCompatibilityTest, and a Groovy 7 compatibility entry.

Testing

codeconsole and others added 10 commits November 26, 2026 21:54
…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.
@paulk-asert paulk-asert changed the title GEP-34: native lambdas and method references for functional targets GROOVY-12836: native lambdas and method references for functional targets Nov 26, 2026
@paulk-asert paulk-asert changed the title GROOVY-12836: native lambdas and method references for functional targets GROOVY-12836: native lambdas and method references for functional targets (GEP-34) Nov 26, 2026
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 68.93204% with 96 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.9698%. Comparing base (5e36030) to head (bb79875).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
...oovy/classgen/asm/sc/StaticTypesClosureWriter.java 17.9487% 30 Missing and 2 partials ⚠️
...rg/codehaus/groovy/classgen/asm/ClosureWriter.java 75.8064% 5 Missing and 10 partials ⚠️
...java/org/codehaus/groovy/vmplugin/v8/Selector.java 69.7674% 2 Missing and 11 partials ⚠️
src/main/java/groovy/lang/MetaClassImpl.java 76.4706% 3 Missing and 9 partials ⚠️
...oovy/internal/metaclass/FunctionalCallSupport.java 67.7419% 5 Missing and 5 partials ⚠️
...aus/groovy/runtime/metaclass/ClosureMetaClass.java 81.5790% 1 Missing and 6 partials ⚠️
...haus/groovy/classgen/asm/sc/SamAdapterFactory.java 89.6552% 0 Missing and 3 partials ⚠️
...groovy/classgen/asm/sc/StaticTypesTypeChooser.java 77.7778% 0 Missing and 2 partials ⚠️
...roovy/classgen/asm/sc/StaticTypesLambdaWriter.java 0.0000% 0 Missing and 1 partial ⚠️
.../groovy/transform/sc/StaticCompilationVisitor.java 50.0000% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##               master      #3364        +/-   ##
==================================================
+ Coverage     74.9577%   74.9698%   +0.0121%     
- Complexity      48936      49473       +537     
==================================================
  Files            1768       1769         +1     
  Lines          161255     162256      +1001     
  Branches        31743      32163       +420     
==================================================
+ Hits           120873     121643       +770     
- Misses          28970      29027        +57     
- Partials        11412      11586       +174     
Files with missing lines Coverage Δ
...sgen/asm/sc/AbstractFunctionalInterfaceWriter.java 95.6522% <100.0000%> (+0.0317%) ⬆️
...codehaus/groovy/control/CompilerConfiguration.java 75.6164% <ø> (ø)
...aus/groovy/tools/NativeImageMetadataGenerator.java 90.9910% <ø> (ø)
...roovy/transform/stc/StaticTypeCheckingVisitor.java 86.8878% <ø> (-1.0655%) ⬇️
...dehaus/groovy/transform/stc/StaticTypesMarker.java 100.0000% <100.0000%> (ø)
...roovy/classgen/asm/sc/StaticTypesLambdaWriter.java 89.7887% <0.0000%> (-0.3521%) ⬇️
.../groovy/transform/sc/StaticCompilationVisitor.java 86.0465% <50.0000%> (-0.3348%) ⬇️
...groovy/classgen/asm/sc/StaticTypesTypeChooser.java 92.8571% <77.7778%> (-7.1429%) ⬇️
...haus/groovy/classgen/asm/sc/SamAdapterFactory.java 90.0000% <89.6552%> (+0.2564%) ⬆️
...aus/groovy/runtime/metaclass/ClosureMetaClass.java 77.1208% <81.5790%> (+0.9168%) ⬆️
... and 5 more

... and 19 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@testlens-app

testlens-app Bot commented Nov 26, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: bb79875
▶️ Tests: 145643 executed
⚪️ Checks: 27/27 completed


Learn more about TestLens at testlens.app/docs.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants