Skip to content

Commit 4bf10f3

Browse files
author
akirchhoff-modular
authored
[YAMLTraits] Fix std::optional input on empty documents (#68947)
When the input document is non-empty, `mapOptional` works as expected, setting `std::optional` to `std::nullopt` when the field is not present. When the input document is empty, we hit a special case inside of `Input::preflightKey` that results in `UseDefault = false`, which results in the `std::optional` erroneously being set to a non-nullopt value. `preflightKey` is changed to set `UseDefault = true` in this case to make the behavior consistent between empty and non-empty documents.
1 parent 528b5e6 commit 4bf10f3

File tree

2 files changed

+5
-0
lines changed

2 files changed

+5
-0
lines changed

llvm/lib/Support/YAMLTraits.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,8 @@ bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
156156
if (!CurrentNode) {
157157
if (Required)
158158
EC = make_error_code(errc::invalid_argument);
159+
else
160+
UseDefault = true;
159161
return false;
160162
}
161163

llvm/unittests/Support/YAMLIOTest.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2392,6 +2392,7 @@ TEST(YAMLIO, TestMalformedMapFailsGracefully) {
23922392

23932393
struct OptionalTest {
23942394
std::vector<int> Numbers;
2395+
std::optional<int> MaybeNumber;
23952396
};
23962397

23972398
struct OptionalTestSeq {
@@ -2405,6 +2406,7 @@ namespace yaml {
24052406
struct MappingTraits<OptionalTest> {
24062407
static void mapping(IO& IO, OptionalTest &OT) {
24072408
IO.mapOptional("Numbers", OT.Numbers);
2409+
IO.mapOptional("MaybeNumber", OT.MaybeNumber);
24082410
}
24092411
};
24102412

@@ -2466,6 +2468,7 @@ TEST(YAMLIO, TestEmptyStringSucceedsForMapWithOptionalFields) {
24662468
Input yin("");
24672469
yin >> doc;
24682470
EXPECT_FALSE(yin.error());
2471+
EXPECT_FALSE(doc.MaybeNumber.has_value());
24692472
}
24702473

24712474
TEST(YAMLIO, TestEmptyStringSucceedsForSequence) {

0 commit comments

Comments
 (0)