Skip to content

GROOVY-12621: STC: reject more private superclass field accesses that fail at run time under type checking - #3147

Open
codeconsole wants to merge 10 commits into
apache:masterfrom
codeconsole:stc-tc-private-field-more
Open

codeconsole wants to merge 10 commits into
apache:masterfrom
codeconsole:stc-tc-private-field-more

Conversation

@codeconsole

Copy link
Copy Markdown
Contributor

Stacked on #3137 (GROOVY-12610). After that change, @TypeChecked still accepted three kinds of private superclass field access that fail at run time with a MissingPropertyException:

@groovy.transform.TypeChecked
enum E {
    A { def n() { z } }          // also this.z, super.z
    private String z = 'x'
}

@groovy.transform.TypeChecked
class Base {
    private String z = 'x'
    static class Nested extends Base {}
    class Sub extends Base {
        def m() { super.z = 'y' } // also super.z += .., super.z++
    }
    class Inner {
        def m(Nested n) { n.z }   // receiver is not an Inner
    }
}

The enum case fails the same way in 4.0.33, 5.0.8 and 6.0.0.

  • Enum constant body. It is created by the enum's static initializer, so it has no enum instance to fall back to. ClassNodeUtils.hasNoEnclosingInstance now says so. As a result E.this in the body is a compile error instead of a VerifyError.
  • Write through super. The runtime falls back to the enclosing instance for reads and writes in an inner class, but not for a write through super (GROOVY-11823). StaticTypeCheckingVisitor.isFieldAccessible now knows whether the access is a write, and rejects a super write from a class other than the declaring class.
  • Receiver of another class. The fallback applies only when the receiver is an instance of the calling class. A receiver that is not super must now be derived from the current class. The exception is the Outer.this.z that the checker builds for an implicit z: it is still dispatched on this, so it is marked and left unaffected.

@CompileStatic still accesses the field directly in every case. A non-static inner subclass still reaches the field through this.z, z, super.z reads, closures, lambdas and writes. Attribute access and access from the declaring class are unchanged.

Tests

FieldsAndPropertiesSTCTest.testPrivateFieldOfEnumViaConstantBody, testPrivateFieldOfSuperclassWrittenThroughSuperInInnerSubclass, testPrivateFieldOfSuperclassViaReceiverOfOtherClass and InnerClassTest.testOuterThisInEnumConstantBody fail without the change. testPrivateFieldOfSuperclassViaReceiverOfCallingClass and the FieldsAndPropertiesStaticCompileTest overrides cover the forms that must keep compiling under type checking and static compilation. groovy.transform.stc.*, org.codehaus.groovy.classgen.asm.sc.*, gls.*, org.codehaus.groovy.transform.traitx.*, groovy.ThisAndSuperTest, bugs.* and groovy.bugs.* pass. The Checkstyle and CodeNarc gates pass.

…est-mate subclass under type checking

Type-checked code is dispatched dynamically, and the metaclass of a subclass
does not list a private instance field of a superclass. Property access to
such a field through the subclass, from a class of the same nest other than
the declaring class, was accepted by the type checker and then failed with a
MissingPropertyException. It is now reported as a missing property, as it is
for a superclass that encloses neither class. Static compilation still
accesses the field directly, and an inner class whose enclosing instances
lead to the declaring class still reaches it dynamically.
…ance

The body of an enum constant is an anonymous class created by the static
initializer of the enum, so it has no instance of the enum to fall back to.
ClassNodeUtils.hasNoEnclosingInstance did not say so, and the type checker
accepted access to a private instance field of the enum from the body, as
"z", "this.z" or "super.z", which then failed at run time with a
MissingPropertyException. "E.this" in the body is now a compile error
instead of a VerifyError.
…per in a nested subclass under type checking

The runtime falls back to the enclosing instance when a property read or
write fails in an inner class, but not for a write through "super"
(GROOVY-11823). The type checker accepted "super.z = value", "super.z += value"
and "super.z++" for a private field of the enclosing superclass from a
non-static inner subclass, which then failed with a MissingPropertyException.
They are now reported as a missing property. Static compilation still writes
the field directly, and "super.z" reads are unchanged.
…er of another class from an inner class under type checking

The runtime falls back to the enclosing instance of an inner class only when
the receiver is an instance of the calling class. The type checker accepted
"that.z", for a private field of an enclosing superclass, from an inner or
anonymous class whose enclosing instances lead to the declaring class, also
when "that" was not an instance of that class, and the access failed with a
MissingPropertyException. It is now reported as a missing property. An
implicit "z" that the checker resolves as "Outer.this.z" is still dispatched
on "this", so it is unaffected. Static compilation still accesses the field
directly.
… compilation

After master's GROOVY-12533 change, this.z in an enum constant body is
compiled through the enum instance under static compilation and fails
verification; that is GROOVY-12626 (apache#3152).
@codecov-commenter

codecov-commenter commented Oct 31, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.47059% with 4 lines in your changes missing coverage. Please review.
βœ… Project coverage is 74.4222%. Comparing base (ef76fcb) to head (4e75002).
⚠️ Report is 150 commits behind head on master.

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

Impacted file tree graph

@@                Coverage Diff                 @@
##               master      #3147        +/-   ##
==================================================
+ Coverage     74.1012%   74.4222%   +0.3210%     
- Complexity      43600      44399       +799     
==================================================
  Files            1692       1699         +7     
  Lines          149254     151084      +1830     
  Branches        28286      28798       +512     
==================================================
+ Hits           110599     112440      +1841     
+ Misses          28475      28376        -99     
- Partials        10180      10268        +88     
Files with missing lines Coverage Ξ”
...va/org/apache/groovy/ast/tools/ClassNodeUtils.java 85.5670% <100.0000%> (+0.0748%) ⬆️
...roovy/transform/stc/StaticTypeCheckingVisitor.java 88.1269% <75.0000%> (-0.0820%) ⬇️

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

Looks correct for GROOVY-12621 as a follow-on to GROOVY-12610.

Three remaining TC holes that still failed at run time are closed carefully: (1) enum constant bodies have no enclosing instance (EnumConstantClassNode in hasNoEnclosingInstance, so E.this becomes a compile error instead of VerifyError); (2) writes through super from a nested subclass are rejected (runtime does not fall back for super writes); (3) a receiver that is not derived from the calling class is rejected, with the checker-built implicit Outer.this.z marked so it stays dispatched on this. @CompileStatic continues to access the field directly via the SC overrides.

Related work: same design tension as #3137 vs Paul #3169 (MetaClass nest-mate reachability spike). Please coordinate land order / direction with #3169 before merging this stack, so TC rejection does not outlive a MetaClass change that would make these accesses succeed dynamically. Stacked on #3137 β€” land that (or an agreed #3169 path) first.

CI is fully green; the new STC / InnerClass / SC tests are clear.

The test used 'x' for the enclosing instance, the inner subclass instance
and the static nested subclass instance, so it could not tell which object
a read reached. With distinct values it asserts that type checking reads
the enclosing instance for this.z, z and super.z, while static compilation
reads super.z from this instance.
# Conflicts:
#	src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy
…alling class test

The test used 'x' for every object, so it could not tell which one a read
reached. With distinct values, and a receiver whose enclosing instance is
not the caller's, it asserts that type checking reads the field of the
receiver's enclosing instance, as dynamic Groovy does, while static
compilation reads the field of the receiver itself.
@testlens-app

testlens-app Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

βœ… All tests passed βœ…

🏷️ Commit: 4e75002
▢️ Tests: 35322 executed
βšͺ️ Checks: 26/26 completed


Learn more about TestLens at testlens.app/docs.

@codeconsole

Copy link
Copy Markdown
Contributor Author

@daniellansun On the land order: I answered this on #3137 (#3137 (comment)). In short, @paulk-asert's preference on #3169 is path (1) for 6.0.x regardless: keep the run-time behaviour and have type checking report the access. That is #3137 and then this PR, which is stacked on it. So the order I'd suggest is #3137, then #3147, both on master for cherry-picking to GROOVY_6_0_X. If path (2) is taken for Groovy 7, the rule is narrowed or dropped on master then, as Paul describes on #3169.

The run of these shapes against #3169 is in #3137 (comment): three of them still fail at run time under #3169 (a receiver that is not an instance of the calling class, a write through super in a non-static inner subclass, and an enum constant body), so those rejections would stay under (2) as well. The E.this compile error for an enum constant body is independent of the direction.

@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.

Thanks Scott β€” I re-checked tip 4e750024b432 against my earlier comment on 364d46348b4e.

The three type-checking closures are the same as before: an enum constant body has no enclosing instance, a write through super from a nested subclass is rejected, and a receiver that is not derived from the calling class is rejected, with the implicit Outer.this.z the checker builds still dispatched on this. @CompileStatic still accesses the field directly.

The new tests give each object its own value, including a that built on another enclosing instance. Under type checking, that.z and that.with { z } observe 'far' (the enclosing instance of that), not 'that', and the other forms observe 'outer'. The SC override pins the complementary split, where nest-mate access reads the field of the receiver itself. The old shared 'x' could not show either.

On the direction with #3169: as you set out here and on #3137, path (1) for 6.0.x is #3137 and then this PR, on master for cherry-picking to GROOVY_6_0_X. That is enough for me to approve. This one should still follow #3137. CI is green on this tip.

Approving.

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