Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] dsl::integer and negative numbers #86

Closed
facontidavide opened this issue Sep 4, 2022 · 1 comment
Closed

[Question] dsl::integer and negative numbers #86

facontidavide opened this issue Sep 4, 2022 · 1 comment

Comments

@facontidavide
Copy link

facontidavide commented Sep 4, 2022

Hi,

I notice that dsl::integer is not parsing negative numbers. Is that the desired behavior?

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:

7
120
error: while parsing Integer
     |
   1 | -7
     | ^ exhausted choice
@facontidavide
Copy link
Author

I found the solution looking at the json example, but I am not quite sure why the dsl::peek is required.

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>;
};

Repository owner locked and limited conversation to collaborators Sep 4, 2022
@foonathan foonathan converted this issue into discussion #87 Sep 4, 2022

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant