首页 > 其他 > 详细

Bison matching list

时间:2021-06-06 13:22:00      阅读:16      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/ajanuw/p/14854938.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!