I am studying on the yacc & lex to help me understand the parser of the postgres, but now I'm facing some trouble.
%{
#include <stdio.h>
int yylex();
int yyerror(char *s);
typedef char* string;
#define YYSTPYE string
%}
%token NUMBER
%token ADD SUB MUL DIV ABS
%token NEWLINE
%%
calclist: /* Empty rule */
| calclist expression NEWLINE { printf (" = %lf", $2); }
;
expression: factor { $$ = $1; }
| expression ADD factor { $$ = $1 + $3; }
| expression SUB factor { $$ = $1 - $3; }
;
factor: term { $$ = $1; }
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
term: NUMBER { $$ = $1; }
| ABS term { $$ = $2 > 0 ? $2 : - $2; }
%%
int main(int argc, char *argv[])
{
yyparse();
}
int yyerror(char *s)
{
puts(s);
}
/*
1.3.l
Calc Program
Jing Zhang
*/
%option noyywrap
%option noinput
%{
#include <stdlib.h>
enum yyTokenType
{
NUMBER = 258,
ADD,
SUB,
MUL,
DIV,
ABS,
NEWLINE
};
double yylval;
%}
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
[0-9]+ { yylval = atof (yytext); return NUMBER;}
\n { return NEWLINE; }
[ \t] { ; }
. { ; }
%%
yacc -d 1-3.y
lex 1-3.l
gcc 1-3.tab.c lex.yy.c
/usr/bin/ld: /tmp/ccYqqE5N.o:(.bss+0x28): multiple definition of `yylval'; /tmp/ccdJ12gy.o:(.bss+0x4): first defined here
Jing Zhang.