Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions COMPATIBILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sounds wrong. In dynamic Groovy key=1; map = ["${key}": value]; map["${key}"] is still compiled the same. And actually your changed in DGM depends on that. You should try map."1" in dynamic Groovy for the GString case I mentioned. If I am right this will not find the entry, while m["1"] should. Where you did make a change is for static compilation though.


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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8861,13 +8861,31 @@ public static <T> T getAt(Iterable<T> self, int idx) {
* Support the subscript operator for a Map.
* <pre class="language-groovy groovyTestCase">def map = [1:10]
* assert map[1] == 10</pre>
* <p>
* 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 <K,V> V getAt(Map<K,V> 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);
}

Expand Down
36 changes: 34 additions & 2 deletions src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
* <p>
* 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.
* <p>
* 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}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9638,6 +9638,27 @@ protected ClassNode inferListExpressionType(final ListExpression list) {
return listType;
}

/**
* Static type of one direct key in a map literal.
* <p>
* 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.
*/
Expand All @@ -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]);
Expand Down
4 changes: 2 additions & 2 deletions src/spec/doc/_working-with-collections.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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]
---------------------
Expand Down
2 changes: 1 addition & 1 deletion src/spec/doc/core-semantics.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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<GString,String>` be careful, the key is a `GString`!
|`java.util.LinkedHashMap<String,String>` a `GString` key expression is stored as the `String` it renders

|[source,groovy]
----
Expand Down
8 changes: 4 additions & 4 deletions src/spec/doc/core-syntax.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion src/spec/test/SyntaxTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -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[]
}

Expand Down
23 changes: 22 additions & 1 deletion src/spec/test/typing/TypeCheckingTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -513,14 +513,35 @@ 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[]
def map = ["${someKey}": 'someValue']
// 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)
Expand Down
6 changes: 4 additions & 2 deletions src/test/groovy/bugs/Groovy12165.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -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() }
Expand Down
Loading
Loading