jpsim / Yams

A Sweet and Swifty YAML parser.
https://jpsim.com/Yams
MIT License
1.11k stars 141 forks source link

Yams should fail if there are duplicate keys in a mapping #415

Open tejassharma96 opened 5 months ago

tejassharma96 commented 5 months ago

I recently encountered a bug when using Yams to read and write some yaml, and realized that the cause was a duplicate key in my yaml file that was being handled silently.

Per the yaml spec:

The content of a mapping node is an unordered set of key: value node pairs, with the restriction that each of the keys is unique. YAML places no further restrictions on the nodes. In particular, keys may be arbitrary nodes, the same node may be used as the value of several key: value pairs, and a mapping could even contain itself as a key or a value (directly or indirectly).

Basically, duplicate keys are not allowed. Yams should recognize when there is a duplicate key in a mapping and throw an error rather than having undefined behaviour (I think it just picks the version that is lowest in the file).

As an example:

import Foundation
import Yams

struct MyCodable: Codable {
    let thing: String
}

let yaml = """
key:
  thing: hello
key:
  thing: goodbye
"""

let data = Data(yaml.utf8)

let decoder = YAMLDecoder()
let test = try decoder.decode([String: MyCodable].self, from: data)
print(test)

prints ["key": __lldb_expr_7.MyCodable(thing: "goodbye")] - it doesn't throw any errors and selects the key that is lower in the text.