Flex/Lex is a compiler construction tool that can be used to design a compiler.In this example flex is used to create a sample lexical analyzer for c programming language,it can recognize the valid symbols in c programming language including valid programming constructs.
The following is a complete source code Flex/Lex program to implement a Lexical analyzer for C programming language
The following is a complete source code Flex/Lex program to implement a Lexical analyzer for C programming language
letter [a-zA-Z]
digit[0-9]
%%
{digit}+("E"("+"|"-")?{digit}+)? printf("\n%s\tis real number",yytext);
{digit}+"."{digit}+("E"("+"|"-")?{digit}+)? printf("\n%s\t is floating pt no ",yytext);
"if"|"else"|"int"|"char"|"scanf"|"printf"|"switch"|"return"|"struct"|"do"|"while"|"void"|"for"|"float" printf("\n%s\t is keywords",yytext);
"\a"|"\\n"|"\\b"|"\t"|"\\t"|"\b"|"\\a" printf("\n%s\tis Escape sequences",yytext);
{letter}({letter}|{digit})* printf("\n%s\tis identifier",yytext);
"&&"|"<"|">"|"<="|">="|"="|"+"|"-"|"?"|"*"|"/"|"%"|"&"|"||" printf("\n%s\toperator ",yytext);
"{"|"}"|"["|"]"|"("|")"|"#"|"'"|"."|"\""|"\\"|";"|"," printf("\n%s\t is a special character",yytext);
"%d"|"%s"|"%c"|"%f"|"%e" printf("\n%s\tis a format specifier",yytext);
%%
int yywrap()
{
return 1;
}
int main(int argc,char *argv[])
{
yyin=fopen(argv[1],"r");
yylex();
fclose(yyin);
return 0;
}
/*INPUT PROGRAM
#include<stdio.h>
void main()
{
printf("\nhai\n");
}
/*
OUTPUT
# is a special character
include is identifier
< operator
stdio is identifier
. is a special character
h is identifier
> operator
void is keywords
main is identifier
( is a special character
) is a special character
{ is a special character
printf is keywords
( is a special character
" is a special character
\n is Escape sequences
hai is identifier
\n is Escape sequences
" is a special character
) is a special character
; is a special character
} is a special character
*/
No comments:
Post a Comment