Merge from vendor branch BINUTILS:
[dragonfly.git] / usr.bin / lex / lex.1
1 .\" $FreeBSD: src/usr.bin/lex/lex.1,v 1.10.2.6 2003/02/24 22:37:41 trhodes Exp $
2 .\" $DragonFly: src/usr.bin/lex/lex.1,v 1.2 2003/06/17 04:29:27 dillon Exp $
3 .\"
4 .TH FLEX 1 "April 1995" "Version 2.5"
5 .SH NAME
6 flex \- fast lexical analyzer generator
7 .SH SYNOPSIS
8 .B flex
9 .B [\-bcdfhilnpstvwBFILTV78+? \-C[aefFmr] \-ooutput \-Pprefix \-Sskeleton]
10 .B [\-\-help \-\-version]
11 .I [filename ...]
12 .SH OVERVIEW
13 This manual describes
14 .I flex,
15 a tool for generating programs that perform pattern-matching on text.  The
16 manual includes both tutorial and reference sections:
17 .nf
18
19     Description
20         a brief overview of the tool
21
22     Some Simple Examples
23
24     Format Of The Input File
25
26     Patterns
27         the extended regular expressions used by flex
28
29     How The Input Is Matched
30         the rules for determining what has been matched
31
32     Actions
33         how to specify what to do when a pattern is matched
34
35     The Generated Scanner
36         details regarding the scanner that flex produces;
37         how to control the input source
38
39     Start Conditions
40         introducing context into your scanners, and
41         managing "mini-scanners"
42
43     Multiple Input Buffers
44         how to manipulate multiple input sources; how to
45         scan from strings instead of files
46
47     End-of-file Rules
48         special rules for matching the end of the input
49
50     Miscellaneous Macros
51         a summary of macros available to the actions
52
53     Values Available To The User
54         a summary of values available to the actions
55
56     Interfacing With Yacc
57         connecting flex scanners together with yacc parsers
58
59     Options
60         flex command-line options, and the "%option"
61         directive
62
63     Performance Considerations
64         how to make your scanner go as fast as possible
65
66     Generating C++ Scanners
67         the (experimental) facility for generating C++
68         scanner classes
69
70     Incompatibilities With Lex And POSIX
71         how flex differs from AT&T lex and the POSIX lex
72         standard
73
74     Diagnostics
75         those error messages produced by flex (or scanners
76         it generates) whose meanings might not be apparent
77
78     Files
79         files used by flex
80
81     Deficiencies / Bugs
82         known problems with flex
83
84     See Also
85         other documentation, related tools
86
87     Author
88         includes contact information
89
90 .fi
91 .SH DESCRIPTION
92 .I flex
93 is a tool for generating
94 .I scanners:
95 programs which recognize lexical patterns in text.
96 .I flex
97 reads
98 the given input files, or its standard input if no file names are given,
99 for a description of a scanner to generate.  The description is in
100 the form of pairs
101 of regular expressions and C code, called
102 .I rules.  flex
103 generates as output a C source file,
104 .B lex.yy.c,
105 which defines a routine
106 .B yylex().
107 This file is compiled and linked with the
108 .B \-ll
109 library to produce an executable.  When the executable is run,
110 it analyzes its input for occurrences
111 of the regular expressions.  Whenever it finds one, it executes
112 the corresponding C code.
113 .SH SOME SIMPLE EXAMPLES
114 First some simple examples to get the flavor of how one uses
115 .I flex.
116 The following
117 .I flex
118 input specifies a scanner which whenever it encounters the string
119 "username" will replace it with the user's login name:
120 .nf
121
122     %%
123     username    printf( "%s", getlogin() );
124
125 .fi
126 By default, any text not matched by a
127 .I flex
128 scanner
129 is copied to the output, so the net effect of this scanner is
130 to copy its input file to its output with each occurrence
131 of "username" expanded.
132 In this input, there is just one rule.  "username" is the
133 .I pattern
134 and the "printf" is the
135 .I action.
136 The "%%" marks the beginning of the rules.
137 .PP
138 Here's another simple example:
139 .nf
140
141     %{
142             int num_lines = 0, num_chars = 0;
143     %}
144
145     %%
146     \\n      ++num_lines; ++num_chars;
147     .       ++num_chars;
148
149     %%
150     main()
151             {
152             yylex();
153             printf( "# of lines = %d, # of chars = %d\\n",
154                     num_lines, num_chars );
155             }
156
157 .fi
158 This scanner counts the number of characters and the number
159 of lines in its input (it produces no output other than the
160 final report on the counts).  The first line
161 declares two globals, "num_lines" and "num_chars", which are accessible
162 both inside
163 .B yylex()
164 and in the
165 .B main()
166 routine declared after the second "%%".  There are two rules, one
167 which matches a newline ("\\n") and increments both the line count and
168 the character count, and one which matches any character other than
169 a newline (indicated by the "." regular expression).
170 .PP
171 A somewhat more complicated example:
172 .nf
173
174     /* scanner for a toy Pascal-like language */
175
176     %{
177     /* need this for the call to atof() below */
178     #include <math.h>
179     %}
180
181     DIGIT    [0-9]
182     ID       [a-z][a-z0-9]*
183
184     %%
185
186     {DIGIT}+    {
187                 printf( "An integer: %s (%d)\\n", yytext,
188                         atoi( yytext ) );
189                 }
190
191     {DIGIT}+"."{DIGIT}*        {
192                 printf( "A float: %s (%g)\\n", yytext,
193                         atof( yytext ) );
194                 }
195
196     if|then|begin|end|procedure|function        {
197                 printf( "A keyword: %s\\n", yytext );
198                 }
199
200     {ID}        printf( "An identifier: %s\\n", yytext );
201
202     "+"|"-"|"*"|"/"   printf( "An operator: %s\\n", yytext );
203
204     "{"[^}\\n]*"}"     /* eat up one-line comments */
205
206     [ \\t\\n]+          /* eat up whitespace */
207
208     .           printf( "Unrecognized character: %s\\n", yytext );
209
210     %%
211
212     main( argc, argv )
213     int argc;
214     char **argv;
215         {
216         ++argv, --argc;  /* skip over program name */
217         if ( argc > 0 )
218                 yyin = fopen( argv[0], "r" );
219         else
220                 yyin = stdin;
221
222         yylex();
223         }
224
225 .fi
226 This is the beginnings of a simple scanner for a language like
227 Pascal.  It identifies different types of
228 .I tokens
229 and reports on what it has seen.
230 .PP
231 The details of this example will be explained in the following
232 sections.
233 .SH FORMAT OF THE INPUT FILE
234 The
235 .I flex
236 input file consists of three sections, separated by a line with just
237 .B %%
238 in it:
239 .nf
240
241     definitions
242     %%
243     rules
244     %%
245     user code
246
247 .fi
248 The
249 .I definitions
250 section contains declarations of simple
251 .I name
252 definitions to simplify the scanner specification, and declarations of
253 .I start conditions,
254 which are explained in a later section.
255 .PP
256 Name definitions have the form:
257 .nf
258
259     name definition
260
261 .fi
262 The "name" is a word beginning with a letter or an underscore ('_')
263 followed by zero or more letters, digits, '_', or '-' (dash).
264 The definition is taken to begin at the first non-white-space character
265 following the name and continuing to the end of the line.
266 The definition can subsequently be referred to using "{name}", which
267 will expand to "(definition)".  For example,
268 .nf
269
270     DIGIT    [0-9]
271     ID       [a-z][a-z0-9]*
272
273 .fi
274 defines "DIGIT" to be a regular expression which matches a
275 single digit, and
276 "ID" to be a regular expression which matches a letter
277 followed by zero-or-more letters-or-digits.
278 A subsequent reference to
279 .nf
280
281     {DIGIT}+"."{DIGIT}*
282
283 .fi
284 is identical to
285 .nf
286
287     ([0-9])+"."([0-9])*
288
289 .fi
290 and matches one-or-more digits followed by a '.' followed
291 by zero-or-more digits.
292 .PP
293 The
294 .I rules
295 section of the
296 .I flex
297 input contains a series of rules of the form:
298 .nf
299
300     pattern   action
301
302 .fi
303 where the pattern must be unindented and the action must begin
304 on the same line.
305 .PP
306 See below for a further description of patterns and actions.
307 .PP
308 Finally, the user code section is simply copied to
309 .B lex.yy.c
310 verbatim.
311 It is used for companion routines which call or are called
312 by the scanner.  The presence of this section is optional;
313 if it is missing, the second
314 .B %%
315 in the input file may be skipped, too.
316 .PP
317 In the definitions and rules sections, any
318 .I indented
319 text or text enclosed in
320 .B %{
321 and
322 .B %}
323 is copied verbatim to the output (with the %{}'s removed).
324 The %{}'s must appear unindented on lines by themselves.
325 .PP
326 In the rules section,
327 any indented or %{} text appearing before the
328 first rule may be used to declare variables
329 which are local to the scanning routine and (after the declarations)
330 code which is to be executed whenever the scanning routine is entered.
331 Other indented or %{} text in the rule section is still copied to the output,
332 but its meaning is not well-defined and it may well cause compile-time
333 errors (this feature is present for
334 .I POSIX
335 compliance; see below for other such features).
336 .PP
337 In the definitions section (but not in the rules section),
338 an unindented comment (i.e., a line
339 beginning with "/*") is also copied verbatim to the output up
340 to the next "*/".
341 .SH PATTERNS
342 The patterns in the input are written using an extended set of regular
343 expressions.  These are:
344 .nf
345
346     x          match the character 'x'
347     .          any character (byte) except newline
348     [xyz]      a "character class"; in this case, the pattern
349                  matches either an 'x', a 'y', or a 'z'
350     [abj-oZ]   a "character class" with a range in it; matches
351                  an 'a', a 'b', any letter from 'j' through 'o',
352                  or a 'Z'
353     [^A-Z]     a "negated character class", i.e., any character
354                  but those in the class.  In this case, any
355                  character EXCEPT an uppercase letter.
356     [^A-Z\\n]   any character EXCEPT an uppercase letter or
357                  a newline
358     r*         zero or more r's, where r is any regular expression
359     r+         one or more r's
360     r?         zero or one r's (that is, "an optional r")
361     r{2,5}     anywhere from two to five r's
362     r{2,}      two or more r's
363     r{4}       exactly 4 r's
364     {name}     the expansion of the "name" definition
365                (see above)
366     "[xyz]\\"foo"
367                the literal string: [xyz]"foo
368     \\X         if X is an 'a', 'b', 'f', 'n', 'r', 't', or 'v',
369                  then the ANSI-C interpretation of \\x.
370                  Otherwise, a literal 'X' (used to escape
371                  operators such as '*')
372     \\0         a NUL character (ASCII code 0)
373     \\123       the character with octal value 123
374     \\x2a       the character with hexadecimal value 2a
375     (r)        match an r; parentheses are used to override
376                  precedence (see below)
377
378
379     rs         the regular expression r followed by the
380                  regular expression s; called "concatenation"
381
382
383     r|s        either an r or an s
384
385
386     r/s        an r but only if it is followed by an s.  The
387                  text matched by s is included when determining
388                  whether this rule is the "longest match",
389                  but is then returned to the input before
390                  the action is executed.  So the action only
391                  sees the text matched by r.  This type
392                  of pattern is called trailing context".
393                  (There are some combinations of r/s that flex
394                  cannot match correctly; see notes in the
395                  Deficiencies / Bugs section below regarding
396                  "dangerous trailing context".)
397     ^r         an r, but only at the beginning of a line (i.e.,
398                  which just starting to scan, or right after a
399                  newline has been scanned).
400     r$         an r, but only at the end of a line (i.e., just
401                  before a newline).  Equivalent to "r/\\n".
402
403                Note that flex's notion of "newline" is exactly
404                whatever the C compiler used to compile flex
405                interprets '\\n' as; in particular, on some DOS
406                systems you must either filter out \\r's in the
407                input yourself, or explicitly use r/\\r\\n for "r$".
408
409
410     <s>r       an r, but only in start condition s (see
411                  below for discussion of start conditions)
412     <s1,s2,s3>r
413                same, but in any of start conditions s1,
414                  s2, or s3
415     <*>r       an r in any start condition, even an exclusive one.
416
417
418     <<EOF>>    an end-of-file
419     <s1,s2><<EOF>>
420                an end-of-file when in start condition s1 or s2
421
422 .fi
423 Note that inside of a character class, all regular expression operators
424 lose their special meaning except escape ('\\') and the character class
425 operators, '-', ']', and, at the beginning of the class, '^'.
426 .PP
427 The regular expressions listed above are grouped according to
428 precedence, from highest precedence at the top to lowest at the bottom.
429 Those grouped together have equal precedence.  For example,
430 .nf
431
432     foo|bar*
433
434 .fi
435 is the same as
436 .nf
437
438     (foo)|(ba(r*))
439
440 .fi
441 since the '*' operator has higher precedence than concatenation,
442 and concatenation higher than alternation ('|').  This pattern
443 therefore matches
444 .I either
445 the string "foo"
446 .I or
447 the string "ba" followed by zero-or-more r's.
448 To match "foo" or zero-or-more "bar"'s, use:
449 .nf
450
451     foo|(bar)*
452
453 .fi
454 and to match zero-or-more "foo"'s-or-"bar"'s:
455 .nf
456
457     (foo|bar)*
458
459 .fi
460 .PP
461 In addition to characters and ranges of characters, character classes
462 can also contain character class
463 .I expressions.
464 These are expressions enclosed inside
465 .B [:
466 and
467 .B :]
468 delimiters (which themselves must appear between the '[' and ']' of the
469 character class; other elements may occur inside the character class, too).
470 The valid expressions are:
471 .nf
472
473     [:alnum:] [:alpha:] [:blank:]
474     [:cntrl:] [:digit:] [:graph:]
475     [:lower:] [:print:] [:punct:]
476     [:space:] [:upper:] [:xdigit:]
477
478 .fi
479 These expressions all designate a set of characters equivalent to
480 the corresponding standard C
481 .B isXXX
482 function.  For example,
483 .B [:alnum:]
484 designates those characters for which
485 .B isalnum()
486 returns true - i.e., any alphabetic or numeric.
487 Some systems don't provide
488 .B isblank(),
489 so flex defines
490 .B [:blank:]
491 as a blank or a tab.
492 .PP
493 For example, the following character classes are all equivalent:
494 .nf
495
496     [[:alnum:]]
497     [[:alpha:][:digit:]]
498     [[:alpha:]0-9]
499     [a-zA-Z0-9]
500
501 .fi
502 If your scanner is case-insensitive (the
503 .B \-i
504 flag), then
505 .B [:upper:]
506 and
507 .B [:lower:]
508 are equivalent to
509 .B [:alpha:].
510 .PP
511 Some notes on patterns:
512 .IP -
513 A negated character class such as the example "[^A-Z]"
514 above
515 .I will match a newline
516 unless "\\n" (or an equivalent escape sequence) is one of the
517 characters explicitly present in the negated character class
518 (e.g., "[^A-Z\\n]").  This is unlike how many other regular
519 expression tools treat negated character classes, but unfortunately
520 the inconsistency is historically entrenched.
521 Matching newlines means that a pattern like [^"]* can match the entire
522 input unless there's another quote in the input.
523 .IP -
524 A rule can have at most one instance of trailing context (the '/' operator
525 or the '$' operator).  The start condition, '^', and "<<EOF>>" patterns
526 can only occur at the beginning of a pattern, and, as well as with '/' and '$',
527 cannot be grouped inside parentheses.  A '^' which does not occur at
528 the beginning of a rule or a '$' which does not occur at the end of
529 a rule loses its special properties and is treated as a normal character.
530 .IP
531 The following are illegal:
532 .nf
533
534     foo/bar$
535     <sc1>foo<sc2>bar
536
537 .fi
538 Note that the first of these, can be written "foo/bar\\n".
539 .IP
540 The following will result in '$' or '^' being treated as a normal character:
541 .nf
542
543     foo|(bar$)
544     foo|^bar
545
546 .fi
547 If what's wanted is a "foo" or a bar-followed-by-a-newline, the following
548 could be used (the special '|' action is explained below):
549 .nf
550
551     foo      |
552     bar$     /* action goes here */
553
554 .fi
555 A similar trick will work for matching a foo or a
556 bar-at-the-beginning-of-a-line.
557 .SH HOW THE INPUT IS MATCHED
558 When the generated scanner is run, it analyzes its input looking
559 for strings which match any of its patterns.  If it finds more than
560 one match, it takes the one matching the most text (for trailing
561 context rules, this includes the length of the trailing part, even
562 though it will then be returned to the input).  If it finds two
563 or more matches of the same length, the
564 rule listed first in the
565 .I flex
566 input file is chosen.
567 .PP
568 Once the match is determined, the text corresponding to the match
569 (called the
570 .I token)
571 is made available in the global character pointer
572 .B yytext,
573 and its length in the global integer
574 .B yyleng.
575 The
576 .I action
577 corresponding to the matched pattern is then executed (a more
578 detailed description of actions follows), and then the remaining
579 input is scanned for another match.
580 .PP
581 If no match is found, then the
582 .I default rule
583 is executed: the next character in the input is considered matched and
584 copied to the standard output.  Thus, the simplest legal
585 .I flex
586 input is:
587 .nf
588
589     %%
590
591 .fi
592 which generates a scanner that simply copies its input (one character
593 at a time) to its output.
594 .PP
595 Note that
596 .B yytext
597 can be defined in two different ways: either as a character
598 .I pointer
599 or as a character
600 .I array.
601 You can control which definition
602 .I flex
603 uses by including one of the special directives
604 .B %pointer
605 or
606 .B %array
607 in the first (definitions) section of your flex input.  The default is
608 .B %pointer,
609 unless you use the
610 .B -l
611 lex compatibility option, in which case
612 .B yytext
613 will be an array.
614 The advantage of using
615 .B %pointer
616 is substantially faster scanning and no buffer overflow when matching
617 very large tokens (unless you run out of dynamic memory).  The disadvantage
618 is that you are restricted in how your actions can modify
619 .B yytext
620 (see the next section), and calls to the
621 .B unput()
622 function destroys the present contents of
623 .B yytext,
624 which can be a considerable porting headache when moving between different
625 .I lex
626 versions.
627 .PP
628 The advantage of
629 .B %array
630 is that you can then modify
631 .B yytext
632 to your heart's content, and calls to
633 .B unput()
634 do not destroy
635 .B yytext
636 (see below).  Furthermore, existing
637 .I lex
638 programs sometimes access
639 .B yytext
640 externally using declarations of the form:
641 .nf
642     extern char yytext[];
643 .fi
644 This definition is erroneous when used with
645 .B %pointer,
646 but correct for
647 .B %array.
648 .PP
649 .B %array
650 defines
651 .B yytext
652 to be an array of
653 .B YYLMAX
654 characters, which defaults to a fairly large value.  You can change
655 the size by simply #define'ing
656 .B YYLMAX
657 to a different value in the first section of your
658 .I flex
659 input.  As mentioned above, with
660 .B %pointer
661 yytext grows dynamically to accommodate large tokens.  While this means your
662 .B %pointer
663 scanner can accommodate very large tokens (such as matching entire blocks
664 of comments), bear in mind that each time the scanner must resize
665 .B yytext
666 it also must rescan the entire token from the beginning, so matching such
667 tokens can prove slow.
668 .B yytext
669 presently does
670 .I not
671 dynamically grow if a call to
672 .B unput()
673 results in too much text being pushed back; instead, a run-time error results.
674 .PP
675 Also note that you cannot use
676 .B %array
677 with C++ scanner classes
678 (the
679 .B c++
680 option; see below).
681 .SH ACTIONS
682 Each pattern in a rule has a corresponding action, which can be any
683 arbitrary C statement.  The pattern ends at the first non-escaped
684 whitespace character; the remainder of the line is its action.  If the
685 action is empty, then when the pattern is matched the input token
686 is simply discarded.  For example, here is the specification for a program
687 which deletes all occurrences of "zap me" from its input:
688 .nf
689
690     %%
691     "zap me"
692
693 .fi
694 (It will copy all other characters in the input to the output since
695 they will be matched by the default rule.)
696 .PP
697 Here is a program which compresses multiple blanks and tabs down to
698 a single blank, and throws away whitespace found at the end of a line:
699 .nf
700
701     %%
702     [ \\t]+        putchar( ' ' );
703     [ \\t]+$       /* ignore this token */
704
705 .fi
706 .PP
707 If the action contains a '{', then the action spans till the balancing '}'
708 is found, and the action may cross multiple lines.
709 .I flex
710 knows about C strings and comments and won't be fooled by braces found
711 within them, but also allows actions to begin with
712 .B %{
713 and will consider the action to be all the text up to the next
714 .B %}
715 (regardless of ordinary braces inside the action).
716 .PP
717 An action consisting solely of a vertical bar ('|') means "same as
718 the action for the next rule."  See below for an illustration.
719 .PP
720 Actions can include arbitrary C code, including
721 .B return
722 statements to return a value to whatever routine called
723 .B yylex().
724 Each time
725 .B yylex()
726 is called it continues processing tokens from where it last left
727 off until it either reaches
728 the end of the file or executes a return.
729 .PP
730 Actions are free to modify
731 .B yytext
732 except for lengthening it (adding
733 characters to its end--these will overwrite later characters in the
734 input stream).  This however does not apply when using
735 .B %array
736 (see above); in that case,
737 .B yytext
738 may be freely modified in any way.
739 .PP
740 Actions are free to modify
741 .B yyleng
742 except they should not do so if the action also includes use of
743 .B yymore()
744 (see below).
745 .PP
746 There are a number of special directives which can be included within
747 an action:
748 .IP -
749 .B ECHO
750 copies yytext to the scanner's output.
751 .IP -
752 .B BEGIN
753 followed by the name of a start condition places the scanner in the
754 corresponding start condition (see below).
755 .IP -
756 .B REJECT
757 directs the scanner to proceed on to the "second best" rule which matched the
758 input (or a prefix of the input).  The rule is chosen as described
759 above in "How the Input is Matched", and
760 .B yytext
761 and
762 .B yyleng
763 set up appropriately.
764 It may either be one which matched as much text
765 as the originally chosen rule but came later in the
766 .I flex
767 input file, or one which matched less text.
768 For example, the following will both count the
769 words in the input and call the routine special() whenever "frob" is seen:
770 .nf
771
772             int word_count = 0;
773     %%
774
775     frob        special(); REJECT;
776     [^ \\t\\n]+   ++word_count;
777
778 .fi
779 Without the
780 .B REJECT,
781 any "frob"'s in the input would not be counted as words, since the
782 scanner normally executes only one action per token.
783 Multiple
784 .B REJECT's
785 are allowed, each one finding the next best choice to the currently
786 active rule.  For example, when the following scanner scans the token
787 "abcd", it will write "abcdabcaba" to the output:
788 .nf
789
790     %%
791     a        |
792     ab       |
793     abc      |
794     abcd     ECHO; REJECT;
795     .|\\n     /* eat up any unmatched character */
796
797 .fi
798 (The first three rules share the fourth's action since they use
799 the special '|' action.)
800 .B REJECT
801 is a particularly expensive feature in terms of scanner performance;
802 if it is used in
803 .I any
804 of the scanner's actions it will slow down
805 .I all
806 of the scanner's matching.  Furthermore,
807 .B REJECT
808 cannot be used with the
809 .I -Cf
810 or
811 .I -CF
812 options (see below).
813 .IP
814 Note also that unlike the other special actions,
815 .B REJECT
816 is a
817 .I branch;
818 code immediately following it in the action will
819 .I not
820 be executed.
821 .IP -
822 .B yymore()
823 tells the scanner that the next time it matches a rule, the corresponding
824 token should be
825 .I appended
826 onto the current value of
827 .B yytext
828 rather than replacing it.  For example, given the input "mega-kludge"
829 the following will write "mega-mega-kludge" to the output:
830 .nf
831
832     %%
833     mega-    ECHO; yymore();
834     kludge   ECHO;
835
836 .fi
837 First "mega-" is matched and echoed to the output.  Then "kludge"
838 is matched, but the previous "mega-" is still hanging around at the
839 beginning of
840 .B yytext
841 so the
842 .B ECHO
843 for the "kludge" rule will actually write "mega-kludge".
844 .PP
845 Two notes regarding use of
846 .B yymore().
847 First,
848 .B yymore()
849 depends on the value of
850 .I yyleng
851 correctly reflecting the size of the current token, so you must not
852 modify
853 .I yyleng
854 if you are using
855 .B yymore().
856 Second, the presence of
857 .B yymore()
858 in the scanner's action entails a minor performance penalty in the
859 scanner's matching speed.
860 .IP -
861 .B yyless(n)
862 returns all but the first
863 .I n
864 characters of the current token back to the input stream, where they
865 will be rescanned when the scanner looks for the next match.
866 .B yytext
867 and
868 .B yyleng
869 are adjusted appropriately (e.g.,
870 .B yyleng
871 will now be equal to
872 .I n
873 ).  For example, on the input "foobar" the following will write out
874 "foobarbar":
875 .nf
876
877     %%
878     foobar    ECHO; yyless(3);
879     [a-z]+    ECHO;
880
881 .fi
882 An argument of 0 to
883 .B yyless
884 will cause the entire current input string to be scanned again.  Unless you've
885 changed how the scanner will subsequently process its input (using
886 .B BEGIN,
887 for example), this will result in an endless loop.
888 .PP
889 Note that
890 .B yyless
891 is a macro and can only be used in the flex input file, not from
892 other source files.
893 .IP -
894 .B unput(c)
895 puts the character
896 .I c
897 back onto the input stream.  It will be the next character scanned.
898 The following action will take the current token and cause it
899 to be rescanned enclosed in parentheses.
900 .nf
901
902     {
903     int i;
904     /* Copy yytext because unput() trashes yytext */
905     char *yycopy = strdup( yytext );
906     unput( ')' );
907     for ( i = yyleng - 1; i >= 0; --i )
908         unput( yycopy[i] );
909     unput( '(' );
910     free( yycopy );
911     }
912
913 .fi
914 Note that since each
915 .B unput()
916 puts the given character back at the
917 .I beginning
918 of the input stream, pushing back strings must be done back-to-front.
919 .PP
920 An important potential problem when using
921 .B unput()
922 is that if you are using
923 .B %pointer
924 (the default), a call to
925 .B unput()
926 .I destroys
927 the contents of
928 .I yytext,
929 starting with its rightmost character and devouring one character to
930 the left with each call.  If you need the value of yytext preserved
931 after a call to
932 .B unput()
933 (as in the above example),
934 you must either first copy it elsewhere, or build your scanner using
935 .B %array
936 instead (see How The Input Is Matched).
937 .PP
938 Finally, note that you cannot put back
939 .B EOF
940 to attempt to mark the input stream with an end-of-file.
941 .IP -
942 .B input()
943 reads the next character from the input stream.  For example,
944 the following is one way to eat up C comments:
945 .nf
946
947     %%
948     "/*"        {
949                 register int c;
950
951                 for ( ; ; )
952                     {
953                     while ( (c = input()) != '*' &&
954                             c != EOF )
955                         ;    /* eat up text of comment */
956
957                     if ( c == '*' )
958                         {
959                         while ( (c = input()) == '*' )
960                             ;
961                         if ( c == '/' )
962                             break;    /* found the end */
963                         }
964
965                     if ( c == EOF )
966                         {
967                         error( "EOF in comment" );
968                         break;
969                         }
970                     }
971                 }
972
973 .fi
974 (Note that if the scanner is compiled using
975 .B C++,
976 then
977 .B input()
978 is instead referred to as
979 .B yyinput(),
980 in order to avoid a name clash with the
981 .B C++
982 stream by the name of
983 .I input.)
984 .IP -
985 .B YY_FLUSH_BUFFER
986 flushes the scanner's internal buffer
987 so that the next time the scanner attempts to match a token, it will
988 first refill the buffer using
989 .B YY_INPUT
990 (see The Generated Scanner, below).  This action is a special case
991 of the more general
992 .B yy_flush_buffer()
993 function, described below in the section Multiple Input Buffers.
994 .IP -
995 .B yyterminate()
996 can be used in lieu of a return statement in an action.  It terminates
997 the scanner and returns a 0 to the scanner's caller, indicating "all done".
998 By default,
999 .B yyterminate()
1000 is also called when an end-of-file is encountered.  It is a macro and
1001 may be redefined.
1002 .SH THE GENERATED SCANNER
1003 The output of
1004 .I flex
1005 is the file
1006 .B lex.yy.c,
1007 which contains the scanning routine
1008 .B yylex(),
1009 a number of tables used by it for matching tokens, and a number
1010 of auxiliary routines and macros.  By default,
1011 .B yylex()
1012 is declared as follows:
1013 .nf
1014
1015     int yylex()
1016         {
1017         ... various definitions and the actions in here ...
1018         }
1019
1020 .fi
1021 (If your environment supports function prototypes, then it will
1022 be "int yylex( void )".)  This definition may be changed by defining
1023 the "YY_DECL" macro.  For example, you could use:
1024 .nf
1025
1026     #define YY_DECL float lexscan( a, b ) float a, b;
1027
1028 .fi
1029 to give the scanning routine the name
1030 .I lexscan,
1031 returning a float, and taking two floats as arguments.  Note that
1032 if you give arguments to the scanning routine using a
1033 K&R-style/non-prototyped function declaration, you must terminate
1034 the definition with a semi-colon (;).
1035 .PP
1036 Whenever
1037 .B yylex()
1038 is called, it scans tokens from the global input file
1039 .I yyin
1040 (which defaults to stdin).  It continues until it either reaches
1041 an end-of-file (at which point it returns the value 0) or
1042 one of its actions executes a
1043 .I return
1044 statement.
1045 .PP
1046 If the scanner reaches an end-of-file, subsequent calls are undefined
1047 unless either
1048 .I yyin
1049 is pointed at a new input file (in which case scanning continues from
1050 that file), or
1051 .B yyrestart()
1052 is called.
1053 .B yyrestart()
1054 takes one argument, a
1055 .B FILE *
1056 pointer (which can be nil, if you've set up
1057 .B YY_INPUT
1058 to scan from a source other than
1059 .I yyin),
1060 and initializes
1061 .I yyin
1062 for scanning from that file.  Essentially there is no difference between
1063 just assigning
1064 .I yyin
1065 to a new input file or using
1066 .B yyrestart()
1067 to do so; the latter is available for compatibility with previous versions
1068 of
1069 .I flex,
1070 and because it can be used to switch input files in the middle of scanning.
1071 It can also be used to throw away the current input buffer, by calling
1072 it with an argument of
1073 .I yyin;
1074 but better is to use
1075 .B YY_FLUSH_BUFFER
1076 (see above).
1077 Note that
1078 .B yyrestart()
1079 does
1080 .I not
1081 reset the start condition to
1082 .B INITIAL
1083 (see Start Conditions, below).
1084 .PP
1085 If
1086 .B yylex()
1087 stops scanning due to executing a
1088 .I return
1089 statement in one of the actions, the scanner may then be called again and it
1090 will resume scanning where it left off.
1091 .PP
1092 By default (and for purposes of efficiency), the scanner uses
1093 block-reads rather than simple
1094 .I getc()
1095 calls to read characters from
1096 .I yyin.
1097 The nature of how it gets its input can be controlled by defining the
1098 .B YY_INPUT
1099 macro.
1100 YY_INPUT's calling sequence is "YY_INPUT(buf,result,max_size)".  Its
1101 action is to place up to
1102 .I max_size
1103 characters in the character array
1104 .I buf
1105 and return in the integer variable
1106 .I result
1107 either the
1108 number of characters read or the constant YY_NULL (0 on Unix systems)
1109 to indicate EOF.  The default YY_INPUT reads from the
1110 global file-pointer "yyin".
1111 .PP
1112 A sample definition of YY_INPUT (in the definitions
1113 section of the input file):
1114 .nf
1115
1116     %{
1117     #define YY_INPUT(buf,result,max_size) \\
1118         { \\
1119         int c = getchar(); \\
1120         result = (c == EOF) ? YY_NULL : (buf[0] = c, 1); \\
1121         }
1122     %}
1123
1124 .fi
1125 This definition will change the input processing to occur
1126 one character at a time.
1127 .PP
1128 When the scanner receives an end-of-file indication from YY_INPUT,
1129 it then checks the
1130 .B yywrap()
1131 function.  If
1132 .B yywrap()
1133 returns false (zero), then it is assumed that the
1134 function has gone ahead and set up
1135 .I yyin
1136 to point to another input file, and scanning continues.  If it returns
1137 true (non-zero), then the scanner terminates, returning 0 to its
1138 caller.  Note that in either case, the start condition remains unchanged;
1139 it does
1140 .I not
1141 revert to
1142 .B INITIAL.
1143 .PP
1144 If you do not supply your own version of
1145 .B yywrap(),
1146 then you must either use
1147 .B %option noyywrap
1148 (in which case the scanner behaves as though
1149 .B yywrap()
1150 returned 1), or you must link with
1151 .B \-ll
1152 to obtain the default version of the routine, which always returns 1.
1153 .PP
1154 Three routines are available for scanning from in-memory buffers rather
1155 than files:
1156 .B yy_scan_string(), yy_scan_bytes(),
1157 and
1158 .B yy_scan_buffer().
1159 See the discussion of them below in the section Multiple Input Buffers.
1160 .PP
1161 The scanner writes its
1162 .B ECHO
1163 output to the
1164 .I yyout
1165 global (default, stdout), which may be redefined by the user simply
1166 by assigning it to some other
1167 .B FILE
1168 pointer.
1169 .SH START CONDITIONS
1170 .I flex
1171 provides a mechanism for conditionally activating rules.  Any rule
1172 whose pattern is prefixed with "<sc>" will only be active when
1173 the scanner is in the start condition named "sc".  For example,
1174 .nf
1175
1176     <STRING>[^"]*        { /* eat up the string body ... */
1177                 ...
1178                 }
1179
1180 .fi
1181 will be active only when the scanner is in the "STRING" start
1182 condition, and
1183 .nf
1184
1185     <INITIAL,STRING,QUOTE>\\.        { /* handle an escape ... */
1186                 ...
1187                 }
1188
1189 .fi
1190 will be active only when the current start condition is
1191 either "INITIAL", "STRING", or "QUOTE".
1192 .PP
1193 Start conditions
1194 are declared in the definitions (first) section of the input
1195 using unindented lines beginning with either
1196 .B %s
1197 or
1198 .B %x
1199 followed by a list of names.
1200 The former declares
1201 .I inclusive
1202 start conditions, the latter
1203 .I exclusive
1204 start conditions.  A start condition is activated using the
1205 .B BEGIN
1206 action.  Until the next
1207 .B BEGIN
1208 action is executed, rules with the given start
1209 condition will be active and
1210 rules with other start conditions will be inactive.
1211 If the start condition is
1212 .I inclusive,
1213 then rules with no start conditions at all will also be active.
1214 If it is
1215 .I exclusive,
1216 then
1217 .I only
1218 rules qualified with the start condition will be active.
1219 A set of rules contingent on the same exclusive start condition
1220 describe a scanner which is independent of any of the other rules in the
1221 .I flex
1222 input.  Because of this,
1223 exclusive start conditions make it easy to specify "mini-scanners"
1224 which scan portions of the input that are syntactically different
1225 from the rest (e.g., comments).
1226 .PP
1227 If the distinction between inclusive and exclusive start conditions
1228 is still a little vague, here's a simple example illustrating the
1229 connection between the two.  The set of rules:
1230 .nf
1231
1232     %s example
1233     %%
1234
1235     <example>foo   do_something();
1236
1237     bar            something_else();
1238
1239 .fi
1240 is equivalent to
1241 .nf
1242
1243     %x example
1244     %%
1245
1246     <example>foo   do_something();
1247
1248     <INITIAL,example>bar    something_else();
1249
1250 .fi
1251 Without the
1252 .B <INITIAL,example>
1253 qualifier, the
1254 .I bar
1255 pattern in the second example wouldn't be active (i.e., couldn't match)
1256 when in start condition
1257 .B example.
1258 If we just used
1259 .B <example>
1260 to qualify
1261 .I bar,
1262 though, then it would only be active in
1263 .B example
1264 and not in
1265 .B INITIAL,
1266 while in the first example it's active in both, because in the first
1267 example the
1268 .B example
1269 start condition is an
1270 .I inclusive
1271 .B (%s)
1272 start condition.
1273 .PP
1274 Also note that the special start-condition specifier
1275 .B <*>
1276 matches every start condition.  Thus, the above example could also
1277 have been written;
1278 .nf
1279
1280     %x example
1281     %%
1282
1283     <example>foo   do_something();
1284
1285     <*>bar    something_else();
1286
1287 .fi
1288 .PP
1289 The default rule (to
1290 .B ECHO
1291 any unmatched character) remains active in start conditions.  It
1292 is equivalent to:
1293 .nf
1294
1295     <*>.|\\n     ECHO;
1296
1297 .fi
1298 .PP
1299 .B BEGIN(0)
1300 returns to the original state where only the rules with
1301 no start conditions are active.  This state can also be
1302 referred to as the start-condition "INITIAL", so
1303 .B BEGIN(INITIAL)
1304 is equivalent to
1305 .B BEGIN(0).
1306 (The parentheses around the start condition name are not required but
1307 are considered good style.)
1308 .PP
1309 .B BEGIN
1310 actions can also be given as indented code at the beginning
1311 of the rules section.  For example, the following will cause
1312 the scanner to enter the "SPECIAL" start condition whenever
1313 .B yylex()
1314 is called and the global variable
1315 .I enter_special
1316 is true:
1317 .nf
1318
1319             int enter_special;
1320
1321     %x SPECIAL
1322     %%
1323             if ( enter_special )
1324                 BEGIN(SPECIAL);
1325
1326     <SPECIAL>blahblahblah
1327     ...more rules follow...
1328
1329 .fi
1330 .PP
1331 To illustrate the uses of start conditions,
1332 here is a scanner which provides two different interpretations
1333 of a string like "123.456".  By default it will treat it as
1334 three tokens, the integer "123", a dot ('.'), and the integer "456".
1335 But if the string is preceded earlier in the line by the string
1336 "expect-floats"
1337 it will treat it as a single token, the floating-point number
1338 123.456:
1339 .nf
1340
1341     %{
1342     #include <math.h>
1343     %}
1344     %s expect
1345
1346     %%
1347     expect-floats        BEGIN(expect);
1348
1349     <expect>[0-9]+"."[0-9]+      {
1350                 printf( "found a float, = %f\\n",
1351                         atof( yytext ) );
1352                 }
1353     <expect>\\n           {
1354                 /* that's the end of the line, so
1355                  * we need another "expect-number"
1356                  * before we'll recognize any more
1357                  * numbers
1358                  */
1359                 BEGIN(INITIAL);
1360                 }
1361
1362     [0-9]+      {
1363                 printf( "found an integer, = %d\\n",
1364                         atoi( yytext ) );
1365                 }
1366
1367     "."         printf( "found a dot\\n" );
1368
1369 .fi
1370 Here is a scanner which recognizes (and discards) C comments while
1371 maintaining a count of the current input line.
1372 .nf
1373
1374     %x comment
1375     %%
1376             int line_num = 1;
1377
1378     "/*"         BEGIN(comment);
1379
1380     <comment>[^*\\n]*        /* eat anything that's not a '*' */
1381     <comment>"*"+[^*/\\n]*   /* eat up '*'s not followed by '/'s */
1382     <comment>\\n             ++line_num;
1383     <comment>"*"+"/"        BEGIN(INITIAL);
1384
1385 .fi
1386 This scanner goes to a bit of trouble to match as much
1387 text as possible with each rule.  In general, when attempting to write
1388 a high-speed scanner try to match as much possible in each rule, as
1389 it's a big win.
1390 .PP
1391 Note that start-conditions names are really integer values and
1392 can be stored as such.  Thus, the above could be extended in the
1393 following fashion:
1394 .nf
1395
1396     %x comment foo
1397     %%
1398             int line_num = 1;
1399             int comment_caller;
1400
1401     "/*"         {
1402                  comment_caller = INITIAL;
1403                  BEGIN(comment);
1404                  }
1405
1406     ...
1407
1408     <foo>"/*"    {
1409                  comment_caller = foo;
1410                  BEGIN(comment);
1411                  }
1412
1413     <comment>[^*\\n]*        /* eat anything that's not a '*' */
1414     <comment>"*"+[^*/\\n]*   /* eat up '*'s not followed by '/'s */
1415     <comment>\\n             ++line_num;
1416     <comment>"*"+"/"        BEGIN(comment_caller);
1417
1418 .fi
1419 Furthermore, you can access the current start condition using
1420 the integer-valued
1421 .B YY_START
1422 macro.  For example, the above assignments to
1423 .I comment_caller
1424 could instead be written
1425 .nf
1426
1427     comment_caller = YY_START;
1428
1429 .fi
1430 Flex provides
1431 .B YYSTATE
1432 as an alias for
1433 .B YY_START
1434 (since that is what's used by AT&T
1435 .I lex).
1436 .PP
1437 Note that start conditions do not have their own name-space; %s's and %x's
1438 declare names in the same fashion as #define's.
1439 .PP
1440 Finally, here's an example of how to match C-style quoted strings using
1441 exclusive start conditions, including expanded escape sequences (but
1442 not including checking for a string that's too long):
1443 .nf
1444
1445     %x str
1446
1447     %%
1448             char string_buf[MAX_STR_CONST];
1449             char *string_buf_ptr;
1450
1451
1452     \\"      string_buf_ptr = string_buf; BEGIN(str);
1453
1454     <str>\\"        { /* saw closing quote - all done */
1455             BEGIN(INITIAL);
1456             *string_buf_ptr = '\\0';
1457             /* return string constant token type and
1458              * value to parser
1459              */
1460             }
1461
1462     <str>\\n        {
1463             /* error - unterminated string constant */
1464             /* generate error message */
1465             }
1466
1467     <str>\\\\[0-7]{1,3} {
1468             /* octal escape sequence */
1469             int result;
1470
1471             (void) sscanf( yytext + 1, "%o", &result );
1472
1473             if ( result > 0xff )
1474                     /* error, constant is out-of-bounds */
1475
1476             *string_buf_ptr++ = result;
1477             }
1478
1479     <str>\\\\[0-9]+ {
1480             /* generate error - bad escape sequence; something
1481              * like '\\48' or '\\0777777'
1482              */
1483             }
1484
1485     <str>\\\\n  *string_buf_ptr++ = '\\n';
1486     <str>\\\\t  *string_buf_ptr++ = '\\t';
1487     <str>\\\\r  *string_buf_ptr++ = '\\r';
1488     <str>\\\\b  *string_buf_ptr++ = '\\b';
1489     <str>\\\\f  *string_buf_ptr++ = '\\f';
1490
1491     <str>\\\\(.|\\n)  *string_buf_ptr++ = yytext[1];
1492
1493     <str>[^\\\\\\n\\"]+        {
1494             char *yptr = yytext;
1495
1496             while ( *yptr )
1497                     *string_buf_ptr++ = *yptr++;
1498             }
1499
1500 .fi
1501 .PP
1502 Often, such as in some of the examples above, you wind up writing a
1503 whole bunch of rules all preceded by the same start condition(s).  Flex
1504 makes this a little easier and cleaner by introducing a notion of
1505 start condition
1506 .I scope.
1507 A start condition scope is begun with:
1508 .nf
1509
1510     <SCs>{
1511
1512 .fi
1513 where
1514 .I SCs
1515 is a list of one or more start conditions.  Inside the start condition
1516 scope, every rule automatically has the prefix
1517 .I <SCs>
1518 applied to it, until a
1519 .I '}'
1520 which matches the initial
1521 .I '{'.
1522 So, for example,
1523 .nf
1524
1525     <ESC>{
1526         "\\\\n"   return '\\n';
1527         "\\\\r"   return '\\r';
1528         "\\\\f"   return '\\f';
1529         "\\\\0"   return '\\0';
1530     }
1531
1532 .fi
1533 is equivalent to:
1534 .nf
1535
1536     <ESC>"\\\\n"  return '\\n';
1537     <ESC>"\\\\r"  return '\\r';
1538     <ESC>"\\\\f"  return '\\f';
1539     <ESC>"\\\\0"  return '\\0';
1540
1541 .fi
1542 Start condition scopes may be nested.
1543 .PP
1544 Three routines are available for manipulating stacks of start conditions:
1545 .TP
1546 .B void yy_push_state(int new_state)
1547 pushes the current start condition onto the top of the start condition
1548 stack and switches to
1549 .I new_state
1550 as though you had used
1551 .B BEGIN new_state
1552 (recall that start condition names are also integers).
1553 .TP
1554 .B void yy_pop_state()
1555 pops the top of the stack and switches to it via
1556 .B BEGIN.
1557 .TP
1558 .B int yy_top_state()
1559 returns the top of the stack without altering the stack's contents.
1560 .PP
1561 The start condition stack grows dynamically and so has no built-in
1562 size limitation.  If memory is exhausted, program execution aborts.
1563 .PP
1564 To use start condition stacks, your scanner must include a
1565 .B %option stack
1566 directive (see Options below).
1567 .SH MULTIPLE INPUT BUFFERS
1568 Some scanners (such as those which support "include" files)
1569 require reading from several input streams.  As
1570 .I flex
1571 scanners do a large amount of buffering, one cannot control
1572 where the next input will be read from by simply writing a
1573 .B YY_INPUT
1574 which is sensitive to the scanning context.
1575 .B YY_INPUT
1576 is only called when the scanner reaches the end of its buffer, which
1577 may be a long time after scanning a statement such as an "include"
1578 which requires switching the input source.
1579 .PP
1580 To negotiate these sorts of problems,
1581 .I flex
1582 provides a mechanism for creating and switching between multiple
1583 input buffers.  An input buffer is created by using:
1584 .nf
1585
1586     YY_BUFFER_STATE yy_create_buffer( FILE *file, int size )
1587
1588 .fi
1589 which takes a
1590 .I FILE
1591 pointer and a size and creates a buffer associated with the given
1592 file and large enough to hold
1593 .I size
1594 characters (when in doubt, use
1595 .B YY_BUF_SIZE
1596 for the size).  It returns a
1597 .B YY_BUFFER_STATE
1598 handle, which may then be passed to other routines (see below).  The
1599 .B YY_BUFFER_STATE
1600 type is a pointer to an opaque
1601 .B struct yy_buffer_state
1602 structure, so you may safely initialize YY_BUFFER_STATE variables to
1603 .B ((YY_BUFFER_STATE) 0)
1604 if you wish, and also refer to the opaque structure in order to
1605 correctly declare input buffers in source files other than that
1606 of your scanner.  Note that the
1607 .I FILE
1608 pointer in the call to
1609 .B yy_create_buffer
1610 is only used as the value of
1611 .I yyin
1612 seen by
1613 .B YY_INPUT;
1614 if you redefine
1615 .B YY_INPUT
1616 so it no longer uses
1617 .I yyin,
1618 then you can safely pass a nil
1619 .I FILE
1620 pointer to
1621 .B yy_create_buffer.
1622 You select a particular buffer to scan from using:
1623 .nf
1624
1625     void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer )
1626
1627 .fi
1628 switches the scanner's input buffer so subsequent tokens will
1629 come from
1630 .I new_buffer.
1631 Note that
1632 .B yy_switch_to_buffer()
1633 may be used by yywrap() to set things up for continued scanning, instead
1634 of opening a new file and pointing
1635 .I yyin
1636 at it.  Note also that switching input sources via either
1637 .B yy_switch_to_buffer()
1638 or
1639 .B yywrap()
1640 does
1641 .I not
1642 change the start condition.
1643 .nf
1644
1645     void yy_delete_buffer( YY_BUFFER_STATE buffer )
1646
1647 .fi
1648 is used to reclaim the storage associated with a buffer.  (
1649 .B buffer
1650 can be nil, in which case the routine does nothing.)
1651 You can also clear the current contents of a buffer using:
1652 .nf
1653
1654     void yy_flush_buffer( YY_BUFFER_STATE buffer )
1655
1656 .fi
1657 This function discards the buffer's contents,
1658 so the next time the scanner attempts to match a token from the
1659 buffer, it will first fill the buffer anew using
1660 .B YY_INPUT.
1661 .PP
1662 .B yy_new_buffer()
1663 is an alias for
1664 .B yy_create_buffer(),
1665 provided for compatibility with the C++ use of
1666 .I new
1667 and
1668 .I delete
1669 for creating and destroying dynamic objects.
1670 .PP
1671 Finally, the
1672 .B YY_CURRENT_BUFFER
1673 macro returns a
1674 .B YY_BUFFER_STATE
1675 handle to the current buffer.
1676 .PP
1677 Here is an example of using these features for writing a scanner
1678 which expands include files (the
1679 .B <<EOF>>
1680 feature is discussed below):
1681 .nf
1682
1683     /* the "incl" state is used for picking up the name
1684      * of an include file
1685      */
1686     %x incl
1687
1688     %{
1689     #define MAX_INCLUDE_DEPTH 10
1690     YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH];
1691     int include_stack_ptr = 0;
1692     %}
1693
1694     %%
1695     include             BEGIN(incl);
1696
1697     [a-z]+              ECHO;
1698     [^a-z\\n]*\\n?        ECHO;
1699
1700     <incl>[ \\t]*      /* eat the whitespace */
1701     <incl>[^ \\t\\n]+   { /* got the include file name */
1702             if ( include_stack_ptr >= MAX_INCLUDE_DEPTH )
1703                 {
1704                 fprintf( stderr, "Includes nested too deeply" );
1705                 exit( 1 );
1706                 }
1707
1708             include_stack[include_stack_ptr++] =
1709                 YY_CURRENT_BUFFER;
1710
1711             yyin = fopen( yytext, "r" );
1712
1713             if ( ! yyin )
1714                 error( ... );
1715
1716             yy_switch_to_buffer(
1717                 yy_create_buffer( yyin, YY_BUF_SIZE ) );
1718
1719             BEGIN(INITIAL);
1720             }
1721
1722     <<EOF>> {
1723             if ( --include_stack_ptr < 0 )
1724                 {
1725                 yyterminate();
1726                 }
1727
1728             else
1729                 {
1730                 yy_delete_buffer( YY_CURRENT_BUFFER );
1731                 yy_switch_to_buffer(
1732                      include_stack[include_stack_ptr] );
1733                 }
1734             }
1735
1736 .fi
1737 Three routines are available for setting up input buffers for
1738 scanning in-memory strings instead of files.  All of them create
1739 a new input buffer for scanning the string, and return a corresponding
1740 .B YY_BUFFER_STATE
1741 handle (which you should delete with
1742 .B yy_delete_buffer()
1743 when done with it).  They also switch to the new buffer using
1744 .B yy_switch_to_buffer(),
1745 so the next call to
1746 .B yylex()
1747 will start scanning the string.
1748 .TP
1749 .B yy_scan_string(const char *str)
1750 scans a NUL-terminated string.
1751 .TP
1752 .B yy_scan_bytes(const char *bytes, int len)
1753 scans
1754 .I len
1755 bytes (including possibly NUL's)
1756 starting at location
1757 .I bytes.
1758 .PP
1759 Note that both of these functions create and scan a
1760 .I copy
1761 of the string or bytes.  (This may be desirable, since
1762 .B yylex()
1763 modifies the contents of the buffer it is scanning.)  You can avoid the
1764 copy by using:
1765 .TP
1766 .B yy_scan_buffer(char *base, yy_size_t size)
1767 which scans in place the buffer starting at
1768 .I base,
1769 consisting of
1770 .I size
1771 bytes, the last two bytes of which
1772 .I must
1773 be
1774 .B YY_END_OF_BUFFER_CHAR
1775 (ASCII NUL).
1776 These last two bytes are not scanned; thus, scanning
1777 consists of
1778 .B base[0]
1779 through
1780 .B base[size-2],
1781 inclusive.
1782 .IP
1783 If you fail to set up
1784 .I base
1785 in this manner (i.e., forget the final two
1786 .B YY_END_OF_BUFFER_CHAR
1787 bytes), then
1788 .B yy_scan_buffer()
1789 returns a nil pointer instead of creating a new input buffer.
1790 .IP
1791 The type
1792 .B yy_size_t
1793 is an integral type to which you can cast an integer expression
1794 reflecting the size of the buffer.
1795 .SH END-OF-FILE RULES
1796 The special rule "<<EOF>>" indicates
1797 actions which are to be taken when an end-of-file is
1798 encountered and yywrap() returns non-zero (i.e., indicates
1799 no further files to process).  The action must finish
1800 by doing one of four things:
1801 .IP -
1802 assigning
1803 .I yyin
1804 to a new input file (in previous versions of flex, after doing the
1805 assignment you had to call the special action
1806 .B YY_NEW_FILE;
1807 this is no longer necessary);
1808 .IP -
1809 executing a
1810 .I return
1811 statement;
1812 .IP -
1813 executing the special
1814 .B yyterminate()
1815 action;
1816 .IP -
1817 or, switching to a new buffer using
1818 .B yy_switch_to_buffer()
1819 as shown in the example above.
1820 .PP
1821 <<EOF>> rules may not be used with other
1822 patterns; they may only be qualified with a list of start
1823 conditions.  If an unqualified <<EOF>> rule is given, it
1824 applies to
1825 .I all
1826 start conditions which do not already have <<EOF>> actions.  To
1827 specify an <<EOF>> rule for only the initial start condition, use
1828 .nf
1829
1830     <INITIAL><<EOF>>
1831
1832 .fi
1833 .PP
1834 These rules are useful for catching things like unclosed comments.
1835 An example:
1836 .nf
1837
1838     %x quote
1839     %%
1840
1841     ...other rules for dealing with quotes...
1842
1843     <quote><<EOF>>   {
1844              error( "unterminated quote" );
1845              yyterminate();
1846              }
1847     <<EOF>>  {
1848              if ( *++filelist )
1849                  yyin = fopen( *filelist, "r" );
1850              else
1851                 yyterminate();
1852              }
1853
1854 .fi
1855 .SH MISCELLANEOUS MACROS
1856 The macro
1857 .B YY_USER_ACTION
1858 can be defined to provide an action
1859 which is always executed prior to the matched rule's action.  For example,
1860 it could be #define'd to call a routine to convert yytext to lower-case.
1861 When
1862 .B YY_USER_ACTION
1863 is invoked, the variable
1864 .I yy_act
1865 gives the number of the matched rule (rules are numbered starting with 1).
1866 Suppose you want to profile how often each of your rules is matched.  The
1867 following would do the trick:
1868 .nf
1869
1870     #define YY_USER_ACTION ++ctr[yy_act]
1871
1872 .fi
1873 where
1874 .I ctr
1875 is an array to hold the counts for the different rules.  Note that
1876 the macro
1877 .B YY_NUM_RULES
1878 gives the total number of rules (including the default rule, even if
1879 you use
1880 .B \-s),
1881 so a correct declaration for
1882 .I ctr
1883 is:
1884 .nf
1885
1886     int ctr[YY_NUM_RULES];
1887
1888 .fi
1889 .PP
1890 The macro
1891 .B YY_USER_INIT
1892 may be defined to provide an action which is always executed before
1893 the first scan (and before the scanner's internal initializations are done).
1894 For example, it could be used to call a routine to read
1895 in a data table or open a logging file.
1896 .PP
1897 The macro
1898 .B yy_set_interactive(is_interactive)
1899 can be used to control whether the current buffer is considered
1900 .I interactive.
1901 An interactive buffer is processed more slowly,
1902 but must be used when the scanner's input source is indeed
1903 interactive to avoid problems due to waiting to fill buffers
1904 (see the discussion of the
1905 .B \-I
1906 flag below).  A non-zero value
1907 in the macro invocation marks the buffer as interactive, a zero
1908 value as non-interactive.  Note that use of this macro overrides
1909 .B %option interactive ,
1910 .B %option always-interactive
1911 or
1912 .B %option never-interactive
1913 (see Options below).
1914 .B yy_set_interactive()
1915 must be invoked prior to beginning to scan the buffer that is
1916 (or is not) to be considered interactive.
1917 .PP
1918 The macro
1919 .B yy_set_bol(at_bol)
1920 can be used to control whether the current buffer's scanning
1921 context for the next token match is done as though at the
1922 beginning of a line.  A non-zero macro argument makes rules anchored with
1923 \&'^' active, while a zero argument makes '^' rules inactive.
1924 .PP
1925 The macro
1926 .B YY_AT_BOL()
1927 returns true if the next token scanned from the current buffer
1928 will have '^' rules active, false otherwise.
1929 .PP
1930 In the generated scanner, the actions are all gathered in one large
1931 switch statement and separated using
1932 .B YY_BREAK,
1933 which may be redefined.  By default, it is simply a "break", to separate
1934 each rule's action from the following rule's.
1935 Redefining
1936 .B YY_BREAK
1937 allows, for example, C++ users to
1938 #define YY_BREAK to do nothing (while being very careful that every
1939 rule ends with a "break" or a "return"!) to avoid suffering from
1940 unreachable statement warnings where because a rule's action ends with
1941 "return", the
1942 .B YY_BREAK
1943 is inaccessible.
1944 .SH VALUES AVAILABLE TO THE USER
1945 This section summarizes the various values available to the user
1946 in the rule actions.
1947 .IP -
1948 .B char *yytext
1949 holds the text of the current token.  It may be modified but not lengthened
1950 (you cannot append characters to the end).
1951 .IP
1952 If the special directive
1953 .B %array
1954 appears in the first section of the scanner description, then
1955 .B yytext
1956 is instead declared
1957 .B char yytext[YYLMAX],
1958 where
1959 .B YYLMAX
1960 is a macro definition that you can redefine in the first section
1961 if you don't like the default value (generally 8KB).  Using
1962 .B %array
1963 results in somewhat slower scanners, but the value of
1964 .B yytext
1965 becomes immune to calls to
1966 .I input()
1967 and
1968 .I unput(),
1969 which potentially destroy its value when
1970 .B yytext
1971 is a character pointer.  The opposite of
1972 .B %array
1973 is
1974 .B %pointer,
1975 which is the default.
1976 .IP
1977 You cannot use
1978 .B %array
1979 when generating C++ scanner classes
1980 (the
1981 .B \-+
1982 flag).
1983 .IP -
1984 .B int yyleng
1985 holds the length of the current token.
1986 .IP -
1987 .B FILE *yyin
1988 is the file which by default
1989 .I flex
1990 reads from.  It may be redefined but doing so only makes sense before
1991 scanning begins or after an EOF has been encountered.  Changing it in
1992 the midst of scanning will have unexpected results since
1993 .I flex
1994 buffers its input; use
1995 .B yyrestart()
1996 instead.
1997 Once scanning terminates because an end-of-file
1998 has been seen, you can assign
1999 .I yyin
2000 at the new input file and then call the scanner again to continue scanning.
2001 .IP -
2002 .B void yyrestart( FILE *new_file )
2003 may be called to point
2004 .I yyin
2005 at the new input file.  The switch-over to the new file is immediate
2006 (any previously buffered-up input is lost).  Note that calling
2007 .B yyrestart()
2008 with
2009 .I yyin
2010 as an argument thus throws away the current input buffer and continues
2011 scanning the same input file.
2012 .IP -
2013 .B FILE *yyout
2014 is the file to which
2015 .B ECHO
2016 actions are done.  It can be reassigned by the user.
2017 .IP -
2018 .B YY_CURRENT_BUFFER
2019 returns a
2020 .B YY_BUFFER_STATE
2021 handle to the current buffer.
2022 .IP -
2023 .B YY_START
2024 returns an integer value corresponding to the current start
2025 condition.  You can subsequently use this value with
2026 .B BEGIN
2027 to return to that start condition.
2028 .SH INTERFACING WITH YACC
2029 One of the main uses of
2030 .I flex
2031 is as a companion to the
2032 .I yacc
2033 parser-generator.
2034 .I yacc
2035 parsers expect to call a routine named
2036 .B yylex()
2037 to find the next input token.  The routine is supposed to
2038 return the type of the next token as well as putting any associated
2039 value in the global
2040 .B yylval.
2041 To use
2042 .I flex
2043 with
2044 .I yacc,
2045 one specifies the
2046 .B \-d
2047 option to
2048 .I yacc
2049 to instruct it to generate the file
2050 .B y.tab.h
2051 containing definitions of all the
2052 .B %tokens
2053 appearing in the
2054 .I yacc
2055 input.  This file is then included in the
2056 .I flex
2057 scanner.  For example, if one of the tokens is "TOK_NUMBER",
2058 part of the scanner might look like:
2059 .nf
2060
2061     %{
2062     #include "y.tab.h"
2063     %}
2064
2065     %%
2066
2067     [0-9]+        yylval = atoi( yytext ); return TOK_NUMBER;
2068
2069 .fi
2070 .SH OPTIONS
2071 .I flex
2072 has the following options:
2073 .TP
2074 .B \-b
2075 Generate backing-up information to
2076 .I lex.backup.
2077 This is a list of scanner states which require backing up
2078 and the input characters on which they do so.  By adding rules one
2079 can remove backing-up states.  If
2080 .I all
2081 backing-up states are eliminated and
2082 .B \-Cf
2083 or
2084 .B \-CF
2085 is used, the generated scanner will run faster (see the
2086 .B \-p
2087 flag).  Only users who wish to squeeze every last cycle out of their
2088 scanners need worry about this option.  (See the section on Performance
2089 Considerations below.)
2090 .TP
2091 .B \-c
2092 is a do-nothing, deprecated option included for POSIX compliance.
2093 .TP
2094 .B \-d
2095 makes the generated scanner run in
2096 .I debug
2097 mode.  Whenever a pattern is recognized and the global
2098 .B yy_flex_debug
2099 is non-zero (which is the default),
2100 the scanner will write to
2101 .I stderr
2102 a line of the form:
2103 .nf
2104
2105     --accepting rule at line 53 ("the matched text")
2106
2107 .fi
2108 The line number refers to the location of the rule in the file
2109 defining the scanner (i.e., the file that was fed to flex).  Messages
2110 are also generated when the scanner backs up, accepts the
2111 default rule, reaches the end of its input buffer (or encounters
2112 a NUL; at this point, the two look the same as far as the scanner's concerned),
2113 or reaches an end-of-file.
2114 .TP
2115 .B \-f
2116 specifies
2117 .I fast scanner.
2118 No table compression is done and stdio is bypassed.
2119 The result is large but fast.  This option is equivalent to
2120 .B \-Cfr
2121 (see below).
2122 .TP
2123 .B \-h
2124 generates a "help" summary of
2125 .I flex's
2126 options to
2127 .I stdout
2128 and then exits.
2129 .B \-?
2130 and
2131 .B \-\-help
2132 are synonyms for
2133 .B \-h.
2134 .TP
2135 .B \-i
2136 instructs
2137 .I flex
2138 to generate a
2139 .I case-insensitive
2140 scanner.  The case of letters given in the
2141 .I flex
2142 input patterns will
2143 be ignored, and tokens in the input will be matched regardless of case.  The
2144 matched text given in
2145 .I yytext
2146 will have the preserved case (i.e., it will not be folded).
2147 .TP
2148 .B \-l
2149 turns on maximum compatibility with the original AT&T
2150 .I lex
2151 implementation.  Note that this does not mean
2152 .I full
2153 compatibility.  Use of this option costs a considerable amount of
2154 performance, and it cannot be used with the
2155 .B \-+, -f, -F, -Cf,
2156 or
2157 .B -CF
2158 options.  For details on the compatibilities it provides, see the section
2159 "Incompatibilities With Lex And POSIX" below.  This option also results
2160 in the name
2161 .B YY_FLEX_LEX_COMPAT
2162 being #define'd in the generated scanner.
2163 .TP
2164 .B \-n
2165 is another do-nothing, deprecated option included only for
2166 POSIX compliance.
2167 .TP
2168 .B \-p
2169 generates a performance report to stderr.  The report
2170 consists of comments regarding features of the
2171 .I flex
2172 input file which will cause a serious loss of performance in the resulting
2173 scanner.  If you give the flag twice, you will also get comments regarding
2174 features that lead to minor performance losses.
2175 .IP
2176 Note that the use of
2177 .B REJECT,
2178 .B %option yylineno,
2179 and variable trailing context (see the Deficiencies / Bugs section below)
2180 entails a substantial performance penalty; use of
2181 .I yymore(),
2182 the
2183 .B ^
2184 operator,
2185 and the
2186 .B \-I
2187 flag entail minor performance penalties.
2188 .TP
2189 .B \-s
2190 causes the
2191 .I default rule
2192 (that unmatched scanner input is echoed to
2193 .I stdout)
2194 to be suppressed.  If the scanner encounters input that does not
2195 match any of its rules, it aborts with an error.  This option is
2196 useful for finding holes in a scanner's rule set.
2197 .TP
2198 .B \-t
2199 instructs
2200 .I flex
2201 to write the scanner it generates to standard output instead
2202 of
2203 .B lex.yy.c.
2204 .TP
2205 .B \-v
2206 specifies that
2207 .I flex
2208 should write to
2209 .I stderr
2210 a summary of statistics regarding the scanner it generates.
2211 Most of the statistics are meaningless to the casual
2212 .I flex
2213 user, but the first line identifies the version of
2214 .I flex
2215 (same as reported by
2216 .B \-V),
2217 and the next line the flags used when generating the scanner, including
2218 those that are on by default.
2219 .TP
2220 .B \-w
2221 suppresses warning messages.
2222 .TP
2223 .B \-B
2224 instructs
2225 .I flex
2226 to generate a
2227 .I batch
2228 scanner, the opposite of
2229 .I interactive
2230 scanners generated by
2231 .B \-I
2232 (see below).  In general, you use
2233 .B \-B
2234 when you are
2235 .I certain
2236 that your scanner will never be used interactively, and you want to
2237 squeeze a
2238 .I little
2239 more performance out of it.  If your goal is instead to squeeze out a
2240 .I lot
2241 more performance, you should  be using the
2242 .B \-Cf
2243 or
2244 .B \-CF
2245 options (discussed below), which turn on
2246 .B \-B
2247 automatically anyway.
2248 .TP
2249 .B \-F
2250 specifies that the
2251 .ul
2252 fast
2253 scanner table representation should be used (and stdio
2254 bypassed).  This representation is
2255 about as fast as the full table representation
2256 .B (-f),
2257 and for some sets of patterns will be considerably smaller (and for
2258 others, larger).  In general, if the pattern set contains both "keywords"
2259 and a catch-all, "identifier" rule, such as in the set:
2260 .nf
2261
2262     "case"    return TOK_CASE;
2263     "switch"  return TOK_SWITCH;
2264     ...
2265     "default" return TOK_DEFAULT;
2266     [a-z]+    return TOK_ID;
2267
2268 .fi
2269 then you're better off using the full table representation.  If only
2270 the "identifier" rule is present and you then use a hash table or some such
2271 to detect the keywords, you're better off using
2272 .B -F.
2273 .IP
2274 This option is equivalent to
2275 .B \-CFr
2276 (see below).  It cannot be used with
2277 .B \-+.
2278 .TP
2279 .B \-I
2280 instructs
2281 .I flex
2282 to generate an
2283 .I interactive
2284 scanner.  An interactive scanner is one that only looks ahead to decide
2285 what token has been matched if it absolutely must.  It turns out that
2286 always looking one extra character ahead, even if the scanner has already
2287 seen enough text to disambiguate the current token, is a bit faster than
2288 only looking ahead when necessary.  But scanners that always look ahead
2289 give dreadful interactive performance; for example, when a user types
2290 a newline, it is not recognized as a newline token until they enter
2291 .I another
2292 token, which often means typing in another whole line.
2293 .IP
2294 .I Flex
2295 scanners default to
2296 .I interactive
2297 unless you use the
2298 .B \-Cf
2299 or
2300 .B \-CF
2301 table-compression options (see below).  That's because if you're looking
2302 for high-performance you should be using one of these options, so if you
2303 didn't,
2304 .I flex
2305 assumes you'd rather trade off a bit of run-time performance for intuitive
2306 interactive behavior.  Note also that you
2307 .I cannot
2308 use
2309 .B \-I
2310 in conjunction with
2311 .B \-Cf
2312 or
2313 .B \-CF.
2314 Thus, this option is not really needed; it is on by default for all those
2315 cases in which it is allowed.
2316 .IP
2317 Note that if
2318 .B isatty()
2319 returns false for the scanner input, flex will revert to batch mode, even if
2320 .B \-I
2321 was specified.  To force interactive mode no matter what, use
2322 .B %option always-interactive
2323 (see Options below).
2324 .IP
2325 You can force a scanner to
2326 .I not
2327 be interactive by using
2328 .B \-B
2329 (see above).
2330 .TP
2331 .B \-L
2332 instructs
2333 .I flex
2334 not to generate
2335 .B #line
2336 directives.  Without this option,
2337 .I flex
2338 peppers the generated scanner
2339 with #line directives so error messages in the actions will be correctly
2340 located with respect to either the original
2341 .I flex
2342 input file (if the errors are due to code in the input file), or
2343 .B lex.yy.c
2344 (if the errors are
2345 .I flex's
2346 fault -- you should report these sorts of errors to the email address
2347 given below).
2348 .TP
2349 .B \-T
2350 makes
2351 .I flex
2352 run in
2353 .I trace
2354 mode.  It will generate a lot of messages to
2355 .I stderr
2356 concerning
2357 the form of the input and the resultant non-deterministic and deterministic
2358 finite automata.  This option is mostly for use in maintaining
2359 .I flex.
2360 .TP
2361 .B \-V
2362 prints the version number to
2363 .I stdout
2364 and exits.
2365 .B \-\-version
2366 is a synonym for
2367 .B \-V.
2368 .TP
2369 .B \-7
2370 instructs
2371 .I flex
2372 to generate a 7-bit scanner, i.e., one which can only recognize 7-bit
2373 characters in its input.  The advantage of using
2374 .B \-7
2375 is that the scanner's tables can be up to half the size of those generated
2376 using the
2377 .B \-8
2378 option (see below).  The disadvantage is that such scanners often hang
2379 or crash if their input contains an 8-bit character.
2380 .IP
2381 Note, however, that unless you generate your scanner using the
2382 .B \-Cf
2383 or
2384 .B \-CF
2385 table compression options, use of
2386 .B \-7
2387 will save only a small amount of table space, and make your scanner
2388 considerably less portable.
2389 .I Flex's
2390 default behavior is to generate an 8-bit scanner unless you use the
2391 .B \-Cf
2392 or
2393 .B \-CF,
2394 in which case
2395 .I flex
2396 defaults to generating 7-bit scanners unless your site was always
2397 configured to generate 8-bit scanners (as will often be the case
2398 with non-USA sites).  You can tell whether flex generated a 7-bit
2399 or an 8-bit scanner by inspecting the flag summary in the
2400 .B \-v
2401 output as described above.
2402 .IP
2403 Note that if you use
2404 .B \-Cfe
2405 or
2406 .B \-CFe
2407 (those table compression options, but also using equivalence classes as
2408 discussed see below), flex still defaults to generating an 8-bit
2409 scanner, since usually with these compression options full 8-bit tables
2410 are not much more expensive than 7-bit tables.
2411 .TP
2412 .B \-8
2413 instructs
2414 .I flex
2415 to generate an 8-bit scanner, i.e., one which can recognize 8-bit
2416 characters.  This flag is only needed for scanners generated using
2417 .B \-Cf
2418 or
2419 .B \-CF,
2420 as otherwise flex defaults to generating an 8-bit scanner anyway.
2421 .IP
2422 See the discussion of
2423 .B \-7
2424 above for flex's default behavior and the tradeoffs between 7-bit
2425 and 8-bit scanners.
2426 .TP
2427 .B \-+
2428 specifies that you want flex to generate a C++
2429 scanner class.  See the section on Generating C++ Scanners below for
2430 details.
2431 .TP
2432 .B \-C[aefFmr]
2433 controls the degree of table compression and, more generally, trade-offs
2434 between small scanners and fast scanners.
2435 .IP
2436 .B \-Ca
2437 ("align") instructs flex to trade off larger tables in the
2438 generated scanner for faster performance because the elements of
2439 the tables are better aligned for memory access and computation.  On some
2440 RISC architectures, fetching and manipulating longwords is more efficient
2441 than with smaller-sized units such as shortwords.  This option can
2442 double the size of the tables used by your scanner.
2443 .IP
2444 .B \-Ce
2445 directs
2446 .I flex
2447 to construct
2448 .I equivalence classes,
2449 i.e., sets of characters
2450 which have identical lexical properties (for example, if the only
2451 appearance of digits in the
2452 .I flex
2453 input is in the character class
2454 "[0-9]" then the digits '0', '1', ..., '9' will all be put
2455 in the same equivalence class).  Equivalence classes usually give
2456 dramatic reductions in the final table/object file sizes (typically
2457 a factor of 2-5) and are pretty cheap performance-wise (one array
2458 look-up per character scanned).
2459 .IP
2460 .B \-Cf
2461 specifies that the
2462 .I full
2463 scanner tables should be generated -
2464 .I flex
2465 should not compress the
2466 tables by taking advantages of similar transition functions for
2467 different states.
2468 .IP
2469 .B \-CF
2470 specifies that the alternate fast scanner representation (described
2471 above under the
2472 .B \-F
2473 flag)
2474 should be used.  This option cannot be used with
2475 .B \-+.
2476 .IP
2477 .B \-Cm
2478 directs
2479 .I flex
2480 to construct
2481 .I meta-equivalence classes,
2482 which are sets of equivalence classes (or characters, if equivalence
2483 classes are not being used) that are commonly used together.  Meta-equivalence
2484 classes are often a big win when using compressed tables, but they
2485 have a moderate performance impact (one or two "if" tests and one
2486 array look-up per character scanned).
2487 .IP
2488 .B \-Cr
2489 causes the generated scanner to
2490 .I bypass
2491 use of the standard I/O library (stdio) for input.  Instead of calling
2492 .B fread()
2493 or
2494 .B getc(),
2495 the scanner will use the
2496 .B read()
2497 system call, resulting in a performance gain which varies from system
2498 to system, but in general is probably negligible unless you are also using
2499 .B \-Cf
2500 or
2501 .B \-CF.
2502 Using
2503 .B \-Cr
2504 can cause strange behavior if, for example, you read from
2505 .I yyin
2506 using stdio prior to calling the scanner (because the scanner will miss
2507 whatever text your previous reads left in the stdio input buffer).
2508 .IP
2509 .B \-Cr
2510 has no effect if you define
2511 .B YY_INPUT
2512 (see The Generated Scanner above).
2513 .IP
2514 A lone
2515 .B \-C
2516 specifies that the scanner tables should be compressed but neither
2517 equivalence classes nor meta-equivalence classes should be used.
2518 .IP
2519 The options
2520 .B \-Cf
2521 or
2522 .B \-CF
2523 and
2524 .B \-Cm
2525 do not make sense together - there is no opportunity for meta-equivalence
2526 classes if the table is not being compressed.  Otherwise the options
2527 may be freely mixed, and are cumulative.
2528 .IP
2529 The default setting is
2530 .B \-Cem,
2531 which specifies that
2532 .I flex
2533 should generate equivalence classes
2534 and meta-equivalence classes.  This setting provides the highest
2535 degree of table compression.  You can trade off
2536 faster-executing scanners at the cost of larger tables with
2537 the following generally being true:
2538 .nf
2539
2540     slowest & smallest
2541           -Cem
2542           -Cm
2543           -Ce
2544           -C
2545           -C{f,F}e
2546           -C{f,F}
2547           -C{f,F}a
2548     fastest & largest
2549
2550 .fi
2551 Note that scanners with the smallest tables are usually generated and
2552 compiled the quickest, so
2553 during development you will usually want to use the default, maximal
2554 compression.
2555 .IP
2556 .B \-Cfe
2557 is often a good compromise between speed and size for production
2558 scanners.
2559 .TP
2560 .B \-ooutput
2561 directs flex to write the scanner to the file
2562 .B output
2563 instead of
2564 .B lex.yy.c.
2565 If you combine
2566 .B \-o
2567 with the
2568 .B \-t
2569 option, then the scanner is written to
2570 .I stdout
2571 but its
2572 .B #line
2573 directives (see the
2574 .B \\-L
2575 option above) refer to the file
2576 .B output.
2577 .TP
2578 .B \-Pprefix
2579 changes the default
2580 .I "yy"
2581 prefix used by
2582 .I flex
2583 for all globally-visible variable and function names to instead be
2584 .I prefix.
2585 For example,
2586 .B \-Pfoo
2587 changes the name of
2588 .B yytext
2589 to
2590 .B footext.
2591 It also changes the name of the default output file from
2592 .B lex.yy.c
2593 to
2594 .B lex.foo.c.
2595 Here are all of the names affected:
2596 .nf
2597
2598     yy_create_buffer
2599     yy_delete_buffer
2600     yy_flex_debug
2601     yy_init_buffer
2602     yy_flush_buffer
2603     yy_load_buffer_state
2604     yy_switch_to_buffer
2605     yyin
2606     yyleng
2607     yylex
2608     yylineno
2609     yyout
2610     yyrestart
2611     yytext
2612     yywrap
2613
2614 .fi
2615 (If you are using a C++ scanner, then only
2616 .B yywrap
2617 and
2618 .B yyFlexLexer
2619 are affected.)
2620 Within your scanner itself, you can still refer to the global variables
2621 and functions using either version of their name; but externally, they
2622 have the modified name.
2623 .IP
2624 This option lets you easily link together multiple
2625 .I flex
2626 programs into the same executable.  Note, though, that using this
2627 option also renames
2628 .B yywrap(),
2629 so you now
2630 .I must
2631 either
2632 provide your own (appropriately-named) version of the routine for your
2633 scanner, or use
2634 .B %option noyywrap,
2635 as linking with
2636 .B \-ll
2637 no longer provides one for you by default.
2638 .TP
2639 .B \-Sskeleton_file
2640 overrides the default skeleton file from which
2641 .I flex
2642 constructs its scanners.  You'll never need this option unless you are doing
2643 .I flex
2644 maintenance or development.
2645 .PP
2646 .I flex
2647 also provides a mechanism for controlling options within the
2648 scanner specification itself, rather than from the flex command-line.
2649 This is done by including
2650 .B %option
2651 directives in the first section of the scanner specification.
2652 You can specify multiple options with a single
2653 .B %option
2654 directive, and multiple directives in the first section of your flex input
2655 file.
2656 .PP
2657 Most options are given simply as names, optionally preceded by the
2658 word "no" (with no intervening whitespace) to negate their meaning.
2659 A number are equivalent to flex flags or their negation:
2660 .nf
2661
2662     7bit            -7 option
2663     8bit            -8 option
2664     align           -Ca option
2665     backup          -b option
2666     batch           -B option
2667     c++             -+ option
2668
2669     caseful or
2670     case-sensitive  opposite of -i (default)
2671
2672     case-insensitive or
2673     caseless        -i option
2674
2675     debug           -d option
2676     default         opposite of -s option
2677     ecs             -Ce option
2678     fast            -F option
2679     full            -f option
2680     interactive     -I option
2681     lex-compat      -l option
2682     meta-ecs        -Cm option
2683     perf-report     -p option
2684     read            -Cr option
2685     stdout          -t option
2686     verbose         -v option
2687     warn            opposite of -w option
2688                     (use "%option nowarn" for -w)
2689
2690     array           equivalent to "%array"
2691     pointer         equivalent to "%pointer" (default)
2692
2693 .fi
2694 Some
2695 .B %option's
2696 provide features otherwise not available:
2697 .TP
2698 .B always-interactive
2699 instructs flex to generate a scanner which always considers its input
2700 "interactive".  Normally, on each new input file the scanner calls
2701 .B isatty()
2702 in an attempt to determine whether
2703 the scanner's input source is interactive and thus should be read a
2704 character at a time.  When this option is used, however, then no
2705 such call is made.
2706 .TP
2707 .B main
2708 directs flex to provide a default
2709 .B main()
2710 program for the scanner, which simply calls
2711 .B yylex().
2712 This option implies
2713 .B noyywrap
2714 (see below).
2715 .TP
2716 .B never-interactive
2717 instructs flex to generate a scanner which never considers its input
2718 "interactive" (again, no call made to
2719 .B isatty()).
2720 This is the opposite of
2721 .B always-interactive.
2722 .TP
2723 .B stack
2724 enables the use of start condition stacks (see Start Conditions above).
2725 .TP
2726 .B stdinit
2727 if set (i.e.,
2728 .B %option stdinit)
2729 initializes
2730 .I yyin
2731 and
2732 .I yyout
2733 to
2734 .I stdin
2735 and
2736 .I stdout,
2737 instead of the default of
2738 .I nil.
2739 Some existing
2740 .I lex
2741 programs depend on this behavior, even though it is not compliant with
2742 ANSI C, which does not require
2743 .I stdin
2744 and
2745 .I stdout
2746 to be compile-time constant.
2747 .TP
2748 .B yylineno
2749 directs
2750 .I flex
2751 to generate a scanner that maintains the number of the current line
2752 read from its input in the global variable
2753 .B yylineno.
2754 This option is implied by
2755 .B %option lex-compat.
2756 .TP
2757 .B yywrap
2758 if unset (i.e.,
2759 .B %option noyywrap),
2760 makes the scanner not call
2761 .B yywrap()
2762 upon an end-of-file, but simply assume that there are no more
2763 files to scan (until the user points
2764 .I yyin
2765 at a new file and calls
2766 .B yylex()
2767 again).
2768 .PP
2769 .I flex
2770 scans your rule actions to determine whether you use the
2771 .B REJECT
2772 or
2773 .B yymore()
2774 features.  The
2775 .B reject
2776 and
2777 .B yymore
2778 options are available to override its decision as to whether you use the
2779 options, either by setting them (e.g.,
2780 .B %option reject)
2781 to indicate the feature is indeed used, or
2782 unsetting them to indicate it actually is not used
2783 (e.g.,
2784 .B %option noyymore).
2785 .PP
2786 Three options take string-delimited values, offset with '=':
2787 .nf
2788
2789     %option outfile="ABC"
2790
2791 .fi
2792 is equivalent to
2793 .B -oABC,
2794 and
2795 .nf
2796
2797     %option prefix="XYZ"
2798
2799 .fi
2800 is equivalent to
2801 .B -PXYZ.
2802 Finally,
2803 .nf
2804
2805     %option yyclass="foo"
2806
2807 .fi
2808 only applies when generating a C++ scanner (
2809 .B \-+
2810 option).  It informs
2811 .I flex
2812 that you have derived
2813 .B foo
2814 as a subclass of
2815 .B yyFlexLexer,
2816 so
2817 .I flex
2818 will place your actions in the member function
2819 .B foo::yylex()
2820 instead of
2821 .B yyFlexLexer::yylex().
2822 It also generates a
2823 .B yyFlexLexer::yylex()
2824 member function that emits a run-time error (by invoking
2825 .B yyFlexLexer::LexerError())
2826 if called.
2827 See Generating C++ Scanners, below, for additional information.
2828 .PP
2829 A number of options are available for lint purists who want to suppress
2830 the appearance of unneeded routines in the generated scanner.  Each of the
2831 following, if unset
2832 (e.g.,
2833 .B %option nounput
2834 ), results in the corresponding routine not appearing in
2835 the generated scanner:
2836 .nf
2837
2838     input, unput
2839     yy_push_state, yy_pop_state, yy_top_state
2840     yy_scan_buffer, yy_scan_bytes, yy_scan_string
2841
2842 .fi
2843 (though
2844 .B yy_push_state()
2845 and friends won't appear anyway unless you use
2846 .B %option stack).
2847 .SH PERFORMANCE CONSIDERATIONS
2848 The main design goal of
2849 .I flex
2850 is that it generate high-performance scanners.  It has been optimized
2851 for dealing well with large sets of rules.  Aside from the effects on
2852 scanner speed of the table compression
2853 .B \-C
2854 options outlined above,
2855 there are a number of options/actions which degrade performance.  These
2856 are, from most expensive to least:
2857 .nf
2858
2859     REJECT
2860     %option yylineno
2861     arbitrary trailing context
2862
2863     pattern sets that require backing up
2864     %array
2865     %option interactive
2866     %option always-interactive
2867
2868     '^' beginning-of-line operator
2869     yymore()
2870
2871 .fi
2872 with the first three all being quite expensive and the last two
2873 being quite cheap.  Note also that
2874 .B unput()
2875 is implemented as a routine call that potentially does quite a bit of
2876 work, while
2877 .B yyless()
2878 is a quite-cheap macro; so if just putting back some excess text you
2879 scanned, use
2880 .B yyless().
2881 .PP
2882 .B REJECT
2883 should be avoided at all costs when performance is important.
2884 It is a particularly expensive option.
2885 .PP
2886 Getting rid of backing up is messy and often may be an enormous
2887 amount of work for a complicated scanner.  In principal, one begins
2888 by using the
2889 .B \-b
2890 flag to generate a
2891 .I lex.backup
2892 file.  For example, on the input
2893 .nf
2894
2895     %%
2896     foo        return TOK_KEYWORD;
2897     foobar     return TOK_KEYWORD;
2898
2899 .fi
2900 the file looks like:
2901 .nf
2902
2903     State #6 is non-accepting -
2904      associated rule line numbers:
2905            2       3
2906      out-transitions: [ o ]
2907      jam-transitions: EOF [ \\001-n  p-\\177 ]
2908
2909     State #8 is non-accepting -
2910      associated rule line numbers:
2911            3
2912      out-transitions: [ a ]
2913      jam-transitions: EOF [ \\001-`  b-\\177 ]
2914
2915     State #9 is non-accepting -
2916      associated rule line numbers:
2917            3
2918      out-transitions: [ r ]
2919      jam-transitions: EOF [ \\001-q  s-\\177 ]
2920
2921     Compressed tables always back up.
2922
2923 .fi
2924 The first few lines tell us that there's a scanner state in
2925 which it can make a transition on an 'o' but not on any other
2926 character, and that in that state the currently scanned text does not match
2927 any rule.  The state occurs when trying to match the rules found
2928 at lines 2 and 3 in the input file.
2929 If the scanner is in that state and then reads
2930 something other than an 'o', it will have to back up to find
2931 a rule which is matched.  With
2932 a bit of headscratching one can see that this must be the
2933 state it's in when it has seen "fo".  When this has happened,
2934 if anything other than another 'o' is seen, the scanner will
2935 have to back up to simply match the 'f' (by the default rule).
2936 .PP
2937 The comment regarding State #8 indicates there's a problem
2938 when "foob" has been scanned.  Indeed, on any character other
2939 than an 'a', the scanner will have to back up to accept "foo".
2940 Similarly, the comment for State #9 concerns when "fooba" has
2941 been scanned and an 'r' does not follow.
2942 .PP
2943 The final comment reminds us that there's no point going to
2944 all the trouble of removing backing up from the rules unless
2945 we're using
2946 .B \-Cf
2947 or
2948 .B \-CF,
2949 since there's no performance gain doing so with compressed scanners.
2950 .PP
2951 The way to remove the backing up is to add "error" rules:
2952 .nf
2953
2954     %%
2955     foo         return TOK_KEYWORD;
2956     foobar      return TOK_KEYWORD;
2957
2958     fooba       |
2959     foob        |
2960     fo          {
2961                 /* false alarm, not really a keyword */
2962                 return TOK_ID;
2963                 }
2964
2965 .fi
2966 .PP
2967 Eliminating backing up among a list of keywords can also be
2968 done using a "catch-all" rule:
2969 .nf
2970
2971     %%
2972     foo         return TOK_KEYWORD;
2973     foobar      return TOK_KEYWORD;
2974
2975     [a-z]+      return TOK_ID;
2976
2977 .fi
2978 This is usually the best solution when appropriate.
2979 .PP
2980 Backing up messages tend to cascade.
2981 With a complicated set of rules it's not uncommon to get hundreds
2982 of messages.  If one can decipher them, though, it often
2983 only takes a dozen or so rules to eliminate the backing up (though
2984 it's easy to make a mistake and have an error rule accidentally match
2985 a valid token.  A possible future
2986 .I flex
2987 feature will be to automatically add rules to eliminate backing up).
2988 .PP
2989 It's important to keep in mind that you gain the benefits of eliminating
2990 backing up only if you eliminate
2991 .I every
2992 instance of backing up.  Leaving just one means you gain nothing.
2993 .PP
2994 .I Variable
2995 trailing context (where both the leading and trailing parts do not have
2996 a fixed length) entails almost the same performance loss as
2997 .B REJECT
2998 (i.e., substantial).  So when possible a rule like:
2999 .nf
3000
3001     %%
3002     mouse|rat/(cat|dog)   run();
3003
3004 .fi
3005 is better written:
3006 .nf
3007
3008     %%
3009     mouse/cat|dog         run();
3010     rat/cat|dog           run();
3011
3012 .fi
3013 or as
3014 .nf
3015
3016     %%
3017     mouse|rat/cat         run();
3018     mouse|rat/dog         run();
3019
3020 .fi
3021 Note that here the special '|' action does
3022 .I not
3023 provide any savings, and can even make things worse (see
3024 Deficiencies / Bugs below).
3025 .LP
3026 Another area where the user can increase a scanner's performance
3027 (and one that's easier to implement) arises from the fact that
3028 the longer the tokens matched, the faster the scanner will run.
3029 This is because with long tokens the processing of most input
3030 characters takes place in the (short) inner scanning loop, and
3031 does not often have to go through the additional work of setting up
3032 the scanning environment (e.g.,
3033 .B yytext)
3034 for the action.  Recall the scanner for C comments:
3035 .nf
3036
3037     %x comment
3038     %%
3039             int line_num = 1;
3040
3041     "/*"         BEGIN(comment);
3042
3043     <comment>[^*\\n]*
3044     <comment>"*"+[^*/\\n]*
3045     <comment>\\n             ++line_num;
3046     <comment>"*"+"/"        BEGIN(INITIAL);
3047
3048 .fi
3049 This could be sped up by writing it as:
3050 .nf
3051
3052     %x comment
3053     %%
3054             int line_num = 1;
3055
3056     "/*"         BEGIN(comment);
3057
3058     <comment>[^*\\n]*
3059     <comment>[^*\\n]*\\n      ++line_num;
3060     <comment>"*"+[^*/\\n]*
3061     <comment>"*"+[^*/\\n]*\\n ++line_num;
3062     <comment>"*"+"/"        BEGIN(INITIAL);
3063
3064 .fi
3065 Now instead of each newline requiring the processing of another
3066 action, recognizing the newlines is "distributed" over the other rules
3067 to keep the matched text as long as possible.  Note that
3068 .I adding
3069 rules does
3070 .I not
3071 slow down the scanner!  The speed of the scanner is independent
3072 of the number of rules or (modulo the considerations given at the
3073 beginning of this section) how complicated the rules are with
3074 regard to operators such as '*' and '|'.
3075 .PP
3076 A final example in speeding up a scanner: suppose you want to scan
3077 through a file containing identifiers and keywords, one per line
3078 and with no other extraneous characters, and recognize all the
3079 keywords.  A natural first approach is:
3080 .nf
3081
3082     %%
3083     asm      |
3084     auto     |
3085     break    |
3086     ... etc ...
3087     volatile |
3088     while    /* it's a keyword */
3089
3090     .|\\n     /* it's not a keyword */
3091
3092 .fi
3093 To eliminate the back-tracking, introduce a catch-all rule:
3094 .nf
3095
3096     %%
3097     asm      |
3098     auto     |
3099     break    |
3100     ... etc ...
3101     volatile |
3102     while    /* it's a keyword */
3103
3104     [a-z]+   |
3105     .|\\n     /* it's not a keyword */
3106
3107 .fi
3108 Now, if it's guaranteed that there's exactly one word per line,
3109 then we can reduce the total number of matches by a half by
3110 merging in the recognition of newlines with that of the other
3111 tokens:
3112 .nf
3113
3114     %%
3115     asm\\n    |
3116     auto\\n   |
3117     break\\n  |
3118     ... etc ...
3119     volatile\\n |
3120     while\\n  /* it's a keyword */
3121
3122     [a-z]+\\n |
3123     .|\\n     /* it's not a keyword */
3124
3125 .fi
3126 One has to be careful here, as we have now reintroduced backing up
3127 into the scanner.  In particular, while
3128 .I we
3129 know that there will never be any characters in the input stream
3130 other than letters or newlines,
3131 .I flex
3132 can't figure this out, and it will plan for possibly needing to back up
3133 when it has scanned a token like "auto" and then the next character
3134 is something other than a newline or a letter.  Previously it would
3135 then just match the "auto" rule and be done, but now it has no "auto"
3136 rule, only an "auto\\n" rule.  To eliminate the possibility of backing up,
3137 we could either duplicate all rules but without final newlines, or,
3138 since we never expect to encounter such an input and therefore don't
3139 how it's classified, we can introduce one more catch-all rule, this
3140 one which doesn't include a newline:
3141 .nf
3142
3143     %%
3144     asm\\n    |
3145     auto\\n   |
3146     break\\n  |
3147     ... etc ...
3148     volatile\\n |
3149     while\\n  /* it's a keyword */
3150
3151     [a-z]+\\n |
3152     [a-z]+   |
3153     .|\\n     /* it's not a keyword */
3154
3155 .fi
3156 Compiled with
3157 .B \-Cf,
3158 this is about as fast as one can get a
3159 .I flex
3160 scanner to go for this particular problem.
3161 .PP
3162 A final note:
3163 .I flex
3164 is slow when matching NUL's, particularly when a token contains
3165 multiple NUL's.
3166 It's best to write rules which match
3167 .I short
3168 amounts of text if it's anticipated that the text will often include NUL's.
3169 .PP
3170 Another final note regarding performance: as mentioned above in the section
3171 How the Input is Matched, dynamically resizing
3172 .B yytext
3173 to accommodate huge tokens is a slow process because it presently requires that
3174 the (huge) token be rescanned from the beginning.  Thus if performance is
3175 vital, you should attempt to match "large" quantities of text but not
3176 "huge" quantities, where the cutoff between the two is at about 8K
3177 characters/token.
3178 .SH GENERATING C++ SCANNERS
3179 .I flex
3180 provides two different ways to generate scanners for use with C++.  The
3181 first way is to simply compile a scanner generated by
3182 .I flex
3183 using a C++ compiler instead of a C compiler.  You should not encounter
3184 any compilations errors (please report any you find to the email address
3185 given in the Author section below).  You can then use C++ code in your
3186 rule actions instead of C code.  Note that the default input source for
3187 your scanner remains
3188 .I yyin,
3189 and default echoing is still done to
3190 .I yyout.
3191 Both of these remain
3192 .I FILE *
3193 variables and not C++
3194 .I streams.
3195 .PP
3196 You can also use
3197 .I flex
3198 to generate a C++ scanner class, using the
3199 .B \-+
3200 option (or, equivalently,
3201 .B %option c++),
3202 which is automatically specified if the name of the flex
3203 executable ends in a '+', such as
3204 .I flex++.
3205 When using this option, flex defaults to generating the scanner to the file
3206 .B lex.yy.cc
3207 instead of
3208 .B lex.yy.c.
3209 The generated scanner includes the header file
3210 .I FlexLexer.h,
3211 which defines the interface to two C++ classes.
3212 .PP
3213 The first class,
3214 .B FlexLexer,
3215 provides an abstract base class defining the general scanner class
3216 interface.  It provides the following member functions:
3217 .TP
3218 .B const char* YYText()
3219 returns the text of the most recently matched token, the equivalent of
3220 .B yytext.
3221 .TP
3222 .B int YYLeng()
3223 returns the length of the most recently matched token, the equivalent of
3224 .B yyleng.
3225 .TP
3226 .B int lineno() const
3227 returns the current input line number
3228 (see
3229 .B %option yylineno),
3230 or
3231 .B 1
3232 if
3233 .B %option yylineno
3234 was not used.
3235 .TP
3236 .B void set_debug( int flag )
3237 sets the debugging flag for the scanner, equivalent to assigning to
3238 .B yy_flex_debug
3239 (see the Options section above).  Note that you must build the scanner
3240 using
3241 .B %option debug
3242 to include debugging information in it.
3243 .TP
3244 .B int debug() const
3245 returns the current setting of the debugging flag.
3246 .PP
3247 Also provided are member functions equivalent to
3248 .B yy_switch_to_buffer(),
3249 .B yy_create_buffer()
3250 (though the first argument is an
3251 .B istream*
3252 object pointer and not a
3253 .B FILE*),
3254 .B yy_flush_buffer(),
3255 .B yy_delete_buffer(),
3256 and
3257 .B yyrestart()
3258 (again, the first argument is a
3259 .B istream*
3260 object pointer).
3261 .PP
3262 The second class defined in
3263 .I FlexLexer.h
3264 is
3265 .B yyFlexLexer,
3266 which is derived from
3267 .B FlexLexer.
3268 It defines the following additional member functions:
3269 .TP
3270 .B
3271 yyFlexLexer( istream* arg_yyin = 0, ostream* arg_yyout = 0 )
3272 constructs a
3273 .B yyFlexLexer
3274 object using the given streams for input and output.  If not specified,
3275 the streams default to
3276 .B cin
3277 and
3278 .B cout,
3279 respectively.
3280 .TP
3281 .B virtual int yylex()
3282 performs the same role is
3283 .B yylex()
3284 does for ordinary flex scanners: it scans the input stream, consuming
3285 tokens, until a rule's action returns a value.  If you derive a subclass
3286 .B S
3287 from
3288 .B yyFlexLexer
3289 and want to access the member functions and variables of
3290 .B S
3291 inside
3292 .B yylex(),
3293 then you need to use
3294 .B %option yyclass="S"
3295 to inform
3296 .I flex
3297 that you will be using that subclass instead of
3298 .B yyFlexLexer.
3299 In this case, rather than generating
3300 .B yyFlexLexer::yylex(),
3301 .I flex
3302 generates
3303 .B S::yylex()
3304 (and also generates a dummy
3305 .B yyFlexLexer::yylex()
3306 that calls
3307 .B yyFlexLexer::LexerError()
3308 if called).
3309 .TP
3310 .B
3311 virtual void switch_streams(istream* new_in = 0,
3312 .B
3313 ostream* new_out = 0)
3314 reassigns
3315 .B yyin
3316 to
3317 .B new_in
3318 (if non-nil)
3319 and
3320 .B yyout
3321 to
3322 .B new_out
3323 (ditto), deleting the previous input buffer if
3324 .B yyin
3325 is reassigned.
3326 .TP
3327 .B
3328 int yylex( istream* new_in, ostream* new_out = 0 )
3329 first switches the input streams via
3330 .B switch_streams( new_in, new_out )
3331 and then returns the value of
3332 .B yylex().
3333 .PP
3334 In addition,
3335 .B yyFlexLexer
3336 defines the following protected virtual functions which you can redefine
3337 in derived classes to tailor the scanner:
3338 .TP
3339 .B
3340 virtual int LexerInput( char* buf, int max_size )
3341 reads up to
3342 .B max_size
3343 characters into
3344 .B buf
3345 and returns the number of characters read.  To indicate end-of-input,
3346 return 0 characters.  Note that "interactive" scanners (see the
3347 .B \-B
3348 and
3349 .B \-I
3350 flags) define the macro
3351 .B YY_INTERACTIVE.
3352 If you redefine
3353 .B LexerInput()
3354 and need to take different actions depending on whether or not
3355 the scanner might be scanning an interactive input source, you can
3356 test for the presence of this name via
3357 .B #ifdef.
3358 .TP
3359 .B
3360 virtual void LexerOutput( const char* buf, int size )
3361 writes out
3362 .B size
3363 characters from the buffer
3364 .B buf,
3365 which, while NUL-terminated, may also contain "internal" NUL's if
3366 the scanner's rules can match text with NUL's in them.
3367 .TP
3368 .B
3369 virtual void LexerError( const char* msg )
3370 reports a fatal error message.  The default version of this function
3371 writes the message to the stream
3372 .B cerr
3373 and exits.
3374 .PP
3375 Note that a
3376 .B yyFlexLexer
3377 object contains its
3378 .I entire
3379 scanning state.  Thus you can use such objects to create reentrant
3380 scanners.  You can instantiate multiple instances of the same
3381 .B yyFlexLexer
3382 class, and you can also combine multiple C++ scanner classes together
3383 in the same program using the
3384 .B \-P
3385 option discussed above.
3386 .PP
3387 Finally, note that the
3388 .B %array
3389 feature is not available to C++ scanner classes; you must use
3390 .B %pointer
3391 (the default).
3392 .PP
3393 Here is an example of a simple C++ scanner:
3394 .nf
3395
3396         // An example of using the flex C++ scanner class.
3397
3398     %{
3399     int mylineno = 0;
3400     %}
3401
3402     string  \\"[^\\n"]+\\"
3403
3404     ws      [ \\t]+
3405
3406     alpha   [A-Za-z]
3407     dig     [0-9]
3408     name    ({alpha}|{dig}|\\$)({alpha}|{dig}|[_.\\-/$])*
3409     num1    [-+]?{dig}+\\.?([eE][-+]?{dig}+)?
3410     num2    [-+]?{dig}*\\.{dig}+([eE][-+]?{dig}+)?
3411     number  {num1}|{num2}
3412
3413     %%
3414
3415     {ws}    /* skip blanks and tabs */
3416
3417     "/*"    {
3418             int c;
3419
3420             while((c = yyinput()) != 0)
3421                 {
3422                 if(c == '\\n')
3423                     ++mylineno;
3424
3425                 else if(c == '*')
3426                     {
3427                     if((c = yyinput()) == '/')
3428                         break;
3429                     else
3430                         unput(c);
3431                     }
3432                 }
3433             }
3434
3435     {number}  cout << "number " << YYText() << '\\n';
3436
3437     \\n        mylineno++;
3438
3439     {name}    cout << "name " << YYText() << '\\n';
3440
3441     {string}  cout << "string " << YYText() << '\\n';
3442
3443     %%
3444
3445     int main( int /* argc */, char** /* argv */ )
3446         {
3447         FlexLexer* lexer = new yyFlexLexer;
3448         while(lexer->yylex() != 0)
3449             ;
3450         return 0;
3451         }
3452 .fi
3453 If you want to create multiple (different) lexer classes, you use the
3454 .B \-P
3455 flag (or the
3456 .B prefix=
3457 option) to rename each
3458 .B yyFlexLexer
3459 to some other
3460 .B xxFlexLexer.
3461 You then can include
3462 .B <FlexLexer.h>
3463 in your other sources once per lexer class, first renaming
3464 .B yyFlexLexer
3465 as follows:
3466 .nf
3467
3468     #undef yyFlexLexer
3469     #define yyFlexLexer xxFlexLexer
3470     #include <FlexLexer.h>
3471
3472     #undef yyFlexLexer
3473     #define yyFlexLexer zzFlexLexer
3474     #include <FlexLexer.h>
3475
3476 .fi
3477 if, for example, you used
3478 .B %option prefix="xx"
3479 for one of your scanners and
3480 .B %option prefix="zz"
3481 for the other.
3482 .PP
3483 IMPORTANT: the present form of the scanning class is
3484 .I experimental
3485 and may change considerably between major releases.
3486 .SH INCOMPATIBILITIES WITH LEX AND POSIX
3487 .I flex
3488 is a rewrite of the AT&T Unix
3489 .I lex
3490 tool (the two implementations do not share any code, though),
3491 with some extensions and incompatibilities, both of which
3492 are of concern to those who wish to write scanners acceptable
3493 to either implementation.  Flex is fully compliant with the POSIX
3494 .I lex
3495 specification, except that when using
3496 .B %pointer
3497 (the default), a call to
3498 .B unput()
3499 destroys the contents of
3500 .B yytext,
3501 which is counter to the POSIX specification.
3502 .PP
3503 In this section we discuss all of the known areas of incompatibility
3504 between flex, AT&T lex, and the POSIX specification.
3505 .PP
3506 .I flex's
3507 .B \-l
3508 option turns on maximum compatibility with the original AT&T
3509 .I lex
3510 implementation, at the cost of a major loss in the generated scanner's
3511 performance.  We note below which incompatibilities can be overcome
3512 using the
3513 .B \-l
3514 option.
3515 .PP
3516 .I flex
3517 is fully compatible with
3518 .I lex
3519 with the following exceptions:
3520 .IP -
3521 The undocumented
3522 .I lex
3523 scanner internal variable
3524 .B yylineno
3525 is not supported unless
3526 .B \-l
3527 or
3528 .B %option yylineno
3529 is used.
3530 .IP
3531 .B yylineno
3532 should be maintained on a per-buffer basis, rather than a per-scanner
3533 (single global variable) basis.
3534 .IP
3535 .B yylineno
3536 is not part of the POSIX specification.
3537 .IP -
3538 The
3539 .B input()
3540 routine is not redefinable, though it may be called to read characters
3541 following whatever has been matched by a rule.  If
3542 .B input()
3543 encounters an end-of-file the normal
3544 .B yywrap()
3545 processing is done.  A ``real'' end-of-file is returned by
3546 .B input()
3547 as
3548 .I EOF.
3549 .IP
3550 Input is instead controlled by defining the
3551 .B YY_INPUT
3552 macro.
3553 .IP
3554 The
3555 .I flex
3556 restriction that
3557 .B input()
3558 cannot be redefined is in accordance with the POSIX specification,
3559 which simply does not specify any way of controlling the
3560 scanner's input other than by making an initial assignment to
3561 .I yyin.
3562 .IP -
3563 The
3564 .B unput()
3565 routine is not redefinable.  This restriction is in accordance with POSIX.
3566 .IP -
3567 .I flex
3568 scanners are not as reentrant as
3569 .I lex
3570 scanners.  In particular, if you have an interactive scanner and
3571 an interrupt handler which long-jumps out of the scanner, and
3572 the scanner is subsequently called again, you may get the following
3573 message:
3574 .nf
3575
3576     fatal flex scanner internal error--end of buffer missed
3577
3578 .fi
3579 To reenter the scanner, first use
3580 .nf
3581
3582     yyrestart( yyin );
3583
3584 .fi
3585 Note that this call will throw away any buffered input; usually this
3586 isn't a problem with an interactive scanner.
3587 .IP
3588 Also note that flex C++ scanner classes
3589 .I are
3590 reentrant, so if using C++ is an option for you, you should use
3591 them instead.  See "Generating C++ Scanners" above for details.
3592 .IP -
3593 .B output()
3594 is not supported.
3595 Output from the
3596 .B ECHO
3597 macro is done to the file-pointer
3598 .I yyout
3599 (default
3600 .I stdout).
3601 .IP
3602 .B output()
3603 is not part of the POSIX specification.
3604 .IP -
3605 .I lex
3606 does not support exclusive start conditions (%x), though they
3607 are in the POSIX specification.
3608 .IP -
3609 When definitions are expanded,
3610 .I flex
3611 encloses them in parentheses.
3612 With lex, the following:
3613 .nf
3614
3615     NAME    [A-Z][A-Z0-9]*
3616     %%
3617     foo{NAME}?      printf( "Found it\\n" );
3618     %%
3619
3620 .fi
3621 will not match the string "foo" because when the macro
3622 is expanded the rule is equivalent to "foo[A-Z][A-Z0-9]*?"
3623 and the precedence is such that the '?' is associated with
3624 "[A-Z0-9]*".  With
3625 .I flex,
3626 the rule will be expanded to
3627 "foo([A-Z][A-Z0-9]*)?" and so the string "foo" will match.
3628 .IP
3629 Note that if the definition begins with
3630 .B ^
3631 or ends with
3632 .B $
3633 then it is
3634 .I not
3635 expanded with parentheses, to allow these operators to appear in
3636 definitions without losing their special meanings.  But the
3637 .B <s>, /,
3638 and
3639 .B <<EOF>>
3640 operators cannot be used in a
3641 .I flex
3642 definition.
3643 .IP
3644 Using
3645 .B \-l
3646 results in the
3647 .I lex
3648 behavior of no parentheses around the definition.
3649 .IP
3650 The POSIX specification is that the definition be enclosed in parentheses.
3651 .IP -
3652 Some implementations of
3653 .I lex
3654 allow a rule's action to begin on a separate line, if the rule's pattern
3655 has trailing whitespace:
3656 .nf
3657
3658     %%
3659     foo|bar<space here>
3660       { foobar_action(); }
3661
3662 .fi
3663 .I flex
3664 does not support this feature.
3665 .IP -
3666 The
3667 .I lex
3668 .B %r
3669 (generate a Ratfor scanner) option is not supported.  It is not part
3670 of the POSIX specification.
3671 .IP -
3672 After a call to
3673 .B unput(),
3674 .I yytext
3675 is undefined until the next token is matched, unless the scanner
3676 was built using
3677 .B %array.
3678 This is not the case with
3679 .I lex
3680 or the POSIX specification.  The
3681 .B \-l
3682 option does away with this incompatibility.
3683 .IP -
3684 The precedence of the
3685 .B {}
3686 (numeric range) operator is different.
3687 .I lex
3688 interprets "abc{1,3}" as "match one, two, or
3689 three occurrences of 'abc'", whereas
3690 .I flex
3691 interprets it as "match 'ab'
3692 followed by one, two, or three occurrences of 'c'".  The latter is
3693 in agreement with the POSIX specification.
3694 .IP -
3695 The precedence of the
3696 .B ^
3697 operator is different.
3698 .I lex
3699 interprets "^foo|bar" as "match either 'foo' at the beginning of a line,
3700 or 'bar' anywhere", whereas
3701 .I flex
3702 interprets it as "match either 'foo' or 'bar' if they come at the beginning
3703 of a line".  The latter is in agreement with the POSIX specification.
3704 .IP -
3705 The special table-size declarations such as
3706 .B %a
3707 supported by
3708 .I lex
3709 are not required by
3710 .I flex
3711 scanners;
3712 .I flex
3713 ignores them.
3714 .IP -
3715 The name
3716 .B FLEX_SCANNER
3717 is #define'd so scanners may be written for use with either
3718 .I flex
3719 or
3720 .I lex.
3721 Scanners also include
3722 .B YY_FLEX_MAJOR_VERSION
3723 and
3724 .B YY_FLEX_MINOR_VERSION
3725 indicating which version of
3726 .I flex
3727 generated the scanner
3728 (for example, for the 2.5 release, these defines would be 2 and 5
3729 respectively).
3730 .PP
3731 The following
3732 .I flex
3733 features are not included in
3734 .I lex
3735 or the POSIX specification:
3736 .nf
3737
3738     C++ scanners
3739     %option
3740     start condition scopes
3741     start condition stacks
3742     interactive/non-interactive scanners
3743     yy_scan_string() and friends
3744     yyterminate()
3745     yy_set_interactive()
3746     yy_set_bol()
3747     YY_AT_BOL()
3748     <<EOF>>
3749     <*>
3750     YY_DECL
3751     YY_START
3752     YY_USER_ACTION
3753     YY_USER_INIT
3754     #line directives
3755     %{}'s around actions
3756     multiple actions on a line
3757
3758 .fi
3759 plus almost all of the flex flags.
3760 The last feature in the list refers to the fact that with
3761 .I flex
3762 you can put multiple actions on the same line, separated with
3763 semi-colons, while with
3764 .I lex,
3765 the following
3766 .nf
3767
3768     foo    handle_foo(); ++num_foos_seen;
3769
3770 .fi
3771 is (rather surprisingly) truncated to
3772 .nf
3773
3774     foo    handle_foo();
3775
3776 .fi
3777 .I flex
3778 does not truncate the action.  Actions that are not enclosed in
3779 braces are simply terminated at the end of the line.
3780 .SH DIAGNOSTICS
3781 .I warning, rule cannot be matched
3782 indicates that the given rule
3783 cannot be matched because it follows other rules that will
3784 always match the same text as it.  For
3785 example, in the following "foo" cannot be matched because it comes after
3786 an identifier "catch-all" rule:
3787 .nf
3788
3789     [a-z]+    got_identifier();
3790     foo       got_foo();
3791
3792 .fi
3793 Using
3794 .B REJECT
3795 in a scanner suppresses this warning.
3796 .PP
3797 .I warning,
3798 .B \-s
3799 .I
3800 option given but default rule can be matched
3801 means that it is possible (perhaps only in a particular start condition)
3802 that the default rule (match any single character) is the only one
3803 that will match a particular input.  Since
3804 .B \-s
3805 was given, presumably this is not intended.
3806 .PP
3807 .I reject_used_but_not_detected undefined
3808 or
3809 .I yymore_used_but_not_detected undefined -
3810 These errors can occur at compile time.  They indicate that the
3811 scanner uses
3812 .B REJECT
3813 or
3814 .B yymore()
3815 but that
3816 .I flex
3817 failed to notice the fact, meaning that
3818 .I flex
3819 scanned the first two sections looking for occurrences of these actions
3820 and failed to find any, but somehow you snuck some in (via a #include
3821 file, for example).  Use
3822 .B %option reject
3823 or
3824 .B %option yymore
3825 to indicate to flex that you really do use these features.
3826 .PP
3827 .I flex scanner jammed -
3828 a scanner compiled with
3829 .B \-s
3830 has encountered an input string which wasn't matched by
3831 any of its rules.  This error can also occur due to internal problems.
3832 .PP
3833 .I token too large, exceeds YYLMAX -
3834 your scanner uses
3835 .B %array
3836 and one of its rules matched a string longer than the
3837 .B YYLMAX
3838 constant (8K bytes by default).  You can increase the value by
3839 #define'ing
3840 .B YYLMAX
3841 in the definitions section of your
3842 .I flex
3843 input.
3844 .PP
3845 .I scanner requires \-8 flag to
3846 .I use the character 'x' -
3847 Your scanner specification includes recognizing the 8-bit character
3848 .I 'x'
3849 and you did not specify the \-8 flag, and your scanner defaulted to 7-bit
3850 because you used the
3851 .B \-Cf
3852 or
3853 .B \-CF
3854 table compression options.  See the discussion of the
3855 .B \-7
3856 flag for details.
3857 .PP
3858 .I flex scanner push-back overflow -
3859 you used
3860 .B unput()
3861 to push back so much text that the scanner's buffer could not hold
3862 both the pushed-back text and the current token in
3863 .B yytext.
3864 Ideally the scanner should dynamically resize the buffer in this case, but at
3865 present it does not.
3866 .PP
3867 .I
3868 input buffer overflow, can't enlarge buffer because scanner uses REJECT -
3869 the scanner was working on matching an extremely large token and needed
3870 to expand the input buffer.  This doesn't work with scanners that use
3871 .B
3872 REJECT.
3873 .PP
3874 .I
3875 fatal flex scanner internal error--end of buffer missed -
3876 This can occur in a scanner which is reentered after a long-jump
3877 has jumped out (or over) the scanner's activation frame.  Before
3878 reentering the scanner, use:
3879 .nf
3880
3881     yyrestart( yyin );
3882
3883 .fi
3884 or, as noted above, switch to using the C++ scanner class.
3885 .PP
3886 .I too many start conditions in <> construct! -
3887 you listed more start conditions in a <> construct than exist (so
3888 you must have listed at least one of them twice).
3889 .SH FILES
3890 .TP
3891 .B \-ll
3892 library with which scanners must be linked.
3893 .TP
3894 .I lex.yy.c
3895 generated scanner (called
3896 .I lexyy.c
3897 on some systems).
3898 .TP
3899 .I lex.yy.cc
3900 generated C++ scanner class, when using
3901 .B -+.
3902 .TP
3903 .I <FlexLexer.h>
3904 header file defining the C++ scanner base class,
3905 .B FlexLexer,
3906 and its derived class,
3907 .B yyFlexLexer.
3908 .TP
3909 .I flex.skl
3910 skeleton scanner.  This file is only used when building flex, not when
3911 flex executes.
3912 .TP
3913 .I lex.backup
3914 backing-up information for
3915 .B \-b
3916 flag (called
3917 .I lex.bck
3918 on some systems).
3919 .SH DEFICIENCIES / BUGS
3920 Some trailing context
3921 patterns cannot be properly matched and generate
3922 warning messages ("dangerous trailing context").  These are
3923 patterns where the ending of the
3924 first part of the rule matches the beginning of the second
3925 part, such as "zx*/xy*", where the 'x*' matches the 'x' at
3926 the beginning of the trailing context.  (Note that the POSIX draft
3927 states that the text matched by such patterns is undefined.)
3928 .PP
3929 For some trailing context rules, parts which are actually fixed-length are
3930 not recognized as such, leading to the above mentioned performance loss.
3931 In particular, parts using '|' or {n} (such as "foo{3}") are always
3932 considered variable-length.
3933 .PP
3934 Combining trailing context with the special '|' action can result in
3935 .I fixed
3936 trailing context being turned into the more expensive
3937 .I variable
3938 trailing context.  For example, in the following:
3939 .nf
3940
3941     %%
3942     abc      |
3943     xyz/def
3944
3945 .fi
3946 .PP
3947 Use of
3948 .B unput()
3949 invalidates yytext and yyleng, unless the
3950 .B %array
3951 directive
3952 or the
3953 .B \-l
3954 option has been used.
3955 .PP
3956 Pattern-matching of NUL's is substantially slower than matching other
3957 characters.
3958 .PP
3959 Dynamic resizing of the input buffer is slow, as it entails rescanning
3960 all the text matched so far by the current (generally huge) token.
3961 .PP
3962 Due to both buffering of input and read-ahead, you cannot intermix
3963 calls to <stdio.h> routines, such as, for example,
3964 .B getchar(),
3965 with
3966 .I flex
3967 rules and expect it to work.  Call
3968 .B input()
3969 instead.
3970 .PP
3971 The total table entries listed by the
3972 .B \-v
3973 flag excludes the number of table entries needed to determine
3974 what rule has been matched.  The number of entries is equal
3975 to the number of DFA states if the scanner does not use
3976 .B REJECT,
3977 and somewhat greater than the number of states if it does.
3978 .PP
3979 .B REJECT
3980 cannot be used with the
3981 .B \-f
3982 or
3983 .B \-F
3984 options.
3985 .PP
3986 The
3987 .I flex
3988 internal algorithms need documentation.
3989 .SH SEE ALSO
3990 lex(1), yacc(1), sed(1), awk(1).
3991 .PP
3992 John Levine, Tony Mason, and Doug Brown,
3993 .I Lex & Yacc,
3994 O'Reilly and Associates.  Be sure to get the 2nd edition.
3995 .PP
3996 M. E. Lesk and E. Schmidt,
3997 .I LEX \- Lexical Analyzer Generator
3998 .PP
3999 Alfred Aho, Ravi Sethi and Jeffrey Ullman,
4000 .I Compilers: Principles, Techniques and Tools,
4001 Addison-Wesley (1986).  Describes the pattern-matching techniques used by
4002 .I flex
4003 (deterministic finite automata).
4004 .SH AUTHOR
4005 Vern Paxson, with the help of many ideas and much inspiration from
4006 Van Jacobson.  Original version by Jef Poskanzer.  The fast table
4007 representation is a partial implementation of a design done by Van
4008 Jacobson.  The implementation was done by Kevin Gong and Vern Paxson.
4009 .PP
4010 Thanks to the many
4011 .I flex
4012 beta-testers, feedbackers, and contributors, especially Francois Pinard,
4013 Casey Leedom,
4014 Robert Abramovitz,
4015 Stan Adermann, Terry Allen, David Barker-Plummer, John Basrai,
4016 Neal Becker, Nelson H.F. Beebe, benson@odi.com,
4017 Karl Berry, Peter A. Bigot, Simon Blanchard,
4018 Keith Bostic, Frederic Brehm, Ian Brockbank, Kin Cho, Nick Christopher,
4019 Brian Clapper, J.T. Conklin,
4020 Jason Coughlin, Bill Cox, Nick Cropper, Dave Curtis, Scott David
4021 Daniels, Chris G. Demetriou, Theo Deraadt,
4022 Mike Donahue, Chuck Doucette, Tom Epperly, Leo Eskin,
4023 Chris Faylor, Chris Flatters, Jon Forrest, Jeffrey Friedl,
4024 Joe Gayda, Kaveh R. Ghazi, Wolfgang Glunz,
4025 Eric Goldman, Christopher M. Gould, Ulrich Grepel, Peer Griebel,
4026 Jan Hajic, Charles Hemphill, NORO Hideo,
4027 Jarkko Hietaniemi, Scott Hofmann,
4028 Jeff Honig, Dana Hudes, Eric Hughes, John Interrante,
4029 Ceriel Jacobs, Michal Jaegermann, Sakari Jalovaara, Jeffrey R. Jones,
4030 Henry Juengst, Klaus Kaempf, Jonathan I. Kamens, Terrence O Kane,
4031 Amir Katz, ken@ken.hilco.com, Kevin B. Kenny,
4032 Steve Kirsch, Winfried Koenig, Marq Kole, Ronald Lamprecht,
4033 Greg Lee, Rohan Lenard, Craig Leres, John Levine, Steve Liddle,
4034 David Loffredo, Mike Long,
4035 Mohamed el Lozy, Brian Madsen, Malte, Joe Marshall,
4036 Bengt Martensson, Chris Metcalf,
4037 Luke Mewburn, Jim Meyering, R. Alexander Milowski, Erik Naggum,
4038 G.T. Nicol, Landon Noll, James Nordby, Marc Nozell,
4039 Richard Ohnemus, Karsten Pahnke,
4040 Sven Panne, Roland Pesch, Walter Pelissero, Gaumond
4041 Pierre, Esmond Pitt, Jef Poskanzer, Joe Rahmeh, Jarmo Raiha,
4042 Frederic Raimbault, Pat Rankin, Rick Richardson,
4043 Kevin Rodgers, Kai Uwe Rommel, Jim Roskind, Alberto Santini,
4044 Andreas Scherer, Darrell Schiebel, Raf Schietekat,
4045 Doug Schmidt, Philippe Schnoebelen, Andreas Schwab,
4046 Larry Schwimmer, Alex Siegel, Eckehard Stolz, Jan-Erik Strvmquist,
4047 Mike Stump, Paul Stuart, Dave Tallman, Ian Lance Taylor,
4048 Chris Thewalt, Richard M. Timoney, Jodi Tsai,
4049 Paul Tuinenga, Gary Weik, Frank Whaley, Gerhard Wilhelms, Kent Williams, Ken
4050 Yap, Ron Zellar, Nathan Zelle, David Zuhn,
4051 and those whose names have slipped my marginal
4052 mail-archiving skills but whose contributions are appreciated all the
4053 same.
4054 .PP
4055 Thanks to Keith Bostic, Jon Forrest, Noah Friedman,
4056 John Gilmore, Craig Leres, John Levine, Bob Mulcahy, G.T.
4057 Nicol, Francois Pinard, Rich Salz, and Richard Stallman for help with various
4058 distribution headaches.
4059 .PP
4060 Thanks to Esmond Pitt and Earle Horton for 8-bit character support; to
4061 Benson Margulies and Fred Burke for C++ support; to Kent Williams and Tom
4062 Epperly for C++ class support; to Ove Ewerlid for support of NUL's; and to
4063 Eric Hughes for support of multiple buffers.
4064 .PP
4065 This work was primarily done when I was with the Real Time Systems Group
4066 at the Lawrence Berkeley Laboratory in Berkeley, CA.  Many thanks to all there
4067 for the support I received.
4068 .PP
4069 Send comments to vern@ee.lbl.gov.