- 論壇徽章:
- 0
|
本帖最后由 zhangd83 于 2010-03-08 09:32 編輯
我要做的解析器的功能是轉(zhuǎn)換(A語法轉(zhuǎn)換成B語法),
例如:\DCV UCJCL2,CHAR='&DATA2 ',LEN=8; -->(轉(zhuǎn)換成) \JP_DCV UCJCL2 '&DATA2 '
哪位大大會做請貼出例子,謝謝了。。。。。。。!
下面是我自己做的,執(zhí)行結(jié)果有問題:
flex:
/* recognize tokens for the calculator and print them out */
%option noyywrap
%{
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
# include "flex3_tab.h"
%}
IDENTIFIER [a-zA-Z_][A-Za-z0-9_]*
WHITESPACE [ \n\t]
%%
"\\DCV" {return JP_DCV;}
"CHAR" {return CHAR;}
"LEN" {return LEN;}
"," {yylval = " ";return *yytext;}
"=" {return *yytext;}
";" {return *yytext;}
[0-9]+ { yylval = yytext; return NUMBER; }
{IDENTIFIER} {yylval = yytext; return VAR;}
\'.*\' {yylval = yytext; return STR;}
[ \t\n] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%
----------------------------------------------------------------------------------------------------------------------
Bison:
/* simplest version of calculator */
/* 先掃描匹配,匹配到最高優(yōu)先級語法后解析語法,循環(huán)*/
%{
#include <malloc.h>
#include <stdlib.h>
%}
/* declare tokens */
%token VAR
%token NUMBER STR
%right JP_DCV
%token CHAR LEN
%token '='
%left ',' ';'
%%
program: /* nothing */
| program exp ';' { printf("| program exp ';' = %s \n", $2); }
| program ';' {printf("| program ';' \n");}
;
exp: factor
| JP_DCV factor {printf("\\JP_DCV\n");printf(" $$:%s, $1:%s, $2:%s, $3:e\n",$$,$1,$2);}
;
factor: term3
| factor term1 {printf("factor term1 : \n");
printf(" $$:%s, $1:%s, $2:%s\n", $$,$1,$2);}
;
term1: term2
| ',' term2 ',' term2 {printf(" ',' term2 ',' term2 : \n");
printf(" $$:%s, $1:%s, $2:%s, $3:%s, $4:%s\n", $$,$1,$2,$3,$4);}
;
term2: term3
| CHAR '=' term3 {printf("CHAR '=' term3: \n");$$ = $3;printf(" $$:%s, $1:%s, $2:%s, $3:%s\n", $$,$1,$2,$3);}
| LEN '=' term3 {printf("LEN '=' term3: \n");$$ = $3;
printf(" $$:%s, $1:%s, $2:%s, $3:%s\n", $$,$1,$2,$3);}
;
term3: VAR {printf("VAR: \n"); $$ = $1;printf(" $$:%s, $1:%s, $2:e, $3:e\n", $$,$1);}
| STR {printf("STR: \n");$$ = $1;printf(" $$:%s, $1:%s, $2:e, $3:e\n", $$,$1);}
| NUMBER {printf("NUMBER: \n");$$ = $1;
printf(" $$:%s, $1:%s, $2:e, $3:e\n", $$,$1);}
;
%%
main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, " error: %s\n", s);
}
執(zhí)行結(jié)果如下:
VAR:
$$:UCJCL2, $1:UCJCL2, $2:e, $3:e
STR:
$$:'&DATA2 ', $1:'&DATA2 ', $2:e, $3:e
CHAR '=' term3:
$$:'&DATA2 ', $1: , $2: , $3:'&DATA2 '
NUMBER:
$$:8, $1:8, $2:e, $3:e
LEN '=' term3:
$$:8, $1: , $2: , $3:8
',' term2 ',' term2 :
$$: , $1: , $2:'&DATA2 ',LEN=8, $3: , $4:8
factor term1 :
$$:UCJCL2,CHAR='&DATA2 ',LEN=8, $1:UCJCL2,CHAR='&DATA2 ',LEN=8, $2:
\JP_DCV
$$: (null), $1: (null), $2: (null), $3:e
| program exp ';' = (null)
好幾處遞歸返回的值都不是我指定的值,最后還出現(xiàn)了(null)值,實在不知道是怎么回事,哪位大大可以給出個正確答案,貼出個代碼,謝謝。。! |
|