100 likes | 248 Views
SET 5a. Standard parts of the input files for Lex and Yacc. The parts in red in the slides following are the standard parts which should be included in every use of Lex combined with Yacc. Generating the Parser Using YACC. The structure of a grammar to be used with
E N D
SET 5a Standard parts of the input files for Lex and Yacc
The parts in red in the slides following are the standard parts which should be included in every use of Lex combined with Yacc.
Generating the Parser Using YACC • The structure of a grammar to be used with • YACC for generating a parser is similar to • that of LEX. There is a definition section, • a rules (productions) section, and a code • section.
Example of an Input Grammar for YACC %{ /* ARITH.text Yacc input for a arithmetic expression evaluator The text in red will occur as shown in every Yacc input file */ #include <stdio.h> /* for printf */ #define YYSTYPE int int yyparse(void); int yylex(void); void yyerror(char *mes); %} %token number %%
Example of an Input Grammar for YACC (Cont.1) program : expression {printf("answer = %d\n", $1);} ; expression : expression '+' term {$$ = $1 + $3;} | term ; term : term '*' number {$$ = $1 * $3;} | number ; %%
Example of an Input Grammar for YACC (Cont.2) void main() { printf("Enter an arithmetic expression\n"); yyparse();} /* prints an error message */ void yyerror(char *mes) {printf("%s\n", mes);} NOTE. It is never necessary to employ $$ = $1 since that is the default.
The LEX scanner definition file for the arithmetic expressions grammar %{ /* lexarith.text lex input for a arithmetic expression evaluator */ #include “y.tab.h" /* may be called something else in non-Unix systems*/ #include <stdlib.h> /* for atoi */ #define YYSTYPE int extern YYSTYPE yylval; %} digit [0-9] %% {digit}+ {yylval = atoi(yytext); return number; } (" "|\t)* ; \n {return(0);} /* recognize Enter key as EOF */ . {return yytext[0];} %% int yywrap() {}
To produce a compiler from the above files lexarith.text and arith.text, employ the following (in Cygwin): flex lexarith.text yacc –d arith.text gcc y.tab.c lex.yy.c If the source to be compiled is source.text, then employ ./a < source.text
The use of the –d option in yacc –d ...creates y.tab.h. In Cygwin, this file contains default definitions that should be erased. Erase from the line starting with #if ! defined to the end. Unless you change the set of terminals in your grammar, omit the –d option is subsequent uses of Yacc, and so avoid needing to alter y.tab.h again.
Note 2. For those unfamiliar with C. In Cygwin gcc produces a.exe. In other Unix systems, it usually produces a.out, in which the compile step would be ./a.out < source.text To get gcc to produce an output with another name e.g. myprog, employ: gcc –o myprog y.tab.c lex.yy.c