Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How does one prevent X3 symbol parsers from matching partial tokens? In the example below, I want to match "foo", but not "foobar". I tried throwing the symbol parser in a lexeme directive as one would for an identifier, but then nothing matches.

Thanks for any insights!

#include <string>
#include <iostream>
#include <iomanip>

#include <boost/spirit/home/x3.hpp>


int main() {

  boost::spirit::x3::symbols<int> sym;
  sym.add("foo", 1);

  for (std::string const input : {
      "foo",
      "foobar",
      "barfoo"
        })
    {
      using namespace boost::spirit::x3;

      std::cout << "
Parsing " << std::left << std::setw(20) << ("'" + input + "':");

      int v;
      auto iter = input.begin();
      auto end  = input.end();
      bool ok;
      {
        // what's right rule??

        // this matches nothing
        // auto r = lexeme[sym - alnum];

        // this matchs prefix strings
        auto r = sym;

        ok = phrase_parse(iter, end, r, space, v);
      }

      if (ok) {
        std::cout << v << " Remaining: " << std::string(iter, end);
      } else {
        std::cout << "Parse failed";
      }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
260 views
Welcome To Ask or Share your Answers For Others

1 Answer

Qi used to have distinct in their repository.

X3 doesn't.

The thing that solves it for the case you showed is a simple lookahead assertion:

auto r = lexeme [ sym >> !alnum ];

You could make a distinct helper easily too, e.g.:

auto kw = [](auto p) { return lexeme [ p >> !(alnum | '_') ]; };

Now you can just parse kw(sym).

Live On Coliru

#include <iostream>
#include <boost/spirit/home/x3.hpp>

int main() {

    boost::spirit::x3::symbols<int> sym;
    sym.add("foo", 1);

    for (std::string const input : { "foo", "foobar", "barfoo" }) {

        std::cout << "
Parsing '" << input << "': ";

        auto iter      = input.begin();
        auto const end = input.end();

        int v = -1;
        bool ok;
        {
            using namespace boost::spirit::x3;
            auto kw = [](auto p) { return lexeme [ p >> !(alnum | '_') ]; };

            ok = phrase_parse(iter, end, kw(sym), space, v);
        }

        if (ok) {
            std::cout << v << " Remaining: '" << std::string(iter, end) << "'
";
        } else {
            std::cout << "Parse failed";
        }
    }
}

Prints

Parsing 'foo': 1 Remaining: ''

Parsing 'foobar': Parse failed
Parsing 'barfoo': Parse failed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...