You are on page 1of 4

System Programming | 2150708

OPEN ENDED PROBLEM


System Programming
(2150708)

Topic: YACC Programs

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.

2. YACC Program to evaluate a given arithmetic


expression
Prerequisite – Introduction to YACC
Problem: Write a YACC program to evaluate a given arithmetic expression consisting of
‘+’, ‘-‘, ‘*’, ‘/’ including brackets.
Examples:
Input: 7*(5-3)/2
Output: 7

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

%%

Parser Source Code:


%{

/* Definition section */
#include
%

% token NUMBER ID
// setting the precedence
// and associativity of operators
% left '+' '-'
% left '*' '/'

/* Rule Section */
%
%E:T
{

printf("Result = %d\n", $$);


return 0;

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();
}

/* For printing error messages */


int yyerror(char* s)
System Programming | 2150708

{
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

You might also like