zoukankan      html  css  js  c++  java
  • 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); }
    [ 	
    ] { }
    . { printf("char error.
    "); }
    
    %%
    
    

    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
    ", $1.size());
    	for(const auto& i: $1) printf("%s
    ", 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 << "
    ";
    }
    

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

  • 相关阅读:
    查看网站上保存的密码
    前端图片预览
    Amaze UI的一点总结
    简单实现图片验证码
    获取网页数据的例子
    谈谈网页中的ajax
    网页小技巧-360doc个人图书馆复制文字
    Js中的4个事件
    网页页面蒙版实现
    Spring+SprinMVC配置学习总结
  • 原文地址:https://www.cnblogs.com/ajanuw/p/14854938.html
Copyright © 2011-2022 走看看