From aa2cf0d006f6631c8df2cbf031e685bce9b643a2 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 25 Oct 2026 12:16:55 -0700 Subject: [PATCH 01/38] GROOVY-12510: STC: reject a private superclass method called through 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. --- ...cTypesMethodReferenceExpressionWriter.java | 27 ++- .../stc/StaticTypeCheckingSupport.java | 16 ++ .../stc/StaticTypeCheckingVisitor.java | 54 +++++- .../transform/stc/MethodCallsSTCTest.groovy | 171 ++++++++++++++++++ .../transform/stc/MethodReferenceTest.groovy | 60 ++++++ .../MethodCallsStaticCompilationTest.groovy | 37 ++++ 6 files changed, 358 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java index 01f9c07ae43..4d6d62bc44c 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java @@ -22,15 +22,18 @@ import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; +import org.codehaus.groovy.ast.DynamicVariable; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.Parameter; +import org.codehaus.groovy.ast.Variable; import org.codehaus.groovy.ast.expr.ArgumentListExpression; import org.codehaus.groovy.ast.expr.ArrayExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.Expression; import org.codehaus.groovy.ast.expr.MethodCallExpression; import org.codehaus.groovy.ast.expr.MethodReferenceExpression; +import org.codehaus.groovy.ast.expr.VariableExpression; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.ast.tools.GeneralUtils; import org.codehaus.groovy.classgen.AsmClassGenerator; @@ -84,6 +87,7 @@ import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isAssignableTo; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isClassClassNodeWrappingConcreteType; +import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isInheritedPrivateMethod; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.resolveClassNodeGenerics; import static org.objectweb.asm.Opcodes.ACC_PRIVATE; import static org.objectweb.asm.Opcodes.ACC_STATIC; @@ -594,7 +598,7 @@ private Parameter[] createParametersWithExactType(final MethodNode abstractMetho } private MethodNode findMethodRefMethod(final String methodName, final Parameter[] samParameters, final Expression typeOrTargetRef, final ClassNode typeOrTargetRefType) { - List methods = findVisibleMethods(methodName, typeOrTargetRefType); + List methods = findVisibleMethods(methodName, typeOrTargetRefType, typeOrTargetRef); ToIntFunction distance = (parameters) -> { // GROOVY-10972: select from closest matches return allParametersAndArgumentsMatch(parameters, Arrays.stream(samParameters).map(Parameter::getType).toArray(ClassNode[]::new)); @@ -670,7 +674,7 @@ private MethodNode chooseMethodRefMethod(final List methods, final E }).thenComparing(StaticTypesMethodReferenceExpressionWriter::isExtensionMethod)).orElse(null); } - private List findVisibleMethods(final String name, final ClassNode type) { + private List findVisibleMethods(final String name, final ClassNode type, final Expression typeOrTargetRef) { List methods = type.getMethods(name); // GROOVY-10791, GROOVY-11467: include non-static interface methods Set implemented = getInterfacesAndSuperInterfaces(type); @@ -683,7 +687,24 @@ private List findVisibleMethods(final String name, final ClassNode t } } methods.addAll(findDGMMethodsForClassNode(controller.getSourceUnit().getClassLoader(), type, name)); - return filterMethodsByVisibility(methods, controller.getClassNode()); + methods = filterMethodsByVisibility(methods, controller.getClassNode()); + + // a private method of a superclass is not a member of the type (JLS 8.2), + // but it is one of the declared type of a variable whose type is narrower + ClassNode declaredType = getDeclaredType(typeOrTargetRef); + methods.removeIf(method -> isInheritedPrivateMethod(method, type) && !method.getDeclaringClass().equals(declaredType)); + return methods; + } + + private static ClassNode getDeclaredType(final Expression expression) { + if (expression instanceof VariableExpression variable && !variable.isThisExpression() && !variable.isSuperExpression()) { + Variable target = variable; + while (target instanceof VariableExpression ve && ve.getAccessedVariable() != null && ve.getAccessedVariable() != ve) { + target = ve.getAccessedVariable(); + } + if (!(target instanceof DynamicVariable)) return target.getOriginType(); + } + return null; } private void addFatalError(final String msg, final ASTNode node) { diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java index 8d0a433f477..9b08779ecdd 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java @@ -3341,6 +3341,22 @@ public static List filterMethodsByVisibility(final List return result; } + /** + * Determines if a method is a private method that a receiver of the given type + * would only inherit from a superclass. Private members are not inherited + * (JLS 8.2), so such a method is not a member of the receiver type, and dynamic + * Groovy does not find it there either. + * + * @param method the candidate method + * @param receiverType the type that the method is looked up on + * @return {@code true} if the method is private and declared by another class + * @since 7.0.0 + */ + public static boolean isInheritedPrivateMethod(final MethodNode method, final ClassNode receiverType) { + return method.isPrivate() && !(method instanceof ExtensionMethodNode) + && !method.getDeclaringClass().equals(receiverType); + } + /** * @return true if the class node is either a GString or the LUB of String and GString. */ diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 75ffb02d16f..15af65dfea8 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -179,6 +179,7 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.IntPredicate; +import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -372,6 +373,7 @@ import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isCompareToBoolean; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isGStringOrGStringStringLUB; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isGenericsPlaceHolderOrArrayOf; +import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isInheritedPrivateMethod; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isOperationInGroup; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isParameterizedWithGStringOrGStringString; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.isParameterizedWithString; @@ -581,6 +583,8 @@ private static ClassNode literalDefaultImplementation(final ClassNode target, fi * class and member visit gets its own set, dropped when the visit ends, see {@link #pushInstanceOfGuards()}. */ private Set instanceOfGuards = Collections.newSetFromMap(new IdentityHashMap<>()); + /** Declared type of the variable whose method {@link #findMethod} is looking up, if any. */ + private ClassNode declaredReceiverType; /** * Creates a static type-checking visitor for the supplied source and class. @@ -4865,7 +4869,7 @@ && isStringType(getType(nameExpr))) { for (Receiver currentReceiver : receivers) { receiverType = wrapTypeIfNecessary(currentReceiver.getType()); - candidates = findMethodsWithGenerated(receiverType, nameText); + candidates = removeInheritedPrivateMethods(findMethodsWithGenerated(receiverType, nameText), receiverType, getDeclaredType(expression.getExpression()), false); // GROOVY-10741: check for reference to a property node's method MethodNode generated = findPropertyMethod(receiverType, nameText); if (generated != null && candidates.stream().noneMatch(m -> m.getName().equals(generated.getName()))) { @@ -6790,7 +6794,12 @@ && isOwnerClosure(typeCheckingContext.getEnclosingClosureStack())) { for (Receiver currentReceiver : receivers) { ClassNode receiverType = currentReceiver.getType(); if (isClassType(receiverType)) receiverType = receiverType.getPlainNodeReference(); - mn = findMethod(receiverType, name, args); + declaredReceiverType = getDeclaredType(objectExpression); + try { + mn = findMethod(receiverType, name, args); + } finally { + declaredReceiverType = null; + } if (!mn.isEmpty()) { first = mn.get(0); // capture for error reporting chosenReceiver = currentReceiver; @@ -9092,7 +9101,7 @@ protected List findMethod(ClassNode receiver, final String name, fin } } } else { - methods = findMethodsWithGenerated(receiver, name); + methods = removeInheritedPrivateMethods(findMethodsWithGenerated(receiver, name), receiver, declaredReceiverType, true); if ("call".equals(name) && receiver.isInterface()) { MethodNode sam = findSAM(receiver); if (sam != null && !"call".equals(sam.getName())) { @@ -9107,7 +9116,7 @@ protected List findMethod(ClassNode receiver, final String name, fin boolean staticOnly = hasNoEnclosingInstance(receiver); for (ClassNode outer = receiver; (outer = outer.getOuterClass()) != null; staticOnly = staticOnly || hasNoEnclosingInstance(outer)) { - methods.addAll(allowStaticAccessToMember(findMethodsWithGenerated(outer, name), staticOnly)); + methods.addAll(allowStaticAccessToMember(removeInheritedPrivateMethods(findMethodsWithGenerated(outer, name), outer, null, true), staticOnly)); } } if (args == null || args.length == 0) { @@ -9205,6 +9214,43 @@ protected List findMethod(ClassNode receiver, final String name, fin return EMPTY_METHODNODE_LIST; } + /** + * Removes the private methods that {@code type} only inherits from a superclass + * (JLS 8.2). A method declared by {@code declaredType} is kept: that is the + * declared type of a variable whose inferred type is the narrower type. For a + * call, three cases that dynamic Groovy runs are kept as well: a private static + * method, a private method called from its declaring class, and one called on + * an enum constant body or an anonymous class created in a static context that + * is nested in the declaring class: having no enclosing instance, it calls the + * method on itself. For a method reference or pointer they are not, because + * dynamic Groovy fails on those. + */ + private List removeInheritedPrivateMethods(final List methods, final ClassNode type, final ClassNode declaredType, final boolean call) { + ClassNode enclosingClass = typeCheckingContext.getEnclosingClassNode(); + boolean selfWithoutEnclosingInstance = type.equals(enclosingClass) + && hasNoEnclosingInstance(enclosingClass) && !Modifier.isStatic(enclosingClass.getModifiers()); + Predicate inherited = method -> isInheritedPrivateMethod(method, type) + && !method.getDeclaringClass().equals(declaredType) + && !(call && (method.isStatic() || method.getDeclaringClass().equals(enclosingClass) + || (selfWithoutEnclosingInstance && enclosingClass.getOuterClasses().contains(method.getDeclaringClass())))); + if (methods.stream().noneMatch(inherited)) return methods; + + List result = new ArrayList<>(methods); + result.removeIf(inherited); + return result; + } + + /** + * Returns the declared type of a variable, which flow typing may have narrowed. + */ + private static ClassNode getDeclaredType(final Expression expression) { + if (expression instanceof VariableExpression variable && !variable.isThisExpression() && !variable.isSuperExpression()) { + Variable target = findTargetVariable(variable); + if (!(target instanceof DynamicVariable)) return target.getOriginType(); + } + return null; + } + /** * The property from {@code property}'s declaring class upward for which * Verifier will emit {@code name}, or null. A more specific property that diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index b79efb9a1f5..d83095fd570 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -442,6 +442,177 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12510: a private method is not inherited (JLS 8.2), so javac rejects + // these calls and dynamic Groovy throws MissingMethodException + @Test + void testCallToPrivateMethodOfSuperclassThroughSubclass() { + def sub = 'Cannot find matching method Outer$Sub#im()' + def nested = 'Cannot find matching method Outer$Box$Nested#im()' + [ + outer: [ + 'static test() { new Sub().im() }' : sub, + 'static test() { def sub = new Sub(); sub.im() }' : sub, + 'static test(Object o) { if (o instanceof Sub) o.im() }' : sub, + 'static test() { def c = { -> new Sub().im() }; c() }' : sub, + 'static test() { Supplier s = () -> new Sub().im(); s.get() }' : sub, + 'static test() { new Object() { def get() { new Sub().im() } }.get() }' : sub, + 'static class Sub2 extends Sub { }\n static test() { new Sub2().im() }' : 'Cannot find matching method Outer$Sub2#im()', + 'static test() { new Sub().with { im() } }' : 'Cannot find matching method java.lang.Class#im() or static method Outer#im()', + ], + box: [ + 'static class In { def test() { new Sub().im() } }' : sub, + 'class In { def test() { new Sub().im() } }' : sub, + 'def test() { new Object() { def get() { new Sub().im() } }.get() }' : sub, + 'static class Nested extends Box { def test() { im() } }' : nested, + 'static class Nested extends Box { def test() { this.im() } }' : nested, + 'static class Nested extends Box { def test() { new Nested().im() } }' : nested, + 'static class Nested extends Box { def test() { def c = { -> im() }; c() } }' : nested, + ], + ].each { where, cases -> + cases.each { code, message -> + shouldFailWithMessages """ + import java.util.function.Supplier + + class Outer { + static class Box { + private String im(String s = '') { 'im' } + ${where == 'box' ? code : ''} + } + static class Sub extends Box { + } + ${where == 'outer' ? code : ''} + } + """, message + } + } + + shouldFailWithMessages ''' + class Shape { + private String helper() { 'helper' } + static class Circle extends Shape { + String area() { helper() } + } + } + ''', + 'Cannot find matching method Shape$Circle#helper()' + } + + // GROOVY-12510: as in dynamic Groovy, the declaring class may call it through + // an instance of a subclass, and a private static method is found through a + // subclass + @Test + void testCallToPrivateMethodOfSuperclassFromDeclaringClass() { + assertScript ''' + import java.util.function.Supplier + + class Outer { + static class Box { + String id = 'box' + private String im() { 'im:' + id } + private static String sm() { 'sm' } + static String test() { + def sub = new Sub() + def c = { -> sub.im() } + Supplier s = () -> sub.im() + [sub.im(), c(), s.get(), sub.with { im() }, Sub.sm()].join(',') + } + static class Nested extends Box { + String test() { sm() + Nested.sm() } + } + } + static class Sub extends Box { + Sub() { id = 'sub' } + } + static String test() { Sub.sm() } + } + assert Outer.Box.test() == 'im:sub,im:sub,im:sub,im:sub,sm' + assert new Outer.Box.Nested().test() == 'smsm' + assert Outer.test() == 'sm' + ''' + } + + /** + * Calls a private method through a receiver whose static type declares it. + * Run by the static compilation test; @TypeChecked dispatches these calls + * dynamically, and the meta-class of a subclass offers no private method of + * its superclass, so here they are only compiled. + */ + protected static final String PRIVATE_METHOD_THROUGH_DECLARING_TYPE = ''' + class Outer { + static class Box { + String id = 'box' + private String im() { 'im:' + id } + static class Nested extends Box { + Nested() { id = 'nested' } + String viaSuper() { super.im() } + String viaCast() { ((Box) this).im() } + } + } + static class Sub extends Box { + Sub() { id = 'sub' } + } + static String param(Box b) { b.im() } + static String local() { Box b = new Sub(); b.im() } + static Box make() { new Sub() } + static String result() { make().im() } + static String coerced() { (new Sub() as Box).im() } + static String narrowed(Box b) { if (b instanceof Sub) { return b.im() }; null } + static String closure() { Box b = new Sub(); def c = { -> b.im() }; c() } + } + def sub = new Outer.Sub() + ''' + + // GROOVY-12510 + @Test + void testCallToPrivateMethodOfSuperclassThroughReceiverOfItsType() { + assertScript PRIVATE_METHOD_THROUGH_DECLARING_TYPE + } + + // GROOVY-12510: an enum constant body and an anonymous subclass are nested in + // the declaring class, so they find the private method on their enclosing class + @Test + void testCallToPrivateMethodOfEnclosingClassFromNestedSubclass() { + assertScript ''' + enum E { + A { + String f() { helper() + this.helper() + [1].collect { helper() }.join() } + } + String f() { 'base' } + private String helper() { 'h' } + } + assert E.A.f() == 'hhh' + ''' + assertScript ''' + class Box { + private String im() { 'im' } + String test() { + new Box() { + String get() { im() + this.im() } + }.get() + } + } + assert new Box().test() == 'imim' + ''' + } + + // GROOVY-12510: javac and dynamic Groovy select the subclass method, because + // the private method of the superclass is not a member of the subclass + @Test + void testPrivateMethodOfSuperclassIsNoOverloadThroughSubclass() { + assertScript ''' + class Outer { + static class Box { + private String m(String s) { 'Box.m(String)' } + } + static class Sub extends Box { + String m(Object o) { 'Sub.m(Object)' } + } + static String test() { new Sub().m('x') } + } + assert Outer.test() == 'Sub.m(Object)' + ''' + } + @Test void testCallToPrivateInnerClassConstant() { assertScript ''' diff --git a/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy b/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy index e45d3527a57..da465e4f210 100644 --- a/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy @@ -3005,6 +3005,66 @@ final class MethodReferenceTest { ''' } + // GROOVY-12510: a private method is not inherited (JLS 8.2); javac rejects these + // references and dynamic Groovy throws MissingMethodException, even in the class + // that declares the method + @ParameterizedTest + @ValueSource(strings=['TypeChecked','CompileStatic']) + void testPrivateMethodOfSuperclassReferenceThroughSubclass(String mode) { + def refs = [ + 'Function f = Sub::im' : 'im', + 'Supplier f = new Sub()::im' : 'im', + 'Supplier f = Sub::sm' : 'sm', + 'def f = new Sub().&im' : 'im', + 'def f = Sub.&sm' : 'sm', + ] + refs.each { ref, name -> + for (where in ['Outer', 'Box']) { + def err = shouldFail shell, """ + @$mode + class Outer { + static class Box { + private String im() { 'im' } + private static String sm() { 'sm' } + ${where == 'Box' ? "static test() { $ref }" : ''} + } + static class Sub extends Box { + } + ${where == 'Outer' ? "static test() { $ref }" : ''} + } + """ + if (mode == 'TypeChecked' || ref.contains('.&')) { + assert err.message.contains("Cannot find matching method Outer\$Sub#${name}.") + } else { + assert err.message =~ /Failed to find (class )?method '${name}\(.*\)'.* for the type: Outer[$]Sub/ + } + } + } + } + + // GROOVY-12510 + @ParameterizedTest + @ValueSource(strings=['@CompileDynamic','@TypeChecked','@CompileStatic']) + void testPrivateMethodOfSuperclassReferenceThroughItsType(String tag) { + assertScript shell, """ + $tag + class Outer { + static class Box { + private String im() { 'im' } + } + static class Sub extends Box { + } + static String test() { + Function f = Box::im + Box b = new Sub() + Supplier g = b::im + f.apply(new Sub()) + g.get() + } + } + assert Outer.test() == 'imim' + """ + } + // GROOVY-11365 @Test void testInnerClassProtectedMethodReference() { diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy index 083fce15adc..4cac7a28401 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy @@ -58,4 +58,41 @@ final class MethodCallsStaticCompilationTest extends MethodCallsSTCTest implemen ''' assert astTrees['Foo$Bar$Baz'][1].contains('INVOKEVIRTUAL Foo.d ()I') } + + // GROOVY-12510 + @Override @Test + void testCallToPrivateMethodOfSuperclassThroughReceiverOfItsType() { + assertScript PRIVATE_METHOD_THROUGH_DECLARING_TYPE + ''' + def nested = new Outer.Box.Nested() + assert nested.viaSuper() == 'im:nested' + assert nested.viaCast() == 'im:nested' + assert Outer.param(sub) == 'im:sub' + assert Outer.local() == 'im:sub' + assert Outer.result() == 'im:sub' + assert Outer.coerced() == 'im:sub' + assert Outer.narrowed(sub) == 'im:sub' + assert Outer.closure() == 'im:sub' + ''' + } + + // GROOVY-12510: dynamic Groovy and @TypeChecked reject a class that mixes private + // and public methods of one name. Through the subclass only the public method is + // a member; through a variable declared with the superclass type both are + @Test + void testPrivateOverloadOfSuperclassThroughSubclassOrDeclaredType() { + assertScript ''' + class Outer { + static class Box { + private String m(String s) { 'm(String)' } + String m(Object o) { 'm(Object)' } + } + static class Sub extends Box { + } + static String viaSubclass() { new Sub().m('x') } + static String viaDeclaredType() { Box b = new Sub(); b.m('x') } + } + assert Outer.viaSubclass() == 'm(Object)' + assert Outer.viaDeclaredType() == 'm(String)' + ''' + } } From 50c436ee04aaee8980b9ec5ed9da499d13fec247 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 25 Oct 2026 12:20:20 -0700 Subject: [PATCH 02/38] GROOVY-12509: STC: allow private methods and constructors of another 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). --- .../stc/StaticTypeCheckingSupport.java | 10 +- .../transform/stc/ConstructorsSTCTest.groovy | 108 ++++++++ .../transform/stc/MethodCallsSTCTest.groovy | 253 ++++++++++++++++++ .../transform/stc/MethodReferenceTest.groovy | 131 ++++++++- .../MethodCallsStaticCompilationTest.groovy | 35 +++ .../sc/StaticCompileConstructorsTest.groovy | 14 + 6 files changed, 548 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java index 9b08779ecdd..481cde9058c 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java @@ -79,6 +79,7 @@ import java.util.stream.BaseStream; import static org.apache.groovy.ast.tools.ClassNodeUtils.addGeneratedMethod; +import static org.apache.groovy.ast.tools.ClassNodeUtils.getNestHost; import static org.apache.groovy.ast.tools.ClassNodeUtils.samePackageName; import static org.apache.groovy.ast.tools.ExpressionUtils.isNullConstant; import static org.codehaus.groovy.ast.ClassHelper.BigInteger_TYPE; @@ -3274,7 +3275,11 @@ private static Map extractGenericsParameterMapOf } /** - * Filter methods according to visibility + * Filter methods according to visibility. A private method or constructor is + * visible from every class of its nest, that is the top-level class that + * encloses its declaring class and every class nested in it, as in Java + * (JLS 6.6.1). The rules for protected and package-private members are + * unchanged. * * @param methodNodeList method nodes to filter * @param enclosingClassNode the enclosing class @@ -3323,7 +3328,8 @@ public static List filterMethodsByVisibility(final List } } - if (methodNode.isPrivate() && !enclosingClassNode.equals(declaringClass)) { + if (methodNode.isPrivate() && !enclosingClassNode.equals(declaringClass) + && !getNestHost(enclosingClassNode).equals(getNestHost(declaringClass))) { continue; } if (methodNode.isProtected() diff --git a/src/test/groovy/groovy/transform/stc/ConstructorsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/ConstructorsSTCTest.groovy index e7e3819b815..93949ff1653 100644 --- a/src/test/groovy/groovy/transform/stc/ConstructorsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/ConstructorsSTCTest.groovy @@ -828,4 +828,112 @@ import static groovy.test.GroovyAssert.shouldFail ''', 'Cannot find matching constructor C()' } + + // GROOVY-12509 + @Test + void testPrivateConstructorOfSiblingClass() { + assertScript ''' + import java.util.function.Supplier + + class Outer { + static class Box { + final String v + private Box(String a, String b) { v = a + b } + } + static class Other { + static String test() { new Box('a', 'b').v } + static String viaClosure() { + def c = { -> new Box('c', 'd').v } + c() + } + static String viaLambda() { + Supplier s = () -> new Box('e', 'f').v + s.get() + } + static String viaAnonymousClass() { + new Object() { + String get() { new Box('g', 'h').v } + }.get() + } + } + } + assert Outer.Other.test() == 'ab' + assert Outer.Other.viaClosure() == 'cd' + assert Outer.Other.viaLambda() == 'ef' + assert Outer.Other.viaAnonymousClass() == 'gh' + ''' + } + + // GROOVY-12509 + @Test + void testPrivateConstructorOfSiblingClassWithDefaultArgument() { + assertScript ''' + class Outer { + static class Box { + final String v + private Box(String a, String b = 'b') { v = a + b } + } + static class Other { + static String test() { new Box('a').v + new Box('c', 'd').v } + } + } + assert Outer.Other.test() == 'abcd' + ''' + } + + // GROOVY-12509 + @Test + void testPrivateConstructorOfNestMateSuperclass() { + assertScript ''' + class Outer { + static class Box { + final String v + private Box() { v = 'implicit' } + private Box(String s) { v = s } + } + static class Sub1 extends Box { + Sub1() { } + } + static class Sub2 extends Box { + Sub2() { super('explicit') } + } + } + assert new Outer.Sub1().v == 'implicit' + assert new Outer.Sub2().v == 'explicit' + ''' + } + + // GROOVY-12509 + @Test + void testPrivateConstructorOfSiblingClassIsPreferredOverload() { + assertScript ''' + class Outer { + static class Box { + final String v + private Box(String s) { v = 'Box(String)' } + Box(Object o) { v = 'Box(Object)' } + } + static class Other { + static String test() { new Box('x').v } + } + } + assert Outer.Other.test() == 'Box(String)' + ''' + } + + // GROOVY-12509 + @Test + void testPrivateConstructorOfClassInAnotherNest() { + shouldFailWithMessages ''' + class Outer1 { + static class Box { + private Box(String s) { } + } + } + class Outer2 { + static test() { new Outer1.Box('x') } + } + ''', + 'Cannot find matching constructor Outer1$Box(java.lang.String)' + } } diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index d83095fd570..efe9781f434 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -459,6 +459,24 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { 'static class Sub2 extends Sub { }\n static test() { new Sub2().im() }' : 'Cannot find matching method Outer$Sub2#im()', 'static test() { new Sub().with { im() } }' : 'Cannot find matching method java.lang.Class#im() or static method Outer#im()', ], + other: [ // a sibling of Box + 'static test() { new Sub().im() }' : sub, + 'static test() { def sub = new Sub(); sub.im() }' : sub, + 'static test(Object o) { if (o instanceof Sub) o.im() }' : sub, + 'static test() { def c = { -> new Sub().im() }; c() }' : sub, + 'static test() { Supplier s = () -> new Sub().im(); s.get() }' : sub, + 'static test() { new Object() { def get() { new Sub().im() } }.get() }' : sub, + 'static class Sub2 extends Sub { }\n static test() { new Sub2().im() }' : 'Cannot find matching method Outer$Other$Sub2#im()', + 'static test() { new Sub().with { im() } }' : 'Cannot find matching method java.lang.Class#im() or static method Outer$Other#im()', + ], + sub: [ // Sub is a sibling of Box + 'def test() { im() }' : sub, + 'def test() { this.im() }' : sub, + 'def test() { def c = { -> im() }; c() }' : sub, + 'def test() { Supplier s = () -> im(); s.get() }' : sub, + 'static class In { def test() { new Sub().im() } }' : sub, + 'class In { def test() { im() } }' : 'Cannot find matching method Outer$Sub$In#im()', + ], box: [ 'static class In { def test() { new Sub().im() } }' : sub, 'class In { def test() { new Sub().im() } }' : sub, @@ -479,6 +497,10 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ${where == 'box' ? code : ''} } static class Sub extends Box { + ${where == 'sub' ? code : ''} + } + static class Other { + ${where == 'other' ? code : ''} } ${where == 'outer' ? code : ''} } @@ -522,11 +544,17 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { } static class Sub extends Box { Sub() { id = 'sub' } + String test() { sm() + Sub.sm() } + } + static class Other { + static String test() { Sub.sm() } } static String test() { Sub.sm() } } assert Outer.Box.test() == 'im:sub,im:sub,im:sub,im:sub,sm' assert new Outer.Box.Nested().test() == 'smsm' + assert new Outer.Sub().test() == 'smsm' + assert Outer.Other.test() == 'sm' assert Outer.test() == 'sm' ''' } @@ -550,6 +578,12 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { } static class Sub extends Box { Sub() { id = 'sub' } + String viaSuper() { super.im() } + String viaCast() { ((Box) this).im() } + } + static class Other { + static String param(Box b) { b.im() } + static String local() { Box b = new Sub(); b.im() } } static String param(Box b) { b.im() } static String local() { Box b = new Sub(); b.im() } @@ -613,6 +647,225 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12509 + @Test + void testCallToPrivateMethodOfSiblingClass() { + assertScript ''' + class Outer { + static class Box { + private static String sm() { 'sm' } + private String im() { 'im' } + } + static class Other { + static String test() { Box.sm() + new Box().im() } + } + class Inner { + String test() { Box.sm() + new Box().im() } + } + static String inner() { new Inner(new Outer()).test() } + } + assert Outer.Other.test() == 'smim' + assert Outer.inner() == 'smim' + ''' + } + + // GROOVY-12509 + @Test + void testCallToPrivateMethodOfInnerSiblingClass() { + assertScript ''' + class Outer { + class Box { + private String im() { 'im' } + } + class Other { + String test() { new Box().im() } + } + static String test() { new Other(new Outer()).test() } + } + assert Outer.test() == 'im' + ''' + } + + // GROOVY-12509 + @Test + void testCallToPrivateMethodOfCousinAndNephewClass() { + assertScript ''' + class Outer { + static class P { + static class Deep { + static String test() { Q.p() + new Q().q() } + } + static String test() { Q.Deep.p() + new Q.Deep().q() } + } + static class Q { + private static String p() { 'Q.p' } + private String q() { 'Q.q' } + static class Deep { + private static String p() { 'Deep.p' } + private String q() { 'Deep.q' } + } + } + } + assert Outer.P.Deep.test() == 'Q.pQ.q' + assert Outer.P.test() == 'Deep.pDeep.q' + ''' + } + + // GROOVY-12509 + @Test + void testCallToPrivateMethodOfSiblingEnumAndRecord() { + assertScript ''' + class Outer { + enum E { + ONE + private static String p() { 'E.p' } + private String q() { 'E.q' } + } + record R(String a) { + private static String p() { 'R.p' } + private String q() { 'R.q' + a } + } + static class Other { + static String test() { E.p() + E.ONE.q() + R.p() + new R('!').q() } + } + } + assert Outer.Other.test() == 'E.pE.qR.pR.q!' + ''' + } + + // GROOVY-12509 + @Test + void testCallToPrivateMethodOfSiblingClassFromClosureLambdaOrAnonymousClass() { + assertScript ''' + import java.util.function.Supplier + + class Outer { + static class Box { + private static String sm() { 'sm' } + private String im() { 'im' } + } + static class Other { + static String viaClosure() { + def c = { -> Box.sm() + new Box().im() } + c() + } + static String viaLambda() { + Supplier s = () -> Box.sm() + new Box().im() + s.get() + } + static String viaAnonymousClass() { + new Object() { + String get() { Box.sm() + new Box().im() } + }.get() + } + static String viaDelegate() { + new Box().with { im() } + } + } + } + assert Outer.Other.viaClosure() == 'smim' + assert Outer.Other.viaLambda() == 'smim' + assert Outer.Other.viaAnonymousClass() == 'smim' + assert Outer.Other.viaDelegate() == 'im' + ''' + } + + // GROOVY-12509 + @Test + void testCallToPrivateMethodOfSiblingClassWithDefaultArgument() { + assertScript ''' + class Outer { + static class Box { + private static String sm(String a, String b = 'b') { a + b } + } + static class Other { + static String test() { Box.sm('a') + Box.sm('c', 'd') } + } + } + assert Outer.Other.test() == 'abcd' + ''' + } + + // GROOVY-12509 + @Test + void testCallToPrivateMethodOfSiblingClassFromTrait() { + assertScript ''' + class Outer { + static class Box { + private static String sm() { 'sm' } + } + trait T { + String test() { Box.sm() } + } + static class U implements T { + } + } + assert new Outer.U().test() == 'sm' + ''' + } + + // GROOVY-12509 + @Test + void testCallToPrivateMethodOfClassInAnotherNest() { + shouldFailWithMessages ''' + class Box { + private static String sm() { 'sm' } + } + class Other { + static test() { Box.sm() } + } + ''', + 'Cannot find matching method java.lang.Class#sm() or static method Box#sm()' + + shouldFailWithMessages ''' + class Outer1 { + static class Box { + private String im() { 'im' } + } + } + class Outer2 { + static test() { new Outer1.Box().im() } + } + ''', + 'Cannot find matching method Outer1$Box#im()' + } + + // GROOVY-12509 + @Test + void testPrivateMethodOfSiblingClassIsPreferredOverload() { + assertScript ''' + class Outer { + static class Base { + String m(Object o) { 'Base.m(Object)' } + } + static class Box extends Base { + private String m(String s) { 'Box.m(String)' } + } + static class Other { + static String test() { new Box().m('x') } + } + } + assert Outer.Other.test() == 'Box.m(String)' + ''' + } + + // GROOVY-12509 + @Test + void testPrivateMethodOfSiblingDelegateIsPreferredOverOwnerMethod() { + assertScript ''' + class Outer { + static class Box { + private String n(String s) { 'Box.n' } + } + static class Other { + static String n(Object o) { 'Other.n' } + static String test() { new Box().with { n('x') } } + } + } + assert Outer.Other.test() == 'Box.n' + ''' + } + @Test void testCallToPrivateInnerClassConstant() { assertScript ''' diff --git a/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy b/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy index da465e4f210..b252b2baa36 100644 --- a/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy @@ -3005,6 +3005,88 @@ final class MethodReferenceTest { ''' } + // GROOVY-12509 + @ParameterizedTest + @ValueSource(strings=['@CompileDynamic','@TypeChecked','@CompileStatic']) + void testSiblingClassPrivateMemberReference(String tag) { + assertScript shell, """ + $tag + class Outer { + static class Box { + final String v + private Box(String a, String b) { v = a + b } + Box() { v = '!' } + private static String sm() { 'sm' } + private String im() { 'im' + v } + } + static class Other { + static String test() { + BiFunction ctor = Box::new + Supplier sm = Box::sm + Function im = Box::im + Supplier bound = new Box()::im + ctor.apply('a', 'b').v + sm.get() + im.apply(new Box()) + bound.get() + } + static String viaClosure() { + def c = { -> + Supplier sm = Box::sm + Function im = Box::im + sm.get() + im.apply(new Box()) + } + c() + } + } + } + assert Outer.Other.test() == 'absmim!im!' + assert Outer.Other.viaClosure() == 'smim!' + """ + } + + // GROOVY-12509 + @ParameterizedTest + @ValueSource(strings=['@CompileDynamic','@TypeChecked','@CompileStatic']) + void testSiblingClassPrivateConstructorReferenceIsPreferredOverload(String tag) { + assertScript shell, """ + $tag + class Outer { + static class Box { + final String v + private Box(String s) { v = 'Box(String)' } + Box(Object o) { v = 'Box(Object)' } + } + static class Other { + static String test() { + Function f = Box::new + f.apply('x').v + } + } + } + assert Outer.Other.test() == 'Box(String)' + """ + } + + // GROOVY-12509: dynamic Groovy and @TypeChecked reject a class that mixes + // private and public methods of one name, so this overload exists only here + @Test + void testSiblingClassPrivateMethodReferenceIsPreferredOverload() { + assertScript shell, ''' + @CompileStatic + class Outer { + static class Box { + private static String sm(String s) { 'sm(String)' } + static String sm(Object o) { 'sm(Object)' } + } + static class Other { + static String test() { + Function f = Box::sm + f.apply('x') + } + } + } + assert Outer.Other.test() == 'sm(String)' + ''' + } + // GROOVY-12510: a private method is not inherited (JLS 8.2); javac rejects these // references and dynamic Groovy throws MissingMethodException, even in the class // that declares the method @@ -3019,7 +3101,7 @@ final class MethodReferenceTest { 'def f = Sub.&sm' : 'sm', ] refs.each { ref, name -> - for (where in ['Outer', 'Box']) { + for (where in ['Outer', 'Box', 'Other']) { def err = shouldFail shell, """ @$mode class Outer { @@ -3030,6 +3112,9 @@ final class MethodReferenceTest { } static class Sub extends Box { } + static class Other { + ${where == 'Other' ? "static test() { $ref }" : ''} + } ${where == 'Outer' ? "static test() { $ref }" : ''} } """ @@ -3054,6 +3139,14 @@ final class MethodReferenceTest { } static class Sub extends Box { } + static class Other { + static String test() { + Function f = Box::im + Box b = new Sub() + Supplier g = b::im + f.apply(new Sub()) + g.get() + } + } static String test() { Function f = Box::im Box b = new Sub() @@ -3062,6 +3155,7 @@ final class MethodReferenceTest { } } assert Outer.test() == 'imim' + assert Outer.Other.test() == 'imim' """ } @@ -3946,6 +4040,41 @@ final class MethodReferenceTest { assert !bytecode.hasSequence(['INVOKEDYNAMIC applyAsInt(Ljava/lang/Integer;)Ljava/util/function/ToIntFunction;']) } + // GROOVY-12509 + @Test + void testSiblingClassPrivateMethodReferenceUsesDirectBootstrapTarget() { + def script = ''' + @CompileStatic + class C { + static class Box { + private static String sm() { 'sm' } + private String im() { 'im' } + } + static class Other { + static Supplier staticMethod() { + Box::sm + } + static Function instanceMethod() { + Box::im + } + } + } + ''' + + assertUsesInvokeDynamicFactory( + compileStaticBytecode(classNamePattern: 'C\\$Other', method: 'staticMethod', script), + 'INVOKEDYNAMIC get()Ljava/util/function/Supplier;', + 'java/lang/invoke/LambdaMetafactory.metafactory', + 'C$Box.sm()Ljava/lang/String;' + ) + assertUsesInvokeDynamicFactory( + compileStaticBytecode(classNamePattern: 'C\\$Other', method: 'instanceMethod', script), + 'INVOKEDYNAMIC apply()Ljava/util/function/Function;', + 'java/lang/invoke/LambdaMetafactory.metafactory', + 'C$Box.im()Ljava/lang/String;' + ) + } + @Test void testClassReferringStaticMethodUsesDirectBootstrapTarget() { def bytecode = compileStaticBytecode(classNamePattern: 'C', method: 'create', ''' diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy index 4cac7a28401..770df8ed87e 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy @@ -59,6 +59,37 @@ final class MethodCallsStaticCompilationTest extends MethodCallsSTCTest implemen assert astTrees['Foo$Bar$Baz'][1].contains('INVOKEVIRTUAL Foo.d ()I') } + // GROOVY-12509 + @Override @Test + void testCallToPrivateMethodOfSiblingClass() { + super.testCallToPrivateMethodOfSiblingClass() + String other = astTrees['Outer$Other'][1] + assert other.contains('INVOKESTATIC Outer$Box.sm ()Ljava/lang/String;') + assert other.contains('INVOKEVIRTUAL Outer$Box.im ()Ljava/lang/String;') + assert !other.contains('ScriptBytecodeAdapter.invoke') + } + + // GROOVY-12509: dynamic Groovy and @TypeChecked reject a class that mixes + // private and public methods of one name, so these overloads exist only here + @Test + void testPrivateOverloadOfSiblingClassIsPreferred() { + assertScript ''' + class Outer { + static class Box { + private String m(int i) { 'm(int)' } + String m(Object o) { 'm(Object)' } + private static String sm(String s) { 'sm(String)' } + static String sm(Object o) { 'sm(Object)' } + } + static class Other { + static String test() { new Box().m(1) + Box.sm('x') } + static String viaDelegate() { new Box().with { m(1) } } + } + } + assert Outer.Other.test() == 'm(int)sm(String)' + assert Outer.Other.viaDelegate() == 'm(int)' + ''' + } // GROOVY-12510 @Override @Test void testCallToPrivateMethodOfSuperclassThroughReceiverOfItsType() { @@ -72,6 +103,10 @@ final class MethodCallsStaticCompilationTest extends MethodCallsSTCTest implemen assert Outer.coerced() == 'im:sub' assert Outer.narrowed(sub) == 'im:sub' assert Outer.closure() == 'im:sub' + assert sub.viaSuper() == 'im:sub' + assert sub.viaCast() == 'im:sub' + assert Outer.Other.param(sub) == 'im:sub' + assert Outer.Other.local() == 'im:sub' ''' } diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/StaticCompileConstructorsTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/StaticCompileConstructorsTest.groovy index 330feff6480..41a51203fd7 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/StaticCompileConstructorsTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/StaticCompileConstructorsTest.groovy @@ -181,6 +181,20 @@ final class StaticCompileConstructorsTest extends ConstructorsSTCTest implements assert bar.contains('INVOKESPECIAL Foo. (Ljava/lang/String;)V') } + // GROOVY-12509: the sibling, its closure, its lambda and its anonymous class + // all call the private constructor directly + @Override @Test + void testPrivateConstructorOfSiblingClass() { + super.testPrivateConstructorOfSiblingClass() + def callers = astTrees.findAll { it.key.startsWith('Outer$Other') } + assert callers.size() == 4 + callers.each { name, tree -> + assert tree[1].contains('NEW Outer$Box') + assert tree[1].contains('INVOKESPECIAL Outer$Box. (Ljava/lang/String;Ljava/lang/String;)V') + assert !tree[1].contains('ScriptBytecodeAdapter.invokeNew') + } + } + @Test void testPrivateConstructorFromAnonymousInnerClass() { assertScript ''' From 5a679bef5d2e160969632ec6bddefe39005d6676 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 25 Oct 2026 12:22:08 -0700 Subject: [PATCH 03/38] GROOVY-12509: STC: allow private accessors of another class of the same 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. --- .../stc/StaticTypeCheckingVisitor.java | 16 ++- .../stc/FieldsAndPropertiesSTCTest.groovy | 125 ++++++++++++++++++ ...ieldsAndPropertiesStaticCompileTest.groovy | 11 ++ 3 files changed, 150 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 15af65dfea8..37af30d7ed1 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3145,7 +3145,7 @@ protected boolean existsProperty(final PropertyExpression pexp, final boolean re for (MethodNode method : findMethodsWithGenerated(wrapTypeIfNecessary(receiverType), setterName)) { if (method.getParameters().length == 1 && (!staticOnly || method.isStatic()) && (!publicOnly || method.isPublic()) // GROOVY-11319: - && hasAccessToMember(typeCheckingContext.getEnclosingClassNode(), method.getDeclaringClass(), method.getModifiers())) { + && isAccessibleAccessor(method, receiverType)) { setters.add(method); } } @@ -3216,7 +3216,7 @@ else if (field != null && enclosingTypes.contains(current) && !superReceiver && } if (getter != null && ((publicOnly && (!getter.isPublic() || propertyName.equals("class") || propertyName.equals("empty"))) // GROOVY-11319: - || !hasAccessToMember(typeCheckingContext.getEnclosingClassNode(), getter.getDeclaringClass(), getter.getModifiers()))) { + || !isAccessibleAccessor(getter, receiverType))) { getter = null; } @@ -3386,6 +3386,18 @@ private static MethodNode getGetterMethod(final ClassNode classNode, final Strin return getter; } + /** + * Determines if a getter or setter may be used through property syntax. A + * private accessor is reachable from every class of its nest (JLS 6.6.1), + * but only through its own class, because private members are not + * inherited (JLS 8.2). + */ + private boolean isAccessibleAccessor(final MethodNode accessor, final ClassNode receiverType) { + ClassNode enclosingClass = typeCheckingContext.getEnclosingClassNode(); + return hasAccessToMember(enclosingClass, accessor.getDeclaringClass(), accessor.getModifiers()) + || (accessor.isPrivate() && accessor.getDeclaringClass().equals(receiverType) && inSameNest(accessor.getDeclaringClass(), enclosingClass)); + } + private static boolean hasAccessToMember(final ClassNode accessor, final ClassNode receiver, final int modifiers) { if (Modifier.isPublic(modifiers) || accessor.equals(receiver) diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index c2f57b223d0..05f0d2c01f6 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2440,6 +2440,131 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { 'Cannot access field: x of class: P$Hidden from class: Q' } + // GROOVY-12509 + @Test + void testPrivateAccessorOfNestMateViaPropertySyntax() { + assertScript ''' + import java.util.function.Supplier + + class Outer { + static class Box { + List log = [] + private String getX() { 'gx' } + private boolean isB() { true } + private void setY(String s) { log << 'sy' + s } + private static String getZ() { 'gz' } + } + static class Other { + static String read() { new Box().x + new Box().b + Box.z } + static List write() { def box = new Box(); box.y = '1'; box.log } + static List mapConstructor() { new Box(y: '2').log } + static String viaClosure() { + def c = { -> new Box().x + Box.z } + c() + } + static String viaLambda() { + Supplier s = () -> new Box().x + s.get() + } + static String viaAnonymousClass() { + new Object() { + String get() { new Box().x } + }.get() + } + static String viaDelegate() { + new Box().with { x + b } + } + } + static String read() { new Box().x + Box.z } + static List write() { def box = new Box(); box.y = '3'; box.log } + } + assert Outer.Other.read() == 'gxtruegz' + assert Outer.Other.write() == ['sy1'] + assert Outer.Other.mapConstructor() == ['sy2'] + assert Outer.Other.viaClosure() == 'gxgz' + assert Outer.Other.viaLambda() == 'gx' + assert Outer.Other.viaAnonymousClass() == 'gx' + assert Outer.Other.viaDelegate() == 'gxtrue' + assert Outer.read() == 'gxgz' + assert Outer.write() == ['sy3'] + ''' + } + + // GROOVY-12509: dynamic Groovy also calls the accessors here, not the field + @Test + void testPrivateAccessorOfNestMateVersusPrivateField() { + assertScript ''' + class Outer { + static class Box { + private String w = 'field' + private String getW() { 'getter' } + private void setW(String s) { w = 'setter:' + s } + } + static class Other { + static String read() { new Box().w } + static String write() { def box = new Box(); box.w = 'v'; box.@w } + } + static String read() { new Box().w } + static String write() { def box = new Box(); box.w = 'v'; box.@w } + } + assert Outer.Other.read() == 'getter' + assert Outer.Other.write() == 'setter:v' + assert Outer.read() == 'getter' + assert Outer.write() == 'setter:v' + ''' + } + + // GROOVY-12509: private members are not inherited (JLS 8.2) + @Test + void testPrivateAccessorOrFieldOfNestMateSuperclassViaSubclass() { + for (expr in ['new Sub().x', 'new Sub().y = "1"', 'new Sub().f']) { + def name = expr.substring(10, 11) + shouldFailWithMessages """ + class Outer { + static class Box { + private String f = 'f' + private String getX() { 'gx' } + private void setY(String s) { } + } + static class Sub extends Box { + } + static class Other { + static test() { $expr } + } + static test() { $expr } + } + """, + "No such property: $name for class: Outer\$Sub", // sibling + "No such property: $name for class: Outer\$Sub" // outer class + } + + shouldFailWithMessages ''' + class Outer { + static class Box { + private static String getZ() { 'gz' } + } + static class Sub extends Box { + } + static class Other { + static test() { Sub.z } + } + } + ''', + 'No such property: z for Class or static property for class: Outer$Sub' + + shouldFailWithMessages ''' + class Outer { + static class Box { + private String f = 'f' + } + static class Sub extends Box { + def test() { f } + } + } + ''', + 'No such property: f for class: Outer$Sub' + } + // GROOVY-12314: package-private and protected fields that Java access rules // reject are not admitted via property syntax either; resolution falls // through to accessors, extensions and map/list handling. When nothing else diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy index 25009095874..09522c4b8ce 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy @@ -1253,4 +1253,15 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT assert inner.contains('GETFIELD Base.x') assert inner.contains('PUTFIELD Base.x') } + + // GROOVY-12509 + @Override @Test + void testPrivateAccessorOfNestMateViaPropertySyntax() { + super.testPrivateAccessorOfNestMateViaPropertySyntax() + String other = astTrees['Outer$Other'][1] + assert other.contains('INVOKEVIRTUAL Outer$Box.getX ()Ljava/lang/String;') + assert other.contains('INVOKEVIRTUAL Outer$Box.isB ()Z') + assert other.contains('INVOKEVIRTUAL Outer$Box.setY (Ljava/lang/String;)V') + assert other.contains('INVOKESTATIC Outer$Box.getZ ()Ljava/lang/String;') + } } From bf75cb4fd43b009f2c691a605f3709c05a49e25e Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 25 Oct 2026 12:48:42 -0700 Subject: [PATCH 04/38] GROOVY-12511: SC: use the enclosing instance for a private member of 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". --- .../asm/sc/StaticInvocationWriter.java | 56 ++++++++++++++-- .../stc/StaticTypeCheckingVisitor.java | 41 +++++++++++- .../stc/FieldsAndPropertiesSTCTest.groovy | 67 +++++++++++++++++++ .../transform/stc/MethodCallsSTCTest.groovy | 62 +++++++++++++++++ ...ieldsAndPropertiesStaticCompileTest.groovy | 16 +++++ 5 files changed, 232 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java index 9d0c010a762..31bb3a806b8 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java @@ -261,6 +261,15 @@ private static MethodNode getObjectMethod(final MethodNode method) { } private Expression thisObjectExpression(final ClassNode source, final ClassNode target) { + return thisObjectExpression(source, target, false); + } + + /** + * Returns the expression for the instance of {@code target} that code in + * {@code source} uses: "this", or an enclosing instance. With {@code exact}, + * the enclosing instance must be of {@code target} itself, not a subclass. + */ + private Expression thisObjectExpression(final ClassNode source, final ClassNode target, final boolean exact) { ClassNode thisType = source; while (ClassHelper.isGeneratedFunction(thisType)) { thisType = thisType.getOuterClass(); @@ -273,7 +282,7 @@ private Expression thisObjectExpression(final ClassNode source, final ClassNode } else { thisExpr = varX("thisObject", thisType); // adjust for multiple levels of nesting - while (!isSubtype(target, thisType)) { + while (exact ? !thisType.equals(target) : !isSubtype(target, thisType)) { FieldNode thisZero = thisType.getDeclaredField("this$0"); if (thisZero != null) { thisExpr = attrX(thisExpr, "this$0"); @@ -433,22 +442,30 @@ protected boolean writeDirectMethodCall(final MethodNode target, final boolean i boolean isThisImplicit = implicitThis; Expression theReceiver = receiver; MethodNode theTarget = target; - if (implicitThis && isThisExpression(receiver) - && (!isSubtype(declaringClass, enclosingClass) + ClassNode thisType = enclosingClass; + while (ClassHelper.isGeneratedFunction(thisType)) { + thisType = thisType.getOuterClass(); + } + boolean enclosingPrivate = isPrivateMethodOfEnclosingInstance(target, thisType); + if (isThisExpression(receiver) && (implicitThis + ? !isSubtype(declaringClass, enclosingClass) || enclosingPrivate // a method of Object called in a closure or lambda is not called on it, // unless it was resolved against the closure itself (TO_SELF) || (ClassHelper.isObjectType(declaringClass) && controller.isInGeneratedFunction() - && !isSubtype(ClassHelper.CLOSURE_TYPE, receiverType)))) { + && !isSubtype(ClassHelper.CLOSURE_TYPE, receiverType)) + : !controller.isStaticContext() && (!isSubtype(declaringClass, thisType) || enclosingPrivate) + && isMemberOfOuterClass(declaringClass, thisType, enclosingPrivate))) { if (target.isStatic()) { theReceiver = classX(declaringClass); } else if (controller.isStaticMethod() && !controller.isInGeneratedFunction()) { theReceiver = classX(enclosingClass); // method of the Class object, like getName() } else if (!controller.isInGeneratedFunction()) { - ClassNode outerType = getImplicitReceiverType(enclosingClass, declaringClass); + // a private method is called on the instance of its declaring class, not of a subclass + ClassNode outerType = enclosingPrivate ? null : getImplicitReceiverType(enclosingClass, declaringClass); theReceiver = propX(classX(outerType != null ? outerType : declaringClass), "this"); } else { - theReceiver = thisObjectExpression(enclosingClass, declaringClass); - MethodNode objectMethod = getObjectMethod(target); + theReceiver = thisObjectExpression(enclosingClass, declaringClass, enclosingPrivate); + MethodNode objectMethod = implicitThis ? getObjectMethod(target) : null; if (objectMethod != null && !enclosingClass.implementsInterface(ClassHelper.GENERATED_LAMBDA_TYPE)) { // a closure without a this object, e.g. after rehydrate(), uses its owner's method, // or its own method when it has no owner either, e.g. after dehydrate() @@ -484,6 +501,31 @@ protected boolean writeDirectMethodCall(final MethodNode target, final boolean i } } + /** + * Determines if a call on "this", in code of {@code thisType}, to the given + * method is a call to a private method of an enclosing class. A private + * method is not inherited (JLS 8.2), so a nested class that extends the + * declaring class calls the method on its enclosing instance, not on itself. + * A nested class with no enclosing instance, such as an enum constant body, + * calls it on itself. + */ + private static boolean isPrivateMethodOfEnclosingInstance(final MethodNode target, final ClassNode thisType) { + return target.isPrivate() && !target.isStatic() && !target.getDeclaringClass().equals(thisType) + && thisType.getDeclaredField("this$0") != null; + } + + /** + * Determines if an outer class of {@code enclosingClass} is {@code declaringClass} + * or, unless {@code exact}, one of its subclasses: then this.name() in an inner + * class names a method of an enclosing instance, as in dynamic Groovy. + */ + private static boolean isMemberOfOuterClass(final ClassNode declaringClass, final ClassNode enclosingClass, final boolean exact) { + for (ClassNode outer = enclosingClass.getOuterClass(); outer != null; outer = outer.getOuterClass()) { + if (exact ? outer.equals(declaringClass) : isSubtype(declaringClass, outer)) return true; + } + return false; + } + /** * Returns the trait helper method behind {@code target} when {@code target} is a * static method of a trait, which the trait interface forwards to its helper with diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 37af30d7ed1..1880037a137 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -47,6 +47,7 @@ import org.codehaus.groovy.ast.CodeVisitorSupport; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.DynamicVariable; +import org.codehaus.groovy.ast.EnumConstantClassNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.GenericsType.GenericsTypeName; @@ -3171,6 +3172,14 @@ && isAccessibleAccessor(method, receiverType)) { if (!handledTypes.add(current)) continue; FieldNode field = current.getDeclaredField(propertyName); + if (field != null && !(pexp instanceof AttributeExpression) && !current.equals(receiverType) + && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass()) + // GROOVY-12600, GROOVY-12610, GROOVY-12626: static compilation uses the field directly from any class of its nest + && !isStaticDispatchScope() && isDynamicallyUnreachableThroughSubclass(field, receiverType, pexp, !readMode) + // GROOVY-12533: in a class nested in the declaring class, this.name is the field of the enclosing instance, or of this instance without one + && !(isThisExpression(objectExpression) && isNestedIn(typeCheckingContext.getEnclosingClassNode(), field.getDeclaringClass()))) { + field = null; // JLS 8.2: find the outer class's field, if any, as Outer.this.name + } if (field == null) { if (current.getSuperClass() != null) queue.addFirst(current.getSuperClass()); @@ -3362,7 +3371,8 @@ else if (field != null && enclosingTypes.contains(current) && !superReceiver && if (pexp.isImplicitThis() && isThisExpression(objectExpression)) { Iterator iter = enclosingTypes.iterator(); // first enclosing is "this" type - boolean staticOnly = hasNoEnclosingInstance(iter.next()) || typeCheckingContext.isInStaticContext; + ClassNode thisType = iter.next(); // an enum constant body has no enclosing instance either + boolean staticOnly = hasNoEnclosingInstance(thisType) || thisType.redirect() instanceof EnumConstantClassNode || typeCheckingContext.isInStaticContext; while (iter.hasNext()) { ClassNode outer = iter.next(); // GROOVY-7994, GROOVY-11198: try "this.propertyName" as "Outer.propertyName" or "Outer.this.propertyName" @@ -3394,8 +3404,33 @@ private static MethodNode getGetterMethod(final ClassNode classNode, final Strin */ private boolean isAccessibleAccessor(final MethodNode accessor, final ClassNode receiverType) { ClassNode enclosingClass = typeCheckingContext.getEnclosingClassNode(); - return hasAccessToMember(enclosingClass, accessor.getDeclaringClass(), accessor.getModifiers()) - || (accessor.isPrivate() && accessor.getDeclaringClass().equals(receiverType) && inSameNest(accessor.getDeclaringClass(), enclosingClass)); + ClassNode declaringClass = accessor.getDeclaringClass(); + if (!declaringClass.equals(receiverType) && isInheritedPrivateMember(accessor.getModifiers(), declaringClass)) { + return false; + } + return hasAccessToMember(enclosingClass, declaringClass, accessor.getModifiers()) + || (accessor.isPrivate() && inSameNest(declaringClass, enclosingClass)); + } + + /** + * Determines if a private field or accessor of the given class, found on a + * subclass, is out of reach because private members are not inherited + * (JLS 8.2). The declaring class itself may still use it, as in dynamic + * Groovy. A nested subclass then finds the outer class's member through its + * enclosing instance, if it has one. + */ + private boolean isInheritedPrivateMember(final int modifiers, final ClassNode declaringClass) { + return Modifier.isPrivate(modifiers) && !declaringClass.equals(typeCheckingContext.getEnclosingClassNode()); + } + + /** + * Determines if {@code type} is nested, at any depth, in {@code outer}. + */ + private static boolean isNestedIn(final ClassNode type, final ClassNode outer) { + for (ClassNode cn = type.getOuterClass(); cn != null; cn = cn.getOuterClass()) { + if (cn.equals(outer)) return true; + } + return false; } private static boolean hasAccessToMember(final ClassNode accessor, final ClassNode receiver, final int modifiers) { diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index 05f0d2c01f6..d7b144bb797 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2565,6 +2565,73 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { 'No such property: f for class: Outer$Sub' } + // GROOVY-12511: a nested class that extends its outer class does not inherit the + // outer class's private fields and accessors, so an unqualified name refers to the + // enclosing instance, as in javac and dynamic Groovy; this.@name is its own field + @Test + void testPrivateFieldOfEnclosingClassFromNestedSubclass() { + assertScript ''' + class Box { + private String f = 'outer' + private static String sf = 'static' + private String getP() { 'p:' + f } + class Sub extends Box { + Sub() { this.@f = 'own' } + String read() { f } + String viaClosure() { def c = { -> f }; c() } + String property() { p } + String statics() { sf + Box.sf } + String write() { f = 'w'; [this.@f, f].join(',') } + } + String anonymous() { + new Box() { + { this.@f = 'own' } + String toString() { f + ',' + this.@f } + }.toString() + } + } + def box = new Box() + def sub = new Box.Sub(box) + assert sub.read() == 'outer' + assert sub.viaClosure() == 'outer' + assert sub.property() == 'p:outer' + assert sub.statics() == 'staticstatic' + assert box.anonymous() == 'outer,own' + assert sub.write() == 'own,w' + assert box.@f == 'w' + ''' + } + + // GROOVY-12511: without an enclosing instance there is no private accessor to use; + // dynamic Groovy throws MissingPropertyException. A private field of the outer + // class is the field of this instance there (GROOVY-12533). + @Test + void testPrivateFieldOfSuperclassFromNestedSubclassWithoutEnclosingInstance() { + [ + 'class Shape { private String getP() { "p" }; static class Circle extends Shape { def d() { p } } }' : 'p for class: Shape$Circle', + 'enum E { A { def d() { p } }; private String getP() { "p" } }' : 'p for class: E$1', + ].each { code, message -> + shouldFailWithMessages code, "No such property: $message" + } + + assertScript ''' + class Shape { + private String nm = 'shape' + private static String sf = 'static' + static class Circle extends Shape { + String d() { this.@nm + sf } + } + } + enum E { + A { String d() { sf } } + private static String sf = 'enum' + String d() { 'base' } + } + assert new Shape.Circle().d() == 'shapestatic' + assert E.A.d() == 'enum' + ''' + } + // GROOVY-12314: package-private and protected fields that Java access rules // reject are not admitted via property syntax either; resolution falls // through to accessors, extensions and map/list handling. When nothing else diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index efe9781f434..4a5910d90f7 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -647,6 +647,68 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12511: a nested class that extends its outer class does not inherit the + // outer class's private method, so an unqualified call refers to the enclosing + // instance, as in javac and dynamic Groovy + @Test + void testCallToPrivateMethodOfEnclosingClassUsesEnclosingInstance() { + assertScript ''' + import java.util.function.Supplier + + class Box { + String id = 'outer' + private String im() { 'im:' + id } + class Sub extends Box { + Sub() { id = 'sub' } + String implicit() { im() } + String explicit() { this.im() } + String viaClosure() { def c = { -> im() }; c() } + String viaLambda() { Supplier s = () -> im(); s.get() } + String explicitInClosure() { def c = { -> this.im() }; c() } + class In { + String deeper() { im() } + } + } + List anonymous() { + new Box() { + { id = 'anon' } + List test() { [im(), this.im(), { -> im() }()] } + }.test() + } + String anonymousInClosure() { + def c = { -> new Box() { { id = 'anon' }; String test() { im() } }.test() } + c() + } + } + def box = new Box() + def sub = new Box.Sub(box) + assert [sub.implicit(), sub.explicit(), sub.viaClosure(), sub.viaLambda(), sub.explicitInClosure()] == ['im:outer'] * 5 + assert new Box.Sub.In(sub).deeper() == 'im:outer' + assert box.anonymous() == ['im:outer'] * 3 + assert box.anonymousInClosure() == 'im:outer' + ''' + } + + // GROOVY-12511: this.m() in an inner class may name a method of the enclosing + // class, as in dynamic Groovy + @Test + void testCallToMethodOfEnclosingClassThroughThis() { + assertScript ''' + class Box { + String id = 'outer' + String om() { 'om:' + id } + private String im() { 'im:' + id } + class In { + String test() { this.om() + ',' + this.im() } + String viaClosure() { def c = { -> this.om() + ',' + this.im() }; c() } + } + } + def inner = new Box.In(new Box()) + assert inner.test() == 'om:outer,im:outer' + assert inner.viaClosure() == 'om:outer,im:outer' + ''' + } + // GROOVY-12509 @Test void testCallToPrivateMethodOfSiblingClass() { diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy index 09522c4b8ce..5b0da04f1ff 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy @@ -1264,4 +1264,20 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT assert other.contains('INVOKEVIRTUAL Outer$Box.setY (Ljava/lang/String;)V') assert other.contains('INVOKESTATIC Outer$Box.getZ ()Ljava/lang/String;') } + + // GROOVY-12533: without an enclosing instance, a private field of the outer + // class is the field of this instance + @Test + void testPrivateFieldOfSuperclassFromNestedSubclassWithoutEnclosingInstanceIsItsOwn() { + assertScript ''' + class Shape { + private String nm = 'shape' + static class Circle extends Shape { + Circle() { nm = 'circle' } + String d() { [nm, this.nm, { -> nm }()].join(',') } + } + } + assert new Shape.Circle().d() == 'circle,circle,circle' + ''' + } } From ee9162dec6e7f12ae3f9818c09119e57dd6f9ed8 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 00:13:34 -0800 Subject: [PATCH 05/38] GROOVY-12513: STC: allow a private field of a variable's declared type 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. --- .../stc/StaticTypeCheckingVisitor.java | 19 +++--- .../stc/FieldsAndPropertiesSTCTest.groovy | 58 +++++++++++++++++++ ...ieldsAndPropertiesStaticCompileTest.groovy | 14 +++++ 3 files changed, 84 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 1880037a137..1fe24525d1c 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3032,6 +3032,8 @@ protected boolean existsProperty(final PropertyExpression pexp, final boolean re if (propertyName == null) return false; Expression objectExpression = pexp.getObjectExpression(); + // a private member of the declared type is reachable when flow typing narrows the variable + ClassNode declaredType = getDeclaredType(objectExpression); if (objectExpression instanceof ConstructorCallExpression) { ClassNode rawType = getType(objectExpression).getPlainNodeReference(); inferDiamondType((ConstructorCallExpression) objectExpression, rawType); @@ -3146,7 +3148,7 @@ protected boolean existsProperty(final PropertyExpression pexp, final boolean re for (MethodNode method : findMethodsWithGenerated(wrapTypeIfNecessary(receiverType), setterName)) { if (method.getParameters().length == 1 && (!staticOnly || method.isStatic()) && (!publicOnly || method.isPublic()) // GROOVY-11319: - && isAccessibleAccessor(method, receiverType)) { + && isAccessibleAccessor(method, receiverType, declaredType)) { setters.add(method); } } @@ -3172,7 +3174,7 @@ && isAccessibleAccessor(method, receiverType)) { if (!handledTypes.add(current)) continue; FieldNode field = current.getDeclaredField(propertyName); - if (field != null && !(pexp instanceof AttributeExpression) && !current.equals(receiverType) + if (field != null && !(pexp instanceof AttributeExpression) && !current.equals(receiverType) && !current.equals(declaredType) && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass()) // GROOVY-12600, GROOVY-12610, GROOVY-12626: static compilation uses the field directly from any class of its nest && !isStaticDispatchScope() && isDynamicallyUnreachableThroughSubclass(field, receiverType, pexp, !readMode) @@ -3225,7 +3227,7 @@ else if (field != null && enclosingTypes.contains(current) && !superReceiver && } if (getter != null && ((publicOnly && (!getter.isPublic() || propertyName.equals("class") || propertyName.equals("empty"))) // GROOVY-11319: - || !isAccessibleAccessor(getter, receiverType))) { + || !isAccessibleAccessor(getter, receiverType, declaredType))) { getter = null; } @@ -3400,12 +3402,14 @@ private static MethodNode getGetterMethod(final ClassNode classNode, final Strin * Determines if a getter or setter may be used through property syntax. A * private accessor is reachable from every class of its nest (JLS 6.6.1), * but only through its own class, because private members are not - * inherited (JLS 8.2). + * inherited (JLS 8.2). Its own class may also be the declared type of a + * variable whose inferred type is a subclass. */ - private boolean isAccessibleAccessor(final MethodNode accessor, final ClassNode receiverType) { + private boolean isAccessibleAccessor(final MethodNode accessor, final ClassNode receiverType, final ClassNode declaredType) { ClassNode enclosingClass = typeCheckingContext.getEnclosingClassNode(); ClassNode declaringClass = accessor.getDeclaringClass(); - if (!declaringClass.equals(receiverType) && isInheritedPrivateMember(accessor.getModifiers(), declaringClass)) { + if (!declaringClass.equals(receiverType) && !declaringClass.equals(declaredType) + && isInheritedPrivateMember(accessor.getModifiers(), declaringClass)) { return false; } return hasAccessToMember(enclosingClass, declaringClass, accessor.getModifiers()) @@ -3619,7 +3623,8 @@ private boolean isFieldAccessible(final FieldNode field, final ClassNode receive return false; } boolean superField = isSuperExpression(expression.getObjectExpression()); - boolean exactReceiver = (!superField && receiver.equals(field.getDeclaringClass()) && !field.getDeclaringClass().isAbstract()); // GROOVY-7300, GROOVY-11358 + boolean exactReceiver = (!superField && !field.getDeclaringClass().isAbstract() // GROOVY-7300, GROOVY-11358 + && (receiver.equals(field.getDeclaringClass()) || field.getDeclaringClass().equals(getDeclaredType(expression.getObjectExpression())))); if (exactReceiver && delegationData == null && typeCheckingContext.getEnclosingClosure() == null && !(expression instanceof AttributeExpression) diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index d7b144bb797..736cb2dc528 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2632,6 +2632,64 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { ''' } + /** + * Uses a private field and a private getter through a variable declared with + * their class, which flow typing narrows to a subclass. Run by the static + * compilation test; @TypeChecked accesses these properties dynamically, and + * the meta-class of a subclass offers no private field of its superclass, so + * here they are only compiled, and property syntax for the field is rejected + * (GROOVY-12610). + */ + protected static final String PRIVATE_FIELD_THROUGH_DECLARED_TYPE = ''' + import java.util.function.Supplier + + class Outer { + static class Box { + private String f = 'f' + private String getX() { 'x' } + } + static class Sub extends Box { + } + static class Other { + static String read() { Box b = new Sub(); b.f + b.@f + b.x } + static String write() { Box b = new Sub(); b.f = 'w'; b.f += '!'; b.@f } + static String attribute() { Box b = new Sub(); b.@f = 'a'; b.@f } + static String viaClosure() { Box b = new Sub(); def c = { -> b.f }; c() } + static String viaLambda() { Box b = new Sub(); Supplier s = () -> b.f; s.get() } + static String narrowed(Box b) { if (b instanceof Sub) { return b.f + b.x }; null } + } + static String read() { Box b = new Sub(); b.f + b.x } + } + def sub = new Outer.Sub() + ''' + + // GROOVY-12513, GROOVY-12610: b.@f, b.x and the cast compile; b.f does not, because + // dynamic dispatch looks for the field on the meta-class of Sub + @Test + void testPrivateFieldThroughDeclaredTypeOfNarrowedVariable() { + shouldFailWithMessages PRIVATE_FIELD_THROUGH_DECLARED_TYPE, + *['No such property: f for class: Outer$Sub'] * 7 + } + + // GROOVY-12513: a private field is not inherited, so a receiver whose type is + // only the subclass still has no such property + @Test + void testPrivateFieldThroughSubclassTypedReceiver() { + for (code in ['def b = new Sub(); b.f', 'new Sub().f', 'Object o = new Sub(); if (o instanceof Sub) o.f']) { + shouldFailWithMessages """ + class Outer { + static class Box { + private String f = 'f' + } + static class Sub extends Box { + } + static test() { $code } + } + """, + 'No such property: f for class: Outer$Sub' + } + } + // GROOVY-12314: package-private and protected fields that Java access rules // reject are not admitted via property syntax either; resolution falls // through to accessors, extensions and map/list handling. When nothing else diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy index 5b0da04f1ff..b0aa8f0413e 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy @@ -1265,6 +1265,20 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT assert other.contains('INVOKESTATIC Outer$Box.getZ ()Ljava/lang/String;') } + // GROOVY-12513 + @Override @Test + void testPrivateFieldThroughDeclaredTypeOfNarrowedVariable() { + assertScript PRIVATE_FIELD_THROUGH_DECLARED_TYPE + ''' + assert Outer.Other.read() == 'ffx' + assert Outer.Other.write() == 'w!' + assert Outer.Other.attribute() == 'a' + assert Outer.Other.viaClosure() == 'f' + assert Outer.Other.viaLambda() == 'f' + assert Outer.Other.narrowed(sub) == 'fx' + assert Outer.read() == 'fx' + ''' + } + // GROOVY-12533: without an enclosing instance, a private field of the outer // class is the field of this instance @Test From 9015ff57e1a66418c6124fd5da6dfc5cac1b4e59 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 25 Oct 2026 12:49:19 -0700 Subject: [PATCH 06/38] GROOVY-12509, GROOVY-12510, GROOVY-12511: document private access between 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. --- src/spec/doc/core-object-orientation.adoc | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/spec/doc/core-object-orientation.adoc b/src/spec/doc/core-object-orientation.adoc index 267211d15d7..667ae3197dd 100644 --- a/src/spec/doc/core-object-orientation.adoc +++ b/src/spec/doc/core-object-orientation.adoc @@ -247,6 +247,10 @@ include::../test/ClassTest.groovy[tags=inner_class,indent=0] <2> inner class definition, inside its enclosing class <3> even being private, a field of the enclosing class is accessed by the inner class +As in Java, the classes nested in the same top-level class can also use each other's private members. +Private members are not inherited, though: when `Sub` extends `Base`, a private field or instance method of `Base` cannot be used through a `Sub` receiver, such as `new Sub().secret()`, except in `Base` itself. +In an inner class of `Base` that also extends `Base`, an unqualified `secret()` therefore calls the method of the enclosing `Base` instance. + There are some reasons for using inner classes: * They increase encapsulation by hiding the inner class from other classes, which do not need to know about it. This also leads to cleaner packages and workspaces. From d73831df6be7d47d1baf273b892d1ff54cc855b3 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 25 Oct 2026 18:27:57 -0700 Subject: [PATCH 07/38] GROOVY-12511: keep a private static field of the superclass reachable 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. --- .../stc/StaticTypeCheckingVisitor.java | 2 +- .../stc/FieldsAndPropertiesSTCTest.groovy | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 1fe24525d1c..8ce3ce86924 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3174,7 +3174,7 @@ && isAccessibleAccessor(method, receiverType, declaredType)) { if (!handledTypes.add(current)) continue; FieldNode field = current.getDeclaredField(propertyName); - if (field != null && !(pexp instanceof AttributeExpression) && !current.equals(receiverType) && !current.equals(declaredType) + if (field != null && !field.isStatic() && !(pexp instanceof AttributeExpression) && !current.equals(receiverType) && !current.equals(declaredType) && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass()) // GROOVY-12600, GROOVY-12610, GROOVY-12626: static compilation uses the field directly from any class of its nest && !isStaticDispatchScope() && isDynamicallyUnreachableThroughSubclass(field, receiverType, pexp, !readMode) diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index 736cb2dc528..fe0150a5f38 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2632,6 +2632,27 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12511: a private static field of the superclass stays reachable through + // the subclass, as in dynamic Groovy and like a private static method + @Test + void testPrivateStaticFieldOfSuperclassThroughNestedSubclass() { + assertScript ''' + class Outer { + private static String sf = 'static' + static class Sub extends Outer { + String read() { Sub.sf + new Sub().sf } + static String write() { Sub.sf = 'w'; Outer.sf } + } + static class Other { + static String read() { Sub.sf } + } + } + assert new Outer.Sub().read() == 'staticstatic' + assert Outer.Other.read() == 'static' + assert Outer.Sub.write() == 'w' + ''' + } + /** * Uses a private field and a private getter through a variable declared with * their class, which flow typing narrows to a subclass. Run by the static From bbe3b81bf47e1bf7e3f5266deb66fbaedaddfab2 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 25 Oct 2026 18:30:30 -0700 Subject: [PATCH 08/38] GROOVY-12523: STC: reject x.@name for a private field of a superclass 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. --- .../stc/StaticTypeCheckingVisitor.java | 16 +++++- src/spec/doc/core-object-orientation.adoc | 1 + .../stc/FieldsAndPropertiesSTCTest.groovy | 56 +++++++++++++++++++ ...ieldsAndPropertiesStaticCompileTest.groovy | 1 + 4 files changed, 72 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 8ce3ce86924..2fe1dea3458 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3612,8 +3612,10 @@ private boolean isStaticInContext(final MethodNode method) { * syntax to a field of a foreign nest that Java rules would reject — a * direct field access that static compilation cannot honour (no access * bridge exists). The deliberate dynamic escape hatches remain: attribute - * access (.@), and closure bodies (GROOVY-9195) — including delegate-resolved - * access — whose property dispatch stays dynamic-capable under static compilation. + * access (.@), except to a private field of a superclass through a receiver + * whose type is a subclass (JLS 8.2), which dynamic Groovy rejects too, and + * closure bodies (GROOVY-9195) — including delegate-resolved access — whose + * property dispatch stays dynamic-capable under static compilation. */ private boolean isFieldAccessible(final FieldNode field, final ClassNode receiver, final PropertyExpression expression, final String delegationData, final boolean lhsOfAssignment) { // GROOVY-12310: when the qualifying type itself is out of reach (e.g. a public @@ -3623,6 +3625,16 @@ private boolean isFieldAccessible(final FieldNode field, final ClassNode receive return false; } boolean superField = isSuperExpression(expression.getObjectExpression()); + // JLS 8.2: a private instance field is not a member of a subclass, and the meta-class + // of a subclass offers no private field of its superclass, so "sub.@name" fails at run + // time; "this.@name" and "super.@name" use the field directly, as in dynamic Groovy + if (expression instanceof AttributeExpression && !field.isStatic() && !superField + && !isThisExpression(expression.getObjectExpression()) + && !field.getDeclaringClass().equals(receiver) + && !field.getDeclaringClass().equals(getDeclaredType(expression.getObjectExpression())) + && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass())) { + return false; + } boolean exactReceiver = (!superField && !field.getDeclaringClass().isAbstract() // GROOVY-7300, GROOVY-11358 && (receiver.equals(field.getDeclaringClass()) || field.getDeclaringClass().equals(getDeclaredType(expression.getObjectExpression())))); if (exactReceiver && delegationData == null diff --git a/src/spec/doc/core-object-orientation.adoc b/src/spec/doc/core-object-orientation.adoc index 667ae3197dd..05c86bdf77f 100644 --- a/src/spec/doc/core-object-orientation.adoc +++ b/src/spec/doc/core-object-orientation.adoc @@ -249,6 +249,7 @@ include::../test/ClassTest.groovy[tags=inner_class,indent=0] As in Java, the classes nested in the same top-level class can also use each other's private members. Private members are not inherited, though: when `Sub` extends `Base`, a private field or instance method of `Base` cannot be used through a `Sub` receiver, such as `new Sub().secret()`, except in `Base` itself. +Within `Sub`, only `this.@name` and `super.@name` reach such a field directly. In an inner class of `Base` that also extends `Base`, an unqualified `secret()` therefore calls the method of the enclosing `Base` instance. There are some reasons for using inner classes: diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index fe0150a5f38..5b0dba57143 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2678,6 +2678,7 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { static String viaClosure() { Box b = new Sub(); def c = { -> b.f }; c() } static String viaLambda() { Box b = new Sub(); Supplier s = () -> b.f; s.get() } static String narrowed(Box b) { if (b instanceof Sub) { return b.f + b.x }; null } + static String cast() { Sub s = new Sub(); ((Box) s).@f } } static String read() { Box b = new Sub(); b.f + b.x } } @@ -2711,6 +2712,61 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { } } + // GROOVY-12523: a private field is not inherited, and the meta-class of a subclass + // offers no private field of its superclass, so "sub.@f" is rejected, as javac does + @Test + void testPrivateFieldOfSuperclassThroughSubclassTypedReceiverViaAttribute() { + for (code in [ + 'class Outer { private String f; static class Sub extends Outer { def t(Sub sub) { sub.@f } } }', + 'class Outer { private String f; static class Sub extends Outer { def t(Sub sub) { sub.@f = "w" } } }', + 'class Outer { private String f; static class Sub extends Outer { def t(Sub sub) { sub.@f += "!" } } }', + 'class Outer { private String f; static class Sub extends Outer { def t(Sub sub) { def c = { -> sub.@f }; c() } } }', + 'class Outer { private String f; static class Sub extends Outer { def t(Sub sub) { java.util.function.Supplier s = () -> sub.@f; s.get() } } }', + 'class Outer { private String f; static class Sub extends Outer { def t() { new Sub().@f } } }', + 'class Outer { private String f; static class Sub extends Outer { def t() { def d = new Sub(); d.@f } } }', + 'class Outer { private String f; static class Sub extends Outer { def t(Object o) { if (o instanceof Sub) o.@f } } }', + 'class Outer { private String f; static class Sub extends Outer { def t(Sub sub) { sub.with { it.@f } } } }', + 'class Outer { private String f; static class Sub extends Outer { def t(Sub2 s) { s.@f } }; static class Sub2 extends Sub { } }', + 'class Outer { private String f; static class Sub extends Outer { }; static class Other { static t(Sub sub) { sub.@f } } }', + 'class Outer { private String f; static class Sub extends Outer { }; static class Other { static t(Sub sub) { sub.@f = "w" } } }', + 'class Outer { private String f; class Sub extends Outer { def t(Sub sub) { sub.@f } } }', + ]) { + shouldFailWithMessages code, 'Cannot access field: f of class: Outer' + } + } + + // GROOVY-12523: "this.@f" and "super.@f" use the field directly, as dynamic Groovy + // does, and so does the declaring class itself + @Test + void testPrivateFieldOfSuperclassViaThisOrSuperAttribute() { + assertScript ''' + class Outer { + private String f = 'outer' + String read(Sub sub) { sub.@f } + String write(Sub sub) { sub.@f = 'w'; sub.@f } + static class Sub extends Outer { + String own() { this.@f = 'own'; this.@f } + String viaSuper() { super.@f } + } + static class Sub2 extends Sub { + String viaSuper2() { super.@f = 's2'; super.@f } + } + } + enum E { + A { String d() { this.@g } } + private String g = 'g' + abstract String d() + } + def sub = new Outer.Sub() + assert new Outer().read(sub) == 'outer' + assert new Outer().write(sub) == 'w' + assert sub.own() == 'own' + assert sub.viaSuper() == 'own' + assert new Outer.Sub2().viaSuper2() == 's2' + assert E.A.d() == 'g' + ''' + } + // GROOVY-12314: package-private and protected fields that Java access rules // reject are not admitted via property syntax either; resolution falls // through to accessors, extensions and map/list handling. When nothing else diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy index b0aa8f0413e..69642f8e895 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy @@ -1275,6 +1275,7 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT assert Outer.Other.viaClosure() == 'f' assert Outer.Other.viaLambda() == 'f' assert Outer.Other.narrowed(sub) == 'fx' + assert Outer.Other.cast() == 'f' assert Outer.read() == 'fx' ''' } From fb8c2702f5bb6f014d01ab1d818cc4404d761642 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 8 Nov 2026 01:48:13 -0800 Subject: [PATCH 09/38] GROOVY-12523: say which receivers reach a private superclass field directly 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. --- src/spec/doc/core-object-orientation.adoc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/spec/doc/core-object-orientation.adoc b/src/spec/doc/core-object-orientation.adoc index 05c86bdf77f..1340703cb29 100644 --- a/src/spec/doc/core-object-orientation.adoc +++ b/src/spec/doc/core-object-orientation.adoc @@ -249,7 +249,8 @@ include::../test/ClassTest.groovy[tags=inner_class,indent=0] As in Java, the classes nested in the same top-level class can also use each other's private members. Private members are not inherited, though: when `Sub` extends `Base`, a private field or instance method of `Base` cannot be used through a `Sub` receiver, such as `new Sub().secret()`, except in `Base` itself. -Within `Sub`, only `this.@name` and `super.@name` reach such a field directly. +Within `Sub`, `this.@name` and `super.@name` reach such a field of the current instance directly. +With static compilation, a receiver typed as `Base`, as in `((Base) other).@name`, reaches the field of that receiver. In an inner class of `Base` that also extends `Base`, an unqualified `secret()` therefore calls the method of the enclosing `Base` instance. There are some reasons for using inner classes: From d0435226561089a1b151fffd998fabd3f2c7defc Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 8 Nov 2026 01:48:13 -0800 Subject: [PATCH 10/38] GROOVY-12510: mark StaticTypeCheckingSupport.isInheritedPrivateMethod 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. --- .../groovy/transform/stc/StaticTypeCheckingSupport.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java index 481cde9058c..7699bc40c3e 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java @@ -19,6 +19,7 @@ package org.codehaus.groovy.transform.stc; import groovy.lang.GroovyClassLoader; +import groovy.transform.Internal; import org.apache.groovy.util.Maps; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ClassNode; @@ -3358,6 +3359,7 @@ public static List filterMethodsByVisibility(final List * @return {@code true} if the method is private and declared by another class * @since 7.0.0 */ + @Internal public static boolean isInheritedPrivateMethod(final MethodNode method, final ClassNode receiverType) { return method.isPrivate() && !(method instanceof ExtensionMethodNode) && !method.getDeclaringClass().equals(receiverType); From f5b98e5b48363bff74c7e3df97aab2cd9412326d Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 21 Nov 2026 22:03:20 -0800 Subject: [PATCH 11/38] GROOVY-12513: use a private member of a variable's declared type only 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. --- .../stc/StaticTypeCheckingVisitor.java | 25 +++- .../stc/FieldsAndPropertiesSTCTest.groovy | 115 ++++++++++++++---- .../transform/stc/MethodCallsSTCTest.groovy | 48 +++++++- .../MethodCallsStaticCompilationTest.groovy | 13 +- 4 files changed, 168 insertions(+), 33 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 2fe1dea3458..11a53dc3404 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3033,7 +3033,7 @@ protected boolean existsProperty(final PropertyExpression pexp, final boolean re Expression objectExpression = pexp.getObjectExpression(); // a private member of the declared type is reachable when flow typing narrows the variable - ClassNode declaredType = getDeclaredType(objectExpression); + ClassNode declaredType = getDeclaredReceiverType(objectExpression); if (objectExpression instanceof ConstructorCallExpression) { ClassNode rawType = getType(objectExpression).getPlainNodeReference(); inferDiamondType((ConstructorCallExpression) objectExpression, rawType); @@ -3174,7 +3174,7 @@ && isAccessibleAccessor(method, receiverType, declaredType)) { if (!handledTypes.add(current)) continue; FieldNode field = current.getDeclaredField(propertyName); - if (field != null && !field.isStatic() && !(pexp instanceof AttributeExpression) && !current.equals(receiverType) && !current.equals(declaredType) + if (field != null && !field.isStatic() && !(pexp instanceof AttributeExpression) && !current.equals(receiverType) && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass()) // GROOVY-12600, GROOVY-12610, GROOVY-12626: static compilation uses the field directly from any class of its nest && !isStaticDispatchScope() && isDynamicallyUnreachableThroughSubclass(field, receiverType, pexp, !readMode) @@ -3625,18 +3625,21 @@ private boolean isFieldAccessible(final FieldNode field, final ClassNode receive return false; } boolean superField = isSuperExpression(expression.getObjectExpression()); + // GROOVY-12513: statically compiled code of the field's nest reads the field of a variable's declared type directly + boolean declaredTypeField = field.getDeclaringClass().equals(getDeclaredReceiverType(expression.getObjectExpression())) + && inSameNest(field.getDeclaringClass(), typeCheckingContext.getEnclosingClassNode()); // JLS 8.2: a private instance field is not a member of a subclass, and the meta-class // of a subclass offers no private field of its superclass, so "sub.@name" fails at run // time; "this.@name" and "super.@name" use the field directly, as in dynamic Groovy if (expression instanceof AttributeExpression && !field.isStatic() && !superField && !isThisExpression(expression.getObjectExpression()) && !field.getDeclaringClass().equals(receiver) - && !field.getDeclaringClass().equals(getDeclaredType(expression.getObjectExpression())) + && !declaredTypeField && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass())) { return false; } boolean exactReceiver = (!superField && !field.getDeclaringClass().isAbstract() // GROOVY-7300, GROOVY-11358 - && (receiver.equals(field.getDeclaringClass()) || field.getDeclaringClass().equals(getDeclaredType(expression.getObjectExpression())))); + && (receiver.equals(field.getDeclaringClass()) || declaredTypeField)); if (exactReceiver && delegationData == null && typeCheckingContext.getEnclosingClosure() == null && !(expression instanceof AttributeExpression) @@ -6858,7 +6861,7 @@ && isOwnerClosure(typeCheckingContext.getEnclosingClosureStack())) { for (Receiver currentReceiver : receivers) { ClassNode receiverType = currentReceiver.getType(); if (isClassType(receiverType)) receiverType = receiverType.getPlainNodeReference(); - declaredReceiverType = getDeclaredType(objectExpression); + declaredReceiverType = getDeclaredReceiverType(objectExpression); try { mn = findMethod(receiverType, name, args); } finally { @@ -9304,6 +9307,18 @@ private List removeInheritedPrivateMethods(final List me return result; } + /** + * Returns the declared type of a variable through which a private member of + * that type may be used although flow typing narrows the variable to a + * subclass. Only statically compiled code uses the member of the declared + * type; dynamic dispatch looks for it on the meta-class of the object's + * class, which offers no private member of a superclass, so elsewhere this + * is {@code null}. + */ + private ClassNode getDeclaredReceiverType(final Expression expression) { + return isStaticDispatchScope() ? getDeclaredType(expression) : null; + } + /** * Returns the declared type of a variable, which flow typing may have narrowed. */ diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index 5b0dba57143..ef9755b5494 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2519,23 +2519,24 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { void testPrivateAccessorOrFieldOfNestMateSuperclassViaSubclass() { for (expr in ['new Sub().x', 'new Sub().y = "1"', 'new Sub().f']) { def name = expr.substring(10, 11) - shouldFailWithMessages """ - class Outer { - static class Box { - private String f = 'f' - private String getX() { 'gx' } - private void setY(String s) { } - } - static class Sub extends Box { - } - static class Other { - static test() { $expr } + for (sibling in [true, false]) { // one access per script, so that each one is rejected + shouldFailWithMessages """ + class Outer { + static class Box { + private String f = 'f' + private String getX() { 'gx' } + private void setY(String s) { } + } + static class Sub extends Box { + } + static class Other { + static test() { ${sibling ? expr : ''} } + } + static test() { ${sibling ? '' : expr} } } - static test() { $expr } - } - """, - "No such property: $name for class: Outer\$Sub", // sibling - "No such property: $name for class: Outer\$Sub" // outer class + """, + "No such property: $name for class: Outer\$Sub" + } } shouldFailWithMessages ''' @@ -2657,9 +2658,8 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { * Uses a private field and a private getter through a variable declared with * their class, which flow typing narrows to a subclass. Run by the static * compilation test; @TypeChecked accesses these properties dynamically, and - * the meta-class of a subclass offers no private field of its superclass, so - * here they are only compiled, and property syntax for the field is rejected - * (GROOVY-12610). + * the meta-class of a subclass offers no private member of its superclass, + * so there each of them is rejected. */ protected static final String PRIVATE_FIELD_THROUGH_DECLARED_TYPE = ''' import java.util.function.Supplier @@ -2685,12 +2685,81 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { def sub = new Outer.Sub() ''' - // GROOVY-12513, GROOVY-12610: b.@f, b.x and the cast compile; b.f does not, because - // dynamic dispatch looks for the field on the meta-class of Sub + // GROOVY-12513, GROOVY-12610: under type checking a private member of Box is not + // found through a variable that flow typing narrows to Sub, because dynamic dispatch + // looks for it on the meta-class of Sub; one access per script, so that each is rejected @Test void testPrivateFieldThroughDeclaredTypeOfNarrowedVariable() { - shouldFailWithMessages PRIVATE_FIELD_THROUGH_DECLARED_TYPE, - *['No such property: f for class: Outer$Sub'] * 7 + [ + 'Box b = new Sub(); b.f' : 'No such property: f for class: Outer$Sub', + 'Box b = new Sub(); b.f = "w"' : 'No such property: f for class: Outer$Sub', + 'Box b = new Sub(); b.f += "!"' : 'No such property: f for class: Outer$Sub', + 'Box b = new Sub(); b.@f' : 'Cannot access field: f of class: Outer$Box', + 'Box b = new Sub(); b.@f = "a"' : 'Cannot access field: f of class: Outer$Box', + 'Box b = new Sub(); b.x' : 'No such property: x for class: Outer$Sub', + 'Box b = new Sub(); def c = { -> b.f }; c()' : 'No such property: f for class: Outer$Sub', + 'Box b = new Sub(); def c = { -> b.@f }; c()' : 'Cannot access field: f of class: Outer$Box', + 'Box b = new Sub(); Supplier s = () -> b.f; s.get()' : 'No such property: f for class: Outer$Sub', + 'if (p instanceof Sub) { p.f }' : 'No such property: f for class: Outer$Sub', + 'if (p instanceof Sub) { p.@f }' : 'Cannot access field: f of class: Outer$Box', + 'if (p instanceof Sub) { p.x }' : 'No such property: x for class: Outer$Sub', + ].each { code, message -> + for (sibling in [true, false]) { + shouldFailWithMessages """ + import java.util.function.Supplier + + class Outer { + static class Box { + private String f = 'f' + private String getX() { 'x' } + } + static class Sub extends Box { + } + static class Other { + static test(Box p) { ${sibling ? code : ''} } + } + static test(Box p) { ${sibling ? '' : code} } + } + """, message + } + } + + // a variable that flow typing does not narrow is taken at its declared type + assertScript ''' + class Outer { + static class Box { + private String f = 'f' + private String getX() { 'x' } + } + static class Sub extends Box { + } + static class Other { + static String read(Box b) { b.f + b.@f + b.x } + } + static String read(Box b) { b.f + b.@f + b.x } + } + assert Outer.Other.read(new Outer.Box()) == 'ffx' + assert Outer.read(new Outer.Box()) == 'ffx' + ''' + } + + // GROOVY-12513: a private field of a class of another nest is not reached through + // a variable declared with that class, as through one of the subclass type + @Test + void testPrivateFieldOfOtherNestThroughDeclaredTypeOfNarrowedVariable() { + for (code in ['Base b = new Base.Sub(); b.@f', 'Base b = new Base.Sub(); b.@f = "w"']) { + shouldFailWithMessages """ + class Base { + private String f = 'f' + static class Sub extends Base { + } + } + class Other { + static test() { $code } + } + """, + 'Cannot access field: f of class: Base' + } } // GROOVY-12513: a private field is not inherited, so a receiver whose type is diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index 4a5910d90f7..2e47bb79e38 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -583,13 +583,34 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { } static class Other { static String param(Box b) { b.im() } - static String local() { Box b = new Sub(); b.im() } } static String param(Box b) { b.im() } - static String local() { Box b = new Sub(); b.im() } static Box make() { new Sub() } static String result() { make().im() } static String coerced() { (new Sub() as Box).im() } + } + def sub = new Outer.Sub() + ''' + + /** + * Calls a private method through a variable declared with its class, which + * flow typing narrows to a subclass. Run by the static compilation test; + * @TypeChecked calls the method dynamically, and the meta-class of a subclass + * offers no private method of its superclass, so there each call is rejected. + */ + protected static final String PRIVATE_METHOD_THROUGH_NARROWED_VARIABLE = ''' + class Outer { + static class Box { + String id = 'box' + private String im() { 'im:' + id } + } + static class Sub extends Box { + Sub() { id = 'sub' } + } + static class Other { + static String local() { Box b = new Sub(); b.im() } + } + static String local() { Box b = new Sub(); b.im() } static String narrowed(Box b) { if (b instanceof Sub) { return b.im() }; null } static String closure() { Box b = new Sub(); def c = { -> b.im() }; c() } } @@ -602,6 +623,29 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { assertScript PRIVATE_METHOD_THROUGH_DECLARING_TYPE } + // GROOVY-12513: one call per script, so that each one is rejected + @Test + void testCallToPrivateMethodOfSuperclassThroughNarrowedVariable() { + for (code in ['Box b = new Sub(); b.im()', 'if (p instanceof Sub) { p.im() }', 'Box b = new Sub(); def c = { -> b.im() }; c()']) { + for (sibling in [true, false]) { + shouldFailWithMessages """ + class Outer { + static class Box { + private String im() { 'im' } + } + static class Sub extends Box { + } + static class Other { + static test(Box p) { ${sibling ? code : ''} } + } + static test(Box p) { ${sibling ? '' : code} } + } + """, + 'Cannot find matching method Outer$Sub#im()' + } + } + } + // GROOVY-12510: an enum constant body and an anonymous subclass are nested in // the declaring class, so they find the private method on their enclosing class @Test diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy index 770df8ed87e..faf15507a24 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy @@ -98,14 +98,21 @@ final class MethodCallsStaticCompilationTest extends MethodCallsSTCTest implemen assert nested.viaSuper() == 'im:nested' assert nested.viaCast() == 'im:nested' assert Outer.param(sub) == 'im:sub' - assert Outer.local() == 'im:sub' assert Outer.result() == 'im:sub' assert Outer.coerced() == 'im:sub' - assert Outer.narrowed(sub) == 'im:sub' - assert Outer.closure() == 'im:sub' assert sub.viaSuper() == 'im:sub' assert sub.viaCast() == 'im:sub' assert Outer.Other.param(sub) == 'im:sub' + ''' + } + + // GROOVY-12513 + @Override @Test + void testCallToPrivateMethodOfSuperclassThroughNarrowedVariable() { + assertScript PRIVATE_METHOD_THROUGH_NARROWED_VARIABLE + ''' + assert Outer.local() == 'im:sub' + assert Outer.narrowed(sub) == 'im:sub' + assert Outer.closure() == 'im:sub' assert Outer.Other.local() == 'im:sub' ''' } From 63f431ccc41765e17645ae876ad350c738b97729 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 21 Nov 2026 22:19:09 -0800 Subject: [PATCH 12/38] GROOVY-12513: find a private method of a variable's declared type for 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. --- .../groovy/transform/stc/ClassTagSupport.java | 4 +- .../transform/stc/SecondPassExpression.java | 18 ++++- .../stc/StaticTypeCheckingVisitor.java | 68 +++++++++++++++---- .../transform/stc/MethodCallsSTCTest.groovy | 55 +++++++++++++++ .../MethodCallsStaticCompilationTest.groovy | 20 ++++++ 5 files changed, 147 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/ClassTagSupport.java b/src/main/java/org/codehaus/groovy/transform/stc/ClassTagSupport.java index c64cfb345d9..02421c421b4 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/ClassTagSupport.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/ClassTagSupport.java @@ -85,7 +85,7 @@ static ClassTagMatch matchAdditive(final StaticTypeCheckingVisitor visitor, fina for (Receiver receiver : receivers) { ClassNode receiverType = receiver.getType(); ClassNode plain = receiverType.getPlainNodeReference(); - List candidates = new ArrayList<>(visitor.findMethodsWithGenerated(plain, name)); + List candidates = new ArrayList<>(visitor.findCallableMethodsWithGenerated(plain, name)); candidates.addAll(findDGMMethodsForClassNode(visitor.getSourceUnit().getClassLoader(), plain, name)); ClassTagMatch best = bestMatch(candidates, receiver, receiverType, args.length); if (best != null) return best; @@ -144,7 +144,7 @@ static ClassTagMatch matchPreemption(final StaticTypeCheckingVisitor visitor, fi } } if (instanceIncumbent) { - candidates.addAll(visitor.findMethodsWithGenerated(plain, name)); + candidates.addAll(visitor.findCallableMethodsWithGenerated(plain, name)); } candidates.removeIf(candidate -> !declaresPreemptIntent(candidate)); diff --git a/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java b/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java index b4e394fcb51..9fc4f7633ee 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java @@ -18,6 +18,7 @@ */ package org.codehaus.groovy.transform.stc; +import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.expr.Expression; import java.util.Objects; @@ -30,15 +31,28 @@ class SecondPassExpression { private final Expression expression; private final T data; + private final ClassNode declaredReceiverType; SecondPassExpression(final Expression expression) { - this.expression = expression; - this.data = null; + this(expression, null, null); } SecondPassExpression(final Expression expression, final T data) { + this(expression, data, null); + } + + SecondPassExpression(final Expression expression, final T data, final ClassNode declaredReceiverType) { this.data = data; this.expression = expression; + this.declaredReceiverType = declaredReceiverType; + } + + /** + * Returns the declared type of the receiver variable through which the first + * pass found a private member of that type, or {@code null}. + */ + ClassNode getDeclaredReceiverType() { + return declaredReceiverType; } /** diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 11a53dc3404..4682858a34f 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -1252,7 +1252,7 @@ public Expression transform(final Expression expr) { ClassNode rhsType = isNullConstant(rightExpression) ? UNKNOWN_PARAMETER_TYPE : getInferredTypeFromTempInfo(rightExpression, getType(rightExpression)); - List candidates = findMethod(lhsType, assignName, rhsType); + List candidates = findMethodThrough(leftExpression, lhsType, assignName, rhsType); if (candidates.size() == 1) { MethodNode target = candidates.get(0); expression.putNodeMetaData(COMPOUND_ASSIGN_TARGET, target); @@ -1502,7 +1502,7 @@ && mapValueTypeToConvertTo(lType, arguments[0], arguments[1]) == null) { // GROOVY-5874: if left expression is a closure shared variable, a second pass should be done if (leftExpression instanceof VariableExpression vexp && vexp.isClosureSharedVariable()) { - typeCheckingContext.secondPassExpressions.add(new SecondPassExpression<>(expression)); + typeCheckingContext.secondPassExpressions.add(new SecondPassExpression<>(expression, null, getDeclaredReceiverType(vexp))); } } finally { typeCheckingContext.popEnclosingBinaryExpression(); @@ -6861,12 +6861,7 @@ && isOwnerClosure(typeCheckingContext.getEnclosingClosureStack())) { for (Receiver currentReceiver : receivers) { ClassNode receiverType = currentReceiver.getType(); if (isClassType(receiverType)) receiverType = receiverType.getPlainNodeReference(); - declaredReceiverType = getDeclaredReceiverType(objectExpression); - try { - mn = findMethod(receiverType, name, args); - } finally { - declaredReceiverType = null; - } + mn = findMethodThrough(objectExpression, receiverType, name, args); if (!mn.isEmpty()) { first = mn.get(0); // capture for error reporting chosenReceiver = currentReceiver; @@ -6889,14 +6884,21 @@ && isOwnerClosure(typeCheckingContext.getEnclosingClosureStack())) { // selection binds a method on the matched receiver, so a failed match leaves the // call - and its error reporting - exactly as written. if (mn.isEmpty() || ClassTagSupport.isPreemptionPossible(this)) { - ClassTagSupport.ClassTagMatch tagged = mn.isEmpty() + ClassTagSupport.ClassTagMatch tagged; + ClassNode previousDeclaredType = declaredReceiverType; + declaredReceiverType = getDeclaredReceiverType(objectExpression); // candidates as findMethod sees them + try { + tagged = mn.isEmpty() ? ClassTagSupport.matchAdditive(this, receivers, name, args) : ClassTagSupport.matchPreemption(this, chosenReceiver, mn, name, args); + } finally { + declaredReceiverType = previousDeclaredType; + } if (tagged != null) { ClassNode[] taggedArgs = tagged.expandArgumentTypes(args); ClassNode taggedReceiverType = tagged.receiver.getType(); if (isClassType(taggedReceiverType)) taggedReceiverType = taggedReceiverType.getPlainNodeReference(); - List taggedMn = findMethod(taggedReceiverType, name, taggedArgs); + List taggedMn = findMethodThrough(objectExpression, taggedReceiverType, name, taggedArgs); // the tagged overload must accept the call with its generics, else the call stays as written taggedMn.removeIf(taggedMethod -> !typeCheckMethodsWithGenerics(tagged.receiver.getType(), taggedArgs, taggedMethod)); if (!taggedMn.isEmpty()) { @@ -7048,7 +7050,7 @@ && isSuperExpression(objectExpression)) { // GROOVY-12470: super.m() invokes the if (objectExpression instanceof VariableExpression variable && variable.isClosureSharedVariable()) { // if the object expression is a closure shared variable we will have to perform a second pass - typeCheckingContext.secondPassExpressions.add(new SecondPassExpression<>(call, args)); + typeCheckingContext.secondPassExpressions.add(new SecondPassExpression<>(call, args, getDeclaredReceiverType(variable))); } } else { call.removeNodeMetaData(DIRECT_METHOD_CALL_TARGET); @@ -9021,7 +9023,7 @@ protected ClassNode inferComponentType(final ClassNode receiverType, final Class * Finds a matching method or reports a static type error when none is available. */ protected MethodNode findMethodOrFail(final Expression expr, final ClassNode receiver, final String name, final ClassNode... args) { - List methods = findMethod(receiver, name, args); + List methods = findMethodThrough(getOperatorReceiver(expr), receiver, name, args); if (methods.isEmpty() && (expr instanceof BinaryExpression be)) { MethodCallExpression call = callX(be.getLeftExpression(), name, be.getRightExpression()); methods = extension.handleMissingMethod(receiver, name, args(be.getLeftExpression()), args, call); @@ -9319,6 +9321,44 @@ private ClassNode getDeclaredReceiverType(final Expression expression) { return isStaticDispatchScope() ? getDeclaredType(expression) : null; } + /** + * Finds the methods for a call through {@code objectExpression}, which may + * reach a private method of its declared type, see {@link #getDeclaredReceiverType}. + */ + private List findMethodThrough(final Expression objectExpression, final ClassNode receiver, final String name, final ClassNode... args) { + return findMethodWithDeclaredType(getDeclaredReceiverType(objectExpression), receiver, name, args); + } + + private List findMethodWithDeclaredType(final ClassNode declaredType, final ClassNode receiver, final String name, final ClassNode... args) { + ClassNode previous = declaredReceiverType; + declaredReceiverType = declaredType; + try { + return findMethod(receiver, name, args); + } finally { + declaredReceiverType = previous; + } + } + + /** + * Returns the operand on which an operator calls its method: the left operand + * of a binary operator, or the operand itself, as {@link #findMethodOrFail} is + * given for {@code ++} and {@code --}. For {@code -x}, {@code +x} and {@code ~x} + * it is the unary expression, which has no declared type: static compilation + * calls their methods dynamically, as it does {@code putAt} for {@code x[i] = v}. + */ + private static Expression getOperatorReceiver(final Expression expr) { + return expr instanceof BinaryExpression be ? be.getLeftExpression() : expr; + } + + /** + * Returns the methods of {@code type} that a call through the current receiver + * may use: those of {@link #findMethodsWithGenerated} without a private method + * that {@code type} only inherits, as {@link #findMethod} selects them. + */ + List findCallableMethodsWithGenerated(final ClassNode type, final String name) { + return removeInheritedPrivateMethods(findMethodsWithGenerated(type, name), type, declaredReceiverType, true); + } + /** * Returns the declared type of a variable, which flow typing may have narrowed. */ @@ -10528,7 +10568,7 @@ public void performSecondPass() { ClassNode type = lowestUpperBound(classNodes); String message = getOperationName(((BinaryExpression) expression).getOperation().getType()); if (message != null) { - List methods = findMethod(type, message, getType(((BinaryExpression) expression).getRightExpression())); + List methods = findMethodWithDeclaredType(wrapper.getDeclaredReceiverType(), type, message, getType(((BinaryExpression) expression).getRightExpression())); if (methods.isEmpty()) { String methSpec = toMethodParametersString(message, getType(((BinaryExpression) expression).getRightExpression())); String stcError = String.format("The closure shared variable \"%s\" has been assigned with various types and the method %s does not exist in the lowest upper bound of those types: %s", target.getName(), methSpec, prettyPrintTypeName(type)); @@ -10549,7 +10589,7 @@ public void performSecondPass() { ClassNode type = lowestUpperBound(classNodes); MethodNode mct = call.getNodeMetaData(DIRECT_METHOD_CALL_TARGET); // we must check that such a method exists for the common type(s) - List methods = findMethod(type, mct.getName(), (ClassNode[]) wrapper.getData()); + List methods = findMethodWithDeclaredType(wrapper.getDeclaredReceiverType(), type, mct.getName(), (ClassNode[]) wrapper.getData()); if (methods.size() != 1) { String methSpec = toMethodParametersString(mct.getName(), extractTypesFromParameters(mct.getParameters())); String stcError = String.format("The closure shared variable \"%s\" has been assigned with various types and the method %s does not exist in the lowest upper bound of those types: %s", target.getName(), methSpec, prettyPrintTypeName(type)); diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index 2e47bb79e38..4c718b37418 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -646,6 +646,61 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { } } + /** + * Uses a private method of Box through a variable declared as Box, which flow + * typing narrows to Sub, in the place of {@code code}. + */ + protected static String privateMethodOfNarrowedVariable(String code) { + """ + import groovy.transform.stc.ClassTag + + class Outer { + static class Box { + String log = '' + private String plus(String s) { 'plus' + s } + private String negative() { 'negative' } + private String bitwiseNegate() { 'negate' } + private Box next() { log += 'next'; this } + private String getAt(int i) { 'getAt' + i } + private void putAt(int i, String v) { log += 'putAt' + i + v } + private boolean isCase(Object o) { o == 'in' } + private void plusAssign(String s) { log += 'plusAssign' + s } + private Class token(@ClassTag Class type) { type } + } + static class Sub extends Box { + } + static class Sub2 extends Sub { + } + static test() { Box b = new Sub(); $code } + } + """ + } + + // GROOVY-12513: operators, a compiler-supplied @ClassTag token and a closure that + // shares the variable with a later assignment; one use per script, so that each + // one is rejected + @Test + void testPrivateOperatorMethodsThroughNarrowedVariable() { + [ + 'b + "x"' : 'Cannot find matching method Outer$Sub#plus(java.lang.String)', + 'b++' : 'Cannot find matching method Outer$Sub#next()', + 'b[1]' : 'Cannot find matching method Outer$Sub#getAt(int)', + 'b += "y"' : 'Cannot find matching method Outer$Sub#plus(java.lang.String)', + 'b.token()' : 'Cannot find matching method Outer$Sub#token()', + 'def c = { -> b.plus("x") }; b = new Sub2(); c()' : 'Cannot find matching method Outer$Sub#plus(java.lang.String)', + 'def c = { -> b + "y" }; b = new Sub2(); c()' : 'Cannot find matching method Outer$Sub#plus(java.lang.String)', + ].each { code, message -> + shouldFailWithMessages privateMethodOfNarrowedVariable(code), message + } + } + + // GROOVY-12513: static compilation also calls the method of -x and ~x dynamically + @Test + void testPrivateUnaryOperatorMethodsThroughNarrowedVariable() { + shouldFailWithMessages privateMethodOfNarrowedVariable('-b'), 'Cannot find matching method Outer$Sub#negative()' + shouldFailWithMessages privateMethodOfNarrowedVariable('~b'), 'Cannot find matching method Outer$Sub#bitwiseNegate()' + } + // GROOVY-12510: an enum constant body and an anonymous subclass are nested in // the declaring class, so they find the private method on their enclosing class @Test diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy index faf15507a24..767dd5a052c 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy @@ -117,6 +117,26 @@ final class MethodCallsStaticCompilationTest extends MethodCallsSTCTest implemen ''' } + // GROOVY-12513 + @Override @Test + void testPrivateOperatorMethodsThroughNarrowedVariable() { + [ + 'b + "x"' : "'plusx'", + 'b++; b.log' : "'next'", + 'b[1]' : "'getAt1'", + 'b += "y"; b.log' : "'plusAssigny'", + '"in" in b' : 'true', + 'b.token()' : 'String', + 'def c = { -> b.plus("x") + (b + "y") }; b = new Sub2(); c()' : "'plusxplusy'", + ].each { code, value -> + assertScript privateMethodOfNarrowedVariable(code) + "assert Outer.test() == $value" + } + + // static compilation calls putAt for x[i] = v dynamically + shouldFailWithMessages privateMethodOfNarrowedVariable('b[2] = "v"'), + 'Cannot find matching method Outer\$Sub#putAt(int, java.lang.String)' + } + // GROOVY-12510: dynamic Groovy and @TypeChecked reject a class that mixes private // and public methods of one name. Through the subclass only the public method is // a member; through a variable declared with the superclass type both are From e4e2928d8cbc57799f030478a4fed1a1557e9b33 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 21 Nov 2026 22:21:11 -0800 Subject: [PATCH 13/38] GROOVY-12511: under type checking, let a skipped private field of a superclass 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. --- .../stc/StaticTypeCheckingVisitor.java | 4 ++- .../stc/FieldsAndPropertiesSTCTest.groovy | 30 +++++++++++++++++++ ...ieldsAndPropertiesStaticCompileTest.groovy | 9 ++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 4682858a34f..3a01b3d29f7 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3169,11 +3169,12 @@ && isAccessibleAccessor(method, receiverType, declaredType)) { } else if (receiverType.isInterface()) { queue.add(OBJECT_TYPE);//GROOVY-5585 } + boolean fieldHidden = false; while (!queue.isEmpty()) { ClassNode current = queue.remove(); if (!handledTypes.add(current)) continue; - FieldNode field = current.getDeclaredField(propertyName); + FieldNode field = fieldHidden ? null : current.getDeclaredField(propertyName); if (field != null && !field.isStatic() && !(pexp instanceof AttributeExpression) && !current.equals(receiverType) && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass()) // GROOVY-12600, GROOVY-12610, GROOVY-12626: static compilation uses the field directly from any class of its nest @@ -3181,6 +3182,7 @@ && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass()) // GROOVY-12533: in a class nested in the declaring class, this.name is the field of the enclosing instance, or of this instance without one && !(isThisExpression(objectExpression) && isNestedIn(typeCheckingContext.getEnclosingClassNode(), field.getDeclaringClass()))) { field = null; // JLS 8.2: find the outer class's field, if any, as Outer.this.name + fieldHidden = true; // nor does the meta-class offer a field of this name that it hides } if (field == null) { if (current.getSuperClass() != null) diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index ef9755b5494..dd0925e98c8 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2232,6 +2232,36 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { 'No such property: z for class: Base', 'No such property: z for class: Base' } + /** + * Reads f through a static nested subclass of Base, where the private field + * f of Base hides the public field f of Parent, with {@code sub} in Sub and + * {@code other} in another class nested in Base. + */ + protected static String hiddenFieldOfSuperclass(String sub, String other) { + """ + class Parent { + public int f = 1 + } + class Base extends Parent { + private int f = 2 + static class Sub extends Base { + static read(Sub s) { $sub } + } + static class Other { + static read(Sub s) { $other } + } + } + """ + } + + // GROOVY-12610: the meta-class of Sub offers neither the private field of Base nor + // the field of Parent that it hides, so dynamic dispatch finds no field f + @Test + void testPrivateFieldOfSuperclassHidingFieldViaStaticNestedSubclass() { + shouldFailWithMessages hiddenFieldOfSuperclass('s.f', ''), 'No such property: f for class: Base$Sub' + shouldFailWithMessages hiddenFieldOfSuperclass('', 's.f'), 'No such property: f for class: Base$Sub' + } + // GROOVY-12610: an inner class reaches the field through its enclosing instance, // and the declaring class reaches it on any subclass instance @Test diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy index 69642f8e895..e3983cd5e8c 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy @@ -1265,6 +1265,15 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT assert other.contains('INVOKESTATIC Outer$Box.getZ ()Ljava/lang/String;') } + // GROOVY-12610: static compilation reads the private field of Base + @Override @Test + void testPrivateFieldOfSuperclassHidingFieldViaStaticNestedSubclass() { + assertScript hiddenFieldOfSuperclass('s.f', 's.f') + ''' + assert Base.Sub.read(new Base.Sub()) == 2 + assert Base.Other.read(new Base.Sub()) == 2 + ''' + } + // GROOVY-12513 @Override @Test void testPrivateFieldThroughDeclaredTypeOfNarrowedVariable() { From f312d8af3d730bc89d041cbe7d809f1ef9815283 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 21 Nov 2026 22:23:44 -0800 Subject: [PATCH 14/38] GROOVY-12511: resolve this.name for a private accessor of the enclosing 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. --- .../stc/StaticTypeCheckingVisitor.java | 8 ++++++- .../stc/FieldsAndPropertiesSTCTest.groovy | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 3a01b3d29f7..2cfaab6ede2 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3373,12 +3373,18 @@ else if (field != null && enclosingTypes.contains(current) && !superReceiver && } } - if (pexp.isImplicitThis() && isThisExpression(objectExpression)) { + if (isThisExpression(objectExpression)) { Iterator iter = enclosingTypes.iterator(); // first enclosing is "this" type ClassNode thisType = iter.next(); // an enum constant body has no enclosing instance either boolean staticOnly = hasNoEnclosingInstance(thisType) || thisType.redirect() instanceof EnumConstantClassNode || typeCheckingContext.isInStaticContext; while (iter.hasNext()) { ClassNode outer = iter.next(); + // GROOVY-12511: an explicit "this.name" is the enclosing instance's property only where this + // class extends the enclosing class, whose private accessor it does not inherit (JLS 8.2) + if (!pexp.isImplicitThis() && !thisType.isDerivedFrom(outer)) { + staticOnly = staticOnly || hasNoEnclosingInstance(outer); + continue; + } // GROOVY-7994, GROOVY-11198: try "this.propertyName" as "Outer.propertyName" or "Outer.this.propertyName" Expression outerThis = staticOnly ? classX(outer) : propX(classX(outer), "this"); outerThis.putNodeMetaData("implicit outer this", Boolean.TRUE); // dispatched on "this" diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index dd0925e98c8..1bde33f9b88 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2232,6 +2232,27 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { 'No such property: z for class: Base', 'No such property: z for class: Base' } + // GROOVY-12511: in an inner subclass, this.name for a private accessor of the enclosing + // class is the enclosing instance's property, as without "this" and in dynamic Groovy + @Test + void testPrivateAccessorOfEnclosingSuperclassViaThisInInnerSubclass() { + assertScript ''' + class Outer { + String id = 'O' + String log = '' + private String getP() { 'p' + id } + private void setQ(String v) { log += id + v } + class Sub extends Outer { + Sub() { id = 'S' } + List read() { [p, this.p, { -> this.p }()] } + List write() { q = '1'; this.q = '2'; { -> this.q = '3' }(); [Outer.this.log, log] } + } + List test() { def sub = new Sub(); [sub.read(), sub.write()] } + } + assert new Outer().test() == [['pO', 'pO', 'pO'], ['O1O2O3', '']] + ''' + } + /** * Reads f through a static nested subclass of Base, where the private field * f of Base hides the public field f of Parent, with {@code sub} in Sub and From 70c5e07fd3fdf314609d006524b5b69500a96e64 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 21 Nov 2026 22:25:02 -0800 Subject: [PATCH 15/38] GROOVY-12523: say in the guide which mode reaches a private superclass 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. --- src/spec/doc/core-object-orientation.adoc | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/spec/doc/core-object-orientation.adoc b/src/spec/doc/core-object-orientation.adoc index 1340703cb29..8b191b8a66e 100644 --- a/src/spec/doc/core-object-orientation.adoc +++ b/src/spec/doc/core-object-orientation.adoc @@ -248,10 +248,12 @@ include::../test/ClassTest.groovy[tags=inner_class,indent=0] <3> even being private, a field of the enclosing class is accessed by the inner class As in Java, the classes nested in the same top-level class can also use each other's private members. -Private members are not inherited, though: when `Sub` extends `Base`, a private field or instance method of `Base` cannot be used through a `Sub` receiver, such as `new Sub().secret()`, except in `Base` itself. +Private members are not inherited, though, and the meta-class of a subclass offers none of its superclass. +When `Sub` extends `Base`, a private instance method of `Base` cannot be called through a `Sub` receiver, such as `new Sub().secret()`, except in `Base` itself, and outside `Base` `sub.@name` does not reach a private field of `Base` either. Within `Sub`, `this.@name` and `super.@name` reach such a field of the current instance directly. -With static compilation, a receiver typed as `Base`, as in `((Base) other).@name`, reaches the field of that receiver. -In an inner class of `Base` that also extends `Base`, an unqualified `secret()` therefore calls the method of the enclosing `Base` instance. +With static compilation, a receiver whose static type is `Base`, such as `((Base) sub).@name` or a variable declared as `Base`, reaches the private members of `Base`, and `sub.name` reads the field in `Base` and in the classes nested in it. +Dynamic code, `@TypeChecked` code included, finds the field through `sub.name` only in `Base` or in an inner class whose enclosing instance is a `Base`. +In an inner class of `Base` that also extends `Base`, `secret()`, `this.secret()`, `name` and `this.name` for a private member of `Base` therefore use the enclosing `Base` instance. There are some reasons for using inner classes: From be77774d593ac2ef1151a69f16430ead87afe65a Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sat, 21 Nov 2026 22:30:22 -0800 Subject: [PATCH 16/38] GROOVY-12511: under type checking, find an interface constant past a 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. --- .../stc/StaticTypeCheckingVisitor.java | 4 ++-- .../stc/FieldsAndPropertiesSTCTest.groovy | 21 +++++++++++++++++++ ...ieldsAndPropertiesStaticCompileTest.groovy | 8 +++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 2cfaab6ede2..f1d11c194a5 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3174,7 +3174,7 @@ && isAccessibleAccessor(method, receiverType, declaredType)) { ClassNode current = queue.remove(); if (!handledTypes.add(current)) continue; - FieldNode field = fieldHidden ? null : current.getDeclaredField(propertyName); + FieldNode field = fieldHidden && !current.isInterface() ? null : current.getDeclaredField(propertyName); if (field != null && !field.isStatic() && !(pexp instanceof AttributeExpression) && !current.equals(receiverType) && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass()) // GROOVY-12600, GROOVY-12610, GROOVY-12626: static compilation uses the field directly from any class of its nest @@ -3182,7 +3182,7 @@ && isInheritedPrivateMember(field.getModifiers(), field.getDeclaringClass()) // GROOVY-12533: in a class nested in the declaring class, this.name is the field of the enclosing instance, or of this instance without one && !(isThisExpression(objectExpression) && isNestedIn(typeCheckingContext.getEnclosingClassNode(), field.getDeclaringClass()))) { field = null; // JLS 8.2: find the outer class's field, if any, as Outer.this.name - fieldHidden = true; // nor does the meta-class offer a field of this name that it hides + fieldHidden = true; // nor does the meta-class offer a field of a superclass that it hides; a getter or an interface constant it does } if (field == null) { if (current.getSuperClass() != null) diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index 1bde33f9b88..9fc45e0ecda 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2283,6 +2283,27 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { shouldFailWithMessages hiddenFieldOfSuperclass('', 's.f'), 'No such property: f for class: Base$Sub' } + // GROOVY-12610: past the private field of Base, dynamic dispatch still finds an + // interface constant or a getter of a superclass, so type checking does too + @Test + void testInterfaceConstantOrGetterBeyondPrivateFieldOfSuperclass() { + assertScript PRIVATE_FIELD_BEFORE_CONSTANT_OR_GETTER + ''' + assert Base.Sub.read(new Base.Sub()) == [1, 3] + ''' + } + + protected static final String PRIVATE_FIELD_BEFORE_CONSTANT_OR_GETTER = ''' + interface I { int f = 1 } + class Parent { int getG() { 3 } } + class Base extends Parent implements I { + private int f = 2 + private int g = 4 + static class Sub extends Base { + static List read(Sub s) { [s.f, s.g] } + } + } + ''' + // GROOVY-12610: an inner class reaches the field through its enclosing instance, // and the declaring class reaches it on any subclass instance @Test diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy index e3983cd5e8c..74d40b009d4 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy @@ -1265,6 +1265,14 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT assert other.contains('INVOKESTATIC Outer$Box.getZ ()Ljava/lang/String;') } + // GROOVY-12610: static compilation reads the private fields of Base + @Override @Test + void testInterfaceConstantOrGetterBeyondPrivateFieldOfSuperclass() { + assertScript PRIVATE_FIELD_BEFORE_CONSTANT_OR_GETTER + ''' + assert Base.Sub.read(new Base.Sub()) == [2, 4] + ''' + } + // GROOVY-12610: static compilation reads the private field of Base @Override @Test void testPrivateFieldOfSuperclassHidingFieldViaStaticNestedSubclass() { From f781c3615502e5b0002edea177f8a01abb05f3f8 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 01:44:53 -0800 Subject: [PATCH 17/38] GROOVY-12523: also reject Sub.this.@name for a private field of the superclass 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. --- .../groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index 9fc45e0ecda..fea88f7278b 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2871,6 +2871,11 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { 'class Outer { private String f; static class Sub extends Outer { }; static class Other { static t(Sub sub) { sub.@f } } }', 'class Outer { private String f; static class Sub extends Outer { }; static class Other { static t(Sub sub) { sub.@f = "w" } } }', 'class Outer { private String f; class Sub extends Outer { def t(Sub sub) { sub.@f } } }', + // GROOVY-12514: Sub.this is a receiver of type Sub, not "this" + 'class Outer { private String f; static class Sub extends Outer { def t() { Sub.this.@f } } }', + 'class Outer { private String f; static class Sub extends Outer { def t() { Sub.this.@f = "w" } } }', + 'class Outer { private String f; static class Sub extends Outer { def t() { def c = { -> Sub.this.@f }; c() } } }', + 'class Outer { private String f; class Sub extends Outer { def t() { Sub.this.@f } } }', ]) { shouldFailWithMessages code, 'Cannot access field: f of class: Outer' } From af0a768876906670765149c30912ad415f7fdd28 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 07:11:28 -0800 Subject: [PATCH 18/38] GROOVY-12511: SC: call a private method of the enclosing class on the 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). --- .../asm/sc/StaticInvocationWriter.java | 22 ++++++++++ .../stc/StaticTypeCheckingVisitor.java | 25 +++++++++++ .../transform/stc/StaticTypesMarker.java | 4 +- .../transform/stc/MethodCallsSTCTest.groovy | 42 +++++++++++++++++++ 4 files changed, 92 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java index 31bb3a806b8..743a374ff2e 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java @@ -18,6 +18,7 @@ */ package org.codehaus.groovy.classgen.asm.sc; +import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; @@ -297,6 +298,22 @@ private Expression thisObjectExpression(final ClassNode source, final ClassNode } + /** + * Returns the expression for the enclosing instance of {@code receiver}, of + * type {@code receiverType}, that is an instance of {@code outer}: the chain + * of {@code this$0} fields from the receiver's class out to {@code outer}. + */ + private static Expression enclosingInstanceExpression(final Expression receiver, final ClassNode receiverType, final ClassNode outer) { + Expression expr = receiver; + for (ClassNode type = receiverType; !type.equals(outer); type = type.getOuterClass()) { + FieldNode thisZero = type.getDeclaredField("this$0"); + if (thisZero == null) throw new GroovyBugError("no enclosing instance of " + outer.getName() + " for " + receiverType.getName()); + expr = attrX(expr, "this$0"); + expr.setType(thisZero.getType()); + } + return expr; + } + /** * Attempts to make a direct method call on a bridge method, if it exists. */ @@ -475,6 +492,10 @@ && isMemberOfOuterClass(declaringClass, thisType, enclosingPrivate))) { } if (!(theReceiver instanceof VariableExpression)) isThisImplicit = false; theReceiver.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, theTarget.getDeclaringClass()); + } else if (receiver != null && currentCall != null && declaringClass.equals(currentCall.getNodeMetaData(StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER))) { + // GROOVY-12511: the receiver only inherits this private method of an outer class + theReceiver = enclosingInstanceExpression(receiver, receiverType, declaringClass); + theReceiver.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, declaringClass); } if (theReceiver != null && !target.isStatic() && !isSuperExpression(receiver) && !isClassWithSuper(receiver) && currentCall.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER) == null) { @@ -853,6 +874,7 @@ public void makeCall(final Expression origin, final Expression receiver, final E newMCE.setImplicitThis(false); MethodNode target = oldMCE.getMethodTarget(); newMCE.setMethodTarget(target); + newMCE.putNodeMetaData(StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER, oldMCE.getNodeMetaData(StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER)); if (target == null || !target.isVoidMethod()) newMCE.setNodeMetaData(StaticTypesMarker.INFERRED_TYPE, valuesType); newMCE.setSafe(true); diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index f1d11c194a5..c727df7bb81 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -398,6 +398,7 @@ import static org.codehaus.groovy.transform.stc.StaticTypesMarker.DELEGATION_METADATA; import static org.codehaus.groovy.transform.stc.StaticTypesMarker.DIRECT_METHOD_CALL_TARGET; import static org.codehaus.groovy.transform.stc.StaticTypesMarker.DYNAMIC_RESOLUTION; +import static org.codehaus.groovy.transform.stc.StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER; import static org.codehaus.groovy.transform.stc.StaticTypesMarker.IMPLICIT_RECEIVER; import static org.codehaus.groovy.transform.stc.StaticTypesMarker.INFERRED_RETURN_TYPE; import static org.codehaus.groovy.transform.stc.StaticTypesMarker.INFERRED_TYPE; @@ -6758,6 +6759,7 @@ public void visitMethodCallExpression(final MethodCallExpression call) { // inferred type should be a list of what sub-call returns storeType(call, extension.buildListType(getType(subcall))); storeTargetMethod(call, subcall.getNodeMetaData(DIRECT_METHOD_CALL_TARGET)); + call.putNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER, subcall.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER)); } typeCheckingContext.popEnclosingMethodCall(); return; @@ -7051,6 +7053,8 @@ && isSuperExpression(objectExpression)) { // GROOVY-12470: super.m() invokes the // the chosen method is supposed to be a call on delegate, owner, or thisObject // so store the delegation information for the static compiler storeReceiverData(call, chosenReceiver); + call.putNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER, // not kept from an earlier visit + isPrivateMethodOfEnclosingInstanceOfReceiver(targetMethod, objectExpression, chosenReceiver.getType()) ? targetMethod.getDeclaringClass() : null); receiver = chosenReceiver.getType(); if (mergeType || call.getNodeMetaData(INFERRED_TYPE) == null) @@ -9317,6 +9321,27 @@ private List removeInheritedPrivateMethods(final List me return result; } + /** + * Determines if a call through {@code objectExpression}, other than "this", + * selects a private method of an outer class that the receiver type only + * inherits (JLS 8.2): {@link #findMethod} offers the methods of the outer + * classes in code of the receiver's own class. The receiver itself has no + * such method, so dynamic Groovy calls it on the receiver's enclosing + * instance. It stays a member of the receiver in its declaring class, and + * through a variable declared with the declaring class under static + * compilation, see {@link #removeInheritedPrivateMethods}. + */ + private boolean isPrivateMethodOfEnclosingInstanceOfReceiver(final MethodNode method, final Expression objectExpression, final ClassNode receiverType) { + if (!method.isPrivate() || method.isStatic() || isThisExpression(objectExpression) + || isSuperExpression(objectExpression) || objectExpression instanceof ClassExpression) { + return false; + } + ClassNode declaringClass = method.getDeclaringClass(); + return !receiverType.equals(declaringClass) && receiverType.isDerivedFrom(declaringClass) + && receiverType.getOuterClasses().contains(declaringClass) + && removeInheritedPrivateMethods(List.of(method), receiverType, getDeclaredReceiverType(objectExpression), true).isEmpty(); + } + /** * Returns the declared type of a variable through which a private member of * that type may be used although flow typing narrows the variable to a diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypesMarker.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypesMarker.java index 6b838a72f26..c064db0ae7f 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypesMarker.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypesMarker.java @@ -73,5 +73,7 @@ public enum StaticTypesMarker { /** marks a method-reference ({@code ::}) argument type so overload selection prefers a functional-interface parameter over a {@code Closure} parameter: as a call argument a method reference is coerced only to a functional interface, so a {@code Closure} overload does not apply (unlike assignment, where {@code Closure c = Foo::bar} is valid) */ METHOD_REFERENCE_TYPE, /** on a {@code SwitchExpression} without a {@code default}: {@code Boolean.TRUE} when its labels were proven to cover every non-null selector value (a complete enum, an unconditional pattern, or a covered sealed hierarchy), so that matching nothing at run time means a constant or subtype was added after compilation */ - SWITCH_EXHAUSTIVE + SWITCH_EXHAUSTIVE, + /** GROOVY-12511: on a method call whose receiver, not {@code this}, only inherits the private method of an outer class that the call selects, that outer class: the method is called on the receiver's enclosing instance, as dynamic Groovy calls it */ + ENCLOSING_INSTANCE_OF_RECEIVER } diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index 4c718b37418..b044fa2e90e 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -788,6 +788,48 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12511: through a receiver other than "this", the private method of the + // enclosing class is the method of that receiver's enclosing instance, as in dynamic + // Groovy; in the declaring class itself it is the method of the receiver + @Test + void testCallToPrivateMethodOfEnclosingClassThroughOtherReceiverInInnerSubclass() { + assertScript ''' + import java.util.function.Supplier + + class Box { + String id + Box(String id) { this.id = id } + private String im() { 'im:' + id } + class Sub extends Box { + Sub() { super('self') } + String implicit() { im() } + String explicit() { this.im() } + String qualified() { Sub.this.im() } + String onNew() { new Sub().im() } + String onOther(Sub other) { other.im() } + String inClosure(Sub other) { def c = { -> other.im() }; c() } + String inLambda(Sub other) { Supplier s = () -> other.im(); s.get() } + String safe(Sub other) { other?.im() } + List spread(List others) { others*.im() } + class In { + String deeper(Sub other) { other.im() } + } + } + Sub make() { new Sub() } + String inBox(Sub sub) { sub.im() + ',' + new Sub().im() } + } + def a = new Box('A'), b = new Box('B') + def sa = a.make(), sb = b.make() + assert [sa.implicit(), sa.explicit(), sa.qualified(), sa.onNew()] == ['im:A'] * 4 + assert [sa.onOther(sb), sb.onOther(sa)] == ['im:B', 'im:A'] + assert [sa.inClosure(sb), sa.inLambda(sb), sa.safe(sb)] == ['im:B'] * 3 + assert sa.safe(null) == null + assert sa.spread([sb, sa]) == ['im:B', 'im:A'] + assert new Box.Sub.In(sa).deeper(sb) == 'im:B' + assert a.inBox(sb) == 'im:self,im:self' + ''' + } + // GROOVY-12511: this.m() in an inner class may name a method of the enclosing // class, as in dynamic Groovy @Test From 9c85a73fd6bd3147185da8c7a400672385839064 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 07:11:59 -0800 Subject: [PATCH 19/38] GROOVY-12513: state in the guide which receivers reach a private superclass 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. --- src/spec/doc/core-object-orientation.adoc | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/spec/doc/core-object-orientation.adoc b/src/spec/doc/core-object-orientation.adoc index 8b191b8a66e..bc1b23f7c51 100644 --- a/src/spec/doc/core-object-orientation.adoc +++ b/src/spec/doc/core-object-orientation.adoc @@ -248,12 +248,14 @@ include::../test/ClassTest.groovy[tags=inner_class,indent=0] <3> even being private, a field of the enclosing class is accessed by the inner class As in Java, the classes nested in the same top-level class can also use each other's private members. -Private members are not inherited, though, and the meta-class of a subclass offers none of its superclass. -When `Sub` extends `Base`, a private instance method of `Base` cannot be called through a `Sub` receiver, such as `new Sub().secret()`, except in `Base` itself, and outside `Base` `sub.@name` does not reach a private field of `Base` either. -Within `Sub`, `this.@name` and `super.@name` reach such a field of the current instance directly. -With static compilation, a receiver whose static type is `Base`, such as `((Base) sub).@name` or a variable declared as `Base`, reaches the private members of `Base`, and `sub.name` reads the field in `Base` and in the classes nested in it. -Dynamic code, `@TypeChecked` code included, finds the field through `sub.name` only in `Base` or in an inner class whose enclosing instance is a `Base`. -In an inner class of `Base` that also extends `Base`, `secret()`, `this.secret()`, `name` and `this.name` for a private member of `Base` therefore use the enclosing `Base` instance. +Private members are not inherited, though, and the meta-class of a subclass offers none of the private members of its superclass. +When `Sub` extends `Base`, a private instance method of `Base` cannot be called through a `Sub` receiver, such as `new Sub().secret()`, except in `Base` itself, and in an enum constant body or an anonymous subclass of `Base` created in a static context, which have no enclosing instance and call the method on themselves. +Outside `Base`, `sub.@name` does not reach a private field of `Base` either; within `Sub`, `this.@name` and `super.@name` reach such a field of the current instance directly. +With static compilation, a receiver whose static type is `Base`, such as `((Base) sub).@name` or a variable declared as `Base`, reaches the private members of `Base`, also where flow typing knows that the variable holds a `Sub`, as in Java. +`sub.name` reads the private field there only in `Base` and in the classes nested in `Base`; from another class of the same top-level class it is rejected. +Dynamic code looks a member up on the meta-class of the object's class, so it does not find a private member of `Base` through a variable that holds a `Sub`, and `@TypeChecked` rejects such a use where flow typing knows that the variable holds a `Sub`. +It finds the field through `sub.name` only in `Base` or in an inner class whose enclosing instance is a `Base`. +In an inner class of `Base` that also extends `Base`, `secret()`, `this.secret()`, `name` and `this.name` for a private member of `Base` therefore use the enclosing `Base` instance, and `other.secret()`, for another instance `other` of that inner class, uses the enclosing instance of `other`. There are some reasons for using inner classes: From d88fdcce4dd7f35d1947219098464cf9a2db700e Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 08:20:00 -0800 Subject: [PATCH 20/38] GROOVY-12511: keep this.@name out of the enclosing-instance property 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. --- .../transform/stc/StaticTypeCheckingVisitor.java | 2 +- .../stc/FieldsAndPropertiesSTCTest.groovy | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index c727df7bb81..37c6d928601 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3374,7 +3374,7 @@ else if (field != null && enclosingTypes.contains(current) && !superReceiver && } } - if (isThisExpression(objectExpression)) { + if (isThisExpression(objectExpression) && !(pexp instanceof AttributeExpression)) { // this.@name is a field of this class Iterator iter = enclosingTypes.iterator(); // first enclosing is "this" type ClassNode thisType = iter.next(); // an enum constant body has no enclosing instance either boolean staticOnly = hasNoEnclosingInstance(thisType) || thisType.redirect() instanceof EnumConstantClassNode || typeCheckingContext.isInStaticContext; diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index fea88f7278b..fc9cdd6e083 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2253,6 +2253,21 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12511: this.@name is a field of this class, not the enclosing instance's + // property, so a private getter of the enclosing superclass does not stand in for it + @Test + void testPrivateGetterOfEnclosingSuperclassViaThisAttributeInInnerSubclass() { + shouldFailWithMessages ''' + class Outer { + private String getP() { 'p' } + class Sub extends Outer { + def t() { this.@p } + } + } + ''', + 'No such attribute: p for class: Outer$Sub' + } + /** * Reads f through a static nested subclass of Base, where the private field * f of Base hides the public field f of Parent, with {@code sub} in Sub and From dee4934baa00f9ae794d24ba0e0a93614939dd73 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 08:25:06 -0800 Subject: [PATCH 21/38] GROOVY-12510: invent a property accessor only where Verifier will emit 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. --- .../stc/StaticTypeCheckingVisitor.java | 7 +++- .../transform/stc/MethodCallsSTCTest.groovy | 38 +++++++++++++++++++ .../transform/stc/MethodReferenceTest.groovy | 35 +++++++++++++++++ 3 files changed, 79 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 37c6d928601..bb7ce7f626f 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -5119,12 +5119,15 @@ private static ClassNode wrapClosureType(final ClassNode returnType) { private static MethodNode findPropertyMethod(final ClassNode type, final String name) { for (ClassNode cn = type; cn != null; cn = cn.getSuperClass()) { for (PropertyNode pn : cn.getProperties()) { + // only an accessor that Verifier will emit; an explicit one may have been dropped, e.g. one that is private and only inherited if (name.equals(pn.getGetterNameOrDefault())) { + if (!generatesPropertyGetter(pn, name)) return null; MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC | (pn.isStatic() ? Opcodes.ACC_STATIC : 0), pn.getType(), Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, null); node.setDeclaringClass(pn.getDeclaringClass()); node.setSynthetic(true); return node; } else if (name.equals(pn.getSetterNameOrDefault()) && !pn.isFinal()) { + if (pn.getSetterBlock() == null && (pn.isPrivate() || !needsGeneratedAccessor(cn, cn.getSetterMethod(name, false)))) return null; MethodNode node = new MethodNode(name, Opcodes.ACC_PUBLIC | (pn.isStatic() ? Opcodes.ACC_STATIC : 0), VOID_TYPE, new Parameter[]{new Parameter(pn.getType(), pn.getName())}, ClassNode.EMPTY_ARRAY, null); node.setDeclaringClass(pn.getDeclaringClass()); node.setSynthetic(true); @@ -9249,7 +9252,9 @@ protected List findMethod(ClassNode receiver, final String name, fin String pname = extractPropertyNameFromMethodName("set", name); if (pname != null) { PropertyNode property = findProperty(receiver, pname); - if (property != null && !property.isFinal()) { + if (property != null && !property.isFinal() && property.getDeclaringClass() != null + // only a setter that Verifier will emit; an explicit one may have been dropped, e.g. one that is private and only inherited + && (property.getSetterBlock() != null || (!property.isPrivate() && needsGeneratedAccessor(property.getDeclaringClass(), property.getDeclaringClass().getSetterMethod(name, false))))) { ClassNode type = property.getOriginType(); // GROOVY-12229: the synthetic mutator accepts whatever the property // assignment form accepts, including implicit conversions like GString-String diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index b044fa2e90e..e9070c8fab2 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -788,6 +788,44 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12510: a property's explicit private accessor is not inherited, and Verifier + // generates no public one beside it; a generated accessor is still found + @Test + void testPrivateAccessorOfPropertyOfSuperclassThroughSubclass() { + for (code in ['def s = new Sub(); s.setP("x")', 'new Sub().getQ()']) { + def name = code.contains('setP') ? 'setP(java.lang.String)' : 'getQ()' + shouldFailWithMessages """ + class Outer { + static class Box { + String p, q + private void setP(String v) { p = v } + private String getQ() { q } + } + static class Sub extends Box { + } + static class Other { + static test() { $code } + } + } + """, + "Cannot find matching method Outer\$Sub#$name" + } + + assertScript ''' + class Outer { + static class Box { + String r = 'r' + } + static class Sub extends Box { + } + static class Other { + static test() { def s = new Sub(); s.setR('w'); s.getR() } + } + } + assert Outer.Other.test() == 'w' + ''' + } + // GROOVY-12511: through a receiver other than "this", the private method of the // enclosing class is the method of that receiver's enclosing instance, as in dynamic // Groovy; in the declaring class itself it is the method of the receiver diff --git a/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy b/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy index b252b2baa36..9283db76c61 100644 --- a/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy @@ -3087,6 +3087,41 @@ final class MethodReferenceTest { ''' } + // GROOVY-12510: a property's explicit private accessor is not inherited either, and + // Verifier generates no public one beside it, so there is none to refer to + @ParameterizedTest + @ValueSource(strings=['TypeChecked','CompileStatic']) + void testPrivateAccessorOfPropertyOfSuperclassReferenceThroughSubclass(String mode) { + def refs = [ + 'Consumer f = new Sub()::setP' : 'setP', + 'BiConsumer f = Sub::setP' : 'setP', + 'Supplier f = new Sub()::getQ' : 'getQ', + ] + refs.each { ref, name -> + def err = shouldFail shell, """ + import java.util.function.* + @$mode + class Outer { + static class Box { + String p, q + private void setP(String v) { p = v } + private String getQ() { q } + } + static class Sub extends Box { + } + static class Other { + static test() { $ref } + } + } + """ + if (mode == 'TypeChecked') { + assert err.message.contains("Cannot find matching method Outer\$Sub#${name}.") + } else { + assert err.message =~ /Failed to find (class )?method '${name}\(.*\)'.* for the type: Outer[$]Sub/ + } + } + } + // GROOVY-12510: a private method is not inherited (JLS 8.2); javac rejects these // references and dynamic Groovy throws MissingMethodException, even in the class // that declares the method From 12687c7bd159120e973f5d3da8cb81320696c02b Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 08:28:34 -0800 Subject: [PATCH 22/38] GROOVY-12510: check the second pass for a closure shared variable in 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. --- .../transform/stc/SecondPassExpression.java | 16 ++++++++-- .../stc/StaticTypeCheckingVisitor.java | 23 +++++++++++--- .../transform/stc/MethodCallsSTCTest.groovy | 30 +++++++++++++++++++ .../MethodCallsStaticCompilationTest.groovy | 7 +++++ 4 files changed, 69 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java b/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java index 9fc4f7633ee..9877dcde631 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java @@ -32,19 +32,29 @@ class SecondPassExpression { private final Expression expression; private final T data; private final ClassNode declaredReceiverType; + private final ClassNode enclosingClass; SecondPassExpression(final Expression expression) { - this(expression, null, null); + this(expression, null, null, null); } SecondPassExpression(final Expression expression, final T data) { - this(expression, data, null); + this(expression, data, null, null); } - SecondPassExpression(final Expression expression, final T data, final ClassNode declaredReceiverType) { + SecondPassExpression(final Expression expression, final T data, final ClassNode declaredReceiverType, final ClassNode enclosingClass) { this.data = data; this.expression = expression; this.declaredReceiverType = declaredReceiverType; + this.enclosingClass = enclosingClass; + } + + /** + * Returns the class whose code the first pass checked the expression in, + * which decides the private members it may use, or {@code null}. + */ + ClassNode getEnclosingClass() { + return enclosingClass; } /** diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index bb7ce7f626f..085d0555afa 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -1503,7 +1503,7 @@ && mapValueTypeToConvertTo(lType, arguments[0], arguments[1]) == null) { // GROOVY-5874: if left expression is a closure shared variable, a second pass should be done if (leftExpression instanceof VariableExpression vexp && vexp.isClosureSharedVariable()) { - typeCheckingContext.secondPassExpressions.add(new SecondPassExpression<>(expression, null, getDeclaredReceiverType(vexp))); + typeCheckingContext.secondPassExpressions.add(new SecondPassExpression<>(expression, null, getDeclaredReceiverType(vexp), typeCheckingContext.getEnclosingClassNode())); } } finally { typeCheckingContext.popEnclosingBinaryExpression(); @@ -7065,7 +7065,7 @@ && isSuperExpression(objectExpression)) { // GROOVY-12470: super.m() invokes the if (objectExpression instanceof VariableExpression variable && variable.isClosureSharedVariable()) { // if the object expression is a closure shared variable we will have to perform a second pass - typeCheckingContext.secondPassExpressions.add(new SecondPassExpression<>(call, args, getDeclaredReceiverType(variable))); + typeCheckingContext.secondPassExpressions.add(new SecondPassExpression<>(call, args, getDeclaredReceiverType(variable), typeCheckingContext.getEnclosingClassNode())); } } else { call.removeNodeMetaData(DIRECT_METHOD_CALL_TARGET); @@ -9377,6 +9377,21 @@ private List findMethodWithDeclaredType(final ClassNode declaredType } } + /** + * Finds the methods again for an expression that the first pass checked, + * with the declared receiver type and in the class of the first pass, so + * that the same private members are found. + */ + private List findMethodInSecondPass(final SecondPassExpression wrapper, final ClassNode receiver, final String name, final ClassNode... args) { + ClassNode enclosingClass = wrapper.getEnclosingClass(); + if (enclosingClass != null) typeCheckingContext.pushEnclosingClassNode(enclosingClass); + try { + return findMethodWithDeclaredType(wrapper.getDeclaredReceiverType(), receiver, name, args); + } finally { + if (enclosingClass != null) typeCheckingContext.popEnclosingClassNode(); + } + } + /** * Returns the operand on which an operator calls its method: the left operand * of a binary operator, or the operand itself, as {@link #findMethodOrFail} is @@ -10606,7 +10621,7 @@ public void performSecondPass() { ClassNode type = lowestUpperBound(classNodes); String message = getOperationName(((BinaryExpression) expression).getOperation().getType()); if (message != null) { - List methods = findMethodWithDeclaredType(wrapper.getDeclaredReceiverType(), type, message, getType(((BinaryExpression) expression).getRightExpression())); + List methods = findMethodInSecondPass(wrapper, type, message, getType(((BinaryExpression) expression).getRightExpression())); if (methods.isEmpty()) { String methSpec = toMethodParametersString(message, getType(((BinaryExpression) expression).getRightExpression())); String stcError = String.format("The closure shared variable \"%s\" has been assigned with various types and the method %s does not exist in the lowest upper bound of those types: %s", target.getName(), methSpec, prettyPrintTypeName(type)); @@ -10627,7 +10642,7 @@ public void performSecondPass() { ClassNode type = lowestUpperBound(classNodes); MethodNode mct = call.getNodeMetaData(DIRECT_METHOD_CALL_TARGET); // we must check that such a method exists for the common type(s) - List methods = findMethodWithDeclaredType(wrapper.getDeclaredReceiverType(), type, mct.getName(), (ClassNode[]) wrapper.getData()); + List methods = findMethodInSecondPass(wrapper, type, mct.getName(), (ClassNode[]) wrapper.getData()); if (methods.size() != 1) { String methSpec = toMethodParametersString(mct.getName(), extractTypesFromParameters(mct.getParameters())); String stcError = String.format("The closure shared variable \"%s\" has been assigned with various types and the method %s does not exist in the lowest upper bound of those types: %s", target.getName(), methSpec, prettyPrintTypeName(type)); diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index e9070c8fab2..eda8c41aa9d 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -788,6 +788,36 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + /** + * Calls a private method of Box, and an operator of Box, in code of Box + * through a closure shared variable that is assigned two subclasses. + */ + protected static final String PRIVATE_METHOD_OF_SHARED_VARIABLE_IN_DECLARING_CLASS = ''' + @groovy.transform.TypeChecked + class Outer { + static class Box { + String id = 'box' + private String im() { 'im:' + id } + private String plus(String x) { 'plus:' + id + x } + static String call() { Sub s = new Sub1(); def c = { -> s.im() }; s = new Sub2(); c() } + static String operator() { Sub s = new Sub1(); def c = { -> s + 'x' }; s = new Sub2(); c() } + } + static class Sub extends Box { } + static class Sub1 extends Sub { Sub1() { id = 'sub1' } } + static class Sub2 extends Sub { Sub2() { id = 'sub2' } } + } + ''' + + // GROOVY-12510: the second pass for a closure shared variable checks the call in + // the class that makes it, here the declaring class of the private method + @Test + void testPrivateMethodOfClosureSharedVariableInDeclaringClass() { + assertScript PRIVATE_METHOD_OF_SHARED_VARIABLE_IN_DECLARING_CLASS + ''' + assert Outer.Box.call() == 'im:sub2' + assert Outer.Box.operator() == 'plus:sub2x' + ''' + } + // GROOVY-12510: a property's explicit private accessor is not inherited, and Verifier // generates no public one beside it; a generated accessor is still found @Test diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy index 767dd5a052c..d494502084d 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/MethodCallsStaticCompilationTest.groovy @@ -117,6 +117,13 @@ final class MethodCallsStaticCompilationTest extends MethodCallsSTCTest implemen ''' } + // GROOVY-12510: compiles; running it throws ClassCastException, as it does for a + // public method, because static compilation casts the shared variable to Sub1 + @Override @Test + void testPrivateMethodOfClosureSharedVariableInDeclaringClass() { + shell.parse(PRIVATE_METHOD_OF_SHARED_VARIABLE_IN_DECLARING_CLASS) + } + // GROOVY-12513 @Override @Test void testPrivateOperatorMethodsThroughNarrowedVariable() { From e0e8fd49ede776a8c5564d592d41a6aa793eca72 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 08:33:36 -0800 Subject: [PATCH 23/38] GROOVY-12513: SC: accept a private setter of a variable's declared type 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. --- .../stc/StaticTypeCheckingVisitor.java | 9 ++++-- .../stc/FieldsAndPropertiesSTCTest.groovy | 30 +++++++++++++++++++ ...ieldsAndPropertiesStaticCompileTest.groovy | 8 +++++ 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 085d0555afa..fc2fc6f06f1 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -1688,8 +1688,13 @@ private boolean ensureValidSetter(final Expression expression, final Expression // we know that the RHS type is a closure // but we must check if the binary expression is an assignment // because we need to check if a setter uses @DelegatesTo - VariableExpression receiver = varX("%", setterInfo.receiverType); - receiver.setType(setterInfo.receiverType); // same as origin type + // GROOVY-12513: a variable declared with a superclass of the type flow typing narrows it to keeps that superclass + // as its origin type, so that a private setter of the declared type is found here as by the property lookup + ClassNode declaredType = leftExpression instanceof PropertyExpression pe ? getDeclaredReceiverType(pe.getObjectExpression()) : null; + boolean narrowed = declaredType != null && !declaredType.equals(setterInfo.receiverType) && setterInfo.receiverType.isDerivedFrom(declaredType) + && setterInfo.setters.stream().anyMatch(setter -> setter.isPrivate() && setter.getDeclaringClass().equals(declaredType)); + VariableExpression receiver = varX("%", narrowed ? declaredType : setterInfo.receiverType); + receiver.setType(setterInfo.receiverType); // same as origin type, unless narrowed Function setterCall = (value) -> { typeCheckingContext.pushEnclosingBinaryExpression(null); // GROOVY-10628: LHS re-purposed diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index fc9cdd6e083..96fe8dc6a9a 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2830,6 +2830,36 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { ''' } + /** + * Assigns a property through a variable declared as Box, which flow typing + * narrows to Sub, where Box has a private setter, in the place of {@code code}. + */ + protected static String privateSetterOfNarrowedVariable(String code) { + """ + class Outer { + static class Box { + String log = '' + private String getY() { 'y' } + private void setY(String s) { log += s } + private void setZ(String s) { log += 'z' + s } + } + static class Sub extends Box { + } + static class Other { + static String test() { Box b = new Sub(); $code; b.log } + } + } + """ + } + + // GROOVY-12513: under type checking the setter is looked up on the meta-class of Sub + @Test + void testPrivateSetterThroughDeclaredTypeOfNarrowedVariable() { + ['b.y = "p"': 'y', 'b.y += "e"': 'y', 'b.z = "z"': 'z'].each { code, name -> + shouldFailWithMessages privateSetterOfNarrowedVariable(code), "No such property: $name for class: Outer\$Sub" + } + } + // GROOVY-12513: a private field of a class of another nest is not reached through // a variable declared with that class, as through one of the subclass type @Test diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy index 74d40b009d4..6c41af21f5f 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy @@ -1282,6 +1282,14 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT ''' } + // GROOVY-12513: the private setter of the declared type, as for b.setY(v) + @Override @Test + void testPrivateSetterThroughDeclaredTypeOfNarrowedVariable() { + ['b.y = "p"': 'p', 'b.y += "e"': 'ye', 'b.z = "z"': 'zz', 'b.setY("c")': 'c'].each { code, log -> + assertScript privateSetterOfNarrowedVariable(code) + "assert Outer.Other.test() == '$log'" + } + } + // GROOVY-12513 @Override @Test void testPrivateFieldThroughDeclaredTypeOfNarrowedVariable() { From 40a571a9b15bce1cabe4f36205d1b448e36e6e5d Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 08:55:08 -0800 Subject: [PATCH 24/38] GROOVY-12511: SC: call any method of an enclosing instance of the receiver 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. --- .../asm/sc/StaticInvocationWriter.java | 35 +++++++--- .../BinaryExpressionTransformer.java | 2 + .../stc/StaticTypeCheckingSupport.java | 22 ++++++ .../stc/StaticTypeCheckingVisitor.java | 69 ++++++++++++++----- .../transform/stc/MethodCallsSTCTest.groovy | 60 ++++++++++++++++ 5 files changed, 160 insertions(+), 28 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java index 743a374ff2e..e4d0688c6d4 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java @@ -99,6 +99,7 @@ import static org.codehaus.groovy.ast.tools.GeneralUtils.attrX; import static org.codehaus.groovy.ast.tools.GeneralUtils.bytecodeX; import static org.codehaus.groovy.ast.tools.GeneralUtils.callX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.castX; import static org.codehaus.groovy.ast.tools.GeneralUtils.classX; import static org.codehaus.groovy.ast.tools.GeneralUtils.ctorX; import static org.codehaus.groovy.ast.tools.GeneralUtils.inSamePackage; @@ -299,17 +300,28 @@ private Expression thisObjectExpression(final ClassNode source, final ClassNode /** - * Returns the expression for the enclosing instance of {@code receiver}, of - * type {@code receiverType}, that is an instance of {@code outer}: the chain - * of {@code this$0} fields from the receiver's class out to {@code outer}. + * Returns the expression for the enclosing instance of {@code receiver} that + * has {@code method}: the chain of {@code this$0} fields from the receiver's + * class out to that outer class. {@code receiverType} is the type that the + * receiver is written with here, {@code selectedType} the type that the type + * checker selected the method for, which a safe or spread call writes as a + * wider type. */ - private static Expression enclosingInstanceExpression(final Expression receiver, final ClassNode receiverType, final ClassNode outer) { - Expression expr = receiver; - for (ClassNode type = receiverType; !type.equals(outer); type = type.getOuterClass()) { + private static Expression enclosingInstanceExpression(final Expression receiver, final ClassNode receiverType, final ClassNode selectedType, final MethodNode method) { + ClassNode outer = StaticTypeCheckingSupport.findEnclosingInstanceTypeWithMethod(selectedType, method); + if (outer == null) throw new GroovyBugError("no enclosing instance with " + method.getTypeDescriptor() + " for " + selectedType.getName()); + Expression expr = receiverType.equals(selectedType) ? receiver : castX(selectedType, receiver); + for (ClassNode type = selectedType; !type.equals(outer); type = type.getOuterClass()) { FieldNode thisZero = type.getDeclaredField("this$0"); - if (thisZero == null) throw new GroovyBugError("no enclosing instance of " + outer.getName() + " for " + receiverType.getName()); + if (thisZero == null) throw new GroovyBugError("no enclosing instance of " + outer.getName() + " for " + selectedType.getName()); expr = attrX(expr, "this$0"); expr.setType(thisZero.getType()); + if (ClassHelper.CLOSURE_TYPE.equals(thisZero.getType())) { // a class created in a closure: the closure's this object, as for Outer.this + MethodCallExpression thisObject = callX(expr, "getThisObject"); + thisObject.setImplicitThis(false); + thisObject.setMethodTarget(ClassHelper.CLOSURE_TYPE.getMethod("getThisObject", Parameter.EMPTY_ARRAY)); + expr = castX(type.getOuterClass(), thisObject); + } } return expr; } @@ -492,10 +504,11 @@ && isMemberOfOuterClass(declaringClass, thisType, enclosingPrivate))) { } if (!(theReceiver instanceof VariableExpression)) isThisImplicit = false; theReceiver.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, theTarget.getDeclaringClass()); - } else if (receiver != null && currentCall != null && declaringClass.equals(currentCall.getNodeMetaData(StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER))) { - // GROOVY-12511: the receiver only inherits this private method of an outer class - theReceiver = enclosingInstanceExpression(receiver, receiverType, declaringClass); - theReceiver.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, declaringClass); + } else if (receiver != null && !target.isStatic() && currentCall != null + && currentCall.getNodeMetaData(StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER) instanceof ClassNode selectedType) { + // GROOVY-12511: the method is one of an enclosing instance of the receiver, not of the receiver + theReceiver = enclosingInstanceExpression(receiver, receiverType, selectedType, target); + theReceiver.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, theReceiver.getType()); } if (theReceiver != null && !target.isStatic() && !isSuperExpression(receiver) && !isClassWithSuper(receiver) && currentCall.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER) == null) { diff --git a/src/main/java/org/codehaus/groovy/transform/sc/transformers/BinaryExpressionTransformer.java b/src/main/java/org/codehaus/groovy/transform/sc/transformers/BinaryExpressionTransformer.java index 5807602fed0..214fa8cc7d5 100644 --- a/src/main/java/org/codehaus/groovy/transform/sc/transformers/BinaryExpressionTransformer.java +++ b/src/main/java/org/codehaus/groovy/transform/sc/transformers/BinaryExpressionTransformer.java @@ -461,6 +461,7 @@ private Expression compoundValue(final BinaryExpression bin, final int op, final MethodCallExpression opCall = callX(getterCall, (String) target[1], args(rhs)); opCall.setImplicitThis(false); opCall.setMethodTarget((MethodNode) target[0]); + opCall.putNodeMetaData(StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER, bin.getNodeMetaData(StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER)); opCall.setSourcePosition(bin); ClassNode resultType = bin.getNodeMetaData(INFERRED_TYPE); if (resultType != null) { @@ -826,6 +827,7 @@ private Expression transformToTargetMethodCall(final BinaryExpression bin, final } else { call = callX(left, name, args(right)); call.setMethodTarget(node); + call.putNodeMetaData(StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER, bin.getNodeMetaData(StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER)); } call.setImplicitThis(false); if (Types.isAssignment(operationType)) { // +=, -=, /=, ... diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java index 7699bc40c3e..2ba0b49a0c8 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java @@ -81,6 +81,7 @@ import static org.apache.groovy.ast.tools.ClassNodeUtils.addGeneratedMethod; import static org.apache.groovy.ast.tools.ClassNodeUtils.getNestHost; +import static org.apache.groovy.ast.tools.ClassNodeUtils.hasNoEnclosingInstance; import static org.apache.groovy.ast.tools.ClassNodeUtils.samePackageName; import static org.apache.groovy.ast.tools.ExpressionUtils.isNullConstant; import static org.codehaus.groovy.ast.ClassHelper.BigInteger_TYPE; @@ -3365,6 +3366,27 @@ public static boolean isInheritedPrivateMethod(final MethodNode method, final Cl && !method.getDeclaringClass().equals(receiverType); } + /** + * Finds the outer class of {@code type}, reached through its chain of + * enclosing instances, whose instance has the given method: the class that + * declares it, if it is private, or else a class that inherits it. Dynamic + * Groovy calls a method that an inner class instance lacks on its enclosing + * instance. + * + * @param type the type of the receiver, an inner class + * @param method the method of an outer class + * @return the outer class, or {@code null} if no enclosing instance has the method + * @since 7.0.0 + */ + @Internal + public static ClassNode findEnclosingInstanceTypeWithMethod(final ClassNode type, final MethodNode method) { + ClassNode declaringClass = method.getDeclaringClass(); + for (ClassNode cn = type; !hasNoEnclosingInstance(cn) && (cn = cn.getOuterClass()) != null; ) { + if (method.isPrivate() ? cn.equals(declaringClass) : implementsInterfaceOrIsSubclassOf(cn, declaringClass)) return cn; + } + return null; + } + /** * @return true if the class node is either a GString or the LUB of String and GString. */ diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index fc2fc6f06f1..529e688a9bf 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -354,6 +354,7 @@ import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.extractPlaceHolders; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.filterMethodsByVisibility; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.findDGMMethodsForClassNode; +import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.findEnclosingInstanceTypeWithMethod; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.findTargetVariable; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.fullyResolve; import static org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport.fullyResolveType; @@ -1360,6 +1361,7 @@ public Expression transform(final Expression expr) { && !isOrImplements(rType, MAP_TYPE) && !isOrImplements(rType, CHAR_SEQUENCE_TYPE)) { storeTargetMethod(expression, inTarget); + expression.putNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER, reverseExpression.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER)); } } else { resultType = getResultType(lType, op, rType, expression); @@ -7062,7 +7064,7 @@ && isSuperExpression(objectExpression)) { // GROOVY-12470: super.m() invokes the // so store the delegation information for the static compiler storeReceiverData(call, chosenReceiver); call.putNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER, // not kept from an earlier visit - isPrivateMethodOfEnclosingInstanceOfReceiver(targetMethod, objectExpression, chosenReceiver.getType()) ? targetMethod.getDeclaringClass() : null); + isMethodOfEnclosingInstanceOfReceiver(targetMethod, objectExpression, chosenReceiver.getType()) ? chosenReceiver.getType() : null); receiver = chosenReceiver.getType(); if (mergeType || call.getNodeMetaData(INFERRED_TYPE) == null) @@ -8770,6 +8772,10 @@ protected ClassNode getResultType(ClassNode left, final int op, final ClassNode Expression copy = binX(leftExpression, expr.getOperation(), rightExpression); copy.setSourcePosition(expr); // do not propagate BINARY_EXP_TARGET, etc. MethodNode method = findMethodOrFail(copy, left, "getAt", rightRedirect); + if (method != null && copy.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER) != null && !isTargetOfAssignment(expr)) { + // GROOVY-12511: the getAt of an enclosing instance of the left operand is written as that call + method = findMethodOrFail(expr, left, "getAt", rightRedirect); + } if (method != null && !isNumberCategory(getWrapper(rightRedirect))) { return inferReturnTypeGenerics(left, method, rightExpression); } @@ -9056,7 +9062,11 @@ protected MethodNode findMethodOrFail(final Expression expr, final ClassNode rec } methods = disambiguateMethods(methods, receiver, args, expr); if (methods.size() == 1) { - return methods.get(0); + MethodNode method = methods.get(0); + if (expr instanceof BinaryExpression be) { // GROOVY-12511: an operator of an enclosing instance of the left operand + expr.putNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER, isMethodOfEnclosingInstanceOfReceiver(method, be.getLeftExpression(), receiver) ? receiver : null); + } + return method; } else { addAmbiguousErrorMessage(methods, name, args, expr); } @@ -9201,7 +9211,9 @@ protected List findMethod(ClassNode receiver, final String name, fin methods.add(callMethod); } } - if (typeCheckingContext.getEnclosingClassNodes().contains(receiver)) { + if (isTypeOfEnclosingClass(receiver) + // dynamic Groovy turns to the enclosing instance only for a method the receiver lacks, and javac to the innermost class + && (args == null || chooseBestMethod(receiver, filterMethodsByVisibility(methods, typeCheckingContext.getEnclosingClassNode()), args).isEmpty())) { boolean staticOnly = hasNoEnclosingInstance(receiver); for (ClassNode outer = receiver; (outer = outer.getOuterClass()) != null; staticOnly = staticOnly || hasNoEnclosingInstance(outer)) { @@ -9332,24 +9344,35 @@ private List removeInheritedPrivateMethods(final List me } /** - * Determines if a call through {@code objectExpression}, other than "this", - * selects a private method of an outer class that the receiver type only - * inherits (JLS 8.2): {@link #findMethod} offers the methods of the outer - * classes in code of the receiver's own class. The receiver itself has no - * such method, so dynamic Groovy calls it on the receiver's enclosing - * instance. It stays a member of the receiver in its declaring class, and - * through a variable declared with the declaring class under static - * compilation, see {@link #removeInheritedPrivateMethods}. + * Determines if the selected method is not a member of the receiver type + * but one of an enclosing instance of the receiver, as {@link #findMethod} + * offers the methods of the outer classes for a receiver of the class whose + * code this is: dynamic Groovy calls such a method on that enclosing + * instance. A private method of a superclass is not a member of the + * receiver (JLS 8.2), unless it is called in its declaring class or through + * a variable declared with it under static compilation, see + * {@link #removeInheritedPrivateMethods}. */ - private boolean isPrivateMethodOfEnclosingInstanceOfReceiver(final MethodNode method, final Expression objectExpression, final ClassNode receiverType) { - if (!method.isPrivate() || method.isStatic() || isThisExpression(objectExpression) + private boolean isMethodOfEnclosingInstanceOfReceiver(final MethodNode method, final Expression objectExpression, final ClassNode receiverType) { + if (method.isStatic() || method instanceof ExtensionMethodNode || isSuperExpression(objectExpression) || objectExpression instanceof ClassExpression) { return false; } - ClassNode declaringClass = method.getDeclaringClass(); - return !receiverType.equals(declaringClass) && receiverType.isDerivedFrom(declaringClass) - && receiverType.getOuterClasses().contains(declaringClass) - && removeInheritedPrivateMethods(List.of(method), receiverType, getDeclaredReceiverType(objectExpression), true).isEmpty(); + if (implementsInterfaceOrIsSubclassOf(receiverType, method.getDeclaringClass()) + && !(method.isPrivate() && removeInheritedPrivateMethods(List.of(method), receiverType, getDeclaredReceiverType(objectExpression), true).isEmpty())) { + return false; // a member of the receiver + } + return findEnclosingInstanceTypeWithMethod(receiverType, method) != null; + } + + /** + * Determines if {@code type} is a class whose code this is, or a subclass + * of one that is an inner class itself, so that a method of an outer class + * may be one of its enclosing instance. + */ + private boolean isTypeOfEnclosingClass(final ClassNode type) { + List enclosingClasses = typeCheckingContext.getEnclosingClassNodes(); + return enclosingClasses.contains(type) || (type.getOuterClass() != null && enclosingClasses.stream().anyMatch(type::isDerivedFrom)); } /** @@ -9397,6 +9420,18 @@ private List findMethodInSecondPass(final SecondPassExpression wr } } + /** + * Determines if {@code expr}, a binary expression being checked, is the + * left-hand side of the assignment that encloses it, as {@code x[i]} is in + * {@code x[i] = v}, {@code x[i] += v} and {@code x[i]++}. + */ + private boolean isTargetOfAssignment(final BinaryExpression expr) { + for (BinaryExpression be : typeCheckingContext.getEnclosingBinaryExpressionStack()) { + if (be != expr) return be.getLeftExpression() == expr && isAssignment(be.getOperation().getType()); + } + return false; + } + /** * Returns the operand on which an operator calls its method: the left operand * of a binary operator, or the operand itself, as {@link #findMethodOrFail} is diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index eda8c41aa9d..34debecca9f 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -898,6 +898,66 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12511: a method that the receiver lacks but an outer class has is the method + // of the receiver's enclosing instance, as in dynamic Groovy: also for a plain inner + // class, a public method, "this" in a safe call, a closure delegate, a subclass of + // the inner class and an operator; a method of the receiver itself comes first + @Test + void testCallToMethodOfEnclosingInstanceOfReceiver() { + assertScript ''' + class Box { + String id + Box(String id) { this.id = id } + private String im() { 'im:' + id } + String om() { 'om:' + id } + private String m(String s) { 'box:' + id } + private String plus(String s) { 'plus:' + id + s } + private String getAt(int i) { 'getAt:' + id + i } + private boolean isCase(Object o) { id == 'B' } + class Sub extends Box { + Sub(String id) { super(id) } + String m(Object o) { 'sub:' + id } + String safe(Object other) { if (other instanceof Sub) { return other?.im() }; null } + String safeThis() { this?.im() } + String delegate(Sub other) { other.with { im() } } + String own(Sub other) { other.m('x') } + String sub2(Sub2 other) { other.im() } + List spread(Bag bag) { bag*.im() } + List operators(Sub other) { [other + 'x', other[2], 'q' in other] } + } + class Sub2 extends Sub { + Sub2() { super('sub2') } + } + class In { + List other(In other) { [other.im(), other.om()] } + } + class Bag { + List items + Iterator iterator() { items.iterator() } + } + Sub sub() { new Sub('self') } + Sub2 sub2() { new Sub2() } + In in() { new In() } + Bag bag(List items) { new Bag(items: items) } + String anonymous() { + def c = { -> new Box('anon') { String test() { def other = this; other.im() } }.test() } + c() + } + } + def a = new Box('A'), b = new Box('B') + def sa = a.sub(), sb = b.sub() + assert sa.safe(sb) == 'im:B' + assert sa.safeThis() == 'im:A' + assert sa.delegate(sb) == 'im:B' + assert sa.own(sb) == 'sub:self' + assert sa.sub2(b.sub2()) == 'im:B' + assert sa.spread(a.bag([sb, sa])) == ['im:B', 'im:A'] + assert sa.operators(sb) == ['plus:Bx', 'getAt:B2', true] + assert a.in().other(b.in()) == ['im:B', 'om:B'] + assert a.anonymous() == 'im:A' + ''' + } + // GROOVY-12511: this.m() in an inner class may name a method of the enclosing // class, as in dynamic Groovy @Test From d025abb130a8db464fdabd22e521e5bf28e76234 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 09:00:50 -0800 Subject: [PATCH 25/38] GROOVY-12511: under type checking, find a private accessor of the enclosing 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. --- .../stc/StaticTypeCheckingVisitor.java | 11 ++++++++ .../stc/FieldsAndPropertiesSTCTest.groovy | 28 +++++++++++++++++++ ...ieldsAndPropertiesStaticCompileTest.groovy | 8 ++++++ 3 files changed, 47 insertions(+) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 529e688a9bf..a59f7129899 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3403,6 +3403,17 @@ else if (field != null && enclosingTypes.contains(current) && !superReceiver && } staticOnly = staticOnly || hasNoEnclosingInstance(outer); } + } else if (!isStaticDispatchScope() && !(pexp instanceof AttributeExpression) && !isSuperExpression(objectExpression) + && !(objectExpression instanceof ClassExpression) && getType(objectExpression).equals(typeCheckingContext.getEnclosingClassNode())) { + // GROOVY-12511: dynamic Groovy looks a property that an instance of the calling class lacks up on its enclosing + // instance (GROOVY-12621); static compilation has no access to the receiver's enclosing instance for it here + for (ClassNode type = getType(objectExpression); !hasNoEnclosingInstance(type) && (type = type.getOuterClass()) != null; ) { + PropertyExpression pe = propX(propX(classX(type), "this"), pexp.getProperty()); + if (existsProperty(pe, readMode, visitor)) { + pexp.copyNodeMetaData(pe); + return true; + } + } } return foundGetterOrSetter; diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index 96fe8dc6a9a..dabc6ccb5fc 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2253,6 +2253,34 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { ''' } + protected static final String PRIVATE_ACCESSOR_OF_ENCLOSING_INSTANCE_OF_OTHER_RECEIVER = ''' + class Box { + String id + Box(String id) { this.id = id } + private String getP() { 'p:' + id } + private void setQ(String v) { id = 'q' + v } + class Sub extends Box { + Sub() { super('self') } + String read(Sub other) { other.p } + void write(Sub other) { other.q = '1' } + } + Sub make() { new Sub() } + } + ''' + + // GROOVY-12511: through a receiver other than "this", a private accessor of the enclosing + // class is the property of that receiver's enclosing instance, as in dynamic Groovy + @Test + void testPrivateAccessorOfEnclosingInstanceOfOtherReceiverInInnerSubclass() { + assertScript PRIVATE_ACCESSOR_OF_ENCLOSING_INSTANCE_OF_OTHER_RECEIVER + ''' + def a = new Box('A'), b = new Box('B') + def sa = a.make(), sb = b.make() + assert sa.read(sb) == 'p:B' + sa.write(sb) + assert b.id == 'q1' && sb.id == 'self' + ''' + } + // GROOVY-12511: this.@name is a field of this class, not the enclosing instance's // property, so a private getter of the enclosing superclass does not stand in for it @Test diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy index 6c41af21f5f..fa9a9bffdd6 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/sc/FieldsAndPropertiesStaticCompileTest.groovy @@ -1282,6 +1282,14 @@ final class FieldsAndPropertiesStaticCompileTest extends FieldsAndPropertiesSTCT ''' } + // GROOVY-12511: static compilation does not reach the enclosing instance of the + // receiver for property syntax, so it reports these instead of using the receiver + @Override @Test + void testPrivateAccessorOfEnclosingInstanceOfOtherReceiverInInnerSubclass() { + shouldFailWithMessages PRIVATE_ACCESSOR_OF_ENCLOSING_INSTANCE_OF_OTHER_RECEIVER, + 'No such property: p for class: Box$Sub', 'No such property: q for class: Box$Sub' + } + // GROOVY-12513: the private setter of the declared type, as for b.setY(v) @Override @Test void testPrivateSetterThroughDeclaredTypeOfNarrowedVariable() { From 79b952ee0b99e4f0003a723612202ce300532a47 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 09:01:34 -0800 Subject: [PATCH 26/38] GROOVY-12511: say in the guide where an inner class reaches the enclosing 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. --- src/spec/doc/core-object-orientation.adoc | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/spec/doc/core-object-orientation.adoc b/src/spec/doc/core-object-orientation.adoc index bc1b23f7c51..b6a524c00c9 100644 --- a/src/spec/doc/core-object-orientation.adoc +++ b/src/spec/doc/core-object-orientation.adoc @@ -249,13 +249,16 @@ include::../test/ClassTest.groovy[tags=inner_class,indent=0] As in Java, the classes nested in the same top-level class can also use each other's private members. Private members are not inherited, though, and the meta-class of a subclass offers none of the private members of its superclass. -When `Sub` extends `Base`, a private instance method of `Base` cannot be called through a `Sub` receiver, such as `new Sub().secret()`, except in `Base` itself, and in an enum constant body or an anonymous subclass of `Base` created in a static context, which have no enclosing instance and call the method on themselves. +When `Sub` extends `Base`, a private instance method of `Base` is not called on a `Sub` receiver, such as `new Sub().secret()`, except in `Base` itself, and in an enum constant body or an anonymous subclass of `Base` created in a static context, which have no enclosing instance and call the method on themselves; in an inner class of `Base`, such a call goes to an enclosing instance, as described below. Outside `Base`, `sub.@name` does not reach a private field of `Base` either; within `Sub`, `this.@name` and `super.@name` reach such a field of the current instance directly. With static compilation, a receiver whose static type is `Base`, such as `((Base) sub).@name` or a variable declared as `Base`, reaches the private members of `Base`, also where flow typing knows that the variable holds a `Sub`, as in Java. `sub.name` reads the private field there only in `Base` and in the classes nested in `Base`; from another class of the same top-level class it is rejected. -Dynamic code looks a member up on the meta-class of the object's class, so it does not find a private member of `Base` through a variable that holds a `Sub`, and `@TypeChecked` rejects such a use where flow typing knows that the variable holds a `Sub`. +Dynamic code looks a member up on the meta-class of the object's class, so outside `Base` it does not find a private instance member of `Base` through a `Sub` object, unless an enclosing instance has it, as described below, and `@TypeChecked` rejects such a use where flow typing knows that the variable holds a `Sub`. +Private static members of `Base` stay reachable through `Sub` in every mode. It finds the field through `sub.name` only in `Base` or in an inner class whose enclosing instance is a `Base`. -In an inner class of `Base` that also extends `Base`, `secret()`, `this.secret()`, `name` and `this.name` for a private member of `Base` therefore use the enclosing `Base` instance, and `other.secret()`, for another instance `other` of that inner class, uses the enclosing instance of `other`. +In an inner class of `Base`, a method that the inner class lacks but `Base` has, such as `secret()`, `this.secret()` or, for another instance `other` of that inner class, `other.secret()` and an operator such as `other + x`, is called on the enclosing `Base` instance of `this` or of `other`, as dynamic Groovy calls it. +Where the inner class also extends `Base`, `name` and `this.name` for a private member of `Base` use the enclosing instance as well. +For a private accessor of `Base`, `other.name` uses the enclosing instance of `other` under `@TypeChecked`, and static compilation rejects it; for a private field, static compilation reads the field of `other` itself. There are some reasons for using inner classes: From 08c62aca384f590d0eadbfad460492b46cca0494 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 11:54:53 -0800 Subject: [PATCH 27/38] GROOVY-12510, GROOVY-12523, GROOVY-12637: mark the regression tests that 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. --- src/test/groovy/bugs/RegressionTest.groovy | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/groovy/bugs/RegressionTest.groovy b/src/test/groovy/bugs/RegressionTest.groovy index b682f4505d3..e85c63306f9 100644 --- a/src/test/groovy/bugs/RegressionTest.groovy +++ b/src/test/groovy/bugs/RegressionTest.groovy @@ -4844,7 +4844,7 @@ def cfg = new ConfigSlurper().parse(""" } // GROOVY-12510: STC accepts a private method of a superclass called through a subclass receiver - @NotYetImplemented @Test + @Test void testGroovy12510() { ['TypeChecked', 'CompileStatic'].each { mode -> def src = """ @@ -4929,7 +4929,7 @@ def cfg = new ConfigSlurper().parse(""" } // GROOVY-12523: STC: x.@name is accepted for a private field of a superclass when the type of x is a subclass - @NotYetImplemented @Test + @Test void testGroovy12523() { ['TypeChecked', 'CompileStatic'].each { mode -> def src = """ @@ -5171,7 +5171,7 @@ def cfg = new ConfigSlurper().parse(""" } // GROOVY-12637: CS: an Object method such as toString() or hashCode() called without a receiver inside an inner class (named or anonymous) is resolved to the *outer* class's override, instead of the method the inner class inherits - @NotYetImplemented @Test + @Test void testGroovy12637() { assertScript ''' @groovy.transform.CompileStatic From 57228ef5db1b40df911dca99fe328467586226f8 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 11:55:23 -0800 Subject: [PATCH 28/38] GROOVY-12511: give the guide's sub.name sentence its subject, and describe 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. --- .../org/codehaus/groovy/transform/stc/StaticTypesMarker.java | 2 +- src/spec/doc/core-object-orientation.adoc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypesMarker.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypesMarker.java index c064db0ae7f..03a6b3bc405 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypesMarker.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypesMarker.java @@ -74,6 +74,6 @@ public enum StaticTypesMarker { METHOD_REFERENCE_TYPE, /** on a {@code SwitchExpression} without a {@code default}: {@code Boolean.TRUE} when its labels were proven to cover every non-null selector value (a complete enum, an unconditional pattern, or a covered sealed hierarchy), so that matching nothing at run time means a constant or subtype was added after compilation */ SWITCH_EXHAUSTIVE, - /** GROOVY-12511: on a method call whose receiver, not {@code this}, only inherits the private method of an outer class that the call selects, that outer class: the method is called on the receiver's enclosing instance, as dynamic Groovy calls it */ + /** GROOVY-12511: on a method call or an operator whose selected method is not a member of the receiver but one of an enclosing instance of it, the receiver type that the method was selected for: the method is called on that enclosing instance, as dynamic Groovy calls it */ ENCLOSING_INSTANCE_OF_RECEIVER } diff --git a/src/spec/doc/core-object-orientation.adoc b/src/spec/doc/core-object-orientation.adoc index b6a524c00c9..5ba50f11f77 100644 --- a/src/spec/doc/core-object-orientation.adoc +++ b/src/spec/doc/core-object-orientation.adoc @@ -254,8 +254,8 @@ Outside `Base`, `sub.@name` does not reach a private field of `Base` either; wit With static compilation, a receiver whose static type is `Base`, such as `((Base) sub).@name` or a variable declared as `Base`, reaches the private members of `Base`, also where flow typing knows that the variable holds a `Sub`, as in Java. `sub.name` reads the private field there only in `Base` and in the classes nested in `Base`; from another class of the same top-level class it is rejected. Dynamic code looks a member up on the meta-class of the object's class, so outside `Base` it does not find a private instance member of `Base` through a `Sub` object, unless an enclosing instance has it, as described below, and `@TypeChecked` rejects such a use where flow typing knows that the variable holds a `Sub`. +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`. Private static members of `Base` stay reachable through `Sub` in every mode. -It finds the field through `sub.name` only in `Base` or in an inner class whose enclosing instance is a `Base`. In an inner class of `Base`, a method that the inner class lacks but `Base` has, such as `secret()`, `this.secret()` or, for another instance `other` of that inner class, `other.secret()` and an operator such as `other + x`, is called on the enclosing `Base` instance of `this` or of `other`, as dynamic Groovy calls it. Where the inner class also extends `Base`, `name` and `this.name` for a private member of `Base` use the enclosing instance as well. For a private accessor of `Base`, `other.name` uses the enclosing instance of `other` under `@TypeChecked`, and static compilation rejects it; for a private field, static compilation reads the field of `other` itself. From af520463b0e820e8acf39c3624e986c75e304fad Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 15:39:03 -0800 Subject: [PATCH 29/38] GROOVY-12510, GROOVY-12511: document the member rules of findMethod and 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. --- .../asm/sc/StaticInvocationWriter.java | 4 +++ ...cTypesMethodReferenceExpressionWriter.java | 16 ++++++++++-- .../transform/stc/SecondPassExpression.java | 21 +++++++++++++-- .../stc/StaticTypeCheckingSupport.java | 14 ++++++---- .../stc/StaticTypeCheckingVisitor.java | 26 ++++++++++++++++++- 5 files changed, 71 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java index e4d0688c6d4..bbaf79dfc69 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java @@ -262,6 +262,10 @@ private static MethodNode getObjectMethod(final MethodNode method) { return objectMethod != null && objectMethod.isPublic() && !objectMethod.isStatic() ? objectMethod : null; } + /** + * Returns the expression for the instance of {@code target} that code in {@code source} uses, which + * may be an enclosing instance of a subclass of {@code target}, see {@link #thisObjectExpression(ClassNode, ClassNode, boolean)}. + */ private Expression thisObjectExpression(final ClassNode source, final ClassNode target) { return thisObjectExpression(source, target, false); } diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java index 4d6d62bc44c..5299c4431c1 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java @@ -674,6 +674,16 @@ private MethodNode chooseMethodRefMethod(final List methods, final E }).thenComparing(StaticTypesMethodReferenceExpressionWriter::isExtensionMethod)).orElse(null); } + /** + * Returns the methods named {@code name} that a method reference on {@code type} may use: its methods, + * the default methods of its interfaces and, for an abstract type, their public instance methods, and the + * extension methods, that are visible from the current class. + *

+ * A private method of a superclass is left out, since it is not a member of the type (JLS 8.2), unless it + * is declared by the declared type of the variable {@code typeOrTargetRef}, whose type flow typing narrowed + * to a subclass: the reference is then made through the declared type. Unlike a call, a static method or a + * reference made in the declaring class is no exception, because dynamic Groovy fails on those. + */ private List findVisibleMethods(final String name, final ClassNode type, final Expression typeOrTargetRef) { List methods = type.getMethods(name); // GROOVY-10791, GROOVY-11467: include non-static interface methods @@ -689,13 +699,15 @@ private List findVisibleMethods(final String name, final ClassNode t methods.addAll(findDGMMethodsForClassNode(controller.getSourceUnit().getClassLoader(), type, name)); methods = filterMethodsByVisibility(methods, controller.getClassNode()); - // a private method of a superclass is not a member of the type (JLS 8.2), - // but it is one of the declared type of a variable whose type is narrower ClassNode declaredType = getDeclaredType(typeOrTargetRef); methods.removeIf(method -> isInheritedPrivateMethod(method, type) && !method.getDeclaringClass().equals(declaredType)); return methods; } + /** + * Returns the declared type of a variable, which flow typing may have narrowed: the origin type of a + * variable that is not {@code this} or {@code super} and not a dynamic variable, or else {@code null}. + */ private static ClassNode getDeclaredType(final Expression expression) { if (expression instanceof VariableExpression variable && !variable.isThisExpression() && !variable.isSuperExpression()) { Variable target = variable; diff --git a/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java b/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java index 9877dcde631..976cde51c74 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/SecondPassExpression.java @@ -27,6 +27,12 @@ * A utility class used to wrap an expression with additional metadata used by the type checker. * In particular, this is used to detect closure shared variables misuses. We need in some circumstances * to store the method call expression and its argument types. + *

+ * The second pass also needs to find the same private members as the first pass, which depend on + * where and through what the expression was checked, not only on the types assigned to the variable: + * the declared type of the receiver variable, through which statically compiled code may use a private + * member of that type although flow typing narrowed the variable to a subclass, and the class whose + * code the expression is, which decides the private members it may use. */ class SecondPassExpression { private final Expression expression; @@ -42,6 +48,15 @@ class SecondPassExpression { this(expression, data, null, null); } + /** + * Wraps an expression for the second pass. + * + * @param expression the expression to check again + * @param data the auxiliary data, such as the argument types of a call, or {@code null} + * @param declaredReceiverType the declared type of the receiver variable through which the first pass + * found a private member of that type, or {@code null}, see {@link #getDeclaredReceiverType()} + * @param enclosingClass the class whose code the first pass checked the expression in, or {@code null} + */ SecondPassExpression(final Expression expression, final T data, final ClassNode declaredReceiverType, final ClassNode enclosingClass) { this.data = data; this.expression = expression; @@ -80,7 +95,9 @@ public Expression getExpression() { } /** - * Compares the wrapped expression and auxiliary data. + * Compares the wrapped expression and auxiliary data. The declared receiver type and the enclosing + * class are left out: both follow from the expression, which is one node of one class, with one + * receiver variable, so two wrappers of the same expression never differ in them. */ @Override public boolean equals(final Object o) { @@ -96,7 +113,7 @@ public boolean equals(final Object o) { } /** - * Returns the hash code of the wrapped expression and auxiliary data. + * Returns the hash code of the wrapped expression and auxiliary data, which {@link #equals} compares. */ @Override public int hashCode() { diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java index 2ba0b49a0c8..65400026117 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java @@ -3350,14 +3350,18 @@ public static List filterMethodsByVisibility(final List } /** - * Determines if a method is a private method that a receiver of the given type - * would only inherit from a superclass. Private members are not inherited - * (JLS 8.2), so such a method is not a member of the receiver type, and dynamic - * Groovy does not find it there either. + * Determines if a method is private, is not an extension method, and is declared + * by a class other than the given receiver type. For a method found on that type + * or its superclasses, that is a private method the receiver would only inherit + * from a superclass. Private members are not inherited (JLS 8.2), so such a + * method is not a member of the receiver type, and dynamic Groovy does not find + * it there either. An extension method is never one: it is not a method of a + * superclass but one that an extension class adds to the type. * * @param method the candidate method * @param receiverType the type that the method is looked up on - * @return {@code true} if the method is private and declared by another class + * @return {@code true} if the method is private, is not an {@code ExtensionMethodNode}, + * and is declared by a class other than {@code receiverType} * @since 7.0.0 */ @Internal diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index a59f7129899..39b9f9d959e 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -9193,6 +9193,28 @@ protected List findMethodsWithGenerated(final ClassNode receiver, fi /** * Finds candidate methods matching the supplied receiver, name, and argument types. + *

+ * A private method that the receiver only inherits from a superclass is not a + * candidate, as it is not a member of the receiver (JLS 8.2) and dynamic Groovy + * does not find it there either. It stays one when it is declared by the declared + * type of the receiver variable, which flow typing may have narrowed to a subclass + * (this type is known only under static compilation, where the call is made + * through it), 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, which calls it on itself, see + * {@link #removeInheritedPrivateMethods}. + *

+ * 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 (or + * none are given), the methods of its outer classes are candidates too, only the + * static ones beyond a class that has no enclosing instance: dynamic Groovy calls + * such a method on the enclosing instance, and static compilation does too, see + * {@link StaticTypesMarker#ENCLOSING_INSTANCE_OF_RECEIVER}. + *

+ * These rules are for calls. A method pointer or reference ({@code x.&m}, + * {@code x::m}) 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. */ protected List findMethod(ClassNode receiver, final String name, final ClassNode... args) { if (isPrimitiveType(receiver)) receiver = getWrapper(receiver); @@ -9464,7 +9486,9 @@ List findCallableMethodsWithGenerated(final ClassNode type, final St } /** - * Returns the declared type of a variable, which flow typing may have narrowed. + * Returns the declared type of a variable, which flow typing may have narrowed: + * the origin type of a variable that is not {@code this} or {@code super} and + * not a dynamic variable, or else {@code null}. */ private static ClassNode getDeclaredType(final Expression expression) { if (expression instanceof VariableExpression variable && !variable.isThisExpression() && !variable.isSuperExpression()) { From 2e37bb952f1f3dca88cca0b147303c1ac8474ad5 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 15:39:46 -0800 Subject: [PATCH 30/38] GROOVY-12510: document findMethodWithDeclaredType --- .../groovy/transform/stc/StaticTypeCheckingVisitor.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 39b9f9d959e..4ee2b310bf6 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -9428,6 +9428,12 @@ private List findMethodThrough(final Expression objectExpression, fi return findMethodWithDeclaredType(getDeclaredReceiverType(objectExpression), receiver, name, args); } + /** + * Finds the methods as {@link #findMethod} does, with {@code declaredType} as the + * declared type of the receiver variable: a private method that it declares is + * kept although the receiver only inherits it. With {@code null}, none is kept for + * that reason, see {@link #removeInheritedPrivateMethods}. + */ private List findMethodWithDeclaredType(final ClassNode declaredType, final ClassNode receiver, final String name, final ClassNode... args) { ClassNode previous = declaredReceiverType; declaredReceiverType = declaredType; From 921ac876f9a0f951b0dcb1a1f956d8493f1d9dbd Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 21:28:25 -0800 Subject: [PATCH 31/38] GROOVY-12511: ++, -- and compound assignment with an operator method 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. --- ...esBinaryExpressionMultiTypeDispatcher.java | 3 ++ .../stc/StaticTypeCheckingVisitor.java | 19 +++++++ .../transform/stc/MethodCallsSTCTest.groovy | 52 +++++++++++++++++++ 3 files changed, 74 insertions(+) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java index 96f88ed5181..80105e0c8c3 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java @@ -70,6 +70,7 @@ import static org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor.inferLoopElementType; import static org.codehaus.groovy.transform.stc.StaticTypesMarker.COMPOUND_ASSIGN_TARGET; import static org.codehaus.groovy.transform.stc.StaticTypesMarker.DIRECT_METHOD_CALL_TARGET; +import static org.codehaus.groovy.transform.stc.StaticTypesMarker.ENCLOSING_INSTANCE_OF_RECEIVER; import static org.codehaus.groovy.transform.stc.StaticTypesMarker.INFERRED_TYPE; import static org.codehaus.groovy.transform.stc.StaticTypesMarker.SUPER_MOP_METHOD_REQUIRED; import static org.objectweb.asm.Opcodes.ACC_PUBLIC; @@ -116,6 +117,8 @@ protected void writePostOrPrefixMethod(final int op, final String method, final call.setMethodTarget(mn); call.setImplicitThis(false); call.setSourcePosition(orig); + // GROOVY-12511: next() or previous() of an enclosing instance of the operand is called on that instance + call.putNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER, orig.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER)); call.visit(controller.getAcg()); controller.getCompileStack().removeVar(slot); return; diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 4ee2b310bf6..7e07558531c 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -1255,6 +1255,11 @@ public Expression transform(final Expression expr) { ? UNKNOWN_PARAMETER_TYPE : getInferredTypeFromTempInfo(rightExpression, getType(rightExpression)); List candidates = findMethodThrough(leftExpression, lhsType, assignName, rhsType); + // GROOVY-12511: dynamic Groovy uses a *Assign method only if the receiver itself responds to + // it, and else the base operator, which may be one of an enclosing instance as for "x + y" + if (candidates.size() == 1 && isMethodOfEnclosingInstanceOfReceiver(candidates.get(0), lhsRead, lhsType)) { + candidates = Collections.emptyList(); + } if (candidates.size() == 1) { MethodNode target = candidates.get(0); expression.putNodeMetaData(COMPOUND_ASSIGN_TARGET, target); @@ -4292,6 +4297,7 @@ private void visitPrefixOrPostixExpression(final Expression origin, final Expres MethodNode node = findMethodOrFail(receiver, operandType, name); if (node != null) { storeTargetMethod(origin, node); + storeEnclosingInstanceOfOperand(origin, node, receiver, operandType); storeType(origin, getMathWideningClassNode(operandType)); return; } @@ -4304,6 +4310,7 @@ private void visitPrefixOrPostixExpression(final Expression origin, final Expres MethodNode node = findMethodOrFail(receiver, operandType, name); if (node != null) { storeTargetMethod(origin, node); + storeEnclosingInstanceOfOperand(origin, node, receiver, operandType); storeType(origin, isPostfix ? operandType : inferReturnTypeGenerics(operandType, node, ArgumentListExpression.EMPTY_ARGUMENTS)); } } finally { @@ -9056,6 +9063,18 @@ protected ClassNode inferComponentType(final ClassNode receiverType, final Class return componentType; } + /** + * Records on {@code x++}, {@code ++x}, {@code x--} or {@code --x} whether the selected + * {@code next()} or {@code previous()} is a method of an enclosing instance of the + * operand, not of the operand itself: static compilation then calls it + * on that enclosing instance, as dynamic Groovy does, see + * {@link StaticTypesMarker#ENCLOSING_INSTANCE_OF_RECEIVER}. + */ + private void storeEnclosingInstanceOfOperand(final Expression origin, final MethodNode method, final Expression operand, final ClassNode operandType) { + origin.putNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER, // not kept from an earlier visit + isMethodOfEnclosingInstanceOfReceiver(method, operand, operandType) ? operandType : null); + } + /** * Finds a matching method or reports a static type error when none is available. */ diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index 34debecca9f..89af6a04d22 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -958,6 +958,58 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12511: ++ and -- call next() or previous() of an enclosing instance of the + // operand, as dynamic Groovy does; a compound assignment uses a *Assign method only of + // the receiver itself, as dynamic Groovy does, and else the operator, here of the + // enclosing instance + @Test + void testOperatorOfEnclosingInstanceOfReceiver() { + assertScript ''' + class Box { + String id + Box(String id) { this.id = id } + private Sub next() { new Sub('next:' + id) } + private Sub previous() { new Sub('previous:' + id) } + private Sub plus(String s) { new Sub('plus:' + id + s) } + private void plusAssign(String s) { id = 'plusAssign:' + id + s } + class Sub extends Box { + Sub(String id) { super(id) } + List increments(Sub other) { + Sub a = other, b = other, c = other, d = other, self = this + Sub before = a++ + ++b; c--; --d; self++ + [before.id, a.id, b.id, c.id, d.id, self.id] + } + List operands(Sub other) { + Sub[] array = [other, other] + array[0]++ + Holder holder = new Holder() + holder.sub = other + holder.sub++ + [array[0].id, holder.sub.id] + } + List compound(Sub other) { + Sub a = other + a += 'x' + Sub[] array = [other] + array[0] += 'y' + [a.id, array[0].id, other.id] + } + } + class Holder { + Sub sub + } + Sub sub() { new Sub('self') } + } + def a = new Box('A'), b = new Box('B') + def sa = a.sub(), sb = b.sub() + assert sa.increments(sb) == ['self', 'next:B', 'next:B', 'previous:B', 'previous:B', 'next:A'] + assert sa.operands(sb) == ['next:B', 'next:B'] + assert sa.compound(sb) == ['plus:Bx', 'plus:By', 'self'] + assert a.id == 'A' && b.id == 'B' + ''' + } + // GROOVY-12511: this.m() in an inner class may name a method of the enclosing // class, as in dynamic Groovy @Test From 343dd5cd541d787c5bd6abc28baa7d193f91856f Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 21:28:26 -0800 Subject: [PATCH 32/38] GROOVY-12510: findVisibleMethods: an instance with no enclosing instance is no exception for a method reference --- .../asm/sc/StaticTypesMethodReferenceExpressionWriter.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java index 5299c4431c1..675b2309f6e 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java @@ -681,8 +681,10 @@ private MethodNode chooseMethodRefMethod(final List methods, final E *

* A private method of a superclass is left out, since it is not a member of the type (JLS 8.2), unless it * is declared by the declared type of the variable {@code typeOrTargetRef}, whose type flow typing narrowed - * to a subclass: the reference is then made through the declared type. Unlike a call, a static method or a - * reference made in the declaring class is no exception, because dynamic Groovy fails on those. + * to a subclass: the reference is then made through the declared type. Unlike a call, a static method, a + * reference made in the declaring class, and one on an enum constant body or an anonymous class created in a + * static context nested in the declaring class, which has no enclosing instance, are no exception, because + * dynamic Groovy fails on those. */ private List findVisibleMethods(final String name, final ClassNode type, final Expression typeOrTargetRef) { List methods = type.getMethods(name); From 034df1e4fc49d9402374b308e4458fd10e0bd0bc Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 22:40:55 -0800 Subject: [PATCH 33/38] GROOVY-12511: x op= y uses a *Assign method of the receiver only, and 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. --- ...esBinaryExpressionMultiTypeDispatcher.java | 24 ++++++++ .../stc/StaticTypeCheckingVisitor.java | 23 +++++++- .../transform/stc/MethodCallsSTCTest.groovy | 55 +++++++++++++++++++ 3 files changed, 100 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java index 80105e0c8c3..9cf0a0703b2 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java @@ -63,6 +63,7 @@ import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt; import static org.codehaus.groovy.ast.tools.GeneralUtils.varX; import static org.codehaus.groovy.classgen.AsmClassGenerator.ELIDE_EXPRESSION_VALUE; +import static org.codehaus.groovy.syntax.Types.LEFT_SQUARE_BRACKET; import static org.codehaus.groovy.transform.sc.StaticCompilationVisitor.ARRAYLIST_ADD_METHOD; import static org.codehaus.groovy.transform.sc.StaticCompilationVisitor.ARRAYLIST_CLASSNODE; import static org.codehaus.groovy.transform.sc.StaticCompilationVisitor.ARRAYLIST_CONSTRUCTOR; @@ -151,6 +152,29 @@ private static void visitInsnByType(final ClassNode top, final MethodVisitor mv, } } + /** + * Writes the read of {@code x[i]} in {@code x[i]++} or {@code x[i] += v} as the + * {@code getAt} of an enclosing instance of {@code x} where the type checker + * selected one (GROOVY-12511), as dynamic Groovy reads it; the write stays the + * {@code putAt} of {@code x}. + */ + @Override + protected void evaluateBinaryExpression(final String message, final BinaryExpression binExp) { + if (binExp.getOperation().getType() == LEFT_SQUARE_BRACKET + && binExp.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER) != null + && binExp.getNodeMetaData(DIRECT_METHOD_CALL_TARGET) instanceof MethodNode getAt) { + MethodCallExpression call = callX(binExp.getLeftExpression(), "getAt", binExp.getRightExpression()); + call.setImplicitThis(false); + call.setSafe(binExp.isSafe()); + call.setMethodTarget(getAt); + call.putNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER, binExp.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER)); + call.setSourcePosition(binExp); + call.visit(controller.getAcg()); + return; + } + super.evaluateBinaryExpression(message, binExp); + } + /** {@inheritDoc} */ @Override protected void evaluateBinaryExpressionWithAssignment(final String method, final BinaryExpression expression) { diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 7e07558531c..236786faf81 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -1257,7 +1257,7 @@ public Expression transform(final Expression expr) { List candidates = findMethodThrough(leftExpression, lhsType, assignName, rhsType); // GROOVY-12511: dynamic Groovy uses a *Assign method only if the receiver itself responds to // it, and else the base operator, which may be one of an enclosing instance as for "x + y" - if (candidates.size() == 1 && isMethodOfEnclosingInstanceOfReceiver(candidates.get(0), lhsRead, lhsType)) { + if (candidates.size() == 1 && !isMethodOfReceiver(candidates.get(0), lhsRead, lhsType)) { candidates = Collections.emptyList(); } if (candidates.size() == 1) { @@ -8790,9 +8790,16 @@ protected ClassNode getResultType(ClassNode left, final int op, final ClassNode Expression copy = binX(leftExpression, expr.getOperation(), rightExpression); copy.setSourcePosition(expr); // do not propagate BINARY_EXP_TARGET, etc. MethodNode method = findMethodOrFail(copy, left, "getAt", rightRedirect); - if (method != null && copy.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER) != null && !isTargetOfAssignment(expr)) { + boolean target = isTargetOfAssignment(expr); + if (method != null && copy.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER) != null && !target) { // GROOVY-12511: the getAt of an enclosing instance of the left operand is written as that call method = findMethodOrFail(expr, left, "getAt", rightRedirect); + } else if (target) { + // GROOVY-12511: x[i]++ and x[i] += v read x[i] with the getAt of an enclosing instance of x, as dynamic + // Groovy does; the subscript stays one, for the write, so the read is recorded for the static writer + boolean enclosing = method != null && copy.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER) != null; + expr.putNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER, enclosing ? copy.getNodeMetaData(ENCLOSING_INSTANCE_OF_RECEIVER) : null); + expr.putNodeMetaData(DIRECT_METHOD_CALL_TARGET, enclosing ? method : null); } if (method != null && !isNumberCategory(getWrapper(rightRedirect))) { return inferReturnTypeGenerics(left, method, rightExpression); @@ -9417,6 +9424,17 @@ private boolean isMethodOfEnclosingInstanceOfReceiver(final MethodNode method, f return findEnclosingInstanceTypeWithMethod(receiverType, method) != null; } + /** + * Determines if the selected method is one of the receiver itself, as a + * meta-class lookup on the receiver finds it: not a method of an outer class, + * static or one of an enclosing instance, that {@link #findMethod} offers for + * a receiver of the class whose code this is. + */ + private boolean isMethodOfReceiver(final MethodNode method, final Expression objectExpression, final ClassNode receiverType) { + return (method instanceof ExtensionMethodNode || implementsInterfaceOrIsSubclassOf(receiverType, method.getDeclaringClass())) + && !isMethodOfEnclosingInstanceOfReceiver(method, objectExpression, receiverType); + } + /** * Determines if {@code type} is a class whose code this is, or a subclass * of one that is an inner class itself, so that a method of an outer class @@ -9485,6 +9503,7 @@ private List findMethodInSecondPass(final SecondPassExpression wr */ private boolean isTargetOfAssignment(final BinaryExpression expr) { for (BinaryExpression be : typeCheckingContext.getEnclosingBinaryExpressionStack()) { + if (be == null) break; // a left-hand side re-purposed, as for a setter call if (be != expr) return be.getLeftExpression() == expr && isAssignment(be.getOperation().getType()); } return false; diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index 89af6a04d22..992a90ef40c 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -1010,6 +1010,61 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12511: a compound assignment uses a *Assign method only of the receiver + // itself, as dynamic Groovy does, not a static one of an outer class + @Test + void testCompoundAssignmentWithAssignMethodOfOuterClass() { + assertScript ''' + class Box { + static String log = '' + static void plusAssign(String s) { log += 'Box.plusAssign' } + class Item { + String id + Item(String id) { this.id = id } + Item plus(String s) { new Item(id + s) } + List test() { + Item item = new Item('i'), same = item + item += 'x' + [item.id, same.id, log] + } + } + List test() { new Item('o').test() } + } + assert new Box().test() == ['ix', 'i', ''] + ''' + } + + // GROOVY-12511: x[i]++ and x[i] += v read x[i] with the getAt of an enclosing + // instance of x, as dynamic Groovy does, and write it with the putAt of x + @Test + void testSubscriptUpdateWithGetAtOfEnclosingInstance() { + assertScript ''' + class Box { + int n + Box(int n) { this.n = n } + private int getAt(int i) { n + i } + private String getAt(String s) { 'getAt:' + n + s } + class Sub extends Box { + List stored = [] + Sub(int n) { super(n) } + void putAt(int i, int v) { stored << v } + void putAt(String s, String v) { stored << v } + List test(Sub other) { + def read = other[0] + other[0]++ + ++other[1] + other[1]-- + other['s'] += 'x' + [read, other.stored] + } + } + Sub sub(int n) { new Sub(n) } + } + def a = new Box(1), b = new Box(10) + assert a.sub(100).test(b.sub(1000)) == [10, [11, 12, 10, 'getAt:10sx']] + ''' + } + // GROOVY-12511: this.m() in an inner class may name a method of the enclosing // class, as in dynamic Groovy @Test From 2c03ea16eafac2c16715d6605b1eb79b3bad5c68 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 22:41:02 -0800 Subject: [PATCH 34/38] GROOVY-12510: method pointers and references keep a private method of 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. --- ...cTypesMethodReferenceExpressionWriter.java | 14 +++++--- .../stc/StaticTypeCheckingVisitor.java | 35 +++++++++++++------ src/spec/doc/core-object-orientation.adoc | 4 ++- .../transform/stc/MethodReferenceTest.groovy | 34 ++++++++++++++++++ 4 files changed, 70 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java index 675b2309f6e..74545fe1177 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java @@ -21,6 +21,7 @@ import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; +import org.codehaus.groovy.ast.EnumConstantClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.DynamicVariable; import org.codehaus.groovy.ast.GenericsType; @@ -681,10 +682,11 @@ private MethodNode chooseMethodRefMethod(final List methods, final E *

* A private method of a superclass is left out, since it is not a member of the type (JLS 8.2), unless it * is declared by the declared type of the variable {@code typeOrTargetRef}, whose type flow typing narrowed - * to a subclass: the reference is then made through the declared type. Unlike a call, a static method, a - * reference made in the declaring class, and one on an enum constant body or an anonymous class created in a - * static context nested in the declaring class, which has no enclosing instance, are no exception, because - * dynamic Groovy fails on those. + * to a subclass: the reference is then made through the declared type. As for a call, a private method of the + * enum of an enum constant body is kept, which the meta-class of the body finds, and so is a private static + * method of a class that encloses the type, which dynamic Groovy finds in the outer class. Unlike a call, any + * other private static method, a reference made in the declaring class and one on an anonymous class created in + * a static context are no exception, because dynamic Groovy fails on those. */ private List findVisibleMethods(final String name, final ClassNode type, final Expression typeOrTargetRef) { List methods = type.getMethods(name); @@ -702,7 +704,9 @@ private List findVisibleMethods(final String name, final ClassNode t methods = filterMethodsByVisibility(methods, controller.getClassNode()); ClassNode declaredType = getDeclaredType(typeOrTargetRef); - methods.removeIf(method -> isInheritedPrivateMethod(method, type) && !method.getDeclaringClass().equals(declaredType)); + methods.removeIf(method -> isInheritedPrivateMethod(method, type) && !method.getDeclaringClass().equals(declaredType) + && !(method.isStatic() && type.getOuterClasses().contains(method.getDeclaringClass())) + && !(type.redirect() instanceof EnumConstantClassNode && method.getDeclaringClass().equals(type.getUnresolvedSuperClass()))); return methods; } diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 236786faf81..2ac3b93e769 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -9238,9 +9238,9 @@ protected List findMethodsWithGenerated(final ClassNode receiver, fi * {@link StaticTypesMarker#ENCLOSING_INSTANCE_OF_RECEIVER}. *

* These rules are for calls. A method pointer or reference ({@code x.&m}, - * {@code x::m}) 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. + * {@code x::m}) is resolved elsewhere, with the exceptions for an enum constant + * body and a static method of an enclosing class only, because dynamic Groovy + * fails on the others. */ protected List findMethod(ClassNode receiver, final String name, final ClassNode... args) { if (isPrimitiveType(receiver)) receiver = getWrapper(receiver); @@ -9379,13 +9379,16 @@ protected List findMethod(ClassNode receiver, final String name, fin /** * Removes the private methods that {@code type} only inherits from a superclass * (JLS 8.2). A method declared by {@code declaredType} is kept: that is the - * declared type of a variable whose inferred type is the narrower type. For a - * call, three cases that dynamic Groovy runs are kept as well: a private static - * method, a private method called from its declaring class, and one called on - * an enum constant body or an anonymous class created in a static context that - * is nested in the declaring class: having no enclosing instance, it calls the - * method on itself. For a method reference or pointer they are not, because - * dynamic Groovy fails on those. + * declared type of a variable whose inferred type is the narrower type. The + * cases that dynamic Groovy runs are kept as well. For a call and for a method + * reference or pointer: a private method of the enum of an enum constant body, + * which the meta-class of the body finds, and a private static method of a class + * that encloses {@code type}, which dynamic Groovy finds in the outer class. For + * a call, also any other private static method, a private method called from its + * declaring class, and one called on an anonymous class created in a static + * context that is nested in the declaring class, which has no enclosing instance + * and calls the method on itself. For a method reference or pointer these are + * not kept, because dynamic Groovy fails on those. */ private List removeInheritedPrivateMethods(final List methods, final ClassNode type, final ClassNode declaredType, final boolean call) { ClassNode enclosingClass = typeCheckingContext.getEnclosingClassNode(); @@ -9393,7 +9396,9 @@ private List removeInheritedPrivateMethods(final List me && hasNoEnclosingInstance(enclosingClass) && !Modifier.isStatic(enclosingClass.getModifiers()); Predicate inherited = method -> isInheritedPrivateMethod(method, type) && !method.getDeclaringClass().equals(declaredType) - && !(call && (method.isStatic() || method.getDeclaringClass().equals(enclosingClass) + && !(method.isStatic() && (call || type.getOuterClasses().contains(method.getDeclaringClass()))) + && !isPrivateMethodOfEnumOfConstantBody(method, type) + && !(call && (method.getDeclaringClass().equals(enclosingClass) || (selfWithoutEnclosingInstance && enclosingClass.getOuterClasses().contains(method.getDeclaringClass())))); if (methods.stream().noneMatch(inherited)) return methods; @@ -9424,6 +9429,14 @@ private boolean isMethodOfEnclosingInstanceOfReceiver(final MethodNode method, f return findEnclosingInstanceTypeWithMethod(receiverType, method) != null; } + /** + * Determines if {@code method} is a private method of the enum that {@code type}, + * an enum constant body, extends: the meta-class of the body finds it there. + */ + private static boolean isPrivateMethodOfEnumOfConstantBody(final MethodNode method, final ClassNode type) { + return type.redirect() instanceof EnumConstantClassNode && method.getDeclaringClass().equals(type.getUnresolvedSuperClass()); + } + /** * Determines if the selected method is one of the receiver itself, as a * meta-class lookup on the receiver finds it: not a method of an outer class, diff --git a/src/spec/doc/core-object-orientation.adoc b/src/spec/doc/core-object-orientation.adoc index 5ba50f11f77..2c152331c70 100644 --- a/src/spec/doc/core-object-orientation.adoc +++ b/src/spec/doc/core-object-orientation.adoc @@ -255,7 +255,9 @@ With static compilation, a receiver whose static type is `Base`, such as `((Base `sub.name` reads the private field there only in `Base` and in the classes nested in `Base`; from another class of the same top-level class it is rejected. Dynamic code looks a member up on the meta-class of the object's class, so outside `Base` it does not find a private instance member of `Base` through a `Sub` object, unless an enclosing instance has it, as described below, and `@TypeChecked` rejects such a use where flow typing knows that the variable holds a `Sub`. 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`. -Private static members of `Base` stay reachable through `Sub` in every mode. +A private static method of `Base` stays reachable through `Sub` by a call such as `Sub.secret()` in every mode, and by a method pointer or reference such as `Sub.&secret` or `Sub::secret` where `Sub` is nested in `Base`, as dynamic Groovy finds the method there in the outer class. +Property syntax such as `Sub.name` does not reach a private static field or getter of `Base`: dynamic code fails on it, and the type checker rejects it outside `Base`. +A method pointer or reference to a private instance method of `Base` through a `Sub` receiver, such as `sub.&secret` or `Sub::secret`, is rejected even in `Base` itself and in an anonymous subclass created in a static context, as dynamic Groovy fails on it there, but not in an enum constant body, whose meta-class finds the private methods of its enum. In an inner class of `Base`, a method that the inner class lacks but `Base` has, such as `secret()`, `this.secret()` or, for another instance `other` of that inner class, `other.secret()` and an operator such as `other + x`, is called on the enclosing `Base` instance of `this` or of `other`, as dynamic Groovy calls it. Where the inner class also extends `Base`, `name` and `this.name` for a private member of `Base` use the enclosing instance as well. For a private accessor of `Base`, `other.name` uses the enclosing instance of `other` under `@TypeChecked`, and static compilation rejects it; for a private field, static compilation reads the field of `other` itself. diff --git a/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy b/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy index 9283db76c61..c259614550e 100644 --- a/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodReferenceTest.groovy @@ -3162,6 +3162,40 @@ final class MethodReferenceTest { } } + // GROOVY-12510: dynamic Groovy references a private static method through a + // subclass nested in its class, which it finds in the outer class, and a private + // method of an enum through an enum constant body, which the meta-class of the + // body finds + @ParameterizedTest + @ValueSource(strings=['@CompileDynamic','@TypeChecked','@CompileStatic']) + void testPrivateStaticOrEnumMethodReferenceThroughSubclass(String tag) { + assertScript shell, """ + $tag + class Box { + private static String sm() { 'sm' } + static List test() { [((Supplier) Sub::sm).get(), Sub.&sm()] } + static class Sub extends Box { + static List test() { [((Supplier) Sub::sm).get(), Sub.&sm()] } + } + static class Other { + static List test() { [((Supplier) Sub::sm).get(), Sub.&sm()] } + } + } + $tag + enum E { + A { + List test() { [((Supplier) this::helper).get(), this.&helper()] } + } + private String helper() { 'helper:' + name() } + List test() { null } + } + assert Box.test() == ['sm', 'sm'] + assert Box.Sub.test() == ['sm', 'sm'] + assert Box.Other.test() == ['sm', 'sm'] + assert E.A.test() == ['helper:A', 'helper:A'] + """ + } + // GROOVY-12510 @ParameterizedTest @ValueSource(strings=['@CompileDynamic','@TypeChecked','@CompileStatic']) From 28895346d5a7e479bea254aa6d27a74f3afb9d3e Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 22:41:08 -0800 Subject: [PATCH 35/38] GROOVY-12511: follow a closure-valued this$0 to the closure's this object 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. --- .../asm/sc/StaticInvocationWriter.java | 45 +++++++++++-------- .../transform/stc/MethodCallsSTCTest.groovy | 18 ++++++++ 2 files changed, 45 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java index bbaf79dfc69..fadf2a61d85 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticInvocationWriter.java @@ -289,14 +289,11 @@ private Expression thisObjectExpression(final ClassNode source, final ClassNode thisExpr = varX("thisObject", thisType); // adjust for multiple levels of nesting while (exact ? !thisType.equals(target) : !isSubtype(target, thisType)) { - FieldNode thisZero = thisType.getDeclaredField("this$0"); - if (thisZero != null) { - thisExpr = attrX(thisExpr, "this$0"); - thisExpr.setType(thisZero.getType()); - thisType = thisType.getOuterClass(); - if (thisType != null) continue; - } - break; + Expression outer = enclosingInstanceOf(thisExpr, thisType); + if (outer == null) break; + thisExpr = outer; + thisType = thisType.getOuterClass(); + if (thisType == null) break; } } return thisExpr; @@ -316,20 +313,32 @@ private static Expression enclosingInstanceExpression(final Expression receiver, if (outer == null) throw new GroovyBugError("no enclosing instance with " + method.getTypeDescriptor() + " for " + selectedType.getName()); Expression expr = receiverType.equals(selectedType) ? receiver : castX(selectedType, receiver); for (ClassNode type = selectedType; !type.equals(outer); type = type.getOuterClass()) { - FieldNode thisZero = type.getDeclaredField("this$0"); - if (thisZero == null) throw new GroovyBugError("no enclosing instance of " + outer.getName() + " for " + selectedType.getName()); - expr = attrX(expr, "this$0"); - expr.setType(thisZero.getType()); - if (ClassHelper.CLOSURE_TYPE.equals(thisZero.getType())) { // a class created in a closure: the closure's this object, as for Outer.this - MethodCallExpression thisObject = callX(expr, "getThisObject"); - thisObject.setImplicitThis(false); - thisObject.setMethodTarget(ClassHelper.CLOSURE_TYPE.getMethod("getThisObject", Parameter.EMPTY_ARRAY)); - expr = castX(type.getOuterClass(), thisObject); - } + expr = enclosingInstanceOf(expr, type); + if (expr == null) throw new GroovyBugError("no enclosing instance of " + outer.getName() + " for " + selectedType.getName()); } return expr; } + /** + * Returns the expression for the enclosing instance of {@code expr}, an instance + * of {@code type}: its {@code this$0} field or, for a class created in a closure, + * the this object of that closure, as for {@code Outer.this}; or {@code null} if + * {@code type} has no enclosing instance. + */ + private static Expression enclosingInstanceOf(final Expression expr, final ClassNode type) { + FieldNode thisZero = type.getDeclaredField("this$0"); + if (thisZero == null) return null; + Expression outer = attrX(expr, "this$0"); + outer.setType(thisZero.getType()); + if (ClassHelper.CLOSURE_TYPE.equals(thisZero.getType()) && type.getOuterClass() != null) { + MethodCallExpression thisObject = callX(outer, "getThisObject"); + thisObject.setImplicitThis(false); + thisObject.setMethodTarget(ClassHelper.CLOSURE_TYPE.getMethod("getThisObject", Parameter.EMPTY_ARRAY)); + outer = castX(type.getOuterClass(), thisObject); + } + return outer; + } + /** * Attempts to make a direct method call on a bridge method, if it exists. */ diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index 992a90ef40c..f4b180eb63b 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -1065,6 +1065,24 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12511: in a class created in a closure in an anonymous class created in a + // closure, this.m() is called on the this object of the outer closure + @Test + void testCallToMethodOfEnclosingInstanceThroughClosureInAnonymousClass() { + assertScript ''' + class Box { + String id + Box(String id) { this.id = id } + private String im() { 'im:' + id } + String test() { + def outer = { -> new Box('anon') { String test() { def inner = { -> this.im() }; inner() } }.test() } + outer() + } + } + assert new Box('A').test() == 'im:A' + ''' + } + // GROOVY-12511: this.m() in an inner class may name a method of the enclosing // class, as in dynamic Groovy @Test From d8c93cb22803cff34ffead02af5cfaf09458f855 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 22:41:14 -0800 Subject: [PATCH 36/38] GROOVY-12513: b.p = v selects the setter of a narrowed variable as b.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. --- .../stc/StaticTypeCheckingVisitor.java | 2 ++ .../stc/FieldsAndPropertiesSTCTest.groovy | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 2ac3b93e769..e1a13aeb367 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -1702,6 +1702,8 @@ private boolean ensureValidSetter(final Expression expression, final Expression && setterInfo.setters.stream().anyMatch(setter -> setter.isPrivate() && setter.getDeclaringClass().equals(declaredType)); VariableExpression receiver = varX("%", narrowed ? declaredType : setterInfo.receiverType); receiver.setType(setterInfo.receiverType); // same as origin type, unless narrowed + // the setter is selected for the narrower type, as for a call of it, with the private setter of the declared type + if (narrowed) receiver.putNodeMetaData(INFERRED_TYPE, setterInfo.receiverType); Function setterCall = (value) -> { typeCheckingContext.pushEnclosingBinaryExpression(null); // GROOVY-10628: LHS re-purposed diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index dabc6ccb5fc..5ccc11cc0b3 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2605,6 +2605,31 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12513: through a variable declared with a superclass that has a private + // setter, b.p = v selects the setter as b.setP(v) does + @Test + void testPropertySetterOfNarrowedVariableWithPrivateSetterOfDeclaredType() { + assertScript ''' + class Box { + String log + private void setP(Object o) { log = 'Box.setP(Object)' } + static class Sub extends Box { + void setP(String s) { log = 'Sub.setP(String)' } + } + static class Other { + static List test() { + Box b = new Sub() + b.p = 'x' + Box c = new Sub() + c.setP('x') + [b.log, c.log] + } + } + } + assert Box.Other.test() == ['Sub.setP(String)', 'Sub.setP(String)'] + ''' + } + // GROOVY-12509: dynamic Groovy also calls the accessors here, not the field @Test void testPrivateAccessorOfNestMateVersusPrivateField() { From e024391b81126c60bc84e1eff33f6c085d7be20c Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 22:41:20 -0800 Subject: [PATCH 37/38] GROOVY-12511: look up methods of an enclosing instance from the nearest 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. --- .../stc/StaticTypeCheckingVisitor.java | 28 ++++++++++--- .../transform/stc/MethodCallsSTCTest.groovy | 40 +++++++++++++++++++ 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index e1a13aeb367..9e4d9a43434 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -588,6 +588,12 @@ private static ClassNode literalDefaultImplementation(final ClassNode target, fi private Set instanceOfGuards = Collections.newSetFromMap(new IdentityHashMap<>()); /** Declared type of the variable whose method {@link #findMethod} is looking up, if any. */ private ClassNode declaredReceiverType; + /** + * Set for a receiver that offers only its static methods, such as the class that + * a {@code Class} receiver wraps or the class in a static method, and read once + * by the next {@link #findMethod}. + */ + private boolean staticOnlyReceiver; /** * Creates a static type-checking visitor for the supplied source and class. @@ -6901,6 +6907,7 @@ && isOwnerClosure(typeCheckingContext.getEnclosingClosureStack())) { for (Receiver currentReceiver : receivers) { ClassNode receiverType = currentReceiver.getType(); if (isClassType(receiverType)) receiverType = receiverType.getPlainNodeReference(); + staticOnlyReceiver = !currentReceiver.isObject(); // a static receiver can use only static methods, also of the outer classes mn = findMethodThrough(objectExpression, receiverType, name, args); if (!mn.isEmpty()) { first = mn.get(0); // capture for error reporting @@ -9234,10 +9241,12 @@ protected List findMethodsWithGenerated(final ClassNode receiver, fi *

* 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 (or - * none are given), the methods of its outer classes are candidates too, only the + * none are given), the methods of its outer classes are candidates too, from the + * nearest one out to the first that has a method accepting them, and only the * static ones beyond a class that has no enclosing instance: dynamic Groovy calls * such a method on the enclosing instance, and static compilation does too, see - * {@link StaticTypesMarker#ENCLOSING_INSTANCE_OF_RECEIVER}. + * {@link StaticTypesMarker#ENCLOSING_INSTANCE_OF_RECEIVER}. For a receiver that is + * the class itself, as in a static method, only its static methods count. *

* These rules are for calls. A method pointer or reference ({@code x.&m}, * {@code x::m}) is resolved elsewhere, with the exceptions for an enum constant @@ -9246,6 +9255,8 @@ protected List findMethodsWithGenerated(final ClassNode receiver, fi */ protected List findMethod(ClassNode receiver, final String name, final ClassNode... args) { if (isPrimitiveType(receiver)) receiver = getWrapper(receiver); + boolean staticOnlyReceiver = this.staticOnlyReceiver; // set for the class that a Class receiver wraps, below + this.staticOnlyReceiver = false; List methods; if ("".equals(name)) { @@ -9273,12 +9284,16 @@ protected List findMethod(ClassNode receiver, final String name, fin } } if (isTypeOfEnclosingClass(receiver) - // dynamic Groovy turns to the enclosing instance only for a method the receiver lacks, and javac to the innermost class - && (args == null || chooseBestMethod(receiver, filterMethodsByVisibility(methods, typeCheckingContext.getEnclosingClassNode()), args).isEmpty())) { - boolean staticOnly = hasNoEnclosingInstance(receiver); + // dynamic Groovy turns to the enclosing instance only for a method the receiver lacks, and javac to the innermost + // class; a receiver that is the class itself, as in a static method, has only its static methods + && (args == null || chooseBestMethod(receiver, filterMethodsByVisibility(allowStaticAccessToMember(methods, staticOnlyReceiver), typeCheckingContext.getEnclosingClassNode()), args).isEmpty())) { + boolean staticOnly = staticOnlyReceiver || hasNoEnclosingInstance(receiver); for (ClassNode outer = receiver; (outer = outer.getOuterClass()) != null; staticOnly = staticOnly || hasNoEnclosingInstance(outer)) { - methods.addAll(allowStaticAccessToMember(removeInheritedPrivateMethods(findMethodsWithGenerated(outer, name), outer, null, true), staticOnly)); + List outerMethods = allowStaticAccessToMember(removeInheritedPrivateMethods(findMethodsWithGenerated(outer, name), outer, null, true), staticOnly); + methods.addAll(outerMethods); + // dynamic Groovy tries the nearest enclosing instance first, and stops at one that has an applicable method + if (args != null && !chooseBestMethod(outer, filterMethodsByVisibility(outerMethods, typeCheckingContext.getEnclosingClassNode()), args).isEmpty()) break; } } if (args == null || args.length == 0) { @@ -9366,6 +9381,7 @@ protected List findMethod(ClassNode receiver, final String name, fin } if (isClassClassNodeWrappingConcreteType(receiver)) { // GROOVY-6802, GROOVY-6803, GROOVY-9415 + this.staticOnlyReceiver = true; List result = findMethod(receiver.getGenericsTypes()[0].getType(), name, args); result = allowStaticAccessToMember(result, true); // GROOVY-11427 if (!result.isEmpty()) return result; diff --git a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy index f4b180eb63b..7870fbf0e0a 100644 --- a/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/MethodCallsSTCTest.groovy @@ -1083,6 +1083,46 @@ class MethodCallsSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12511: in a static method, an instance method of the class does not + // stop the call from using an applicable static method of an outer class + @Test + void testCallToStaticMethodOfOuterClassFromStaticMethod() { + assertScript ''' + class Outer { + static String m(String s) { 'Outer.m(String)' } + static String n(String s) { 'Outer.n(String)' } + static class Inner { + String m(Object o) { 'Inner.m(Object)' } + static String n(Object o) { 'Inner.n(Object)' } + static List test() { [m('x'), new Inner().m('x'), n('x')] } + } + } + assert Outer.Inner.test() == ['Outer.m(String)', 'Inner.m(Object)', 'Inner.n(Object)'] + ''' + } + + // GROOVY-12511: the nearest enclosing instance with an applicable method is used, + // as dynamic Groovy tries them from the nearest one out + @Test + void testCallToMethodOfNearestEnclosingInstance() { + assertScript ''' + class Outer { + String m(String s) { 'Outer.m(String)' } + String n(String s) { 'Outer.n(String)' } + class Middle { + String m(Object o) { 'Middle.m(Object)' } + String n(Integer i) { 'Middle.n(Integer)' } + class Inner { + List test() { [this.m('x'), m('x'), n('x'), n(1)] } + } + List test() { new Inner().test() } + } + List test() { new Middle().test() } + } + assert new Outer().test() == ['Middle.m(Object)', 'Middle.m(Object)', 'Outer.n(String)', 'Middle.n(Integer)'] + ''' + } + // GROOVY-12511: this.m() in an inner class may name a method of the enclosing // class, as in dynamic Groovy @Test From 57b71aae4bb87d48e95342a8cf70d2a93e98a892 Mon Sep 17 00:00:00 2001 From: Scott Murphy Heiberg Date: Sun, 22 Nov 2026 22:41:26 -0800 Subject: [PATCH 38/38] GROOVY-12509: a private isX that a receiver only inherits leaves the 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. --- .../stc/StaticTypeCheckingVisitor.java | 3 +++ .../stc/FieldsAndPropertiesSTCTest.groovy | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index 9e4d9a43434..db8b522a9aa 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -3234,6 +3234,9 @@ else if (field != null && enclosingTypes.contains(current) && !superReceiver && MethodNode getter = getGetterMethod(current, isserName, checkUp); getter = allowStaticAccessToMember(getter, staticOnly); + if (getter != null && !isAccessibleAccessor(getter, receiverType, declaredType)) { + getter = null; // a private isX that is not a member of the receiver leaves getX, as for dynamic Groovy + } if (getter == null) { getter = getGetterMethod(current, getterName, checkUp); getter = allowStaticAccessToMember(getter, staticOnly); diff --git a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy index 5ccc11cc0b3..075d803e9cb 100644 --- a/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy +++ b/src/test/groovy/groovy/transform/stc/FieldsAndPropertiesSTCTest.groovy @@ -2605,6 +2605,26 @@ class FieldsAndPropertiesSTCTest extends StaticTypeCheckingTestCase { ''' } + // GROOVY-12509: a private isX that is not a member of the receiver leaves the + // public getX of the same class, as dynamic Groovy finds it + @Test + void testPrivateIsserAndPublicGetterOfSuperclass() { + assertScript ''' + class Outer { + static class Base { + private boolean isReady() { false } + boolean getReady() { true } + } + static class Sub extends Base { + } + static class Other { + static boolean test() { new Sub().ready } + } + } + assert Outer.Other.test() + ''' + } + // GROOVY-12513: through a variable declared with a superclass that has a private // setter, b.p = v selects the setter as b.setP(v) does @Test