SlideShare a Scribd company logo
Compiler Design
Lex & Flex
Lexical Analyzer Generator
• Lex is a program generator designed for lexical
processing of character input streams.
• Lex source is a table of regular expressions and
corresponding program fragments.
• The table is translated to a program which reads an
input stream, copying it to an output stream and
partitioning the input into strings which match the
given expressions.
• The compiler writer uses specialized tools that
produce components that can easily be integrated
in the compiler and help implement various phases
of a compiler.
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
2
Contd…..
• The program fragments written by the user are executed in the
order in which the corresponding regular expressions occur in
the input stream.
• Lex can generate analyzers in either “C” or “Ratfor”, a language
which can be translated automatically to portable Fortran.
• Lex is a program designed to generate scanners, also known as
tokenizers, which recognize lexical patterns in text.
• Lex is an acronym that stands for "lexical analyzer generator.
• It is intended primarily for Unix-based systems.
• The code for Lex was originally developed by Eric Schmidt and
Mike Lesk.
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
3
Contd……
• Lex can be used with a parser generator to perform lexical
analysis.
• It is easy, for example, to interface Lex and Yacc, an open
source program that generates code for the parser in the C
programming language.
• Lex can perform simple transformations by itself but its main
purpose is to facilitate lexical analysis.
• The processing of character sequences such as source code
to produce symbol sequences called tokens for use as input
to other programs such as parsers.
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
4
Contd……
Processes in lexical analyzers
– Scanning
• Pre-processing
– Strip out comments and white space
– Macro functions
– Correlating error messages from compiler with
source program
• A line number can be associated with an error
message
– Lexical analysis
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
5
Contd……
Terms of the lexical analyzer
– Token
• Types of words in source program
• Keywords, operators, identifiers, constants,
literal strings, punctuation symbols(such as
commas, semicolons)
– Lexeme
• Actual words in source program
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
6
Contd…..
– Pattern
• A rule describing the set of lexemes that can
represent a particular token in source program
• Relation {<.<=,>,>=,==,<>}
 Lexical Errors
– Deleting an extraneous character
– Inserting a missing character
– Replacing an incorrect character by a correct character
– Pre-scanning
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
7
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
8
Compilation Sequence
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
9
What is Lex?
• The main job of a lexical analyzer (scanner) is
to break up an input stream into more usable
elements (tokens)
a = b + c * d;
ID ASSIGN ID PLUS ID MULT ID SEMI
• Lex is an utility to help you rapidly generate
your scanners
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
10
Lex – Lexical Analyzer
• Lexical analyzers tokenize input streams
• Tokens are the terminals of a language
– English
• words, punctuation marks, …
– Programming language
• Identifiers, operators, keywords, …
• Regular expressions define terminals/tokens
• Some examples are
• Flex lexical analyser
• Yacc
• Ragel
• PLY (Python Lex-Yacc)
1/31/2017
Contd…..
• Lex turns the user's expressions and actions (called source in this memo)
into the host general-purpose language.
• the generated program is named yylex.
• The yylex program will recognize expressions in a stream (called input in
this memo) and perform the specified actions for each expression as it is
detected. See the below fig….
Source -> -> yylex
Input -> -> Output
Fig. An overview of Lex
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
11
Lex
yylex
yylex()
• It implies the main entry point for lex.
• Reads the input stream generates tokens, returns
0 at the end of input stream.
• It is called to invoke the lexer or scanner.
• Each time yylex() is called, the scanner continues
processing the input from where it last left off.
• Eg:
• yyout
• yyin
• yywrap
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
12
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
Structure of a Lex file
• The structure of a Lex file is intentionally similar to
that of a yacc file.
• files are divided into three sections, separated by
lines that contain only two percent signs, as follows:
• Definition section
%%
• Rules section
%%
• C code section
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
14
Contd…..
• The definition section defines macros and imports header files
written in C. It is also possible to write any C code here, which
will be copied verbatim into the generated source file.
• The rules section associates regular expression patterns with
C statements. When the lexer sees text in the input matching a
given pattern, it will execute the associated C code.
• The C code section contains C statements and functions that are
copied verbatim to the generated source file. These statements
presumably contain code called by the rules in the rules section.
In large programs it is more convenient to place this code in a
separate file linked in at compile time.
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
15
Example
• The following is an example Lex file for the flex version of Lex.
• It recognizes strings of numbers (positive integers) in the input,
and simply prints them out.
/*** Definition section ***/
%{
/* C code to be copied */
#include <stdio.h>
%}
/* This tells flex to read only one input file
*/
%option noyywrap
%%
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
16
Contd……
/*** Rules section ***/
/* [0-9]+ matches a string of one or more digits */
[0-9]+ {
/* yytext is a string containing the matched text.
*/
printf("Saw an integer: %sn", yytext);
}
.|n { /* Ignore all other characters. */
}
%%
/*** C Code section ***/
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
17
Contd…..
int main(void)
{
/* Call the lexer, then quit. */
yylex();
return 0;
}
If this input is given to flex, it will be converted into a C file, lex.yy.c.
This can be compiled into an executable which matches and
outputs strings of integers. Eg.
abc123z.!&*2gj6
the program will print: Saw an integer: 123
Saw an integer: 2
Saw an integer: 6
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
18
Flex, A fast scanner generator
• flex is a tool for generating scanners:
• programs which recognized lexical patterns in text.
• flex reads the given input files,
• or its standard input if no file names are given, for a description
of a scanner to generate.
• The description is in the form of pairs of regular expressions and
C code, called rules.
• flex generates as output a C source file, `lex.yy.c', which defines
a routine `yylex()'.
• This file is compiled and linked with the `-lfl' library to produce
an executable.
• When the executable is run, it analyzes its input for occurrences
of the regular expressions.
• Whenever it finds one, it executes the corresponding C code.
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
19
Contd…
• Flex (fast lexical analyzer generator) is a free and
open-source software alternative to lex.
• It is a computer program that generates lexical
analyzers (also known as "scanners" or "lexers").
• Flex was written in C by Vern Paxson around 1987.
• He was translating a Ratfor generator.
• It had been led by Jef Poskanzer.
• The tokens recognized are: '+', '-', '*', '/', '=', '(', ')', ',',
';', '.', ':=', '<', '<=', '<>', '>', '>=';
• numbers: 0-9 {0-9}; identifiers: a-zA-Z {a-zA-Z0-9} and
keywords: begin, call, const, do, end, if, odd, procedur
e, then, var, while.
1/31/2017
ANKUR SRIVASTAVA ASSISTANT
PROFESSOR JIT
20
Thanks

More Related Content

What's hot

Types of Parser
Types of ParserTypes of Parser
Types of Parser
SomnathMore3
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up Parsing
Gerwin Ocsena
 
Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Lexical Analysis - Compiler design
Lexical Analysis - Compiler design
Aman Sharma
 
Compiler Design
Compiler DesignCompiler Design
Compiler DesignMir Majid
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
Kuppusamy P
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
Akshaya Arunan
 
The role of the parser and Error recovery strategies ppt in compiler design
The role of the parser and Error recovery strategies ppt in compiler designThe role of the parser and Error recovery strategies ppt in compiler design
The role of the parser and Error recovery strategies ppt in compiler design
Sadia Akter
 
A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical Analyzer
Archana Gopinath
 
Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler Design
Akhil Kaushik
 
Compiler Chapter 1
Compiler Chapter 1Compiler Chapter 1
Compiler Chapter 1
Huawei Technologies
 
Parsing
ParsingParsing
Parsing
khush_boo31
 
RECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSINGRECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSING
Jothi Lakshmi
 
Input-Buffering
Input-BufferingInput-Buffering
Input-Buffering
Dattatray Gandhmal
 
Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)
Tasif Tanzim
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
Dr. C.V. Suresh Babu
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
Prankit Mishra
 
Chapter 5 Syntax Directed Translation
Chapter 5   Syntax Directed TranslationChapter 5   Syntax Directed Translation
Chapter 5 Syntax Directed Translation
Radhakrishnan Chinnusamy
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
ASHOK KUMAR REDDY
 
Error Detection & Recovery
Error Detection & RecoveryError Detection & Recovery
Error Detection & Recovery
Akhil Kaushik
 
COMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed TranslationCOMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed Translation
Jyothishmathi Institute of Technology and Science Karimnagar
 

What's hot (20)

Types of Parser
Types of ParserTypes of Parser
Types of Parser
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up Parsing
 
Lexical Analysis - Compiler design
Lexical Analysis - Compiler design Lexical Analysis - Compiler design
Lexical Analysis - Compiler design
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
 
The role of the parser and Error recovery strategies ppt in compiler design
The role of the parser and Error recovery strategies ppt in compiler designThe role of the parser and Error recovery strategies ppt in compiler design
The role of the parser and Error recovery strategies ppt in compiler design
 
A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical Analyzer
 
Parsing in Compiler Design
Parsing in Compiler DesignParsing in Compiler Design
Parsing in Compiler Design
 
Compiler Chapter 1
Compiler Chapter 1Compiler Chapter 1
Compiler Chapter 1
 
Parsing
ParsingParsing
Parsing
 
RECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSINGRECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSING
 
Input-Buffering
Input-BufferingInput-Buffering
Input-Buffering
 
Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)   Intermediate code generation (Compiler Design)
Intermediate code generation (Compiler Design)
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Chapter 5 Syntax Directed Translation
Chapter 5   Syntax Directed TranslationChapter 5   Syntax Directed Translation
Chapter 5 Syntax Directed Translation
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Error Detection & Recovery
Error Detection & RecoveryError Detection & Recovery
Error Detection & Recovery
 
COMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed TranslationCOMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed Translation
 

Viewers also liked

Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
Ashwini Sonawane
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manualSami Said
 
Minimization of dfa
Minimization of dfaMinimization of dfa
Minimization of dfa
BBDITM LUCKNOW
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
Flex y Bison
Flex y BisonFlex y Bison
Flex y Bison
Bryant Arellano
 
Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabus
JK Knowledge
 
Passescd
PassescdPassescd
Passescd
BBDITM LUCKNOW
 
Chapter Five(2)
Chapter Five(2)Chapter Five(2)
Chapter Five(2)bolovv
 
Yacc lex
Yacc lexYacc lex
Yacc lex
915086731
 
Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)
omercomail
 
Compiler design tutorial
Compiler design tutorialCompiler design tutorial
Compiler design tutorial
Varsha Shukla
 
Compiler design
Compiler designCompiler design
Compiler design
Ashraf Hossain
 
Data Locality
Data LocalityData Locality
Data Locality
Syam Lal
 
System Programming Unit IV
System Programming Unit IVSystem Programming Unit IV
System Programming Unit IVManoj Patil
 
C program compiler presentation
C program compiler presentationC program compiler presentation
C program compiler presentation
Rigvendra Kumar Vardhan
 

Viewers also liked (20)

Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Cd2 [autosaved]
Cd2 [autosaved]Cd2 [autosaved]
Cd2 [autosaved]
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
Minimization of dfa
Minimization of dfaMinimization of dfa
Minimization of dfa
 
More on Lex
More on LexMore on Lex
More on Lex
 
Flex y Bison
Flex y BisonFlex y Bison
Flex y Bison
 
Ch4c
Ch4cCh4c
Ch4c
 
Cimplementation
CimplementationCimplementation
Cimplementation
 
Yacc topic beyond syllabus
Yacc   topic beyond syllabusYacc   topic beyond syllabus
Yacc topic beyond syllabus
 
Passescd
PassescdPassescd
Passescd
 
Chapter Five(2)
Chapter Five(2)Chapter Five(2)
Chapter Five(2)
 
Bottomupparser
BottomupparserBottomupparser
Bottomupparser
 
Lexyacc
LexyaccLexyacc
Lexyacc
 
Yacc lex
Yacc lexYacc lex
Yacc lex
 
Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)
 
Compiler design tutorial
Compiler design tutorialCompiler design tutorial
Compiler design tutorial
 
Compiler design
Compiler designCompiler design
Compiler design
 
Data Locality
Data LocalityData Locality
Data Locality
 
System Programming Unit IV
System Programming Unit IVSystem Programming Unit IV
System Programming Unit IV
 
C program compiler presentation
C program compiler presentationC program compiler presentation
C program compiler presentation
 

Similar to Lex

11700220036.pdf
11700220036.pdf11700220036.pdf
11700220036.pdf
SouvikRoy149
 
COMPILER CONSTRUCTION KU 1.pptx
COMPILER CONSTRUCTION KU 1.pptxCOMPILER CONSTRUCTION KU 1.pptx
COMPILER CONSTRUCTION KU 1.pptx
Rossy719186
 
1._Introduction_.pptx
1._Introduction_.pptx1._Introduction_.pptx
1._Introduction_.pptx
Anbarasan Radhakrishnan R
 
LEX & YACC
LEX & YACCLEX & YACC
LEX & YACC
Mahbubur Rahman
 
Compier Design_Unit I.ppt
Compier Design_Unit I.pptCompier Design_Unit I.ppt
Compier Design_Unit I.ppt
sivaganesh293
 
Compier Design_Unit I.ppt
Compier Design_Unit I.pptCompier Design_Unit I.ppt
Compier Design_Unit I.ppt
sivaganesh293
 
Compiler construction tools
Compiler construction toolsCompiler construction tools
Compiler construction tools
Akhil Kaushik
 
COMPILER DESIGN PPTS.pptx
COMPILER DESIGN PPTS.pptxCOMPILER DESIGN PPTS.pptx
COMPILER DESIGN PPTS.pptx
MUSHAMHARIKIRAN6737
 
Plc part 2
Plc  part 2Plc  part 2
Plc part 2
Taymoor Nazmy
 
Compier Design_Unit I_SRM.ppt
Compier Design_Unit I_SRM.pptCompier Design_Unit I_SRM.ppt
Compier Design_Unit I_SRM.ppt
Apoorv Diwan
 
Chapter 1.pptx
Chapter 1.pptxChapter 1.pptx
Chapter 1.pptx
NesredinTeshome1
 
CD U1-5.pptx
CD U1-5.pptxCD U1-5.pptx
CD U1-5.pptx
Himajanaidu2
 
Module4 lex and yacc.ppt
Module4 lex and yacc.pptModule4 lex and yacc.ppt
Module4 lex and yacc.ppt
ProddaturNagaVenkata
 
1 compiler outline
1 compiler outline1 compiler outline
1 compiler outline
ASHOK KUMAR REDDY
 
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
MashaelQ
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
Akhil Kaushik
 
The Phases of a Compiler
The Phases of a CompilerThe Phases of a Compiler
The Phases of a Compiler
Radhika Talaviya
 
Compiler Design.pptx
Compiler Design.pptxCompiler Design.pptx
Compiler Design.pptx
SouvikRoy149
 

Similar to Lex (20)

11700220036.pdf
11700220036.pdf11700220036.pdf
11700220036.pdf
 
COMPILER CONSTRUCTION KU 1.pptx
COMPILER CONSTRUCTION KU 1.pptxCOMPILER CONSTRUCTION KU 1.pptx
COMPILER CONSTRUCTION KU 1.pptx
 
1._Introduction_.pptx
1._Introduction_.pptx1._Introduction_.pptx
1._Introduction_.pptx
 
LEX & YACC
LEX & YACCLEX & YACC
LEX & YACC
 
Compier Design_Unit I.ppt
Compier Design_Unit I.pptCompier Design_Unit I.ppt
Compier Design_Unit I.ppt
 
Compier Design_Unit I.ppt
Compier Design_Unit I.pptCompier Design_Unit I.ppt
Compier Design_Unit I.ppt
 
Compiler construction tools
Compiler construction toolsCompiler construction tools
Compiler construction tools
 
COMPILER DESIGN PPTS.pptx
COMPILER DESIGN PPTS.pptxCOMPILER DESIGN PPTS.pptx
COMPILER DESIGN PPTS.pptx
 
Plc part 2
Plc  part 2Plc  part 2
Plc part 2
 
Compier Design_Unit I_SRM.ppt
Compier Design_Unit I_SRM.pptCompier Design_Unit I_SRM.ppt
Compier Design_Unit I_SRM.ppt
 
Chapter 1.pptx
Chapter 1.pptxChapter 1.pptx
Chapter 1.pptx
 
CD U1-5.pptx
CD U1-5.pptxCD U1-5.pptx
CD U1-5.pptx
 
LANGUAGE TRANSLATOR
LANGUAGE TRANSLATORLANGUAGE TRANSLATOR
LANGUAGE TRANSLATOR
 
Module4 lex and yacc.ppt
Module4 lex and yacc.pptModule4 lex and yacc.ppt
Module4 lex and yacc.ppt
 
1 compiler outline
1 compiler outline1 compiler outline
1 compiler outline
 
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
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
 
Compiler1
Compiler1Compiler1
Compiler1
 
The Phases of a Compiler
The Phases of a CompilerThe Phases of a Compiler
The Phases of a Compiler
 
Compiler Design.pptx
Compiler Design.pptxCompiler Design.pptx
Compiler Design.pptx
 

More from BBDITM LUCKNOW

Unit 5 cspc
Unit 5 cspcUnit 5 cspc
Unit 5 cspc
BBDITM LUCKNOW
 
Unit 4 cspc
Unit 4 cspcUnit 4 cspc
Unit 4 cspc
BBDITM LUCKNOW
 
Unit3 cspc
Unit3 cspcUnit3 cspc
Unit3 cspc
BBDITM LUCKNOW
 
Cse ppt 2018
Cse ppt 2018Cse ppt 2018
Cse ppt 2018
BBDITM LUCKNOW
 
Binary system ppt
Binary system pptBinary system ppt
Binary system ppt
BBDITM LUCKNOW
 
Unit 4 ca-input-output
Unit 4 ca-input-outputUnit 4 ca-input-output
Unit 4 ca-input-output
BBDITM LUCKNOW
 
Unit 3 ca-memory
Unit 3 ca-memoryUnit 3 ca-memory
Unit 3 ca-memory
BBDITM LUCKNOW
 
Unit 2 ca- control unit
Unit 2 ca- control unitUnit 2 ca- control unit
Unit 2 ca- control unit
BBDITM LUCKNOW
 
Unit 1 ca-introduction
Unit 1 ca-introductionUnit 1 ca-introduction
Unit 1 ca-introduction
BBDITM LUCKNOW
 
Bnf and ambiquity
Bnf and ambiquityBnf and ambiquity
Bnf and ambiquity
BBDITM LUCKNOW
 
Compiler unit 4
Compiler unit 4Compiler unit 4
Compiler unit 4
BBDITM LUCKNOW
 
Compiler unit 2&3
Compiler unit 2&3Compiler unit 2&3
Compiler unit 2&3
BBDITM LUCKNOW
 
Compiler unit 1
Compiler unit 1Compiler unit 1
Compiler unit 1
BBDITM LUCKNOW
 
Compiler unit 5
Compiler  unit 5Compiler  unit 5
Compiler unit 5
BBDITM LUCKNOW
 
Cspc final
Cspc finalCspc final
Cspc final
BBDITM LUCKNOW
 
Validation based protocol
Validation based protocolValidation based protocol
Validation based protocol
BBDITM LUCKNOW
 

More from BBDITM LUCKNOW (16)

Unit 5 cspc
Unit 5 cspcUnit 5 cspc
Unit 5 cspc
 
Unit 4 cspc
Unit 4 cspcUnit 4 cspc
Unit 4 cspc
 
Unit3 cspc
Unit3 cspcUnit3 cspc
Unit3 cspc
 
Cse ppt 2018
Cse ppt 2018Cse ppt 2018
Cse ppt 2018
 
Binary system ppt
Binary system pptBinary system ppt
Binary system ppt
 
Unit 4 ca-input-output
Unit 4 ca-input-outputUnit 4 ca-input-output
Unit 4 ca-input-output
 
Unit 3 ca-memory
Unit 3 ca-memoryUnit 3 ca-memory
Unit 3 ca-memory
 
Unit 2 ca- control unit
Unit 2 ca- control unitUnit 2 ca- control unit
Unit 2 ca- control unit
 
Unit 1 ca-introduction
Unit 1 ca-introductionUnit 1 ca-introduction
Unit 1 ca-introduction
 
Bnf and ambiquity
Bnf and ambiquityBnf and ambiquity
Bnf and ambiquity
 
Compiler unit 4
Compiler unit 4Compiler unit 4
Compiler unit 4
 
Compiler unit 2&3
Compiler unit 2&3Compiler unit 2&3
Compiler unit 2&3
 
Compiler unit 1
Compiler unit 1Compiler unit 1
Compiler unit 1
 
Compiler unit 5
Compiler  unit 5Compiler  unit 5
Compiler unit 5
 
Cspc final
Cspc finalCspc final
Cspc final
 
Validation based protocol
Validation based protocolValidation based protocol
Validation based protocol
 

Recently uploaded

Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 

Recently uploaded (20)

Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 

Lex

  • 2. Lexical Analyzer Generator • Lex is a program generator designed for lexical processing of character input streams. • Lex source is a table of regular expressions and corresponding program fragments. • The table is translated to a program which reads an input stream, copying it to an output stream and partitioning the input into strings which match the given expressions. • The compiler writer uses specialized tools that produce components that can easily be integrated in the compiler and help implement various phases of a compiler. 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 2
  • 3. Contd….. • The program fragments written by the user are executed in the order in which the corresponding regular expressions occur in the input stream. • Lex can generate analyzers in either “C” or “Ratfor”, a language which can be translated automatically to portable Fortran. • Lex is a program designed to generate scanners, also known as tokenizers, which recognize lexical patterns in text. • Lex is an acronym that stands for "lexical analyzer generator. • It is intended primarily for Unix-based systems. • The code for Lex was originally developed by Eric Schmidt and Mike Lesk. 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 3
  • 4. Contd…… • Lex can be used with a parser generator to perform lexical analysis. • It is easy, for example, to interface Lex and Yacc, an open source program that generates code for the parser in the C programming language. • Lex can perform simple transformations by itself but its main purpose is to facilitate lexical analysis. • The processing of character sequences such as source code to produce symbol sequences called tokens for use as input to other programs such as parsers. 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 4
  • 5. Contd…… Processes in lexical analyzers – Scanning • Pre-processing – Strip out comments and white space – Macro functions – Correlating error messages from compiler with source program • A line number can be associated with an error message – Lexical analysis 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 5
  • 6. Contd…… Terms of the lexical analyzer – Token • Types of words in source program • Keywords, operators, identifiers, constants, literal strings, punctuation symbols(such as commas, semicolons) – Lexeme • Actual words in source program 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 6
  • 7. Contd….. – Pattern • A rule describing the set of lexemes that can represent a particular token in source program • Relation {<.<=,>,>=,==,<>}  Lexical Errors – Deleting an extraneous character – Inserting a missing character – Replacing an incorrect character by a correct character – Pre-scanning 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 7
  • 8. ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 8 Compilation Sequence 1/31/2017
  • 9. ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 9 What is Lex? • The main job of a lexical analyzer (scanner) is to break up an input stream into more usable elements (tokens) a = b + c * d; ID ASSIGN ID PLUS ID MULT ID SEMI • Lex is an utility to help you rapidly generate your scanners 1/31/2017
  • 10. ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 10 Lex – Lexical Analyzer • Lexical analyzers tokenize input streams • Tokens are the terminals of a language – English • words, punctuation marks, … – Programming language • Identifiers, operators, keywords, … • Regular expressions define terminals/tokens • Some examples are • Flex lexical analyser • Yacc • Ragel • PLY (Python Lex-Yacc) 1/31/2017
  • 11. Contd….. • Lex turns the user's expressions and actions (called source in this memo) into the host general-purpose language. • the generated program is named yylex. • The yylex program will recognize expressions in a stream (called input in this memo) and perform the specified actions for each expression as it is detected. See the below fig…. Source -> -> yylex Input -> -> Output Fig. An overview of Lex 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 11 Lex yylex
  • 12. yylex() • It implies the main entry point for lex. • Reads the input stream generates tokens, returns 0 at the end of input stream. • It is called to invoke the lexer or scanner. • Each time yylex() is called, the scanner continues processing the input from where it last left off. • Eg: • yyout • yyin • yywrap 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 12
  • 13. 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
  • 14. Structure of a Lex file • The structure of a Lex file is intentionally similar to that of a yacc file. • files are divided into three sections, separated by lines that contain only two percent signs, as follows: • Definition section %% • Rules section %% • C code section 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 14
  • 15. Contd….. • The definition section defines macros and imports header files written in C. It is also possible to write any C code here, which will be copied verbatim into the generated source file. • The rules section associates regular expression patterns with C statements. When the lexer sees text in the input matching a given pattern, it will execute the associated C code. • The C code section contains C statements and functions that are copied verbatim to the generated source file. These statements presumably contain code called by the rules in the rules section. In large programs it is more convenient to place this code in a separate file linked in at compile time. 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 15
  • 16. Example • The following is an example Lex file for the flex version of Lex. • It recognizes strings of numbers (positive integers) in the input, and simply prints them out. /*** Definition section ***/ %{ /* C code to be copied */ #include <stdio.h> %} /* This tells flex to read only one input file */ %option noyywrap %% 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 16
  • 17. Contd…… /*** Rules section ***/ /* [0-9]+ matches a string of one or more digits */ [0-9]+ { /* yytext is a string containing the matched text. */ printf("Saw an integer: %sn", yytext); } .|n { /* Ignore all other characters. */ } %% /*** C Code section ***/ 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 17
  • 18. Contd….. int main(void) { /* Call the lexer, then quit. */ yylex(); return 0; } If this input is given to flex, it will be converted into a C file, lex.yy.c. This can be compiled into an executable which matches and outputs strings of integers. Eg. abc123z.!&*2gj6 the program will print: Saw an integer: 123 Saw an integer: 2 Saw an integer: 6 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 18
  • 19. Flex, A fast scanner generator • flex is a tool for generating scanners: • programs which recognized lexical patterns in text. • flex reads the given input files, • or its standard input if no file names are given, for a description of a scanner to generate. • The description is in the form of pairs of regular expressions and C code, called rules. • flex generates as output a C source file, `lex.yy.c', which defines a routine `yylex()'. • This file is compiled and linked with the `-lfl' library to produce an executable. • When the executable is run, it analyzes its input for occurrences of the regular expressions. • Whenever it finds one, it executes the corresponding C code. 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 19
  • 20. Contd… • Flex (fast lexical analyzer generator) is a free and open-source software alternative to lex. • It is a computer program that generates lexical analyzers (also known as "scanners" or "lexers"). • Flex was written in C by Vern Paxson around 1987. • He was translating a Ratfor generator. • It had been led by Jef Poskanzer. • The tokens recognized are: '+', '-', '*', '/', '=', '(', ')', ',', ';', '.', ':=', '<', '<=', '<>', '>', '>='; • numbers: 0-9 {0-9}; identifiers: a-zA-Z {a-zA-Z0-9} and keywords: begin, call, const, do, end, if, odd, procedur e, then, var, while. 1/31/2017 ANKUR SRIVASTAVA ASSISTANT PROFESSOR JIT 20