Skip to content

GROOVY-12756: STC: a value that is not a Class may be assigned to a parameterized Class - #3289

Open
codeconsole wants to merge 2 commits into
apache:masterfrom
codeconsole:stc-parameterized-class-coercion
Open

codeconsole wants to merge 2 commits into
apache:masterfrom
codeconsole:stc-parameterized-class-coercion

Conversation

@codeconsole

@codeconsole codeconsole commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

https://issues.apache.org/jira/browse/GROOVY-12756

Anything can be assigned to a Class, String or Boolean variable: the value is converted at run time, so Class c = 'java.lang.String' loads the class. Since GROOVY-12714, static type checking rejects that when the target's type has a type argument, even Class<?>, while the same assignment to a raw Class still compiles:

Class raw = type                          // compiles
Class<?> any = type                       // a java.lang.reflect.Type: error
Class<String> string = 'java.lang.String' // error
Class<? extends Number> number = object   // an Object parameter: error

class C {
    Class<String> init = 'java.lang.String'  // error
    Class<String> f
    void set(C other, String name) {
        this.f = name                        // error
        other.f = name                       // error
    }
}
[Static type checking] - Incompatible generic argument types. Cannot assign java.lang.reflect.Type to: java.lang.Class<?>

Grails no longer compiles against GROOVY_6_0_X because of this: AbstractStructuredBindingEditor assigns actualTypeArguments[0], a Type, to its Class<T> targetType.

For a variable, getResultType returned the variable's type. GROOVY-12714 made it keep the type of the value when the variable is a parameterized Class, so that Class<?> is not accepted for Class<? extends CharSequence>. When the value is not a Class there are no type arguments to compare, and checkTypeGenerics reported the value's type as an incompatible generic argument. The type of the value is now kept only when it is a Class, so a Class value is still checked against the type arguments.

A field initializer (a FieldExpression) and a property write (this.f, other.f) never took the variable branch, so for them the value's type was always checked against the type arguments. They now use the target type too when the value is not a Class, and a Class value is still checked.

STCAssignmentTest, and so AssignmentsStaticCompileTest, gets the forms above, plus a Class<?> assigned to Class<? extends CharSequence> through a variable, a field initializer and both property writes, all of which must stay errors. The test fails without the change. groovy.transform.stc.*, org.codehaus.groovy.classgen.asm.sc.* and groovy.bugs.* pass.

Please also apply this to GROOVY_6_0_X, where the change applies cleanly.

…arameterized Class

Anything can be assigned to a Class, String or Boolean variable; the value
is converted at run time. Since GROOVY-12714 the type checker keeps the
type of the value for a parameterized Class variable, so that Class<?> is
not accepted for Class<? extends CharSequence>. It did so for a value that
is not a Class as well, and then reported that type as an incompatible
generic argument:

    Class<T> targetType = types[0]             // a java.lang.reflect.Type
    Class<String> c = 'java.lang.String'

while the same assignments to a raw Class compiled. The type of the value
is now kept only when it is a Class.
@codecov-commenter

codecov-commenter commented Nov 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 74.4533%. Comparing base (856b28a) to head (2ceac52).
⚠️ Report is 15 commits behind head on master.

Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##               master      #3289        +/-   ##
==================================================
+ Coverage     74.4429%   74.4533%   +0.0104%     
- Complexity      44774      44840        +66     
==================================================
  Files            1702       1702                
  Lines          151891     151996       +105     
  Branches        29091      29120        +29     
==================================================
+ Hits           113072     113166        +94     
- Misses          28413      28419         +6     
- Partials        10406      10411         +5     
Files with missing lines Coverage Δ
...roovy/transform/stc/StaticTypeCheckingVisitor.java 87.9713% <100.0000%> (+0.0009%) ⬆️

... and 24 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.

@daniellansun daniellansun left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked this on the current master type checker (the visitor is unchanged since 856b28a) and on GROOVY_6_0_X.

Without the change, testAssignmentToParameterizedClass fails on both, and only on these two lines:

Class<String> c = 'java.lang.String'
targetType = types[0]    // java.lang.reflect.Type

With the change those compile, Class<?> -> Class<? extends CharSequence> is still rejected, and STCAssignmentTest plus AssignmentsStaticCompileTest pass. The cherry-pick onto GROOVY_6_0_X is clean.

The shortcut still runs only when the left-hand side is a VariableExpression. These are still rejected under @TypeChecked and @CompileStatic, while the same writes to a raw Class compile:

class C {
    Class<String> init = 'java.lang.String'          // error
    Class<String> f
    void viaCtor() { f = 'java.lang.String' }        // ok, bare name
    void viaProperty(C other, String name) {
        this.f = name                                 // error
        other.f = name                                // error
    }
}

getResultType never enters the new condition for them. A field initializer is a FieldExpression (visitInitialExpression), and this.f / other.f are property expressions. Please apply the "not a Class, so keep the target type" rule to those assignments as well. A local and a bare field name already go through castToClass: the bytecode is an invokedynamic cast to Class, linked by CastSelector to DefaultTypeTransformation.castToType / ShortTypeHandling.castToClass. A value that is already a Class is returned unchanged, so a type argument is not checked at run time. That is why the generic check has to stay when the static type is a Class.

Object o = Integer; Class<? extends Number> n = o does not fail without this patch. o is flow-typed to Class<Integer>, which is a legal Class<? extends Number>. The String and Type lines are the regression. An Object or Type parameter does exercise the coercion:

Class<? extends Number> go(Object o) { Class<? extends Number> n = o; n }

go(Integer) is Integer. go(String) also type-checks and yields String.class, because castToClass returns any Class as-is. Same as a raw Class. Editor<List<String>> now type-checks and throws GroovyCastException in the constructor: actualTypeArguments[0] is a ParameterizedType, and castToClass calls Class.forName on its toString(). Same as assigning that value to a raw Class.

Method arguments are unchanged, and that is consistent. void take(Class<String> c) and void take(Class c) both reject take('java.lang.String'). javac 21 rejects the parameterized form too. Returns of a String from Class<String> were already accepted before this patch.

<T extends Class<? extends CharSequence>> void m(T t) { Class<? extends CharSequence> c = t } is still rejected. javac 21 accepts it. This patch does not change that: isClassType is true for such a T, so the generic check still runs and does not use the bound. Not a regression, but it is not the JLS rule either.

No COMPATIBILITY.md entry. GROOVY-12714 has not been released, and this restores the coercion a raw Class already has. I would backport it once the field initializer and the property writes are included.

…lass field initializer or property

The previous change kept the target type only when the left-hand side is
a variable. A field initializer and a property write go through the same
check, so these were still rejected while a raw Class compiled:

    Class<String> init = 'java.lang.String'
    this.f = name
    other.f = name

They now use the target type when the value is not a Class. A Class
value is still checked against the type arguments.
@codeconsole

Copy link
Copy Markdown
Contributor Author

Thanks. 2ceac52 applies the same rule to a field initializer and to this.f / other.f: when the target is a parameterized Class and the value is not a Class, the target type is used. A Class value still goes through the generic check, so Class<?> to Class<? extends CharSequence> is still rejected in all three places, and the test now covers that.

I also replaced the Object o = Integer lines with an Object parameter, because, as you pointed out, the flow typing made the local a Class<Integer>. Without the change the test fails on the String and Type lines and on the three new writes. STCAssignmentTest, AssignmentsStaticCompileTest, groovy.transform.stc.*, org.codehaus.groovy.classgen.asm.sc.* and groovy.bugs.* pass.

@testlens-app

testlens-app Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🚨 All tests passed but jobs failed 🚨

Failed Jobs without Test Failures

❌ Lint gate / lint

🏷️ Commit: 2ceac52
▶️ Tests: 126352 executed
⚪️ Checks: 26/26 completed

Rerun Controls

Click the checkbox to trigger a rerun:

  • Rerun jobs

Learn more about TestLens at testlens.app/docs.

@paulk-asert

Copy link
Copy Markdown
Contributor

Thanks Scott, I am going to put together a bundle of related PRs affecting Grails with our generics rules spelt out a bit more clearly. I'll notify when done.

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.

4 participants