SlideShare a Scribd company logo
1 of 14
Lexical Analyzer Generator
      Lex (Flex in recent implementation)




         Samy Said Mohamed Eshaish

 Pre-Masters student, Department of Computer Science

                    2012-2013

               Compiler Design 2




Contents:-
1- Lex
        What is Lex
        Structure of Lex Program
        Lex Predefined Variables
        Lex Library Routines


2- Set up the Tool

    Install on Windows
    Install on Linux (Ubuntu)


3- Running the Tool

    Run on Windows
    Run on Linux (Ubuntu)


4- Decaf Example

    Example Code
    Run The Example


5- References
    References




1. Lex
 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



 Structure of Lex Program
       • Lex source is separated into three sections by %% delimiters

       • The general format of Lex source is




       •   The absolute minimum Lex program is thus



   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)

 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

 Translation Rules

    •       The form of rules are:

                    Pattern               { action }

    •       The actions are C/C++ code.

                    [0-9]+       { return(Integer); } // RE

                    {DIGIT}+     { return(Integer); } // RD



 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




 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.




 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




2. Set up the Tool
 Windows
 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'

 4.   Now add the BIN folders of both folders into your PATH variable. In case
      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

 5. 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.
 Linux (Ubuntu)
NOTE: You have to install m4 (general purpose macro processor) before installing Flex:-

   •   Downloading m4:

       Run the command below,

       wget ftp://ftp.gnu.org/gnu/m4/m4-1.4.10.tar.gz

   •   Extracting files from the downloaded package:

       tar -xvzf m4-1.4.10.tar.gz

       Now, enter the directory where the package is extracted.

       cd m4-1.4.10

   •   Configuring m4:

       ./configure

   •   Compiling m4:

       make

       Note: check for any error message.

   •   Installing m4:

       As root (for privileges on destination directory), run the following.

       sudo make install




       Note: check for any error messages.
•   Downloading Flex (The fast lexical analyzer):

    Run the command below,

    wget http://prdownloads.sourceforge.net/flex/flex-.5.33.tar.gz?download


         Note: Replace 2.5.33 with your version number.

•   Extracting files from the downloaded package:

    tar -xvzf flex-2.5.33.tar.gz

    Now, enter the directory where the package is extracted.

    cd flex-2.5.33

•   Configuring flex before installation:

    PATH=$PATH: /usr/local/m4

    NOTE: Replace '/usr/local/m4/bin' with the location of m4 installation
    directory. Now, configure the source code before installation.

    ./configure

•   Compiling flex:

    make

      Note: check for any error message.

•   Installing flex:

           As root (for privileges on destination directory), run the following.

sudo make install
Note: check for any error messages.




3. Running the Tool




 Windows
   •   Open CMD

   •   First Go to Directory Contains Files With CD Command

   •   To run Lex on a source file, type  flex (lex source file.l) Command

   •   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 Command

   •   To run the lexical analyzer program, type  a.exe < input file > output file Command


 Linux (Ubuntu)
 Open Terminal

 First Go to Directory Contains Files With CD Command

 To run Lex on a source file, type  flex (lex source file.l) Command

 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 Command

 To run the lexical analyzer program, type  ./a.out < input file > output file Command


4. Decaf Example
 CODE
             //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})

   %%

                       //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 */

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 ); }

%%

                           //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;         }



 Run the CODE
  •       Save file with name “decaf.l”

  •       Open CMD or Terminal then go to directory contains file with cd command

  •       Type this command  flex decaf.l

  •       Type this command  gcc lex.yy.c

  •       Type this command  a.exe<source prog file .txt> output file.txt (Windows)
          or ./ a.out <source prog file .txt> output file.txt (Ubunto)




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




   • Mastering Regular Expressions by Jeffrey E.F.Friedl
     O’Reilly
Lex tool manual

More Related Content

What's hot

knowledge representation using rules
knowledge representation using rulesknowledge representation using rules
knowledge representation using rulesHarini Balamurugan
 
Storage organization and stack allocation of space
Storage organization and stack allocation of spaceStorage organization and stack allocation of space
Storage organization and stack allocation of spaceMuhammad Haroon
 
Knowledge representation and Predicate logic
Knowledge representation and Predicate logicKnowledge representation and Predicate logic
Knowledge representation and Predicate logicAmey Kerkar
 
Inference in First-Order Logic
Inference in First-Order Logic Inference in First-Order Logic
Inference in First-Order Logic Junya Tanaka
 
Unification and Lifting
Unification and LiftingUnification and Lifting
Unification and LiftingMegha Sharma
 
Register allocation and assignment
Register allocation and assignmentRegister allocation and assignment
Register allocation and assignmentKarthi Keyan
 
Artificial Intelligence: The Nine Phases of the Expert System Development Lif...
Artificial Intelligence: The Nine Phases of the Expert System Development Lif...Artificial Intelligence: The Nine Phases of the Expert System Development Lif...
Artificial Intelligence: The Nine Phases of the Expert System Development Lif...The Integral Worm
 
17. Recovery System in DBMS
17. Recovery System in DBMS17. Recovery System in DBMS
17. Recovery System in DBMSkoolkampus
 
data generalization and summarization
data generalization and summarization data generalization and summarization
data generalization and summarization janani thirupathi
 
Artificial Intelligence Notes Unit 2
Artificial Intelligence Notes Unit 2Artificial Intelligence Notes Unit 2
Artificial Intelligence Notes Unit 2DigiGurukul
 
Control Strategies in AI
Control Strategies in AI Control Strategies in AI
Control Strategies in AI Bharat Bhushan
 
Finite automata-for-lexical-analysis
Finite automata-for-lexical-analysisFinite automata-for-lexical-analysis
Finite automata-for-lexical-analysisDattatray Gandhmal
 
14. Query Optimization in DBMS
14. Query Optimization in DBMS14. Query Optimization in DBMS
14. Query Optimization in DBMSkoolkampus
 
ELEMENTS OF TRANSPORT PROTOCOL
ELEMENTS OF TRANSPORT PROTOCOLELEMENTS OF TRANSPORT PROTOCOL
ELEMENTS OF TRANSPORT PROTOCOLShashank Rustagi
 
15 puzzle problem using branch and bound
15 puzzle problem using branch and bound15 puzzle problem using branch and bound
15 puzzle problem using branch and boundAbhishek Singh
 

What's hot (20)

knowledge representation using rules
knowledge representation using rulesknowledge representation using rules
knowledge representation using rules
 
Bankers algorithm
Bankers algorithmBankers algorithm
Bankers algorithm
 
Storage organization and stack allocation of space
Storage organization and stack allocation of spaceStorage organization and stack allocation of space
Storage organization and stack allocation of space
 
Knowledge representation and Predicate logic
Knowledge representation and Predicate logicKnowledge representation and Predicate logic
Knowledge representation and Predicate logic
 
Inference in First-Order Logic
Inference in First-Order Logic Inference in First-Order Logic
Inference in First-Order Logic
 
Unification and Lifting
Unification and LiftingUnification and Lifting
Unification and Lifting
 
Register allocation and assignment
Register allocation and assignmentRegister allocation and assignment
Register allocation and assignment
 
Artificial Intelligence: The Nine Phases of the Expert System Development Lif...
Artificial Intelligence: The Nine Phases of the Expert System Development Lif...Artificial Intelligence: The Nine Phases of the Expert System Development Lif...
Artificial Intelligence: The Nine Phases of the Expert System Development Lif...
 
AI: Logic in AI
AI: Logic in AIAI: Logic in AI
AI: Logic in AI
 
17. Recovery System in DBMS
17. Recovery System in DBMS17. Recovery System in DBMS
17. Recovery System in DBMS
 
data generalization and summarization
data generalization and summarization data generalization and summarization
data generalization and summarization
 
Unit iv(simple code generator)
Unit iv(simple code generator)Unit iv(simple code generator)
Unit iv(simple code generator)
 
NLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit DistanceNLP_KASHK:Minimum Edit Distance
NLP_KASHK:Minimum Edit Distance
 
Artificial Intelligence Notes Unit 2
Artificial Intelligence Notes Unit 2Artificial Intelligence Notes Unit 2
Artificial Intelligence Notes Unit 2
 
Control Strategies in AI
Control Strategies in AI Control Strategies in AI
Control Strategies in AI
 
Finite automata-for-lexical-analysis
Finite automata-for-lexical-analysisFinite automata-for-lexical-analysis
Finite automata-for-lexical-analysis
 
14. Query Optimization in DBMS
14. Query Optimization in DBMS14. Query Optimization in DBMS
14. Query Optimization in DBMS
 
ELEMENTS OF TRANSPORT PROTOCOL
ELEMENTS OF TRANSPORT PROTOCOLELEMENTS OF TRANSPORT PROTOCOL
ELEMENTS OF TRANSPORT PROTOCOL
 
Shortest path algorithm
Shortest  path algorithmShortest  path algorithm
Shortest path algorithm
 
15 puzzle problem using branch and bound
15 puzzle problem using branch and bound15 puzzle problem using branch and bound
15 puzzle problem using branch and bound
 

Viewers also liked

Viewers also liked (20)

Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Lexical analyzer
Lexical analyzerLexical analyzer
Lexical analyzer
 
Lex and Yacc ppt
Lex and Yacc pptLex and Yacc ppt
Lex and Yacc ppt
 
Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)Yacc (yet another compiler compiler)
Yacc (yet another compiler compiler)
 
Lex
LexLex
Lex
 
Lexical analysis - Compiler Design
Lexical analysis - Compiler DesignLexical analysis - Compiler Design
Lexical analysis - Compiler Design
 
Two pass Assembler
Two pass AssemblerTwo pass Assembler
Two pass Assembler
 
Input-Buffering
Input-BufferingInput-Buffering
Input-Buffering
 
Lexical1
Lexical1Lexical1
Lexical1
 
1 compiler outline
1 compiler outline1 compiler outline
1 compiler outline
 
Optimizing Flex Applications
Optimizing Flex ApplicationsOptimizing Flex Applications
Optimizing Flex Applications
 
Lexical
LexicalLexical
Lexical
 
More on Lex
More on LexMore on Lex
More on Lex
 
Pollution and its types
Pollution and its typesPollution and its types
Pollution and its types
 
Chapter 4: Lexical & Syntax Analysis (Programming Exercises)
Chapter 4: Lexical & Syntax Analysis (Programming Exercises)Chapter 4: Lexical & Syntax Analysis (Programming Exercises)
Chapter 4: Lexical & Syntax Analysis (Programming Exercises)
 
Apt programming
Apt programmingApt programming
Apt programming
 
Yacc lex
Yacc lexYacc lex
Yacc lex
 
Compilers
CompilersCompilers
Compilers
 
Minimization of dfa
Minimization of dfaMinimization of dfa
Minimization of dfa
 

Similar to Lex tool manual

LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfThninh2
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdfTigabu Yaya
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdfKhaledIbrahim10923
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain艾鍗科技
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444PurvaShyama
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_netNico Ludwig
 
Basics of c Nisarg Patel
Basics of c Nisarg PatelBasics of c Nisarg Patel
Basics of c Nisarg PatelTechNGyan
 
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 ToolMashaelQ
 
Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell ScriptingJaibeer Malik
 

Similar to Lex tool manual (20)

Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdf
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
7986-lect 7.pdf
7986-lect 7.pdf7986-lect 7.pdf
7986-lect 7.pdf
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Lex programming
Lex programmingLex programming
Lex programming
 
Nithi
NithiNithi
Nithi
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain
 
c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444c programming L-1.pdf43333333544444444444444444444
c programming L-1.pdf43333333544444444444444444444
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net
 
Basics of c Nisarg Patel
Basics of c Nisarg PatelBasics of c Nisarg Patel
Basics of c Nisarg Patel
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C
CC
C
 
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
 
C tutorials
C tutorialsC tutorials
C tutorials
 
Unix And Shell Scripting
Unix And Shell ScriptingUnix And Shell Scripting
Unix And Shell Scripting
 
Golang
GolangGolang
Golang
 

Lex tool manual

  • 1. Lexical Analyzer Generator Lex (Flex in recent implementation) Samy Said Mohamed Eshaish Pre-Masters student, Department of Computer Science 2012-2013 Compiler Design 2 Contents:-
  • 2. 1- Lex  What is Lex  Structure of Lex Program  Lex Predefined Variables  Lex Library Routines 2- Set up the Tool  Install on Windows  Install on Linux (Ubuntu) 3- Running the Tool  Run on Windows  Run on Linux (Ubuntu) 4- Decaf Example  Example Code  Run The Example 5- References  References 1. Lex  What is Lex?
  • 3. • 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  Structure of Lex Program • Lex source is separated into three sections by %% delimiters • The general format of Lex source is • The absolute minimum Lex program is thus  Definitions • Declarations of ordinary C variables, constants and Libraries. %{
  • 4. #include <math.h> #include <stdio.h> #include <stdlib.h> %} • flex definitions :- name definition Digit [0-9] (Regular Definition)  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  Translation Rules • The form of rules are: Pattern { action } • The actions are C/C++ code. [0-9]+ { return(Integer); } // RE {DIGIT}+ { return(Integer); } // RD  User Subroutines Section • You can use your Lex routines in the same ways you use routines in other programming languages (Create functions, identifiers).
  • 5. • The section where main() is placed  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.  Lex Library Routines • yylex() – The default main() contains a call of yylex()
  • 6. 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 2. Set up the Tool
  • 7.  Windows 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' 4. Now add the BIN folders of both folders into your PATH variable. In case 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 5. 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.
  • 8.  Linux (Ubuntu) NOTE: You have to install m4 (general purpose macro processor) before installing Flex:- • Downloading m4: Run the command below, wget ftp://ftp.gnu.org/gnu/m4/m4-1.4.10.tar.gz • Extracting files from the downloaded package: tar -xvzf m4-1.4.10.tar.gz Now, enter the directory where the package is extracted. cd m4-1.4.10 • Configuring m4: ./configure • Compiling m4: make Note: check for any error message. • Installing m4: As root (for privileges on destination directory), run the following. sudo make install Note: check for any error messages.
  • 9. Downloading Flex (The fast lexical analyzer): Run the command below, wget http://prdownloads.sourceforge.net/flex/flex-.5.33.tar.gz?download Note: Replace 2.5.33 with your version number. • Extracting files from the downloaded package: tar -xvzf flex-2.5.33.tar.gz Now, enter the directory where the package is extracted. cd flex-2.5.33 • Configuring flex before installation: PATH=$PATH: /usr/local/m4 NOTE: Replace '/usr/local/m4/bin' with the location of m4 installation directory. Now, configure the source code before installation. ./configure • Compiling flex: make Note: check for any error message. • Installing flex: As root (for privileges on destination directory), run the following. sudo make install
  • 10. Note: check for any error messages. 3. Running the Tool  Windows • Open CMD • First Go to Directory Contains Files With CD Command • To run Lex on a source file, type  flex (lex source file.l) Command • 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 Command • To run the lexical analyzer program, type  a.exe < input file > output file Command  Linux (Ubuntu)  Open Terminal  First Go to Directory Contains Files With CD Command  To run Lex on a source file, type  flex (lex source file.l) Command  It produces a file named lex.yy.c which is a C program for the lexical analyzer.
  • 11.  To compile lex.yy.c, type  gcc lex.yy.c Command  To run the lexical analyzer program, type  ./a.out < input file > output file Command 4. Decaf Example  CODE //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}) %% //Rule Section {DIGIT}+ { printf( "An integer: %s (%d)n", yytext,atoi( yytext ) ); }
  • 12. {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 */ 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 ); } %% //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();
  • 13. } int yywrap(){ return 1; }  Run the CODE • Save file with name “decaf.l” • Open CMD or Terminal then go to directory contains file with cd command • Type this command  flex decaf.l • Type this command  gcc lex.yy.c • Type this command  a.exe<source prog file .txt> output file.txt (Windows) or ./ a.out <source prog file .txt> output file.txt (Ubunto) 5. References • lex & yacc 2nd_edition John R. Levine, Tony Mason, Doug Brown, O’reilly • Mastering Regular Expressions by Jeffrey E.F.Friedl O’Reilly