您的位置:首页 > 其它

程序中,调用Bison和Flex结合的小例子(语法分析中处理数据)

2013-05-17 16:57 423 查看
接着前面的 <程序中,调用Bison和Flex结合的小例子> 那一篇,再来整点新东西:

/article/4819321.html

我想,实际的工作中,绝对不会像逆波兰式计算器那样简单,直接就在语法分析器里完成计算。

常常需要构造一颗语法树,然后把它传出来!例如各种数据库系统处理SQL文就是这样子。

上程序:

[root@lex total]# cat lexer.l
%{

#include "y.tab.h"
#include <stdio.h>

#undef YY_INPUT
#define YY_INPUT(b,r,s) readInputForLexer(b,&r,s)

#ifndef YYSTYPE
#define YYSTYPE int
#endif
extern YYSTYPE yylval;

%}

DIGIT   [0-9]
%%

\+      { printf("got plus\n"); return FUNCTION_PLUS; }
\-      { printf("got minus\n"); return FUNCTION_MINUS; }
{DIGIT}* { printf("got number\n"); yylval = atoi(yytext); return NUMBER; }
\n      { printf("got end of line\n"); return EOL;}
%%

void yyerror(char* s) {
printf("error %s \n",s);
}

int yywrap() {
return -1;
}
[root@lex total]#


这里,通过 yylval,在词法分析器运行的时候,保持数据。

再看句法分析程序:

目前先不要求这么高,暂时看看如何在此处获得数据。

[root@lex total]# cat parser.y
%{
#include <stdio.h>
extern void yyerror(char* s);
extern int yylex();
extern int readInputForLexer(char* buffer,int *numBytesRead,int maxBytesToRead);
%}

%token FUNCTION_PLUS FUNCTION_MINUS NUMBER EOL

%%
exp:
NUMBER FUNCTION_PLUS NUMBER { fprintf(stderr,"---\n"); }
|
NUMBER FUNCTION_MINUS NUMBER {
fprintf(stderr,"left value is: %d\n",$1);
fprintf(stderr,"right value is: %d\n",$3);
}
;
%%
[root@lex total]#


此处,使用了 $1,$3等。

再看主程序:

[root@lex total]# cat myparser.c
#include <stdio.h>
#include <string.h>

int yyparse();
int readInputForLexer( char *buffer, int *numBytesRead, int maxBytesToRead );

static int globalReadOffset;
// Text to read:
static const char *globalInputText = "23 - 5";

int main() {
globalReadOffset = 0;
yyparse();
return 0;
}

int readInputForLexer( char *buffer, int *numBytesRead, int maxBytesToRead ) {
int numBytesToRead = maxBytesToRead;
int bytesRemaining = strlen(globalInputText)-globalReadOffset;
int i;
if ( numBytesToRead > bytesRemaining ) { numBytesToRead = bytesRemaining; }
for ( i = 0; i < numBytesToRead; i++ ) {
buffer[i] = globalInputText[globalReadOffset+i];
}
*numBytesRead = numBytesToRead;
globalReadOffset += numBytesToRead;
return 0;
}
[root@lex total]#


运行结果:

[root@lex total]# yacc -d parser.y
[root@lex total]# lex lexer.l
[root@lex total]# gcc -o myparser *.c
[root@lex total]# ./myparser
got number
got minus
got number
left value is: 23
right value is: 5
[root@lex total]#


下一篇,写一下如何构造一个结构保留语法分析的结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐