SlideShare a Scribd company logo
1 of 26
Download to read offline
By
Dr. Prem Nath
Associate Professor
Computer Science & Engineering Department,
H N B Garhwal University
(A Central University)
Lex And Yacc
1
Outline
▪ Lex:
▪ Theory
▪ Execution
▪ Example
▪ Yacc:
▪ Theory
▪ Description
▪ Example
▪ Lex & Yacc linking.
2
Lex
 Lex is a Programming Language or Tool that generates lexical
analyzers, (widely used on Unix with vi editor).
 It is mostly used with Yacc parser generator.
 Written by Eric Schmidt and Mike Lesk.
 It reads the input stream (specifying the lexical analyzer ) and
outputs source code implementing the lexical analyzer in the C
programming language.
 Lex will read patterns (regular expressions) then produces C
code.
3
4
LEX…
A Language for Specifying Lexical Analyzers
• Not only a table generator, but also allows “actions”
to associate with RE’s.
• Lex is widely used in the Unix community
• Lex is not efficient enough for production
compilers, however.
Lex…
Dr. Prem Nath 5
General Information:
• Input is stored in a file with *.l extension
• File consists of three main sections
• lex generates C function stored in lex.yy.c
Using Lex:
1) Specify words to be used as tokens (Extension of regular
expressions)
2) Run the lex utility on the source file to generate yylex( ),
a C function
3) Declares global variables char* yytext and int yyleng
6
Lex…
Lex
compiler
Lex
source
program
lex.l
lex.yy.c
C
compiler
lex.yy.c a.out
a.out
Input
stream
sequence
of tokens
Structure of Lex
Dr. Prem Nath 7
➢ Declaration (Variables, Constants, etc.)
➢ Translation Rules (Pattern and Action)
➢ Auxiliary Functions
/* Declaration
%%
/* Translation Rules
%%
Auxiliary Functions
Lex…
❑ Declaration
%{
#include<stdio.h>
int a, b;
%}
❑ Translation Rules
%%
Pattern1 {Action1}
Pattern2 {Action2}
%%
❑ Auxiliary Functions
int main()
{
…
yywrap();
} Dr. Prem Nath 8
Lex…
A simple pattern: letter(letter|digit)*
 Regular expressions are translated by Lex to a computer program that
mimics an FA.
 This pattern matches a string of characters that begins with a single
letter followed by zero or more letters or digits.
9
Lex…
 Some limitations, Lex cannot be used to recognize nested structures such
as parentheses, since it only has states and transitions between states.
 So, Lex is good at pattern matching, while Yacc is for more challenging
tasks.
10
Lex…
Pattern Matching Primitives
11
Lex…
Pattern Matching examples:
12
Lex…
Lex predefined variables:
13
Lex…
 Whitespace must separate the defining term and the associated expression.
 Code in the definitions section is simply copied as-is to the top of the generated C file and
must be bracketed with “%{“ and “%}” markers.
 substitutions in the rules section are surrounded by braces ({letter}) to distinguish them
from literals.
14
Lex…
/* Lex Program to Recognize Id, Keywords, and Number
%{ #include<stdio.h>
letter [a-z A-Z]
digit [0-9] %}
%%
id {letter}({letter}I{letter})*
number {digit}+(.{digit})+?(E[+, -]?{digit})+
%%
/* Auxiliary Functions
{id} {printf(“%s is an Identifier”, yytext);}
{if} {printf(“%s is a Keyword”, yytext);}
{number} {printf(“%s is a Number”, yytext);}
Dr. Prem Nath 15
Yacc
➢ Yacc reads the grammar and generate C code for a
parser .
➢ Parser Generator (Compiler to Compiler)
➢ Files are with .y extension
◦ Grammars written in Backus Naur Form (BNF)
◦ BNF grammar used to express context-free languages .
◦ e.g. to parse an expression , do reverse operation(
reducing the expression)
◦ LALR(1) Parser (Look Ahead Left to Right One)
◦ Using stack for storing (LIFO)
◦ Written by Stefen C Johnson
16
Yacc…
Input to Yacc is divided into three sections.
... definitions ...
%%
... rules ...
%%
... subroutines ...
17
Yacc…
 The definitions section consists of:
◦ token declarations .
◦ C code bracketed by “%{“ and “%}”.
◦ the rules section consists of:
 BNF grammar .
 the subroutines section consists of:
◦ user subroutines .
18
Linking lex and Yacc
19
CC: C Compiler
20
Linking lex and Yacc…
Yacc
Compiler
Lex
a.out
parse.y
y.tab.c
(yyparse)
scan.l
source
program
output
C
Compiler
lex.yy.c
a.out
Included
Linking lex and Yacc…
21
• yyval: Vallue Associated With Token
• yytext: Pointer to Input String
Linking lex and Yacc…
22
$$: First Symbol of the Body
$i: ith Symbol of the Body
Linking lex and Yacc…
❑Construct a Lexical Analyzer and Parser for
Language L={anbn: n ≥1}.
/* Lex Tool ab.l
%{
#include<y.tab.h>
%}
%%
[a] {return a;}
[b] {return b;}
[n] {return 0;}
%%
/* No Main Function
Dr. Prem Nath 23
Linking lex and Yacc…
/* Yacc Tool cd.y
%{
#include<stdio.h>
#include<stdlib.h>
%}
% token a b
%%
start: S ‘n’ {return 0;}
S: aSb {$S=$1$2;}
%%
Dr. Prem Nath 24
Linking lex and Yacc…
/* Yacc Tool CD.y
/* Main Function
int main( )
{
printf(“Enter a String:”);
if(yyparse= = 0)
printf(“Valid String”);
yyerror( )
{
printf(“Invalid String”);
exit(0);
}
int yywrap( )
{
return 1;
}
}
Dr. Prem Nath 25
26
Thanks

More Related Content

Similar to Lex and Yacc: Tools for Specifying Lexical and Syntactic Analyzers

Similar to Lex and Yacc: Tools for Specifying Lexical and Syntactic Analyzers (20)

Viva
VivaViva
Viva
 
Viva
VivaViva
Viva
 
Handout#02
Handout#02Handout#02
Handout#02
 
Lex programming
Lex programmingLex programming
Lex programming
 
LANGUAGE PROCESSOR
LANGUAGE PROCESSORLANGUAGE PROCESSOR
LANGUAGE PROCESSOR
 
Lexical Analyzers and Parsers
Lexical Analyzers and ParsersLexical Analyzers and Parsers
Lexical Analyzers and Parsers
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
11700220036.pdf
11700220036.pdf11700220036.pdf
11700220036.pdf
 
Compiler design Project
Compiler design ProjectCompiler design Project
Compiler design Project
 
Language for specifying lexical Analyzer
Language for specifying lexical AnalyzerLanguage for specifying lexical Analyzer
Language for specifying lexical Analyzer
 
Compiler design and lexical analyser
Compiler design and lexical analyserCompiler design and lexical analyser
Compiler design and lexical analyser
 
Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabus
 
Lexyacc
LexyaccLexyacc
Lexyacc
 
Lexyacc
LexyaccLexyacc
Lexyacc
 
Compiler Engineering Lab#5 : Symbol Table, Flex Tool
Compiler Engineering Lab#5 : Symbol Table, Flex ToolCompiler Engineering Lab#5 : Symbol Table, Flex Tool
Compiler Engineering Lab#5 : Symbol Table, Flex Tool
 
CD UNIT-1.3 LEX PPT.pptx
CD UNIT-1.3 LEX PPT.pptxCD UNIT-1.3 LEX PPT.pptx
CD UNIT-1.3 LEX PPT.pptx
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Yacc lex
Yacc lexYacc lex
Yacc lex
 
Group 19 CD project
Group 19 CD projectGroup 19 CD project
Group 19 CD project
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 

Recently uploaded

Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
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
 
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
 
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
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
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
 

Recently uploaded (20)

young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
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
 
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
 
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
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
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
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
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
 

Lex and Yacc: Tools for Specifying Lexical and Syntactic Analyzers

  • 1. By Dr. Prem Nath Associate Professor Computer Science & Engineering Department, H N B Garhwal University (A Central University) Lex And Yacc 1
  • 2. Outline ▪ Lex: ▪ Theory ▪ Execution ▪ Example ▪ Yacc: ▪ Theory ▪ Description ▪ Example ▪ Lex & Yacc linking. 2
  • 3. Lex  Lex is a Programming Language or Tool that generates lexical analyzers, (widely used on Unix with vi editor).  It is mostly used with Yacc parser generator.  Written by Eric Schmidt and Mike Lesk.  It reads the input stream (specifying the lexical analyzer ) and outputs source code implementing the lexical analyzer in the C programming language.  Lex will read patterns (regular expressions) then produces C code. 3
  • 4. 4 LEX… A Language for Specifying Lexical Analyzers • Not only a table generator, but also allows “actions” to associate with RE’s. • Lex is widely used in the Unix community • Lex is not efficient enough for production compilers, however.
  • 5. Lex… Dr. Prem Nath 5 General Information: • Input is stored in a file with *.l extension • File consists of three main sections • lex generates C function stored in lex.yy.c Using Lex: 1) Specify words to be used as tokens (Extension of regular expressions) 2) Run the lex utility on the source file to generate yylex( ), a C function 3) Declares global variables char* yytext and int yyleng
  • 7. Structure of Lex Dr. Prem Nath 7 ➢ Declaration (Variables, Constants, etc.) ➢ Translation Rules (Pattern and Action) ➢ Auxiliary Functions /* Declaration %% /* Translation Rules %% Auxiliary Functions
  • 8. Lex… ❑ Declaration %{ #include<stdio.h> int a, b; %} ❑ Translation Rules %% Pattern1 {Action1} Pattern2 {Action2} %% ❑ Auxiliary Functions int main() { … yywrap(); } Dr. Prem Nath 8
  • 9. Lex… A simple pattern: letter(letter|digit)*  Regular expressions are translated by Lex to a computer program that mimics an FA.  This pattern matches a string of characters that begins with a single letter followed by zero or more letters or digits. 9
  • 10. Lex…  Some limitations, Lex cannot be used to recognize nested structures such as parentheses, since it only has states and transitions between states.  So, Lex is good at pattern matching, while Yacc is for more challenging tasks. 10
  • 14. Lex…  Whitespace must separate the defining term and the associated expression.  Code in the definitions section is simply copied as-is to the top of the generated C file and must be bracketed with “%{“ and “%}” markers.  substitutions in the rules section are surrounded by braces ({letter}) to distinguish them from literals. 14
  • 15. Lex… /* Lex Program to Recognize Id, Keywords, and Number %{ #include<stdio.h> letter [a-z A-Z] digit [0-9] %} %% id {letter}({letter}I{letter})* number {digit}+(.{digit})+?(E[+, -]?{digit})+ %% /* Auxiliary Functions {id} {printf(“%s is an Identifier”, yytext);} {if} {printf(“%s is a Keyword”, yytext);} {number} {printf(“%s is a Number”, yytext);} Dr. Prem Nath 15
  • 16. Yacc ➢ Yacc reads the grammar and generate C code for a parser . ➢ Parser Generator (Compiler to Compiler) ➢ Files are with .y extension ◦ Grammars written in Backus Naur Form (BNF) ◦ BNF grammar used to express context-free languages . ◦ e.g. to parse an expression , do reverse operation( reducing the expression) ◦ LALR(1) Parser (Look Ahead Left to Right One) ◦ Using stack for storing (LIFO) ◦ Written by Stefen C Johnson 16
  • 17. Yacc… Input to Yacc is divided into three sections. ... definitions ... %% ... rules ... %% ... subroutines ... 17
  • 18. Yacc…  The definitions section consists of: ◦ token declarations . ◦ C code bracketed by “%{“ and “%}”. ◦ the rules section consists of:  BNF grammar .  the subroutines section consists of: ◦ user subroutines . 18
  • 19. Linking lex and Yacc 19 CC: C Compiler
  • 20. 20 Linking lex and Yacc… Yacc Compiler Lex a.out parse.y y.tab.c (yyparse) scan.l source program output C Compiler lex.yy.c a.out Included
  • 21. Linking lex and Yacc… 21 • yyval: Vallue Associated With Token • yytext: Pointer to Input String
  • 22. Linking lex and Yacc… 22 $$: First Symbol of the Body $i: ith Symbol of the Body
  • 23. Linking lex and Yacc… ❑Construct a Lexical Analyzer and Parser for Language L={anbn: n ≥1}. /* Lex Tool ab.l %{ #include<y.tab.h> %} %% [a] {return a;} [b] {return b;} [n] {return 0;} %% /* No Main Function Dr. Prem Nath 23
  • 24. Linking lex and Yacc… /* Yacc Tool cd.y %{ #include<stdio.h> #include<stdlib.h> %} % token a b %% start: S ‘n’ {return 0;} S: aSb {$S=$1$2;} %% Dr. Prem Nath 24
  • 25. Linking lex and Yacc… /* Yacc Tool CD.y /* Main Function int main( ) { printf(“Enter a String:”); if(yyparse= = 0) printf(“Valid String”); yyerror( ) { printf(“Invalid String”); exit(0); } int yywrap( ) { return 1; } } Dr. Prem Nath 25