Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions include/iris/x4/operator/difference.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,27 +33,28 @@ struct difference : binary_parser<Left, Right, difference<Left, Right>>
[[nodiscard]] constexpr bool
parse(It& first, Se const& last, Context const& ctx, Attr& attr) const
{
// Try Right first
It start = first;
// Try `Right`
It const orig_first = first;
if (this->right.parse(first, last, ctx, unused)) {
// Right succeeds, we fail.
first = start;
// `Right` succeeds, we fail.
first = orig_first;
return false;
}

if constexpr (has_context_v<Context, contexts::expectation_failure>) {
// In case of `Left - expect[r]`,
// if Right yielded expectation error,
// the whole difference expression (*this) should also yield error.
// In other words, when the THROW macro was 1 (i.e. traditional behavior),
// Right should already have thrown an exception.
if (x4::has_expectation_failure(ctx)) {
// don't rollback iterator (mimicking exception-like behavior)
return false;
}
}
// `Right` failed, now try `Left` ------------------

// Right fails, now try Left
// Rollback iterator
// This rolls back the iterator position, including the amount skipped by
// `Right`'s skipper (`x4::skip_over(...)`).
first = orig_first;
return this->left.parse(first, last, ctx, attr);
}
};
Expand Down
20 changes: 20 additions & 0 deletions test/x4/difference.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@
#include <iris/x4/operator/difference.hpp>
#include <iris/x4/operator/sequence.hpp>
#include <iris/x4/operator/kleene.hpp>
#include <iris/x4/operator/plus.hpp>
#include <iris/x4/directive/skip.hpp>

#include <string>

TEST_CASE("difference")
{
using x4::standard::char_;
using x4::standard::blank;
using x4::standard::space;
using x4::lit;
using x4::skip;
using x4::_attr;

IRIS_X4_ASSERT_CONSTEXPR_CTORS(char_ - 'a');
Expand Down Expand Up @@ -66,4 +70,20 @@ TEST_CASE("difference")
));
CHECK(s == "abcdefghijk");
}

{
// Rollback on failed parse
std::string s;
REQUIRE(parse(
"foo die ,",
+(
// RHS fails, so the difference parser should rollback iterator
// Note that RHS has a skipper, so the buffer skipped by `skip_over`
// should also be rolled back
char_ - skip(blank)[',']
) >> skip(blank)[','],
s
));
CHECK(s == "foo die"); // wrong implementation yields "foodie"
}
}