Compiler Design Experiment 3a
Compiler Design Experiment 3a
AIM:
To recognize valid arithmetic expressions using LEX and YACC.
ALGORITHM:
Step 1: Scan the input character stream to identify tokens for arithmetic operators, assignment
operator, identifiers, numbers, and terminating symbols.
Step 2: Define grammar rules for arithmetic expressions including assignment statements and
simple expressions.
Step 3: Implement parsing logic using recursive descent for expression parsing.
Step 6: Process assignment expressions where an identifier is followed by an equal sign and
an expression.
Step 7: Handle binary operations where expressions contain two operands separated by an
operator.
Step 9: Execute semantic actions when valid expressions are successfully parsed.
Step 10: Build internal abstract syntax tree representation of the expression.
Step 11: Generate success messages when valid arithmetic expressions are recognized.
Step 12: Handle error cases with appropriate error messages for invalid expressions.
PROGRAM:
Ex3a.l
%{
#include "ex3a.tab.h"
%}
%%
"=" { printf("\n Operator is EQUAL"); return A; }
"+" { printf("\n Operator is PLUS"); return '+'; }
"-" { printf("\n Operator is MINUS"); return '-'; }
"/" { printf("\n Operator is DIVISION"); return '/'; }
"*" { printf("\n Operator is MULTIPLICATION"); return '*'; }
([a-zA-Z][a-zA-Z0-9]*) { printf("\n Identifier is %s", yytext); return ID; }
\n { return 0; }
. { return yytext[0]; }
%%
int yywrap() {
return 1;
}
Ex3a.y
%{
#include <stdio.h>
%token A
%token ID
%%
statement: ID A E
| E { printf("\n Valid arithmetic expression"); $$ = $1; }
;
E: E '+' ID
| E '-' ID
| E '*' ID
| E '/' ID
| ID
;
%%
int main() {
yyin = stdin; // read input from standard input
yyparse();
return 0;
}
OUTPUT:
E:\CDLab\EX3\3a>flex ex3a.l
E:\CDLab\EX3\3a>bison -d ex3a.y
E:\CDLab\EX3\3a>gcc lex.yy.c ex3a.tab.c -o programs
E:\CDLab\EX3\3a>programs.exe
a=b+c
Identifier is a
Operator is EQUAL
Identifier is b
Operator is PLUS
Identifier is c
RESULT:
Valid arithmetic expressions are successfully recognized.