Repository navigation
GROOVY-12509, GROOVY-12510, GROOVY-12511, GROOVY-12513, GROOVY-12523: private members of nested classes and superclasses under static type checking and compilation - #3050
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
9cba923 to
a2ad8c1
Compare
12bc47d to
99abb40
Compare
daniellansun
left a comment
There was a problem hiding this comment.
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::sminside 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()andthis.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-thisreceiver case above. - Flow typing of
Box b = new Sub()reaches the private members ofBoxunder@CompileStatic(javac’s static type) and is rejected under@TypeChecked, where the meta-class ofSubcannot see them (GROOVY-12513). Parameters and casts that are not narrowed stay taken at the declared type in both modes. sub.@fandSub.this.@ffor a private superclass field are now compile errors in both modes (GROOVY-12523);this.@f,super.@fand 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.
|
Thank you for the careful review. The non- The same holds for:
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 For property syntax, 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, You are right about |
daniellansun
left a comment
There was a problem hiding this comment.
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 ofBaseis now a compile error under both@TypeCheckedand@CompileStatic.testGroovy12523— likewise this PR:sub.@fnow 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 in5adeb0e. UnqualifiedtoString()inside a named or anonymous inner class is no longer taken from the outer class's override, because the inner class already inheritstoString()fromObject. 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.
|
Thank you. The branch is updated onto current master by a merge in 40c262d; there were no conflicts. ffbb294 drops |
daniellansun
left a comment
There was a problem hiding this comment.
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.
|
Thank you. All of these are in a851725, with one more in af95df5.
I left |
daniellansun
left a comment
There was a problem hiding this comment.
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.
|
Thank you. The
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:
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 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.
… 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.
…nce is no exception for a method reference
… 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.
e9c5645 to
57b71aa
Compare
✅ All tests passed ✅🏷️ Commit: 57b71aa Learn more about TestLens at testlens.app/docs. |
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
@TypeCheckedcode 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, sonew Sub().xstays rejected whengetX()is private in the superclass.GROOVY-12510: a private method is not inherited
new Sub().im(), whereim()is private inBoxandSub extends Box, compiled in the outer class ofBox, in a class nested inBox, and asim()in a static subclass nested inBox.@TypeCheckedthen threwMissingMethodException,@CompileStaticcalled it, and javac rejects it. Method references and method pointers (Sub::im,new Sub().&im) behaved the same way.findMethodnow 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::helperin an enum constant body for a private method of the enum, andSub::smfor a private static method of a class that enclosesSub. Calls through a receiver whose static type declares the method (aBoxparameter, a cast toBox,super.im()) keep compiling too, because javac accepts them and@CompileStaticruns them. Dynamic Groovy, and with it@TypeCheckedcode, throwsMissingMethodExceptionfor them when the object is aSub. 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
Boxthat also extendsBox, an unqualifiedim(), or a private getter used as a property, refers to the enclosingBoxinstance, as javac, dynamic Groovy and@TypeCheckedhave it.@CompileStaticused the subclass instance, also forthis.im()and in closures and lambdas, andthis.om()in a plain inner class failed withGroovyCastException. The call writer now uses the enclosing instance, andthis.pandthis.q = vfor a private accessor of the enclosing superclass resolve aspandq = vdo;this.@pstays 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 asother + 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 asother += xuses aplusAssignmethod only of the receiver itself, as dynamic Groovy does, and otherwiseplus, 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, wheretoString()in an inner class was the outer class's override under@CompileStatic.@TypeCheckedalso acceptsother.pandother.q = vfor 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@CompileStaticis 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
Boxthat flow typing narrows toSub(Box b = new Sub()), statically compiled code ofBox's nest reaches the private members ofBox, as javac does for the static typeBox:b.f,b.@f, a private getterb.x, a private setter throughb.y = vandb.y += v, a private methodb.im(), the operators that call a private method ofBox(b + x,b++,b[i],b += x,x in b), a compiler-supplied@ClassTagtoken and a closure shared variable.-b,+b,~bandb[i] = vstay rejected, because static compilation calls their methods dynamically. Under@TypeChecked, which dispatches all of these on the meta-class ofSub, they are rejected instead of throwing at run time. A parameter or cast declared asBoxis taken at its type in both modes.GROOVY-12523:
x.@namefor a private field of a superclassIn a class nested in
Outer, the type checker acceptedsub.@f, wherefis a private field ofOuterandsubis typed as a subclass ofOuter. Dynamic Groovy and@TypeCheckedthrewMissingFieldException, javac rejects it, and@CompileStaticread 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.@finsideSuband a receiver typed as a deeper subclass.this.@f,Outer.this.@fandsuper.@fkeep working, as dosub.@finOuteritself and a receiver declared asOuter; under@CompileStatic,((Outer) sub).@freads 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
@CompileStaticcode that compiled and ran, not only a rejection of what failed at run time, as GROOVY-12610 and GROOVY-12621 are.@CompileStatic, as javac rejects them:new Sub().im()for a privateim()of a superclass outside the declaring class; method references and pointers to it such asSub::im, andSub::smwhere the class ofsmdoes not encloseSub, 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; andsub.@f. In an inner subclass,other.pandother.q = vfor a private accessor of the outer class, which master ran onotheritself, are reported as well.Sub.m(Object)and a privateBox.m(String),new Sub().m('x')now selectsSub.m(Object), as javac, dynamic Groovy and@TypeCheckeddo. In an inner class, a call such asm('x'),toString()orother.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 implicitthis.im(),this.im(),other.im(),new Sub().im(),Sub.this.im(),other + xorother++, and in an inner subclasspandthis.pfor a private getter, now run on an enclosing instance instead of on the receiver, as dynamic Groovy and@TypeCheckedrun them.other += x, which called aplusAssignof the outer class onotherin both modes, now callsplus, here on the enclosing instance, as dynamic Groovy does;other[i]++andother[i] += xreadother[i]through the enclosing instance too.Under
@TypeChecked, the accesses above that threw at run time are reported at compile time.Tests
FieldsAndPropertiesSTCTest,MethodCallsSTCTestandConstructorsSTCTest, also run statically compiled byFieldsAndPropertiesStaticCompileTest,MethodCallsStaticCompilationTestandStaticCompileConstructorsTest, andMethodReferenceTest. The rejected forms fail without the change, and each is compiled in a script of its own. Inbugs.RegressionTest,testGroovy12510,testGroovy12523andtestGroovy12637now pass and are no longer marked@NotYetImplemented. The 18,765 tests in thegroovy,gls,bugs,org.codehaus.groovy.classgen,transform,runtime,reflection,vmplugin,controlandastpackages and the stub generator tests pass.groovy-contracts,groovy-typecheckers,groovy-ginq,groovy-macro-library,groovy-json,groovy-xmlandgroovy-templatespass their tests, and every subproject compiles its main and test sources. The Checkstyle and CodeNarc gates pass.