foonathan / lexy

C++ parsing DSL
https://lexy.foonathan.net
Boost Software License 1.0
991 stars 66 forks source link

Get any rule's value as a string #198

Closed 0x0015 closed 4 months ago

0x0015 commented 4 months ago

Hello,

I was wondering if there is a way that for any rule that has been matched, to return the value of whatever string was matched, rather than what other value type that should be returned.

Two examples (one over simplified, and one more actual use-case-y):

A boolean parser (yes this is not generally how you would actually want to do this, and rather have a separate parser for true and false)

struct boolean{
    static constexpr auto rule = LEXY_LIT("true") | LEXY_LIT("false");
    static constexpr auto value = lexy::callback<bool>([](const auto& lx){
        std::string s(lx.begin(), lx.end());
        return s == "true";
    });
    //value = lexy::as_string<std::string>; //also doesn't work
    //if it did, I could (I think) do:  value = lexy::as_string<std::string> >> lexy::callback(.......)
};

and a more realistic example of trying to parse a decimal

struct decimal{
    static constexpr auto rule = dsl::sign + dsl::digits<> + dsl::period + dsl::digits<>;
    static constexpr auto value = lexy::callback<float>([](const auto& lx){
        std::string s(lx.begin(), lx.end());
        return std::stof(s);
    });

};