You are on page 1of 5

COMPILER CONSTRUCTION

LAB REPORT # 06

Submitted To:

Sir Shahzad Arif

Submitted By:

Malik M.Shahzaib

Reg No:

17-CS-036
Lab #06

LEXICAL ANALYSIS USING FLEX

Objectives:

• To download and install flex in system.


• To implement different codes in flex.
• To perform lab tasks given in lab manual.
Software tools:
• Command Prompt
• Flex

Theory:
The lexical analyser is the part of the compiler that reads the source text, it may also perform
certain secondary tasks at the user interface. One such task is stripping out comments and white
space in the form of blanks, tabs and new line characters, from the source program. Another is
correlating error messages from the compiler with the source program i.e. keeping a
correspondence between errors and source line numbers.

Description:

Lexical analysis is the process of converting a sequence of characters into a sequence of tokens. A
program or function which performs lexical analysis is called a lexical analyser, lexer or scanner.
A lexer often exists as a single function which is called by a parser or another function.

Flex (Fast Lexical Analyzer Generator ) :

FLEX (fast lexical analyzer generator) is a tool/computer program for generating lexical analyzers
(scanners or lexers) written by Vern Paxson in C around 1987. It is used together with Berkeley
Yacc parser generator or GNU Bison parser generator. Flex and Bison both are more flexible than
Lex and Yacc and produces faster code. Bison produces parser from the input file provided by the
user. The function yylex() is automatically generated by the flex when it is provided with a .l file
and this yylex() function is expected by parser to call to retrieve tokens from current/this token
stream.

Procedure:

Task 01:

Write a flex program to Count the number of characters in a string.

Input:

%{

int length = 0;

%}

%%

[a-z A-Z 0-9]+ {length=yyleng; }

%%

int yywrap(){}

int main(){

yylex();

printf("\nLength of String "

"in the given input - %d\n", length);

return 0;

}
Output:

Task 02:

Write a program in lex language to Count the number of characters and number of lines in the
input.

Input:

%{

#include<stdio.h>

int lines=1, characters=0;

%}

%%

\n { lines++;}

[A-Z] characters++;

[a-z] characters++;

[0-9] characters++;

. characters++;

%%

main(void)

{
yyin= fopen("myfile.txt","r");

yylex();

printf(" This File contains ...");

printf("\n\t%d lines", lines);

printf("\n\tIn total %d characters.\n",characters);

int yywrap()

return(1);

Output:

Conclusion:
In this lab we learned to implement codes for lexical analysis. We implemented different codes in
flex to understand it’s working and at the end of the lab session we performed different tasks to
test our concepts.

=======================================================

You might also like