home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 8 / FreshFishVol8-CD1.bin / gnu / man / catl / flexdoc.0 < prev   
Text File  |  1993-12-07  |  90KB  |  2,311 lines

  1.  
  2.  
  3.  
  4. FLEX(1)                                                   FLEX(1)
  5.  
  6.  
  7. NNAAMMEE
  8.        flex - fast lexical analyzer generator
  9.  
  10. SSYYNNOOPPSSIISS
  11.        fflleexx [[--bbccddffiinnppssttvvFFIILLTT88 --CC[[eeffmmFF]] --SSsskkeelleettoonn]] _[_f_i_l_e_n_a_m_e _._._._]
  12.  
  13. DDEESSCCRRIIPPTTIIOONN
  14.        _f_l_e_x is a tool for  generating  _s_c_a_n_n_e_r_s_:  programs  which
  15.        recognized lexical patterns in text.  _f_l_e_x reads the given
  16.        input files, or its standard input if no  file  names  are
  17.        given,  for  a  description of a scanner to generate.  The
  18.        description is in the form of pairs of regular expressions
  19.        and  C  code,  called  _r_u_l_e_s_. _f_l_e_x generates as output a C
  20.        source file, lleexx..yyyy..cc,, which defines  a  routine  yyyylleexx(())..
  21.        This  file is compiled and linked with the --llffll library to
  22.        produce an executable.  When the  executable  is  run,  it
  23.        analyzes  its input for occurrences of the regular expres-
  24.        sions.  Whenever it finds one, it executes the correspond-
  25.        ing C code.
  26.  
  27. SSOOMMEE SSIIMMPPLLEE EEXXAAMMPPLLEESS
  28.        First  some  simple  examples to get the flavor of how one
  29.        uses _f_l_e_x_.  The following _f_l_e_x input specifies  a  scanner
  30.        which  whenever  it  encounters the string "username" will
  31.        replace it with the user's login name:
  32.  
  33.            %%
  34.            username    printf( "%s", getlogin() );
  35.  
  36.        By default, any text not matched  by  a  _f_l_e_x  scanner  is
  37.        copied to the output, so the net effect of this scanner is
  38.        to copy its input file to its output with each  occurrence
  39.        of  "username" expanded.  In this input, there is just one
  40.        rule.  "username" is the _p_a_t_t_e_r_n and the "printf"  is  the
  41.        _a_c_t_i_o_n_.  The "%%" marks the beginning of the rules.
  42.  
  43.        Here's another simple example:
  44.  
  45.                int num_lines = 0, num_chars = 0;
  46.  
  47.            %%
  48.            \n    ++num_lines; ++num_chars;
  49.            .     ++num_chars;
  50.  
  51.            %%
  52.            main()
  53.                {
  54.                yylex();
  55.                printf( "# of lines = %d, # of chars = %d\n",
  56.                        num_lines, num_chars );
  57.                }
  58.  
  59.        This  scanner counts the number of characters and the num-
  60.        ber of lines in its input (it  produces  no  output  other
  61.  
  62.  
  63.  
  64. Version 2.3                26 May 1990                          1
  65.  
  66.  
  67.  
  68.  
  69.  
  70. FLEX(1)                                                   FLEX(1)
  71.  
  72.  
  73.        than  the  final  report  on  the counts).  The first line
  74.        declares two globals, "num_lines" and  "num_chars",  which
  75.        are  accessible both inside yyyylleexx(()) and in the mmaaiinn(()) rou-
  76.        tine declared after the second "%%".  There are two rules,
  77.        one which matches a newline ("\n") and increments both the
  78.        line count and the character count, and one which  matches
  79.        any  character  other than a newline (indicated by the "."
  80.        regular expression).
  81.  
  82.        A somewhat more complicated example:
  83.  
  84.            /* scanner for a toy Pascal-like language */
  85.  
  86.            %{
  87.            /* need this for the call to atof() below */
  88.            #include <math.h>
  89.            %}
  90.  
  91.            DIGIT    [0-9]
  92.            ID       [a-z][a-z0-9]*
  93.  
  94.            %%
  95.  
  96.            {DIGIT}+    {
  97.                        printf( "An integer: %s (%d)\n", yytext,
  98.                                atoi( yytext ) );
  99.                        }
  100.  
  101.            {DIGIT}+"."{DIGIT}*        {
  102.                        printf( "A float: %s (%g)\n", yytext,
  103.                                atof( yytext ) );
  104.                        }
  105.  
  106.            if|then|begin|end|procedure|function        {
  107.                        printf( "A keyword: %s\n", yytext );
  108.                        }
  109.  
  110.            {ID}        printf( "An identifier: %s\n", yytext );
  111.  
  112.            "+"|"-"|"*"|"/"   printf( "An operator: %s\n", yytext );
  113.  
  114.            "{"[^}\n]*"}"     /* eat up one-line comments */
  115.  
  116.            [ \t\n]+          /* eat up whitespace */
  117.  
  118.            .           printf( "Unrecognized character: %s\n", yytext );
  119.  
  120.            %%
  121.  
  122.            main( argc, argv )
  123.            int argc;
  124.            char **argv;
  125.                {
  126.                ++argv, --argc;  /* skip over program name */
  127.  
  128.  
  129.  
  130. Version 2.3                26 May 1990                          2
  131.  
  132.  
  133.  
  134.  
  135.  
  136. FLEX(1)                                                   FLEX(1)
  137.  
  138.  
  139.                if ( argc > 0 )
  140.                        yyin = fopen( argv[0], "r" );
  141.                else
  142.                        yyin = stdin;
  143.  
  144.                yylex();
  145.                }
  146.  
  147.        This is the beginnings of a simple scanner for a  language
  148.        like  Pascal.  It identifies different types of _t_o_k_e_n_s and
  149.        reports on what it has seen.
  150.  
  151.        The details of this example will be explained in the  fol-
  152.        lowing sections.
  153.  
  154. FFOORRMMAATT OOFF TTHHEE IINNPPUUTT FFIILLEE
  155.        The  _f_l_e_x input file consists of three sections, separated
  156.        by a line with just %%%% in it:
  157.  
  158.            definitions
  159.            %%
  160.            rules
  161.            %%
  162.            user code
  163.  
  164.        The _d_e_f_i_n_i_t_i_o_n_s section contains  declarations  of  simple
  165.        _n_a_m_e  definitions  to  simplify the scanner specification,
  166.        and declarations of _s_t_a_r_t _c_o_n_d_i_t_i_o_n_s_, which are  explained
  167.        in a later section.
  168.  
  169.        Name definitions have the form:
  170.  
  171.            name definition
  172.  
  173.        The  "name" is a word beginning with a letter or an under-
  174.        score ('_') followed by zero or more letters, digits, '_',
  175.        or  '-'  (dash).   The definition is taken to begin at the
  176.        first non-white-space character  following  the  name  and
  177.        continuing  to  the  end  of the line.  The definition can
  178.        subsequently be referred to  using  "{name}",  which  will
  179.        expand to "(definition)".  For example,
  180.  
  181.            DIGIT    [0-9]
  182.            ID       [a-z][a-z0-9]*
  183.  
  184.        defines "DIGIT" to be a regular expression which matches a
  185.        single digit, and "ID" to be a  regular  expression  which
  186.        matches  a  letter  followed  by  zero-or-more letters-or-
  187.        digits.  A subsequent reference to
  188.  
  189.            {DIGIT}+"."{DIGIT}*
  190.  
  191.        is identical to
  192.  
  193.  
  194.  
  195.  
  196. Version 2.3                26 May 1990                          3
  197.  
  198.  
  199.  
  200.  
  201.  
  202. FLEX(1)                                                   FLEX(1)
  203.  
  204.  
  205.            ([0-9])+"."([0-9])*
  206.  
  207.        and matches one-or-more digits followed by a '.'  followed
  208.        by zero-or-more digits.
  209.  
  210.        The  _r_u_l_e_s  section of the _f_l_e_x input contains a series of
  211.        rules of the form:
  212.  
  213.            pattern   action
  214.  
  215.        where the pattern must be unindented and the  action  must
  216.        begin on the same line.
  217.  
  218.        See  below  for  a  further  description  of  patterns and
  219.        actions.
  220.  
  221.        Finally,  the  user  code  section  is  simply  copied  to
  222.        lleexx..yyyy..cc  verbatim.   It  is  used  for companion routines
  223.        which call or are called by the scanner.  The presence  of
  224.        this  section is optional; if it is missing, the second %%%%
  225.        in the input file may be skipped, too.
  226.  
  227.        In the definitions and rules sections, any  _i_n_d_e_n_t_e_d  text
  228.        or  text  enclosed  in %%{{ and %%}} is copied verbatim to the
  229.        output (with the %{}'s removed).  The  %{}'s  must  appear
  230.        unindented on lines by themselves.
  231.  
  232.        In  the  rules section, any indented or %{} text appearing
  233.        before the first rule may be  used  to  declare  variables
  234.        which  are  local  to  the scanning routine and (after the
  235.        declarations) code which is to be  executed  whenever  the
  236.        scanning  routine  is entered.  Other indented or %{} text
  237.        in the rule section is still copied to the output, but its
  238.        meaning is not well-defined and it may well cause compile-
  239.        time errors (this feature is present for _P_O_S_I_X compliance;
  240.        see below for other such features).
  241.  
  242.        In the definitions section, an unindented comment (i.e., a
  243.        line beginning with "/*") is also copied verbatim  to  the
  244.        output up to the next "*/".  Also, any line in the defini-
  245.        tions section beginning with '#' is ignored,  though  this
  246.        style  of  comment  is  deprecated  and may go away in the
  247.        future.
  248.  
  249. PPAATTTTEERRNNSS
  250.        The patterns in the input are written  using  an  extended
  251.        set of regular expressions.  These are:
  252.  
  253.            x          match the character 'x'
  254.            .          any character except newline
  255.            [xyz]      a "character class"; in this case, the pattern
  256.                         matches either an 'x', a 'y', or a 'z'
  257.            [abj-oZ]   a "character class" with a range in it; matches
  258.                         an 'a', a 'b', any letter from 'j' through 'o',
  259.  
  260.  
  261.  
  262. Version 2.3                26 May 1990                          4
  263.  
  264.  
  265.  
  266.  
  267.  
  268. FLEX(1)                                                   FLEX(1)
  269.  
  270.  
  271.                         or a 'Z'
  272.            [^A-Z]     a "negated character class", i.e., any character
  273.                         but those in the class.  In this case, any
  274.                         character EXCEPT an uppercase letter.
  275.            [^A-Z\n]   any character EXCEPT an uppercase letter or
  276.                         a newline
  277.            r*         zero or more r's, where r is any regular expression
  278.            r+         one or more r's
  279.            r?         zero or one r's (that is, "an optional r")
  280.            r{2,5}     anywhere from two to five r's
  281.            r{2,}      two or more r's
  282.            r{4}       exactly 4 r's
  283.            {name}     the expansion of the "name" definition
  284.                       (see above)
  285.            "[xyz]\"foo"
  286.                       the literal string: [xyz]"foo
  287.            \X         if X is an 'a', 'b', 'f', 'n', 'r', 't', or 'v',
  288.                         then the ANSI-C interpretation of \x.
  289.                         Otherwise, a literal 'X' (used to escape
  290.                         operators such as '*')
  291.            \123       the character with octal value 123
  292.            \x2a       the character with hexadecimal value 2a
  293.            (r)        match an r; parentheses are used to override
  294.                         precedence (see below)
  295.  
  296.  
  297.            rs         the regular expression r followed by the
  298.                         regular expression s; called "concatenation"
  299.  
  300.  
  301.            r|s        either an r or an s
  302.  
  303.  
  304.            r/s        an r but only if it is followed by an s.  The
  305.                         s is not part of the matched text.  This type
  306.                         of pattern is called as "trailing context".
  307.            ^r         an r, but only at the beginning of a line
  308.            r$         an r, but only at the end of a line.  Equivalent
  309.                         to "r/\n".
  310.  
  311.  
  312.            <s>r       an r, but only in start condition s (see
  313.                       below for discussion of start conditions)
  314.            <s1,s2,s3>r
  315.                       same, but in any of start conditions s1,
  316.                       s2, or s3
  317.  
  318.  
  319.            <<EOF>>    an end-of-file
  320.            <s1,s2><<EOF>>
  321.                       an end-of-file when in start condition s1 or s2
  322.  
  323.        The regular expressions listed above are grouped according
  324.        to precedence, from  highest  precedence  at  the  top  to
  325.  
  326.  
  327.  
  328. Version 2.3                26 May 1990                          5
  329.  
  330.  
  331.  
  332.  
  333.  
  334. FLEX(1)                                                   FLEX(1)
  335.  
  336.  
  337.        lowest  at  the bottom.  Those grouped together have equal
  338.        precedence.  For example,
  339.  
  340.            foo|bar*
  341.  
  342.        is the same as
  343.  
  344.            (foo)|(ba(r*))
  345.  
  346.        since the '*' operator has higher precedence than concate-
  347.        nation,  and  concatenation higher than alternation ('|').
  348.        This pattern therefore matches _e_i_t_h_e_r the string "foo"  _o_r
  349.        the  string  "ba"  followed by zero-or-more r's.  To match
  350.        "foo" or zero-or-more "bar"'s, use:
  351.  
  352.            foo|(bar)*
  353.  
  354.        and to match zero-or-more "foo"'s-or-"bar"'s:
  355.  
  356.            (foo|bar)*
  357.  
  358.  
  359.        Some notes on patterns:
  360.  
  361.        -      A negated character class such as the example "[^A-
  362.               Z]"  above  _w_i_l_l _m_a_t_c_h _a _n_e_w_l_i_n_e unless "\n" (or an
  363.               equivalent escape sequence) is one of  the  charac-
  364.               ters  explicitly  present  in the negated character
  365.               class (e.g., "[^A-Z\n]").  This is unlike how  many
  366.               other  regular expression tools treat negated char-
  367.               acter classes, but unfortunately the  inconsistency
  368.               is   historically  entrenched.   Matching  newlines
  369.               means that a pattern like [^"]* can match an entire
  370.               input  (overflowing  the  scanner's  input  buffer)
  371.               unless there's another quote in the input.
  372.  
  373.        -      A rule can have at most one  instance  of  trailing
  374.               context  (the  '/'  operator  or the '$' operator).
  375.               The start condition, '^',  and  "<<EOF>>"  patterns
  376.               can  only occur at the beginning of a pattern, and,
  377.               as well as with '/'  and  '$',  cannot  be  grouped
  378.               inside  parentheses.  A '^' which does not occur at
  379.               the beginning of a rule or a  '$'  which  does  not
  380.               occur  at the end of a rule loses its special prop-
  381.               erties and is treated as a normal character.
  382.  
  383.               The following are illegal:
  384.  
  385.                   foo/bar$
  386.                   <sc1>foo<sc2>bar
  387.  
  388.               Note that  the  first  of  these,  can  be  written
  389.               "foo/bar\n".
  390.  
  391.  
  392.  
  393.  
  394. Version 2.3                26 May 1990                          6
  395.  
  396.  
  397.  
  398.  
  399.  
  400. FLEX(1)                                                   FLEX(1)
  401.  
  402.  
  403.               The  following  will  result  in  '$'  or '^' being
  404.               treated as a normal character:
  405.  
  406.                   foo|(bar$)
  407.                   foo|^bar
  408.  
  409.               If what's wanted is a "foo" or a bar-followed-by-a-
  410.               newline,  the  following could be used (the special
  411.               '|' action is explained below):
  412.  
  413.                   foo      |
  414.                   bar$     /* action goes here */
  415.  
  416.               A similar trick will work for matching a foo  or  a
  417.               bar-at-the-beginning-of-a-line.
  418.  
  419. HHOOWW TTHHEE IINNPPUUTT IISS MMAATTCCHHEEDD
  420.        When  the  generated scanner is run, it analyzes its input
  421.        looking for strings which match any of its  patterns.   If
  422.        it  finds  more  than one match, it takes the one matching
  423.        the most text (for trailing context rules,  this  includes
  424.        the  length of the trailing part, even though it will then
  425.        be returned to the  input).   If  it  finds  two  or  more
  426.        matches  of  the same length, the rule listed first in the
  427.        _f_l_e_x input file is chosen.
  428.  
  429.        Once the match is determined, the  text  corresponding  to
  430.        the  match  (called  the  _t_o_k_e_n_)  is made available in the
  431.        global character pointer yyyytteexxtt,, and  its  length  in  the
  432.        global  integer  yyyylleenngg..   The _a_c_t_i_o_n corresponding to the
  433.        matched pattern is then executed (a more detailed descrip-
  434.        tion  of actions follows), and then the remaining input is
  435.        scanned for another match.
  436.  
  437.        If no match is found, then the _d_e_f_a_u_l_t _r_u_l_e  is  executed:
  438.        the  next character in the input is considered matched and
  439.        copied to the standard output.  Thus, the  simplest  legal
  440.        _f_l_e_x input is:
  441.  
  442.            %%
  443.  
  444.        which  generates  a  scanner  that simply copies its input
  445.        (one character at a time) to its output.
  446.  
  447. AACCTTIIOONNSS
  448.        Each pattern in a rule has a corresponding  action,  which
  449.        can be any arbitrary C statement.  The pattern ends at the
  450.        first non-escaped whitespace character; the  remainder  of
  451.        the line is its action.  If the action is empty, then when
  452.        the pattern is matched the  input  token  is  simply  dis-
  453.        carded.  For example, here is the specification for a pro-
  454.        gram which deletes all occurrences of "zap  me"  from  its
  455.        input:
  456.  
  457.  
  458.  
  459.  
  460. Version 2.3                26 May 1990                          7
  461.  
  462.  
  463.  
  464.  
  465.  
  466. FLEX(1)                                                   FLEX(1)
  467.  
  468.  
  469.            %%
  470.            "zap me"
  471.  
  472.        (It  will  copy  all  other characters in the input to the
  473.        output since they will be matched by the default rule.)
  474.  
  475.        Here is a program which  compresses  multiple  blanks  and
  476.        tabs  down  to  a single blank, and throws away whitespace
  477.        found at the end of a line:
  478.  
  479.            %%
  480.            [ \t]+        putchar( ' ' );
  481.            [ \t]+$       /* ignore this token */
  482.  
  483.  
  484.        If the action contains a '{', then the action  spans  till
  485.        the  balancing '}' is found, and the action may cross mul-
  486.        tiple lines.  _f_l_e_x knows about C strings and comments  and
  487.        won't  be  fooled  by  braces  found within them, but also
  488.        allows actions to begin with  %%{{  and  will  consider  the
  489.        action to be all the text up to the next %%}} (regardless of
  490.        ordinary braces inside the action).
  491.  
  492.        An action consisting solely of a vertical bar ('|')  means
  493.        "same  as the action for the next rule."  See below for an
  494.        illustration.
  495.  
  496.        Actions can include arbitrary  C  code,  including  rreettuurrnn
  497.        statements  to  return  a value to whatever routine called
  498.        yyyylleexx(())..  Each time yyyylleexx(()) is called  it  continues  pro-
  499.        cessing tokens from where it last left off until it either
  500.        reaches the end of the file or executes a return.  Once it
  501.        reaches  an end-of-file, however, then any subsequent call
  502.        to  yyyylleexx(())  will  simply   immediately   return,   unless
  503.        yyyyrreessttaarrtt(()) is first called (see below).
  504.  
  505.        Actions are not allowed to modify yytext or yyleng.
  506.  
  507.        There  are  a  number  of  special directives which can be
  508.        included within an action:
  509.  
  510.        -      EECCHHOO copies yytext to the scanner's output.
  511.  
  512.        -      BBEEGGIINN followed by the name  of  a  start  condition
  513.               places  the scanner in the corresponding start con-
  514.               dition (see below).
  515.  
  516.        -      RREEJJEECCTT directs the scanner to  proceed  on  to  the
  517.               "second  best"  rule  which matched the input (or a
  518.               prefix of  the  input).   The  rule  is  chosen  as
  519.               described  above in "How the Input is Matched", and
  520.               yyyytteexxtt and yyyylleenngg set  up  appropriately.   It  may
  521.               either  be  one  which  matched as much text as the
  522.               originally chosen rule but came later in  the  _f_l_e_x
  523.  
  524.  
  525.  
  526. Version 2.3                26 May 1990                          8
  527.  
  528.  
  529.  
  530.  
  531.  
  532. FLEX(1)                                                   FLEX(1)
  533.  
  534.  
  535.               input  file,  or  one which matched less text.  For
  536.               example, the following will both count the words in
  537.               the  input  and call the routine special() whenever
  538.               "frob" is seen:
  539.  
  540.                           int word_count = 0;
  541.                   %%
  542.  
  543.                   frob        special(); REJECT;
  544.                   [^ \t\n]+   ++word_count;
  545.  
  546.               Without the RREEJJEECCTT,, any "frob"'s in the input would
  547.               not be counted as words, since the scanner normally
  548.               executes  only  one  action  per  token.   Multiple
  549.               RREEJJEECCTT''ss  are  allowed,  each  one finding the next
  550.               best choice to  the  currently  active  rule.   For
  551.               example, when the following scanner scans the token
  552.               "abcd", it will write "abcdabcaba" to the output:
  553.  
  554.                   %%
  555.                   a        |
  556.                   ab       |
  557.                   abc      |
  558.                   abcd     ECHO; REJECT;
  559.                   .|\n     /* eat up any unmatched character */
  560.  
  561.               (The first three rules share  the  fourth's  action
  562.               since  they use the special '|' action.)  RREEJJEECCTT is
  563.               a particularly expensive feature in  terms  scanner
  564.               performance;  if it is used in _a_n_y of the scanner's
  565.               actions it will slow  down  _a_l_l  of  the  scanner's
  566.               matching.   Furthermore, RREEJJEECCTT cannot be used with
  567.               the _-_f or _-_F options (see below).
  568.  
  569.               Note also that unlike the  other  special  actions,
  570.               RREEJJEECCTT  is  a _b_r_a_n_c_h_; code immediately following it
  571.               in the action will _n_o_t be executed.
  572.  
  573.        -      yyyymmoorree(()) tells the scanner that the  next  time  it
  574.               matches  a  rule, the corresponding token should be
  575.               _a_p_p_e_n_d_e_d onto the current value  of  yyyytteexxtt  rather
  576.               than  replacing  it.   For example, given the input
  577.               "mega-kludge" the following will write  "mega-mega-
  578.               kludge" to the output:
  579.  
  580.                   %%
  581.                   mega-    ECHO; yymore();
  582.                   kludge   ECHO;
  583.  
  584.               First  "mega-" is matched and echoed to the output.
  585.               Then "kludge" is matched, but the previous  "mega-"
  586.               is  still hanging around at the beginning of yyyytteexxtt
  587.               so the EECCHHOO for the  "kludge"  rule  will  actually
  588.               write  "mega-kludge".   The presence of yyyymmoorree(()) in
  589.  
  590.  
  591.  
  592. Version 2.3                26 May 1990                          9
  593.  
  594.  
  595.  
  596.  
  597.  
  598. FLEX(1)                                                   FLEX(1)
  599.  
  600.  
  601.               the scanner's action entails  a  minor  performance
  602.               penalty in the scanner's matching speed.
  603.  
  604.        -      yyyylleessss((nn)) returns all but the first _n characters of
  605.               the current token back to the input  stream,  where
  606.               they  will  be rescanned when the scanner looks for
  607.               the next match.  yyyytteexxtt  and  yyyylleenngg  are  adjusted
  608.               appropriately  (e.g., yyyylleenngg will now be equal to _n
  609.               ).  For example, on the input "foobar" the  follow-
  610.               ing will write out "foobarbar":
  611.  
  612.                   %%
  613.                   foobar    ECHO; yyless(3);
  614.                   [a-z]+    ECHO;
  615.  
  616.               An  argument  of  0 to yyyylleessss will cause the entire
  617.               current input string to be scanned  again.   Unless
  618.               you've  changed  how  the scanner will subsequently
  619.               process its input (using BBEEGGIINN,, for example),  this
  620.               will result in an endless loop.
  621.  
  622.        -      uunnppuutt((cc))  puts  the character _c back onto the input
  623.               stream.  It will be  the  next  character  scanned.
  624.               The  following  action  will take the current token
  625.               and cause it to be rescanned enclosed in  parenthe-
  626.               ses.
  627.  
  628.                   {
  629.                   int i;
  630.                   unput( ')' );
  631.                   for ( i = yyleng - 1; i >= 0; --i )
  632.                       unput( yytext[i] );
  633.                   unput( '(' );
  634.                   }
  635.  
  636.               Note that since each uunnppuutt(()) puts the given charac-
  637.               ter back at the  _b_e_g_i_n_n_i_n_g  of  the  input  stream,
  638.               pushing back strings must be done back-to-front.
  639.  
  640.        -      iinnppuutt(())  reads  the  next  character from the input
  641.               stream.  For example, the following is one  way  to
  642.               eat up C comments:
  643.  
  644.                   %%
  645.                   "/*"        {
  646.                               register int c;
  647.  
  648.                               for ( ; ; )
  649.                                   {
  650.                                   while ( (c = input()) != '*' &&
  651.                                           c != EOF )
  652.                                       ;    /* eat up text of comment */
  653.  
  654.                                   if ( c == '*' )
  655.  
  656.  
  657.  
  658. Version 2.3                26 May 1990                         10
  659.  
  660.  
  661.  
  662.  
  663.  
  664. FLEX(1)                                                   FLEX(1)
  665.  
  666.  
  667.                                       {
  668.                                       while ( (c = input()) == '*' )
  669.                                           ;
  670.                                       if ( c == '/' )
  671.                                           break;    /* found the end */
  672.                                       }
  673.  
  674.                                   if ( c == EOF )
  675.                                       {
  676.                                       error( "EOF in comment" );
  677.                                       break;
  678.                                       }
  679.                                   }
  680.                               }
  681.  
  682.               (Note  that  if  the scanner is compiled using CC++++,,
  683.               then iinnppuutt(()) is instead referred to  as  yyyyiinnppuutt(()),,
  684.               in  order to avoid a name clash with the CC++++ stream
  685.               by the name of _i_n_p_u_t_._)
  686.  
  687.        -      yyyytteerrmmiinnaattee(()) can be  used  in  lieu  of  a  return
  688.               statement  in an action.  It terminates the scanner
  689.               and returns a 0 to the scanner's caller, indicating
  690.               "all  done".   Subsequent calls to the scanner will
  691.               immediately return unless preceded  by  a  call  to
  692.               yyyyrreessttaarrtt(()) (see below).  By default, yyyytteerrmmiinnaattee(())
  693.               is also called when an end-of-file is  encountered.
  694.               It is a macro and may be redefined.
  695.  
  696. TTHHEE GGEENNEERRAATTEEDD SSCCAANNNNEERR
  697.        The  output  of  _f_l_e_x is the file lleexx..yyyy..cc,, which contains
  698.        the scanning routine yyyylleexx(()),, a number of tables  used  by
  699.        it for matching tokens, and a number of auxiliary routines
  700.        and macros.  By default, yyyylleexx(()) is declared as follows:
  701.  
  702.            int yylex()
  703.                {
  704.                ... various definitions and the actions in here ...
  705.                }
  706.  
  707.        (If your environment supports function prototypes, then it
  708.        will  be  "int  yylex(  void  )".)  This definition may be
  709.        changed by redefining the "YY_DECL" macro.   For  example,
  710.        you could use:
  711.  
  712.            #undef YY_DECL
  713.            #define YY_DECL float lexscan( a, b ) float a, b;
  714.  
  715.        to give the scanning routine the name _l_e_x_s_c_a_n_, returning a
  716.        float, and taking two floats as arguments.  Note  that  if
  717.        you  give  arguments  to the scanning routine using a K&R-
  718.        style/non-prototyped function declaration, you must termi-
  719.        nate the definition with a semi-colon (;).
  720.  
  721.  
  722.  
  723.  
  724. Version 2.3                26 May 1990                         11
  725.  
  726.  
  727.  
  728.  
  729.  
  730. FLEX(1)                                                   FLEX(1)
  731.  
  732.  
  733.        Whenever  yyyylleexx(())  is  called,  it  scans  tokens from the
  734.        global input file _y_y_i_n (which defaults to stdin).  It con-
  735.        tinues  until  it  either reaches an end-of-file (at which
  736.        point it returns the value 0) or one of its  actions  exe-
  737.        cutes a _r_e_t_u_r_n statement.  In the former case, when called
  738.        again  the  scanner   will   immediately   return   unless
  739.        yyyyrreessttaarrtt(()) is called to point _y_y_i_n at the new input file.
  740.        ( yyyyrreessttaarrtt(()) takes one argument, a FFIILLEE **  pointer.)   In
  741.        the  latter case (i.e., when an action executes a return),
  742.        the scanner may then be called again and  it  will  resume
  743.        scanning where it left off.
  744.  
  745.        By  default  (and for purposes of efficiency), the scanner
  746.        uses block-reads rather than simple _g_e_t_c_(_) calls  to  read
  747.        characters from _y_y_i_n_.  The nature of how it gets its input
  748.        can  be  controlled  by  redefining  the  YYYY__IINNPPUUTT  macro.
  749.        YY_INPUT's           calling          sequence          is
  750.        "YY_INPUT(buf,result,max_size)".  Its action is  to  place
  751.        up  to  _m_a_x___s_i_z_e characters in the character array _b_u_f and
  752.        return in the integer variable _r_e_s_u_l_t either the number of
  753.        characters  read  or  the constant YY_NULL (0 on Unix sys-
  754.        tems) to indicate EOF.  The default  YY_INPUT  reads  from
  755.        the global file-pointer "yyin".
  756.  
  757.        A sample redefinition of YY_INPUT (in the definitions sec-
  758.        tion of the input file):
  759.  
  760.            %{
  761.            #undef YY_INPUT
  762.            #define YY_INPUT(buf,result,max_size) \
  763.                { \
  764.                int c = getchar(); \
  765.                result = (c == EOF) ? YY_NULL : (buf[0] = c, 1); \
  766.                }
  767.            %}
  768.  
  769.        This definition will change the input processing to  occur
  770.        one character at a time.
  771.  
  772.        You also can add in things like keeping track of the input
  773.        line number this way; but don't expect your scanner to  go
  774.        very fast.
  775.  
  776.        When  the  scanner receives an end-of-file indication from
  777.        YY_INPUT,  it  then  checks  the  yyyywwrraapp(())  function.   If
  778.        yyyywwrraapp(()) returns false (zero), then it is assumed that the
  779.        function has gone ahead  and  set  up  _y_y_i_n  to  point  to
  780.        another input file, and scanning continues.  If it returns
  781.        true (non-zero), then the scanner terminates, returning  0
  782.        to its caller.
  783.  
  784.        The  default  yyyywwrraapp(())  always  returns  1.  Presently, to
  785.        redefine it you must first "#undef yywrap", as it is  cur-
  786.        rently  implemented  as  a  macro.   As  indicated  by the
  787.  
  788.  
  789.  
  790. Version 2.3                26 May 1990                         12
  791.  
  792.  
  793.  
  794.  
  795.  
  796. FLEX(1)                                                   FLEX(1)
  797.  
  798.  
  799.        hedging in the previous sentence, it may be changed  to  a
  800.        true function in the near future.
  801.  
  802.        The  scanner  writes  its  EECCHHOO output to the _y_y_o_u_t global
  803.        (default, stdout), which may be redefined by the user sim-
  804.        ply by assigning it to some other FFIILLEE pointer.
  805.  
  806. SSTTAARRTT CCOONNDDIITTIIOONNSS
  807.        _f_l_e_x  provides  a  mechanism  for conditionally activating
  808.        rules.  Any rule whose pattern  is  prefixed  with  "<sc>"
  809.        will  only be active when the scanner is in the start con-
  810.        dition named "sc".  For example,
  811.  
  812.            <STRING>[^"]*        { /* eat up the string body ... */
  813.                        ...
  814.                        }
  815.  
  816.        will be active only when the scanner is  in  the  "STRING"
  817.        start condition, and
  818.  
  819.            <INITIAL,STRING,QUOTE>\.        { /* handle an escape ... */
  820.                        ...
  821.                        }
  822.  
  823.        will  be  active  only when the current start condition is
  824.        either "INITIAL", "STRING", or "QUOTE".
  825.  
  826.        Start conditions are declared in the  definitions  (first)
  827.        section of the input using unindented lines beginning with
  828.        either %%ss or %%xx followed by a list of names.   The  former
  829.        declares  _i_n_c_l_u_s_i_v_e start conditions, the latter _e_x_c_l_u_s_i_v_e
  830.        start conditions.  A start condition  is  activated  using
  831.        the  BBEEGGIINN  action.   Until  the next BBEEGGIINN action is exe-
  832.        cuted, rules with the given start condition will be active
  833.        and  rules  with  other start conditions will be inactive.
  834.        If the start condition is _i_n_c_l_u_s_i_v_e_, then  rules  with  no
  835.        start  conditions  at  all  will also be active.  If it is
  836.        _e_x_c_l_u_s_i_v_e_, then _o_n_l_y rules qualified with the start condi-
  837.        tion  will  be  active.   A set of rules contingent on the
  838.        same exclusive start condition describe a scanner which is
  839.        independent  of  any of the other rules in the _f_l_e_x input.
  840.        Because of this, exclusive start conditions make  it  easy
  841.        to  specify  "mini-scanners"  which  scan  portions of the
  842.        input that  are  syntactically  different  from  the  rest
  843.        (e.g., comments).
  844.  
  845.        If  the  distinction between inclusive and exclusive start
  846.        conditions is still a little vague, here's a simple  exam-
  847.        ple  illustrating the connection between the two.  The set
  848.        of rules:
  849.  
  850.            %s example
  851.            %%
  852.            <example>foo           /* do something */
  853.  
  854.  
  855.  
  856. Version 2.3                26 May 1990                         13
  857.  
  858.  
  859.  
  860.  
  861.  
  862. FLEX(1)                                                   FLEX(1)
  863.  
  864.  
  865.        is equivalent to
  866.  
  867.            %x example
  868.            %%
  869.            <INITIAL,example>foo   /* do something */
  870.  
  871.  
  872.        The default rule (to EECCHHOO any unmatched character) remains
  873.        active in start conditions.
  874.  
  875.        BBEEGGIINN((00))  returns  to  the  original  state where only the
  876.        rules with no start conditions are active.  This state can
  877.        also  be  referred to as the start-condition "INITIAL", so
  878.        BBEEGGIINN((IINNIITTIIAALL)) is equivalent to BBEEGGIINN((00))..  (The  parenthe-
  879.        ses  around  the start condition name are not required but
  880.        are considered good style.)
  881.  
  882.        BBEEGGIINN actions can also be given as indented  code  at  the
  883.        beginning  of the rules section.  For example, the follow-
  884.        ing will cause the scanner to enter  the  "SPECIAL"  start
  885.        condition  whenever _y_y_l_e_x_(_) is called and the global vari-
  886.        able _e_n_t_e_r___s_p_e_c_i_a_l is true:
  887.  
  888.                    int enter_special;
  889.  
  890.            %x SPECIAL
  891.            %%
  892.                    if ( enter_special )
  893.                        BEGIN(SPECIAL);
  894.  
  895.            <SPECIAL>blahblahblah
  896.            ...more rules follow...
  897.  
  898.  
  899.        To illustrate the uses of  start  conditions,  here  is  a
  900.        scanner  which provides two different interpretations of a
  901.        string like "123.456".  By default it will treat it as  as
  902.        three  tokens,  the  integer  "123",  a dot ('.'), and the
  903.        integer "456".  But if the string is preceded  earlier  in
  904.        the line by the string "expect-floats" it will treat it as
  905.        a single token, the floating-point number 123.456:
  906.  
  907.            %{
  908.            #include <math.h>
  909.            %}
  910.            %s expect
  911.  
  912.            %%
  913.            expect-floats        BEGIN(expect);
  914.  
  915.            <expect>[0-9]+"."[0-9]+      {
  916.                        printf( "found a float, = %f\n",
  917.                                atof( yytext ) );
  918.                        }
  919.  
  920.  
  921.  
  922. Version 2.3                26 May 1990                         14
  923.  
  924.  
  925.  
  926.  
  927.  
  928. FLEX(1)                                                   FLEX(1)
  929.  
  930.  
  931.            <expect>\n           {
  932.                        /* that's the end of the line, so
  933.                         * we need another "expect-number"
  934.                         * before we'll recognize any more
  935.                         * numbers
  936.                         */
  937.                        BEGIN(INITIAL);
  938.                        }
  939.  
  940.            [0-9]+      {
  941.                        printf( "found an integer, = %d\n",
  942.                                atoi( yytext ) );
  943.                        }
  944.  
  945.            "."         printf( "found a dot\n" );
  946.  
  947.        Here is a scanner which recognizes (and discards)  C  com-
  948.        ments while maintaining a count of the current input line.
  949.  
  950.            %x comment
  951.            %%
  952.                    int line_num = 1;
  953.  
  954.            "/*"         BEGIN(comment);
  955.  
  956.            <comment>[^*\n]*        /* eat anything that's not a '*' */
  957.            <comment>"*"+[^*/\n]*   /* eat up '*'s not followed by '/'s */
  958.            <comment>\n             ++line_num;
  959.            <comment>"*"+"/"        BEGIN(INITIAL);
  960.  
  961.        Note that start-conditions names are really integer values
  962.        and  can  be  stored  as  such.   Thus, the above could be
  963.        extended in the following fashion:
  964.  
  965.            %x comment foo
  966.            %%
  967.                    int line_num = 1;
  968.                    int comment_caller;
  969.  
  970.            "/*"         {
  971.                         comment_caller = INITIAL;
  972.                         BEGIN(comment);
  973.                         }
  974.  
  975.            ...
  976.  
  977.            <foo>"/*"    {
  978.                         comment_caller = foo;
  979.                         BEGIN(comment);
  980.                         }
  981.  
  982.            <comment>[^*\n]*        /* eat anything that's not a '*' */
  983.            <comment>"*"+[^*/\n]*   /* eat up '*'s not followed by '/'s */
  984.            <comment>\n             ++line_num;
  985.  
  986.  
  987.  
  988. Version 2.3                26 May 1990                         15
  989.  
  990.  
  991.  
  992.  
  993.  
  994. FLEX(1)                                                   FLEX(1)
  995.  
  996.  
  997.            <comment>"*"+"/"        BEGIN(comment_caller);
  998.  
  999.        One can then implement a "stack" of start conditions using
  1000.        an array of integers.  (It is likely that such stacks will
  1001.        become a full-fledged _f_l_e_x feature in the future.)   Note,
  1002.        though,  that start conditions do not have their own name-
  1003.        space; %s's and %x's declare names in the same fashion  as
  1004.        #define's.
  1005.  
  1006. MMUULLTTIIPPLLEE IINNPPUUTT BBUUFFFFEERRSS
  1007.        Some  scanners  (such  as  those  which  support "include"
  1008.        files) require reading from  several  input  streams.   As
  1009.        _f_l_e_x  scanners  do a large amount of buffering, one cannot
  1010.        control where the next input will be read from  by  simply
  1011.        writing a YYYY__IINNPPUUTT which is sensitive to the scanning con-
  1012.        text.  YYYY__IINNPPUUTT is only called when  the  scanner  reaches
  1013.        the  end  of  its  buffer,  which may be a long time after
  1014.        scanning a statement such as an "include"  which  requires
  1015.        switching the input source.
  1016.  
  1017.        To  negotiate  these  sorts  of  problems, _f_l_e_x provides a
  1018.        mechanism for  creating  and  switching  between  multiple
  1019.        input buffers.  An input buffer is created by using:
  1020.  
  1021.            YY_BUFFER_STATE yy_create_buffer( FILE *file, int size )
  1022.  
  1023.        which takes a _F_I_L_E pointer and a size and creates a buffer
  1024.        associated with the given file and large  enough  to  hold
  1025.        _s_i_z_e  characters  (when  in doubt, use YYYY__BBUUFF__SSIIZZEE for the
  1026.        size).  It returns a  YYYY__BBUUFFFFEERR__SSTTAATTEE  handle,  which  may
  1027.        then be passed to other routines:
  1028.  
  1029.            void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer )
  1030.  
  1031.        switches  the  scanner's input buffer so subsequent tokens
  1032.        will     come     from     _n_e_w___b_u_f_f_e_r_.      Note      that
  1033.        yyyy__sswwiittcchh__ttoo__bbuuffffeerr(())  may  be  used  by  yywrap() to sets
  1034.        things up for continued scanning, instead of opening a new
  1035.        file and pointing _y_y_i_n at it.
  1036.  
  1037.            void yy_delete_buffer( YY_BUFFER_STATE buffer )
  1038.  
  1039.        is used to reclaim the storage associated with a buffer.
  1040.  
  1041.        yyyy__nneeww__bbuuffffeerr(())  is  an alias for yyyy__ccrreeaattee__bbuuffffeerr(()),, pro-
  1042.        vided for compatibility with the C++ use of _n_e_w and _d_e_l_e_t_e
  1043.        for creating and destroying dynamic objects.
  1044.  
  1045.        Finally,    the    YYYY__CCUURRRREENNTT__BBUUFFFFEERR   macro   returns   a
  1046.        YYYY__BBUUFFFFEERR__SSTTAATTEE handle to the current buffer.
  1047.  
  1048.        Here is an example of using these features for  writing  a
  1049.        scanner  which  expands include files (the <<<<EEOOFF>>>> feature
  1050.        is discussed below):
  1051.  
  1052.  
  1053.  
  1054. Version 2.3                26 May 1990                         16
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. FLEX(1)                                                   FLEX(1)
  1061.  
  1062.  
  1063.            /* the "incl" state is used for picking up the name
  1064.             * of an include file
  1065.             */
  1066.            %x incl
  1067.  
  1068.            %{
  1069.            #define MAX_INCLUDE_DEPTH 10
  1070.            YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
  1071.            int include_stack_ptr = 0;
  1072.            %}
  1073.  
  1074.            %%
  1075.            include             BEGIN(incl);
  1076.  
  1077.            [a-z]+              ECHO;
  1078.            [^a-z\n]*\n?        ECHO;
  1079.  
  1080.            <incl>[ \t]*      /* eat the whitespace */
  1081.            <incl>[^ \t\n]+   { /* got the include file name */
  1082.                    if ( include_stack_ptr >= MAX_INCLUDE_DEPTH )
  1083.                        {
  1084.                        fprintf( stderr, "Includes nested too deeply" );
  1085.                        exit( 1 );
  1086.                        }
  1087.  
  1088.                    include_stack[include_stack_ptr++] =
  1089.                        YY_CURRENT_BUFFER;
  1090.  
  1091.                    yyin = fopen( yytext, "r" );
  1092.  
  1093.                    if ( ! yyin )
  1094.                        error( ... );
  1095.  
  1096.                    yy_switch_to_buffer(
  1097.                        yy_create_buffer( yyin, YY_BUF_SIZE ) );
  1098.  
  1099.                    BEGIN(INITIAL);
  1100.                    }
  1101.  
  1102.            <<EOF>> {
  1103.                    if ( --include_stack_ptr < 0 )
  1104.                        {
  1105.                        yyterminate();
  1106.                        }
  1107.  
  1108.                    else
  1109.                        yy_switch_to_buffer(
  1110.                             include_stack[include_stack_ptr] );
  1111.                    }
  1112.  
  1113.  
  1114. EENNDD--OOFF--FFIILLEE RRUULLEESS
  1115.        The special rule "<<EOF>>" indicates actions which are  to
  1116.        be  taken  when an end-of-file is encountered and yywrap()
  1117.  
  1118.  
  1119.  
  1120. Version 2.3                26 May 1990                         17
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. FLEX(1)                                                   FLEX(1)
  1127.  
  1128.  
  1129.        returns non-zero (i.e., indicates no further files to pro-
  1130.        cess).   The  action  must  finish  by  doing  one of four
  1131.        things:
  1132.  
  1133.        -      the special YYYY__NNEEWW__FFIILLEE action, if  _y_y_i_n  has  been
  1134.               pointed at a new file to process;
  1135.  
  1136.        -      a _r_e_t_u_r_n statement;
  1137.  
  1138.        -      the special yyyytteerrmmiinnaattee(()) action;
  1139.  
  1140.        -      or,    switching    to    a    new   buffer   using
  1141.               yyyy__sswwiittcchh__ttoo__bbuuffffeerr(())  as  shown  in  the   example
  1142.               above.
  1143.  
  1144.        <<EOF>>  rules  may  not be used with other patterns; they
  1145.        may only be qualified with a list of start conditions.  If
  1146.        an  unqualified  <<EOF>>  rule is given, it applies to _a_l_l
  1147.        start  conditions  which  do  not  already  have   <<EOF>>
  1148.        actions.   To specify an <<EOF>> rule for only the initial
  1149.        start condition, use
  1150.  
  1151.            <INITIAL><<EOF>>
  1152.  
  1153.  
  1154.        These rules are useful for catching things  like  unclosed
  1155.        comments.  An example:
  1156.  
  1157.            %x quote
  1158.            %%
  1159.  
  1160.            ...other rules for dealing with quotes...
  1161.  
  1162.            <quote><<EOF>>   {
  1163.                     error( "unterminated quote" );
  1164.                     yyterminate();
  1165.                     }
  1166.            <<EOF>>  {
  1167.                     if ( *++filelist )
  1168.                         {
  1169.                         yyin = fopen( *filelist, "r" );
  1170.                         YY_NEW_FILE;
  1171.                         }
  1172.                     else
  1173.                        yyterminate();
  1174.                     }
  1175.  
  1176.  
  1177. MMIISSCCEELLLLAANNEEOOUUSS MMAACCRROOSS
  1178.        The  macro  YY_USER_ACTION  can be redefined to provide an
  1179.        action which is  always  executed  prior  to  the  matched
  1180.        rule's action.  For example, it could be #define'd to call
  1181.        a routine to convert yytext to lower-case.
  1182.  
  1183.  
  1184.  
  1185.  
  1186. Version 2.3                26 May 1990                         18
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. FLEX(1)                                                   FLEX(1)
  1193.  
  1194.  
  1195.        The macro YYYY__UUSSEERR__IINNIITT may  be  redefined  to  provide  an
  1196.        action which is always executed before the first scan (and
  1197.        before the scanner's internal initializations  are  done).
  1198.        For example, it could be used to call a routine to read in
  1199.        a data table or open a logging file.
  1200.  
  1201.        In the generated scanner, the actions are all gathered  in
  1202.        one  large  switch statement and separated using YYYY__BBRREEAAKK,,
  1203.        which may be  redefined.   By  default,  it  is  simply  a
  1204.        "break", to separate each rule's action from the following
  1205.        rule's.  Redefining  YYYY__BBRREEAAKK  allows,  for  example,  C++
  1206.        users  to #define YY_BREAK to do nothing (while being very
  1207.        careful  that  every  rule  ends  with  a  "break"  or   a
  1208.        "return"!)  to  avoid suffering from unreachable statement
  1209.        warnings where because a rule's action ends with "return",
  1210.        the YYYY__BBRREEAAKK is inaccessible.
  1211.  
  1212. IINNTTEERRFFAACCIINNGG WWIITTHH YYAACCCC
  1213.        One of the main uses of _f_l_e_x is as a companion to the _y_a_c_c
  1214.        parser-generator.  _y_a_c_c parsers expect to call  a  routine
  1215.        named  yyyylleexx(())  to find the next input token.  The routine
  1216.        is supposed to return the type of the next token  as  well
  1217.        as  putting any associated value in the global yyyyllvvaall..  To
  1218.        use _f_l_e_x with _y_a_c_c_, one specifies the --dd option to _y_a_c_c to
  1219.        instruct  it to generate the file yy..ttaabb..hh containing defi-
  1220.        nitions of all the %%ttookkeennss appearing in  the  _y_a_c_c  input.
  1221.        This file is then included in the _f_l_e_x scanner.  For exam-
  1222.        ple, if one of the tokens is  "TOK_NUMBER",  part  of  the
  1223.        scanner might look like:
  1224.  
  1225.            %{
  1226.            #include "y.tab.h"
  1227.            %}
  1228.  
  1229.            %%
  1230.  
  1231.            [0-9]+        yylval = atoi( yytext ); return TOK_NUMBER;
  1232.  
  1233.  
  1234. TTRRAANNSSLLAATTIIOONN TTAABBLLEE
  1235.        In  the name of POSIX compliance, _f_l_e_x supports a _t_r_a_n_s_l_a_-
  1236.        _t_i_o_n _t_a_b_l_e for mapping input characters into groups.   The
  1237.        table  is  specified  in the first section, and its format
  1238.        looks like:
  1239.  
  1240.            %t
  1241.            1        abcd
  1242.            2        ABCDEFGHIJKLMNOPQRSTUVWXYZ
  1243.            52       0123456789
  1244.            6        \t\ \n
  1245.            %t
  1246.  
  1247.        This example specifies that the characters 'a', 'b',  'c',
  1248.        and  'd'  are  to  all be lumped into group #1, upper-case
  1249.  
  1250.  
  1251.  
  1252. Version 2.3                26 May 1990                         19
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. FLEX(1)                                                   FLEX(1)
  1259.  
  1260.  
  1261.        letters in group #2, digits in group  #52,  tabs,  blanks,
  1262.        and  newlines  into group #6, and _n_o _o_t_h_e_r _c_h_a_r_a_c_t_e_r_s _w_i_l_l
  1263.        _a_p_p_e_a_r _i_n _t_h_e _p_a_t_t_e_r_n_s_.  The group  numbers  are  actually
  1264.        disregarded by _f_l_e_x_; %%tt serves, though, to lump characters
  1265.        together.  Given the above table, for example, the pattern
  1266.        "a(AA)*5"  is  equivalent  to  "d(ZQ)*0".   They both say,
  1267.        "match any character in group #1, followed by zero-or-more
  1268.        pairs of characters from group #2, followed by a character
  1269.        from group #52."  Thus %%tt provides a crude way for  intro-
  1270.        ducing equivalence classes into the scanner specification.
  1271.  
  1272.        Note that the --ii  option  (see  below)  coupled  with  the
  1273.        equivalence  classes  which  _f_l_e_x  automatically generates
  1274.        take care of virtually all the instances  when  one  might
  1275.        consider  using  %%tt..  But what the hell, it's there if you
  1276.        want it.
  1277.  
  1278. OOPPTTIIOONNSS
  1279.        _f_l_e_x has the following options:
  1280.  
  1281.        --bb     Generate backtracking information to _l_e_x_._b_a_c_k_t_r_a_c_k_.
  1282.               This  is  a  list  of  scanner states which require
  1283.               backtracking and the input characters on which they
  1284.               do so.  By adding rules one can remove backtracking
  1285.               states.  If all backtracking states are  eliminated
  1286.               and  --ff  or  --FF is used, the generated scanner will
  1287.               run faster (see the --pp flag).  Only users who  wish
  1288.               to  squeeze  every last cycle out of their scanners
  1289.               need worry about this option.  (See the section  on
  1290.               PERFORMANCE CONSIDERATIONS below.)
  1291.  
  1292.        --cc     is  a  do-nothing,  deprecated  option included for
  1293.               POSIX compliance.
  1294.  
  1295.               NNOOTTEE:: in previous releases  of  _f_l_e_x  --cc  specified
  1296.               table-compression  options.   This functionality is
  1297.               now given by the --CC flag.  To ease the  the  impact
  1298.               of  this  change,  when _f_l_e_x encounters --cc,, it cur-
  1299.               rently issues a warning message and assumes that --CC
  1300.               was  desired  instead.   In the future this "promo-
  1301.               tion" of --cc to --CC will go away in the name of  full
  1302.               POSIX  compliance  (unless  the  POSIX  meaning  is
  1303.               removed first).
  1304.  
  1305.        --dd     makes the generated  scanner  run  in  _d_e_b_u_g  mode.
  1306.               Whenever  a  pattern  is  recognized and the global
  1307.               yyyy__fflleexx__ddeebbuugg is non-zero (which is  the  default),
  1308.               the  scanner  will  write  to  _s_t_d_e_r_r a line of the
  1309.               form:
  1310.  
  1311.                   --accepting rule at line 53 ("the matched text")
  1312.  
  1313.               The line number refers to the location of the  rule
  1314.               in  the  file  defining the scanner (i.e., the file
  1315.  
  1316.  
  1317.  
  1318. Version 2.3                26 May 1990                         20
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324. FLEX(1)                                                   FLEX(1)
  1325.  
  1326.  
  1327.               that was fed to flex).  Messages are also generated
  1328.               when  the  scanner  backtracks, accepts the default
  1329.               rule, reaches the  end  of  its  input  buffer  (or
  1330.               encounters  a  NUL; at this point, the two look the
  1331.               same as far as the scanner's concerned), or reaches
  1332.               an end-of-file.
  1333.  
  1334.        --ff     specifies (take your pick) _f_u_l_l _t_a_b_l_e or _f_a_s_t _s_c_a_n_-
  1335.               _n_e_r_.  No table compression is done.  The result  is
  1336.               large  but  fast.  This option is equivalent to --CCff
  1337.               (see below).
  1338.  
  1339.        --ii     instructs _f_l_e_x to generate a _c_a_s_e_-_i_n_s_e_n_s_i_t_i_v_e scan-
  1340.               ner.   The  case of letters given in the _f_l_e_x input
  1341.               patterns will be ignored, and tokens in  the  input
  1342.               will  be  matched  regardless of case.  The matched
  1343.               text given in _y_y_t_e_x_t will have the  preserved  case
  1344.               (i.e., it will not be folded).
  1345.  
  1346.        --nn     is  another  do-nothing, deprecated option included
  1347.               only for POSIX compliance.
  1348.  
  1349.        --pp     generates a  performance  report  to  stderr.   The
  1350.               report  consists  of comments regarding features of
  1351.               the _f_l_e_x input file which will cause a loss of per-
  1352.               formance  in  the resulting scanner.  Note that the
  1353.               use of _R_E_J_E_C_T and variable  trailing  context  (see
  1354.               the  BUGS section in flex(1)) entails a substantial
  1355.               performance penalty; use of _y_y_m_o_r_e_(_)_, the ^^  opera-
  1356.               tor,  and  the  --II  flag  entail  minor performance
  1357.               penalties.
  1358.  
  1359.        --ss     causes the _d_e_f_a_u_l_t  _r_u_l_e  (that  unmatched  scanner
  1360.               input  is  echoed  to _s_t_d_o_u_t_) to be suppressed.  If
  1361.               the scanner encounters input that  does  not  match
  1362.               any  of  its  rules, it aborts with an error.  This
  1363.               option is useful for finding holes in  a  scanner's
  1364.               rule set.
  1365.  
  1366.        --tt     instructs _f_l_e_x to write the scanner it generates to
  1367.               standard output instead of lleexx..yyyy..cc..
  1368.  
  1369.        --vv     specifies that _f_l_e_x should write to _s_t_d_e_r_r  a  sum-
  1370.               mary  of statistics regarding the scanner it gener-
  1371.               ates.  Most of the statistics  are  meaningless  to
  1372.               the casual _f_l_e_x user, but the first line identifies
  1373.               the version of _f_l_e_x_, which is useful  for  figuring
  1374.               out where you stand with respect to patches and new
  1375.               releases, and the next two lines give the date when
  1376.               the  scanner was created and a summary of the flags
  1377.               which were in effect.
  1378.  
  1379.        --FF     specifies that the _f_a_s_t scanner  table  representa-
  1380.               tion  should be used.  This representation is about
  1381.  
  1382.  
  1383.  
  1384. Version 2.3                26 May 1990                         21
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390. FLEX(1)                                                   FLEX(1)
  1391.  
  1392.  
  1393.               as fast as the full table representation _(_-_f_)_,  and
  1394.               for  some  sets  of  patterns  will be considerably
  1395.               smaller (and for others, larger).  In  general,  if
  1396.               the  pattern  set  contains  both  "keywords" and a
  1397.               catch-all, "identifier" rule, such as in the set:
  1398.  
  1399.                   "case"    return TOK_CASE;
  1400.                   "switch"  return TOK_SWITCH;
  1401.                   ...
  1402.                   "default" return TOK_DEFAULT;
  1403.                   [a-z]+    return TOK_ID;
  1404.  
  1405.               then you're better off using the full table  repre-
  1406.               sentation.   If  only the "identifier" rule is pre-
  1407.               sent and you then use a hash table or some such  to
  1408.               detect the keywords, you're better off using _-_F_.
  1409.  
  1410.               This option is equivalent to --CCFF (see below).
  1411.  
  1412.        --II     instructs  _f_l_e_x to generate an _i_n_t_e_r_a_c_t_i_v_e scanner.
  1413.               Normally, scanners generated by  _f_l_e_x  always  look
  1414.               ahead one character before deciding that a rule has
  1415.               been matched.  At the cost of some  scanning  over-
  1416.               head, _f_l_e_x will generate a scanner which only looks
  1417.               ahead when needed.  Such scanners are called _i_n_t_e_r_-
  1418.               _a_c_t_i_v_e  because  if you want to write a scanner for
  1419.               an interactive system such as a command shell,  you
  1420.               will  probably  want  the user's input to be termi-
  1421.               nated with a newline, and without --II the user  will
  1422.               have to type a character in addition to the newline
  1423.               in order to  have  the  newline  recognized.   This
  1424.               leads to dreadful interactive performance.
  1425.  
  1426.               If  all this seems to confusing, here's the general
  1427.               rule: if a human will be typing in  input  to  your
  1428.               scanner, use --II,, otherwise don't; if you don't care
  1429.               about squeezing the utmost  performance  from  your
  1430.               scanner  and you don't want to make any assumptions
  1431.               about the input to your scanner, use --II..
  1432.  
  1433.               Note, --II cannot be used in conjunction with _f_u_l_l or
  1434.               _f_a_s_t _t_a_b_l_e_s_, i.e., the --ff,, --FF,, --CCff,, or --CCFF flags.
  1435.  
  1436.        --LL     instructs  _f_l_e_x  not  to generate ##lliinnee directives.
  1437.               Without this option,  _f_l_e_x  peppers  the  generated
  1438.               scanner  with #line directives so error messages in
  1439.               the actions will be correctly located with  respect
  1440.               to  the  original  _f_l_e_x  input file, and not to the
  1441.               fairly  meaningless  line  numbers   of   lleexx..yyyy..cc..
  1442.               (Unfortunately _f_l_e_x does not presently generate the
  1443.               necessary directives to "retarget" the line numbers
  1444.               for those parts of lleexx..yyyy..cc which it generated.  So
  1445.               if there is an error in the generated code, a mean-
  1446.               ingless line number is reported.)
  1447.  
  1448.  
  1449.  
  1450. Version 2.3                26 May 1990                         22
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456. FLEX(1)                                                   FLEX(1)
  1457.  
  1458.  
  1459.        --TT     makes  _f_l_e_x  run in _t_r_a_c_e mode.  It will generate a
  1460.               lot of messages to _s_t_d_o_u_t concerning  the  form  of
  1461.               the  input  and the resultant non-deterministic and
  1462.               deterministic  finite  automata.   This  option  is
  1463.               mostly for use in maintaining _f_l_e_x_.
  1464.  
  1465.        --88     instructs  _f_l_e_x to generate an 8-bit scanner, i.e.,
  1466.               one which can recognize 8-bit characters.  On  some
  1467.               sites,  _f_l_e_x  is  installed with this option as the
  1468.               default.  On others, the default is  7-bit  charac-
  1469.               ters.   To see which is the case, check the verbose
  1470.               ((--vv)) output for "equivalence classes created".   If
  1471.               the denominator of the number shown is 128, then by
  1472.               default _f_l_e_x is generating 7-bit characters.  If it
  1473.               is  256,  then  the default is 8-bit characters and
  1474.               the --88 flag is not required (but may be a good idea
  1475.               to keep the scanner specification portable).  Feed-
  1476.               ing a 7-bit scanner 8-bit characters will result in
  1477.               infinite  loops,  bus  errors,  or other such fire-
  1478.               works, so when in doubt, use the flag.   Note  that
  1479.               if  equivalence  classes  are  used, 8-bit scanners
  1480.               take only slightly  more  table  space  than  7-bit
  1481.               scanners  (128  bytes, to be exact); if equivalence
  1482.               classes are not used, however, then the tables  may
  1483.               grow up to twice their 7-bit size.
  1484.  
  1485.        --CC[[eeffmmFF]]
  1486.               controls the degree of table compression.
  1487.  
  1488.               --CCee  directs _f_l_e_x to construct _e_q_u_i_v_a_l_e_n_c_e _c_l_a_s_s_e_s_,
  1489.               i.e., sets of characters which have identical lexi-
  1490.               cal properties (for example, if the only appearance
  1491.               of digits in the _f_l_e_x input  is  in  the  character
  1492.               class  "[0-9]"  then  the digits '0', '1', ..., '9'
  1493.               will all be put in  the  same  equivalence  class).
  1494.               Equivalence  classes  usually  give dramatic reduc-
  1495.               tions in the final table/object file  sizes  (typi-
  1496.               cally a factor of 2-5) and are pretty cheap perfor-
  1497.               mance-wise  (one  array   look-up   per   character
  1498.               scanned).
  1499.  
  1500.               --CCff  specifies  that the _f_u_l_l scanner tables should
  1501.               be generated - _f_l_e_x should not compress the  tables
  1502.               by  taking  advantages  of similar transition func-
  1503.               tions for different states.
  1504.  
  1505.               --CCFF specifies that the alternate fast scanner  rep-
  1506.               resentation  (described  above  under  the --FF flag)
  1507.               should be used.
  1508.  
  1509.               --CCmm  directs  _f_l_e_x  to  construct  _m_e_t_a_-_e_q_u_i_v_a_l_e_n_c_e
  1510.               _c_l_a_s_s_e_s_,  which are sets of equivalence classes (or
  1511.               characters, if equivalence classes  are  not  being
  1512.               used)  that  are  commonly  used  together.   Meta-
  1513.  
  1514.  
  1515.  
  1516. Version 2.3                26 May 1990                         23
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522. FLEX(1)                                                   FLEX(1)
  1523.  
  1524.  
  1525.               equivalence classes are often a big win when  using
  1526.               compressed tables, but they have a moderate perfor-
  1527.               mance impact (one or two "if" tests and  one  array
  1528.               look-up per character scanned).
  1529.  
  1530.               A  lone --CC specifies that the scanner tables should
  1531.               be compressed but neither equivalence  classes  nor
  1532.               meta-equivalence classes should be used.
  1533.  
  1534.               The  options  --CCff  or --CCFF and --CCmm do not make sense
  1535.               together  -  there  is  no  opportunity  for  meta-
  1536.               equivalence  classes if the table is not being com-
  1537.               pressed.   Otherwise  the  options  may  be  freely
  1538.               mixed.
  1539.  
  1540.               The  default  setting is --CCeemm,, which specifies that
  1541.               _f_l_e_x should generate equivalence classes and  meta-
  1542.               equivalence  classes.   This  setting  provides the
  1543.               highest degree of table compression.  You can trade
  1544.               off faster-executing scanners at the cost of larger
  1545.               tables with the following generally being true:
  1546.  
  1547.                   slowest & smallest
  1548.                         -Cem
  1549.                         -Cm
  1550.                         -Ce
  1551.                         -C
  1552.                         -C{f,F}e
  1553.                         -C{f,F}
  1554.                   fastest & largest
  1555.  
  1556.               Note that scanners with  the  smallest  tables  are
  1557.               usually  generated  and  compiled  the quickest, so
  1558.               during development you will usually want to use the
  1559.               default, maximal compression.
  1560.  
  1561.               --CCffee  is  often a good compromise between speed and
  1562.               size for production scanners.
  1563.  
  1564.               --CC options are not cumulative; whenever the flag is
  1565.               encountered,  the  previous -C settings are forgot-
  1566.               ten.
  1567.  
  1568.        --SSsskkeelleettoonn__ffiillee
  1569.               overrides the default skeleton file from which _f_l_e_x
  1570.               constructs  its  scanners.   You'll never need this
  1571.               option unless you are  doing  _f_l_e_x  maintenance  or
  1572.               development.
  1573.  
  1574. PPEERRFFOORRMMAANNCCEE CCOONNSSIIDDEERRAATTIIOONNSS
  1575.        The  main  design  goal  of _f_l_e_x is that it generate high-
  1576.        performance scanners.  It has been optimized  for  dealing
  1577.        well  with large sets of rules.  Aside from the effects of
  1578.        table compression on scanner speed outlined  above,  there
  1579.  
  1580.  
  1581.  
  1582. Version 2.3                26 May 1990                         24
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588. FLEX(1)                                                   FLEX(1)
  1589.  
  1590.  
  1591.        are a number of options/actions which degrade performance.
  1592.        These are, from most expensive to least:
  1593.  
  1594.            REJECT
  1595.  
  1596.            pattern sets that require backtracking
  1597.            arbitrary trailing context
  1598.  
  1599.            '^' beginning-of-line operator
  1600.            yymore()
  1601.  
  1602.        with the first three all being  quite  expensive  and  the
  1603.        last two being quite cheap.
  1604.  
  1605.        RREEJJEECCTT  should be avoided at all costs when performance is
  1606.        important.  It is a particularly expensive option.
  1607.  
  1608.        Getting rid of backtracking is messy and often may  be  an
  1609.        enormous  amount  of  work  for a complicated scanner.  In
  1610.        principal, one begins by using the --bb flag to  generate  a
  1611.        _l_e_x_._b_a_c_k_t_r_a_c_k file.  For example, on the input
  1612.  
  1613.            %%
  1614.            foo        return TOK_KEYWORD;
  1615.            foobar     return TOK_KEYWORD;
  1616.  
  1617.        the file looks like:
  1618.  
  1619.            State #6 is non-accepting -
  1620.             associated rule line numbers:
  1621.                   2       3
  1622.             out-transitions: [ o ]
  1623.             jam-transitions: EOF [ \001-n  p-\177 ]
  1624.  
  1625.            State #8 is non-accepting -
  1626.             associated rule line numbers:
  1627.                   3
  1628.             out-transitions: [ a ]
  1629.             jam-transitions: EOF [ \001-`  b-\177 ]
  1630.  
  1631.            State #9 is non-accepting -
  1632.             associated rule line numbers:
  1633.                   3
  1634.             out-transitions: [ r ]
  1635.             jam-transitions: EOF [ \001-q  s-\177 ]
  1636.  
  1637.            Compressed tables always backtrack.
  1638.  
  1639.        The  first  few lines tell us that there's a scanner state
  1640.        in which it can make a transition on an 'o' but not on any
  1641.        other  character,  and  that  in  that state the currently
  1642.        scanned text does not match any rule.   The  state  occurs
  1643.        when  trying  to match the rules found at lines 2 and 3 in
  1644.        the input file.  If the scanner is in that state and  then
  1645.  
  1646.  
  1647.  
  1648. Version 2.3                26 May 1990                         25
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654. FLEX(1)                                                   FLEX(1)
  1655.  
  1656.  
  1657.        reads  something  other than an 'o', it will have to back-
  1658.        track to find a rule which is  matched.   With  a  bit  of
  1659.        headscratching  one  can  see  that this must be the state
  1660.        it's in when it has seen "fo".  When this has happened, if
  1661.        anything  other than another 'o' is seen, the scanner will
  1662.        have to back up to simply match the 'f'  (by  the  default
  1663.        rule).
  1664.  
  1665.        The comment regarding State #8 indicates there's a problem
  1666.        when "foob" has been scanned.  Indeed,  on  any  character
  1667.        other  than  a  'b',  the  scanner will have to back up to
  1668.        accept "foo".  Similarly, the comment for  State  #9  con-
  1669.        cerns when "fooba" has been scanned.
  1670.  
  1671.        The  final  comment reminds us that there's no point going
  1672.        to all the trouble of removing backtracking from the rules
  1673.        unless  we're using --ff or --FF,, since there's no performance
  1674.        gain doing so with compressed scanners.
  1675.  
  1676.        The way to remove  the  backtracking  is  to  add  "error"
  1677.        rules:
  1678.  
  1679.            %%
  1680.            foo         return TOK_KEYWORD;
  1681.            foobar      return TOK_KEYWORD;
  1682.  
  1683.            fooba       |
  1684.            foob        |
  1685.            fo          {
  1686.                        /* false alarm, not really a keyword */
  1687.                        return TOK_ID;
  1688.                        }
  1689.  
  1690.  
  1691.        Eliminating backtracking among a list of keywords can also
  1692.        be done using a "catch-all" rule:
  1693.  
  1694.            %%
  1695.            foo         return TOK_KEYWORD;
  1696.            foobar      return TOK_KEYWORD;
  1697.  
  1698.            [a-z]+      return TOK_ID;
  1699.  
  1700.        This is usually the best solution when appropriate.
  1701.  
  1702.        Backtracking messages tend to cascade.  With a complicated
  1703.        set  of  rules  it's  not uncommon to get hundreds of mes-
  1704.        sages.  If one can decipher them, though,  it  often  only
  1705.        takes  a  dozen  or so rules to eliminate the backtracking
  1706.        (though it's easy to make a mistake and have an error rule
  1707.        accidentally  match a valid token.  A possible future _f_l_e_x
  1708.        feature will be to automatically add  rules  to  eliminate
  1709.        backtracking).
  1710.  
  1711.  
  1712.  
  1713.  
  1714. Version 2.3                26 May 1990                         26
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720. FLEX(1)                                                   FLEX(1)
  1721.  
  1722.  
  1723.        _V_a_r_i_a_b_l_e  trailing  context  (where  both  the leading and
  1724.        trailing parts do not have a fixed length) entails  almost
  1725.        the  same  performance loss as _R_E_J_E_C_T (i.e., substantial).
  1726.        So when possible a rule like:
  1727.  
  1728.            %%
  1729.            mouse|rat/(cat|dog)   run();
  1730.  
  1731.        is better written:
  1732.  
  1733.            %%
  1734.            mouse/cat|dog         run();
  1735.            rat/cat|dog           run();
  1736.  
  1737.        or as
  1738.  
  1739.            %%
  1740.            mouse|rat/cat         run();
  1741.            mouse|rat/dog         run();
  1742.  
  1743.        Note that here the special '|' action does _n_o_t provide any
  1744.        savings,  and  can  even  make  things  worse (see BBUUGGSS in
  1745.        flex(1)).
  1746.  
  1747.        Another area where the user can increase a scanner's  per-
  1748.        formance  (and one that's easier to implement) arises from
  1749.        the fact that the longer the tokens  matched,  the  faster
  1750.        the  scanner  will  run.  This is because with long tokens
  1751.        the processing of most input characters takes place in the
  1752.        (short) inner scanning loop, and does not often have to go
  1753.        through the additional work of  setting  up  the  scanning
  1754.        environment  (e.g.,  yyyytteexxtt))  for  the action.  Recall the
  1755.        scanner for C comments:
  1756.  
  1757.            %x comment
  1758.            %%
  1759.                    int line_num = 1;
  1760.  
  1761.            "/*"         BEGIN(comment);
  1762.  
  1763.            <comment>[^*\n]*
  1764.            <comment>"*"+[^*/\n]*
  1765.            <comment>\n             ++line_num;
  1766.            <comment>"*"+"/"        BEGIN(INITIAL);
  1767.  
  1768.        This could be sped up by writing it as:
  1769.  
  1770.            %x comment
  1771.            %%
  1772.                    int line_num = 1;
  1773.  
  1774.            "/*"         BEGIN(comment);
  1775.  
  1776.            <comment>[^*\n]*
  1777.  
  1778.  
  1779.  
  1780. Version 2.3                26 May 1990                         27
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786. FLEX(1)                                                   FLEX(1)
  1787.  
  1788.  
  1789.            <comment>[^*\n]*\n      ++line_num;
  1790.            <comment>"*"+[^*/\n]*
  1791.            <comment>"*"+[^*/\n]*\n ++line_num;
  1792.            <comment>"*"+"/"        BEGIN(INITIAL);
  1793.  
  1794.        Now instead of each newline requiring  the  processing  of
  1795.        another  action, recognizing the newlines is "distributed"
  1796.        over the other rules to keep the matched text as  long  as
  1797.        possible.   Note  that _a_d_d_i_n_g rules does _n_o_t slow down the
  1798.        scanner!  The speed of the scanner is independent  of  the
  1799.        number of rules or (modulo the considerations given at the
  1800.        beginning of this section) how complicated the  rules  are
  1801.        with regard to operators such as '*' and '|'.
  1802.  
  1803.        A final example in speeding up a scanner: suppose you want
  1804.        to scan through a file  containing  identifiers  and  key-
  1805.        words,  one  per line and with no other extraneous charac-
  1806.        ters, and recognize all the  keywords.   A  natural  first
  1807.        approach is:
  1808.  
  1809.            %%
  1810.            asm      |
  1811.            auto     |
  1812.            break    |
  1813.            ... etc ...
  1814.            volatile |
  1815.            while    /* it's a keyword */
  1816.  
  1817.            .|\n     /* it's not a keyword */
  1818.  
  1819.        To  eliminate  the  back-tracking,  introduce  a catch-all
  1820.        rule:
  1821.  
  1822.            %%
  1823.            asm      |
  1824.            auto     |
  1825.            break    |
  1826.            ... etc ...
  1827.            volatile |
  1828.            while    /* it's a keyword */
  1829.  
  1830.            [a-z]+   |
  1831.            .|\n     /* it's not a keyword */
  1832.  
  1833.        Now, if it's guaranteed that there's exactly one word  per
  1834.        line,  then we can reduce the total number of matches by a
  1835.        half by merging in the recognition of newlines  with  that
  1836.        of the other tokens:
  1837.  
  1838.            %%
  1839.            asm\n    |
  1840.            auto\n   |
  1841.            break\n  |
  1842.            ... etc ...
  1843.  
  1844.  
  1845.  
  1846. Version 2.3                26 May 1990                         28
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852. FLEX(1)                                                   FLEX(1)
  1853.  
  1854.  
  1855.            volatile\n |
  1856.            while\n  /* it's a keyword */
  1857.  
  1858.            [a-z]+\n |
  1859.            .|\n     /* it's not a keyword */
  1860.  
  1861.        One  has  to  be careful here, as we have now reintroduced
  1862.        backtracking into the scanner.  In  particular,  while  _w_e
  1863.        know  that there will never be any characters in the input
  1864.        stream other than letters or newlines, _f_l_e_x  can't  figure
  1865.        this out, and it will plan for possibly needing backtrack-
  1866.        ing when it has scanned a token like "auto" and  then  the
  1867.        next character is something other than a newline or a let-
  1868.        ter.  Previously it would then just match the "auto"  rule
  1869.        and  be  done,  but  now  it  has  no  "auto" rule, only a
  1870.        "auto\n" rule.  To eliminate the possibility of backtrack-
  1871.        ing, we could either duplicate all rules but without final
  1872.        newlines, or, since we never expect to encounter  such  an
  1873.        input  and  therefore  don't  how  it's classified, we can
  1874.        introduce one more catch-all rule, this one which  doesn't
  1875.        include a newline:
  1876.  
  1877.            %%
  1878.            asm\n    |
  1879.            auto\n   |
  1880.            break\n  |
  1881.            ... etc ...
  1882.            volatile\n |
  1883.            while\n  /* it's a keyword */
  1884.  
  1885.            [a-z]+\n |
  1886.            [a-z]+   |
  1887.            .|\n     /* it's not a keyword */
  1888.  
  1889.        Compiled  with --CCff,, this is about as fast as one can get a
  1890.        _f_l_e_x scanner to go for this particular problem.
  1891.  
  1892.        A final note: _f_l_e_x is slow when matching  NUL's,  particu-
  1893.        larly  when a token contains multiple NUL's.  It's best to
  1894.        write rules which match _s_h_o_r_t  amounts  of  text  if  it's
  1895.        anticipated that the text will often include NUL's.
  1896.  
  1897. IINNCCOOMMPPAATTIIBBIILLIITTIIEESS WWIITTHH LLEEXX AANNDD PPOOSSIIXX
  1898.        _f_l_e_x  is a rewrite of the Unix _l_e_x tool (the two implemen-
  1899.        tations do not share any code, though), with  some  exten-
  1900.        sions  and incompatibilities, both of which are of concern
  1901.        to those who wish to write scanners acceptable  to  either
  1902.        implementation.   At  present, the POSIX _l_e_x draft is very
  1903.        close to the original _l_e_x implementation, so some of these
  1904.        incompatibilities  are  also  in  conflict  with the POSIX
  1905.        draft.  But the intent is that except as noted below, _f_l_e_x
  1906.        as it presently stands will ultimately be POSIX conformant
  1907.        (i.e., that those areas of conflict with the  POSIX  draft
  1908.        will  be  resolved  in _f_l_e_x_'_s favor).  Please bear in mind
  1909.  
  1910.  
  1911.  
  1912. Version 2.3                26 May 1990                         29
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918. FLEX(1)                                                   FLEX(1)
  1919.  
  1920.  
  1921.        that all the comments which follow are with regard to  the
  1922.        POSIX  _d_r_a_f_t  standard  of  Summer 1989, and not the final
  1923.        document (or subsequent drafts); they are included so _f_l_e_x
  1924.        users can be aware of the standardization issues and those
  1925.        areas where _f_l_e_x may in the near  future  undergo  changes
  1926.        incompatible with its current definition.
  1927.  
  1928.        _f_l_e_x  is  fully  compatible  with  _l_e_x  with the following
  1929.        exceptions:
  1930.  
  1931.        -      The  undocumented  _l_e_x  scanner  internal  variable
  1932.               yyyylliinneennoo is not supported.  It is difficult to sup-
  1933.               port this option  efficiently,  since  it  requires
  1934.               examining  every  character scanned and reexamining
  1935.               the characters when the scanner backs  up.   Things
  1936.               get more complicated when the end of buffer or file
  1937.               is reached or a NUL is scanned (since the scan must
  1938.               then  be  restarted  with  the  proper  line number
  1939.               count), or the user uses the yyless(), unput(),  or
  1940.               REJECT  actions, or the multiple input buffer func-
  1941.               tions.
  1942.  
  1943.               The fix is to add rules which, upon seeing  a  new-
  1944.               line,  increment yylineno.  This is usually an easy
  1945.               process, though it can be a drag  if  some  of  the
  1946.               patterns  can  match  multiple  newlines along with
  1947.               other characters.
  1948.  
  1949.               yylineno is not part of the POSIX draft.
  1950.  
  1951.        -      The iinnppuutt(()) routine is not redefinable,  though  it
  1952.               may be called to read characters following whatever
  1953.               has been matched by a rule.  If iinnppuutt(())  encounters
  1954.               an  end-of-file  the  normal yyyywwrraapp(()) processing is
  1955.               done.   A  ``real''  end-of-file  is  returned   by
  1956.               iinnppuutt(()) as _E_O_F_.
  1957.  
  1958.               Input  is  instead  controlled  by  redefining  the
  1959.               YYYY__IINNPPUUTT macro.
  1960.  
  1961.               The _f_l_e_x restriction that iinnppuutt(()) cannot  be  rede-
  1962.               fined  is  in  accordance with the POSIX draft, but
  1963.               YYYY__IINNPPUUTT has not yet been accepted into  the  draft
  1964.               (and  probably  won't; it looks like the draft will
  1965.               simply not specify any way of controlling the scan-
  1966.               ner's input other than by making an initial assign-
  1967.               ment to _y_y_i_n_)_.
  1968.  
  1969.        -      _f_l_e_x scanners do not use stdio for input.   Because
  1970.               of  this,  when  writing an interactive scanner one
  1971.               must explicitly call fflush() on the stream associ-
  1972.               ated  with the terminal after writing out a prompt.
  1973.               With _l_e_x  such  writes  are  automatically  flushed
  1974.               since  _l_e_x  scanners use ggeettcchhaarr(()) for their input.
  1975.  
  1976.  
  1977.  
  1978. Version 2.3                26 May 1990                         30
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984. FLEX(1)                                                   FLEX(1)
  1985.  
  1986.  
  1987.               Also, when writing interactive scanners with  _f_l_e_x_,
  1988.               the --II flag must be used.
  1989.  
  1990.        -      _f_l_e_x scanners are not as reentrant as _l_e_x scanners.
  1991.               In particular, if you have an  interactive  scanner
  1992.               and  an  interrupt  handler which long-jumps out of
  1993.               the scanner, and the scanner is subsequently called
  1994.               again, you may get the following message:
  1995.  
  1996.                   fatal flex scanner internal error--end of buffer missed
  1997.  
  1998.               To reenter the scanner, first use
  1999.  
  2000.                   yyrestart( yyin );
  2001.  
  2002.  
  2003.        -      oouuttppuutt(())  is  not  supported.  Output from the EECCHHOO
  2004.               macro is done to the  file-pointer  _y_y_o_u_t  (default
  2005.               _s_t_d_o_u_t_)_.
  2006.  
  2007.               The  POSIX  draft mentions that an oouuttppuutt(()) routine
  2008.               exists but currently gives no details as to what it
  2009.               does.
  2010.  
  2011.        -      _l_e_x  does  not  support  exclusive start conditions
  2012.               (%x), though they are in the current POSIX draft.
  2013.  
  2014.        -      When definitions are expanded, _f_l_e_x  encloses  them
  2015.               in parentheses.  With lex, the following:
  2016.  
  2017.                   NAME    [A-Z][A-Z0-9]*
  2018.                   %%
  2019.                   foo{NAME}?      printf( "Found it\n" );
  2020.                   %%
  2021.  
  2022.               will  not  match  the string "foo" because when the
  2023.               macro is expanded the rule is equivalent to "foo[A-
  2024.               Z][A-Z0-9]*?"   and the precedence is such that the
  2025.               '?' is associated with "[A-Z0-9]*".  With _f_l_e_x_, the
  2026.               rule will be expanded to "foo([A-Z][A-Z0-9]*)?" and
  2027.               so the string "foo" will match.  Note that  because
  2028.               of  this,  the  ^^,, $$,, <<ss>>,, //,, and <<<<EEOOFF>>>> operators
  2029.               cannot be used in a _f_l_e_x definition.
  2030.  
  2031.               The POSIX  draft  interpretation  is  the  same  as
  2032.               _f_l_e_x_'_s_.
  2033.  
  2034.        -      To specify a character class which matches anything
  2035.               but a left bracket (']'), in _l_e_x one can use "[^]]"
  2036.               but  with  _f_l_e_x  one  must use "[^\]]".  The latter
  2037.               works with _l_e_x_, too.
  2038.  
  2039.        -      The _l_e_x %%rr (generate a Ratfor  scanner)  option  is
  2040.               not  supported.  It is not part of the POSIX draft.
  2041.  
  2042.  
  2043.  
  2044. Version 2.3                26 May 1990                         31
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050. FLEX(1)                                                   FLEX(1)
  2051.  
  2052.  
  2053.        -      If you are providing your own yywrap() routine, you
  2054.               must  include  a "#undef yywrap" in the definitions
  2055.               section (section 1).  Note that the  "#undef"  will
  2056.               have to be enclosed in %{}'s.
  2057.  
  2058.               The  POSIX draft specifies that yywrap() is a func-
  2059.               tion and this is very unlikely to change;  so  _f_l_e_x
  2060.               _u_s_e_r_s  _a_r_e  _w_a_r_n_e_d  that  yyyywwrraapp(())  is likely to be
  2061.               changed to a function in the near future.
  2062.  
  2063.        -      After a call to  uunnppuutt(()),,  _y_y_t_e_x_t  and  _y_y_l_e_n_g  are
  2064.               undefined until the next token is matched.  This is
  2065.               not the case with _l_e_x or the present POSIX draft.
  2066.  
  2067.        -      The precedence of the {{}} (numeric  range)  operator
  2068.               is  different.  _l_e_x interprets "abc{1,3}" as "match
  2069.               one, two, or three occurrences of  'abc'",  whereas
  2070.               _f_l_e_x  interprets it as "match 'ab' followed by one,
  2071.               two, or three occurrences of 'c'".  The  latter  is
  2072.               in agreement with the current POSIX draft.
  2073.  
  2074.        -      The precedence of the ^^ operator is different.  _l_e_x
  2075.               interprets "^foo|bar" as "match either 'foo' at the
  2076.               beginning  of  a  line, or 'bar' anywhere", whereas
  2077.               _f_l_e_x interprets it as "match either 'foo' or  'bar'
  2078.               if they come at the beginning of a line".  The lat-
  2079.               ter is in agreement with the current POSIX draft.
  2080.  
  2081.        -      To refer to yytext outside of  the  scanner  source
  2082.               file,  the  correct definition with _f_l_e_x is "extern
  2083.               char *yytext" rather than "extern  char  yytext[]".
  2084.               This  is  contrary to the current POSIX draft but a
  2085.               point on which _f_l_e_x will not be  changing,  as  the
  2086.               array  representation entails a serious performance
  2087.               penalty.  It is hoped that the POSIX draft will  be
  2088.               emended  to support the _f_l_e_x variety of declaration
  2089.               (as this is a fairly painless change to require  of
  2090.               _l_e_x users).
  2091.  
  2092.        -      _y_y_i_n  is  _i_n_i_t_i_a_l_i_z_e_d  by _l_e_x to be _s_t_d_i_n_; _f_l_e_x_, on
  2093.               the other hand, initializes _y_y_i_n to NULL  and  then
  2094.               _a_s_s_i_g_n_s  it  to _s_t_d_i_n the first time the scanner is
  2095.               called,  providing  _y_y_i_n  has  not   already   been
  2096.               assigned  to  a  non-NULL value.  The difference is
  2097.               subtle, but the net effect is that with _f_l_e_x  scan-
  2098.               ners,  _y_y_i_n  does  not have a valid value until the
  2099.               scanner has been called.
  2100.  
  2101.        -      The special table-size declarations such as %%aa sup-
  2102.               ported  by  _l_e_x  are not required by _f_l_e_x scanners;
  2103.               _f_l_e_x ignores them.
  2104.  
  2105.        -      The name FLEX_SCANNER is #define'd so scanners  may
  2106.               be written for use with either _f_l_e_x or _l_e_x_.
  2107.  
  2108.  
  2109.  
  2110. Version 2.3                26 May 1990                         32
  2111.  
  2112.  
  2113.  
  2114.  
  2115.  
  2116. FLEX(1)                                                   FLEX(1)
  2117.  
  2118.  
  2119.        The following _f_l_e_x features are not included in _l_e_x or the
  2120.        POSIX draft standard:
  2121.  
  2122.            yyterminate()
  2123.            <<EOF>>
  2124.            YY_DECL
  2125.            #line directives
  2126.            %{}'s around actions
  2127.            yyrestart()
  2128.            comments beginning with '#' (deprecated)
  2129.            multiple actions on a line
  2130.  
  2131.        This last feature refers to the fact that  with  _f_l_e_x  you
  2132.        can  put multiple actions on the same line, separated with
  2133.        semi-colons, while with _l_e_x_, the following
  2134.  
  2135.            foo    handle_foo(); ++num_foos_seen;
  2136.  
  2137.        is (rather surprisingly) truncated to
  2138.  
  2139.            foo    handle_foo();
  2140.  
  2141.        _f_l_e_x does not truncate the action.  Actions that  are  not
  2142.        enclosed in braces are simply terminated at the end of the
  2143.        line.
  2144.  
  2145. DDIIAAGGNNOOSSTTIICCSS
  2146.        _r_e_j_e_c_t___u_s_e_d___b_u_t___n_o_t___d_e_t_e_c_t_e_d         _u_n_d_e_f_i_n_e_d          or
  2147.        _y_y_m_o_r_e___u_s_e_d___b_u_t___n_o_t___d_e_t_e_c_t_e_d  _u_n_d_e_f_i_n_e_d _- These errors can
  2148.        occur at compile time.  They  indicate  that  the  scanner
  2149.        uses RREEJJEECCTT or yyyymmoorree(()) but that _f_l_e_x failed to notice the
  2150.        fact, meaning that _f_l_e_x scanned  the  first  two  sections
  2151.        looking  for  occurrences  of  these actions and failed to
  2152.        find any, but somehow you snuck some in  (via  a  #include
  2153.        file,  for  example).   Make  an explicit reference to the
  2154.        action in your _f_l_e_x input  file.   (Note  that  previously
  2155.        _f_l_e_x  supported a %%uusseedd//%%uunnuusseedd mechanism for dealing with
  2156.        this problem; this feature is still supported but now dep-
  2157.        recated,  and  will  go  away soon unless the author hears
  2158.        from people who can argue compellingly that they need it.)
  2159.  
  2160.        _f_l_e_x  _s_c_a_n_n_e_r  _j_a_m_m_e_d  _-  a  scanner  compiled with --ss has
  2161.        encountered an input string which wasn't matched by any of
  2162.        its rules.
  2163.  
  2164.        _f_l_e_x  _i_n_p_u_t  _b_u_f_f_e_r  _o_v_e_r_f_l_o_w_e_d _- a scanner rule matched a
  2165.        string long enough  to  overflow  the  scanner's  internal
  2166.        input  buffer  (16K  bytes  by  default  -  controlled  by
  2167.        YYYY__BBUUFF__SSIIZZEE in "flex.skel".  Note that  to  redefine  this
  2168.        macro, you must first ##uunnddeeffiinnee it).
  2169.  
  2170.        _s_c_a_n_n_e_r  _r_e_q_u_i_r_e_s  _-_8  _f_l_a_g  _-  Your scanner specification
  2171.        includes recognizing 8-bit  characters  and  you  did  not
  2172.        specify  the -8 flag (and your site has not installed flex
  2173.  
  2174.  
  2175.  
  2176. Version 2.3                26 May 1990                         33
  2177.  
  2178.  
  2179.  
  2180.  
  2181.  
  2182. FLEX(1)                                                   FLEX(1)
  2183.  
  2184.  
  2185.        with -8 as the default).
  2186.  
  2187.        _f_a_t_a_l _f_l_e_x _s_c_a_n_n_e_r _i_n_t_e_r_n_a_l _e_r_r_o_r_-_-_e_n_d _o_f _b_u_f_f_e_r _m_i_s_s_e_d  _-
  2188.        This  can  occur  in an scanner which is reentered after a
  2189.        long-jump has jumped out (or over) the  scanner's  activa-
  2190.        tion frame.  Before reentering the scanner, use:
  2191.  
  2192.            yyrestart( yyin );
  2193.  
  2194.  
  2195.        _t_o_o  _m_a_n_y  _%_t  _c_l_a_s_s_e_s_!  _- You managed to put every single
  2196.        character into its own %t class.  _f_l_e_x  requires  that  at
  2197.        least one of the classes share characters.
  2198.  
  2199. DDEEFFIICCIIEENNCCIIEESS // BBUUGGSS
  2200.        See flex(1).
  2201.  
  2202. SSEEEE AALLSSOO
  2203.        flex(1), lex(1), yacc(1), sed(1), awk(1).
  2204.  
  2205.        M.  E. Lesk and E. Schmidt, _L_E_X _- _L_e_x_i_c_a_l _A_n_a_l_y_z_e_r _G_e_n_e_r_a_-
  2206.        _t_o_r
  2207.  
  2208. AAUUTTHHOORR
  2209.        Vern Paxson, with the help of many ideas and much inspira-
  2210.        tion   from   Van   Jacobson.   Original  version  by  Jef
  2211.        Poskanzer.  The fast table  representation  is  a  partial
  2212.        implementation  of  a  design  done  by Van Jacobson.  The
  2213.        implementation was done by Kevin Gong and Vern Paxson.
  2214.  
  2215.        Thanks to the many  _f_l_e_x  beta-testers,  feedbackers,  and
  2216.        contributors,  especially  Casey  Leedom,  benson@odi.com,
  2217.        Keith Bostic,  Frederic  Brehm,  Nick  Christopher,  Jason
  2218.        Coughlin,  Scott  David  Daniels, Leo Eskin, Chris Faylor,
  2219.        Eric Goldman, Eric Hughes,  Jeffrey  R.  Jones,  Kevin  B.
  2220.        Kenny, Ronald Lamprecht, Greg Lee, Craig Leres, Mohamed el
  2221.        Lozy,  Jim  Meyering,  Marc  Nozell,  Esmond   Pitt,   Jef
  2222.        Poskanzer,  Jim  Roskind,  Dave Tallman, Frank Whaley, Ken
  2223.        Yap, and those whose names have slipped my marginal  mail-
  2224.        archiving  skills  but whose contributions are appreciated
  2225.        all the same.
  2226.  
  2227.        Thanks to Keith Bostic, John  Gilmore,  Craig  Leres,  Bob
  2228.        Mulcahy,  Rich  Salz,  and  Richard Stallman for help with
  2229.        various distribution headaches.
  2230.  
  2231.        Thanks to Esmond Pitt and Earle Horton for 8-bit character
  2232.        support;  to  Benson Margulies and Fred Burke for C++ sup-
  2233.        port; to Ove Ewerlid for the basics of support for  NUL's;
  2234.        and  to Eric Hughes for the basics of support for multiple
  2235.        buffers.
  2236.  
  2237.        Work is being done on extending _f_l_e_x to generate  scanners
  2238.        in  which  the  state machine is directly represented in C
  2239.  
  2240.  
  2241.  
  2242. Version 2.3                26 May 1990                         34
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248. FLEX(1)                                                   FLEX(1)
  2249.  
  2250.  
  2251.        code rather than tables.  These scanners may well be  sub-
  2252.        stantially faster than those generated using -f or -F.  If
  2253.        you are working in this area and are interested in compar-
  2254.        ing  notes  and  seeing  whether  redundant  work  can  be
  2255.        avoided, contact Ove Ewerlid (ewerlid@mizar.DoCS.UU.SE).
  2256.  
  2257.        This work was primarily done when I was at the  Real  Time
  2258.        Systems  Group  at  the  Lawrence  Berkeley  Laboratory in
  2259.        Berkeley, CA.  Many thanks to all there for the support  I
  2260.        received.
  2261.  
  2262.        Send comments to:
  2263.  
  2264.             Vern Paxson
  2265.             Computer Systems Engineering
  2266.             Bldg. 46A, Room 1123
  2267.             Lawrence Berkeley Laboratory
  2268.             University of California
  2269.             Berkeley, CA 94720
  2270.  
  2271.             vern@ee.lbl.gov
  2272.             ucbvax!ee.lbl.gov!vern
  2273.  
  2274.  
  2275.  
  2276.  
  2277.  
  2278.  
  2279.  
  2280.  
  2281.  
  2282.  
  2283.  
  2284.  
  2285.  
  2286.  
  2287.  
  2288.  
  2289.  
  2290.  
  2291.  
  2292.  
  2293.  
  2294.  
  2295.  
  2296.  
  2297.  
  2298.  
  2299.  
  2300.  
  2301.  
  2302.  
  2303.  
  2304.  
  2305.  
  2306.  
  2307.  
  2308. Version 2.3                26 May 1990                         35
  2309.  
  2310.  
  2311.