You are on page 1of 3

Ex No : 3 IMPLEMENTATION OF LEXICAL ANALYZER USING LEX

AIM:
To implement lexical analyzer program in LEX tool.
ALGORITHM:
Step 1: Start the program.
Step 2: Lex program consists of three parts.
a. Declaration %%
b. Translation rules %%
c. Auxilary procedure.
Step 3: The declaration section includes declaration of variables, maintest, constants and regular
definitions.
Step 4: Translation rule of lex program are statements of the form
a. P1 {action}
b. P2 {action}
c. ...
d. ...
e. Pn {action}
Step 5: Write a program in the vi editor and save it with .l extension.
Step 6: Compile the lex program with lex compiler to produce output file as
lex.yy.c. eg $ lex filename.l $ cc lex.yy.c - ll
Step 7: Compile that file with C compiler and verify the output.
PROGRAM: lexii.l
%{
int COMMENT=0;
%}
id [A-za-z]([A-Za-z]|[0-9])*
%%
#.* {printf("\n%s is a preprocessor directive",yytext);}
("int"|"float"|"char"|"double"|"if"|"else"|"do") {printf("\n%s is a keyword",yytext);}
[A-za-z]([A-Za-z]|[0-9])* {printf("\n%s is a identifier",yytext);}
[0-9]+ {printf("\n%s is a constants",yytext);}
("+"|"-"|"*"|"/"|"="|"<"|">") {printf("\n%s is a operators",yytext);}
"("|","|"."|")"|"{"|"}"|";" {printf("\n%s is a special symbols",yytext);}
%%
int main()
{
yyin=fopen("input.c","r");
yylex();
fclose (yyin);
return 0;
}
int yywrap()
{
return 0;
}
INPUT
input.c
#include<stdio.h>
void main()
{
int a=10;
float b;
a+b;
}
OUTPUT

[root@localhost ~]# vi expptwo.l

[root@localhost ~]# flex expptwo.l

[root@localhost ~]# vi input.c

[root@localhost ~]# gcc lex.yy.c

[root@localhost ~]# ./a.out<input.c

#include<stdio.h> is a preprocessor directive

void is a identifier

main is a identifier

( is a special symbols

) is a special symbols

{ is a special symbols

int is a keyword

a is a identifier

= is a operators

10 is a constants

; is a special symbols

float is a keyword

b is a identifier

; is a special symbols

a is a identifier

+ is a operators

b is a identifier

; is a special symbols

} is a special symbols

RESULT:
Thus, we implemented lexical analyzer program in LEX tool.

You might also like