SlideShare a Scribd company logo
Lexical Analyzer Generator


  Lex(Flex in recent implementation)


                                       1
What is Lex?
• The main job of a lexical analyzer
  (scanner) is to break up an input stream
  into tokens(tokenize input streams).
• Ex :-
  a = b + c * d;
  ID ASSIGN ID PLUS ID MULT ID SEMI

• Lex is an utility to help you rapidly
  generate your scanners                  2
Structure of Lex Program
• Lex source is separated into three sections by %
  % delimiters
• The general format of Lex source is

  {definitions}
  %%                                  (required)
  {transition rules}
  %%                                  (optional)
  {user Code}

• The absolute minimumProgramming Languages is thus
  %%         PLLab, NTHU,Cs2403 Lex program           3
Definitions
• Declarations of ordinary C variables
  ,constants and Libraries.
%{
#include <math.h>
#include <stdio.h>
  #include <stdlib.h>
%}

• flex definitions :- name definition
              Digit [0-9] (Regular Definition)
                                                 4
Operators
“  [ ] ^ - ? . * + | ( ) $ / { } % < >

• 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

                                                 5
Translation Rules
• The form of rules are:
        Pattern                  { action }

   The actions are C/C++ code.

[0-9]+            { return(Integer); } // RE
{DIGIT}+           { return(Integer); } // RD
                                                6
User Subroutines Section
• You can use your Lex routines in the same
  ways you use routines in other programming
  languages (Create functions, identifiers) .
• The section where main() is placed
%{
     void print(String x);
%}
%%
{letter}+    print(“ID”);
%%
main() {
   yylex();
}
void print(String x) {
   printf(x);
}            PLLab, NTHU,Cs2403 Programming Languages   7
An Overview of Lex

Lex source                    lex.yy.c
 program
               Lex compiler

  lex.yy.c      C compiler     a.out


   input          a.out       tokens


                                         8
Lex Predefined Variables
• yytext -- a string containing the lexeme

• yyleng -- the length of the lexeme

• yyin -- the input stream pointer
   – the default input of default main() is stdin

• yyout -- the output stream pointer
   – the default output of default main() is stdout.




                                                       9
Lex Library Routines
• yylex()
  – The default main() contains a call of yylex()
• yymore()
  – return the next token
• yyless(n)
  – retain the first n characters in yytext
• yywarp()
  – is called whenever Lex reaches an end-of-file
  – The default yywarp() always returns 1

                                                    10
Review of Lex Predefined
                 Variables
Name                    Function
char *yytext            pointer to matched string
int yyleng              length of matched string
FILE *yyin              input stream pointer
FILE *yyout             output stream pointer
int yylex(void)         call to invoke lexer, returns token
char* yymore(void)      return the next token
int yyless(int n)       retain the first n characters in yytext
int yywrap(void)        wrapup, return 1 if done, 0 if not done
ECHO                    write matched string
REJECT                  go to the next alternative rule
INITAL                  initial start condition
BEGIN                   condition switch start condition          11
                  PLLab, NTHU,Cs2403 Programming Languages
Installation & Usage



                       12
Installation
1) Download the Windows version of FLEX

2) Download a C/C++ Compiler DevCPP or Code::Blocks

3) Install all . It's recommended to install in folders WITHOUT spaces in their names.
        I use 'C:GNUWin32' for FLEX and 'C: DevCPP'

5) Now add the BIN folders of both folders into your PATH variable. Incase you don't
   know how to go about this, see how to do it on Windows XP ,Windows
   Vista and Windows 7. You will have to add '; C:GNUWin32bin;C:Dev-Cpp' to the
   end of your PATH

6) Open up a CMD prompt and type in the following
              C:flex --version
                          flex version 2.5.4
              C:>gcc --version
                       gcc (GCC) 3.4.2 (mingw-special)
                       Copyright (C) 2004 Free Software Foundation, Inc.
                       This is free software; see the source for copying conditions.
                    There is NO warranty; not even for MERCHANTABILITY
                    or FITNESS FOR A PARTICULAR PURPOSE.                         13
Usage
• First Go to Directory Contains Files
• To run Lex on a source file, type
  flex (lex source file.l)
• It produces a file named lex.yy.c which is a C
  program for the lexical analyzer.
• To compile lex.yy.c, type
  gcc lex.yy.c
• To run the lexical analyzer program, type
  a.exe < input file > output file

                                             14
Examples
• Ex1
%{
int numChars = 0, numWords = 0, numLines = 0;
%}
%%
n              {numLines++; numChars++;}
[^ tn]+       {numWords++; numChars += yyleng;}
.               {numChars++;}
%%
int main() {
yylex();
printf("%dt%dt%dn", numChars, numWords, numLines);
}
    int yywrap(){
          return 1;
                                                        15
          }
Example on Decaf
•   Definitions Section
%{
/* need this for the call to atof() below */
#include <math.h>
 #include <stdio.h>
   #include <stdlib.h>
%}
DIGIT                                 [0-9]
LITTER                                [a-zA-Z]
C                                    [//]
S                                   []
L                                   [n]
ID                                 {LITTER}({LITTER}|{DIGIT}|_)*
double                            {DIGIT}+(.{DIGIT}+)?([Ee][+-]?{DIGIT}+)?
hex                                (0[xX])({DIGIT}|[a-fA-F])*
String                             ("({LITTER}|{S})*")
Sym                               [~!@#$%^&*()_+|><""''{}.,]
Comment                           (({LITTER}|{DIGIT}|{Sym}|{S}|{L})*)
Comment2                          ({C}+({LITTER}|{DIGIT}|{Sym}|{S})*{L})
%%
                                                                              16
Example on Decaf
•   Rule Section
{DIGIT}+                 {
                          printf( "An integer: %s (%d)n", yytext,atoi( yytext ) );

                          }

{double}                  {
                                    printf( "A double: %s (%g)n", yytext,
                                                 atof( yytext ) );
                          }

{hex}                         {
                                     printf( "A Hexadecimal: %s n", yytext );
                              }

{String}                  {
                                    printf( "A String: %s n", yytext );
                     }
"/*"{Comment}+"*/"                      /* eat up one-line comments */

{Comment2}                             /* eat up one-line comments */                 17
Example on Decaf
•      Rule Section Cont~

void|int|double|bool|string|class|interface|null|this|extends|implements|for|while|if|else|return|break
|new|NewArray|Print|ReadInteger|ReadLine|true|false
                            { printf( "A keyword: %sn", yytext ); }

{ID}                            {   printf( "An identifier: %sn", yytext ); }

"+"|"-"|"*"|"/"|"="|"=="|"<"|"<="|">"|">="|"!="|"&&"|"||"|"!"|";"|","|"."|"["|"]"|"("|")"|"{"|"}"
                               { printf( "An operator: %sn", yytext ); }

"{"[^}n]*"}"    /* eat up one-line comments */

[ tn]+        /* eat up whitespace */


.          {printf( "Unrecognized character: %sn", yytext ); }


%%


                                                                                                    18
Example on Decaf
•    User Code Section

main( argc, argv )
int argc;
char **argv;
   {
   ++argv, --argc; /* skip over program name */
   if ( argc > 0 )
          yyin = fopen( argv[0], "r" );
   else
          yyin = stdin;

    yylex();
    }

int yywrap(){
          return 1;
          }


                                                       19
Run The Decaf Example

    Run It With Me 




                        20
Reference Books

• lex & yacc 2nd_edition John
  R. Levine, Tony Mason, Doug
  Brown, O’reilly

• Mastering Regular Expressions
  – by Jeffrey E.F. Friedl
  – O’Reilly
  – ISBN: 1-56592-257-3


                                  21

More Related Content

What's hot

Intro to trigger and constraint
Intro to trigger and constraintIntro to trigger and constraint
Intro to trigger and constraintLearningTech
 
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
 
Nonrecursive predictive parsing
Nonrecursive predictive parsingNonrecursive predictive parsing
Nonrecursive predictive parsing
alldesign
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Yacc
YaccYacc
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
samairaakram
 
Python functional programming
Python functional programmingPython functional programming
Python functional programming
Geison Goes
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
Prof. Dr. K. Adisesha
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generationrawan_z
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
RamchandraRegmi
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
sunilchute1
 
Grep - A powerful search utility
Grep - A powerful search utilityGrep - A powerful search utility
Grep - A powerful search utility
Nirajan Pant
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
LakshmiSamivel
 
Quick sort data structures
Quick sort data structuresQuick sort data structures
Quick sort data structures
chauhankapil
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 

What's hot (20)

Intro to trigger and constraint
Intro to trigger and constraintIntro to trigger and constraint
Intro to trigger and constraint
 
Top down and botttom up Parsing
Top down     and botttom up ParsingTop down     and botttom up Parsing
Top down and botttom up Parsing
 
Nonrecursive predictive parsing
Nonrecursive predictive parsingNonrecursive predictive parsing
Nonrecursive predictive parsing
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Inline function
Inline functionInline function
Inline function
 
Yacc
YaccYacc
Yacc
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
 
Python functional programming
Python functional programmingPython functional programming
Python functional programming
 
9 python data structure-2
9 python data structure-29 python data structure-2
9 python data structure-2
 
Intermediate code- generation
Intermediate code- generationIntermediate code- generation
Intermediate code- generation
 
Intermediate code generation
Intermediate code generationIntermediate code generation
Intermediate code generation
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
 
Grep - A powerful search utility
Grep - A powerful search utilityGrep - A powerful search utility
Grep - A powerful search utility
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Quick sort data structures
Quick sort data structuresQuick sort data structures
Quick sort data structures
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 

Similar to Lex (lexical analyzer)

Lex tool manual
Lex tool manualLex tool manual
Lex tool manualSami Said
 
system software
system software system software
system software randhirlpu
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
Saifur Rahman
 
Compiler Design Tutorial
Compiler Design Tutorial Compiler Design Tutorial
Compiler Design Tutorial
Sarit Chakraborty
 
Introduction to Python , Overview
Introduction to Python , OverviewIntroduction to Python , Overview
Introduction to Python , Overview
NB Veeresh
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
rik0
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
PyCon Italia
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
pssraikar
 
Lex programming
Lex programmingLex programming
Lex programming
sureshmoharana2013
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
Atul Setu
 
lecture_lex.pdf
lecture_lex.pdflecture_lex.pdf
lecture_lex.pdf
DrNilotpalChakrabort
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in cgkgaur1987
 

Similar to Lex (lexical analyzer) (20)

Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
system software
system software system software
system software
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
Compiler Design Tutorial
Compiler Design Tutorial Compiler Design Tutorial
Compiler Design Tutorial
 
Introduction to Python , Overview
Introduction to Python , OverviewIntroduction to Python , Overview
Introduction to Python , Overview
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
First c program
First c programFirst c program
First c program
 
Lex programming
Lex programmingLex programming
Lex programming
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C
CC
C
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
lecture_lex.pdf
lecture_lex.pdflecture_lex.pdf
lecture_lex.pdf
 
Mouse programming in c
Mouse programming in cMouse programming in c
Mouse programming in c
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
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
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
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
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
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
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
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
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
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
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
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
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
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
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
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
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
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
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
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
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 

Lex (lexical analyzer)

  • 1. Lexical Analyzer Generator Lex(Flex in recent implementation) 1
  • 2. What is Lex? • The main job of a lexical analyzer (scanner) is to break up an input stream into tokens(tokenize input streams). • Ex :- a = b + c * d; ID ASSIGN ID PLUS ID MULT ID SEMI • Lex is an utility to help you rapidly generate your scanners 2
  • 3. Structure of Lex Program • Lex source is separated into three sections by % % delimiters • The general format of Lex source is {definitions} %% (required) {transition rules} %% (optional) {user Code} • The absolute minimumProgramming Languages is thus %% PLLab, NTHU,Cs2403 Lex program 3
  • 4. Definitions • Declarations of ordinary C variables ,constants and Libraries. %{ #include <math.h> #include <stdio.h> #include <stdlib.h> %} • flex definitions :- name definition Digit [0-9] (Regular Definition) 4
  • 5. Operators “ [ ] ^ - ? . * + | ( ) $ / { } % < > • 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 5
  • 6. Translation Rules • The form of rules are: Pattern { action } The actions are C/C++ code. [0-9]+ { return(Integer); } // RE {DIGIT}+ { return(Integer); } // RD 6
  • 7. User Subroutines Section • You can use your Lex routines in the same ways you use routines in other programming languages (Create functions, identifiers) . • The section where main() is placed %{ void print(String x); %} %% {letter}+ print(“ID”); %% main() { yylex(); } void print(String x) { printf(x); } PLLab, NTHU,Cs2403 Programming Languages 7
  • 8. An Overview of Lex Lex source lex.yy.c program Lex compiler lex.yy.c C compiler a.out input a.out tokens 8
  • 9. Lex Predefined Variables • yytext -- a string containing the lexeme • yyleng -- the length of the lexeme • yyin -- the input stream pointer – the default input of default main() is stdin • yyout -- the output stream pointer – the default output of default main() is stdout. 9
  • 10. Lex Library Routines • yylex() – The default main() contains a call of yylex() • yymore() – return the next token • yyless(n) – retain the first n characters in yytext • yywarp() – is called whenever Lex reaches an end-of-file – The default yywarp() always returns 1 10
  • 11. Review of Lex Predefined Variables Name Function char *yytext pointer to matched string int yyleng length of matched string FILE *yyin input stream pointer FILE *yyout output stream pointer int yylex(void) call to invoke lexer, returns token char* yymore(void) return the next token int yyless(int n) retain the first n characters in yytext int yywrap(void) wrapup, return 1 if done, 0 if not done ECHO write matched string REJECT go to the next alternative rule INITAL initial start condition BEGIN condition switch start condition 11 PLLab, NTHU,Cs2403 Programming Languages
  • 13. Installation 1) Download the Windows version of FLEX 2) Download a C/C++ Compiler DevCPP or Code::Blocks 3) Install all . It's recommended to install in folders WITHOUT spaces in their names. I use 'C:GNUWin32' for FLEX and 'C: DevCPP' 5) Now add the BIN folders of both folders into your PATH variable. Incase you don't know how to go about this, see how to do it on Windows XP ,Windows Vista and Windows 7. You will have to add '; C:GNUWin32bin;C:Dev-Cpp' to the end of your PATH 6) Open up a CMD prompt and type in the following C:flex --version flex version 2.5.4 C:>gcc --version gcc (GCC) 3.4.2 (mingw-special) Copyright (C) 2004 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 13
  • 14. Usage • First Go to Directory Contains Files • To run Lex on a source file, type flex (lex source file.l) • It produces a file named lex.yy.c which is a C program for the lexical analyzer. • To compile lex.yy.c, type gcc lex.yy.c • To run the lexical analyzer program, type a.exe < input file > output file 14
  • 15. Examples • Ex1 %{ int numChars = 0, numWords = 0, numLines = 0; %} %% n {numLines++; numChars++;} [^ tn]+ {numWords++; numChars += yyleng;} . {numChars++;} %% int main() { yylex(); printf("%dt%dt%dn", numChars, numWords, numLines); } int yywrap(){ return 1; 15 }
  • 16. Example on Decaf • Definitions Section %{ /* need this for the call to atof() below */ #include <math.h> #include <stdio.h> #include <stdlib.h> %} DIGIT [0-9] LITTER [a-zA-Z] C [//] S [] L [n] ID {LITTER}({LITTER}|{DIGIT}|_)* double {DIGIT}+(.{DIGIT}+)?([Ee][+-]?{DIGIT}+)? hex (0[xX])({DIGIT}|[a-fA-F])* String ("({LITTER}|{S})*") Sym [~!@#$%^&*()_+|><""''{}.,] Comment (({LITTER}|{DIGIT}|{Sym}|{S}|{L})*) Comment2 ({C}+({LITTER}|{DIGIT}|{Sym}|{S})*{L}) %% 16
  • 17. Example on Decaf • Rule Section {DIGIT}+ { printf( "An integer: %s (%d)n", yytext,atoi( yytext ) ); } {double} { printf( "A double: %s (%g)n", yytext, atof( yytext ) ); } {hex} { printf( "A Hexadecimal: %s n", yytext ); } {String} { printf( "A String: %s n", yytext ); } "/*"{Comment}+"*/" /* eat up one-line comments */ {Comment2} /* eat up one-line comments */ 17
  • 18. Example on Decaf • Rule Section Cont~ void|int|double|bool|string|class|interface|null|this|extends|implements|for|while|if|else|return|break |new|NewArray|Print|ReadInteger|ReadLine|true|false { printf( "A keyword: %sn", yytext ); } {ID} { printf( "An identifier: %sn", yytext ); } "+"|"-"|"*"|"/"|"="|"=="|"<"|"<="|">"|">="|"!="|"&&"|"||"|"!"|";"|","|"."|"["|"]"|"("|")"|"{"|"}" { printf( "An operator: %sn", yytext ); } "{"[^}n]*"}" /* eat up one-line comments */ [ tn]+ /* eat up whitespace */ . {printf( "Unrecognized character: %sn", yytext ); } %% 18
  • 19. Example on Decaf • User Code Section main( argc, argv ) int argc; char **argv; { ++argv, --argc; /* skip over program name */ if ( argc > 0 ) yyin = fopen( argv[0], "r" ); else yyin = stdin; yylex(); } int yywrap(){ return 1; } 19
  • 20. Run The Decaf Example Run It With Me  20
  • 21. Reference Books • lex & yacc 2nd_edition John R. Levine, Tony Mason, Doug Brown, O’reilly • Mastering Regular Expressions – by Jeffrey E.F. Friedl – O’Reilly – ISBN: 1-56592-257-3 21