manpagez: man pages & more
info flex
Home | html | info | man

File: flex.info,  Node: Actions,  Next: Generated Scanner,  Prev: Matching,  Up: Top

8 Actions
*********

Each pattern in a rule has a corresponding "action", which can be any
arbitrary target-language statement.  The pattern ends at the first
non-escaped whitespace character; the remainder of the line is its
action.  If the action is empty, then when the pattern is matched the
input token is simply discarded.  For example, here is the specification
for a program which deletes all occurrences of 'zap me' from its input:

         %%
         "zap me"

   This example will copy all other characters in the input to the
output since they will be matched by the default rule.

   Here is a program which compresses multiple blanks and tabs down to a
single blank, and throws away whitespace found at the end of a line:

         %%
         [ \t]+        putchar( ' ' );
         [ \t]+$       /* ignore this token */

   If the action contains a '{', then the action spans till the
balancing '}' is found, and the action may cross multiple lines.  'flex'
knows about C strings and comments and won't be fooled by braces found
within them, but also allows actions to begin with '%{' and will
consider the action to be all the text up to the next '%}' (regardless
of ordinary braces inside the action).

   An action consisting solely of a vertical bar ('|') means "same as
the action for the next rule".  See below for an illustration.

   Actions can include arbitrary C code, including 'return' statements
to return a value to whatever routine called 'yylex()'.  Each time
'yylex()' is called it continues processing tokens from where it last
left off until it either reaches the end of the file or executes a
return.

   Actions are free to modify 'yytext' except for lengthening it (adding
characters to its end-these will overwrite later characters in the input
stream).  This however does not apply when using '%array' (*note
Matching::).  In that case, 'yytext' may be freely modified in any way.

   Actions are free to modify 'yyleng' except they should not do so if
the action also includes use of 'yymore()' (see below).

   There are a number of special hooks which can be included within an
action.

'yyecho()'
     copies yytext to the scanner's output.

'yybegin()'
     followed by the name of a start condition places the scanner in the
     corresponding start condition (see below).

'yyreject()'
     directs the scanner to proceed on to the "second best" rule which
     matched the input (or a prefix of the input).  The rule is chosen
     as described above in *note Matching::, and 'yytext' and 'yyleng'
     set up appropriately.  It may either be one which matched as much
     text as the originally chosen rule but came later in the 'flex'
     input file, or one which matched less text.  For example, the
     following will both count the words in the input and call the
     routine 'special()' whenever 'frob' is seen:

          %{
                  int word_count = 0;
          %}
          %%
          
          frob        special(); yyreject();
          [^ \t\n]+   ++word_count;

     Without the 'yyreject()', any occurrences of 'frob' in the input
     would not be counted as words, since the scanner normally executes
     only one action per token.  Multiple uses of 'yyreject()' are
     allowed, each one finding the next best choice to the currently
     active rule.  For example, when the following scanner scans the
     token 'abcd', it will write 'abcdabcaba' to the output:

          %%
          a        |
          ab       |
          abc      |
          abcd     yyecho(); yyreject();
          .|\n     /* eat up any unmatched character */

     The first three rules share the fourth's action since they use the
     special '|' action.

     'yyreject()' is a particularly expensive feature in terms of
     scanner performance; if it is used in _any_ of the scanner's
     actions it will slow down _all_ of the scanner's matching.
     Furthermore, 'yyreject()' cannot be used with the '-Cf' or '-CF'
     options (*note Scanner Options::).

     Note also that unlike the other special actions, 'yyreject()' is a
     _branch_.  Code immediately following it in the action will _not_
     be executed.

'yymore()'
     tells the scanner that the next time it matches a rule, the
     corresponding token should be _appended_ onto the current value of
     'yytext' rather than replacing it.  For example, given the input
     'mega-kludge' the following will write 'mega-mega-kludge' to the
     output:

          %%
          mega-    yyecho(); yymore();
          kludge   yyecho();

     First 'mega-' is matched and echoed to the output.  Then 'kludge'
     is matched, but the previous 'mega-' is still hanging around at the
     beginning of 'yytext' so the 'yyecho()' for the 'kludge' rule will
     actually write 'mega-kludge'.

   Two notes regarding use of 'yymore()'.  First, 'yymore()' depends on
the value of 'yyleng' correctly reflecting the size of the current
token, so you must not modify 'yyleng' if you are using 'yymore()'.
Second, the presence of 'yymore()' in the scanner's action entails a
minor performance penalty in the scanner's matching speed.

   'yyless(n)' returns all but the first 'n' characters of the current
token back to the input stream, where they will be rescanned when the
scanner looks for the next match.  'yytext' and 'yyleng' are adjusted
appropriately (e.g., 'yyleng' will now be equal to 'n').  For example,
on the input 'foobar' the following will write out 'foobarbar':

     %%
     foobar    yyecho(); yyless(3);
     [a-z]+    yyecho();

   An argument of 0 to 'yyless()' will cause the entire current input
string to be scanned again.  Unless you've changed how the scanner will
subsequently process its input (using 'yybegin()', for example), this
will result in an endless loop.

   'yyunput(c)' puts the character 'c' back onto the input stream.  It
will be the next character scanned.  The following action will take the
current token and cause it to be rescanned enclosed in parentheses.

     {
         int i;
         /* Copy yytext because yyunput() trashes yytext */
         char *yycopy = strdup( yytext );
         yyunput( ')' );
         for ( i = yyleng - 1; i >= 0; --i )
             yyunput( yycopy[i] );
         yyunput( '(' );
         free( yycopy );
     }

   Note that since each 'yyunput()' puts the given character back at the
_beginning_ of the input stream, pushing back strings must be done
back-to-front.

   An important potential problem when using 'yyunput()' in C (and,
generally, in target languages with C-like manual memory management) is
that if you are using '%pointer' (the default), a call to 'yyunput()'
_destroys_ the contents of 'yytext', starting with its rightmost
character and devouring one character to the left with each call.  If
you need the value of 'yytext' preserved after a call to 'yyunput()' (as
in the above example), you must either first copy it elsewhere, or build
your scanner using '%array' instead (*note Matching::).

   Finally, note that you cannot put back 'EOF' to attempt to mark the
input stream with an end-of-file.

   'yyinput()' reads the next character from the input stream.  In a
rule's action, the default C back end reads 'yyinput()' as the function
that flex 2.6.4 called 'input()', so a program can declare a 'yyinput'
of its own.  A call outside an action must use the name the C compiler
sees: 'input()', or 'yyinput()' when the scanner is compiled as C++.
For example, the following is one way to eat up C comments:

     %%
     "/*"    {
                 int c;
     
                 for ( ; ; ) {
                     while ( (c = yyinput()) != '*' && c != EOF )
                         ;    /* eat up text of comment */
     
                     if ( c == '*' ) {
                         while ( (c = yyinput()) == '*' )
                             ;
                         if ( c == '/' )
                             break;    /* found the end */
                     }
     
                     if ( c == EOF ) {
                         error( "EOF in comment" );
                         break;
                     }
                 }
             }

   'yy_flush_current_buffer()' flushes the scanner's internal buffer so
that the next time the scanner attempts to match a token, it will first
refill the buffer using 'yyread()' (*note Generated Scanner::).  This
action is a special case of the more general 'yy_flush_buffer()'
function, described below (*note Multiple Input Buffers::)

   'yyterminate()' can be used in lieu of a return statement in an
action.  It terminates the scanner and returns a 0 to the scanner's
caller, indicating "all done".  By default, 'yyterminate()' is also
called when an end-of-file is encountered.  It may be redefined.

   When the target language is C/C++, 'yyterminate()' is a macro.
Redefining it using the C/C++ preprocessor in your definitions section
is allowed, but not recommended as doing this makes code more difficult
to port out of C/C++.  In other target languages you can swt what
yyterminate() expands to with '%option yyterminate'.

© manpagez.com 2000-2026
Individual documents may contain additional copyright information.