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(); }