C++ 如何将PEGTL解析器与单独的lexer一起使用?
我已经有了一个lexer,希望使用我自己的令牌类型作为PEGTL解析器的输入。例如,下面是sum示例的一个修改版本,其内容来自stdin:C++ 如何将PEGTL解析器与单独的lexer一起使用?,c++,C++,我已经有了一个lexer,希望使用我自己的令牌类型作为PEGTL解析器的输入。例如,下面是sum示例的一个修改版本,其内容来自stdin: #include <cstdlib> #include <iostream> #include <sstream> #include <string> #include <tao/pegtl.hpp> using namespace TAO_PEGTL_NAMESPACE; namespace
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <tao/pegtl.hpp>
using namespace TAO_PEGTL_NAMESPACE;
namespace sum
{
struct num : seq< plus< digit > > {};
struct int_list
: list< num, one< ',' > >
{};
struct grammar
: seq< int_list, eof >
{};
template< typename Rule >
struct action
{};
template<>
struct action< num >
{
template< typename ActionInput >
static void apply( const ActionInput& in, int& sum )
{
sum += atoi(in.string().c_str());
}
};
} // namespace sum
struct Token {
typedef enum { COMMA, NUM, END_OF_FILE } Type;
Token(Type type, int num = 0) : type(type), num(num) {}
Type type;
int num;
};
int main()
{
// this works, can be called like this:
// echo -n "1,2,3" | ./a.out
int d = 0.0;
if( parse< sum::grammar, sum::action >( istream_input(std::cin, 16, "stdin"), d )) {
std::cout << "parsing OK; sum = " << d << std::endl;
}
else {
std::cout << "parsing failed" << std::endl;
}
// how can I do this when I have already the tokens in a vector?
std::vector<Token> tokens;
tokens.push_back(Token(Token::Type::NUM, 1));
tokens.push_back(Token(Token::Type::COMMA));
tokens.push_back(Token(Token::Type::NUM, 2));
tokens.push_back(Token(Token::Type::COMMA));
tokens.push_back(Token(Token::Type::NUM, 3));
tokens.push_back(Token(Token::Type::END_OF_FILE));
}
#包括
#包括
#包括
#包括
#包括
使用名称空间TAO_PEGTL_名称空间;
名称空间和
{
struct num:seq>{};
结构整数列表
:list>
{};
结构语法
:seq
{};
模板
结构动作
{};
模板
结构操作
{
模板
静态无效应用(常量ActionInput&in、int&sum)
{
sum+=atoi(in.string().c_str());
}
};
}//名称空间和
结构令牌{
typedef枚举{COMMA,NUM,END_OF_FILE}类型;
令牌(Type-Type,int-num=0):Type(Type),num(num){
类型;
int-num;
};
int main()
{
//这是可行的,可以这样称呼:
//回声-n“1,2,3”|/a.out
int d=0.0;
if(解析(istream_输入(std::cin,16,“stdin”),d)){
标准::cout