yacc 入门 demo

看了 mysql parse 着手看了看 yyparse

include.h

#ifndef MAIN_HPP
#define MAIN_HPP

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;


#define YYSTYPE string

#endif


lex.l

%{

#include "include.h"
#include "yacc.tab.h"


extern "C"
{   
    int yywrap(void);
    int yylex(void);
}
%}

%%
                
"abc"   {    

            yylval = yytext;

            return ABC;
        }

"123" {

        yylval = yytext;

        return A123;


}

%%

int yywrap(void)
{
    puts("-----the file is end");
    return 1;
}
yacc.y


%{

#include "include.h"

extern "C"
{    
    void yyerror(const char *s);
    extern int yylex(void);
}

%}

%token ABC
%token A123

//%type tokens


%%

file:  
    tokens  
    {
        cout<<"all abc:"<<$1<<endl;
    };
tokens:
    {
        cout<< "3";
    }
    |  tokens ABC A123
    {
        $$ = $2;
        cout<<"----->"<<$2<<"---->"<<$3<<endl;
    }
    ;

%%

void yyerror(const char *s)
{
    cerr<<"err:"<<s<<endl;
}

int main()
{
    const char* sFile="file.txt";
    FILE* fp=fopen(sFile, "r");
    if(fp==NULL)
    {
        printf("cannot open %s\n", sFile);
        return -1;
    }
    extern FILE* yyin;   
    yyin=fp;
    printf("-----begin parsing %s\n", sFile);
    yyparse();
    puts("-----end parsing");

    fclose(fp);

    return 0;
}

file.txt</>

abc 123

Makefile


LEX=flex
YACC=bison
CC=g++
OBJECT=main

$(OBJECT):clean lex.yy.o  yacc.tab.o
	$(CC) lex.yy.o yacc.tab.o -o $(OBJECT)
	@./$(OBJECT) #编译后立刻运行

lex.yy.o: lex.yy.c  yacc.tab.h
	$(CC) -c lex.yy.c

yacc.tab.o: yacc.tab.c 
	$(CC) -c yacc.tab.c

yacc.tab.c  yacc.tab.h:
	$(YACC) -d yacc.y

lex.yy.c: #lex.l
	$(LEX) lex.l

clean:
	@rm -f $(OBJECT)  *.o
	@rm -f yacc.tab.c lex.yy.c yacc.tab.h




猜你喜欢

转载自blog.csdn.net/qq948993066/article/details/77942841
今日推荐