Recommit [YAML IO] Check that mapping doesn't contain duplicating keys
authorAnton Sidorenko <anton.sidorenko@syntacore.com>
Mon, 13 Feb 2023 14:10:39 +0000 (17:10 +0300)
committerAnton Sidorenko <anton.sidorenko@syntacore.com>
Mon, 13 Feb 2023 14:45:07 +0000 (17:45 +0300)
The revert reason is fixed in D143727 (test changes).

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 4eb0b3afd563068b0310eb2731d5563b75e2dd26..0273059e7c27ffffa9ceba0f1aba9a20cb3e0486 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 f282d23dc500b763a79faafe49641829308a2913..40846f52b80b8f33124f7ce412312169c6286db5 100644 (file)
@@ -114,6 +114,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
 //