SlideShare a Scribd company logo
1 of 14
COMPILER
ENGINEERING
  LAB # 6: FLEX
REVISION: FLEX

 • A flex program consists of three sections, separated
   by %% lines, which are:
     1. Definition Section: contains declarations and option
        settings
        • Any code inside of %{ and %} is copied through verbatim near
          the beginning of the generated C source file
     2. Rules Section: is a list of patterns and actions.
        • Each pattern must start at the beginning of the line, since flex
          considers any line that starts with whitespace to be code to be
          copied into the generated C program.




                          Department of Computer Science -
7-11/4/12                                                                2
                             Compiler Engineering Lab
REVISION: FLEX

 • A flex program consists of three sections, separated
   by %% lines, which are:
     3. Sub-routines Section: is C code that is copied to the
        generated scanner, usually small routines related to the
        code in the actions.
        • The C code at the end is a main program that calls yylex(), the
          name that flex gives to the scanner routine, and then prints the
          results
 • Note:
     • In the absence of any other arrangements, the scanner
       reads from the standard input



                          Department of Computer Science -
7-11/4/12                                                                3
                             Compiler Engineering Lab
REVISION: FLEX

 • yytext  is set to point to the input text that the
   pattern just matched.
 • Each Token Flex returns has two parts:
     1. The Token (The Token Zero always means End-of-File)
     2. The Token Value




                      Department of Computer Science -
7-11/4/12                                                     4
                         Compiler Engineering Lab
REGULAR EXPRESSIONS
  Regular                                  Meaning
 Expression
  Symbol
        +           Match one or more of the preceding patterns
        *           Match Zero or more of the preceding patterns
        |                                       Or
        .                   Any character except new line
       n                                   New line
        []                             Character Class
        -                                    Range
        ^      Not (Negative), ^ at the beginning of the character class
               means to match any character other than the ones in the
                                         class

                       Department of Computer Science -
7-11/4/12                                                             5
                          Compiler Engineering Lab
REVISION: FLEX

 • Ex: for the input (3+44+100) which regular expression will be
    used?
        digit       [0-9]
        %%
        “+”          {printf (“Plusn”);}
        [a-zA-Z]     {printf (“IDn”);}
        digit+       {printf (“Plusn”);}
        ([0-9]digit) {printf (“Plusn”);}
        %%
 • What happens If Flex matches two patterns:
     • It will take the longer match (number of characters)
     • If both were equal in length, it will take the first match to
       appear.

                             Department of Computer Science -
7-11/4/12                                                              6
                                Compiler Engineering Lab
USING FLEX TOOL

 1. $ flex WordCount.l
     • First we tell flex to translate our program, and in classic Unix
       fashion since there are no errors, it does so and says
       nothing.
 2. $ cc lex.yy.c –lfl
     • Then we compile lex.yy.c, the C program it generated; link it
       with the flex library, -lfl
 3. $ ./a.out
    This is an example for compiler lab
     • run it; and type a little input for it to count (to stop input to
       file press Ctrl + D [or type End-of-File character: ^D on
       Unix, ot ^Z on Windows]).


                          Department of Computer Science -
7-11/4/12                                                                  7
                             Compiler Engineering Lab
FLEX FILE EXAMPLE # 1:
                    CALCULATOR
 • Write a Calculator .l scanner, returning token for
   following lexemes:
     •   Plus +
     •   Minus –
     •   Multiplication *
     •   division /
     •   Absolute|
     •   Number types and values
     •   End of line
     •   White space
     •   Any other character print an error message

                         Department of Computer Science -
7-11/4/12                                                   8
                            Compiler Engineering Lab
* recognize tokens for the calculator and print them out */
                                                         Cal.l
%%
“+”    { printf("PLUSn"); }
“-”    { printf("MINUSn"); }
“*”    { printf("TIMESn"); }
“/”    { printf("DIVIDEn"); }
“|” { printf("ABSn"); }
[0-9]+ { printf("NUMBER %sn", yytext); }
 n     { printf("NEWLINEn"); }
[ t] { }
       { printf("Mystery character %sn", yytext); }
%%




                       Department of Computer Science -
7-11/4/12                                                        9
                          Compiler Engineering Lab
FLEX FILE EXAMPLE # 2:
                CALCULATOR
 • Adjust the Calculator.l scanner written in the
   previous example (#1), where the scanner will
   return the value of the tokens instead of printing
   them:
 • NUMBER = 258,
   ADD = 259,
   SUB = 260,
   MUL = 261,
   DIV = 262,
   ABS = 263,
   EOL = 264 end of line

                   Department of Computer Science -
7-11/4/12                                               10
                      Compiler Engineering Lab
/* recognize tokens for the calculator and print them out */                  Cal2.l
%{
enum yytokentype {
NUMBER = 258, ADD = 259, SUB = 260, MUL = 261, DIV = 262, ABS = 263, EOL = 264};
int yylval;
%}
%%
”+”          { return ADD; }
”-”         { return SUB; }
”*”         { return MUL; }
”/”         { return DIV; }
”|”         { return ABS; }
[0-9]+      { yylval = atoi(yytext); return NUMBER; }
n          { return EOL; }
[ t]       { /* ignore whitespace */ }
.           { printf("Mystery character %cn", *yytext); }
%%
main(int argc, char **argv)
{ int tok;
            while(tok = yylex())
            {           printf("%d", tok);
                        if(tok == NUMBER)
                                     printf(" = %dn", yylval);
                        else printf("n");
}}

                               Department of Computer Science -
7-11/4/12                                                                              11
                                  Compiler Engineering Lab
FLEX FILE EXAMPLE # 3:
                 WORD COUNTER
 • Write a Flex file that is capable to produce a
   scanner that counts:
     • Characters,
     • New lines,
     • And words




                     Department of Computer Science -
7-11/4/12                                               12
                        Compiler Engineering Lab
WordCount.l
/* just like Unix wc */
%{
int chars = 0;
int words = 0;
int lines = 0;
%}
%%
[a-zA-Z]+        { words++; chars += strlen(yytext); }
 n              { chars++; lines++; }
.                { chars++; }
%%
main(int argc, char **argv)
{
yylex();
printf("%8d%8d%8dn", lines, words, chars);
}
                         Department of Computer Science -
7-11/4/12                                                   13
                            Compiler Engineering Lab
QUESTIONS?

 Thank you for listening 




                   Department of Computer Science -
7-11/4/12                                             14
                      Compiler Engineering Lab

More Related Content

What's hot (20)

Lecture26
Lecture26Lecture26
Lecture26
 
Scheme Programming Language
Scheme Programming LanguageScheme Programming Language
Scheme Programming Language
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Design of a two pass assembler
Design of a two pass assemblerDesign of a two pass assembler
Design of a two pass assembler
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
2. Characteristics of Algorithm.ppt
2. Characteristics of Algorithm.ppt2. Characteristics of Algorithm.ppt
2. Characteristics of Algorithm.ppt
 
ENTORNOS DE DESARROLLO: PRESENTACIÓN DEL MÓDULO
ENTORNOS DE DESARROLLO: PRESENTACIÓN DEL MÓDULO ENTORNOS DE DESARROLLO: PRESENTACIÓN DEL MÓDULO
ENTORNOS DE DESARROLLO: PRESENTACIÓN DEL MÓDULO
 
Treebank annotation
Treebank annotationTreebank annotation
Treebank annotation
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compiler
 
Type checking
Type checkingType checking
Type checking
 
Object-Oriented Paradigm
Object-Oriented Paradigm Object-Oriented Paradigm
Object-Oriented Paradigm
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
System Programming Unit III
System Programming Unit IIISystem Programming Unit III
System Programming Unit III
 
Lisp
LispLisp
Lisp
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Lecture 3 RE NFA DFA
Lecture 3   RE NFA DFA Lecture 3   RE NFA DFA
Lecture 3 RE NFA DFA
 
Symbol Table
Symbol TableSymbol Table
Symbol Table
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 

Similar to 6 compiler lab - Flex

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
 
Compiler Engineering Lab#3
Compiler Engineering Lab#3Compiler Engineering Lab#3
Compiler Engineering Lab#3MashaelQ
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manualAnil Bishnoi
 
7 compiler lab
7 compiler lab 7 compiler lab
7 compiler lab MashaelQ
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)Sami Said
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manualSami Said
 
cmp104 lec 8
cmp104 lec 8cmp104 lec 8
cmp104 lec 8kapil078
 
(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
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language CourseVivek chan
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxfaithxdunce63732
 
(1) cpp introducing the_cpp_programming_language
(1) cpp introducing the_cpp_programming_language(1) cpp introducing the_cpp_programming_language
(1) cpp introducing the_cpp_programming_languageNico Ludwig
 

Similar to 6 compiler lab - Flex (20)

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 Engineering Lab#3
Compiler Engineering Lab#3Compiler Engineering Lab#3
Compiler Engineering Lab#3
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manual
 
Matlab-3.pptx
Matlab-3.pptxMatlab-3.pptx
Matlab-3.pptx
 
C++
C++C++
C++
 
7 compiler lab
7 compiler lab 7 compiler lab
7 compiler lab
 
IN4308 1
IN4308 1IN4308 1
IN4308 1
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
Lecture 01 2017
Lecture 01 2017Lecture 01 2017
Lecture 01 2017
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
cmp104 lec 8
cmp104 lec 8cmp104 lec 8
cmp104 lec 8
 
(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
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docxCS 23001 Computer Science II Data Structures & AbstractionPro.docx
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
c.ppt
c.pptc.ppt
c.ppt
 
(1) cpp introducing the_cpp_programming_language
(1) cpp introducing the_cpp_programming_language(1) cpp introducing the_cpp_programming_language
(1) cpp introducing the_cpp_programming_language
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 

Recently uploaded

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 

Recently uploaded (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 

6 compiler lab - Flex

  • 2. REVISION: FLEX • A flex program consists of three sections, separated by %% lines, which are: 1. Definition Section: contains declarations and option settings • Any code inside of %{ and %} is copied through verbatim near the beginning of the generated C source file 2. Rules Section: is a list of patterns and actions. • Each pattern must start at the beginning of the line, since flex considers any line that starts with whitespace to be code to be copied into the generated C program. Department of Computer Science - 7-11/4/12 2 Compiler Engineering Lab
  • 3. REVISION: FLEX • A flex program consists of three sections, separated by %% lines, which are: 3. Sub-routines Section: is C code that is copied to the generated scanner, usually small routines related to the code in the actions. • The C code at the end is a main program that calls yylex(), the name that flex gives to the scanner routine, and then prints the results • Note: • In the absence of any other arrangements, the scanner reads from the standard input Department of Computer Science - 7-11/4/12 3 Compiler Engineering Lab
  • 4. REVISION: FLEX • yytext  is set to point to the input text that the pattern just matched. • Each Token Flex returns has two parts: 1. The Token (The Token Zero always means End-of-File) 2. The Token Value Department of Computer Science - 7-11/4/12 4 Compiler Engineering Lab
  • 5. REGULAR EXPRESSIONS Regular Meaning Expression Symbol + Match one or more of the preceding patterns * Match Zero or more of the preceding patterns | Or . Any character except new line n New line [] Character Class - Range ^ Not (Negative), ^ at the beginning of the character class means to match any character other than the ones in the class Department of Computer Science - 7-11/4/12 5 Compiler Engineering Lab
  • 6. REVISION: FLEX • Ex: for the input (3+44+100) which regular expression will be used? digit [0-9] %% “+” {printf (“Plusn”);} [a-zA-Z] {printf (“IDn”);} digit+ {printf (“Plusn”);} ([0-9]digit) {printf (“Plusn”);} %% • What happens If Flex matches two patterns: • It will take the longer match (number of characters) • If both were equal in length, it will take the first match to appear. Department of Computer Science - 7-11/4/12 6 Compiler Engineering Lab
  • 7. USING FLEX TOOL 1. $ flex WordCount.l • First we tell flex to translate our program, and in classic Unix fashion since there are no errors, it does so and says nothing. 2. $ cc lex.yy.c –lfl • Then we compile lex.yy.c, the C program it generated; link it with the flex library, -lfl 3. $ ./a.out This is an example for compiler lab • run it; and type a little input for it to count (to stop input to file press Ctrl + D [or type End-of-File character: ^D on Unix, ot ^Z on Windows]). Department of Computer Science - 7-11/4/12 7 Compiler Engineering Lab
  • 8. FLEX FILE EXAMPLE # 1: CALCULATOR • Write a Calculator .l scanner, returning token for following lexemes: • Plus + • Minus – • Multiplication * • division / • Absolute| • Number types and values • End of line • White space • Any other character print an error message Department of Computer Science - 7-11/4/12 8 Compiler Engineering Lab
  • 9. * recognize tokens for the calculator and print them out */ Cal.l %% “+” { printf("PLUSn"); } “-” { printf("MINUSn"); } “*” { printf("TIMESn"); } “/” { printf("DIVIDEn"); } “|” { printf("ABSn"); } [0-9]+ { printf("NUMBER %sn", yytext); } n { printf("NEWLINEn"); } [ t] { } { printf("Mystery character %sn", yytext); } %% Department of Computer Science - 7-11/4/12 9 Compiler Engineering Lab
  • 10. FLEX FILE EXAMPLE # 2: CALCULATOR • Adjust the Calculator.l scanner written in the previous example (#1), where the scanner will return the value of the tokens instead of printing them: • NUMBER = 258, ADD = 259, SUB = 260, MUL = 261, DIV = 262, ABS = 263, EOL = 264 end of line Department of Computer Science - 7-11/4/12 10 Compiler Engineering Lab
  • 11. /* recognize tokens for the calculator and print them out */ Cal2.l %{ enum yytokentype { NUMBER = 258, ADD = 259, SUB = 260, MUL = 261, DIV = 262, ABS = 263, EOL = 264}; int yylval; %} %% ”+” { return ADD; } ”-” { return SUB; } ”*” { return MUL; } ”/” { return DIV; } ”|” { return ABS; } [0-9]+ { yylval = atoi(yytext); return NUMBER; } n { return EOL; } [ t] { /* ignore whitespace */ } . { printf("Mystery character %cn", *yytext); } %% main(int argc, char **argv) { int tok; while(tok = yylex()) { printf("%d", tok); if(tok == NUMBER) printf(" = %dn", yylval); else printf("n"); }} Department of Computer Science - 7-11/4/12 11 Compiler Engineering Lab
  • 12. FLEX FILE EXAMPLE # 3: WORD COUNTER • Write a Flex file that is capable to produce a scanner that counts: • Characters, • New lines, • And words Department of Computer Science - 7-11/4/12 12 Compiler Engineering Lab
  • 13. WordCount.l /* just like Unix wc */ %{ int chars = 0; int words = 0; int lines = 0; %} %% [a-zA-Z]+ { words++; chars += strlen(yytext); } n { chars++; lines++; } . { chars++; } %% main(int argc, char **argv) { yylex(); printf("%8d%8d%8dn", lines, words, chars); } Department of Computer Science - 7-11/4/12 13 Compiler Engineering Lab
  • 14. QUESTIONS? Thank you for listening  Department of Computer Science - 7-11/4/12 14 Compiler Engineering Lab