dsl::integer and negative numbers #87
Answered
by
facontidavide
facontidavide
asked this question in
Q&A
-
Hi, I notice that I am not sure how to address this. This is my sample code: #include <lexy/action/parse.hpp>
#include <lexy/callback.hpp>
#include <lexy/dsl.hpp>
#include <lexy_ext/report_error.hpp>
#include <lexy/input/string_input.hpp>
namespace dsl = lexy::dsl;
struct production
{
static constexpr auto whitespace = dsl::ascii::space;
static constexpr auto rule =
[] {
auto integer = dsl::integer<int64_t>;
auto hex_integer = LEXY_LIT("0x") >> dsl::integer<int, dsl::hex>;
return (hex_integer | integer) + dsl::eof;
}();
static constexpr auto value = lexy::forward<int>;
};
int main()
{
const char* strings[] = {"7", "0x78", "-7"};
for( const auto& str: strings )
{
auto input = lexy::zstring_input(str);
auto result = lexy::parse<production>(input, lexy_ext::report_error);
if (result.has_value())
{
std::printf("%d\n", result.value());
}
}
return 0;
} Output:
|
Beta Was this translation helpful? Give feedback.
Answered by
facontidavide
Sep 4, 2022
Replies: 1 comment 1 reply
-
I found the solution looking at the json example, but I am not quite sure why the struct production
{
struct integer
{
static constexpr auto rule = dsl::sign + dsl::integer<int64_t>;
static constexpr auto value = lexy::as_integer<int64_t>;
};
static constexpr auto rule = [] {
auto hex_integer = LEXY_LIT("0x") >> dsl::integer<int64_t, dsl::hex>;
auto regular_integer = dsl::peek(dsl::lit_c<'-'> / dsl::lit_c<'+'> / dsl::digit<>) >> dsl::p<integer>;
return ( hex_integer | regular_integer ) + dsl::eof;
}();
static constexpr auto value = lexy::forward<int64_t>;
}; |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
foonathan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found the solution looking at the json example, but I am not quite sure why the
dsl::peek
is required.