I'm used to compiling (1) a lex definition file and (2) a yacc definition file as follows:
1. lex mylexfile.l
2. yacc -d -l myfile.y
3. gcc y.tab.c lex.yy.c -ly -ll
4. ./a.out
I found this example, and I'm trying to understand it. What is this BISON business? Is there a way to separate them into one lex (mylexfile.l) and one yacc file (myfile.y)? Any help appreciated.
--------------------------
----------
---
/* Infix notation calculator--calc */
%{
#define YYSTYPE double
#define alloca malloc
#include <math.h>
%}
/* BISON Declarations */
%token NUM
%left '-' '+'
%left '*' '/'
%left NEG /* negation--unary minus */
%right '^' /* exponentiation */
/* Grammar follows */
%%
input: /* empty string */
| input line
;
line: '\n'
| exp '\n' { printf("\t%.10g\n", $1); }
;
exp: NUM { $$ = $1; }
| exp '+' exp { $$ = $1 + $3; }
| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp { $$ = $1 / $3; }
| '-' exp %prec NEG { $$ = -$2; }
| exp '^' exp { $$ = pow ($1, $3); }
| '(' exp ')' { $$ = $2; }
;
%%
/* Lexical analyzer returns a double floating point
number on the stack and the token NUM, or the ASCII
character read if not a number. Skips all blanks
and tabs, returns 0 for EOF. */
#include <ctype.h>
yylex ()
{
int c;
/* skip white space */
while ((c = getchar ()) == ' ' || c == '\t')
;
/* process numbers */
if (c == '.' || isdigit (c))
{
ungetc (c, stdin);
scanf ("%lf", &yylval);
return NUM;
}
/* return end-of-file */
if (c == EOF)
return 0;
/* return single chars */
return c;
}
main ()
{
yyparse ();
}
#include <stdio.h>
yyerror (s) /* Called by yyparse on error */
char *s;
{
printf ("%s\n", s);
}
Start Free Trial