Lex and Yacc Program to detect errors in a 'C' Language Program
Lex Code:
%{
#include"y.tab.h"
#include<stdio.h>
int LineNo=1;
%}
identifier[a-zA-Z][_a-zA-Z0-9]*
number [0-9]+|([0-9]*\.[0-9]+)
%%
main\(\) return MAIN;
if return IF;
else return ELSE;
while return WHILE;
int |
char |
flaot return TYPE;
{identifier} return VAR;
{number} return NUM;
\> |
\< |
\<= |
\>= |
== return RELOP;
[\t] ;
[\n] LineNo++;
. return yytext[0];
%%
Yacc Code:
%{
#include<string.h>
#include<stdio.h>
extern int LineNo;
int errno=0;
%}
%token NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%left '-' '+'
%left '*' '/'
%%
PROGRAM: MAIN BLOCK
;
BLOCK: '{'CODE'}'
;
CODE: BLOCK
|STATEMENT CODE
|STATEMENT
;
STATEMENT:DECST';'
|DECST {printf("\nLine number %d:syntax error",lineNo);errno++;}
|ASSIGNMENT ';'
|ASSIGNMENT {printf("\nLine number %d:syntax error",lineNo);errno++;}
|CONDST
|WHILEST
;
DECST: TYPE VARLIST
;
VARLIST: VAR ','VARLIST
| VAR
;
ASSIGNMENT:VAR'='EXPR
;
EXPR: EXPR '+' EXPR
| EXPR '-' EXPR
| EXPR '*' EXPR
| EXPR '/' EXPR
| '-' EXPR
| '(' EXPR ')'
| VAR
| NUM
;
CONDST: IFST
| IFST ELSEST
;
IFST: IF '(' CONDITION ')'
BLOCK
;
ELSEST: ELSE
BLOCK
;
CONDITION: VAR RELOP VAR
| VAR
| NUM
;
WHILEST: WHILELOOP
;
WHILELOOP: WHILE '(' CONDITION ')'
BLOCK
;
%%
extern FILE *yyin;
int main(int argc, char *argv[])
{
FILE *fp;
int i;
/*Check for cmd line args*/
if(argc>1)
{
/*open file in read mode*/
fp = fopen(argv[1],"r");
if(!fp)
{
printf("\n File not found");
exit(0);
}//end if
yyin = fp;
}//end if
yyparse();
/*
check for the number of errors present and display
the read message
*/
if(errno==0)
printf("\nNo errors found!\n");
else
printf("\n%d error(s) found!\n",errno);
return(0);
}//End main
/* error handling routine which gets called if a statement cannot be
parsed with the grammer defined */
yyerror()
{
printf("\nSyntax Error on line %d\n",LineNo);
errno++;
}//End yyerror
what is the output of this code
ReplyDeleteInteresting.Thanks a lot for sharing
ReplyDeleteweb development oman