SlideShare a Scribd company logo
2
Most read
9
Most read
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

PPTX
Core java complete ppt(note)
PDF
Lecture1 introduction compilers
PPTX
Features of java
PPT
Chapter 6 intermediate code generation
PPT
PPTX
Gpu with cuda architecture
PPTX
04 Multi-layer Feedforward Networks
Core java complete ppt(note)
Lecture1 introduction compilers
Features of java
Chapter 6 intermediate code generation
Gpu with cuda architecture
04 Multi-layer Feedforward Networks

What's hot (20)

PPTX
TCP and UDP
PPTX
Wireless transmission
PDF
CS6701 CRYPTOGRAPHY AND NETWORK SECURITY
PPTX
Radial basis function network ppt bySheetal,Samreen and Dhanashri
PDF
Deep Learning - Overview of my work II
PPSX
Elements of Java Language
PPTX
IP addressing seminar ppt
PPTX
compiler ppt on symbol table
PPSX
Perceptron (neural network)
PPT
Artificial Intelligence -- Search Algorithms
PPT
1 - Introduction to Compilers.ppt
PDF
RPL - Routing Protocol for Low Power and Lossy Networks
PPT
Wireless transmission
PPTX
JavaFX Presentation
PPTX
Text generation and_advanced_topics
PPTX
Routing algorithm
PPTX
Chapter 3 servlet & jsp
PDF
Authenticated Encryption Gcm Ccm
PPTX
Applets in java
PPTX
Important features of java
TCP and UDP
Wireless transmission
CS6701 CRYPTOGRAPHY AND NETWORK SECURITY
Radial basis function network ppt bySheetal,Samreen and Dhanashri
Deep Learning - Overview of my work II
Elements of Java Language
IP addressing seminar ppt
compiler ppt on symbol table
Perceptron (neural network)
Artificial Intelligence -- Search Algorithms
1 - Introduction to Compilers.ppt
RPL - Routing Protocol for Low Power and Lossy Networks
Wireless transmission
JavaFX Presentation
Text generation and_advanced_topics
Routing algorithm
Chapter 3 servlet & jsp
Authenticated Encryption Gcm Ccm
Applets in java
Important features of java
Ad

Similar to 6 compiler lab - Flex (20)

PPTX
Compiler Engineering Lab#5 : Symbol Table, Flex Tool
PPT
LEX lexical analyzer for compiler theory.ppt
PPTX
Compiler Engineering Lab#3
PDF
Programming with c language practical manual
PPTX
Matlab-3.pptx
PPTX
7 compiler lab
PDF
IN4308 1
PPT
Lex (lexical analyzer)
PPT
Lecture 01 2017
DOC
Lex tool manual
PPTX
cmp104 lec 8
PDF
(1) c sharp introduction_basics_dot_net
PPSX
Complete C programming Language Course
DOCX
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
PDF
C Tutorials
PPT
The Basics of C - Math Functions and characters
PPT
PPTX
iii-ii cd nCompiler design UNIT-V-1.pptx
PDF
(1) cpp introducing the_cpp_programming_language
Compiler Engineering Lab#5 : Symbol Table, Flex Tool
LEX lexical analyzer for compiler theory.ppt
Compiler Engineering Lab#3
Programming with c language practical manual
Matlab-3.pptx
7 compiler lab
IN4308 1
Lex (lexical analyzer)
Lecture 01 2017
Lex tool manual
cmp104 lec 8
(1) c sharp introduction_basics_dot_net
Complete C programming Language Course
CS 23001 Computer Science II Data Structures & AbstractionPro.docx
C Tutorials
The Basics of C - Math Functions and characters
iii-ii cd nCompiler design UNIT-V-1.pptx
(1) cpp introducing the_cpp_programming_language
Ad

Recently uploaded (20)

PDF
Pre independence Education in Inndia.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
01-Introduction-to-Information-Management.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Cell Types and Its function , kingdom of life
PDF
Sports Quiz easy sports quiz sports quiz
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Institutional Correction lecture only . . .
PDF
RMMM.pdf make it easy to upload and study
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Pre independence Education in Inndia.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Microbial diseases, their pathogenesis and prophylaxis
01-Introduction-to-Information-Management.pdf
Basic Mud Logging Guide for educational purpose
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Module 4: Burden of Disease Tutorial Slides S2 2025
Cell Types and Its function , kingdom of life
Sports Quiz easy sports quiz sports quiz
TR - Agricultural Crops Production NC III.pdf
Cell Structure & Organelles in detailed.
Final Presentation General Medicine 03-08-2024.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Pharma ospi slides which help in ospi learning
Institutional Correction lecture only . . .
RMMM.pdf make it easy to upload and study
Renaissance Architecture: A Journey from Faith to Humanism
Pharmacology of Heart Failure /Pharmacotherapy of CHF

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