Ex: No:3 a Generate YACC specification for a few syntactic categories
Date: Program to recognize a valid arithmetic expression that uses operator
Aim:
To write aYacc program to recognize a valid arithmetic expression that uses operators.
Algorithm
1. Start the program to recognize valid arithmetic expressions.
2. Define the pattern for digits in the lex file.
3. Assign yyval to return the token number as integer in the lex file.
4. Define the patterns for operators and expressions in the Yacc file.
5. Use yywrap() to print an error using yyerror() in the yacc file.
6. Use yyparse() to read a stream of value pairs in the yacc file.
7. Display the valid arithmetic expressions
8. Stop the program.
Prepared by R.Anne Pratheeba, AP/CSE Page1
Program: Lex
/* File: ex3a.l */
%{
#include "y.tab.h"
%}
%%
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
[ \t] ; /* Ignore whitespace */
\n return '\n';
[-+*/()] return yytext[0];
. { printf("Invalid character: %s\n", yytext); }
%%
int yywrap(void) {
return 1;
}
Program : YACC
/* File: ex3a.y */
%{
#include <stdio.h>
#include <stdlib.h>
int yylex(void);
void yyerror(const char *s);
%}
/* Token
declarations */
%token NUMBER
/* Operator precedence (optional but useful) */
%left '+' '-'
%left '*' '/'
%right UMINUS
%%
/* Grammar rules */
expr:
expr '+' expr { printf("Valid: Addition\n"); }
| expr '-' expr { printf("Valid: Subtraction\n"); }
| expr '*' expr { printf("Valid: Multiplication\n"); }
| expr '/' expr { printf("Valid: Division\n"); }
| '-' expr %prec UMINUS { printf("Valid: Unary minus\n"); }
| '(' expr ')' { /* Parenthesized expression */ }
| NUMBER { /* A number is valid */ }
;
Prepared by R.Anne Pratheeba, AP/CSE Page2
input:
expr '\n' { printf("Expression is valid.\n"); }
;
%%
void yyerror(const char *s) {
fprintf(stderr, "Error: %s\n", s);
}
int main(void) {
printf("Enter an arithmetic expression:\n");
yyparse();
return 0;
}
Output:
-bash-4.1$ vi ex3a.l
-bash-4.1$ vi ex3a.y
-bash-4.1$ yacc –d ex3a.y # generates y.tab.c and y.tab.h
-bash-4.1$ lex ex3a.l #generates lex.yy.c
-bash-4.1$gcc y.tab.c lex.yy.c -o ex3a -ll
-bash-4.1$ ./ ex3a
Enter an arithmetic expression:
(5+3)*2
Expression is valid
Result:
The program is to recognize valid arithmetic expressions that are verified and executed
successfully.
Prepared by R.Anne Pratheeba, AP/CSE Page3
Ex: No: 3b Generate YACC specification for a few syntactic categories.
Date: Program to recognize a valid variable which starts with a letter followed
by any number of letters or digits.
Aim:
To Write a YACC program to recognize a valid variable which starts with a letter followed
by any number of letters or digits.
Algorithm:
1. Start the program to recognize valid arithmetic expressions.
2. Define the pattern for letters and digits in the lex file.
3. Define the pattern for identifiers in the yacc file.
4. Use yywrap() to print an error using yyerror() in the yacc file.
5. Use yyparse() to read a stream of value pairs in the yacc file.
6. Print the valid identifiers using yylex().
7. Display the valid identifiers.
8. Stop the program.
Prepared by R.Anne Pratheeba, AP/CSE Page4
Program:Lex
/* File: var.l */
%{
#include "y.tab.h"
%}
/* Pattern rules */
%%
[a-zA-Z][a-zA-Z0-9]* { return VARIABLE; }
[ \t] ; /* Ignore whitespace */
\n return '\n';
. { printf("Invalid variable name.\n"); }
%%
int yywrap(void) {
return 1;
}
Program: YACC
/* File: var.y */
%{
#include <stdio.h>
#include <stdlib.h>
int yylex(void);
void yyerror(const char *s);
%}
/* Token declaration */
%token VARIABLE
%%
start:
VARIABLE '\n' { printf("Valid variable name.\n"); }
| '\n' { printf("No input.\n"); }
;
%%
void yyerror(const char *s) {
Prepared by R.Anne Pratheeba, AP/CSE Page5
fprintf(stderr, "Error: %s\n", s);
}
int main(void) {
printf("Enter a variable name:\n");
yyparse();
return 0;
}
Output
-bash-4.1$ vi var.l
-bash-4.1$ vi var.y
-bash-4.1$ yacc –d var.y # generates y.tab.c and y.tab.h
-bash-4.1$ lex var.l #generates lex.yy.c
-bash-4.1$gcc y.tab.c lex.yy.c -o var -ll
-bash-4.1$ ./var
myVar123
Valid variable name: myVar123
123abc
Error: Invalid variable name
Result:
Thus the given program to validate variables is implemented and executed successfully.
Prepared by R.Anne Pratheeba, AP/CSE Page6
Ex: No: 3c Generate YACC specification for a few syntactic categories.
Date: Program to recognize valid control structures syntax of C
language (For loop, while loop, if-else, if-else-if, etc.).
Aim:
To write a Yacc program to validate control structures syntax.
Algorithm:
1. Start the program.
2. Define the Problem: Recognize valid control structures in C (e.g., if, if-else, if-else-if,
while, for) using Lex (for lexical analysis) and YACC (for syntax analysis). Read the
statement
3. Design Lex specification:
• the tokens for Keyword(if,else,while,for), Symbols(;,(,),etc), Identifier(variable
name), Numbers and Operator(+,-,etc).
• Return these tokens to the YACC
4. Design YACC specification:
• Declare the tokens using %token
• Define the grammar rules for :
• if
• for
• while
• For each rule provide productions that match valid syntax.
• Handle the error using yyerror().
•
5. Compile the parser and lex
6. Using the syntax rule check the given expression
7. Stop the Program.
Prepared by R.Anne Pratheeba, AP/CSE Page7
Program:
Filename : expr3c.l
%{
#include "y.tab.h"
%}
%%
"if" {return IF;}
"else" {return ELSE;}
"while" {return WHILE;}
"for" {return FOR;}
"(" {return LPAREN;}
")" {return RPAREN;}
"{" {return LBRACE;}
"}" {return RBRACE;}
";" {return SEMICOLON;}
[0-9]+ {return NUMBER;}
[a-zA-Z_][a-zA-Z0-9_]* {return ID;}
"=="|"!="|"<="|">="|"<"|">"|"="|"+"|"-"|"*"|"/" {return OP;}
[ \t\n] ;//ignore whitespace
. ; //ignore any other character
%%
int yywrap() {
return 1;
}
Prepared by R.Anne Pratheeba, AP/CSE Page8
Program:
FileName: expr3c.y
%{
#include<stdio.h>
#include<stdlib.h>
int yylex();
void yyerror(const char *s);
%}
%token IF ELSE WHILE FOR
%token LPAREN RPAREN LBRACE RBRACE
%token SEMICOLON OP ID NUMBER
%%
program:
stmt_list
;
stmt_list:
stmt
|stmt_list stmt
;
stmt:
if_stmt
|while_stmt
|for_stmt
;
if_stmt:
IF LPAREN condition RPAREN block optional_else
Prepared by R.Anne Pratheeba, AP/CSE Page9
;
optional_else:
/*empty*/
|ELSE block
|ELSE if_stmt
;
while_stmt:
WHILE LPAREN condition RPAREN block
;
for_stmt:
FOR LPAREN assignment SEMICOLON condition SEMICOLON assignment RPAREN block;
condition:
ID OP ID
| ID OP NUMBER
|NUMBER OP ID
;
assignment:
ID OP ID
|ID OP NUMBER
;
block:
LBRACE stmt_list RBRACE
|LBRACE RBRACE
;
%%
Prepared by R.Anne Pratheeba, AP/CSE Page10
void yyerror(const char *s){
printf("Syntax Error: %s\n",s);
}
int main(){
printf("Enter C Control structure code:\n");
if (yyparse()==0)
printf("Valid control structure syntax!\n");
return 0;
}
Prepared by R.Anne Pratheeba, AP/CSE Page11
Output:
-bash-4.1$ vi expr3c.l
-bash-4.1$ vi expr3c.y
-bash-4.1$ yacc –d expr3c.y # generates y.tab.c and y.tab.h
-bash-4.1$ lex expr3c.l #generates lex.yy.c
-bash-4.1$ gcc y,tab.c lex.yy.c -o expr3c -ll
Sample Input1:
-bash-4.1$ ./expr3c
Enter C Control structure code:
if (a == b) {
while (x < y) {
}
}
Ctrl+D
Output: Valid control structure syntax!
Sample Input2:
-bash-4.1$ ./expr3c
Enter C Control structure code:
for (i = 0; i < 10; i ++) {
if (i == 5)
break;
}
Output:Syntax Error:
Result:
Thus the given program to recognize control structures is executed successfully.
Prepared by R.Anne Pratheeba, AP/CSE Page12
Ex: No: 3d Implementation of calculator using LEX and YACC
Date:
Aim
To write a lex and yacc program to implement a calculator.
Algorithm
1. Start the program
2. In the declaration part of lex, includes declaration of regular definitions as digit.
3. In the translation rules part of lex, specifies the pattern and its action that is to be
executed whenever a lexeme matched by pattern is found in the input in the calc.l
4. By use of Yacc program all the arithmetic operations are done such as +, -, *, /.
5. Display error is persisting.
6. Verify the output.
7. Stop the Program.
Prepared by R.Anne Pratheeba, AP/CSE Page13
Filename: calc.l
%{
#include "y.tab.h"
#include <stdlib.h>
%}
%%
[0-9]+ {yylval.val = atoi(yytext);return NUMBER;}
[+\-*/()] {return yytext[0];}
\n { return '\n';}
[\t] {/*skip w\Whitspace*/}
. { printf("Invalid Character:%s\n",yytext);}
%%
int yywrap(){
return 1;
}
Prepared by R.Anne Pratheeba, AP/CSE Page14
Filename: calc.y
%{
#include<stdio.h>
#include<stdlib.h>
int yylex();
void yyerror(const char *s);
%}
%union {
int val;
}
%token <val> NUMBER
%type <val> expr
%left '+' '-'
%left '*' '/'
%%
stmt : expr '\n' { printf("Result:%d\n", $1); }
;
expr: expr '+' expr {$$ = $1+$3;}
| expr '-' expr {$$ = $1 - $3;}
| expr '*' expr {$$ = $1 * $3;}
| expr '/' expr {$$ = $1 / $3;}
| '(' expr ')' {$$ = $2;}
| NUMBER {$$= $1;}
;
%%
void yyerror(const char *s){
printf("Syntax Error: %s\n",s);
}
int main() {
printf("Enter the arithmetic expression:\n");
yyparse();
return 0;
Prepared by R.Anne Pratheeba, AP/CSE Page15
Output:
-bash-4.1$ vi calc.l
-bash-4.1$ vi calc.y
-bash-4.1$ yacc –d calc.y # generates y.tab.c and y.tab.h
-bash-4.1$ lex calc.l #generates lex.yy.c
-bash-4.1$ gcc lex.yy.c y.tab.c -o calc -ll
-bash-4.1$ ./calc
Enter the arithmetic expression:
3 + 5 * (4 - 2)
Result:13
Result:
Thus the program to implement a calculator using lex is executed successfully.
Prepared by R.Anne Pratheeba, AP/CSE Page16