Skip to content

GROOVY-12509, GROOVY-12510, GROOVY-12511, GROOVY-12513, GROOVY-12523: private members of nested classes and superclasses under static type checking and compilation - #3050

Open
codeconsole wants to merge 38 commits into
apache:masterfrom
codeconsole:stc-private-field-attribute

Conversation

@codeconsole

@codeconsole codeconsole commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

This pull request makes the type checker and static compilation follow Java's rules for private members between classes nested in the same top-level class: such classes can use each other's private members (JLS 6.6.1), but a private member is not inherited (JLS 8.2). Where @TypeChecked code is dispatched dynamically, it also stops accepting accesses that throw at run time because the meta-class of a subclass offers no private member of its superclass. It covers five issues, one commit or more each.

GROOVY-12509: private members of another class of the same nest

#3044 made a private nested type usable from every class of its nest. Private methods and constructors, and private accessors used through property syntax (box.x, box.y = v, Box.z), were still accepted only from the declaring class, the classes it encloses and its enclosing classes, so a sibling, cousin or nephew class got "Cannot find matching method/constructor" or "No such property". The JVM allows these calls between nestmates, and dynamic Groovy makes them. A private accessor is accepted through its own class only, so new Sub().x stays rejected when getX() is private in the superclass.

GROOVY-12510: a private method is not inherited

new Sub().im(), where im() is private in Box and Sub extends Box, compiled in the outer class of Box, in a class nested in Box, and as im() in a static subclass nested in Box. @TypeChecked then threw MissingMethodException, @CompileStatic called it, and javac rejects it. Method references and method pointers (Sub::im, new Sub().&im) behaved the same way. findMethod now drops a private method that the receiver type only inherits, before it selects an overload, and it invents a property accessor, for a call or a method reference, only where Verifier generates one, so an explicit private accessor of a property is not replaced by a public one. The calls dynamic Groovy runs keep compiling: those in the declaring class itself, private static methods, and calls in an enum constant body or an anonymous subclass created in a static context, which call the method on themselves. The method references and pointers dynamic Groovy runs keep compiling as well: this::helper in an enum constant body for a private method of the enum, and Sub::sm for a private static method of a class that encloses Sub. Calls through a receiver whose static type declares the method (a Box parameter, a cast to Box, super.im()) keep compiling too, because javac accepts them and @CompileStatic runs them. Dynamic Groovy, and with it @TypeChecked code, throws MissingMethodException for them when the object is a Sub. The second pass for a closure shared variable checks the call in the class that makes it.

GROOVY-12511: a nested subclass uses the enclosing instance

In a class nested in Box that also extends Box, an unqualified im(), or a private getter used as a property, refers to the enclosing Box instance, as javac, dynamic Groovy and @TypeChecked have it. @CompileStatic used the subclass instance, also for this.im() and in closures and lambdas, and this.om() in a plain inner class failed with GroovyCastException. The call writer now uses the enclosing instance, and this.p and this.q = v for a private accessor of the enclosing superclass resolve as p and q = v do; this.@p stays a field of this class.

Through any receiver, a method that the receiver lacks and an enclosing instance of it has is called on that enclosing instance, as dynamic Groovy calls it: other.im(), new Sub().im(), Sub.this.im(), this?.im(), other.with { im() }, a spread call, an operator such as other + x, other[i], x in other, other++ or --other, a public method of the outer class through a plain inner class, and a receiver of a subclass of the class being written. A compound assignment such as other += x uses a plusAssign method only of the receiver itself, as dynamic Groovy does, and otherwise plus, which may be one of the enclosing instance. A method of the receiver itself comes first, as dynamic Groovy only turns to the enclosing instance for a method the receiver lacks; this also fixes GROOVY-12637, where toString() in an inner class was the outer class's override under @CompileStatic. @TypeChecked also accepts other.p and other.q = v for a private accessor of the enclosing class through another receiver of the calling class, where the run time falls back to the enclosing instance (GROOVY-12621); static compilation rejects them. A private field of the enclosing class read through such a receiver under @CompileStatic is still the receiver's own field, as GROOVY-12621 has it.

For a private field, the type checker skips it only where dispatch is dynamic and cannot reach it (GROOVY-12610, GROOVY-12621), and such a skipped field hides a field of the same name in a superclass, as the meta-class does, but not an interface constant or a getter. Private static fields keep the behaviour they have on master.

GROOVY-12513: a variable declared with the field's class

Through a variable declared as Box that flow typing narrows to Sub (Box b = new Sub()), statically compiled code of Box's nest reaches the private members of Box, as javac does for the static type Box: b.f, b.@f, a private getter b.x, a private setter through b.y = v and b.y += v, a private method b.im(), the operators that call a private method of Box (b + x, b++, b[i], b += x, x in b), a compiler-supplied @ClassTag token and a closure shared variable. -b, +b, ~b and b[i] = v stay rejected, because static compilation calls their methods dynamically. Under @TypeChecked, which dispatches all of these on the meta-class of Sub, they are rejected instead of throwing at run time. A parameter or cast declared as Box is taken at its type in both modes.

GROOVY-12523: x.@name for a private field of a superclass

In a class nested in Outer, the type checker accepted sub.@f, where f is a private field of Outer and sub is typed as a subclass of Outer. Dynamic Groovy and @TypeChecked threw MissingFieldException, javac rejects it, and @CompileStatic read the field. Both modes now report "Cannot access field: f of class: Outer", also for writes, compound assignments, closures, lambdas, new Sub().@f, Sub.this.@f inside Sub and a receiver typed as a deeper subclass.

@TypeChecked
class Outer {
    private String f = 'outer'
    static class Sub extends Outer {
        String read(Sub sub) { sub.@f }  // threw MissingFieldException; now "Cannot access field: f of class: Outer"
    }
}

this.@f, Outer.this.@f and super.@f keep working, as do sub.@f in Outer itself and a receiver declared as Outer; under @CompileStatic, ((Outer) sub).@f reads the field. Private static fields are left alone.

The object orientation guide now says that classes nested in the same top-level class can use each other's private members, that private members are not inherited, and which receivers reach such a member in each mode, including the flow-typing split of GROOVY-12513 and the inner-class cases.

Behaviour change

This is a compatibility break for @CompileStatic code that compiled and ran, not only a rejection of what failed at run time, as GROOVY-12610 and GROOVY-12621 are.

  • These stop compiling under @CompileStatic, as javac rejects them: new Sub().im() for a private im() of a superclass outside the declaring class; method references and pointers to it such as Sub::im, and Sub::sm where the class of sm does not enclose Sub, also inside the declaring class; im() in a static subclass nested in the declaring class; a private getter of the superclass used as a property in a static nested subclass or an enum constant body; new Sub().setP(v) for an explicit private setter of a property of the superclass; and sub.@f. In an inner subclass, other.p and other.q = v for a private accessor of the outer class, which master ran on other itself, are reported as well.
  • Overload selection can change: with a public Sub.m(Object) and a private Box.m(String), new Sub().m('x') now selects Sub.m(Object), as javac, dynamic Groovy and @TypeChecked do. In an inner class, a call such as m('x'), toString() or other.m('x') selects an applicable method of the inner class before a more specific one of an outer class, and one of a nearer outer class before one of a farther one, also for implicit this.
  • In an inner class, a method that the receiver lacks and the outer class has, such as im(), this.im(), other.im(), new Sub().im(), Sub.this.im(), other + x or other++, and in an inner subclass p and this.p for a private getter, now run on an enclosing instance instead of on the receiver, as dynamic Groovy and @TypeChecked run them. other += x, which called a plusAssign of the outer class on other in both modes, now calls plus, here on the enclosing instance, as dynamic Groovy does; other[i]++ and other[i] += x read other[i] through the enclosing instance too.

Under @TypeChecked, the accesses above that threw at run time are reported at compile time.

Tests

FieldsAndPropertiesSTCTest, MethodCallsSTCTest and ConstructorsSTCTest, also run statically compiled by FieldsAndPropertiesStaticCompileTest, MethodCallsStaticCompilationTest and StaticCompileConstructorsTest, and MethodReferenceTest. The rejected forms fail without the change, and each is compiled in a script of its own. In bugs.RegressionTest, testGroovy12510, testGroovy12523 and testGroovy12637 now pass and are no longer marked @NotYetImplemented. The 18,765 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.

@codecov-commenter

codecov-commenter commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.34694% with 31 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.9723%. Comparing base (09e84fa) to head (57b71aa).
⚠️ Report is 6 commits behind head on master.

Files with missing lines Patch % Lines
...roovy/transform/stc/StaticTypeCheckingVisitor.java 89.2617% 2 Missing and 14 partials ⚠️
...groovy/classgen/asm/sc/StaticInvocationWriter.java 86.9565% 0 Missing and 6 partials ⚠️
...sc/StaticTypesMethodReferenceExpressionWriter.java 76.9231% 0 Missing and 3 partials ⚠️
...aus/groovy/transform/stc/SecondPassExpression.java 66.6667% 3 Missing ⚠️
...roovy/transform/stc/StaticTypeCheckingSupport.java 75.0000% 0 Missing and 2 partials ⚠️
...taticTypesBinaryExpressionMultiTypeDispatcher.java 92.8571% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##               master      #3050        +/-   ##
==================================================
+ Coverage     74.9518%   74.9723%   +0.0205%     
- Complexity      48908      49119       +211     
==================================================
  Files            1768       1768                
  Lines          161213     161453       +240     
  Branches        31728      31831       +103     
==================================================
+ Hits           120832     121045       +213     
- Misses          28968      28972         +4     
- Partials        11413      11436        +23     
Files with missing lines Coverage Δ
...m/sc/transformers/BinaryExpressionTransformer.java 93.7374% <100.0000%> (+0.0254%) ⬆️
...codehaus/groovy/transform/stc/ClassTagSupport.java 92.0290% <100.0000%> (ø)
...dehaus/groovy/transform/stc/StaticTypesMarker.java 100.0000% <100.0000%> (ø)
...taticTypesBinaryExpressionMultiTypeDispatcher.java 89.6739% <92.8571%> (+0.8504%) ⬆️
...roovy/transform/stc/StaticTypeCheckingSupport.java 81.0477% <75.0000%> (-0.0398%) ⬇️
...sc/StaticTypesMethodReferenceExpressionWriter.java 86.9919% <76.9231%> (+0.2975%) ⬆️
...aus/groovy/transform/stc/SecondPassExpression.java 65.2174% <66.6667%> (-13.7300%) ⬇️
...groovy/classgen/asm/sc/StaticInvocationWriter.java 78.7879% <86.9565%> (+0.5417%) ⬆️
...roovy/transform/stc/StaticTypeCheckingVisitor.java 88.0225% <89.2617%> (+0.1054%) ⬆️

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

@codeconsole
codeconsole marked this pull request as draft October 26, 2026 16:03
@codeconsole
codeconsole force-pushed the stc-private-field-attribute branch from 9cba923 to a2ad8c1 Compare November 22, 2026 09:40
@codeconsole
codeconsole marked this pull request as ready for review November 22, 2026 09:53
@codeconsole
codeconsole force-pushed the stc-private-field-attribute branch from 12bc47d to 99abb40 Compare November 22, 2026 10:19
@codeconsole codeconsole changed the title GROOVY-12523: STC: reject x.@name for a private field of a superclass when the type of x is a subclass GROOVY-12509, GROOVY-12510, GROOVY-12511, GROOVY-12513, GROOVY-12523: private members of nested classes and superclasses under static type checking and compilation Nov 22, 2026

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

Thank you, Scott — this is a careful split of the remaining nestmate / inheritance work after #3044, #3049 and the 12610/12621 field rules, and the tests do a really good job of pinning down where @TypeChecked and @CompileStatic must differ.

I went through tip 99abb400 against JLS 6.6.1 and 8.2, the open tickets, and current master. The #3044 claim checks out on master: filterMethodsByVisibility still drops a private method when the enclosing class is only a nestmate, and property-syntax accessors still go through hasAccessToMember, which does not treat a sibling as in-scope. What this PR adds for GROOVY-12509 therefore still looks necessary.

There is one must-fix before this can land.

In an inner subclass, a call to a private method of the enclosing class is rewritten to the enclosing instance only when the receiver is this (implicit or explicit). A non-this receiver is left as a direct invokevirtual on the subclass instance. That disagrees with dynamic Groovy and @TypeChecked, and it uses the wrong object.

With two enclosing boxes:

class Box {
    String id
    Box(String id) { this.id = id }
    private String im() { 'im:' + id }
    class Sub extends Box {
        Sub() { super('self') }
        String onOther(Sub other) { other.im() }
        String onNew() { new Sub().im() }
        String implicit() { im() }
        String explicit() { this.im() }
    }
    Sub make() { new Sub() }
}
def a = new Box('A')
def b = new Box('B')
def sa = a.make()
def sb = b.make()
[sa.implicit(), sa.explicit(), sa.onNew(), sa.onOther(sb), sb.onOther(sa)]

Dynamic Groovy and @TypeChecked both return [im:A, im:A, im:A, im:B, im:A]. @CompileStatic returns [im:A, im:A, im:self, im:self, im:self]. javap of Box$Sub.onOther is aload_1; invokevirtual im, and onNew likewise invokes im on the new Sub rather than on its enclosing Box. implicit() correctly does getfield this$0; invokevirtual Box.im. The redirect is in StaticInvocationWriter.writeDirectMethodCall, which only enters that path when isThisExpression(receiver) is true. The existing GROOVY-12511 tests cover im() and this.im(), but not other.im() or new Sub().im() from inside the inner subclass.

The keep-working case to preserve is new Sub().im() written inside Box itself (the declaring class), which should still run on that Sub instance.

The rest of the design generally looks right to me:

  • Nestmate private methods, constructors and property-syntax accessors are visible (GROOVY-12509), but not through a receiver that only inherits them.
  • A private method is not a member of a subclass (GROOVY-12510), with the keep-working cases that dynamic Groovy already runs (a call from the declaring class, a private static method through a subclass, a receiver typed as the declaring class, and an enum constant body or anonymous subclass with no enclosing instance). Method references and pointers are tighter, including Sub::im / Sub::sm inside the declaring class, which matches javac and the note that dynamic Groovy fails on those.
  • An inner or anonymous subclass now uses the enclosing instance for im() and this.im() / this.p (GROOVY-12511). this.im() remains a Groovy extension — javac would reject it — and following dynamic Groovy here seems right. The hole is the non-this receiver case above.
  • Flow typing of Box b = new Sub() reaches the private members of Box under @CompileStatic (javac’s static type) and is rejected under @TypeChecked, where the meta-class of Sub cannot see them (GROOVY-12513). Parameters and casts that are not narrowed stay taken at the declared type in both modes.
  • sub.@f and Sub.this.@f for a private superclass field are now compile errors in both modes (GROOVY-12523); this.@f, super.@f and access from the declaring class itself are kept.

I also want to be explicit about the @CompileStatic compatibility break, because it is stronger than GROOVY-12610 / GROOVY-12621: this is not only “reject what already failed at run time”. new Sub().im() outside the declaring class, Sub::im / Sub::sm, sub.@f, and some private getters used as properties in a static nested subclass or enum constant body stop compiling; overload selection through a subclass can change; and an inner subclass’s im() / this.im() / p / this.p now run on the enclosing instance. That seems correct, but it is a behaviour change for code that compiled and ran under @CompileStatic.

One smaller request: the new paragraph in core-object-orientation.adoc is easy to read as broader than the tests. “The meta-class of a subclass offers none of its superclass” is missing “private members”; the “except in Base itself” wording leaves out the no-enclosing-instance case; and “sub.name reads the field in Base and in the classes nested in it” can be taken to mean that a Sub-typed receiver always reaches the private field under @CompileStatic, which the sibling new Sub().f tests reject. It would also help to state the GROOVY-12513 flow-typing split in the guide.

A typo in the PR description, if you are editing it anyway: dynamic Groovy does not run super.im() or ((Box) sub).im(); both throw MissingMethodException. @CompileStatic and javac run them.

I have not changed GROOVY-12509 (already Resolved for #3044, with a note that the rest would follow). If this work lands, a short comment on that ticket pointing here would be enough; GROOVY-12510, 12511, 12513 and 12523 are the ones still open.

The PR is about 30 test-only commits behind current master; I did not see any overlap in the STC/SC production files. CI on this tip looks green.

Thank you again for the increment size and for keeping the @TypeChecked and @CompileStatic cases honest.

@codeconsole

Copy link
Copy Markdown
Contributor Author

Thank you for the careful review.

The non-this receiver case is fixed in 07dce78 and generalized in 5adeb0e. When the type checker selects a method that the receiver lacks and an enclosing instance of it has, it marks the call with the receiver type. The call writer then calls the method on that receiver's enclosing instance, through its this$0 chain. Your script now gives [im:A, im:A, im:A, im:B, im:A] under @CompileStatic too.

The same holds for:

  • Sub.this.im();
  • a closure, a native lambda, a safe call (also this?.im()) and a spread call;
  • a closure delegate (other.with { im() });
  • a class nested in Sub, and a receiver of a subclass of Sub;
  • an anonymous class created in a closure;
  • a plain inner class, also for a public method of the outer class;
  • the operators other + x, other[i] and x in other.

A method of the receiver itself comes first, as dynamic Groovy only turns to the enclosing instance for a method the receiver lacks: with a public Sub.m(Object), other.m('x') calls it rather than a private Box.m(String). new Sub().im() written in Box itself still runs on that Sub. Box x = other; x.im() and ((Box) other).im() keep calling on the object under @CompileStatic, as javac does for the static type Box (GROOVY-12513). testCallToPrivateMethodOfEnclosingClassThroughOtherReceiverInInnerSubclass and testCallToMethodOfEnclosingInstanceOfReceiver cover these, and both fail without the change.

For property syntax, @TypeChecked accepts other.p and other.q = v for a private accessor of the enclosing class through another receiver of the calling class (69f2236), where the run time falls back to the enclosing instance (GROOVY-12621). @CompileStatic reports "No such property" for them instead of using the receiver, as master did. For a private field, other.f under @CompileStatic still reads other's own field, as GROOVY-12621's testPrivateFieldOfSuperclassViaReceiverOfCallingClass pins it, so for a non-this receiver methods and fields differ under static compilation. Aligning the fields would mean changing that master test.

The guide paragraph is reworded in 28583c9 and c51a496: "none of the private members", the enum constant body and anonymous-subclass-in-a-static-context exception, sub.name limited to Base and the classes nested in it, the GROOVY-12513 flow-typing split restricted to private instance members outside Base, private static members staying reachable, and the inner-class cases.

You are right about super.im() and ((Box) sub).im(): dynamic Groovy and @TypeChecked throw MissingMethodException for both, as for a Box parameter that holds a Sub. Only @CompileStatic and javac run them. The description is corrected, and it now states the @CompileStatic compatibility break explicitly.

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

Thank you, Scott — the follow-up work on tip c51a496e addresses the must-fix from the review of 99abb400, and the new tests pin the cases down carefully.

I re-checked the non-this receiver path independently against the nine new commits and against your list. The type checker now marks a call when the selected method is one of an enclosing instance of the receiver, and StaticInvocationWriter rewrites it through that receiver's this$0 chain (including an anonymous class created in a closure). The script from the earlier review now returns [im:A, im:A, im:A, im:B, im:A] under @CompileStatic as well. The same holds for Sub.this.im(), closures, native lambdas, safe and spread calls, other.with { im() }, a class nested in Sub, a receiver of a subclass of Sub, a plain inner class (including a public method of the outer class), and the operators other + x, other[i] and x in other. A method of the receiver itself comes first, so other.m('x') selects public Sub.m(Object) rather than private Box.m(String). new Sub().im() written in Box itself still runs on that Sub. Box x = other; x.im() and ((Box) other).im() keep calling on the object under @CompileStatic, as javac does for the static type Box.

The property-syntax split you describe is consistent with the tests and with GROOVY-12621: @TypeChecked accepts other.p and other.q = v for a private accessor of the enclosing class, @CompileStatic reports “No such property” instead of using the receiver, this.@name stays a field of this class, and a private field read through such a receiver under @CompileStatic is still the receiver's own field. Aligning the fields would be a separate change to that master behaviour; it does not need to block this work. The invented-accessor, shared-variable second-pass, and private-setter-of-declared-type fixes look right as well, and the guide now states the flow-typing split, the no-enclosing-instance exception, the inner-class cases, and that private static members stay reachable. Thank you also for correcting the description of super.im() and ((Box) sub).im().

There is one remaining must-fix before this can land.

Current master already contains src/test/groovy/bugs/RegressionTest.groovy, which this branch does not yet include. After a merge, three methods marked @NotYetImplemented pass, and CI on this tip already reports that on the LTS jobs (TestLens, 0% flakiness):

  • testGroovy12510 — this is a case this PR fixes: new Sub().im() from a nestmate of Base is now a compile error under both @TypeChecked and @CompileStatic.
  • testGroovy12523 — likewise this PR: sub.@f now reports “Cannot access field: f of class: Outer”, which matches the test's message check.
  • testGroovy12637 — not in the original ticket list, but the pass is a genuine consequence of the “method of the receiver comes first” rule in 5adeb0e. Unqualified toString() inside a named or anonymous inner class is no longer taken from the outer class's override, because the inner class already inherits toString() from Object. The assertion != 'C' is the right direction.

Please update the branch onto current master and drop @NotYetImplemented from those three methods, without weakening the assertions. testGroovy12511 and testGroovy12513 in the same file should be left as they are: they still fail, and their expected results do not match this design (the 12511 script expects the enclosing class's im() even when Sub and the anonymous class declare their own; the 12513 script expects @TypeChecked to accept Box b = new Sub(); b.f, which this PR correctly rejects). Those two will not break CI.

Two smaller wording nits, not merge blockers once the tests are updated: in the object-orientation guide, the sentence “It finds the field through sub.name…” no longer has a clear antecedent after “Private static members of Base stay reachable…”. And the javadoc on StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER still describes a private inherited method and “that outer class”, whereas the value stored is the receiver type used for selection, and the rule now covers any method of an enclosing instance.

I have not changed JIRA. GROOVY-12509 remains Resolved for #3044; GROOVY-12510, 12511, 12513 and 12523 are the open tickets this PR targets. When this lands, GROOVY-12637 could be noted as well, since that residual case is now fixed.

Thank you again for the thorough follow-up.

@codeconsole

Copy link
Copy Markdown
Contributor Author

Thank you. The branch is updated onto current master by a merge in 40c262d; there were no conflicts. ffbb294 drops @NotYetImplemented from testGroovy12510, testGroovy12523 and testGroovy12637, with the assertions unchanged. On the merged tree those three were the only RegressionTest failures, and the whole class now passes. testGroovy12511 and testGroovy12513 stay as they are. Both wording nits are fixed in 86afb3f: the guide sentence now reads "Dynamic code finds a private field of Base through sub.name only in Base or in an inner class whose enclosing instance is a Base", ahead of the one on private static members, and the javadoc of StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER now describes any call or operator whose method is one of an enclosing instance of the receiver, with the receiver type as its value.

@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 went through 86afb3ff again. The earlier functional request is done: @NotYetImplemented is gone from testGroovy12510, testGroovy12523, and testGroovy12637 only, with the assertions unchanged, and testGroovy12511 and testGroovy12513 stay marked. CI on this tip is green. I am not approving yet, because the javadoc still does not describe the rules this change introduced.

StaticTypeCheckingVisitor.findMethod is the method that now drops a private method a receiver only inherits (JLS 8.2), keeps a method of the variable's declared type, and offers methods of an enclosing instance when the receiver is a type of the current class. Its javadoc is still only "Finds candidate methods matching the supplied receiver, name, and argument types." Please document those rules, including that method references and pointers do not get the same exceptions as a call, because dynamic Groovy fails on those.

SecondPassExpression now also stores declaredReceiverType and enclosingClass so the second pass can find the same private members as the first pass. The class javadoc still mentions only closure-shared variables and argument types, and the four-argument constructor has no javadoc. Please document the new fields and that constructor. equals and hashCode still compare only the wrapped expression and the auxiliary data; if that is intentional, the javadoc should say that the new fields are excluded, and why.

isInheritedPrivateMethod is a new public @Internal API. The prose talks about a private method inherited from a superclass, but @return says "true if the method is private and declared by another class," and the body also excludes an ExtensionMethodNode. Please make the javadoc match the implementation.

Two private helpers that encode the same declared-type rule, StaticTypesMethodReferenceExpressionWriter.findVisibleMethods and getDeclaredType, have no javadoc. The three-line comment in findVisibleMethods should be a proper javadoc, and getDeclaredType should say that it returns the origin type of a non-this, non-super variable, or null. The two-argument thisObjectExpression overload should point at the three-argument method, or say that it allows a subclass enclosing instance.

The wording of ENCLOSING_INSTANCE_OF_RECEIVER is accurate now. A short multi-line comment, in the same shape as the neighboring markers, would be easier to read, but that is optional.

Master has moved by one commit since this branch was updated (4f83940a, GROOVY-12727). A merge of that commit onto this tip is clean; I don't need another rebase for that.

@codeconsole

Copy link
Copy Markdown
Contributor Author

Thank you. All of these are in a851725, with one more in af95df5.

  • findMethod: its javadoc now states the rules. A private method the receiver only inherits is not a candidate (JLS 8.2). It is kept when it is declared by the declared type of the receiver variable (known only under static compilation), when it is static, when the call is made in its declaring class, and when the receiver is an enum constant body or an anonymous class created in a static context nested in its declaring class. When the receiver is a class whose code this is, or an inner class that is a subclass of one, and none of its own methods accepts the argument types, the methods of its outer classes are offered too, only the static ones beyond a class with no enclosing instance, as ENCLOSING_INSTANCE_OF_RECEIVER records. It also says that a method pointer or reference is resolved elsewhere, without the exceptions for a static method, the declaring class and an instance with no enclosing instance, because dynamic Groovy fails on those.
  • SecondPassExpression: the class javadoc now explains the declared receiver type and the enclosing class, and why the second pass needs them to find the same private members. The four-argument constructor documents each parameter. Leaving them out of equals and hashCode is intentional, and the javadoc now says why: both follow from the wrapped expression, which is one node of one class with one receiver variable, so two wrappers of the same expression never differ in them.
  • isInheritedPrivateMethod: the javadoc and @return now say what the body checks: the method is private, is not an extension method, and is declared by a class other than the receiver type. It goes on to say that for a method found on that type or its superclasses, this is a private method the receiver would only inherit.
  • findVisibleMethods has javadoc in place of the inline comment, including that a static method or a reference made in the declaring class is no exception there, unlike a call. getDeclaredType says it returns the origin type of a variable that is not this, super or a dynamic variable, or else null. The two-argument thisObjectExpression says it allows an enclosing instance of a subclass of target and links to the three-argument method.
  • findMethodWithDeclaredType, the helper that findMethodThrough and the second pass go through, had no javadoc either; af95df5 adds it.

I left ENCLOSING_INSTANCE_OF_RECEIVER as a one-line comment, since every neighbouring marker in StaticTypesMarker is one; I can split it if you would still like that. I also merged current master, including 4f83940 (GROOVY-12727), in 16dddda; there were no conflicts, and since that commit also changes StaticTypeCheckingVisitor, I ran the core tests, the subproject tests, Checkstyle and CodeNarc on the merged tree, and all pass.

@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. The member-rule comments now match the code, including findMethod, findMethodWithDeclaredType, removeInheritedPrivateMethods, isInheritedPrivateMethod, SecondPassExpression, and the method-reference helpers. The enclosing-instance rewrite for other.im() holds, including the call written in Box itself.

One functional gap is still open. ++ / --, and a compound assignment that selects a *Assign method, resolve to a method of an enclosing instance and then invoke it on the inner receiver. findMethodOrFail records ENCLOSING_INSTANCE_OF_RECEIVER only on a binary expression, and neither writePostOrPrefixMethod nor emitCompoundAssignCall rewrites the receiver. In an inner subclass, that is a silent call on the wrong instance. other + x is already covered by testCallToMethodOfEnclosingInstanceOfReceiver; I would like a test next to it for other++ and other += x before this lands.

Please sync master with rebase rather than merge. This tip currently includes a merge of 4f83940a.

Small doc follow-up on that same pass: findVisibleMethods should also say that an enum-constant body or an anonymous class with no enclosing instance is not an exception for a method reference, matching findMethod.

@codeconsole

codeconsole commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you. The ++ / -- gap was real and is fixed in 921ac87, with testOperatorOfEnclosingInstanceOfReceiver next to testCallToMethodOfEnclosingInstanceOfReceiver.

  • other++, ++other, other-- and --other: under @CompileStatic they called Box.next() on other itself (next:self), where dynamic Groovy and @TypeChecked call it on the enclosing instance (next:B). The type checker now records ENCLOSING_INSTANCE_OF_RECEIVER on ++ and -- as findMethodOrFail does on a binary operator, and StaticTypesBinaryExpressionMultiTypeDispatcher.writePostOrPrefixMethod passes it to the next() or previous() call, which StaticInvocationWriter then makes on the enclosing instance. The test covers the four forms, the value of other++, a this operand, an array element array[0]++, and a property holder.sub++.
  • other += x is different from what the comment suggests: dynamic Groovy never calls a *Assign method of an enclosing instance. ScriptBytecodeAdapter.compoundAssign and IndyCompoundAssign.resolve use plusAssign only when the receiver's own meta-class responds to it (respondsTo, which does not reach the enclosing instance), and otherwise call plus through invokeMethod, which does. So the type checker now keeps a *Assign method only if it is one of the receiver itself, and other += x otherwise becomes other = other + x, with plus called on the enclosing instance as for other + x. Before, both @TypeChecked and @CompileStatic called Box.plusAssign on other. 034df1e extends this to a static plusAssign of an outer class, which item += 'x' also picked.
  • A subscript operand was a gap of the same kind: other[0]++ and other[0] += x, with a private getAt of Box and a putAt of Sub, read other[0] through other's own getAt under @CompileStatic, although a plain other[0] already read it through the enclosing instance. In 034df1e the type checker records that getAt on an assigned subscript, and the static writer reads with it while the write stays other.putAt; testSubscriptUpdateWithGetAtOfEnclosingInstance covers ++, -- and +=.

Testing the neighbours of these turned up five more cases, each with a test that fails without its fix and gives the asserted values when run dynamically:

  • 2c03ea1: this::helper and this.&helper in an enum constant body for a private method of the enum, and Sub::sm / Sub.&sm for a private static method of a class that encloses Sub, run in dynamic Groovy and compiled on master; this change had rejected them. They compile again; a reference through Sub to a private static method of a sibling Box, which dynamic Groovy fails on, stays rejected. The guide no longer says that every private static member of Base stays reachable through Sub, since property syntax Sub.name does not reach a private static field or getter.
  • 2889534: this.im() in a closure in an anonymous class created in a closure cast the outer closure to the outer class under @CompileStatic; the this$0 walk now goes through the closure's this object, as the walk for another receiver already did.
  • d8c93cb: Box b = new Sub(); b.p = 'x' called a private Box.setP(Object) instead of Sub.setP(String) under @CompileStatic, unlike b.setP('x').
  • e024391: the enclosing-instance lookup now goes from the nearest outer class out and stops at the first with an applicable method, as dynamic Groovy does (Middle.m(Object) before Outer.m(String)), and in a static method an instance method of the class no longer blocks a static method of an outer class (m('x') calling Outer.m(String), as on master).
  • 57b71aa: a private isReady() of a superclass no longer hides its public getReady() from new Sub().ready.

The 18,765 core tests, the subproject tests, Checkstyle and CodeNarc pass, and every commit compiles on its own. The description is updated for these.

The findVisibleMethods javadoc, in 343dd5c and 2c03ea1, now states which private methods a reference keeps: as for a call, a private method of the enum of an enum constant body and a private static method of an enclosing class; unlike a call, no other private static method, and none for a reference made in the declaring class or on an anonymous class created in a static context.

The branch is now rebased onto current master (4f83940), as you asked, in place of the merges: 38 commits and no merge commits, with a tree identical to the tip that was tested; the commit ids above are those of the rebased branch.

…a subclass receiver

A private method is not inherited (JLS 8.2), but the type checker found
it through a subclass whenever the caller could see the method: in the
outer class of Box, new Sub().im(), where im() is private in Box and
Sub extends Box; in a class nested in Box, the same call; and in a
static subclass nested in Box, im() or this.im(). @TypeChecked compiled
such a call and it then failed with MissingMethodException, because
dynamic Groovy does not find a private method of a superclass either.
@CompileStatic called it directly. javac rejects it. Method references
and method pointers (Sub::im, new Sub()::im, Sub::sm, new Sub().&im)
behaved the same way, and method pointers failed at run time even under
@CompileStatic.

findMethod now drops a private method that the receiver type only
inherits, before it selects an overload, so these calls fail with
"Cannot find matching method" and a public overload of the subclass is
selected as javac selects it. Method references and pointers drop it
too, in the type checker and in the method reference writer (which is
where @CompileStatic reports an unresolved method reference).

These calls keep compiling, because dynamic Groovy runs them:
- calls in the declaring class itself, including its closures and
  lambdas: inside Box, new Sub().im() works in all three modes;
- private static methods through a subclass (Sub.sm(), sm() in a
  subclass).
These keep compiling because the receiver's type declares the method:
a Box parameter or method result, a cast to Box, super.im(), and a
variable declared as Box even when flow typing narrows it to Sub
(Box b = new Sub(); b.im()). An anonymous subclass nested in Box still
finds the method on its enclosing instance, and an enum constant body
or an anonymous subclass created in a static context, which have no
enclosing instance (GROOVY-12621), call it on themselves, as dynamic
Groovy does.

Method references and pointers get no such exceptions, because dynamic
Groovy fails on them even in the declaring class: Sub::im and Sub::sm
are rejected inside Box as well.

Under @CompileStatic this stops compiling: new Sub().im() and the
method references above in the outer class of Box or in a class nested
in Box, also through a def variable, a with { } delegate or an
instanceof check on an Object; Sub::im, new Sub()::im and Sub::sm
inside Box; and im(), this.im() and new S().im() in a static subclass
S nested in Box, as in

    class Shape {
        private String helper() { 'helper' }
        static class Circle extends Shape {
            String area() { helper() }
        }
    }

where javac reports that helper() cannot be referenced from a static
context. With a public Sub.m(Object) and a private Box.m(String),
new Sub().m('x') now selects Sub.m(Object), as javac, dynamic Groovy
and @TypeChecked do.
…class of the same nest

Under @TypeChecked and @CompileStatic, a private method or constructor
of a nested class could be used only from its declaring class, from the
classes it encloses and from its enclosing classes. Java allows any
class nested in the same top-level class (JLS 6.6.1), and the JVM
allows it between nestmates (JEP 181), which Groovy's minimum target of
17 always provides. Code generation already treats the nest as one unit
(AsmClassGenerator.isMemberDirectlyAccessible), and the type checker
already does for fields (GROOVY-12290). Only filterMethodsByVisibility
still used the older rule, so a sibling, cousin or nephew class was
rejected with "Cannot find matching method/constructor", and a method
reference such as Box::sm passed @TypeChecked but failed in the
@CompileStatic writer with "Failed to find class method".

filterMethodsByVisibility now admits a private method or constructor
when the caller and the declaring class have the same nest host, using
the same predicate as code generation. The calls compile to direct
INVOKESTATIC, INVOKEVIRTUAL and INVOKESPECIAL instructions, also from a
closure, a lambda, an anonymous class or a trait of the nest. A class
of another nest is still rejected. A private method of a superclass
stays out of reach through a subclass from the new callers as well
(GROOVY-12510); its tests now also cover a sibling of the declaring
class.

Under @CompileStatic this changes which overload some calls select,
because the private candidate used to be filtered out. The new choice
is the one javac, dynamic Groovy and @TypeChecked already make:
private Box(String) over Box(Object) for new Box('x'), a private
m(String) of the receiver's class over an inherited m(Object), a
private method of a with { } delegate over an owner method of the same
name, and private m(int) over m(Object) for m(1).
…me nest through property syntax

Property syntax checked a getter or setter with hasAccessToMember, which
knows only "the declaring class and the classes it encloses", so
box.x, box.y = v and Box.z failed with "No such property" when getX,
setY or getZ is private and the caller is a sibling nested class, or
even the outer class of Box. Dynamic Groovy calls the private accessor
in all of these places, and javac allows the equivalent method calls
(JLS 6.6.1).

isAccessibleAccessor now admits a private accessor from any class of
its nest, but only through its own class: private members are not
inherited (JLS 8.2), so new Sub().x still fails when getX is private in
the superclass, and new Sub().f still fails for a private field.
hasAccessToMember itself is unchanged; giving it a nest clause would
also admit private fields through a subclass receiver.

Under @CompileStatic, a nestmate that reads or writes a private field
through property syntax now calls the private getter or setter of the
same name when there is one, instead of the field. Dynamic Groovy and
@TypeChecked already call the accessor there.
…the outer class

A class nested in Box that also extends Box does not inherit the
private members of Box (JLS 8.2), so in it an unqualified im(), or a
private getter used as a property (p for getP()), refers to the
enclosing Box instance, as if written Box.this.im(). javac, dynamic
Groovy and @TypeChecked use the enclosing instance. @CompileStatic
called them on the subclass instance instead, in an inner class
Sub extends Box, for this.im() and in closures and lambdas. Separately,
this.om() in a plain inner class, where om() is a method of the outer
class, failed with GroovyCastException.

GROOVY-12510 makes the type checker find such a private method on the
enclosing class only. The call writer now also calls it on the
enclosing instance when the subclass has one, and calls this.name() on
the enclosing instance when the method belongs to an outer class. An
enum constant body has no enclosing instance; it still calls the
private methods of its enum on itself, as every mode does.

For property syntax, the type checker now skips a private field or
accessor that the receiver type only inherits, unless the code is in
the declaring class, and finds the outer class's member as
Outer.this.name. A field is skipped only where dispatch is dynamic and
cannot reach it, as GROOVY-12610 reports: static compilation uses the
field directly from the classes of its nest (GROOVY-12600,
GROOVY-12626), and this.name or a bare name in a class nested in the
declaring class is left to GROOVY-12533, which reads the field of the
enclosing instance, or of this instance where there is none.

Under @CompileStatic this stops compiling: a private getter of the
superclass used as a property in a static nested subclass or an enum
constant body, which has no enclosing instance to use. @TypeChecked
compiled it too, and it threw MissingPropertyException at run time, as
in dynamic Groovy; both modes now report "No such property".
…e when flow typing narrows the variable

A private method of Box is found through a variable declared as Box
even when flow typing narrows it to a subclass (Box b = new Sub();
b.im()), because the declared type declares the method. A private
field or accessor of Box was not: b.f, b.f = v, b.f += v, b.@f and
b.x (with a private getX()) failed with "No such property: f for class:
Sub" or "Cannot access field", also inside a closure or lambda and when
a Box parameter was narrowed by instanceof. Through a parameter
declared as Box, which flow typing does not narrow, the same access
compiled. javac accepts it, because the static type of b is Box.

Property lookup now treats a private field or accessor declared by the
variable's declared type like one of the receiver type itself, for the
inherited-member rule and for the field access check. A receiver whose
type is only the subclass, such as new Sub().f or a def variable, is
still rejected, because a private member is not inherited.

@TypeChecked accesses such a property dynamically, and the meta-class
of Sub offers no private field of Box, so there GROOVY-12610 still
rejects b.f; the test of the type-checked script expects those errors.
…ween nested classes

The "Inner class" section said only that an inner class can use the
private members of its enclosing class. State that, as in Java, all
classes nested in the same top-level class can use each other's private
members, that private members are not inherited, so they cannot be used
through a subclass receiver except in the declaring class, and that an
unqualified name of such a member in a nested subclass refers to the
enclosing instance.
… through a subclass

The rule that a private field of the superclass is not found through a
subclass, so that a name in a nested subclass refers to the enclosing
instance, also dropped private static fields: Sub.sf, Sub.sf = v and
new Sub().sf in a static class Sub nested in Outer, or Sub.sf in a
sibling, failed with "No such property" under @TypeChecked and
@CompileStatic, where 6.0.0 and dynamic Groovy run them. The rule now
leaves static fields alone, as GROOVY-12510 leaves private static
methods.
… when the type of x is a subclass

A private field is not a member of a subclass (JLS 8.2), and the
meta-class of a subclass offers no private field of its superclass, so
sub.@f, where f is private in Outer and sub is typed as a subclass of
Outer, throws MissingFieldException in dynamic Groovy and under
@TypeChecked, in every version. The type checker accepted it in a class
nested in Outer, through the rule that a nested class sees the private
members of its outer class; with f in a nested class Box and Sub
extending Box, the same access was already rejected. It now reports
"Cannot access field: f of class: Outer", as javac reports that f has
private access, also for a write, a compound assignment, a closure, a
lambda, new Sub().@f and a receiver typed as a deeper subclass.

this.@f and super.@f, which read the field directly in every mode,
keep working, as do sub.@f in Outer itself and a receiver declared as
Outer or cast to it. Private static fields are left alone, as private
static methods are.

Under @CompileStatic, which read the field directly, such code stops
compiling; ((Outer) sub).@f reads it. Groovy 4.0.33 failed at run time
in every mode.
…rectly

The guide said that only this.@name and super.@name reach a private field of
Base from within Sub. Static compilation also reaches it through a receiver
typed as Base, as in ((Base) other).@name.
… as internal

It is a helper for the type checker and the method reference writer, which
are in different packages, so it stays public but is not public API.
… in statically compiled code of its nest

A private field, accessor or method of Box was found through a variable
declared as Box that flow typing narrows to Sub in every mode. Under
@TypeChecked the access is dispatched dynamically, and the meta-class of
Sub offers no private member of Box, so b.@f, b.x and b.im() compiled
and then threw MissingFieldException, MissingPropertyException or
MissingMethodException. For a field, the declared type also counted from
a class of another nest: Base b = new Base.Sub(); b.@f in a top-level
class compiled in both modes and failed at run time, where master
reports "Cannot access field: f of class: Base".

The declared type now counts only where dispatch is static, and for a
field only from a class of the field's nest. A method reference keeps
it: b::im with Box b = new Sub() runs under @TypeChecked, as
MethodReferenceTest shows. A parameter or cast declared as Box is still
taken at its type, as GROOVY-12610 does for b.f.

The type-checked tests now compile each rejected access in a script of
its own, so that every one of them has to be rejected: with several in
one script, shouldFailWithMessages found one error for repeated messages,
and past ten errors the compiler reports no more. The statically
compiled tests still run the accesses.
… operators, @ClassTag and shared variables too

Under static compilation, a private method of Box was found through a
variable declared as Box that flow typing narrows to Sub only for an
explicit call. Every other lookup for the same receiver dropped it:

- an operator: b + 'x' for a private plus(String), b++, b[1],
  b += 'y' for a private plusAssign, and 'in' in b, which then bound
  the GDK isCase and returned false instead of calling Box.isCase;
- the retry with a compiler-supplied @ClassTag token, b.token(), while
  b.token(String) compiled; the overload to retry was also chosen
  among private methods the subclass only inherits;
- the second pass for a closure shared variable assigned Sub and then
  Sub2, which looked the call up again on Sub without the declared type.

Each of these lookups now takes the declared type as the call does.
The second pass gets it from where the first pass recorded the
expression, in its scope. -x, +x, ~x and x[i] = v are left alone:
static compilation calls their methods dynamically, so they stay
rejected, as under type checking.
…uperclass hide a field of the same name further up

Where dynamic dispatch cannot reach a private field of Base through a
subclass, the property lookup skips it and goes on to the superclasses
of Base. With a public field f in Parent, which the private f of Base
hides, s.f in a static nested subclass Sub of Base then compiled under
@TypeChecked as a read of Parent.f, and threw MissingPropertyException:
the meta-class of Sub offers neither field. Master rejects it.

The skipped field now ends the search for a field of that name for the
receiver; accessors are still looked up. Static compilation reads
Base.f, as before.
…ng superclass through the enclosing instance

In an inner subclass Sub of Outer, a private getP() or setQ() of Outer
is not inherited, so the property lookup on Sub drops it. For p and
q = v the lookup then tries the enclosing instance, as dynamic Groovy
does, but for this.p and this.q = v it did not, and both were rejected
with "No such property" in either mode. Master accepted them; dynamic
Groovy uses the enclosing instance's property.

The enclosing-instance pass now also runs for an explicit "this", for an
enclosing class that this class extends. In an inner class that does
not extend it, this.name still means only this class's own property.
…s field through a subclass

The guide said that a private field of Base cannot be used through a Sub
receiver anywhere but in Base. Static compilation reads sub.name in Base
and in the classes nested in it (GROOVY-12600, GROOVY-12610), and an
inner class that extends Base reaches the field through its enclosing
instance in every mode. The paragraph now keeps sub.@name apart from
sub.name and says what each mode reaches, including the members of a
variable declared as Base under static compilation.
…skipped private field of a superclass

The skipped private field of Base hides a field of a superclass from
dynamic dispatch, but not a constant of an interface that Base
implements: s.f for a static nested subclass Sub reads I.f there.
Type checking rejected it, as master does. The skipped field now ends
the search through superclasses only. A getter of a superclass, which
master rejected too, was already found past the field; the test covers
both.
…uperclass

With GROOVY-12514 on master, Sub.this compiles inside Sub. It is a
receiver of type Sub, not "this", so Sub.this.@f for a private field f
of the superclass is rejected as sub.@f is: dynamic Groovy throws
MissingFieldException for it, as for sub.@f, while this.@f and
Outer.this.@f read the field. On master @TypeChecked compiled it and
threw at run time, and @CompileStatic read the field. The test now has
the read, the write, a closure and an inner subclass.
… enclosing instance of a receiver other than this

In an inner subclass Sub of Box, the type checker finds a private
method im() of Box through a receiver of type Sub only as a method of
the outer class: Sub does not inherit it (JLS 8.2). Dynamic Groovy and
@TypeChecked call it on the receiver's enclosing instance. Static
compilation sent the call to the enclosing instance only for "this";
other.im(), new Sub().im() and Sub.this.im() called im() on the Sub
instance itself, also in a closure, a lambda, a safe call, a spread
call and a class nested in Sub, so they returned the subclass
instance's state.

The type checker now marks such a call with the outer class, and the
call writer calls the method on the enclosing instance of the receiver,
through its chain of this$0 fields. In Box itself, sub.im() stays a
call on sub, and so does a call through a variable declared as Box
under static compilation (GROOVY-12513).
…rclass member in each mode

The paragraph said that the meta-class of a subclass offers none of its
superclass, where it offers none of its private members; that a private
method is called through a subclass receiver only in the declaring
class, leaving out an enum constant body or an anonymous subclass
created in a static context, which call it on themselves; and that
sub.name reads the field in the declaring class and in the classes
nested in it, which reads as if a subclass receiver always reached it
under static compilation, where another class of the nest is rejected.

It now says so, and states the GROOVY-12513 split: under static
compilation a variable declared as Base reaches the private members of
Base where flow typing knows it holds a Sub, as in Java, while dynamic
code does not find them and @TypeChecked rejects such a use. It also
says that other.secret() in an inner subclass uses the enclosing
instance of other.
…lookup

The enclosing-instance pass for an explicit "this" also ran for an
attribute expression, so this.@p in an inner subclass of Outer, where
Outer has a private getP() and no field p, compiled: static
compilation called the getter of the enclosing instance, and
@TypeChecked threw MissingFieldException at run time, as dynamic Groovy
does. this.@name names a field of this class; it is now reported as
"No such attribute" again, as on master.
…t it

With a property p of Box and an explicit private setP(), the inherited
private setter is dropped for a Sub receiver, and findMethod then
invented a public setP for the property in its place: new Sub().setP(x)
in another class of the nest compiled, static compilation called the
private setter, and @TypeChecked threw MissingMethodException, as
dynamic Groovy does; master rejects the call. A method reference such
as new Sub()::setP, Sub::setP or new Sub()::getQ, for an explicit
private getQ(), passed @TypeChecked the same way, through the accessor
invented for a property method reference (GROOVY-10741).

Both now invent an accessor only if Verifier will generate it: a getter
as generatesPropertyGetter decides, and a setter where the property is
not private and no setter it cannot replace is declared. Generated
accessors are found as before.
…the class that makes the call

The second pass looks a call or operator on a closure shared variable
up again on the common type of its assignments, after the class has
been visited, so in the class the annotation is on. With a private
im() of Box called in Box itself through Sub s = new Sub1(); s = new
Sub2(), and @TypeChecked on the outer class of Box, the private method
was then dropped as one that Sub only inherits, and the call was
rejected, where dynamic Groovy and master run it.

The second pass now looks the method up in the class the first pass
checked the expression in, as for the declared receiver type. Running
such code statically compiled still throws ClassCastException, as it
does for a public method.
…pe through property syntax

Under static compilation, Box b = new Sub(); b.setY(v) calls a private
setY() of Box from another class of its nest, and the property lookup
for b.y = v found the setter the same way, through the declared type
Box. Setter validation then looked it up again on a stand-in receiver
of type Sub only, dropped the setter as one that Sub only inherits, and
reported "Cannot assign value of type String to variable of type
String"; b.y += v and a setter without a getter failed the same way.

The stand-in now keeps the declared type as its origin type where it
is a superclass of the narrowed type that declares a private setter in
play, so the validation finds what the property lookup found. Type
checking still rejects these, as dynamic Groovy looks the setter up on
the meta-class of Sub.
…eiver on that instance

The previous commit covered a private method of the outer class reached
through a receiver of a subclass, other than "this". The same mismatch
with dynamic Groovy remained wherever the type checker selects a method
that the receiver lacks and an outer class has:

- a plain inner class In, where other.im() for a private im() threw
  GroovyCastException and other.om() for a public one as well;
- "this" in a safe call, this?.im(), and the delegate of a closure,
  other.with { im() }, which code generation rewrites before the
  receiver is checked for "this";
- an operator: other + x, other[i] and x in other;
- a receiver of a subclass Sub2 of the inner class, which was rejected.

A safe or spread call whose receiver is written with a wider type, as
in if (o instanceof Sub) o?.im() or bag*.im() through an iterator()
method, failed with GroovyBugError, and an anonymous subclass created in
a closure, whose this$0 is the closure, with GroovyCastException.

The type checker now marks any call or operator whose method is one of
an enclosing instance of the receiver with the receiver type it was
selected for, and the call writer casts the receiver to that type and
follows its this$0 chain, through a closure's this object where a class
was created in a closure. The methods of outer classes are also offered
for a receiver of a subclass of the class being written. A method of the
receiver itself now comes first: with a public Sub.m(Object) and a
private Box.m(String), other.m('x') calls Sub.m(Object), as dynamic
Groovy does, which only turns to the enclosing instance for a method the
receiver lacks.
…losing class through another receiver of the calling class

In an inner subclass Sub of Box, other.p and other.q = v for a private
getP() and setQ() of Box, with other another Sub, were rejected under
@TypeChecked since GROOVY-12510 drops the accessors that Sub only
inherits. Dynamic Groovy uses the property of other's enclosing
instance, and master accepted them. Type checking now looks such a
property up on the enclosing instance too, for a receiver of the
calling class, where GROOVY-12621 has the run time fall back.

Static compilation still reports "No such property" for them: it would
have to reach the receiver's enclosing instance for the property, and
master used the receiver itself instead.
…sing instance, and that private static members stay reachable

The paragraph said that @TypeChecked rejects a private member of Base
wherever flow typing knows that a variable holds a Sub, but in Base
itself, and for a private static member, the access is made and works;
and its list of the places where a private method is called on a Sub
receiver left out the inner classes of Base, which the last sentence
then described.

It now restricts the meta-class rule to private instance members
outside Base, says that private static members stay reachable through
Sub, points the inner class case to the sentences on it, and states
what those cover since the previous commits: a method of an enclosing
instance through this, another receiver and an operator in any inner
class, and how other.name behaves for a private accessor and a private
field in each mode.
…hat now pass as implemented

bugs.RegressionTest from master keeps a test for each open issue that
still reproduces, marked @NotYetImplemented. Three of them now pass, so
the marker failed them:

- testGroovy12510: new Sub().im() for a private method of a superclass
  is rejected in both modes;
- testGroovy12523: sub.@f for a private field of a superclass reports
  "Cannot access field";
- testGroovy12637: toString() in an inner class, named or anonymous, is
  no longer the outer class's override under static compilation, now
  that a method of the receiver comes before one of an outer class.

The assertions are unchanged. testGroovy12511 and testGroovy12513 stay
@NotYetImplemented: they expect the enclosing class's im() where Sub and
an anonymous subclass declare their own, and @TypeChecked to accept
Box b = new Sub(); b.f, which dynamic Groovy fails on.
…cribe the marker as it is now used

In the guide, "It finds the field through sub.name" followed the
sentence on private static members, so it no longer read as dynamic
code; it now says so and comes before that sentence.

The javadoc of StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER still
described the first form of the rule: a private method that a receiver
other than this only inherits, with the outer class as the value. It is
set on any call or operator whose method is one of an enclosing
instance of the receiver, and its value is the receiver type the method
was selected for.
…nd the helpers that share them

The javadoc of findMethod now states which private methods a receiver
only inherits it leaves out, the exceptions it keeps for a call (the
declared type of the receiver variable, a static method, a call in the
declaring class, an instance with no enclosing instance), the methods
of the outer classes it offers, and that method pointers and references
are resolved without the call exceptions. SecondPassExpression
documents its declared receiver type and enclosing class, its
four-argument constructor, and why equals and hashCode leave them out.
The javadoc of isInheritedPrivateMethod matches its body, which also
leaves out an extension method. findVisibleMethods and getDeclaredType
of the method reference writer, and the two-argument
thisObjectExpression, have javadoc.
…of an enclosing instance

In a class nested in Box that also extends Box, other++ on another Sub
with a private next() of Box called next() on other under
@CompileStatic, where dynamic Groovy and @TypeChecked call it on the
enclosing instance of other, as they do for other + x. The type checker
now records ENCLOSING_INSTANCE_OF_RECEIVER on ++ and -- as it does on a
binary operator, and the static writer of ++ and -- passes it to the
next() or previous() call, which the call writer then makes on the
enclosing instance. This holds for a variable, a subscript and a
property operand.

A compound assignment such as other += x selected a plusAssign of Box
and called it on other in both modes. Dynamic Groovy uses a *Assign
method only if the receiver itself responds to it, and otherwise the
base operator, which may be one of the enclosing instance. The type
checker now drops a *Assign method of an enclosing instance of the
receiver, so other += x is other = other + x, with plus called on the
enclosing instance.
… x[i]++ reads through the getAt of an enclosing instance

A compound assignment selected a *Assign method that findMethod offers
from an outer class, not only one of an enclosing instance: with a
static Box.plusAssign and an inner Item with plus, item += 'x' called
Box.plusAssign under @CompileStatic, and under @TypeChecked dropped the
result of plus. Dynamic Groovy uses a *Assign method only if the
receiver itself responds to it, so the type checker now keeps only a
method of the receiver, its class or a superclass, or an extension
method.

x[i]++, ++x[i], x[i]-- and x[i] += v read x[i] again in the static
writer, which looked getAt up on the class of x: with a private getAt of
Box and an inner subclass Sub with putAt, other[0]++ read the value of
other itself, where dynamic Groovy reads it through the enclosing
instance, as for a plain other[0]. The type checker now records the
getAt of an enclosing instance on a subscript that is assigned, and the
static writer reads it with that call, so the write stays the putAt of
other. isTargetOfAssignment now stops at the null that marks a
re-purposed left-hand side.
… an enum for its constant body and a private static method of an enclosing class

this::helper and this.&helper in an enum constant body, for a private
helper of the enum, and Sub::sm and Sub.&sm for a private static sm of
Box with Sub nested in Box, ran in dynamic Groovy and compiled on
master; the change rejected them, as it does the other references to a
private method that the receiver only inherits. The meta-class of an
enum constant body finds the private methods of its enum (GROOVY-9523),
and dynamic Groovy finds a static method that a nested class lacks in
its outer class. The type checker and the static method reference writer
now keep both, and still reject a reference through Sub to a private
static method of a sibling Box, which dynamic Groovy fails on.

The object orientation guide no longer says that every private static
member of Base stays reachable through Sub: property syntax such as
Sub.name does not reach a private static field or getter of Base.
…ject for a call on an enclosing instance

In a closure in an anonymous Box subclass created in a closure, this.im()
for a private im() of Box was written through this$0 of the anonymous
class, which holds the outer closure, and cast that closure to Box. The
walk of thisObjectExpression now goes through the this object of such a
closure, as Outer.this and the walk for another receiver already did;
both use one step.
…setP(v) does

With a private Box.setP(Object) and a public Sub.setP(String), Box b =
new Sub(); b.p = 'x' called Box.setP(Object) under @CompileStatic, while
b.setP('x') calls Sub.setP(String), as dynamic Groovy and @TypeChecked do
for both. The setter check gave its stand-in receiver the declared type
Box as its type; it now keeps Box as the origin type, through which the
private setter is reached, and gives the receiver the inferred type Sub.
…st one out, and for a static receiver only by its static methods

findMethod offered the methods of all outer classes at once, so with
Outer.m(String) and Middle.m(Object), this.m('x') in Middle.Inner called
Outer.m(String) under @CompileStatic, where dynamic Groovy calls the
nearer Middle.m(Object). It now goes from the nearest outer class out,
and stops at the first that has an applicable method.

In a static method of a nested Inner with an instance m(Object), m('x')
was reported as a call of an instance method from a static context,
where master and dynamic Groovy call a static Outer.m(String): an
instance method of Inner, which the call cannot use, stopped the lookup
of the outer classes. For a receiver that offers only its static
methods, the class in a static method or the class that a Class receiver
wraps, only those methods now decide it.
…public getX of the same class

With a private isReady() and a public getReady() in Base, new Sub().ready
in a nestmate of Base was "No such property", where dynamic Groovy reads
getReady(): the property lookup took isReady() and dropped it afterwards
as a private accessor that Sub does not have, without trying getReady().
It now drops such an isX before it looks for getX.
@codeconsole
codeconsole force-pushed the stc-private-field-attribute branch from e9c5645 to 57b71aa Compare November 23, 2026 06:52
@testlens-app

testlens-app Bot commented Nov 23, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 57b71aa
▶️ Tests: 145914 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.

3 participants