SlideShare una empresa de Scribd logo
1 de 25
Lex & Yacc
Prepared by:
Taha Malampattiwala 140050107052
Outline
• Lex :
• Theory
• Execution
• Example
• Yacc :
• Theory
• Description
• Example
• Lex & Yacc linking
2
Lex
• lex is a program (generator) that generates lexical analyzers,
(widely used on Unix).
• 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 for a lexical analyzer that scans for identifiers.
3
Lex
• A simple pattern: letter(letter|digit)*
• Regular expressions are translated by lex to a computer program that mimics
an FSA.
• This pattern matches a string of characters that begins with a single letter
followed by zero or more letters or digits.
4
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.
5
Lex
• The input structure to Lex
……..Definitions section……
%%
……Rules section……..
%%
……….C code section (subroutines)……..
6
7Operators
“  [ ] ^ - ? . * + | ( ) $ / { } % < >
• If they are to be used as text characters, an escape
should be used
$ = “$”
 = “”
• Every character but blank, tab (t), newline (n) and
the list above is always a text character
8Precedence of Operators
• Level of precedence
o Kleene closure (*), ?, +
o concatenation
o alternation (|)
• All operators are left associative.
• Ex: a*b|cd* = ((a*)b)|(c(d*))
Lex 9
• Pattern Matching Primitives
Lex 10
• Pattern Matching examples.
Lex
• Lex predefined variables.
11
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.
12
13An Overview of Lex
Lex
C compiler
a.out
Lex source
program
lex.yy.c
input
lex.yy.c
a.out
tokens
14Usage
• To run Lex on a source file, type
lex scanner.l
• It produces a file named lex.yy.c which is a C program for the
lexical analyzer.
• To compile lex.yy.c, type
cc lex.yy.c –ll
• To run the lexical analyzer program, type
./a.out < inputfile
15
Any Question So Far?
Yacc - Yet Another Compiler-Compiler
• Yacc reads the grammar and generate C code for a parser .
• 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)
• This known as bottom-up or shift-reduce parsing .
• Using stack for storing (LIFO).
16
Yacc
• Input to yacc is divided into three sections.
...definitions...
%%
...rules...
%%
... subroutines...
17
Yacc
• The definitions section consists of :
o token declarations .
o C code bracketed by “%{“ and “%}”.
• the rules section consists of :
o BNF grammar.
• the subroutines section consists of :
o user subroutines.
18
19
yacc
An Overview of YACC
(1) Parser generation time
YACC source (*.y)
y.tab.h
y.tab.c
C compiler/linker
(2) Compile time
y.tab.c a.out
a.out
(3) Run time
Token stream
Abstract
Syntax
Tree
y.output
20Lex v.s. Yacc
• Lex
oLex generates C code for a lexical analyzer, or scanner
oLex uses patterns that match strings in the input and
converts the strings to tokens
• Yacc
oYacc generates C code for syntax analyzer, or parser.
oYacc uses grammar rules that allow it to analyze tokens
from Lex and create a syntax tree.
Yacc & Lex in Together
• The grammar:
program -> program expr | ε
expr -> expr + expr | expr - expr | id
• Program and expr are nonterminals.
• Id are terminals (tokens returned by lex).
• expression may be :
o sum of two expressions .
o product of two expressions .
o Or an identifiers
21
Lex file 22
Yacc file 23
Linking lex & yacc 24
Lex Yacc
yylex() yyparse()
Lex source
(Lexical Rules)
Yacc source
(Grammar Rules)
Input
Parsed
Input
lex.yy.c y.tab.c
call
Lex & yacc

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical Analyzer
 
Compiler design syntax analysis
Compiler design syntax analysisCompiler design syntax analysis
Compiler design syntax analysis
 
1.Role lexical Analyzer
1.Role lexical Analyzer1.Role lexical Analyzer
1.Role lexical Analyzer
 
Compiler design lab programs
Compiler design lab programs Compiler design lab programs
Compiler design lab programs
 
Character set of c
Character set of cCharacter set of c
Character set of c
 
Lexical Analyzer Implementation
Lexical Analyzer ImplementationLexical Analyzer Implementation
Lexical Analyzer Implementation
 
Theory of automata and formal language
Theory of automata and formal languageTheory of automata and formal language
Theory of automata and formal language
 
Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
 
LR(1) and SLR(1) parsing
LR(1) and SLR(1) parsingLR(1) and SLR(1) parsing
LR(1) and SLR(1) parsing
 
Lexical analysis-using-lex
Lexical analysis-using-lexLexical analysis-using-lex
Lexical analysis-using-lex
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
LEX & YACC
LEX & YACCLEX & YACC
LEX & YACC
 
Compiler: Syntax Analysis
Compiler: Syntax AnalysisCompiler: Syntax Analysis
Compiler: Syntax Analysis
 
Finite Automata
Finite AutomataFinite Automata
Finite Automata
 
Operator precedence
Operator precedenceOperator precedence
Operator precedence
 
Bootstrapping in Compiler
Bootstrapping in CompilerBootstrapping in Compiler
Bootstrapping in Compiler
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
Specification-of-tokens
Specification-of-tokensSpecification-of-tokens
Specification-of-tokens
 
Data types in python
Data types in pythonData types in python
Data types in python
 

Similar a Lex & yacc

yacc installation & sample program exe.ppt
yacc installation & sample program exe.pptyacc installation & sample program exe.ppt
yacc installation & sample program exe.ppt
Koppala Guravaiah
 

Similar a Lex & yacc (20)

Lex and Yacc.pdf
Lex and Yacc.pdfLex and Yacc.pdf
Lex and Yacc.pdf
 
Module4 lex and yacc.ppt
Module4 lex and yacc.pptModule4 lex and yacc.ppt
Module4 lex and yacc.ppt
 
Lex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.pptLex and Yacc Tool M1.ppt
Lex and Yacc Tool M1.ppt
 
531AlmadhorAlwageed2010.ppt
531AlmadhorAlwageed2010.ppt531AlmadhorAlwageed2010.ppt
531AlmadhorAlwageed2010.ppt
 
10600122065_Animesh mani (CD).pdf
10600122065_Animesh mani (CD).pdf10600122065_Animesh mani (CD).pdf
10600122065_Animesh mani (CD).pdf
 
yacc installation & sample program exe.ppt
yacc installation & sample program exe.pptyacc installation & sample program exe.ppt
yacc installation & sample program exe.ppt
 
LANGUAGE TRANSLATOR
LANGUAGE TRANSLATORLANGUAGE TRANSLATOR
LANGUAGE TRANSLATOR
 
Lex programming
Lex programmingLex programming
Lex programming
 
Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabus
 
Yacc lex
Yacc lexYacc lex
Yacc lex
 
Lex
LexLex
Lex
 
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
 
Ch 2.pptx
Ch 2.pptxCh 2.pptx
Ch 2.pptx
 
Viva
VivaViva
Viva
 
Viva
VivaViva
Viva
 
module 4.pptx
module 4.pptxmodule 4.pptx
module 4.pptx
 
lex and yacc.pdf
lex and yacc.pdflex and yacc.pdf
lex and yacc.pdf
 
Compiler design and lexical analyser
Compiler design and lexical analyserCompiler design and lexical analyser
Compiler design and lexical analyser
 
module 4_ Lex_new.ppt
module 4_ Lex_new.pptmodule 4_ Lex_new.ppt
module 4_ Lex_new.ppt
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 

Más de Taha Malampatti

Más de Taha Malampatti (17)

Cultural heritage tourism
Cultural heritage tourismCultural heritage tourism
Cultural heritage tourism
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
Introduction to Android ppt
Introduction to Android pptIntroduction to Android ppt
Introduction to Android ppt
 
Intodcution to Html
Intodcution to HtmlIntodcution to Html
Intodcution to Html
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Cox and Kings Pvt Industrial Training
Cox and Kings Pvt Industrial TrainingCox and Kings Pvt Industrial Training
Cox and Kings Pvt Industrial Training
 
Steganography ppt
Steganography pptSteganography ppt
Steganography ppt
 
An application of 8085 register interfacing with LCD
An application  of 8085 register interfacing with LCDAn application  of 8085 register interfacing with LCD
An application of 8085 register interfacing with LCD
 
An application of 8085 register interfacing with LED
An application  of 8085 register interfacing with LEDAn application  of 8085 register interfacing with LED
An application of 8085 register interfacing with LED
 
Java Virtual Machine
Java Virtual MachineJava Virtual Machine
Java Virtual Machine
 
The sunsparc architecture
The sunsparc architectureThe sunsparc architecture
The sunsparc architecture
 
Orthogonal Projection
Orthogonal ProjectionOrthogonal Projection
Orthogonal Projection
 
Apple inc
Apple incApple inc
Apple inc
 
Blood donation
Blood donationBlood donation
Blood donation
 
Compressors and its applications
Compressors and its applicationsCompressors and its applications
Compressors and its applications
 
Laws Of Gravitation
Laws Of GravitationLaws Of Gravitation
Laws Of Gravitation
 

Último

1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 

Último (20)

kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 

Lex & yacc

  • 1. Lex & Yacc Prepared by: Taha Malampattiwala 140050107052
  • 2. Outline • Lex : • Theory • Execution • Example • Yacc : • Theory • Description • Example • Lex & Yacc linking 2
  • 3. Lex • lex is a program (generator) that generates lexical analyzers, (widely used on Unix). • 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 for a lexical analyzer that scans for identifiers. 3
  • 4. Lex • A simple pattern: letter(letter|digit)* • Regular expressions are translated by lex to a computer program that mimics an FSA. • This pattern matches a string of characters that begins with a single letter followed by zero or more letters or digits. 4
  • 5. 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. 5
  • 6. Lex • The input structure to Lex ……..Definitions section…… %% ……Rules section…….. %% ……….C code section (subroutines)…….. 6
  • 7. 7Operators “ [ ] ^ - ? . * + | ( ) $ / { } % < > • If they are to be used as text characters, an escape should be used $ = “$” = “” • Every character but blank, tab (t), newline (n) and the list above is always a text character
  • 8. 8Precedence of Operators • Level of precedence o Kleene closure (*), ?, + o concatenation o alternation (|) • All operators are left associative. • Ex: a*b|cd* = ((a*)b)|(c(d*))
  • 9. Lex 9 • Pattern Matching Primitives
  • 10. Lex 10 • Pattern Matching examples.
  • 11. Lex • Lex predefined variables. 11
  • 12. 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. 12
  • 13. 13An Overview of Lex Lex C compiler a.out Lex source program lex.yy.c input lex.yy.c a.out tokens
  • 14. 14Usage • To run Lex on a source file, type lex scanner.l • It produces a file named lex.yy.c which is a C program for the lexical analyzer. • To compile lex.yy.c, type cc lex.yy.c –ll • To run the lexical analyzer program, type ./a.out < inputfile
  • 16. Yacc - Yet Another Compiler-Compiler • Yacc reads the grammar and generate C code for a parser . • 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) • This known as bottom-up or shift-reduce parsing . • Using stack for storing (LIFO). 16
  • 17. Yacc • Input to yacc is divided into three sections. ...definitions... %% ...rules... %% ... subroutines... 17
  • 18. Yacc • The definitions section consists of : o token declarations . o C code bracketed by “%{“ and “%}”. • the rules section consists of : o BNF grammar. • the subroutines section consists of : o user subroutines. 18
  • 19. 19 yacc An Overview of YACC (1) Parser generation time YACC source (*.y) y.tab.h y.tab.c C compiler/linker (2) Compile time y.tab.c a.out a.out (3) Run time Token stream Abstract Syntax Tree y.output
  • 20. 20Lex v.s. Yacc • Lex oLex generates C code for a lexical analyzer, or scanner oLex uses patterns that match strings in the input and converts the strings to tokens • Yacc oYacc generates C code for syntax analyzer, or parser. oYacc uses grammar rules that allow it to analyze tokens from Lex and create a syntax tree.
  • 21. Yacc & Lex in Together • The grammar: program -> program expr | ε expr -> expr + expr | expr - expr | id • Program and expr are nonterminals. • Id are terminals (tokens returned by lex). • expression may be : o sum of two expressions . o product of two expressions . o Or an identifiers 21
  • 24. Linking lex & yacc 24 Lex Yacc yylex() yyparse() Lex source (Lexical Rules) Yacc source (Grammar Rules) Input Parsed Input lex.yy.c y.tab.c call