Skip to content

Commit

Permalink
Fail on duplicate keys in a mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
tejassharma96 committed May 6, 2024
1 parent 9234124 commit ef128c0
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
9 changes: 9 additions & 0 deletions Sources/Yams/Parser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,15 @@ private extension Parser {
pairs.append((key, value))
event = try parse()
}
let keys = pairs.map { $0.0 }
let duplicateKeys = Dictionary(grouping: keys, by: {$0}).filter { $1.count > 1 }.keys
if let duplicatedKey = duplicateKeys.first {
throw YamlError.parser(
context: YamlError.Context(text: "expected all keys in mapping to be unique",
mark: Mark(line: 1, column: 1)),
problem: "but found multiple instances of: \(duplicateKeys.compactMap { $0.string })", duplicatedKey.mark!,
yaml: yaml)
}
let node = Node.mapping(.init(pairs, tag(firstEvent.mappingTag), event.mappingStyle, firstEvent.startMark))
if let anchor = firstEvent.mappingAnchor {
anchors[anchor] = node
Expand Down
16 changes: 16 additions & 0 deletions Tests/YamsTests/YamlErrorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,22 @@ class YamlErrorTests: XCTestCase {
)
}
}

func testDuplicateKeysCannotBeParsed() throws {
let yamlString = """
key: value
key: different_value
"""
XCTAssertThrowsError(try Parser(yaml: yamlString).singleRoot()) { error in
XCTAssertTrue(error is YamlError)
XCTAssertEqual("\(error)", """
1:5: error: parser: expected all keys in mapping to be unique in line 1, column 1
but found multiple instances of: ["key"]:
key: value
^
""")
}
}
}

extension YamlErrorTests {
Expand Down

0 comments on commit ef128c0

Please sign in to comment.