Flex, version 2.5
A fast scanner generator
Edition 2.5, March 1995
Vern PaxsonCopyright (C) 1990 The Regents of the University of California.All rights reserved.
This code is derived from software contributed to Berkeley byVern Paxson.
The United States Government has rights in this work pursuantto contract no. DE-AC03-76SF00098 between the United StatesDepartment of Energy and the University of California.
Redistribution and use in source and binary forms are permittedprovided that: (1) source distributions retain this entirecopyright notice and comment, and (2) distributions includingbinaries display the following acknowledgement: "This productincludes software developed by the University of California,Berkeley and its contributors" in the documentation or othermaterials provided with the distribution and in all advertisingmaterials mentioning features or use of this software. Neither thename of the University nor the names of its contributors may beused to endorse or promote products derived from this softwarewithout specific prior written permission.
THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS ORIMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE.
Name
flex - fast lexical analyzer generator
Synopsis
flex [-bcdfhilnpstvwBFILTV78+? -C[aefFmr] -ooutput -Pprefix -Sskeleton] [--help --version] [filename ...]
Overview
This manual describes flex
, a tool for generating programsthat perform pattern-matching on text. The manualincludes both tutorial and reference sections:
-
Description
- a brief overview of the tool Some Simple Examples
-
Format Of The Input File
-
Patterns
- the extended regular expressions used by flex How The Input Is Matched
- the rules for determining what has been matched Actions
- how to specify what to do when a pattern is matched The Generated Scanner
- details regarding the scanner that flex produces;how to control the input source Start Conditions
- introducing context into your scanners, andmanaging "mini-scanners" Multiple Input Buffers
- how to manipulate multiple input sources; how toscan from strings instead of files End-of-file Rules
- special rules for matching the end of the input Miscellaneous Macros
- a summary of macros available to the actions Values Available To The User
- a summary of values available to the actions Interfacing With Yacc
- connecting flex scanners together with yacc parsers Options
- flex command-line options, and the "%option"directive Performance Considerations
- how to make your scanner go as fast as possible Generating C++ Scanners
- the (experimental) facility for generating C++scanner classes Incompatibilities With Lex And POSIX
- how flex differs from AT&T lex and the POSIX lexstandard Diagnostics
- those error messages produced by flex (or scannersit generates) whose meanings might not be apparent Files
- files used by flex Deficiencies / Bugs
- known problems with flex See Also
- other documentation, related tools Author
- includes contact information
Description
flex
is a tool for generating scanners: programs whichrecognized lexical patterns in text. flex
reads the giveninput files, or its standard input if no file names aregiven, for a description of a scanner to generate. Thedescription is in the form of pairs of regular expressionsand C code, called rules. flex
generates as output a Csource file, `lex.yy.c', which defines a routine `yylex()'.This file is compiled and linked with the `-lfl' library toproduce an executable. When the executable is run, itanalyzes its input for occurrences of the regularexpressions. Whenever it finds one, it executes thecorresponding C code.
Some simple examples
First some simple examples to get the flavor of how oneuses flex
. The following flex
input specifies a scannerwhich whenever it encounters the string "username" willreplace it with the user's login name:
%% username printf( "%s", getlogin() );
By default, any text not matched by a flex
scanner iscopied to the output, so the net effect of this scanner isto copy its input file to its output with each occurrenceof "username" expanded. In this input, there is just onerule. "username" is the pattern and the "printf" is theaction. The "%%" marks the beginning of the rules.
Here's another simple example:
int num_lines = 0, num_chars = 0; %% \n ++num_lines; ++num_chars; . ++num_chars; %% main() { yylex(); printf( "# of lines = %d, # of chars = %d\n", num_lines, num_chars ); }
This scanner counts the number of characters and thenumber of lines in its input (it produces no output otherthan the final report on the counts). The first linedeclares two globals, "num_lines" and "num_chars", whichare 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 theline count and the character count, and one which matchesany 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> %} DIGIT [0-9] ID [a-z][a-z0-9]* %% {DIGIT}+ { printf( "An integer: %s (%d)\n", yytext, atoi( yytext ) ); } {DIGIT}+"."{DIGIT}* { printf( "A float: %s (%g)\n", yytext, atof( yytext ) ); } if|then|begin|end|procedure|function { printf( "A keyword: %s\n", yytext ); } {ID} printf( "An identifier: %s\n", yytext ); "+"|"-"|"*"|"/" printf( "An operator: %s\n", yytext ); "{"[^}\n]*"}" /* eat up one-line comments */ [ \t\n]+ /* eat up whitespace */ . printf( "Unrecognized character: %s\n", yytext ); %% 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 languagelike Pascal. It identifies different types of tokens andreports on what it has seen.
The details of this example will be explained in thefollowing sections.
Format of the input file
The flex
input file consists of three sections, separatedby a line with just `%%' in it:
definitions %% rules %% user code
The definitions section contains declarations of simplename definitions to simplify the scanner specification,and declarations of start conditions, which are explainedin a later section.Name definitions have the form:
name definition
The "name" is a word beginning with a letter or anunderscore ('_') followed by zero or more letters, digits, '_',or '-' (dash). The definition is taken to begin at thefirst non-white-space character following the name andcontinuing to the end of the line. The definition cansubsequently be referred to using "{name}", which willexpand to "(definition)". For example,
DIGIT [0-9] ID [a-z][a-z0-9]*
defines "DIGIT" to be a regular expression which matches asingle digit, and "ID" to be a regular expression whichmatches a letter followed by zero-or-moreletters-or-digits. A subsequent reference to
{DIGIT}+"."{DIGIT}*
is identical to
([0-9])+"."([0-9])*
and matches one-or-more digits followed by a '.' followedby zero-or-more digits.
The rules section of the flex
input contains a series ofrules of the form:
pattern action
where the pattern must be unindented and the action mustbegin on the same line.
See below for a further description of patterns andactions.
Finally, the user code section is simply copied to`lex.yy.c' verbatim. It is used for companion routineswhich call or are called by the scanner. The presence ofthis 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 ortext enclosed in `%{' and `%}' is copied verbatim to theoutput (with the `%{}''s removed). The `%{}''s mustappear unindented on lines by themselves.
In the rules section, any indented or %{} text appearingbefore the first rule may be used to declare variableswhich are local to the scanning routine and (after thedeclarations) code which is to be executed whenever thescanning routine is entered. Other indented or %{} textin the rule section is still copied to the output, but itsmeaning is not well-defined and it may well causecompile-time errors (this feature is present for POSIX
compliance;see below for other such features).
In the definitions section (but not in the rules section),an unindented comment (i.e., a line beginning with "/*")is also copied verbatim to the output up to the next "*/".
Patterns
The patterns in the input are written using an extendedset of regular expressions. These are:
-
`x'
- match the character `x' `.'
- any character (byte) except newline `[xyz]'
- a "character class"; in this case, the patternmatches either an `x', a `y', or a `z' `[abj-oZ]'
- a "character class" with a range in it; matchesan `a', a `b', any letter from `j' through `o',or a `Z' `[^A-Z]'
- a "negated character class", i.e., any characterbut those in the class. In this case, anycharacter EXCEPT an uppercase letter. `[^A-Z\n]'
- any character EXCEPT an uppercase letter ora newline `r*'
- zero or more r's, where r is any regular expression `r+'
- one or more r's `r?'
- zero or one r's (that is, "an optional r") `r{2,5}'
- anywhere from two to five r's `r{2,}'
- two or more r's `r{4}'
- exactly 4 r's `{name}'
- the expansion of the " name" definition(see above) `"[xyz]\"foo"'
- the literal string: `[xyz]"foo' `\x'
- if x is an `a', `b', `f', `n', `r', `t', or `v',then the ANSI-C interpretation of \ x.Otherwise, a literal `x' (used to escapeoperators such as `*') `\0'
- a NUL character (ASCII code 0) `\123'
- the character with octal value 123 `\x2a'
-
the character with hexadecimal value
2a
`(r)'
- match an r; parentheses are used to overrideprecedence (see below) `rs'
- the regular expression r followed by theregular expression s; called "concatenation" `r|s'
- either an r or an s `r/s'
-
an
r but only if it is followed by an
s. The textmatched by
s is included when determining whether this rule isthe
longest match, but is then returned to the input beforethe action is executed. So the action only sees the text matchedby
r. This type of pattern is called
trailing context.(There are some combinations of
`r/s' that
flex
cannot match correctly; see notes in the Deficiencies / Bugs sectionbelow regarding "dangerous trailing context".)
`^r'
- an r, but only at the beginning of a line (i.e.,which just starting to scan, or right after anewline has been scanned). `r$'
- an r, but only at the end of a line (i.e., justbefore a newline). Equivalent to " r/\n".Note that flex's notion of "newline" is exactlywhatever the C compiler used to compile flexinterprets '\n' as; in particular, on some DOSsystems you must either filter out \r's in theinput yourself, or explicitly use r/\r\n for "r$". `<s>r'
- an r, but only in start condition s (seebelow for discussion of start conditions)< s1, s2, s3> rsame, but in any of start conditions s1, s2, or s3 `<*>r'
- an r in any start condition, even an exclusive one. `<<EOF>>'
- an end-of-file< s1, s2><<EOF>>an end-of-file when in start condition s1 or s2
Note that inside of a character class, all regularexpression operators lose their special meaning except escape('\') and the character class operators, '-', ']', and, atthe beginning of the class, '^'.
The regular expressions listed above are grouped accordingto precedence, from highest precedence at the top tolowest at the bottom. Those grouped together have equalprecedence. For example,
foo|bar*
is the same as
(foo)|(ba(r*))
since the '*' operator has higher precedence thanconcatenation, and concatenation higher than alternation ('|').This pattern therefore matches either the string "foo" orthe 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)*
In addition to characters and ranges of characters,character classes can also contain character classexpressions. These are expressions enclosed inside `[': and `:']delimiters (which themselves must appear between the '['and ']' of the character class; other elements may occurinside the character class, too). The valid expressionsare:
[:alnum:] [:alpha:] [:blank:] [:cntrl:] [:digit:] [:graph:] [:lower:] [:print:] [:punct:] [:space:] [:upper:] [:xdigit:]
These expressions all designate a set of charactersequivalent to the corresponding standard C `isXXX' function. Forexample, `[:alnum:]' designates those characters for which`isalnum()' returns true - i.e., any alphabetic or numeric.Some systems don't provide `isblank()', so flex defines`[:blank:]' as a blank or a tab.
For example, the following character classes are allequivalent:
[[:alnum:]] [[:alpha:][:digit:] [[:alpha:]0-9] [a-zA-Z0-9]
If your scanner is case-insensitive (the `-i' flag), then`[:upper:]' and `[:lower:]' are equivalent to `[:alpha:]'.
Some notes on patterns:
- A negated character class such as the example"[^A-Z]" above will match a newline unless "\n" (or anequivalent escape sequence) is one of thecharacters explicitly present in the negated characterclass (e.g., "[^A-Z\n]"). This is unlike how manyother regular expression tools treat negatedcharacter classes, but unfortunately the inconsistencyis historically entrenched. Matching newlinesmeans that a pattern like [^"]* can match theentire input unless there's another quote in theinput.
- A rule can have at most one instance of trailingcontext (the '/' operator or the '$' operator).The start condition, '^', and "<<EOF>>" patternscan only occur at the beginning of a pattern, and,as well as with '/' and '$', cannot be groupedinside parentheses. A '^' which does not occur atthe beginning of a rule or a '$' which does notoccur at the end of a rule loses its specialproperties and is treated as a normal character.The following are illegal:
foo/bar$ <sc1>foo<sc2>bar
Note that the first of these, can be written"foo/bar\n".The following will result in '$' or '^' beingtreated as a normal character:foo|(bar$) foo|^bar
If what's wanted is a "foo" or abar-followed-by-a-newline, the following could be used (the special'|' action is explained below):foo | bar$ /* action goes here */
A similar trick will work for matching a foo or abar-at-the-beginning-of-a-line.
How the input is matched
When the generated scanner is run, it analyzes its inputlooking for strings which match any of its patterns. Ifit finds more than one match, it takes the one matchingthe most text (for trailing context rules, this includesthe length of the trailing part, even though it will thenbe returned to the input). If it finds two or morematches of the same length, the rule listed first in theflex
input file is chosen.
Once the match is determined, the text corresponding tothe match (called the token) is made available in theglobal character pointer yytext
, and its length in theglobal integer yyleng
. The action corresponding to thematched pattern is then executed (a more detaileddescription of actions follows), and then the remaining input isscanned for another match.
If no match is found, then the default rule is executed:the next character in the input is considered matched andcopied to the standard output. Thus, the simplest legalflex
input is:
%%
which generates a scanner that simply copies its input(one character at a time) to its output.
Note that yytext
can be defined in two different ways:either as a character pointer or as a character array.You can control which definition flex
uses by includingone of the special directives `%pointer' or `%array' in thefirst (definitions) section of your flex input. Thedefault is `%pointer', unless you use the `-l' lexcompatibility option, in which case yytext
will be an array. Theadvantage of using `%pointer' is substantially fasterscanning and no buffer overflow when matching very largetokens (unless you run out of dynamic memory). Thedisadvantage is that you are restricted in how your actions canmodify yytext
(see the next section), and calls to the`unput()' function destroys the present contents of yytext
,which can be a considerable porting headache when movingbetween different lex
versions.
The advantage of `%array' is that you can then modify yytext
to your heart's content, and calls to `unput()' do notdestroy yytext
(see below). Furthermore, existing lex
programs sometimes access yytext
externally usingdeclarations of the form:
extern char yytext[];
This definition is erroneous when used with `%pointer', butcorrect for `%array'.
`%array' defines yytext
to be an array of YYLMAX
characters,which defaults to a fairly large value. You can changethe size by simply #define'ing YYLMAX
to a different valuein the first section of your flex
input. As mentionedabove, with `%pointer' yytext grows dynamically toaccommodate large tokens. While this means your `%pointer' scannercan accommodate very large tokens (such as matching entireblocks of comments), bear in mind that each time thescanner must resize yytext
it also must rescan the entiretoken from the beginning, so matching such tokens canprove slow. yytext
presently does not dynamically grow ifa call to `unput()' results in too much text being pushedback; instead, a run-time error results.
Also note that you cannot use `%array' with C++ scannerclasses (the c++
option; see below).
Actions
Each pattern in a rule has a corresponding action, whichcan be any arbitrary C statement. The pattern ends at thefirst non-escaped whitespace character; the remainder ofthe line is its action. If the action is empty, then whenthe pattern is matched the input token is simplydiscarded. For example, here is the specification for aprogram which deletes all occurrences of "zap me" from itsinput:
%% "zap me"
(It will copy all other characters in the input to theoutput since they will be matched by the default rule.)
Here is a program which compresses multiple blanks andtabs down to a single blank, and throws away whitespacefound at the end of a line:
%% [ \t]+ putchar( ' ' ); [ \t]+$ /* ignore this token */
If the action contains a '{', then the action spans tillthe balancing '}' is found, and the action may crossmultiple lines. flex
knows about C strings and comments andwon't be fooled by braces found within them, but alsoallows actions to begin with `%{' and will consider theaction to be all the text up to the next `%}' (regardless ofordinary braces inside the action).
An action consisting solely of a vertical bar ('|') means"same as the action for the next rule." See below for anillustration.
Actions can include arbitrary C code, including return
statements to return a value to whatever routine called`yylex()'. Each time `yylex()' is called it continuesprocessing tokens from where it last left off until it eitherreaches the end of the file or executes a return.
Actions are free to modify yytext
except for lengtheningit (adding characters to its end--these will overwritelater characters in the input stream). This however doesnot apply when using `%array' (see above); in that case,yytext
may be freely modified in any way.
Actions are free to modify yyleng
except they should notdo so if the action also includes use of `yymore()' (seebelow).
There are a number of special directives which can beincluded within an action:
- `ECHO' copies yytext to the scanner's output.
BEGIN
followed by the name of a start conditionplaces the scanner in the corresponding startcondition (see below).REJECT
directs the scanner to proceed on to the"second best" rule which matched the input (or aprefix of the input). The rule is chosen asdescribed above in "How the Input is Matched", andyytext
andyyleng
set up appropriately. It mayeither be one which matched as much text as theoriginally chosen rule but came later in theflex
input file, or one which matched less text. Forexample, the following will both count the words inthe input and call the routine special() whenever"frob" is seen:int word_count = 0; %% frob special(); REJECT; [^ \t\n]+ ++word_count;
Without theREJECT
, any "frob"'s in the input wouldnot be counted as words, since the scanner normallyexecutes only one action per token. MultipleREJECT's
are allowed, each one finding the nextbest choice to the currently active rule. Forexample, when the following scanner scans the token"abcd", it will write "abcdabcaba" to the output:%% a | ab | abc | abcd ECHO; REJECT; .|\n /* eat up any unmatched character */
(The first three rules share the fourth's actionsince they use the special '|' action.)REJECT
isa particularly expensive feature in terms ofscanner performance; if it is used in any of thescanner's actions it will slow down all of thescanner's matching. Furthermore,REJECT
cannot be usedwith the `-Cf' or `-CF' options (see below).Note also that unlike the other special actions,REJECT
is a branch; code immediately following itin the action will not be executed.- `yymore()' tells the scanner that the next time itmatches a rule, the corresponding token should beappended onto the current value of
yytext
ratherthan replacing it. For example, given the input"mega-kludge" the following will write"mega-mega-kludge" to the output:%% mega- ECHO; yymore(); kludge ECHO;
First "mega-" is matched and echoed to the output.Then "kludge" is matched, but the previous "mega-"is still hanging around at the beginning ofyytext
so the `ECHO' for the "kludge" rule will actuallywrite "mega-kludge".
Two notes regarding use of `yymore()'. First, `yymore()'depends on the value of yyleng
correctly reflecting thesize 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 minorperformance penalty in the scanner's matching speed.
- `yyless(n)' returns all but the first n characters ofthe current token back to the input stream, wherethey will be rescanned when the scanner looks forthe next match.
yytext
andyyleng
are adjustedappropriately (e.g.,yyleng
will now be equal to n). For example, on the input "foobar" thefollowing will write out "foobarbar":%% foobar ECHO; yyless(3); [a-z]+ ECHO;
An argument of 0 toyyless
will cause the entirecurrent input string to be scanned again. Unlessyou've changed how the scanner will subsequentlyprocess its input (usingBEGIN
, for example), thiswill result in an endless loop.Note thatyyless
is a macro and can only be used in theflex input file, not from other source files. - `unput(c)' puts the character
c
back onto the inputstream. It will be the next character scanned.The following action will take the current tokenand cause it to be rescanned enclosed inparentheses.{ int i; /* Copy yytext because unput() trashes yytext */ char *yycopy = strdup( yytext ); unput( ')' ); for ( i = yyleng - 1; i >= 0; --i ) unput( yycopy[i] ); unput( '(' ); free( yycopy ); }
Note that since each `unput()' puts the givencharacter back at the beginning of the input stream,pushing back strings must be done back-to-front.An important potential problem when using `unput()' is thatif you are using `%pointer' (the default), a call to `unput()'destroys the contents ofyytext
, starting with itsrightmost character and devouring one character to the leftwith each call. If you need the value of yytext preservedafter a call to `unput()' (as in the above example), youmust either first copy it elsewhere, or build your scannerusing `%array' instead (see How The Input Is Matched).Finally, note that you cannot put backEOF
to attempt tomark the input stream with an end-of-file. - `input()' reads the next character from the inputstream. For example, the following is one way toeat up C comments:
%% "/*" { register int c; for ( ; ; ) { while ( (c = input()) != '*' && c != EOF ) ; /* eat up text of comment */ if ( c == '*' ) { while ( (c = input()) == '*' ) ; if ( c == '/' ) break; /* found the end */ } if ( c == EOF ) { error( "EOF in comment" ); break; } } }
(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++' streamby the name ofinput
.) - YY_FLUSH_BUFFERflushes the scanner's internal buffer so that the next time the scannerattempts to match a token, it will first refill the buffer using
YY_INPUT
(see The Generated Scanner, below). This action isa special case of the more general `yy_flush_buffer()' function,described below in the section Multiple Input Buffers. - `yyterminate()' can be used in lieu of a returnstatement in an action. It terminates the scannerand returns a 0 to the scanner's caller, indicating"all done". By default, `yyterminate()' is alsocalled when an end-of-file is encountered. It is amacro and may be redefined.
The generated scanner
The output of flex
is the file `lex.yy.c', which containsthe scanning routine `yylex()', a number of tables used byit for matching tokens, and a number of auxiliary routinesand macros. By default, `yylex()' is declared as follows:
int yylex() { ... various definitions and the actions in here ... }
(If your environment supports function prototypes, then itwill be "int yylex( void )".) This definition may bechanged by defining the "YY_DECL" macro. For example, youcould use:
#define YY_DECL float lexscan( a, b ) float a, b;
to give the scanning routine the name lexscan
, returning afloat, and taking two floats as arguments. Note that ifyou give arguments to the scanning routine using aK&R-style/non-prototyped function declaration, you mustterminate the definition with a semi-colon (`;').
Whenever `yylex()' is called, it scans tokens from theglobal input file yyin
(which defaults to stdin). Itcontinues until it either reaches an end-of-file (at whichpoint it returns the value 0) or one of its actionsexecutes a return
statement.
If the scanner reaches an end-of-file, subsequent calls are undefinedunless either yyin
is pointed at a new input file (in which casescanning continues from that file), or `yyrestart()' is called.`yyrestart()' takes one argument, a `FILE *' pointer (whichcan be nil, if you've set up YY_INPUT
to scan from a sourceother than yyin
), and initializes yyin
for scanning fromthat file. Essentially there is no difference between just assigningyyin
to a new input file or using `yyrestart()' to do so;the latter is available for compatibility with previous versions offlex
, and because it can be used to switch input files in themiddle of scanning. It can also be used to throw away the currentinput buffer, by calling it with an argument of yyin
; butbetter is to use YY_FLUSH_BUFFER
(see above). Note that`yyrestart()' does not reset the start condition toINITIAL
(see Start Conditions, below).
If `yylex()' stops scanning due to executing a return
statement in one of the actions, the scanner may then be calledagain and it will resume scanning where it left off.
By default (and for purposes of efficiency), the scanneruses block-reads rather than simple `getc()' calls to readcharacters from yyin
. The nature of how it gets its inputcan be controlled by defining the YY_INPUT
macro.YY_INPUT's calling sequence is"YY_INPUT(buf,result,max_size)". Its action is to placeup to max_size characters in the character array buf andreturn in the integer variable result either the number ofcharacters read or the constant YY_NULL (0 on Unixsystems) to indicate EOF. The default YY_INPUT reads fromthe global file-pointer "yyin".
A sample definition of YY_INPUT (in the definitionssection of the input file):
%{ #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 occurone character at a time.
When the scanner receives an end-of-file indication fromYY_INPUT, it then checks the `yywrap()' function. If`yywrap()' returns false (zero), then it is assumed that thefunction has gone ahead and set up yyin
to point toanother input file, and scanning continues. If it returnstrue (non-zero), then the scanner terminates, returning 0to its caller. Note that in either case, the startcondition remains unchanged; it does not revert to INITIAL
.
If you do not supply your own version of `yywrap()', then youmust either use `%option noyywrap' (in which case the scannerbehaves as though `yywrap()' returned 1), or you must link with`-lfl' to obtain the default version of the routine, which alwaysreturns 1.
Three routines are available for scanning from in-memorybuffers rather than files: `yy_scan_string()',`yy_scan_bytes()', and `yy_scan_buffer()'. See the discussionof them below in the section Multiple Input Buffers.
The scanner writes its `ECHO' output to the yyout
global(default, stdout), which may be redefined by the usersimply by assigning it to some other FILE
pointer.
Start conditions
flex
provides a mechanism for conditionally activatingrules. Any rule whose pattern is prefixed with "<sc>"will only be active when the scanner is in the startcondition named "sc". For example,
<STRING>[^"]* { /* eat up the string body ... */ ... }
will be active only when the scanner is in the "STRING"start condition, and
<INITIAL,STRING,QUOTE>\. { /* handle an escape ... */ ... }
will be active only when the current start condition iseither "INITIAL", "STRING", or "QUOTE".
Start conditions are declared in the definitions (first)section of the input using unindented lines beginning witheither `%s' or `%x' followed by a list of names. The formerdeclares inclusive start conditions, the latter exclusivestart conditions. A start condition is activated usingthe BEGIN
action. Until the next BEGIN
action isexecuted, rules with the given start condition will be activeand rules with other start conditions will be inactive.If the start condition is inclusive, then rules with nostart conditions at all will also be active. If it isexclusive, then only rules qualified with the startcondition will be active. A set of rules contingent on thesame exclusive start condition describe a scanner which isindependent of any of the other rules in the flex
input.Because of this, exclusive start conditions make it easyto specify "mini-scanners" which scan portions of theinput that are syntactically different from the rest(e.g., comments).
If the distinction between inclusive and exclusive startconditions is still a little vague, here's a simpleexample illustrating the connection between the two. The setof rules:
%s example %% <example>foo do_something(); bar something_else();
is equivalent to
%x example %% <example>foo do_something(); <INITIAL,example>bar something_else();
Without the `<INITIAL,example>' qualifier, the `bar' patternin the second example wouldn't be active (i.e., couldn't match) whenin start condition `example'. If we just used `<example>'to qualify `bar', though, then it would only be active in`example' and not in INITIAL
, while in the first exampleit's active in both, because in the first example the `example'starting condition is an inclusive (`%s') start condition.
Also note that the special start-condition specifier `<*>'matches every start condition. Thus, the above examplecould also have been written;
%x example %% <example>foo do_something(); <*>bar something_else();
The default rule (to `ECHO' any unmatched character) remainsactive in start conditions. It is equivalent to:
<*>.|\\n ECHO;
`BEGIN(0)' returns to the original state where only therules with no start conditions are active. This state canalso be referred to as the start-condition "INITIAL", so`BEGIN(INITIAL)' is equivalent to `BEGIN(0)'. (Theparentheses around the start condition name are not required butare considered good style.)
BEGIN
actions can also be given as indented code at thebeginning of the rules section. For example, thefollowing will cause the scanner to enter the "SPECIAL" startcondition whenever `yylex()' is called and the globalvariable 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 ascanner which provides two different interpretations of astring like "123.456". By default it will treat it as asthree tokens, the integer "123", a dot ('.'), and theinteger "456". But if the string is preceded earlier inthe line by the string "expect-floats" it will treat it asa single token, the floating-point number 123.456:
%{ #include <math.h> %} %s expect %% expect-floats BEGIN(expect); <expect>[0-9]+"."[0-9]+ { printf( "found a float, = %f\n", atof( yytext ) ); } <expect>\n { /* that's the end of the line, so * we need another "expect-number" * before we'll recognize any more * numbers */ BEGIN(INITIAL); } [0-9]+ { Version 2.5 December 1994 18 printf( "found an integer, = %d\n", atoi( yytext ) ); } "." printf( "found a dot\n" );
Here is a scanner which recognizes (and discards) Ccomments while maintaining a count of the current input line.
%x comment %% int line_num = 1; "/*" BEGIN(comment); <comment>[^*\n]* /* eat anything that's not a '*' */ <comment>"*"+[^*/\n]* /* eat up '*'s not followed by '/'s */ <comment>\n ++line_num; <comment>"*"+"/" BEGIN(INITIAL);
This scanner goes to a bit of trouble to match as muchtext as possible with each rule. In general, whenattempting to write a high-speed scanner try to match asmuch possible in each rule, as it's a big win.
Note that start-conditions names are really integer valuesand can be stored as such. Thus, the above could beextended in the following fashion:
%x comment foo %% int line_num = 1; int comment_caller; "/*" { comment_caller = INITIAL; BEGIN(comment); } ... <foo>"/*" { comment_caller = foo; BEGIN(comment); } <comment>[^*\n]* /* eat anything that's not a '*' */ <comment>"*"+[^*/\n]* /* eat up '*'s not followed by '/'s */ <comment>\n ++line_num; <comment>"*"+"/" BEGIN(comment_caller);
Furthermore, you can access the current start conditionusing the integer-valued YY_START
macro. For example, theabove assignments to comment_caller
could instead bewritten
comment_caller = YY_START;
Flex provides YYSTATE
as an alias for YY_START
(since thatis what's used by AT&T lex
).
Note that start conditions do not have their ownname-space; %s's and %x's declare names in the same fashion as#define's.
Finally, here's an example of how to match C-style quotedstrings using exclusive start conditions, includingexpanded escape sequences (but not including checking fora string that's too long):
%x str %% char string_buf[MAX_STR_CONST]; char *string_buf_ptr; \" string_buf_ptr = string_buf; BEGIN(str); <str>\" { /* saw closing quote - all done */ BEGIN(INITIAL); *string_buf_ptr = '\0'; /* return string constant token type and * value to parser */ } <str>\n { /* error - unterminated string constant */ /* generate error message */ } <str>\\[0-7]{1,3} { /* octal escape sequence */ int result; (void) sscanf( yytext + 1, "%o", &result ); if ( result > 0xff ) /* error, constant is out-of-bounds */ *string_buf_ptr++ = result; } <str>\\[0-9]+ { /* generate error - bad escape sequence; something * like '\48' or '\0777777' */ } <str>\\n *string_buf_ptr++ = '\n'; <str>\\t *string_buf_ptr++ = '\t'; <str>\\r *string_buf_ptr++ = '\r'; <str>\\b *string_buf_ptr++ = '\b'; <str>\\f *string_buf_ptr++ = '\f'; <str>\\(.|\n) *string_buf_ptr++ = yytext[1]; <str>[^\\\n\"]+ { char *yptr = yytext; while ( *yptr ) *string_buf_ptr++ = *yptr++; }
Often, such as in some of the examples above, you wind upwriting a whole bunch of rules all preceded by the samestart condition(s). Flex makes this a little easier andcleaner by introducing a notion of start condition scope.A start condition scope is begun with:
<SCs>{
where SCs is a list of one or more start conditions.Inside the start condition scope, every rule automaticallyhas the prefix `<SCs>' applied to it, until a `}' whichmatches the initial `{'. So, for example,
<ESC>{ "\\n" return '\n'; "\\r" return '\r'; "\\f" return '\f'; "\\0" return '\0'; }
is equivalent to:
<ESC>"\\n" return '\n'; <ESC>"\\r" return '\r'; <ESC>"\\f" return '\f'; <ESC>"\\0" return '\0';
Start condition scopes may be nested.
Three routines are available for manipulating stacks ofstart conditions:
-
`void yy_push_state(int new_state)'
- pushes the current start condition onto the top ofthe start condition stack and switches to new_stateas though you had used `BEGIN new_state' (recall thatstart condition names are also integers). `void yy_pop_state()'
-
pops the top of the stack and switches to it via
BEGIN
.
`int yy_top_state()'
- returns the top of the stack without altering thestack's contents.
The start condition stack grows dynamically and so has nobuilt-in size limitation. If memory is exhausted, programexecution aborts.
To use start condition stacks, your scanner must include a`%option stack' directive (see Options below).
Multiple input buffers
Some scanners (such as those which support "include"files) require reading from several input streams. Asflex
scanners do a large amount of buffering, one cannotcontrol where the next input will be read from by simplywriting a YY_INPUT
which is sensitive to the scanningcontext. YY_INPUT
is only called when the scanner reachesthe end of its buffer, which may be a long time afterscanning a statement such as an "include" which requiresswitching the input source.
To negotiate these sorts of problems, flex
provides amechanism for creating and switching between multipleinput 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 bufferassociated with the given file and large enough to holdsize characters (when in doubt, use YY_BUF_SIZE
for thesize). It returns a YY_BUFFER_STATE
handle, which maythen be passed to other routines (see below). TheYY_BUFFER_STATE
type is a pointer to an opaque struct
yy_buffer_state
structure, so you may safely initializeYY_BUFFER_STATE variables to `((YY_BUFFER_STATE) 0)' if youwish, and also refer to the opaque structure in order tocorrectly declare input buffers in source files other thanthat of your scanner. Note that the FILE
pointer in thecall to yy_create_buffer
is only used as the value of yyin
seen by YY_INPUT
; if you redefine YY_INPUT
so it no longeruses yyin
, then you can safely pass a nil FILE
pointer toyy_create_buffer
. You select a particular buffer to scanfrom using:
void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer )
switches the scanner's input buffer so subsequent tokenswill come from new_buffer. Note that`yy_switch_to_buffer()' may be used by `yywrap()' to setthings up for continued scanning, instead of opening a newfile and pointing yyin
at it. Note also that switchinginput sources via either `yy_switch_to_buffer()' or `yywrap()'does not change the start condition.
void yy_delete_buffer( YY_BUFFER_STATE buffer )
is used to reclaim the storage associated with a buffer.You can also clear the current contents of a buffer using:
void yy_flush_buffer( YY_BUFFER_STATE buffer )
This function discards the buffer's contents, so the next time thescanner attempts to match a token from the buffer, it will first fillthe buffer anew using YY_INPUT
.
`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 aYY_BUFFER_STATE
handle to the current buffer.
Here is an example of using these features for writing ascanner which expands include files (the `<<EOF>>' featureis 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; %} %% include BEGIN(incl); [a-z]+ ECHO; [^a-z\n]*\n? ECHO; <incl>[ \t]* /* eat the whitespace */ <incl>[^ \t\n]+ { /* got the include file name */ if ( include_stack_ptr >= MAX_INCLUDE_DEPTH ) { fprintf( stderr, "Includes nested too deeply" ); exit( 1 ); } include_stack[include_stack_ptr++] = YY_CURRENT_BUFFER; 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_delete_buffer( YY_CURRENT_BUFFER ); yy_switch_to_buffer( include_stack[include_stack_ptr] ); } }
Three routines are available for setting up input buffersfor scanning in-memory strings instead of files. All ofthem create a new input buffer for scanning the string,and return a corresponding YY_BUFFER_STATE
handle (whichyou should delete with `yy_delete_buffer()' when done withit). They also switch to the new buffer using`yy_switch_to_buffer()', so the next call to `yylex()' willstart scanning the string.
-
`yy_scan_string(const char *str)'
- scans a NUL-terminated string. `yy_scan_bytes(const char *bytes, int len)'
-
scans
len
bytes (including possibly NUL's) startingat location bytes.
Note that both of these functions create and scan a copyof the string or bytes. (This may be desirable, since`yylex()' modifies the contents of the buffer it isscanning.) You can avoid the copy by using:
-
`yy_scan_buffer(char *base, yy_size_t size)'
-
which scans in place the buffer starting at
base,consisting of
size bytes, the last two bytes ofwhich
must be
YY_END_OF_BUFFER_CHAR
(ASCII NUL).These last two bytes are not scanned; thus,scanning consists of `base[0]' through `base[size-2]',inclusive.If you fail to set up base in this manner (i.e.,forget the final twoYY_END_OF_BUFFER_CHAR
bytes),then `yy_scan_buffer()' returns a nil pointer insteadof creating a new input buffer.The typeyy_size_t
is an integral type to which youcan cast an integer expression reflecting the sizeof the buffer.
End-of-file rules
The special rule "<<EOF>>" indicates actions which are tobe taken when an end-of-file is encountered and yywrap()returns non-zero (i.e., indicates no further files toprocess). The action must finish by doing one of fourthings:
- assigning
yyin
to a new input file (in previousversions of flex, after doing the assignment youhad to call the special actionYY_NEW_FILE
; this isno longer necessary); - executing a
return
statement; - executing the special `yyterminate()' action;
- or, switching to a new buffer using`yy_switch_to_buffer()' as shown in the exampleabove.
<<EOF>> rules may not be used with other patterns; theymay only be qualified with a list of start conditions. Ifan unqualified <<EOF>> rule is given, it applies to allstart conditions which do not already have <<EOF>>actions. To specify an <<EOF>> rule for only the initialstart condition, use
<INITIAL><<EOF>>
These rules are useful for catching things like unclosedcomments. An example:
%x quote %% ...other rules for dealing with quotes... <quote><<EOF>> { error( "unterminated quote" ); yyterminate(); } <<EOF>> { if ( *++filelist ) yyin = fopen( *filelist, "r" ); else yyterminate(); }
Miscellaneous macros
The macro YY_USER_ACTION
can be defined to provide anaction which is always executed prior to the matchedrule's action. For example, it could be #define'd to calla routine to convert yytext to lower-case. WhenYY_USER_ACTION
is invoked, the variable yy_act
gives thenumber of the matched rule (rules are numbered startingwith 1). Suppose you want to profile how often each ofyour rules is matched. The following would do the trick:
#define YY_USER_ACTION ++ctr[yy_act]
where ctr
is an array to hold the counts for the differentrules. Note that the macro YY_NUM_RULES
gives the total numberof rules (including the default rule, even if you use `-s', soa correct declaration for ctr
is:
int ctr[YY_NUM_RULES];
The macro YY_USER_INIT
may be defined to provide an actionwhich is always executed before the first scan (and beforethe scanner's internal initializations are done). Forexample, it could be used to call a routine to read in adata table or open a logging file.
The macro `yy_set_interactive(is_interactive)' can be usedto control whether the current buffer is consideredinteractive. An interactive buffer is processed more slowly,but must be used when the scanner's input source is indeedinteractive to avoid problems due to waiting to fillbuffers (see the discussion of the `-I' flag below). Anon-zero value in the macro invocation marks the buffer asinteractive, a zero value as non-interactive. Note thatuse of this macro overrides `%option always-interactive' or`%option never-interactive' (see Options below).`yy_set_interactive()' must be invoked prior to beginning toscan the buffer that is (or is not) to be consideredinteractive.
The macro `yy_set_bol(at_bol)' can be used to controlwhether the current buffer's scanning context for the nexttoken match is done as though at the beginning of a line.A non-zero macro argument makes rules anchored with
The macro `YY_AT_BOL()' returns true if the next tokenscanned from the current buffer will have '^' rulesactive, false otherwise.
In the generated scanner, the actions are all gathered inone 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 followingrule's. Redefining YY_BREAK
allows, for example, C++users to #define YY_BREAK to do nothing (while being verycareful that every rule ends with a "break" or a"return"!) to avoid suffering from unreachable statementwarnings where because a rule's action ends with "return",the YY_BREAK
is inaccessible.
Values available to the user
This section summarizes the various values available tothe user in the rule actions.
- `char *yytext' holds the text of the current token.It may be modified but not lengthened (you cannotappend characters to the end).If the special directive `%array' appears in thefirst section of the scanner description, then
yytext
is instead declared `char yytext[YYLMAX]',whereYYLMAX
is a macro definition that you canredefine in the first section if you don't like thedefault value (generally 8KB). Using `%array'results in somewhat slower scanners, but the valueofyytext
becomes immune to calls to `input()' and`unput()', which potentially destroy its value whenyytext
is a character pointer. The opposite of`%array' is `%pointer', which is the default.You cannot use `%array' when generating C++ scannerclasses (the `-+' flag). - `int yyleng' holds the length of the current token.
- `FILE *yyin' is the file which by default
flex
readsfrom. It may be redefined but doing so only makessense before scanning begins or after an EOF hasbeen encountered. Changing it in the midst ofscanning will have unexpected results sinceflex
buffers its input; use `yyrestart()' instead. Oncescanning terminates because an end-of-file has beenseen, you can assignyyin
at the new input file andthen call the scanner again to continue scanning. - `void yyrestart( FILE *new_file )' may be called topoint
yyin
at the new input file. The switch-overto the new file is immediate (any previouslybuffered-up input is lost). Note that calling`yyrestart()' withyyin
as an argument thus throwsaway the current input buffer and continuesscanning the same input file. - `FILE *yyout' is the file to which `ECHO' actions aredone. It can be reassigned by the user.
YY_CURRENT_BUFFER
returns aYY_BUFFER_STATE
handleto the current buffer.YY_START
returns an integer value corresponding tothe current start condition. You can subsequentlyuse this value withBEGIN
to return to that startcondition.
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 routinenamed `yylex()' to find the next input token. The routineis supposed to return the type of the next token as wellas putting any associated value in the global yylval
. Touse flex
with yacc
, one specifies the `-d' option to yacc
toinstruct it to generate the file `y.tab.h' containingdefinitions of all the `%tokens' appearing in the yacc
input.This file is then included in the flex
scanner. Forexample, if one of the tokens is "TOK_NUMBER", part of thescanner might look like:
%{ #include "y.tab.h" %} %% [0-9]+ yylval = atoi( yytext ); return TOK_NUMBER;
Options
flex
has the following options:
-
`-b'
- Generate backing-up information to `lex.backup'.This is a list of scanner states which requirebacking up and the input characters on which theydo so. By adding rules one can remove backing-upstates. If all backing-up states are eliminatedand `-Cf' or `-CF' is used, the generated scanner willrun faster (see the `-p' flag). Only users who wishto squeeze every last cycle out of their scannersneed worry about this option. (See the section onPerformance Considerations below.) `-c'
- is a do-nothing, deprecated option included forPOSIX compliance. `-d'
-
makes the generated scanner run in
debug mode.Whenever a pattern is recognized and the global
yy_flex_debug
is non-zero (which is the default),the scanner will write tostderr
a line of theform:--accepting rule at line 53 ("the matched text")
The line number refers to the location of the rulein the file defining the scanner (i.e., the filethat was fed to flex). Messages are also generatedwhen the scanner backs up, accepts the defaultrule, reaches the end of its input buffer (orencounters a NUL; at this point, the two look thesame as far as the scanner's concerned), or reachesan end-of-file.
`-f'
- specifies fast scanner. No table compression isdone and stdio is bypassed. The result is largebut fast. This option is equivalent to `-Cfr' (seebelow). `-h'
-
generates a "help" summary of
flex's
options tostdout
and then exits. `-?' and `--help' are synonymsfor `-h'.
`-i'
-
instructs
flex
to generate a case-insensitivescanner. The case of letters given in theflex
inputpatterns will be ignored, and tokens in the inputwill be matched regardless of case. The matchedtext given inyytext
will have the preserved case(i.e., it will not be folded).
`-l'
-
turns on maximum compatibility with the originalAT&T
lex
implementation. Note that this does notmean full compatibility. Use of this option costsa considerable amount of performance, and it cannotbe used with the `-+, -f, -F, -Cf', or `-CF' options.For details on the compatibilities it provides, seethe section "Incompatibilities With Lex And POSIX"below. This option also results in the nameYY_FLEX_LEX_COMPAT
being #define'd in the generatedscanner.
`-n'
- is another do-nothing, deprecated option includedonly for POSIX compliance. `-p'
-
generates a performance report to stderr. Thereport consists of comments regarding features ofthe
flex
input file which will cause a serious lossof performance in the resulting scanner. If yougive the flag twice, you will also get commentsregarding features that lead to minor performancelosses.Note that the use ofREJECT
, `%option yylineno' andvariable trailing context (see the Deficiencies / Bugs section below)entails a substantial performance penalty; use of `yymore()',the `^' operator, and the `-I' flag entail minor performancepenalties.
`-s'
-
causes the
default rule (that unmatched scannerinput is echoed to
stdout
) to be suppressed. Ifthe scanner encounters input that does not matchany of its rules, it aborts with an error. Thisoption is useful for finding holes in a scanner'srule set.
`-t'
-
instructs
flex
to write the scanner it generates tostandard output instead of `lex.yy.c'.
`-v'
-
specifies that
flex
should write tostderr
asummary of statistics regarding the scanner itgenerates. Most of the statistics are meaningless tothe casualflex
user, but the first line identifiesthe version offlex
(same as reported by `-V'), andthe next line the flags used when generating thescanner, including those that are on by default.
`-w'
- suppresses warning messages. `-B'
-
instructs
flex
to generate a batch scanner, theopposite of interactive scanners generated by `-I'(see below). In general, you use `-B' when you are certain that your scanner will never be usedinteractively, and you want to squeeze a little moreperformance out of it. If your goal is instead tosqueeze out a lot more performance, you should beusing the `-Cf' or `-CF' options (discussed below),which turn on `-B' automatically anyway.
`-F'
-
specifies that the
fast scanner tablerepresentation should be used (and stdio bypassed). Thisrepresentation is about as fast as the full tablerepresentation
`(-f)', and for some sets of patternswill be considerably smaller (and for others,larger). In general, if the pattern set containsboth "keywords" and a catch-all, "identifier" rule,such as in the set:
"case" return TOK_CASE; "switch" return TOK_SWITCH; ... "default" return TOK_DEFAULT; [a-z]+ return TOK_ID;
then you're better off using the full tablerepresentation. If only the "identifier" rule ispresent and you then use a hash table or some such todetect the keywords, you're better off using `-F'.This option is equivalent to `-CFr' (see below). Itcannot be used with `-+'.
`-I'
-
instructs
flex
to generate an interactive scanner.An interactive scanner is one that only looks aheadto decide what token has been matched if itabsolutely must. It turns out that always looking oneextra character ahead, even if the scanner hasalready seen enough text to disambiguate thecurrent token, is a bit faster than only looking aheadwhen necessary. But scanners that always lookahead give dreadful interactive performance; forexample, when a user types a newline, it is notrecognized as a newline token until they enter another token, which often means typing in anotherwhole line.Flex
scanners default to interactive unless you usethe `-Cf' or `-CF' table-compression options (seebelow). That's because if you're looking forhigh-performance you should be using one of theseoptions, so if you didn't,flex
assumes you'drather trade off a bit of run-time performance forintuitive interactive behavior. Note also that you cannot use `-I' in conjunction with `-Cf' or `-CF'.Thus, this option is not really needed; it is on bydefault for all those cases in which it is allowed.You can force a scanner to not be interactive byusing `-B' (see above).
`-L'
-
instructs
flex
not to generate `#line' directives.Without this option,flex
peppers the generatedscanner with #line directives so error messages inthe actions will be correctly located with respectto either the originalflex
input file (if theerrors are due to code in the input file), or `lex.yy.c' (if the errors areflex's
fault -- youshould report these sorts of errors to the emailaddress given below).
`-T'
-
makes
flex
run intrace
mode. It will generate alot of messages tostderr
concerning the form ofthe input and the resultant non-deterministic anddeterministic finite automata. This option ismostly for use in maintainingflex
.
`-V'
-
prints the version number to
stdout
and exits. `--version' is a synonym for `-V'.
`-7'
-
instructs
flex
to generate a 7-bit scanner, i.e.,one which can only recognized 7-bit characters inits input. The advantage of using `-7' is that thescanner's tables can be up to half the size ofthose generated using the `-8' option (see below).The disadvantage is that such scanners often hangor crash if their input contains an 8-bitcharacter.Note, however, that unless you generate yourscanner using the `-Cf' or `-CF' table compression options,use of `-7' will save only a small amount of tablespace, and make your scanner considerably lessportable.Flex's
default behavior is to generatean 8-bit scanner unless you use the `-Cf' or `-CF', inwhich caseflex
defaults to generating 7-bitscanners unless your site was always configured togenerate 8-bit scanners (as will often be the casewith non-USA sites). You can tell whether flexgenerated a 7-bit or an 8-bit scanner by inspectingthe flag summary in the `-v' output as describedabove.Note that if you use `-Cfe' or `-CFe' (those tablecompression options, but also using equivalenceclasses as discussed see below), flex stilldefaults to generating an 8-bit scanner, sinceusually with these compression options full 8-bittables are not much more expensive than 7-bittables.
`-8'
-
instructs
flex
to generate an 8-bit scanner, i.e.,one which can recognize 8-bit characters. Thisflag is only needed for scanners generated using `-Cf' or `-CF', as otherwise flex defaults togenerating an 8-bit scanner anyway.See the discussion of `-7' above for flex's defaultbehavior and the tradeoffs between 7-bit and 8-bitscanners.
`-+'
- specifies that you want flex to generate a C++scanner class. See the section on Generating C++Scanners below for details. `-C[aefFmr]'
-
controls the degree of table compression and, moregenerally, trade-offs between small scanners andfast scanners.
`-Ca' ("align") instructs flex to trade off largertables in the generated scanner for fasterperformance because the elements of the tables are betteraligned for memory access and computation. On someRISC architectures, fetching and manipulatinglong-words is more efficient than with smaller-sizedunits such as shortwords. This option can doublethe size of the tables used by your scanner.
`-Ce' directs
flex
to construct equivalence classes,i.e., sets of characters which have identicallexical properties (for example, if the only appearanceof digits in theflex
input is in the characterclass "[0-9]" then the digits '0', '1', ..., '9'will all be put in the same equivalence class).Equivalence classes usually give dramaticreductions in the final table/object file sizes(typically a factor of 2-5) and are pretty cheapperformance-wise (one array look-up per characterscanned). `-Cf' specifies that the full scanner tables shouldbe generated -flex
should not compress the tablesby taking advantages of similar transitionfunctions for different states. `-CF' specifies that the alternate fast scannerrepresentation (described above under the `-F' flag)should be used. This option cannot be used with `-+'. `-Cm' directsflex
to construct meta-equivalenceclasses, which are sets of equivalence classes (orcharacters, if equivalence classes are not beingused) that are commonly used together.Meta-equivalence classes are often a big win when usingcompressed tables, but they have a moderateperformance impact (one or two "if" tests and one arraylook-up per character scanned). `-Cr' causes the generated scanner to bypass use ofthe standard I/O library (stdio) for input.Instead of calling `fread()' or `getc()', the scannerwill use the `read()' system call, resulting in aperformance gain which varies from system tosystem, but in general is probably negligible unlessyou are also using `-Cf' or `-CF'. Using `-Cr' can causestrange behavior if, for example, you read fromyyin
using stdio prior to calling the scanner(because the scanner will miss whatever text yourprevious reads left in the stdio input buffer). `-Cr' has no effect if you defineYY_INPUT
(see TheGenerated Scanner above).A lone `-C' specifies that the scanner tables shouldbe compressed but neither equivalence classes normeta-equivalence classes should be used.The options `-Cf' or `-CF' and `-Cm' do not make sensetogether - there is no opportunity formeta-equivalence classes if the table is not beingcompressed. Otherwise the options may be freelymixed, and are cumulative.The default setting is `-Cem', which specifies thatflex
should generate equivalence classes andmeta-equivalence classes. This setting provides thehighest degree of table compression. You can tradeoff faster-executing scanners at the cost of largertables with the following generally being true:slowest & smallest -Cem -Cm -Ce -C -C{f,F}e -C{f,F} -C{f,F}a fastest & largest
Note that scanners with the smallest tables areusually generated and compiled the quickest, soduring development you will usually want to use thedefault, maximal compression. `-Cfe' is often a good compromise between speed andsize for production scanners.
`-ooutput'
-
directs flex to write the scanner to the file
`out-'
put
instead of `lex.yy.c'. If you combine `-o' withthe `-t' option, then the scanner is written tostdout
but its `#line' directives (see the `-L' optionabove) refer to the fileoutput
.
`-Pprefix'
-
changes the default
`yy' prefix used by
flex
for allglobally-visible variable and function names toinstead be prefix. For example, `-Pfoo' changes thename ofyytext
to `footext'. It also changes thename of the default output file from `lex.yy.c' to `lex.foo.c'. Here are all of the names affected:yy_create_buffer yy_delete_buffer yy_flex_debug yy_init_buffer yy_flush_buffer yy_load_buffer_state yy_switch_to_buffer yyin yyleng yylex yylineno yyout yyrestart yytext yywrap
(If you are using a C++ scanner, then onlyyywrap
andyyFlexLexer
are affected.) Within your scanneritself, you can still refer to the global variablesand functions using either version of their name;but externally, they have the modified name.This option lets you easily link together multipleflex
programs into the same executable. Note,though, that using this option also renames `yywrap()', so you now must either provide your own(appropriately-named) version of the routine foryour scanner, or use `%option noyywrap', as linkingwith `-lfl' no longer provides one for you bydefault.
`-Sskeleton_file'
-
overrides the default skeleton file from which
flex
constructs its scanners. You'll never need thisoption unless you are doingflex
maintenance ordevelopment.
flex
also provides a mechanism for controlling optionswithin the scanner specification itself, rather than fromthe flex command-line. This is done by including `%option'directives in the first section of the scannerspecification. You can specify multiple options with a single`%option' directive, and multiple directives in the firstsection of your flex input file. Most options are givensimply as names, optionally preceded by the word "no"(with no intervening whitespace) to negate their meaning.A number are equivalent to flex flags or their negation:
7bit -7 option 8bit -8 option align -Ca option backup -b option batch -B option c++ -+ option caseful or case-sensitive opposite of -i (default) case-insensitive or caseless -i option debug -d option default opposite of -s option ecs -Ce option fast -F option full -f option interactive -I option lex-compat -l option meta-ecs -Cm option perf-report -p option read -Cr option stdout -t option verbose -v option warn opposite of -w option (use "%option nowarn" for -w) array equivalent to "%array" pointer equivalent to "%pointer" (default)
Some `%option's' provide features otherwise not available:
-
`always-interactive'
- instructs flex to generate a scanner which alwaysconsiders its input "interactive". Normally, oneach new input file the scanner calls `isatty()' inan attempt to determine whether the scanner's inputsource is interactive and thus should be read acharacter at a time. When this option is used,however, then no such call is made. `main'
-
directs flex to provide a default
`main()' programfor the scanner, which simply calls
`yylex()'. Thisoption implies
noyywrap
(see below).
`never-interactive'
- instructs flex to generate a scanner which neverconsiders its input "interactive" (again, no callmade to `isatty())'. This is the opposite of `always-' interactive. `stack'
- enables the use of start condition stacks (seeStart Conditions above). `stdinit'
-
if unset (i.e.,
`%option nostdinit') initializes
yyin
andyyout
to nilFILE
pointers, instead ofstdin
andstdout
.
`yylineno'
-
directs
flex
to generate a scanner that maintains the numberof the current line read from its input in the global variableyylineno
. This option is implied by `%option lex-compat'.
`yywrap'
-
if unset (i.e.,
`%option noyywrap'), makes thescanner not call
`yywrap()' upon an end-of-file, butsimply assume that there are no more files to scan(until the user points
yyin
at a new file and calls `yylex()' again).
flex
scans your rule actions to determine whether you usethe REJECT
or `yymore()' features. The reject
and yymore
options are available to override its decision as towhether you use the options, either by setting them (e.g.,`%option reject') to indicate the feature is indeed used, orunsetting them to indicate it actually is not used (e.g.,`%option noyymore').
Three options take string-delimited values, offset with '=':
%option outfile="ABC"
is equivalent to `-oABC', and
%option prefix="XYZ"
is equivalent to `-PXYZ'.
Finally,
%option yyclass="foo"
only applies when generating a C++ scanner (`-+' option). Itinforms flex
that you have derived `foo' as a subclass ofyyFlexLexer
so flex
will place your actions in the memberfunction `foo::yylex()' instead of `yyFlexLexer::yylex()'.It also generates a `yyFlexLexer::yylex()' member function thatemits a run-time error (by invoking `yyFlexLexer::LexerError()')if called. See Generating C++ Scanners, below, for additionalinformation.
A number of options are available for lint purists whowant to suppress the appearance of unneeded routines inthe generated scanner. Each of the following, if unset,results in the corresponding routine not appearing in thegenerated scanner:
input, unput yy_push_state, yy_pop_state, yy_top_state yy_scan_buffer, yy_scan_bytes, yy_scan_string
(though `yy_push_state()' and friends won't appear anywayunless you use `%option stack').
Performance considerations
The main design goal of flex
is that it generatehigh-performance scanners. It has been optimized for dealingwell with large sets of rules. Aside from the effects onscanner speed of the table compression `-C' options outlinedabove, there are a number of options/actions which degradeperformance. These are, from most expensive to least:
REJECT %option yylineno arbitrary trailing context pattern sets that require backing up %array %option interactive %option always-interactive '^' beginning-of-line operator yymore()
with the first three all being quite expensive and thelast two being quite cheap. Note also that `unput()' isimplemented as a routine call that potentially does quitea bit of work, while `yyless()' is a quite-cheap macro; soif just putting back some excess text you scanned, use`yyless()'.
REJECT
should be avoided at all costs when performance isimportant. It is a particularly expensive option.
Getting rid of backing up is messy and often may be anenormous amount of work for a complicated scanner. Inprincipal, one begins by using the `-b' flag to generate a`lex.backup' file. For example, on the input
%% foo return TOK_KEYWORD; foobar return TOK_KEYWORD;
the file looks like:
State #6 is non-accepting - associated rule line numbers: 2 3 out-transitions: [ o ] jam-transitions: EOF [ \001-n p-\177 ] 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 back up.
The first few lines tell us that there's a scanner statein which it can make a transition on an 'o' but not on anyother character, and that in that state the currentlyscanned text does not match any rule. The state occurswhen trying to match the rules found at lines 2 and 3 inthe input file. If the scanner is in that state and thenreads something other than an 'o', it will have to back upto find a rule which is matched. With a bit ofhead-scratching one can see that this must be the state it's inwhen it has seen "fo". When this has happened, ifanything other than another 'o' is seen, the scanner willhave to back up to simply match the 'f' (by the defaultrule).
The comment regarding State #8 indicates there's a problemwhen "foob" has been scanned. Indeed, on any characterother than an 'a', the scanner will have to back up toaccept "foo". Similarly, the comment for State #9concerns when "fooba" has been scanned and an 'r' does notfollow.
The final comment reminds us that there's no point goingto all the trouble of removing backing up from the rulesunless we're using `-Cf' or `-CF', since there's noperformance gain doing so with compressed scanners.
The way to remove the backing up is to add "error" rules:
%% foo return TOK_KEYWORD; foobar return TOK_KEYWORD; fooba | foob | fo { /* false alarm, not really a keyword */ return TOK_ID; }
Eliminating backing up among a list of keywords can alsobe done using a "catch-all" rule:
%% foo return TOK_KEYWORD; foobar return TOK_KEYWORD; [a-z]+ return TOK_ID;
This is usually the best solution when appropriate.
Backing up messages tend to cascade. With a complicatedset of rules it's not uncommon to get hundreds ofmessages. If one can decipher them, though, it often onlytakes a dozen or so rules to eliminate the backing up(though it's easy to make a mistake and have an error ruleaccidentally match a valid token. A possible future flex
feature will be to automatically add rules to eliminatebacking up).
It's important to keep in mind that you gain the benefitsof eliminating backing up only if you eliminate everyinstance of backing up. Leaving just one means you gainnothing.
Variable trailing context (where both the leading andtrailing parts do not have a fixed length) entails almostthe same performance loss as REJECT
(i.e., substantial).So when possible a rule like:
%% mouse|rat/(cat|dog) run();
is better written:
%% mouse/cat|dog run(); rat/cat|dog run();
or as
%% mouse|rat/cat run(); mouse|rat/dog run();
Note that here the special '|' action does not provide anysavings, and can even make things worse (see Deficiencies/ Bugs below).
Another area where the user can increase a scanner'sperformance (and one that's easier to implement) arises fromthe fact that the longer the tokens matched, the fasterthe scanner will run. This is because with long tokensthe processing of most input characters takes place in the(short) inner scanning loop, and does not often have to gothrough the additional work of setting up the scanningenvironment (e.g., yytext
) for the action. Recall thescanner for C comments:
%x comment %% int line_num = 1; "/*" BEGIN(comment); <comment>[^*\n]* <comment>"*"+[^*/\n]* <comment>\n ++line_num; <comment>"*"+"/" BEGIN(INITIAL);
This could be sped up by writing it as:
%x comment %% int line_num = 1; "/*" BEGIN(comment); <comment>[^*\n]* <comment>[^*\n]*\n ++line_num; <comment>"*"+[^*/\n]* <comment>"*"+[^*/\n]*\n ++line_num; <comment>"*"+"/" BEGIN(INITIAL);
Now instead of each newline requiring the processing ofanother action, recognizing the newlines is "distributed"over the other rules to keep the matched text as long aspossible. Note that adding rules does not slow down thescanner! The speed of the scanner is independent of thenumber of rules or (modulo the considerations given at thebeginning of this section) how complicated the rules arewith regard to operators such as '*' and '|'.
A final example in speeding up a scanner: suppose you wantto scan through a file containing identifiers andkeywords, one per line and with no other extraneouscharacters, and recognize all the keywords. A natural firstapproach is:
%% asm | auto | break | ... etc ... volatile | while /* it's a keyword */ .|\n /* it's not a keyword */
To eliminate the back-tracking, introduce a catch-allrule:
%% asm | auto | break | ... etc ... volatile | while /* it's a keyword */ [a-z]+ | .|\n /* it's not a keyword */
Now, if it's guaranteed that there's exactly one word perline, then we can reduce the total number of matches by ahalf by merging in the recognition of newlines with thatof the other tokens:
%% asm\n | auto\n | break\n | ... etc ... volatile\n | while\n /* it's a keyword */ [a-z]+\n | .|\n /* it's not a keyword */
One has to be careful here, as we have now reintroducedbacking up into the scanner. In particular, while we knowthat there will never be any characters in the inputstream other than letters or newlines, flex
can't figurethis out, and it will plan for possibly needing to back upwhen it has scanned a token like "auto" and then the nextcharacter is something other than a newline or a letter.Previously it would then just match the "auto" rule and bedone, but now it has no "auto" rule, only a "auto\n" rule.To eliminate the possibility of backing up, we couldeither duplicate all rules but without final newlines, or,since we never expect to encounter such an input andtherefore don't how it's classified, we can introduce onemore catch-all rule, this one which doesn't include anewline:
%% asm\n | auto\n | break\n | ... etc ... volatile\n | while\n /* it's a keyword */ [a-z]+\n | [a-z]+ | .|\n /* it's not a keyword */
Compiled with `-Cf', this is about as fast as one can get aflex
scanner to go for this particular problem.
A final note: flex
is slow when matching NUL's,particularly when a token contains multiple NUL's. It's best towrite rules which match short amounts of text if it'santicipated that the text will often include NUL's.
Another final note regarding performance: as mentionedabove in the section How the Input is Matched, dynamicallyresizing yytext
to accommodate huge tokens is a slowprocess because it presently requires that the (huge) tokenbe rescanned from the beginning. Thus if performance isvital, you should attempt to match "large" quantities oftext but not "huge" quantities, where the cutoff betweenthe two is at about 8K characters/token.
Generating C++ scanners
flex
provides two different ways to generate scanners foruse with C++. The first way is to simply compile ascanner generated by flex
using a C++ compiler instead of a Ccompiler. You should not encounter any compilationserrors (please report any you find to the email addressgiven in the Author section below). You can then use C++code in your rule actions instead of C code. Note thatthe default input source for your scanner remains yyin
,and default echoing is still done to yyout
. Both of theseremain `FILE *' variables and not C++ streams
.
You can also use flex
to generate a C++ scanner class, usingthe `-+' option, (or, equivalently, `%option c++'), whichis automatically specified if the name of the flex executable endsin a `+', such as flex++
. When using this option, flexdefaults to generating the scanner to the file `lex.yy.cc' insteadof `lex.yy.c'. The generated scanner includes the header file`FlexLexer.h', which defines the interface to two C++ classes.
The first class, FlexLexer
, provides an abstract baseclass defining the general scanner class interface. Itprovides the following member functions:
-
`const char* YYText()'
-
returns the text of the most recently matchedtoken, the equivalent of
yytext
.
`int YYLeng()'
-
returns the length of the most recently matchedtoken, the equivalent of
yyleng
.
`int lineno() const'
- returns the current input line number (see `%option yylineno'),or 1 if `%option yylineno' was not used. `void set_debug( int flag )'
-
sets the debugging flag for the scanner, equivalent to assigning to
yy_flex_debug
(see the Options section above). Note that youmust build the scanner using `%option debug' to include debugginginformation in it.
`int debug() const'
- returns the current setting of the debugging flag.
Also provided are member functions equivalent to`yy_switch_to_buffer(), yy_create_buffer()' (though thefirst argument is an `istream*' object pointer and not a`FILE*', `yy_flush_buffer()', `yy_delete_buffer()',and `yyrestart()' (again, the first argument is a `istream*'object pointer).
The second class defined in `FlexLexer.h' is yyFlexLexer
,which is derived from FlexLexer
. It defines the followingadditional member functions:
-
`yyFlexLexer( istream* arg_yyin = 0, ostream* arg_yyout = 0 )'
-
constructs a
yyFlexLexer
object using the givenstreams for input and output. If not specified,the streams default tocin
andcout
, respectively.
`virtual int yylex()'
-
performs the same role is
`yylex()' does for ordinaryflex scanners: it scans the input stream, consumingtokens, until a rule's action returns a value. If you derive a subclass
Sfrom
yyFlexLexer
and want to access the member functions and variables of Sinside `yylex()',then you need to use `%option yyclass="S"'to informflex
that you will be using that subclass instead ofyyFlexLexer
.In this case, rather than generating `yyFlexLexer::yylex()',flex
generates `S::yylex()'(and also generates a dummy `yyFlexLexer::yylex()'that calls `yyFlexLexer::LexerError()'if called).
`virtual void switch_streams(istream* new_in = 0, ostream* new_out = 0)'
-
reassigns
yyin
tonew_in
(if non-nil)andyyout
tonew_out
(ditto), deleting the previous input buffer ifyyin
is reassigned.
`int yylex( istream* new_in = 0, ostream* new_out = 0 )'
- first switches the input streams via `switch_streams( new_in, new_out )'and then returns the value of `yylex()'.
In addition, yyFlexLexer
defines the following protectedvirtual functions which you can redefine in derivedclasses to tailor the scanner:
-
`virtual int LexerInput( char* buf, int max_size )'
-
reads up to
`max_size' characters into
buf andreturns the number of characters read. To indicateend-of-input, return 0 characters. Note that"interactive" scanners (see the
`-B' and
`-I' flags)define the macro
YY_INTERACTIVE
. If you redefineLexerInput()
and need to take different actionsdepending on whether or not the scanner might bescanning an interactive input source, you can testfor the presence of this name via `#ifdef'.
`virtual void LexerOutput( const char* buf, int size )'
- writes out size characters from the buffer buf,which, while NUL-terminated, may also contain"internal" NUL's if the scanner's rules can matchtext with NUL's in them. `virtual void LexerError( const char* msg )'
-
reports a fatal error message. The default versionof this function writes the message to the stream
cerr
and exits.
Note that a yyFlexLexer
object contains its entirescanning state. Thus you can use such objects to createreentrant scanners. You can instantiate multiple instances ofthe same yyFlexLexer
class, and you can also combinemultiple C++ scanner classes together in the same programusing the `-P' option discussed above.Finally, note that the `%array' feature is not available toC++ scanner classes; you must use `%pointer' (the default).
Here is an example of a simple C++ scanner:
// An example of using the flex C++ scanner class. %{ int mylineno = 0; %} string \"[^\n"]+\" ws [ \t]+ alpha [A-Za-z] dig [0-9] name ({alpha}|{dig}|\$)({alpha}|{dig}|[_.\-/$])* num1 [-+]?{dig}+\.?([eE][-+]?{dig}+)? num2 [-+]?{dig}*\.{dig}+([eE][-+]?{dig}+)? number {num1}|{num2} %% {ws} /* skip blanks and tabs */ "/*" { int c; while((c = yyinput()) != 0) { if(c == '\n') ++mylineno; else if(c == '*') { if((c = yyinput()) == '/') break; else unput(c); } } } {number} cout << "number " << YYText() << '\n'; \n mylineno++; {name} cout << "name " << YYText() << '\n'; {string} cout << "string " << YYText() << '\n'; %% Version 2.5 December 1994 44 int main( int /* argc */, char** /* argv */ ) { FlexLexer* lexer = new yyFlexLexer; while(lexer->yylex() != 0) ; return 0; }
If you want to create multiple (different) lexer classes,you use the `-P' flag (or the `prefix=' option) to rename eachyyFlexLexer
to some other xxFlexLexer
. You then caninclude `<FlexLexer.h>' in your other sources once per lexerclass, first renaming yyFlexLexer
as follows:
#undef yyFlexLexer #define yyFlexLexer xxFlexLexer #include <FlexLexer.h> #undef yyFlexLexer #define yyFlexLexer zzFlexLexer #include <FlexLexer.h>
if, for example, you used `%option prefix="xx"' for one ofyour scanners and `%option prefix="zz"' for the other.
IMPORTANT: the present form of the scanning class isexperimental and may change considerably between majorreleases.
Incompatibilities with lex
and POSIX
flex
is a rewrite of the AT&T Unix lex
tool (the twoimplementations do not share any code, though), with someextensions and incompatibilities, both of which are ofconcern to those who wish to write scanners acceptable toeither implementation. Flex is fully compliant with thePOSIX lex
specification, except that when using `%pointer'(the default), a call to `unput()' destroys the contents ofyytext
, which is counter to the POSIX specification.
In this section we discuss all of the known areas ofincompatibility between flex, AT&T lex, and the POSIXspecification.
flex's
`-l' option turns on maximum compatibility with theoriginal AT&T lex
implementation, at the cost of a majorloss in the generated scanner's performance. We notebelow which incompatibilities can be overcome using the `-l'option.
flex
is fully compatible with lex
with the followingexceptions:
- The undocumented
lex
scanner internal variableyylineno
is not supported unless `-l' or `%option yylineno' is used.yylineno
should be maintained on a per-buffer basis, ratherthan a per-scanner (single global variable) basis.yylineno
isnot part of the POSIX specification. - The `input()' routine is not redefinable, though itmay be called to read characters following whateverhas been matched by a rule. If `input()' encountersan end-of-file the normal `yywrap()' processing isdone. A "real" end-of-file is returned by`input()' as
EOF
.Input is instead controlled by defining theYY_INPUT
macro.Theflex
restriction that `input()' cannot beredefined is in accordance with the POSIXspecification, which simply does not specify any way ofcontrolling the scanner's input other than by makingan initial assignment toyyin
. - The `unput()' routine is not redefinable. Thisrestriction is in accordance with POSIX.
flex
scanners are not as reentrant aslex
scanners.In particular, if you have an interactive scannerand an interrupt handler which long-jumps out ofthe scanner, and the scanner is subsequently calledagain, you may get the following message:fatal flex scanner internal error--end of buffer missed
To reenter the scanner, first useyyrestart( yyin );
Note that this call will throw away any bufferedinput; usually this isn't a problem with aninteractive scanner.Also note that flex C++ scanner classes arereentrant, so if using C++ is an option for you, youshould use them instead. See "Generating C++Scanners" above for details.- `output()' is not supported. Output from the `ECHO'macro is done to the file-pointer
yyout
(defaultstdout
).`output()' is not part of the POSIX specification. lex
does not support exclusive start conditions(%x), though they are in the POSIX specification.- When definitions are expanded,
flex
encloses themin parentheses. With lex, the following:NAME [A-Z][A-Z0-9]* %% foo{NAME}? printf( "Found it\n" ); %%
will not match the string "foo" because when themacro is expanded the rule is equivalent to"foo[A-Z][A-Z0-9]*?" and the precedence is such that the'?' is associated with "[A-Z0-9]*". Withflex
, therule will be expanded to "foo([A-Z][A-Z0-9]*)?" andso the string "foo" will match.Note that if the definition begins with `^' or endswith `$' then it is not expanded with parentheses, toallow these operators to appear in definitionswithout losing their special meanings. But the`<s>, /', and `<<EOF>>' operators cannot be used in aflex
definition.Using `-l' results in thelex
behavior of noparentheses around the definition.The POSIX specification is that the definition be enclosed inparentheses. - Some implementations of
lex
allow a rule's action to begin ona separate line, if the rule's pattern has trailing whitespace:%% foo|bar<space here> { foobar_action(); }
flex
does not support this feature. - The
lex
`%r' (generate a Ratfor scanner) option isnot supported. It is not part of the POSIXspecification. - After a call to `unput()',
yytext
is undefined untilthe next token is matched, unless the scanner wasbuilt using `%array'. This is not the case withlex
or the POSIX specification. The `-l' option doesaway with this incompatibility. - The precedence of the `{}' (numeric range) operatoris different.
lex
interprets "abc{1,3}" as "matchone, two, or three occurrences of 'abc'", whereasflex
interprets it as "match 'ab' followed by one,two, or three occurrences of 'c'". The latter isin agreement with the POSIX specification. - The precedence of the `^' operator is different.
lex
interprets "^foo|bar" as "match either 'foo' at thebeginning of a line, or 'bar' anywhere", whereasflex
interprets it as "match either 'foo' or 'bar'if they come at the beginning of a line". Thelatter is in agreement with the POSIX specification. - The special table-size declarations such as `%a'supported by
lex
are not required byflex
scanners;flex
ignores them. - The name FLEX_SCANNER is #define'd so scanners maybe written for use with either
flex
orlex
.Scanners also includeYY_FLEX_MAJOR_VERSION
andYY_FLEX_MINOR_VERSION
indicating which version offlex
generated the scanner (for example, for the2.5 release, these defines would be 2 and 5respectively).
The following flex
features are not included in lex
or thePOSIX specification:
C++ scanners %option start condition scopes start condition stacks interactive/non-interactive scanners yy_scan_string() and friends yyterminate() yy_set_interactive() yy_set_bol() YY_AT_BOL() <<EOF>> <*> YY_DECL YY_START YY_USER_ACTION YY_USER_INIT #line directives %{}'s around actions multiple actions on a line
plus almost all of the flex flags. The last feature inthe list refers to the fact that with flex
you can putmultiple actions on the same line, separated withsemicolons, while with lex
, the following
foo handle_foo(); ++num_foos_seen;
is (rather surprisingly) truncated to
foo handle_foo();
flex
does not truncate the action. Actions that are notenclosed in braces are simply terminated at the end of theline.
Diagnostics
-
`warning, rule cannot be matched'
-
indicates that the givenrule cannot be matched because it follows other rules thatwill always match the same text as it. For example, inthe following "foo" cannot be matched because it comesafter an identifier "catch-all" rule:
[a-z]+ got_identifier(); foo got_foo();
UsingREJECT
in a scanner suppresses this warning.
`warning, -s option given but default rule can be matched'
- means that it is possible (perhaps only in a particularstart condition) that the default rule (match any singlecharacter) is the only one that will match a particularinput. Since `-s' was given, presumably this is notintended. `reject_used_but_not_detected undefined'
-
`yymore_used_but_not_detected undefined'
-
These errors canoccur at compile time. They indicate that the scanneruses
REJECT
or `yymore()' but thatflex
failed to notice thefact, meaning thatflex
scanned the first two sectionslooking for occurrences of these actions and failed tofind any, but somehow you snuck some in (via a #includefile, for example). Use `%option reject' or `%option yymore'to indicate to flex that you really do use these features.
`flex scanner jammed'
- a scanner compiled with `-s' hasencountered an input string which wasn't matched by any ofits rules. This error can also occur due to internalproblems. `token too large, exceeds YYLMAX'
-
your scanner uses
`%array'and one of its rules matched a string longer than the
`YYL-'
MAX
constant (8K bytes by default). You can increase thevalue by #define'ingYYLMAX
in the definitions section ofyourflex
input.
`scanner requires -8 flag to use the character 'x''
- Yourscanner specification includes recognizing the 8-bitcharacter x and you did not specify the -8 flag, and yourscanner defaulted to 7-bit because you used the `-Cf' or `-CF'table compression options. See the discussion of the `-7'flag for details. `flex scanner push-back overflow'
-
you used
`unput()' to pushback so much text that the scanner's buffer could not holdboth the pushed-back text and the current token in
yytext
.Ideally the scanner should dynamically resize the bufferin this case, but at present it does not.
`input buffer overflow, can't enlarge buffer because scanner uses REJECT'
-
the scanner was working on matching anextremely large token and needed to expand the inputbuffer. This doesn't work with scanners that use
REJECT
.
`fatal flex scanner internal error--end of buffer missed'
-
This can occur in an scanner which is reentered after along-jump has jumped out (or over) the scanner'sactivation frame. Before reentering the scanner, use:
yyrestart( yyin );
or, as noted above, switch to using the C++ scanner class.
`too many start conditions in <> construct!'
- you listedmore start conditions in a <> construct than exist (so youmust have listed at least one of them twice).
Files
-
`-lfl'
- library with which scanners must be linked. `lex.yy.c'
- generated scanner (called `lexyy.c' on some systems). `lex.yy.cc'
- generated C++ scanner class, when using `-+'. `<FlexLexer.h>'
-
header file defining the C++ scanner base class,
FlexLexer
, and its derived class,yyFlexLexer
.
`flex.skl'
- skeleton scanner. This file is only used whenbuilding flex, not when flex executes. `lex.backup'
- backing-up information for `-b' flag (called `lex.bck'on some systems).
Deficiencies / Bugs
Some trailing context patterns cannot be properly matchedand generate warning messages ("dangerous trailingcontext"). These are patterns where the ending of the firstpart of the rule matches the beginning of the second part,such as "zx*/xy*", where the 'x*' matches the 'x' at thebeginning of the trailing context. (Note that the POSIXdraft states that the text matched by such patterns isundefined.)
For some trailing context rules, parts which are actuallyfixed-length are not recognized as such, leading to theabovementioned performance loss. In particular, partsusing '|' or {n} (such as "foo{3}") are always consideredvariable-length.
Combining trailing context with the special '|' action canresult in fixed trailing context being turned into themore expensive variable trailing context. For example, inthe following:
%% abc | xyz/def
Use of `unput()' invalidates yytext and yyleng, unless the`%array' directive or the `-l' option has been used.
Pattern-matching of NUL's is substantially slower thanmatching other characters.
Dynamic resizing of the input buffer is slow, as itentails rescanning all the text matched so far by thecurrent (generally huge) token.
Due to both buffering of input and read-ahead, you cannotintermix calls to <stdio.h> routines, such as, forexample, `getchar()', with flex
rules and expect it to work.Call `input()' instead.
The total table entries listed by the `-v' flag excludes thenumber of table entries needed to determine what rule hasbeen matched. The number of entries is equal to thenumber of DFA states if the scanner does not use REJECT
, andsomewhat greater than the number of states if it does.
REJECT
cannot be used with the `-f' or `-F' options.
The flex
internal algorithms need documentation.
See also
lex
(1), yacc
(1), sed
(1), awk
(1).
John Levine, Tony Mason, and Doug Brown: Lex & Yacc;O'Reilly and Associates. Be sure to get the 2nd edition.
M. E. Lesk and E. Schmidt, LEX - Lexical Analyzer Generator.
Alfred Aho, Ravi Sethi and Jeffrey Ullman: Compilers:Principles, Techniques and Tools; Addison-Wesley (1986).Describes the pattern-matching techniques used by flex
(deterministic finite automata).
Author
Vern Paxson, with the help of many ideas and much inspiration fromVan Jacobson. Original version by Jef Poskanzer. The fast tablerepresentation is a partial implementation of a design done by VanJacobson. The implementation was done by Kevin Gong and Vern Paxson.
Thanks to the many flex
beta-testers, feedbackers, andcontributors, especially Francois Pinard, Casey Leedom, StanAdermann, Terry Allen, David Barker-Plummer, John Basrai, NelsonH.F. Beebe, `benson@odi.com', Karl Berry, Peter A. Bigot,Simon Blanchard, Keith Bostic, Frederic Brehm, Ian Brockbank, KinCho, Nick Christopher, Brian Clapper, J.T. Conklin, Jason Coughlin,Bill Cox, Nick Cropper, Dave Curtis, Scott David Daniels, ChrisG. Demetriou, Theo Deraadt, Mike Donahue, Chuck Doucette, Tom Epperly,Leo Eskin, Chris Faylor, Chris Flatters, Jon Forrest, Joe Gayda, KavehR. Ghazi, Eric Goldman, Christopher M. Gould, Ulrich Grepel, PeerGriebel, Jan Hajic, Charles Hemphill, NORO Hideo, Jarkko Hietaniemi,Scott Hofmann, Jeff Honig, Dana Hudes, Eric Hughes, John Interrante,Ceriel Jacobs, Michal Jaegermann, Sakari Jalovaara, Jeffrey R. Jones,Henry Juengst, Klaus Kaempf, Jonathan I. Kamens, Terrence O Kane,Amir Katz, `ken@ken.hilco.com', Kevin B. Kenny, Steve Kirsch,Winfried Koenig, Marq Kole, Ronald Lamprecht, Greg Lee, Rohan Lenard,Craig Leres, John Levine, Steve Liddle, Mike Long, Mohamed el Lozy,Brian Madsen, Malte, Joe Marshall, Bengt Martensson, Chris Metcalf,Luke Mewburn, Jim Meyering, R. Alexander Milowski, Erik Naggum,G.T. Nicol, Landon Noll, James Nordby, Marc Nozell, Richard Ohnemus,Karsten Pahnke, Sven Panne, Roland Pesch, Walter Pelissero, GaumondPierre, Esmond Pitt, Jef Poskanzer, Joe Rahmeh, Jarmo Raiha, FredericRaimbault, Pat Rankin, Rick Richardson, Kevin Rodgers, Kai Uwe Rommel,Jim Roskind, Alberto Santini, Andreas Scherer, Darrell Schiebel, RafSchietekat, Doug Schmidt, Philippe Schnoebelen, Andreas Schwab, AlexSiegel, Eckehard Stolz, Jan-Erik Strvmquist, Mike Stump, Paul Stuart,Dave Tallman, Ian Lance Taylor, Chris Thewalt, Richard M. Timoney,Jodi Tsai, Paul Tuinenga, Gary Weik, Frank Whaley, Gerhard Wilhelms,Kent Williams, Ken Yap, Ron Zellar, Nathan Zelle, David Zuhn, andthose whose names have slipped my marginal mail-archiving skills butwhose contributions are appreciated all the same.
Thanks to Keith Bostic, Jon Forrest, Noah Friedman, John Gilmore,Craig Leres, John Levine, Bob Mulcahy, G.T. Nicol, Francois Pinard,Rich Salz, and Richard Stallman for help with various distributionheadaches.
Thanks to Esmond Pitt and Earle Horton for 8-bit character support;to Benson Margulies and Fred Burke for C++ support; to Kent Williamsand Tom Epperly for C++ class support; to Ove Ewerlid for support ofNUL's; and to Eric Hughes for support of multiple buffers.
This work was primarily done when I was with the Real Time SystemsGroup at the Lawrence Berkeley Laboratory in Berkeley, CA. Many thanksto all there for the support I received.
Send comments to `vern@ee.lbl.gov'.