PROGRAM 2:

Implementation of Lexical Analyzer using Lex Tool.

ALGORITHM:

1. Start the program
2. Lex program consists of three parts.
3. Declaration %%
4. Translation rules %%
5. Auxiliary procedure.
6. The declaration section includes declaration of variables, main test, constants and regular
7. Definitions.
8. Translation rule of lex program are statements of the form
9. P1{action}
10. P2{action}
11. …..
12. …..
13. Pn{action}
14. Write program in the vi editor and save it with .1 extension.
15. Compile the lex program with lex compiler to produce output file as lex.yy.c.
16. Eg. $ lex filename.1
17. $gcc lex.yy.c -11
18. Compile that file with C compiler and verify the output.


PROGRAM:


%{
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* {printf("\n%s is a preprocessor directive",yytext);}
int |
float |
char |
double |
while |
for |
struct |
typedef |
do |
if |
break |
continue |
void |
switch |
return |
else |
goto     {printf("\n\t%s is a keyword",yytext);}
"/*"      {COMMENT=1;}{printf("\n\t %s is a COMMENT",yytext);}
{identifier}\(     {if(!COMMENT)printf("\n FUNCTION \n\t%s",yytext);}
\{         {if(!COMMENT)printf("\n BLOCK BEGINS");}
\}         {if(!COMMENT)printf("BLOCK ENDS ");}
{identifier}(\[[0-9]*\])?   {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\"    {if(!COMMENT)printf("\n\t %s is a STRING",yytext);}
[0-9]+   {if(!COMMENT) printf("\n %s is a NUMBER ",yytext);}
\)(\:)?    {if(!COMMENT)printf("\n\t");ECHO;printf("\n");}
\(          ECHO;
=          {if(!COMMENT)printf("\n\t %s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\>         {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
int main(int argc, char **argv)
{
FILE *file;
file=fopen("var.c","r");
if(!file)
{
printf("could not open the file");
exit(0);
}
yyin=file;
yylex();
printf("\n");
return(0);
}
int yywrap()
{
return(1);
}

INPUT:

//var.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
a=1;
b=2;
c=a+b;
printf("Sum:%d",c);
}


OUTPUT

#include<stdio.h> is a preprocessor directive

#include<conio.h> is a preprocessor directive

            void is a keyword
FUNCTION
            main(
            )


 BLOCK BEGINS

            int is a keyword
 a IDENTIFIER,
 b IDENTIFIER,
 c IDENTIFIER;

 a IDENTIFIER
             = is an ASSIGNMENT OPERATOR
 1 is a NUMBER ;

 b IDENTIFIER
             = is an ASSIGNMENT OPERATOR
 2 is a NUMBER ;

 c IDENTIFIER
             = is an ASSIGNMENT OPERATOR
 a IDENTIFIER+
 b IDENTIFIER;

FUNCTION
            printf(
            "Sum:%d" is a STRING,
 c IDENTIFIER
            )
;
BLOCK ENDS