Professional Documents
Culture Documents
CSE-1
5th Sem
Year: 2019-20
Prepared By:
1. Sarthak Gandhi (170050107030)
2. Ashutosh Fichadia (170050107026)
3. Viren Desai (170050107020)
Guided By:
Prof. Pragna Makwana
System Programming | 2150708
1. Introduction to YACC
A parser generator is a program that takes as input a specification of a syntax, and
produces as output a procedure for recognizing that language. Historically, they are
also called compiler-compilers.
YACC (yet another compiler-compiler) is an LALR(1) (LookAhead, Left-to-right,
Rightmost derivation producer with 1 lookahead token) parser generator. YACC was
originally designed for being complemented by Lex.
Input: 6/((3-2)*(-5+2))
Output: -2
Lexical Analyzer Source Code:
%
{
/* Definition section*/
#include "y.tab.h"
extern yylval;
%
}
%%
[0 - 9]
+
{
yylval = atoi(yytext);
return NUMBER;
}
[a - zA - Z] + { return ID; }
[\t] + ;
\n { return 0; }
. { return yytext[0]; }
System Programming | 2150708
%%
/* Definition section */
#include
%
% token NUMBER ID
// setting the precedence
// and associativity of operators
% left '+' '-'
% left '*' '/'
/* Rule Section */
%
%E:T
{
T : T '+' T { $$ = $1 + $3; }
| T '-' T { $$ = $1 - $3; }
| T '*' T { $$ = $1 * $3; }
| T '/' T { $$ = $1 / $3; }
| '-' NUMBER { $$ = -$2; }
| '-' ID { $$ = -$2; }
| '(' T ')' { $$ = $2; }
| NUMBER { $$ = $1; }
| ID { $$ = $1; };
%%
int main()
{
printf("Enter the expression\n");
yyparse();
}
{
printf("\nExpression is invalid\n");
}
Output:
Notes:
Yacc programs are generally written in 2 files one for lex with .l extension(for tokenization
and send the tokens to yacc) and another for yacc with .y extension (for grammar evaluation
and result evaluation).
Steps for execution of Yacc program:
lex sample_lex_program.l
yacc -d sample_yacc_program.y
cc lex.yy.c y.tab.c -ll
./a.out