Skip to content

Commit

Permalink
[YAMLTraits] Fix std::optional input on empty documents (#68947)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
akirchhoff-modular authored Oct 16, 2023
1 parent 528b5e6 commit 4bf10f3
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 0 deletions.
2 changes: 2 additions & 0 deletions llvm/lib/Support/YAMLTraits.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
if (!CurrentNode) {
if (Required)
EC = make_error_code(errc::invalid_argument);
else
UseDefault = true;
return false;
}

Expand Down
3 changes: 3 additions & 0 deletions llvm/unittests/Support/YAMLIOTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2392,6 +2392,7 @@ TEST(YAMLIO, TestMalformedMapFailsGracefully) {

struct OptionalTest {
std::vector<int> Numbers;
std::optional<int> MaybeNumber;
};

struct OptionalTestSeq {
Expand All @@ -2405,6 +2406,7 @@ namespace yaml {
struct MappingTraits<OptionalTest> {
static void mapping(IO& IO, OptionalTest &OT) {
IO.mapOptional("Numbers", OT.Numbers);
IO.mapOptional("MaybeNumber", OT.MaybeNumber);
}
};

Expand Down Expand Up @@ -2466,6 +2468,7 @@ TEST(YAMLIO, TestEmptyStringSucceedsForMapWithOptionalFields) {
Input yin("");
yin >> doc;
EXPECT_FALSE(yin.error());
EXPECT_FALSE(doc.MaybeNumber.has_value());
}

TEST(YAMLIO, TestEmptyStringSucceedsForSequence) {
Expand Down

0 comments on commit 4bf10f3

Please sign in to comment.