You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/10/22 20:11:31 UTC
(groovy) 02/03: GROOVY-12476: STC: toString() on an interface-typed receiver selects DGM toString(Object) over the runtime override (regression from 4.x)
This is an automated email from the ASF dual-hosted git repository.
paulk-asert pushed a commit to branch GROOVY_5_1_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 960bc2c426643fd744a683d0f245652244c246e5
Author: Paul King <pa...@asert.com.au>
AuthorDate: Thu Oct 22 14:56:34 2026 +1000
GROOVY-12476: STC: toString() on an interface-typed receiver selects DGM toString(Object) over the runtime override (regression from 4.x)
When toString() is called on a receiver whose static type does not declare
it, static compilation binds to a DefaultGroovyMethods toString extension.
Those extensions now call the runtime class's own toString() when dynamic
dispatch would select it: one declared below AbstractCollection, AbstractMap
or Object (whichever the class extends) and visible to Groovy. Otherwise
they format as before. The answer is cached per class.
Statically compiled toString() now matches dynamic Groovy, including through
Object-typed receivers and for JDK classes with their own public toString()
such as CopyOnWriteArrayList, ConcurrentHashMap and Properties.
String concatenation (plus/minus) and ConvertedMap.toString() keep the Groovy
formatting, matching GString interpolation.
---
.../org/codehaus/groovy/runtime/ConvertedMap.java | 2 +-
.../groovy/runtime/DefaultGroovyMethods.java | 38 +++++-
.../groovy/runtime/StringGroovyMethods.java | 6 +-
src/test/groovy/bugs/Groovy12476.groovy | 128 +++++++++++++++++++++
4 files changed, 165 insertions(+), 9 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/runtime/ConvertedMap.java b/src/main/java/org/codehaus/groovy/runtime/ConvertedMap.java
index c0c98127dd..536cc423fd 100644
--- a/src/main/java/org/codehaus/groovy/runtime/ConvertedMap.java
+++ b/src/main/java/org/codehaus/groovy/runtime/ConvertedMap.java
@@ -56,7 +56,7 @@ public class ConvertedMap extends ConversionHandler {
@Override
public String toString() {
- return DefaultGroovyMethods.toString(getDelegate());
+ return FormatHelper.toString(getDelegate());
}
@Override
diff --git a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
index b505dc7d77..b9b8f91ccb 100644
--- a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
+++ b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -58,8 +58,10 @@ import org.apache.groovy.io.StringBuilderWriter;
import org.apache.groovy.util.ReversedList;
import org.apache.groovy.util.SystemUtil;
import org.codehaus.groovy.classgen.Verifier;
+import org.codehaus.groovy.reflection.CachedMethod;
import org.codehaus.groovy.reflection.ClassInfo;
import org.codehaus.groovy.reflection.MixinInMetaClass;
+import org.codehaus.groovy.reflection.ReflectionCache;
import org.codehaus.groovy.reflection.ReflectionUtils;
import org.codehaus.groovy.reflection.stdclasses.CachedSAMClass;
import org.codehaus.groovy.runtime.callsite.BooleanClosureForMapPredicate;
@@ -11608,7 +11610,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* @since 4.0.3
*/
public static String plus(Map left, String right) {
- return DefaultGroovyMethods.toString(left) + right;
+ return FormatHelper.toString(left) + right;
}
/**
@@ -11624,7 +11626,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* @since 4.0.3
*/
public static String plus(Map left, GString right) {
- return DefaultGroovyMethods.toString(left) + right;
+ return FormatHelper.toString(left) + right;
}
/**
@@ -15643,6 +15645,32 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
//--------------------------------------------------------------------------
// toString
+ /**
+ * Whether a class declares a {@code toString()} that dynamic dispatch selects
+ * over the matching extension method: one declared by a class below
+ * {@code AbstractCollection}, {@code AbstractMap} or {@code Object} (whichever
+ * the class extends) and visible to Groovy.
+ */
+ private static final ClassValue<Boolean> DECLARES_TO_STRING = new ClassValue<>() {
+ @Override
+ protected Boolean computeValue(final Class<?> type) {
+ Class<?> bound = AbstractCollection.class.isAssignableFrom(type) ? AbstractCollection.class
+ : AbstractMap.class.isAssignableFrom(type) ? AbstractMap.class : Object.class;
+ for (Class<?> c = type; c != null && c != bound; c = c.getSuperclass()) {
+ for (CachedMethod m : ReflectionCache.getCachedClass(c).getMethods()) {
+ if (m.getParamsCount() == 0 && !m.isStatic() && "toString".equals(m.getName())) {
+ return Boolean.TRUE;
+ }
+ }
+ }
+ return Boolean.FALSE;
+ }
+ };
+
+ private static boolean declaresToString(final Object self) {
+ return self != null && DECLARES_TO_STRING.get(self.getClass());
+ }
+
/**
* Returns the string representation of the given map.
*
@@ -15652,7 +15680,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* @since 1.0
*/
public static String toString(AbstractMap self) {
- return toMapString(self);
+ return declaresToString(self) ? self.toString() : toMapString(self);
}
/**
@@ -15666,7 +15694,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* @since 1.0
*/
public static String toString(AbstractCollection self) {
- return toListString(self);
+ return declaresToString(self) ? self.toString() : toListString(self);
}
/**
@@ -15676,7 +15704,7 @@ public class DefaultGroovyMethods extends DefaultGroovyMethodsSupport {
* @since 1.0
*/
public static String toString(Object value) {
- return FormatHelper.toString(value);
+ return declaresToString(value) ? value.toString() : FormatHelper.toString(value);
}
//--------------------------------------------------------------------------
diff --git a/src/main/java/org/codehaus/groovy/runtime/StringGroovyMethods.java b/src/main/java/org/codehaus/groovy/runtime/StringGroovyMethods.java
index 5b006db751..deafe8feeb 100644
--- a/src/main/java/org/codehaus/groovy/runtime/StringGroovyMethods.java
+++ b/src/main/java/org/codehaus/groovy/runtime/StringGroovyMethods.java
@@ -2047,7 +2047,7 @@ public class StringGroovyMethods extends DefaultGroovyMethodsSupport {
*/
public static String minus(final CharSequence self, final Object target) {
String s = self.toString();
- String text = DefaultGroovyMethods.toString(target);
+ String text = FormatHelper.toString(target);
int index = s.indexOf(text);
if (index == -1) return s;
int end = index + text.length();
@@ -2341,7 +2341,7 @@ public class StringGroovyMethods extends DefaultGroovyMethodsSupport {
* @since 1.8.2
*/
public static String plus(final CharSequence left, final Object right) {
- return left + DefaultGroovyMethods.toString(right);
+ return left + FormatHelper.toString(right);
}
/**
@@ -2354,7 +2354,7 @@ public class StringGroovyMethods extends DefaultGroovyMethodsSupport {
* @since 1.0
*/
public static String plus(final Number left, final String right) {
- return DefaultGroovyMethods.toString(left) + right;
+ return FormatHelper.toString(left) + right;
}
/**
diff --git a/src/test/groovy/bugs/Groovy12476.groovy b/src/test/groovy/bugs/Groovy12476.groovy
new file mode 100644
index 0000000000..02b5ddae16
--- /dev/null
+++ b/src/test/groovy/bugs/Groovy12476.groovy
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package bugs
+
+import org.junit.jupiter.api.Test
+
+import static groovy.test.GroovyAssert.assertScript
+
+/**
+ * Under static compilation, {@code toString()} on a receiver whose static type
+ * does not declare it resolves to a {@code DefaultGroovyMethods} extension. The
+ * result must match dynamic dispatch, which picks a {@code toString()} override
+ * declared below {@code AbstractCollection}, {@code AbstractMap} or {@code Object}.
+ */
+final class Groovy12476 {
+
+ private static final String CLASSES = '''
+ import groovy.transform.CompileStatic
+
+ interface Element {}
+ class JsonList extends ArrayList<Object> implements Element { String toString() { 'JSONLIST' } }
+ class JsonMap extends HashMap<String, Object> implements Element { String toString() { 'JSONMAP' } }
+ class Plain implements Element { String toString() { 'PLAIN' } }
+
+ @CompileStatic
+ class SC {
+ static String element(Element e) { e.toString() }
+ static String list(List e) { e.toString() }
+ static String collection(Collection e) { e.toString() }
+ static String iterable(Iterable e) { e.toString() }
+ static String map(Map e) { e.toString() }
+ static String object(Object e) { e.toString() }
+ static String arrayList(ArrayList e) { e.toString() }
+ static String hashMap(HashMap e) { e.toString() }
+ }
+ String dyn(Object e) { e.toString() }
+ '''
+
+ @Test
+ void testOverrideReachedThroughInterfaceOrObject() {
+ assertScript CLASSES + '''
+ def list = new JsonList() << [k: 1]
+ def map = new JsonMap(k: [1])
+ assert SC.element(list) == 'JSONLIST'
+ assert SC.list(list) == 'JSONLIST'
+ assert SC.collection(list) == 'JSONLIST'
+ assert SC.iterable(list) == 'JSONLIST'
+ assert SC.object(list) == 'JSONLIST'
+ assert SC.element(map) == 'JSONMAP'
+ assert SC.map(map) == 'JSONMAP'
+ assert SC.object(map) == 'JSONMAP'
+ assert SC.element(new Plain()) == 'PLAIN'
+ '''
+ }
+
+ @Test
+ void testOverrideReachedThroughSuperclassWithoutOwnToString() {
+ assertScript CLASSES + '''
+ assert SC.arrayList(new JsonList() << 1) == 'JSONLIST'
+ assert SC.hashMap(new JsonMap(k: 1)) == 'JSONMAP'
+ '''
+ }
+
+ @Test
+ void testStaticAndDynamicAgree() {
+ assertScript CLASSES + '''
+ import java.util.concurrent.ConcurrentHashMap
+ import java.util.concurrent.CopyOnWriteArrayList
+
+ def nested = [k: 1]
+ def lists = [new ArrayList([nested]), Arrays.asList(nested), List.of(nested), new HashSet([nested]),
+ Collections.unmodifiableList([nested]), Collections.synchronizedList([nested]),
+ new CopyOnWriteArrayList([nested]), new JsonList() << nested,
+ new ArrayList([nested]) { String toString() { 'ANON' } }]
+ def maps = [new HashMap(k: [1]), new TreeMap(k: [1]), Map.of('k', [1]),
+ Collections.unmodifiableMap([k: [1]]), new ConcurrentHashMap(k: [1]),
+ new Properties().tap { put('k', 'v') }, new JsonMap(k: [1])]
+ lists.each { v ->
+ String d = dyn(v)
+ assert SC.collection(v) == d
+ assert SC.iterable(v) == d
+ assert SC.object(v) == d
+ if (v instanceof List) assert SC.list(v) == d
+ }
+ maps.each { v ->
+ String d = dyn(v)
+ assert SC.map(v) == d
+ assert SC.object(v) == d
+ }
+ [1..3, 'abc', 1.50G, new Object(), [1, 2] as int[], Optional.of(nested)].each { v ->
+ assert SC.object(v) == dyn(v)
+ }
+ '''
+ }
+
+ @Test
+ void testStringConcatenationMatchesInterpolation() {
+ assertScript '''
+ import java.util.concurrent.ConcurrentHashMap
+ import java.util.concurrent.CopyOnWriteArrayList
+
+ def values = [new Hashtable(k: [1]), new ConcurrentHashMap(k: [1]), new CopyOnWriteArrayList([[k: 1]])]
+ values.each { v ->
+ assert 'x' + v == "x$v"
+ if (v instanceof Map) assert v + 'x' == "${v}x"
+ }
+ assert 'x' + new Hashtable(k: 1) == 'x[k:1]'
+ assert new Hashtable(k: 1) + 'x' == '[k:1]x'
+ assert 'x[k:1]' - new Hashtable(k: 1) == 'x'
+ '''
+ }
+}