Reputation: 63154
I'm writing a Qi parser to parse IRC messages, transcribing RFC 2812. Among the grammar is a completely mundate alternative :
auto const hostname = shortname >> *('.' >> shortname);
auto const nickUserHost = nickname >> -(-('!' >> user) >> '@' >> host);
auto const prefix = hostname | nickUserHost;
I'm baffled to see that my test string ("[email protected]"
) matches nickUserHost
, but not prefix
.
The only remarkable thing that I see is that nickUserHost
's host
is itself defined in terms of hostname
, but I'm not sure how it would affect the parsing in any way.
Upvotes: 2
Views: 188
Reputation: 393789
By appending >> eoi
you explicitly make the parse failed if it didn't reach the end of the input.
#include <string>
#include <iostream>
#include <iomanip>
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
template <typename Expr>
void test(std::string name, Expr const& expr) {
std::string const test = "[email protected]";
auto f = begin(test);
bool ok = qi::parse(f, end(test), expr);
std::cout << name << ": " << ok << "\n";
if (f != end(test))
std::cout << " -- remaining input: '" << std::string(f, end(test)) << "'\n";
}
int main() {
auto const hexdigit = qi::char_("0123456789ABCDEF");
auto const special = qi::char_("\x5b-\x60\x7b-\x7d");
auto const oneToThreeDigits = qi::repeat(1, 3)[qi::digit];
auto const ip4addr = oneToThreeDigits >> '.' >> oneToThreeDigits >> '.' >> oneToThreeDigits >> '.' >> oneToThreeDigits;
auto const ip6addr = +(hexdigit >> qi::repeat(7)[':' >> +hexdigit]) | ("0:0:0:0:0:" >> (qi::lit('0') | "FFFF") >> ':' >> ip4addr);
auto const hostaddr = ip4addr | ip6addr;
auto const nickname = (qi::alpha | special) >> qi::repeat(0, 8)[qi::alnum | special | '-'];
auto const user = +(~qi::char_("\x0d\x0a\x20\x40"));
auto const shortname = qi::alnum >> *(qi::alnum | '-');
auto const hostname = shortname >> *('.' >> shortname);
auto const host = hostname | hostaddr;
auto const nickUserHost = nickname >> -(-('!' >> user) >> '@' >> host);
auto const prefix = hostname | nickUserHost; // The problematic alternative
std::cout << std::boolalpha;
test("hostname", hostname);
test("nickUserHost", nickUserHost);
test("prefix", prefix);
}
Prints
hostname: true
-- remaining input: '[email protected]'
nickUserHost: true
prefix: true
-- remaining input: '[email protected]'
Upvotes: 2