Bison matching list
Posted Ajanuw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Bison matching list相关的知识,希望对你有一定的参考价值。
words demo
lexer.l:
%option noyywrap noline
%{
#include <iostream>
#include "parser.h"
#define YY_DECL yy::parser::symbol_type yylex()
#define yyterminate() return yy::parser::make_YYEOF()
#define _T(t) return yy::parser::make_##t()
#define _ST(t) return yy::parser::make_##t(std::string(yytext, yyleng))
%}
WORD (?i:[a-z]+)
%%
";" { _T(NL); }
{WORD} { _ST(WORD); }
[ \\t\\r\\n] { }
. { printf("char error.\\n"); }
%%
parser.y:
%require "3.7"
%skeleton "lalr1.cc"
%language "c++"
%defines "parser.h"
%define api.token.constructor
%define api.value.type variant
%code requires {
#include <memory>
#define M(o) std::move(o)
#define WORDS std::vector<std::string>
}
%code {
#include <iostream>
extern yy::parser::symbol_type yylex();
}
%token WORD "word" NL ";"
%type <std::string> WORD
%type <WORDS> words
%start main
%%
main: words ";" {
printf("words length %d\\n", $1.size());
for(const auto& i: $1) printf("%s\\n", i.data());
}
;
words: %empty { $$ = WORDS(); }
| WORD { $$ = WORDS(); $$.push_back($1); }
| words WORD { $$ = M($1); $$.push_back($2); }
;
%%
void yy::parser::error(const std::string& msg)
{
std::cout << msg << "\\n";
}
test 1
aaa ddd ss o i w ;
words length 6
aaa
ddd
ss
o
i
w
test 2
;
words length 0
words: %empty { $$ = WORDS(); }
等同于words: { $$ = WORDS(); }
以上是关于Bison matching list的主要内容,如果未能解决你的问题,请参考以下文章