NAME
flex - fast lexical analyzer generator
SYNOPSIS
flex [-bcdfinpstvFILT8 -C[efmF] -Sskeleton] [filename ...]
DESCRIPTION
flex is a tool for generating scanners: programs which recognized lexical patterns in text. flex reads the given input files, or its standard input if no file names are given, for a description of a scanner to generate. The description is in the form of pairs of regular expressions and C code, called rules. flex generates as output a C source file, lex.yy.c, which defines a routine yylex(). This file is compiled and linked with the -lfl library to produce an executable. When the executable is run, it analyzes its input for occurrences of the regular expressions. Whenever it finds one, it executes the corresponding C code.
SOME SIMPLE EXAMPLES
First some simple examples to get the flavor of how one uses flex. The following flex input specifies a scanner which whenever it encounters the string "username" will replace it with the user's login name:
%%
Here's another simple example:
int num_lines = 0, num_chars = 0;
%%
This scanner counts the number of characters and the number of lines in its input (it produces no output other than the final report on the counts). The first line declares two globals, "num_lines" and "num_chars", which are accessible both inside yylex() and in the main() routine declared after the second "%%". There are two rules, one which matches a newline ("\n") and increments both the line count and the character count, and one which matches any character other than a newline (indicated by the "." regular expression).
A somewhat more complicated example:
/* scanner for a toy Pascal-like language */
%{
/* need this for the call to atof() below */ #include <math.h>
%}
main( argc, argv )
int argc;
char **argv;
{
++argv, --argc; /* skip over program name */ if ( argc > 0 )
yyin = fopen( argv[0], "r" ); else
yyin = stdin;
yylex();
}
This is the beginnings of a simple scanner for a language like Pascal. It identifies different types of tokens and reports on what it has seen.
The details of this example will be explained in the following sections.
FORMAT OF THE INPUT FILE
The flex input file consists of three sections, separated by a line with just %% in it:
definitions
%%
rules
%%
user code
The definitions section contains declarations of simple name definitions to simplify the scanner specification, and declarations of start conditions, which are explained in a later section.
Name definitions have the form:
name definition
The "name" is a word beginning with a letter or an underscore ('_') followed by zero or more letters, digits, `_', or `-' (dash). The definition is taken to begin at the first non-white-space character following the name and continuing to the end of the line. The definition can subsequently be referred to using "{name}", which will expand to "(definition)". For example,
{DIGIT}+"."{DIGIT}*
is identical to
([0-9])+"."([0-9])*
and matches one-or-more digits followed by a `.' followed by zero-or-more digits.
The rules section of the flex input contains a series of rules of the form:
pattern action
where the pattern must be unindented and the action must begin on the same line.
See below for a further description of patterns and actions.
Finally, the user code section is simply copied to lex.yy.c verbatim. It is used for companion routines which call or are called by the scanner. The presence of this section is optional; if it is missing, the second %% in the input file may be skipped, too.
In the definitions and rules sections, any indented text or text enclosed in %{ and %} is copied verbatim to the output (with the %{}'s removed). The %{}'s must appear unindented on lines by themselves.
In the rules section, any indented or %{} text appearing before the first rule may be used to declare variables which are local to the scanning routine and (after the declarations) code which is to be executed whenever the scanning routine is entered. Other indented or %{} text in the rule section is still copied to the output, but its meaning is not well-defined and it may well cause compile-time errors (this feature is present for POSIX compliance; see below for other such features).
In the definitions section, an unindented comment (i.e., a line beginning with "/*") is also copied verbatim to the output up to the next "*/". Also, any line in the definitions section beginning with `#' is ignored, though this style of comment is deprecated and may go away in the future.
PATTERNS
The patterns in the input are written using an extended set of regular expressions. These are:
foo|bar*
is the same as
(foo)|(ba(r*))
since the `*' operator has higher precedence than concatenation, and concatenation higher than alternation ('|'). This pattern therefore matches either the string "foo" or the string "ba" followed by zero-or-more r's. To match "foo" or zero-or-more "bar"'s, use:
foo|(bar)*
and to match zero-or-more "foo"'s-or-"bar"'s:
(foo|bar)*
Some notes on patterns:
foo/bar$
<sc1>foo<sc2>bar
Note that the first of these, can be written "foo/bar\n".
The following will result in `$' or `^' being treated as a normal character:
foo|(bar$)
foo|^bar
If what's wanted is a "foo" or a bar-followed-by-anewline, the following could be used (the special `|' action is explained below):
HOW THE INPUT IS MATCHED
When the generated scanner is run, it analyzes its input looking for strings which match any of its patterns. If it finds more than one match, it takes the one matching the most text (for trailing context rules, this includes the length of the trailing part, even though it will then be returned to the input). If it finds two or more matches of the same length, the rule listed first in the flex input file is chosen.
Once the match is determined, the text corresponding to the match (called the token) is made available in the global character pointer yytext, and its length in the global integer yyleng. The action corresponding to the matched pattern is then executed (a more detailed description of actions follows), and then the remaining input is scanned for another match.
If no match is found, then the default rule is executed: the next character in the input is considered matched and copied to the standard output. Thus, the simplest legal flex input is:
%%
which generates a scanner that simply copies its input (one character at a time) to its output.
ACTIONS
Each pattern in a rule has a corresponding action, which can be any arbitrary C 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"
(It 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:
%%
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. Once it reaches an end-of-file, however, then any subsequent call to yylex() will simply immediately return, unless yyrestart() is first called (see below).
Actions are not allowed to modify yytext or yyleng.
There are a number of special directives which can be included within an action:
%%
Note also that unlike the other special actions, REJECT is a branch; code immediately following it in the action will not be executed.
Note that since each unput() puts the given character back at the beginning of the input stream, pushing back strings must be done back-to-front.
(Note that if the scanner is compiled using C++, then input() is instead referred to as yyinput(), in order to avoid a name clash with the C++ stream by the name of input.)
int yylex()
{
... various definitions and the actions in here ... }
(If your environment supports function prototypes, then it will be "int yylex( void )".) This definition may be changed by redefining the "YY_DECL" macro. For example, you could use:
#undef YY_DECL
#define YY_DECL float lexscan( a, b ) float a, b;
to give the scanning routine the name lexscan, returning a float, and taking two floats as arguments. Note that if you give arguments to the scanning routine using a K&Rstyle/non-prototyped function declaration, you must terminate the definition with a semi-colon (;).
Whenever yylex() is called, it scans tokens from the global input file yyin (which defaults to stdin). It continues until it either reaches an end-of-file (at which point it returns the value 0) or one of its actions executes a return statement. In the former case, when called again the scanner will immediately return unless yyrestart() is called to point yyin at the new input file. ( yyrestart() takes one argument, a FILE * pointer.) In the latter case (i.e., when an action executes a return), the scanner may then be called again and it will resume scanning where it left off.
By default (and for purposes of efficiency), the scanner uses block-reads rather than simple getc() calls to read characters from yyin. The nature of how it gets its input can be controlled by redefining the YY_INPUT macro. YY_INPUT's calling sequence is "YY_INPUT(buf,result,max_size)". Its action is to place up to max_size characters in the character array buf and return in the integer variable result either the number of characters read or the constant YY_NULL (0 on Unix systems) to indicate EOF. The default YY_INPUT reads from the global file-pointer "yyin".
A sample redefinition of YY_INPUT (in the definitions section of the input file):
%{
#undef YY_INPUT
#define YY_INPUT(buf,result,max_size) \ { \
int c = getchar(); \
result = (c == EOF) ? YY_NULL : (buf[0] = c, 1); \ }
%}
This definition will change the input processing to occur one character at a time.
You also can add in things like keeping track of the input line number this way; but don't expect your scanner to go very fast.
When the scanner receives an end-of-file indication from YY_INPUT, it then checks the yywrap() function. If yywrap() returns false (zero), then it is assumed that the function has gone ahead and set up yyin to point to another input file, and scanning continues. If it returns true (nonzero), then the scanner terminates, returning 0 to its caller.
The default yywrap() always returns 1. Presently, to redefine it you must first "#undef yywrap", as it is currently implemented as a macro. As indicated by the hedging in the previous sentence, it may be changed to a true function in the near future.
The scanner writes its ECHO output to the yyout global (default, stdout), which may be redefined by the user simply by assigning it to some other FILE pointer.
START CONDITIONS
flex provides a mechanism for conditionally activating rules. Any rule whose pattern is prefixed with "<sc>" will only be active when the scanner is in the start condition named "sc". For example,
<INITIAL,STRING,QUOTE>\. { /* handle an escape ... */ ...
}
will be active only when the current start condition is either "INITIAL", "STRING", or "QUOTE".
Start conditions are declared in the definitions (first) section of the input using unindented lines beginning with either %s or %x followed by a list of names. The former declares inclusive start conditions, the latter exclusive start conditions. A start condition is activated using the BEGIN action. Until the next BEGIN action is executed, rules with the given start condition will be active and rules with other start conditions will be inactive. If the start condition is inclusive, then rules with no start conditions at all will also be active. If it is exclusive, then only rules qualified with the start condition will be active. A set of rules contingent on the same exclusive start condition describe a scanner which is independent of any of the other rules in the flex input. Because of this, exclusive start conditions make it easy to specify "miniscanners" which scan portions of the input that are syntactically different from the rest (e.g., comments).
If the distinction between inclusive and exclusive start conditions is still a little vague, here's a simple example illustrating the connection between the two. The set of rules:
%s example
%%
%x example
%%
BEGIN(0) returns to the original state where only the rules with no start conditions are active. This state can also be referred to as the start-condition "INITIAL", so BEGIN(INITIAL) is equivalent to BEGIN(0). (The parentheses around the start condition name are not required but are considered good style.)
BEGIN actions can also be given as indented code at the beginning of the rules section. For example, the following will cause the scanner to enter the "SPECIAL" start condition whenever yylex() is called and the global variable enter_special is true:
int enter_special;
%x SPECIAL
%%
if ( enter_special )
BEGIN(SPECIAL);
<SPECIAL>blahblahblah
...more rules follow...
To illustrate the uses of start conditions, here is a scanner which provides two different interpretations of a string like "123.456". By default it will treat it as as three tokens, the integer "123", a dot ('.'), and the integer "456". But if the string is preceded earlier in the line by the string "expect-floats" it will treat it as a single token, the floating-point number 123.456:
%{
#include <math.h>
%}
%s expect
%%
%x comment
%%
int line_num = 1;
%x comment foo
%%
int line_num = 1;
int comment_caller;
MULTIPLE INPUT BUFFERS
Some scanners (such as those which support "include" files) require reading from several input streams. As flex scanners do a large amount of buffering, one cannot control where the next input will be read from by simply writing a YY_INPUT which is sensitive to the scanning context. YY_INPUT is only called when the scanner reaches the end of its buffer, which may be a long time after scanning a statement such as an "include" which requires switching the input source.
To negotiate these sorts of problems, flex provides a mechanism for creating and switching between multiple input buffers. An input buffer is created by using:
YY_BUFFER_STATE yy_create_buffer( FILE *file, int size )
which takes a FILE pointer and a size and creates a buffer associated with the given file and large enough to hold size characters (when in doubt, use YY_BUF_SIZE for the size). It returns a YY_BUFFER_STATE handle, which may then be passed to other routines:
void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer )
switches the scanner's input buffer so subsequent tokens will come from new_buffer. Note that yy_switch_to_buffer() may be used by yywrap() to sets things up for continued scanning, instead of opening a new file and pointing yyin at it.
void yy_delete_buffer( YY_BUFFER_STATE buffer )
is used to reclaim the storage associated with a buffer.
yy_new_buffer() is an alias for yy_create_buffer(), provided for compatibility with the C++ use of new and delete for creating and destroying dynamic objects.
Finally, the YY_CURRENT_BUFFER macro returns a YY_BUFFER_STATE handle to the current buffer.
Here is an example of using these features for writing a scanner which expands include files (the <<EOF>> feature is discussed below):
/* the "incl" state is used for picking up the name * of an include file
*/
%x incl
%{
#define MAX_INCLUDE_DEPTH 10
YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH]; int include_stack_ptr = 0;
%}
%%
yyin = fopen( yytext, "r" );
if ( ! yyin )
error( ... );
yy_switch_to_buffer(
yy_create_buffer( yyin, YY_BUF_SIZE ) );
BEGIN(INITIAL);
}
<<EOF>> {
if ( --include_stack_ptr < 0 ) {
yyterminate();
}
else
yy_switch_to_buffer(
include_stack[include_stack_ptr] ); }
END-OF-FILE RULES
The special rule "<<EOF>>" indicates actions which are to be taken when an end-of-file is encountered and yywrap() returns non-zero (i.e., indicates no further files to process). The action must finish by doing one of four things:
<INITIAL><<EOF>>
These rules are useful for catching things like unclosed comments. An example:
%x quote
%%
MISCELLANEOUS MACROS
The macro YY_USER_ACTION can be redefined to provide an action which is always executed prior to the matched rule's action. For example, it could be #define'd to call a routine to convert yytext to lower-case.
The macro YY_USER_INIT may be redefined to provide an action which is always executed before the first scan (and before the scanner's internal initializations are done). For example, it could be used to call a routine to read in a data table or open a logging file.
In the generated scanner, the actions are all gathered in one large switch statement and separated using YY_BREAK, which may be redefined. By default, it is simply a "break", to separate each rule's action from the following rule's. Redefining YY_BREAK allows, for example, C++ users to #define YY_BREAK to do nothing (while being very careful that every rule ends with a "break" or a "return"!) to avoid suffering from unreachable statement warnings where because a rule's action ends with "return", the YY_BREAK is inaccessible.
INTERFACING WITH YACC
One of the main uses of flex is as a companion to the yacc parser-generator. yacc parsers expect to call a routine named yylex() to find the next input token. The routine is supposed to return the type of the next token as well as putting any associated value in the global yylval. To use flex with yacc, one specifies the -d option to yacc to instruct it to generate the file y.tab.h containing definitions of all the %tokens appearing in the yacc input. This file is then included in the flex scanner. For example, if one of the tokens is "TOK_NUMBER", part of the scanner might look like:
%{
#include "y.tab.h"
%}
%%
%t
Note that the -i option (see below) coupled with the equivalence classes which flex automatically generates take care of virtually all the instances when one might consider using %t. But what the hell, it's there if you want it.
OPTIONS
flex has the following options:
This option is equivalent to -CF (see below).
Note, -I cannot be used in conjunction with full or fast tables, i.e., the -f, -F, -Cf, or -CF flags.
The options -Cf or -CF and -Cm do not make sense together - there is no opportunity for meta-equivalence classes if the table is not being compressed. Otherwise the options may be freely mixed.
The default setting is -Cem, which specifies that flex should generate equivalence classes and metaequivalence classes. This setting provides the highest degree of table compression. You can trade off faster-executing scanners at the cost of larger tables with the following generally being true:
slowest & smallest
-Cem
-Cm
-Ce
-C
-C{f,F}e
-C{f,F}
fastest & largest
Note that scanners with the smallest tables are usually generated and compiled the quickest, so during development you will usually want to use the default, maximal compression.
`^' beginning-of-line operator
yymore()
with the first three all being quite expensive and the last two being quite cheap.
REJECT should be avoided at all costs when performance is important. It is a particularly expensive option.
Getting rid of backtracking is messy and often may be an enormous amount of work for a complicated scanner. In principal, one begins by using the -b flag to generate a lex.backtrack file. For example, on the input
%%
State #6 is non-accepting associated
rule line numbers:
State #8 is non-accepting associated
rule line numbers:
3
out-transitions: [ a ]
jam-transitions: EOF [ \001-` b-\177 ]
State #9 is non-accepting associated
rule line numbers:
3
out-transitions: [ r ]
jam-transitions: EOF [ \001-q s-\177 ]
Compressed tables always backtrack.
The first few lines tell us that there's a scanner state in which it can make a transition on an `o' but not on any other character, and that in that state the currently scanned text does not match any rule. The state occurs when trying to match the rules found at lines 2 and 3 in the input file. If the scanner is in that state and then reads something other than an `o', it will have to backtrack to find a rule which is matched. With a bit of headscratching one can see that this must be the state it's in when it has seen "fo". When this has happened, if anything other than another `o' is seen, the scanner will have to back up to simply match the `f' (by the default rule).
The comment regarding State #8 indicates there's a problem when "foob" has been scanned. Indeed, on any character other than a `b', the scanner will have to back up to accept "foo". Similarly, the comment for State #9 concerns when "fooba" has been scanned.
The final comment reminds us that there's no point going to all the trouble of removing backtracking from the rules unless we're using -f or -F, since there's no performance gain doing so with compressed scanners.
The way to remove the backtracking is to add "error" rules:
%%
%%
Backtracking messages tend to cascade. With a complicated set of rules it's not uncommon to get hundreds of messages. If one can decipher them, though, it often only takes a dozen or so rules to eliminate the backtracking (though it's easy to make a mistake and have an error rule accidentally match a valid token. A possible future flex feature will be to automatically add rules to eliminate backtracking).
Variable trailing context (where both the leading and trailing parts do not have a fixed length) entails almost the same performance loss as REJECT (i.e., substantial). So when possible a rule like:
%%
mouse|rat/(cat|dog) run();
is better written:
%%
%%
Another area where the user can increase a scanner's performance (and one that's easier to implement) arises from the fact that the longer the tokens matched, the faster the scanner will run. This is because with long tokens the processing of most input characters takes place in the (short) inner scanning loop, and does not often have to go through the additional work of setting up the scanning environment (e.g., yytext) for the action. Recall the scanner for C comments:
%x comment
%%
int line_num = 1;
%x comment
%%
int line_num = 1;
A final example in speeding up a scanner: suppose you want to scan through a file containing identifiers and keywords, one per line and with no other extraneous characters, and recognize all the keywords. A natural first approach is:
%%
%%
%%
%%
A final note: flex is slow when matching NUL's, particularly when a token contains multiple NUL's. It's best to write rules which match short amounts of text if it's anticipated that the text will often include NUL's.
INCOMPATIBILITIES WITH LEX AND POSIX
flex is a rewrite of the Unix lex tool (the two implementations do not share any code, though), with some extensions and incompatibilities, both of which are of concern to those who wish to write scanners acceptable to either implementation. At present, the POSIX lex draft is very close to the original lex implementation, so some of these incompatibilities are also in conflict with the POSIX draft. But the intent is that except as noted below, flex as it presently stands will ultimately be POSIX conformant (i.e., that those areas of conflict with the POSIX draft will be resolved in flex's favor). Please bear in mind that all the comments which follow are with regard to the POSIX draft standard of Summer 1989, and not the final document (or subsequent drafts); they are included so flex users can be aware of the standardization issues and those areas where flex may in the near future undergo changes incompatible with its current definition.
flex is fully compatible with lex with the following exceptions:
yylineno is not part of the POSIX draft.
The flex restriction that input() cannot be redefined is in accordance with the POSIX draft, but YY_INPUT has not yet been accepted into the draft (and probably won't; it looks like the draft will simply not specify any way of controlling the scanner's input other than by making an initial assignment to yyin).
To reenter the scanner, first use
yyrestart( yyin );
The POSIX draft interpretation is the same as flex's.
yyterminate()
<<EOF>>
YY_DECL
#line directives
%{}'s around actions
yyrestart()
comments beginning with `#' (deprecated) multiple actions on a line
This last feature refers to the fact that with flex you can put multiple actions on the same line, separated with semicolons, while with lex, the following
DIAGNOSTICS
reject_used_but_not_detected undefined or yymore_used_but_not_detected undefined - These errors can occur at compile time. They indicate that the scanner uses REJECT or yymore() but that flex failed to notice the fact, meaning that flex scanned the first two sections looking for occurrences of these actions and failed to find any, but somehow you snuck some in (via a #include file, for example). Make an explicit reference to the action in your flex input file. (Note that previously flex supported a %used/%unused mechanism for dealing with this problem; this feature is still supported but now deprecated, and will go away soon unless the author hears from people who can argue compellingly that they need it.)
flex scanner jammed - a scanner compiled with -s has encountered an input string which wasn't matched by any of its rules.
flex input buffer overflowed - a scanner rule matched a string long enough to overflow the scanner's internal input buffer (16K bytes by default - controlled by YY_BUF_SIZE in "flex.skel". Note that to redefine this macro, you must first #undefine it).
scanner requires -8 flag - Your scanner specification includes recognizing 8-bit characters and you did not specify the -8 flag (and your site has not installed flex with -8 as the default).
fatal flex scanner internal error--end of buffer missed This can occur in an scanner which is reentered after a long-jump has jumped out (or over) the scanner's activation frame. Before reentering the scanner, use:
yyrestart( yyin );
too many %t classes! - You managed to put every single character into its own %t class. flex requires that at least one of the classes share characters.
DEFICIENCIES / BUGS
See flex(1).
SEE ALSO
flex(1), lex(1), yacc(1), sed(1), awk(1).
M. E. Lesk and E. Schmidt, LEX - Lexical Analyzer Generator
AUTHOR
Vern Paxson, with the help of many ideas and much inspiration from Van Jacobson. Original version by Jef Poskanzer. The fast table representation is a partial implementation of a design done by Van Jacobson. The implementation was done by Kevin Gong and Vern Paxson.
Thanks to the many flex beta-testers, feedbackers, and contributors, especially Casey Leedom, benson@odi.com, Keith Bostic, Frederic Brehm, Nick Christopher, Jason Coughlin, Scott David Daniels, Leo Eskin, Chris Faylor, Eric Goldman, Eric Hughes, Jeffrey R. Jones, Kevin B. Kenny, Ronald Lamprecht, Greg Lee, Craig Leres, Mohamed el Lozy, Jim Meyering, Marc Nozell, Esmond Pitt, Jef Poskanzer, Jim Roskind, Dave Tallman, Frank Whaley, Ken Yap, and those whose names have slipped my marginal mail-archiving skills but whose contributions are appreciated all the same.
Thanks to Keith Bostic, John Gilmore, Craig Leres, Bob Mulcahy, Rich Salz, and Richard Stallman for help with various distribution headaches.
Thanks to Esmond Pitt and Earle Horton for 8-bit character support; to Benson Margulies and Fred Burke for C++ support; to Ove Ewerlid for the basics of support for NUL's; and to Eric Hughes for the basics of support for multiple buffers.
Work is being done on extending flex to generate scanners in which the state machine is directly represented in C code rather than tables. These scanners may well be substantially faster than those generated using -f or -F. If you are working in this area and are interested in comparing notes and seeing whether redundant work can be avoided, contact Ove Ewerlid (ewerlid@mizar.DoCS.UU.SE).
This work was primarily done when I was at the Real Time Systems Group at the Lawrence Berkeley Laboratory in Berkeley, CA. Many thanks to all there for the support I received.
Send comments to:
Vern Paxson
Computer Systems Engineering
Bldg. 46A, Room 1123
Lawrence Berkeley Laboratory
University of California
Berkeley, CA 94720
vern@ee.lbl.gov
ucbvax!ee.lbl.gov!vern