Skip to content

Instantly share code, notes, and snippets.

@utkarshsingh99
Last active November 26, 2019 16:10
Show Gist options
  • Save utkarshsingh99/9c6ed6d27c9d066ae895579b8002ea4f to your computer and use it in GitHub Desktop.
Save utkarshsingh99/9c6ed6d27c9d066ae895579b8002ea4f to your computer and use it in GitHub Desktop.
A Lex Program to detect errors in a C/C++ program
%{
int n = 0, limit = 0, cursor = 0;
char identifiers[100][100];
int identify = 0;
%}
%%
"while"|"if"|"else"|"for" {n++;printf("\t keywords : %s\n", yytext);}
"int"|"float" {n++;printf("\t keywords : %s\t", yytext);
if(strcmp(yytext, "int") == 0) {
identify = 1;
} else if(strcmp(yytext, "float") == 0) {
identify = 1;
}
}
[a-zA-Z_][a-zA-Z0-9_]* {
if(identify) {
printf("\t identifier : %s\n", yytext);
strcpy(identifiers[limit], yytext);
} else {
int k = 0;
for(int i = 0; i <= limit; i++) {
if(strcmp(identifiers[i], yytext) == 0) {
printf("\t identifier: %s\n", yytext);
k = 1;
break;
}
}
if(k == 0) {
printf("\t Unrecognized Token: %s\n", yytext);
return 0;
}
} };
"<="|"=="|"="|"++"|"-"|"*"|"+" {n++;printf("\t operator : %s\n", yytext);}
[(){}|,;] {n++;printf("\t separator : %s\n", yytext);
if(strcmp(yytext, ";")== 0){
identify = 0;
limit++;
}
if(strcmp(yytext, ",") == 0) {
limit++;
}
}
[0-9]*"."[0-9]+ {n++;printf("\t float : %s\n", yytext);}
[0-9]+ {n++;printf("\t integer : %s\n", yytext);}
%%
int main()
{
yylex();
printf("\n total no. of token = %d\n", n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment