SlideShare a Scribd company logo
V.Anusuya,AP(SG)/CSE
1/21/2020 V.Anusuya,AP(SG)/CSE 1
LEX
 LEX is a tool that allows one to specify a Lexical
Analyzer by specifying RE to describe patterns for
tokens.
 Input Notation-Lex language(Specification)
 Lex Compiler-Transforms Input patterns into a
Transition diagram and generates code in a file called
lex.yy.c
1/21/2020 V.Anusuya,AP(SG)/CSE 2
Lexical Analyzer Generator - Lex
Lexical Compiler
Lex Source program
lex.l
lex.yy.c
C
compiler
lex.yy.c a.out
a.outInput stream Sequence
of tokens
1/21/2020 V.Anusuya,AP(SG)/CSE 3
Structure of Lex programs
Lex program has the following form:
declarations
%%
translation rules
%%
auxiliary functions
Pattern {Action}
1/21/2020 V.Anusuya,AP(SG)/CSE 4
 The declarations section includes declarations of
variables, manifest constants (identifiers declared to
stand for a constant, e.g., the name of a token), and
regular definitions.
 The translation rules each have the form
 Pattern { Action }
 pattern is a regular expression
 Action-Fragment of code written in C.
 Third Section-holds whatever additional functions are used in the
actions.
 Alternatively, these functions can be compiled separately and loaded
with the lexical analyser.
1/21/2020 V.Anusuya,AP(SG)/CSE 5
 The lexical analyzer returns a single value, the token
name, to the parser, but uses the shared, integer
variable yylval to pass additional information about
the lexeme found, if needed.
1/21/2020 V.Anusuya,AP(SG)/CSE 6
Sample Lex Program:
digit [0-9]
letter [a-zA-Z]
%%
{letter}({letter}|{digit})* printf(“id: %sn”, yytext);
n printf(“new linen”);
%%
main() {
yylex();
}
1/21/2020 V.Anusuya,AP(SG)/CSE 7
 Lex Predefined Variables
 yytext -- a string containing the lexeme
 yyleng -- the length of the lexeme
 yyin -- the input stream pointer
 yyout -- the output stream pointer
1/21/2020 V.Anusuya,AP(SG)/CSE 8
 Lex Library Routines
 yylex() - The default main() contains a call of yylex()
 yymore() - return the next token
 yyless(n) - retain the first n characters in yytext
 yywarp()-is called whenever Lex reaches an end-of-
file.By default yywarp() always returns 1
1/21/2020 V.Anusuya,AP(SG)/CSE 9
Program: LEX Specification
%%
{letter}({letter}|{digit})* printf("id: %sn", yytext);
n printf("new linen");
%%
int main(int argc,char **argv)
{
if (argc > 1)
{
FILE *file;
file = fopen(argv[1],"r");
if(!file)
{
printf("could not open %s n",argv[1]);
exit(0);
}
yyin = file;
}
1/21/2020 V.Anusuya,AP(SG)/CSE 10
yylex();
fclose(yyin);
return 0;
}
int yywrap()
{
return 1;
}
1/21/2020 V.Anusuya,AP(SG)/CSE 11
Input File
Sam.c
void main()
{
int a=5,b;
char c[]="GOOD";
b=a+10;
printf("%d",b);
}
1/21/2020 V.Anusuya,AP(SG)/CSE 12
Output
id: c
[]="id: GOOD
";new line
id: b
=id: a
+10;new line
id: printf
("%id: d
",id: b
);new line
}new line
new line
1/21/2020 V.Anusuya,AP(SG)/CSE 13
 Conflict Resolution in Lex
 There are two rules that Lex uses to decide on the
proper lexeme to select, when several prefixes of the
input match one or more patterns:
 1. Always prefer a longer prefix to a shorter prefix.
 2. If the longest possible prefix matches two or more
patterns, prefer the pattern listed first in the Lex
program.
1/21/2020 V.Anusuya,AP(SG)/CSE 14
The Lookahead Operator
 Lex automatically reads one character ahead of the last
character that forms the selected lexeme, and then
retracts the input so only the lexeme itself is consumed
from the input.
 However, sometimes, we want a certain pattern to be
matched to the input only when it is followed by a certain
other characters. If so, we may use the slash in a pattern
to indicate the end of the part of the pattern that
matches the lexeme.
 What follows / is additional pattern that must be
matched before we can decide that the token in question
was seen, but what matches this second pattern is not
part of the lexeme.
1/21/2020 V.Anusuya,AP(SG)/CSE 15
%{
/* program to recognize a c 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 |do |if |break |
continue |void | switch |case |long |struct |const |
typedef | return |else | goto {printf("nt%s is a
KEYWORD",yytext);}
"/*" {COMMENT = 1;}
"*/" {COMMENT = 0;}
1/21/2020 V.Anusuya,AP(SG)/CSE 16
{identifier}(
{if(!COMMENT)printf("nnFUNCTIONnt%s",yytext);
}
"{" {if(!COMMENT) printf("n BLOCK BEGINS");}
"}" {if(!COMMENT) printf("n BLOCK ENDS");}
{identifier}([[0-9]*])? {if(!COMMENT) printf("n %s
IDENTIFIER",yytext);}
"a"|"n"|"b"|"t"|"t"|"b"|"a" printf("n%stis
Escape sequences",yytext);
""%d""|"%s"|"%c"|"%f"|"%e" printf("n%stis a format
specifier",yytext);
".*" {if(!COMMENT) printf("nt%s is a
STRING",yytext);}
1/21/2020 V.Anusuya,AP(SG)/CSE 17
[0-9]+ {if(!COMMENT) printf("nt%s is a
NUMBER",yytext);}
"=" {if(!COMMENT)printf("nt%s is an ASSIGNMENT
OPERATOR",yytext);}
"+"|"-"|"*"|"/"|"%" {printf("n %s is an arithmetic
operator",yytext);}
"<="|">="|"<"|"=="|">" {if(!COMMENT) printf("nt%s is
a RELATIONAL OPERATOR",yytext);}
%%
1/21/2020 V.Anusuya,AP(SG)/CSE 18
int main(int argc,char **argv)
{
if (argc > 1)
{
FILE *file;
file = fopen(argv[1],"r");
if(!file)
{
printf("could not open %s n",argv[1]);
exit(0);
}
1/21/2020 V.Anusuya,AP(SG)/CSE 19
yyin = file;
}
yylex();
fclose(yyin);
return 0;
}
int yywrap()
{
return 1;
}
1/21/2020 V.Anusuya,AP(SG)/CSE 20

More Related Content

What's hot

Finite Automata
Finite AutomataFinite Automata
Finite Automata
Mukesh Tekwani
 
Input-Buffering
Input-BufferingInput-Buffering
Input-Buffering
Dattatray Gandhmal
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
ASHOK KUMAR REDDY
 
Yacc
YaccYacc
Token, Pattern and Lexeme
Token, Pattern and LexemeToken, Pattern and Lexeme
Token, Pattern and Lexeme
A. S. M. Shafi
 
Type Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLikeType Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLike
United International University
 
Minimization of DFA
Minimization of DFAMinimization of DFA
Minimization of DFA
kunj desai
 
Lecture 14 run time environment
Lecture 14 run time environmentLecture 14 run time environment
Lecture 14 run time environment
Iffat Anjum
 
Loops in flow
Loops in flowLoops in flow
Loops in flow
indhu mathi
 
Attributes of Output Primitives
Attributes of Output PrimitivesAttributes of Output Primitives
Attributes of Output Primitives
Renita Santhmayora
 
Code generation
Code generationCode generation
Code generation
Aparna Nayak
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
Muhammed Afsal Villan
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
United International University
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
Radhakrishnan Chinnusamy
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
Akshaya Arunan
 
1.1. the central concepts of automata theory
1.1. the central concepts of automata theory1.1. the central concepts of automata theory
1.1. the central concepts of automata theory
Sampath Kumar S
 
Lexical Analysis - Compiler Design
Lexical Analysis - Compiler DesignLexical Analysis - Compiler Design
Lexical Analysis - Compiler Design
Akhil Kaushik
 
Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design
MAHASREEM
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
Akhil Kaushik
 
Data link layer
Data link layer Data link layer
Data link layer
Mukesh Chinta
 

What's hot (20)

Finite Automata
Finite AutomataFinite Automata
Finite Automata
 
Input-Buffering
Input-BufferingInput-Buffering
Input-Buffering
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Yacc
YaccYacc
Yacc
 
Token, Pattern and Lexeme
Token, Pattern and LexemeToken, Pattern and Lexeme
Token, Pattern and Lexeme
 
Type Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLikeType Checking(Compiler Design) #ShareThisIfYouLike
Type Checking(Compiler Design) #ShareThisIfYouLike
 
Minimization of DFA
Minimization of DFAMinimization of DFA
Minimization of DFA
 
Lecture 14 run time environment
Lecture 14 run time environmentLecture 14 run time environment
Lecture 14 run time environment
 
Loops in flow
Loops in flowLoops in flow
Loops in flow
 
Attributes of Output Primitives
Attributes of Output PrimitivesAttributes of Output Primitives
Attributes of Output Primitives
 
Code generation
Code generationCode generation
Code generation
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
 
1.1. the central concepts of automata theory
1.1. the central concepts of automata theory1.1. the central concepts of automata theory
1.1. the central concepts of automata theory
 
Lexical Analysis - Compiler Design
Lexical Analysis - Compiler DesignLexical Analysis - Compiler Design
Lexical Analysis - Compiler Design
 
Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design
 
Code Optimization
Code OptimizationCode Optimization
Code Optimization
 
Data link layer
Data link layer Data link layer
Data link layer
 

Similar to Lexical analyzer generator lex

module 4.pptx
module 4.pptxmodule 4.pptx
module 4.pptx
ShwetaNirmanik
 
system software
system software system software
system software randhirlpu
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flexvip_du
 
LANGUAGE PROCESSOR
LANGUAGE PROCESSORLANGUAGE PROCESSOR
LANGUAGE PROCESSOR
EZIOAUDITORE15070
 
Lex programming
Lex programmingLex programming
Lex programming
sureshmoharana2013
 
lecture_lex.pdf
lecture_lex.pdflecture_lex.pdf
lecture_lex.pdf
DrNilotpalChakrabort
 
Lex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.pptLex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.ppt
MohitJain296729
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
Handout#02
Handout#02Handout#02
Handout#02
Sunita Milind Dol
 
Ch 2.pptx
Ch 2.pptxCh 2.pptx
Ch 2.pptx
woldu2
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
Sami Said
 
3. Lexical analysis
3. Lexical analysis3. Lexical analysis
3. Lexical analysis
Saeed Parsa
 
module 4_ Lex_new.ppt
module 4_ Lex_new.pptmodule 4_ Lex_new.ppt
module 4_ Lex_new.ppt
leyobi6147
 
Lexical
LexicalLexical
role of lexical anaysis
role of lexical anaysisrole of lexical anaysis
role of lexical anaysis
Sudhaa Ravi
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manualSami Said
 
Compilers Design
Compilers DesignCompilers Design
Compilers Design
Akshaya Arunan
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
pssraikar
 
Module4 lex and yacc.ppt
Module4 lex and yacc.pptModule4 lex and yacc.ppt
Module4 lex and yacc.ppt
ProddaturNagaVenkata
 
A simple approach of lexical analyzers
A simple approach of lexical analyzersA simple approach of lexical analyzers
A simple approach of lexical analyzers
Archana Gopinath
 

Similar to Lexical analyzer generator lex (20)

module 4.pptx
module 4.pptxmodule 4.pptx
module 4.pptx
 
system software
system software system software
system software
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flex
 
LANGUAGE PROCESSOR
LANGUAGE PROCESSORLANGUAGE PROCESSOR
LANGUAGE PROCESSOR
 
Lex programming
Lex programmingLex programming
Lex programming
 
lecture_lex.pdf
lecture_lex.pdflecture_lex.pdf
lecture_lex.pdf
 
Lex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.pptLex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.ppt
 
More on Lex
More on LexMore on Lex
More on Lex
 
Handout#02
Handout#02Handout#02
Handout#02
 
Ch 2.pptx
Ch 2.pptxCh 2.pptx
Ch 2.pptx
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
3. Lexical analysis
3. Lexical analysis3. Lexical analysis
3. Lexical analysis
 
module 4_ Lex_new.ppt
module 4_ Lex_new.pptmodule 4_ Lex_new.ppt
module 4_ Lex_new.ppt
 
Lexical
LexicalLexical
Lexical
 
role of lexical anaysis
role of lexical anaysisrole of lexical anaysis
role of lexical anaysis
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
Compilers Design
Compilers DesignCompilers Design
Compilers Design
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
Module4 lex and yacc.ppt
Module4 lex and yacc.pptModule4 lex and yacc.ppt
Module4 lex and yacc.ppt
 
A simple approach of lexical analyzers
A simple approach of lexical analyzersA simple approach of lexical analyzers
A simple approach of lexical analyzers
 

More from Anusuya123

Unit-III Correlation and Regression.pptx
Unit-III Correlation and Regression.pptxUnit-III Correlation and Regression.pptx
Unit-III Correlation and Regression.pptx
Anusuya123
 
Types of Data-Introduction.pptx
Types of Data-Introduction.pptxTypes of Data-Introduction.pptx
Types of Data-Introduction.pptx
Anusuya123
 
Basic Statistical Descriptions of Data.pptx
Basic Statistical Descriptions of Data.pptxBasic Statistical Descriptions of Data.pptx
Basic Statistical Descriptions of Data.pptx
Anusuya123
 
Data warehousing.pptx
Data warehousing.pptxData warehousing.pptx
Data warehousing.pptx
Anusuya123
 
Unit 1-Data Science Process Overview.pptx
Unit 1-Data Science Process Overview.pptxUnit 1-Data Science Process Overview.pptx
Unit 1-Data Science Process Overview.pptx
Anusuya123
 
Introduction to Data Science.pptx
Introduction to Data Science.pptxIntroduction to Data Science.pptx
Introduction to Data Science.pptx
Anusuya123
 
5.2.2. Memory Consistency Models.pptx
5.2.2. Memory Consistency Models.pptx5.2.2. Memory Consistency Models.pptx
5.2.2. Memory Consistency Models.pptx
Anusuya123
 
5.1.3. Chord.pptx
5.1.3. Chord.pptx5.1.3. Chord.pptx
5.1.3. Chord.pptx
Anusuya123
 
3. Descriptive statistics.ppt
3. Descriptive statistics.ppt3. Descriptive statistics.ppt
3. Descriptive statistics.ppt
Anusuya123
 
1. Intro DS.pptx
1. Intro DS.pptx1. Intro DS.pptx
1. Intro DS.pptx
Anusuya123
 
5.Collective bargaining.pptx
5.Collective bargaining.pptx5.Collective bargaining.pptx
5.Collective bargaining.pptx
Anusuya123
 
Runtimeenvironment
RuntimeenvironmentRuntimeenvironment
Runtimeenvironment
Anusuya123
 
Think pair share
Think pair shareThink pair share
Think pair share
Anusuya123
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
Anusuya123
 

More from Anusuya123 (14)

Unit-III Correlation and Regression.pptx
Unit-III Correlation and Regression.pptxUnit-III Correlation and Regression.pptx
Unit-III Correlation and Regression.pptx
 
Types of Data-Introduction.pptx
Types of Data-Introduction.pptxTypes of Data-Introduction.pptx
Types of Data-Introduction.pptx
 
Basic Statistical Descriptions of Data.pptx
Basic Statistical Descriptions of Data.pptxBasic Statistical Descriptions of Data.pptx
Basic Statistical Descriptions of Data.pptx
 
Data warehousing.pptx
Data warehousing.pptxData warehousing.pptx
Data warehousing.pptx
 
Unit 1-Data Science Process Overview.pptx
Unit 1-Data Science Process Overview.pptxUnit 1-Data Science Process Overview.pptx
Unit 1-Data Science Process Overview.pptx
 
Introduction to Data Science.pptx
Introduction to Data Science.pptxIntroduction to Data Science.pptx
Introduction to Data Science.pptx
 
5.2.2. Memory Consistency Models.pptx
5.2.2. Memory Consistency Models.pptx5.2.2. Memory Consistency Models.pptx
5.2.2. Memory Consistency Models.pptx
 
5.1.3. Chord.pptx
5.1.3. Chord.pptx5.1.3. Chord.pptx
5.1.3. Chord.pptx
 
3. Descriptive statistics.ppt
3. Descriptive statistics.ppt3. Descriptive statistics.ppt
3. Descriptive statistics.ppt
 
1. Intro DS.pptx
1. Intro DS.pptx1. Intro DS.pptx
1. Intro DS.pptx
 
5.Collective bargaining.pptx
5.Collective bargaining.pptx5.Collective bargaining.pptx
5.Collective bargaining.pptx
 
Runtimeenvironment
RuntimeenvironmentRuntimeenvironment
Runtimeenvironment
 
Think pair share
Think pair shareThink pair share
Think pair share
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
 

Recently uploaded

ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
BrazilAccount1
 

Recently uploaded (20)

ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
English lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdfEnglish lab ppt no titlespecENG PPTt.pdf
English lab ppt no titlespecENG PPTt.pdf
 

Lexical analyzer generator lex

  • 2. LEX  LEX is a tool that allows one to specify a Lexical Analyzer by specifying RE to describe patterns for tokens.  Input Notation-Lex language(Specification)  Lex Compiler-Transforms Input patterns into a Transition diagram and generates code in a file called lex.yy.c 1/21/2020 V.Anusuya,AP(SG)/CSE 2
  • 3. Lexical Analyzer Generator - Lex Lexical Compiler Lex Source program lex.l lex.yy.c C compiler lex.yy.c a.out a.outInput stream Sequence of tokens 1/21/2020 V.Anusuya,AP(SG)/CSE 3
  • 4. Structure of Lex programs Lex program has the following form: declarations %% translation rules %% auxiliary functions Pattern {Action} 1/21/2020 V.Anusuya,AP(SG)/CSE 4
  • 5.  The declarations section includes declarations of variables, manifest constants (identifiers declared to stand for a constant, e.g., the name of a token), and regular definitions.  The translation rules each have the form  Pattern { Action }  pattern is a regular expression  Action-Fragment of code written in C.  Third Section-holds whatever additional functions are used in the actions.  Alternatively, these functions can be compiled separately and loaded with the lexical analyser. 1/21/2020 V.Anusuya,AP(SG)/CSE 5
  • 6.  The lexical analyzer returns a single value, the token name, to the parser, but uses the shared, integer variable yylval to pass additional information about the lexeme found, if needed. 1/21/2020 V.Anusuya,AP(SG)/CSE 6
  • 7. Sample Lex Program: digit [0-9] letter [a-zA-Z] %% {letter}({letter}|{digit})* printf(“id: %sn”, yytext); n printf(“new linen”); %% main() { yylex(); } 1/21/2020 V.Anusuya,AP(SG)/CSE 7
  • 8.  Lex Predefined Variables  yytext -- a string containing the lexeme  yyleng -- the length of the lexeme  yyin -- the input stream pointer  yyout -- the output stream pointer 1/21/2020 V.Anusuya,AP(SG)/CSE 8
  • 9.  Lex Library Routines  yylex() - The default main() contains a call of yylex()  yymore() - return the next token  yyless(n) - retain the first n characters in yytext  yywarp()-is called whenever Lex reaches an end-of- file.By default yywarp() always returns 1 1/21/2020 V.Anusuya,AP(SG)/CSE 9
  • 10. Program: LEX Specification %% {letter}({letter}|{digit})* printf("id: %sn", yytext); n printf("new linen"); %% int main(int argc,char **argv) { if (argc > 1) { FILE *file; file = fopen(argv[1],"r"); if(!file) { printf("could not open %s n",argv[1]); exit(0); } yyin = file; } 1/21/2020 V.Anusuya,AP(SG)/CSE 10
  • 11. yylex(); fclose(yyin); return 0; } int yywrap() { return 1; } 1/21/2020 V.Anusuya,AP(SG)/CSE 11
  • 12. Input File Sam.c void main() { int a=5,b; char c[]="GOOD"; b=a+10; printf("%d",b); } 1/21/2020 V.Anusuya,AP(SG)/CSE 12
  • 13. Output id: c []="id: GOOD ";new line id: b =id: a +10;new line id: printf ("%id: d ",id: b );new line }new line new line 1/21/2020 V.Anusuya,AP(SG)/CSE 13
  • 14.  Conflict Resolution in Lex  There are two rules that Lex uses to decide on the proper lexeme to select, when several prefixes of the input match one or more patterns:  1. Always prefer a longer prefix to a shorter prefix.  2. If the longest possible prefix matches two or more patterns, prefer the pattern listed first in the Lex program. 1/21/2020 V.Anusuya,AP(SG)/CSE 14
  • 15. The Lookahead Operator  Lex automatically reads one character ahead of the last character that forms the selected lexeme, and then retracts the input so only the lexeme itself is consumed from the input.  However, sometimes, we want a certain pattern to be matched to the input only when it is followed by a certain other characters. If so, we may use the slash in a pattern to indicate the end of the part of the pattern that matches the lexeme.  What follows / is additional pattern that must be matched before we can decide that the token in question was seen, but what matches this second pattern is not part of the lexeme. 1/21/2020 V.Anusuya,AP(SG)/CSE 15
  • 16. %{ /* program to recognize a c 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 |do |if |break | continue |void | switch |case |long |struct |const | typedef | return |else | goto {printf("nt%s is a KEYWORD",yytext);} "/*" {COMMENT = 1;} "*/" {COMMENT = 0;} 1/21/2020 V.Anusuya,AP(SG)/CSE 16
  • 17. {identifier}( {if(!COMMENT)printf("nnFUNCTIONnt%s",yytext); } "{" {if(!COMMENT) printf("n BLOCK BEGINS");} "}" {if(!COMMENT) printf("n BLOCK ENDS");} {identifier}([[0-9]*])? {if(!COMMENT) printf("n %s IDENTIFIER",yytext);} "a"|"n"|"b"|"t"|"t"|"b"|"a" printf("n%stis Escape sequences",yytext); ""%d""|"%s"|"%c"|"%f"|"%e" printf("n%stis a format specifier",yytext); ".*" {if(!COMMENT) printf("nt%s is a STRING",yytext);} 1/21/2020 V.Anusuya,AP(SG)/CSE 17
  • 18. [0-9]+ {if(!COMMENT) printf("nt%s is a NUMBER",yytext);} "=" {if(!COMMENT)printf("nt%s is an ASSIGNMENT OPERATOR",yytext);} "+"|"-"|"*"|"/"|"%" {printf("n %s is an arithmetic operator",yytext);} "<="|">="|"<"|"=="|">" {if(!COMMENT) printf("nt%s is a RELATIONAL OPERATOR",yytext);} %% 1/21/2020 V.Anusuya,AP(SG)/CSE 18
  • 19. int main(int argc,char **argv) { if (argc > 1) { FILE *file; file = fopen(argv[1],"r"); if(!file) { printf("could not open %s n",argv[1]); exit(0); } 1/21/2020 V.Anusuya,AP(SG)/CSE 19
  • 20. yyin = file; } yylex(); fclose(yyin); return 0; } int yywrap() { return 1; } 1/21/2020 V.Anusuya,AP(SG)/CSE 20