lex yacc简单实例

来源:互联网 发布:数据库实施工程师 编辑:程序博客网 时间:2024/06/18 10:24

//文件Name.y

%{

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef char* string;

#define YYSTYPE string

%}

%token NAME EQ AGE

%%

file : record file

| record

;

record : NAME EQ AGE {

printf("%s is %s years old!!!\n",$1,$3);}

;

%%

 

int main()

{

yyparse();

return 0;

}

int yyerror(char *msg)

{

         printf("Error encountered:%s \n",msg);

}

 

//Name.l文件

%{

#include "y.tab.h"

#include <stdio.h>

#include <string.h>

extern char* yylval;

%}

char [A-Za-z]

num [0-9]

eq [=]

name {char}+

age {num}+

%%

{name} {yylval=strdup(yytext);

              return NAME;}

{eq} {return EQ;}

{age} {yylval=strdup(yytext);

           return AGE;}

%%

 

int yywrap()

{

          return 1;

}

 

//text.txt

test = 123

 

编译链接:

$yacc -d Name.y

$lex Name.l

$gcc y.tab.c lex.yy.c

$./a.out < text.txt

输出:test is 123 years old!!!

 

0 0