diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index dfafee634f7..8123f5c31ca 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -1674,6 +1674,43 @@ is still rejected. `CompilerConfiguration.setClassTagPreemptionDisabled`) keeps the previous behaviour. +### Groovy 7 — a map literal stores a GString key as a String (GROOVY-3676) + +A map literal such as `["${key}": value]` used to store the key as a +`GString`. A subscript renders a `GString` to a `String` before `Map.get`, +and `String.equals` does not treat a `GString` as equal, so both +`map["${key}"]` and `map[key]` returned null while iteration still showed +the entry. The literal now stores the `String` from one `toString()` call, +taken when the literal is evaluated. That is the same rendering a dynamic +subscript assignment `map["${key}"] = value` already stored. A later change +to an interpolated value does not rename the entry. Two literal keys that +render the same text are one entry; the later value wins and the first +position is kept. + +A subscript whose argument is compiled as `Object` rather than `String` or +`GString` looks the `GString` up as itself and, only when that key is +absent, as the rendered `String`. An entry stored under the `GString` still +wins over a `String` of the same text. + +**Who is affected.** Code that read a map-literal key back as a `GString` +(`instanceof`, `is`, or a cast) or depended on a later change to an +interpolated value being visible in the key. `Map.get`, `containsKey` and +`remove` with a `GString` no longer find a literal's entry, because the +stored key is a `String` and `GString.equals` does not accept a `String`. +Use the `String`, or a subscript. Static type inference of a literal whose +key is a `GString`, a subclass of `GString`, or the `String`/`GString` +least upper bound now reports `String`. + +**What is unchanged.** Values are not rendered. `null` and every key that +is not a `GString` are stored as themselves. A spread copies the source +map's keys unchanged, so a `GString` passed to `Map.put` stays a `GString` +and remains distinct from a `String` of the same text. `Map.put` and +`Map.get` are not otherwise changed. The map is still a `LinkedHashMap`. + +**Who is not affected (binary).** `InvokerHelper.createMap` and +`ScriptBytecodeAdapter.createMap` keep their signatures. `japicmp` does +not report this. + ### Groovy 6.0.1 — a closure method call skips a null owner or delegate (GROOVY-12667) A closure's owner or delegate can be null: after `dehydrate()`, after diff --git a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java index 809fa5fa483..fe7077baa5e 100644 --- a/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java +++ b/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java @@ -8861,13 +8861,31 @@ public static T getAt(Iterable self, int idx) { * Support the subscript operator for a Map. *
def map = [1:10]
      * assert map[1] == 10
+ *

+ * A {@link GString} is looked up as itself first. When that key is + * present its value is returned, including null, and a {@code String} + * of the same text is not consulted. When the {@code GString} is absent, + * the {@link String} from one {@code toString()} call is looked up. + * A map literal stores that rendering, and a subscript whose static type + * is not {@code String} or {@code GString} selects this method, so the + * literal's entry is still found. A null key and every other key are + * passed to {@link Map#get(Object)} unchanged. Dynamic dispatch of a + * {@code GString} subscript selects the {@code String} overload instead, + * which renders the argument before {@code get}. * * @param self a Map * @param key an Object as a key for the map - * @return the value corresponding to the given key + * @return the value for the key that matched, or null when no key matched * @since 1.0 */ public static V getAt(Map self, Object key) { + if (key instanceof GString gString) { + V stored = self.get(key); + if (stored != null || self.containsKey(key)) { + return stored; + } + return self.get(gString.toString()); + } return self.get(key); } diff --git a/src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java b/src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java index 5efdae34c19..3685ae1240b 100644 --- a/src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java +++ b/src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java @@ -594,8 +594,12 @@ public static int initialCapacity(int initialEntryCnt) { * The initial capacity is {@link #initialCapacity(int)} of * {@code values.length / 2}. A pair whose first element is a * {@link SpreadMap} and whose second element is a {@link Map} contributes - * that map's entries. Every other pair is stored as one key and value. + * that map's entries, keeping each key as that map stored it. Every other + * pair is stored as one key and value. A direct key that is a + * {@link GString} is stored as the {@link String} from one + * {@code toString()} call, so a later subscript can find the entry. * A trailing element left without a pair is ignored. + * Values are stored as they are, including a {@code GString} value. * * @param values alternating keys and values, with optional spread pairs * @return the collected entries in insertion order @@ -611,12 +615,40 @@ public static Map createMap(Object[] values) { } i += 2; } else { - answer.put(values[i++], values[i++]); + answer.put(renderedMapKey(values[i++]), values[i++]); } } return answer; } + /** + * Key stored for one direct entry of a map literal. + *

+ * A {@link GString} is replaced by the result of one {@code toString()} + * call. Subscript lookup renders a {@code GString} argument to + * {@link String} before {@link Map#get(Object)}, and + * {@code String.equals} does not accept a {@code GString}, so a key left + * as a {@code GString} cannot be read back with the same interpolation or + * with the equivalent {@code String}. The text is the rendering at the + * moment the literal is evaluated. A later change to an interpolated + * value does not rename the entry, and two keys that render the same + * text are one entry; the later value wins and the first insertion + * position is kept. {@code null} stays {@code null}. A {@code toString()} + * that returns null is stored as a null key. Every other key is stored + * unchanged. + *

+ * A spread entry does not come through here. The source map's key is + * copied as stored, so a {@code GString} passed to + * {@link Map#put(Object, Object)} stays a {@code GString} and remains + * distinct from a {@code String} of the same text. + * + * @param key the key expression's value, or null + * @return the key to store + */ + private static Object renderedMapKey(Object key) { + return key instanceof GString gString ? gString.toString() : key; + } + /** * Throws the {@code AssertionError} returned by * {@link #createAssertError(Object, Object)} for {@code expression} diff --git a/src/main/java/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java b/src/main/java/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java index 37096f5bf4d..782cd44aafe 100644 --- a/src/main/java/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java +++ b/src/main/java/org/codehaus/groovy/runtime/ScriptBytecodeAdapter.java @@ -1528,9 +1528,10 @@ public static Wrapper createGroovyObjectWrapper(GroovyObject val, Class clazz) { /** * Creates a {@link Map} from {@code values} by calling {@code InvokerHelper.createMap}. - * Entries are taken as alternating keys and values, in pair order. A {@code SpreadMap} - * followed by a {@link Map} contributes that map's entries. A trailing value left without a - * pair is ignored. + * Entries are taken as alternating keys and values, in pair order. A direct key that is a + * {@code GString} is stored as the {@link String} it renders then, so the entry can be read + * back with that text. A {@code SpreadMap} followed by a {@link Map} contributes that map's + * entries with their existing keys. A trailing value left without a pair is ignored. * * @param values alternating keys and values, with optional spread pairs * @return the new map 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..ec3accd4ef0 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -9638,6 +9638,27 @@ protected ClassNode inferListExpressionType(final ListExpression list) { return listType; } + /** + * Static type of one direct key in a map literal. + *

+ * The literal stores a {@code GString} as the {@code String} it renders, + * and the same for the least upper bound of {@code String} and + * {@code GString}, because either value is a {@code String} after the + * literal is built. A subclass of {@code GString} is rendered too. A + * spread entry does not use this method: its key type is the key type of + * the spread map, which may still be a {@code GString} placed with + * {@code Map.put}. Every other key type is left as inferred. + * + * @param keyType the inferred type of the key expression, or null + * @return {@code String} when the stored key is that rendering, otherwise {@code keyType} + */ + private static ClassNode mapLiteralKeyType(final ClassNode keyType) { + if (keyType != null && (isGStringOrGStringStringLUB(keyType) || keyType.isDerivedFrom(ClassHelper.GSTRING_TYPE))) { + return STRING_TYPE; + } + return keyType; + } + /** * Infers the static type of a map literal. */ @@ -9658,7 +9679,7 @@ protected ClassNode inferMapExpressionType(final MapExpression map) { for (MapEntryExpression entryExpression : entryExpressions) { valueType = getType(entryExpression.getValueExpression()); if (!(entryExpression.getKeyExpression() instanceof SpreadMapExpression)) { - keyType = getType(entryExpression.getKeyExpression()); + keyType = mapLiteralKeyType(getType(entryExpression.getKeyExpression())); } else { // GROOVY-7247 valueType = GenericsUtils.parameterizeType(valueType, MAP_TYPE); keyType = getCombinedBoundType(valueType.getGenericsTypes()[0]); diff --git a/src/spec/doc/_working-with-collections.adoc b/src/spec/doc/_working-with-collections.adoc index 113973f6774..49829a6f37e 100644 --- a/src/spec/doc/_working-with-collections.adoc +++ b/src/spec/doc/_working-with-collections.adoc @@ -441,8 +441,8 @@ Maps generated using the map literal syntax are using the object `equals` and `h you should *never* use an object which hash code is subject to change over time, or you wouldn't be able to get the associated value back. -It is also worth noting that you should *never* use a `GString` as the key of a map, because the hash code of a `GString` -is not the same as the hash code of an equivalent `String`: +A map literal renders a `GString` key to a `String` when the map is created, so lookup with that `String` or with an equivalent `GString` finds the entry. +`Map.put` does not. The hash code of a `GString` is not the hash code of the equivalent `String`, so a key stored with `put` is missed by `get` of that `String`: [source,groovy] --------------------- diff --git a/src/spec/doc/core-semantics.adoc b/src/spec/doc/core-semantics.adoc index 2c0b71e746f..a6849e96dea 100644 --- a/src/spec/doc/core-semantics.adoc +++ b/src/spec/doc/core-semantics.adoc @@ -2362,7 +2362,7 @@ include::../test/typing/TypeCheckingTest.groovy[tags=map_literal_inference_simpl ---- include::../test/typing/TypeCheckingTest.groovy[tags=map_literal_inference_gstring,indent=0] ---- -|`java.util.LinkedHashMap` be careful, the key is a `GString`! +|`java.util.LinkedHashMap` a `GString` key expression is stored as the `String` it renders |[source,groovy] ---- diff --git a/src/spec/doc/core-syntax.adoc b/src/spec/doc/core-syntax.adoc index 644179bea49..692a1b2cc8e 100644 --- a/src/spec/doc/core-syntax.adoc +++ b/src/spec/doc/core-syntax.adoc @@ -558,15 +558,15 @@ Even for the same resulting string, GStrings and Strings don't have the same has include::../test/SyntaxTest.groovy[tags=gstring_hashcode_1,indent=0] ---- -GString and Strings having different hashCode values, using GString as Map keys should be avoided, -especially if we try to retrieve an associated value with a String instead of a GString. +GString and Strings having different hashCode values, `Map.put` of a GString does not match a later `get` with the equivalent String. +A map literal does not keep that GString: it stores the String rendered when the literal is evaluated, so the entry is found with that String or with another GString that renders the same text. [source,groovy] ---- include::../test/SyntaxTest.groovy[tags=gstring_hashcode_2,indent=0] ---- -<1> The map is created with an initial pair whose key is a GString -<2> When we try to fetch the value with a String key, we will not find it, as Strings and GString have different hashCode values +<1> The map literal stores the key as the String rendered from the GString +<2> A String subscript finds that entry, and so does the same GString === Triple-double-quoted string diff --git a/src/spec/test/SyntaxTest.groovy b/src/spec/test/SyntaxTest.groovy index c743db5ca75..87ba3310201 100644 --- a/src/spec/test/SyntaxTest.groovy +++ b/src/spec/test/SyntaxTest.groovy @@ -472,7 +472,8 @@ final class SyntaxTest extends CompilableTestSupport { def key = "a" def m = ["${key}": "letter ${key}"] // <1> - assert m["a"] == null // <2> + assert m["a"] == "letter a" // <2> + assert m["${key}"] == "letter a" // end::gstring_hashcode_2[] } diff --git a/src/spec/test/typing/TypeCheckingTest.groovy b/src/spec/test/typing/TypeCheckingTest.groovy index ca1fb546bf2..4a89517a79b 100644 --- a/src/spec/test/typing/TypeCheckingTest.groovy +++ b/src/spec/test/typing/TypeCheckingTest.groovy @@ -513,7 +513,7 @@ final class TypeCheckingTest extends StaticTypeCheckingTestCase { @ASTTest(phase=INSTRUCTION_SELECTION,value={ def inft = node.getNodeMetaData(INFERRED_TYPE) assert inft == make(LinkedHashMap) - assert inft.genericsTypes[0].type == GSTRING_TYPE + assert inft.genericsTypes[0].type == STRING_TYPE assert inft.genericsTypes[1].type == STRING_TYPE }) // tag::map_literal_inference_gstring[] @@ -521,6 +521,27 @@ final class TypeCheckingTest extends StaticTypeCheckingTestCase { // end::map_literal_inference_gstring[] ''' + assertScript ''' + def someKey = 'k' + def flag = true + @ASTTest(phase=INSTRUCTION_SELECTION,value={ + def inft = node.getNodeMetaData(INFERRED_TYPE) + assert inft.genericsTypes[0].type == STRING_TYPE + }) + def fromBound = [(flag ? 'a' : "${someKey}"): 'v'] + + class GS extends GString { + GS() { super(new Object[0]) } + String[] getStrings() { ['sub'] as String[] } + } + GS sub = new GS() + @ASTTest(phase=INSTRUCTION_SELECTION,value={ + def inft = node.getNodeMetaData(INFERRED_TYPE) + assert inft.genericsTypes[0].type == STRING_TYPE + }) + def fromSub = [(sub): 'v'] + ''' + assertScript ''' @ASTTest(phase=INSTRUCTION_SELECTION,value={ def type = node.getNodeMetaData(INFERRED_TYPE) diff --git a/src/test/groovy/bugs/Groovy12165.groovy b/src/test/groovy/bugs/Groovy12165.groovy index 20af501c92a..3e213994418 100644 --- a/src/test/groovy/bugs/Groovy12165.groovy +++ b/src/test/groovy/bugs/Groovy12165.groovy @@ -86,9 +86,11 @@ final class Groovy12165 { void testTypedGuardFallsThroughToCoercion() { assertScript ''' // a GString key is NOT an instance of the String parameter type: the guard fails, - // the call falls through to the metaclass, and its coercion produces a real String + // the call falls through to the metaclass, and its coercion produces a real String. + // Map.put keeps the GString; a map literal would store the rendered String def name = 'a' - def m = [("k${name}"): 1] + def m = [:] + m.put(("k${name}"), 1) assert m.keySet()[0] !instanceof String // premise: the key stays a GString def out = [] m.each { String k, Integer v -> assert k.class == String; out << "$k=$v".toString() } diff --git a/src/test/groovy/bugs/Groovy3676.groovy b/src/test/groovy/bugs/Groovy3676.groovy new file mode 100644 index 00000000000..8fde558cee8 --- /dev/null +++ b/src/test/groovy/bugs/Groovy3676.groovy @@ -0,0 +1,249 @@ +/* + * 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 groovy.lang.GString +import groovy.transform.CompileStatic +import org.codehaus.groovy.runtime.GStringImpl +import org.codehaus.groovy.runtime.InvokerHelper +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.assertScript + +/** + * A map literal used to keep a GString key, while a subscript renders a + * GString to a String before {@code Map.get}. The entry was visible to + * iteration and invisible to {@code map["${key}"]} and {@code map[key]}. + * The literal now stores that rendering. {@code Map.put} is unchanged, so a + * GString placed that way stays distinct from the equivalent String. + */ +final class Groovy3676 { + + // GROOVY-3676 + @Test + void testLiteralIsReadableByTheSameGStringAndByTheString() { + assertScript ''' + key1 = "VARIABLE_1" + a1 = [ "${key1}" : "YES 3" ] + def seen = [] + a1.eachWithIndex { entry, index -> seen << "$entry" } + assert seen == ['VARIABLE_1=YES 3'] + assert a1["${key1}"] == "YES 3" + assert a1[key1] == "YES 3" + assert a1.VARIABLE_1 == "YES 3" + assert a1.get(key1) == "YES 3" + assert a1.containsKey(key1) + ''' + } + + // GROOVY-3676 + @Test + void testLiteralKeyIsTheRenderedString() { + assertScript ''' + def key = 'a' + def value = "${'letter'} ${key}" + def m = ["${key}": value] + assert m.keySet().iterator().next() instanceof String + assert m.keySet().iterator().next() == 'a' + assert m["${key}"] == 'letter a' + assert m['a'] == 'letter a' + assert m.get('a') == 'letter a' + assert m.get("${key}") == null + assert !m.containsKey("${key}") + assert m == [a: 'letter a'] + assert value instanceof GString + assert m['a'].is(value) + ''' + } + + // GROOVY-3676 + @Test + void testRenderedKeyDoesNotFollowLaterChanges() { + assertScript ''' + def buf = new StringBuilder('ab') + def m = ["$buf": 'v'] + buf.append('c') + assert m['ab'] == 'v' + assert m['abc'] == null + assert m.keySet().iterator().next() == 'ab' + assert !m.containsKey("$buf") + ''' + } + + // GROOVY-3676 + @Test + void testKeysThatRenderTheSameTextAreOneEntry() { + assertScript ''' + def m = ["${'a'}": 1, b: 2, a: 3] + assert m.size() == 2 + assert m['a'] == 3 + assert m['b'] == 2 + assert m.keySet() as List == ['a', 'b'] + ''' + } + + // GROOVY-3676 + @Test + void testNamedArgumentAndPropertyReadUseTheRenderedKey() { + assertScript ''' + def take(Map args) { args.name } + assert take("${'name'}": 'Ada') == 'Ada' + def m = ["${'name'}": 'Ada'] + assert m."${'name'}" == 'Ada' + ''' + } + + // GROOVY-3676 + @Test + void testPutStillKeepsAGStringDistinctFromItsString() { + assertScript ''' + def g = "${'SOME KEY'}" + def map = [:] + map.put(g, 'value') + assert map.get('SOME KEY') == null + assert map.get(g) == 'value' + assert map[g] == null + assert map['SOME KEY'] == null + assert map.keySet().iterator().next().is(g) + ''' + } + + // GROOVY-3676 + @Test + void testSpreadCopiesAStoredGStringAndALiteralRenders() { + assertScript ''' + def g = "${'a'}" + def src = [:] + src.put(g, 'from-gstring') + src.put('a', 'from-string') + def copy = [*:src, "${'b'}": 'bee'] + assert copy.size() == 3 + assert copy.get(g) == 'from-gstring' + assert copy.get('a') == 'from-string' + assert copy['b'] == 'bee' + assert copy.keySet().any { it.is(g) } + + def k = 'a' + def over = [*:["${k}": 1], "${k}": 2] + assert over.size() == 1 + assert over[k] == 2 + assert over.keySet().iterator().next() instanceof String + ''' + } + + // GROOVY-3676 + @Test + void testOtherKeysAndNullAreStoredAsThemselves() { + def map = InvokerHelper.createMap([null, 'nil', 1, 'n', true, 'b'] as Object[]) + assert map[null] == 'nil' + assert map[1] == 'n' + assert map[true] == 'b' + assert map.size() == 3 + + def trailing = InvokerHelper.createMap(['only-key'] as Object[]) + assert trailing.isEmpty() + } + + // GROOVY-3676 + @Test + void testCustomGStringIsRenderedOnce() { + def calls = 0 + def g = new GString(['z'] as Object[]) { + @Override + String[] getStrings() { ['', ''] as String[] } + + @Override + String toString() { + calls++ + 'z' + } + } + Object[] values = new Object[4] + values[0] = g + values[1] = 'v' + values[2] = new GStringImpl(new Object[] {'a'}, new String[] {'', ''}) + values[3] = 'w' + def map = InvokerHelper.createMap(values) + assert calls == 1 + assert map == [z: 'v', a: 'w'] + assert map.keySet().every { it instanceof String } + } + + // GROOVY-3676 + @Test + void testCompileStaticLiteralLookup() { + assertScript ''' + import groovy.transform.CompileStatic + + @CompileStatic + def read(Map map, Object key) { map[key] } + + def key1 = 'VARIABLE_1' + def a1 = ["${key1}": 'YES 3'] + assert a1["${key1}"] == 'YES 3' + assert a1[key1] == 'YES 3' + assert read(a1, key1) == 'YES 3' + assert read(a1, "${key1}") == 'YES 3' + assert a1.keySet().iterator().next() instanceof String + ''' + } + + // GROOVY-3676 + @Test + void testObjectGetAtFindsAStringKeyWhenNoGStringEntryExists() { + def g = "${'a'}" + def map = new LinkedHashMap() + map.put('a', 'yes') + assert readKey(map, g) == 'yes' + + map.put('a', null) + assert readKey(map, g) == null + assert map.containsKey('a') + + def blanks = new LinkedHashMap() + blanks.put('', 'empty') + blanks.put(null, 'nil') + assert readKey(blanks, "${''}") == 'empty' + assert readKey(blanks, null) == 'nil' + } + + // GROOVY-3676 + @Test + void testObjectGetAtKeepsAStoredGStringAheadOfTheSameString() { + def g = "${'a'}" + def map = new LinkedHashMap() + map.put(g, 'from-gstring') + map.put('a', 'from-string') + assert readKey(map, g) == 'from-gstring' + + map.clear() + map.put(g, null) + assert readKey(map, g) == null + assert map.containsKey(g) + assert !map.containsKey('a') + + assert readKey(new LinkedHashMap(), "${'missing'}") == null + assert readKey([1: 'n'], 1) == 'n' + } + + @CompileStatic + private static Object readKey(Map map, Object key) { + map[key] + } +} diff --git a/src/test/groovy/bugs/RegressionTest.groovy b/src/test/groovy/bugs/RegressionTest.groovy index b682f4505d3..ec7abe56cf2 100644 --- a/src/test/groovy/bugs/RegressionTest.groovy +++ b/src/test/groovy/bugs/RegressionTest.groovy @@ -261,7 +261,7 @@ final class RegressionTest { } // GROOVY-3676: Explicitly dereferenced hash values created by variables return null - @NotYetImplemented @Test + @Test void testGroovy3676() { assertScript ''' def key1 = "VARIABLE_1"