[YAML IO] Check that mapping doesn't contain duplicating keys
authorAnton Sidorenko <anton.sidorenko@syntacore.com>
Mon, 16 Jan 2023 15:03:12 +0000 (18:03 +0300)
committerAnton Sidorenko <anton.sidorenko@syntacore.com>
Thu, 9 Feb 2023 11:45:51 +0000 (14:45 +0300)
According to YAML specification keys must be unique for a mapping node:
"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".

Differential Revision: https://reviews.llvm.org/D140474

llvm/lib/Support/YAMLTraits.cpp
llvm/unittests/Support/YAMLIOTest.cpp

index 4eb0b3a..0273059 100644 (file)
@@ -435,6 +435,11 @@ std::unique_ptr<Input::HNode> Input::createHNodes(Node *N) {
         // Copy string to permanent storage
         KeyStr = StringStorage.str().copy(StringAllocator);
       }
+      if (mapHNode->Mapping.count(KeyStr))
+        // From 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."
+        setError(KeyNode, Twine("duplicated mapping key '") + KeyStr + "'");
       auto ValueHNode = createHNodes(Value);
       if (EC)
         break;
index 2ed79ca..fa427f2 100644 (file)
@@ -105,6 +105,16 @@ TEST(YAMLIO, TestMalformedMapRead) {
   EXPECT_TRUE(!!yin.error());
 }
 
+TEST(YAMLIO, TestMapDuplicatedKeysRead) {
+  auto testDiagnostic = [](const llvm::SMDiagnostic &Error, void *) {
+    EXPECT_EQ(Error.getMessage(), "duplicated mapping key 'foo'");
+  };
+  FooBar doc;
+  Input yin("{foo: 3, bar: 5, foo: 4}", nullptr, testDiagnostic);
+  yin >> doc;
+  EXPECT_TRUE(!!yin.error());
+}
+
 //
 // Test the reading of a yaml sequence of mappings
 //