我正在用lex和yacc编写代码,并且试图为变量赋值,例如:
x = 5;
我的变量是[A-Za-z0-9]
,我的数字是整数[0-9]
或浮点数[0-9]+[.]?[0-9]*
我试图将其写入lex文件:
alpha [A-Za-z0-9]
然后
{alpha} {yylval.id = (char *) strdup(yytext); return ID;}
在yacc文件中,我写了:%union{char *id, int num}
并且我也将其定义为令牌,然后尝试编写ID '=' expr { $$=$3 }
但这没用。
lex代码:
%{
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "y.tab.h"
extern YYSTYPE yylval;
%}
%option noyywrap
delim [ \t]
white {delim}+
integer [0-9]
float [0-9]+[.]?[0-9]*
%%
{integer} {printf("got INTEGER token\n"); sscanf(yytext,"%lf",&yylval);
return INTEGER;}
{float} {printf("got FLOAT token\n"); sscanf(yytext,"%lf",&yylval); return FLOAT;}
"add" {printf("got ADDITION token\n"); return ADDITION;}
"sub" {printf("got SUBTRACTION token\n"); return SUBTRACTION;}
"mul" {printf("got MULTIPLICATION token\n"); return MULTIPLICATION;}
"div" {printf("got DIVISION token\n"); return DIVISION;}
"=" {printf("got ASSIGN token\n"); return ASSIGN;}
";" {printf("got SEMI token\n); return SEMI;}
"(" {return LPAREN;}
")" {return RPAREN;}
"\n" {return NEWLINE;}
{white} {}
%%
yacc代码:
%{
#include <stdio.h>
#define YYSTYPE double
#include <malloc.h>
#include <stdlib.h>
%}
%token NEWLINE INTEGER FLOAT ADDITION SUBTRACTION MULTIPLICATION DIVISION LPAREN RPAREN ASSIGN SEMI
%%
input:
| input line
;
line: NEWLINE
| expr NEWLINE { printf("\t%.10g\n",$1); }
;
expr: expr ADDITION term { $$ = $1 + $3; }
| expr SUBTRACTION term { $$ = $1 - $3; }
| expr MULTIPLICATION term { $$ = $1 * $3; }
| expr DIVISION term { $$ = $1 / $3; }
| term
;
;
term: LPAREN expr RPAREN { $$ = $2; }
| INTEGER
| FLOAT
;
%%
int yyerror(char *s)
{
printf("%s\n",s);
return(0);
}
int main()
{
yyparse();
exit(0);
}