Skip to content

GROOVY-12821: SC: use a closure shared variable in a closure through the common type of its assignments - #3332

Open
codeconsole wants to merge 2 commits into
apache:masterfrom
codeconsole:sc-closure-shared-variable-subclasses
Open

codeconsole wants to merge 2 commits into
apache:masterfrom
codeconsole:sc-closure-shared-variable-subclasses

Conversation

@codeconsole

Copy link
Copy Markdown
Contributor

With Sub s = new Sub1(), a closure { -> s.pm() } and a later s = new Sub2(), the closure was compiled for s as a Sub1, the type flow typing gave it where the closure was created. The call cast the value to Sub1 and threw ClassCastException at run time once s held a Sub2, although dynamic Groovy and @TypeChecked run it.

@groovy.transform.CompileStatic
class Outer {
    static class Box {
        String id = 'box'
        String pm() { 'pm:' + id }
        static String t() { Sub s = new Sub1(); def c = { -> s.pm() }; s = new Sub2(); c() }
    }
    static class Sub extends Box { }
    static class Sub1 extends Sub { Sub1() { id = 'sub1' } }
    static class Sub2 extends Sub { Sub2() { id = 'sub2' } }
}
assert Outer.Box.t() == 'pm:sub2'  // ClassCastException: Outer$Sub2 cannot be cast to Outer$Sub1

The same held for a lambda, a property read or write (s.id), an attribute (s.@f), an overridden method, and s passed as an argument, where the overload chosen for Sub1 was called. The type checker's second pass already checks a call on such a variable against the common type of its assignments, but only to report a missing method.

When a closure or lambda makes the call, the second pass now also takes the method it finds on the common type as the target and the class that declares it as the type of the receiver. A property or attribute expression on such a variable in a closure is checked there too, and is given the common type where that type has the property. A call with such a variable as an argument selects the method again for the common type, with the common type for a receiver that is such a variable as well. Calls outside closures keep the type flow typing gives the variable there.

Behaviour change

A closure call that passes such a variable, where no method accepts the common type of its assignments, is now reported, in both modes, as a call on such a variable already is: "The closure shared variable "s" has been assigned with various types and the method only1(Sub) does not accept the lowest upper bound of those types: Sub". Dynamic Groovy throws MissingMethodException for it once the variable holds a value the method does not take. Under @CompileStatic, an argument overload is selected for the common type, as javac selects one for the variable's static type.

Tests

ClosuresSTCTest (also run statically compiled by ClosuresStaticCompileTest): testClosureSharedVariable9 covers a call, a lambda, a property read and write, an attribute, an overridden method, an argument, a receiver and argument that are both such variables, and an interface-only common type; testClosureSharedVariable10 covers the new error. Without the change, the first fails with the ClassCastException under static compilation and the second in both modes. The 18,621 tests in the groovy, gls, bugs, org.codehaus.groovy.classgen, transform, runtime, reflection, vmplugin, control and ast packages and the stub generator tests pass. groovy-contracts, groovy-typecheckers, groovy-ginq, groovy-macro-library, groovy-json, groovy-xml and groovy-templates pass their tests, and every subproject compiles its main and test sources. The Checkstyle and CodeNarc gates pass.

This branch and #3050 both change StaticTypeCheckingVisitor.performSecondPass, so whichever is merged second needs a small merge there.

…the common type of its assignments

With Sub s = new Sub1(), a closure { -> s.pm() } and a later s = new
Sub2(), the closure was compiled for s as a Sub1, the type flow typing
gave it where the closure was created: the call cast the value to Sub1
and threw ClassCastException at run time once s held a Sub2, although
dynamic Groovy and @TypeChecked run it. The same held for a lambda, a
property read or write (s.id), an attribute (s.@f), an overridden
method, and s passed as an argument, where the overload chosen for Sub1
was called. The second pass already checks a call on such a variable
against the common type of its assignments, but only to report a
missing method.

When a closure or lambda makes the call, the second pass now also takes
the method it finds on the common type as the target and the class
that declares it as the type of the receiver. A property or attribute
expression on such a variable in a closure is checked there too, and
is given the common type where that type has the property. A call with
such a variable as an argument selects the method again for the common
type, and is reported as the receiver case is when no method accepts
it. Calls outside closures keep the type flow typing gives the
variable there.
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.14286% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.9599%. Comparing base (09e84fa) to head (0d8c333).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...roovy/transform/stc/StaticTypeCheckingVisitor.java 87.1429% 1 Missing and 8 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##               master      #3332        +/-   ##
==================================================
+ Coverage     74.9518%   74.9599%   +0.0081%     
- Complexity      48908      48962        +54     
==================================================
  Files            1768       1768                
  Lines          161213     161325       +112     
  Branches        31728      31767        +39     
==================================================
+ Hits           120832     120929        +97     
- Misses          28968      28975         +7     
- Partials        11413      11421         +8     
Files with missing lines Coverage Δ
...roovy/transform/stc/StaticTypeCheckingVisitor.java 87.9435% <87.1429%> (+0.0264%) ⬆️

... and 12 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 23, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 0d8c333
▶️ Tests: 145289 executed
⚪️ Checks: 26/26 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.

2 participants