From 388d679c1dfa7c0cb5c9ee6cd0b8592c3c3d09ef Mon Sep 17 00:00:00 2001 From: Anton Sidorenko Date: Mon, 13 Feb 2023 17:10:39 +0300 Subject: [PATCH] Recommit [YAML IO] Check that mapping doesn't contain duplicating keys 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 | 5 +++++ llvm/unittests/Support/YAMLIOTest.cpp | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/llvm/lib/Support/YAMLTraits.cpp b/llvm/lib/Support/YAMLTraits.cpp index 4eb0b3afd563..0273059e7c27 100644 --- a/llvm/lib/Support/YAMLTraits.cpp +++ b/llvm/lib/Support/YAMLTraits.cpp @@ -435,6 +435,11 @@ std::unique_ptr 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; diff --git a/llvm/unittests/Support/YAMLIOTest.cpp b/llvm/unittests/Support/YAMLIOTest.cpp index f282d23dc500..40846f52b80b 100644 --- a/llvm/unittests/Support/YAMLIOTest.cpp +++ b/llvm/unittests/Support/YAMLIOTest.cpp @@ -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 // -- 2.34.1