You are on page 1of 6

Lex

Prepared By: Dr. D. P. Singh


LEX (Lexical Analyzer Generator)
• Lex helps to write programs whose control flow is directed by
instances of regular expressions in the input stream
• Lex source is a table of regular expressions and corresponding
program fragments.
• The table is translated to a program which reads an input program,
copying it to an output stream and partitioning the input into strings
which match the given expressions.
• As each such string is recognized the corresponding program
fragment is executed.
• The recognition of the expressions is performed by a deterministic
finite automation generated by Lex.
• The program fragments written by user are executed in the order in
which the corresponding regular expressions occur in the input
stream
YACC (Yet another compiler compiler)-Parser
Generator
• Yacc provides a general tool for describing the input to a computer
program
• The Yacc user specifies the structure of his input, together with the
code to be invoked as each structure is recognized.
• Yacc turns such a specification into a subroutine that handles the
input process
Structure of Lex Program
• The Program Lex generates a so called ‘Lexer’
%{
Declaration section
%}
%%
Rule section
%%
Subroutine Section

• First %% is required to mark the beginning of the rules, second %%


required only if user subroutines follow.
Example (sample.l)
%{
#include<stdio.h>
int line_no=0;
#lex sample.l
%} #gcc lex.yy.c –ll
%% #./a.out
\n {line_no++;} The couse name
Is system software
. ; Ctrl+d
%% Total Lines: 2

int main()
{
yylex();
printf(“Total Lines:%d”, line_no);
return 0;
}
Thank You

You might also like