SlideShare a Scribd company logo
1 of 14
LEX PROGRAMMING
What is Lex?
• Lex/Flex allows to specify a LA by specifying
regular definitions to describe pattern for tokens.
• The input notation for the lex tool is reffered as
the Lex language and tool itself is the Lex tool.
• Lex compiler transforms the input patterns into a
TD and generates a code, in a file called lex.yy.c
that simulates the TD.
How Lex Works?
lex.l lex.yy.c
lex.yy.c a.out
Input Stream Sequence of
Tokens
Lex Compiler
C Compiler
a.out
Lex in Detail
User Tokens
Lex
(regex+action)
yylex()
{
}
Optional
Driver
Code
GCC
Lex Specification
A lex program has following form,
declarations
%%
translation rules
%%
driver functions
Note: %% is the smallest possible lex program
Declarations
A series of rules of the form
name definitions
E.g. DIGIT [0-9]
COMMENTSTART “*”
ID [a-zA-Z][a-zA-Z0-9]*
Contd...
The parts required to be copied to lex.yy.c
should be written inside %{... %}.
E.g.
%{
//comment
#include<stdio.h>
%}
Translation Rules
Rules portion of the lex program contains a
sequence of rules of the form,
pattern action
E.g.
{letter}({letter}|{digit})* return id;
{digit}+ return num;
Note: action must begin in same line
Sample Program
%{
#include<stdio.h>
%}
dgt [0-9]
%%
{dgt}+ return atoi(yytext);
%%
void main() {
int val,sum=0,n=0;
while((val=yylex())>0){
sum=sum+val;
n++;
}
If(n>0)
printf(“avg=%dn”,sum/n);
}
Compiling Lex
Installation: sudo apt-get install flex
Step-1: lex demo.l
Step-2: gcc lex.yy.c –ll
Step-3: ./a.out
Note: -ll is used to link the default yywarp().
Lex Functions
yylex(): each invocation scans the input where
left off, returns 0 on EOF
yytext: buffer holds the characters that match
the pattern, char *yytext
yyleng: length of lexeme matched, return an
integer
yyin: the input stream pointer, FILE *
yyout: the output stream pointer, FILE *
Conflict Resolution in Lex
Conflict possible when more than one pattern
matches the input or lexeme. Rules to avoid the
conflict,
a. The longest match is chosen
b. If multiple rules match, rule enlisted top
most is chosen
Contd...
E.g. Input: CS335
(CS) {printf(“Department”);}
(CS)[0-9]3 {printf(“Course”);}
[a-zA-Z]+[0-9]+ {printf(“AnythingElse”);}
Output: Course
E.g.
Input: CS3351 Output: AnythingElse
Some More Translation Rules
[ tn] ; (represents no action)
[a-z]+ ECHO; (display the matched
lexeme)
. (class of characters except
n)
[^a-zA-Z] (any character is not a
letter)
ab?c (ac or abc)

More Related Content

What's hot

Operators in Python
Operators in PythonOperators in Python
Operators in PythonAnusuya123
 
Lexical Analysis
Lexical AnalysisLexical Analysis
Lexical AnalysisNayemid4676
 
Compiler Design
Compiler DesignCompiler Design
Compiler DesignMir Majid
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysisRicha Sharma
 
Python If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaPython If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaEdureka!
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compilerIffat Anjum
 
Regular Expression in Compiler design
Regular Expression in Compiler designRegular Expression in Compiler design
Regular Expression in Compiler designRiazul Islam
 
Compiler design and lexical analyser
Compiler design and lexical analyserCompiler design and lexical analyser
Compiler design and lexical analyserabhishek gupta
 
Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design MAHASREEM
 
Ambiguous & Unambiguous Grammar
Ambiguous & Unambiguous GrammarAmbiguous & Unambiguous Grammar
Ambiguous & Unambiguous GrammarMdImamHasan1
 
Lecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular LanguagesLecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular LanguagesMarina Santini
 

What's hot (20)

Role-of-lexical-analysis
Role-of-lexical-analysisRole-of-lexical-analysis
Role-of-lexical-analysis
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Lexical Analysis
Lexical AnalysisLexical Analysis
Lexical Analysis
 
Peephole Optimization
Peephole OptimizationPeephole Optimization
Peephole Optimization
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysis
 
Python If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaPython If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | Edureka
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compiler
 
Regular Expression in Compiler design
Regular Expression in Compiler designRegular Expression in Compiler design
Regular Expression in Compiler design
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
 
Compiler design and lexical analyser
Compiler design and lexical analyserCompiler design and lexical analyser
Compiler design and lexical analyser
 
java Features
java Featuresjava Features
java Features
 
Theory of computation and automata
Theory of computation and automataTheory of computation and automata
Theory of computation and automata
 
Parse Tree
Parse TreeParse Tree
Parse Tree
 
Finite automata
Finite automataFinite automata
Finite automata
 
Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design Syntax Analysis in Compiler Design
Syntax Analysis in Compiler Design
 
Ambiguous & Unambiguous Grammar
Ambiguous & Unambiguous GrammarAmbiguous & Unambiguous Grammar
Ambiguous & Unambiguous Grammar
 
Lecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular LanguagesLecture: Regular Expressions and Regular Languages
Lecture: Regular Expressions and Regular Languages
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 

Similar to Lex programming

Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabusJK Knowledge
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manualSami Said
 
Lex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.pptLex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.pptMohitJain296729
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)Sami Said
 
system software
system software system software
system software randhirlpu
 
Lec 04 intro assembly
Lec 04 intro assemblyLec 04 intro assembly
Lec 04 intro assemblyAbdul Khan
 
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...Prof Chethan Raj C
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc pptpssraikar
 
1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdfSemsemSameer1
 
module 4_ Lex_new.ppt
module 4_ Lex_new.pptmodule 4_ Lex_new.ppt
module 4_ Lex_new.pptleyobi6147
 
Lex and Yacc.pdf
Lex and Yacc.pdfLex and Yacc.pdf
Lex and Yacc.pdfAKASHPAL102
 
Generacion de codigo ensamblado
Generacion de codigo ensambladoGeneracion de codigo ensamblado
Generacion de codigo ensambladotre_na_gil
 

Similar to Lex programming (20)

Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabus
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
module 4.pptx
module 4.pptxmodule 4.pptx
module 4.pptx
 
Lex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.pptLex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.ppt
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
LEX & YACC
LEX & YACCLEX & YACC
LEX & YACC
 
system software
system software system software
system software
 
7986-lect 7.pdf
7986-lect 7.pdf7986-lect 7.pdf
7986-lect 7.pdf
 
Module4 lex and yacc.ppt
Module4 lex and yacc.pptModule4 lex and yacc.ppt
Module4 lex and yacc.ppt
 
Lec 04 intro assembly
Lec 04 intro assemblyLec 04 intro assembly
Lec 04 intro assembly
 
Assignment2
Assignment2Assignment2
Assignment2
 
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operat...
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf
 
Al2ed chapter17
Al2ed chapter17Al2ed chapter17
Al2ed chapter17
 
module 4_ Lex_new.ppt
module 4_ Lex_new.pptmodule 4_ Lex_new.ppt
module 4_ Lex_new.ppt
 
Lex and Yacc.pdf
Lex and Yacc.pdfLex and Yacc.pdf
Lex and Yacc.pdf
 
Generacion de codigo ensamblado
Generacion de codigo ensambladoGeneracion de codigo ensamblado
Generacion de codigo ensamblado
 
LLVM
LLVMLLVM
LLVM
 
Alp 05
Alp 05Alp 05
Alp 05
 

Recently uploaded

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 

Recently uploaded (20)

Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 

Lex programming

  • 2. What is Lex? • Lex/Flex allows to specify a LA by specifying regular definitions to describe pattern for tokens. • The input notation for the lex tool is reffered as the Lex language and tool itself is the Lex tool. • Lex compiler transforms the input patterns into a TD and generates a code, in a file called lex.yy.c that simulates the TD.
  • 3. How Lex Works? lex.l lex.yy.c lex.yy.c a.out Input Stream Sequence of Tokens Lex Compiler C Compiler a.out
  • 4. Lex in Detail User Tokens Lex (regex+action) yylex() { } Optional Driver Code GCC
  • 5. Lex Specification A lex program has following form, declarations %% translation rules %% driver functions Note: %% is the smallest possible lex program
  • 6. Declarations A series of rules of the form name definitions E.g. DIGIT [0-9] COMMENTSTART “*” ID [a-zA-Z][a-zA-Z0-9]*
  • 7. Contd... The parts required to be copied to lex.yy.c should be written inside %{... %}. E.g. %{ //comment #include<stdio.h> %}
  • 8. Translation Rules Rules portion of the lex program contains a sequence of rules of the form, pattern action E.g. {letter}({letter}|{digit})* return id; {digit}+ return num; Note: action must begin in same line
  • 9. Sample Program %{ #include<stdio.h> %} dgt [0-9] %% {dgt}+ return atoi(yytext); %% void main() { int val,sum=0,n=0; while((val=yylex())>0){ sum=sum+val; n++; } If(n>0) printf(“avg=%dn”,sum/n); }
  • 10. Compiling Lex Installation: sudo apt-get install flex Step-1: lex demo.l Step-2: gcc lex.yy.c –ll Step-3: ./a.out Note: -ll is used to link the default yywarp().
  • 11. Lex Functions yylex(): each invocation scans the input where left off, returns 0 on EOF yytext: buffer holds the characters that match the pattern, char *yytext yyleng: length of lexeme matched, return an integer yyin: the input stream pointer, FILE * yyout: the output stream pointer, FILE *
  • 12. Conflict Resolution in Lex Conflict possible when more than one pattern matches the input or lexeme. Rules to avoid the conflict, a. The longest match is chosen b. If multiple rules match, rule enlisted top most is chosen
  • 13. Contd... E.g. Input: CS335 (CS) {printf(“Department”);} (CS)[0-9]3 {printf(“Course”);} [a-zA-Z]+[0-9]+ {printf(“AnythingElse”);} Output: Course E.g. Input: CS3351 Output: AnythingElse
  • 14. Some More Translation Rules [ tn] ; (represents no action) [a-z]+ ECHO; (display the matched lexeme) . (class of characters except n) [^a-zA-Z] (any character is not a letter) ab?c (ac or abc)