Lexical Analysis & Lex Tool
Lexical Analysis & Lex Tool
LEX TOOL
2. Building of
compiler
3.Execution of
lexical analyzer
LEX FILE FORMAT
A Lex program consists of three parts and is separated
by %% delimiters:-
Declarations
%%
Translation rules
%%
Auxiliary procedures
abc* ababcabccabccc…
LEX PROGRAM IMPORTANT FUNCTIONS
yylex()
– Reads the input stream and
generates token according to the
regular expression.
%{
int flag=0;
%}
%%
[(] {flag++;}
[)] {flag--;}
[\n] {if(flag==0)
printf("\t Well formed parathensis"); else if(flag>0)
printf("\t Closing parathens missing"); else
printf("\topening parathens missing");
}
%%
int main(void)
{
printf("enter the expression");
yylex();
return(0);
}
int yywrap(void)
{
return 0;
}
int yyerror(void)
{
printf("Error\n"); exit(1);
}
PROGRAMS COUNTS THE NUMBER OF LINES, WORDS AND CHARACTERS IN A
TEXT FILE.
%{
#include<stdio.h>
int lines=0, words=0,s_letters=0,c_letters=0, num=0,
spl_char=0,total=0;
%}
%%
\n { lines++; words++;}
[\t ' '] words++;
[A-Z] c_letters++;
[a-z] s_letters++;
[0-9] num++;
. spl_char++;
%%
main(void)
{
yyin= fopen("myfile.txt","r");
yylex();
total=s_letters+c_letters+num+spl_char;
printf(" This File contains ...");
printf("\n\t%d lines", lines);
printf("\n\t%d words",words);
printf("\n\t%d small letters", s_letters);
printf("\n\t%d capital letters",c_letters);
printf("\n\t%d digits", num);
printf("\n\t%d special characters",spl_char);
printf("\n\tIn total %d characters.\n",total);
}
int yywrap()
{
return(1);
}
OUTPUT
Let the 'myfile.txt' contains this.
This is my 1st lex program!!!
Cheers!! It works!!:)