1 \input texinfo.tex @c -*-texinfo-*-
5 @settitle Lexical Analysis With Flex
7 @set authors Vern Paxson, Will Estes and John Millaway
12 @dircategory Programming
14 * flex: (flex). Fast lexical analyzer generator (lex replacement).
20 The flex manual is placed under the same licensing conditions as the
23 Copyright @copyright{} 2001, 2002, 2003, 2004, 2005, 2006, 2007 The Flex
26 Copyright @copyright{} 1990, 1997 The Regents of the University of California.
29 This code is derived from software contributed to Berkeley by
32 The United States Government has rights in this work pursuant
33 to contract no. DE-AC03-76SF00098 between the United States
34 Department of Energy and the University of California.
36 Redistribution and use in source and binary forms, with or without
37 modification, are permitted provided that the following conditions
42 Redistributions of source code must retain the above copyright
43 notice, this list of conditions and the following disclaimer.
46 Redistributions in binary form must reproduce the above copyright
47 notice, this list of conditions and the following disclaimer in the
48 documentation and/or other materials provided with the distribution.
51 Neither the name of the University nor the names of its contributors
52 may be used to endorse or promote products derived from this software
53 without specific prior written permission.
55 THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
56 IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
57 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
63 @subtitle Edition @value{EDITION}, @value{UPDATED}
64 @author @value{authors}
66 @vskip 0pt plus 1filll
71 @node Top, Copyright, (dir), (dir)
74 This manual describes @code{flex}, a tool for generating programs that
75 perform pattern-matching on text. The manual includes both tutorial and
78 This edition of @cite{The flex Manual} documents @code{flex} version
79 @value{VERSION}. It was last updated on @value{UPDATED}.
81 This manual was written by @value{authors}.
94 * Multiple Input Buffers::
104 * Memory Management::
105 * Serialized Tables::
114 --- The Detailed Node Listing ---
116 Format of the Input File
118 * Definitions Section::
120 * User Code Section::
121 * Comments in the Input::
125 * Options for Specifying Filenames::
126 * Options Affecting Scanner Behavior::
127 * Code-Level And API Options::
128 * Options for Scanner Speed and Size::
129 * Debugging Options::
130 * Miscellaneous Options::
135 * Reentrant Overview::
136 * Reentrant Example::
138 * Reentrant Functions::
140 The Reentrant API in Detail
142 * Specify Reentrant::
143 * Extra Reentrant Argument::
144 * Global Replacement::
145 * Init and Destroy Functions::
152 * The Default Memory Management::
153 * Overriding The Default Memory Management::
154 * A Note About yytext And Memory::
158 * Creating Serialized Tables::
159 * Loading and Unloading Serialized Tables::
160 * Tables File Format::
164 * When was flex born?::
165 * How do I expand backslash-escape sequences in C-style quoted strings?::
166 * Why do flex scanners call fileno if it is not ANSI compatible?::
167 * Does flex support recursive pattern definitions?::
168 * How do I skip huge chunks of input (tens of megabytes) while using flex?::
169 * Flex is not matching my patterns in the same order that I defined them.::
170 * My actions are executing out of order or sometimes not at all.::
171 * How can I have multiple input sources feed into the same scanner at the same time?::
172 * Can I build nested parsers that work with the same input file?::
173 * How can I match text only at the end of a file?::
174 * How can I make REJECT cascade across start condition boundaries?::
175 * Why cant I use fast or full tables with interactive mode?::
176 * How much faster is -F or -f than -C?::
177 * If I have a simple grammar cant I just parse it with flex?::
178 * Why doesn't yyrestart() set the start state back to INITIAL?::
179 * How can I match C-style comments?::
180 * The period isn't working the way I expected.::
181 * Can I get the flex manual in another format?::
182 * Does there exist a "faster" NDFA->DFA algorithm?::
183 * How does flex compile the DFA so quickly?::
184 * How can I use more than 8192 rules?::
185 * How do I abandon a file in the middle of a scan and switch to a new file?::
186 * How do I execute code only during initialization (only before the first scan)?::
187 * How do I execute code at termination?::
188 * Where else can I find help?::
189 * Can I include comments in the "rules" section of the file?::
190 * I get an error about undefined yywrap().::
191 * How can I change the matching pattern at run time?::
192 * How can I expand macros in the input?::
193 * How can I build a two-pass scanner?::
194 * How do I match any string not matched in the preceding rules?::
195 * I am trying to port code from AT&T lex that uses yysptr and yysbuf.::
196 * Is there a way to make flex treat NULL like a regular character?::
197 * Whenever flex can not match the input it says "flex scanner jammed".::
198 * Why doesn't flex have non-greedy operators like perl does?::
199 * Memory leak - 16386 bytes allocated by malloc.::
200 * How do I track the byte offset for lseek()?::
201 * How do I use my own I/O classes in a C++ scanner?::
202 * How do I skip as many chars as possible?::
204 * Are certain equivalent patterns faster than others?::
205 * Is backing up a big deal?::
206 * Can I fake multi-byte character support?::
208 * Can you discuss some flex internals?::
209 * unput() messes up yy_at_bol::
210 * The | operator is not doing what I want::
211 * Why can't flex understand this variable trailing context pattern?::
212 * The ^ operator isn't working::
213 * Trailing context is getting confused with trailing optional patterns::
214 * Is flex GNU or not?::
216 * I need to scan if-then-else blocks and while loops::
220 * Is there a repository for flex scanners?::
221 * How can I conditionally compile or preprocess my flex input file?::
222 * Where can I find grammars for lex and yacc?::
223 * I get an end-of-buffer message for each character scanned.::
263 * What is the difference between YYLEX_PARAM and YY_DECL?::
264 * Why do I get "conflicting types for yylex" error?::
265 * How do I access the values set in a Flex action from within a Bison action?::
269 * Makefiles and Flex::
277 * Index of Functions and Macros::
278 * Index of Variables::
279 * Index of Data Types::
281 * Index of Scanner Options::
286 @node Copyright, Reporting Bugs, Top, Top
289 @cindex copyright of flex
290 @cindex distributing flex
293 @node Reporting Bugs, Introduction, Copyright, Top
294 @chapter Reporting Bugs
296 @cindex bugs, reporting
297 @cindex reporting bugs
299 If you find a bug in @code{flex}, please report it using
300 the SourceForge Bug Tracking facilities which can be found on
301 @url{http://sourceforge.net/projects/flex,flex's SourceForge Page}.
303 @node Introduction, Simple Examples, Reporting Bugs, Top
304 @chapter Introduction
306 @cindex scanner, definition of
307 @code{flex} is a tool for generating @dfn{scanners}. A scanner is a
308 program which recognizes lexical patterns in text. The @code{flex}
309 program reads the given input files, or its standard input if no file
310 names are given, for a description of a scanner to generate. The
311 description is in the form of pairs of regular expressions and C code,
312 called @dfn{rules}. @code{flex} generates as output a C source file,
313 @file{lex.yy.c} by default, which defines a routine @code{yylex()}.
314 This file can be compiled and linked with the flex runtime library to
315 produce an executable. When the executable is run, it analyzes its
316 input for occurrences of the regular expressions. Whenever it finds
317 one, it executes the corresponding C code.
319 @node Simple Examples, Format, Introduction, Top
320 @chapter Some Simple Examples
322 First some simple examples to get the flavor of how one uses
325 @cindex username expansion
326 The following @code{flex} input specifies a scanner which, when it
327 encounters the string @samp{username} will replace it with the user's
333 username printf( "%s", getlogin() );
338 @cindex rules, default
339 By default, any text not matched by a @code{flex} scanner is copied to
340 the output, so the net effect of this scanner is to copy its input file
341 to its output with each occurrence of @samp{username} expanded. In this
342 input, there is just one rule. @samp{username} is the @dfn{pattern} and
343 the @samp{printf} is the @dfn{action}. The @samp{%%} symbol marks the
344 beginning of the rules.
346 Here's another simple example:
348 @cindex counting characters and lines
351 int num_lines = 0, num_chars = 0;
354 \n ++num_lines; ++num_chars;
361 printf( "# of lines = %d, # of chars = %d\n",
362 num_lines, num_chars );
367 This scanner counts the number of characters and the number of lines in
368 its input. It produces no output other than the final report on the
369 character and line counts. The first line declares two globals,
370 @code{num_lines} and @code{num_chars}, which are accessible both inside
371 @code{yylex()} and in the @code{main()} routine declared after the
372 second @samp{%%}. There are two rules, one which matches a newline
373 (@samp{\n}) and increments both the line count and the character count,
374 and one which matches any character other than a newline (indicated by
375 the @samp{.} regular expression).
377 A somewhat more complicated example:
379 @cindex Pascal-like language
382 /* scanner for a toy Pascal-like language */
385 /* need this for the call to atof() below */
395 printf( "An integer: %s (%d)\n", yytext,
399 {DIGIT}+"."{DIGIT}* {
400 printf( "A float: %s (%g)\n", yytext,
404 if|then|begin|end|procedure|function {
405 printf( "A keyword: %s\n", yytext );
408 {ID} printf( "An identifier: %s\n", yytext );
410 "+"|"-"|"*"|"/" printf( "An operator: %s\n", yytext );
412 "{"[\^{}}\n]*"}" /* eat up one-line comments */
414 [ \t\n]+ /* eat up whitespace */
416 . printf( "Unrecognized character: %s\n", yytext );
424 ++argv, --argc; /* skip over program name */
426 yyin = fopen( argv[0], "r" );
435 This is the beginnings of a simple scanner for a language like Pascal.
436 It identifies different types of @dfn{tokens} and reports on what it has
439 The details of this example will be explained in the following
442 @node Format, Patterns, Simple Examples, Top
443 @chapter Format of the Input File
446 @cindex format of flex input
447 @cindex input, format of
449 @cindex sections of flex input
451 The @code{flex} input file consists of three sections, separated by a
452 line containing only @samp{%%}.
454 @cindex format of input file
466 * Definitions Section::
468 * User Code Section::
469 * Comments in the Input::
472 @node Definitions Section, Rules Section, Format, Format
473 @section Format of the Definitions Section
475 @cindex input file, Definitions section
476 @cindex Definitions, in flex input
477 The @dfn{definitions section} contains declarations of simple @dfn{name}
478 definitions to simplify the scanner specification, and declarations of
479 @dfn{start conditions}, which are explained in a later section.
481 @cindex aliases, how to define
482 @cindex pattern aliases, how to define
483 Name definitions have the form:
491 The @samp{name} is a word beginning with a letter or an underscore
492 (@samp{_}) followed by zero or more letters, digits, @samp{_}, or
493 @samp{-} (dash). The definition is taken to begin at the first
494 non-whitespace character following the name and continuing to the end of
495 the line. The definition can subsequently be referred to using
496 @samp{@{name@}}, which will expand to @samp{(definition)}. For example,
498 @cindex pattern aliases, defining
499 @cindex defining pattern aliases
507 Defines @samp{DIGIT} to be a regular expression which matches a single
508 digit, and @samp{ID} to be a regular expression which matches a letter
509 followed by zero-or-more letters-or-digits. A subsequent reference to
511 @cindex pattern aliases, use of
526 and matches one-or-more digits followed by a @samp{.} followed by
529 @cindex comments in flex input
530 An unindented comment (i.e., a line
531 beginning with @samp{/*}) is copied verbatim to the output up
532 to the next @samp{*/}.
534 @cindex %@{ and %@}, in Definitions Section
535 @cindex embedding C code in flex input
536 @cindex C code in flex input
537 Any @emph{indented} text or text enclosed in @samp{%@{} and @samp{%@}}
538 is also copied verbatim to the output (with the %@{ and %@} symbols
539 removed). The %@{ and %@} symbols must appear unindented on lines by
544 A @code{%top} block is similar to a @samp{%@{} ... @samp{%@}} block, except
545 that the code in a @code{%top} block is relocated to the @emph{top} of the
546 generated file, before any flex definitions @footnote{Actually,
547 @code{yyIN_HEADER} is defined before the @samp{%top} block.}.
548 The @code{%top} block is useful when you want certain preprocessor macros to be
549 defined or certain files to be included before the generated code.
550 The single characters, @samp{@{} and @samp{@}} are used to delimit the
551 @code{%top} block, as show in the example below:
556 /* This code goes at the "top" of the generated file. */
558 #include <inttypes.h>
563 Multiple @code{%top} blocks are allowed, and their order is preserved.
565 @node Rules Section, User Code Section, Definitions Section, Format
566 @section Format of the Rules Section
568 @cindex input file, Rules Section
569 @cindex rules, in flex input
570 The @dfn{rules} section of the @code{flex} input contains a series of
579 where the pattern must be unindented and the action must begin
581 @xref{Patterns}, for a further description of patterns and actions.
583 In the rules section, any indented or %@{ %@} enclosed text appearing
584 before the first rule may be used to declare variables which are local
585 to the scanning routine and (after the declarations) code which is to be
586 executed whenever the scanning routine is entered. Other indented or
587 %@{ %@} text in the rule section is still copied to the output, but its
588 meaning is not well-defined and it may well cause compile-time errors
589 (this feature is present for @acronym{POSIX} compliance. @xref{Lex and
590 Posix}, for other such features).
592 Any @emph{indented} text or text enclosed in @samp{%@{} and @samp{%@}}
593 is copied verbatim to the output (with the %@{ and %@} symbols removed).
594 The %@{ and %@} symbols must appear unindented on lines by themselves.
596 @node User Code Section, Comments in the Input, Rules Section, Format
597 @section Format of the User Code Section
599 @cindex input file, user code Section
600 @cindex user code, in flex input
601 The user code section is simply copied to @file{lex.yy.c} verbatim. It
602 is used for companion routines which call or are called by the scanner.
603 The presence of this section is optional; if it is missing, the second
604 @samp{%%} in the input file may be skipped, too.
606 @node Comments in the Input, , User Code Section, Format
607 @section Comments in the Input
609 @cindex comments, syntax of
610 Flex supports C-style comments, that is, anything between @samp{/*} and
612 considered a comment. Whenever flex encounters a comment, it copies the
613 entire comment verbatim to the generated source code. Comments may
614 appear just about anywhere, but with the following exceptions:
617 @cindex comments, in rules section
619 Comments may not appear in the Rules Section wherever flex is expecting
620 a regular expression. This means comments may not appear at the
621 beginning of a line, or immediately following a list of scanner states.
623 Comments may not appear on an @samp{%option} line in the Definitions
627 If you want to follow a simple rule, then always begin a comment on a
628 new line, with one or more whitespace characters before the initial
629 @samp{/*}). This rule will work anywhere in the input file.
631 All the comments in the following example are valid:
633 @cindex comments, valid uses of
634 @cindex comments in the input
641 /* Definitions Section */
646 ruleA /* after regex */ { /* code block */ } /* after code block */
647 /* Rules Section (indented) */
656 /* User Code Section */
661 @node Patterns, Matching, Format, Top
664 @cindex patterns, in rules section
665 @cindex regular expressions, in patterns
666 The patterns in the input (see @ref{Rules Section}) are written using an
667 extended set of regular expressions. These are:
669 @cindex patterns, syntax
670 @cindex patterns, syntax
673 match the character 'x'
676 any character (byte) except newline
678 @cindex [] in patterns
679 @cindex character classes in patterns, syntax of
680 @cindex POSIX, character classes in patterns, syntax of
682 a @dfn{character class}; in this case, the pattern
683 matches either an 'x', a 'y', or a 'z'
685 @cindex ranges in patterns
687 a "character class" with a range in it; matches
688 an 'a', a 'b', any letter from 'j' through 'o',
691 @cindex ranges in patterns, negating
692 @cindex negating ranges in patterns
694 a "negated character class", i.e., any character
695 but those in the class. In this case, any
696 character EXCEPT an uppercase letter.
699 any character EXCEPT an uppercase letter or
702 @item [a-z]@{-@}[aeiou]
703 the lowercase consonants
706 zero or more r's, where r is any regular expression
712 zero or one r's (that is, ``an optional r'')
714 @cindex braces in patterns
716 anywhere from two to five r's
724 @cindex pattern aliases, expansion of
726 the expansion of the @samp{name} definition
729 @cindex literal text in patterns, syntax of
730 @cindex verbatim text in patterns, syntax of
732 the literal string: @samp{[xyz]"foo}
734 @cindex escape sequences in patterns, syntax of
736 if X is @samp{a}, @samp{b}, @samp{f}, @samp{n}, @samp{r}, @samp{t}, or
737 @samp{v}, then the ANSI-C interpretation of @samp{\x}. Otherwise, a
738 literal @samp{X} (used to escape operators such as @samp{*})
740 @cindex NULL character in patterns, syntax of
742 a NUL character (ASCII code 0)
744 @cindex octal characters in patterns
746 the character with octal value 123
749 the character with hexadecimal value 2a
752 match an @samp{r}; parentheses are used to override precedence (see below)
755 apply option @samp{r} and omit option @samp{s} while interpreting pattern.
756 Options may be zero or more of the characters @samp{i}, @samp{s}, or @samp{x}.
758 @samp{i} means case-insensitive. @samp{-i} means case-sensitive.
760 @samp{s} alters the meaning of the @samp{.} syntax to match any single byte whatsoever.
761 @samp{-s} alters the meaning of @samp{.} to match any byte except @samp{\n}.
763 @samp{x} ignores comments and whitespace in patterns. Whitespace is ignored unless
764 it is backslash-escaped, contained within @samp{""}s, or appears inside a
767 The following are all valid:
770 (?:foo) same as (foo)
771 (?i:ab7) same as ([aA][bB]7)
772 (?-i:ab) same as (ab)
773 (?s:.) same as [\x00-\xFF]
774 (?-s:.) same as [^\n]
775 (?ix-s: a . b) same as ([Aa][^\n][bB])
776 (?x:a b) same as ("ab")
777 (?x:a\ b) same as ("a b")
778 (?x:a" "b) same as ("a b")
779 (?x:a[ ]b) same as ("a b")
787 omit everything within @samp{()}. The first @samp{)}
788 character encountered ends the pattern. It is not possible to for the comment
789 to contain a @samp{)} character. The comment may span lines.
791 @cindex concatenation, in patterns
793 the regular expression @samp{r} followed by the regular expression @samp{s}; called
797 either an @samp{r} or an @samp{s}
799 @cindex trailing context, in patterns
801 an @samp{r} but only if it is followed by an @samp{s}. The text matched by @samp{s} is
802 included when determining whether this rule is the longest match, but is
803 then returned to the input before the action is executed. So the action
804 only sees the text matched by @samp{r}. This type of pattern is called
805 @dfn{trailing context}. (There are some combinations of @samp{r/s} that flex
806 cannot match correctly. @xref{Limitations}, regarding dangerous trailing
809 @cindex beginning of line, in patterns
810 @cindex BOL, in patterns
812 an @samp{r}, but only at the beginning of a line (i.e.,
813 when just starting to scan, or right after a
814 newline has been scanned).
816 @cindex end of line, in patterns
817 @cindex EOL, in patterns
819 an @samp{r}, but only at the end of a line (i.e., just before a
820 newline). Equivalent to @samp{r/\n}.
822 @cindex newline, matching in patterns
823 Note that @code{flex}'s notion of ``newline'' is exactly
824 whatever the C compiler used to compile @code{flex}
825 interprets @samp{\n} as; in particular, on some DOS
826 systems you must either filter out @samp{\r}s in the
827 input yourself, or explicitly use @samp{r/\r\n} for @samp{r$}.
829 @cindex start conditions, in patterns
831 an @samp{r}, but only in start condition @code{s} (see @ref{Start
832 Conditions} for discussion of start conditions).
835 same, but in any of start conditions @code{s1}, @code{s2}, or @code{s3}.
838 an @samp{r} in any start condition, even an exclusive one.
840 @cindex end of file, in patterns
841 @cindex EOF in patterns, syntax of
846 an end-of-file when in start condition @code{s1} or @code{s2}
849 Note that inside of a character class, all regular expression operators
850 lose their special meaning except escape (@samp{\}) and the character class
851 operators, @samp{-}, @samp{]]}, and, at the beginning of the class, @samp{^}.
853 @cindex patterns, precedence of operators
854 The regular expressions listed above are grouped according to
855 precedence, from highest precedence at the top to lowest at the bottom.
856 Those grouped together have equal precedence (see special note on the
857 precedence of the repeat operator, @samp{@{@}}, under the documentation
858 for the @samp{--posix} POSIX compliance option). For example,
860 @cindex patterns, grouping and precedence
875 since the @samp{*} operator has higher precedence than concatenation,
876 and concatenation higher than alternation (@samp{|}). This pattern
877 therefore matches @emph{either} the string @samp{foo} @emph{or} the
878 string @samp{ba} followed by zero-or-more @samp{r}'s. To match
879 @samp{foo} or zero-or-more repetitions of the string @samp{bar}, use:
887 And to match a sequence of zero or more repetitions of @samp{foo} and
890 @cindex patterns, repetitions with grouping
897 @cindex character classes in patterns
898 In addition to characters and ranges of characters, character classes
899 can also contain @dfn{character class expressions}. These are
900 expressions enclosed inside @samp{[}: and @samp{:]} delimiters (which
901 themselves must appear between the @samp{[} and @samp{]} of the
902 character class. Other elements may occur inside the character class,
903 too). The valid expressions are:
905 @cindex patterns, valid character classes
908 [:alnum:] [:alpha:] [:blank:]
909 [:cntrl:] [:digit:] [:graph:]
910 [:lower:] [:print:] [:punct:]
911 [:space:] [:upper:] [:xdigit:]
915 These expressions all designate a set of characters equivalent to the
916 corresponding standard C @code{isXXX} function. For example,
917 @samp{[:alnum:]} designates those characters for which @code{isalnum()}
918 returns true - i.e., any alphabetic or numeric character. Some systems
919 don't provide @code{isblank()}, so flex defines @samp{[:blank:]} as a
922 For example, the following character classes are all equivalent:
924 @cindex character classes, equivalence of
925 @cindex patterns, character class equivalence
935 A word of caution. Character classes are expanded immediately when seen in the @code{flex} input.
936 This means the character classes are sensitive to the locale in which @code{flex}
937 is executed, and the resulting scanner will not be sensitive to the runtime locale.
938 This may or may not be desirable.
942 @cindex case-insensitive, effect on character classes
943 @item If your scanner is case-insensitive (the @samp{-i} flag), then
944 @samp{[:upper:]} and @samp{[:lower:]} are equivalent to
947 @anchor{case and character ranges}
948 @item Character classes with ranges, such as @samp{[a-Z]}, should be used with
949 caution in a case-insensitive scanner if the range spans upper or lowercase
950 characters. Flex does not know if you want to fold all upper and lowercase
951 characters together, or if you want the literal numeric range specified (with
952 no case folding). When in doubt, flex will assume that you meant the literal
953 numeric range, and will issue a warning. The exception to this rule is a
954 character range such as @samp{[a-z]} or @samp{[S-W]} where it is obvious that you
955 want case-folding to occur. Here are some examples with the @samp{-i} flag
958 @multitable {@samp{[a-zA-Z]}} {ambiguous} {@samp{[A-Z\[\\\]_`a-t]}} {@samp{[@@A-Z\[\\\]_`abc]}}
959 @item Range @tab Result @tab Literal Range @tab Alternate Range
960 @item @samp{[a-t]} @tab ok @tab @samp{[a-tA-T]} @tab
961 @item @samp{[A-T]} @tab ok @tab @samp{[a-tA-T]} @tab
962 @item @samp{[A-t]} @tab ambiguous @tab @samp{[A-Z\[\\\]_`a-t]} @tab @samp{[a-tA-T]}
963 @item @samp{[_-@{]} @tab ambiguous @tab @samp{[_`a-z@{]} @tab @samp{[_`a-zA-Z@{]}
964 @item @samp{[@@-C]} @tab ambiguous @tab @samp{[@@ABC]} @tab @samp{[@@A-Z\[\\\]_`abc]}
967 @cindex end of line, in negated character classes
968 @cindex EOL, in negated character classes
970 A negated character class such as the example @samp{[^A-Z]} above
971 @emph{will} match a newline unless @samp{\n} (or an equivalent escape
972 sequence) is one of the characters explicitly present in the negated
973 character class (e.g., @samp{[^A-Z\n]}). This is unlike how many other
974 regular expression tools treat negated character classes, but
975 unfortunately the inconsistency is historically entrenched. Matching
976 newlines means that a pattern like @samp{[^"]*} can match the entire
977 input unless there's another quote in the input.
979 Flex allows negation of character class expressions by prepending @samp{^} to
980 the POSIX character class name.
984 [:^alnum:] [:^alpha:] [:^blank:]
985 [:^cntrl:] [:^digit:] [:^graph:]
986 [:^lower:] [:^print:] [:^punct:]
987 [:^space:] [:^upper:] [:^xdigit:]
991 Flex will issue a warning if the expressions @samp{[:^upper:]} and
992 @samp{[:^lower:]} appear in a case-insensitive scanner, since their meaning is
993 unclear. The current behavior is to skip them entirely, but this may change
994 without notice in future revisions of flex.
998 The @samp{@{-@}} operator computes the difference of two character classes. For
999 example, @samp{[a-c]@{-@}[b-z]} represents all the characters in the class
1000 @samp{[a-c]} that are not in the class @samp{[b-z]} (which in this case, is
1001 just the single character @samp{a}). The @samp{@{-@}} operator is left
1002 associative, so @samp{[abc]@{-@}[b]@{-@}[c]} is the same as @samp{[a]}. Be careful
1003 not to accidentally create an empty set, which will never match.
1007 The @samp{@{+@}} operator computes the union of two character classes. For
1008 example, @samp{[a-z]@{+@}[0-9]} is the same as @samp{[a-z0-9]}. This operator
1009 is useful when preceded by the result of a difference operation, as in,
1010 @samp{[[:alpha:]]@{-@}[[:lower:]]@{+@}[q]}, which is equivalent to
1011 @samp{[A-Zq]} in the "C" locale.
1013 @cindex trailing context, limits of
1014 @cindex ^ as non-special character in patterns
1015 @cindex $ as normal character in patterns
1017 A rule can have at most one instance of trailing context (the @samp{/} operator
1018 or the @samp{$} operator). The start condition, @samp{^}, and @samp{<<EOF>>} patterns
1019 can only occur at the beginning of a pattern, and, as well as with @samp{/} and @samp{$},
1020 cannot be grouped inside parentheses. A @samp{^} which does not occur at
1021 the beginning of a rule or a @samp{$} which does not occur at the end of
1022 a rule loses its special properties and is treated as a normal character.
1025 The following are invalid:
1027 @cindex patterns, invalid trailing context
1035 Note that the first of these can be written @samp{foo/bar\n}.
1038 The following will result in @samp{$} or @samp{^} being treated as a normal character:
1040 @cindex patterns, special characters treated as non-special
1048 If the desired meaning is a @samp{foo} or a
1049 @samp{bar}-followed-by-a-newline, the following could be used (the
1050 special @code{|} action is explained below, @pxref{Actions}):
1052 @cindex patterns, end of line
1056 bar$ /* action goes here */
1060 A similar trick will work for matching a @samp{foo} or a
1061 @samp{bar}-at-the-beginning-of-a-line.
1064 @node Matching, Actions, Patterns, Top
1065 @chapter How the Input Is Matched
1067 @cindex patterns, matching
1068 @cindex input, matching
1069 @cindex trailing context, matching
1070 @cindex matching, and trailing context
1071 @cindex matching, length of
1072 @cindex matching, multiple matches
1073 When the generated scanner is run, it analyzes its input looking for
1074 strings which match any of its patterns. If it finds more than one
1075 match, it takes the one matching the most text (for trailing context
1076 rules, this includes the length of the trailing part, even though it
1077 will then be returned to the input). If it finds two or more matches of
1078 the same length, the rule listed first in the @code{flex} input file is
1084 Once the match is determined, the text corresponding to the match
1085 (called the @dfn{token}) is made available in the global character
1086 pointer @code{yytext}, and its length in the global integer
1087 @code{yyleng}. The @dfn{action} corresponding to the matched pattern is
1088 then executed (@pxref{Actions}), and then the remaining input is scanned
1091 @cindex default rule
1092 If no match is found, then the @dfn{default rule} is executed: the next
1093 character in the input is considered matched and copied to the standard
1094 output. Thus, the simplest valid @code{flex} input is:
1096 @cindex minimal scanner
1103 which generates a scanner that simply copies its input (one character at
1104 a time) to its output.
1106 @cindex yytext, two types of
1107 @cindex %array, use of
1108 @cindex %pointer, use of
1110 Note that @code{yytext} can be defined in two different ways: either as
1111 a character @emph{pointer} or as a character @emph{array}. You can
1112 control which definition @code{flex} uses by including one of the
1113 special directives @code{%pointer} or @code{%array} in the first
1114 (definitions) section of your flex input. The default is
1115 @code{%pointer}, unless you use the @samp{-l} lex compatibility option,
1116 in which case @code{yytext} will be an array. The advantage of using
1117 @code{%pointer} is substantially faster scanning and no buffer overflow
1118 when matching very large tokens (unless you run out of dynamic memory).
1119 The disadvantage is that you are restricted in how your actions can
1120 modify @code{yytext} (@pxref{Actions}), and calls to the @code{unput()}
1121 function destroys the present contents of @code{yytext}, which can be a
1122 considerable porting headache when moving between different @code{lex}
1125 @cindex %array, advantages of
1126 The advantage of @code{%array} is that you can then modify @code{yytext}
1127 to your heart's content, and calls to @code{unput()} do not destroy
1128 @code{yytext} (@pxref{Actions}). Furthermore, existing @code{lex}
1129 programs sometimes access @code{yytext} externally using declarations of
1134 extern char yytext[];
1138 This definition is erroneous when used with @code{%pointer}, but correct
1141 The @code{%array} declaration defines @code{yytext} to be an array of
1142 @code{YYLMAX} characters, which defaults to a fairly large value. You
1143 can change the size by simply #define'ing @code{YYLMAX} to a different
1144 value in the first section of your @code{flex} input. As mentioned
1145 above, with @code{%pointer} yytext grows dynamically to accommodate
1146 large tokens. While this means your @code{%pointer} scanner can
1147 accommodate very large tokens (such as matching entire blocks of
1148 comments), bear in mind that each time the scanner must resize
1149 @code{yytext} it also must rescan the entire token from the beginning,
1150 so matching such tokens can prove slow. @code{yytext} presently does
1151 @emph{not} dynamically grow if a call to @code{unput()} results in too
1152 much text being pushed back; instead, a run-time error results.
1154 @cindex %array, with C++
1155 Also note that you cannot use @code{%array} with C++ scanner classes
1158 @node Actions, Generated Scanner, Matching, Top
1162 Each pattern in a rule has a corresponding @dfn{action}, which can be
1163 any arbitrary C statement. The pattern ends at the first non-escaped
1164 whitespace character; the remainder of the line is its action. If the
1165 action is empty, then when the pattern is matched the input token is
1166 simply discarded. For example, here is the specification for a program
1167 which deletes all occurrences of @samp{zap me} from its input:
1169 @cindex deleting lines from input
1177 This example will copy all other characters in the input to the output
1178 since they will be matched by the default rule.
1180 Here is a program which compresses multiple blanks and tabs down to a
1181 single blank, and throws away whitespace found at the end of a line:
1183 @cindex whitespace, compressing
1184 @cindex compressing whitespace
1188 [ \t]+ putchar( ' ' );
1189 [ \t]+$ /* ignore this token */
1193 @cindex %@{ and %@}, in Rules Section
1194 @cindex actions, use of @{ and @}
1195 @cindex actions, embedded C strings
1196 @cindex C-strings, in actions
1197 @cindex comments, in actions
1198 If the action contains a @samp{@{}, then the action spans till the
1199 balancing @samp{@}} is found, and the action may cross multiple lines.
1200 @code{flex} knows about C strings and comments and won't be fooled by
1201 braces found within them, but also allows actions to begin with
1202 @samp{%@{} and will consider the action to be all the text up to the
1203 next @samp{%@}} (regardless of ordinary braces inside the action).
1205 @cindex |, in actions
1206 An action consisting solely of a vertical bar (@samp{|}) means ``same as the
1207 action for the next rule''. See below for an illustration.
1209 Actions can include arbitrary C code, including @code{return} statements
1210 to return a value to whatever routine called @code{yylex()}. Each time
1211 @code{yylex()} is called it continues processing tokens from where it
1212 last left off until it either reaches the end of the file or executes a
1215 @cindex yytext, modification of
1216 Actions are free to modify @code{yytext} except for lengthening it
1217 (adding characters to its end--these will overwrite later characters in
1218 the input stream). This however does not apply when using @code{%array}
1219 (@pxref{Matching}). In that case, @code{yytext} may be freely modified
1222 @cindex yyleng, modification of
1223 @cindex yymore, and yyleng
1224 Actions are free to modify @code{yyleng} except they should not do so if
1225 the action also includes use of @code{yymore()} (see below).
1227 @cindex preprocessor macros, for use in actions
1228 There are a number of special directives which can be included within an
1234 copies yytext to the scanner's output.
1238 followed by the name of a start condition places the scanner in the
1239 corresponding start condition (see below).
1243 directs the scanner to proceed on to the ``second best'' rule which
1244 matched the input (or a prefix of the input). The rule is chosen as
1245 described above in @ref{Matching}, and @code{yytext} and @code{yyleng}
1246 set up appropriately. It may either be one which matched as much text
1247 as the originally chosen rule but came later in the @code{flex} input
1248 file, or one which matched less text. For example, the following will
1249 both count the words in the input and call the routine @code{special()}
1250 whenever @samp{frob} is seen:
1257 frob special(); REJECT;
1258 [^ \t\n]+ ++word_count;
1262 Without the @code{REJECT}, any occurrences of @samp{frob} in the input
1263 would not be counted as words, since the scanner normally executes only
1264 one action per token. Multiple uses of @code{REJECT} are allowed, each
1265 one finding the next best choice to the currently active rule. For
1266 example, when the following scanner scans the token @samp{abcd}, it will
1267 write @samp{abcdabcaba} to the output:
1269 @cindex REJECT, calling multiple times
1278 .|\n /* eat up any unmatched character */
1282 The first three rules share the fourth's action since they use the
1283 special @samp{|} action.
1285 @code{REJECT} is a particularly expensive feature in terms of scanner
1286 performance; if it is used in @emph{any} of the scanner's actions it
1287 will slow down @emph{all} of the scanner's matching. Furthermore,
1288 @code{REJECT} cannot be used with the @samp{-Cf} or @samp{-CF} options
1289 (@pxref{Scanner Options}).
1291 Note also that unlike the other special actions, @code{REJECT} is a
1292 @emph{branch}. Code immediately following it in the action will
1293 @emph{not} be executed.
1297 tells the scanner that the next time it matches a rule, the
1298 corresponding token should be @emph{appended} onto the current value of
1299 @code{yytext} rather than replacing it. For example, given the input
1300 @samp{mega-kludge} the following will write @samp{mega-mega-kludge} to
1303 @cindex yymore(), mega-kludge
1304 @cindex yymore() to append token to previous token
1308 mega- ECHO; yymore();
1313 First @samp{mega-} is matched and echoed to the output. Then @samp{kludge}
1314 is matched, but the previous @samp{mega-} is still hanging around at the
1319 for the @samp{kludge} rule will actually write @samp{mega-kludge}.
1322 @cindex yymore, performance penalty of
1323 Two notes regarding use of @code{yymore()}. First, @code{yymore()}
1324 depends on the value of @code{yyleng} correctly reflecting the size of
1325 the current token, so you must not modify @code{yyleng} if you are using
1326 @code{yymore()}. Second, the presence of @code{yymore()} in the
1327 scanner's action entails a minor performance penalty in the scanner's
1331 @code{yyless(n)} returns all but the first @code{n} characters of the
1332 current token back to the input stream, where they will be rescanned
1333 when the scanner looks for the next match. @code{yytext} and
1334 @code{yyleng} are adjusted appropriately (e.g., @code{yyleng} will now
1335 be equal to @code{n}). For example, on the input @samp{foobar} the
1336 following will write out @samp{foobarbar}:
1338 @cindex yyless(), pushing back characters
1339 @cindex pushing back characters with yyless
1343 foobar ECHO; yyless(3);
1348 An argument of 0 to @code{yyless()} will cause the entire current input
1349 string to be scanned again. Unless you've changed how the scanner will
1350 subsequently process its input (using @code{BEGIN}, for example), this
1351 will result in an endless loop.
1353 Note that @code{yyless()} is a macro and can only be used in the flex
1354 input file, not from other source files.
1357 @cindex pushing back characters with unput
1358 @code{unput(c)} puts the character @code{c} back onto the input stream.
1359 It will be the next character scanned. The following action will take
1360 the current token and cause it to be rescanned enclosed in parentheses.
1362 @cindex unput(), pushing back characters
1363 @cindex pushing back characters with unput()
1368 /* Copy yytext because unput() trashes yytext */
1369 char *yycopy = strdup( yytext );
1371 for ( i = yyleng - 1; i >= 0; --i )
1379 Note that since each @code{unput()} puts the given character back at the
1380 @emph{beginning} of the input stream, pushing back strings must be done
1383 @cindex %pointer, and unput()
1384 @cindex unput(), and %pointer
1385 An important potential problem when using @code{unput()} is that if you
1386 are using @code{%pointer} (the default), a call to @code{unput()}
1387 @emph{destroys} the contents of @code{yytext}, starting with its
1388 rightmost character and devouring one character to the left with each
1389 call. If you need the value of @code{yytext} preserved after a call to
1390 @code{unput()} (as in the above example), you must either first copy it
1391 elsewhere, or build your scanner using @code{%array} instead
1394 @cindex pushing back EOF
1395 @cindex EOF, pushing back
1396 Finally, note that you cannot put back @samp{EOF} to attempt to mark the
1397 input stream with an end-of-file.
1400 @code{input()} reads the next character from the input stream. For
1401 example, the following is one way to eat up C comments:
1403 @cindex comments, discarding
1404 @cindex discarding C comments
1413 while ( (c = input()) != '*' &&
1415 ; /* eat up text of comment */
1419 while ( (c = input()) == '*' )
1422 break; /* found the end */
1427 error( "EOF in comment" );
1435 @cindex input(), and C++
1437 (Note that if the scanner is compiled using @code{C++}, then
1438 @code{input()} is instead referred to as @b{yyinput()}, in order to
1439 avoid a name clash with the @code{C++} stream by the name of
1442 @cindex flushing the internal buffer
1443 @cindex YY_FLUSH_BUFFER()
1444 @code{YY_FLUSH_BUFFER()} flushes the scanner's internal buffer so that
1445 the next time the scanner attempts to match a token, it will first
1446 refill the buffer using @code{YY_INPUT()} (@pxref{Generated Scanner}).
1447 This action is a special case of the more general
1448 @code{yy_flush_buffer()} function, described below (@pxref{Multiple
1451 @cindex yyterminate()
1452 @cindex terminating with yyterminate()
1453 @cindex exiting with yyterminate()
1454 @cindex halting with yyterminate()
1455 @code{yyterminate()} can be used in lieu of a return statement in an
1456 action. It terminates the scanner and returns a 0 to the scanner's
1457 caller, indicating ``all done''. By default, @code{yyterminate()} is
1458 also called when an end-of-file is encountered. It is a macro and may
1461 @node Generated Scanner, Start Conditions, Actions, Top
1462 @chapter The Generated Scanner
1464 @cindex yylex(), in generated scanner
1465 The output of @code{flex} is the file @file{lex.yy.c}, which contains
1466 the scanning routine @code{yylex()}, a number of tables used by it for
1467 matching tokens, and a number of auxiliary routines and macros. By
1468 default, @code{yylex()} is declared as follows:
1474 ... various definitions and the actions in here ...
1479 @cindex yylex(), overriding
1480 (If your environment supports function prototypes, then it will be
1481 @code{int yylex( void )}.) This definition may be changed by defining
1482 the @code{YY_DECL} macro. For example, you could use:
1484 @cindex yylex, overriding the prototype of
1487 #define YY_DECL float lexscan( a, b ) float a, b;
1491 to give the scanning routine the name @code{lexscan}, returning a float,
1492 and taking two floats as arguments. Note that if you give arguments to
1493 the scanning routine using a K&R-style/non-prototyped function
1494 declaration, you must terminate the definition with a semi-colon (;).
1496 @code{flex} generates @samp{C99} function definitions by
1497 default. However flex does have the ability to generate obsolete, er,
1498 @samp{traditional}, function definitions. This is to support
1499 bootstrapping gcc on old systems. Unfortunately, traditional
1500 definitions prevent us from using any standard data types smaller than
1501 int (such as short, char, or bool) as function arguments. For this
1502 reason, future versions of @code{flex} may generate standard C99 code
1503 only, leaving K&R-style functions to the historians. Currently, if you
1504 do @strong{not} want @samp{C99} definitions, then you must use
1505 @code{%option noansi-definitions}.
1507 @cindex stdin, default for yyin
1509 Whenever @code{yylex()} is called, it scans tokens from the global input
1510 file @file{yyin} (which defaults to stdin). It continues until it
1511 either reaches an end-of-file (at which point it returns the value 0) or
1512 one of its actions executes a @code{return} statement.
1514 @cindex EOF and yyrestart()
1515 @cindex end-of-file, and yyrestart()
1517 If the scanner reaches an end-of-file, subsequent calls are undefined
1518 unless either @file{yyin} is pointed at a new input file (in which case
1519 scanning continues from that file), or @code{yyrestart()} is called.
1520 @code{yyrestart()} takes one argument, a @code{FILE *} pointer (which
1521 can be NULL, if you've set up @code{YY_INPUT} to scan from a source other
1522 than @code{yyin}), and initializes @file{yyin} for scanning from that
1523 file. Essentially there is no difference between just assigning
1524 @file{yyin} to a new input file or using @code{yyrestart()} to do so;
1525 the latter is available for compatibility with previous versions of
1526 @code{flex}, and because it can be used to switch input files in the
1527 middle of scanning. It can also be used to throw away the current input
1528 buffer, by calling it with an argument of @file{yyin}; but it would be
1529 better to use @code{YY_FLUSH_BUFFER} (@pxref{Actions}). Note that
1530 @code{yyrestart()} does @emph{not} reset the start condition to
1531 @code{INITIAL} (@pxref{Start Conditions}).
1533 @cindex RETURN, within actions
1534 If @code{yylex()} stops scanning due to executing a @code{return}
1535 statement in one of the actions, the scanner may then be called again
1536 and it will resume scanning where it left off.
1539 By default (and for purposes of efficiency), the scanner uses
1540 block-reads rather than simple @code{getc()} calls to read characters
1541 from @file{yyin}. The nature of how it gets its input can be controlled
1542 by defining the @code{YY_INPUT} macro. The calling sequence for
1543 @code{YY_INPUT()} is @code{YY_INPUT(buf,result,max_size)}. Its action
1544 is to place up to @code{max_size} characters in the character array
1545 @code{buf} and return in the integer variable @code{result} either the
1546 number of characters read or the constant @code{YY_NULL} (0 on Unix
1547 systems) to indicate @samp{EOF}. The default @code{YY_INPUT} reads from
1548 the global file-pointer @file{yyin}.
1550 @cindex YY_INPUT, overriding
1551 Here is a sample definition of @code{YY_INPUT} (in the definitions
1552 section of the input file):
1557 #define YY_INPUT(buf,result,max_size) \
1559 int c = getchar(); \
1560 result = (c == EOF) ? YY_NULL : (buf[0] = c, 1); \
1566 This definition will change the input processing to occur one character
1570 When the scanner receives an end-of-file indication from YY_INPUT, it
1571 then checks the @code{yywrap()} function. If @code{yywrap()} returns
1572 false (zero), then it is assumed that the function has gone ahead and
1573 set up @file{yyin} to point to another input file, and scanning
1574 continues. If it returns true (non-zero), then the scanner terminates,
1575 returning 0 to its caller. Note that in either case, the start
1576 condition remains unchanged; it does @emph{not} revert to
1579 @cindex yywrap, default for
1580 @cindex nowrap, %option
1581 @cindex %option nowrap
1582 If you do not supply your own version of @code{yywrap()}, then you must
1583 either use @code{%option noyywrap} (in which case the scanner behaves as
1584 though @code{yywrap()} returned 1), or you must link with @samp{-lfl} to
1585 obtain the default version of the routine, which always returns 1.
1587 For scanning from in-memory buffers (e.g., scanning strings), see
1588 @ref{Scanning Strings}. @xref{Multiple Input Buffers}.
1590 @cindex ECHO, and yyout
1592 @cindex stdout, as default for yyout
1593 The scanner writes its @code{ECHO} output to the @file{yyout} global
1594 (default, @file{stdout}), which may be redefined by the user simply by
1595 assigning it to some other @code{FILE} pointer.
1597 @node Start Conditions, Multiple Input Buffers, Generated Scanner, Top
1598 @chapter Start Conditions
1600 @cindex start conditions
1601 @code{flex} provides a mechanism for conditionally activating rules.
1602 Any rule whose pattern is prefixed with @samp{<sc>} will only be active
1603 when the scanner is in the @dfn{start condition} named @code{sc}. For
1606 @c proofread edit stopped here
1609 <STRING>[^"]* { /* eat up the string body ... */
1615 will be active only when the scanner is in the @code{STRING} start
1618 @cindex start conditions, multiple
1621 <INITIAL,STRING,QUOTE>\. { /* handle an escape ... */
1627 will be active only when the current start condition is either
1628 @code{INITIAL}, @code{STRING}, or @code{QUOTE}.
1630 @cindex start conditions, inclusive v.s.@: exclusive
1631 Start conditions are declared in the definitions (first) section of the
1632 input using unindented lines beginning with either @samp{%s} or
1633 @samp{%x} followed by a list of names. The former declares
1634 @dfn{inclusive} start conditions, the latter @dfn{exclusive} start
1635 conditions. A start condition is activated using the @code{BEGIN}
1636 action. Until the next @code{BEGIN} action is executed, rules with the
1637 given start condition will be active and rules with other start
1638 conditions will be inactive. If the start condition is inclusive, then
1639 rules with no start conditions at all will also be active. If it is
1640 exclusive, then @emph{only} rules qualified with the start condition
1641 will be active. A set of rules contingent on the same exclusive start
1642 condition describe a scanner which is independent of any of the other
1643 rules in the @code{flex} input. Because of this, exclusive start
1644 conditions make it easy to specify ``mini-scanners'' which scan portions
1645 of the input that are syntactically different from the rest (e.g.,
1648 If the distinction between inclusive and exclusive start conditions
1649 is still a little vague, here's a simple example illustrating the
1650 connection between the two. The set of rules:
1652 @cindex start conditions, inclusive
1658 <example>foo do_something();
1660 bar something_else();
1666 @cindex start conditions, exclusive
1672 <example>foo do_something();
1674 <INITIAL,example>bar something_else();
1678 Without the @code{<INITIAL,example>} qualifier, the @code{bar} pattern in
1679 the second example wouldn't be active (i.e., couldn't match) when in
1680 start condition @code{example}. If we just used @code{<example>} to
1681 qualify @code{bar}, though, then it would only be active in
1682 @code{example} and not in @code{INITIAL}, while in the first example
1683 it's active in both, because in the first example the @code{example}
1684 start condition is an inclusive @code{(%s)} start condition.
1686 @cindex start conditions, special wildcard condition
1687 Also note that the special start-condition specifier
1689 matches every start condition. Thus, the above example could also
1692 @cindex start conditions, use of wildcard condition (<*>)
1698 <example>foo do_something();
1700 <*>bar something_else();
1704 The default rule (to @code{ECHO} any unmatched character) remains active
1705 in start conditions. It is equivalent to:
1707 @cindex start conditions, behavior of default rule
1714 @cindex BEGIN, explanation
1717 @code{BEGIN(0)} returns to the original state where only the rules with
1718 no start conditions are active. This state can also be referred to as
1719 the start-condition @code{INITIAL}, so @code{BEGIN(INITIAL)} is
1720 equivalent to @code{BEGIN(0)}. (The parentheses around the start
1721 condition name are not required but are considered good style.)
1723 @code{BEGIN} actions can also be given as indented code at the beginning
1724 of the rules section. For example, the following will cause the scanner
1725 to enter the @code{SPECIAL} start condition whenever @code{yylex()} is
1726 called and the global variable @code{enter_special} is true:
1728 @cindex start conditions, using BEGIN
1735 if ( enter_special )
1738 <SPECIAL>blahblahblah
1739 ...more rules follow...
1743 To illustrate the uses of start conditions, here is a scanner which
1744 provides two different interpretations of a string like @samp{123.456}.
1745 By default it will treat it as three tokens, the integer @samp{123}, a
1746 dot (@samp{.}), and the integer @samp{456}. But if the string is
1747 preceded earlier in the line by the string @samp{expect-floats} it will
1748 treat it as a single token, the floating-point number @samp{123.456}:
1750 @cindex start conditions, for different interpretations of same input
1759 expect-floats BEGIN(expect);
1761 <expect>[0-9]+@samp{.}[0-9]+ {
1762 printf( "found a float, = %f\n",
1766 /* that's the end of the line, so
1767 * we need another "expect-number"
1768 * before we'll recognize any more
1775 printf( "found an integer, = %d\n",
1779 "." printf( "found a dot\n" );
1783 @cindex comments, example of scanning C comments
1784 Here is a scanner which recognizes (and discards) C comments while
1785 maintaining a count of the current input line.
1787 @cindex recognizing C comments
1794 "/*" BEGIN(comment);
1796 <comment>[^*\n]* /* eat anything that's not a '*' */
1797 <comment>"*"+[^*/\n]* /* eat up '*'s not followed by '/'s */
1798 <comment>\n ++line_num;
1799 <comment>"*"+"/" BEGIN(INITIAL);
1803 This scanner goes to a bit of trouble to match as much
1804 text as possible with each rule. In general, when attempting to write
1805 a high-speed scanner try to match as much possible in each rule, as
1808 Note that start-conditions names are really integer values and
1809 can be stored as such. Thus, the above could be extended in the
1812 @cindex start conditions, integer values
1813 @cindex using integer values of start condition names
1822 comment_caller = INITIAL;
1829 comment_caller = foo;
1833 <comment>[^*\n]* /* eat anything that's not a '*' */
1834 <comment>"*"+[^*/\n]* /* eat up '*'s not followed by '/'s */
1835 <comment>\n ++line_num;
1836 <comment>"*"+"/" BEGIN(comment_caller);
1840 @cindex YY_START, example
1841 Furthermore, you can access the current start condition using the
1842 integer-valued @code{YY_START} macro. For example, the above
1843 assignments to @code{comment_caller} could instead be written
1845 @cindex getting current start state with YY_START
1848 comment_caller = YY_START;
1853 Flex provides @code{YYSTATE} as an alias for @code{YY_START} (since that
1854 is what's used by AT&T @code{lex}).
1856 For historical reasons, start conditions do not have their own
1857 name-space within the generated scanner. The start condition names are
1858 unmodified in the generated scanner and generated header.
1859 @xref{option-header}. @xref{option-prefix}.
1863 Finally, here's an example of how to match C-style quoted strings using
1864 exclusive start conditions, including expanded escape sequences (but
1865 not including checking for a string that's too long):
1867 @cindex matching C-style double-quoted strings
1873 char string_buf[MAX_STR_CONST];
1874 char *string_buf_ptr;
1877 \" string_buf_ptr = string_buf; BEGIN(str);
1879 <str>\" { /* saw closing quote - all done */
1881 *string_buf_ptr = '\0';
1882 /* return string constant token type and
1888 /* error - unterminated string constant */
1889 /* generate error message */
1893 /* octal escape sequence */
1896 (void) sscanf( yytext + 1, "%o", &result );
1898 if ( result > 0xff )
1899 /* error, constant is out-of-bounds */
1901 *string_buf_ptr++ = result;
1905 /* generate error - bad escape sequence; something
1906 * like '\48' or '\0777777'
1910 <str>\\n *string_buf_ptr++ = '\n';
1911 <str>\\t *string_buf_ptr++ = '\t';
1912 <str>\\r *string_buf_ptr++ = '\r';
1913 <str>\\b *string_buf_ptr++ = '\b';
1914 <str>\\f *string_buf_ptr++ = '\f';
1916 <str>\\(.|\n) *string_buf_ptr++ = yytext[1];
1919 char *yptr = yytext;
1922 *string_buf_ptr++ = *yptr++;
1927 @cindex start condition, applying to multiple patterns
1928 Often, such as in some of the examples above, you wind up writing a
1929 whole bunch of rules all preceded by the same start condition(s). Flex
1930 makes this a little easier and cleaner by introducing a notion of start
1931 condition @dfn{scope}. A start condition scope is begun with:
1939 where @code{SCs} is a list of one or more start conditions. Inside the
1940 start condition scope, every rule automatically has the prefix
1941 @code{SCs>} applied to it, until a @samp{@}} which matches the initial
1942 @samp{@{}. So, for example,
1944 @cindex extended scope of start conditions
1960 <ESC>"\\n" return '\n';
1961 <ESC>"\\r" return '\r';
1962 <ESC>"\\f" return '\f';
1963 <ESC>"\\0" return '\0';
1967 Start condition scopes may be nested.
1969 @cindex stacks, routines for manipulating
1970 @cindex start conditions, use of a stack
1972 The following routines are available for manipulating stacks of start conditions:
1974 @deftypefun void yy_push_state ( int @code{new_state} )
1975 pushes the current start condition onto the top of the start condition
1976 stack and switches to
1978 as though you had used
1979 @code{BEGIN new_state}
1980 (recall that start condition names are also integers).
1983 @deftypefun void yy_pop_state ()
1984 pops the top of the stack and switches to it via
1988 @deftypefun int yy_top_state ()
1989 returns the top of the stack without altering the stack's contents.
1992 @cindex memory, for start condition stacks
1993 The start condition stack grows dynamically and so has no built-in size
1994 limitation. If memory is exhausted, program execution aborts.
1996 To use start condition stacks, your scanner must include a @code{%option
1997 stack} directive (@pxref{Scanner Options}).
1999 @node Multiple Input Buffers, EOF, Start Conditions, Top
2000 @chapter Multiple Input Buffers
2002 @cindex multiple input streams
2003 Some scanners (such as those which support ``include'' files) require
2004 reading from several input streams. As @code{flex} scanners do a large
2005 amount of buffering, one cannot control where the next input will be
2006 read from by simply writing a @code{YY_INPUT()} which is sensitive to
2007 the scanning context. @code{YY_INPUT()} is only called when the scanner
2008 reaches the end of its buffer, which may be a long time after scanning a
2009 statement such as an @code{include} statement which requires switching
2012 To negotiate these sorts of problems, @code{flex} provides a mechanism
2013 for creating and switching between multiple input buffers. An input
2014 buffer is created by using:
2016 @cindex memory, allocating input buffers
2017 @deftypefun YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size )
2020 which takes a @code{FILE} pointer and a size and creates a buffer
2021 associated with the given file and large enough to hold @code{size}
2022 characters (when in doubt, use @code{YY_BUF_SIZE} for the size). It
2023 returns a @code{YY_BUFFER_STATE} handle, which may then be passed to
2024 other routines (see below).
2025 @tindex YY_BUFFER_STATE
2026 The @code{YY_BUFFER_STATE} type is a
2027 pointer to an opaque @code{struct yy_buffer_state} structure, so you may
2028 safely initialize @code{YY_BUFFER_STATE} variables to @code{((YY_BUFFER_STATE)
2029 0)} if you wish, and also refer to the opaque structure in order to
2030 correctly declare input buffers in source files other than that of your
2031 scanner. Note that the @code{FILE} pointer in the call to
2032 @code{yy_create_buffer} is only used as the value of @file{yyin} seen by
2033 @code{YY_INPUT}. If you redefine @code{YY_INPUT()} so it no longer uses
2034 @file{yyin}, then you can safely pass a NULL @code{FILE} pointer to
2035 @code{yy_create_buffer}. You select a particular buffer to scan from
2038 @deftypefun void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer )
2041 The above function switches the scanner's input buffer so subsequent tokens
2042 will come from @code{new_buffer}. Note that @code{yy_switch_to_buffer()} may
2043 be used by @code{yywrap()} to set things up for continued scanning, instead of
2044 opening a new file and pointing @file{yyin} at it. If you are looking for a
2045 stack of input buffers, then you want to use @code{yypush_buffer_state()}
2046 instead of this function. Note also that switching input sources via either
2047 @code{yy_switch_to_buffer()} or @code{yywrap()} does @emph{not} change the
2050 @cindex memory, deleting input buffers
2051 @deftypefun void yy_delete_buffer ( YY_BUFFER_STATE buffer )
2054 is used to reclaim the storage associated with a buffer. (@code{buffer}
2055 can be NULL, in which case the routine does nothing.) You can also clear
2056 the current contents of a buffer using:
2058 @cindex pushing an input buffer
2059 @cindex stack, input buffer push
2060 @deftypefun void yypush_buffer_state ( YY_BUFFER_STATE buffer )
2063 This function pushes the new buffer state onto an internal stack. The pushed
2064 state becomes the new current state. The stack is maintained by flex and will
2065 grow as required. This function is intended to be used instead of
2066 @code{yy_switch_to_buffer}, when you want to change states, but preserve the
2067 current state for later use.
2069 @cindex popping an input buffer
2070 @cindex stack, input buffer pop
2071 @deftypefun void yypop_buffer_state ( )
2074 This function removes the current state from the top of the stack, and deletes
2075 it by calling @code{yy_delete_buffer}. The next state on the stack, if any,
2076 becomes the new current state.
2078 @cindex clearing an input buffer
2079 @cindex flushing an input buffer
2080 @deftypefun void yy_flush_buffer ( YY_BUFFER_STATE buffer )
2083 This function discards the buffer's contents,
2084 so the next time the scanner attempts to match a token from the
2085 buffer, it will first fill the buffer anew using
2088 @deftypefun YY_BUFFER_STATE yy_new_buffer ( FILE *file, int size )
2091 is an alias for @code{yy_create_buffer()},
2092 provided for compatibility with the C++ use of @code{new} and
2093 @code{delete} for creating and destroying dynamic objects.
2095 @cindex YY_CURRENT_BUFFER, and multiple buffers Finally, the macro
2096 @code{YY_CURRENT_BUFFER} macro returns a @code{YY_BUFFER_STATE} handle to the
2097 current buffer. It should not be used as an lvalue.
2099 @cindex EOF, example using multiple input buffers
2100 Here are two examples of using these features for writing a scanner
2101 which expands include files (the
2103 feature is discussed below).
2105 This first example uses yypush_buffer_state and yypop_buffer_state. Flex
2106 maintains the stack internally.
2108 @cindex handling include files with multiple input buffers
2111 /* the "incl" state is used for picking up the name
2112 * of an include file
2116 include BEGIN(incl);
2121 <incl>[ \t]* /* eat the whitespace */
2122 <incl>[^ \t\n]+ { /* got the include file name */
2123 yyin = fopen( yytext, "r" );
2128 yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE ));
2134 yypop_buffer_state();
2136 if ( !YY_CURRENT_BUFFER )
2144 The second example, below, does the same thing as the previous example did, but
2145 manages its own input buffer stack manually (instead of letting flex do it).
2147 @cindex handling include files with multiple input buffers
2150 /* the "incl" state is used for picking up the name
2151 * of an include file
2156 #define MAX_INCLUDE_DEPTH 10
2157 YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
2158 int include_stack_ptr = 0;
2162 include BEGIN(incl);
2167 <incl>[ \t]* /* eat the whitespace */
2168 <incl>[^ \t\n]+ { /* got the include file name */
2169 if ( include_stack_ptr >= MAX_INCLUDE_DEPTH )
2171 fprintf( stderr, "Includes nested too deeply" );
2175 include_stack[include_stack_ptr++] =
2178 yyin = fopen( yytext, "r" );
2183 yy_switch_to_buffer(
2184 yy_create_buffer( yyin, YY_BUF_SIZE ) );
2190 if ( --include_stack_ptr 0 )
2197 yy_delete_buffer( YY_CURRENT_BUFFER );
2198 yy_switch_to_buffer(
2199 include_stack[include_stack_ptr] );
2205 @anchor{Scanning Strings}
2206 @cindex strings, scanning strings instead of files
2207 The following routines are available for setting up input buffers for
2208 scanning in-memory strings instead of files. All of them create a new
2209 input buffer for scanning the string, and return a corresponding
2210 @code{YY_BUFFER_STATE} handle (which you should delete with
2211 @code{yy_delete_buffer()} when done with it). They also switch to the
2212 new buffer using @code{yy_switch_to_buffer()}, so the next call to
2213 @code{yylex()} will start scanning the string.
2215 @deftypefun YY_BUFFER_STATE yy_scan_string ( const char *str )
2216 scans a NUL-terminated string.
2219 @deftypefun YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len )
2220 scans @code{len} bytes (including possibly @code{NUL}s) starting at location
2224 Note that both of these functions create and scan a @emph{copy} of the
2225 string or bytes. (This may be desirable, since @code{yylex()} modifies
2226 the contents of the buffer it is scanning.) You can avoid the copy by
2229 @vindex YY_END_OF_BUFFER_CHAR
2230 @deftypefun YY_BUFFER_STATE yy_scan_buffer (char *base, yy_size_t size)
2231 which scans in place the buffer starting at @code{base}, consisting of
2232 @code{size} bytes, the last two bytes of which @emph{must} be
2233 @code{YY_END_OF_BUFFER_CHAR} (ASCII NUL). These last two bytes are not
2234 scanned; thus, scanning consists of @code{base[0]} through
2235 @code{base[size-2]}, inclusive.
2238 If you fail to set up @code{base} in this manner (i.e., forget the final
2239 two @code{YY_END_OF_BUFFER_CHAR} bytes), then @code{yy_scan_buffer()}
2240 returns a NULL pointer instead of creating a new input buffer.
2242 @deftp {Data type} yy_size_t
2243 is an integral type to which you can cast an integer expression
2244 reflecting the size of the buffer.
2247 @node EOF, Misc Macros, Multiple Input Buffers, Top
2248 @chapter End-of-File Rules
2250 @cindex EOF, explanation
2251 The special rule @code{<<EOF>>} indicates
2252 actions which are to be taken when an end-of-file is
2253 encountered and @code{yywrap()} returns non-zero (i.e., indicates
2254 no further files to process). The action must finish
2255 by doing one of the following things:
2259 @findex YY_NEW_FILE (now obsolete)
2260 assigning @file{yyin} to a new input file (in previous versions of
2261 @code{flex}, after doing the assignment you had to call the special
2262 action @code{YY_NEW_FILE}. This is no longer necessary.)
2265 executing a @code{return} statement;
2268 executing the special @code{yyterminate()} action.
2271 or, switching to a new buffer using @code{yy_switch_to_buffer()} as
2272 shown in the example above.
2275 <<EOF>> rules may not be used with other patterns; they may only be
2276 qualified with a list of start conditions. If an unqualified <<EOF>>
2277 rule is given, it applies to @emph{all} start conditions which do not
2278 already have <<EOF>> actions. To specify an <<EOF>> rule for only the
2279 initial start condition, use:
2287 These rules are useful for catching things like unclosed comments. An
2290 @cindex <<EOF>>, use of
2296 ...other rules for dealing with quotes...
2299 error( "unterminated quote" );
2304 yyin = fopen( *filelist, "r" );
2311 @node Misc Macros, User Values, EOF, Top
2312 @chapter Miscellaneous Macros
2314 @hkindex YY_USER_ACTION
2315 The macro @code{YY_USER_ACTION} can be defined to provide an action
2316 which is always executed prior to the matched rule's action. For
2317 example, it could be #define'd to call a routine to convert yytext to
2318 lower-case. When @code{YY_USER_ACTION} is invoked, the variable
2319 @code{yy_act} gives the number of the matched rule (rules are numbered
2320 starting with 1). Suppose you want to profile how often each of your
2321 rules is matched. The following would do the trick:
2323 @cindex YY_USER_ACTION to track each time a rule is matched
2326 #define YY_USER_ACTION ++ctr[yy_act]
2330 @vindex YY_NUM_RULES
2331 where @code{ctr} is an array to hold the counts for the different rules.
2332 Note that the macro @code{YY_NUM_RULES} gives the total number of rules
2333 (including the default rule), even if you use @samp{-s)}, so a correct
2334 declaration for @code{ctr} is:
2338 int ctr[YY_NUM_RULES];
2342 @hkindex YY_USER_INIT
2343 The macro @code{YY_USER_INIT} may be defined to provide an action which
2344 is always executed before the first scan (and before the scanner's
2345 internal initializations are done). For example, it could be used to
2346 call a routine to read in a data table or open a logging file.
2348 @findex yy_set_interactive
2349 The macro @code{yy_set_interactive(is_interactive)} can be used to
2350 control whether the current buffer is considered @dfn{interactive}. An
2351 interactive buffer is processed more slowly, but must be used when the
2352 scanner's input source is indeed interactive to avoid problems due to
2353 waiting to fill buffers (see the discussion of the @samp{-I} flag in
2354 @ref{Scanner Options}). A non-zero value in the macro invocation marks
2355 the buffer as interactive, a zero value as non-interactive. Note that
2356 use of this macro overrides @code{%option always-interactive} or
2357 @code{%option never-interactive} (@pxref{Scanner Options}).
2358 @code{yy_set_interactive()} must be invoked prior to beginning to scan
2359 the buffer that is (or is not) to be considered interactive.
2361 @cindex BOL, setting it
2363 The macro @code{yy_set_bol(at_bol)} can be used to control whether the
2364 current buffer's scanning context for the next token match is done as
2365 though at the beginning of a line. A non-zero macro argument makes
2366 rules anchored with @samp{^} active, while a zero argument makes
2367 @samp{^} rules inactive.
2369 @cindex BOL, checking the BOL flag
2371 The macro @code{YY_AT_BOL()} returns true if the next token scanned from
2372 the current buffer will have @samp{^} rules active, false otherwise.
2374 @cindex actions, redefining YY_BREAK
2376 In the generated scanner, the actions are all gathered in one large
2377 switch statement and separated using @code{YY_BREAK}, which may be
2378 redefined. By default, it is simply a @code{break}, to separate each
2379 rule's action from the following rule's. Redefining @code{YY_BREAK}
2380 allows, for example, C++ users to #define YY_BREAK to do nothing (while
2381 being very careful that every rule ends with a @code{break} or a
2382 @code{return}!) to avoid suffering from unreachable statement warnings
2383 where because a rule's action ends with @code{return}, the
2384 @code{YY_BREAK} is inaccessible.
2386 @node User Values, Yacc, Misc Macros, Top
2387 @chapter Values Available To the User
2389 This chapter summarizes the various values available to the user in the
2395 holds the text of the current token. It may be modified but not
2396 lengthened (you cannot append characters to the end).
2398 @cindex yytext, default array size
2399 @cindex array, default size for yytext
2401 If the special directive @code{%array} appears in the first section of
2402 the scanner description, then @code{yytext} is instead declared
2403 @code{char yytext[YYLMAX]}, where @code{YYLMAX} is a macro definition
2404 that you can redefine in the first section if you don't like the default
2405 value (generally 8KB). Using @code{%array} results in somewhat slower
2406 scanners, but the value of @code{yytext} becomes immune to calls to
2407 @code{unput()}, which potentially destroy its value when @code{yytext} is
2408 a character pointer. The opposite of @code{%array} is @code{%pointer},
2409 which is the default.
2411 @cindex C++ and %array
2412 You cannot use @code{%array} when generating C++ scanner classes (the
2417 holds the length of the current token.
2421 is the file which by default @code{flex} reads from. It may be
2422 redefined but doing so only makes sense before scanning begins or after
2423 an EOF has been encountered. Changing it in the midst of scanning will
2424 have unexpected results since @code{flex} buffers its input; use
2425 @code{yyrestart()} instead. Once scanning terminates because an
2426 end-of-file has been seen, you can assign @file{yyin} at the new input
2427 file and then call the scanner again to continue scanning.
2430 @item void yyrestart( FILE *new_file )
2431 may be called to point @file{yyin} at the new input file. The
2432 switch-over to the new file is immediate (any previously buffered-up
2433 input is lost). Note that calling @code{yyrestart()} with @file{yyin}
2434 as an argument thus throws away the current input buffer and continues
2435 scanning the same input file.
2439 is the file to which @code{ECHO} actions are done. It can be reassigned
2442 @vindex YY_CURRENT_BUFFER
2443 @item YY_CURRENT_BUFFER
2444 returns a @code{YY_BUFFER_STATE} handle to the current buffer.
2448 returns an integer value corresponding to the current start condition.
2449 You can subsequently use this value with @code{BEGIN} to return to that
2453 @node Yacc, Scanner Options, User Values, Top
2454 @chapter Interfacing with Yacc
2456 @cindex yacc, interface
2458 @vindex yylval, with yacc
2459 One of the main uses of @code{flex} is as a companion to the @code{yacc}
2460 parser-generator. @code{yacc} parsers expect to call a routine named
2461 @code{yylex()} to find the next input token. The routine is supposed to
2462 return the type of the next token as well as putting any associated
2463 value in the global @code{yylval}. To use @code{flex} with @code{yacc},
2464 one specifies the @samp{-d} option to @code{yacc} to instruct it to
2465 generate the file @file{y.tab.h} containing definitions of all the
2466 @code{%tokens} appearing in the @code{yacc} input. This file is then
2467 included in the @code{flex} scanner. For example, if one of the tokens
2468 is @code{TOK_NUMBER}, part of the scanner might look like:
2470 @cindex yacc interface
2479 [0-9]+ yylval = atoi( yytext ); return TOK_NUMBER;
2483 @node Scanner Options, Performance, Yacc, Top
2484 @chapter Scanner Options
2486 @cindex command-line options
2487 @cindex options, command-line
2488 @cindex arguments, command-line
2490 The various @code{flex} options are categorized by function in the following
2491 menu. If you want to lookup a particular option by name, @xref{Index of Scanner Options}.
2494 * Options for Specifying Filenames::
2495 * Options Affecting Scanner Behavior::
2496 * Code-Level And API Options::
2497 * Options for Scanner Speed and Size::
2498 * Debugging Options::
2499 * Miscellaneous Options::
2502 Even though there are many scanner options, a typical scanner might only
2503 specify the following options:
2507 %option 8bit reentrant bison-bridge
2508 %option warn nodefault
2510 %option outfile="scanner.c" header-file="scanner.h"
2514 The first line specifies the general type of scanner we want. The second line
2515 specifies that we are being careful. The third line asks flex to track line
2516 numbers. The last line tells flex what to name the files. (The options can be
2517 specified in any order. We just divided them.)
2519 @code{flex} also provides a mechanism for controlling options within the
2520 scanner specification itself, rather than from the flex command-line.
2521 This is done by including @code{%option} directives in the first section
2522 of the scanner specification. You can specify multiple options with a
2523 single @code{%option} directive, and multiple directives in the first
2524 section of your flex input file.
2526 Most options are given simply as names, optionally preceded by the
2527 word @samp{no} (with no intervening whitespace) to negate their meaning.
2528 The names are the same as their long-option equivalents (but without the
2529 leading @samp{--} ).
2531 @code{flex} scans your rule actions to determine whether you use the
2532 @code{REJECT} or @code{yymore()} features. The @code{REJECT} and
2533 @code{yymore} options are available to override its decision as to
2534 whether you use the options, either by setting them (e.g., @code{%option
2535 reject)} to indicate the feature is indeed used, or unsetting them to
2536 indicate it actually is not used (e.g., @code{%option noyymore)}.
2539 A number of options are available for lint purists who want to suppress
2540 the appearance of unneeded routines in the generated scanner. Each of
2541 the following, if unset (e.g., @code{%option nounput}), results in the
2542 corresponding routine not appearing in the generated scanner:
2547 yy_push_state, yy_pop_state, yy_top_state
2548 yy_scan_buffer, yy_scan_bytes, yy_scan_string
2550 yyget_extra, yyset_extra, yyget_leng, yyget_text,
2551 yyget_lineno, yyset_lineno, yyget_in, yyset_in,
2552 yyget_out, yyset_out, yyget_lval, yyset_lval,
2553 yyget_lloc, yyset_lloc, yyget_debug, yyset_debug
2557 (though @code{yy_push_state()} and friends won't appear anyway unless
2558 you use @code{%option stack)}.
2560 @node Options for Specifying Filenames, Options Affecting Scanner Behavior, Scanner Options, Scanner Options
2561 @section Options for Specifying Filenames
2565 @anchor{option-header}
2566 @opindex ---header-file
2567 @opindex header-file
2568 @item --header-file=FILE, @code{%option header-file="FILE"}
2569 instructs flex to write a C header to @file{FILE}. This file contains
2570 function prototypes, extern variables, and types used by the scanner.
2571 Only the external API is exported by the header file. Many macros that
2572 are usable from within scanner actions are not exported to the header
2573 file. This is due to namespace problems and the goal of a clean
2576 While in the header, the macro @code{yyIN_HEADER} is defined, where @samp{yy}
2577 is substituted with the appropriate prefix.
2579 The @samp{--header-file} option is not compatible with the @samp{--c++} option,
2580 since the C++ scanner provides its own header in @file{yyFlexLexer.h}.
2584 @anchor{option-outfile}
2588 @item -oFILE, --outfile=FILE, @code{%option outfile="FILE"}
2589 directs flex to write the scanner to the file @file{FILE} instead of
2590 @file{lex.yy.c}. If you combine @samp{--outfile} with the @samp{--stdout} option,
2591 then the scanner is written to @file{stdout} but its @code{#line}
2592 directives (see the @samp{-l} option above) refer to the file
2597 @anchor{option-stdout}
2601 @item -t, --stdout, @code{%option stdout}
2602 instructs @code{flex} to write the scanner it generates to standard
2603 output instead of @file{lex.yy.c}.
2608 @item -SFILE, --skel=FILE
2609 overrides the default skeleton file from which
2611 constructs its scanners. You'll never need this option unless you are doing
2613 maintenance or development.
2615 @opindex ---tables-file
2616 @opindex tables-file
2617 @item --tables-file=FILE
2618 Write serialized scanner dfa tables to FILE. The generated scanner will not
2619 contain the tables, and requires them to be loaded at runtime.
2620 @xref{serialization}.
2622 @opindex ---tables-verify
2623 @opindex tables-verify
2624 @item --tables-verify
2625 This option is for flex development. We document it here in case you stumble
2626 upon it by accident or in case you suspect some inconsistency in the serialized
2627 tables. Flex will serialize the scanner dfa tables but will also generate the
2628 in-code tables as it normally does. At runtime, the scanner will verify that
2629 the serialized tables match the in-code tables, instead of loading them.
2633 @node Options Affecting Scanner Behavior, Code-Level And API Options, Options for Specifying Filenames, Scanner Options
2634 @section Options Affecting Scanner Behavior
2637 @anchor{option-case-insensitive}
2639 @opindex ---case-insensitive
2640 @opindex case-insensitive
2641 @item -i, --case-insensitive, @code{%option case-insensitive}
2642 instructs @code{flex} to generate a @dfn{case-insensitive} scanner. The
2643 case of letters given in the @code{flex} input patterns will be ignored,
2644 and tokens in the input will be matched regardless of case. The matched
2645 text given in @code{yytext} will have the preserved case (i.e., it will
2646 not be folded). For tricky behavior, see @ref{case and character ranges}.
2650 @anchor{option-lex-compat}
2652 @opindex ---lex-compat
2654 @item -l, --lex-compat, @code{%option lex-compat}
2655 turns on maximum compatibility with the original AT&T @code{lex}
2656 implementation. Note that this does not mean @emph{full} compatibility.
2657 Use of this option costs a considerable amount of performance, and it
2658 cannot be used with the @samp{--c++}, @samp{--full}, @samp{--fast}, @samp{-Cf}, or
2659 @samp{-CF} options. For details on the compatibilities it provides, see
2660 @ref{Lex and Posix}. This option also results in the name
2661 @code{YY_FLEX_LEX_COMPAT} being @code{#define}'d in the generated scanner.
2665 @anchor{option-batch}
2669 @item -B, --batch, @code{%option batch}
2670 instructs @code{flex} to generate a @dfn{batch} scanner, the opposite of
2671 @emph{interactive} scanners generated by @samp{--interactive} (see below). In
2672 general, you use @samp{-B} when you are @emph{certain} that your scanner
2673 will never be used interactively, and you want to squeeze a
2674 @emph{little} more performance out of it. If your goal is instead to
2675 squeeze out a @emph{lot} more performance, you should be using the
2676 @samp{-Cf} or @samp{-CF} options, which turn on @samp{--batch} automatically
2681 @anchor{option-interactive}
2683 @opindex ---interactive
2684 @opindex interactive
2685 @item -I, --interactive, @code{%option interactive}
2686 instructs @code{flex} to generate an @i{interactive} scanner. An
2687 interactive scanner is one that only looks ahead to decide what token
2688 has been matched if it absolutely must. It turns out that always
2689 looking one extra character ahead, even if the scanner has already seen
2690 enough text to disambiguate the current token, is a bit faster than only
2691 looking ahead when necessary. But scanners that always look ahead give
2692 dreadful interactive performance; for example, when a user types a
2693 newline, it is not recognized as a newline token until they enter
2694 @emph{another} token, which often means typing in another whole line.
2696 @code{flex} scanners default to @code{interactive} unless you use the
2697 @samp{-Cf} or @samp{-CF} table-compression options
2698 (@pxref{Performance}). That's because if you're looking for
2699 high-performance you should be using one of these options, so if you
2700 didn't, @code{flex} assumes you'd rather trade off a bit of run-time
2701 performance for intuitive interactive behavior. Note also that you
2702 @emph{cannot} use @samp{--interactive} in conjunction with @samp{-Cf} or
2703 @samp{-CF}. Thus, this option is not really needed; it is on by default
2704 for all those cases in which it is allowed.
2706 You can force a scanner to
2708 be interactive by using
2713 @anchor{option-7bit}
2717 @item -7, --7bit, @code{%option 7bit}
2718 instructs @code{flex} to generate a 7-bit scanner, i.e., one which can
2719 only recognize 7-bit characters in its input. The advantage of using
2720 @samp{--7bit} is that the scanner's tables can be up to half the size of
2721 those generated using the @samp{--8bit}. The disadvantage is that such
2722 scanners often hang or crash if their input contains an 8-bit character.
2724 Note, however, that unless you generate your scanner using the
2725 @samp{-Cf} or @samp{-CF} table compression options, use of @samp{--7bit}
2726 will save only a small amount of table space, and make your scanner
2727 considerably less portable. @code{Flex}'s default behavior is to
2728 generate an 8-bit scanner unless you use the @samp{-Cf} or @samp{-CF},
2729 in which case @code{flex} defaults to generating 7-bit scanners unless
2730 your site was always configured to generate 8-bit scanners (as will
2731 often be the case with non-USA sites). You can tell whether flex
2732 generated a 7-bit or an 8-bit scanner by inspecting the flag summary in
2733 the @samp{--verbose} output as described above.
2735 Note that if you use @samp{-Cfe} or @samp{-CFe} @code{flex} still
2736 defaults to generating an 8-bit scanner, since usually with these
2737 compression options full 8-bit tables are not much more expensive than
2742 @anchor{option-8bit}
2746 @item -8, --8bit, @code{%option 8bit}
2747 instructs @code{flex} to generate an 8-bit scanner, i.e., one which can
2748 recognize 8-bit characters. This flag is only needed for scanners
2749 generated using @samp{-Cf} or @samp{-CF}, as otherwise flex defaults to
2750 generating an 8-bit scanner anyway.
2752 See the discussion of
2754 above for @code{flex}'s default behavior and the tradeoffs between 7-bit
2759 @anchor{option-default}
2762 @item --default, @code{%option default}
2763 generate the default rule.
2767 @anchor{option-always-interactive}
2768 @opindex ---always-interactive
2769 @opindex always-interactive
2770 @item --always-interactive, @code{%option always-interactive}
2771 instructs flex to generate a scanner which always considers its input
2772 @emph{interactive}. Normally, on each new input file the scanner calls
2773 @code{isatty()} in an attempt to determine whether the scanner's input
2774 source is interactive and thus should be read a character at a time.
2775 When this option is used, however, then no such call is made.
2779 @opindex ---never-interactive
2780 @item --never-interactive, @code{--never-interactive}
2781 instructs flex to generate a scanner which never considers its input
2782 interactive. This is the opposite of @code{always-interactive}.
2785 @anchor{option-posix}
2789 @item -X, --posix, @code{%option posix}
2790 turns on maximum compatibility with the POSIX 1003.2-1992 definition of
2791 @code{lex}. Since @code{flex} was originally designed to implement the
2792 POSIX definition of @code{lex} this generally involves very few changes
2793 in behavior. At the current writing the known differences between
2794 @code{flex} and the POSIX standard are:
2798 In POSIX and AT&T @code{lex}, the repeat operator, @samp{@{@}}, has lower
2799 precedence than concatenation (thus @samp{ab@{3@}} yields @samp{ababab}).
2800 Most POSIX utilities use an Extended Regular Expression (ERE) precedence
2801 that has the precedence of the repeat operator higher than concatenation
2802 (which causes @samp{ab@{3@}} to yield @samp{abbb}). By default, @code{flex}
2803 places the precedence of the repeat operator higher than concatenation
2804 which matches the ERE processing of other POSIX utilities. When either
2805 @samp{--posix} or @samp{-l} are specified, @code{flex} will use the
2806 traditional AT&T and POSIX-compliant precedence for the repeat operator
2807 where concatenation has higher precedence than the repeat operator.
2811 @anchor{option-stack}
2814 @item --stack, @code{%option stack}
2816 start condition stacks (@pxref{Start Conditions}).
2820 @anchor{option-stdinit}
2823 @item --stdinit, @code{%option stdinit}
2824 if set (i.e., @b{%option stdinit)} initializes @code{yyin} and
2825 @code{yyout} to @file{stdin} and @file{stdout}, instead of the default of
2826 @file{NULL}. Some existing @code{lex} programs depend on this behavior,
2827 even though it is not compliant with ANSI C, which does not require
2828 @file{stdin} and @file{stdout} to be compile-time constant. In a
2829 reentrant scanner, however, this is not a problem since initialization
2830 is performed in @code{yylex_init} at runtime.
2834 @anchor{option-yylineno}
2835 @opindex ---yylineno
2837 @item --yylineno, @code{%option yylineno}
2838 directs @code{flex} to generate a scanner
2839 that maintains the number of the current line read from its input in the
2840 global variable @code{yylineno}. This option is implied by @code{%option
2841 lex-compat}. In a reentrant C scanner, the macro @code{yylineno} is
2842 accessible regardless of the value of @code{%option yylineno}, however, its
2843 value is not modified by @code{flex} unless @code{%option yylineno} is enabled.
2847 @anchor{option-yywrap}
2850 @item --yywrap, @code{%option yywrap}
2851 if unset (i.e., @code{--noyywrap)}, makes the scanner not call
2852 @code{yywrap()} upon an end-of-file, but simply assume that there are no
2853 more files to scan (until the user points @file{yyin} at a new file and
2854 calls @code{yylex()} again).
2858 @node Code-Level And API Options, Options for Scanner Speed and Size, Options Affecting Scanner Behavior, Scanner Options
2859 @section Code-Level And API Options
2863 @anchor{option-ansi-definitions}
2864 @opindex ---option-ansi-definitions
2865 @opindex ansi-definitions
2866 @item --ansi-definitions, @code{%option ansi-definitions}
2867 instruct flex to generate ANSI C99 definitions for functions.
2868 This option is enabled by default.
2869 If @code{%option noansi-definitions} is specified, then the obsolete style
2872 @anchor{option-ansi-prototypes}
2873 @opindex ---option-ansi-prototypes
2874 @opindex ansi-prototypes
2875 @item --ansi-prototypes, @code{%option ansi-prototypes}
2876 instructs flex to generate ANSI C99 prototypes for functions.
2877 This option is enabled by default.
2878 If @code{noansi-prototypes} is specified, then
2879 prototypes will have empty parameter lists.
2881 @anchor{option-bison-bridge}
2882 @opindex ---bison-bridge
2883 @opindex bison-bridge
2884 @item --bison-bridge, @code{%option bison-bridge}
2885 instructs flex to generate a C scanner that is
2886 meant to be called by a
2888 parser. The scanner has minor API changes for
2890 compatibility. In particular, the declaration of
2892 is modified to take an additional parameter,
2894 @xref{Bison Bridge}.
2896 @anchor{option-bison-locations}
2897 @opindex ---bison-locations
2898 @opindex bison-locations
2899 @item --bison-locations, @code{%option bison-locations}
2901 @code{GNU bison} @code{%locations} are being used.
2902 This means @code{yylex} will be passed
2903 an additional parameter, @code{yylloc}. This option
2904 implies @code{%option bison-bridge}.
2905 @xref{Bison Bridge}.
2907 @anchor{option-noline}
2911 @item -L, --noline, @code{%option noline}
2916 directives. Without this option,
2918 peppers the generated scanner
2919 with @code{#line} directives so error messages in the actions will be correctly
2920 located with respect to either the original
2922 input file (if the errors are due to code in the input file), or
2926 fault -- you should report these sorts of errors to the email address
2927 given in @ref{Reporting Bugs}).
2931 @anchor{option-reentrant}
2933 @opindex ---reentrant
2935 @item -R, --reentrant, @code{%option reentrant}
2936 instructs flex to generate a reentrant C scanner. The generated scanner
2937 may safely be used in a multi-threaded environment. The API for a
2938 reentrant scanner is different than for a non-reentrant scanner
2939 @pxref{Reentrant}). Because of the API difference between
2940 reentrant and non-reentrant @code{flex} scanners, non-reentrant flex
2941 code must be modified before it is suitable for use with this option.
2942 This option is not compatible with the @samp{--c++} option.
2944 The option @samp{--reentrant} does not affect the performance of
2953 @item -+, --c++, @code{%option c++}
2954 specifies that you want flex to generate a C++
2955 scanner class. @xref{Cxx}, for
2960 @anchor{option-array}
2963 @item --array, @code{%option array}
2964 specifies that you want yytext to be an array instead of a char*
2968 @anchor{option-pointer}
2971 @item --pointer, @code{%option pointer}
2972 specify that @code{yytext} should be a @code{char *}, not an array.
2973 This default is @code{char *}.
2977 @anchor{option-prefix}
2981 @item -PPREFIX, --prefix=PREFIX, @code{%option prefix="PREFIX"}
2982 changes the default @samp{yy} prefix used by @code{flex} for all
2983 globally-visible variable and function names to instead be
2984 @samp{PREFIX}. For example, @samp{--prefix=foo} changes the name of
2985 @code{yytext} to @code{footext}. It also changes the name of the default
2986 output file from @file{lex.yy.c} to @file{lex.foo.c}. Here is a partial
2987 list of the names affected:
2996 yy_load_buffer_state
3012 (If you are using a C++ scanner, then only @code{yywrap} and
3013 @code{yyFlexLexer} are affected.) Within your scanner itself, you can
3014 still refer to the global variables and functions using either version
3015 of their name; but externally, they have the modified name.
3017 This option lets you easily link together multiple
3019 programs into the same executable. Note, though, that using this
3025 provide your own (appropriately-named) version of the routine for your
3027 @code{%option noyywrap},
3030 no longer provides one for you by default.
3034 @anchor{option-main}
3037 @item --main, @code{%option main}
3038 directs flex to provide a default @code{main()} program for the
3039 scanner, which simply calls @code{yylex()}. This option implies
3040 @code{noyywrap} (see below).
3044 @anchor{option-nounistd}
3045 @opindex ---nounistd
3047 @item --nounistd, @code{%option nounistd}
3048 suppresses inclusion of the non-ANSI header file @file{unistd.h}. This option
3049 is meant to target environments in which @file{unistd.h} does not exist. Be aware
3050 that certain options may cause flex to generate code that relies on functions
3051 normally found in @file{unistd.h}, (e.g. @code{isatty()}, @code{read()}.)
3052 If you wish to use these functions, you will have to inform your compiler where
3054 @xref{option-always-interactive}. @xref{option-read}.
3058 @anchor{option-yyclass}
3061 @item --yyclass=NAME, @code{%option yyclass="NAME"}
3062 only applies when generating a C++ scanner (the @samp{--c++} option). It
3063 informs @code{flex} that you have derived @code{NAME} as a subclass of
3064 @code{yyFlexLexer}, so @code{flex} will place your actions in the member
3065 function @code{foo::yylex()} instead of @code{yyFlexLexer::yylex()}. It
3066 also generates a @code{yyFlexLexer::yylex()} member function that emits
3067 a run-time error (by invoking @code{yyFlexLexer::LexerError())} if
3072 @node Options for Scanner Speed and Size, Debugging Options, Code-Level And API Options, Scanner Options
3073 @section Options for Scanner Speed and Size
3078 controls the degree of table compression and, more generally, trade-offs
3079 between small scanners and fast scanners.
3084 A lone @samp{-C} specifies that the scanner tables should be compressed
3085 but neither equivalence classes nor meta-equivalence classes should be
3088 @anchor{option-align}
3092 @item -Ca, --align, @code{%option align}
3093 (``align'') instructs flex to trade off larger tables in the
3094 generated scanner for faster performance because the elements of
3095 the tables are better aligned for memory access and computation. On some
3096 RISC architectures, fetching and manipulating longwords is more efficient
3097 than with smaller-sized units such as shortwords. This option can
3098 quadruple the size of the tables used by your scanner.
3104 @item -Ce, --ecs, @code{%option ecs}
3105 directs @code{flex} to construct @dfn{equivalence classes}, i.e., sets
3106 of characters which have identical lexical properties (for example, if
3107 the only appearance of digits in the @code{flex} input is in the
3108 character class ``[0-9]'' then the digits '0', '1', ..., '9' will all be
3109 put in the same equivalence class). Equivalence classes usually give
3110 dramatic reductions in the final table/object file sizes (typically a
3111 factor of 2-5) and are pretty cheap performance-wise (one array look-up
3112 per character scanned).
3116 specifies that the @dfn{full} scanner tables should be generated -
3117 @code{flex} should not compress the tables by taking advantages of
3118 similar transition functions for different states.
3122 specifies that the alternate fast scanner representation (described
3123 above under the @samp{--fast} flag) should be used. This option cannot be
3124 used with @samp{--c++}.
3126 @anchor{option-meta-ecs}
3128 @opindex ---meta-ecs
3130 @item -Cm, --meta-ecs, @code{%option meta-ecs}
3134 @dfn{meta-equivalence classes},
3135 which are sets of equivalence classes (or characters, if equivalence
3136 classes are not being used) that are commonly used together. Meta-equivalence
3137 classes are often a big win when using compressed tables, but they
3138 have a moderate performance impact (one or two @code{if} tests and one
3139 array look-up per character scanned).
3141 @anchor{option-read}
3145 @item -Cr, --read, @code{%option read}
3146 causes the generated scanner to @emph{bypass} use of the standard I/O
3147 library (@code{stdio}) for input. Instead of calling @code{fread()} or
3148 @code{getc()}, the scanner will use the @code{read()} system call,
3149 resulting in a performance gain which varies from system to system, but
3150 in general is probably negligible unless you are also using @samp{-Cf}
3151 or @samp{-CF}. Using @samp{-Cr} can cause strange behavior if, for
3152 example, you read from @file{yyin} using @code{stdio} prior to calling
3153 the scanner (because the scanner will miss whatever text your previous
3154 reads left in the @code{stdio} input buffer). @samp{-Cr} has no effect
3155 if you define @code{YY_INPUT()} (@pxref{Generated Scanner}).
3158 The options @samp{-Cf} or @samp{-CF} and @samp{-Cm} do not make sense
3159 together - there is no opportunity for meta-equivalence classes if the
3160 table is not being compressed. Otherwise the options may be freely
3161 mixed, and are cumulative.
3163 The default setting is @samp{-Cem}, which specifies that @code{flex}
3164 should generate equivalence classes and meta-equivalence classes. This
3165 setting provides the highest degree of table compression. You can trade
3166 off faster-executing scanners at the cost of larger tables with the
3167 following generally being true:
3183 Note that scanners with the smallest tables are usually generated and
3184 compiled the quickest, so during development you will usually want to
3185 use the default, maximal compression.
3187 @samp{-Cfe} is often a good compromise between speed and size for
3188 production scanners.
3190 @anchor{option-full}
3194 @item -f, --full, @code{%option full}
3197 No table compression is done and @code{stdio} is bypassed.
3198 The result is large but fast. This option is equivalent to
3202 @anchor{option-fast}
3206 @item -F, --fast, @code{%option fast}
3207 specifies that the @emph{fast} scanner table representation should be
3208 used (and @code{stdio} bypassed). This representation is about as fast
3209 as the full table representation @samp{--full}, and for some sets of
3210 patterns will be considerably smaller (and for others, larger). In
3211 general, if the pattern set contains both @emph{keywords} and a
3212 catch-all, @emph{identifier} rule, such as in the set:
3216 "case" return TOK_CASE;
3217 "switch" return TOK_SWITCH;
3219 "default" return TOK_DEFAULT;
3220 [a-z]+ return TOK_ID;
3224 then you're better off using the full table representation. If only
3225 the @emph{identifier} rule is present and you then use a hash table or some such
3226 to detect the keywords, you're better off using
3229 This option is equivalent to @samp{-CFr}. It cannot be used
3234 @node Debugging Options, Miscellaneous Options, Options for Scanner Speed and Size, Scanner Options
3235 @section Debugging Options
3239 @anchor{option-backup}
3243 @item -b, --backup, @code{%option backup}
3244 Generate backing-up information to @file{lex.backup}. This is a list of
3245 scanner states which require backing up and the input characters on
3246 which they do so. By adding rules one can remove backing-up states. If
3247 @emph{all} backing-up states are eliminated and @samp{-Cf} or @code{-CF}
3248 is used, the generated scanner will run faster (see the @samp{--perf-report} flag).
3249 Only users who wish to squeeze every last cycle out of their scanners
3250 need worry about this option. (@pxref{Performance}).
3254 @anchor{option-debug}
3258 @item -d, --debug, @code{%option debug}
3259 makes the generated scanner run in @dfn{debug} mode. Whenever a pattern
3260 is recognized and the global variable @code{yy_flex_debug} is non-zero
3261 (which is the default), the scanner will write to @file{stderr} a line
3266 -accepting rule at line 53 ("the matched text")
3270 The line number refers to the location of the rule in the file defining
3271 the scanner (i.e., the file that was fed to flex). Messages are also
3272 generated when the scanner backs up, accepts the default rule, reaches
3273 the end of its input buffer (or encounters a NUL; at this point, the two
3274 look the same as far as the scanner's concerned), or reaches an
3279 @anchor{option-perf-report}
3281 @opindex ---perf-report
3282 @opindex perf-report
3283 @item -p, --perf-report, @code{%option perf-report}
3284 generates a performance report to @file{stderr}. The report consists of
3285 comments regarding features of the @code{flex} input file which will
3286 cause a serious loss of performance in the resulting scanner. If you
3287 give the flag twice, you will also get comments regarding features that
3288 lead to minor performance losses.
3290 Note that the use of @code{REJECT}, and
3291 variable trailing context (@pxref{Limitations}) entails a substantial
3292 performance penalty; use of @code{yymore()}, the @samp{^} operator, and
3293 the @samp{--interactive} flag entail minor performance penalties.
3297 @anchor{option-nodefault}
3299 @opindex ---nodefault
3301 @item -s, --nodefault, @code{%option nodefault}
3302 causes the @emph{default rule} (that unmatched scanner input is echoed
3303 to @file{stdout)} to be suppressed. If the scanner encounters input
3304 that does not match any of its rules, it aborts with an error. This
3305 option is useful for finding holes in a scanner's rule set.
3309 @anchor{option-trace}
3313 @item -T, --trace, @code{%option trace}
3314 makes @code{flex} run in @dfn{trace} mode. It will generate a lot of
3315 messages to @file{stderr} concerning the form of the input and the
3316 resultant non-deterministic and deterministic finite automata. This
3317 option is mostly for use in maintaining @code{flex}.
3321 @anchor{option-nowarn}
3325 @item -w, --nowarn, @code{%option nowarn}
3326 suppresses warning messages.
3330 @anchor{option-verbose}
3334 @item -v, --verbose, @code{%option verbose}
3335 specifies that @code{flex} should write to @file{stderr} a summary of
3336 statistics regarding the scanner it generates. Most of the statistics
3337 are meaningless to the casual @code{flex} user, but the first line
3338 identifies the version of @code{flex} (same as reported by @samp{--version}),
3339 and the next line the flags used when generating the scanner, including
3340 those that are on by default.
3344 @anchor{option-warn}
3347 @item --warn, @code{%option warn}
3348 warn about certain things. In particular, if the default rule can be
3349 matched but no default rule has been given, the flex will warn you.
3350 We recommend using this option always.
3354 @node Miscellaneous Options, , Debugging Options, Scanner Options
3355 @section Miscellaneous Options
3360 A do-nothing option included for POSIX compliance.
3364 @item -h, -?, --help
3365 generates a ``help'' summary of @code{flex}'s options to @file{stdout}
3370 Another do-nothing option included for
3376 prints the version number to @file{stdout} and exits.
3381 @node Performance, Cxx, Scanner Options, Top
3382 @chapter Performance Considerations
3384 @cindex performance, considerations
3385 The main design goal of @code{flex} is that it generate high-performance
3386 scanners. It has been optimized for dealing well with large sets of
3387 rules. Aside from the effects on scanner speed of the table compression
3388 @samp{-C} options outlined above, there are a number of options/actions
3389 which degrade performance. These are, from most expensive to least:
3391 @cindex REJECT, performance costs
3392 @cindex yylineno, performance costs
3393 @cindex trailing context, performance costs
3397 arbitrary trailing context
3399 pattern sets that require backing up
3404 %option always-interactive
3406 @samp{^} beginning-of-line operator
3411 with the first two all being quite expensive and the last two being
3412 quite cheap. Note also that @code{unput()} is implemented as a routine
3413 call that potentially does quite a bit of work, while @code{yyless()} is
3414 a quite-cheap macro. So if you are just putting back some excess text
3415 you scanned, use @code{yyless()}.
3417 @code{REJECT} should be avoided at all costs when performance is
3418 important. It is a particularly expensive option.
3420 There is one case when @code{%option yylineno} can be expensive. That is when
3421 your patterns match long tokens that could @emph{possibly} contain a newline
3422 character. There is no performance penalty for rules that can not possibly
3423 match newlines, since flex does not need to check them for newlines. In
3424 general, you should avoid rules such as @code{[^f]+}, which match very long
3425 tokens, including newlines, and may possibly match your entire file! A better
3426 approach is to separate @code{[^f]+} into two rules:
3437 The above scanner does not incur a performance penalty.
3439 @cindex patterns, tuning for performance
3440 @cindex performance, backing up
3441 @cindex backing up, example of eliminating
3442 Getting rid of backing up is messy and often may be an enormous amount
3443 of work for a complicated scanner. In principal, one begins by using
3444 the @samp{-b} flag to generate a @file{lex.backup} file. For example,
3447 @cindex backing up, eliminating
3451 foo return TOK_KEYWORD;
3452 foobar return TOK_KEYWORD;
3456 the file looks like:
3460 State #6 is non-accepting -
3461 associated rule line numbers:
3463 out-transitions: [ o ]
3464 jam-transitions: EOF [ \001-n p-\177 ]
3466 State #8 is non-accepting -
3467 associated rule line numbers:
3469 out-transitions: [ a ]
3470 jam-transitions: EOF [ \001-` b-\177 ]
3472 State #9 is non-accepting -
3473 associated rule line numbers:
3475 out-transitions: [ r ]
3476 jam-transitions: EOF [ \001-q s-\177 ]
3478 Compressed tables always back up.
3482 The first few lines tell us that there's a scanner state in which it can
3483 make a transition on an 'o' but not on any other character, and that in
3484 that state the currently scanned text does not match any rule. The
3485 state occurs when trying to match the rules found at lines 2 and 3 in
3486 the input file. If the scanner is in that state and then reads
3487 something other than an 'o', it will have to back up to find a rule
3488 which is matched. With a bit of headscratching one can see that this
3489 must be the state it's in when it has seen @samp{fo}. When this has
3490 happened, if anything other than another @samp{o} is seen, the scanner
3491 will have to back up to simply match the @samp{f} (by the default rule).
3493 The comment regarding State #8 indicates there's a problem when
3494 @samp{foob} has been scanned. Indeed, on any character other than an
3495 @samp{a}, the scanner will have to back up to accept "foo". Similarly,
3496 the comment for State #9 concerns when @samp{fooba} has been scanned and
3497 an @samp{r} does not follow.
3499 The final comment reminds us that there's no point going to all the
3500 trouble of removing backing up from the rules unless we're using
3501 @samp{-Cf} or @samp{-CF}, since there's no performance gain doing so
3502 with compressed scanners.
3504 @cindex error rules, to eliminate backing up
3505 The way to remove the backing up is to add ``error'' rules:
3507 @cindex backing up, eliminating by adding error rules
3511 foo return TOK_KEYWORD;
3512 foobar return TOK_KEYWORD;
3517 /* false alarm, not really a keyword */
3523 Eliminating backing up among a list of keywords can also be done using a
3526 @cindex backing up, eliminating with catch-all rule
3530 foo return TOK_KEYWORD;
3531 foobar return TOK_KEYWORD;
3533 [a-z]+ return TOK_ID;
3537 This is usually the best solution when appropriate.
3539 Backing up messages tend to cascade. With a complicated set of rules
3540 it's not uncommon to get hundreds of messages. If one can decipher
3541 them, though, it often only takes a dozen or so rules to eliminate the
3542 backing up (though it's easy to make a mistake and have an error rule
3543 accidentally match a valid token. A possible future @code{flex} feature
3544 will be to automatically add rules to eliminate backing up).
3546 It's important to keep in mind that you gain the benefits of eliminating
3547 backing up only if you eliminate @emph{every} instance of backing up.
3548 Leaving just one means you gain nothing.
3550 @emph{Variable} trailing context (where both the leading and trailing
3551 parts do not have a fixed length) entails almost the same performance
3552 loss as @code{REJECT} (i.e., substantial). So when possible a rule
3555 @cindex trailing context, variable length
3559 mouse|rat/(cat|dog) run();
3568 mouse/cat|dog run();
3578 mouse|rat/cat run();
3579 mouse|rat/dog run();
3583 Note that here the special '|' action does @emph{not} provide any
3584 savings, and can even make things worse (@pxref{Limitations}).
3586 Another area where the user can increase a scanner's performance (and
3587 one that's easier to implement) arises from the fact that the longer the
3588 tokens matched, the faster the scanner will run. This is because with
3589 long tokens the processing of most input characters takes place in the
3590 (short) inner scanning loop, and does not often have to go through the
3591 additional work of setting up the scanning environment (e.g.,
3592 @code{yytext}) for the action. Recall the scanner for C comments:
3594 @cindex performance optimization, matching longer tokens
3601 "/*" BEGIN(comment);
3604 <comment>"*"+[^*/\n]*
3605 <comment>\n ++line_num;
3606 <comment>"*"+"/" BEGIN(INITIAL);
3610 This could be sped up by writing it as:
3618 "/*" BEGIN(comment);
3621 <comment>[^*\n]*\n ++line_num;
3622 <comment>"*"+[^*/\n]*
3623 <comment>"*"+[^*/\n]*\n ++line_num;
3624 <comment>"*"+"/" BEGIN(INITIAL);
3628 Now instead of each newline requiring the processing of another action,
3629 recognizing the newlines is distributed over the other rules to keep the
3630 matched text as long as possible. Note that @emph{adding} rules does
3631 @emph{not} slow down the scanner! The speed of the scanner is
3632 independent of the number of rules or (modulo the considerations given
3633 at the beginning of this section) how complicated the rules are with
3634 regard to operators such as @samp{*} and @samp{|}.
3636 @cindex keywords, for performance
3637 @cindex performance, using keywords
3638 A final example in speeding up a scanner: suppose you want to scan
3639 through a file containing identifiers and keywords, one per line
3640 and with no other extraneous characters, and recognize all the
3641 keywords. A natural first approach is:
3643 @cindex performance optimization, recognizing keywords
3652 while /* it's a keyword */
3654 .|\n /* it's not a keyword */
3658 To eliminate the back-tracking, introduce a catch-all rule:
3668 while /* it's a keyword */
3671 .|\n /* it's not a keyword */
3675 Now, if it's guaranteed that there's exactly one word per line, then we
3676 can reduce the total number of matches by a half by merging in the
3677 recognition of newlines with that of the other tokens:
3687 while\n /* it's a keyword */
3690 .|\n /* it's not a keyword */
3694 One has to be careful here, as we have now reintroduced backing up
3695 into the scanner. In particular, while
3697 know that there will never be any characters in the input stream
3698 other than letters or newlines,
3700 can't figure this out, and it will plan for possibly needing to back up
3701 when it has scanned a token like @samp{auto} and then the next character
3702 is something other than a newline or a letter. Previously it would
3703 then just match the @samp{auto} rule and be done, but now it has no @samp{auto}
3704 rule, only a @samp{auto\n} rule. To eliminate the possibility of backing up,
3705 we could either duplicate all rules but without final newlines, or,
3706 since we never expect to encounter such an input and therefore don't
3707 how it's classified, we can introduce one more catch-all rule, this
3708 one which doesn't include a newline:
3718 while\n /* it's a keyword */
3722 .|\n /* it's not a keyword */
3726 Compiled with @samp{-Cf}, this is about as fast as one can get a
3727 @code{flex} scanner to go for this particular problem.
3729 A final note: @code{flex} is slow when matching @code{NUL}s,
3730 particularly when a token contains multiple @code{NUL}s. It's best to
3731 write rules which match @emph{short} amounts of text if it's anticipated
3732 that the text will often include @code{NUL}s.
3734 Another final note regarding performance: as mentioned in
3735 @ref{Matching}, dynamically resizing @code{yytext} to accommodate huge
3736 tokens is a slow process because it presently requires that the (huge)
3737 token be rescanned from the beginning. Thus if performance is vital,
3738 you should attempt to match ``large'' quantities of text but not
3739 ``huge'' quantities, where the cutoff between the two is at about 8K
3740 characters per token.
3742 @node Cxx, Reentrant, Performance, Top
3743 @chapter Generating C++ Scanners
3745 @cindex c++, experimental form of scanner class
3746 @cindex experimental form of c++ scanner class
3747 @strong{IMPORTANT}: the present form of the scanning class is @emph{experimental}
3748 and may change considerably between major releases.
3751 @cindex member functions, C++
3752 @cindex methods, c++
3753 @code{flex} provides two different ways to generate scanners for use
3754 with C++. The first way is to simply compile a scanner generated by
3755 @code{flex} using a C++ compiler instead of a C compiler. You should
3756 not encounter any compilation errors (@pxref{Reporting Bugs}). You can
3757 then use C++ code in your rule actions instead of C code. Note that the
3758 default input source for your scanner remains @file{yyin}, and default
3759 echoing is still done to @file{yyout}. Both of these remain @code{FILE
3760 *} variables and not C++ @emph{streams}.
3762 You can also use @code{flex} to generate a C++ scanner class, using the
3763 @samp{-+} option (or, equivalently, @code{%option c++)}, which is
3764 automatically specified if the name of the @code{flex} executable ends
3765 in a '+', such as @code{flex++}. When using this option, @code{flex}
3766 defaults to generating the scanner to the file @file{lex.yy.cc} instead
3767 of @file{lex.yy.c}. The generated scanner includes the header file
3768 @file{FlexLexer.h}, which defines the interface to two C++ classes.
3772 provides an abstract base class defining the general scanner class
3773 interface. It provides the following member functions:
3776 @findex YYText (C++ only)
3777 @item const char* YYText()
3778 returns the text of the most recently matched token, the equivalent of
3781 @findex YYLeng (C++ only)
3783 returns the length of the most recently matched token, the equivalent of
3786 @findex lineno (C++ only)
3787 @item int lineno() const
3788 returns the current input line number (see @code{%option yylineno)}, or
3789 @code{1} if @code{%option yylineno} was not used.
3791 @findex set_debug (C++ only)
3792 @item void set_debug( int flag )
3793 sets the debugging flag for the scanner, equivalent to assigning to
3794 @code{yy_flex_debug} (@pxref{Scanner Options}). Note that you must build
3795 the scanner using @code{%option debug} to include debugging information
3798 @findex debug (C++ only)
3799 @item int debug() const
3800 returns the current setting of the debugging flag.
3803 Also provided are member functions equivalent to
3804 @code{yy_switch_to_buffer()}, @code{yy_create_buffer()} (though the
3805 first argument is an @code{istream*} object pointer and not a
3806 @code{FILE*)}, @code{yy_flush_buffer()}, @code{yy_delete_buffer()}, and
3807 @code{yyrestart()} (again, the first argument is a @code{istream*}
3810 @tindex yyFlexLexer (C++ only)
3811 @tindex FlexLexer (C++ only)
3812 The second class defined in @file{FlexLexer.h} is @code{yyFlexLexer},
3813 which is derived from @code{FlexLexer}. It defines the following
3814 additional member functions:
3817 @findex yyFlexLexer constructor (C++ only)
3818 @item yyFlexLexer( istream* arg_yyin = 0, ostream* arg_yyout = 0 )
3819 constructs a @code{yyFlexLexer} object using the given streams for input
3820 and output. If not specified, the streams default to @code{cin} and
3821 @code{cout}, respectively.
3823 @findex yylex (C++ version)
3824 @item virtual int yylex()
3825 performs the same role is @code{yylex()} does for ordinary @code{flex}
3826 scanners: it scans the input stream, consuming tokens, until a rule's
3827 action returns a value. If you derive a subclass @code{S} from
3828 @code{yyFlexLexer} and want to access the member functions and variables
3829 of @code{S} inside @code{yylex()}, then you need to use @code{%option
3830 yyclass="S"} to inform @code{flex} that you will be using that subclass
3831 instead of @code{yyFlexLexer}. In this case, rather than generating
3832 @code{yyFlexLexer::yylex()}, @code{flex} generates @code{S::yylex()}
3833 (and also generates a dummy @code{yyFlexLexer::yylex()} that calls
3834 @code{yyFlexLexer::LexerError()} if called).
3836 @findex switch_streams (C++ only)
3837 @item virtual void switch_streams(istream* new_in = 0, ostream* new_out = 0)
3838 reassigns @code{yyin} to @code{new_in} (if non-null) and @code{yyout} to
3839 @code{new_out} (if non-null), deleting the previous input buffer if
3840 @code{yyin} is reassigned.
3842 @item int yylex( istream* new_in, ostream* new_out = 0 )
3843 first switches the input streams via @code{switch_streams( new_in,
3844 new_out )} and then returns the value of @code{yylex()}.
3847 In addition, @code{yyFlexLexer} defines the following protected virtual
3848 functions which you can redefine in derived classes to tailor the
3852 @findex LexerInput (C++ only)
3853 @item virtual int LexerInput( char* buf, int max_size )
3854 reads up to @code{max_size} characters into @code{buf} and returns the
3855 number of characters read. To indicate end-of-input, return 0
3856 characters. Note that @code{interactive} scanners (see the @samp{-B}
3857 and @samp{-I} flags in @ref{Scanner Options}) define the macro
3858 @code{YY_INTERACTIVE}. If you redefine @code{LexerInput()} and need to
3859 take different actions depending on whether or not the scanner might be
3860 scanning an interactive input source, you can test for the presence of
3861 this name via @code{#ifdef} statements.
3863 @findex LexerOutput (C++ only)
3864 @item virtual void LexerOutput( const char* buf, int size )
3865 writes out @code{size} characters from the buffer @code{buf}, which, while
3866 @code{NUL}-terminated, may also contain internal @code{NUL}s if the
3867 scanner's rules can match text with @code{NUL}s in them.
3869 @cindex error reporting, in C++
3870 @findex LexerError (C++ only)
3871 @item virtual void LexerError( const char* msg )
3872 reports a fatal error message. The default version of this function
3873 writes the message to the stream @code{cerr} and exits.
3876 Note that a @code{yyFlexLexer} object contains its @emph{entire}
3877 scanning state. Thus you can use such objects to create reentrant
3878 scanners, but see also @ref{Reentrant}. You can instantiate multiple
3879 instances of the same @code{yyFlexLexer} class, and you can also combine
3880 multiple C++ scanner classes together in the same program using the
3881 @samp{-P} option discussed above.
3883 Finally, note that the @code{%array} feature is not available to C++
3884 scanner classes; you must use @code{%pointer} (the default).
3886 Here is an example of a simple C++ scanner:
3888 @cindex C++ scanners, use of
3891 // An example of using the flex C++ scanner class.
3903 name ({alpha}|{dig}|\$)({alpha}|{dig}|[_.\-/$])*
3904 num1 [-+]?{dig}+\.?([eE][-+]?{dig}+)?
3905 num2 [-+]?{dig}*\.{dig}+([eE][-+]?{dig}+)?
3906 number {num1}|{num2}
3910 {ws} /* skip blanks and tabs */
3915 while((c = yyinput()) != 0)
3920 else if(c == @samp{*})
3922 if((c = yyinput()) == '/')
3930 {number} cout "number " YYText() '\n';
3934 {name} cout "name " YYText() '\n';
3936 {string} cout "string " YYText() '\n';
3940 int main( int /* argc */, char** /* argv */ )
3942 @code{flex}Lexer* lexer = new yyFlexLexer;
3943 while(lexer->yylex() != 0)
3950 @cindex C++, multiple different scanners
3951 If you want to create multiple (different) lexer classes, you use the
3952 @samp{-P} flag (or the @code{prefix=} option) to rename each
3953 @code{yyFlexLexer} to some other @samp{xxFlexLexer}. You then can
3954 include @file{<FlexLexer.h>} in your other sources once per lexer class,
3955 first renaming @code{yyFlexLexer} as follows:
3957 @cindex include files, with C++
3958 @cindex header files, with C++
3959 @cindex C++ scanners, including multiple scanners
3963 #define yyFlexLexer xxFlexLexer
3964 #include <FlexLexer.h>
3967 #define yyFlexLexer zzFlexLexer
3968 #include <FlexLexer.h>
3972 if, for example, you used @code{%option prefix="xx"} for one of your
3973 scanners and @code{%option prefix="zz"} for the other.
3975 @node Reentrant, Lex and Posix, Cxx, Top
3976 @chapter Reentrant C Scanners
3978 @cindex reentrant, explanation
3979 @code{flex} has the ability to generate a reentrant C scanner. This is
3980 accomplished by specifying @code{%option reentrant} (@samp{-R}) The generated
3981 scanner is both portable, and safe to use in one or more separate threads of
3982 control. The most common use for reentrant scanners is from within
3983 multi-threaded applications. Any thread may create and execute a reentrant
3984 @code{flex} scanner without the need for synchronization with other threads.
3988 * Reentrant Overview::
3989 * Reentrant Example::
3990 * Reentrant Detail::
3991 * Reentrant Functions::
3994 @node Reentrant Uses, Reentrant Overview, Reentrant, Reentrant
3995 @section Uses for Reentrant Scanners
3997 However, there are other uses for a reentrant scanner. For example, you
3998 could scan two or more files simultaneously to implement a @code{diff} at
3999 the token level (i.e., instead of at the character level):
4001 @cindex reentrant scanners, multiple interleaved scanners
4004 /* Example of maintaining more than one active scanner. */
4009 tok1 = yylex( scanner_1 );
4010 tok2 = yylex( scanner_2 );
4013 printf("Files are different.");
4015 } while ( tok1 && tok2 );
4019 Another use for a reentrant scanner is recursion.
4020 (Note that a recursive scanner can also be created using a non-reentrant scanner and
4021 buffer states. @xref{Multiple Input Buffers}.)
4023 The following crude scanner supports the @samp{eval} command by invoking
4024 another instance of itself.
4026 @cindex reentrant scanners, recursive invocation
4029 /* Example of recursive invocation. */
4036 YY_BUFFER_STATE buf;
4038 yylex_init( &scanner );
4039 yytext[yyleng-1] = ' ';
4041 buf = yy_scan_string( yytext + 5, scanner );
4044 yy_delete_buffer(buf,scanner);
4045 yylex_destroy( scanner );
4052 @node Reentrant Overview, Reentrant Example, Reentrant Uses, Reentrant
4053 @section An Overview of the Reentrant API
4055 @cindex reentrant, API explanation
4056 The API for reentrant scanners is different than for non-reentrant
4057 scanners. Here is a quick overview of the API:
4060 @code{%option reentrant} must be specified.
4063 All functions take one additional argument: @code{yyscanner}
4066 All global variables are replaced by their macro equivalents.
4067 (We tell you this because it may be important to you during debugging.)
4070 @code{yylex_init} and @code{yylex_destroy} must be called before and
4071 after @code{yylex}, respectively.
4074 Accessor methods (get/set functions) provide access to common
4075 @code{flex} variables.
4078 User-specific data can be stored in @code{yyextra}.
4081 @node Reentrant Example, Reentrant Detail, Reentrant Overview, Reentrant
4082 @section Reentrant Example
4084 First, an example of a reentrant scanner:
4085 @cindex reentrant, example of
4088 /* This scanner prints "//" comments. */
4090 %option reentrant stack noyywrap
4095 "//" yy_push_state( COMMENT, yyscanner);
4098 <COMMENT>\n yy_pop_state( yyscanner );
4099 <COMMENT>[^\n]+ fprintf( yyout, "%s\n", yytext);
4103 int main ( int argc, char * argv[] )
4107 yylex_init ( &scanner );
4109 yylex_destroy ( scanner );
4115 @node Reentrant Detail, Reentrant Functions, Reentrant Example, Reentrant
4116 @section The Reentrant API in Detail
4118 Here are the things you need to do or know to use the reentrant C API of
4122 * Specify Reentrant::
4123 * Extra Reentrant Argument::
4124 * Global Replacement::
4125 * Init and Destroy Functions::
4126 * Accessor Methods::
4131 @node Specify Reentrant, Extra Reentrant Argument, Reentrant Detail, Reentrant Detail
4132 @subsection Declaring a Scanner As Reentrant
4134 %option reentrant (--reentrant) must be specified.
4136 Notice that @code{%option reentrant} is specified in the above example
4137 (@pxref{Reentrant Example}. Had this option not been specified,
4138 @code{flex} would have happily generated a non-reentrant scanner without
4139 complaining. You may explicitly specify @code{%option noreentrant}, if
4140 you do @emph{not} want a reentrant scanner, although it is not
4141 necessary. The default is to generate a non-reentrant scanner.
4143 @node Extra Reentrant Argument, Global Replacement, Specify Reentrant, Reentrant Detail
4144 @subsection The Extra Argument
4146 @cindex reentrant, calling functions
4147 @vindex yyscanner (reentrant only)
4148 All functions take one additional argument: @code{yyscanner}.
4150 Notice that the calls to @code{yy_push_state} and @code{yy_pop_state}
4151 both have an argument, @code{yyscanner} , that is not present in a
4152 non-reentrant scanner. Here are the declarations of
4153 @code{yy_push_state} and @code{yy_pop_state} in the reentrant scanner:
4157 static void yy_push_state ( int new_state , yyscan_t yyscanner ) ;
4158 static void yy_pop_state ( yyscan_t yyscanner ) ;
4162 Notice that the argument @code{yyscanner} appears in the declaration of
4163 both functions. In fact, all @code{flex} functions in a reentrant
4164 scanner have this additional argument. It is always the last argument
4165 in the argument list, it is always of type @code{yyscan_t} (which is
4166 typedef'd to @code{void *}) and it is
4167 always named @code{yyscanner}. As you may have guessed,
4168 @code{yyscanner} is a pointer to an opaque data structure encapsulating
4169 the current state of the scanner. For a list of function declarations,
4170 see @ref{Reentrant Functions}. Note that preprocessor macros, such as
4171 @code{BEGIN}, @code{ECHO}, and @code{REJECT}, do not take this
4172 additional argument.
4174 @node Global Replacement, Init and Destroy Functions, Extra Reentrant Argument, Reentrant Detail
4175 @subsection Global Variables Replaced By Macros
4177 @cindex reentrant, accessing flex variables
4178 All global variables in traditional flex have been replaced by macro equivalents.
4180 Note that in the above example, @code{yyout} and @code{yytext} are
4181 not plain variables. These are macros that will expand to their equivalent lvalue.
4182 All of the familiar @code{flex} globals have been replaced by their macro
4183 equivalents. In particular, @code{yytext}, @code{yyleng}, @code{yylineno},
4184 @code{yyin}, @code{yyout}, @code{yyextra}, @code{yylval}, and @code{yylloc}
4185 are macros. You may safely use these macros in actions as if they were plain
4186 variables. We only tell you this so you don't expect to link to these variables
4187 externally. Currently, each macro expands to a member of an internal struct, e.g.,
4191 #define yytext (((struct yyguts_t*)yyscanner)->yytext_r)
4195 One important thing to remember about
4199 is not a global variable in a reentrant
4200 scanner, you can not access it directly from outside an action or from
4201 other functions. You must use an accessor method, e.g.,
4203 to accomplish this. (See below).
4205 @node Init and Destroy Functions, Accessor Methods, Global Replacement, Reentrant Detail
4206 @subsection Init and Destroy Functions
4208 @cindex memory, considerations for reentrant scanners
4209 @cindex reentrant, initialization
4211 @findex yylex_destroy
4213 @code{yylex_init} and @code{yylex_destroy} must be called before and
4214 after @code{yylex}, respectively.
4218 int yylex_init ( yyscan_t * ptr_yy_globals ) ;
4219 int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t * ptr_yy_globals ) ;
4220 int yylex ( yyscan_t yyscanner ) ;
4221 int yylex_destroy ( yyscan_t yyscanner ) ;
4225 The function @code{yylex_init} must be called before calling any other
4226 function. The argument to @code{yylex_init} is the address of an
4227 uninitialized pointer to be filled in by @code{yylex_init}, overwriting
4228 any previous contents. The function @code{yylex_init_extra} may be used
4229 instead, taking as its first argument a variable of type @code{YY_EXTRA_TYPE}.
4230 See the section on yyextra, below, for more details.
4232 The value stored in @code{ptr_yy_globals} should
4233 thereafter be passed to @code{yylex} and @code{yylex_destroy}. Flex
4234 does not save the argument passed to @code{yylex_init}, so it is safe to
4235 pass the address of a local pointer to @code{yylex_init} so long as it remains
4236 in scope for the duration of all calls to the scanner, up to and including
4237 the call to @code{yylex_destroy}.
4240 @code{yylex} should be familiar to you by now. The reentrant version
4241 takes one argument, which is the value returned (via an argument) by
4242 @code{yylex_init}. Otherwise, it behaves the same as the non-reentrant
4243 version of @code{yylex}.
4245 Both @code{yylex_init} and @code{yylex_init_extra} returns 0 (zero) on success,
4246 or non-zero on failure, in which case errno is set to one of the following values:
4250 Memory allocation error. @xref{memory-management}.
4256 The function @code{yylex_destroy} should be
4257 called to free resources used by the scanner. After @code{yylex_destroy}
4258 is called, the contents of @code{yyscanner} should not be used. Of
4259 course, there is no need to destroy a scanner if you plan to reuse it.
4260 A @code{flex} scanner (both reentrant and non-reentrant) may be
4261 restarted by calling @code{yyrestart}.
4263 Below is an example of a program that creates a scanner, uses it, then destroys
4273 yylex_init(&scanner);
4275 while ((tok=yylex()) > 0)
4276 printf("tok=%d yytext=%s\n", tok, yyget_text(scanner));
4278 yylex_destroy(scanner);
4284 @node Accessor Methods, Extra Data, Init and Destroy Functions, Reentrant Detail
4285 @subsection Accessing Variables with Reentrant Scanners
4287 @cindex reentrant, accessor functions
4288 Accessor methods (get/set functions) provide access to common
4289 @code{flex} variables.
4291 Many scanners that you build will be part of a larger project. Portions
4292 of your project will need access to @code{flex} values, such as
4293 @code{yytext}. In a non-reentrant scanner, these values are global, so
4294 there is no problem accessing them. However, in a reentrant scanner, there are no
4295 global @code{flex} values. You can not access them directly. Instead,
4296 you must access @code{flex} values using accessor methods (get/set
4297 functions). Each accessor method is named @code{yyget_NAME} or
4298 @code{yyset_NAME}, where @code{NAME} is the name of the @code{flex}
4299 variable you want. For example:
4301 @cindex accessor functions, use of
4304 /* Set the last character of yytext to NULL. */
4305 void chop ( yyscan_t scanner )
4307 int len = yyget_leng( scanner );
4308 yyget_text( scanner )[len - 1] = '\0';
4313 The above code may be called from within an action like this:
4318 .+\n { chop( yyscanner );}
4322 You may find that @code{%option header-file} is particularly useful for generating
4323 prototypes of all the accessor functions. @xref{option-header}.
4325 @node Extra Data, About yyscan_t, Accessor Methods, Reentrant Detail
4326 @subsection Extra Data
4328 @cindex reentrant, extra data
4330 User-specific data can be stored in @code{yyextra}.
4332 In a reentrant scanner, it is unwise to use global variables to
4333 communicate with or maintain state between different pieces of your program.
4334 However, you may need access to external data or invoke external functions
4335 from within the scanner actions.
4336 Likewise, you may need to pass information to your scanner
4337 (e.g., open file descriptors, or database connections).
4338 In a non-reentrant scanner, the only way to do this would be through the
4339 use of global variables.
4340 @code{Flex} allows you to store arbitrary, ``extra'' data in a scanner.
4341 This data is accessible through the accessor methods
4342 @code{yyget_extra} and @code{yyset_extra}
4343 from outside the scanner, and through the shortcut macro
4345 from within the scanner itself. They are defined as follows:
4347 @tindex YY_EXTRA_TYPE (reentrant only)
4352 #define YY_EXTRA_TYPE void*
4353 YY_EXTRA_TYPE yyget_extra ( yyscan_t scanner );
4354 void yyset_extra ( YY_EXTRA_TYPE arbitrary_data , yyscan_t scanner);
4358 In addition, an extra form of @code{yylex_init} is provided,
4359 @code{yylex_init_extra}. This function is provided so that the yyextra value can
4360 be accessed from within the very first yyalloc, used to allocate
4363 By default, @code{YY_EXTRA_TYPE} is defined as type @code{void *}. You
4364 may redefine this type using @code{%option extra-type="your_type"} in
4367 @cindex YY_EXTRA_TYPE, defining your own type
4370 /* An example of overriding YY_EXTRA_TYPE. */
4372 #include <sys/stat.h>
4376 %option extra-type="struct stat *"
4379 __filesize__ printf( "%ld", yyextra->st_size );
4380 __lastmod__ printf( "%ld", yyextra->st_mtime );
4382 void scan_file( char* filename )
4388 in = fopen( filename, "r" );
4389 stat( filename, &buf );
4391 yylex_init_extra( buf, &scanner );
4392 yyset_in( in, scanner );
4394 yylex_destroy( scanner );
4402 @node About yyscan_t, , Extra Data, Reentrant Detail
4403 @subsection About yyscan_t
4405 @tindex yyscan_t (reentrant only)
4406 @code{yyscan_t} is defined as:
4410 typedef void* yyscan_t;
4414 It is initialized by @code{yylex_init()} to point to
4415 an internal structure. You should never access this value
4416 directly. In particular, you should never attempt to free it
4417 (use @code{yylex_destroy()} instead.)
4419 @node Reentrant Functions, , Reentrant Detail, Reentrant
4420 @section Functions and Macros Available in Reentrant C Scanners
4422 The following Functions are available in a reentrant scanner:
4428 @findex yyget_lineno
4431 @findex yyset_lineno
4439 char *yyget_text ( yyscan_t scanner );
4440 int yyget_leng ( yyscan_t scanner );
4441 FILE *yyget_in ( yyscan_t scanner );
4442 FILE *yyget_out ( yyscan_t scanner );
4443 int yyget_lineno ( yyscan_t scanner );
4444 YY_EXTRA_TYPE yyget_extra ( yyscan_t scanner );
4445 int yyget_debug ( yyscan_t scanner );
4447 void yyset_debug ( int flag, yyscan_t scanner );
4448 void yyset_in ( FILE * in_str , yyscan_t scanner );
4449 void yyset_out ( FILE * out_str , yyscan_t scanner );
4450 void yyset_lineno ( int line_number , yyscan_t scanner );
4451 void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t scanner );
4455 There are no ``set'' functions for yytext and yyleng. This is intentional.
4457 The following Macro shortcuts are available in actions in a reentrant
4472 @cindex yylineno, in a reentrant scanner
4473 In a reentrant C scanner, support for yylineno is always present
4474 (i.e., you may access yylineno), but the value is never modified by
4475 @code{flex} unless @code{%option yylineno} is enabled. This is to allow
4476 the user to maintain the line count independently of @code{flex}.
4478 @anchor{bison-functions}
4479 The following functions and macros are made available when @code{%option
4480 bison-bridge} (@samp{--bison-bridge}) is specified:
4484 YYSTYPE * yyget_lval ( yyscan_t scanner );
4485 void yyset_lval ( YYSTYPE * yylvalp , yyscan_t scanner );
4490 The following functions and macros are made available
4491 when @code{%option bison-locations} (@samp{--bison-locations}) is specified:
4495 YYLTYPE *yyget_lloc ( yyscan_t scanner );
4496 void yyset_lloc ( YYLTYPE * yyllocp , yyscan_t scanner );
4501 Support for yylval assumes that @code{YYSTYPE} is a valid type. Support for
4502 yylloc assumes that @code{YYSLYPE} is a valid type. Typically, these types are
4503 generated by @code{bison}, and are included in section 1 of the @code{flex}
4506 @node Lex and Posix, Memory Management, Reentrant, Top
4507 @chapter Incompatibilities with Lex and Posix
4509 @cindex POSIX and lex
4510 @cindex lex (traditional) and POSIX
4512 @code{flex} is a rewrite of the AT&T Unix @emph{lex} tool (the two
4513 implementations do not share any code, though), with some extensions and
4514 incompatibilities, both of which are of concern to those who wish to
4515 write scanners acceptable to both implementations. @code{flex} is fully
4516 compliant with the POSIX @code{lex} specification, except that when
4517 using @code{%pointer} (the default), a call to @code{unput()} destroys
4518 the contents of @code{yytext}, which is counter to the POSIX
4519 specification. In this section we discuss all of the known areas of
4520 incompatibility between @code{flex}, AT&T @code{lex}, and the POSIX
4521 specification. @code{flex}'s @samp{-l} option turns on maximum
4522 compatibility with the original AT&T @code{lex} implementation, at the
4523 cost of a major loss in the generated scanner's performance. We note
4524 below which incompatibilities can be overcome using the @samp{-l}
4525 option. @code{flex} is fully compatible with @code{lex} with the
4526 following exceptions:
4530 The undocumented @code{lex} scanner internal variable @code{yylineno} is
4531 not supported unless @samp{-l} or @code{%option yylineno} is used.
4534 @code{yylineno} should be maintained on a per-buffer basis, rather than
4535 a per-scanner (single global variable) basis.
4538 @code{yylineno} is not part of the POSIX specification.
4541 The @code{input()} routine is not redefinable, though it may be called
4542 to read characters following whatever has been matched by a rule. If
4543 @code{input()} encounters an end-of-file the normal @code{yywrap()}
4544 processing is done. A ``real'' end-of-file is returned by
4545 @code{input()} as @code{EOF}.
4548 Input is instead controlled by defining the @code{YY_INPUT()} macro.
4551 The @code{flex} restriction that @code{input()} cannot be redefined is
4552 in accordance with the POSIX specification, which simply does not
4553 specify any way of controlling the scanner's input other than by making
4554 an initial assignment to @file{yyin}.
4557 The @code{unput()} routine is not redefinable. This restriction is in
4558 accordance with POSIX.
4561 @code{flex} scanners are not as reentrant as @code{lex} scanners. In
4562 particular, if you have an interactive scanner and an interrupt handler
4563 which long-jumps out of the scanner, and the scanner is subsequently
4564 called again, you may get the following message:
4566 @cindex error messages, end of buffer missed
4569 fatal @code{flex} scanner internal error--end of buffer missed
4573 To reenter the scanner, first use:
4575 @cindex restarting the scanner
4582 Note that this call will throw away any buffered input; usually this
4583 isn't a problem with an interactive scanner. @xref{Reentrant}, for
4584 @code{flex}'s reentrant API.
4587 Also note that @code{flex} C++ scanner classes
4589 reentrant, so if using C++ is an option for you, you should use
4590 them instead. @xref{Cxx}, and @ref{Reentrant} for details.
4593 @code{output()} is not supported. Output from the @b{ECHO} macro is
4594 done to the file-pointer @code{yyout} (default @file{stdout)}.
4597 @code{output()} is not part of the POSIX specification.
4600 @code{lex} does not support exclusive start conditions (%x), though they
4601 are in the POSIX specification.
4604 When definitions are expanded, @code{flex} encloses them in parentheses.
4605 With @code{lex}, the following:
4607 @cindex name definitions, not POSIX
4612 foo{NAME}? printf( "Found it\n" );
4617 will not match the string @samp{foo} because when the macro is expanded
4618 the rule is equivalent to @samp{foo[A-Z][A-Z0-9]*?} and the precedence
4619 is such that the @samp{?} is associated with @samp{[A-Z0-9]*}. With
4620 @code{flex}, the rule will be expanded to @samp{foo([A-Z][A-Z0-9]*)?}
4621 and so the string @samp{foo} will match.
4624 Note that if the definition begins with @samp{^} or ends with @samp{$}
4625 then it is @emph{not} expanded with parentheses, to allow these
4626 operators to appear in definitions without losing their special
4627 meanings. But the @samp{<s>}, @samp{/}, and @code{<<EOF>>} operators
4628 cannot be used in a @code{flex} definition.
4631 Using @samp{-l} results in the @code{lex} behavior of no parentheses
4632 around the definition.
4635 The POSIX specification is that the definition be enclosed in parentheses.
4638 Some implementations of @code{lex} allow a rule's action to begin on a
4639 separate line, if the rule's pattern has trailing whitespace:
4641 @cindex patterns and actions on different lines
4650 @code{flex} does not support this feature.
4653 The @code{lex} @code{%r} (generate a Ratfor scanner) option is not
4654 supported. It is not part of the POSIX specification.
4657 After a call to @code{unput()}, @emph{yytext} is undefined until the
4658 next token is matched, unless the scanner was built using @code{%array}.
4659 This is not the case with @code{lex} or the POSIX specification. The
4660 @samp{-l} option does away with this incompatibility.
4663 The precedence of the @samp{@{,@}} (numeric range) operator is
4664 different. The AT&T and POSIX specifications of @code{lex}
4665 interpret @samp{abc@{1,3@}} as match one, two,
4666 or three occurrences of @samp{abc}'', whereas @code{flex} interprets it
4667 as ``match @samp{ab} followed by one, two, or three occurrences of
4668 @samp{c}''. The @samp{-l} and @samp{--posix} options do away with this
4672 The precedence of the @samp{^} operator is different. @code{lex}
4673 interprets @samp{^foo|bar} as ``match either 'foo' at the beginning of a
4674 line, or 'bar' anywhere'', whereas @code{flex} interprets it as ``match
4675 either @samp{foo} or @samp{bar} if they come at the beginning of a
4676 line''. The latter is in agreement with the POSIX specification.
4679 The special table-size declarations such as @code{%a} supported by
4680 @code{lex} are not required by @code{flex} scanners.. @code{flex}
4683 The name @code{FLEX_SCANNER} is @code{#define}'d so scanners may be
4684 written for use with either @code{flex} or @code{lex}. Scanners also
4685 include @code{YY_FLEX_MAJOR_VERSION}, @code{YY_FLEX_MINOR_VERSION}
4686 and @code{YY_FLEX_SUBMINOR_VERSION}
4687 indicating which version of @code{flex} generated the scanner. For
4688 example, for the 2.5.22 release, these defines would be 2, 5 and 22
4689 respectively. If the version of @code{flex} being used is a beta
4690 version, then the symbol @code{FLEX_BETA} is defined.
4693 The symbols @samp{[[} and @samp{]]} in the code sections of the input
4694 may conflict with the m4 delimiters. @xref{M4 Dependency}.
4699 @cindex POSIX comp;compliance
4700 @cindex non-POSIX features of flex
4701 The following @code{flex} features are not included in @code{lex} or the
4702 POSIX specification:
4710 start condition scopes
4712 start condition stacks
4714 interactive/non-interactive scanners
4716 yy_scan_string() and friends
4720 yy_set_interactive()
4739 %@{@}'s around actions
4743 multiple actions on a line
4745 almost all of the @code{flex} command-line options
4748 The feature ``multiple actions on a line''
4749 refers to the fact that with @code{flex} you can put multiple actions on
4750 the same line, separated with semi-colons, while with @code{lex}, the
4755 foo handle_foo(); ++num_foos_seen;
4759 is (rather surprisingly) truncated to
4767 @code{flex} does not truncate the action. Actions that are not enclosed
4768 in braces are simply terminated at the end of the line.
4770 @node Memory Management, Serialized Tables, Lex and Posix, Top
4771 @chapter Memory Management
4773 @cindex memory management
4774 @anchor{memory-management}
4775 This chapter describes how flex handles dynamic memory, and how you can
4776 override the default behavior.
4779 * The Default Memory Management::
4780 * Overriding The Default Memory Management::
4781 * A Note About yytext And Memory::
4784 @node The Default Memory Management, Overriding The Default Memory Management, Memory Management, Memory Management
4785 @section The Default Memory Management
4787 Flex allocates dynamic memory during initialization, and once in a while from
4788 within a call to yylex(). Initialization takes place during the first call to
4789 yylex(). Thereafter, flex may reallocate more memory if it needs to enlarge a
4790 buffer. As of version 2.5.9 Flex will clean up all memory when you call @code{yylex_destroy}
4791 @xref{faq-memory-leak}.
4793 Flex allocates dynamic memory for four purposes, listed below @footnote{The
4794 quantities given here are approximate, and may vary due to host architecture,
4795 compiler configuration, or due to future enhancements to flex.}
4799 @item 16kB for the input buffer.
4800 Flex allocates memory for the character buffer used to perform pattern
4801 matching. Flex must read ahead from the input stream and store it in a large
4802 character buffer. This buffer is typically the largest chunk of dynamic memory
4803 flex consumes. This buffer will grow if necessary, doubling the size each time.
4804 Flex frees this memory when you call yylex_destroy(). The default size of this
4805 buffer (16384 bytes) is almost always too large. The ideal size for this
4806 buffer is the length of the longest token expected, in bytes, plus a little more. Flex will allocate a few
4807 extra bytes for housekeeping. Currently, to override the size of the input buffer
4808 you must @code{#define YY_BUF_SIZE} to whatever number of bytes you want. We don't plan
4809 to change this in the near future, but we reserve the right to do so if we ever add a more robust memory management
4812 @item 64kb for the REJECT state. This will only be allocated if you use REJECT.
4813 The size is the large enough to hold the same number of states as characters in the input buffer. If you override the size of the
4814 input buffer (via @code{YY_BUF_SIZE}), then you automatically override the size of this buffer as well.
4816 @item 100 bytes for the start condition stack.
4817 Flex allocates memory for the start condition stack. This is the stack used
4818 for pushing start states, i.e., with yy_push_state(). It will grow if
4819 necessary. Since the states are simply integers, this stack doesn't consume
4820 much memory. This stack is not present if @code{%option stack} is not
4821 specified. You will rarely need to tune this buffer. The ideal size for this
4822 stack is the maximum depth expected. The memory for this stack is
4823 automatically destroyed when you call yylex_destroy(). @xref{option-stack}.
4825 @item 40 bytes for each YY_BUFFER_STATE.
4826 Flex allocates memory for each YY_BUFFER_STATE. The buffer state itself
4827 is about 40 bytes, plus an additional large character buffer (described above.)
4828 The initial buffer state is created during initialization, and with each call
4829 to yy_create_buffer(). You can't tune the size of this, but you can tune the
4830 character buffer as described above. Any buffer state that you explicitly
4831 create by calling yy_create_buffer() is @emph{NOT} destroyed automatically. You
4832 must call yy_delete_buffer() to free the memory. The exception to this rule is
4833 that flex will delete the current buffer automatically when you call
4834 yylex_destroy(). If you delete the current buffer, be sure to set it to NULL.
4835 That way, flex will not try to delete the buffer a second time (possibly
4836 crashing your program!) At the time of this writing, flex does not provide a
4837 growable stack for the buffer states. You have to manage that yourself.
4838 @xref{Multiple Input Buffers}.
4840 @item 84 bytes for the reentrant scanner guts
4841 Flex allocates about 84 bytes for the reentrant scanner structure when
4842 you call yylex_init(). It is destroyed when the user calls yylex_destroy().
4847 @node Overriding The Default Memory Management, A Note About yytext And Memory, The Default Memory Management, Memory Management
4848 @section Overriding The Default Memory Management
4850 @cindex yyalloc, overriding
4851 @cindex yyrealloc, overriding
4852 @cindex yyfree, overriding
4854 Flex calls the functions @code{yyalloc}, @code{yyrealloc}, and @code{yyfree}
4855 when it needs to allocate or free memory. By default, these functions are
4856 wrappers around the standard C functions, @code{malloc}, @code{realloc}, and
4857 @code{free}, respectively. You can override the default implementations by telling
4858 flex that you will provide your own implementations.
4860 To override the default implementations, you must do two things:
4864 @item Suppress the default implementations by specifying one or more of the
4869 @item @code{%option noyyalloc}
4870 @item @code{%option noyyrealloc}
4871 @item @code{%option noyyfree}.
4874 @item Provide your own implementation of the following functions: @footnote{It
4875 is not necessary to override all (or any) of the memory management routines.
4876 You may, for example, override @code{yyrealloc}, but not @code{yyfree} or
4881 // For a non-reentrant scanner
4882 void * yyalloc (size_t bytes);
4883 void * yyrealloc (void * ptr, size_t bytes);
4884 void yyfree (void * ptr);
4886 // For a reentrant scanner
4887 void * yyalloc (size_t bytes, void * yyscanner);
4888 void * yyrealloc (void * ptr, size_t bytes, void * yyscanner);
4889 void yyfree (void * ptr, void * yyscanner);
4895 In the following example, we will override all three memory routines. We assume
4896 that there is a custom allocator with garbage collection. In order to make this
4897 example interesting, we will use a reentrant scanner, passing a pointer to the
4898 custom allocator through @code{yyextra}.
4900 @cindex overriding the memory routines
4904 #include "some_allocator.h"
4907 /* Suppress the default implementations. */
4908 %option noyyalloc noyyrealloc noyyfree
4911 /* Initialize the allocator. */
4912 #define YY_EXTRA_TYPE struct allocator*
4913 #define YY_USER_INIT yyextra = allocator_create();
4919 /* Provide our own implementations. */
4920 void * yyalloc (size_t bytes, void* yyscanner) {
4921 return allocator_alloc (yyextra, bytes);
4924 void * yyrealloc (void * ptr, size_t bytes, void* yyscanner) {
4925 return allocator_realloc (yyextra, bytes);
4928 void yyfree (void * ptr, void * yyscanner) {
4929 /* Do nothing -- we leave it to the garbage collector. */
4936 @node A Note About yytext And Memory, , Overriding The Default Memory Management, Memory Management
4937 @section A Note About yytext And Memory
4939 @cindex yytext, memory considerations
4941 When flex finds a match, @code{yytext} points to the first character of the
4942 match in the input buffer. The string itself is part of the input buffer, and
4943 is @emph{NOT} allocated separately. The value of yytext will be overwritten the next
4944 time yylex() is called. In short, the value of yytext is only valid from within
4945 the matched rule's action.
4947 Often, you want the value of yytext to persist for later processing, i.e., by a
4948 parser with non-zero lookahead. In order to preserve yytext, you will have to
4949 copy it with strdup() or a similar function. But this introduces some headache
4950 because your parser is now responsible for freeing the copy of yytext. If you
4951 use a yacc or bison parser, (commonly used with flex), you will discover that
4952 the error recovery mechanisms can cause memory to be leaked.
4954 To prevent memory leaks from strdup'd yytext, you will have to track the memory
4955 somehow. Our experience has shown that a garbage collection mechanism or a
4956 pooled memory mechanism will save you a lot of grief when writing parsers.
4958 @node Serialized Tables, Diagnostics, Memory Management, Top
4959 @chapter Serialized Tables
4960 @cindex serialization
4961 @cindex memory, serialized tables
4963 @anchor{serialization}
4964 A @code{flex} scanner has the ability to save the DFA tables to a file, and
4965 load them at runtime when needed. The motivation for this feature is to reduce
4966 the runtime memory footprint. Traditionally, these tables have been compiled into
4967 the scanner as C arrays, and are sometimes quite large. Since the tables are
4968 compiled into the scanner, the memory used by the tables can never be freed.
4969 This is a waste of memory, especially if an application uses several scanners,
4970 but none of them at the same time.
4972 The serialization feature allows the tables to be loaded at runtime, before
4973 scanning begins. The tables may be discarded when scanning is finished.
4976 * Creating Serialized Tables::
4977 * Loading and Unloading Serialized Tables::
4978 * Tables File Format::
4981 @node Creating Serialized Tables, Loading and Unloading Serialized Tables, Serialized Tables, Serialized Tables
4982 @section Creating Serialized Tables
4983 @cindex tables, creating serialized
4984 @cindex serialization of tables
4986 You may create a scanner with serialized tables by specifying:
4990 %option tables-file=FILE
4996 These options instruct flex to save the DFA tables to the file @var{FILE}. The tables
4997 will @emph{not} be embedded in the generated scanner. The scanner will not
4998 function on its own. The scanner will be dependent upon the serialized tables. You must
4999 load the tables from this file at runtime before you can scan anything.
5001 If you do not specify a filename to @code{--tables-file}, the tables will be
5002 saved to @file{lex.yy.tables}, where @samp{yy} is the appropriate prefix.
5004 If your project uses several different scanners, you can concatenate the
5005 serialized tables into one file, and flex will find the correct set of tables,
5006 using the scanner prefix as part of the lookup key. An example follows:
5008 @cindex serialized tables, multiple scanners
5011 $ flex --tables-file --prefix=cpp cpp.l
5012 $ flex --tables-file --prefix=c c.l
5013 $ cat lex.cpp.tables lex.c.tables > all.tables
5017 The above example created two scanners, @samp{cpp}, and @samp{c}. Since we did
5018 not specify a filename, the tables were serialized to @file{lex.c.tables} and
5019 @file{lex.cpp.tables}, respectively. Then, we concatenated the two files
5020 together into @file{all.tables}, which we will distribute with our project. At
5021 runtime, we will open the file and tell flex to load the tables from it. Flex
5022 will find the correct tables automatically. (See next section).
5024 @node Loading and Unloading Serialized Tables, Tables File Format, Creating Serialized Tables, Serialized Tables
5025 @section Loading and Unloading Serialized Tables
5026 @cindex tables, loading and unloading
5027 @cindex loading tables at runtime
5028 @cindex tables, freeing
5029 @cindex freeing tables
5030 @cindex memory, serialized tables
5032 If you've built your scanner with @code{%option tables-file}, then you must
5033 load the scanner tables at runtime. This can be accomplished with the following
5036 @deftypefun int yytables_fload (FILE* @var{fp} [, yyscan_t @var{scanner}])
5037 Locates scanner tables in the stream pointed to by @var{fp} and loads them.
5038 Memory for the tables is allocated via @code{yyalloc}. You must call this
5039 function before the first call to @code{yylex}. The argument @var{scanner}
5040 only appears in the reentrant scanner.
5041 This function returns @samp{0} (zero) on success, or non-zero on error.
5044 The loaded tables are @strong{not} automatically destroyed (unloaded) when you
5045 call @code{yylex_destroy}. The reason is that you may create several scanners
5046 of the same type (in a reentrant scanner), each of which needs access to these
5047 tables. To avoid a nasty memory leak, you must call the following function:
5049 @deftypefun int yytables_destroy ([yyscan_t @var{scanner}])
5050 Unloads the scanner tables. The tables must be loaded again before you can scan
5051 any more data. The argument @var{scanner} only appears in the reentrant
5052 scanner. This function returns @samp{0} (zero) on success, or non-zero on
5056 @strong{The functions @code{yytables_fload} and @code{yytables_destroy} are not
5057 thread-safe.} You must ensure that these functions are called exactly once (for
5058 each scanner type) in a threaded program, before any thread calls @code{yylex}.
5059 After the tables are loaded, they are never written to, and no thread
5060 protection is required thereafter -- until you destroy them.
5062 @node Tables File Format, , Loading and Unloading Serialized Tables, Serialized Tables
5063 @section Tables File Format
5064 @cindex tables, file format
5065 @cindex file format, serialized tables
5067 This section defines the file format of serialized @code{flex} tables.
5069 The tables format allows for one or more sets of tables to be
5070 specified, where each set corresponds to a given scanner. Scanners are
5071 indexed by name, as described below. The file format is as follows:
5076 +-------------------------------+
5077 Header | uint32 th_magic; |
5078 | uint32 th_hsize; |
5079 | uint32 th_ssize; |
5080 | uint16 th_flags; |
5081 | char th_version[]; |
5083 | uint8 th_pad64[]; |
5084 +-------------------------------+
5085 Table 1 | uint16 td_id; |
5086 | uint16 td_flags; |
5087 | uint32 td_lolen; |
5088 | uint32 td_hilen; |
5090 | uint8 td_pad64[]; |
5091 +-------------------------------+
5098 +-------------------------------+
5107 The above diagram shows that a complete set of tables consists of a header
5108 followed by multiple individual tables. Furthermore, multiple complete sets may
5109 be present in the same file, each set with its own header and tables. The sets
5110 are contiguous in the file. The only way to know if another set follows is to
5111 check the next four bytes for the magic number (or check for EOF). The header
5112 and tables sections are padded to 64-bit boundaries. Below we describe each
5113 field in detail. This format does not specify how the scanner will expand the
5114 given data, i.e., data may be serialized as int8, but expanded to an int32
5115 array at runtime. This is to reduce the size of the serialized data where
5116 possible. Remember, @emph{all integer values are in network byte order}.
5119 Fields of a table header:
5123 Magic number, always 0xF13C57B1.
5126 Size of this entire header, in bytes, including all fields plus any padding.
5129 Size of this entire set, in bytes, including the header, all tables, plus
5133 Bit flags for this table set. Currently unused.
5136 Flex version in NULL-terminated string format. e.g., @samp{2.5.13a}. This is
5137 the version of flex that was used to create the serialized tables.
5140 Contains the name of this table set. The default is @samp{yytables},
5141 and is prefixed accordingly, e.g., @samp{footables}. Must be NULL-terminated.
5144 Zero or more NULL bytes, padding the entire header to the next 64-bit boundary
5145 as calculated from the beginning of the header.
5153 Specifies the table identifier. Possible values are:
5155 @item YYTD_ID_ACCEPT (0x01)
5157 @item YYTD_ID_BASE (0x02)
5159 @item YYTD_ID_CHK (0x03)
5161 @item YYTD_ID_DEF (0x04)
5163 @item YYTD_ID_EC (0x05)
5165 @item YYTD_ID_META (0x06)
5167 @item YYTD_ID_NUL_TRANS (0x07)
5169 @item YYTD_ID_NXT (0x08)
5170 @code{yy_nxt}. This array may be two dimensional. See the @code{td_hilen}
5172 @item YYTD_ID_RULE_CAN_MATCH_EOL (0x09)
5173 @code{yy_rule_can_match_eol}
5174 @item YYTD_ID_START_STATE_LIST (0x0A)
5175 @code{yy_start_state_list}. This array is handled specially because it is an
5176 array of pointers to structs. See the @code{td_flags} field below.
5177 @item YYTD_ID_TRANSITION (0x0B)
5178 @code{yy_transition}. This array is handled specially because it is an array of
5179 structs. See the @code{td_lolen} field below.
5180 @item YYTD_ID_ACCLIST (0x0C)
5185 Bit flags describing how to interpret the data in @code{td_data}.
5186 The data arrays are one-dimensional by default, but may be
5187 two dimensional as specified in the @code{td_hilen} field.
5190 @item YYTD_DATA8 (0x01)
5191 The data is serialized as an array of type int8.
5192 @item YYTD_DATA16 (0x02)
5193 The data is serialized as an array of type int16.
5194 @item YYTD_DATA32 (0x04)
5195 The data is serialized as an array of type int32.
5196 @item YYTD_PTRANS (0x08)
5197 The data is a list of indexes of entries in the expanded @code{yy_transition}
5198 array. Each index should be expanded to a pointer to the corresponding entry
5199 in the @code{yy_transition} array. We count on the fact that the
5200 @code{yy_transition} array has already been seen.
5201 @item YYTD_STRUCT (0x10)
5202 The data is a list of yy_trans_info structs, each of which consists of
5203 two integers. There is no padding between struct elements or between structs.
5204 The type of each member is determined by the @code{YYTD_DATA*} bits.
5208 Specifies the number of elements in the lowest dimension array. If this is
5209 a one-dimensional array, then it is simply the number of elements in this array.
5210 The element size is determined by the @code{td_flags} field.
5213 If @code{td_hilen} is non-zero, then the data is a two-dimensional array.
5214 Otherwise, the data is a one-dimensional array. @code{td_hilen} contains the
5215 number of elements in the higher dimensional array, and @code{td_lolen} contains
5216 the number of elements in the lowest dimension.
5218 Conceptually, @code{td_data} is either @code{sometype td_data[td_lolen]}, or
5219 @code{sometype td_data[td_hilen][td_lolen]}, where @code{sometype} is specified
5220 by the @code{td_flags} field. It is possible for both @code{td_lolen} and
5221 @code{td_hilen} to be zero, in which case @code{td_data} is a zero length
5222 array, and no data is loaded, i.e., this table is simply skipped. Flex does not
5223 currently generate tables of zero length.
5226 The table data. This array may be a one- or two-dimensional array, of type
5227 @code{int8}, @code{int16}, @code{int32}, @code{struct yy_trans_info}, or
5228 @code{struct yy_trans_info*}, depending upon the values in the
5229 @code{td_flags}, @code{td_lolen}, and @code{td_hilen} fields.
5232 Zero or more NULL bytes, padding the entire table to the next 64-bit boundary as
5233 calculated from the beginning of this table.
5236 @node Diagnostics, Limitations, Serialized Tables, Top
5237 @chapter Diagnostics
5239 @cindex error reporting, diagnostic messages
5240 @cindex warnings, diagnostic messages
5242 The following is a list of @code{flex} diagnostic messages:
5246 @samp{warning, rule cannot be matched} indicates that the given rule
5247 cannot be matched because it follows other rules that will always match
5248 the same text as it. For example, in the following @samp{foo} cannot be
5249 matched because it comes after an identifier ``catch-all'' rule:
5251 @cindex warning, rule cannot be matched
5254 [a-z]+ got_identifier();
5259 Using @code{REJECT} in a scanner suppresses this warning.
5262 @samp{warning, -s option given but default rule can be matched} means
5263 that it is possible (perhaps only in a particular start condition) that
5264 the default rule (match any single character) is the only one that will
5265 match a particular input. Since @samp{-s} was given, presumably this is
5269 @code{reject_used_but_not_detected undefined} or
5270 @code{yymore_used_but_not_detected undefined}. These errors can occur
5271 at compile time. They indicate that the scanner uses @code{REJECT} or
5272 @code{yymore()} but that @code{flex} failed to notice the fact, meaning
5273 that @code{flex} scanned the first two sections looking for occurrences
5274 of these actions and failed to find any, but somehow you snuck some in
5275 (via a #include file, for example). Use @code{%option reject} or
5276 @code{%option yymore} to indicate to @code{flex} that you really do use
5280 @samp{flex scanner jammed}. a scanner compiled with
5281 @samp{-s} has encountered an input string which wasn't matched by any of
5282 its rules. This error can also occur due to internal problems.
5285 @samp{token too large, exceeds YYLMAX}. your scanner uses @code{%array}
5286 and one of its rules matched a string longer than the @code{YYLMAX}
5287 constant (8K bytes by default). You can increase the value by
5288 #define'ing @code{YYLMAX} in the definitions section of your @code{flex}
5292 @samp{scanner requires -8 flag to use the character 'x'}. Your scanner
5293 specification includes recognizing the 8-bit character @samp{'x'} and
5294 you did not specify the -8 flag, and your scanner defaulted to 7-bit
5295 because you used the @samp{-Cf} or @samp{-CF} table compression options.
5296 See the discussion of the @samp{-7} flag, @ref{Scanner Options}, for
5300 @samp{flex scanner push-back overflow}. you used @code{unput()} to push
5301 back so much text that the scanner's buffer could not hold both the
5302 pushed-back text and the current token in @code{yytext}. Ideally the
5303 scanner should dynamically resize the buffer in this case, but at
5304 present it does not.
5307 @samp{input buffer overflow, can't enlarge buffer because scanner uses
5308 REJECT}. the scanner was working on matching an extremely large token
5309 and needed to expand the input buffer. This doesn't work with scanners
5310 that use @code{REJECT}.
5313 @samp{fatal flex scanner internal error--end of buffer missed}. This can
5314 occur in a scanner which is reentered after a long-jump has jumped out
5315 (or over) the scanner's activation frame. Before reentering the
5322 or, as noted above, switch to using the C++ scanner class.
5325 @samp{too many start conditions in <> construct!} you listed more start
5326 conditions in a <> construct than exist (so you must have listed at
5327 least one of them twice).
5330 @node Limitations, Bibliography, Diagnostics, Top
5331 @chapter Limitations
5333 @cindex limitations of flex
5335 Some trailing context patterns cannot be properly matched and generate
5336 warning messages (@samp{dangerous trailing context}). These are
5337 patterns where the ending of the first part of the rule matches the
5338 beginning of the second part, such as @samp{zx*/xy*}, where the 'x*'
5339 matches the 'x' at the beginning of the trailing context. (Note that
5340 the POSIX draft states that the text matched by such patterns is
5341 undefined.) For some trailing context rules, parts which are actually
5342 fixed-length are not recognized as such, leading to the abovementioned
5343 performance loss. In particular, parts using @samp{|} or @samp{@{n@}}
5344 (such as @samp{foo@{3@}}) are always considered variable-length.
5345 Combining trailing context with the special @samp{|} action can result
5346 in @emph{fixed} trailing context being turned into the more expensive
5347 @emph{variable} trailing context. For example, in the following:
5349 @cindex warning, dangerous trailing context
5358 Use of @code{unput()} invalidates yytext and yyleng, unless the
5359 @code{%array} directive or the @samp{-l} option has been used.
5360 Pattern-matching of @code{NUL}s is substantially slower than matching
5361 other characters. Dynamic resizing of the input buffer is slow, as it
5362 entails rescanning all the text matched so far by the current (generally
5363 huge) token. Due to both buffering of input and read-ahead, you cannot
5364 intermix calls to @file{<stdio.h>} routines, such as, @b{getchar()},
5365 with @code{flex} rules and expect it to work. Call @code{input()}
5366 instead. The total table entries listed by the @samp{-v} flag excludes
5367 the number of table entries needed to determine what rule has been
5368 matched. The number of entries is equal to the number of DFA states if
5369 the scanner does not use @code{REJECT}, and somewhat greater than the
5370 number of states if it does. @code{REJECT} cannot be used with the
5371 @samp{-f} or @samp{-F} options.
5373 The @code{flex} internal algorithms need documentation.
5375 @node Bibliography, FAQ, Limitations, Top
5376 @chapter Additional Reading
5378 You may wish to read more about the following programs:
5386 The following books may contain material of interest:
5388 John Levine, Tony Mason, and Doug Brown,
5390 O'Reilly and Associates. Be sure to get the 2nd edition.
5392 M. E. Lesk and E. Schmidt,
5393 @emph{LEX -- Lexical Analyzer Generator}
5395 Alfred Aho, Ravi Sethi and Jeffrey Ullman, @emph{Compilers: Principles,
5396 Techniques and Tools}, Addison-Wesley (1986). Describes the
5397 pattern-matching techniques used by @code{flex} (deterministic finite
5400 @node FAQ, Appendices, Bibliography, Top
5403 From time to time, the @code{flex} maintainer receives certain
5404 questions. Rather than repeat answers to well-understood problems, we
5408 * When was flex born?::
5409 * How do I expand backslash-escape sequences in C-style quoted strings?::
5410 * Why do flex scanners call fileno if it is not ANSI compatible?::
5411 * Does flex support recursive pattern definitions?::
5412 * How do I skip huge chunks of input (tens of megabytes) while using flex?::
5413 * Flex is not matching my patterns in the same order that I defined them.::
5414 * My actions are executing out of order or sometimes not at all.::
5415 * How can I have multiple input sources feed into the same scanner at the same time?::
5416 * Can I build nested parsers that work with the same input file?::
5417 * How can I match text only at the end of a file?::
5418 * How can I make REJECT cascade across start condition boundaries?::
5419 * Why cant I use fast or full tables with interactive mode?::
5420 * How much faster is -F or -f than -C?::
5421 * If I have a simple grammar cant I just parse it with flex?::
5422 * Why doesn't yyrestart() set the start state back to INITIAL?::
5423 * How can I match C-style comments?::
5424 * The period isn't working the way I expected.::
5425 * Can I get the flex manual in another format?::
5426 * Does there exist a "faster" NDFA->DFA algorithm?::
5427 * How does flex compile the DFA so quickly?::
5428 * How can I use more than 8192 rules?::
5429 * How do I abandon a file in the middle of a scan and switch to a new file?::
5430 * How do I execute code only during initialization (only before the first scan)?::
5431 * How do I execute code at termination?::
5432 * Where else can I find help?::
5433 * Can I include comments in the "rules" section of the file?::
5434 * I get an error about undefined yywrap().::
5435 * How can I change the matching pattern at run time?::
5436 * How can I expand macros in the input?::
5437 * How can I build a two-pass scanner?::
5438 * How do I match any string not matched in the preceding rules?::
5439 * I am trying to port code from AT&T lex that uses yysptr and yysbuf.::
5440 * Is there a way to make flex treat NULL like a regular character?::
5441 * Whenever flex can not match the input it says "flex scanner jammed".::
5442 * Why doesn't flex have non-greedy operators like perl does?::
5443 * Memory leak - 16386 bytes allocated by malloc.::
5444 * How do I track the byte offset for lseek()?::
5445 * How do I use my own I/O classes in a C++ scanner?::
5446 * How do I skip as many chars as possible?::
5448 * Are certain equivalent patterns faster than others?::
5449 * Is backing up a big deal?::
5450 * Can I fake multi-byte character support?::
5452 * Can you discuss some flex internals?::
5453 * unput() messes up yy_at_bol::
5454 * The | operator is not doing what I want::
5455 * Why can't flex understand this variable trailing context pattern?::
5456 * The ^ operator isn't working::
5457 * Trailing context is getting confused with trailing optional patterns::
5458 * Is flex GNU or not?::
5460 * I need to scan if-then-else blocks and while loops::
5464 * Is there a repository for flex scanners?::
5465 * How can I conditionally compile or preprocess my flex input file?::
5466 * Where can I find grammars for lex and yacc?::
5467 * I get an end-of-buffer message for each character scanned.::
5507 * What is the difference between YYLEX_PARAM and YY_DECL?::
5508 * Why do I get "conflicting types for yylex" error?::
5509 * How do I access the values set in a Flex action from within a Bison action?::
5512 @node When was flex born?
5513 @unnumberedsec When was flex born?
5515 Vern Paxson took over
5516 the @cite{Software Tools} lex project from Jef Poskanzer in 1982. At that point it
5517 was written in Ratfor. Around 1987 or so, Paxson translated it into C, and
5518 a legend was born :-).
5520 @node How do I expand backslash-escape sequences in C-style quoted strings?
5521 @unnumberedsec How do I expand backslash-escape sequences in C-style quoted strings?
5523 A key point when scanning quoted strings is that you cannot (easily) write
5524 a single rule that will precisely match the string if you allow things
5525 like embedded escape sequences and newlines. If you try to match strings
5526 with a single rule then you'll wind up having to rescan the string anyway
5527 to find any escape sequences.
5529 Instead you can use exclusive start conditions and a set of rules, one for
5530 matching non-escaped text, one for matching a single escape, one for
5531 matching an embedded newline, and one for recognizing the end of the
5532 string. Each of these rules is then faced with the question of where to
5533 put its intermediary results. The best solution is for the rules to
5534 append their local value of @code{yytext} to the end of a ``string literal''
5535 buffer. A rule like the escape-matcher will append to the buffer the
5536 meaning of the escape sequence rather than the literal text in @code{yytext}.
5537 In this way, @code{yytext} does not need to be modified at all.
5539 @node Why do flex scanners call fileno if it is not ANSI compatible?
5540 @unnumberedsec Why do flex scanners call fileno if it is not ANSI compatible?
5542 Flex scanners call @code{fileno()} in order to get the file descriptor
5543 corresponding to @code{yyin}. The file descriptor may be passed to
5544 @code{isatty()} or @code{read()}, depending upon which @code{%options} you specified.
5545 If your system does not have @code{fileno()} support, to get rid of the
5546 @code{read()} call, do not specify @code{%option read}. To get rid of the @code{isatty()}
5547 call, you must specify one of @code{%option always-interactive} or
5548 @code{%option never-interactive}.
5550 @node Does flex support recursive pattern definitions?
5551 @unnumberedsec Does flex support recursive pattern definitions?
5558 block "{"({block}|{statement})*"}"
5562 No. You cannot have recursive definitions. The pattern-matching power of
5563 regular expressions in general (and therefore flex scanners, too) is
5564 limited. In particular, regular expressions cannot ``balance'' parentheses
5565 to an arbitrary degree. For example, it's impossible to write a regular
5566 expression that matches all strings containing the same number of '@{'s
5567 as '@}'s. For more powerful pattern matching, you need a parser, such
5568 as @cite{GNU bison}.
5570 @node How do I skip huge chunks of input (tens of megabytes) while using flex?
5571 @unnumberedsec How do I skip huge chunks of input (tens of megabytes) while using flex?
5573 Use @code{fseek()} (or @code{lseek()}) to position yyin, then call @code{yyrestart()}.
5575 @node Flex is not matching my patterns in the same order that I defined them.
5576 @unnumberedsec Flex is not matching my patterns in the same order that I defined them.
5578 @code{flex} picks the
5579 rule that matches the most text (i.e., the longest possible input string).
5580 This is because @code{flex} uses an entirely different matching technique
5581 (``deterministic finite automata'') that actually does all of the matching
5582 simultaneously, in parallel. (Seems impossible, but it's actually a fairly
5583 simple technique once you understand the principles.)
5585 A side-effect of this parallel matching is that when the input matches more
5586 than one rule, @code{flex} scanners pick the rule that matched the @emph{most} text. This
5587 is explained further in the manual, in the section @xref{Matching}.
5589 If you want @code{flex} to choose a shorter match, then you can work around this
5590 behavior by expanding your short
5591 rule to match more text, then put back the extra:
5595 data_.* yyless( 5 ); BEGIN BLOCKIDSTATE;
5599 Another fix would be to make the second rule active only during the
5600 @code{<BLOCKIDSTATE>} start condition, and make that start condition exclusive
5601 by declaring it with @code{%x} instead of @code{%s}.
5603 A final fix is to change the input language so that the ambiguity for
5604 @samp{data_} is removed, by adding characters to it that don't match the
5605 identifier rule, or by removing characters (such as @samp{_}) from the
5606 identifier rule so it no longer matches @samp{data_}. (Of course, you might
5607 also not have the option of changing the input language.)
5609 @node My actions are executing out of order or sometimes not at all.
5610 @unnumberedsec My actions are executing out of order or sometimes not at all.
5612 Most likely, you have (in error) placed the opening @samp{@{} of the action
5613 block on a different line than the rule, e.g.,
5624 @code{flex} requires that the opening @samp{@{} of an action associated with a rule
5625 begin on the same line as does the rule. You need instead to write your rules
5630 ^(foo|bar) { // CORRECT!
5636 @node How can I have multiple input sources feed into the same scanner at the same time?
5637 @unnumberedsec How can I have multiple input sources feed into the same scanner at the same time?
5642 your scanner is free of backtracking (verified using @code{flex}'s @samp{-b} flag),
5644 AND you run your scanner interactively (@samp{-I} option; default unless using special table
5645 compression options),
5647 AND you feed it one character at a time by redefining @code{YY_INPUT} to do so,
5650 then every time it matches a token, it will have exhausted its input
5651 buffer (because the scanner is free of backtracking). This means you
5652 can safely use @code{select()} at the point and only call @code{yylex()} for another
5653 token if @code{select()} indicates there's data available.
5655 That is, move the @code{select()} out from the input function to a point where
5656 it determines whether @code{yylex()} gets called for the next token.
5658 With this approach, you will still have problems if your input can arrive
5659 piecemeal; @code{select()} could inform you that the beginning of a token is
5660 available, you call @code{yylex()} to get it, but it winds up blocking waiting
5661 for the later characters in the token.
5663 Here's another way: Move your input multiplexing inside of @code{YY_INPUT}. That
5664 is, whenever @code{YY_INPUT} is called, it @code{select()}'s to see where input is
5665 available. If input is available for the scanner, it reads and returns the
5666 next byte. If input is available from another source, it calls whatever
5667 function is responsible for reading from that source. (If no input is
5668 available, it blocks until some input is available.) I've used this technique in an
5669 interpreter I wrote that both reads keyboard input using a @code{flex} scanner and
5670 IPC traffic from sockets, and it works fine.
5672 @node Can I build nested parsers that work with the same input file?
5673 @unnumberedsec Can I build nested parsers that work with the same input file?
5675 This is not going to work without some additional effort. The reason is
5676 that @code{flex} block-buffers the input it reads from @code{yyin}. This means that the
5677 ``outermost'' @code{yylex()}, when called, will automatically slurp up the first 8K
5678 of input available on yyin, and subsequent calls to other @code{yylex()}'s won't
5679 see that input. You might be tempted to work around this problem by
5680 redefining @code{YY_INPUT} to only return a small amount of text, but it turns out
5681 that that approach is quite difficult. Instead, the best solution is to
5682 combine all of your scanners into one large scanner, using a different
5683 exclusive start condition for each.
5685 @node How can I match text only at the end of a file?
5686 @unnumberedsec How can I match text only at the end of a file?
5688 There is no way to write a rule which is ``match this text, but only if
5689 it comes at the end of the file''. You can fake it, though, if you happen
5690 to have a character lying around that you don't allow in your input.
5691 Then you redefine @code{YY_INPUT} to call your own routine which, if it sees
5692 an @samp{EOF}, returns the magic character first (and remembers to return a
5693 real @code{EOF} next time it's called). Then you could write:
5697 <COMMENT>(.|\n)*{EOF_CHAR} /* saw comment at EOF */
5701 @node How can I make REJECT cascade across start condition boundaries?
5702 @unnumberedsec How can I make REJECT cascade across start condition boundaries?
5704 You can do this as follows. Suppose you have a start condition @samp{A}, and
5705 after exhausting all of the possible matches in @samp{<A>}, you want to try
5706 matches in @samp{<INITIAL>}. Then you could use the following:
5712 <A>rule_that_is_long ...; REJECT;
5713 <A>rule ...; REJECT; /* shorter rule */
5717 /* Shortest and last rule in <A>, so
5718 * cascaded REJECTs will eventually
5719 * wind up matching this rule. We want
5720 * to now switch to the initial state
5721 * and try matching from there instead.
5723 yyless(0); /* put back matched text */
5729 @node Why cant I use fast or full tables with interactive mode?
5730 @unnumberedsec Why can't I use fast or full tables with interactive mode?
5732 One of the assumptions
5733 flex makes is that interactive applications are inherently slow (they're
5734 waiting on a human after all).
5735 It has to do with how the scanner detects that it must be finished scanning
5736 a token. For interactive scanners, after scanning each character the current
5737 state is looked up in a table (essentially) to see whether there's a chance
5738 of another input character possibly extending the length of the match. If
5739 not, the scanner halts. For non-interactive scanners, the end-of-token test
5740 is much simpler, basically a compare with 0, so no memory bus cycles. Since
5741 the test occurs in the innermost scanning loop, one would like to make it go
5742 as fast as possible.
5744 Still, it seems reasonable to allow the user to choose to trade off a bit
5745 of performance in this area to gain the corresponding flexibility. There
5746 might be another reason, though, why fast scanners don't support the
5749 @node How much faster is -F or -f than -C?
5750 @unnumberedsec How much faster is -F or -f than -C?
5752 Much faster (factor of 2-3).
5754 @node If I have a simple grammar cant I just parse it with flex?
5755 @unnumberedsec If I have a simple grammar can't I just parse it with flex?
5757 Is your grammar recursive? That's almost always a sign that you're
5758 better off using a parser/scanner rather than just trying to use a scanner
5761 @node Why doesn't yyrestart() set the start state back to INITIAL?
5762 @unnumberedsec Why doesn't yyrestart() set the start state back to INITIAL?
5764 There are two reasons. The first is that there might
5765 be programs that rely on the start state not changing across file changes.
5766 The second is that beginning with @code{flex} version 2.4, use of @code{yyrestart()} is no longer required,
5767 so fixing the problem there doesn't solve the more general problem.
5769 @node How can I match C-style comments?
5770 @unnumberedsec How can I match C-style comments?
5772 You might be tempted to try something like this:
5776 "/*".*"*/" // WRONG!
5784 "/*"(.|\n)"*/" // WRONG!
5788 The above rules will eat too much input, and blow up on things like:
5792 /* a comment */ do_my_thing( "oops */" );
5796 Here is one way which allows you to track line information:
5801 "/*" BEGIN(IN_COMMENT);
5804 "*/" BEGIN(INITIAL);
5805 [^*\n]+ // eat comment in chunks
5806 "*" // eat the lone star
5812 @node The period isn't working the way I expected.
5813 @unnumberedsec The '.' isn't working the way I expected.
5815 Here are some tips for using @samp{.}:
5819 A common mistake is to place the grouping parenthesis AFTER an operator, when
5820 you really meant to place the parenthesis BEFORE the operator, e.g., you
5821 probably want this @code{(foo|bar)+} and NOT this @code{(foo|bar+)}.
5823 The first pattern matches the words @samp{foo} or @samp{bar} any number of
5824 times, e.g., it matches the text @samp{barfoofoobarfoo}. The
5825 second pattern matches a single instance of @code{foo} or a single instance of
5826 @code{bar} followed by one or more @samp{r}s, e.g., it matches the text @code{barrrr} .
5828 A @samp{.} inside @samp{[]}'s just means a literal@samp{.} (period),
5829 and NOT ``any character except newline''.
5831 Remember that @samp{.} matches any character EXCEPT @samp{\n} (and @samp{EOF}).
5832 If you really want to match ANY character, including newlines, then use @code{(.|\n)}
5833 Beware that the regex @code{(.|\n)+} will match your entire input!
5835 Finally, if you want to match a literal @samp{.} (a period), then use @samp{[.]} or @samp{"."}
5838 @node Can I get the flex manual in another format?
5839 @unnumberedsec Can I get the flex manual in another format?
5841 The @code{flex} source distribution includes a texinfo manual. You are
5842 free to convert that texinfo into whatever format you desire. The
5843 @code{texinfo} package includes tools for conversion to a number of formats.
5845 @node Does there exist a "faster" NDFA->DFA algorithm?
5846 @unnumberedsec Does there exist a "faster" NDFA->DFA algorithm?
5848 There's no way around the potential exponential running time - it
5849 can take you exponential time just to enumerate all of the DFA states.
5850 In practice, though, the running time is closer to linear, or sometimes
5853 @node How does flex compile the DFA so quickly?
5854 @unnumberedsec How does flex compile the DFA so quickly?
5856 There are two big speed wins that @code{flex} uses:
5860 It analyzes the input rules to construct equivalence classes for those
5861 characters that always make the same transitions. It then rewrites the NFA
5862 using equivalence classes for transitions instead of characters. This cuts
5863 down the NFA->DFA computation time dramatically, to the point where, for
5864 uncompressed DFA tables, the DFA generation is often I/O bound in writing out
5867 It maintains hash values for previously computed DFA states, so testing
5868 whether a newly constructed DFA state is equivalent to a previously constructed
5869 state can be done very quickly, by first comparing hash values.
5872 @node How can I use more than 8192 rules?
5873 @unnumberedsec How can I use more than 8192 rules?
5875 @code{Flex} is compiled with an upper limit of 8192 rules per scanner.
5876 If you need more than 8192 rules in your scanner, you'll have to recompile @code{flex}
5877 with the following changes in @file{flexdef.h}:
5881 < #define YY_TRAILING_MASK 0x2000
5882 < #define YY_TRAILING_HEAD_MASK 0x4000
5884 > #define YY_TRAILING_MASK 0x20000000
5885 > #define YY_TRAILING_HEAD_MASK 0x40000000
5889 This should work okay as long as your C compiler uses 32 bit integers.
5890 But you might want to think about whether using such a huge number of rules
5891 is the best way to solve your problem.
5893 The following may also be relevant:
5895 With luck, you should be able to increase the definitions in flexdef.h for:
5899 #define JAMSTATE -32766 /* marks a reference to the state that always jams */
5900 #define MAXIMUM_MNS 31999
5901 #define BAD_SUBSCRIPT -32767
5905 recompile everything, and it'll all work. Flex only has these 16-bit-like
5906 values built into it because a long time ago it was developed on a machine
5907 with 16-bit ints. I've given this advice to others in the past but haven't
5908 heard back from them whether it worked okay or not...
5910 @node How do I abandon a file in the middle of a scan and switch to a new file?
5911 @unnumberedsec How do I abandon a file in the middle of a scan and switch to a new file?
5913 Just call @code{yyrestart(newfile)}. Be sure to reset the start state if you want a
5914 ``fresh start, since @code{yyrestart} does NOT reset the start state back to @code{INITIAL}.
5916 @node How do I execute code only during initialization (only before the first scan)?
5917 @unnumberedsec How do I execute code only during initialization (only before the first scan)?
5919 You can specify an initial action by defining the macro @code{YY_USER_INIT} (though
5920 note that @code{yyout} may not be available at the time this macro is executed). Or you
5921 can add to the beginning of your rules section:
5926 /* Must be indented! */
5927 static int did_init = 0;
5936 @node How do I execute code at termination?
5937 @unnumberedsec How do I execute code at termination?
5939 You can specify an action for the @code{<<EOF>>} rule.
5941 @node Where else can I find help?
5942 @unnumberedsec Where else can I find help?
5944 You can find the flex homepage on the web at
5945 @uref{http://flex.sourceforge.net/}. See that page for details about flex
5946 mailing lists as well.
5948 @node Can I include comments in the "rules" section of the file?
5949 @unnumberedsec Can I include comments in the "rules" section of the file?
5951 Yes, just about anywhere you want to. See the manual for the specific syntax.
5953 @node I get an error about undefined yywrap().
5954 @unnumberedsec I get an error about undefined yywrap().
5956 You must supply a @code{yywrap()} function of your own, or link to @file{libfl.a}
5957 (which provides one), or use
5965 in your source to say you don't want a @code{yywrap()} function.
5967 @node How can I change the matching pattern at run time?
5968 @unnumberedsec How can I change the matching pattern at run time?
5970 You can't, it's compiled into a static table when flex builds the scanner.
5972 @node How can I expand macros in the input?
5973 @unnumberedsec How can I expand macros in the input?
5975 The best way to approach this problem is at a higher level, e.g., in the parser.
5977 However, you can do this using multiple input buffers.
5983 /* Saw the macro "macro" followed by extra stuff. */
5984 main_buffer = YY_CURRENT_BUFFER;
5985 expansion_buffer = yy_scan_string(expand(yytext));
5986 yy_switch_to_buffer(expansion_buffer);
5990 if ( expansion_buffer )
5992 // We were doing an expansion, return to where
5994 yy_switch_to_buffer(main_buffer);
5995 yy_delete_buffer(expansion_buffer);
5996 expansion_buffer = 0;
6004 You probably will want a stack of expansion buffers to allow nested macros.
6005 From the above though hopefully the idea is clear.
6007 @node How can I build a two-pass scanner?
6008 @unnumberedsec How can I build a two-pass scanner?
6010 One way to do it is to filter the first pass to a temporary file,
6011 then process the temporary file on the second pass. You will probably see a
6012 performance hit, due to all the disk I/O.
6014 When you need to look ahead far forward like this, it almost always means
6015 that the right solution is to build a parse tree of the entire input, then
6016 walk it after the parse in order to generate the output. In a sense, this
6017 is a two-pass approach, once through the text and once through the parse
6018 tree, but the performance hit for the latter is usually an order of magnitude
6019 smaller, since everything is already classified, in binary format, and
6022 @node How do I match any string not matched in the preceding rules?
6023 @unnumberedsec How do I match any string not matched in the preceding rules?
6025 One way to assign precedence, is to place the more specific rules first. If
6026 two rules would match the same input (same sequence of characters) then the
6027 first rule listed in the @code{flex} input wins, e.g.,
6032 foo[a-zA-Z_]+ return FOO_ID;
6033 bar[a-zA-Z_]+ return BAR_ID;
6034 [a-zA-Z_]+ return GENERIC_ID;
6038 Note that the rule @code{[a-zA-Z_]+} must come *after* the others. It will match the
6039 same amount of text as the more specific rules, and in that case the
6040 @code{flex} scanner will pick the first rule listed in your scanner as the
6043 @node I am trying to port code from AT&T lex that uses yysptr and yysbuf.
6044 @unnumberedsec I am trying to port code from AT&T lex that uses yysptr and yysbuf.
6046 Those are internal variables pointing into the AT&T scanner's input buffer. I
6047 imagine they're being manipulated in user versions of the @code{input()} and @code{unput()}
6048 functions. If so, what you need to do is analyze those functions to figure out
6049 what they're doing, and then replace @code{input()} with an appropriate definition of
6050 @code{YY_INPUT}. You shouldn't need to (and must not) replace
6051 @code{flex}'s @code{unput()} function.
6053 @node Is there a way to make flex treat NULL like a regular character?
6054 @unnumberedsec Is there a way to make flex treat NULL like a regular character?
6056 Yes, @samp{\0} and @samp{\x00} should both do the trick. Perhaps you have an ancient
6057 version of @code{flex}. The latest release is version @value{VERSION}.
6059 @node Whenever flex can not match the input it says "flex scanner jammed".
6060 @unnumberedsec Whenever flex can not match the input it says "flex scanner jammed".
6062 You need to add a rule that matches the otherwise-unmatched text,
6069 [[a bunch of rules here]]
6071 . printf("bad input character '%s' at line %d\n", yytext, yylineno);
6075 See @code{%option default} for more information.
6077 @node Why doesn't flex have non-greedy operators like perl does?
6078 @unnumberedsec Why doesn't flex have non-greedy operators like perl does?
6080 A DFA can do a non-greedy match by stopping
6081 the first time it enters an accepting state, instead of consuming input until
6082 it determines that no further matching is possible (a ``jam'' state). This
6083 is actually easier to implement than longest leftmost match (which flex does).
6085 But it's also much less useful than longest leftmost match. In general,
6086 when you find yourself wishing for non-greedy matching, that's usually a
6087 sign that you're trying to make the scanner do some parsing. That's
6088 generally the wrong approach, since it lacks the power to do a decent job.
6089 Better is to either introduce a separate parser, or to split the scanner
6090 into multiple scanners using (exclusive) start conditions.
6093 a separate start state once you've seen the @samp{BEGIN}. In that state, you
6094 might then have a regex that will match @samp{END} (to kick you out of the
6095 state), and perhaps @samp{(.|\n)} to get a single character within the chunk ...
6097 This approach also has much better error-reporting properties.
6099 @node Memory leak - 16386 bytes allocated by malloc.
6100 @unnumberedsec Memory leak - 16386 bytes allocated by malloc.
6101 @anchor{faq-memory-leak}
6103 UPDATED 2002-07-10: As of @code{flex} version 2.5.9, this leak means that you did not
6104 call @code{yylex_destroy()}. If you are using an earlier version of @code{flex}, then read
6107 The leak is about 16426 bytes. That is, (8192 * 2 + 2) for the read-buffer, and
6108 about 40 for @code{struct yy_buffer_state} (depending upon alignment). The leak is in
6109 the non-reentrant C scanner only (NOT in the reentrant scanner, NOT in the C++
6110 scanner). Since @code{flex} doesn't know when you are done, the buffer is never freed.
6112 However, the leak won't multiply since the buffer is reused no matter how many
6113 times you call @code{yylex()}.
6115 If you want to reclaim the memory when you are completely done scanning, then
6120 /* For non-reentrant C scanner only. */
6121 yy_delete_buffer(YY_CURRENT_BUFFER);
6126 Note: @code{yy_init} is an "internal variable", and hasn't been tested in this
6127 situation. It is possible that some other globals may need resetting as well.
6129 @node How do I track the byte offset for lseek()?
6130 @unnumberedsec How do I track the byte offset for lseek()?
6134 > We thought that it would be possible to have this number through the
6135 > evaluation of the following expression:
6137 > seek_position = (no_buffers)*YY_READ_BUF_SIZE + yy_c_buf_p - YY_CURRENT_BUFFER->yy_ch_buf
6141 While this is the right idea, it has two problems. The first is that
6142 it's possible that @code{flex} will request less than @code{YY_READ_BUF_SIZE} during
6143 an invocation of @code{YY_INPUT} (or that your input source will return less
6144 even though @code{YY_READ_BUF_SIZE} bytes were requested). The second problem
6145 is that when refilling its internal buffer, @code{flex} keeps some characters
6146 from the previous buffer (because usually it's in the middle of a match,
6147 and needs those characters to construct @code{yytext} for the match once it's
6148 done). Because of this, @code{yy_c_buf_p - YY_CURRENT_BUFFER->yy_ch_buf} won't
6149 be exactly the number of characters already read from the current buffer.
6151 An alternative solution is to count the number of characters you've matched
6152 since starting to scan. This can be done by using @code{YY_USER_ACTION}. For
6157 #define YY_USER_ACTION num_chars += yyleng;
6161 (You need to be careful to update your bookkeeping if you use @code{yymore(}),
6162 @code{yyless()}, @code{unput()}, or @code{input()}.)
6164 @node How do I use my own I/O classes in a C++ scanner?
6165 @section How do I use my own I/O classes in a C++ scanner?
6167 When the flex C++ scanning class rewrite finally happens, then this sort of thing should become much easier.
6169 @cindex LexerOutput, overriding
6170 @cindex LexerInput, overriding
6171 @cindex overriding LexerOutput
6172 @cindex overriding LexerInput
6173 @cindex customizing I/O in C++ scanners
6174 @cindex C++ I/O, customizing
6175 You can do this by passing the various functions (such as @code{LexerInput()}
6176 and @code{LexerOutput()}) NULL @code{iostream*}'s, and then
6177 dealing with your own I/O classes surreptitiously (i.e., stashing them in
6178 special member variables). This works because the only assumption about
6179 the lexer regarding what's done with the iostream's is that they're
6180 ultimately passed to @code{LexerInput()} and @code{LexerOutput}, which then do whatever
6181 is necessary with them.
6183 @c faq edit stopped here
6184 @node How do I skip as many chars as possible?
6185 @unnumberedsec How do I skip as many chars as possible?
6187 How do I skip as many chars as possible -- without interfering with the other
6190 In the example below, we want to skip over characters until we see the phrase
6191 "endskip". The following will @emph{NOT} work correctly (do you see why not?)
6195 /* INCORRECT SCANNER */
6198 <INITIAL>startskip BEGIN(SKIP);
6200 <SKIP>"endskip" BEGIN(INITIAL);
6205 The problem is that the pattern .* will eat up the word "endskip."
6206 The simplest (but slow) fix is:
6210 <SKIP>"endskip" BEGIN(INITIAL);
6215 The fix involves making the second rule match more, without
6216 making it match "endskip" plus something else. So for example:
6220 <SKIP>"endskip" BEGIN(INITIAL);
6222 <SKIP>. ;/* so you eat up e's, too */
6226 @c TODO: Evaluate this faq.
6228 @unnumberedsec deleteme00
6234 Vern Paxson took over
6235 the Software Tools lex project from Jef Poskanzer in 1982. At that point it
6236 was written in Ratfor. Around 1987 or so, Paxson translated it into C, and
6237 a legend was born :-).
6241 @c TODO: Evaluate this faq.
6242 @node Are certain equivalent patterns faster than others?
6243 @unnumberedsec Are certain equivalent patterns faster than others?
6246 To: Adoram Rogel <adoram@orna.hybridge.com>
6247 Subject: Re: Flex 2.5.2 performance questions
6248 In-reply-to: Your message of Wed, 18 Sep 96 11:12:17 EDT.
6249 Date: Wed, 18 Sep 96 10:51:02 PDT
6250 From: Vern Paxson <vern>
6252 [Note, the most recent flex release is 2.5.4, which you can get from
6253 ftp.ee.lbl.gov. It has bug fixes over 2.5.2 and 2.5.3.]
6255 > 1. Using the pattern
6256 > ([Ff](oot)?)?[Nn](ote)?(\.)?
6258 > (((F|f)oot(N|n)ote)|((N|n)ote)|((N|n)\.)|((F|f)(N|n)(\.)))
6259 > (in a very complicated flex program) caused the program to slow from
6260 > 300K+/min to 100K/min (no other changes were done).
6262 These two are not equivalent. For example, the first can match "footnote."
6263 but the second can only match "footnote". This is almost certainly the
6264 cause in the discrepancy - the slower scanner run is matching more tokens,
6265 and/or having to do more backing up.
6267 > 2. Which of these two are better: [Ff]oot or (F|f)oot ?
6269 From a performance point of view, they're equivalent (modulo presumably
6270 minor effects such as memory cache hit rates; and the presence of trailing
6271 context, see below). From a space point of view, the first is slightly
6274 > 3. I have a pattern that look like this:
6275 > pats {p1}|{p2}|{p3}|...|{p50} (50 patterns ORd)
6277 > running yet another complicated program that includes the following rule:
6278 > <snext>{and}/{no4}{bb}{pats}
6280 > gets me to "too complicated - over 32,000 states"...
6282 I can't tell from this example whether the trailing context is variable-length
6283 or fixed-length (it could be the latter if {and} is fixed-length). If it's
6284 variable length, which flex -p will tell you, then this reflects a basic
6285 performance problem, and if you can eliminate it by restructuring your
6286 scanner, you will see significant improvement.
6288 > so I divided {pats} to {pats1}, {pats2},..., {pats5} each consists of about
6289 > 10 patterns and changed the rule to be 5 rules.
6290 > This did compile, but what is the rule of thumb here ?
6292 The rule is to avoid trailing context other than fixed-length, in which for
6293 a/b, either the 'a' pattern or the 'b' pattern have a fixed length. Use
6294 of the '|' operator automatically makes the pattern variable length, so in
6295 this case '[Ff]oot' is preferred to '(F|f)oot'.
6297 > 4. I changed a rule that looked like this:
6298 > <snext8>{and}{bb}/{ROMAN}[^A-Za-z] { BEGIN...
6300 > to the next 2 rules:
6301 > <snext8>{and}{bb}/{ROMAN}[A-Za-z] { ECHO;}
6302 > <snext8>{and}{bb}/{ROMAN} { BEGIN...
6304 > Again, I understand the using [^...] will cause a great performance loss
6306 Actually, it doesn't cause any sort of performance loss. It's a surprising
6307 fact about regular expressions that they always match in linear time
6308 regardless of how complex they are.
6310 > but are there any specific rules about it ?
6312 See the "Performance Considerations" section of the man page, and also
6313 the example in MISC/fastwc/.
6319 @c TODO: Evaluate this faq.
6320 @node Is backing up a big deal?
6321 @unnumberedsec Is backing up a big deal?
6324 To: Adoram Rogel <adoram@hybridge.com>
6325 Subject: Re: Flex 2.5.2 performance questions
6326 In-reply-to: Your message of Thu, 19 Sep 96 10:16:04 EDT.
6327 Date: Thu, 19 Sep 96 09:58:00 PDT
6328 From: Vern Paxson <vern>
6330 > a lot about the backing up problem.
6331 > I believe that there lies my biggest problem, and I'll try to improve
6334 Since you have variable trailing context, this is a bigger performance
6335 problem. Fixing it is usually easier than fixing backing up, which in a
6336 complicated scanner (yours seems to fit the bill) can be extremely
6337 difficult to do correctly.
6339 You also don't mention what flags you are using for your scanner.
6340 -f makes a large speed difference, and -Cfe buys you nearly as much
6341 speed but the resulting scanner is considerably smaller.
6343 > I have an | operator in {and} and in {pats} so both of them are variable
6346 -p should have reported this.
6348 > Is changing one of them to fixed-length is enough ?
6352 > Is it possible to change the 32,000 states limit ?
6354 Yes. I've appended instructions on how. Before you make this change,
6355 though, you should think about whether there are ways to fundamentally
6356 simplify your scanner - those are certainly preferable!
6360 To increase the 32K limit (on a machine with 32 bit integers), you increase
6361 the magnitude of the following in flexdef.h:
6363 #define JAMSTATE -32766 /* marks a reference to the state that always jams */
6364 #define MAXIMUM_MNS 31999
6365 #define BAD_SUBSCRIPT -32767
6366 #define MAX_SHORT 32700
6368 Adding a 0 or two after each should do the trick.
6372 @c TODO: Evaluate this faq.
6373 @node Can I fake multi-byte character support?
6374 @unnumberedsec Can I fake multi-byte character support?
6377 To: Heeman_Lee@hp.com
6378 Subject: Re: flex - multi-byte support?
6379 In-reply-to: Your message of Thu, 03 Oct 1996 17:24:04 PDT.
6380 Date: Fri, 04 Oct 1996 11:42:18 PDT
6381 From: Vern Paxson <vern>
6383 > I assume as long as my *.l file defines the
6384 > range of expected character code values (in octal format), flex will
6385 > scan the file and read multi-byte characters correctly. But I have no
6386 > confidence in this assumption.
6388 Your lack of confidence is justified - this won't work.
6390 Flex has in it a widespread assumption that the input is processed
6391 one byte at a time. Fixing this is on the to-do list, but is involved,
6392 so it won't happen any time soon. In the interim, the best I can suggest
6393 (unless you want to try fixing it yourself) is to write your rules in
6394 terms of pairs of bytes, using definitions in the first section:
6399 foo{X}bar found_foo_fe_c2_bar();
6401 etc. Definitely a pain - sorry about that.
6403 By the way, the email address you used for me is ancient, indicating you
6404 have a very old version of flex. You can get the most recent, 2.5.4, from
6411 @c TODO: Evaluate this faq.
6413 @unnumberedsec deleteme01
6416 To: moleary@primus.com
6417 Subject: Re: Flex / Unicode compatibility question
6418 In-reply-to: Your message of Tue, 22 Oct 1996 10:15:42 PDT.
6419 Date: Tue, 22 Oct 1996 11:06:13 PDT
6420 From: Vern Paxson <vern>
6422 Unfortunately flex at the moment has a widespread assumption within it
6423 that characters are processed 8 bits at a time. I don't see any easy
6424 fix for this (other than writing your rules in terms of double characters -
6425 a pain). I also don't know of a wider lex, though you might try surfing
6426 the Plan 9 stuff because I know it's a Unicode system, and also the PCCT
6427 toolkit (try searching say Alta Vista for "Purdue Compiler Construction
6430 Fixing flex to handle wider characters is on the long-term to-do list.
6431 But since flex is a strictly spare-time project these days, this probably
6432 won't happen for quite a while, unless someone else does it first.
6438 @c TODO: Evaluate this faq.
6439 @node Can you discuss some flex internals?
6440 @unnumberedsec Can you discuss some flex internals?
6443 To: Johan Linde <jl@theophys.kth.se>
6444 Subject: Re: translation of flex
6445 In-reply-to: Your message of Sun, 10 Nov 1996 09:16:36 PST.
6446 Date: Mon, 11 Nov 1996 10:33:50 PST
6447 From: Vern Paxson <vern>
6449 > I'm working for the Swedish team translating GNU program, and I'm currently
6450 > working with flex. I have a few questions about some of the messages which
6451 > I hope you can answer.
6453 All of the things you're wondering about, by the way, concerning flex
6454 internals - probably the only person who understands what they mean in
6455 English is me! So I wouldn't worry too much about getting them right.
6459 > msgid " %d protos created\n"
6461 > Does proto mean prototype?
6463 Yes - prototypes of state compression tables.
6466 > msgid " %d/%d (peak %d) template nxt-chk entries created\n"
6468 > Here I'm mainly puzzled by 'nxt-chk'. I guess it means 'next-check'. (?)
6469 > However, 'template next-check entries' doesn't make much sense to me. To be
6470 > able to find a good translation I need to know a little bit more about it.
6472 There is a scheme in the Aho/Sethi/Ullman compiler book for compressing
6473 scanner tables. It involves creating two pairs of tables. The first has
6474 "base" and "default" entries, the second has "next" and "check" entries.
6475 The "base" entry is indexed by the current state and yields an index into
6476 the next/check table. The "default" entry gives what to do if the state
6477 transition isn't found in next/check. The "next" entry gives the next
6478 state to enter, but only if the "check" entry verifies that this entry is
6479 correct for the current state. Flex creates templates of series of
6480 next/check entries and then encodes differences from these templates as a
6481 way to compress the tables.
6484 > msgid " %d/%d base-def entries created\n"
6486 > The same problem here for 'base-def'.
6494 @c TODO: Evaluate this faq.
6495 @node unput() messes up yy_at_bol
6496 @unnumberedsec unput() messes up yy_at_bol
6499 To: Xinying Li <xli@npac.syr.edu>
6501 In-reply-to: Your message of Wed, 13 Nov 1996 17:28:38 PST.
6502 Date: Wed, 13 Nov 1996 19:51:54 PST
6503 From: Vern Paxson <vern>
6505 > "unput()" them to input flow, question occurs. If I do this after I scan
6506 > a carriage, the variable "YY_CURRENT_BUFFER->yy_at_bol" is changed. That
6507 > means the carriage flag has gone.
6509 You can control this by calling yy_set_bol(). It's described in the manual.
6511 > And if in pre-reading it goes to the end of file, is anything done
6512 > to control the end of curren buffer and end of file?
6514 No, there's no way to put back an end-of-file.
6516 > By the way I am using flex 2.5.2 and using the "-l".
6518 The latest release is 2.5.4, by the way. It fixes some bugs in 2.5.2 and
6519 2.5.3. You can get it from ftp.ee.lbl.gov.
6525 @c TODO: Evaluate this faq.
6526 @node The | operator is not doing what I want
6527 @unnumberedsec The | operator is not doing what I want
6530 To: Alain.ISSARD@st.com
6531 Subject: Re: Start condition with FLEX
6532 In-reply-to: Your message of Mon, 18 Nov 1996 09:45:02 PST.
6533 Date: Mon, 18 Nov 1996 10:41:34 PST
6534 From: Vern Paxson <vern>
6536 > I am not able to use the start condition scope and to use the | (OR) with
6537 > rules having start conditions.
6539 The problem is that if you use '|' as a regular expression operator, for
6540 example "a|b" meaning "match either 'a' or 'b'", then it must *not* have
6541 any blanks around it. If you instead want the special '|' *action* (which
6542 from your scanner appears to be the case), which is a way of giving two
6543 different rules the same action:
6546 bar matched_foo_or_bar();
6548 then '|' *must* be separated from the first rule by whitespace and *must*
6549 be followed by a new line. You *cannot* write it as:
6551 foo | bar matched_foo_or_bar();
6553 even though you might think you could because yacc supports this syntax.
6554 The reason for this unfortunately incompatibility is historical, but it's
6555 unlikely to be changed.
6557 Your problems with start condition scope are simply due to syntax errors
6558 from your use of '|' later confusing flex.
6560 Let me know if you still have problems.
6566 @c TODO: Evaluate this faq.
6567 @node Why can't flex understand this variable trailing context pattern?
6568 @unnumberedsec Why can't flex understand this variable trailing context pattern?
6571 To: Gregory Margo <gmargo@newton.vip.best.com>
6572 Subject: Re: flex-2.5.3 bug report
6573 In-reply-to: Your message of Sat, 23 Nov 1996 16:50:09 PST.
6574 Date: Sat, 23 Nov 1996 17:07:32 PST
6575 From: Vern Paxson <vern>
6577 > Enclosed is a lex file that "real" lex will process, but I cannot get
6578 > flex to process it. Could you try it and maybe point me in the right direction?
6580 Your problem is that some of the definitions in the scanner use the '/'
6581 trailing context operator, and have it enclosed in ()'s. Flex does not
6582 allow this operator to be enclosed in ()'s because doing so allows undefined
6583 regular expressions such as "(a/b)+". So the solution is to remove the
6584 parentheses. Note that you must also be building the scanner with the -l
6585 option for AT&T lex compatibility. Without this option, flex automatically
6586 encloses the definitions in parentheses.
6592 @c TODO: Evaluate this faq.
6593 @node The ^ operator isn't working
6594 @unnumberedsec The ^ operator isn't working
6597 To: Thomas Hadig <hadig@toots.physik.rwth-aachen.de>
6598 Subject: Re: Flex Bug ?
6599 In-reply-to: Your message of Tue, 26 Nov 1996 14:35:01 PST.
6600 Date: Tue, 26 Nov 1996 11:15:05 PST
6601 From: Vern Paxson <vern>
6603 > In my lexer code, i have the line :
6606 > Thus all lines starting with an astrix (*) are comment lines.
6607 > This does not work !
6609 I can't get this problem to reproduce - it works fine for me. Note
6610 though that if what you have is slightly different:
6616 then it won't work, because flex pushes back macro definitions enclosed
6617 in ()'s, so the rule becomes
6621 and now that the '^' operator is not at the immediate beginning of the
6622 line, it's interpreted as just a regular character. You can avoid this
6623 behavior by using the "-l" lex-compatibility flag, or "%option lex-compat".
6629 @c TODO: Evaluate this faq.
6630 @node Trailing context is getting confused with trailing optional patterns
6631 @unnumberedsec Trailing context is getting confused with trailing optional patterns
6634 To: Adoram Rogel <adoram@hybridge.com>
6635 Subject: Re: Flex 2.5.4 BOF ???
6636 In-reply-to: Your message of Tue, 26 Nov 1996 16:10:41 PST.
6637 Date: Wed, 27 Nov 1996 10:56:25 PST
6638 From: Vern Paxson <vern>
6640 > Organization(s)?/[a-z]
6642 > This matched "Organizations" (looking in debug mode, the trailing s
6643 > was matched with trailing context instead of the optional (s) in the
6646 That should only happen with lex. Flex can properly match this pattern.
6647 (That might be what you're saying, I'm just not sure.)
6649 > Is there a way to avoid this dangerous trailing context problem ?
6651 Unfortunately, there's no easy way. On the other hand, I don't see why
6652 it should be a problem. Lex's matching is clearly wrong, and I'd hope
6653 that usually the intent remains the same as expressed with the pattern,
6654 so flex's matching will be correct.
6660 @c TODO: Evaluate this faq.
6661 @node Is flex GNU or not?
6662 @unnumberedsec Is flex GNU or not?
6665 To: Cameron MacKinnon <mackin@interlog.com>
6666 Subject: Re: Flex documentation bug
6667 In-reply-to: Your message of Mon, 02 Dec 1996 00:07:08 PST.
6668 Date: Sun, 01 Dec 1996 22:29:39 PST
6669 From: Vern Paxson <vern>
6671 > I'm not sure how or where to submit bug reports (documentation or
6672 > otherwise) for the GNU project stuff ...
6674 Well, strictly speaking flex isn't part of the GNU project. They just
6675 distribute it because no one's written a decent GPL'd lex replacement.
6676 So you should send bugs directly to me. Those sent to the GNU folks
6677 sometimes find there way to me, but some may drop between the cracks.
6679 > In GNU Info, under the section 'Start Conditions', and also in the man
6680 > page (mine's dated April '95) is a nice little snippet showing how to
6681 > parse C quoted strings into a buffer, defined to be MAX_STR_CONST in
6682 > size. Unfortunately, no overflow checking is ever done ...
6684 This is already mentioned in the manual:
6686 Finally, here's an example of how to match C-style quoted
6687 strings using exclusive start conditions, including expanded
6688 escape sequences (but not including checking for a string
6691 The reason for not doing the overflow checking is that it will needlessly
6692 clutter up an example whose main purpose is just to demonstrate how to
6695 The latest release is 2.5.4, by the way, available from ftp.ee.lbl.gov.
6701 @c TODO: Evaluate this faq.
6703 @unnumberedsec ERASEME53
6706 To: tsv@cs.UManitoba.CA
6707 Subject: Re: Flex (reg)..
6708 In-reply-to: Your message of Thu, 06 Mar 1997 23:50:16 PST.
6709 Date: Thu, 06 Mar 1997 15:54:19 PST
6710 From: Vern Paxson <vern>
6712 > [:alpha:] ([:alnum:] | \\_)*
6714 If your rule really has embedded blanks as shown above, then it won't
6715 work, as the first blank delimits the rule from the action. (It wouldn't
6716 even compile ...) You need instead:
6718 [:alpha:]([:alnum:]|\\_)*
6720 and that should work fine - there's no restriction on what can go inside
6721 of ()'s except for the trailing context operator, '/'.
6727 @c TODO: Evaluate this faq.
6728 @node I need to scan if-then-else blocks and while loops
6729 @unnumberedsec I need to scan if-then-else blocks and while loops
6732 To: "Mike Stolnicki" <mstolnic@ford.com>
6733 Subject: Re: FLEX help
6734 In-reply-to: Your message of Fri, 30 May 1997 13:33:27 PDT.
6735 Date: Fri, 30 May 1997 10:46:35 PDT
6736 From: Vern Paxson <vern>
6738 > We'd like to add "if-then-else", "while", and "for" statements to our
6740 > We've investigated many possible solutions. The one solution that seems
6741 > the most reasonable involves knowing the position of a TOKEN in yyin.
6743 I strongly advise you to instead build a parse tree (abstract syntax tree)
6744 and loop over that instead. You'll find this has major benefits in keeping
6745 your interpreter simple and extensible.
6747 That said, the functionality you mention for get_position and set_position
6748 have been on the to-do list for a while. As flex is a purely spare-time
6749 project for me, no guarantees when this will be added (in particular, it
6750 for sure won't be for many months to come).
6756 @c TODO: Evaluate this faq.
6758 @unnumberedsec ERASEME55
6761 To: Colin Paul Adams <colin@colina.demon.co.uk>
6762 Subject: Re: Flex C++ classes and Bison
6763 In-reply-to: Your message of 09 Aug 1997 17:11:41 PDT.
6764 Date: Fri, 15 Aug 1997 10:48:19 PDT
6765 From: Vern Paxson <vern>
6767 > #define YY_DECL int yylex (YYSTYPE *lvalp, struct parser_control
6770 > I have been trying to get this to work as a C++ scanner, but it does
6771 > not appear to be possible (warning that it matches no declarations in
6772 > yyFlexLexer, or something like that).
6774 > Is this supposed to be possible, or is it being worked on (I DID
6775 > notice the comment that scanner classes are still experimental, so I'm
6778 What you need to do is derive a subclass from yyFlexLexer that provides
6779 the above yylex() method, squirrels away lvalp and parm into member
6780 variables, and then invokes yyFlexLexer::yylex() to do the regular scanning.
6786 @c TODO: Evaluate this faq.
6788 @unnumberedsec ERASEME56
6791 To: Mikael.Latvala@lmf.ericsson.se
6792 Subject: Re: Possible mistake in Flex v2.5 document
6793 In-reply-to: Your message of Fri, 05 Sep 1997 16:07:24 PDT.
6794 Date: Fri, 05 Sep 1997 10:01:54 PDT
6795 From: Vern Paxson <vern>
6797 > In that example you show how to count comment lines when using
6798 > C style /* ... */ comments. My question is, shouldn't you take into
6799 > account a scenario where end of a comment marker occurs inside
6800 > character or string literals?
6802 The scanner certainly needs to also scan character and string literals.
6803 However it does that (there's an example in the man page for strings), the
6804 lexer will recognize the beginning of the literal before it runs across the
6805 embedded "/*". Consequently, it will finish scanning the literal before it
6806 even considers the possibility of matching "/*".
6810 '([^']*|{ESCAPE_SEQUENCE})'
6812 will match all the text between the ''s (inclusive). So the lexer
6813 considers this as a token beginning at the first ', and doesn't even
6814 attempt to match other tokens inside it.
6816 I thinnk this subtlety is not worth putting in the manual, as I suspect
6817 it would confuse more people than it would enlighten.
6823 @c TODO: Evaluate this faq.
6825 @unnumberedsec ERASEME57
6828 To: "Marty Leisner" <leisner@sdsp.mc.xerox.com>
6829 Subject: Re: flex limitations
6830 In-reply-to: Your message of Sat, 06 Sep 1997 11:27:21 PDT.
6831 Date: Mon, 08 Sep 1997 11:38:08 PDT
6832 From: Vern Paxson <vern>
6835 > [a-zA-Z]+ /* skip a line */
6836 > { printf("got %s\n", yytext); }
6839 What version of flex are you using? If I feed this to 2.5.4, it complains:
6841 "bug.l", line 5: EOF encountered inside an action
6842 "bug.l", line 5: unrecognized rule
6843 "bug.l", line 5: fatal parse error
6845 Not the world's greatest error message, but it manages to flag the problem.
6847 (With the introduction of start condition scopes, flex can't accommodate
6848 an action on a separate line, since it's ambiguous with an indented rule.)
6850 You can get 2.5.4 from ftp.ee.lbl.gov.
6856 @c TODO: Evaluate this faq.
6857 @node Is there a repository for flex scanners?
6858 @unnumberedsec Is there a repository for flex scanners?
6860 Not that we know of. You might try asking on comp.compilers.
6862 @c TODO: Evaluate this faq.
6863 @node How can I conditionally compile or preprocess my flex input file?
6864 @unnumberedsec How can I conditionally compile or preprocess my flex input file?
6867 Flex doesn't have a preprocessor like C does. You might try using m4, or the C
6868 preprocessor plus a sed script to clean up the result.
6871 @c TODO: Evaluate this faq.
6872 @node Where can I find grammars for lex and yacc?
6873 @unnumberedsec Where can I find grammars for lex and yacc?
6875 In the sources for flex and bison.
6877 @c TODO: Evaluate this faq.
6878 @node I get an end-of-buffer message for each character scanned.
6879 @unnumberedsec I get an end-of-buffer message for each character scanned.
6881 This will happen if your LexerInput() function returns only one character
6882 at a time, which can happen either if you're scanner is "interactive", or
6883 if the streams library on your platform always returns 1 for yyin->gcount().
6885 Solution: override LexerInput() with a version that returns whole buffers.
6887 @c TODO: Evaluate this faq.
6888 @node unnamed-faq-62
6889 @unnumberedsec unnamed-faq-62
6892 To: Georg.Rehm@CL-KI.Uni-Osnabrueck.DE
6893 Subject: Re: Flex maximums
6894 In-reply-to: Your message of Mon, 17 Nov 1997 17:16:06 PST.
6895 Date: Mon, 17 Nov 1997 17:16:15 PST
6896 From: Vern Paxson <vern>
6898 > I took a quick look into the flex-sources and altered some #defines in
6901 > #define INITIAL_MNS 64000
6902 > #define MNS_INCREMENT 1024000
6903 > #define MAXIMUM_MNS 64000
6905 The things to fix are to add a couple of zeroes to:
6907 #define JAMSTATE -32766 /* marks a reference to the state that always jams */
6908 #define MAXIMUM_MNS 31999
6909 #define BAD_SUBSCRIPT -32767
6910 #define MAX_SHORT 32700
6912 and, if you get complaints about too many rules, make the following change too:
6914 #define YY_TRAILING_MASK 0x200000
6915 #define YY_TRAILING_HEAD_MASK 0x400000
6921 @c TODO: Evaluate this faq.
6922 @node unnamed-faq-63
6923 @unnumberedsec unnamed-faq-63
6926 To: jimmey@lexis-nexis.com (Jimmey Todd)
6927 Subject: Re: FLEX question regarding istream vs ifstream
6928 In-reply-to: Your message of Mon, 08 Dec 1997 15:54:15 PST.
6929 Date: Mon, 15 Dec 1997 13:21:35 PST
6930 From: Vern Paxson <vern>
6932 > stdin_handle = YY_CURRENT_BUFFER;
6933 > ifstream fin( "aFile" );
6934 > yy_switch_to_buffer( yy_create_buffer( fin, YY_BUF_SIZE ) );
6936 > What I'm wanting to do, is pass the contents of a file thru one set
6937 > of rules and then pass stdin thru another set... It works great if, I
6938 > don't use the C++ classes. But since everything else that I'm doing is
6939 > in C++, I thought I'd be consistent.
6941 > The problem is that 'yy_create_buffer' is expecting an istream* as it's
6942 > first argument (as stated in the man page). However, fin is a ifstream
6943 > object. Any ideas on what I might be doing wrong? Any help would be
6944 > appreciated. Thanks!!
6946 You need to pass &fin, to turn it into an ifstream* instead of an ifstream.
6947 Then its type will be compatible with the expected istream*, because ifstream
6948 is derived from istream.
6954 @c TODO: Evaluate this faq.
6955 @node unnamed-faq-64
6956 @unnumberedsec unnamed-faq-64
6959 To: Enda Fadian <fadiane@piercom.ie>
6960 Subject: Re: Question related to Flex man page?
6961 In-reply-to: Your message of Tue, 16 Dec 1997 15:17:34 PST.
6962 Date: Tue, 16 Dec 1997 14:17:09 PST
6963 From: Vern Paxson <vern>
6965 > Can you explain to me what is ment by a long-jump in relation to flex?
6967 Using the longjmp() function while inside yylex() or a routine called by it.
6969 > what is the flex activation frame.
6971 Just yylex()'s stack frame.
6973 > As far as I can see yyrestart will bring me back to the sart of the input
6974 > file and using flex++ isnot really an option!
6976 No, yyrestart() doesn't imply a rewind, even though its name might sound
6977 like it does. It tells the scanner to flush its internal buffers and
6978 start reading from the given file at its present location.
6984 @c TODO: Evaluate this faq.
6985 @node unnamed-faq-65
6986 @unnumberedsec unnamed-faq-65
6989 To: hassan@larc.info.uqam.ca (Hassan Alaoui)
6990 Subject: Re: Need urgent Help
6991 In-reply-to: Your message of Sat, 20 Dec 1997 19:38:19 PST.
6992 Date: Sun, 21 Dec 1997 21:30:46 PST
6993 From: Vern Paxson <vern>
6995 > /usr/lib/yaccpar: In function `int yyparse()':
6996 > /usr/lib/yaccpar:184: warning: implicit declaration of function `int yylex(...)'
6998 > ld: Undefined symbol
7003 This is a known problem with Solaris C++ (and/or Solaris yacc). I believe
7004 the fix is to explicitly insert some 'extern "C"' statements for the
7005 corresponding routines/symbols.
7011 @c TODO: Evaluate this faq.
7012 @node unnamed-faq-66
7013 @unnumberedsec unnamed-faq-66
7016 To: mc0307@mclink.it
7017 Cc: gnu@prep.ai.mit.edu
7018 Subject: Re: [mc0307@mclink.it: Help request]
7019 In-reply-to: Your message of Fri, 12 Dec 1997 17:57:29 PST.
7020 Date: Sun, 21 Dec 1997 22:33:37 PST
7021 From: Vern Paxson <vern>
7023 > This is my definition for float and integer types:
7027 > I've tested my program on other lex version (on UNIX Sun Solaris an HP
7028 > UNIX) and it work well, so I think that my definitions are correct.
7029 > There are any differences between Lex and Flex?
7031 There are indeed differences, as discussed in the man page. The one
7032 you are probably running into is that when flex expands a name definition,
7033 it puts parentheses around the expansion, while lex does not. There's
7034 an example in the man page of how this can lead to different matching.
7035 Flex's behavior complies with the POSIX standard (or at least with the
7036 last POSIX draft I saw).
7042 @c TODO: Evaluate this faq.
7043 @node unnamed-faq-67
7044 @unnumberedsec unnamed-faq-67
7047 To: hassan@larc.info.uqam.ca (Hassan Alaoui)
7049 In-reply-to: Your message of Mon, 22 Dec 1997 16:06:35 PST.
7050 Date: Mon, 22 Dec 1997 14:35:05 PST
7051 From: Vern Paxson <vern>
7053 > Thank you very much for your help. I compile and link well with C++ while
7054 > declaring 'yylex ...' extern, But a little problem remains. I get a
7055 > segmentation default when executing ( I linked with lfl library) while it
7056 > works well when using LEX instead of flex. Do you have some ideas about the
7059 The one possible reason for this that comes to mind is if you've defined
7060 yytext as "extern char yytext[]" (which is what lex uses) instead of
7061 "extern char *yytext" (which is what flex uses). If it's not that, then
7062 I'm afraid I don't know what the problem might be.
7068 @c TODO: Evaluate this faq.
7069 @node unnamed-faq-68
7070 @unnumberedsec unnamed-faq-68
7073 To: "Bart Niswonger" <NISWONGR@almaden.ibm.com>
7074 Subject: Re: flex 2.5: c++ scanners & start conditions
7075 In-reply-to: Your message of Tue, 06 Jan 1998 10:34:21 PST.
7076 Date: Tue, 06 Jan 1998 19:19:30 PST
7077 From: Vern Paxson <vern>
7079 > The problem is that when I do this (using %option c++) start
7080 > conditions seem to not apply.
7082 The BEGIN macro modifies the yy_start variable. For C scanners, this
7083 is a static with scope visible through the whole file. For C++ scanners,
7084 it's a member variable, so it only has visible scope within a member
7085 function. Your lexbegin() routine is not a member function when you
7086 build a C++ scanner, so it's not modifying the correct yy_start. The
7087 diagnostic that indicates this is that you found you needed to add
7088 a declaration of yy_start in order to get your scanner to compile when
7089 using C++; instead, the correct fix is to make lexbegin() a member
7090 function (by deriving from yyFlexLexer).
7096 @c TODO: Evaluate this faq.
7097 @node unnamed-faq-69
7098 @unnumberedsec unnamed-faq-69
7101 To: "Boris Zinin" <boris@ippe.rssi.ru>
7102 Subject: Re: current position in flex buffer
7103 In-reply-to: Your message of Mon, 12 Jan 1998 18:58:23 PST.
7104 Date: Mon, 12 Jan 1998 12:03:15 PST
7105 From: Vern Paxson <vern>
7107 > The problem is how to determine the current position in flex active
7108 > buffer when a rule is matched....
7110 You will need to keep track of this explicitly, such as by redefining
7111 YY_USER_ACTION to count the number of characters matched.
7113 The latest flex release, by the way, is 2.5.4, available from ftp.ee.lbl.gov.
7119 @c TODO: Evaluate this faq.
7120 @node unnamed-faq-70
7121 @unnumberedsec unnamed-faq-70
7124 To: Bik.Dhaliwal@bis.org
7125 Subject: Re: Flex question
7126 In-reply-to: Your message of Mon, 26 Jan 1998 13:05:35 PST.
7127 Date: Tue, 27 Jan 1998 22:41:52 PST
7128 From: Vern Paxson <vern>
7130 > That requirement involves knowing
7131 > the character position at which a particular token was matched
7134 The way you have to do this is by explicitly keeping track of where
7135 you are in the file, by counting the number of characters scanned
7136 for each token (available in yyleng). It may prove convenient to
7137 do this by redefining YY_USER_ACTION, as described in the manual.
7143 @c TODO: Evaluate this faq.
7144 @node unnamed-faq-71
7145 @unnumberedsec unnamed-faq-71
7148 To: Vladimir Alexiev <vladimir@cs.ualberta.ca>
7149 Subject: Re: flex: how to control start condition from parser?
7150 In-reply-to: Your message of Mon, 26 Jan 1998 05:50:16 PST.
7151 Date: Tue, 27 Jan 1998 22:45:37 PST
7152 From: Vern Paxson <vern>
7154 > It seems useful for the parser to be able to tell the lexer about such
7155 > context dependencies, because then they don't have to be limited to
7156 > local or sequential context.
7158 One way to do this is to have the parser call a stub routine that's
7159 included in the scanner's .l file, and consequently that has access ot
7160 BEGIN. The only ugliness is that the parser can't pass in the state
7161 it wants, because those aren't visible - but if you don't have many
7162 such states, then using a different set of names doesn't seem like
7163 to much of a burden.
7165 While generating a .h file like you suggests is certainly cleaner,
7166 flex development has come to a virtual stand-still :-(, so a workaround
7167 like the above is much more pragmatic than waiting for a new feature.
7173 @c TODO: Evaluate this faq.
7174 @node unnamed-faq-72
7175 @unnumberedsec unnamed-faq-72
7178 To: Barbara Denny <denny@3com.com>
7179 Subject: Re: freebsd flex bug?
7180 In-reply-to: Your message of Fri, 30 Jan 1998 12:00:43 PST.
7181 Date: Fri, 30 Jan 1998 12:42:32 PST
7182 From: Vern Paxson <vern>
7184 > lex.yy.c:1996: parse error before `='
7186 This is the key, identifying this error. (It may help to pinpoint
7187 it by using flex -L, so it doesn't generate #line directives in its
7188 output.) I will bet you heavy money that you have a start condition
7189 name that is also a variable name, or something like that; flex spits
7190 out #define's for each start condition name, mapping them to a number,
7191 so you can wind up with:
7202 and the penultimate will turn into "int 1 = 3" after C preprocessing,
7203 since flex will put "#define foo 1" in the generated scanner.
7209 @c TODO: Evaluate this faq.
7210 @node unnamed-faq-73
7211 @unnumberedsec unnamed-faq-73
7214 To: Maurice Petrie <mpetrie@infoscigroup.com>
7215 Subject: Re: Lost flex .l file
7216 In-reply-to: Your message of Mon, 02 Feb 1998 14:10:01 PST.
7217 Date: Mon, 02 Feb 1998 11:15:12 PST
7218 From: Vern Paxson <vern>
7220 > I am curious as to
7221 > whether there is a simple way to backtrack from the generated source to
7222 > reproduce the lost list of tokens we are searching on.
7224 In theory, it's straight-forward to go from the DFA representation
7225 back to a regular-expression representation - the two are isomorphic.
7226 In practice, a huge headache, because you have to unpack all the tables
7227 back into a single DFA representation, and then write a program to munch
7228 on that and translate it into an RE.
7230 Sorry for the less-than-happy news ...
7236 @c TODO: Evaluate this faq.
7237 @node unnamed-faq-74
7238 @unnumberedsec unnamed-faq-74
7241 To: jimmey@lexis-nexis.com (Jimmey Todd)
7242 Subject: Re: Flex performance question
7243 In-reply-to: Your message of Thu, 19 Feb 1998 11:01:17 PST.
7244 Date: Thu, 19 Feb 1998 08:48:51 PST
7245 From: Vern Paxson <vern>
7247 > What I have found, is that the smaller the data chunk, the faster the
7248 > program executes. This is the opposite of what I expected. Should this be
7249 > happening this way?
7251 This is exactly what will happen if your input file has embedded NULs.
7254 A final note: flex is slow when matching NUL's, particularly
7255 when a token contains multiple NUL's. It's best to write
7256 rules which match short amounts of text if it's anticipated
7257 that the text will often include NUL's.
7259 So that's the first thing to look for.
7265 @c TODO: Evaluate this faq.
7266 @node unnamed-faq-75
7267 @unnumberedsec unnamed-faq-75
7270 To: jimmey@lexis-nexis.com (Jimmey Todd)
7271 Subject: Re: Flex performance question
7272 In-reply-to: Your message of Thu, 19 Feb 1998 11:01:17 PST.
7273 Date: Thu, 19 Feb 1998 15:42:25 PST
7274 From: Vern Paxson <vern>
7276 So there are several problems.
7278 First, to go fast, you want to match as much text as possible, which
7279 your scanners don't in the case that what they're scanning is *not*
7280 a <RN> tag. So you want a rule like:
7284 Second, C++ scanners are particularly slow if they're interactive,
7285 which they are by default. Using -B speeds it up by a factor of 3-4
7288 Third, C++ scanners that use the istream interface are slow, because
7289 of how poorly implemented istream's are. I built two versions of
7290 the following scanner:
7297 and the C version inhales a 2.5MB file on my workstation in 0.8 seconds.
7298 The C++ istream version, using -B, takes 3.8 seconds.
7304 @c TODO: Evaluate this faq.
7305 @node unnamed-faq-76
7306 @unnumberedsec unnamed-faq-76
7309 To: "Frescatore, David (CRD, TAD)" <frescatore@exc01crdge.crd.ge.com>
7310 Subject: Re: FLEX 2.5 & THE YEAR 2000
7311 In-reply-to: Your message of Wed, 03 Jun 1998 11:26:22 PDT.
7312 Date: Wed, 03 Jun 1998 10:22:26 PDT
7313 From: Vern Paxson <vern>
7315 > I am researching the Y2K problem with General Electric R&D
7316 > and need to know if there are any known issues concerning
7317 > the above mentioned software and Y2K regardless of version.
7319 There shouldn't be, all it ever does with the date is ask the system
7320 for it and then print it out.
7326 @c TODO: Evaluate this faq.
7327 @node unnamed-faq-77
7328 @unnumberedsec unnamed-faq-77
7331 To: "Hans Dermot Doran" <htd@ibhdoran.com>
7332 Subject: Re: flex problem
7333 In-reply-to: Your message of Wed, 15 Jul 1998 21:30:13 PDT.
7334 Date: Tue, 21 Jul 1998 14:23:34 PDT
7335 From: Vern Paxson <vern>
7337 > To overcome this, I gets() the stdin into a string and lex the string. The
7338 > string is lexed OK except that the end of string isn't lexed properly
7339 > (yy_scan_string()), that is the lexer dosn't recognise the end of string.
7341 Flex doesn't contain mechanisms for recognizing buffer endpoints. But if
7342 you use fgets instead (which you should anyway, to protect against buffer
7343 overflows), then the final \n will be preserved in the string, and you can
7344 scan that in order to find the end of the string.
7350 @c TODO: Evaluate this faq.
7351 @node unnamed-faq-78
7352 @unnumberedsec unnamed-faq-78
7355 To: soumen@almaden.ibm.com
7356 Subject: Re: Flex++ 2.5.3 instance member vs. static member
7357 In-reply-to: Your message of Mon, 27 Jul 1998 02:10:04 PDT.
7358 Date: Tue, 28 Jul 1998 01:10:34 PDT
7359 From: Vern Paxson <vern>
7369 > Now you'd expect mylineno to be a member of each instance of class
7370 > yyFlexLexer, but is this the case? A look at the lex.yy.cc file seems to
7371 > indicate otherwise; unless I am missing something the declaration of
7372 > mylineno seems to be outside any class scope.
7374 > How will this work if I want to run a multi-threaded application with each
7375 > thread creating a FlexLexer instance?
7377 Derive your own subclass and make mylineno a member variable of it.
7383 @c TODO: Evaluate this faq.
7384 @node unnamed-faq-79
7385 @unnumberedsec unnamed-faq-79
7388 To: Adoram Rogel <adoram@hybridge.com>
7389 Subject: Re: More than 32K states change hangs
7390 In-reply-to: Your message of Tue, 04 Aug 1998 16:55:39 PDT.
7391 Date: Tue, 04 Aug 1998 22:28:45 PDT
7392 From: Vern Paxson <vern>
7396 > I followed your advice, posted on Usenet bu you, and emailed to me
7397 > personally by you, on how to overcome the 32K states limit. I'm running
7398 > on Linux machines.
7399 > I took the full source of version 2.5.4 and did the following changes in
7401 > #define JAMSTATE -327660
7402 > #define MAXIMUM_MNS 319990
7403 > #define BAD_SUBSCRIPT -327670
7404 > #define MAX_SHORT 327000
7407 > All looked fine, including check and bigcheck, so I installed.
7409 Hmmm, you shouldn't increase MAX_SHORT, though looking through my email
7410 archives I see that I did indeed recommend doing so. Try setting it back
7411 to 32700; that should suffice that you no longer need -Ca. If it still
7412 hangs, then the interesting question is - where?
7414 > Compiling the same hanged program with a out-of-the-box (RedHat 4.2
7415 > distribution of Linux)
7416 > flex 2.5.4 binary works.
7418 Since Linux comes with source code, you should diff it against what
7419 you have to see what problems they missed.
7421 > Should I always compile with the -Ca option now ? even short and simple
7424 No, definitely not. It's meant to be for those situations where you
7425 absolutely must squeeze every last cycle out of your scanner.
7431 @c TODO: Evaluate this faq.
7432 @node unnamed-faq-80
7433 @unnumberedsec unnamed-faq-80
7436 To: "Schmackpfeffer, Craig" <Craig.Schmackpfeffer@usa.xerox.com>
7437 Subject: Re: flex output for static code portion
7438 In-reply-to: Your message of Tue, 11 Aug 1998 11:55:30 PDT.
7439 Date: Mon, 17 Aug 1998 23:57:42 PDT
7440 From: Vern Paxson <vern>
7442 > I would like to use flex under the hood to generate a binary file
7443 > containing the data structures that control the parse.
7445 This has been on the wish-list for a long time. In principle it's
7446 straight-forward - you redirect mkdata() et al's I/O to another file,
7447 and modify the skeleton to have a start-up function that slurps these
7448 into dynamic arrays. The concerns are (1) the scanner generation code
7449 is hairy and full of corner cases, so it's easy to get surprised when
7450 going down this path :-( ; and (2) being careful about buffering so
7451 that when the tables change you make sure the scanner starts in the
7452 correct state and reading at the right point in the input file.
7454 > I was wondering if you know of anyone who has used flex in this way.
7456 I don't - but it seems like a reasonable project to undertake (unlike
7457 numerous other flex tweaks :-).
7463 @c TODO: Evaluate this faq.
7464 @node unnamed-faq-81
7465 @unnumberedsec unnamed-faq-81
7468 Received: from 131.173.17.11 (131.173.17.11 [131.173.17.11])
7469 by ee.lbl.gov (8.9.1/8.9.1) with ESMTP id AAA03838
7470 for <vern@ee.lbl.gov>; Thu, 20 Aug 1998 00:47:57 -0700 (PDT)
7471 Received: from hal.cl-ki.uni-osnabrueck.de (hal.cl-ki.Uni-Osnabrueck.DE [131.173.141.2])
7472 by deimos.rz.uni-osnabrueck.de (8.8.7/8.8.8) with ESMTP id JAA34694
7473 for <vern@ee.lbl.gov>; Thu, 20 Aug 1998 09:47:55 +0200
7474 Received: (from georg@localhost) by hal.cl-ki.uni-osnabrueck.de (8.6.12/8.6.12) id JAA34834 for vern@ee.lbl.gov; Thu, 20 Aug 1998 09:47:54 +0200
7475 From: Georg Rehm <georg@hal.cl-ki.uni-osnabrueck.de>
7476 Message-Id: <199808200747.JAA34834@hal.cl-ki.uni-osnabrueck.de>
7477 Subject: "flex scanner push-back overflow"
7479 Date: Thu, 20 Aug 1998 09:47:54 +0200 (MEST)
7480 Reply-To: Georg.Rehm@CL-KI.Uni-Osnabrueck.DE
7481 X-NoJunk: Do NOT send commercial mail, spam or ads to this address!
7482 X-URL: http://www.cl-ki.uni-osnabrueck.de/~georg/
7483 X-Mailer: ELM [version 2.4ME+ PL28 (25)]
7485 Content-Type: text/plain; charset=US-ASCII
7486 Content-Transfer-Encoding: 7bit
7490 Yesterday, I encountered a strange problem: I use the macro processor m4
7491 to include some lengthy lists into a .l file. Following is a flex macro
7492 definition that causes some serious pain in my neck:
7494 AUTHOR ("A. Boucard / L. Boucard"|"A. Dastarac / M. Levent"|"A.Boucaud / L.Boucaud"|"Abderrahim Lamchichi"|"Achmat Dangor"|"Adeline Toullier"|"Adewale Maja-Pearce"|"Ahmed Ziri"|"Akram Ellyas"|"Alain Bihr"|"Alain Gresh"|"Alain Guillemoles"|"Alain Joxe"|"Alain Morice"|"Alain Renon"|"Alain Zecchini"|"Albert Memmi"|"Alberto Manguel"|"Alex De Waal"|"Alfonso Artico"| [...])
7496 The complete list contains about 10kB. When I try to "flex" this file
7497 (on a Solaris 2.6 machine, using a modified flex 2.5.4 (I only increased
7498 some of the predefined values in flexdefs.h) I get the error:
7500 myflex/flex -8 sentag.tmp.l
7501 flex scanner push-back overflow
7503 When I remove the slashes in the macro definition everything works fine.
7504 As I understand it, the double quotes escape the slash-character so it
7505 really means "/" and not "trailing context". Furthermore, I tried to
7506 escape the slashes with backslashes, but with no use, the same error message
7507 appeared when flexing the code.
7509 Do you have an idea what's going on here?
7511 Greetings from Germany,
7514 Georg Rehm georg@cl-ki.uni-osnabrueck.de
7515 Institute for Semantic Information Processing, University of Osnabrueck, FRG
7519 @c TODO: Evaluate this faq.
7520 @node unnamed-faq-82
7521 @unnumberedsec unnamed-faq-82
7524 To: Georg.Rehm@CL-KI.Uni-Osnabrueck.DE
7525 Subject: Re: "flex scanner push-back overflow"
7526 In-reply-to: Your message of Thu, 20 Aug 1998 09:47:54 PDT.
7527 Date: Thu, 20 Aug 1998 07:05:35 PDT
7528 From: Vern Paxson <vern>
7530 > myflex/flex -8 sentag.tmp.l
7531 > flex scanner push-back overflow
7533 Flex itself uses a flex scanner. That scanner is running out of buffer
7534 space when it tries to unput() the humongous macro you've defined. When
7535 you remove the '/'s, you make it small enough so that it fits in the buffer;
7536 removing spaces would do the same thing.
7538 The fix is to either rethink how come you're using such a big macro and
7539 perhaps there's another/better way to do it; or to rebuild flex's own
7540 scan.c with a larger value for
7542 #define YY_BUF_SIZE 16384
7548 @c TODO: Evaluate this faq.
7549 @node unnamed-faq-83
7550 @unnumberedsec unnamed-faq-83
7553 To: Jan Kort <jan@research.techforce.nl>
7555 In-reply-to: Your message of Fri, 04 Sep 1998 12:18:43 +0200.
7556 Date: Sat, 05 Sep 1998 00:59:49 PDT
7557 From: Vern Paxson <vern>
7561 > "TEST1\n" { fprintf(stderr, "TEST1\n"); yyless(5); }
7562 > ^\n { fprintf(stderr, "empty line\n"); }
7564 > \n { fprintf(stderr, "new line\n"); }
7567 > -- input ---------------------------------------
7569 > -- output --------------------------------------
7572 > ------------------------------------------------
7574 IMHO, it's not clear whether or not this is in fact a bug. It depends
7575 on whether you view yyless() as backing up in the input stream, or as
7576 pushing new characters onto the beginning of the input stream. Flex
7577 interprets it as the latter (for implementation convenience, I'll admit),
7578 and so considers the newline as in fact matching at the beginning of a
7579 line, as after all the last token scanned an entire line and so the
7580 scanner is now at the beginning of a new line.
7582 I agree that this is counter-intuitive for yyless(), given its
7583 functional description (it's less so for unput(), depending on whether
7584 you're unput()'ing new text or scanned text). But I don't plan to
7585 change it any time soon, as it's a pain to do so. Consequently,
7586 you do indeed need to use yy_set_bol() and YY_AT_BOL() to tweak
7587 your scanner into the behavior you desire.
7589 Sorry for the less-than-completely-satisfactory answer.
7595 @c TODO: Evaluate this faq.
7596 @node unnamed-faq-84
7597 @unnumberedsec unnamed-faq-84
7600 To: Patrick Krusenotto <krusenot@mac-info-link.de>
7601 Subject: Re: Problems with restarting flex-2.5.2-generated scanner
7602 In-reply-to: Your message of Thu, 24 Sep 1998 10:14:07 PDT.
7603 Date: Thu, 24 Sep 1998 23:28:43 PDT
7604 From: Vern Paxson <vern>
7606 > I am using flex-2.5.2 and bison 1.25 for Solaris and I am desperately
7607 > trying to make my scanner restart with a new file after my parser stops
7608 > with a parse error. When my compiler restarts, the parser always
7609 > receives the token after the token (in the old file!) that caused the
7612 I suspect the problem is that your parser has read ahead in order
7613 to attempt to resolve an ambiguity, and when it's restarted it picks
7614 up with that token rather than reading a fresh one. If you're using
7615 yacc, then the special "error" production can sometimes be used to
7616 consume tokens in an attempt to get the parser into a consistent state.
7622 @c TODO: Evaluate this faq.
7623 @node unnamed-faq-85
7624 @unnumberedsec unnamed-faq-85
7627 To: Henric Jungheim <junghelh@pe-nelson.com>
7628 Subject: Re: flex 2.5.4a
7629 In-reply-to: Your message of Tue, 27 Oct 1998 16:41:42 PST.
7630 Date: Tue, 27 Oct 1998 16:50:14 PST
7631 From: Vern Paxson <vern>
7633 > This brings up a feature request: How about a command line
7634 > option to specify the filename when reading from stdin? That way one
7635 > doesn't need to create a temporary file in order to get the "#line"
7636 > directives to make sense.
7638 Use -o combined with -t (per the man page description of -o).
7640 > P.S., Is there any simple way to use non-blocking IO to parse multiple
7645 One approach might be to return a magic character on EWOULDBLOCK and
7648 .*<magic-character> // put back .*, eat magic character
7650 This is off the top of my head, not sure it'll work.
7656 @c TODO: Evaluate this faq.
7657 @node unnamed-faq-86
7658 @unnumberedsec unnamed-faq-86
7661 To: "Repko, Billy D" <billy.d.repko@intel.com>
7662 Subject: Re: Compiling scanners
7663 In-reply-to: Your message of Wed, 13 Jan 1999 10:52:47 PST.
7664 Date: Thu, 14 Jan 1999 00:25:30 PST
7665 From: Vern Paxson <vern>
7667 > It appears that maybe it cannot find the lfl library.
7669 The Makefile in the distribution builds it, so you should have it.
7670 It's exceedingly trivial, just a main() that calls yylex() and
7671 a yyrap() that always returns 1.
7674 > \n ++num_lines; ++num_chars;
7677 You can't indent your rules like this - that's where the errors are coming
7678 from. Flex copies indented text to the output file, it's how you do things
7681 int num_lines_seen = 0;
7683 to declare local variables.
7689 @c TODO: Evaluate this faq.
7690 @node unnamed-faq-87
7691 @unnumberedsec unnamed-faq-87
7694 To: Erick Branderhorst <Erick.Branderhorst@asml.nl>
7695 Subject: Re: flex input buffer
7696 In-reply-to: Your message of Tue, 09 Feb 1999 13:53:46 PST.
7697 Date: Tue, 09 Feb 1999 21:03:37 PST
7698 From: Vern Paxson <vern>
7700 > In the flex.skl file the size of the default input buffers is set. Can you
7701 > explain why this size is set and why it is such a high number.
7703 It's large to optimize performance when scanning large files. You can
7704 safely make it a lot lower if needed.
7710 @c TODO: Evaluate this faq.
7711 @node unnamed-faq-88
7712 @unnumberedsec unnamed-faq-88
7715 To: "Guido Minnen" <guidomi@cogs.susx.ac.uk>
7716 Subject: Re: Flex error message
7717 In-reply-to: Your message of Wed, 24 Feb 1999 15:31:46 PST.
7718 Date: Thu, 25 Feb 1999 00:11:31 PST
7719 From: Vern Paxson <vern>
7721 > I'm extending a larger scanner written in Flex and I keep running into
7722 > problems. More specifically, I get the error message:
7723 > "flex: input rules are too complicated (>= 32000 NFA states)"
7725 Increase the definitions in flexdef.h for:
7727 #define JAMSTATE -32766 /* marks a reference to the state that always j
7729 #define MAXIMUM_MNS 31999
7730 #define BAD_SUBSCRIPT -32767
7732 recompile everything, and it should all work.
7738 @c TODO: Evaluate this faq.
7739 @node unnamed-faq-90
7740 @unnumberedsec unnamed-faq-90
7743 To: "Dmitriy Goldobin" <gold@ems.chel.su>
7744 Subject: Re: FLEX trouble
7745 In-reply-to: Your message of Mon, 31 May 1999 18:44:49 PDT.
7746 Date: Tue, 01 Jun 1999 00:15:07 PDT
7747 From: Vern Paxson <vern>
7749 > I have a trouble with FLEX. Why rule "/*".*"*/" work properly,=20
7750 > but rule "/*"(.|\n)*"*/" don't work ?
7752 The second of these will have to scan the entire input stream (because
7753 "(.|\n)*" matches an arbitrary amount of any text) in order to see if
7754 it ends with "*/", terminating the comment. That potentially will overflow
7757 > More complex rule "/*"([^*]|(\*/[^/]))*"*/ give an error
7758 > 'unrecognized rule'.
7760 You can't use the '/' operator inside parentheses. It's not clear
7761 what "(a/b)*" actually means.
7763 > I now use workaround with state <comment>, but single-rule is
7766 Single-rule is nice but will always have the problem of either setting
7767 restrictions on comments (like not allowing multi-line comments) and/or
7768 running the risk of consuming the entire input stream, as noted above.
7774 @c TODO: Evaluate this faq.
7775 @node unnamed-faq-91
7776 @unnumberedsec unnamed-faq-91
7779 Received: from mc-qout4.whowhere.com (mc-qout4.whowhere.com [209.185.123.18])
7780 by ee.lbl.gov (8.9.3/8.9.3) with SMTP id IAA05100
7781 for <vern@ee.lbl.gov>; Tue, 15 Jun 1999 08:56:06 -0700 (PDT)
7782 Received: from Unknown/Local ([?.?.?.?]) by my-deja.com; Tue Jun 15 08:55:43 1999
7784 Date: Tue, 15 Jun 1999 08:55:43 -0700
7785 From: "Aki Niimura" <neko@my-deja.com>
7786 Message-ID: <KNONDOHDOBGAEAAA@my-deja.com>
7791 X-Mailer: MailCity Service
7792 Subject: A question on flex C++ scanner
7793 X-Sender-Ip: 12.72.207.61
7794 Organization: My Deja Email (http://www.my-deja.com:80)
7795 Content-Type: text/plain; charset=us-ascii
7796 Content-Transfer-Encoding: 7bit
7800 I have been using flex for years.
7801 It works very well on many projects.
7802 Most case, I used it to generate a scanner on C language.
7803 However, one project I needed to generate a scanner
7804 on C++ lanuage. Thanks to your enhancement, flex did
7807 Currently, I'm working on enhancing my previous project.
7808 I need to deal with multiple input streams (recursive
7809 inclusion) in this scanner (C++).
7810 I did similar thing for another scanner (C) as you
7811 explained in your documentation.
7813 The generated scanner (C++) has necessary methods:
7814 - switch_to_buffer(struct yy_buffer_state *b)
7815 - yy_create_buffer(istream *is, int sz)
7816 - yy_delete_buffer(struct yy_buffer_state *b)
7818 However, I couldn't figure out how to access current
7819 buffer (yy_current_buffer).
7821 yy_current_buffer is a protected member of yyFlexLexer.
7822 I can't access it directly.
7823 Then, I thought yy_create_buffer() with is = 0 might
7824 return current stream buffer. But it seems not as far
7825 as I checked the source. (flex 2.5.4)
7827 I went through the Web in addition to Flex documentation.
7828 However, it hasn't been successful, so far.
7830 It is not my intention to bother you, but, can you
7831 comment about how to obtain the current stream buffer?
7833 Your response would be highly appreciated.
7838 --== Sent via Deja.com http://www.deja.com/ ==--
7839 Share what you know. Learn what you don't.
7843 @c TODO: Evaluate this faq.
7844 @node unnamed-faq-92
7845 @unnumberedsec unnamed-faq-92
7848 To: neko@my-deja.com
7849 Subject: Re: A question on flex C++ scanner
7850 In-reply-to: Your message of Tue, 15 Jun 1999 08:55:43 PDT.
7851 Date: Tue, 15 Jun 1999 09:04:24 PDT
7852 From: Vern Paxson <vern>
7854 > However, I couldn't figure out how to access current
7855 > buffer (yy_current_buffer).
7857 Derive your own subclass from yyFlexLexer.
7863 @c TODO: Evaluate this faq.
7864 @node unnamed-faq-93
7865 @unnumberedsec unnamed-faq-93
7868 To: "Stones, Darren" <Darren.Stones@nectech.co.uk>
7869 Subject: Re: You're the man to see?
7870 In-reply-to: Your message of Wed, 23 Jun 1999 11:10:29 PDT.
7871 Date: Wed, 23 Jun 1999 09:01:40 PDT
7872 From: Vern Paxson <vern>
7874 > I hope you can help me. I am using Flex and Bison to produce an interpreted
7875 > language. However all goes well until I try to implement an IF statement or
7876 > a WHILE. I cannot get this to work as the parser parses all the conditions
7877 > eg. the TRUE and FALSE conditons to check for a rule match. So I cannot
7880 You need to use the parser to build a parse tree (= abstract syntax trwee),
7881 and when that's all done you recursively evaluate the tree, binding variables
7882 to values at that time.
7888 @c TODO: Evaluate this faq.
7889 @node unnamed-faq-94
7890 @unnumberedsec unnamed-faq-94
7893 To: Petr Danecek <petr@ics.cas.cz>
7894 Subject: Re: flex - question
7895 In-reply-to: Your message of Mon, 28 Jun 1999 19:21:41 PDT.
7896 Date: Fri, 02 Jul 1999 16:52:13 PDT
7897 From: Vern Paxson <vern>
7899 > file, it takes an enormous amount of time. It is funny, because the
7900 > source code has only 12 rules!!! I think it looks like an exponencial
7903 Right, that's the problem - some patterns (those with a lot of
7904 ambiguity, where yours has because at any given time the scanner can
7905 be in the middle of all sorts of combinations of the different
7906 rules) blow up exponentially.
7908 For your rules, there is an easy fix. Change the ".*" that comes fater
7909 the directory name to "[^ ]*". With that in place, the rules are no
7910 longer nearly so ambiguous, because then once one of the directories
7911 has been matched, no other can be matched (since they all require a
7914 If that's not an acceptable solution, then you can enter a start state
7915 to pick up the .*\n after each directory is matched.
7917 Also note that for speed, you'll want to add a ".*" rule at the end,
7918 otherwise rules that don't match any of the patterns will be matched
7919 very slowly, a character at a time.
7925 @c TODO: Evaluate this faq.
7926 @node unnamed-faq-95
7927 @unnumberedsec unnamed-faq-95
7930 To: Tielman Koekemoer <tielman@spi.co.za>
7931 Subject: Re: Please help.
7932 In-reply-to: Your message of Thu, 08 Jul 1999 13:20:37 PDT.
7933 Date: Thu, 08 Jul 1999 08:20:39 PDT
7934 From: Vern Paxson <vern>
7936 > I was hoping you could help me with my problem.
7938 > I tried compiling (gnu)flex on a Solaris 2.4 machine
7939 > but when I ran make (after configure) I got an error.
7941 > --------------------------------------------------------------
7942 > gcc -c -I. -I. -g -O parse.c
7943 > ./flex -t -p ./scan.l >scan.c
7944 > sh: ./flex: not found
7946 > make: Fatal error: Command failed for target `scan.c'
7947 > -------------------------------------------------------------
7949 > What's strange to me is that I'm only
7950 > trying to install flex now. I then edited the Makefile to
7951 > and changed where it says "FLEX = flex" to "FLEX = lex"
7952 > ( lex: the native Solaris one ) but then it complains about
7953 > the "-p" option. Is there any way I can compile flex without
7954 > using flex or lex?
7956 > Thanks so much for your time.
7958 You managed to step on the bootstrap sequence, which first copies
7959 initscan.c to scan.c in order to build flex. Try fetching a fresh
7960 distribution from ftp.ee.lbl.gov. (Or you can first try removing
7961 ".bootstrap" and doing a make again.)
7967 @c TODO: Evaluate this faq.
7968 @node unnamed-faq-96
7969 @unnumberedsec unnamed-faq-96
7972 To: Tielman Koekemoer <tielman@spi.co.za>
7973 Subject: Re: Please help.
7974 In-reply-to: Your message of Fri, 09 Jul 1999 09:16:14 PDT.
7975 Date: Fri, 09 Jul 1999 00:27:20 PDT
7976 From: Vern Paxson <vern>
7978 > First I removed .bootstrap (and ran make) - no luck. I downloaded the
7979 > software but I still have the same problem. Is there anything else I
7984 cp initscan.c scan.c
7988 If this last tries to first build scan.c from scan.l using ./flex, then
7989 your "make" is broken, in which case compile scan.c to scan.o by hand.
7995 @c TODO: Evaluate this faq.
7996 @node unnamed-faq-97
7997 @unnumberedsec unnamed-faq-97
8000 To: Sumanth Kamenani <skamenan@crl.nmsu.edu>
8002 In-reply-to: Your message of Mon, 19 Jul 1999 23:08:41 PDT.
8003 Date: Tue, 20 Jul 1999 00:18:26 PDT
8004 From: Vern Paxson <vern>
8006 > I am getting a compilation error. The error is given as "unknown symbol- yylex".
8008 The parser relies on calling yylex(), but you're instead using the C++ scanning
8009 class, so you need to supply a yylex() "glue" function that calls an instance
8010 scanner of the scanner (e.g., "scanner->yylex()").
8016 @c TODO: Evaluate this faq.
8017 @node unnamed-faq-98
8018 @unnumberedsec unnamed-faq-98
8021 To: daniel@synchrods.synchrods.COM (Daniel Senderowicz)
8023 In-reply-to: Your message of Mon, 22 Nov 1999 11:19:04 PST.
8024 Date: Tue, 23 Nov 1999 15:54:30 PST
8025 From: Vern Paxson <vern>
8027 Well, your problem is the
8029 switch (yybgin-yysvec-1) { /* witchcraft */
8031 at the beginning of lex rules. "witchcraft" == "non-portable". It's
8032 assuming knowledge of the AT&T lex's internal variables.
8034 For flex, you can probably do the equivalent using a switch on YYSTATE.
8040 @c TODO: Evaluate this faq.
8041 @node unnamed-faq-99
8042 @unnumberedsec unnamed-faq-99
8045 To: archow@hss.hns.com
8046 Subject: Re: Regarding distribution of flex and yacc based grammars
8047 In-reply-to: Your message of Sun, 19 Dec 1999 17:50:24 +0530.
8048 Date: Wed, 22 Dec 1999 01:56:24 PST
8049 From: Vern Paxson <vern>
8051 > When we provide the customer with an object code distribution, is it
8052 > necessary for us to provide source
8053 > for the generated C files from flex and bison since they are generated by
8056 For flex, no. I don't know what the current state of this is for bison.
8058 > Also, is there any requrirement for us to neccessarily provide source for
8059 > the grammar files which are fed into flex and bison ?
8061 Again, for flex, no.
8063 See the file "COPYING" in the flex distribution for the legalese.
8069 @c TODO: Evaluate this faq.
8070 @node unnamed-faq-100
8071 @unnumberedsec unnamed-faq-100
8074 To: Martin Gallwey <gallweym@hyperion.moe.ul.ie>
8075 Subject: Re: Flex, and self referencing rules
8076 In-reply-to: Your message of Sun, 20 Feb 2000 01:01:21 PST.
8077 Date: Sat, 19 Feb 2000 18:33:16 PST
8078 From: Vern Paxson <vern>
8080 > However, I do not use unput anywhere. I do use self-referencing
8083 > UnaryExpr ({UnionExpr})|("-"{UnaryExpr})
8085 You can't do this - flex is *not* a parser like yacc (which does indeed
8086 allow recursion), it is a scanner that's confined to regular expressions.
8092 @c TODO: Evaluate this faq.
8093 @node unnamed-faq-101
8094 @unnumberedsec unnamed-faq-101
8097 To: slg3@lehigh.edu (SAMUEL L. GULDEN)
8098 Subject: Re: Flex problem
8099 In-reply-to: Your message of Thu, 02 Mar 2000 12:29:04 PST.
8100 Date: Thu, 02 Mar 2000 23:00:46 PST
8101 From: Vern Paxson <vern>
8103 If this is exactly your program:
8107 > whitespace [ \t\n]+
8110 > "[" { printf("open_brac\n");}
8111 > "]" { printf("close_brac\n");}
8112 > "+" { printf("addop\n");}
8113 > "*" { printf("multop\n");}
8114 > {digits} { printf("NUMBER = %s\n", yytext);}
8117 then the problem is that the last rule needs to be "{whitespace}" !
8123 @node What is the difference between YYLEX_PARAM and YY_DECL?
8124 @unnumberedsec What is the difference between YYLEX_PARAM and YY_DECL?
8126 YYLEX_PARAM is not a flex symbol. It is for Bison. It tells Bison to pass extra
8127 params when it calls yylex() from the parser.
8129 YY_DECL is the Flex declaration of yylex. The default is similar to this:
8133 #define int yy_lex ()
8138 @node Why do I get "conflicting types for yylex" error?
8139 @unnumberedsec Why do I get "conflicting types for yylex" error?
8141 This is a compiler error regarding a generated Bison parser, not a Flex scanner.
8142 It means you need a prototype of yylex() in the top of the Bison file.
8143 Be sure the prototype matches YY_DECL.
8145 @node How do I access the values set in a Flex action from within a Bison action?
8146 @unnumberedsec How do I access the values set in a Flex action from within a Bison action?
8148 With $1, $2, $3, etc. These are called "Semantic Values" in the Bison manual.
8149 See @ref{Top, , , bison, the GNU Bison Manual}.
8151 @node Appendices, Indices, FAQ, Top
8152 @appendix Appendices
8155 * Makefiles and Flex::
8161 @node Makefiles and Flex, Bison Bridge, Appendices, Appendices
8162 @appendixsec Makefiles and Flex
8164 @cindex Makefile, syntax
8166 In this appendix, we provide tips for writing Makefiles to build your scanners.
8168 In a traditional build environment, we say that the @file{.c} files are the
8169 sources, and the @file{.o} files are the intermediate files. When using
8170 @code{flex}, however, the @file{.l} files are the sources, and the generated
8171 @file{.c} files (along with the @file{.o} files) are the intermediate files.
8172 This requires you to carefully plan your Makefile.
8174 Modern @command{make} programs understand that @file{foo.l} is intended to
8175 generate @file{lex.yy.c} or @file{foo.c}, and will behave
8176 accordingly@footnote{GNU @command{make} and GNU @command{automake} are two such
8177 programs that provide implicit rules for flex-generated scanners.}@footnote{GNU @command{automake}
8178 may generate code to execute flex in lex-compatible mode, or to stdout. If this is not what you want,
8179 then you should provide an explicit rule in your Makefile.am}. The
8180 following Makefile does not explicitly instruct @command{make} how to build
8181 @file{foo.c} from @file{foo.l}. Instead, it relies on the implicit rules of the
8182 @command{make} program to build the intermediate file, @file{scan.c}:
8184 @cindex Makefile, example of implicit rules
8187 # Basic Makefile -- relies on implicit rules
8188 # Creates "myprogram" from "scan.l" and "myprogram.c"
8191 myprogram: scan.o myprogram.o
8198 For simple cases, the above may be sufficient. For other cases,
8199 you may have to explicitly instruct @command{make} how to build your scanner.
8200 The following is an example of a Makefile containing explicit rules:
8202 @cindex Makefile, explicit example
8205 # Basic Makefile -- provides explicit rules
8206 # Creates "myprogram" from "scan.l" and "myprogram.c"
8209 myprogram: scan.o myprogram.o
8210 $(CC) -o $@ $(LDFLAGS) $^
8212 myprogram.o: myprogram.c
8213 $(CC) $(CPPFLAGS) $(CFLAGS) -o $@ -c $^
8216 $(CC) $(CPPFLAGS) $(CFLAGS) -o $@ -c $^
8219 $(LEX) $(LFLAGS) -o $@ $^
8227 Notice in the above example that @file{scan.c} is in the @code{clean} target.
8228 This is because we consider the file @file{scan.c} to be an intermediate file.
8230 Finally, we provide a realistic example of a @code{flex} scanner used with a
8231 @code{bison} parser@footnote{This example also applies to yacc parsers.}.
8232 There is a tricky problem we have to deal with. Since a @code{flex} scanner
8233 will typically include a header file (e.g., @file{y.tab.h}) generated by the
8234 parser, we need to be sure that the header file is generated BEFORE the scanner
8235 is compiled. We handle this case in the following example:
8239 # Makefile example -- scanner and parser.
8240 # Creates "myprogram" from "scan.l", "parse.y", and "myprogram.c"
8245 objects = scan.o parse.o myprogram.o
8247 myprogram: $(objects)
8248 scan.o: scan.l parse.c
8250 myprogram.o: myprogram.c
8255 In the above example, notice the line,
8259 scan.o: scan.l parse.c
8263 , which lists the file @file{parse.c} (the generated parser) as a dependency of
8264 @file{scan.o}. We want to ensure that the parser is created before the scanner
8265 is compiled, and the above line seems to do the trick. Feel free to experiment
8266 with your specific implementation of @command{make}.
8269 For more details on writing Makefiles, see @ref{Top, , , make, The
8272 @node Bison Bridge, M4 Dependency, Makefiles and Flex, Appendices
8273 @section C Scanners with Bison Parsers
8275 @cindex bison, bridging with flex
8281 This section describes the @code{flex} features useful when integrating
8282 @code{flex} with @code{GNU bison}@footnote{The features described here are
8283 purely optional, and are by no means the only way to use flex with bison.
8284 We merely provide some glue to ease development of your parser-scanner pair.}.
8285 Skip this section if you are not using
8286 @code{bison} with your scanner. Here we discuss only the @code{flex}
8287 half of the @code{flex} and @code{bison} pair. We do not discuss
8288 @code{bison} in any detail. For more information about generating
8289 @code{bison} parsers, see @ref{Top, , , bison, the GNU Bison Manual}.
8291 A compatible @code{bison} scanner is generated by declaring @samp{%option
8292 bison-bridge} or by supplying @samp{--bison-bridge} when invoking @code{flex}
8293 from the command line. This instructs @code{flex} that the macro
8294 @code{yylval} may be used. The data type for
8295 @code{yylval}, @code{YYSTYPE},
8296 is typically defined in a header file, included in section 1 of the
8297 @code{flex} input file. For a list of functions and macros
8298 available, @xref{bison-functions}.
8300 The declaration of yylex becomes,
8302 @findex yylex (reentrant version)
8305 int yylex ( YYSTYPE * lvalp, yyscan_t scanner );
8309 If @code{%option bison-locations} is specified, then the declaration
8312 @findex yylex (reentrant version)
8315 int yylex ( YYSTYPE * lvalp, YYLTYPE * llocp, yyscan_t scanner );
8319 Note that the macros @code{yylval} and @code{yylloc} evaluate to pointers.
8320 Support for @code{yylloc} is optional in @code{bison}, so it is optional in
8321 @code{flex} as well. The following is an example of a @code{flex} scanner that
8322 is compatible with @code{bison}.
8324 @cindex bison, scanner to be called from bison
8327 /* Scanner for "C" assignment statements... sort of. */
8329 #include "y.tab.h" /* Generated by bison. */
8332 %option bison-bridge bison-locations
8335 [[:digit:]]+ { yylval->num = atoi(yytext); return NUMBER;}
8336 [[:alnum:]]+ { yylval->str = strdup(yytext); return STRING;}
8337 "="|";" { return yytext[0];}
8343 As you can see, there really is no magic here. We just use
8344 @code{yylval} as we would any other variable. The data type of
8345 @code{yylval} is generated by @code{bison}, and included in the file
8346 @file{y.tab.h}. Here is the corresponding @code{bison} parser:
8348 @cindex bison, parser
8351 /* Parser to convert "C" assignments to lisp. */
8353 /* Pass the argument to yyparse through to yylex. */
8354 #define YYPARSE_PARAM scanner
8355 #define YYLEX_PARAM scanner
8367 STRING '=' NUMBER ';' {
8368 printf( "(setf %s %d)", $1, $3 );
8374 @node M4 Dependency, Common Patterns, Bison Bridge, Appendices
8375 @section M4 Dependency
8377 The macro processor @code{m4}@footnote{The use of m4 is subject to change in
8378 future revisions of flex. It is not part of the public API of flex. Do not depend on it.}
8379 must be installed wherever flex is installed.
8380 @code{flex} invokes @samp{m4}, found by searching the directories in the
8381 @code{PATH} environment variable. Any code you place in section 1 or in the
8382 actions will be sent through m4. Please follow these rules to protect your
8383 code from unwanted @code{m4} processing.
8387 @item Do not use symbols that begin with, @samp{m4_}, such as, @samp{m4_define},
8388 or @samp{m4_include}, since those are reserved for @code{m4} macro names. If for
8389 some reason you need m4_ as a prefix, use a preprocessor #define to get your
8390 symbol past m4 unmangled.
8392 @item Do not use the strings @samp{[[} or @samp{]]} anywhere in your code. The
8393 former is not valid in C, except within comments and strings, but the latter is valid in
8394 code such as @code{x[y[z]]}. The solution is simple. To get the literal string
8395 @code{"]]"}, use @code{"]""]"}. To get the array notation @code{x[y[z]]},
8396 use @code{x[y[z] ]}. Flex will attempt to detect these sequences in user code, and
8397 escape them. However, it's best to avoid this complexity where possible, by
8398 removing such sequences from your code.
8402 @code{m4} is only required at the time you run @code{flex}. The generated
8403 scanner is ordinary C or C++, and does @emph{not} require @code{m4}.
8405 @node Common Patterns, ,M4 Dependency, Appendices
8406 @section Common Patterns
8407 @cindex patterns, common
8409 This appendix provides examples of common regular expressions you might use
8415 * Quoted Constructs::
8420 @node Numbers, Identifiers, ,Common Patterns
8425 @item C99 decimal constant
8426 @code{([[:digit:]]@{-@}[0])[[:digit:]]*}
8428 @item C99 hexadecimal constant
8429 @code{0[xX][[:xdigit:]]+}
8431 @item C99 octal constant
8434 @item C99 floating point constant
8436 {dseq} ([[:digit:]]+)
8437 {dseq_opt} ([[:digit:]]*)
8438 {frac} (({dseq_opt}"."{dseq})|{dseq}".")
8439 {exp} ([eE][+-]?{dseq})
8442 {fsuff_opt} ({fsuff}?)
8444 {hdseq} ([[:xdigit:]]+)
8445 {hdseq_opt} ([[:xdigit:]]*)
8446 {hfrac} (({hdseq_opt}"."{hdseq})|({hdseq}"."))
8447 {bexp} ([pP][+-]?{dseq})
8448 {dfc} (({frac}{exp_opt}{fsuff_opt})|({dseq}{exp}{fsuff_opt}))
8449 {hfc} (({hpref}{hfrac}{bexp}{fsuff_opt})|({hpref}{hdseq}{bexp}{fsuff_opt}))
8451 {c99_floating_point_constant} ({dfc}|{hfc})
8454 See C99 section 6.4.4.2 for the gory details.
8458 @node Identifiers, Quoted Constructs, Numbers, Common Patterns
8459 @subsection Identifiers
8463 @item C99 Identifier
8465 ucn ((\\u([[:xdigit:]]{4}))|(\\U([[:xdigit:]]{8})))
8466 nondigit [_[:alpha:]]
8467 c99_id ([_[:alpha:]]|{ucn})([_[:alnum:]]|{ucn})*
8470 Technically, the above pattern does not encompass all possible C99 identifiers, since C99 allows for
8471 "implementation-defined" characters. In practice, C compilers follow the above pattern, with the
8472 addition of the @samp{$} character.
8474 @item UTF-8 Encoded Unicode Code Point
8476 [\x09\x0A\x0D\x20-\x7E]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF]([\x80-\xBF]{2})|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF]([\x80-\xBF]{2})|[\xF1-\xF3]([\x80-\xBF]{3})|\xF4[\x80-\x8F]([\x80-\xBF]{2})
8481 @node Quoted Constructs, Addresses, Identifiers, Common Patterns
8482 @subsection Quoted Constructs
8485 @item C99 String Literal
8486 @code{L?\"([^\"\\\n]|(\\['\"?\\abfnrtv])|(\\([0123456]@{1,3@}))|(\\x[[:xdigit:]]+)|(\\u([[:xdigit:]]@{4@}))|(\\U([[:xdigit:]]@{8@})))*\"}
8489 @code{("/*"([^*]|"*"[^/])*"*/")|("/"(\\\n)*"/"[^\n]*)}
8491 Note that in C99, a @samp{//}-style comment may be split across lines, and, contrary to popular belief,
8492 does not include the trailing @samp{\n} character.
8494 A better way to scan @samp{/* */} comments is by line, rather than matching
8495 possibly huge comments all at once. This will allow you to scan comments of
8496 unlimited length, as long as line breaks appear at sane intervals. This is also
8497 more efficient when used with automatic line number processing. @xref{option-yylineno}.
8501 "/*" BEGIN(COMMENT);
8513 @node Addresses, ,Quoted Constructs, Common Patterns
8514 @subsection Addresses
8519 @code{(([[:digit:]]@{1,3@}".")@{3@}([[:digit:]]@{1,3@}))}
8523 hex4 ([[:xdigit:]]{1,4})
8524 hexseq ({hex4}(:{hex4}*))
8525 hexpart ({hexseq}|({hexseq}::({hexseq}?))|::{hexseq})
8526 IPv6address ({hexpart}(":"{IPv4address})?)
8529 See RFC2373 for details.
8532 @code{(([^:/?#]+):)?("//"([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?}
8534 This pattern is nearly useless, since it allows just about any character to
8535 appear in a URI, including spaces and control characters. See RFC2396 for
8541 @node Indices, , Appendices, Top
8546 * Index of Functions and Macros::
8547 * Index of Variables::
8548 * Index of Data Types::
8550 * Index of Scanner Options::
8553 @node Concept Index, Index of Functions and Macros, Indices, Indices
8554 @unnumberedsec Concept Index
8558 @node Index of Functions and Macros, Index of Variables, Concept Index, Indices
8559 @unnumberedsec Index of Functions and Macros
8561 This is an index of functions and preprocessor macros that look like functions.
8562 For macros that expand to variables or constants, see @ref{Index of Variables}.
8566 @node Index of Variables, Index of Data Types, Index of Functions and Macros, Indices
8567 @unnumberedsec Index of Variables
8569 This is an index of variables, constants, and preprocessor macros
8570 that expand to variables or constants.
8574 @node Index of Data Types, Index of Hooks, Index of Variables, Indices
8575 @unnumberedsec Index of Data Types
8578 @node Index of Hooks, Index of Scanner Options, Index of Data Types, Indices
8579 @unnumberedsec Index of Hooks
8581 This is an index of "hooks" that the user may define. These hooks typically correspond
8582 to specific locations in the generated scanner, and may be used to insert arbitrary code.
8586 @node Index of Scanner Options, , Index of Hooks, Indices
8587 @unnumberedsec Index of Scanner Options
8591 @c A vim script to name the faq entries. delete this when faqs are no longer
8592 @c named "unnamed-faq-XXX".
8594 @c fu! Faq2 () range abort
8595 @c let @r=input("Rename to: ")
8596 @c exe "%s/" . @w . "/" . @r . "/g"
8599 @c nnoremap <F5> 1G/@node\s\+unnamed-faq-\d\+<cr>mfww"wy5ezt:call Faq2()<cr>