Nila Assign5
Nila Assign5
Programming Assignment-5
Implementation of Syntax Checker using Lex and Yacc Tools
Name : Nila Sureshkumar
Reg No : 3122 21 5001 061
------------------------------------------------------------------------------------------------------------------
Develop a Syntax checker to recognize the following statements by writing suitable grammars
• Assignment statement
• Conditional statement
• Looping statement
• Declaration statement
Aim
Develop a Syntax checker to recognize the following statements by writing suitable grammars
• Assignment statement
• Conditional statement
• Looping statement
• Declaration statement
Code
Parser.l
%{
#include "parser.tab.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
%}
%%
// Keywords
int { return INT; }
if { return IF; }
else { return ELSE; }
while { return WHILE; }
// Symbol tokens
";" { return SEMICOLON; }
"," { return COMMA; }
"=" { return ASSIGN; }
"==" { return EQ; }
"!=" { return NEQ; }
"<" { return LT; }
">" { return GT; }
"<=" { return LE; }
">=" { return GE; }
"+" { return PLUS; }
"-" { return MINUS; }
"*" { return MULTIPLY; }
"/" { return DIVIDE; }
// Ignore whitespace
{whitespace} { /* ignore whitespace */ }
// Wrap function
%%
int yywrap() {
return 1;
}
Parser.y
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
%}
%union {
char *str;
int num;
}
%%
// Grammar rules
program:
statements
;
statements:
statement
| statements statement
;
statement:
declaration_statement
| assignment_statement
| conditional_statement
| looping_statement
;
declaration_statement:
INT identifier_list SEMICOLON
;
identifier_list:
IDENTIFIER
| identifier_list COMMA IDENTIFIER
;
assignment_statement:
IDENTIFIER ASSIGN expression SEMICOLON
;
expression:
expression PLUS term
| expression MINUS term
| term
;
term:
term MULTIPLY factor
| term DIVIDE factor
| factor
;
factor:
IDENTIFIER
| NUMBER
| LPAREN expression RPAREN
;
conditional_statement:
IF LPAREN condition RPAREN statement
| IF LPAREN condition RPAREN statement ELSE statement
;
condition:
expression relational_operator expression
;
relational_operator:
EQ | NEQ | LT | GT | LE | GE
;
looping_statement:
WHILE LPAREN condition RPAREN LBRACE statements RBRACE
;
%%
int main(void) {
if (yyparse() == 0) {
printf("Syntactically correct\n");
} else {
printf("Syntax error detected\n");
}
return 0;
}
Output
Learning Outcome
Learning Outcomes: