Scott Murphy Heiberg created GROOVY-12837:
---------------------------------------------
Summary: STC: a value written to a raw or def map started from a
map literal is converted to the literal's inferred value type
Key: GROOVY-12837
URL: https://issues.apache.org/jira/browse/GROOVY-12837
Project: Groovy
Issue Type: Bug
Components: Static Type Checker
Affects Versions: 7.0.0-alpha-1, 6.0.1
Reporter: Scott Murphy Heiberg
GROOVY-12535 converts a value written to a map by a property or subscript
assignment to the map's value type. COMPATIBILITY.md says of it: "a map whose
value type is not known (def, raw or a wildcard) is written as before". That
holds when the variable starts from an empty literal
(Groovy12535.rawMapKeepsGString uses Map m = \[:\]), but not when it starts
from a literal with entries. The literal gives the variable an inferred type of
LinkedHashMap<String,String>, the write is checked against that inferred type,
and the value is converted to String:
{code:groovy}
import groovy.transform.CompileStatic
@CompileStatic
def go(boolean ok) {
Map hints = [threadTs: '1787.0001', username: 'Dana']
hints.settleReactionOk = ok
hints.settleReactionOk
}
def v = go(false)
assert v instanceof Boolean // 6.0.0: passes. 6.0.1-SNAPSHOT and master: v is
the String 'false'
{code}
The same happens with def hints = \[...\] and var hints = \[...\]. Nothing is
reported at compile time. The stored String 'false' is truthy, so code that
reads the entry back as a flag takes the wrong branch; this is how it was found
(a failure status was shown as success in an application moved from 6.0.0 to
6.0.1-SNAPSHOT).
Results of m.b = ok for a boolean ok, by declaration of m:
|| declaration || 6.0.0 || 6.0.1-SNAPSHOT / master (2026-11-26) ||
| Map<String,String> m = \[a: 'x'\] | Boolean | String (intended by
GROOVY-12535) |
| Map m = \[a: 'x'\] | Boolean | String |
| def m = \[a: 'x'\] | Boolean | String |
| var m = \[a: 'x'\] | Boolean | String |
| Map<String,Object> m = \[a: 'x'\] | Boolean | Boolean |
| Map m = new HashMap() | Boolean | Boolean |
| Map m = \[:\] | Boolean | Boolean |
Expected: the declared type of a local variable decides. A variable declared
raw, def or var declares no value type, so the value is stored as it is, as on
6.0.0 and as COMPATIBILITY.md states.
Proposed fix (pull request to follow): mapValueTypeToConvertTo takes the map
type of a local variable receiver from the variable's declared type instead of
its inferred type. A subscript write to such a variable (m\['b'\] = ok) is then
rejected as it is on 6.0.0, instead of being accepted and converted.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)