Skip to content
Merged
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
27 changes: 24 additions & 3 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -924,10 +924,10 @@ func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) {
if d.unmarshal(n.Content[i], k) {
if mergedFields != nil {
ki := k.Interface()
if mergedFields[ki] {
if d.getPossiblyUnhashableKey(mergedFields, ki) {
continue
}
mergedFields[ki] = true
d.setPossiblyUnhashableKey(mergedFields, ki, true)
}
kkind := k.Kind()
if kkind == reflect.Interface {
Expand Down Expand Up @@ -1052,14 +1052,35 @@ func failWantMap() {
failf("map merge requires map or sequence of maps as the value")
}

// A key of a mapping being merged is not checked for hashability before it is
// looked up, and a map or a sequence key panics when hashed. Report it as a
// yaml error, like the key check further down the mapping does.
func (d *decoder) setPossiblyUnhashableKey(m map[interface{}]bool, key interface{}, value bool) {
defer func() {
if err := recover(); err != nil {
failf("%v", err)
}
}()
m[key] = value
}

func (d *decoder) getPossiblyUnhashableKey(m map[interface{}]bool, key interface{}) bool {
defer func() {
if err := recover(); err != nil {
failf("%v", err)
}
}()
return m[key]
}

func (d *decoder) merge(parent *Node, merge *Node, out reflect.Value) {
mergedFields := d.mergedFields
if mergedFields == nil {
d.mergedFields = make(map[interface{}]bool)
for i := 0; i < len(parent.Content); i += 2 {
k := reflect.New(ifaceType).Elem()
if d.unmarshal(parent.Content[i], k) {
d.mergedFields[k.Interface()] = true
d.setPossiblyUnhashableKey(d.mergedFields, k.Interface(), true)
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1036,6 +1036,10 @@ var unmarshalErrorTests = []struct {
{"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"},
{"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`},
{"{{.}}", `yaml: invalid map key: map\[string]interface \{\}\{".":interface \{\}\(nil\)\}`},
// A map or sequence key of a merged mapping is looked up among the keys
// already seen before the key check rejects it, and hashing one panics.
{"<<:\n ? [1]\n : v\n1: x\n", `yaml: runtime error: hash of unhashable type \[\]interface \{\}`},
{"<<:\n ? {k: v}\n : 1\n1: x\n", `yaml: runtime error: hash of unhashable type map\[string]interface \{\}`},
{"b: *a\na: &a {c: 1}", `yaml: unknown anchor 'a' referenced`},
{"%TAG !%79! tag:yaml.org,2002:\n---\nv: !%79!int '1'", "yaml: did not find expected whitespace"},
{"a:\n 1:\nb\n 2:", ".*could not find expected ':'"},
Expand Down
Loading