Index: ossp-adm/autotools/bison.html RCS File: /v/ossp/cvs/ossp-adm/autotools/bison.html,v rcsdiff -q -kk '-r1.1' '-r1.2' -u '/v/ossp/cvs/ossp-adm/autotools/bison.html,v' 2>/dev/null --- bison.html 2002/07/10 08:46:24 1.1 +++ bison.html 2002/11/09 14:28:38 1.2 @@ -1,13 +1,13 @@
- + -
@@ -47,7 +47,7 @@
-This edition corresponds to version 1.30 of Bison. +This edition corresponds to version 1.75 of Bison. @@ -56,9 +56,9 @@
As of Bison version 1.24, we have changed the distribution terms for
-yyparse
to permit using Bison's output in nonfree programs.
-Formerly, Bison parsers could be used only in programs that were free
-software.
+yyparse
to permit using Bison's output in nonfree programs when
+Bison is generating C code for LALR(1) parsers. Formerly, these
+parsers could be used only in programs that were free software.
@@ -87,6 +87,15 @@ using the other GNU tools. +
+This exception applies only when Bison is generating C code for a +LALR(1) parser; otherwise, the GPL terms operate as usual. You can +tell whether the exception applies to your `.c' output file by +inspecting it to see whether it says "As a special exception, when +this file is copied by Bison into a Bison output file, you may use +that output file without restriction." + +
-Not all context-free languages can be handled by Bison, only those -that are LALR(1). In brief, this means that it must be possible to + + +There are various important subclasses of context-free grammar. Although it +can handle almost all context-free grammars, Bison is optimized for what +are called LALR(1) grammars. +In brief, in these grammars, it must be possible to tell how to parse any portion of an input string with just a single token of look-ahead. Strictly speaking, that is a description of an LR(1) grammar, and LALR(1) involves additional restrictions that are hard to explain simply; but it is rare in actual practice to find an -LR(1) grammar that fails to be LALR(1). See section Mysterious Reduce/Reduce Conflicts, for more information on this. +LR(1) grammar that fails to be LALR(1). See section Mysterious Reduce/Reduce Conflicts, for more information on this.
- - + + +Parsers for LALR(1) grammars are deterministic, meaning roughly that +the next grammar rule to apply at any point in the input is uniquely +determined by the preceding input and a fixed, finite portion (called +a look-ahead) of the remaining input. +A context-free grammar can be ambiguous, meaning that +there are multiple ways to apply the grammar rules to get the some inputs. +Even unambiguous grammars can be non-deterministic, meaning that no +fixed look-ahead always suffices to determine the next grammar rule to apply. +With the proper declarations, Bison is also able to parse these more general +context-free grammars, using a technique known as GLR parsing (for +Generalized LR). Bison's GLR parsers are able to handle any context-free +grammar for which the number of possible parses of any given string +is finite. + + +
+ + + + In the formal grammatical rules for a language, each kind of syntactic unit or grouping is named by a symbol. Those which are built by grouping smaller constructs according to grammatical rules are called @@ -591,6 +624,7 @@ corresponding to a single terminal symbol a token, and a piece corresponding to a single nonterminal symbol a grouping. +
We can use the C language as an example of what symbols, terminal and nonterminal, mean. The tokens of C are identifiers, constants (numeric and @@ -607,15 +641,14 @@ Here is a simple C function subdivided into tokens: +
+@ifnotinfo
int /* keyword `int' */ -square (x) /* identifier, open-paren, */ - /* identifier, close-paren */ - int x; /* keyword `int', identifier, semicolon */ +square (int x) /* identifier, open-paren, identifier, identifier, close-paren */ { /* open-brace */ - return x * x; /* keyword `return', identifier, */ - /* asterisk, identifier, semicolon */ + return x * x; /* keyword `return', identifier, asterisk, identifier, semicolon */ } /* close-brace */@@ -650,7 +683,7 @@
- + One nonterminal symbol must be distinguished as the special one which defines a complete utterance in the language. It is called the start symbol. In a compiler, this means a complete input program. In the C @@ -678,15 +711,15 @@
A formal grammar is a mathematical construct. To define the language for Bison, you must write a file expressing the grammar in Bison syntax: -a Bison grammar file. See section Bison Grammar Files. +a Bison grammar file. See section Bison Grammar Files.
@@ -703,7 +736,7 @@
RETURN
. A terminal symbol that stands for a particular keyword in
the language should be named after that keyword converted to upper case.
The terminal symbol error
is reserved for error recovery.
-See section Symbols, Terminal and Nonterminal.
+See section Symbols, Terminal and Nonterminal.
@@ -715,7 +748,7 @@
A third way to represent a terminal symbol is with a C string constant -containing several characters. See section Symbols, Terminal and Nonterminal, for more information. +containing several characters. See section Symbols, Terminal and Nonterminal, for more information.
@@ -733,15 +766,15 @@
-See section Syntax of Grammar Rules. +See section Syntax of Grammar Rules.
@@ -752,11 +785,12 @@ `x+4' is grammatical then `x+1' or `x+3989' is equally grammatical. +
But the precise value is very important for what the input means once it is parsed. A compiler is useless if it fails to distinguish between 4, 1 and 3989 as constants in the program! Therefore, each token in a Bison grammar -has both a token type and a semantic value. See section Defining Language Semantics, +has both a token type and a semantic value. See section Defining Language Semantics, for details. @@ -767,6 +801,7 @@ group it with other tokens. The grammar rules know nothing about tokens except their types. +
The semantic value has all the rest of the information about the meaning of the token, such as the value of an integer, or the name of an @@ -795,8 +830,8 @@
@@ -804,7 +839,7 @@ also produce some output based on the input. In a Bison grammar, a grammar rule can have an action made up of C statements. Each time the parser recognizes a match for that rule, the action is executed. -See section Actions. +See section Actions.
@@ -835,52 +870,257 @@ -
+In some grammars, there will be cases where Bison's standard LALR(1) +parsing algorithm cannot decide whether to apply a certain grammar rule +at a given point. That is, it may not be able to decide (on the basis +of the input read so far) which of two possible reductions (applications +of a grammar rule) applies, or whether to apply a reduction or read more +of the input and apply a reduction later in the input. These are known +respectively as reduce/reduce conflicts (see section Reduce/Reduce Conflicts), +and shift/reduce conflicts (see section Shift/Reduce Conflicts). + + +
+To use a grammar that is not easily modified to be LALR(1), a more
+general parsing algorithm is sometimes necessary. If you include
+%glr-parser
among the Bison declarations in your file
+(see section Outline of a Bison Grammar), the result will be a Generalized LR (GLR)
+parser. These parsers handle Bison grammars that contain no unresolved
+conflicts (i.e., after applying precedence declarations) identically to
+LALR(1) parsers. However, when faced with unresolved shift/reduce and
+reduce/reduce conflicts, GLR parsers use the simple expedient of doing
+both, effectively cloning the parser to follow both possibilities. Each
+of the resulting parsers can again split, so that at any given time,
+there can be any number of possible parses being explored. The parsers
+proceed in lockstep; that is, all of them consume (shift) a given input
+symbol before any of them proceed to the next. Each of the cloned
+parsers eventually meets one of two possible fates: either it runs into
+a parsing error, in which case it simply vanishes, or it merges with
+another parser, because the two of them have reduced the input to an
+identical set of symbols.
+
+
+
+During the time that there are multiple parsers, semantic actions are +recorded, but not performed. When a parser disappears, its recorded +semantic actions disappear as well, and are never performed. When a +reduction makes two parsers identical, causing them to merge, Bison +records both sets of semantic actions. Whenever the last two parsers +merge, reverting to the single-parser case, Bison resolves all the +outstanding actions either by precedences given to the grammar rules +involved, or by performing both actions, and then calling a designated +user-defined function on the resulting values to produce an arbitrary +merged result. + + +
+Let's consider an example, vastly simplified from C++. + + + +
+%{ + #define YYSTYPE const char* +%} + +%token TYPENAME ID + +%right '=' +%left '+' + +%glr-parser + +%% + +prog : + | prog stmt { printf ("\n"); } + ; + +stmt : expr ';' %dprec 1 + | decl %dprec 2 + ; + +expr : ID { printf ("%s ", $$); } + | TYPENAME '(' expr ')' + { printf ("%s <cast> ", $1); } + | expr '+' expr { printf ("+ "); } + | expr '=' expr { printf ("= "); } + ; + +decl : TYPENAME declarator ';' + { printf ("%s <declare> ", $1); } + | TYPENAME declarator '=' expr ';' + { printf ("%s <init-declare> ", $1); } + ; + +declarator : ID { printf ("\"%s\" ", $1); } + | '(' declarator ')' + ; ++ +
+This models a problematic part of the C++ grammar--the ambiguity between +certain declarations and statements. For example, + + + +
+T (x) = y+z; ++ +
+parses as either an expr
or a stmt
+(assuming that `T' is recognized as a TYPENAME and `x' as an ID).
+Bison detects this as a reduce/reduce conflict between the rules
+expr : ID
and declarator : ID
, which it cannot resolve at the
+time it encounters x
in the example above. The two %dprec
+declarations, however, give precedence to interpreting the example as a
+decl
, which implies that x
is a declarator.
+The parser therefore prints
+
+
+
+
+"x" y z + T <init-declare> ++ +
+Consider a different input string for this parser: + + + +
+T (x) + y; ++ +
+Here, there is no ambiguity (this cannot be parsed as a declaration).
+However, at the time the Bison parser encounters x
, it does not
+have enough information to resolve the reduce/reduce conflict (again,
+between x
as an expr
or a declarator
). In this
+case, no precedence declaration is used. Instead, the parser splits
+into two, one assuming that x
is an expr
, and the other
+assuming x
is a declarator
. The second of these parsers
+then vanishes when it sees +
, and the parser prints
+
+
+
+
+x T <cast> y + ++ +
+Suppose that instead of resolving the ambiguity, you wanted to see all
+the possibilities. For this purpose, we must merge the semantic
+actions of the two possible parsers, rather than choosing one over the
+other. To do so, you could change the declaration of stmt
as
+follows:
+
+
+
+
+stmt : expr ';' %merge <stmtMerge> + | decl %merge <stmtMerge> + ; ++ +
+ + +
+and define the stmtMerge
function as:
+
+
+
+
+static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1) +{ + printf ("<OR> "); + return ""; +} ++ +
+with an accompanying forward declaration +in the C declarations at the beginning of the file: + + + +
+%{ + #define YYSTYPE const char* + static YYSTYPE stmtMerge (YYSTYPE x0, YYSTYPE x1); +%} ++ +
+With these declarations, the resulting parser will parse the first example
+as both an expr
and a decl
, and print
+
+
+
+
+"x" y z + T <init-declare> x T <cast> y z + = <OR> ++ + + +
Many applications, like interpreters or compilers, have to produce verbose -and useful error messages. To achieve this, one must be able to keep track of +and useful error messages. To achieve this, one must be able to keep track of the textual position, or location, of each syntactic construct. Bison provides a mechanism for handling these locations.
-Each token has a semantic value. In a similar fashion, each token has an +Each token has a semantic value. In a similar fashion, each token has an associated location, but the type of locations is the same for all tokens and -groupings. Moreover, the output parser is equipped with a default data -structure for storing locations (see section Tracking Locations, for more details). +groupings. Moreover, the output parser is equipped with a default data +structure for storing locations (see section Tracking Locations, for more details).
Like semantic values, locations can be reached in actions using a dedicated
-set of constructs. In the example above, the location of the whole grouping
+set of constructs. In the example above, the location of the whole grouping
is @$
, while the locations of the subexpressions are @1
and
@3
.
When a rule is matched, a default action is used to compute the semantic value
-of its left hand side (see section Actions). In the same way, another default
-action is used for locations. However, the action for locations is general
+of its left hand side (see section Actions). In the same way, another default
+action is used for locations. However, the action for locations is general
enough for most cases, meaning there is usually no need to describe for each
-rule how @$
should be formed. When building a new location for a given
+rule how @$
should be formed. When building a new location for a given
grouping, the default behavior of the output parser is to take the beginning
of the first symbol, and the end of the last symbol.
-
@@ -900,12 +1140,13 @@
-The tokens come from a function called the lexical analyzer that you
-must supply in some fashion (such as by writing it in C). The Bison parser
-calls the lexical analyzer each time it wants a new token. It doesn't know
-what is "inside" the tokens (though their semantic values may reflect
-this). Typically the lexical analyzer makes the tokens by parsing
-characters of text, but Bison does not depend on this. See section The Lexical Analyzer Function yylex
.
+The tokens come from a function called the lexical analyzer that
+you must supply in some fashion (such as by writing it in C). The Bison
+parser calls the lexical analyzer each time it wants a new token. It
+doesn't know what is "inside" the tokens (though their semantic values
+may reflect this). Typically the lexical analyzer makes the tokens by
+parsing characters of text, but Bison does not depend on this.
+See section The Lexical Analyzer Function yylex
.
@@ -916,12 +1157,12 @@
parser calls to report an error. In addition, a complete C program must
start with a function called main
; you have to provide this, and
arrange for it to call yyparse
or the parser will never run.
-See section Parser C-Language Interface.
+See section Parser C-Language Interface.
Aside from the token type names and the symbols in the actions you
-write, all variable and function names used in the Bison parser file
+write, all symbols defined in the Bison parser file itself
begin with `yy' or `YY'. This includes interface functions
such as the lexical analyzer function yylex
, the error reporting
function yyerror
and the parser function yyparse
itself.
@@ -931,12 +1172,22 @@
this manual.
+
+In some cases the Bison parser file includes system headers, and in
+those cases your code should respect the identifiers reserved by those
+headers. On some non-GNU hosts, <alloca.h>
,
+<stddef.h>
, and <stdlib.h>
are included as needed to
+declare memory allocators and related types. Other system headers may
+be included if you define YYDEBUG
to a nonzero value
+(see section Tracing Your Parser).
+
+
-
@@ -949,16 +1200,16 @@
yylex
). It could also be produced using Lex, but the use
-of Lex is not discussed in this manual.
+Write a lexical analyzer to process input and pass tokens to the parser.
+The lexical analyzer may be written by hand in C (see section The Lexical Analyzer Function yylex
). It could also be produced
+using Lex, but the use of Lex is not discussed in this manual.
@@ -1007,7 +1258,7 @@
%{ -C declarations +Prologue %} Bison declarations @@ -1015,7 +1266,7 @@ %% Grammar rules %% -Additional C code +Epilogue
@@ -1024,8 +1275,8 @@
-The C declarations may define types and variables used in the actions.
-You can also use preprocessor commands to define macros used there, and use
+The prologue may define types and variables used in the actions. You can
+also use preprocessor commands to define macros used there, and use
#include
to include header files that do any of these things.
@@ -1041,18 +1292,18 @@
-The additional C code can contain any C code you want to use. Often the
-definition of the lexical analyzer yylex
goes here, plus subroutines
-called by the actions in the grammar rules. In a simple program, all the
-rest of the program can go here.
+The epilogue can contain any code you want to use. Often the definition of
+the lexical analyzer yylex
goes here, plus subroutines called by the
+actions in the grammar rules. In a simple program, all the rest of the
+program can go here.
-
@@ -1070,12 +1321,12 @@ -
@@ -1092,7 +1343,7 @@ -
rpcalc
rpcalc
Here are the C and Bison declarations for the reverse polish notation @@ -1101,7 +1352,7 @@
-/* Reverse polish notation calculator. */ +/* Reverse polish notation calculator. */ %{ #define YYSTYPE double @@ -1110,21 +1361,22 @@ %token NUM -%% /* Grammar rules and actions follow */ +%% /* Grammar rules and actions follow. */
-The C declarations section (see section The C Declarations Section) contains two +The declarations section (see section The prologue) contains two preprocessor directives.
The #define
directive defines the macro YYSTYPE
, thus
-specifying the C data type for semantic values of both tokens and groupings
-(see section Data Types of Semantic Values). The Bison parser will use whatever type
-YYSTYPE
is defined as; if you don't define it, int
is the
-default. Because we specify double
, each token and each expression
-has an associated value, which is a floating point number.
+specifying the C data type for semantic values of both tokens and
+groupings (see section Data Types of Semantic Values). The
+Bison parser will use whatever type YYSTYPE
is defined as; if you
+don't define it, int
is the default. Because we specify
+double
, each token and each expression has an associated value,
+which is a floating point number.
@@ -1133,9 +1385,9 @@
-The second section, Bison declarations, provides information to Bison about
-the token types (see section The Bison Declarations Section). Each terminal symbol that is
-not a single-character literal must be declared here. (Single-character
+The second section, Bison declarations, provides information to Bison
+about the token types (see section The Bison Declarations Section). Each terminal symbol that is not a
+single-character literal must be declared here. (Single-character
literals normally don't need to be declared.) In this example, all the
arithmetic operators are designated by single-character literals, so the
only terminal symbol that needs to be declared is NUM
, the token
@@ -1144,7 +1396,7 @@
-
rpcalc
rpcalc
Here are the grammar rules for the reverse polish notation calculator. @@ -1185,7 +1437,7 @@
The semantics of the language is determined by the actions taken when a grouping is recognized. The actions are the C code that appears inside -braces. See section Actions. +braces. See section Actions.
@@ -1199,7 +1451,7 @@ -
input
input
Consider the definition of input
:
@@ -1217,7 +1469,7 @@
string, or a complete input followed by an input line". Notice that
"complete input" is defined in terms of itself. This definition is said
to be left recursive since input
appears always as the
-leftmost symbol in the sequence. See section Recursive Rules.
+leftmost symbol in the sequence. See section Recursive Rules.
@@ -1240,12 +1492,12 @@
The parser function yyparse
continues to process input until a
grammatical error is seen or the lexical analyzer says there are no more
-input tokens; we will arrange for the latter to happen at end of file.
+input tokens; we will arrange for the latter to happen at end-of-input.
-
line
line
Now consider the definition of line
:
@@ -1278,7 +1530,7 @@
-
expr
expr
The exp
grouping has several rules, one for each kind of expression.
@@ -1317,7 +1569,7 @@
associated semantic value, but if it had one you could refer to it as
$3
. When yyparse
recognizes a sum expression using this
rule, the sum of the two subexpressions' values is produced as the value of
-the entire expression. See section Actions.
+the entire expression. See section Actions.
@@ -1328,7 +1580,7 @@
The formatting shown here is the recommended convention, but Bison does -not require it. You can add or change whitespace as much as you wish. +not require it. You can add or change white space as much as you wish. For example, this: @@ -1354,16 +1606,16 @@ -
rpcalc
Lexical Analyzerrpcalc
Lexical Analyzer
-The lexical analyzer's job is low-level parsing: converting characters or
-sequences of characters into tokens. The Bison parser gets its tokens by
-calling the lexical analyzer. See section The Lexical Analyzer Function yylex
.
+The lexical analyzer's job is low-level parsing: converting characters
+or sequences of characters into tokens. The Bison parser gets its
+tokens by calling the lexical analyzer. See section The Lexical Analyzer Function yylex
.
@@ -1379,7 +1631,7 @@ represents a token type. The same text used in Bison rules to stand for this token type is also a C expression for the numeric code for the type. This works in two ways. If the token type is a character literal, then its -numeric code is the ASCII code for that character; you can use the same +numeric code is that of the character; you can use the same character literal in the lexical analyzer to express the number. If the token type is an identifier, that identifier is defined by Bison as a C macro whose definition is the appropriate number. In this example, @@ -1387,16 +1639,15 @@
-The semantic value of the token (if it has one) is stored into the global
-variable yylval
, which is where the Bison parser will look for it.
-(The C data type of yylval
is YYSTYPE
, which was defined
-at the beginning of the grammar; see section Declarations for rpcalc
.)
+The semantic value of the token (if it has one) is stored into the
+global variable yylval
, which is where the Bison parser will look
+for it. (The C data type of yylval
is YYSTYPE
, which was
+defined at the beginning of the grammar; see section Declarations for rpcalc
.)
-A token type code of zero is returned if the end-of-file is encountered. -(Bison recognizes any nonpositive value as indicating the end of the -input.) +A token type code of zero is returned if the end-of-input is encountered. +(Bison recognizes any nonpositive value as indicating end-of-input.)
@@ -1405,10 +1656,10 @@
-/* Lexical analyzer returns a double floating point - number on the stack and the token NUM, or the ASCII - character read if not a number. Skips all blanks - and tabs, returns 0 for EOF. */ +/* The lexical analyzer returns a double floating point + number on the stack and the token NUM, or the numeric code + of the character read if not a number. It skips all blanks + and tabs, and returns 0 for end-of-input. */ #include <ctype.h> @@ -1417,30 +1668,30 @@ { int c; - /* skip white space */ + /* Skip white space. */ while ((c = getchar ()) == ' ' || c == '\t') ; - /* process numbers */ + /* Process numbers. */ if (c == '.' || isdigit (c)) { ungetc (c, stdin); scanf ("%lf", &yylval); return NUM; } - /* return end-of-file */ + /* Return end-of-input. */ if (c == EOF) return 0; - /* return single chars */ + /* Return a single char. */ return c; }-
@@ -1460,16 +1711,16 @@ -
When yyparse
detects a syntax error, it calls the error reporting
function yyerror
to print an error message (usually but not
always "parse error"
). It is up to the programmer to supply
-yyerror
(see section Parser C-Language Interface), so
+yyerror
(see section Parser C-Language Interface), so
here is the definition we will use:
@@ -1478,7 +1729,7 @@
#include <stdio.h>
void
-yyerror (const char *s) /* Called by yyparse on error */
+yyerror (const char *s) /* called by yyparse on error */
{
printf ("%s\n", s);
}
@@ -1487,7 +1738,7 @@
After yyerror
returns, the Bison parser may recover from the error
and continue parsing if the grammar contains a suitable error rule
-(see section Error Recovery). Otherwise, yyparse
returns nonzero. We
+(see section Error Recovery). Otherwise, yyparse
returns nonzero. We
have not written any error rules in this example, so any invalid input will
cause the calculator program to exit. This is not clean behavior for a
real calculator, but it is adequate for the first example.
@@ -1495,9 +1746,9 @@
-
@@ -1505,7 +1756,8 @@
arrange all the source code in one or more source files. For such a
simple example, the easiest thing is to put everything in one file. The
definitions of yylex
, yyerror
and main
go at the
-end, in the "additional C code" section of the file (see section The Overall Layout of a Bison Grammar).
+end, in the epilogue of the file
+(see section The Overall Layout of a Bison Grammar).
@@ -1526,7 +1778,7 @@
In this example the file was called `rpcalc.y' (for "Reverse Polish
CALCulator"). Bison produces a file named `file_name.tab.c',
-removing the `.y' from the original file name. The file output by
+removing the `.y' from the original file name. The file output by
Bison contains the source code for yyparse
. The additional
functions in the input file (yylex
, yyerror
and main
)
are copied verbatim to the output.
@@ -1534,9 +1786,9 @@
-
@@ -1546,15 +1798,15 @@
# List files in current directory.
-% ls
+$ ls
rpcalc.tab.c rpcalc.y
# Compile the Bison parser.
# `-lm' tells compiler to search math library for pow
.
-% cc rpcalc.tab.c -lm -o rpcalc
+$ cc -lm -o rpcalc rpcalc.tab.c
# List files again.
-% ls
+$ ls
rpcalc rpcalc.tab.c rpcalc.y
@@ -1565,28 +1817,28 @@
-% rpcalc -4 9 + +$ rpcalc +4 9 + 13 -3 7 + 3 4 5 *+- +3 7 + 3 4 5 *+- -13 -3 7 + 3 4 5 * + - n Note the unary minus, `n' +3 7 + 3 4 5 * + - n Note the unary minus, `n' 13 -5 6 / 4 n + +5 6 / 4 n + -3.166666667 -3 4 ^ Exponentiation +3 4 ^ Exponentiation 81 -^D End-of-file indicator -% +^D End-of-file indicator +$-
calc
calc
@@ -1658,14 +1910,14 @@
declarations; the higher the line number of the declaration (lower on
the page or screen), the higher the precedence. Hence, exponentiation
has the highest precedence, unary minus (NEG
) is next, followed
-by `*' and `/', and so on. See section Operator Precedence.
+by `*' and `/', and so on. See section Operator Precedence.
-The other important new feature is the %prec
in the grammar section
-for the unary minus operator. The %prec
simply instructs Bison that
-the rule `| '-' exp' has the same precedence as NEG
---in this
-case the next-to-highest. See section Context-Dependent Precedence.
+The other important new feature is the %prec
in the grammar
+section for the unary minus operator. The %prec
simply instructs
+Bison that the rule `| '-' exp' has the same precedence as
+NEG
---in this case the next-to-highest. See section Context-Dependent Precedence.
@@ -1674,20 +1926,20 @@
-% calc -4 + 4.5 - (34/(8*3+-3)) +$ calc +4 + 4.5 - (34/(8*3+-3)) 6.880952381 --56 + 2 +-56 + 2 -54 -3 ^ 2 +3 ^ 2 9-
@@ -1720,10 +1972,11 @@
and parsing will continue. (The yyerror
function is still called
upon to print its message as well.) The action executes the statement
yyerrok
, a macro defined automatically by Bison; its meaning is
-that error recovery is complete (see section Error Recovery). Note the
+that error recovery is complete (see section Error Recovery). Note the
difference between yyerrok
and yyerror
; neither one is a
misprint.
+
This form of error recovery deals with syntax errors. There are other kinds of errors; for example, division by zero, which raises an exception @@ -1736,32 +1989,28 @@ -
ltcalc
ltcalc
-This example extends the infix notation calculator with location tracking. -This feature will be used to improve error reporting, and provide better -error messages. + + +
-For the sake of clarity, we will switch for this example to an integer -calculator, since most of the work needed to use locations will be done -in the lexical analyser. +This example extends the infix notation calculator with location +tracking. This feature will be used to improve the error messages. For +the sake of clarity, this example is a simple integer calculator, since +most of the work needed to use locations will be done in the lexical +analyzer. -
ltcalc
ltcalc
-The C and Bison declarations for the location tracking calculator are the same -as the declarations for the infix notation calculator. +The C and Bison declarations for the location tracking calculator are +the same as the declarations for the infix notation calculator. @@ -1785,27 +2034,28 @@
-In the code above, there are no declarations specific to locations. Defining
-a data type for storing locations is not needed: we will use the type provided
-by default (see section Data Type of Locations), which is a four
-member structure with the following integer fields: first_line
,
-first_column
, last_line
and last_column
.
+Note there are no declarations specific to locations. Defining a data
+type for storing locations is not needed: we will use the type provided
+by default (see section Data Type of Locations), which is a
+four member structure with the following integer fields:
+first_line
, first_column
, last_line
and
+last_column
.
-
ltcalc
ltcalc
-Whether you choose to handle locations or not has no effect on the syntax of -your language. Therefore, grammar rules for this example will be very close to -those of the previous example: we will only modify them to benefit from the new -informations we will have. +Whether handling locations or not has no effect on the syntax of your +language. Therefore, grammar rules for this example will be very close +to those of the previous example: we will only modify them to benefit +from the new information.
-Here, we will use locations to report divisions by zero, and locate the wrong -expressions or subexpressions. +Here, we will use locations to report divisions by zero, and locate the +wrong expressions or subexpressions. @@ -1829,9 +2079,9 @@ else { $$ = 1; - printf("Division by zero, l%d,c%d-l%d,c%d", - @3.first_line, @3.first_column, - @3.last_line, @3.last_column); + fprintf (stderr, "%d.%d-%d.%d: division by zero", + @3.first_line, @3.first_column, + @3.last_line, @3.last_column); } } | '-' exp %preg NEG { $$ = -$2; } @@ -1846,31 +2096,28 @@
-In this example, we never assign a value to @$
, because the
-output parser can do this automatically. By default, before executing
-the C code of each action, @$
is set to range from the beginning
-of @1
to the end of @n
, for a rule with n
-components.
+We don't need to assign a value to @$
: the output parser does it
+automatically. By default, before executing the C code of each action,
+@$
is set to range from the beginning of @1
to the end
+of @n
, for a rule with n components. This behavior
+can be redefined (see section Default Action for Locations), and for very specific rules, @$
can be computed by
+hand.
-
-Of course, this behavior can be redefined (see section Default Action for Locations), and for very specific rules,
-@$
can be computed by hand.
-
-
-
ltcalc
Lexical Analyzer.ltcalc
Lexical Analyzer.-Until now, we relied on Bison's defaults to enable location tracking. The next -step is to rewrite the lexical analyser, and make it able to feed the parser -with locations of tokens, as he already does for semantic values. +Until now, we relied on Bison's defaults to enable location +tracking. The next step is to rewrite the lexical analyzer, and make it +able to feed the parser with the token locations, as it already does for +semantic values.
-To do so, we must take into account every single character of the input text, -to avoid the computed locations of being fuzzy or wrong: +To this end, we must take into account every single character of the +input text, to avoid the computed locations of being fuzzy or wrong: @@ -1880,15 +2127,15 @@ { int c; - /* skip white space */ + /* Skip white space. */ while ((c = getchar ()) == ' ' || c == '\t') ++yylloc.last_column; - /* step */ + /* Step. */ yylloc.first_line = yylloc.last_line; yylloc.first_column = yylloc.last_column; - /* process numbers */ + /* Process numbers. */ if (isdigit (c)) { yylval = c - '0'; @@ -1902,11 +2149,11 @@ return NUM; } - /* return end-of-file */ + /* Return end-of-input. */ if (c == EOF) return 0; - /* return single chars and update location */ + /* Return a single char, and update location. */ if (c == '\n') { ++yylloc.last_line; @@ -1919,17 +2166,17 @@
-Basically, the lexical analyzer does the same processing as before: it skips
-blanks and tabs, and reads numbers or single-character tokens. In addition
-to this, it updates the yylloc
global variable (of type YYLTYPE
),
-where the location of tokens is stored.
+Basically, the lexical analyzer performs the same processing as before:
+it skips blanks and tabs, and reads numbers or single-character tokens.
+In addition, it updates yylloc
, the global variable (of type
+YYLTYPE
) containing the token's location.
-Now, each time this function returns a token, the parser has it's number as
-well as it's semantic value, and it's position in the text. The last needed
-change is to initialize yylloc
, for example in the controlling
-function:
+Now, each time this function returns a token, the parser has its number
+as well as its semantic value, and its location in the text. The last
+needed change is to initialize yylloc
, for example in the
+controlling function:
@@ -1944,18 +2191,18 @@
-Remember that computing locations is not a matter of syntax. Every character -must be associated to a location update, whether it is in valid input, in -comments, in literal strings, and so on... +Remember that computing locations is not a matter of syntax. Every +character must be associated to a location update, whether it is in +valid input, in comments, in literal strings, and so on. -
mfcalc
mfcalc
@@ -1987,20 +2234,20 @@
-% mfcalc -pi = 3.141592653589 +$ mfcalc +pi = 3.141592653589 3.1415926536 -sin(pi) +sin(pi) 0.0000000000 -alpha = beta1 = 2.3 +alpha = beta1 = 2.3 2.3000000000 -alpha +alpha 2.3000000000 -ln(alpha) +ln(alpha) 0.8329091229 -exp(ln(beta1)) +exp(ln(beta1)) 2.3000000000 -% +$
@@ -2009,7 +2256,7 @@ -
mfcalc
mfcalc
Here are the C and Bison declarations for the multi-function calculator. @@ -2018,7 +2265,7 @@
%{ -#include <math.h> /* For math functions, cos(), sin(), etc. */ +#include <math.h> /* For math functions, cos(), sin(), etc. */ #include "calc.h" /* Contains definition of `symrec' */ %} %union { @@ -2044,14 +2291,14 @@The above grammar introduces only two new features of the Bison language. These features allow semantic values to have various data types -(see section More Than One Value Type). +(see section More Than One Value Type).
The
%union
declaration specifies the entire list of possible types; this is instead of definingYYSTYPE
. The allowable types are now double-floats (forexp
andNUM
) and pointers to entries in -the symbol table. See section The Collection of Value Types. +the symbol table. See section The Collection of Value Types.@@ -2063,16 +2310,17 @@
-The Bison construct
%type
is used for declaring nonterminal symbols, -just as%token
is used for declaring token types. We have not used -%type
before because nonterminal symbols are normally declared -implicitly by the rules that define them. Butexp
must be declared -explicitly so we can specify its value type. See section Nonterminal Symbols. +The Bison construct%type
is used for declaring nonterminal +symbols, just as%token
is used for declaring token types. We +have not used%type
before because nonterminal symbols are +normally declared implicitly by the rules that define them. But +exp
must be declared explicitly so we can specify its value type. +See section Nonterminal Symbols. -Grammar Rules for
+mfcalc
Grammar Rules for
mfcalc
Here are the grammar rules for the multi-function calculator. @@ -2110,9 +2358,9 @@ -
The
+mfcalc
Symbol TableThe
mfcalc
Symbol Table@@ -2130,7 +2378,7 @@
-/* Fonctions type. */ +/* Function type. */ typedef double (*func_t) (double); /* Data type for links in the chain of symbols. */ @@ -2198,7 +2446,7 @@ /* The symbol table: a chain of `struct symrec'. */ symrec *sym_table = (symrec *) 0; -/* Put arithmetic functions in table. */ +/* Put arithmetic functions in table. */ void init_table (void) { @@ -2236,7 +2484,7 @@ ptr->name = (char *) malloc (strlen (sym_name) + 1); strcpy (ptr->name,sym_name); ptr->type = sym_type; - ptr->value.var = 0; /* set value to 0 even if fctn. */ + ptr->value.var = 0; /* Set value to 0 even if fctn. */ ptr->next = (struct symrec *)sym_table; sym_table = ptr; return ptr; @@ -2269,6 +2517,7 @@putsym
. Again, a pointer and its type (which must beVAR
) is returned toyyparse
. +No change is needed in the handling of numeric values and arithmetic operators in
yylex
. @@ -2283,7 +2532,7 @@ { int c; - /* Ignore whitespace, get first nonwhite character. */ + /* Ignore white space, get first nonwhite character. */ while ((c = getchar ()) == ' ' || c == '\t'); if (c == EOF) @@ -2324,7 +2573,7 @@ /* Get another character. */ c = getchar (); } - while (c != EOF && isalnum (c)); + while (isalnum (c)); ungetc (c, stdin); symbuf[i] = '\0'; @@ -2342,16 +2591,16 @@-This program is both powerful and flexible. You may easily add new -functions, and it is a simple job to modify this code to install predefined -variables such as
pi
ore
as well. +This program is both powerful and flexible. You may easily add new +functions, and it is a simple job to modify this code to install +predefined variables such aspi
ore
as well. -Exercises
+Exercises
Bison Grammar Files
+Bison Grammar Files
Bison takes as input a context-free grammar specification and produces a @@ -2383,12 +2632,12 @@
The Bison grammar input file conventionally has a name ending in `.y'. -See section Invoking Bison. +See section Invoking Bison. -
Outline of a Bison Grammar
+Outline of a Bison Grammar
A Bison grammar file has four main sections, shown here with the @@ -2398,7 +2647,7 @@
%{ -C declarations +Prologue %} Bison declarations @@ -2407,7 +2656,7 @@ Grammar rules %% -Additional C code +Epilogue@@ -2416,14 +2665,15 @@ -
The C Declarations Section
+The prologue
-The C declarations section contains macro definitions and +The Prologue section contains macro definitions and declarations of functions and variables that are used in the actions in the grammar rules. These are copied to the beginning of the parser file so that they precede the definition of
yyparse
. You can use @@ -2432,32 +2682,62 @@ delimiters that bracket this section. ++You may have more than one Prologue section, intermixed with the +Bison declarations. This allows you to have C and Bison +declarations that refer to each other. For example, the
%union
+declaration may use types defined in a header file, and you may wish to +prototype functions that take arguments of typeYYSTYPE
. This +can be done with two Prologue blocks, one before and one after the +%union
declaration. + + + ++%{ +#include <stdio.h> +#include "ptypes.h" +%} + +%union { + long n; + tree t; /*+ -tree
is defined in `ptypes.h'. */ +} + +%{ +static void yyprint(FILE *, int, YYSTYPE); +#define YYPRINT(F, N, L) yyprint(F, N, L) +%} + +... +The Bison Declarations Section
+The Bison Declarations Section
The Bison declarations section contains declarations that define terminal and nonterminal symbols, specify precedence, and so on. In some simple grammars you may not need any declarations. -See section Bison Declarations. +See section Bison Declarations. -
The Grammar Rules Section
+The Grammar Rules Section
The grammar rules section contains one or more Bison grammar -rules, and nothing else. See section Syntax of Grammar Rules. +rules, and nothing else. See section Syntax of Grammar Rules.
@@ -2468,19 +2748,20 @@ -
The Additional C Code Section
+The epilogue
-The additional C code section is copied verbatim to the end of the -parser file, just as the C declarations section is copied to the -beginning. This is the most convenient place to put anything that you -want to have in the parser file but which need not come before the -definition of
yyparse
. For example, the definitions of -yylex
andyyerror
often go here. See section Parser C-Language Interface. +The Epilogue is copied verbatim to the end of the parser file, just as +the Prologue is copied to the beginning. This is the most convenient +place to put anything that you want to have in the parser file but which need +not come before the definition ofyyparse
. For example, the +definitions ofyylex
andyyerror
often go here. +See section Parser C-Language Interface.@@ -2492,17 +2773,17 @@ The Bison parser itself contains many static variables whose names start with `yy' and many macros whose names start with `YY'. It is a good idea to avoid using any such names (except those documented in this -manual) in the additional C code section of the grammar file. +manual) in the epilogue of the grammar file. -
Symbols, Terminal and Nonterminal
+Symbols, Terminal and Nonterminal
@@ -2542,18 +2823,18 @@ A named token type is written with an identifier, like an identifier in C. By convention, it should be all upper case. Each such name must be defined with a Bison declaration such as -
%token
. See section Token Type Names. +%token
. See section Token Type Names.
'+'
is a character token type. A
character token type doesn't need to be declared unless you need to
-specify its semantic value data type (see section Data Types of Semantic Values), associativity, or precedence (see section Operator Precedence).
+specify its semantic value data type (see section Data Types of Semantic Values), associativity, or precedence (see section Operator Precedence).
By convention, a character token type is used only to represent a
token that consists of that particular character. Thus, the token
@@ -2563,24 +2844,24 @@
All the usual escape sequences used in character literals in C can be
used in Bison as well, but you must not use the null character as a
-character literal because its ASCII code, zero, is the code yylex
-returns for end-of-input (see section Calling Convention for yylex
).
+character literal because its numeric code, zero, signifies
+end-of-input (see section Calling Convention for yylex
).
"<="
is a literal string token. A literal string token
doesn't need to be declared unless you need to specify its semantic
-value data type (see section Data Types of Semantic Values), associativity, or precedence
-(see section Operator Precedence).
+value data type (see section Data Types of Semantic Values), associativity, or precedence
+(see section Operator Precedence).
You can associate the literal string token with a symbolic name as an
-alias, using the %token
declaration (see section Token Type Names). If you don't do that, the lexical analyzer has to
+alias, using the %token
declaration (see section Token Type Names). If you don't do that, the lexical analyzer has to
retrieve the token number for the literal string token from the
-yytname
table (see section Calling Convention for yylex
).
+yytname
table (see section Calling Convention for yylex
).
WARNING: literal string tokens do not work in Yacc.
@@ -2603,15 +2884,18 @@
-The value returned by yylex
is always one of the terminal symbols
-(or 0 for end-of-input). Whichever way you write the token type in the
-grammar rules, you write it the same way in the definition of yylex
.
-The numeric code for a character token type is simply the ASCII code for
-the character, so yylex
can use the identical character constant to
-generate the requisite code. Each named token type becomes a C macro in
+The value returned by yylex
is always one of the terminal
+symbols, except that a zero or negative value signifies end-of-input.
+Whichever way you write the token type in the grammar rules, you write
+it the same way in the definition of yylex
. The numeric code
+for a character token type is simply the positive numeric code of the
+character, so yylex
can use the identical value to generate the
+requisite code, though you may need to convert it to unsigned
+char
to avoid sign-extension on hosts where char
is signed.
+Each named token type becomes a C macro in
the parser file, so yylex
can use the name to stand for the code.
(This is why periods don't make sense in terminal symbols.)
-See section Calling Convention for yylex
.
+See section Calling Convention for yylex
.
@@ -2619,22 +2903,51 @@ token-type macro definitions to be available there. Use the `-d' option when you run Bison, so that it will write these macro definitions into a separate header file `name.tab.h' which you can include -in the other source files that need it. See section Invoking Bison. +in the other source files that need it. See section Invoking Bison. + + +
+If you want to write a grammar that is portable to any Standard C +host, you must use only non-null character tokens taken from the basic +execution character set of Standard C. This set consists of the ten +digits, the 52 lower- and upper-case English letters, and the +characters in the following C-language string: + + + +
+"\a\b\t\n\v\f\r !\"#%&'()*+,-./:;<=>?[\\]^_{|}~" ++ +
+The yylex
function and Bison must use a consistent character
+set and encoding for character tokens. For example, if you run Bison in an
+ASCII environment, but then compile and run the resulting program
+in an environment that uses an incompatible character set like
+EBCDIC, the resulting program may not work because the
+tables generated by Bison will assume ASCII numeric values for
+character tokens. It is standard
+practice for software distributions to contain C source files that
+were generated by Bison in an ASCII environment, so installers on
+platforms that are incompatible with ASCII must rebuild those
+files before compiling them.
The symbol error
is a terminal symbol reserved for error recovery
-(see section Error Recovery); you shouldn't use it for any other purpose.
-In particular, yylex
should never return this value.
+(see section Error Recovery); you shouldn't use it for any other purpose.
+In particular, yylex
should never return this value. The default
+value of the error token is 256, unless you explicitly assigned 256 to
+one of your tokens with a %token
declaration.
-
@@ -2650,7 +2963,7 @@
where result is the nonterminal symbol that this rule describes, and components are various terminal and nonterminal symbols that -are put together by this rule (see section Symbols, Terminal and Nonterminal). +are put together by this rule (see section Symbols, Terminal and Nonterminal).
@@ -2669,8 +2982,8 @@
-Whitespace in rules is significant only to separate symbols. You can add -extra whitespace as you wish. +White space in rules is significant only to separate symbols. You can add +extra white space as you wish.
@@ -2685,11 +2998,11 @@
Usually there is only one action and it follows the components. -See section Actions. +See section Actions.
- + Multiple rules for the same result can be written separately or can be joined with the vertical-bar character `|' as follows: @@ -2730,9 +3043,9 @@ -
@@ -2751,8 +3064,8 @@
-
-
+
+
Since the recursive use of expseq1
is the leftmost symbol in the
right hand side, we call this left recursion. By contrast, here
the same construct is defined using right recursion:
@@ -2766,18 +3079,18 @@
-Any kind of sequence can be defined using either left recursion or -right recursion, but you should always use left recursion, because it -can parse a sequence of any number of elements with bounded stack -space. Right recursion uses up space on the Bison stack in proportion -to the number of elements in the sequence, because all the elements -must be shifted onto the stack before the rule can be applied even -once. See section The Bison Parser Algorithm, for -further explanation of this. +Any kind of sequence can be defined using either left recursion or right +recursion, but you should always use left recursion, because it can +parse a sequence of any number of elements with bounded stack space. +Right recursion uses up space on the Bison stack in proportion to the +number of elements in the sequence, because all the elements must be +shifted onto the stack before the rule can be applied even once. +See section The Bison Parser Algorithm, for further explanation +of this.
- + Indirect or mutual recursion occurs when the result of the rule does not appear directly on its right hand side, but does appear in rules for other nonterminals which do appear on its right hand @@ -2806,10 +3119,10 @@ -
@@ -2827,18 +3140,18 @@ -
In a simple program it may be sufficient to use the same data type for the semantic values of all language constructs. This was true in the -RPN and infix calculator examples (see section Reverse Polish Notation Calculator). +RPN and infix calculator examples (see section Reverse Polish Notation Calculator).
@@ -2852,13 +3165,13 @@
-This macro definition must go in the C declarations section of the grammar -file (see section Outline of a Bison Grammar). +This macro definition must go in the prologue of the grammar file +(see section Outline of a Bison Grammar). -
In most programs, you will need different data types for different kinds @@ -2877,23 +3190,23 @@
%union
Bison declaration (see section The Collection of Value Types).
+%union
Bison declaration (see section The Collection of Value Types).
%token
Bison declaration (see section Token Type Names)
-and for groupings with the %type
Bison declaration (see section Nonterminal Symbols).
+%token
Bison declaration (see section Token Type Names)
+and for groupings with the %type
Bison declaration (see section Nonterminal Symbols).
-@@ -2905,10 +3218,10 @@
An action consists of C statements surrounded by braces, much like a -compound statement in C. It can be placed at any position in the rule; it -is executed at that position. Most rules have just one action at the end -of the rule, following all the components. Actions in the middle of a rule -are tricky and used only for special purposes (see section Actions in Mid-Rule). +compound statement in C. It can be placed at any position in the rule; +it is executed at that position. Most rules have just one action at the +end of the rule, following all the components. Actions in the middle of +a rule are tricky and used only for special purposes (see section Actions in Mid-Rule).
@@ -2941,8 +3254,22 @@
useful semantic value associated with the `+' token, it could be
referred to as $2
.
+
- +Note that the vertical-bar character `|' is really a rule +separator, and actions are attached to a single rule. This is a +difference with tools like Flex, for which `|' stands for either +"or", or "the same action as that of the next rule". In the +following example, the action is triggered only when `b' is found: + + + +
+a-or-b: 'a'|'b' { a_or_b_found = 1; }; ++ +
+
If you don't specify an action for a rule, Bison supplies a default:
$$ = $1
. Thus, the value of the first symbol in the rule becomes
the value of the whole rule. Of course, the default rule is valid only
@@ -2978,10 +3305,10 @@
-
@@ -2997,6 +3324,7 @@ in the rule. In this example, +
exp: ... | exp '+' exp @@ -3009,6 +3337,7 @@$2
were used, it would have the data type declared for the terminal symbol'+'
, whatever that might be. +Alternatively, you can specify the data type when you refer to the value, by inserting `<type>' after the `$' at the beginning of the @@ -3030,10 +3359,10 @@ -
Actions in Mid-Rule
+Actions in Mid-Rule
@@ -3143,7 +3472,7 @@ must commit to using one rule or the other, without sufficient information to do it correctly. (The open-brace token is what is called the look-ahead token at this time, since the parser is still -deciding what to do about it. See section Look-Ahead Tokens.) +deciding what to do about it. See section Look-Ahead Tokens.)
@@ -3212,30 +3541,30 @@ -
Tracking Locations
+Tracking Locations
Though grammar rules and semantic actions are enough to write a fully -functional parser, it can be useful to process some additionnal informations, +functional parser, it can be useful to process some additional information, especially symbol locations.
-The way locations are handled is defined by providing a data type, and actions -to take when rules are matched. +The way locations are handled is defined by providing a data type, and +actions to take when rules are matched. -
Data Type of Locations
+Data Type of Locations
@@ -3262,12 +3591,12 @@ -
Actions and Locations
+Actions and Locations
@@ -3277,7 +3606,7 @@
The most obvious way for building locations of syntactic groupings is very -similar to the way semantic values are computed. In a given rule, several +similar to the way semantic values are computed. In a given rule, several constructs can be used to access the locations of the elements being matched. The location of the nth component of the right hand side is
@n
, while the location of the left hand side grouping is @@ -3311,13 +3640,13 @@As for semantic values, there is a default action for locations that is -run each time a rule is matched. It sets the beginning of
@$
to the +run each time a rule is matched. It sets the beginning of@$
to the beginning of the first symbol, and the end of@$
to the end of the last symbol.-With this default action, the location tracking can be fully automatic. The +With this default action, the location tracking can be fully automatic. The example above simply rewrites this way: @@ -3340,17 +3669,17 @@ -
Default Action for Locations
+Default Action for Locations
-Actually, actions are not the best place to compute locations. Since locations -are much more general than semantic values, there is room in the output parser -to redefine the default action to take for each rule. The -
YYLLOC_DEFAULT
macro is called each time a rule is matched, before the -associated action is run. +Actually, actions are not the best place to compute locations. Since +locations are much more general than semantic values, there is room in +the output parser to redefine the default action to take for each +rule. TheYYLLOC_DEFAULT
macro is invoked each time a rule is +matched, before the associated action is run.@@ -3359,21 +3688,36 @@
-The
YYLLOC_DEFAULT
macro takes three parameters. The first one is -the location of the grouping (the result of the computation). The second one +TheYYLLOC_DEFAULT
macro takes three parameters. The first one is +the location of the grouping (the result of the computation). The second one is an array holding locations of all right hand side elements of the rule -being matched. The last one is the size of the right hand side rule. +being matched. The last one is the size of the right hand side rule. + + ++By default, it is defined this way for simple LALR(1) parsers: + +
+#define YYLLOC_DEFAULT(Current, Rhs, N) \ + Current.first_line = Rhs[1].first_line; \ + Current.first_column = Rhs[1].first_column; \ + Current.last_line = Rhs[N].last_line; \ + Current.last_column = Rhs[N].last_column; ++-By default, it is defined this way: +and like this for GLR parsers:
-#define YYLLOC_DEFAULT(Current, Rhs, N) \ - Current.last_line = Rhs[N].last_line; \ - Current.last_column = Rhs[N].last_column; +#define YYLLOC_DEFAULT(Current, Rhs, N) \ + Current.first_line = YYRHSLOC(Rhs,1).first_line; \ + Current.first_column = YYRHSLOC(Rhs,1).first_column; \ + Current.last_line = YYRHSLOC(Rhs,N).last_line; \ + Current.last_column = YYRHSLOC(Rhs,N).last_column;@@ -3384,39 +3728,34 @@
YYLLOC_DEFAULT
.
YYLLOC_DEFAULT
is executed, the output parser sets @$
-to @1
.
-
-The Bison declarations section of a Bison grammar defines the symbols used in formulating the grammar and the data types of semantic values. -See section Symbols, Terminal and Nonterminal. +See section Symbols, Terminal and Nonterminal.
All token type names (but not single-character literal tokens such as
'+'
and '*'
) must be declared. Nonterminal symbols must be
declared if you need to specify which data type to use for the semantic
-value (see section More Than One Value Type).
+value (see section More Than One Value Type).
@@ -3427,12 +3766,12 @@ -
@@ -3453,7 +3792,7 @@
Alternatively, you can use %left
, %right
, or
%nonassoc
instead of %token
, if you wish to specify
-associativity and precedence. See section Operator Precedence.
+associativity and precedence. See section Operator Precedence.
@@ -3469,13 +3808,13 @@
It is generally best, however, to let Bison choose the numeric codes for all token types. Bison will automatically select codes that don't conflict -with each other or with ASCII characters. +with each other or with normal characters.
In the event that the stack type is a union, you must augment the
%token
or other token declaration to include the data type
-alternative delimited by angle-brackets (see section More Than One Value Type).
+alternative delimited by angle-brackets (see section More Than One Value Type).
@@ -3518,23 +3857,24 @@
Once you equate the literal string and the token name, you can use them
interchangeably in further declarations or the grammar rules. The
yylex
function can use the token name or the literal string to
-obtain the token type code number (see section Calling Convention for yylex
).
+obtain the token type code number (see section Calling Convention for yylex
).
-
Use the %left
, %right
or %nonassoc
declaration to
declare a token and specify its precedence and associativity, all at
once. These are called precedence declarations.
-See section Operator Precedence, for general information on operator precedence.
+See section Operator Precedence, for general information on
+operator precedence.
@@ -3587,11 +3927,11 @@ -
@@ -3617,7 +3957,7 @@
This says that the two alternative types are double
and symrec
*
. They are given names val
and tptr
; these names are used
in the %token
and %type
declarations to pick one of the types
-for a terminal or nonterminal symbol (see section Nonterminal Symbols).
+for a terminal or nonterminal symbol (see section Nonterminal Symbols).
@@ -3627,11 +3967,11 @@ -
@@ -3646,11 +3986,12 @@
-Here nonterminal is the name of a nonterminal symbol, and type
-is the name given in the %union
to the alternative that you want
-(see section The Collection of Value Types). You can give any number of nonterminal symbols in
-the same %type
declaration, if they have the same value type. Use
-spaces to separate the symbol names.
+Here nonterminal is the name of a nonterminal symbol, and
+type is the name given in the %union
to the alternative
+that you want (see section The Collection of Value Types). You
+can give any number of nonterminal symbols in the same %type
+declaration, if they have the same value type. Use spaces to separate
+the symbol names.
@@ -3662,22 +4003,22 @@ -
Bison normally warns if there are any conflicts in the grammar
-(see section Shift/Reduce Conflicts), but most real grammars have harmless shift/reduce
-conflicts which are resolved in a predictable way and would be difficult to
-eliminate. It is desirable to suppress the warning about these conflicts
-unless the number of conflicts changes. You can do this with the
-%expect
declaration.
+(see section Shift/Reduce Conflicts), but most real grammars
+have harmless shift/reduce conflicts which are resolved in a predictable
+way and would be difficult to eliminate. It is desirable to suppress
+the warning about these conflicts unless the number of conflicts
+changes. You can do this with the %expect
declaration.
@@ -3690,10 +4031,11 @@
-Here n is a decimal integer. The declaration says there should be no -warning if there are n shift/reduce conflicts and no reduce/reduce -conflicts. The usual warning is given if there are either more or fewer -conflicts, or if there are any reduce/reduce conflicts. +Here n is a decimal integer. The declaration says there should be +no warning if there are n shift/reduce conflicts and no +reduce/reduce conflicts. An error, instead of the usual warning, is +given if there are either more or fewer conflicts, or if there are any +reduce/reduce conflicts.
@@ -3728,12 +4070,12 @@ -
@@ -3749,11 +4091,11 @@ -
@@ -3775,21 +4117,21 @@
Alternatively, you can generate a pure, reentrant parser. The Bison
-declaration %pure_parser
says that you want the parser to be
+declaration %pure-parser
says that you want the parser to be
reentrant. It looks like this:
-%pure_parser +%pure-parser
The result is that the communication variables yylval
and
yylloc
become local variables in yyparse
, and a different
calling convention is used for the lexical analyzer function
-yylex
. See section Calling Conventions for Pure Parsers, for the details of this. The variable yynerrs
also
-becomes local in yyparse
(see section The Error Reporting Function yyerror
). The convention for calling
+yylex
. See section Calling Conventions for Pure Parsers, for the details of this. The variable yynerrs
also
+becomes local in yyparse
(see section The Error Reporting Function yyerror
). The convention for calling
yyparse
itself is unchanged.
@@ -3801,15 +4143,15 @@
-
-Here is a summary of all Bison declarations: +Here is a summary of the declarations used to define a grammar:
%union
%token
%right
%left
%nonassoc
%type
%start
%expect
%yacc
++In order to change the behavior of @command{bison}, use the following +directives: + + +
%debug
%fixed_output_files
+In the parser file, define the macro YYDEBUG
to 1 if it is not
+already defined, so that the debugging facilities are compiled.
+See section Tracing Your Parser.
+
+%defines
YYSTYPE
, as well as a few extern
variable declarations.
+
+If the parser output file is named `name.c' then this file
+is named `name.h'.
+
+This output file is essential if you wish to put the definition of
+yylex
in a separate source file, because yylex
needs to
+be able to refer to token type codes and the variable
+yylval
. See section Semantic Values of Tokens.
+
+%file-prefix="prefix"
+%locations
%pure_parser
+%name-prefix="prefix"
yyparse
, yylex
, yyerror
, yynerrs
,
+yylval
, yychar
, yydebug
, and possible
+yylloc
. For example, if you use `%name-prefix="c_"', the
+names become c_parse
, c_lex
, and so on. See section Multiple Parsers in the Same Program.
-%no_parser
+%no-parser
#define
directives and static variable
@@ -3882,7 +4255,7 @@
into a file named `filename.act', in the form of a
brace-surrounded body fit for a switch
statement.
-%no_lines
+%no-lines
#line
preprocessor commands in the parser
file. Ordinarily Bison writes these commands in the parser file so that
@@ -3891,45 +4264,22 @@
associate errors with the parser file, treating it an independent source
file in its own right.
-%debug
+%output="filename"
YYDEBUG
into the parser file, so
-that the debugging facilities are compiled. See section Debugging Your Parser.
+Specify the filename for the parser file.
-%defines
-YYSTYPE
, as well as a few extern
variable declarations.
-
-If the parser output file is named `name.c' then this file
-is named `name.h'.
-This output file is essential if you wish to put the definition of
-yylex
in a separate source file, because yylex
needs to
-be able to refer to token type codes and the variable
-yylval
. See section Semantic Values of Tokens.
-%verbose
+%pure-parser
%token_table
+%token-table
yytname
; yytname[i]
is the name of the
-token whose internal Bison token code number is i. The first three
-elements of yytname
are always "$"
, "error"
, and
-"$illegal"
; after these come the symbols defined in the grammar
-file.
+token whose internal Bison token code number is i. The first
+three elements of yytname
are always "$end"
,
+"error"
, and "$undefined"
; after these come the symbols
+defined in the grammar file.
For single-character literal tokens and literal string tokens, the name
in the table includes the single-quote or double-quote characters: for
@@ -3941,7 +4291,7 @@
contains `"*"*"'. (In C, that would be written as
"\"*\"*\""
).
-When you specify %token_table
, Bison also generates macro
+When you specify %token-table
, Bison also generates macro
definitions for macros YYNTOKENS
, YYNNTS
, and
YYNRULES
, and YYNSTATES
:
@@ -3958,13 +4308,25 @@
The number of grammar rules,
YYNSTATES
%verbose
+%yacc
+Most programs that use Bison parse only one language and therefore contain @@ -3975,10 +4337,10 @@
The easy way to do this is to use the option `-p prefix' -(see section Invoking Bison). This renames the interface functions and -variables of the Bison parser to start with prefix instead of -`yy'. You can use this to give each parser distinct names that do -not conflict. +(see section Invoking Bison). This renames the interface +functions and variables of the Bison parser to start with prefix +instead of `yy'. You can use this to give each parser distinct +names that do not conflict.
@@ -3993,7 +4355,7 @@
renamed. These others are not global; there is no conflict if the same
name is used in different parsers. For example, YYSTYPE
is not
renamed, but defining this in different ways in different parsers causes
-no trouble (see section Data Types of Semantic Values).
+no trouble (see section Data Types of Semantic Values).
@@ -4005,10 +4367,10 @@ -
@@ -4020,15 +4382,15 @@
Keep in mind that the parser uses many C identifiers starting with `yy' and `YY' for internal purposes. If you use such an -identifier (aside from those in this manual) in an action or in additional -C code in the grammar file, you are likely to run into trouble. +identifier (aside from those in this manual) in an action or in epilogue +in the grammar file, you are likely to run into trouble. -
yyparse
yyparse
@@ -4057,21 +4419,21 @@
YYACCEPT
YYABORT
yylex
yylex
@@ -4088,29 +4450,32 @@ To do this, use the `-d' option when you run Bison, so that it will write these macro definitions into a separate header file `name.tab.h' which you can include in the other source files -that need it. See section Invoking Bison. +that need it. See section Invoking Bison. -
yylex
yylex
-The value that yylex
returns must be the numeric code for the type
-of token it has just found, or 0 for end-of-input.
+The value that yylex
returns must be the positive numeric code
+for the type of token it has just found; a zero or negative value
+signifies end-of-input.
When a token is referred to in the grammar rules by a name, that name
in the parser file becomes a C macro whose definition is the proper
numeric code for that token type. So yylex
can use the name
-to indicate that type. See section Symbols, Terminal and Nonterminal.
+to indicate that type. See section Symbols, Terminal and Nonterminal.
When a token is referred to in the grammar rules by a character literal,
the numeric code for that character is also the code for the token type.
-So yylex
can simply return that character code. The null character
-must not be used this way, because its code is zero and that is what
+So yylex
can simply return that character code, possibly converted
+to unsigned char
to avoid sign-extension. The null character
+must not be used this way, because its code is zero and that
signifies end-of-input.
@@ -4124,13 +4489,13 @@
yylex (void)
{
...
- if (c == EOF) /* Detect end of file. */
+ if (c == EOF) /* Detect end-of-input. */
return 0;
...
if (c == '+' || c == '-')
- return c; /* Assume token type for `+' is '+'. */
+ return c; /* Assume token type for `+' is '+'. */
...
- return INT; /* Return the type of the token. */
+ return INT; /* Return the type of the token. */
...
}
@@ -4172,8 +4537,8 @@
{
if (yytname[i] != 0
&& yytname[i][0] == '"'
- && strncmp (yytname[i] + 1, token_buffer,
- strlen (token_buffer))
+ && ! strncmp (yytname[i] + 1, token_buffer,
+ strlen (token_buffer))
&& yytname[i][strlen (token_buffer) + 1] == '"'
&& yytname[i][strlen (token_buffer) + 2] == 0)
break;
@@ -4181,15 +4546,15 @@
The yytname
table is generated only if you use the
-%token_table
declaration. See section Bison Declaration Summary.
+%token-table
declaration. See section Bison Declaration Summary.
-
-
+
In an ordinary (non-reentrant) parser, the semantic value of the token must
be stored into the global variable yylval
. When you are using
just one data type for semantic values, yylval
has that type.
@@ -4200,16 +4565,16 @@
... - yylval = value; /* Put value onto Bison stack. */ - return INT; /* Return the type of the token. */ + yylval = value; /* Put value onto Bison stack. */ + return INT; /* Return the type of the token. */ ...
When you are using multiple data types, yylval
's type is a union
-made from the %union
declaration (see section The Collection of Value Types). So when
-you store a token's value, you must use the proper member of the union.
-If the %union
declaration looks like this:
+made from the %union
declaration (see section The Collection of Value Types). So when you store a token's value, you
+must use the proper member of the union. If the %union
+declaration looks like this:
@@ -4228,18 +4593,18 @@
... - yylval.intval = value; /* Put value onto Bison stack. */ - return INT; /* Return the type of the token. */ + yylval.intval = value; /* Put value onto Bison stack. */ + return INT; /* Return the type of the token. */ ...-
-
-If you are using the `@n'-feature (see section Tracking Locations) in actions to keep track of the
+
+If you are using the `@n'-feature (see section Tracking Locations) in actions to keep track of the
textual locations of tokens and groupings, then you must provide this
information in yylex
. The function yyparse
expects to
find the textual location of a token just parsed in the global variable
@@ -4256,18 +4621,18 @@
-
+
The data type of yylloc
has the name YYLTYPE
.
-
-When you use the Bison declaration %pure_parser
to request a
+When you use the Bison declaration %pure-parser
to request a
pure, reentrant parser, the global communication variables yylval
-and yylloc
cannot be used. (See section A Pure (Reentrant) Parser.) In such parsers the two global variables are replaced by
+and yylloc
cannot be used. (See section A Pure (Reentrant) Parser.) In such parsers the two global variables are replaced by
pointers passed as arguments to yylex
. You must declare them as
shown here, and pass the information back by storing it through those
pointers.
@@ -4293,7 +4658,7 @@
-
+
If you use a reentrant parser, you can optionally pass additional
parameter information to it in a reentrant way. To do so, define the
macro YYPARSE_PARAM
as a variable name. This modifies the
@@ -4353,7 +4718,7 @@
-
+
If you wish to pass the additional parameter data to yylex
,
define the macro YYLEX_PARAM
just like YYPARSE_PARAM
, as
shown here:
@@ -4383,26 +4748,26 @@
-You can use `%pure_parser' to request a reentrant parser without
+You can use `%pure-parser' to request a reentrant parser without
also using YYPARSE_PARAM
. Then you should call yyparse
with no arguments, as usual.
-
yyerror
yyerror
The Bison parser detects a parse error or syntax error
whenever it reads a token which cannot satisfy any syntax rule. An
action in the grammar can also explicitly proclaim an error, using the
-macro YYERROR
(see section Special Features for Use in Actions).
+macro YYERROR
(see section Special Features for Use in Actions).
@@ -4414,9 +4779,9 @@
-
+
If you define the macro YYERROR_VERBOSE
in the Bison declarations
-section (see section The Bison Declarations Section),
+section (see section The Bison Declarations Section),
then Bison provides a more verbose and specific error message string
instead of just plain "parse error"
. It doesn't matter what
definition you use for YYERROR_VERBOSE
, just whether you define
@@ -4449,24 +4814,24 @@
After yyerror
returns to yyparse
, the latter will attempt
error recovery if you have written suitable error recovery grammar rules
-(see section Error Recovery). If recovery is impossible, yyparse
will
+(see section Error Recovery). If recovery is impossible, yyparse
will
immediately return 1.
-
+
The variable yynerrs
contains the number of syntax errors
encountered so far. Normally this variable is global; but if you
-request a pure parser (see section A Pure (Reentrant) Parser) then it is a local variable
-which only the actions can access.
+request a pure parser (see section A Pure (Reentrant) Parser)
+then it is a local variable which only the actions can access.
-
@@ -4479,38 +4844,40 @@
$$
but specifies alternative typealt in the union
-specified by the %union
declaration. See section Data Types of Values in Actions.
+specified by the %union
declaration. See section Data Types of Values in Actions.
$n
but specifies alternative typealt in the
union specified by the %union
declaration.
-See section Data Types of Values in Actions.
+See section Data Types of Values in Actions.
+
yyparse
, indicating failure.
-See section The Parser Function yyparse
.
+See section The Parser Function yyparse
.
yyparse
, indicating success.
-See section The Parser Function yyparse
.
+See section The Parser Function yyparse
.
yychar
when there is no look-ahead token.
yyerror
, and does not print any message. If you
want to print an error message, call yyerror
explicitly before
-the `YYERROR;' statement. See section Error Recovery.
+the `YYERROR;' statement. See section Error Recovery.
yyparse
.) When there is
no look-ahead token, the value YYEMPTY
is stored in the variable.
-See section Look-Ahead Tokens.
+See section Look-Ahead Tokens.
@@ -4653,9 +5020,9 @@ -
@@ -4713,19 +5080,19 @@
-
+
The current look-ahead token is stored in the variable yychar
.
-See section Special Features for Use in Actions.
+See section Special Features for Use in Actions.
-
@@ -4803,7 +5170,7 @@
To avoid warnings from Bison about predictable, legitimate shift/reduce
conflicts, use the %expect n
declaration. There will be no
warning as long as the number of shift/reduce conflicts is exactly n.
-See section Suppressing Conflict Warnings.
+See section Suppressing Conflict Warnings.
@@ -4832,10 +5199,10 @@ -
@@ -4847,7 +5214,7 @@ -
Consider the following ambiguous grammar fragment (ambiguous because the @@ -4888,7 +5255,7 @@
- + What about input such as `1 - 2 - 5'; should this be `(1 - 2) - 5' or should it be `1 - (2 - 5)'? For most operators we prefer the former, which is called left association. @@ -4901,11 +5268,11 @@ -
@@ -4929,7 +5296,7 @@ -
In our example, we would want the following declarations: @@ -4963,25 +5330,25 @@ -
The first effect of the precedence declarations is to assign precedence levels to the terminal symbols declared. The second effect is to assign -precedence levels to certain rules: each rule gets its precedence from the -last terminal symbol mentioned in the components. (You can also specify -explicitly the precedence of a rule. See section Context-Dependent Precedence.) +precedence levels to certain rules: each rule gets its precedence from +the last terminal symbol mentioned in the components. (You can also +specify explicitly the precedence of a rule. See section Context-Dependent Precedence.)
-Finally, the resolution of conflicts works by comparing the -precedence of the rule being considered with that of the -look-ahead token. If the token's precedence is higher, the -choice is to shift. If the rule's precedence is higher, the -choice is to reduce. If they have equal precedence, the choice -is made based on the associativity of that precedence level. The -verbose output file made by `-v' (see section Invoking Bison) says -how each conflict was resolved. +Finally, the resolution of conflicts works by comparing the precedence +of the rule being considered with that of the look-ahead token. If the +token's precedence is higher, the choice is to shift. If the rule's +precedence is higher, the choice is to reduce. If they have equal +precedence, the choice is made based on the associativity of that +precedence level. The verbose output file made by `-v' +(see section Invoking Bison) says how each conflict was +resolved.
@@ -4991,13 +5358,13 @@ -
@@ -5014,6 +5381,7 @@
precedence, you need to use an additional mechanism: the %prec
modifier for rules.
+
The %prec
modifier declares the precedence of a particular rule by
specifying a terminal symbol whose precedence should be used for that rule.
@@ -5031,7 +5399,7 @@
assign the rule the precedence of terminal-symbol, overriding
the precedence that would be deduced for it in the ordinary way. The
altered rule precedence then affects how conflicts involving that rule
-are resolved (see section Operator Precedence).
+are resolved (see section Operator Precedence).
@@ -5063,11 +5431,11 @@ -
@@ -5093,15 +5461,15 @@
There is one other alternative: the table can say that the look-ahead token is erroneous in the current state. This causes error processing to begin -(see section Error Recovery). +(see section Error Recovery). -
@@ -5241,7 +5609,7 @@ -
Sometimes reduce/reduce conflicts can occur that don't look warranted. @@ -5281,8 +5649,8 @@
-
-
+
+
However, Bison, like most parser generators, cannot actually handle all
LR(1) grammars. In this grammar, two contexts, that after an ID
at the beginning of a param_spec
and likewise at the beginning of
@@ -5357,11 +5725,100 @@
-
+Bison produces deterministic parsers that choose uniquely +when to reduce and which reduction to apply +based on a summary of the preceding input and on one extra token of lookahead. +As a result, normal Bison handles a proper subset of the family of +context-free languages. +Ambiguous grammars, since they have strings with more than one possible +sequence of reductions cannot have deterministic parsers in this sense. +The same is true of languages that require more than one symbol of +lookahead, since the parser lacks the information necessary to make a +decision at the point it must be made in a shift-reduce parser. +Finally, as previously mentioned (see section Mysterious Reduce/Reduce Conflicts), +there are languages where Bison's particular choice of how to +summarize the input seen so far loses necessary information. + + +
+When you use the `%glr-parser' declaration in your grammar file, +Bison generates a parser that uses a different algorithm, called +Generalized LR (or GLR). A Bison GLR parser uses the same basic +algorithm for parsing as an ordinary Bison parser, but behaves +differently in cases where there is a shift-reduce conflict that has not +been resolved by precedence rules (see section Operator Precedence) or a +reduce-reduce conflict. When a GLR parser encounters such a situation, it +effectively splits into a several parsers, one for each possible +shift or reduction. These parsers then proceed as usual, consuming +tokens in lock-step. Some of the stacks may encounter other conflicts +and split further, with the result that instead of a sequence of states, +a Bison GLR parsing stack is what is in effect a tree of states. + + +
+In effect, each stack represents a guess as to what the proper parse +is. Additional input may indicate that a guess was wrong, in which case +the appropriate stack silently disappears. Otherwise, the semantics +actions generated in each stack are saved, rather than being executed +immediately. When a stack disappears, its saved semantic actions never +get executed. When a reduction causes two stacks to become equivalent, +their sets of semantic actions are both saved with the state that +results from the reduction. We say that two stacks are equivalent +when they both represent the same sequence of states, +and each pair of corresponding states represents a +grammar symbol that produces the same segment of the input token +stream. + + +
+Whenever the parser makes a transition from having multiple +states to having one, it reverts to the normal LALR(1) parsing +algorithm, after resolving and executing the saved-up actions. +At this transition, some of the states on the stack will have semantic +values that are sets (actually multisets) of possible actions. The +parser tries to pick one of the actions by first finding one whose rule +has the highest dynamic precedence, as set by the `%dprec' +declaration. Otherwise, if the alternative actions are not ordered by +precedence, but there the same merging function is declared for both +rules by the `%merge' declaration, +Bison resolves and evaluates both and then calls the merge function on +the result. Otherwise, it reports an ambiguity. + + +
+It is possible to use a data structure for the GLR parsing tree that +permits the processing of any LALR(1) grammar in linear time (in the +size of the input), any unambiguous (not necessarily LALR(1)) grammar in +quadratic worst-case time, and any general (possibly ambiguous) +context-free grammar in cubic worst-case time. However, Bison currently +uses a simpler data structure that requires time proportional to the +length of the input times the maximum number of stacks required for any +prefix of the input. Thus, really ambiguous or non-deterministic +grammars can require exponential time and space to process. Such badly +behaving examples, however, are not generally of practical interest. +Usually, non-determinism in a grammar is local--the parser is "in +doubt" only for a few tokens at a time. Therefore, the current data +structure should generally be adequate. On LALR(1) portions of a +grammar, in particular, it is only slightly slower than with the default +Bison parser. + + + + +
@@ -5372,7 +5829,13 @@
- +Becaue Bison parsers have growing stacks, hitting the upper limit +usually results from using a right recursion instead of a left +recursion, See section Recursive Rules. + + +
+
By defining the macro YYMAXDEPTH
, you can control how deep the
parser stack can become before a stack overflow occurs. Define the
macro with a value that is an integer. This value is the maximum number
@@ -5390,24 +5853,32 @@
-
+
The default value of YYMAXDEPTH
, if you do not define it, is
10000.
-
+
You can control how much stack is allocated initially by defining the
macro YYINITDEPTH
. This value too must be a compile-time
constant integer. The default is 200.
+
+Because of semantical differences between C and C++, the LALR(1) parsers
+in C produced by Bison by compiled as C++ cannot grow. In this precise
+case (compiling a C parser as C++) you are suggested to grow
+YYINITDEPTH
. In the near future, a C++ output output will be
+provided which addresses this issue.
+
-
@@ -5428,7 +5899,7 @@
-
+
You can define how to recover from a syntax error by writing rules to
recognize the special token error
. This is a terminal symbol that
is always defined (you need not declare it) and reserved for error
@@ -5485,7 +5956,7 @@
-stmnt: error ';' /* on error, skip until ';' is read */ +stmnt: error ';' /* On error, skip until ';' is read. */
@@ -5527,7 +5998,7 @@
-
+
You can make error messages resume immediately by using the macro
yyerrok
in an action. If you do this in the error rule's action, no
error messages will be suppressed. This macro requires no arguments;
@@ -5535,7 +6006,7 @@
-
+
The previous look-ahead token is reanalyzed immediately after an error. If
this is unacceptable, then the macro yyclearin
may be used to clear
this token. Write the statement `yyclearin;' in the error rule's
@@ -5551,7 +6022,7 @@
-
+
The macro YYRECOVERING
stands for an expression that has the
value 1 when the parser is recovering from a syntax error, and 0 the
rest of the time. A value of 1 indicates that error messages are
@@ -5560,7 +6031,7 @@
-
The Bison paradigm is to parse tokens first, then group them into larger @@ -5577,7 +6048,7 @@ -
The C language has a context dependency: the way an identifier is used @@ -5673,9 +6144,9 @@ -
@@ -5724,19 +6195,18 @@
-The declaration of hexflag
shown in the C declarations section of
-the parser file is needed to make it accessible to the actions
-(see section The C Declarations Section). You must also write the code in yylex
-to obey the flag.
+The declaration of hexflag
shown in the prologue of the parser file
+is needed to make it accessible to the actions (see section The prologue).
+You must also write the code in yylex
to obey the flag.
-
Lexical tie-ins make strict demands on any error recovery rules you have. -See section Error Recovery. +See section Error Recovery.
@@ -5802,12 +6272,473 @@ -
- - - - +Developing a parser can be a challenge, especially if you don't +understand the algorithm (see section The Bison Parser Algorithm). Even so, sometimes a detailed description of the automaton +can help (see section Understanding Your Parser), or +tracing the execution of the parser can give some insight on why it +behaves improperly (see section Tracing Your Parser). + + + + +
+As documented elsewhere (see section The Bison Parser Algorithm) +Bison parsers are shift/reduce automata. In some cases (much more +frequent than one would hope), looking at this automaton is required to +tune or simply fix a parser. Bison provides two different +representation of it, either textually or graphically (as a VCG +file). + + +
+The textual file is generated when the options @option{--report} or +@option{--verbose} are specified, see See section Invoking Bison. Its name is made by removing `.tab.c' or `.c' from +the parser output file name, and adding `.output' instead. +Therefore, if the input file is `foo.y', then the parser file is +called `foo.tab.c' by default. As a consequence, the verbose +output file is called `foo.output'. + + +
+The following grammar file, `calc.y', will be used in the sequel: + + + +
+%token NUM STR +%left '+' '-' +%left '*' +%% +exp: exp '+' exp + | exp '-' exp + | exp '*' exp + | exp '/' exp + | NUM + ; +useless: STR; +%% ++ +
+@command{bison} reports: + + + +
+calc.y: warning: 1 useless nonterminal and 1 useless rule +calc.y:11.1-7: warning: useless nonterminal: useless +calc.y:11.8-12: warning: useless rule: useless: STR +calc.y contains 7 shift/reduce conflicts. ++ +
+When given @option{--report=state}, in addition to `calc.tab.c', it +creates a file `calc.output' with contents detailed below. The +order of the output and the exact presentation might vary, but the +interpretation is the same. + + +
+The first section includes details on conflicts that were solved thanks +to precedence and/or associativity: + + + +
+Conflict in state 8 between rule 2 and token '+' resolved as reduce. +Conflict in state 8 between rule 2 and token '-' resolved as reduce. +Conflict in state 8 between rule 2 and token '*' resolved as shift. +... ++ +
+The next section lists states that still have conflicts. + + + +
+State 8 contains 1 shift/reduce conflict. +State 9 contains 1 shift/reduce conflict. +State 10 contains 1 shift/reduce conflict. +State 11 contains 4 shift/reduce conflicts. ++ +
+ + + + + + +The next section reports useless tokens, nonterminal and rules. Useless +nonterminals and rules are removed in order to produce a smaller parser, +but useless tokens are preserved, since they might be used by the +scanner (note the difference between "useless" and "not used" +below): + + + +
+Useless nonterminals: + useless + +Terminals which are not used: + STR + +Useless rules: +#6 useless: STR; ++ +
+The next section reproduces the exact grammar that Bison used: + + + +
+Grammar + + Number, Line, Rule + 0 5 $accept -> exp $end + 1 5 exp -> exp '+' exp + 2 6 exp -> exp '-' exp + 3 7 exp -> exp '*' exp + 4 8 exp -> exp '/' exp + 5 9 exp -> NUM ++ +
+and reports the uses of the symbols: + + + +
+Terminals, with rules where they appear + +$end (0) 0 +'*' (42) 3 +'+' (43) 1 +'-' (45) 2 +'/' (47) 4 +error (256) +NUM (258) 5 + +Nonterminals, with rules where they appear + +$accept (8) + on left: 0 +exp (9) + on left: 1 2 3 4 5, on right: 0 1 2 3 4 ++ +
+ + + +Bison then proceeds onto the automaton itself, describing each state +with it set of items, also known as pointed rules. Each +item is a production rule together with a point (marked by `.') +that the input cursor. + + + +
+state 0 + + $accept -> . exp $ (rule 0) + + NUM shift, and go to state 1 + + exp go to state 2 ++ +
+This reads as follows: "state 0 corresponds to being at the very
+beginning of the parsing, in the initial rule, right before the start
+symbol (here, exp
). When the parser returns to this state right
+after having reduced a rule that produced an exp
, the control
+flow jumps to state 2. If there is no such transition on a nonterminal
+symbol, and the lookahead is a NUM
, then this token is shifted on
+the parse stack, and the control flow jumps to state 1. Any other
+lookahead triggers a parse error."
+
+
+
+
+
+
+
+Even though the only active rule in state 0 seems to be rule 0, the
+report lists NUM
as a lookahead symbol because NUM
can be
+at the beginning of any rule deriving an exp
. By default Bison
+reports the so-called core or kernel of the item set, but if
+you want to see more detail you can invoke @command{bison} with
+@option{--report=itemset} to list all the items, include those that can
+be derived:
+
+
+
+
+state 0 + + $accept -> . exp $ (rule 0) + exp -> . exp '+' exp (rule 1) + exp -> . exp '-' exp (rule 2) + exp -> . exp '*' exp (rule 3) + exp -> . exp '/' exp (rule 4) + exp -> . NUM (rule 5) + + NUM shift, and go to state 1 + + exp go to state 2 ++ +
+In the state 1... + + + +
+state 1 + + exp -> NUM . (rule 5) + + $default reduce using rule 5 (exp) ++ +
+the rule 5, `exp: NUM;', is completed. Whatever the lookahead +(`$default'), the parser will reduce it. If it was coming from +state 0, then, after this reduction it will return to state 0, and will +jump to state 2 (`exp: go to state 2'). + + + +
+state 2 + + $accept -> exp . $ (rule 0) + exp -> exp . '+' exp (rule 1) + exp -> exp . '-' exp (rule 2) + exp -> exp . '*' exp (rule 3) + exp -> exp . '/' exp (rule 4) + + $ shift, and go to state 3 + '+' shift, and go to state 4 + '-' shift, and go to state 5 + '*' shift, and go to state 6 + '/' shift, and go to state 7 ++ +
+In state 2, the automaton can only shift a symbol. For instance, +because of the item `exp -> exp . '+' exp', if the lookahead if +`+', it will be shifted on the parse stack, and the automaton +control will jump to state 4, corresponding to the item `exp -> exp +'+' . exp'. Since there is no default action, any other token than +those listed above will trigger a parse error. + + +
+The state 3 is named the final state, or the accepting +state: + + + +
+state 3 + + $accept -> exp $ . (rule 0) + + $default accept ++ +
+the initial rule is completed (the start symbol and the end +of input were read), the parsing exits successfully. + + +
+The interpretation of states 4 to 7 is straightforward, and is left to +the reader. + + + +
+state 4 + + exp -> exp '+' . exp (rule 1) + + NUM shift, and go to state 1 + + exp go to state 8 + +state 5 + + exp -> exp '-' . exp (rule 2) + + NUM shift, and go to state 1 + + exp go to state 9 + +state 6 + + exp -> exp '*' . exp (rule 3) + + NUM shift, and go to state 1 + + exp go to state 10 + +state 7 + + exp -> exp '/' . exp (rule 4) + + NUM shift, and go to state 1 + + exp go to state 11 ++ +
+As was announced in beginning of the report, `State 8 contains 1 +shift/reduce conflict': + + + +
+state 8 + + exp -> exp . '+' exp (rule 1) + exp -> exp '+' exp . (rule 1) + exp -> exp . '-' exp (rule 2) + exp -> exp . '*' exp (rule 3) + exp -> exp . '/' exp (rule 4) + + '*' shift, and go to state 6 + '/' shift, and go to state 7 + + '/' [reduce using rule 1 (exp)] + $default reduce using rule 1 (exp) ++ +
+Indeed, there are two actions associated to the lookahead `/': +either shifting (and going to state 7), or reducing rule 1. The +conflict means that either the grammar is ambiguous, or the parser lacks +information to make the right decision. Indeed the grammar is +ambiguous, as, since we did not specify the precedence of `/', the +sentence `NUM + NUM / NUM' can be parsed as `NUM + (NUM / +NUM)', which corresponds to shifting `/', or as `(NUM + NUM) / +NUM', which corresponds to reducing rule 1. + + +
+Because in LALR(1) parsing a single decision can be made, Bison +arbitrarily chose to disable the reduction, see section Shift/Reduce Conflicts. Discarded actions are reported in between +square brackets. + + +
+Note that all the previous states had a single possible action: either +shifting the next token and going to the corresponding state, or +reducing a single rule. In the other cases, i.e., when shifting +and reducing is possible or when several reductions are +possible, the lookahead is required to select the action. State 8 is +one such state: if the lookahead is `*' or `/' then the action +is shifting, otherwise the action is reducing rule 1. In other words, +the first two items, corresponding to rule 1, are not eligible when the +lookahead is `*', since we specified that `*' has higher +precedence that `+'. More generally, some items are eligible only +with some set of possible lookaheads. When run with +@option{--report=lookahead}, Bison specifies these lookaheads: + + + +
+state 8 + + exp -> exp . '+' exp [$, '+', '-', '/'] (rule 1) + exp -> exp '+' exp . [$, '+', '-', '/'] (rule 1) + exp -> exp . '-' exp (rule 2) + exp -> exp . '*' exp (rule 3) + exp -> exp . '/' exp (rule 4) + + '*' shift, and go to state 6 + '/' shift, and go to state 7 + + '/' [reduce using rule 1 (exp)] + $default reduce using rule 1 (exp) ++ +
+The remaining states are similar: + + + +
+state 9 + + exp -> exp . '+' exp (rule 1) + exp -> exp . '-' exp (rule 2) + exp -> exp '-' exp . (rule 2) + exp -> exp . '*' exp (rule 3) + exp -> exp . '/' exp (rule 4) + + '*' shift, and go to state 6 + '/' shift, and go to state 7 + + '/' [reduce using rule 2 (exp)] + $default reduce using rule 2 (exp) + +state 10 + + exp -> exp . '+' exp (rule 1) + exp -> exp . '-' exp (rule 2) + exp -> exp . '*' exp (rule 3) + exp -> exp '*' exp . (rule 3) + exp -> exp . '/' exp (rule 4) + + '/' shift, and go to state 7 + + '/' [reduce using rule 3 (exp)] + $default reduce using rule 3 (exp) + +state 11 + + exp -> exp . '+' exp (rule 1) + exp -> exp . '-' exp (rule 2) + exp -> exp . '*' exp (rule 3) + exp -> exp . '/' exp (rule 4) + exp -> exp '/' exp . (rule 4) + + '+' shift, and go to state 4 + '-' shift, and go to state 5 + '*' shift, and go to state 6 + '/' shift, and go to state 7 + + '+' [reduce using rule 4 (exp)] + '-' [reduce using rule 4 (exp)] + '*' [reduce using rule 4 (exp)] + '/' [reduce using rule 4 (exp)] + $default reduce using rule 4 (exp) ++ +
+Observe that state 11 contains conflicts due to the lack of precedence +of `/' wrt `+', `-', and `*', but also because the +associativity of `/' is not specified. + + + + +
@@ -5816,18 +6747,44 @@
-To enable compilation of trace facilities, you must define the macro
-YYDEBUG
when you compile the parser. You could use
+There are several means to enable compilation of trace facilities:
+
+
+
YYDEBUG
+YYDEBUG
to a nonzero value when you compile the
+parser. This is compliant with POSIX Yacc. You could use
`-DYYDEBUG=1' as a compiler option or you could put `#define
-YYDEBUG 1' in the C declarations section of the grammar file
-(see section The C Declarations Section). Alternatively, use the `-t' option when
-you run Bison (see section Invoking Bison). We always define YYDEBUG
so that
-debugging is always possible.
+YYDEBUG 1' in the prologue of the grammar file (see section The prologue).
+
+%debug
directive (see section Bison Declaration Summary). This is a Bison extension, which will prove
+useful when Bison will output parsers for languages that don't use a
+preprocessor. Useless POSIX and Yacc portability matter to you, this is
+the preferred solution.
+
-The trace facility uses stderr
, so you must add #include
-<stdio.h>
to the C declarations section unless it is already there.
+We suggest that you always enable the debug option so that debugging is
+always possible.
+
+
+
+The trace facility outputs messages with macro calls of the form
+YYFPRINTF (stderr, format, args)
where
+format and args are the usual printf
format and
+arguments. If you define YYDEBUG
to a nonzero value but do not
+define YYFPRINTF
, <stdio.h>
is automatically included
+and YYPRINTF
is defined to fprintf
.
@@ -5852,7 +6809,7 @@
To make sense of this information, it helps to refer to the listing file -produced by the Bison `-v' option (see section Invoking Bison). This file -shows the meaning of each state in terms of positions in various rules, and -also what each state will do with each possible input token. As you read -the successive trace messages, you can see that the parser is functioning -according to its specification in the listing file. Eventually you will -arrive at the place where something undesirable happens, and you will see -which parts of the grammar are to blame. +produced by the Bison `-v' option (see section Invoking Bison). This file shows the meaning of each state in terms of +positions in various rules, and also what each state will do with each +possible input token. As you read the successive trace messages, you +can see that the parser is functioning according to its specification in +the listing file. Eventually you will arrive at the place where +something undesirable happens, and you will see which parts of the +grammar are to blame.
@@ -5880,7 +6837,7 @@
-
+
The debugging information normally gives the token type of each token
read, but not its semantic value. You can optionally define a macro
named YYPRINT
to provide a way to print the value. If you define
@@ -5891,7 +6848,7 @@
Here is an example of YYPRINT
suitable for the multi-function
-calculator (see section Declarations for mfcalc
):
+calculator (see section Declarations for mfcalc
):
@@ -5910,11 +6867,11 @@
-
@@ -5931,10 +6888,11 @@ `.y'. The parser file's name is made by replacing the `.y' with `.tab.c'. Thus, the `bison foo.y' filename yields `foo.tab.c', and the `bison hack/foo.y' filename yields -`hack/foo.tab.c'. It's is also possible, in case you are writting +`hack/foo.tab.c'. It's also possible, in case you are writing C++ code instead of C in your grammar file, to name it `foo.ypp' -or `foo.y++'. Then, the output files will take an extention like -the given one as input (repectively `foo.tab.cpp' and `foo.tab.c++'). +or `foo.y++'. Then, the output files will take an extension like +the given one as input (respectively `foo.tab.cpp' and +`foo.tab.c++'). This feature takes effect with all options that manipulate filenames like `-o' or `-d'. @@ -5949,12 +6907,12 @@
-will produce `infile.tab.cxx' and `infile.tab.hxx'. and +will produce `infile.tab.cxx' and `infile.tab.hxx', and
-bison -d infile.y -o output.c++ +bison -d -o output.c++ infile.y
@@ -5963,7 +6921,7 @@ -
Bison supports both traditional single-letter options and mnemonic long @@ -6000,14 +6958,13 @@
bison -y $*@@ -6031,26 +6988,20 @@
YYDEBUG
into the parser file, so
-that the debugging facilities are compiled. See section Debugging Your Parser.
+In the parser file, define the macro YYDEBUG
to 1 if it is not
+already defined, so that the debugging facilities are compiled.
+See section Tracing Your Parser.
%locactions
was specified. See section Bison Declaration Summary.
+Pretend that %locations
was specified. See section Bison Declaration Summary.
yyparse
, yylex
, yyerror
, yynerrs
,
-yylval
, yychar
and yydebug
.
-
-For example, if you use `-p c', the names become cparse
,
-clex
, and so on.
-
-See section Multiple Parsers in the Same Program.
+Pretend that %name-prefix="prefix"
was specified.
+See section Bison Declaration Summary.
%no_parser
was specified. See section Bison Declaration Summary.
+Pretend that %no-parser
was specified. See section Bison Declaration Summary.
%token_table
was specified. See section Bison Declaration Summary.
+Pretend that %token-table
was specified. See section Bison Declaration Summary.
@@ -6083,23 +7034,50 @@
%verbose
was specified, i.e., write an extra output
+%defines
was specified, i.e., write an extra output
file containing macro definitions for the token type names defined in
the grammar and the semantic value type YYSTYPE
, as well as a few
-extern
variable declarations. See section Bison Declaration Summary.
+extern
variable declarations. See section Bison Declaration Summary.
%verbose
was specified, i.e, specify prefix to use
+for all Bison output file names. See section Bison Declaration Summary.
+
+state
+lookahead
+state
and augments the description of the automaton with
+each rule's lookahead set.
+
+itemset
+state
and augments the description of the automaton with
+the full set of items for each state, instead of its core only.
+%verbose
was specified, i.e, write an extra output
file containing verbose descriptions of the grammar and
-parser. See section Bison Declaration Summary, for more.
+parser. See section Bison Declaration Summary.
--Here is a list of environment variables which affect the way Bison -runs. - - -
BISON_SIMPLE
to the path of the file will
-cause Bison to use that copy instead.
-
-When the `%semantic_parser' declaration is used, Bison copies from
-a file called `bison.hairy' instead. The location of this file can
-also be specified or overridden in a similar fashion, with the
-BISON_HAIRY
environment variable.
-
-Here is a list of options, alphabetized by long option, to help you find @@ -6175,10 +7120,10 @@ -
@@ -6215,14 +7160,77 @@ -
+Several questions about Bison come up occasionally. Here some of them +are addressed. + + + + +
+My parser returns with error with a `parser stack overflow' +message. What can I do? ++ +
+This question is already addressed elsewhere, See section Recursive Rules. + + + + +
@$
+@n
+$$
+$n
+$accept
+$end
+$undefined
+yylex
are mapped. It cannot be used in the grammar, rather, use
+error
.
+
error
error
becomes the current look-ahead token. Actions
corresponding to error
are then executed, and the look-ahead
token is reset to the token that originally caused the violation.
-See section Error Recovery.
+See section Error Recovery.
YYABORT
yyparse
return 1 immediately. The error reporting
-function yyerror
is not called. See section The Parser Function yyparse
.
+function yyerror
is not called. See section The Parser Function yyparse
.
YYACCEPT
yyparse
return 0 immediately.
-See section The Parser Function yyparse
.
+See section The Parser Function yyparse
.
YYBACKUP
YYDEBUG
+YYERROR
yyerror
and then perform normal error recovery if possible
-(see section Error Recovery), or (if recovery is impossible) make
-yyparse
return 1. See section Error Recovery.
+(see section Error Recovery), or (if recovery is impossible) make
+yyparse
return 1. See section Error Recovery.
YYERROR_VERBOSE
YYINITDEPTH
YYLEX_PARAM
yyparse
to pass to yylex
. See section Calling Conventions for Pure Parsers.
+yyparse
to pass to yylex
. See section Calling Conventions for Pure Parsers.
YYLTYPE
yylloc
; a structure with four
-members. See section Data Type of Locations.
+members. See section Data Type of Locations.
yyltype
YYMAXDEPTH
YYPARSE_PARAM
yyparse
should
-accept. See section Calling Conventions for Pure Parsers.
+accept. See section Calling Conventions for Pure Parsers.
YYRECOVERING
YYSTACK_USE_ALLOCA
alloca
. If defined to `0',
+Macro used to control the use of alloca
. If defined to `0',
the parser will not use alloca
but malloc
when trying to
-grow its internal stacks. Do not define YYSTACK_USE_ALLOCA
+grow its internal stacks. Do not define YYSTACK_USE_ALLOCA
to anything else.
YYSTYPE
int
by default.
-See section Data Types of Semantic Values.
+See section Data Types of Semantic Values.
yychar
yyparse
.) Error-recovery rule actions may examine this variable.
-See section Special Features for Use in Actions.
+See section Special Features for Use in Actions.
yyclearin
yydebug
yydebug
is given a nonzero value, the parser will output information on input
-symbols and parser action. See section Debugging Your Parser.
+symbols and parser action. See section Tracing Your Parser.
yyerrok
yyerror
yyparse
on error. The
function receives one argument, a pointer to a character string
-containing an error message. See section The Error Reporting Function yyerror
.
+containing an error message. See section The Error Reporting Function yyerror
.
yylex
yylex
.
+User-supplied lexical analyzer function, called with no arguments to get
+the next token. See section The Lexical Analyzer Function yylex
.
yylval
yylex
should place the semantic
value associated with a token. (In a pure parser, it is a local
variable within yyparse
, and its address is passed to
-yylex
.) See section Semantic Values of Tokens.
+yylex
.) See section Semantic Values of Tokens.
yylloc
yyparse
, and its address is passed to
yylex
.) You can ignore this variable if you don't use the
-`@' feature in the grammar actions. See section Textual Positions of Tokens.
+`@' feature in the grammar actions. See section Textual Positions of Tokens.
yynerrs
yyparse
.)
-See section The Error Reporting Function yyerror
.
+See section The Error Reporting Function yyerror
.
yyparse
yyparse
.
+parsing. See section The Parser Function yyparse
.
%debug
%defines
%dprec
+%file-prefix="prefix"
+%glr-parser
+%left
%merge
+%name-prefix="prefix"
+%no_lines
+%no-lines
#line
directives in the
-parser file. See section Bison Declaration Summary.
+parser file. See section Bison Declaration Summary.
%nonassoc
%output="filename"
+%prec
%pure_parser
+%pure-parser
%right
%start
%token
%token_table
+%token-table
%type
%union
@@ -6442,14 +7482,14 @@
yylex
.
+See section The Lexical Analyzer Function yylex
.
mfcalc
.
+information in repeated uses of a symbol. See section Multi-Function Calculator: mfcalc
.
- + Version 1.1, March 2000 @@ -7065,7 +8113,7 @@ -
To use this License in a document you have written, include a copy of @@ -7101,7 +8149,7 @@ -
Jump to: @@ -7127,6 +8175,8 @@ - i - +k +- l - m @@ -7137,6 +8187,8 @@ - p - +q +- r - s @@ -7155,295 +8207,322 @@
calc
-calc
+else
-else
+else
, dangling
-else
, dangling
+ltcalc
+ltcalc
mfcalc
-mfcalc
+rpcalc
-rpcalc
+-This document was generated on 4 November 2001 using +This document was generated on 9 November 2002 using texi2html 1.56k. Index: ossp-adm/autotools/bison_toc.html RCS File: /v/ossp/cvs/ossp-adm/autotools/bison_toc.html,v co -q -kk -p'1.1' '/v/ossp/cvs/ossp-adm/autotools/bison_toc.html,v' | diff -u /dev/null - -L'ossp-adm/autotools/bison_toc.html' 2>/dev/null --- ossp-adm/autotools/bison_toc.html +++ - 2025-04-19 11:03:21.559928847 +0200 @@ -0,0 +1,175 @@ + +
+ + ++
+
+This document was generated on 9 November 2002 using +texi2html 1.56k. + + Index: ossp-adm/autotools/flex.html RCS File: /v/ossp/cvs/ossp-adm/autotools/flex.html,v rcsdiff -q -kk '-r1.1' '-r1.2' -u '/v/ossp/cvs/ossp-adm/autotools/flex.html,v' 2>/dev/null --- flex.html 2002/07/10 08:46:25 1.1 +++ flex.html 2002/11/09 14:28:38 1.2 @@ -1,76 +1,147 @@
- + -
-
-flex
-is a tool for generating
-scanners.
-A scanner is a program which recognizes lexical patterns in text.
-The
-flex
-program
-reads
-the given input files, or its standard input if no file names are given,
-for a description of a scanner to generate. The description is in
-the form of pairs
-of regular expressions and C code, called
-rules. flex
-generates as output a C source file,
-`lex.yy.c' by default,
-which defines a routine
-yylex().
-This file is compiled and linked with the
-flex runtime library
-library to produce an executable. When the executable is run,
-it analyzes its input for occurrences
-of the regular expressions. Whenever it finds one, it executes
-the corresponding C code.
+
+
+
+
+The flex manual is placed under the same licensing conditions as the +rest of flex: + + +
+Copyright (C) 1990, 1997 The Regents of the University of California. +All rights reserved. + + +
+This code is derived from software contributed to Berkeley by +Vern Paxson. + + +
+The United States Government has rights in this work pursuant +to contract no. DE-AC03-76SF00098 between the United States +Department of Energy and the University of California. + + +
+Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + + +
+Neither the name of the University nor the names of its contributors +may be used to endorse or promote products derived from this software +without specific prior written permission. + + +
+THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. + + + +
+If you have problems with flex
or think you have found a bug,
+please send mail detailing your problem to
+help-flex@gnu.org. Patches are always welcome.
-
+
+flex
is a tool for generating scanners. A scanner is a
+program which recognizes lexical patterns in text. The flex
+program reads the given input files, or its standard input if no file
+names are given, for a description of a scanner to generate. The
+description is in the form of pairs of regular expressions and C code,
+called rules. flex
generates as output a C source file,
+`lex.yy.c' by default, which defines a routine yylex()
.
+This file can be compiled and linked with the flex runtime library to
+produce an executable. When the executable is run, it analyzes its
+input for occurrences of the regular expressions. Whenever it finds
+one, it executes the corresponding C code.
+
+
+
+
+
First some simple examples to get the flavor of how one uses
flex
.
-The following
-flex
-input specifies a scanner which whenever it encounters the string
-`username' will replace it with the user's login name:
+
+The following flex
input specifies a scanner which, when it
+encounters the string `username' will replace it with the user's
+login name:
+
+
+
+
@verbatim %% username printf( "%s", getlogin() ); - +
-
-By default, any text not matched by a
-flex
-scanner
-is copied to the output, so the net effect of this scanner is
-to copy its input file to its output with each occurrence
-of `username' expanded.
-In this input, there is just one rule. `username' is the
-pattern
-and the `printf' is the
-action.
-The `%%' symbol marks the beginning of the rules.
+
+
+By default, any text not matched by a flex
scanner is copied to
+the output, so the net effect of this scanner is to copy its input file
+to its output with each occurrence of `username' expanded. In this
+input, there is just one rule. `username' is the pattern and
+the `printf' is the action. The `%%' symbol marks the
+beginning of the rules.
@@ -78,7 +149,7 @@
@verbatim @@ -98,18 +169,15 @@
-This scanner counts the number of characters and the number
-of lines in its input (it produces no output other than the
-final report on the counts). The first line
-declares two globals, num_lines
and num_chars
, which are accessible
-both inside
-yylex()
-and in the
-main()
-routine declared after the second `%%'. There are two rules, one
-which matches a newline (`\n') and increments both the line count and
-the character count, and one which matches any character other than
-a newline (indicated by the `.' regular expression).
+This scanner counts the number of characters and the number of lines in
+its input. It produces no output other than the final report on the
+character and line counts. The first line declares two globals,
+num_lines
and num_chars
, which are accessible both inside
+yylex()
and in the main()
routine declared after the
+second `%%'. There are two rules, one which matches a newline
+(`\n') and increments both the line count and the character count,
+and one which matches any character other than a newline (indicated by
+the `.' regular expression).
@@ -117,7 +185,7 @@
@verbatim @@ -168,16 +236,15 @@ yyin = fopen( argv[0], "r" ); else yyin = stdin; - + yylex(); }
-This is the beginnings of a simple scanner for a language like -Pascal. It identifies different types of -tokens -and reports on what it has seen. +This is the beginnings of a simple scanner for a language like Pascal. +It identifies different types of tokens and reports on what it has +seen.
@@ -187,24 +254,22 @@ -
-The
-flex
-input file consists of three sections, separated by a line with just
-`%%'
-in it:
+The flex
input file consists of three sections, separated by a
+line containing only `%%'.
@verbatim @@ -217,25 +282,19 @@ -Format of the Definitions Section
-Format of the Definitions Section
-The -definitions -section contains declarations of simple -name + + +The definitions section contains declarations of simple name definitions to simplify the scanner specification, and declarations of -start conditions, -which are explained in a later section. +start conditions, which are explained in a later section.
-The `name' is a word beginning with a letter or an underscore (`_') -followed by zero or more letters, digits, `_', or `-' (dash). -The definition is taken to begin at the first non-whitespace character -following the name and continuing to the end of the line. -The definition can subsequently be referred to using `{name}', which -will expand to `(definition)'. For example, +The `name' is a word beginning with a letter or an underscore +(`_') followed by zero or more letters, digits, `_', or +`-' (dash). The definition is taken to begin at the first +non-whitespace character following the name and continuing to the end of +the line. The definition can subsequently be referred to using +`{name}', which will expand to `(definition)'. For example,
@verbatim @@ -264,15 +324,13 @@
-Defines `DIGIT' to be a regular expression which matches a -single digit, and -`ID' to be a regular expression which matches a letter -followed by zero-or-more letters-or-digits. -A subsequent reference to +Defines `DIGIT' to be a regular expression which matches a single +digit, and `ID' to be a regular expression which matches a letter +followed by zero-or-more letters-or-digits. A subsequent reference to
@verbatim @@ -290,46 +348,36 @@
-and matches one-or-more digits followed by a '.' followed -by zero-or-more digits. +and matches one-or-more digits followed by a `.' followed by +zero-or-more digits.
+ An unindented comment (i.e., a line beginning with `/*') is copied verbatim to the output up to the next `*/'.
- - - - -Any -indented -text or text enclosed in -`%{' -and -`%}' -is also copied verbatim to the output (with the %{ and %} symbols removed). -The %{ and %} symbols must appear unindented on lines by themselves. - + + + +Any indented text or text enclosed in `%{' and `%}' +is also copied verbatim to the output (with the %{ and %} symbols +removed). The %{ and %} symbols must appear unindented on lines by +themselves. -
-The
-rules
-section of the
-flex
-input contains a series of rules of the form:
+
+
+The rules section of the flex
input contains a series of
+rules of the form:
@@ -341,93 +389,78 @@
where the pattern must be unindented and the action must begin on the same line. +See section Patterns, for a further description of patterns and actions.
-See section Patterns, for a further description of patterns and actions. +In the rules section, any indented or %{ %} enclosed text appearing +before the first rule may be used to declare variables which are local +to the scanning routine and (after the declarations) code which is to be +executed whenever the scanning routine is entered. Other indented or +%{ %} text in the rule section is still copied to the output, but its +meaning is not well-defined and it may well cause compile-time errors +(this feature is present for @acronym{POSIX} compliance. See section Incompatibilities with Lex and Posix, for other such features).
-In the rules section, -any indented or %{ %} enclosed text appearing before the -first rule may be used to declare variables -which are local to the scanning routine and (after the declarations) -code which is to be executed whenever the scanning routine is entered. -Other indented or %{ %} text in the rule section is still copied to the output, -but its meaning is not well-defined and it may well cause compile-time -errors (this feature is present for -POSIX -compliance. See section Incompatibilities with Lex and Posix, for other such features). - - -
-Any -indented -text or text enclosed in -`%{' -and -`%}' +Any indented text or text enclosed in `%{' and `%}' is copied verbatim to the output (with the %{ and %} symbols removed). The %{ and %} symbols must appear unindented on lines by themselves. -
-The user code section is simply copied to -`lex.yy.c' -verbatim. -It is used for companion routines which call or are called -by the scanner. The presence of this section is optional; -if it is missing, the second -`%%' -in the input file may be skipped, too. - + + +The user code section is simply copied to `lex.yy.c' verbatim. It +is used for companion routines which call or are called by the scanner. +The presence of this section is optional; if it is missing, the second +`%%' in the input file may be skipped, too. -
+ Flex supports C-style comments, that is, anything between /* and */ is -considered a comment. Whenever flex encounters a comment, it copies -the entire comment verbatim to the generated source code. Comments -may appear just about anywhere, but with the following exceptions: +considered a comment. Whenever flex encounters a comment, it copies the +entire comment verbatim to the generated source code. Comments may +appear just about anywhere, but with the following exceptions:
-If you want to follow a simple rule, then always begin a comment on a new line, -with one or more whitespace characters before the initial `/*'). -This rule will work anywhere in the input file. +If you want to follow a simple rule, then always begin a comment on a +new line, with one or more whitespace characters before the initial +`/*'). This rule will work anywhere in the input file.
-All the comments in the following example are OK: +All the comments in the following example are valid:
@verbatim @@ -456,19 +489,18 @@ -Patterns
-Patterns
-The patterns in the input are written using an extended set of regular -expressions. These are: + + +The patterns in the input (see section Format of the Rules Section) are written using an +extended set of regular expressions. These are:
flex
's notion of "newline" is exactly
whatever the C compiler used to compile flex
interprets `\n' as; in particular, on some DOS
systems you must either filter out `\r's in the
input yourself, or explicitly use `r/\r\n' for `r$'.
-
+
s
(see section Start Conditions for discussion of start conditions).
s1
, s2
, or s3
.
s1
or s2
@@ -644,7 +675,7 @@
- + The regular expressions listed above are grouped according to precedence, from highest precedence at the top to lowest at the bottom. Those grouped together have equal precedence (see special note on the @@ -653,7 +684,7 @@
@verbatim @@ -671,11 +702,11 @@
-since the '*' operator has higher precedence than concatenation, and -concatenation higher than alternation ('|'). This pattern therefore -matches either the string `foo' or the string -`ba' followed by zero-or-more r's. To match `foo' or -zero-or-more repetitions of the string `bar', use: +since the `*' operator has higher precedence than concatenation, +and concatenation higher than alternation (`|'). This pattern +therefore matches either the string `foo' or the +string `ba' followed by zero-or-more `r''s. To match +`foo' or zero-or-more repetitions of the string `bar', use: @@ -690,7 +721,7 @@
@verbatim @@ -698,7 +729,7 @@
- + In addition to characters and ranges of characters, character classes can also contain character class expressions. These are expressions enclosed inside `[': and `:]' delimiters (which @@ -708,7 +739,7 @@
@verbatim @@ -719,19 +750,12 @@
-These expressions all designate a set of characters equivalent to
-the corresponding standard C
-isXXX
-function. For example,
-`[:alnum:]'
-designates those characters for which
-isalnum()
-returns true - i.e., any alphabetic or numeric character.
-Some systems don't provide
-isblank()
,
-so flex defines
-`[:blank:]'
-as a blank or a tab.
+These expressions all designate a set of characters equivalent to the
+corresponding standard C isXXX
function. For example,
+`[:alnum:]' designates those characters for which isalnum()
+returns true - i.e., any alphabetic or numeric character. Some systems
+don't provide isblank()
, so flex defines `[:blank:]' as a
+blank or a tab.
@@ -739,8 +763,8 @@
@verbatim @@ -751,35 +775,35 @@
- + If your scanner is case-insensitive (the `-i' flag), then `[:upper:]' and `[:lower:]' are equivalent to `[:alpha:]'.
-Some notes on patterns: - - - - +Some notes on patterns are in order.
@verbatim @@ -807,7 +831,7 @@ The following will result in `$' or `^' being treated as a normal character: - +@verbatim @@ -817,9 +841,9 @@ If the desired meaning is a `foo' or a `bar'-followed-by-a-newline, the following could be used (the -special|
action is explained below, see section Actions): +special|
action is explained below, see section Actions): - +@verbatim @@ -827,18 +851,21 @@ bar$ /* action goes here */-A similar trick will work for matching a foo or a -bar-at-the-beginning-of-a-line. +A similar trick will work for matching a `foo' or a +`bar'-at-the-beginning-of-a-line.
+ + + + + + When the generated scanner is run, it analyzes its input looking for strings which match any of its patterns. If it finds more than one match, it takes the one matching the most text (for trailing context @@ -849,26 +876,26 @@
+
+
+
Once the match is determined, the text corresponding to the match
(called the token) is made available in the global character
-pointer yytext
, and its length in the global integer yyleng
.
-The action corresponding to the matched pattern is then executed
-(see section Actions), and then the remaining input is scanned for another
-match.
+pointer yytext
, and its length in the global integer
+yyleng
. The action corresponding to the matched pattern is
+then executed (see section Actions), and then the remaining input is scanned
+for another match.
-
-If no match is found, then the
-default rule
-is executed: the next character in the input is considered matched and
-copied to the standard output. Thus, the simplest valid
-flex
-input is:
+
+If no match is found, then the default rule is executed: the next
+character in the input is considered matched and copied to the standard
+output. Thus, the simplest valid flex
input is:
@verbatim @@ -876,20 +903,17 @@
-which generates a scanner that simply copies its input (one character -at a time) to its output. - - -
- - - +which generates a scanner that simply copies its input (one character at +a time) to its output.
-
-Note that yytext
can be defined in two different ways: either as a
-character pointer or as a character array. You can
+
+
+
+
+Note that yytext
can be defined in two different ways: either as
+a character pointer or as a character array. You can
control which definition flex
uses by including one of the
special directives %pointer
or %array
in the first
(definitions) section of your flex input. The default is
@@ -898,26 +922,19 @@
%pointer
is substantially faster scanning and no buffer overflow
when matching very large tokens (unless you run out of dynamic memory).
The disadvantage is that you are restricted in how your actions can
-modify yytext
(see section Actions), and calls to the unput()
+modify yytext
(see section Actions), and calls to the unput()
function destroys the present contents of yytext
, which can be a
considerable porting headache when moving between different lex
versions.
-The advantage of
-%array
-is that you can then modify
-yytext
-to your heart's content, and calls to
-unput()
-do not destroy
-yytext
-(see section Actions). Furthermore, existing
-lex
-programs sometimes access
-yytext
-externally using declarations of the form:
+
+The advantage of %array
is that you can then modify yytext
+to your heart's content, and calls to unput()
do not destroy
+yytext
(see section Actions). Furthermore, existing lex
+programs sometimes access yytext
externally using declarations of
+the form:
@@ -940,23 +957,23 @@
large tokens. While this means your %pointer
scanner can
accommodate very large tokens (such as matching entire blocks of
comments), bear in mind that each time the scanner must resize
-yytext
it also must rescan the entire token from the beginning, so
-matching such tokens can prove slow. yytext
presently does
+yytext
it also must rescan the entire token from the beginning,
+so matching such tokens can prove slow. yytext
presently does
not dynamically grow if a call to unput()
results in too
much text being pushed back; instead, a run-time error results.
-
+
Also note that you cannot use %array
with C++ scanner classes
-(see section Generating C++ Scanners).
+(see section Generating C++ Scanners).
-
@@ -969,7 +986,7 @@
@verbatim @@ -988,8 +1005,8 @@@verbatim @@ -999,11 +1016,11 @@@@ -1032,17 +1049,17 @@
- + Actions are free to modify
yytext
except for lengthening it (adding characters to its end--these will overwrite later characters in the input stream). This however does not apply when using%array
-(see section How the Input Is Matched). In that case,yytext
may be freely modified in +(see section How the Input Is Matched). In that case,yytext
may be freely modified in any way.- - + + Actions are free to modify
yyleng
except they should not do so if the action also includes use of @@ -1051,7 +1068,7 @@@@ -1063,30 +1080,30 @@
ECHO
BEGIN
REJECT
yytext
and yyleng
set
+described above in section How the Input Is Matched, and yytext
and yyleng
set
up appropriately. It may either be one which matched as much text as
the originally chosen rule but came later in the flex
input file,
or one which matched less text. For example, the following will both
count the words in the input and call the routine special()
whenever `frob' is seen:
-
-
+
+
@verbatim @@ -1104,7 +1121,7 @@ example, when the following scanner scans the token `abcd', it will write `abcdabcaba' to the output: - +@verbatim @@ -1130,13 +1147,13 @@ `-Cf' or `-CF' -options (see section Invoking Flex). +options (see section Scanner Options). Note also that unlike the other special actions,REJECT
is a branch. code immediately following it in the action will not be executed. - +
yymore()
@verbatim @@ -1174,7 +1191,7 @@- +
yyless(n)
returns all but the firstn
characters of the current token back to the input stream, where they will be rescanned when the scanner looks for the next match.yytext
and @@ -1184,9 +1201,9 @@@verbatim @@ -1212,8 +1229,8 @@- - + +
unput(c)
puts the characterc
@@ -1223,7 +1240,7 @@@verbatim @@ -1246,8 +1263,8 @@@@ -1267,25 +1284,25 @@ (as in the above example), you must either first copy it elsewhere, or build your scanner using
%array
-instead (see section How the Input Is Matched). +instead (see section How the Input Is Matched).- - + + Finally, note that you cannot put back `EOF' to attempt to mark the input stream with an end-of-file.
- +
input()
reads the next character from the input stream. For example, the following is one way to eat up C comments:@verbatim @@ -1317,7 +1334,7 @@- + (Note that if the scanner is compiled using
C++
, theninput()
is instead referred to as yyinput(), in order to avoid a name clash with theC++
stream by the name of @@ -1325,24 +1342,24 @@- +
YY_FLUSH_BUFFER()
flushes the scanner's internal buffer so that the next time the scanner attempts to match a token, it will first refill the buffer usingYY_INPUT()
-(see section The Generated Scanner). This action is a special case +(see section The Generated Scanner). This action is a special case of the more generalyy_flush_buffer()
-function, described below (see section Multiple Input Buffers) +function, described below (see section Multiple Input Buffers)@@ -1357,10 +1374,10 @@ -
The Generated Scanner
+The Generated Scanner
- + The output of
flex
is the file `lex.yy.c', which contains the scanning routineyylex()
, a number of tables used by it for matching tokens, and a number of auxiliary routines and macros. By @@ -1377,7 +1394,7 @@- + (If your environment supports function prototypes, then it will be
int yylex( void )
.) This definition may be changed by defining @@ -1385,7 +1402,7 @@@verbatim @@ -1400,7 +1417,19 @@- +
flex
generates `C99' function definitions by default. However flex +does have the ability to generate obsolete, er, `traditional', function +definitions. This is to support bootstrapping gcc on old systems. +Unfortunately, traditional definitions prevent us from using any standard data +types smaller than int (such as short, char, or bool) as function arguments. +For this reason, future versions offlex
may generate standard C99 code +only, leaving K&R-style functions to the historians. Currently, if you do +not want `C99' definitions, then you must define +YY_TRADITIONAL_FUNC_DEFS
. + + ++ Whenever
yylex()
is called, it scans tokens from the global input file `yyin' (which defaults to stdin). It continues until it either reaches an end-of-file (at which point it returns the value 0) or @@ -1408,7 +1437,7 @@- + If the scanner reaches an end-of-file, subsequent calls are undefined unless either `yyin' is pointed at a new input file (in which case scanning continues from that file), or
yyrestart()
is called. @@ -1421,13 +1450,13 @@flex
, and because it can be used to switch input files in the middle of scanning. It can also be used to throw away the current input buffer, by calling it with an argument of `yyin'; but it would be -better to useYY_FLUSH_BUFFER
(see section Actions). Note that +better to useYY_FLUSH_BUFFER
(see section Actions). Note thatyyrestart()
does not reset the start condition to -INITIAL
(see section Start Conditions). +INITIAL
(see section Start Conditions).- + If
yylex()
stops scanning due to executing a @@ -1450,13 +1479,13 @@- + Here is a sample definition of
YY_INPUT
(in the definitions section of the input file):@verbatim @@ -1475,7 +1504,7 @@- + When the scanner receives an end-of-file indication from YY_INPUT, it then checks the
yywrap()
function. Ifyywrap()
returns false (zero), then it is assumed that the function has gone ahead and @@ -1496,7 +1525,7 @@For scanning from in-memory buffers (e.g., scanning strings), see @xref{Scanning Strings} -See section Multiple Input Buffers. +See section Multiple Input Buffers.
@@ -1512,10 +1541,10 @@ -
Start Conditions
+Start Conditions
- +
flex
provides a mechanism for conditionally activating rules. Any rule whose pattern is prefixed with `<sc>' will only be active when @@ -1523,7 +1552,7 @@@verbatim @@ -1538,7 +1567,7 @@@verbatim @@ -1553,7 +1582,7 @@- + Start conditions are declared in the definitions (first) section of the input using unindented lines beginning with either `%s' or `%x' followed by a list of names. The former declares @@ -1579,7 +1608,7 @@
@verbatim @@ -1596,7 +1625,7 @@@verbatim @@ -1619,7 +1648,7 @@- + Also note that the special start-condition specifier
<*>
matches every start condition. Thus, the above example could also @@ -1627,7 +1656,7 @@@verbatim @@ -1645,7 +1674,7 @@@verbatim @@ -1653,9 +1682,9 @@- - - + + +
BEGIN(0)
returns to the original state where only the rules with no start conditions are active. This state can also be referred to as the start-conditionINITIAL
, soBEGIN(INITIAL)
is @@ -1671,7 +1700,7 @@@verbatim @@ -1696,7 +1725,7 @@@verbatim @@ -1730,13 +1759,13 @@- + Here is a scanner which recognizes (and discards) C comments while maintaining a count of the current input line.
@verbatim @@ -1766,8 +1795,8 @@@verbatim @@ -1795,14 +1824,14 @@- + Furthermore, you can access the current start condition using the integer-valued
YY_START
macro. For example, the above assignments tocomment_caller
could instead be written@verbatim @@ -1810,14 +1839,16 @@- + Flex provides
YYSTATE
as an alias forYY_START
(since that is what's used by AT&Tlex
).-Note that start conditions do not have their own name-space; %s's and %x's -declare names in the same fashion as #define's. +For historical reasons, start conditions do not have their own +name-space within the generated scanner. The start condition names are +unmodified in the generated scanner and generated header. +@xref{option-header}. @xref{option-prefix}.
@@ -1827,7 +1858,7 @@
@verbatim @@ -1887,7 +1918,7 @@- + Often, such as in some of the examples above, you wind up writing a whole bunch of rules all preceded by the same start condition(s). Flex makes this a little easier and cleaner by introducing a notion of start @@ -1908,7 +1939,7 @@
@verbatim @@ -1938,8 +1969,8 @@@@ -1949,7 +1980,7 @@
new_state
)
-new_state
@@ -1962,7 +1993,7 @@
@@ -1971,28 +2002,28 @@
- + The start condition stack grows dynamically and so has no built-in size limitation. If memory is exhausted, program execution aborts.
To use start condition stacks, your scanner must include a %option
-stack
directive (see section Invoking Flex).
+stack directive (see section Scanner Options).
-
-
+
Some scanners (such as those which support "include" files) require
reading from several input streams. As flex
scanners do a large
amount of buffering, one cannot control where the next input will be
@@ -2010,10 +2041,10 @@
size
characters (when in doubt, use YY_BUF_SIZE
for the size). It
returns a YY_BUFFER_STATE
handle, which may then be passed to
-other routines (see below).
-
+other routines (see below).
+
The YY_BUFFER_STATE
type is a
pointer to an opaque struct yy_buffer_state
structure, so you may
safely initialize YY_BUFFER_STATE
variables to ((YY_BUFFER_STATE)
@@ -2040,7 +2071,7 @@
@@ -2054,10 +2085,10 @@
@@ -2068,11 +2099,11 @@
@@ -2086,7 +2117,7 @@
@@ -2097,13 +2128,13 @@
-
+
Finally, the macro YY_CURRENT_BUFFER
macro returns a
YY_BUFFER_STATE
handle to the current buffer.
-
+
Here is an example of using these features for writing a scanner
which expands include files (the
<<EOF>>
@@ -2111,7 +2142,7 @@
@verbatim
@@ -2171,7 +2202,7 @@
@anchor{Scanning Strings}
-
+
The following routines are available for setting up input buffers for
scanning in-memory strings instead of files. All of them create a new
input buffer for scanning the string, and return a corresponding
@@ -2184,7 +2215,7 @@
@@ -2192,7 +2223,7 @@
- Function: YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len )
-
-
+
-
scans
len
bytes (including possibly NUL
s) starting at location
bytes
.
@@ -2206,10 +2237,10 @@
- Function: YY_BUFFER_STATE yy_scan_buffer (char *base, yy_size_t size)
-
-
+
-
which scans in place the buffer starting at
base
, consisting of
size
bytes, the last two bytes of which must be
YY_END_OF_BUFFER_CHAR
(ASCII NUL). These last two bytes are not
@@ -2227,7 +2258,7 @@
- Data type: yy_size_t
-
-
+
-
is an integral type to which you can cast an integer expression
reflecting the size of the buffer.
@@ -2235,10 +2266,10 @@
-End-of-File Rules
+End-of-File Rules
-
+
The special rule <<EOF>>
indicates
actions which are to be taken when an end-of-file is
encountered and yywrap()
returns non-zero (i.e., indicates
@@ -2250,7 +2281,7 @@
-
-
+
assigning `yyin' to a new input file (in previous versions of
flex
, after doing the assignment you had to call the special
action YY_NEW_FILE
. This is no longer necessary.)
@@ -2289,7 +2320,7 @@
@verbatim
@@ -2312,10 +2343,10 @@
-Miscellaneous Macros
+Miscellaneous Macros
-
+
The macro YY_USER_ACTION
can be defined to provide an action
which is always executed prior to the matched rule's action. For
example, it could be #define'd to call a routine to convert yytext to
@@ -2326,7 +2357,7 @@
@verbatim
@@ -2334,7 +2365,7 @@
-
+
where ctr
is an array to hold the counts for the different rules.
Note that the macro YY_NUM_RULES
gives the total number of rules
(including the default rule), even if you use `-s)', so a correct
@@ -2348,7 +2379,7 @@
-
+
The macro YY_USER_INIT
may be defined to provide an action which
is always executed before the first scan (and before the scanner's
internal initializations are done). For example, it could be used to
@@ -2356,23 +2387,23 @@
-
+
The macro yy_set_interactive(is_interactive)
can be used to
control whether the current buffer is considered interactive. An
interactive buffer is processed more slowly, but must be used when the
scanner's input source is indeed interactive to avoid problems due to
waiting to fill buffers (see the discussion of the `-I' flag in
-section Invoking Flex). A non-zero value in the macro invocation marks
+section Scanner Options). A non-zero value in the macro invocation marks
the buffer as interactive, a zero value as non-interactive. Note that
use of this macro overrides %option always-interactive
or
-%option never-interactive
(see section Invoking Flex).
+%option never-interactive
(see section Scanner Options).
yy_set_interactive()
must be invoked prior to beginning to scan
the buffer that is (or is not) to be considered interactive.
-
-
+
+
The macro yy_set_bol(at_bol)
can be used to control whether the
current buffer's scanning context for the next token match is done as
though at the beginning of a line. A non-zero macro argument makes
@@ -2381,15 +2412,15 @@
-
-
+
+
The macro YY_AT_BOL()
returns true if the next token scanned from
the current buffer will have `^' rules active, false otherwise.
-
-
+
+
In the generated scanner, the actions are all gathered in one large
switch statement and separated using YY_BREAK
, which may be
redefined. By default, it is simply a break
, to separate each
@@ -2403,7 +2434,7 @@
-
Values Available To the User
+Values Available To the User
This chapter summarizes the various values available to the user in the
@@ -2414,14 +2445,14 @@
char *yytext
-
-
+
holds the text of the current token. It may be modified but not
lengthened (you cannot append characters to the end).
-
-
-
+
+
+
If the special directive
%array
appears in the first section of
the scanner description, then yytext
is instead declared
char yytext[YYLMAX]
, where YYLMAX
is a macro definition
@@ -2432,16 +2463,16 @@
a character pointer. The opposite of %array
is %pointer
,
which is the default.
-
+
You cannot use %array
when generating C++ scanner classes (the
`-+' flag).
-
+
int yyleng
-
holds the length of the current token.
-
+
FILE *yyin
-
is the file which by default
flex
reads from. It may be
@@ -2452,7 +2483,7 @@
end-of-file has been seen, you can assign `yyin' at the new input
file and then call the scanner again to continue scanning.
-
+
void yyrestart( FILE *new_file )
-
may be called to point `yyin' at the new input file. The
@@ -2461,18 +2492,18 @@
as an argument thus throws away the current input buffer and continues
scanning the same input file.
-
+
FILE *yyout
-
is the file to which
ECHO
actions are done. It can be reassigned
by the user.
-
+
YY_CURRENT_BUFFER
-
returns a
YY_BUFFER_STATE
handle to the current buffer.
-
+
YY_START
-
returns an integer value corresponding to the current start condition.
@@ -2482,14 +2513,14 @@
-
Interfacing with Yacc
+Interfacing with Yacc
-
+
One of the main uses of flex
is as a companion to the yacc
parser-generator. yacc
parsers expect to call a routine named
yylex()
to find the next input token. The routine is supposed to
@@ -2503,7 +2534,7 @@
@verbatim
@@ -2518,138 +2549,203 @@
-Invoking Flex
+Scanner Options
-flex
-has the following options.
+The various flex
options are categorized by function in the following
+menu. If you want to lookup a particular option by name, See section Index of Scanner Options.
-
+
+Even though there are many scanner options, a typical scanner might only
+specify the following options:
-
- `-b, --backup'
-
-
-Generate backing-up information to `lex.backup'. This is a list of
-scanner states which require backing up and the input characters on
-which they do so. By adding rules one can remove backing-up states. If
-all backing-up states are eliminated and `-Cf' or
-CF
-is used, the generated scanner will run faster (see the `--perf-report' flag).
-Only users who wish to squeeze every last cycle out of their scanners
-need worry about this option. (see section Performance Considerations).
- - `-c'
-
-
-is a do-nothing option included for POSIX compliance.
-
- `-d, --debug'
-
-
-makes the generated scanner run in debug mode. Whenever a pattern
-is recognized and the global variable
yy_flex_debug
is non-zero
-(which is the default), the scanner will write to `stderr' a line
-of the form:
+
+@verbatim
+%option 8-bit reentrant bison-bridge
+%option warn nodefault
+%option yylineno
+%option outfile="scanner.c" header-file="scanner.h"
+
+
+
+The first line specifies the general type of scanner we want. The second line
+specifies that we are being careful. The third line asks flex to track line
+numbers. The last line tells flex what to name the files. (The options can be
+specified in any order. We just dividied them.)
+
+
+
+flex
also provides a mechanism for controlling options within the
+scanner specification itself, rather than from the flex command-line.
+This is done by including %option
directives in the first section
+of the scanner specification. You can specify multiple options with a
+single %option
directive, and multiple directives in the first
+section of your flex input file.
+
+
+
+Most options are given simply as names, optionally preceded by the
+word `no' (with no intervening whitespace) to negate their meaning.
+The names are the same as their long-option equivalents (but without the
+leading `--' ).
+
+
+
+flex
scans your rule actions to determine whether you use the
+REJECT
or yymore()
features. The REJECT
and
+yymore
options are available to override its decision as to
+whether you use the options, either by setting them (e.g., %option
+reject)
to indicate the feature is indeed used, or unsetting them to
+indicate it actually is not used (e.g., %option noyymore)
.
+
+
+
+A number of options are available for lint purists who want to suppress
+the appearance of unneeded routines in the generated scanner. Each of
+the following, if unset (e.g., %option nounput
), results in the
+corresponding routine not appearing in the generated scanner:
+
@verbatim
- -accepting rule at line 53 ("the matched text")
+ input, unput
+ yy_push_state, yy_pop_state, yy_top_state
+ yy_scan_buffer, yy_scan_bytes, yy_scan_string
+
+ yyget_extra, yyset_extra, yyget_leng, yyget_text,
+ yyget_lineno, yyset_lineno, yyget_in, yyset_in,
+ yyget_out, yyset_out, yyget_lval, yyset_lval,
+ yyget_lloc, yyset_lloc, yyget_debug, yyset_debug
-The line number refers to the location of the rule in the file defining
-the scanner (i.e., the file that was fed to flex). Messages are also
-generated when the scanner backs up, accepts the default rule, reaches
-the end of its input buffer (or encounters a NUL; at this point, the two
-look the same as far as the scanner's concerned), or reaches an
-end-of-file.
+
+(though yy_push_state()
and friends won't appear anyway unless
+you use %option stack)
.
-
- `-f, --full'
-
-
-specifies
-fast scanner.
-No table compression is done and
stdio
is bypassed.
-The result is large but fast. This option is equivalent to
-`--Cfr'
- - `-h, -?, --help'
-
-
-generates a "help" summary of
flex
's options to `stdout'
-and then exits.
- - `--header=FILE'
+
+
Options for Specifing Filenames
+
+
+
+@anchor{option-header}
+- `--header-file=FILE,
%option header-file="FILE"
'
-
+
+
+
instructs flex to write a C header to `FILE'. This file contains
-function prototypes, extern variables, and macros used by the scanner.
-It is meant to be included in other C files to avoid compiler warnings.
-The `--header' option is not compatible with the `--c++' option,
+function prototypes, extern variables, and types used by the scanner.
+Only the external API is exported by the header file. Many macros that
+are usable from within scanner actions are not exported to the header
+file. This is due to namespace problems and the goal of a clean
+external API.
+
+While in the header, the macro
yyIN_HEADER
is defined, where `yy'
+is substituted with the appropriate prefix.
+
+The `--header-file' option is not compatible with the `--c++' option,
since the C++ scanner provides its own header in `yyFlexLexer.h'.
- - `-i, --case-insensitive'
+@anchor{option-outfile}
+
+
+
+
- `-oFILE, --outfile=FILE,
%option outfile="FILE"
'
-
-instructs
flex
to generate a case-insensitive scanner. The
-case of letters given in the flex
input patterns will be ignored,
-and tokens in the input will be matched regardless of case. The matched
-text given in yytext
will have the preserved case (i.e., it will
-not be folded).
+directs flex to write the scanner to the file `FILE' instead of
+`lex.yy.c'. If you combine `--outfile' with the `--stdout' option,
+then the scanner is written to `stdout' but its #line
+directives (see the `-l' option above) refer to the file
+`FILE'.
- - `-l, --lex-compat'
+@anchor{option-stdout}
+
+
+
+
- `-t, --stdout,
%option stdout
'
-
-turns on maximum compatibility with the original AT&T
lex
-implementation. Note that this does not mean full compatibility.
-Use of this option costs a considerable amount of performance, and it
-cannot be used with the `--c++', `--full', `--fast', `-Cf', or
-`-CF' options. For details on the compatibilities it provides, see
-section Incompatibilities with Lex and Posix. This option also results in the name
-YY_FLEX_LEX_COMPAT
being #define
'd in the generated scanner.
+instructs flex
to write the scanner it generates to standard
+output instead of `lex.yy.c'.
- - `-n'
+
+
- `-SFILE, --skel=FILE'
-
-is another do-nothing option included only for
-POSIX compliance.
+overrides the default skeleton file from which
+
flex
+constructs its scanners. You'll never need this option unless you are doing
+flex
+maintenance or development.
- - `-p, --perf-report'
+
+
+
- `--tables-file=FILE'
-
-generates a performance report to `stderr'. The report consists of
-comments regarding features of the
flex
input file which will
-cause a serious loss of performance in the resulting scanner. If you
-give the flag twice, you will also get comments regarding features that
-lead to minor performance losses.
-
-Note that the use of REJECT
, %option yylineno
, and
-variable trailing context (see section Limitations) entails a substantial
-performance penalty; use of yymore()
, the `^' operator, and
-the `--interactive' flag entail minor performance penalties.
+Write serialized scanner dfa tables to FILE. The generated scanner will not
+contain the tables, and requires them to be loaded at runtime.
+@xref{serialization}.
- - `-s, --nodefault'
+
+
+
- `--tables-verify'
-
-causes the default rule (that unmatched scanner input is echoed
-to `stdout)' to be suppressed. If the scanner encounters input
-that does not match any of its rules, it aborts with an error. This
-option is useful for finding holes in a scanner's rule set.
+This option is for flex development. We document it here in case you stumble
+upon it by accident or in case you suspect some inconsistency in the serialized
+tables. Flex will serialize the scanner dfa tables but will also generate the
+in-code tables as it normally does. At runtime, the scanner will verify that
+the serialized tables match the in-code tables, instead of loading them.
+
+
+
-- `-t, --stdout'
-
-
-instructs
flex
to write the scanner it generates to standard
-output instead of `lex.yy.c'.
- - `-v, --verbose'
+
Options Affecting Scanner Behavior
+
+
+
+@anchor{option-case-insensitive}
+- `-i, --case-insensitive,
%option case-insensitive
'
-
-specifies that
flex
should write to `stderr' a summary of
-statistics regarding the scanner it generates. Most of the statistics
-are meaningless to the casual flex
user, but the first line
-identifies the version of flex
(same as reported by `--version'),
-and the next line the flags used when generating the scanner, including
-those that are on by default.
+
+
+
+
+instructs flex
to generate a case-insensitive scanner. The
+case of letters given in the flex
input patterns will be ignored,
+and tokens in the input will be matched regardless of case. The matched
+text given in yytext
will have the preserved case (i.e., it will
+not be folded).
- - `-w, --nowarn'
+@anchor{option-lex-compat}
+
+
+
+
- `-l, --lex-compat,
%option lex-compat
'
-
-suppresses warning messages.
+turns on maximum compatibility with the original AT&T
lex
+implementation. Note that this does not mean full compatibility.
+Use of this option costs a considerable amount of performance, and it
+cannot be used with the `--c++', `--full', `--fast', `-Cf', or
+`-CF' options. For details on the compatibilities it provides, see
+section Incompatibilities with Lex and Posix. This option also results in the name
+YY_FLEX_LEX_COMPAT
being #define
'd in the generated scanner.
- - `-B, --batch'
+@anchor{option-batch}
+
+
+
+
- `-B, --batch,
%option batch
'
-
instructs
flex
to generate a batch scanner, the opposite of
interactive scanners generated by `--interactive' (see below). In
@@ -2660,34 +2756,11 @@
`-Cf' or `-CF' options, which turn on `--batch' automatically
anyway.
- - `-F, --fast'
-
-
-specifies that the fast scanner table representation should be
-used (and
stdio
bypassed). This representation is about as fast
-as the full table representation `--full', and for some sets of
-patterns will be considerably smaller (and for others, larger). In
-general, if the pattern set contains both keywords and a
-catch-all, identifier rule, such as in the set:
-
-
-
-@verbatim
- "case" return TOK_CASE;
- "switch" return TOK_SWITCH;
- ...
- "default" return TOK_DEFAULT;
- [a-z]+ return TOK_ID;
-
-
-then you're better off using the full table representation. If only
-the identifier rule is present and you then use a hash table or some such
-to detect the keywords, you're better off using
-`--fast'.
-
-This option is equivalent to `-CFr' (see below). It cannot be used
-with `--c++'.
-
- - `-I, --interactive'
+@anchor{option-interactive}
+
+
+
+
- `-I, --interactive,
%option interactive
'
-
instructs
flex
to generate an interactive scanner. An
interactive scanner is one that only looks ahead to decide what token
@@ -2701,7 +2774,7 @@
flex
scanners default to interactive
unless you use the
`-Cf' or `-CF' table-compression options
-(see section Performance Considerations). That's because if you're looking for
+(see section Performance Considerations). That's because if you're looking for
high-performance you should be using one of these options, so if you
didn't, flex
assumes you'd rather trade off a bit of run-time
performance for intuitive interactive behavior. Note also that you
@@ -2714,67 +2787,79 @@
be interactive by using
`--batch'
- - `-L, --noline'
+@anchor{option-7bit}
+
+
+
+
- `-7, --7bit,
%option 7bit
'
-
-instructs
-
flex
-not to generate
-#line
-directives. Without this option,
-flex
-peppers the generated scanner
-with #line
directives so error messages in the actions will be correctly
-located with respect to either the original
-flex
-input file (if the errors are due to code in the input file), or
-`lex.yy.c'
-(if the errors are
-flex
's
-fault -- you should report these sorts of errors to the email address
-given in section Reporting Bugs).
+instructs flex
to generate a 7-bit scanner, i.e., one which can
+only recognize 7-bit characters in its input. The advantage of using
+`--7bit' is that the scanner's tables can be up to half the size of
+those generated using the `--8bit'. The disadvantage is that such
+scanners often hang or crash if their input contains an 8-bit character.
- - `-R, --reentrant'
-
-
-instructs flex to generate a reentrant C scanner. The generated scanner
-may safely be used in a multi-threaded environment. The API for a
-reentrant scanner is different than for a non-reentrant scanner
-see section Reentrant C Scanners). Because of the API difference between
-reentrant and non-reentrant
flex
scanners, non-reentrant flex
-code must be modified before it is suitable for use with this option.
-This option is not compatible with the `--c++' option.
+Note, however, that unless you generate your scanner using the
+`-Cf' or `-CF' table compression options, use of `--7bit'
+will save only a small amount of table space, and make your scanner
+considerably less portable. Flex
's default behavior is to
+generate an 8-bit scanner unless you use the `-Cf' or `-CF',
+in which case flex
defaults to generating 7-bit scanners unless
+your site was always configured to generate 8-bit scanners (as will
+often be the case with non-USA sites). You can tell whether flex
+generated a 7-bit or an 8-bit scanner by inspecting the flag summary in
+the `--verbose' output as described above.
- - `-Rb, --reentrant-bison'
+Note that if you use `-Cfe' or `-CFe'
flex
still
+defaults to generating an 8-bit scanner, since usually with these
+compression options full 8-bit tables are not much more expensive than
+7-bit tables.
+
+@anchor{option-8bit}
+
+
+
+- `-8, --8bit,
%option 8bit
'
-
-instructs flex to generate a reentrant C scanner that is
-meant to be called by a
-
GNU bison
-pure parser. The scanner is the same as the scanner generated by the
-`--reentrant'
-option, but with minor API changes for
-bison
-compatibility. In particular, the declaration of
-yylex
-is modified, and support for
-yylval
-and
-yylloc
-is incorporated. See section Reentrant C Scanners with Bison Pure Parsers.
+instructs flex
to generate an 8-bit scanner, i.e., one which can
+recognize 8-bit characters. This flag is only needed for scanners
+generated using `-Cf' or `-CF', as otherwise flex defaults to
+generating an 8-bit scanner anyway.
-The options `--reentrant' and `--reentrant-bison' do not affect the performance of
-the scanner.
+See the discussion of
+`--7bit'
+above for flex
's default behavior and the tradeoffs between 7-bit
+and 8-bit scanners.
- - `-T, --trace'
+@anchor{option-default}
+
+
+
- `--default,
%option default
'
-
-makes
flex
run in trace mode. It will generate a lot of
-messages to `stderr' concerning the form of the input and the
-resultant non-deterministic and deterministic finite automata. This
-option is mostly for use in maintaining flex
.
+generate the default rule.
- - `-V, --version'
+@anchor{option-always-interactive}
+
+
+
- `--always-interactive,
%option always-interactive
'
-
-prints the version number to `stdout' and exits.
+instructs flex to generate a scanner which always considers its input
+interactive. Normally, on each new input file the scanner calls
+
isatty()
in an attempt to determine whether the scanner's input
+source is interactive and thus should be read a character at a time.
+When this option is used, however, then no such call is made.
- - `-X, --posix'
+
+
- `--never-interactive,
--never-interactive
'
+ -
+instructs flex to generate a scanner which never considers its input
+interactive. This is the opposite of
always-interactive
.
+
+@anchor{option-posix}
+
+
+
+ - `-X, --posix,
%option posix
'
-
turns on maximum compatibility with the POSIX 1003.2-1992 definition of
lex
. Since flex
was originally designed to implement the
@@ -2798,54 +2883,260 @@
where concatenation has higher precedence than the repeat operator.
- - `-7, --7bit'
+@anchor{option-stack}
+
+
+
- `--stack,
%option stack
'
-
-instructs
flex
to generate a 7-bit scanner, i.e., one which can
-only recognize 7-bit characters in its input. The advantage of using
-`--7bit' is that the scanner's tables can be up to half the size of
-those generated using the `--8bit'. The disadvantage is that such
-scanners often hang or crash if their input contains an 8-bit character.
+enables the use of
+start condition stacks (see section Start Conditions).
-Note, however, that unless you generate your scanner using the
-`-Cf' or `-CF' table compression options, use of `--7bit'
-will save only a small amount of table space, and make your scanner
-considerably less portable. Flex
's default behavior is to
-generate an 8-bit scanner unless you use the `-Cf' or `-CF',
-in which case flex
defaults to generating 7-bit scanners unless
-your site was always configured to generate 8-bit scanners (as will
-often be the case with non-USA sites). You can tell whether flex
-generated a 7-bit or an 8-bit scanner by inspecting the flag summary in
-the `--verbose' output as described above.
+@anchor{option-stdinit}
+
+
+ - `--stdinit,
%option stdinit
'
+ -
+if set (i.e., %option stdinit) initializes
yyin
and
+yyout
to `stdin' and `stdout', instead of the default of
+`nil'. Some existing lex
programs depend on this behavior,
+even though it is not compliant with ANSI C, which does not require
+`stdin' and `stdout' to be compile-time constant. In a
+reentrant scanner, however, this is not a problem since initialization
+is performed in yylex_init
at runtime.
-Note that if you use `-Cfe' or `-CFe' flex
still
-defaults to generating an 8-bit scanner, since usually with these
-compression options full 8-bit tables are not much more expensive than
-7-bit tables.
+@anchor{option-yylineno}
+
+
+ - `--yylineno,
%option yylineno
'
+ -
+directs
flex
to generate a scanner
+that maintains the number of the current line read from its input in the
+global variable yylineno
. This option is implied by %option
+lex-compat
. In a reentrant C scanner, the macro yylineno
is
+accessible regardless of the value of %option yylineno
, however, its
+value is not modified by flex
unless %option yylineno
is enabled.
- - `-8, --8bit'
+@anchor{option-yywrap}
+
+
+
- `--yywrap,
%option yywrap
'
-
-instructs
flex
to generate an 8-bit scanner, i.e., one which can
-recognize 8-bit characters. This flag is only needed for scanners
-generated using `-Cf' or `-CF', as otherwise flex defaults to
-generating an 8-bit scanner anyway.
+if unset (i.e., --noyywrap)
, makes the scanner not call
+yywrap()
upon an end-of-file, but simply assume that there are no
+more files to scan (until the user points `yyin' at a new file and
+calls yylex()
again).
-See the discussion of
-`--7bit'
-above for flex
's default behavior and the tradeoffs between 7-bit
-and 8-bit scanners.
+
+
+
+
+Code-Level And API Options
+
+
-- `-+, --c++'
+@anchor{option-bison-bridge}
+
- `--bison-bridge,
%option bison-bridge
'
+ -
+
+
+
+instructs flex to generate a C scanner that is
+meant to be called by a
+
GNU bison
+parser. The scanner has minor API changes for
+bison
+compatibility. In particular, the declaration of
+yylex
+is modified, and support for
+yylval
+and
+yylloc
+is incorporated. See section C Scanners with Bison Parsers.
+
+@anchor{option-noline}
+
+
+
+ - `-L, --noline,
%option noline
'
+ -
+instructs
+
flex
+not to generate
+#line
+directives. Without this option,
+flex
+peppers the generated scanner
+with #line
directives so error messages in the actions will be correctly
+located with respect to either the original
+flex
+input file (if the errors are due to code in the input file), or
+`lex.yy.c'
+(if the errors are
+flex
's
+fault -- you should report these sorts of errors to the email address
+given in section Reporting Bugs).
+
+@anchor{option-reentrant}
+
+
+
+ - `-R, --reentrant,
%option reentrant
'
+ -
+instructs flex to generate a reentrant C scanner. The generated scanner
+may safely be used in a multi-threaded environment. The API for a
+reentrant scanner is different than for a non-reentrant scanner
+see section Reentrant C Scanners). Because of the API difference between
+reentrant and non-reentrant
flex
scanners, non-reentrant flex
+code must be modified before it is suitable for use with this option.
+This option is not compatible with the `--c++' option.
+
+The option `--reentrant' does not affect the performance of
+the scanner.
+
+@anchor{option-c++}
+
+
+
+ - `-+, --c++,
%option c++
'
-
specifies that you want flex to generate a C++
-scanner class. See section Generating C++ Scanners, for
+scanner class. See section Generating C++ Scanners, for
details.
+@anchor{option-array}
+
+
+
- `--array,
%option array
'
+ -
+specifies that you want yytext to be an array instead of a char*
+
+@anchor{option-pointer}
+
+
+
- `--pointer,
%option pointer
'
+ -
+specify that
yytext
should be a char *
, not an array.
+This default is char *
.
+
+@anchor{option-prefix}
+
+
+
+ - `-PPREFIX, --prefix=PREFIX,
%option prefix="PREFIX"
'
+ -
+changes the default `yy' prefix used by
flex
for all
+globally-visible variable and function names to instead be
+`PREFIX'. For example, `--prefix=foo' changes the name of
+yytext
to footext
. It also changes the name of the default
+output file from `lex.yy.c' to `lex.foo.c'. Here is a partial
+list of the names affected:
+
+
+
+@verbatim
+ yy_create_buffer
+ yy_delete_buffer
+ yy_flex_debug
+ yy_init_buffer
+ yy_flush_buffer
+ yy_load_buffer_state
+ yy_switch_to_buffer
+ yyin
+ yyleng
+ yylex
+ yylineno
+ yyout
+ yyrestart
+ yytext
+ yywrap
+ yyalloc
+ yyrealloc
+ yyfree
+
+
+(If you are using a C++ scanner, then only yywrap
and
+yyFlexLexer
are affected.) Within your scanner itself, you can
+still refer to the global variables and functions using either version
+of their name; but externally, they have the modified name.
+
+This option lets you easily link together multiple
+flex
+programs into the same executable. Note, though, that using this
+option also renames
+yywrap()
,
+so you now
+must
+either
+provide your own (appropriately-named) version of the routine for your
+scanner, or use
+%option noyywrap
,
+as linking with
+`-lfl'
+no longer provides one for you by default.
+
+@anchor{option-main}
+
+
+ - `--main,
%option main
'
+ -
+ directs flex to provide a default
main()
program for the
+scanner, which simply calls yylex()
. This option implies
+noyywrap
(see below).
+
+@anchor{option-nounistd}
+
+
+ - `--nounistd,
%option nounistd
'
+ -
+suppresses inclusion of the non-ANSI header file `unistd.h'. This option
+is meant to target environments in which `unistd.h' does not exist. Be aware
+that certain options may cause flex to generate code that relies on functions
+normally found in `unistd.h', (e.g.
isatty()
, read()
.)
+If you wish to use these functions, you will have to inform your compiler where
+to find them.
+@xref{option-always-interactive}. @xref{option-read}.
+
+@anchor{option-yyclass}
+
+
+ - `--yyclass,
%option yyclass="NAME"
'
+ -
+only applies when generating a C++ scanner (the `--c++' option). It
+informs
flex
that you have derived foo
as a subclass of
+yyFlexLexer
, so flex
will place your actions in the member
+function foo::yylex()
instead of yyFlexLexer::yylex()
. It
+also generates a yyFlexLexer::yylex()
member function that emits
+a run-time error (by invoking yyFlexLexer::LexerError())
if
+called. See section Generating C++ Scanners.
+
+
+
+
+
+Options for Scanner Speed and Size
+
+
+
- `-C[aefFmr]'
-
controls the degree of table compression and, more generally, trade-offs
between small scanners and fast scanners.
-
- `-Ca, --align'
+
+
+- `-C'
+
-
+
+
+A lone `-C' specifies that the scanner tables should be compressed
+but neither equivalence classes nor meta-equivalence classes should be
+used.
+
+@anchor{option-align}
+
+
+
+
- `-Ca, --align,
%option align
'
-
("align") instructs flex to trade off larger tables in the
generated scanner for faster performance because the elements of
@@ -2854,7 +3145,11 @@
than with smaller-sized units such as shortwords. This option can
quadruple the size of the tables used by your scanner.
-
- `-Ce, --ecs'
+@anchor{option-ecs}
+
+
+
+
- `-Ce, --ecs,
%option ecs
'
-
directs
flex
to construct equivalence classes, i.e., sets
of characters which have identical lexical properties (for example, if
@@ -2865,19 +3160,25 @@
factor of 2-5) and are pretty cheap performance-wise (one array look-up
per character scanned).
+
- `-Cf'
-
specifies that the full scanner tables should be generated -
flex
should not compress the tables by taking advantages of
similar transition functions for different states.
+
- `-CF'
-
specifies that the alternate fast scanner representation (described
above under the `--fast' flag) should be used. This option cannot be
used with `--c++'.
-
- `-Cm, --meta-ecs'
+@anchor{option-meta-ecs}
+
+
+
+
- `-Cm, --meta-ecs,
%option meta-ecs
'
-
directs
flex
@@ -2889,8 +3190,11 @@
have a moderate performance impact (one or two if
tests and one
array look-up per character scanned).
-@anchor{Option-Read}
- - `-Cr, --read'
+@anchor{option-read}
+
+
+
+
- `-Cr, --read,
%option read
'
-
causes the generated scanner to bypass use of the standard I/O
library (
stdio
) for input. Instead of calling fread()
or
@@ -2901,13 +3205,8 @@
example, you read from `yyin' using stdio
prior to calling
the scanner (because the scanner will miss whatever text your previous
reads left in the stdio
input buffer). `-Cr' has no effect
-if you define YY_INPUT()
(see section The Generated Scanner).
-
- - `-C'
-
-
-A lone `-C' specifies that the scanner tables should be compressed
-but neither equivalence classes nor meta-equivalence classes should be
-used.
+if you define
YY_INPUT()
(see section The Generated Scanner).
+
The options `-Cf' or `-CF' and `-Cm' do not make sense
together - there is no opportunity for meta-equivalence classes if the
@@ -2941,245 +3240,207 @@
`-Cfe' is often a good compromise between speed and size for
production scanners.
-- `-oFILE, --outfile=FILE'
+@anchor{option-full}
+
+
+
+
- `-f, --full,
%option full
'
-
-directs flex to write the scanner to the file `FILE' instead of
-`lex.yy.c'. If you combine `--outfile' with the `--stdout' option,
-then the scanner is written to `stdout' but its
#line
-directives (see the `-l' option above) refer to the file
-`FILE'.
+specifies
+fast scanner.
+No table compression is done and stdio
is bypassed.
+The result is large but fast. This option is equivalent to
+`--Cfr'
- - `-PPREFIX, --prefix=PREFIX'
+@anchor{option-fast}
+
+
+
+
- `-F, --fast,
%option fast
'
-
-changes the default `yy' prefix used by
flex
for all
-globally-visible variable and function names to instead be
-`PREFIX'. For example, `--prefix=foo' changes the name of
-yytext
to footext
. It also changes the name of the default
-output file from `lex.yy.c' to `lex.foo.c'. Here are all of
-the names affected:
+specifies that the fast scanner table representation should be
+used (and stdio
bypassed). This representation is about as fast
+as the full table representation `--full', and for some sets of
+patterns will be considerably smaller (and for others, larger). In
+general, if the pattern set contains both keywords and a
+catch-all, identifier rule, such as in the set:
@verbatim
- yy_create_buffer
- yy_delete_buffer
- yy_flex_debug
- yy_init_buffer
- yy_flush_buffer
- yy_load_buffer_state
- yy_switch_to_buffer
- yyin
- yyleng
- yylex
- yylineno
- yyout
- yyrestart
- yytext
- yywrap
+ "case" return TOK_CASE;
+ "switch" return TOK_SWITCH;
+ ...
+ "default" return TOK_DEFAULT;
+ [a-z]+ return TOK_ID;
-(If you are using a C++ scanner, then only yywrap
and
-yyFlexLexer
are affected.) Within your scanner itself, you can
-still refer to the global variables and functions using either version
-of their name; but externally, they have the modified name.
-
-This option lets you easily link together multiple
-flex
-programs into the same executable. Note, though, that using this
-option also renames
-yywrap()
,
-so you now
-must
-either
-provide your own (appropriately-named) version of the routine for your
-scanner, or use
-%option noyywrap
,
-as linking with
-`-lfl'
-no longer provides one for you by default.
-
- - `-SFILE, --skel=FILE'
-
-
-overrides the default skeleton file from which
-
flex
-constructs its scanners. You'll never need this option unless you are doing
-flex
-maintenance or development.
+then you're better off using the full table representation. If only
+the identifier rule is present and you then use a hash table or some such
+to detect the keywords, you're better off using
+`--fast'.
-@anchor{Option-Always-Interactive}
- - `--always-interactive'
-
-
-instructs flex to generate a scanner which always considers its input
-interactive. Normally, on each new input file the scanner calls
-
isatty()
in an attempt to determine whether the scanner's input
-source is interactive and thus should be read a character at a time.
-When this option is used, however, then no such call is made.
+This option is equivalent to `-CFr' (see below). It cannot be used
+with `--c++'.
- - `--main'
-
-
- directs flex to provide a default
main()
program for the
-scanner, which simply calls yylex()
. This option implies
-noyywrap
(see below).
+
-- `--never-interactive'
-
-
-instructs flex to generate a scanner which never considers its input
-interactive. This is the opposite of
always-interactive
.
- - `--nounistd'
-
-
-suppresses inclusion of the non-ANSI header file `unistd.h'. This option
-is meant to target environments in which `unistd.h' does not exist. Be aware
-that certain options may cause flex to generate code that relies on functions
-normally found in `unistd.h', (e.g.
isatty()
, read()
.)
-If you wish to use these functions, you will have to inform your compiler where
-to find them.
-@xref{Option-Always-Interactive}. @xref{Option-Read}.
- - `--stack'
-
-
-enables the use of
-start condition stacks (see section Start Conditions).
+
Debugging Options
- - `--stdinit'
-
-
-if set (i.e., %option stdinit) initializes
yyin
and
-yyout
to `stdin' and `stdout', instead of the default of
-`nil'. Some existing lex
programs depend on this behavior,
-even though it is not compliant with ANSI C, which does not require
-`stdin' and `stdout' to be compile-time constant. In a
-reentrant scanner, however, this is not a problem since initialization
-is performed in yylex_init
at runtime.
+
-- `--yylineno'
+@anchor{option-backup}
+
- `-b, --backup,
%option backup
'
-
-directs
flex
to generate a scanner
-that maintains the number of the current line read from its input in the
-global variable yylineno
. This option is implied by %option
-lex-compat
. In a reentrant C scanner, the macro yylineno
is
-accessible regardless of the value of %option yylineno
, however, its
-value is not modified by flex
unless %option yylineno
is enabled.
+
+
+
+
+Generate backing-up information to `lex.backup'. This is a list of
+scanner states which require backing up and the input characters on
+which they do so. By adding rules one can remove backing-up states. If
+all backing-up states are eliminated and `-Cf' or -CF
+is used, the generated scanner will run faster (see the `--perf-report' flag).
+Only users who wish to squeeze every last cycle out of their scanners
+need worry about this option. (see section Performance Considerations).
- - `--yywrap'
+@anchor{option-debug}
+
+
+
+
- `-d, --debug,
%option debug
'
-
-if unset (i.e.,
--noyywrap)
, makes the scanner not call
-yywrap()
upon an end-of-file, but simply assume that there are no
-more files to scan (until the user points `yyin' at a new file and
-calls yylex()
again).
-
-
+makes the generated scanner run in debug mode. Whenever a pattern
+is recognized and the global variable yy_flex_debug
is non-zero
+(which is the default), the scanner will write to `stderr' a line
+of the form:
-Option Directives Within Scanners
+
+@verbatim
+ -accepting rule at line 53 ("the matched text")
+
-
-flex
also provides a mechanism for controlling options within the
-scanner specification itself, rather than from the flex command-line.
-This is done by including %option
directives in the first section
-of the scanner specification. You can specify multiple options with a
-single %option
directive, and multiple directives in the first
-section of your flex input file.
+The line number refers to the location of the rule in the file defining
+the scanner (i.e., the file that was fed to flex). Messages are also
+generated when the scanner backs up, accepts the default rule, reaches
+the end of its input buffer (or encounters a NUL; at this point, the two
+look the same as far as the scanner's concerned), or reaches an
+end-of-file.
+@anchor{option-perf-report}
+
+
+
+
- `-p, --perf-report,
%option perf-report
'
+ -
+generates a performance report to `stderr'. The report consists of
+comments regarding features of the
flex
input file which will
+cause a serious loss of performance in the resulting scanner. If you
+give the flag twice, you will also get comments regarding features that
+lead to minor performance losses.
-
-Most options are given simply as names, optionally preceded by the
-word `no' (with no intervening whitespace) to negate their meaning.
-The names are the same as their long-option equivalents (but without the
-leading `--' ).
+Note that the use of REJECT
, and
+variable trailing context (see section Limitations) entails a substantial
+performance penalty; use of yymore()
, the `^' operator, and
+the `--interactive' flag entail minor performance penalties.
+@anchor{option-nodefault}
+
+
+
+
- `-s, --nodefault,
%option nodefault
'
+ -
+causes the default rule (that unmatched scanner input is echoed
+to `stdout)' to be suppressed. If the scanner encounters input
+that does not match any of its rules, it aborts with an error. This
+option is useful for finding holes in a scanner's rule set.
+@anchor{option-trace}
+
+
+
+
- `-T, --trace,
%option trace
'
+ -
+makes
flex
run in trace mode. It will generate a lot of
+messages to `stderr' concerning the form of the input and the
+resultant non-deterministic and deterministic finite automata. This
+option is mostly for use in maintaining flex
.
-
-@verbatim
- 7bit -7 --7bit
- 8bit -8 --8bit
- align -Ca --align
- array --array equivalent to "%array"
- backup -b --backup
- batch -B --batch
- c++ -+ --c++
-
- caseful or
- case-sensitive (default)
-
- case-insensitive or
- caseless -i --case-insensitive
-
- debug -d --debug
- default --default
- ecs -Ce --ecs
- fast -F --fast
- full -f --full
- header="FILE" --header=FILE
- interactive -I --interactive
- lex-compat -l --lex-compat
- meta-ecs -Cm --meta-ecs
- nounistd --nounistd
- perf-report -p --perf-report
- pointer --pointer equivalent to "%pointer" (default)
- prefix="PREFIX" -P --prefix
- outfile="FILE" -o --outfile=FILE
- read -Cr --read
- reentrant -R --reentrant
- reentrant-bison -Rb --reentrant-bison
- stdout -t --stdout
- verbose -v --verbose
- warn --warn (use "%option nowarn" for -w)
- yyclass="NAME" --yyclass=NAME
+@anchor{option-nowarn}
+
+
+
+
- `-w, --nowarn,
%option nowarn
'
+ -
+suppresses warning messages.
-
+@anchor{option-verbose}
+
+
+
+
- `-v, --verbose,
%option verbose
'
+ -
+specifies that
flex
should write to `stderr' a summary of
+statistics regarding the scanner it generates. Most of the statistics
+are meaningless to the casual flex
user, but the first line
+identifies the version of flex
(same as reported by `--version'),
+and the next line the flags used when generating the scanner, including
+those that are on by default.
-
-flex
scans your rule actions to determine whether you use the
-REJECT
or yymore()
features. The REJECT
and
-yymore
options are available to override its decision as to
-whether you use the options, either by setting them (e.g., %option
-reject)
to indicate the feature is indeed used, or unsetting them to
-indicate it actually is not used (e.g., %option noyymore)
.
+@anchor{option-warn}
+
+
+
- `--warn,
%option warn
'
+ -
+warn about certain things. In particular, if the default rule can be
+matched but no defualt rule has been given, the flex will warn you.
+We recommend using this option always.
+
-%option yyclass
-only applies when generating a C++ scanner (the `--c++' option). It
-informs flex
that you have derived foo
as a subclass of
-yyFlexLexer
, so flex
will place your actions in the member
-function foo::yylex()
instead of yyFlexLexer::yylex()
. It
-also generates a yyFlexLexer::yylex()
member function that emits
-a run-time error (by invoking yyFlexLexer::LexerError())
if
-called. See section Generating C++ Scanners.
-
-A number of options are available for lint purists who want to suppress
-the appearance of unneeded routines in the generated scanner. Each of
-the following, if unset (e.g., %option nounput
), results in the
-corresponding routine not appearing in the generated scanner:
+
-@verbatim - input, unput - yy_push_state, yy_pop_state, yy_top_state - yy_scan_buffer, yy_scan_bytes, yy_scan_string + + +generates +
flex
's options to `stdout'
+and then exits.
- yyget_extra, yyset_extra, yyget_leng, yyget_text,
- yyget_lineno, yyset_lineno, yyget_in, yyset_in,
- yyget_out, yyset_out, yyget_lval, yyset_lval,
- yyget_lloc, yyset_lloc,
-
+
+
-(though yy_push_state()
and friends won't appear anyway unless
-you use %option stack)
.
+
+
+
-
+
The main design goal of flex
is that it generate high-performance
scanners. It has been optimized for dealing well with large sets of
rules. Aside from the effects on scanner speed of the table compression
@@ -3188,18 +3449,19 @@
@verbatim REJECT - %option yylineno arbitrary trailing context pattern sets that require backing up + %option yylineno %array + %option interactive %option always-interactive @@ -3208,7 +3470,7 @@
-with the first three all being quite expensive and the last two being
+with the first two all being quite expensive and the last two being
quite cheap. Note also that unput()
is implemented as a routine
call that potentially does quite a bit of work, while yyless()
is
a quite-cheap macro. So if you are just putting back some excess text
@@ -3221,9 +3483,32 @@
-
-
-
+There is one case when %option yylineno
can be expensive. That is when
+your patterns match long tokens that could possibly contain a newline
+character. There is no performance penalty for rules that can not possibly
+match newlines, since flex does not need to check them for newlines. In
+general, you should avoid rules such as [^f]+
, which match very long
+tokens, including newlines, and may possibly match your entire file! A better
+approach is to separate [^f]+
into two rules:
+
+
+
+
+@verbatim +%option yylineno +%% + [^f\n]+ + \n+ ++ +
+The above scanner does not incur a performance penalty. + + +
+ + + Getting rid of backing up is messy and often may be an enormous amount of work for a complicated scanner. In principal, one begins by using the `-b' flag to generate a `lex.backup' file. For example, @@ -3231,7 +3516,7 @@
@verbatim @@ -3297,12 +3582,12 @@- + The way to remove the backing up is to add "error" rules:
@verbatim @@ -3324,7 +3609,7 @@@verbatim @@ -3362,7 +3647,7 @@@verbatim @@ -3396,7 +3681,7 @@Note that here the special '|' action does not provide any -savings, and can even make things worse (see section Limitations). +savings, and can even make things worse (see section Limitations).
@@ -3410,7 +3695,7 @@
@verbatim @@ -3457,8 +3742,8 @@- - + + A final example in speeding up a scanner: suppose you want to scan through a file containing identifiers and keywords, one per line and with no other extraneous characters, and recognize all the @@ -3466,7 +3751,7 @@
@verbatim @@ -3569,7 +3854,7 @@Another final note regarding performance: as mentioned in -section How the Input Is Matched, dynamically resizing
yytext
to accommodate huge +section How the Input Is Matched, dynamically resizingyytext
to accommodate huge tokens is a slow process because it presently requires that the (huge) token be rescanned from the beginning. Thus if performance is vital, you should attempt to match "large" quantities of text but not @@ -3579,16 +3864,23 @@ -Generating C++ Scanners
+Generating C++ Scanners
- - - + + +IMPORTANT: the present form of the scanning class is experimental +and may change considerably between major releases. + + +
+ + +
flex
provides two different ways to generate scanners for use with C++. The first way is to simply compile a scanner generated byflex
using a C++ compiler instead of a C compiler. You should -not encounter any compilation errors (see section Reporting Bugs). You can +not encounter any compilation errors (see section Reporting Bugs). You can then use C++ code in your rule actions instead of C code. Note that the default input source for your scanner remains `yyin', and default echoing is still done to `yyout'. Both of these remainFILE @@ -3616,32 +3908,32 @@
const char* YYText()
- - + returns the text of the most recently matched token, the equivalent of
yytext
. - +int YYLeng()
- returns the length of the most recently matched token, the equivalent of
yyleng
. - +int lineno() const
- returns the current input line number (see
%option yylineno)
, or1
if%option yylineno
was not used. - +void set_debug( int flag )
- sets the debugging flag for the scanner, equivalent to assigning to -
yy_flex_debug
(see section Invoking Flex). Note that you must build +yy_flex_debug
(see section Scanner Options). Note that you must build the scannerusing%option debug
to include debugging information in it. - +int debug() const
- returns the current setting of the debugging flag. @@ -3657,8 +3949,8 @@
- - + + The second class defined in `FlexLexer.h' is
yyFlexLexer
, which is derived fromFlexLexer
. It defines the following additional member functions: @@ -3668,13 +3960,13 @@yyFlexLexer( istream* arg_yyin = 0, ostream* arg_yyout = 0 )
- - + constructs a
yyFlexLexer
object using the given streams for input and output. If not specified, the streams default tocin
andcout
, respectively. - +virtual int yylex()
- performs the same role is
yylex()
does for ordinaryflex
@@ -3688,7 +3980,7 @@ (and also generates a dummyyyFlexLexer::yylex()
that callsyyFlexLexer::LexerError()
if called). - +virtual void switch_streams(istream* new_in = 0, ostream* new_out = 0)
- reassigns
yyin
tonew_in
(if non-nil) andyyout
to @@ -3711,26 +4003,26 @@virtual int LexerInput( char* buf, int max_size )
- - + reads up to
max_size
characters intobuf
and returns the number of characters read. To indicate end-of-input, return 0 characters. Note thatinteractive
scanners (see the `-B' -and `-I' flags in section Invoking Flex) define the macro +and `-I' flags in section Scanner Options) define the macroYY_INTERACTIVE
. If you redefineLexerInput()
and need to take different actions depending on whether or not the scanner might be scanning an interactive input source, you can test for the presence of this name via#ifdef
statements. - +virtual void LexerOutput( const char* buf, int size )
- writes out
size
characters from the bufferbuf
, which, whileNUL
-terminated, may also contain internalNUL
s if the scanner's rules can match text withNUL
s in them. - - + +virtual void LexerError( const char* msg )
- reports a fatal error message. The default version of this function @@ -3740,10 +4032,10 @@
Note that a
yyFlexLexer
object contains its entire scanning state. Thus you can use such objects to create reentrant -scanners. You can instantiate multiple instances of the same -yyFlexLexer
class, and you can also combine multiple C++ scanner -classes together in the same program using the `-P' option -discussed above. +scanners, but see also section Reentrant C Scanners. You can instantiate multiple +instances of the sameyyFlexLexer
class, and you can also combine +multiple C++ scanner classes together in the same program using the +`-P' option discussed above.@@ -3756,7 +4048,7 @@
@verbatim @@ -3819,7 +4111,7 @@- + If you want to create multiple (different) lexer classes, you use the `-P' flag (or the
prefix=
option) to rename eachyyFlexLexer
to some other `xxFlexLexer'. You then can @@ -3828,9 +4120,9 @@@verbatim @@ -3848,30 +4140,23 @@ scanners and%option prefix="zz"
for the other. --IMPORTANT: the present form of the scanning class is experimental -and may change considerably between major releases. - - -
Reentrant C Scanners
+Reentrant C Scanners
- +
flex
has the ability to generate a reentrant C scanner. This is -accomplished by specifying%option reentrant
(`-R') or -%option reentrant-bison
(`-Rb'). The generated scanner is -both portable, and safe to use in one or more separate threads of +accomplished by specifying%option reentrant
(`-R') The generated +scanner is both portable, and safe to use in one or more separate threads of control. The most common use for reentrant scanners is from within -multi-threaded applications. Any thread may create and execute a -reentrantflex
scanner without the need for synchronization with -other threads. +multi-threaded applications. Any thread may create and execute a reentrant +flex
scanner without the need for synchronization with other threads. -Uses for Reentrant Scanners
+Uses for Reentrant Scanners
However, there are other uses for a reentrant scanner. For example, you @@ -3880,7 +4165,7 @@
@verbatim @@ -3901,7 +4186,7 @@Another use for a reentrant scanner is recursion. (Note that a recursive scanner can also be created using a non-reentrant scanner and -buffer states. See section Multiple Input Buffers.) +buffer states. See section Multiple Input Buffers.)
@@ -3910,7 +4195,7 @@
@verbatim @@ -3919,12 +4204,12 @@ %option reentrant %% - "eval(".+")" { + "eval(".+")" { yyscan_t scanner; YY_BUFFER_STATE buf; yylex_init( &scanner ); - yytext[yyleng-1] = ' '; + yytext[yyleng-1] = ' '; buf = yy_scan_string( yytext + 5, scanner ); yylex( scanner ); @@ -3938,10 +4223,10 @@ -An Overview of the Reentrant API
+An Overview of the Reentrant API
- + The API for reentrant scanners is different than for non-reentrant scanners. Here is a quick overview of the API: @@ -3952,7 +4237,7 @@
- -All functions take one additional argument:
yy_globals
+All functions take one additional argument:yyscanner
- @@ -3976,11 +4261,11 @@ -
Reentrant Example
+Reentrant Example
First, an example of a reentrant scanner: - +
@verbatim @@ -3988,15 +4273,15 @@ %option reentrant stack %x COMMENT %% - "//" yy_push_state( COMMENT, yy_globals); + "//" yy_push_state( COMMENT, yyscanner); .|\n - <COMMENT>\n yy_pop_state( yy_globals ); + <COMMENT>\n yy_pop_state( yyscanner ); <COMMENT>[^\n]+ fprintf( yyout, "%s\n", yytext); %% - int main ( int argc, char * argv[] ) + int main ( int argc, char * argv[] ) { yyscan_t scanner; - + yylex_init ( &scanner ); yylex ( scanner ); yylex_destroy ( scanner ); @@ -4006,7 +4291,7 @@ -The Reentrant API in Detail
+The Reentrant API in Detail
Here are the things you need to do or know to use the reentrant C API of @@ -4015,7 +4300,7 @@ -
Declaring a Scanner As Reentrant
+Declaring a Scanner As Reentrant
%option reentrant (--reentrant) must be specified. @@ -4023,7 +4308,7 @@
Notice that
%option reentrant
is specified in the above example -(see section Reentrant Example. Had this option not been specified, +(see section Reentrant Example. Had this option not been specified,flex
would have happily generated a non-reentrant scanner without complaining. You may explicitly specify%option noreentrant
, if you do not want a reentrant scanner, although it is not @@ -4032,17 +4317,17 @@ -The Extra Argument
+The Extra Argument
- - -All functions take one additional argument:
yy_globals
. + + +All functions take one additional argument:yyscanner
.Notice that the calls to
yy_push_state
andyy_pop_state
-both have an argument,yy_globals
, that is not present in a +both have an argument,yyscanner
, that is not present in a non-reentrant scanner. Here are the declarations ofyy_push_state
andyy_pop_state
in the generated scanner: @@ -4050,30 +4335,30 @@@verbatim - static void yy_push_state ( int new_state , yyscan_t yy_globals ) ; - static void yy_pop_state ( yyscan_t yy_globals ) ; + static void yy_push_state ( int new_state , yyscan_t yyscanner ) ; + static void yy_pop_state ( yyscan_t yyscanner ) ;-Notice that the argument
yy_globals
appears in the declaration of +Notice that the argumentyyscanner
appears in the declaration of both functions. In fact, allflex
functions in a reentrant scanner have this additional argument. It is always the last argument in the argument list, it is always of typeyyscan_t
(which is typedef'd tovoid *
) and it is -always namedyy_globals
. As you may have guessed, -yy_globals
is a pointer to an opaque data structure encapsulating +always namedyyscanner
. As you may have guessed, +yyscanner
is a pointer to an opaque data structure encapsulating the current state of the scanner. For a list of function declarations, -see section Functions and Macros Available in Reentrant C Scanners. Note that preprocessor macros, such as +see section Functions and Macros Available in Reentrant C Scanners. Note that preprocessor macros, such asBEGIN
,ECHO
, andREJECT
, do not take this additional argument. -Global Variables Replaced By Macros
+Global Variables Replaced By Macros
- + All global variables in traditional flex have been replaced by macro equivalents. @@ -4091,7 +4376,7 @@
@verbatim -#define yytext (((struct yy_globals_t*)yy_globals)->yytext_r) +#define yytext (((struct yyguts_t*)yyscanner)->yytext_r)@@ -4101,20 +4386,20 @@
yytext
is not a global variable in a reentrant scanner, you can not access it directly from outside an action or from -other functions. You must use an accessor method, e.g., -yyget_text
, +other functions. You must use an accessor method, e.g., +yyget_text
, to accomplish this. (See below). -Init and Destroy Functions
+Init and Destroy Functions
@@ -4126,8 +4411,8 @@
@verbatim int yylex_init ( yyscan_t * ptr_yy_globals ) ; - int yylex ( yyscan_t yy_globals ) ; - int yylex_destroy ( yyscan_t yy_globals ) ; + int yylex ( yyscan_t yyscanner ) ; + int yylex_destroy ( yyscan_t yyscanner ) ;@@ -4142,13 +4427,28 @@
yylex
should be familiar to you by now. The reentrant version takes one argument, which is the value returned (via an argument) byyylex_init
. Otherwise, it behaves the same as the non-reentrant -version ofyylex
. +version ofyylex
. + + ++
yylex_init
returns 0 (zero) on success, or non-zero on failure, +in which case, errno is set to one of the following values: + ++
+- ENOMEM + +Memory allocation error. @xref{memory-management}. +
- EINVAL + +Invalid argument. +
The function
yylex_destroy
should be called to free resources used by the scanner. Afteryylex_destroy
-is called, the contents ofyy_globals
should not be used. Of +is called, the contents ofyyscanner
should not be used. Of course, there is no need to destroy a scanner if you plan to reuse it. Aflex
scanner (both reentrant and non-reentrant) may be restarted by callingyyrestart
. @@ -4179,10 +4479,10 @@ -Accessing Variables with Reentrant Scanners
+Accessing Variables with Reentrant Scanners
- + Accessor methods (get/set functions) provide access to common
flex
variables. @@ -4200,15 +4500,15 @@@verbatim /* Set the last character of yytext to NULL. */ void chop ( yyscan_t scanner ) { - int len = yyget_leng( scanner ); - yyget_text( scanner )[len - 1] = '\0'; + int len = yyget_leng( scanner ); + yyget_text( scanner )[len - 1] = '\0'; }@@ -4220,16 +4520,21 @@@verbatim %% - .+\n { chop( yy_globals );} + .+\n { chop( yyscanner );}++You may find that
%option header-file
is particularly useful for generating +prototypes of all the accessor functions. @xref{option-header}. + -Extra Data
+ +Extra Data
- - + + User-specific data can be stored in
yyextra
. @@ -4253,9 +4558,9 @@@verbatim @@ -4273,19 +4578,19 @@- - - -@verbatim /* An example of overriding YY_EXTRA_TYPE. */ - %{ + %{ #include <sys/stat.h> #include <unistd.h> #define YY_EXTRA_TYPE struct stat* %} %option reentrant %% - + __filesize__ printf( "%ld", yyextra->st_size ); __lastmod__ printf( "%ld", yyextra->st_mtime ); %% @@ -4293,10 +4598,10 @@ { yyscan_t scanner; struct stat buf; - + yylex_init ( &scanner ); yyset_in( fopen(filename,"r"), scanner ); - + stat( filename, &buf); yyset_extra( &buf, scanner ); yylex ( scanner ); @@ -4306,10 +4611,10 @@ -About yyscan_t
+About yyscan_t
- +
yyscan_t
is defined as: @@ -4328,156 +4633,25 @@ -Reentrant C Scanners with Bison Pure Parsers
- --This section describes the
flex
features useful when integrating -flex
withGNU bison
(1). -Skip this section if you are not using -bison
with your scanner. Here we discuss only theflex
-half of theflex
andbison
pair. We do not discuss -bison
in any detail. For more information about generating pure -bison
parsers, see section `Top' in the GNU Bison Manual. - - --A
bison
-compatible scanner is generated by declaring `%option -reentrant-bison' or by supplying `--reentrant-bison' when invokingflex
-from the command line. This instructsflex
that the macros -yylval
andyylloc
may be used. The data types for -yylval
andyylloc
, (YYSTYPE
andYYLTYPE
, -are typically defined in a header file, included in section 1 of the -flex
input file.%option reentrant-bison
implies -%option reentrant
. If%option reentrant-bison
is -specified,flex
provides support for the functions -yyget_lval
,yyset_lval
,yyget_lloc
, and -yyset_lloc
, defined below, and the corresponding macros -yylval
andyylloc
, for use within actions. - - --
-
- - - --Accordingly, the declaration of yylex becomes one of the following: - - -
-@verbatim - int yylex ( YYSTYPE * lvalp, yyscan_t scanner ); - int yylex ( YYSTYPE * lvalp, YYLTYPE * llocp, yyscan_t scanner ); -- --Note that the macros
yylval
andyylloc
evaluate to -pointers. Support foryylloc
is optional inbison
, so it -is optional inflex
as well. This support is automatically -handled byflex
. Specifically, support foryyloc
is only -present in aflex
scanner if the preprocessor symbol -YYLTYPE
is defined. The following is an example of aflex
-scanner that isbison
-compatible. - - --@verbatim - /* Scanner for "C" assignment statements... sort of. */ - %{ - #include "y.tab.h" /* Generated by bison. */ - %} - - %option reentrant-bison - % - - [[:digit:]]+ { yylval->num = atoi(yytext); return NUMBER;} - [[:alnum:]]+ { yylval->str = strdup(yytext); return STRING;} - "="|";" { return yytext[0];} - . {} - % -- --As you can see, there really is no magic here. We just use -
yylval
as we would any other variable. The data type of -yylval
is generated bybison
, and included in the file -`y.tab.h'. Here is the correspondingbison
parser: - - --@verbatim - /* Parser to convert "C" assignments to lisp. */ - %{ - /* Pass the argument to yyparse through to yylex. */ - #define YYPARSE_PARAM scanner - #define YYLEX_PARAM scanner - %} - %pure_parser - %union { - int num; - char* str; - } - %token <str> STRING - %token <num> NUMBER - %% - assignment: - STRING '=' NUMBER ';' { - printf( "(setf %s %d)", $1, $3 ); - } - ; -- - - -Functions and Macros Available in Reentrant C Scanners
+Functions and Macros Available in Reentrant C Scanners
The following Functions are available in a reentrant scanner:
- - - - - - - - + + + + + + + + + + + + @@ -4489,7 +4663,9 @@ FILE *yyget_out ( yyscan_t scanner ); int yyget_lineno ( yyscan_t scanner ); YY_EXTRA_TYPE yyget_extra ( yyscan_t scanner ); + int yyget_debug ( yyscan_t scanner ); + void yyset_debug ( int flag, yyscan_t scanner ); void yyset_in ( FILE * in_str , yyscan_t scanner ); void yyset_out ( FILE * out_str , yyscan_t scanner ); void yyset_lineno ( int line_number , yyscan_t scanner ); @@ -4514,10 +4690,11 @@ yyout yylineno yyextra + yy_flex_debug
- + In a reentrant C scanner, support for yylineno is always present (i.e., you may access yylineno), but the value is never modified by
flex
unless%option yylineno
is enabled. This is to allow @@ -4526,7 +4703,7 @@The following functions and macros are made available when
%option -reentrant-bison
(`--reentrant-bison') is specified: +bison-bridge (`--bison-bridge') is specified: @@ -4550,11 +4727,11 @@ -Incompatibilities with Lex and Posix
+Incompatibilities with Lex and Posix
@@ -4622,7 +4799,7 @@ which long-jumps out of the scanner, and the scanner is subsequently called again, you may get the following message: - +
@verbatim @@ -4631,7 +4808,7 @@ To reenter the scanner, first use: - +@verbatim @@ -4639,7 +4816,7 @@Note that this call will throw away any buffered input; usually this -isn't a problem with an interactive scanner. See section Reentrant C Scanners, for +isn't a problem with an interactive scanner. See section Reentrant C Scanners, forflex
's reentrant API.
flex
C++ scanner classes
are
reentrant, so if using C++ is an option for you, you should use
-them instead. See section Generating C++ Scanners, and section Reentrant C Scanners for details.
+them instead. See section Generating C++ Scanners, and section Reentrant C Scanners for details.
flex
encloses them in parentheses.
With lex
, the following:
-
+
@verbatim @@ -4706,7 +4883,7 @@ Some implementations oflex
allow a rule's action to begin on a separate line, if the rule's pattern has trailing whitespace: - +@verbatim @@ -4756,48 +4933,88 @@ The nameFLEX_SCANNER
is#define
'd so scanners may be written for use with eitherflex
orlex
. Scanners also -includeYY_FLEX_MAJOR_VERSION
andYY_FLEX_MINOR_VERSION
-indicating which version offlex
generated the scanner (for -example, for the 2.5 release, these defines would be 2 and 5 -respectively). +includeYY_FLEX_MAJOR_VERSION
,YY_FLEX_MINOR_VERSION
+andYY_FLEX_SUBMINOR_VERSION
+indicating which version offlex
generated the scanner. For +example, for the 2.5.22 release, these defines would be 2, 5 and 22 +respectively. If the version offlex
being used is a beta +version, then the symbolFLEX_BETA
is defined.+ + The following
flex
features are not included inlex
or the POSIX specification: --@verbatim - C++ scanners - %option - start condition scopes - start condition stacks - interactive/non-interactive scanners - yy_scan_string() and friends - yyterminate() - yy_set_interactive() - yy_set_bol() - YY_AT_BOL() +
flex
command-line options
+
-plus almost all of the flex
flags. The last feature in the list
+The feature "multiple actions on a line"
refers to the fact that with flex
you can put multiple actions on
the same line, separated with semi-colons, while with lex
, the
following:
@@ -4826,11 +5043,577 @@
-
- - + +@anchor{memory-management} +This chapter describes how flex handles dynamic memory, and how you can +override the default behavior. + + + + +
+Flex allocates dynamic memory during initialization, and once in a while from
+within a call to yylex(). Initialization takes place during the first call to
+yylex(). Thereafter, flex may reallocate more memory if it needs to enlarge a
+buffer. As of version 2.5.9 Flex will clean up all memory when you call yylex_destroy
+@xref{faq-memory-leak}.
+
+
+
+Flex allocates dynamic memory for four purposes, listed below (1) + + +
%option stack
is not
+specified. You will rarely need to tune this buffer. The ideal size for this
+stack is the maximum depth expected. The memory for this stack is
+automatically destroyed when you call yylex_destroy(). @xref{option-stack}.
+
+
+Flex calls the functions yyalloc
, yyrealloc
, and yyfree
+when it needs to allocate or free memory. By default, these functions are
+wrappers around the standard C functions, malloc
, realloc
, and
+free
, respectively. You can override the default implementations by telling
+flex that you will provide your own implementations.
+
+
+
+To override the default implementations, you must do two things: + + + +
+@verbatim +// For a non-reentrant scanner +void * yyalloc (size_t bytes); +void * yyrealloc (void * ptr, size_t bytes); +void yyfree (void * ptr); + +// For a reentrant scanner +void * yyalloc (size_t bytes, void * yyscanner); +void * yyrealloc (void * ptr, size_t bytes, void * yyscanner); +void yyfree (void * ptr, void * yyscanner); ++ +
+In the following example, we will override all three memory routines. We assume
+that there is a custom allocator with garbage collection. In order to make this
+example interesting, we will use a reentrant scanner, passing a pointer to the
+custom allocator through yyextra
.
+
+
+
+@verbatim +%{ +#include "some_allocator.h" +%} + +/* Suppress the default implementations. */ +%option noyyalloc noyyrealloc noyyfree +%option reentrant + +/* Initialize the allocator. */ +#define YY_EXTRA_TYPE struct allocator* +#define YY_USER_INIT yyextra = allocator_create(); + +%% +.|\n ; +%% + +/* Provide our own implementations. */ +void * yyalloc (size_t bytes, void* yyscanner) { + return allocator_alloc (yyextra, bytes); +} + +void * yyrealloc (void * ptr, size_t bytes, void* yyscanner) { + return allocator_realloc (yyextra, bytes); +} + +void yyfree (void * ptr, void * yyscanner) { + /* Do nothing -- we leave it to the garbage collector. */ +} + ++ + + +
+When flex finds a match, yytext
points to the first character of the
+match in the input buffer. The string itself is part of the input buffer, and
+is NOT allocated separately. The value of yytext will be overwritten the next
+time yylex() is called. In short, the value of yytext is only valid from within
+the matched rule's action.
+
+
+
+Often, you want the value of yytext to persist for later processing, i.e., by a +parser with non-zero lookahead. In order to preserve yytext, you will have to +copy it with strdup() or a similar function. But this introduces some headache +because your parser is now responsible for freeing the copy of yytext. If you +use a yacc or bison parser, (commonly used with flex), you will discover that +the error recovery mechanisms can cause memory to be leaked. + + +
+To prevent memory leaks from strdup'd yytext, you will have to track the memory +somehow. Our experience has shown that a garbage collection mechanism or a +pooled memory mechanism will save you a lot of grief when writing parsers. + + + + +
+@anchor{serialization}
+A flex
scanner has the ability to save the DFA tables to a file, and
+load them at runtime when needed. The motivation for this feature is to reduce
+the runtime memory footprint. Traditionally, these tables have been compiled into
+the scanner as C arrays, and are sometimes quite large. Since the tables are
+compiled into the scanner, the memory used by the tables can never be freed.
+This is a waste of memory, especially if an application uses several scanners,
+but none of them at the same time.
+
+
+
+The serialization feature allows the tables to be loaded at runtime, before +scanning begins. The tables may be discarded when scanning is finished. + + + + +
+You may create a scanner with serialized tables by specifying: + + + +
+@verbatim + %option tables-file=FILE +or + --tables-file=FILE ++ +
+These options instruct flex to save the DFA tables to the file FILE. The tables +will not be embedded in the generated scanner. The scanner will not +function on its own. The scanner will be dependent upon the serialized tables. You must +load the tables from this file at runtime before you can scan anything. + + +
+If you do not specify a filename to --tables-file
, the tables will be
+saved to `lex.yy.tables', where `yy' is the appropriate prefix.
+
+
+
+If your project uses several different scanners, you can concatenate the +serialized tables into one file, and flex will find the correct set of tables, +using the scanner prefix as part of the lookup key. An example follows: + + +
+@verbatim +$ flex --tables-file --prefix=cpp cpp.l +$ flex --tables-file --prefix=c c.l +$ cat lex.cpp.tables lex.c.tables > all.tables ++ +
+The above example created two scanners, `cpp', and `c'. Since we did +not specify a filename, the tables were serialized to `lex.c.tables' and +`lex.cpp.tables', respectively. Then, we concatenated the two files +together into `all.tables', which we will distribute with our project. At +runtime, we will open the file and tell flex to load the tables from it. Flex +will find the correct tables automatically. (See next section). + + + + +
+If you've built your scanner with %option tables-file
, then you must
+load the scanner tables at runtime. This can be accomplished with the following
+function:
+
+
+
+
yyalloc
. You must call this
+function before the first call to yylex
. The argument scanner
+only appears in the reentrant scanner.
+This function returns `0' (zero) on success, or non-zero on error.
+
+The loaded tables are not automatically destroyed (unloaded) when you
+call yylex_destroy
. The reason is that you may create several scanners
+of the same type (in a reentrant scanner), each of which needs access to these
+tables. To avoid a nasty memory leak, you must call the following function:
+
+
+
+
+The functions yytables_fload
and yytables_destroy
are not
+thread-safe. You must ensure that these functions are called exactly once (for
+each scanner type) in a threaded program, before any thread calls yylex
.
+After the tables are loaded, they are never written to, and no thread
+protection is required thereafter -- until you destroy them.
+
+
+
+
+
+This section defines the file format of serialized flex
tables.
+
+
+
+The tables format allows for one or more sets of tables to be +specified, where each set corresponds to a given scanner. Scanners are +indexed by name, as described below. The file format is as follows: + + + +
+@verbatim + TABLE SET 1 + +-------------------------------+ + Header | uint32 th_magic; | + | uint32 th_hsize; | + | uint32 th_ssize; | + | uint16 th_flags; | + | char th_version[]; | + | char th_name[]; | + | uint8 th_pad64[]; | + +-------------------------------+ + Table 1 | uint16 td_id; | + | uint16 td_flags; | + | uint32 td_lolen; | + | uint32 td_hilen; | + | void td_data[]; | + | uint8 td_pad64[]; | + +-------------------------------+ + Table 2 | | + . . . + . . . + . . . + . . . + Table n | | + +-------------------------------+ + TABLE SET 2 + . + . + . + TABLE SET N ++ +
+The above diagram shows that a complete set of tables consists of a header +followed by multiple individual tables. Furthermore, multiple complete sets may +be present in the same file, each set with its own header and tables. The sets +are contiguous in the file. The only way to know if another set follows is to +check the next four bytes for the magic number (or check for EOF). The header +and tables sections are padded to 64-bit boundaries. Below we describe each +field in detail. This format does not specify how the scanner will expand the +given data, i.e., data may be serialized as int8, but expanded to an int32 +array at runtime. This is to reduce the size of the serialized data where +possible. Remember, all integer values are in network byte order. + + +
+Fields of a table header: + + +
th_magic
+th_hsize
+th_ssize
+th_flags
+th_version[]
+th_name[]
+th_pad64[]
++Fields of a table: + + +
td_id
+YYTD_ID_ACCEPT (0x01)
+yy_accept
+YYTD_ID_BASE (0x02)
+yy_base
+YYTD_ID_CHK (0x03)
+yy_chk
+YYTD_ID_DEF (0x04)
+yy_def
+YYTD_ID_EC (0x05)
+yy_ec
+YYTD_ID_META (0x06)
+yy_meta
+YYTD_ID_NUL_TRANS (0x07)
+yy_NUL_trans
+YYTD_ID_NXT (0x08)
+yy_nxt
. This array may be two dimensional. See the td_hilen
+field below.
+YYTD_ID_RULE_CAN_MATCH_EOL (0x09)
+yy_rule_can_match_eol
+YYTD_ID_START_STATE_LIST (0x0A)
+yy_start_state_list
. This array is handled specially because it is an
+array of pointers to structs. See the td_flags
field below.
+YYTD_ID_TRANSITION (0x0B)
+yy_transition
. This array is handled specially because it is an array of
+structs. See the td_lolen
field below.
+YYTD_ID_ACCLIST (0x0C)
+yy_acclist
+td_flags
+td_data
.
+The data arrays are one-dimensional by default, but may be
+two dimensional as specified in the td_hilen
field.
+
+YYTD_DATA8 (0x01)
+YYTD_DATA16 (0x02)
+YYTD_DATA32 (0x04)
+YYTD_PTRANS (0x08)
+yy_transition
+array. Each index should be expanded to a pointer to the corresponding entry
+in the yy_transition
array. We count on the fact that the
+yy_transition
array has already been seen.
+YYTD_STRUCT (0x10)
+YYTD_DATA*
bits.
+td_lolen
+td_flags
field.
+
+td_hilen
+td_hilen
is non-zero, then the data is a two-dimensional array.
+Otherwise, the data is a one-dimensional array. td_hilen
contains the
+number of elements in the higher dimensional array, and td_lolen
contains
+the number of elements in the lowest dimension.
+
+Conceptually, td_data
is either sometype td_data[td_lolen]
, or
+sometype td_data[td_hilen][td_lolen]
, where sometype
is specified
+by the td_flags
field. It is possible for both td_lolen
and
+td_hilen
to be zero, in which case td_data
is a zero length
+array, and no data is loaded, i.e., this table is simply skipped. Flex does not
+currently generate tables of zero length.
+
+td_data[]
+int8
, int16
, int32
, struct yy_trans_info
, or
+struct yy_trans_info*
, depending upon the values in the
+td_flags
, td_lolen
, and td_hilen
fields.
+
+td_pad64[]
+@@ -4846,7 +5629,7 @@ the same text as it. For example, in the following `foo' cannot be matched because it comes after an identifier "catch-all" rule: - +
@verbatim @@ -4862,7 +5645,7 @@ that it is possible (perhaps only in a particular start condition) that the default rule (match any single character) is the only one that will match a particular input. Since `-s' was given, presumably this is -not intended. +not intended.
@@ -4960,7 +5743,7 @@
@verbatim @@ -4992,7 +5775,7 @@ -Additional Reading
+Additional Reading
You may wish to read more about the following programs: @@ -5032,107 +5815,28 @@ -
Copyright
- --The flex manual is placed under the same licensing conditions as the -rest of flex: - - -
-Copyright (C) 1990, 1997 The Regents of the University of California. -All rights reserved. - +
FAQ
-This code is derived from software contributed to Berkeley by -Vern Paxson. - +From time to time, the
flex
maintainer receives certain +questions. Rather than repeat answers to well-understood problems, we +publish them here. --The United States Government has rights in this work pursuant -to contract no. DE-AC03-76SF00098 between the United States -Department of Energy and the University of California. -
-Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - - -
-
- -- - -Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - -
- - -Redistributions in binary form must reproduce the above copyright -notice, this list of conditions and the following disclaimer in the -documentation and/or other materials provided with the distribution. -
-Neither the name of the University nor the names of its contributors -may be used to endorse or promote products derived from this software -without specific prior written permission. - - -
-THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR -IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. - - - - -
Reporting Bugs
- --If you have problems with
flex
or think you have found a bug, -please send mail detailing your problem to -help-flex@gnu.org. Patches are always welcome. - - - - -FAQ
- - - -When was flex born?
- --When was flex born? +
When was flex born?
Vern Paxson took over -the Software Tools lex project from Jef Poskanzer in 1982. At that point it +the Software Tools lex project from Jef Poskanzer in 1982. At that point it was written in Ratfor. Around 1987 or so, Paxson translated it into C, and a legend was born :-). -
How do I expand \ escape sequences in C-style quoted strings?
- --How do I expand \ escape sequences in C-style quoted strings? - +
How do I expand \ escape sequences in C-style quoted strings?
A key point when scanning quoted strings is that you cannot (easily) write @@ -5143,41 +5847,36 @@
-Instead you use exclusive start conditions and a set of rules, one for +Instead you can use exclusive start conditions and a set of rules, one for matching non-escaped text, one for matching a single escape, one for matching an embedded newline, and one for recognizing the end of the string. Each of these rules is then faced with the question of where to put its intermediary results. The best solution is for the rules to -append their local value of yytext to the end of a "string literal" +append their local value of
yytext
to the end of a "string literal" buffer. A rule like the escape-matcher will append to the buffer the -meaning of the escape sequence rather than the literal text in yytext. -In this way, yytext does not need to be modified at all. +meaning of the escape sequence rather than the literal text inyytext
. +In this way,yytext
does not need to be modified at all. -Why do flex scanners call fileno if it is not ANSI compatible?
+Why do flex scanners call fileno if it is not ANSI compatible?
-Why do flex scanners call fileno if it is not ANSI compatible? +Flex scanners call
fileno()
in order to get the file descriptor +corresponding toyyin
. The file descriptor may be passed to +isatty()
orread()
, depending upon which%options
you specified. +If your system does not havefileno()
support, to get rid of the +read()
call, do not specify%option read
. To get rid of theisatty()
+call, you must specify one of%option always-interactive
or +%option never-interactive
. --Flex scanners call fileno() in order to get the file descriptor -corresponding to yyin. The file descriptor may be passed to -isatty() or read(), depending upon which %options you specified. -If your system does not have fileno() support. To get rid of the -read() call, do not specify %option read. To get rid of the isatty() -call, you must specify one of %option always-interactive or -%option never-interactive. - - -
Does flex support recursive pattern definitions?
+Does flex support recursive pattern definitions?
-Does flex support recursive pattern definitions? e.g., @@ -5189,39 +5888,31 @@
-No. You cannot have recursive definitions. The pattern-matching power of +No. You cannot have recursive definitions. The pattern-matching power of regular expressions in general (and therefore flex scanners, too) is limited. In particular, regular expressions cannot "balance" parentheses to an arbitrary degree. For example, it's impossible to write a regular expression that matches all strings containing the same number of '{'s as '}'s. For more powerful pattern matching, you need a parser, such -as GNU bison. - +as GNU bison. -
-How do skip huge chunks of input (tens of megabytes) while using flex? +
-Use fseek (or lseek) to position yyin, then call yyrestart().
+Use fseek()
(or lseek()
) to position yyin, then call yyrestart()
.
-
-Flex is not matching my patterns in the same order that I defined them. - - -
-This is indeed the natural way to expect it to work, however, flex picks the
+flex
picks the
rule that matches the most text (i.e., the longest possible input string).
-This is because flex uses an entirely different matching technique
+This is because flex
uses an entirely different matching technique
("deterministic finite automata") that actually does all of the matching
simultaneously, in parallel. (Seems impossible, but it's actually a fairly
simple technique once you understand the principles.)
@@ -5229,13 +5920,12 @@
A side-effect of this parallel matching is that when the input matches more
-than one rule, flex scanners pick the rule that matched the *most* text. This
-is explained further in the manual, in the section "How the input
-is Matched".
+than one rule, flex
scanners pick the rule that matched the most text. This
+is explained further in the manual, in the section See section How the Input Is Matched.
-If you want flex to choose a shorter match, then you can work around this
+If you want flex
to choose a shorter match, then you can work around this
behavior by expanding your short
rule to match more text, then put back the extra:
@@ -5248,26 +5938,21 @@
Another fix would be to make the second rule active only during the
-<BLOCKIDSTATE> start condition, and make that start condition exclusive
-by declaring it with %x instead of %s.
+<BLOCKIDSTATE>
start condition, and make that start condition exclusive
+by declaring it with %x
instead of %s
.
A final fix is to change the input language so that the ambiguity for -data_ is removed, by adding characters to it that don't match the -identifier rule, or by removing characters (such as '_') from the -identifier rule so it no longer matches "data_". (Of course, you might -also not have the option of changing the input language ...) - +`data_' is removed, by adding characters to it that don't match the +identifier rule, or by removing characters (such as `_') from the +identifier rule so it no longer matches `data_'. (Of course, you might +also not have the option of changing the input language.) -
-My actions are executing out of order or sometimes not at all. What's -happening? +
Most likely, you have (in error) placed the opening `{' of the action @@ -5278,13 +5963,13 @@
@verbatim ^(foo|bar) - { <<<--- WRONG! +{ <<<--- WRONG! - } +}
-flex requires that the opening `{' of an action associated with a rule
+flex
requires that the opening `{' of an action associated with a rule
begin on the same line as does the rule. You need instead to write your rules
as follows:
@@ -5294,79 +5979,70 @@
@verbatim
^(foo|bar) { // CORRECT!
- }
+}
-
-How can I have multiple input sources feed into the same scanner at -the same time? - +
-If... +If ...
flex
's `-b' flag),
YY_INPUT
to do so,
then every time it matches a token, it will have exhausted its input
buffer (because the scanner is free of backtracking). This means you
-can safely use select() at the point and only call yylex() for another
-token if select() indicates there's data available.
+can safely use select()
at the point and only call yylex()
for another
+token if select()
indicates there's data available.
-That is, move the select() out from the input function to a point where
-it determines whether yylex() gets called for the next token.
+That is, move the select()
out from the input function to a point where
+it determines whether yylex()
gets called for the next token.
With this approach, you will still have problems if your input can arrive
-piecemeal; select() could inform you that the beginning of a token is
-available, you call yylex() to get it, but it winds up blocking waiting
+piecemeal; select()
could inform you that the beginning of a token is
+available, you call yylex()
to get it, but it winds up blocking waiting
for the later characters in the token.
-Here's another way: Move your input multiplexing inside of YY_INPUT. That
-is, whenever YY_INPUT is called, it select()'s to see where input is
+Here's another way: Move your input multiplexing inside of YY_INPUT
. That
+is, whenever YY_INPUT
is called, it select()
's to see where input is
available. If input is available for the scanner, it reads and returns the
next byte. If input is available from another source, it calls whatever
function is responsible for reading from that source. (If no input is
-available, it blocks until some is.) I've used this technique in an
-interpreter I wrote that both reads keyboard input using a flex scanner and
+available, it blocks until some input is available.) I've used this technique in an
+interpreter I wrote that both reads keyboard input using a flex
scanner and
IPC traffic from sockets, and it works fine.
-
-Can I build nested parsers that work with the same input file? - +
This is not going to work without some additional effort. The reason is
-that flex block-buffers the input it reads from yyin. This means that the
-"outermost" yylex(), when called, will automatically slurp up the first 8K
-of input available on yyin, and subsequent calls to other yylex()'s won't
+that flex
block-buffers the input it reads from yyin
. This means that the
+"outermost" yylex()
, when called, will automatically slurp up the first 8K
+of input available on yyin, and subsequent calls to other yylex()
's won't
see that input. You might be tempted to work around this problem by
-redefining YY_INPUT to only return a small amount of text, but it turns out
+redefining YY_INPUT
to only return a small amount of text, but it turns out
that that approach is quite difficult. Instead, the best solution is to
combine all of your scanners into one large scanner, using a different
exclusive start condition for each.
@@ -5374,19 +6050,15 @@
-
-How can I match text only at the end of a file? - +
There is no way to write a rule which is "match this text, but only if
it comes at the end of the file". You can fake it, though, if you happen
to have a character lying around that you don't allow in your input.
-Then you redefine YY_INPUT to call your own routine which, if it sees
-an EOF, returns the magic character first (and remembers to return a
-real EOF next time it's called). Then you could write:
+Then you redefine YY_INPUT
to call your own routine which, if it sees
+an `EOF', returns the magic character first (and remembers to return a
+real EOF
next time it's called). Then you could write:
@@ -5397,16 +6069,12 @@
-
-How can I make REJECT cascade across start condition boundaries? - +
-You can do this as follows. Suppose you have a start condition A, and -after exhausting all of the possible matches in <A>, you want to try -matches in <INITIAL>. Then you could use the following: +You can do this as follows. Suppose you have a start condition `A', and +after exhausting all of the possible matches in `<A>', you want to try +matches in `<INITIAL>'. Then you could use the following: @@ -5419,29 +6087,25 @@ <A>etc. ... <A>.|\n { - /* Shortest and last rule in <A>, so - * cascaded REJECT's will eventually - * wind up matching this rule. We want - * to now switch to the initial state - * and try matching from there instead. - */ - yyless(0); /* put back matched text */ - BEGIN(INITIAL); - } +/* Shortest and last rule in <A>, so +* cascaded REJECT's will eventually +* wind up matching this rule. We want +* to now switch to the initial state +* and try matching from there instead. +*/ +yyless(0); /* put back matched text */ +BEGIN(INITIAL); +} -
-Why can't I use fast or full tables with interactive mode? - +
One of the assumptions -flex makes is that interactive applications are inherently slow (for just -that reason, they're waiting on a human). +flex makes is that interactive applications are inherently slow (they're +waiting on a human after all). It has to do with how the scanner detects that it must be finished scanning a token. For interactive scanners, after scanning each character the current state is looked up in a table (essentially) to see whether there's a chance @@ -5456,16 +6120,12 @@ Still, it seems reasonable to allow the user to choose to trade off a bit of performance in this area to gain the corresponding flexibility. There might be another reason, though, why fast scanners don't support the -interactive option +interactive option. -
-How much faster is -F or -f than -C? - +
Much faster (factor of 2-3). @@ -5473,11 +6133,7 @@ -
-If I have a simple grammar, can't I just parse it with flex? - +
Is your grammar recursive? That's almost always a sign that you're @@ -5485,26 +6141,20 @@ alone. -
-Why doesn't yyrestart() set the start state back to INITIAL? +
There are two reasons. The first is that there might
be programs that rely on the start state not changing across file changes.
-The second is that with flex 2.4, use of yyrestart() is no longer required,
-so fixing the problem there doesn't solve the more general problem.
-
+The second is that beginning with flex
version 2.4, use of yyrestart()
is no longer required,
+so fixing the problem there doesn't solve the more general problem.
-
-How can I match C-style comments? +
You might be tempted to try something like this: @@ -5533,7 +6183,7 @@
@verbatim - /* a comment */ do_my_thing( "oops */" ); +/* a comment */ do_my_thing( "oops */" );
@@ -5544,23 +6194,19 @@
@verbatim <INITIAL>{ - "/*" BEGIN(IN_COMMENT); +"/*" BEGIN(IN_COMMENT); } <IN_COMMENT>{ - "*/" BEGIN(INITIAL); - [^*\n]+ // eat comment in chunks - "*" // eat the lone star - \n yylineno++; +"*/" BEGIN(INITIAL); +[^*\n]+ // eat comment in chunks +"*" // eat the lone star +\n yylineno++; }-
-The '.' (dot) isn't working the way I expected. - +
Here are some tips for using `.':
@@ -5574,47 +6220,37 @@
you really meant to place the parenthesis BEFORE the operator, e.g., you
probably want this (foo|bar)+
and NOT this (foo|bar+)
.
-The first pattern matches the words foo
or bar
any number of
-times, e.g., it matches the text barfoofoobarfoo
. The
+The first pattern matches the words `foo' or `bar' any number of
+times, e.g., it matches the text `barfoofoobarfoo'. The
second pattern matches a single instance of foo
or a single instance of
-ba
followed by one or more `r's, e.g., it matches the text barrrr
.
+bar
followed by one or more `r's, e.g., it matches the text barrrr
.
(.|\n)
---- Beware that the regex (.|\n)+
will match your entire input!
+Beware that the regex (.|\n)+
will match your entire input!
-Can I get the flex manual in another format?
+The flex
source distribution includes a texinfo manual. You are
+free to convert that texinfo into whatever format you desire. The
+texinfo
package includes tools for conversion to a number of formats.
-
-As of flex 2.5, the manual is distributed in texinfo format. -You can use the "texi2*" tools to convert the manual to any format -you desire (e.g., `texi2html'). - - -
-Does there exist a "faster" NDFA->DFA algorithm? Most standard texts (e.g., -Aho), imply that NDFA->DFA can take exponential time, since there are -exponential number of potential states in NDFA. - +
There's no way around the potential exponential running time - it @@ -5625,14 +6261,10 @@ -
-How does flex compile the DFA so quickly? - - -
-There are two big speed wins that flex uses:
+There are two big speed wins that flex
uses:
@@ -5654,16 +6286,12 @@
-
-How can I use more than 8192 rules? - +
-Flex is compiled with an upper limit of 8192 rules per scanner.
-If you need more than 8192 rules in your scanner, you'll have to recompile flex
-with the following changes in flexdef.h:
+Flex
is compiled with an upper limit of 8192 rules per scanner.
+If you need more than 8192 rules in your scanner, you'll have to recompile flex
+with the following changes in `flexdef.h':
@@ -5682,150 +6310,117 @@
is the best way to solve your problem.
-
-
-
-How do I abandon a file in the middle of a scan and switch to a new file? - - -
-Just all yyrestart(newfile). Be sure to reset the start state if you want a -"fresh" start, since yyrestart does NOT reset the start state back to INITIAL. - - - - -
-How do I execute code only during initialization (only before the first scan)? +The following may also be relevant:
-You can specify an initial action by defining the macro YY_USER_INIT (though -note that yyout may not be available at the time this macro is executed). Or you -can add to the beginning of your rules section: +With luck, you should be able to increase the definitions in flexdef.h for:
@verbatim -%% - /* Must be indented! */ - static int did_init = 0; - - if ( ! did_init ){ - do_my_init(); - did_init = 1; - } +#define JAMSTATE -32766 /* marks a reference to the state that always jams */ +#define MAXIMUM_MNS 31999 +#define BAD_SUBSCRIPT -32767- - -
-How do I execute code at termination (i.e., only after the last scan?) - - -
-You can specifiy an action for the <<EOF>> rule. +recompile everything, and it'll all work. Flex only has these 16-bit-like +values built into it because a long time ago it was developed on a machine +with 16-bit ints. I've given this advice to others in the past but haven't +heard back from them whether it worked okay or not... -
-Where else can I find help? +
-The help-flex
email list is served by GNU. See http://www.gnu.org/ for
-details how to subscribe or search the archives.
+Just call yyrestart(newfile)
. Be sure to reset the start state if you want a
+"fresh start, since yyrestart
does NOT reset the start state back to INITIAL
.
-
-Can I include comments in the "rules" section of the file file?
-
+You can specify an initial action by defining the macro YY_USER_INIT
(though
+note that yyout
may not be available at the time this macro is executed). Or you
+can add to the beginning of your rules section:
-
-Yes, just about anywhere you want to. See the manual for the specific syntax. +
+@verbatim +%% +/* Must be indented! */ +static int did_init = 0; +if ( ! did_init ){ +do_my_init(); +did_init = 1; +} +-
-I get an error about undefined yywrap(). +
-You must supply a yywrap() function of your own, or link to libfl.a
-(which provides one), or use
+You can specify an action for the <<EOF>>
rule.
-
- %option noyywrap -
-in your source to say you don't want a yywrap() function. -See the manual page for more details concerning yywrap(). - +
+The help-flex
email list is served by GNU. See http://www.gnu.org/ for
+details on how to subscribe or search the archives.
-
-How can I change the matching pattern at run time? +
-You can't, it's compiled into a static table when flex builds the scanner. - - +Yes, just about anywhere you want to. See the manual for the specific syntax. -
-Is there a way to increase the rules (NFA states to a bigger number?) +
-With luck, you should be able to increase the definitions in flexdef.h for:
+You must supply a yywrap()
function of your own, or link to `libfl.a'
+(which provides one), or use
@verbatim -#define JAMSTATE -32766 /* marks a reference to the state that always jams */ -#define MAXIMUM_MNS 31999 -#define BAD_SUBSCRIPT -32767 +%option noyywrap
-recompile everything, and it'll all work. Flex only has these 16-bit-like
-values built into it because a long time ago it was developed on a machine
-with 16-bit ints. I've given this advice to others in the past but haven't
-heard back from them whether it worked okay or not...
+in your source to say you don't want a yywrap()
function.
-
-How can I expand macros in the input? +You can't, it's compiled into a static table when flex builds the scanner. + + +
The best way to approach this problem is at a higher level, e.g., in the parser. @@ -5839,24 +6434,24 @@ @verbatim %% macro/[a-z]+ { - /* Saw the macro "macro" followed by extra stuff. */ - main_buffer = YY_CURRENT_BUFFER; - expansion_buffer = yy_scan_string(expand(yytext)); - yy_switch_to_buffer(expansion_buffer); - } +/* Saw the macro "macro" followed by extra stuff. */ +main_buffer = YY_CURRENT_BUFFER; +expansion_buffer = yy_scan_string(expand(yytext)); +yy_switch_to_buffer(expansion_buffer); +} <<EOF>> { - if ( expansion_buffer ) - { - // We were doing an expansion, return to where - // we were. - yy_switch_to_buffer(main_buffer); - yy_delete_buffer(expansion_buffer); - expansion_buffer = 0; - } - else - yyterminate(); - } +if ( expansion_buffer ) +{ +// We were doing an expansion, return to where +// we were. +yy_switch_to_buffer(main_buffer); +yy_delete_buffer(expansion_buffer); +expansion_buffer = 0; +} +else +yyterminate(); +}
@@ -5866,11 +6461,7 @@ -
-How can I build a two-pass scanner? - +
One way to do it is to filter the first pass to a temporary file, @@ -5890,16 +6481,12 @@ -
-How do I match any string not matched in the preceding rules? - +
One way to assign precedence, is to place the more specific rules first. If
two rules would match the same input (same sequence of characters) then the
-first rule listed in the flex input wins. e.g.,
+first rule listed in the flex
input wins. e.g.,
@@ -5914,47 +6501,35 @@
Note that the rule [a-zA-Z_]+
must come *after* the others. It will match the
same amount of text as the more specific rules, and in that case the
-flex scanner will pick the first rule listed in your scanner as the
+flex
scanner will pick the first rule listed in your scanner as the
one to match.
-
-I am trying to port code from AT&T lex that uses yysptr and yysbuf. - +
Those are internal variables pointing into the AT&T scanner's input buffer. I
-imagine they're being manipulated in user versions of the input() and unput()
+imagine they're being manipulated in user versions of the input()
and unput()
functions. If so, what you need to do is analyze those functions to figure out
-what they're doing, and then replace input() with an appropriate definition of
-YY_INPUT (see the flex man page). You shouldn't need to (and must not) replace
-flex's unput() function.
+what they're doing, and then replace input()
with an appropriate definition of
+YY_INPUT
. You shouldn't need to (and must not) replace
+flex
's unput()
function.
-
-Is there a way to make flex treat NULL like a regular character?
+Yes, `\0' and `\x00' should both do the trick. Perhaps you have an ancient
+version of flex
. The latest release is version 2.5.23.
-
-Yes, \0 and \x00 should both do the trick. Perhaps you have an ancient -version of flex. The latest release is version 2.5.8. - - -
-Whenever flex can not match the input it says "flex scanner jammed". - +
You need to add a rule that matches the otherwise-unmatched text. @@ -5972,16 +6547,12 @@
-See %option default for more information.
+See %option default
for more information.
-
-Why doesn't flex have non-greedy operators like perl does? - +
A DFA can do a non-greedy match by stopping @@ -5996,14 +6567,14 @@ sign that you're trying to make the scanner do some parsing. That's generally the wrong approach, since it lacks the power to do a decent job. Better is to either introduce a separate parser, or to split the scanner -into multiple scanners using (exclusive) start conditions. +into multiple scanners using (exclusive) start conditions.
You might have -a separate start state once you've seen the BEGIN. In that state, you -might then have a regex that will match END (to kick you out of the -state), and perhaps (.|\n) to get a single character within the chunk ... +a separate start state once you've seen the `BEGIN'. In that state, you +might then have a regex that will match `END' (to kick you out of the +state), and perhaps `(.|\n)' to get a single character within the chunk ...
@@ -6012,14 +6583,2137 @@ -
+@anchor{faq-memory-leak} +
+UPDATED 2002-07-10: As of flex
version 2.5.9, this leak means that you did not
+call yylex_destroy()
. If you are using an earlier version of flex
, then read
+on.
-
-
+The leak is about 16426 bytes. That is, (8192 * 2 + 2) for the read-buffer, and
+about 40 for struct yy_buffer_state
(depending upon alignment). The leak is in
+the non-reentrant C scanner only (NOT in the reentrant scanner, NOT in the C++
+scanner). Since flex
doesn't know when you are done, the buffer is never freed.
+
+
+
+However, the leak won't multiply since the buffer is reused no matter how many
+times you call yylex()
.
+
+
+
+If you want to reclaim the memory when you are completely done scanning, then +you might try this: + + + +
+@verbatim +/* For non-reentrant C scanner only. */ +yy_delete_buffer(yy_current_buffer); +yy_init = 1; ++ +
+Note: yy_init
is an "internal variable", and hasn't been tested in this
+situation. It is possible that some other globals may need resetting as well.
+
+
+
+
+
+@verbatim +> We thought that it would be possible to have this number through the +> evaluation of the following expression: +> +> seek_position = (no_buffers)*YY_READ_BUF_SIZE + yy_c_buf_p - yy_current_buffer->yy_ch_buf ++ +
+While this is the right idea, it has two problems. The first is that
+it's possible that flex
will request less than YY_READ_BUF_SIZE
during
+an invocation of YY_INPUT
(or that your input source will return less
+even though YY_READ_BUF_SIZE
bytes were requested). The second problem
+is that when refilling its internal buffer, flex
keeps some characters
+from the previous buffer (because usually it's in the middle of a match,
+and needs those characters to construct yytext
for the match once it's
+done). Because of this, yy_c_buf_p - yy_current_buffer->yy_ch_buf
won't
+be exactly the number of characters already read from the current buffer.
+
+
+
+An alternative solution is to count the number of characters you've matched
+since starting to scan. This can be done by using YY_USER_ACTION
. For
+example,
+
+
+
+
+@verbatim +#define YY_USER_ACTION num_chars += yyleng; ++ +
+(You need to be careful to update your bookkeeping if you use yymore(
),
+yyless()
, unput()
, or input()
.)
+
+
+
+
+
+When the flex C++ scanning class rewrite finally happens, then this sort of thing should become much easier. + + +
+
+
+
+
+
+
+You can do this by passing the various functions (such as LexerInput()
+and LexerOutput()
) nil iostream*
's, and then
+dealing with your own I/O classes surreptitiously (i.e., stashing them in
+special member variables). This works because the only assumption about
+the lexer regarding what's done with the iostream's is that they're
+ultimately passed to LexerInput()
and LexerOutput
, which then do whatever
+is necessary with them.
+
+
+
+
+
+How do I skip as many chars as possible -- without interfering with the other +patterns? + + +
+In the example below, we want to skip over characters until we see the phrase +"endskip". The following will NOT work correctly (do you see why not?) + + + +
+@verbatim +/* INCORRECT SCANNER */ +%x SKIP +%% +<INITIAL>startskip BEGIN(SKIP); +... +<SKIP>"endskip" BEGIN(INITIAL); +<SKIP>.* ; ++ +
+The problem is that the pattern .* will eat up the word "endskip." +The simplest (but slow) fix is: + + + +
+@verbatim +<SKIP>"endskip" BEGIN(INITIAL); +<SKIP>. ; ++ +
+The fix involves making the second rule match more, without +making it match "endskip" plus something else. So for example: + + + +
+@verbatim +<SKIP>"endskip" BEGIN(INITIAL); +<SKIP>[^e]+ ; +<SKIP>. ;/* so you eat up e's, too */ ++ + + +
+@verbatim +QUESTION: +When was flex born? + +Vern Paxson took over +the Software Tools lex project from Jef Poskanzer in 1982. At that point it +was written in Ratfor. Around 1987 or so, Paxson translated it into C, and +a legend was born :-). ++ + + +
+@verbatim +To: Adoram Rogel <adoram@orna.hybridge.com> +Subject: Re: Flex 2.5.2 performance questions +In-reply-to: Your message of Wed, 18 Sep 96 11:12:17 EDT. +Date: Wed, 18 Sep 96 10:51:02 PDT +From: Vern Paxson <vern> + +[Note, the most recent flex release is 2.5.4, which you can get from +ftp.ee.lbl.gov. It has bug fixes over 2.5.2 and 2.5.3.] + +> 1. Using the pattern +> ([Ff](oot)?)?[Nn](ote)?(\.)? +> instead of +> (((F|f)oot(N|n)ote)|((N|n)ote)|((N|n)\.)|((F|f)(N|n)(\.))) +> (in a very complicated flex program) caused the program to slow from +> 300K+/min to 100K/min (no other changes were done). + +These two are not equivalent. For example, the first can match "footnote." +but the second can only match "footnote". This is almost certainly the +cause in the discrepancy - the slower scanner run is matching more tokens, +and/or having to do more backing up. + +> 2. Which of these two are better: [Ff]oot or (F|f)oot ? + +From a performance point of view, they're equivalent (modulo presumably +minor effects such as memory cache hit rates; and the presence of trailing +context, see below). From a space point of view, the first is slightly +preferable. + +> 3. I have a pattern that look like this: +> pats {p1}|{p2}|{p3}|...|{p50} (50 patterns ORd) +> +> running yet another complicated program that includes the following rule: +> <snext>{and}/{no4}{bb}{pats} +> +> gets me to "too complicated - over 32,000 states"... + +I can't tell from this example whether the trailing context is variable-length +or fixed-length (it could be the latter if {and} is fixed-length). If it's +variable length, which flex -p will tell you, then this reflects a basic +performance problem, and if you can eliminate it by restructuring your +scanner, you will see significant improvement. + +> so I divided {pats} to {pats1}, {pats2},..., {pats5} each consists of about +> 10 patterns and changed the rule to be 5 rules. +> This did compile, but what is the rule of thumb here ? + +The rule is to avoid trailing context other than fixed-length, in which for +a/b, either the 'a' pattern or the 'b' pattern have a fixed length. Use +of the '|' operator automatically makes the pattern variable length, so in +this case '[Ff]oot' is preferred to '(F|f)oot'. + +> 4. I changed a rule that looked like this: +> <snext8>{and}{bb}/{ROMAN}[^A-Za-z] { BEGIN... +> +> to the next 2 rules: +> <snext8>{and}{bb}/{ROMAN}[A-Za-z] { ECHO;} +> <snext8>{and}{bb}/{ROMAN} { BEGIN... +> +> Again, I understand the using [^...] will cause a great performance loss + +Actually, it doesn't cause any sort of performance loss. It's a surprising +fact about regular expressions that they always match in linear time +regardless of how complex they are. + +> but are there any specific rules about it ? + +See the "Performance Considerations" section of the man page, and also +the example in MISC/fastwc/. + + Vern ++ + + +
+@verbatim +To: Adoram Rogel <adoram@hybridge.com> +Subject: Re: Flex 2.5.2 performance questions +In-reply-to: Your message of Thu, 19 Sep 96 10:16:04 EDT. +Date: Thu, 19 Sep 96 09:58:00 PDT +From: Vern Paxson <vern> + +> a lot about the backing up problem. +> I believe that there lies my biggest problem, and I'll try to improve +> it. + +Since you have variable trailing context, this is a bigger performance +problem. Fixing it is usually easier than fixing backing up, which in a +complicated scanner (yours seems to fit the bill) can be extremely +difficult to do correctly. + +You also don't mention what flags you are using for your scanner. +-f makes a large speed difference, and -Cfe buys you nearly as much +speed but the resulting scanner is considerably smaller. + +> I have an | operator in {and} and in {pats} so both of them are variable +> length. + +-p should have reported this. + +> Is changing one of them to fixed-length is enough ? + +Yes. + +> Is it possible to change the 32,000 states limit ? + +Yes. I've appended instructions on how. Before you make this change, +though, you should think about whether there are ways to fundamentally +simplify your scanner - those are certainly preferable! + + Vern + +To increase the 32K limit (on a machine with 32 bit integers), you increase +the magnitude of the following in flexdef.h: + +#define JAMSTATE -32766 /* marks a reference to the state that always jams */ +#define MAXIMUM_MNS 31999 +#define BAD_SUBSCRIPT -32767 +#define MAX_SHORT 32700 + +Adding a 0 or two after each should do the trick. ++ + + +
+@verbatim +To: Heeman_Lee@hp.com +Subject: Re: flex - multi-byte support? +In-reply-to: Your message of Thu, 03 Oct 1996 17:24:04 PDT. +Date: Fri, 04 Oct 1996 11:42:18 PDT +From: Vern Paxson <vern> + +> I assume as long as my *.l file defines the +> range of expected character code values (in octal format), flex will +> scan the file and read multi-byte characters correctly. But I have no +> confidence in this assumption. + +Your lack of confidence is justified - this won't work. + +Flex has in it a widespread assumption that the input is processed +one byte at a time. Fixing this is on the to-do list, but is involved, +so it won't happen any time soon. In the interim, the best I can suggest +(unless you want to try fixing it yourself) is to write your rules in +terms of pairs of bytes, using definitions in the first section: + + X \xfe\xc2 + ... + %% + foo{X}bar found_foo_fe_c2_bar(); + +etc. Definitely a pain - sorry about that. + +By the way, the email address you used for me is ancient, indicating you +have a very old version of flex. You can get the most recent, 2.5.4, from +ftp.ee.lbl.gov. + + Vern ++ + + +
+@verbatim +To: moleary@primus.com +Subject: Re: Flex / Unicode compatibility question +In-reply-to: Your message of Tue, 22 Oct 1996 10:15:42 PDT. +Date: Tue, 22 Oct 1996 11:06:13 PDT +From: Vern Paxson <vern> + +Unfortunately flex at the moment has a widespread assumption within it +that characters are processed 8 bits at a time. I don't see any easy +fix for this (other than writing your rules in terms of double characters - +a pain). I also don't know of a wider lex, though you might try surfing +the Plan 9 stuff because I know it's a Unicode system, and also the PCCT +toolkit (try searching say Alta Vista for "Purdue Compiler Construction +Toolkit"). + +Fixing flex to handle wider characters is on the long-term to-do list. +But since flex is a strictly spare-time project these days, this probably +won't happen for quite a while, unless someone else does it first. + + Vern ++ + + +
+@verbatim +To: Johan Linde <jl@theophys.kth.se> +Subject: Re: translation of flex +In-reply-to: Your message of Sun, 10 Nov 1996 09:16:36 PST. +Date: Mon, 11 Nov 1996 10:33:50 PST +From: Vern Paxson <vern> + +> I'm working for the Swedish team translating GNU program, and I'm currently +> working with flex. I have a few questions about some of the messages which +> I hope you can answer. + +All of the things you're wondering about, by the way, concerning flex +internals - probably the only person who understands what they mean in +English is me! So I wouldn't worry too much about getting them right. +That said ... + +> #: main.c:545 +> msgid " %d protos created\n" +> +> Does proto mean prototype? + +Yes - prototypes of state compression tables. + +> #: main.c:539 +> msgid " %d/%d (peak %d) template nxt-chk entries created\n" +> +> Here I'm mainly puzzled by 'nxt-chk'. I guess it means 'next-check'. (?) +> However, 'template next-check entries' doesn't make much sense to me. To be +> able to find a good translation I need to know a little bit more about it. + +There is a scheme in the Aho/Sethi/Ullman compiler book for compressing +scanner tables. It involves creating two pairs of tables. The first has +"base" and "default" entries, the second has "next" and "check" entries. +The "base" entry is indexed by the current state and yields an index into +the next/check table. The "default" entry gives what to do if the state +transition isn't found in next/check. The "next" entry gives the next +state to enter, but only if the "check" entry verifies that this entry is +correct for the current state. Flex creates templates of series of +next/check entries and then encodes differences from these templates as a +way to compress the tables. + +> #: main.c:533 +> msgid " %d/%d base-def entries created\n" +> +> The same problem here for 'base-def'. + +See above. + + Vern ++ + + +
+@verbatim +To: Xinying Li <xli@npac.syr.edu> +Subject: Re: FLEX ? +In-reply-to: Your message of Wed, 13 Nov 1996 17:28:38 PST. +Date: Wed, 13 Nov 1996 19:51:54 PST +From: Vern Paxson <vern> + +> "unput()" them to input flow, question occurs. If I do this after I scan +> a carriage, the variable "yy_current_buffer->yy_at_bol" is changed. That +> means the carriage flag has gone. + +You can control this by calling yy_set_bol(). It's described in the manual. + +> And if in pre-reading it goes to the end of file, is anything done +> to control the end of curren buffer and end of file? + +No, there's no way to put back an end-of-file. + +> By the way I am using flex 2.5.2 and using the "-l". + +The latest release is 2.5.4, by the way. It fixes some bugs in 2.5.2 and +2.5.3. You can get it from ftp.ee.lbl.gov. + + Vern ++ + + +
+@verbatim +To: Alain.ISSARD@st.com +Subject: Re: Start condition with FLEX +In-reply-to: Your message of Mon, 18 Nov 1996 09:45:02 PST. +Date: Mon, 18 Nov 1996 10:41:34 PST +From: Vern Paxson <vern> + +> I am not able to use the start condition scope and to use the | (OR) with +> rules having start conditions. + +The problem is that if you use '|' as a regular expression operator, for +example "a|b" meaning "match either 'a' or 'b'", then it must *not* have +any blanks around it. If you instead want the special '|' *action* (which +from your scanner appears to be the case), which is a way of giving two +different rules the same action: + + foo | + bar matched_foo_or_bar(); + +then '|' *must* be separated from the first rule by whitespace and *must* +be followed by a new line. You *cannot* write it as: + + foo | bar matched_foo_or_bar(); + +even though you might think you could because yacc supports this syntax. +The reason for this unfortunately incompatibility is historical, but it's +unlikely to be changed. + +Your problems with start condition scope are simply due to syntax errors +from your use of '|' later confusing flex. + +Let me know if you still have problems. + + Vern ++ + + +
+@verbatim +To: Gregory Margo <gmargo@newton.vip.best.com> +Subject: Re: flex-2.5.3 bug report +In-reply-to: Your message of Sat, 23 Nov 1996 16:50:09 PST. +Date: Sat, 23 Nov 1996 17:07:32 PST +From: Vern Paxson <vern> + +> Enclosed is a lex file that "real" lex will process, but I cannot get +> flex to process it. Could you try it and maybe point me in the right direction? + +Your problem is that some of the definitions in the scanner use the '/' +trailing context operator, and have it enclosed in ()'s. Flex does not +allow this operator to be enclosed in ()'s because doing so allows undefined +regular expressions such as "(a/b)+". So the solution is to remove the +parentheses. Note that you must also be building the scanner with the -l +option for AT&T lex compatibility. Without this option, flex automatically +encloses the definitions in parentheses. + + Vern ++ + + +
+@verbatim +To: Thomas Hadig <hadig@toots.physik.rwth-aachen.de> +Subject: Re: Flex Bug ? +In-reply-to: Your message of Tue, 26 Nov 1996 14:35:01 PST. +Date: Tue, 26 Nov 1996 11:15:05 PST +From: Vern Paxson <vern> + +> In my lexer code, i have the line : +> ^\*.* { } +> +> Thus all lines starting with an astrix (*) are comment lines. +> This does not work ! + +I can't get this problem to reproduce - it works fine for me. Note +though that if what you have is slightly different: + + COMMENT ^\*.* + %% + {COMMENT} { } + +then it won't work, because flex pushes back macro definitions enclosed +in ()'s, so the rule becomes + + (^\*.*) { } + +and now that the '^' operator is not at the immediate beginning of the +line, it's interpreted as just a regular character. You can avoid this +behavior by using the "-l" lex-compatibility flag, or "%option lex-compat". + + Vern ++ + + +
+@verbatim +To: Adoram Rogel <adoram@hybridge.com> +Subject: Re: Flex 2.5.4 BOF ??? +In-reply-to: Your message of Tue, 26 Nov 1996 16:10:41 PST. +Date: Wed, 27 Nov 1996 10:56:25 PST +From: Vern Paxson <vern> + +> Organization(s)?/[a-z] +> +> This matched "Organizations" (looking in debug mode, the trailing s +> was matched with trailing context instead of the optional (s) in the +> end of the word. + +That should only happen with lex. Flex can properly match this pattern. +(That might be what you're saying, I'm just not sure.) + +> Is there a way to avoid this dangerous trailing context problem ? + +Unfortunately, there's no easy way. On the other hand, I don't see why +it should be a problem. Lex's matching is clearly wrong, and I'd hope +that usually the intent remains the same as expressed with the pattern, +so flex's matching will be correct. + + Vern ++ + + +
+@verbatim +To: Cameron MacKinnon <mackin@interlog.com> +Subject: Re: Flex documentation bug +In-reply-to: Your message of Mon, 02 Dec 1996 00:07:08 PST. +Date: Sun, 01 Dec 1996 22:29:39 PST +From: Vern Paxson <vern> + +> I'm not sure how or where to submit bug reports (documentation or +> otherwise) for the GNU project stuff ... + +Well, strictly speaking flex isn't part of the GNU project. They just +distribute it because no one's written a decent GPL'd lex replacement. +So you should send bugs directly to me. Those sent to the GNU folks +sometimes find there way to me, but some may drop between the cracks. + +> In GNU Info, under the section 'Start Conditions', and also in the man +> page (mine's dated April '95) is a nice little snippet showing how to +> parse C quoted strings into a buffer, defined to be MAX_STR_CONST in +> size. Unfortunately, no overflow checking is ever done ... + +This is already mentioned in the manual: + +Finally, here's an example of how to match C-style quoted +strings using exclusive start conditions, including expanded +escape sequences (but not including checking for a string +that's too long): + +The reason for not doing the overflow checking is that it will needlessly +clutter up an example whose main purpose is just to demonstrate how to +use flex. + +The latest release is 2.5.4, by the way, available from ftp.ee.lbl.gov. + + Vern ++ + + +
+@verbatim +To: tsv@cs.UManitoba.CA +Subject: Re: Flex (reg).. +In-reply-to: Your message of Thu, 06 Mar 1997 23:50:16 PST. +Date: Thu, 06 Mar 1997 15:54:19 PST +From: Vern Paxson <vern> + +> [:alpha:] ([:alnum:] | \\_)* + +If your rule really has embedded blanks as shown above, then it won't +work, as the first blank delimits the rule from the action. (It wouldn't +even compile ...) You need instead: + +[:alpha:]([:alnum:]|\\_)* + +and that should work fine - there's no restriction on what can go inside +of ()'s except for the trailing context operator, '/'. + + Vern ++ + + +
+@verbatim +To: "Mike Stolnicki" <mstolnic@ford.com> +Subject: Re: FLEX help +In-reply-to: Your message of Fri, 30 May 1997 13:33:27 PDT. +Date: Fri, 30 May 1997 10:46:35 PDT +From: Vern Paxson <vern> + +> We'd like to add "if-then-else", "while", and "for" statements to our +> language ... +> We've investigated many possible solutions. The one solution that seems +> the most reasonable involves knowing the position of a TOKEN in yyin. + +I strongly advise you to instead build a parse tree (abstract syntax tree) +and loop over that instead. You'll find this has major benefits in keeping +your interpreter simple and extensible. + +That said, the functionality you mention for get_position and set_position +have been on the to-do list for a while. As flex is a purely spare-time +project for me, no guarantees when this will be added (in particular, it +for sure won't be for many months to come). + + Vern ++ + + +
+@verbatim +To: Colin Paul Adams <colin@colina.demon.co.uk> +Subject: Re: Flex C++ classes and Bison +In-reply-to: Your message of 09 Aug 1997 17:11:41 PDT. +Date: Fri, 15 Aug 1997 10:48:19 PDT +From: Vern Paxson <vern> + +> #define YY_DECL int yylex (YYSTYPE *lvalp, struct parser_control +> *parm) +> +> I have been trying to get this to work as a C++ scanner, but it does +> not appear to be possible (warning that it matches no declarations in +> yyFlexLexer, or something like that). +> +> Is this supposed to be possible, or is it being worked on (I DID +> notice the comment that scanner classes are still experimental, so I'm +> not too hopeful)? + +What you need to do is derive a subclass from yyFlexLexer that provides +the above yylex() method, squirrels away lvalp and parm into member +variables, and then invokes yyFlexLexer::yylex() to do the regular scanning. + + Vern ++ + + +
+@verbatim +To: Mikael.Latvala@lmf.ericsson.se +Subject: Re: Possible mistake in Flex v2.5 document +In-reply-to: Your message of Fri, 05 Sep 1997 16:07:24 PDT. +Date: Fri, 05 Sep 1997 10:01:54 PDT +From: Vern Paxson <vern> + +> In that example you show how to count comment lines when using +> C style /* ... */ comments. My question is, shouldn't you take into +> account a scenario where end of a comment marker occurs inside +> character or string literals? + +The scanner certainly needs to also scan character and string literals. +However it does that (there's an example in the man page for strings), the +lexer will recognize the beginning of the literal before it runs across the +embedded "/*". Consequently, it will finish scanning the literal before it +even considers the possibility of matching "/*". + +Example: + + '([^']*|{ESCAPE_SEQUENCE})' + +will match all the text between the ''s (inclusive). So the lexer +considers this as a token beginning at the first ', and doesn't even +attempt to match other tokens inside it. + +I thinnk this subtlety is not worth putting in the manual, as I suspect +it would confuse more people than it would enlighten. + + Vern ++ + + +
+@verbatim +To: "Marty Leisner" <leisner@sdsp.mc.xerox.com> +Subject: Re: flex limitations +In-reply-to: Your message of Sat, 06 Sep 1997 11:27:21 PDT. +Date: Mon, 08 Sep 1997 11:38:08 PDT +From: Vern Paxson <vern> + +> %% +> [a-zA-Z]+ /* skip a line */ +> { printf("got %s\n", yytext); } +> %% + +What version of flex are you using? If I feed this to 2.5.4, it complains: + + "bug.l", line 5: EOF encountered inside an action + "bug.l", line 5: unrecognized rule + "bug.l", line 5: fatal parse error + +Not the world's greatest error message, but it manages to flag the problem. + +(With the introduction of start condition scopes, flex can't accommodate +an action on a separate line, since it's ambiguous with an indented rule.) + +You can get 2.5.4 from ftp.ee.lbl.gov. + + Vern ++ + + +
+@verbatim +To: uocarroll@deagostini.co.uk (Ultan O'Carroll) +Subject: Re: Flex repositries +In-reply-to: Your message of Fri, 12 Sep 1997 15:02:28 PDT. +Date: Fri, 12 Sep 1997 10:31:50 PDT +From: Vern Paxson <vern> + +> before I start beavering away I wonder if you know of any +> place/libraries for flex +> desciption files that might already do this or give me a head start ? + +Unfortunately, no, I don't. You might try asking on comp.compilers. + + Vern ++ + + +
+@verbatim +To: Adoram Rogel <adoram@hybridge.com> +Subject: Re: Conditional compiling in the definitions section +In-reply-to: Your message of Thu, 25 Sep 1997 11:22:42 PDT. +Date: Thu, 25 Sep 1997 10:56:31 PDT +From: Vern Paxson <vern> + +> I'm trying to combine two large lex files that now differ only in +> about 10 lines in the definitions section. +> I would like to have something like this: +> #ifdef FFF +> it \<IT\> +> #else +> it \<I\> +> #endif +> +> Now, I can't add states for these, as I have already too many states +> and the program is very complicated, and I won't be able to handle +> 10 or 20 more states. +> +> Any trick to do this ? + +You might try using m4, or the C preprocessor plus a sed script to +clean up the result (strip out the #line's). + + Vern ++ + + +
+@verbatim +To: Steve Antoch <SteveAn@visio.com> +Subject: Re: lex and yacc grammars +In-reply-to: Your message of Mon, 17 Nov 1997 15:31:25 PST. +Date: Mon, 17 Nov 1997 15:27:01 PST +From: Vern Paxson <vern> + +> Would you happen to know where I can find grammars for lex and yacc? + +The flex sources have a grammar for (f)lex. Dunno about yacc, + + Vern ++ + + +
+@verbatim +To: Bryan Housel <bryan@drawcomp.com> +Subject: Re: Question about Flex v2.5 +In-reply-to: Your message of Tue, 11 Nov 1997 21:30:23 PST. +Date: Mon, 17 Nov 1997 17:12:21 PST +From: Vern Paxson <vern> + +> It prints one of those "end of buffer.." messages for each character in the +> token... + +This will happen if your LexerInput() function returns only one character +at a time, which can happen either if you're scanner is "interactive", or +if the streams library on your platform always returns 1 for yyin->gcount(). + +Solution: override LexerInput() with a version that returns whole buffers. + + Vern ++ + + +
+@verbatim +To: Georg.Rehm@CL-KI.Uni-Osnabrueck.DE +Subject: Re: Flex maximums +In-reply-to: Your message of Mon, 17 Nov 1997 17:16:06 PST. +Date: Mon, 17 Nov 1997 17:16:15 PST +From: Vern Paxson <vern> + +> I took a quick look into the flex-sources and altered some #defines in +> flexdefs.h: +> +> #define INITIAL_MNS 64000 +> #define MNS_INCREMENT 1024000 +> #define MAXIMUM_MNS 64000 + +The things to fix are to add a couple of zeroes to: + +#define JAMSTATE -32766 /* marks a reference to the state that always jams */ +#define MAXIMUM_MNS 31999 +#define BAD_SUBSCRIPT -32767 +#define MAX_SHORT 32700 + +and, if you get complaints about too many rules, make the following change too: + + #define YY_TRAILING_MASK 0x200000 + #define YY_TRAILING_HEAD_MASK 0x400000 + +- Vern ++ + + +
+@verbatim +To: jimmey@lexis-nexis.com (Jimmey Todd) +Subject: Re: FLEX question regarding istream vs ifstream +In-reply-to: Your message of Mon, 08 Dec 1997 15:54:15 PST. +Date: Mon, 15 Dec 1997 13:21:35 PST +From: Vern Paxson <vern> + +> stdin_handle = YY_CURRENT_BUFFER; +> ifstream fin( "aFile" ); +> yy_switch_to_buffer( yy_create_buffer( fin, YY_BUF_SIZE ) ); +> +> What I'm wanting to do, is pass the contents of a file thru one set +> of rules and then pass stdin thru another set... It works great if, I +> don't use the C++ classes. But since everything else that I'm doing is +> in C++, I thought I'd be consistent. +> +> The problem is that 'yy_create_buffer' is expecting an istream* as it's +> first argument (as stated in the man page). However, fin is a ifstream +> object. Any ideas on what I might be doing wrong? Any help would be +> appreciated. Thanks!! + +You need to pass &fin, to turn it into an ifstream* instead of an ifstream. +Then its type will be compatible with the expected istream*, because ifstream +is derived from istream. + + Vern ++ + + +
+@verbatim +To: Enda Fadian <fadiane@piercom.ie> +Subject: Re: Question related to Flex man page? +In-reply-to: Your message of Tue, 16 Dec 1997 15:17:34 PST. +Date: Tue, 16 Dec 1997 14:17:09 PST +From: Vern Paxson <vern> + +> Can you explain to me what is ment by a long-jump in relation to flex? + +Using the longjmp() function while inside yylex() or a routine called by it. + +> what is the flex activation frame. + +Just yylex()'s stack frame. + +> As far as I can see yyrestart will bring me back to the sart of the input +> file and using flex++ isnot really an option! + +No, yyrestart() doesn't imply a rewind, even though its name might sound +like it does. It tells the scanner to flush its internal buffers and +start reading from the given file at its present location. + + Vern ++ + + +
+@verbatim +To: hassan@larc.info.uqam.ca (Hassan Alaoui) +Subject: Re: Need urgent Help +In-reply-to: Your message of Sat, 20 Dec 1997 19:38:19 PST. +Date: Sun, 21 Dec 1997 21:30:46 PST +From: Vern Paxson <vern> + +> /usr/lib/yaccpar: In function `int yyparse()': +> /usr/lib/yaccpar:184: warning: implicit declaration of function `int yylex(...)' +> +> ld: Undefined symbol +> _yylex +> _yyparse +> _yyin + +This is a known problem with Solaris C++ (and/or Solaris yacc). I believe +the fix is to explicitly insert some 'extern "C"' statements for the +corresponding routines/symbols. + + Vern ++ + + +
+@verbatim +To: mc0307@mclink.it +Cc: gnu@prep.ai.mit.edu +Subject: Re: [mc0307@mclink.it: Help request] +In-reply-to: Your message of Fri, 12 Dec 1997 17:57:29 PST. +Date: Sun, 21 Dec 1997 22:33:37 PST +From: Vern Paxson <vern> + +> This is my definition for float and integer types: +> . . . +> NZD [1-9] +> ... +> I've tested my program on other lex version (on UNIX Sun Solaris an HP +> UNIX) and it work well, so I think that my definitions are correct. +> There are any differences between Lex and Flex? + +There are indeed differences, as discussed in the man page. The one +you are probably running into is that when flex expands a name definition, +it puts parentheses around the expansion, while lex does not. There's +an example in the man page of how this can lead to different matching. +Flex's behavior complies with the POSIX standard (or at least with the +last POSIX draft I saw). + + Vern ++ + + +
+@verbatim +To: hassan@larc.info.uqam.ca (Hassan Alaoui) +Subject: Re: Thanks +In-reply-to: Your message of Mon, 22 Dec 1997 16:06:35 PST. +Date: Mon, 22 Dec 1997 14:35:05 PST +From: Vern Paxson <vern> + +> Thank you very much for your help. I compile and link well with C++ while +> declaring 'yylex ...' extern, But a little problem remains. I get a +> segmentation default when executing ( I linked with lfl library) while it +> works well when using LEX instead of flex. Do you have some ideas about the +> reason for this ? + +The one possible reason for this that comes to mind is if you've defined +yytext as "extern char yytext[]" (which is what lex uses) instead of +"extern char *yytext" (which is what flex uses). If it's not that, then +I'm afraid I don't know what the problem might be. + + Vern ++ + + +
+@verbatim +To: "Bart Niswonger" <NISWONGR@almaden.ibm.com> +Subject: Re: flex 2.5: c++ scanners & start conditions +In-reply-to: Your message of Tue, 06 Jan 1998 10:34:21 PST. +Date: Tue, 06 Jan 1998 19:19:30 PST +From: Vern Paxson <vern> + +> The problem is that when I do this (using %option c++) start +> conditions seem to not apply. + +The BEGIN macro modifies the yy_start variable. For C scanners, this +is a static with scope visible through the whole file. For C++ scanners, +it's a member variable, so it only has visible scope within a member +function. Your lexbegin() routine is not a member function when you +build a C++ scanner, so it's not modifying the correct yy_start. The +diagnostic that indicates this is that you found you needed to add +a declaration of yy_start in order to get your scanner to compile when +using C++; instead, the correct fix is to make lexbegin() a member +function (by deriving from yyFlexLexer). + + Vern ++ + + +
+@verbatim +To: "Boris Zinin" <boris@ippe.rssi.ru> +Subject: Re: current position in flex buffer +In-reply-to: Your message of Mon, 12 Jan 1998 18:58:23 PST. +Date: Mon, 12 Jan 1998 12:03:15 PST +From: Vern Paxson <vern> + +> The problem is how to determine the current position in flex active +> buffer when a rule is matched.... + +You will need to keep track of this explicitly, such as by redefining +YY_USER_ACTION to count the number of characters matched. + +The latest flex release, by the way, is 2.5.4, available from ftp.ee.lbl.gov. + + Vern ++ + + +
+@verbatim +To: Bik.Dhaliwal@bis.org +Subject: Re: Flex question +In-reply-to: Your message of Mon, 26 Jan 1998 13:05:35 PST. +Date: Tue, 27 Jan 1998 22:41:52 PST +From: Vern Paxson <vern> + +> That requirement involves knowing +> the character position at which a particular token was matched +> in the lexer. + +The way you have to do this is by explicitly keeping track of where +you are in the file, by counting the number of characters scanned +for each token (available in yyleng). It may prove convenient to +do this by redefining YY_USER_ACTION, as described in the manual. + + Vern ++ + + +
+@verbatim +To: Vladimir Alexiev <vladimir@cs.ualberta.ca> +Subject: Re: flex: how to control start condition from parser? +In-reply-to: Your message of Mon, 26 Jan 1998 05:50:16 PST. +Date: Tue, 27 Jan 1998 22:45:37 PST +From: Vern Paxson <vern> + +> It seems useful for the parser to be able to tell the lexer about such +> context dependencies, because then they don't have to be limited to +> local or sequential context. + +One way to do this is to have the parser call a stub routine that's +included in the scanner's .l file, and consequently that has access ot +BEGIN. The only ugliness is that the parser can't pass in the state +it wants, because those aren't visible - but if you don't have many +such states, then using a different set of names doesn't seem like +to much of a burden. + +While generating a .h file like you suggests is certainly cleaner, +flex development has come to a virtual stand-still :-(, so a workaround +like the above is much more pragmatic than waiting for a new feature. + + Vern ++ + + +
+@verbatim +To: Barbara Denny <denny@3com.com> +Subject: Re: freebsd flex bug? +In-reply-to: Your message of Fri, 30 Jan 1998 12:00:43 PST. +Date: Fri, 30 Jan 1998 12:42:32 PST +From: Vern Paxson <vern> + +> lex.yy.c:1996: parse error before `=' + +This is the key, identifying this error. (It may help to pinpoint +it by using flex -L, so it doesn't generate #line directives in its +output.) I will bet you heavy money that you have a start condition +name that is also a variable name, or something like that; flex spits +out #define's for each start condition name, mapping them to a number, +so you can wind up with: + + %x foo + %% + ... + %% + void bar() + { + int foo = 3; + } + +and the penultimate will turn into "int 1 = 3" after C preprocessing, +since flex will put "#define foo 1" in the generated scanner. + + Vern ++ + + +
+@verbatim +To: Maurice Petrie <mpetrie@infoscigroup.com> +Subject: Re: Lost flex .l file +In-reply-to: Your message of Mon, 02 Feb 1998 14:10:01 PST. +Date: Mon, 02 Feb 1998 11:15:12 PST +From: Vern Paxson <vern> + +> I am curious as to +> whether there is a simple way to backtrack from the generated source to +> reproduce the lost list of tokens we are searching on. + +In theory, it's straight-forward to go from the DFA representation +back to a regular-expression representation - the two are isomorphic. +In practice, a huge headache, because you have to unpack all the tables +back into a single DFA representation, and then write a program to munch +on that and translate it into an RE. + +Sorry for the less-than-happy news ... + + Vern ++ + + +
+@verbatim +To: jimmey@lexis-nexis.com (Jimmey Todd) +Subject: Re: Flex performance question +In-reply-to: Your message of Thu, 19 Feb 1998 11:01:17 PST. +Date: Thu, 19 Feb 1998 08:48:51 PST +From: Vern Paxson <vern> + +> What I have found, is that the smaller the data chunk, the faster the +> program executes. This is the opposite of what I expected. Should this be +> happening this way? + +This is exactly what will happen if your input file has embedded NULs. +From the man page: + +A final note: flex is slow when matching NUL's, particularly +when a token contains multiple NUL's. It's best to write +rules which match short amounts of text if it's anticipated +that the text will often include NUL's. + +So that's the first thing to look for. + + Vern ++ + + +
+@verbatim +To: jimmey@lexis-nexis.com (Jimmey Todd) +Subject: Re: Flex performance question +In-reply-to: Your message of Thu, 19 Feb 1998 11:01:17 PST. +Date: Thu, 19 Feb 1998 15:42:25 PST +From: Vern Paxson <vern> + +So there are several problems. + +First, to go fast, you want to match as much text as possible, which +your scanners don't in the case that what they're scanning is *not* +a <RN> tag. So you want a rule like: + + [^<]+ + +Second, C++ scanners are particularly slow if they're interactive, +which they are by default. Using -B speeds it up by a factor of 3-4 +on my workstation. + +Third, C++ scanners that use the istream interface are slow, because +of how poorly implemented istream's are. I built two versions of +the following scanner: + + %% + .*\n + .* + %% + +and the C version inhales a 2.5MB file on my workstation in 0.8 seconds. +The C++ istream version, using -B, takes 3.8 seconds. + + Vern ++ + + +
+@verbatim +To: "Frescatore, David (CRD, TAD)" <frescatore@exc01crdge.crd.ge.com> +Subject: Re: FLEX 2.5 & THE YEAR 2000 +In-reply-to: Your message of Wed, 03 Jun 1998 11:26:22 PDT. +Date: Wed, 03 Jun 1998 10:22:26 PDT +From: Vern Paxson <vern> + +> I am researching the Y2K problem with General Electric R&D +> and need to know if there are any known issues concerning +> the above mentioned software and Y2K regardless of version. + +There shouldn't be, all it ever does with the date is ask the system +for it and then print it out. + + Vern ++ + + +
+@verbatim +To: "Hans Dermot Doran" <htd@ibhdoran.com> +Subject: Re: flex problem +In-reply-to: Your message of Wed, 15 Jul 1998 21:30:13 PDT. +Date: Tue, 21 Jul 1998 14:23:34 PDT +From: Vern Paxson <vern> + +> To overcome this, I gets() the stdin into a string and lex the string. The +> string is lexed OK except that the end of string isn't lexed properly +> (yy_scan_string()), that is the lexer dosn't recognise the end of string. + +Flex doesn't contain mechanisms for recognizing buffer endpoints. But if +you use fgets instead (which you should anyway, to protect against buffer +overflows), then the final \n will be preserved in the string, and you can +scan that in order to find the end of the string. + + Vern ++ + + +
+@verbatim +To: soumen@almaden.ibm.com +Subject: Re: Flex++ 2.5.3 instance member vs. static member +In-reply-to: Your message of Mon, 27 Jul 1998 02:10:04 PDT. +Date: Tue, 28 Jul 1998 01:10:34 PDT +From: Vern Paxson <vern> + +> %{ +> int mylineno = 0; +> %} +> ws [ \t]+ +> alpha [A-Za-z] +> dig [0-9] +> %% +> +> Now you'd expect mylineno to be a member of each instance of class +> yyFlexLexer, but is this the case? A look at the lex.yy.cc file seems to +> indicate otherwise; unless I am missing something the declaration of +> mylineno seems to be outside any class scope. +> +> How will this work if I want to run a multi-threaded application with each +> thread creating a FlexLexer instance? + +Derive your own subclass and make mylineno a member variable of it. + + Vern ++ + + +
+@verbatim +To: Adoram Rogel <adoram@hybridge.com> +Subject: Re: More than 32K states change hangs +In-reply-to: Your message of Tue, 04 Aug 1998 16:55:39 PDT. +Date: Tue, 04 Aug 1998 22:28:45 PDT +From: Vern Paxson <vern> + +> Vern Paxson, +> +> I followed your advice, posted on Usenet bu you, and emailed to me +> personally by you, on how to overcome the 32K states limit. I'm running +> on Linux machines. +> I took the full source of version 2.5.4 and did the following changes in +> flexdef.h: +> #define JAMSTATE -327660 +> #define MAXIMUM_MNS 319990 +> #define BAD_SUBSCRIPT -327670 +> #define MAX_SHORT 327000 +> +> and compiled. +> All looked fine, including check and bigcheck, so I installed. + +Hmmm, you shouldn't increase MAX_SHORT, though looking through my email +archives I see that I did indeed recommend doing so. Try setting it back +to 32700; that should suffice that you no longer need -Ca. If it still +hangs, then the interesting question is - where? + +> Compiling the same hanged program with a out-of-the-box (RedHat 4.2 +> distribution of Linux) +> flex 2.5.4 binary works. + +Since Linux comes with source code, you should diff it against what +you have to see what problems they missed. + +> Should I always compile with the -Ca option now ? even short and simple +> filters ? + +No, definitely not. It's meant to be for those situations where you +absolutely must squeeze every last cycle out of your scanner. + + Vern ++ + + +
+@verbatim +To: "Schmackpfeffer, Craig" <Craig.Schmackpfeffer@usa.xerox.com> +Subject: Re: flex output for static code portion +In-reply-to: Your message of Tue, 11 Aug 1998 11:55:30 PDT. +Date: Mon, 17 Aug 1998 23:57:42 PDT +From: Vern Paxson <vern> + +> I would like to use flex under the hood to generate a binary file +> containing the data structures that control the parse. + +This has been on the wish-list for a long time. In principle it's +straight-forward - you redirect mkdata() et al's I/O to another file, +and modify the skeleton to have a start-up function that slurps these +into dynamic arrays. The concerns are (1) the scanner generation code +is hairy and full of corner cases, so it's easy to get surprised when +going down this path :-( ; and (2) being careful about buffering so +that when the tables change you make sure the scanner starts in the +correct state and reading at the right point in the input file. + +> I was wondering if you know of anyone who has used flex in this way. + +I don't - but it seems like a reasonable project to undertake (unlike +numerous other flex tweaks :-). + + Vern ++ + + +
+@verbatim +Received: from 131.173.17.11 (131.173.17.11 [131.173.17.11]) + by ee.lbl.gov (8.9.1/8.9.1) with ESMTP id AAA03838 + for <vern@ee.lbl.gov>; Thu, 20 Aug 1998 00:47:57 -0700 (PDT) +Received: from hal.cl-ki.uni-osnabrueck.de (hal.cl-ki.Uni-Osnabrueck.DE [131.173.141.2]) + by deimos.rz.uni-osnabrueck.de (8.8.7/8.8.8) with ESMTP id JAA34694 + for <vern@ee.lbl.gov>; Thu, 20 Aug 1998 09:47:55 +0200 +Received: (from georg@localhost) by hal.cl-ki.uni-osnabrueck.de (8.6.12/8.6.12) id JAA34834 for vern@ee.lbl.gov; Thu, 20 Aug 1998 09:47:54 +0200 +From: Georg Rehm <georg@hal.cl-ki.uni-osnabrueck.de> +Message-Id: <199808200747.JAA34834@hal.cl-ki.uni-osnabrueck.de> +Subject: "flex scanner push-back overflow" +To: vern@ee.lbl.gov +Date: Thu, 20 Aug 1998 09:47:54 +0200 (MEST) +Reply-To: Georg.Rehm@CL-KI.Uni-Osnabrueck.DE +X-NoJunk: Do NOT send commercial mail, spam or ads to this address! +X-URL: http://www.cl-ki.uni-osnabrueck.de/~georg/ +X-Mailer: ELM [version 2.4ME+ PL28 (25)] +MIME-Version: 1.0 +Content-Type: text/plain; charset=US-ASCII +Content-Transfer-Encoding: 7bit + +Hi Vern, + +Yesterday, I encountered a strange problem: I use the macro processor m4 +to include some lengthy lists into a .l file. Following is a flex macro +definition that causes some serious pain in my neck: + +AUTHOR ("A. Boucard / L. Boucard"|"A. Dastarac / M. Levent"|"A.Boucaud / L.Boucaud"|"Abderrahim Lamchichi"|"Achmat Dangor"|"Adeline Toullier"|"Adewale Maja-Pearce"|"Ahmed Ziri"|"Akram Ellyas"|"Alain Bihr"|"Alain Gresh"|"Alain Guillemoles"|"Alain Joxe"|"Alain Morice"|"Alain Renon"|"Alain Zecchini"|"Albert Memmi"|"Alberto Manguel"|"Alex De Waal"|"Alfonso Artico"| [...]) + +The complete list contains about 10kB. When I try to "flex" this file +(on a Solaris 2.6 machine, using a modified flex 2.5.4 (I only increased +some of the predefined values in flexdefs.h) I get the error: + +myflex/flex -8 sentag.tmp.l +flex scanner push-back overflow + +When I remove the slashes in the macro definition everything works fine. +As I understand it, the double quotes escape the slash-character so it +really means "/" and not "trailing context". Furthermore, I tried to +escape the slashes with backslashes, but with no use, the same error message +appeared when flexing the code. + +Do you have an idea what's going on here? + +Greetings from Germany, + Georg +-- +Georg Rehm georg@cl-ki.uni-osnabrueck.de +Institute for Semantic Information Processing, University of Osnabrueck, FRG ++ + + +
+@verbatim +To: Georg.Rehm@CL-KI.Uni-Osnabrueck.DE +Subject: Re: "flex scanner push-back overflow" +In-reply-to: Your message of Thu, 20 Aug 1998 09:47:54 PDT. +Date: Thu, 20 Aug 1998 07:05:35 PDT +From: Vern Paxson <vern> + +> myflex/flex -8 sentag.tmp.l +> flex scanner push-back overflow + +Flex itself uses a flex scanner. That scanner is running out of buffer +space when it tries to unput() the humongous macro you've defined. When +you remove the '/'s, you make it small enough so that it fits in the buffer; +removing spaces would do the same thing. + +The fix is to either rethink how come you're using such a big macro and +perhaps there's another/better way to do it; or to rebuild flex's own +scan.c with a larger value for + + #define YY_BUF_SIZE 16384 + +- Vern ++ + + +
+@verbatim +To: Jan Kort <jan@research.techforce.nl> +Subject: Re: Flex +In-reply-to: Your message of Fri, 04 Sep 1998 12:18:43 +0200. +Date: Sat, 05 Sep 1998 00:59:49 PDT +From: Vern Paxson <vern> + +> %% +> +> "TEST1\n" { fprintf(stderr, "TEST1\n"); yyless(5); } +> ^\n { fprintf(stderr, "empty line\n"); } +> . { } +> \n { fprintf(stderr, "new line\n"); } +> +> %% +> -- input --------------------------------------- +> TEST1 +> -- output -------------------------------------- +> TEST1 +> empty line +> ------------------------------------------------ + +IMHO, it's not clear whether or not this is in fact a bug. It depends +on whether you view yyless() as backing up in the input stream, or as +pushing new characters onto the beginning of the input stream. Flex +interprets it as the latter (for implementation convenience, I'll admit), +and so considers the newline as in fact matching at the beginning of a +line, as after all the last token scanned an entire line and so the +scanner is now at the beginning of a new line. + +I agree that this is counter-intuitive for yyless(), given its +functional description (it's less so for unput(), depending on whether +you're unput()'ing new text or scanned text). But I don't plan to +change it any time soon, as it's a pain to do so. Consequently, +you do indeed need to use yy_set_bol() and YY_AT_BOL() to tweak +your scanner into the behavior you desire. + +Sorry for the less-than-completely-satisfactory answer. + + Vern ++ + + +
+@verbatim +To: Patrick Krusenotto <krusenot@mac-info-link.de> +Subject: Re: Problems with restarting flex-2.5.2-generated scanner +In-reply-to: Your message of Thu, 24 Sep 1998 10:14:07 PDT. +Date: Thu, 24 Sep 1998 23:28:43 PDT +From: Vern Paxson <vern> + +> I am using flex-2.5.2 and bison 1.25 for Solaris and I am desperately +> trying to make my scanner restart with a new file after my parser stops +> with a parse error. When my compiler restarts, the parser always +> receives the token after the token (in the old file!) that caused the +> parser error. + +I suspect the problem is that your parser has read ahead in order +to attempt to resolve an ambiguity, and when it's restarted it picks +up with that token rather than reading a fresh one. If you're using +yacc, then the special "error" production can sometimes be used to +consume tokens in an attempt to get the parser into a consistent state. + + Vern ++ + + +
+@verbatim +To: Henric Jungheim <junghelh@pe-nelson.com> +Subject: Re: flex 2.5.4a +In-reply-to: Your message of Tue, 27 Oct 1998 16:41:42 PST. +Date: Tue, 27 Oct 1998 16:50:14 PST +From: Vern Paxson <vern> + +> This brings up a feature request: How about a command line +> option to specify the filename when reading from stdin? That way one +> doesn't need to create a temporary file in order to get the "#line" +> directives to make sense. + +Use -o combined with -t (per the man page description of -o). + +> P.S., Is there any simple way to use non-blocking IO to parse multiple +> streams? + +Simple, no. + +One approach might be to return a magic character on EWOULDBLOCK and +have a rule + + .*<magic-character> // put back .*, eat magic character + +This is off the top of my head, not sure it'll work. + + Vern ++ + + +
+@verbatim +To: "Repko, Billy D" <billy.d.repko@intel.com> +Subject: Re: Compiling scanners +In-reply-to: Your message of Wed, 13 Jan 1999 10:52:47 PST. +Date: Thu, 14 Jan 1999 00:25:30 PST +From: Vern Paxson <vern> + +> It appears that maybe it cannot find the lfl library. + +The Makefile in the distribution builds it, so you should have it. +It's exceedingly trivial, just a main() that calls yylex() and +a yyrap() that always returns 1. + +> %% +> \n ++num_lines; ++num_chars; +> . ++num_chars; + +You can't indent your rules like this - that's where the errors are coming +from. Flex copies indented text to the output file, it's how you do things +like + + int num_lines_seen = 0; + +to declare local variables. + + Vern ++ + + +
+@verbatim +To: Erick Branderhorst <Erick.Branderhorst@asml.nl> +Subject: Re: flex input buffer +In-reply-to: Your message of Tue, 09 Feb 1999 13:53:46 PST. +Date: Tue, 09 Feb 1999 21:03:37 PST +From: Vern Paxson <vern> + +> In the flex.skl file the size of the default input buffers is set. Can you +> explain why this size is set and why it is such a high number. + +It's large to optimize performance when scanning large files. You can +safely make it a lot lower if needed. + + Vern ++ + + +
+@verbatim +To: "Guido Minnen" <guidomi@cogs.susx.ac.uk> +Subject: Re: Flex error message +In-reply-to: Your message of Wed, 24 Feb 1999 15:31:46 PST. +Date: Thu, 25 Feb 1999 00:11:31 PST +From: Vern Paxson <vern> + +> I'm extending a larger scanner written in Flex and I keep running into +> problems. More specifically, I get the error message: +> "flex: input rules are too complicated (>= 32000 NFA states)" + +Increase the definitions in flexdef.h for: + +#define JAMSTATE -32766 /* marks a reference to the state that always j +ams */ +#define MAXIMUM_MNS 31999 +#define BAD_SUBSCRIPT -32767 + +recompile everything, and it should all work. + + Vern ++ + + +
+@verbatim +To: "Dmitriy Goldobin" <gold@ems.chel.su> +Subject: Re: FLEX trouble +In-reply-to: Your message of Mon, 31 May 1999 18:44:49 PDT. +Date: Tue, 01 Jun 1999 00:15:07 PDT +From: Vern Paxson <vern> + +> I have a trouble with FLEX. Why rule "/*".*"*/" work properly,=20 +> but rule "/*"(.|\n)*"*/" don't work ? + +The second of these will have to scan the entire input stream (because +"(.|\n)*" matches an arbitrary amount of any text) in order to see if +it ends with "*/", terminating the comment. That potentially will overflow +the input buffer. + +> More complex rule "/*"([^*]|(\*/[^/]))*"*/ give an error +> 'unrecognized rule'. + +You can't use the '/' operator inside parentheses. It's not clear +what "(a/b)*" actually means. + +> I now use workaround with state <comment>, but single-rule is +> better, i think. + +Single-rule is nice but will always have the problem of either setting +restrictions on comments (like not allowing multi-line comments) and/or +running the risk of consuming the entire input stream, as noted above. + + Vern ++ + + +
+@verbatim +Received: from mc-qout4.whowhere.com (mc-qout4.whowhere.com [209.185.123.18]) + by ee.lbl.gov (8.9.3/8.9.3) with SMTP id IAA05100 + for <vern@ee.lbl.gov>; Tue, 15 Jun 1999 08:56:06 -0700 (PDT) +Received: from Unknown/Local ([?.?.?.?]) by my-deja.com; Tue Jun 15 08:55:43 1999 +To: vern@ee.lbl.gov +Date: Tue, 15 Jun 1999 08:55:43 -0700 +From: "Aki Niimura" <neko@my-deja.com> +Message-ID: <KNONDOHDOBGAEAAA@my-deja.com> +Mime-Version: 1.0 +Cc: +X-Sent-Mail: on +Reply-To: +X-Mailer: MailCity Service +Subject: A question on flex C++ scanner +X-Sender-Ip: 12.72.207.61 +Organization: My Deja Email (http://www.my-deja.com:80) +Content-Type: text/plain; charset=us-ascii +Content-Transfer-Encoding: 7bit + +Dear Dr. Paxon, + +I have been using flex for years. +It works very well on many projects. +Most case, I used it to generate a scanner on C language. +However, one project I needed to generate a scanner +on C++ lanuage. Thanks to your enhancement, flex did +the job. + +Currently, I'm working on enhancing my previous project. +I need to deal with multiple input streams (recursive +inclusion) in this scanner (C++). +I did similar thing for another scanner (C) as you +explained in your documentation. + +The generated scanner (C++) has necessary methods: +- switch_to_buffer(struct yy_buffer_state *b) +- yy_create_buffer(istream *is, int sz) +- yy_delete_buffer(struct yy_buffer_state *b) + +However, I couldn't figure out how to access current +buffer (yy_current_buffer). + +yy_current_buffer is a protected member of yyFlexLexer. +I can't access it directly. +Then, I thought yy_create_buffer() with is = 0 might +return current stream buffer. But it seems not as far +as I checked the source. (flex 2.5.4) + +I went through the Web in addition to Flex documentation. +However, it hasn't been successful, so far. + +It is not my intention to bother you, but, can you +comment about how to obtain the current stream buffer? + +Your response would be highly appreciated. + +Best regards, +Aki Niimura + +--== Sent via Deja.com http://www.deja.com/ ==-- +Share what you know. Learn what you don't. ++ + + +
+@verbatim +To: neko@my-deja.com +Subject: Re: A question on flex C++ scanner +In-reply-to: Your message of Tue, 15 Jun 1999 08:55:43 PDT. +Date: Tue, 15 Jun 1999 09:04:24 PDT +From: Vern Paxson <vern> + +> However, I couldn't figure out how to access current +> buffer (yy_current_buffer). + +Derive your own subclass from yyFlexLexer. + + Vern ++ + + +
+@verbatim +To: "Stones, Darren" <Darren.Stones@nectech.co.uk> +Subject: Re: You're the man to see? +In-reply-to: Your message of Wed, 23 Jun 1999 11:10:29 PDT. +Date: Wed, 23 Jun 1999 09:01:40 PDT +From: Vern Paxson <vern> + +> I hope you can help me. I am using Flex and Bison to produce an interpreted +> language. However all goes well until I try to implement an IF statement or +> a WHILE. I cannot get this to work as the parser parses all the conditions +> eg. the TRUE and FALSE conditons to check for a rule match. So I cannot +> make a decision!! + +You need to use the parser to build a parse tree (= abstract syntax trwee), +and when that's all done you recursively evaluate the tree, binding variables +to values at that time. + + Vern ++ + + +
+@verbatim +To: Petr Danecek <petr@ics.cas.cz> +Subject: Re: flex - question +In-reply-to: Your message of Mon, 28 Jun 1999 19:21:41 PDT. +Date: Fri, 02 Jul 1999 16:52:13 PDT +From: Vern Paxson <vern> + +> file, it takes an enormous amount of time. It is funny, because the +> source code has only 12 rules!!! I think it looks like an exponencial +> growth. + +Right, that's the problem - some patterns (those with a lot of +ambiguity, where yours has because at any given time the scanner can +be in the middle of all sorts of combinations of the different +rules) blow up exponentially. + +For your rules, there is an easy fix. Change the ".*" that comes fater +the directory name to "[^ ]*". With that in place, the rules are no +longer nearly so ambiguous, because then once one of the directories +has been matched, no other can be matched (since they all require a +leading blank). + +If that's not an acceptable solution, then you can enter a start state +to pick up the .*\n after each directory is matched. + +Also note that for speed, you'll want to add a ".*" rule at the end, +otherwise rules that don't match any of the patterns will be matched +very slowly, a character at a time. + + Vern ++ + + +
+@verbatim +To: Tielman Koekemoer <tielman@spi.co.za> +Subject: Re: Please help. +In-reply-to: Your message of Thu, 08 Jul 1999 13:20:37 PDT. +Date: Thu, 08 Jul 1999 08:20:39 PDT +From: Vern Paxson <vern> + +> I was hoping you could help me with my problem. +> +> I tried compiling (gnu)flex on a Solaris 2.4 machine +> but when I ran make (after configure) I got an error. +> +> -------------------------------------------------------------- +> gcc -c -I. -I. -g -O parse.c +> ./flex -t -p ./scan.l >scan.c +> sh: ./flex: not found +> *** Error code 1 +> make: Fatal error: Command failed for target `scan.c' +> ------------------------------------------------------------- +> +> What's strange to me is that I'm only +> trying to install flex now. I then edited the Makefile to +> and changed where it says "FLEX = flex" to "FLEX = lex" +> ( lex: the native Solaris one ) but then it complains about +> the "-p" option. Is there any way I can compile flex without +> using flex or lex? +> +> Thanks so much for your time. + +You managed to step on the bootstrap sequence, which first copies +initscan.c to scan.c in order to build flex. Try fetching a fresh +distribution from ftp.ee.lbl.gov. (Or you can first try removing +".bootstrap" and doing a make again.) + + Vern ++ + + +
+@verbatim +To: Tielman Koekemoer <tielman@spi.co.za> +Subject: Re: Please help. +In-reply-to: Your message of Fri, 09 Jul 1999 09:16:14 PDT. +Date: Fri, 09 Jul 1999 00:27:20 PDT +From: Vern Paxson <vern> + +> First I removed .bootstrap (and ran make) - no luck. I downloaded the +> software but I still have the same problem. Is there anything else I +> could try. + +Try: + + cp initscan.c scan.c + touch scan.c + make scan.o + +If this last tries to first build scan.c from scan.l using ./flex, then +your "make" is broken, in which case compile scan.c to scan.o by hand. + + Vern ++ + + +
+@verbatim +To: Sumanth Kamenani <skamenan@crl.nmsu.edu> +Subject: Re: Error +In-reply-to: Your message of Mon, 19 Jul 1999 23:08:41 PDT. +Date: Tue, 20 Jul 1999 00:18:26 PDT +From: Vern Paxson <vern> + +> I am getting a compilation error. The error is given as "unknown symbol- yylex". + +The parser relies on calling yylex(), but you're instead using the C++ scanning +class, so you need to supply a yylex() "glue" function that calls an instance +scanner of the scanner (e.g., "scanner->yylex()"). + + Vern ++ + + +
+@verbatim +To: daniel@synchrods.synchrods.COM (Daniel Senderowicz) +Subject: Re: lex +In-reply-to: Your message of Mon, 22 Nov 1999 11:19:04 PST. +Date: Tue, 23 Nov 1999 15:54:30 PST +From: Vern Paxson <vern> + +Well, your problem is the + +switch (yybgin-yysvec-1) { /* witchcraft */ + +at the beginning of lex rules. "witchcraft" == "non-portable". It's +assuming knowledge of the AT&T lex's internal variables. + +For flex, you can probably do the equivalent using a switch on YYSTATE. + + Vern ++ + + +
+@verbatim +To: archow@hss.hns.com +Subject: Re: Regarding distribution of flex and yacc based grammars +In-reply-to: Your message of Sun, 19 Dec 1999 17:50:24 +0530. +Date: Wed, 22 Dec 1999 01:56:24 PST +From: Vern Paxson <vern> + +> When we provide the customer with an object code distribution, is it +> necessary for us to provide source +> for the generated C files from flex and bison since they are generated by +> flex and bison ? + +For flex, no. I don't know what the current state of this is for bison. + +> Also, is there any requrirement for us to neccessarily provide source for +> the grammar files which are fed into flex and bison ? + +Again, for flex, no. + +See the file "COPYING" in the flex distribution for the legalese. + + Vern ++ + + +
+@verbatim +To: Martin Gallwey <gallweym@hyperion.moe.ul.ie> +Subject: Re: Flex, and self referencing rules +In-reply-to: Your message of Sun, 20 Feb 2000 01:01:21 PST. +Date: Sat, 19 Feb 2000 18:33:16 PST +From: Vern Paxson <vern> + +> However, I do not use unput anywhere. I do use self-referencing +> rules like this: +> +> UnaryExpr ({UnionExpr})|("-"{UnaryExpr}) + +You can't do this - flex is *not* a parser like yacc (which does indeed +allow recursion), it is a scanner that's confined to regular expressions. + + Vern ++ + + +
+@verbatim +To: slg3@lehigh.edu (SAMUEL L. GULDEN) +Subject: Re: Flex problem +In-reply-to: Your message of Thu, 02 Mar 2000 12:29:04 PST. +Date: Thu, 02 Mar 2000 23:00:46 PST +From: Vern Paxson <vern> + +If this is exactly your program: + +> digit [0-9] +> digits {digit}+ +> whitespace [ \t\n]+ +> +> %% +> "[" { printf("open_brac\n");} +> "]" { printf("close_brac\n");} +> "+" { printf("addop\n");} +> "*" { printf("multop\n");} +> {digits} { printf("NUMBER = %s\n", yytext);} +> whitespace ; + +then the problem is that the last rule needs to be "{whitespace}" ! + + Vern ++ + + +
@@ -6037,7 +8731,7 @@
Modern @command{make} programs understand that `foo.l' is intended to generate `lex.yy.c' or `foo.c', and will behave -accordingly(2) and GNU @command{automake} are two such +accordingly(3) and GNU @command{automake} are two such programs that provide implicit rules for flex-generated scanners.}. The following Makefile does not explicitly instruct @command{make} how to build `foo.c' from `foo.l'. Instead, it relies on the implicit rules of the @@ -6045,7 +8739,7 @@
@verbatim @@ -6065,7 +8759,7 @@+ + + +@verbatim @@ -6097,7 +8791,7 @@Finally, we provide a realistic example of a
flex
scanner used with a -bison
parser(3). +bison
parser(4). There is a tricky problem we have to deal with. Since aflex
scanner will typically include a header file (e.g., `y.tab.h') generated by the parser, we need to be sure that the header file is generated BEFORE the scanner @@ -6145,28 +8839,155 @@ -Indices
+C Scanners with Bison Parsers
+Concept Index
- - - - - - - - - - - +This section describes the
flex
features useful when integrating +flex
withGNU bison
(5). +Skip this section if you are not using +bison
with your scanner. Here we discuss only theflex
+half of theflex
andbison
pair. We do not discuss +bison
in any detail. For more information about generating +bison
parsers, see section `Top' in the GNU Bison Manual. + + ++A compatible
bison
scanner is generated by declaring `%option +bison-bridge' or by supplying `--bison-bridge' when invokingflex
+from the command line. This instructsflex
that the macros +yylval
andyylloc
may be used. The data types for +yylval
andyylloc
, (YYSTYPE
andYYLTYPE
, +are typically defined in a header file, included in section 1 of the +flex
input file. If%option bison-bridge
is +specified,flex
provides support for the functions +yyget_lval
,yyset_lval
,yyget_lloc
, and +yyset_lloc
, defined below, and the corresponding macros +yylval
andyylloc
, for use within actions. + + ++
+
+ + + ++Where yyscan_t is defined in the reentrant scanner (6). Accordingly, the declaration of +yylex becomes one of the following: + + +
+@verbatim + int yylex ( YYSTYPE * lvalp, yyscan_t scanner ); + int yylex ( YYSTYPE * lvalp, YYLTYPE * llocp, yyscan_t scanner ); ++ +
+Note that the macros yylval
and yylloc
evaluate to
+pointers. Support for yylloc
is optional in bison
, so it
+is optional in flex
as well. This support is automatically
+handled by flex
. Specifically, support for yyloc
is only
+present in a flex
scanner if the preprocessor symbol
+YYLTYPE
is defined. The following is an example of a flex
+scanner that is compatible with bison
.
+
+
+
+@verbatim + /* Scanner for "C" assignment statements... sort of. */ + %{ + #include "y.tab.h" /* Generated by bison. */ + %} + + %option reentrant-bison + % + + [[:digit:]]+ { yylval->num = atoi(yytext); return NUMBER;} + [[:alnum:]]+ { yylval->str = strdup(yytext); return STRING;} + "="|";" { return yytext[0];} + . {} + % ++ +
+As you can see, there really is no magic here. We just use
+yylval
as we would any other variable. The data type of
+yylval
is generated by bison
, and included in the file
+`y.tab.h'. Here is the corresponding bison
parser:
+
+
+
+@verbatim + /* Parser to convert "C" assignments to lisp. */ + %{ + /* Pass the argument to yyparse through to yylex. */ + #define YYPARSE_PARAM scanner + #define YYLEX_PARAM scanner + %} + %pure_parser + %union { + int num; + char* str; + } + %token <str> STRING + %token <num> NUMBER + %% + assignment: + STRING '=' NUMBER ';' { + printf( "(setf %s %d)", $1, $3 ); + } + ; ++ + + +
Jump to: $ - % - +< +- [ - ^ @@ -6183,6 +9004,8 @@ - f - +g +- h - i @@ -6215,260 +9038,366 @@
This is an index of functions and preprocessor macros that look like functions. -For macros that expand to variables or constants, see section Index of Variables. +For macros that expand to variables or constants, see section Index of Variables.
@@ -6485,70 +9414,74 @@
This is an index of variables, constants, and preprocessor macros @@ -6563,30 +9496,30 @@
Jump to: f @@ -6595,23 +9528,23 @@
This is an index of "hooks" that the user may define. These hooks typically correspond @@ -6624,175 +9557,254 @@
Jump to: -< +- +- +7 - -a +8 - -b +a - -c +b - -d +c - -e +d - -f +e - -g +f - -h +h - -m +i - -n +l - -p +m - -r +n - -s +o - -t +p - -u +r - -w +s - -y +t +- +v +- +w +- +y
-
-This document was generated on 2 July 2002 using +This document was generated on 9 November 2002 using texi2html 1.56k. Index: ossp-adm/autotools/flex_toc.html RCS File: /v/ossp/cvs/ossp-adm/autotools/flex_toc.html,v co -q -kk -p'1.1' '/v/ossp/cvs/ossp-adm/autotools/flex_toc.html,v' | diff -u /dev/null - -L'ossp-adm/autotools/flex_toc.html' 2>/dev/null --- ossp-adm/autotools/flex_toc.html +++ - 2025-04-19 11:03:21.591075820 +0200 @@ -0,0 +1,203 @@ + +
+ + ++
+
+This document was generated on 9 November 2002 using +texi2html 1.56k. + +