script/parsing: Allow Const to not skip the found constant

When parsing a descriptor, it is useful to be able to check whether a
string begins with a substring without consuming that substring as
another function such as Func() will be used later which requires that
substring to be present at the beginning.

Specifically, for MuSig2, this modified Const will be used to determine
whether a an expression begins with "musig(" before a subsequent
Func("musig", ...) is used.
This commit is contained in:
Ava Chow
2024-01-15 17:08:47 -05:00
parent 5fe4c66462
commit 8811312571
3 changed files with 19 additions and 5 deletions

View File

@@ -12,10 +12,10 @@
namespace script {
bool Const(const std::string& str, std::span<const char>& sp)
bool Const(const std::string& str, std::span<const char>& sp, bool skip)
{
if ((size_t)sp.size() >= str.size() && std::equal(str.begin(), str.end(), sp.begin())) {
sp = sp.subspan(str.size());
if (skip) sp = sp.subspan(str.size());
return true;
}
return false;

View File

@@ -13,10 +13,10 @@ namespace script {
/** Parse a constant.
*
* If sp's initial part matches str, sp is updated to skip that part, and true is returned.
* If sp's initial part matches str, sp is optionally updated to skip that part, and true is returned.
* Otherwise sp is unmodified and false is returned.
*/
bool Const(const std::string& str, std::span<const char>& sp);
bool Const(const std::string& str, std::span<const char>& sp, bool skip = true);
/** Parse a function call.
*

View File

@@ -1137,13 +1137,24 @@ BOOST_AUTO_TEST_CASE(test_script_parsing)
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "MilkToastHoney");
success = Const("Milk", sp, /*skip=*/false);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "MilkToastHoney");
success = Const("Milk", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "ToastHoney");
success = Const("Bread", sp, /*skip=*/false);
BOOST_CHECK(!success);
success = Const("Bread", sp);
BOOST_CHECK(!success);
success = Const("Toast", sp, /*skip=*/false);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "ToastHoney");
success = Const("Toast", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "Honey");
@@ -1151,10 +1162,13 @@ BOOST_AUTO_TEST_CASE(test_script_parsing)
success = Const("Honeybadger", sp);
BOOST_CHECK(!success);
success = Const("Honey", sp, /*skip=*/false);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "Honey");
success = Const("Honey", sp);
BOOST_CHECK(success);
BOOST_CHECK_EQUAL(SpanToStr(sp), "");
// Func(...): parse a function call, update span to argument if successful
input = "Foo(Bar(xy,z()))";
sp = input;