In: Computer Science
Write a lex program that can identify each of the following
tokens. The program should produce a line
for each token where the first word is token itself followed by the
token type.
• Identifiers: name of variables and functions (identifier name
should be started by a letter
followed by letters or digits and maximum eight characters in
length).
• Keywords: if, then, else, for, while, do, switch, case etc.
• Numbers: integer, float (float number format that supports in
C++/Java)
• Operators:
• Arithmetic operators (+,-,*,/)
• Relational operators (<, <=, >, >=, ==, !=)
• Conditional operators ( &&, ||, !, )
• Increment/decrement operators (++, --)
• Bitwise operators (&, |)
• Assignment operator (=)
• Special Symbols: (, ), {,},; .. etc
SOLUTION:-
%option noyywrap
%{
#include<stdio.h>
%}
TYPE int|char|bool|float|double|void|for|do|while|if|else|return|switch|case|then
DIGIT [0-9]
%%
{TYPE} {printf("Token %s is keywords\n ",yytext);}
[a-zA-Z_][a-zA-Z0-9]* {printf("Token %s is an identifiers\n ",yytext);}
"+"|"-"|"*"|"/" {printf("Token %s is arithmatic operators\n",yytext);}
"=="|"!="|">"|"<"|"<="|">=" {printf("Token %s is relational operators\n",yytext);}
"&&"|"||"|"!" {printf("Token %s is conditional operators\n",yytext);}
"++"|"--" {printf("Token %s is Increment/decrement operators\n",yytext);}
"&"|"|" {printf("Token %s is bitwise operators\n",yytext);}
"=" {printf("Token %s is assignment operators\n",yytext);}
^{DIGIT}+ {printf("Token %s is integer constant.\n",yytext);}
^{DIGIT}+[.]+{DIGIT}+ {printf("Token %s is floating number constant.\n",yytext);}
"("|")"|"{"|"}"|";" {printf("Token %s is special symbols \n",yytext);}
. ;
%%
int main()
{
printf("Enter herer :\n");
yylex();
return 0;
}