I can get a basic parse to run with Boost.Spirit but have trouble getting the message tags (IRCv3) to fully parse. I want the tags to at least parse individually into a vector<>
but would love to have them parse into a map<>
.
#include <string>
#include <optional>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
/// Flags used for IRC protocol messages
enum MSG_FLAGS : uint32_t {
/// Last arg is a trailing parameter
MSG_TRAILING_ARG = (1 << 0),
/// When the message is being wrapped due to excess params, repeat the first arg;
/// e.g., for ISUPPORT this will consistently place the client's name (1st arg) in front of each ISUPPORT message.
MSG_REPEAT_1ST = (1 << 1),
/// Indicates message should never include a prefix; e.g, PING and ERROR for local clients
MSG_NO_PREFIX = (1 << 2),
};
/// Structure describing an IRC protocol message
struct message {
/// IRCv3 tags associated with this message
std::vector<std::string> tags;
/// Source prefix - usually blank from clients
std::string prefix;
/// Command that was received
std::string command;
/// Command arguments
std::vector<std::string> args;
/// Flags for internal processing (not received via IRC)
uint32_t flags;
};
BOOST_FUSION_ADAPT_STRUCT(message,
(std::vector<std::string>, tags)
(std::string, prefix),
(std::string, command),
(std::vector<std::string>, args));
std::optional<message> tokenize(std::string const& data)
{
namespace x3 = boost::spirit::x3;
namespace ascii = boost::spirit::x3::ascii;
namespace phx = boost::phoenix;
using x3::rule;
using x3::int_;
using x3::lit;
using x3::double_;
using x3::lexeme;
using x3::omit;
using ascii::char_;
message msg;
msg.flags = 0;
// parser rules
static auto on_trailing_arg = [&](auto& ctx) { msg.flags |= MSG_TRAILING_ARG; };
static auto const token = lexeme[+(char_ - ' ' - ':')];
static auto const prefix = omit[':'] >> token;
static auto const trail = (omit[':'] >> lexeme[*char_])[on_trailing_arg];
static auto const tags = omit['@'] >> token % ';';
static auto const line = -tags
>> -prefix
>> token
>> ((+token > -trail) | trail);
// run the parse
auto iter = data.begin();
auto const end = data.end();
bool r = x3::phrase_parse(iter, end, line, ascii::space, msg);
if (r && iter == end) {
return msg;
} else {
return std::nullopt;
}
}
Given the following IRC message:
"@aaa=bbb;ccc;example.com/ddd=eee :nick!ident@host.com PRIVMSG me :Hello"
I expect a message
object to be constructed as:
tags = ["aaa=bbb", "ccc", "example.com/ddd=eee"]
prefix = "nick!ident@host.com"
command = "PRIVMSG"
args = ["me", "Hello"]
Currently the tags
are constructed as a single value (aaa=bbb;ccc;example.com/ddd=eee
).
What I'd really like to do is generate a map<>
for the tags:
tags = [["aaa": "bbb"], "ccc", ["example.com/ddd": "eee"]]
prefix = "nick!ident@host.com"
command = "PRIVMSG"
args = ["me", "Hello"]