flex-2.6.0/0002755000175000017500000000000012651103361012727 5ustar srivastasrivastaflex-2.6.0/doc/0002755000175000017500000000000012651104534013477 5ustar srivastasrivastaflex-2.6.0/doc/flex.texi0000644000175000017500000107641012620500343015331 0ustar srivastasrivasta\input texinfo.tex @c -*-texinfo-*- @c %**start of header @setfilename flex.info @include version.texi @settitle Lexical Analysis With Flex, for Flex @value{VERSION} @set authors Vern Paxson, Will Estes and John Millaway @c "Macro Hooks" index @defindex hk @c "Options" index @defindex op @dircategory Programming @direntry * flex: (flex). Fast lexical analyzer generator (lex replacement). @end direntry @c %**end of header @copying The flex manual is placed under the same licensing conditions as the rest of flex: Copyright @copyright{} 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2012 The Flex Project. Copyright @copyright{} 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: @enumerate @item Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. @item 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. @end enumerate 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. @end copying @titlepage @title Lexical Analysis with Flex @subtitle Edition @value{EDITION}, @value{UPDATED} @author @value{authors} @page @vskip 0pt plus 1filll @insertcopying @end titlepage @contents @ifnottex @node Top, Copyright, (dir), (dir) @top flex This manual describes @code{flex}, a tool for generating programs that perform pattern-matching on text. The manual includes both tutorial and reference sections. This edition of @cite{The flex Manual} documents @code{flex} version @value{VERSION}. It was last updated on @value{UPDATED}. This manual was written by @value{authors}. @menu * Copyright:: * Reporting Bugs:: * Introduction:: * Simple Examples:: * Format:: * Patterns:: * Matching:: * Actions:: * Generated Scanner:: * Start Conditions:: * Multiple Input Buffers:: * EOF:: * Misc Macros:: * User Values:: * Yacc:: * Scanner Options:: * Performance:: * Cxx:: * Reentrant:: * Lex and Posix:: * Memory Management:: * Serialized Tables:: * Diagnostics:: * Limitations:: * Bibliography:: * FAQ:: * Appendices:: * Indices:: @detailmenu --- The Detailed Node Listing --- Format of the Input File * Definitions Section:: * Rules Section:: * User Code Section:: * Comments in the Input:: Scanner Options * Options for Specifying Filenames:: * Options Affecting Scanner Behavior:: * Code-Level And API Options:: * Options for Scanner Speed and Size:: * Debugging Options:: * Miscellaneous Options:: Reentrant C Scanners * Reentrant Uses:: * Reentrant Overview:: * Reentrant Example:: * Reentrant Detail:: * Reentrant Functions:: The Reentrant API in Detail * Specify Reentrant:: * Extra Reentrant Argument:: * Global Replacement:: * Init and Destroy Functions:: * Accessor Methods:: * Extra Data:: * About yyscan_t:: Memory Management * The Default Memory Management:: * Overriding The Default Memory Management:: * A Note About yytext And Memory:: Serialized Tables * Creating Serialized Tables:: * Loading and Unloading Serialized Tables:: * Tables File Format:: FAQ * When was flex born?:: * How do I expand backslash-escape sequences in C-style quoted strings?:: * Why do flex scanners call fileno if it is not ANSI compatible?:: * Does flex support recursive pattern definitions?:: * How do I skip huge chunks of input (tens of megabytes) while using flex?:: * Flex is not matching my patterns in the same order that I defined them.:: * My actions are executing out of order or sometimes not at all.:: * How can I have multiple input sources feed into the same scanner at the same time?:: * Can I build nested parsers that work with the same input file?:: * How can I match text only at the end of a file?:: * How can I make REJECT cascade across start condition boundaries?:: * Why cant I use fast or full tables with interactive mode?:: * How much faster is -F or -f than -C?:: * If I have a simple grammar cant I just parse it with flex?:: * Why doesn't yyrestart() set the start state back to INITIAL?:: * How can I match C-style comments?:: * The period isn't working the way I expected.:: * Can I get the flex manual in another format?:: * Does there exist a "faster" NDFA->DFA algorithm?:: * How does flex compile the DFA so quickly?:: * How can I use more than 8192 rules?:: * How do I abandon a file in the middle of a scan and switch to a new file?:: * How do I execute code only during initialization (only before the first scan)?:: * How do I execute code at termination?:: * Where else can I find help?:: * Can I include comments in the "rules" section of the file?:: * I get an error about undefined yywrap().:: * How can I change the matching pattern at run time?:: * How can I expand macros in the input?:: * How can I build a two-pass scanner?:: * How do I match any string not matched in the preceding rules?:: * I am trying to port code from AT&T lex that uses yysptr and yysbuf.:: * Is there a way to make flex treat NULL like a regular character?:: * Whenever flex can not match the input it says "flex scanner jammed".:: * Why doesn't flex have non-greedy operators like perl does?:: * Memory leak - 16386 bytes allocated by malloc.:: * How do I track the byte offset for lseek()?:: * How do I use my own I/O classes in a C++ scanner?:: * How do I skip as many chars as possible?:: * deleteme00:: * Are certain equivalent patterns faster than others?:: * Is backing up a big deal?:: * Can I fake multi-byte character support?:: * deleteme01:: * Can you discuss some flex internals?:: * unput() messes up yy_at_bol:: * The | operator is not doing what I want:: * Why can't flex understand this variable trailing context pattern?:: * The ^ operator isn't working:: * Trailing context is getting confused with trailing optional patterns:: * Is flex GNU or not?:: * ERASEME53:: * I need to scan if-then-else blocks and while loops:: * ERASEME55:: * ERASEME56:: * ERASEME57:: * Is there a repository for flex scanners?:: * How can I conditionally compile or preprocess my flex input file?:: * Where can I find grammars for lex and yacc?:: * I get an end-of-buffer message for each character scanned.:: * unnamed-faq-62:: * unnamed-faq-63:: * unnamed-faq-64:: * unnamed-faq-65:: * unnamed-faq-66:: * unnamed-faq-67:: * unnamed-faq-68:: * unnamed-faq-69:: * unnamed-faq-70:: * unnamed-faq-71:: * unnamed-faq-72:: * unnamed-faq-73:: * unnamed-faq-74:: * unnamed-faq-75:: * unnamed-faq-76:: * unnamed-faq-77:: * unnamed-faq-78:: * unnamed-faq-79:: * unnamed-faq-80:: * unnamed-faq-81:: * unnamed-faq-82:: * unnamed-faq-83:: * unnamed-faq-84:: * unnamed-faq-85:: * unnamed-faq-86:: * unnamed-faq-87:: * unnamed-faq-88:: * unnamed-faq-90:: * unnamed-faq-91:: * unnamed-faq-92:: * unnamed-faq-93:: * unnamed-faq-94:: * unnamed-faq-95:: * unnamed-faq-96:: * unnamed-faq-97:: * unnamed-faq-98:: * unnamed-faq-99:: * unnamed-faq-100:: * unnamed-faq-101:: * What is the difference between YYLEX_PARAM and YY_DECL?:: * Why do I get "conflicting types for yylex" error?:: * How do I access the values set in a Flex action from within a Bison action?:: Appendices * Makefiles and Flex:: * Bison Bridge:: * M4 Dependency:: * Common Patterns:: Indices * Concept Index:: * Index of Functions and Macros:: * Index of Variables:: * Index of Data Types:: * Index of Hooks:: * Index of Scanner Options:: @end detailmenu @end menu @end ifnottex @node Copyright, Reporting Bugs, Top, Top @chapter Copyright @cindex copyright of flex @cindex distributing flex @insertcopying @node Reporting Bugs, Introduction, Copyright, Top @chapter Reporting Bugs @cindex bugs, reporting @cindex reporting bugs If you find a bug in @code{flex}, please report it using the SourceForge Bug Tracking facilities which can be found on @url{http://sourceforge.net/projects/flex,flex's SourceForge Page}. @node Introduction, Simple Examples, Reporting Bugs, Top @chapter Introduction @cindex scanner, definition of @code{flex} is a tool for generating @dfn{scanners}. A scanner is a program which recognizes lexical patterns in text. The @code{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 @dfn{rules}. @code{flex} generates as output a C source file, @file{lex.yy.c} by default, which defines a routine @code{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. @node Simple Examples, Format, Introduction, Top @chapter Some Simple Examples First some simple examples to get the flavor of how one uses @code{flex}. @cindex username expansion The following @code{flex} input specifies a scanner which, when it encounters the string @samp{username} will replace it with the user's login name: @example @verbatim %% username printf( "%s", getlogin() ); @end verbatim @end example @cindex default rule @cindex rules, default By default, any text not matched by a @code{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 @samp{username} expanded. In this input, there is just one rule. @samp{username} is the @dfn{pattern} and the @samp{printf} is the @dfn{action}. The @samp{%%} symbol marks the beginning of the rules. Here's another simple example: @cindex counting characters and lines @example @verbatim int num_lines = 0, num_chars = 0; %% \n ++num_lines; ++num_chars; . ++num_chars; %% int main() { yylex(); printf( "# of lines = %d, # of chars = %d\n", num_lines, num_chars ); } @end verbatim @end example 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, @code{num_lines} and @code{num_chars}, which are accessible both inside @code{yylex()} and in the @code{main()} routine declared after the second @samp{%%}. There are two rules, one which matches a newline (@samp{\n}) and increments both the line count and the character count, and one which matches any character other than a newline (indicated by the @samp{.} regular expression). A somewhat more complicated example: @cindex Pascal-like language @example @verbatim /* scanner for a toy Pascal-like language */ %{ /* need this for the call to atof() below */ #include %} DIGIT [0-9] ID [a-z][a-z0-9]* %% {DIGIT}+ { printf( "An integer: %s (%d)\n", yytext, atoi( yytext ) ); } {DIGIT}+"."{DIGIT}* { printf( "A float: %s (%g)\n", yytext, atof( yytext ) ); } if|then|begin|end|procedure|function { printf( "A keyword: %s\n", yytext ); } {ID} printf( "An identifier: %s\n", yytext ); "+"|"-"|"*"|"/" printf( "An operator: %s\n", yytext ); "{"[\^{}}\n]*"}" /* eat up one-line comments */ [ \t\n]+ /* eat up whitespace */ . printf( "Unrecognized character: %s\n", yytext ); %% int main( int argc, char **argv ) { ++argv, --argc; /* skip over program name */ if ( argc > 0 ) yyin = fopen( argv[0], "r" ); else yyin = stdin; yylex(); } @end verbatim @end example This is the beginnings of a simple scanner for a language like Pascal. It identifies different types of @dfn{tokens} and reports on what it has seen. The details of this example will be explained in the following sections. @node Format, Patterns, Simple Examples, Top @chapter Format of the Input File @cindex format of flex input @cindex input, format of @cindex file format @cindex sections of flex input The @code{flex} input file consists of three sections, separated by a line containing only @samp{%%}. @cindex format of input file @example @verbatim definitions %% rules %% user code @end verbatim @end example @menu * Definitions Section:: * Rules Section:: * User Code Section:: * Comments in the Input:: @end menu @node Definitions Section, Rules Section, Format, Format @section Format of the Definitions Section @cindex input file, Definitions section @cindex Definitions, in flex input The @dfn{definitions section} contains declarations of simple @dfn{name} definitions to simplify the scanner specification, and declarations of @dfn{start conditions}, which are explained in a later section. @cindex aliases, how to define @cindex pattern aliases, how to define Name definitions have the form: @example @verbatim name definition @end verbatim @end example The @samp{name} is a word beginning with a letter or an underscore (@samp{_}) followed by zero or more letters, digits, @samp{_}, or @samp{-} (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 @samp{@{name@}}, which will expand to @samp{(definition)}. For example, @cindex pattern aliases, defining @cindex defining pattern aliases @example @verbatim DIGIT [0-9] ID [a-z][a-z0-9]* @end verbatim @end example Defines @samp{DIGIT} to be a regular expression which matches a single digit, and @samp{ID} to be a regular expression which matches a letter followed by zero-or-more letters-or-digits. A subsequent reference to @cindex pattern aliases, use of @example @verbatim {DIGIT}+"."{DIGIT}* @end verbatim @end example is identical to @example @verbatim ([0-9])+"."([0-9])* @end verbatim @end example and matches one-or-more digits followed by a @samp{.} followed by zero-or-more digits. @cindex comments in flex input An unindented comment (i.e., a line beginning with @samp{/*}) is copied verbatim to the output up to the next @samp{*/}. @cindex %@{ and %@}, in Definitions Section @cindex embedding C code in flex input @cindex C code in flex input Any @emph{indented} text or text enclosed in @samp{%@{} and @samp{%@}} is also copied verbatim to the output (with the %@{ and %@} symbols removed). The %@{ and %@} symbols must appear unindented on lines by themselves. @cindex %top A @code{%top} block is similar to a @samp{%@{} ... @samp{%@}} block, except that the code in a @code{%top} block is relocated to the @emph{top} of the generated file, before any flex definitions @footnote{Actually, @code{yyIN_HEADER} is defined before the @samp{%top} block.}. The @code{%top} block is useful when you want certain preprocessor macros to be defined or certain files to be included before the generated code. The single characters, @samp{@{} and @samp{@}} are used to delimit the @code{%top} block, as show in the example below: @example @verbatim %top{ /* This code goes at the "top" of the generated file. */ #include #include } @end verbatim @end example Multiple @code{%top} blocks are allowed, and their order is preserved. @node Rules Section, User Code Section, Definitions Section, Format @section Format of the Rules Section @cindex input file, Rules Section @cindex rules, in flex input The @dfn{rules} section of the @code{flex} input contains a series of rules of the form: @example @verbatim pattern action @end verbatim @end example where the pattern must be unindented and the action must begin on the same line. @xref{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. @xref{Lex and Posix}, for other such features). Any @emph{indented} text or text enclosed in @samp{%@{} and @samp{%@}} is copied verbatim to the output (with the %@{ and %@} symbols removed). The %@{ and %@} symbols must appear unindented on lines by themselves. @node User Code Section, Comments in the Input, Rules Section, Format @section Format of the User Code Section @cindex input file, user code Section @cindex user code, in flex input The user code section is simply copied to @file{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 @samp{%%} in the input file may be skipped, too. @node Comments in the Input, , User Code Section, Format @section Comments in the Input @cindex comments, syntax of Flex supports C-style comments, that is, anything between @samp{/*} and @samp{*/} 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: @itemize @cindex comments, in rules section @item Comments may not appear in the Rules Section wherever flex is expecting a regular expression. This means comments may not appear at the beginning of a line, or immediately following a list of scanner states. @item Comments may not appear on an @samp{%option} line in the Definitions Section. @end itemize 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 @samp{/*}). This rule will work anywhere in the input file. All the comments in the following example are valid: @cindex comments, valid uses of @cindex comments in the input @example @verbatim %{ /* code block */ %} /* Definitions Section */ %x STATE_X %% /* Rules Section */ ruleA /* after regex */ { /* code block */ } /* after code block */ /* Rules Section (indented) */ { ruleC ECHO; ruleD ECHO; %{ /* code block */ %} } %% /* User Code Section */ @end verbatim @end example @node Patterns, Matching, Format, Top @chapter Patterns @cindex patterns, in rules section @cindex regular expressions, in patterns The patterns in the input (see @ref{Rules Section}) are written using an extended set of regular expressions. These are: @cindex patterns, syntax @cindex patterns, syntax @table @samp @item x match the character 'x' @item . any character (byte) except newline @cindex [] in patterns @cindex character classes in patterns, syntax of @cindex POSIX, character classes in patterns, syntax of @item [xyz] a @dfn{character class}; in this case, the pattern matches either an 'x', a 'y', or a 'z' @cindex ranges in patterns @item [abj-oZ] a "character class" with a range in it; matches an 'a', a 'b', any letter from 'j' through 'o', or a 'Z' @cindex ranges in patterns, negating @cindex negating ranges in patterns @item [^A-Z] a "negated character class", i.e., any character but those in the class. In this case, any character EXCEPT an uppercase letter. @item [^A-Z\n] any character EXCEPT an uppercase letter or a newline @item [a-z]@{-@}[aeiou] the lowercase consonants @item r* zero or more r's, where r is any regular expression @item r+ one or more r's @item r? zero or one r's (that is, ``an optional r'') @cindex braces in patterns @item r@{2,5@} anywhere from two to five r's @item r@{2,@} two or more r's @item r@{4@} exactly 4 r's @cindex pattern aliases, expansion of @item @{name@} the expansion of the @samp{name} definition (@pxref{Format}). @cindex literal text in patterns, syntax of @cindex verbatim text in patterns, syntax of @item "[xyz]\"foo" the literal string: @samp{[xyz]"foo} @cindex escape sequences in patterns, syntax of @item \X if X is @samp{a}, @samp{b}, @samp{f}, @samp{n}, @samp{r}, @samp{t}, or @samp{v}, then the ANSI-C interpretation of @samp{\x}. Otherwise, a literal @samp{X} (used to escape operators such as @samp{*}) @cindex NULL character in patterns, syntax of @item \0 a NUL character (ASCII code 0) @cindex octal characters in patterns @item \123 the character with octal value 123 @item \x2a the character with hexadecimal value 2a @item (r) match an @samp{r}; parentheses are used to override precedence (see below) @item (?r-s:pattern) apply option @samp{r} and omit option @samp{s} while interpreting pattern. Options may be zero or more of the characters @samp{i}, @samp{s}, or @samp{x}. @samp{i} means case-insensitive. @samp{-i} means case-sensitive. @samp{s} alters the meaning of the @samp{.} syntax to match any single byte whatsoever. @samp{-s} alters the meaning of @samp{.} to match any byte except @samp{\n}. @samp{x} ignores comments and whitespace in patterns. Whitespace is ignored unless it is backslash-escaped, contained within @samp{""}s, or appears inside a character class. The following are all valid: @verbatim (?:foo) same as (foo) (?i:ab7) same as ([aA][bB]7) (?-i:ab) same as (ab) (?s:.) same as [\x00-\xFF] (?-s:.) same as [^\n] (?ix-s: a . b) same as ([Aa][^\n][bB]) (?x:a b) same as ("ab") (?x:a\ b) same as ("a b") (?x:a" "b) same as ("a b") (?x:a[ ]b) same as ("a b") (?x:a /* comment */ b c) same as (abc) @end verbatim @item (?# comment ) omit everything within @samp{()}. The first @samp{)} character encountered ends the pattern. It is not possible to for the comment to contain a @samp{)} character. The comment may span lines. @cindex concatenation, in patterns @item rs the regular expression @samp{r} followed by the regular expression @samp{s}; called @dfn{concatenation} @item r|s either an @samp{r} or an @samp{s} @cindex trailing context, in patterns @item r/s an @samp{r} but only if it is followed by an @samp{s}. The text matched by @samp{s} is included when determining whether this rule is the longest match, but is then returned to the input before the action is executed. So the action only sees the text matched by @samp{r}. This type of pattern is called @dfn{trailing context}. (There are some combinations of @samp{r/s} that flex cannot match correctly. @xref{Limitations}, regarding dangerous trailing context.) @cindex beginning of line, in patterns @cindex BOL, in patterns @item ^r an @samp{r}, but only at the beginning of a line (i.e., when just starting to scan, or right after a newline has been scanned). @cindex end of line, in patterns @cindex EOL, in patterns @item r$ an @samp{r}, but only at the end of a line (i.e., just before a newline). Equivalent to @samp{r/\n}. @cindex newline, matching in patterns Note that @code{flex}'s notion of ``newline'' is exactly whatever the C compiler used to compile @code{flex} interprets @samp{\n} as; in particular, on some DOS systems you must either filter out @samp{\r}s in the input yourself, or explicitly use @samp{r/\r\n} for @samp{r$}. @cindex start conditions, in patterns @item r an @samp{r}, but only in start condition @code{s} (see @ref{Start Conditions} for discussion of start conditions). @item r same, but in any of start conditions @code{s1}, @code{s2}, or @code{s3}. @item <*>r an @samp{r} in any start condition, even an exclusive one. @cindex end of file, in patterns @cindex EOF in patterns, syntax of @item <> an end-of-file. @item <> an end-of-file when in start condition @code{s1} or @code{s2} @end table Note that inside of a character class, all regular expression operators lose their special meaning except escape (@samp{\}) and the character class operators, @samp{-}, @samp{]]}, and, at the beginning of the class, @samp{^}. @cindex patterns, precedence of operators 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 precedence of the repeat operator, @samp{@{@}}, under the documentation for the @samp{--posix} POSIX compliance option). For example, @cindex patterns, grouping and precedence @example @verbatim foo|bar* @end verbatim @end example is the same as @example @verbatim (foo)|(ba(r*)) @end verbatim @end example since the @samp{*} operator has higher precedence than concatenation, and concatenation higher than alternation (@samp{|}). This pattern therefore matches @emph{either} the string @samp{foo} @emph{or} the string @samp{ba} followed by zero-or-more @samp{r}'s. To match @samp{foo} or zero-or-more repetitions of the string @samp{bar}, use: @example @verbatim foo|(bar)* @end verbatim @end example And to match a sequence of zero or more repetitions of @samp{foo} and @samp{bar}: @cindex patterns, repetitions with grouping @example @verbatim (foo|bar)* @end verbatim @end example @cindex character classes in patterns In addition to characters and ranges of characters, character classes can also contain @dfn{character class expressions}. These are expressions enclosed inside @samp{[:} and @samp{:]} delimiters (which themselves must appear between the @samp{[} and @samp{]} of the character class. Other elements may occur inside the character class, too). The valid expressions are: @cindex patterns, valid character classes @example @verbatim [:alnum:] [:alpha:] [:blank:] [:cntrl:] [:digit:] [:graph:] [:lower:] [:print:] [:punct:] [:space:] [:upper:] [:xdigit:] @end verbatim @end example These expressions all designate a set of characters equivalent to the corresponding standard C @code{isXXX} function. For example, @samp{[:alnum:]} designates those characters for which @code{isalnum()} returns true - i.e., any alphabetic or numeric character. Some systems don't provide @code{isblank()}, so flex defines @samp{[:blank:]} as a blank or a tab. For example, the following character classes are all equivalent: @cindex character classes, equivalence of @cindex patterns, character class equivalence @example @verbatim [[:alnum:]] [[:alpha:][:digit:]] [[:alpha:][0-9]] [a-zA-Z0-9] @end verbatim @end example A word of caution. Character classes are expanded immediately when seen in the @code{flex} input. This means the character classes are sensitive to the locale in which @code{flex} is executed, and the resulting scanner will not be sensitive to the runtime locale. This may or may not be desirable. @itemize @cindex case-insensitive, effect on character classes @item If your scanner is case-insensitive (the @samp{-i} flag), then @samp{[:upper:]} and @samp{[:lower:]} are equivalent to @samp{[:alpha:]}. @anchor{case and character ranges} @item Character classes with ranges, such as @samp{[a-Z]}, should be used with caution in a case-insensitive scanner if the range spans upper or lowercase characters. Flex does not know if you want to fold all upper and lowercase characters together, or if you want the literal numeric range specified (with no case folding). When in doubt, flex will assume that you meant the literal numeric range, and will issue a warning. The exception to this rule is a character range such as @samp{[a-z]} or @samp{[S-W]} where it is obvious that you want case-folding to occur. Here are some examples with the @samp{-i} flag enabled: @multitable {@samp{[a-zA-Z]}} {ambiguous} {@samp{[A-Z\[\\\]_`a-t]}} {@samp{[@@A-Z\[\\\]_`abc]}} @item Range @tab Result @tab Literal Range @tab Alternate Range @item @samp{[a-t]} @tab ok @tab @samp{[a-tA-T]} @tab @item @samp{[A-T]} @tab ok @tab @samp{[a-tA-T]} @tab @item @samp{[A-t]} @tab ambiguous @tab @samp{[A-Z\[\\\]_`a-t]} @tab @samp{[a-tA-T]} @item @samp{[_-@{]} @tab ambiguous @tab @samp{[_`a-z@{]} @tab @samp{[_`a-zA-Z@{]} @item @samp{[@@-C]} @tab ambiguous @tab @samp{[@@ABC]} @tab @samp{[@@A-Z\[\\\]_`abc]} @end multitable @cindex end of line, in negated character classes @cindex EOL, in negated character classes @item A negated character class such as the example @samp{[^A-Z]} above @emph{will} match a newline unless @samp{\n} (or an equivalent escape sequence) is one of the characters explicitly present in the negated character class (e.g., @samp{[^A-Z\n]}). This is unlike how many other regular expression tools treat negated character classes, but unfortunately the inconsistency is historically entrenched. Matching newlines means that a pattern like @samp{[^"]*} can match the entire input unless there's another quote in the input. Flex allows negation of character class expressions by prepending @samp{^} to the POSIX character class name. @example @verbatim [:^alnum:] [:^alpha:] [:^blank:] [:^cntrl:] [:^digit:] [:^graph:] [:^lower:] [:^print:] [:^punct:] [:^space:] [:^upper:] [:^xdigit:] @end verbatim @end example Flex will issue a warning if the expressions @samp{[:^upper:]} and @samp{[:^lower:]} appear in a case-insensitive scanner, since their meaning is unclear. The current behavior is to skip them entirely, but this may change without notice in future revisions of flex. @item The @samp{@{-@}} operator computes the difference of two character classes. For example, @samp{[a-c]@{-@}[b-z]} represents all the characters in the class @samp{[a-c]} that are not in the class @samp{[b-z]} (which in this case, is just the single character @samp{a}). The @samp{@{-@}} operator is left associative, so @samp{[abc]@{-@}[b]@{-@}[c]} is the same as @samp{[a]}. Be careful not to accidentally create an empty set, which will never match. @item The @samp{@{+@}} operator computes the union of two character classes. For example, @samp{[a-z]@{+@}[0-9]} is the same as @samp{[a-z0-9]}. This operator is useful when preceded by the result of a difference operation, as in, @samp{[[:alpha:]]@{-@}[[:lower:]]@{+@}[q]}, which is equivalent to @samp{[A-Zq]} in the "C" locale. @cindex trailing context, limits of @cindex ^ as non-special character in patterns @cindex $ as normal character in patterns @item A rule can have at most one instance of trailing context (the @samp{/} operator or the @samp{$} operator). The start condition, @samp{^}, and @samp{<>} patterns can only occur at the beginning of a pattern, and, as well as with @samp{/} and @samp{$}, cannot be grouped inside parentheses. A @samp{^} which does not occur at the beginning of a rule or a @samp{$} which does not occur at the end of a rule loses its special properties and is treated as a normal character. @item The following are invalid: @cindex patterns, invalid trailing context @example @verbatim foo/bar$ foobar @end verbatim @end example Note that the first of these can be written @samp{foo/bar\n}. @item The following will result in @samp{$} or @samp{^} being treated as a normal character: @cindex patterns, special characters treated as non-special @example @verbatim foo|(bar$) foo|^bar @end verbatim @end example If the desired meaning is a @samp{foo} or a @samp{bar}-followed-by-a-newline, the following could be used (the special @code{|} action is explained below, @pxref{Actions}): @cindex patterns, end of line @example @verbatim foo | bar$ /* action goes here */ @end verbatim @end example A similar trick will work for matching a @samp{foo} or a @samp{bar}-at-the-beginning-of-a-line. @end itemize @node Matching, Actions, Patterns, Top @chapter How the Input Is Matched @cindex patterns, matching @cindex input, matching @cindex trailing context, matching @cindex matching, and trailing context @cindex matching, length of @cindex matching, multiple matches When the generated scanner is run, it analyzes its input looking for strings which match any of its patterns. If it finds more than one match, it takes the one matching the most text (for trailing context rules, this includes the length of the trailing part, even though it will then be returned to the input). If it finds two or more matches of the same length, the rule listed first in the @code{flex} input file is chosen. @cindex token @cindex yytext @cindex yyleng Once the match is determined, the text corresponding to the match (called the @dfn{token}) is made available in the global character pointer @code{yytext}, and its length in the global integer @code{yyleng}. The @dfn{action} corresponding to the matched pattern is then executed (@pxref{Actions}), and then the remaining input is scanned for another match. @cindex default rule If no match is found, then the @dfn{default rule} is executed: the next character in the input is considered matched and copied to the standard output. Thus, the simplest valid @code{flex} input is: @cindex minimal scanner @example @verbatim %% @end verbatim @end example which generates a scanner that simply copies its input (one character at a time) to its output. @cindex yytext, two types of @cindex %array, use of @cindex %pointer, use of @vindex yytext Note that @code{yytext} can be defined in two different ways: either as a character @emph{pointer} or as a character @emph{array}. You can control which definition @code{flex} uses by including one of the special directives @code{%pointer} or @code{%array} in the first (definitions) section of your flex input. The default is @code{%pointer}, unless you use the @samp{-l} lex compatibility option, in which case @code{yytext} will be an array. The advantage of using @code{%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 @code{yytext} (@pxref{Actions}), and calls to the @code{unput()} function destroys the present contents of @code{yytext}, which can be a considerable porting headache when moving between different @code{lex} versions. @cindex %array, advantages of The advantage of @code{%array} is that you can then modify @code{yytext} to your heart's content, and calls to @code{unput()} do not destroy @code{yytext} (@pxref{Actions}). Furthermore, existing @code{lex} programs sometimes access @code{yytext} externally using declarations of the form: @example @verbatim extern char yytext[]; @end verbatim @end example This definition is erroneous when used with @code{%pointer}, but correct for @code{%array}. The @code{%array} declaration defines @code{yytext} to be an array of @code{YYLMAX} characters, which defaults to a fairly large value. You can change the size by simply #define'ing @code{YYLMAX} to a different value in the first section of your @code{flex} input. As mentioned above, with @code{%pointer} yytext grows dynamically to accommodate large tokens. While this means your @code{%pointer} scanner can accommodate very large tokens (such as matching entire blocks of comments), bear in mind that each time the scanner must resize @code{yytext} it also must rescan the entire token from the beginning, so matching such tokens can prove slow. @code{yytext} presently does @emph{not} dynamically grow if a call to @code{unput()} results in too much text being pushed back; instead, a run-time error results. @cindex %array, with C++ Also note that you cannot use @code{%array} with C++ scanner classes (@pxref{Cxx}). @node Actions, Generated Scanner, Matching, Top @chapter Actions @cindex actions Each pattern in a rule has a corresponding @dfn{action}, which can be any arbitrary C statement. The pattern ends at the first non-escaped whitespace character; the remainder of the line is its action. If the action is empty, then when the pattern is matched the input token is simply discarded. For example, here is the specification for a program which deletes all occurrences of @samp{zap me} from its input: @cindex deleting lines from input @example @verbatim %% "zap me" @end verbatim @end example This example will copy all other characters in the input to the output since they will be matched by the default rule. Here is a program which compresses multiple blanks and tabs down to a single blank, and throws away whitespace found at the end of a line: @cindex whitespace, compressing @cindex compressing whitespace @example @verbatim %% [ \t]+ putchar( ' ' ); [ \t]+$ /* ignore this token */ @end verbatim @end example @cindex %@{ and %@}, in Rules Section @cindex actions, use of @{ and @} @cindex actions, embedded C strings @cindex C-strings, in actions @cindex comments, in actions If the action contains a @samp{@{}, then the action spans till the balancing @samp{@}} is found, and the action may cross multiple lines. @code{flex} knows about C strings and comments and won't be fooled by braces found within them, but also allows actions to begin with @samp{%@{} and will consider the action to be all the text up to the next @samp{%@}} (regardless of ordinary braces inside the action). @cindex |, in actions An action consisting solely of a vertical bar (@samp{|}) means ``same as the action for the next rule''. See below for an illustration. Actions can include arbitrary C code, including @code{return} statements to return a value to whatever routine called @code{yylex()}. Each time @code{yylex()} is called it continues processing tokens from where it last left off until it either reaches the end of the file or executes a return. @cindex yytext, modification of Actions are free to modify @code{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 @code{%array} (@pxref{Matching}). In that case, @code{yytext} may be freely modified in any way. @cindex yyleng, modification of @cindex yymore, and yyleng Actions are free to modify @code{yyleng} except they should not do so if the action also includes use of @code{yymore()} (see below). @cindex preprocessor macros, for use in actions There are a number of special directives which can be included within an action: @table @code @item ECHO @cindex ECHO copies yytext to the scanner's output. @item BEGIN @cindex BEGIN followed by the name of a start condition places the scanner in the corresponding start condition (see below). @item REJECT @cindex REJECT directs the scanner to proceed on to the ``second best'' rule which matched the input (or a prefix of the input). The rule is chosen as described above in @ref{Matching}, and @code{yytext} and @code{yyleng} set up appropriately. It may either be one which matched as much text as the originally chosen rule but came later in the @code{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 @code{special()} whenever @samp{frob} is seen: @example @verbatim int word_count = 0; %% frob special(); REJECT; [^ \t\n]+ ++word_count; @end verbatim @end example Without the @code{REJECT}, any occurrences of @samp{frob} in the input would not be counted as words, since the scanner normally executes only one action per token. Multiple uses of @code{REJECT} are allowed, each one finding the next best choice to the currently active rule. For example, when the following scanner scans the token @samp{abcd}, it will write @samp{abcdabcaba} to the output: @cindex REJECT, calling multiple times @cindex |, use of @example @verbatim %% a | ab | abc | abcd ECHO; REJECT; .|\n /* eat up any unmatched character */ @end verbatim @end example The first three rules share the fourth's action since they use the special @samp{|} action. @code{REJECT} is a particularly expensive feature in terms of scanner performance; if it is used in @emph{any} of the scanner's actions it will slow down @emph{all} of the scanner's matching. Furthermore, @code{REJECT} cannot be used with the @samp{-Cf} or @samp{-CF} options (@pxref{Scanner Options}). Note also that unlike the other special actions, @code{REJECT} is a @emph{branch}. Code immediately following it in the action will @emph{not} be executed. @item yymore() @cindex yymore() tells the scanner that the next time it matches a rule, the corresponding token should be @emph{appended} onto the current value of @code{yytext} rather than replacing it. For example, given the input @samp{mega-kludge} the following will write @samp{mega-mega-kludge} to the output: @cindex yymore(), mega-kludge @cindex yymore() to append token to previous token @example @verbatim %% mega- ECHO; yymore(); kludge ECHO; @end verbatim @end example First @samp{mega-} is matched and echoed to the output. Then @samp{kludge} is matched, but the previous @samp{mega-} is still hanging around at the beginning of @code{yytext} so the @code{ECHO} for the @samp{kludge} rule will actually write @samp{mega-kludge}. @end table @cindex yymore, performance penalty of Two notes regarding use of @code{yymore()}. First, @code{yymore()} depends on the value of @code{yyleng} correctly reflecting the size of the current token, so you must not modify @code{yyleng} if you are using @code{yymore()}. Second, the presence of @code{yymore()} in the scanner's action entails a minor performance penalty in the scanner's matching speed. @cindex yyless() @code{yyless(n)} returns all but the first @code{n} characters of the current token back to the input stream, where they will be rescanned when the scanner looks for the next match. @code{yytext} and @code{yyleng} are adjusted appropriately (e.g., @code{yyleng} will now be equal to @code{n}). For example, on the input @samp{foobar} the following will write out @samp{foobarbar}: @cindex yyless(), pushing back characters @cindex pushing back characters with yyless @example @verbatim %% foobar ECHO; yyless(3); [a-z]+ ECHO; @end verbatim @end example An argument of 0 to @code{yyless()} will cause the entire current input string to be scanned again. Unless you've changed how the scanner will subsequently process its input (using @code{BEGIN}, for example), this will result in an endless loop. Note that @code{yyless()} is a macro and can only be used in the flex input file, not from other source files. @cindex unput() @cindex pushing back characters with unput @code{unput(c)} puts the character @code{c} back onto the input stream. It will be the next character scanned. The following action will take the current token and cause it to be rescanned enclosed in parentheses. @cindex unput(), pushing back characters @cindex pushing back characters with unput() @example @verbatim { int i; /* Copy yytext because unput() trashes yytext */ char *yycopy = strdup( yytext ); unput( ')' ); for ( i = yyleng - 1; i >= 0; --i ) unput( yycopy[i] ); unput( '(' ); free( yycopy ); } @end verbatim @end example Note that since each @code{unput()} puts the given character back at the @emph{beginning} of the input stream, pushing back strings must be done back-to-front. @cindex %pointer, and unput() @cindex unput(), and %pointer An important potential problem when using @code{unput()} is that if you are using @code{%pointer} (the default), a call to @code{unput()} @emph{destroys} the contents of @code{yytext}, starting with its rightmost character and devouring one character to the left with each call. If you need the value of @code{yytext} preserved after a call to @code{unput()} (as in the above example), you must either first copy it elsewhere, or build your scanner using @code{%array} instead (@pxref{Matching}). @cindex pushing back EOF @cindex EOF, pushing back Finally, note that you cannot put back @samp{EOF} to attempt to mark the input stream with an end-of-file. @cindex input() @code{input()} reads the next character from the input stream. For example, the following is one way to eat up C comments: @cindex comments, discarding @cindex discarding C comments @example @verbatim %% "/*" { int c; for ( ; ; ) { while ( (c = input()) != '*' && c != EOF ) ; /* eat up text of comment */ if ( c == '*' ) { while ( (c = input()) == '*' ) ; if ( c == '/' ) break; /* found the end */ } if ( c == EOF ) { error( "EOF in comment" ); break; } } } @end verbatim @end example @cindex input(), and C++ @cindex yyinput() (Note that if the scanner is compiled using @code{C++}, then @code{input()} is instead referred to as @b{yyinput()}, in order to avoid a name clash with the @code{C++} stream by the name of @code{input}.) @cindex flushing the internal buffer @cindex YY_FLUSH_BUFFER @code{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 using @code{YY_INPUT()} (@pxref{Generated Scanner}). This action is a special case of the more general @code{yy_flush_buffer;} function, described below (@pxref{Multiple Input Buffers}) @cindex yyterminate() @cindex terminating with yyterminate() @cindex exiting with yyterminate() @cindex halting with yyterminate() @code{yyterminate()} can be used in lieu of a return statement in an action. It terminates the scanner and returns a 0 to the scanner's caller, indicating ``all done''. By default, @code{yyterminate()} is also called when an end-of-file is encountered. It is a macro and may be redefined. @node Generated Scanner, Start Conditions, Actions, Top @chapter The Generated Scanner @cindex yylex(), in generated scanner The output of @code{flex} is the file @file{lex.yy.c}, which contains the scanning routine @code{yylex()}, a number of tables used by it for matching tokens, and a number of auxiliary routines and macros. By default, @code{yylex()} is declared as follows: @example @verbatim int yylex() { ... various definitions and the actions in here ... } @end verbatim @end example @cindex yylex(), overriding (If your environment supports function prototypes, then it will be @code{int yylex( void )}.) This definition may be changed by defining the @code{YY_DECL} macro. For example, you could use: @cindex yylex, overriding the prototype of @example @verbatim #define YY_DECL float lexscan( a, b ) float a, b; @end verbatim @end example to give the scanning routine the name @code{lexscan}, returning a float, and taking two floats as arguments. Note that if you give arguments to the scanning routine using a K&R-style/non-prototyped function declaration, you must terminate the definition with a semi-colon (;). @code{flex} generates @samp{C99} function definitions by default. However flex does have the ability to generate obsolete, er, @samp{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 of @code{flex} may generate standard C99 code only, leaving K&R-style functions to the historians. Currently, if you do @strong{not} want @samp{C99} definitions, then you must use @code{%option noansi-definitions}. @cindex stdin, default for yyin @cindex yyin Whenever @code{yylex()} is called, it scans tokens from the global input file @file{yyin} (which defaults to stdin). It continues until it either reaches an end-of-file (at which point it returns the value 0) or one of its actions executes a @code{return} statement. @cindex EOF and yyrestart() @cindex end-of-file, and yyrestart() @cindex yyrestart() If the scanner reaches an end-of-file, subsequent calls are undefined unless either @file{yyin} is pointed at a new input file (in which case scanning continues from that file), or @code{yyrestart()} is called. @code{yyrestart()} takes one argument, a @code{FILE *} pointer (which can be NULL, if you've set up @code{YY_INPUT} to scan from a source other than @code{yyin}), and initializes @file{yyin} for scanning from that file. Essentially there is no difference between just assigning @file{yyin} to a new input file or using @code{yyrestart()} to do so; the latter is available for compatibility with previous versions of @code{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 @file{yyin}; but it would be better to use @code{YY_FLUSH_BUFFER} (@pxref{Actions}). Note that @code{yyrestart()} does @emph{not} reset the start condition to @code{INITIAL} (@pxref{Start Conditions}). @cindex RETURN, within actions If @code{yylex()} stops scanning due to executing a @code{return} statement in one of the actions, the scanner may then be called again and it will resume scanning where it left off. @cindex YY_INPUT By default (and for purposes of efficiency), the scanner uses block-reads rather than simple @code{getc()} calls to read characters from @file{yyin}. The nature of how it gets its input can be controlled by defining the @code{YY_INPUT} macro. The calling sequence for @code{YY_INPUT()} is @code{YY_INPUT(buf,result,max_size)}. Its action is to place up to @code{max_size} characters in the character array @code{buf} and return in the integer variable @code{result} either the number of characters read or the constant @code{YY_NULL} (0 on Unix systems) to indicate @samp{EOF}. The default @code{YY_INPUT} reads from the global file-pointer @file{yyin}. @cindex YY_INPUT, overriding Here is a sample definition of @code{YY_INPUT} (in the definitions section of the input file): @example @verbatim %{ #define YY_INPUT(buf,result,max_size) \ { \ int c = getchar(); \ result = (c == EOF) ? YY_NULL : (buf[0] = c, 1); \ } %} @end verbatim @end example This definition will change the input processing to occur one character at a time. @cindex yywrap() When the scanner receives an end-of-file indication from YY_INPUT, it then checks the @code{yywrap()} function. If @code{yywrap()} returns false (zero), then it is assumed that the function has gone ahead and set up @file{yyin} to point to another input file, and scanning continues. If it returns true (non-zero), then the scanner terminates, returning 0 to its caller. Note that in either case, the start condition remains unchanged; it does @emph{not} revert to @code{INITIAL}. @cindex yywrap, default for @cindex noyywrap, %option @cindex %option noyywrapp If you do not supply your own version of @code{yywrap()}, then you must either use @code{%option noyywrap} (in which case the scanner behaves as though @code{yywrap()} returned 1), or you must link with @samp{-lfl} to obtain the default version of the routine, which always returns 1. For scanning from in-memory buffers (e.g., scanning strings), see @ref{Scanning Strings}. @xref{Multiple Input Buffers}. @cindex ECHO, and yyout @cindex yyout @cindex stdout, as default for yyout The scanner writes its @code{ECHO} output to the @file{yyout} global (default, @file{stdout}), which may be redefined by the user simply by assigning it to some other @code{FILE} pointer. @node Start Conditions, Multiple Input Buffers, Generated Scanner, Top @chapter Start Conditions @cindex start conditions @code{flex} provides a mechanism for conditionally activating rules. Any rule whose pattern is prefixed with @samp{} will only be active when the scanner is in the @dfn{start condition} named @code{sc}. For example, @example @verbatim [^"]* { /* eat up the string body ... */ ... } @end verbatim @end example will be active only when the scanner is in the @code{STRING} start condition, and @cindex start conditions, multiple @example @verbatim \. { /* handle an escape ... */ ... } @end verbatim @end example will be active only when the current start condition is either @code{INITIAL}, @code{STRING}, or @code{QUOTE}. @cindex start conditions, inclusive v.s.@: exclusive Start conditions are declared in the definitions (first) section of the input using unindented lines beginning with either @samp{%s} or @samp{%x} followed by a list of names. The former declares @dfn{inclusive} start conditions, the latter @dfn{exclusive} start conditions. A start condition is activated using the @code{BEGIN} action. Until the next @code{BEGIN} action is executed, rules with the given start condition will be active and rules with other start conditions will be inactive. If the start condition is inclusive, then rules with no start conditions at all will also be active. If it is exclusive, then @emph{only} rules qualified with the start condition will be active. A set of rules contingent on the same exclusive start condition describe a scanner which is independent of any of the other rules in the @code{flex} input. Because of this, exclusive start conditions make it easy to specify ``mini-scanners'' which scan portions of the input that are syntactically different from the rest (e.g., comments). If the distinction between inclusive and exclusive start conditions is still a little vague, here's a simple example illustrating the connection between the two. The set of rules: @cindex start conditions, inclusive @example @verbatim %s example %% foo do_something(); bar something_else(); @end verbatim @end example is equivalent to @cindex start conditions, exclusive @example @verbatim %x example %% foo do_something(); bar something_else(); @end verbatim @end example Without the @code{} qualifier, the @code{bar} pattern in the second example wouldn't be active (i.e., couldn't match) when in start condition @code{example}. If we just used @code{} to qualify @code{bar}, though, then it would only be active in @code{example} and not in @code{INITIAL}, while in the first example it's active in both, because in the first example the @code{example} start condition is an inclusive @code{(%s)} start condition. @cindex start conditions, special wildcard condition Also note that the special start-condition specifier @code{<*>} matches every start condition. Thus, the above example could also have been written: @cindex start conditions, use of wildcard condition (<*>) @example @verbatim %x example %% foo do_something(); <*>bar something_else(); @end verbatim @end example The default rule (to @code{ECHO} any unmatched character) remains active in start conditions. It is equivalent to: @cindex start conditions, behavior of default rule @example @verbatim <*>.|\n ECHO; @end verbatim @end example @cindex BEGIN, explanation @findex BEGIN @vindex INITIAL @code{BEGIN(0)} returns to the original state where only the rules with no start conditions are active. This state can also be referred to as the start-condition @code{INITIAL}, so @code{BEGIN(INITIAL)} is equivalent to @code{BEGIN(0)}. (The parentheses around the start condition name are not required but are considered good style.) @code{BEGIN} actions can also be given as indented code at the beginning of the rules section. For example, the following will cause the scanner to enter the @code{SPECIAL} start condition whenever @code{yylex()} is called and the global variable @code{enter_special} is true: @cindex start conditions, using BEGIN @example @verbatim int enter_special; %x SPECIAL %% if ( enter_special ) BEGIN(SPECIAL); blahblahblah ...more rules follow... @end verbatim @end example To illustrate the uses of start conditions, here is a scanner which provides two different interpretations of a string like @samp{123.456}. By default it will treat it as three tokens, the integer @samp{123}, a dot (@samp{.}), and the integer @samp{456}. But if the string is preceded earlier in the line by the string @samp{expect-floats} it will treat it as a single token, the floating-point number @samp{123.456}: @cindex start conditions, for different interpretations of same input @example @verbatim %{ #include %} %s expect %% expect-floats BEGIN(expect); [0-9]+.[0-9]+ { printf( "found a float, = %f\n", atof( yytext ) ); } \n { /* that's the end of the line, so * we need another "expect-number" * before we'll recognize any more * numbers */ BEGIN(INITIAL); } [0-9]+ { printf( "found an integer, = %d\n", atoi( yytext ) ); } "." printf( "found a dot\n" ); @end verbatim @end example @cindex comments, example of scanning C comments Here is a scanner which recognizes (and discards) C comments while maintaining a count of the current input line. @cindex recognizing C comments @example @verbatim %x comment %% int line_num = 1; "/*" BEGIN(comment); [^*\n]* /* eat anything that's not a '*' */ "*"+[^*/\n]* /* eat up '*'s not followed by '/'s */ \n ++line_num; "*"+"/" BEGIN(INITIAL); @end verbatim @end example This scanner goes to a bit of trouble to match as much text as possible with each rule. In general, when attempting to write a high-speed scanner try to match as much possible in each rule, as it's a big win. Note that start-conditions names are really integer values and can be stored as such. Thus, the above could be extended in the following fashion: @cindex start conditions, integer values @cindex using integer values of start condition names @example @verbatim %x comment foo %% int line_num = 1; int comment_caller; "/*" { comment_caller = INITIAL; BEGIN(comment); } ... "/*" { comment_caller = foo; BEGIN(comment); } [^*\n]* /* eat anything that's not a '*' */ "*"+[^*/\n]* /* eat up '*'s not followed by '/'s */ \n ++line_num; "*"+"/" BEGIN(comment_caller); @end verbatim @end example @cindex YY_START, example Furthermore, you can access the current start condition using the integer-valued @code{YY_START} macro. For example, the above assignments to @code{comment_caller} could instead be written @cindex getting current start state with YY_START @example @verbatim comment_caller = YY_START; @end verbatim @end example @vindex YY_START Flex provides @code{YYSTATE} as an alias for @code{YY_START} (since that is what's used by AT&T @code{lex}). 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}. 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): @cindex matching C-style double-quoted strings @example @verbatim %x str %% char string_buf[MAX_STR_CONST]; char *string_buf_ptr; \" string_buf_ptr = string_buf; BEGIN(str); \" { /* saw closing quote - all done */ BEGIN(INITIAL); *string_buf_ptr = '\0'; /* return string constant token type and * value to parser */ } \n { /* error - unterminated string constant */ /* generate error message */ } \\[0-7]{1,3} { /* octal escape sequence */ int result; (void) sscanf( yytext + 1, "%o", &result ); if ( result > 0xff ) /* error, constant is out-of-bounds */ *string_buf_ptr++ = result; } \\[0-9]+ { /* generate error - bad escape sequence; something * like '\48' or '\0777777' */ } \\n *string_buf_ptr++ = '\n'; \\t *string_buf_ptr++ = '\t'; \\r *string_buf_ptr++ = '\r'; \\b *string_buf_ptr++ = '\b'; \\f *string_buf_ptr++ = '\f'; \\(.|\n) *string_buf_ptr++ = yytext[1]; [^\\\n\"]+ { char *yptr = yytext; while ( *yptr ) *string_buf_ptr++ = *yptr++; } @end verbatim @end example @cindex start condition, applying to multiple patterns 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 condition @dfn{scope}. A start condition scope is begun with: @example @verbatim { @end verbatim @end example where @code{} is a list of one or more start conditions. Inside the start condition scope, every rule automatically has the prefix @code{} applied to it, until a @samp{@}} which matches the initial @samp{@{}. So, for example, @cindex extended scope of start conditions @example @verbatim { "\\n" return '\n'; "\\r" return '\r'; "\\f" return '\f'; "\\0" return '\0'; } @end verbatim @end example is equivalent to: @example @verbatim "\\n" return '\n'; "\\r" return '\r'; "\\f" return '\f'; "\\0" return '\0'; @end verbatim @end example Start condition scopes may be nested. @cindex stacks, routines for manipulating @cindex start conditions, use of a stack The following routines are available for manipulating stacks of start conditions: @deftypefun void yy_push_state ( int @code{new_state} ) pushes the current start condition onto the top of the start condition stack and switches to @code{new_state} as though you had used @code{BEGIN new_state} (recall that start condition names are also integers). @end deftypefun @deftypefun void yy_pop_state () pops the top of the stack and switches to it via @code{BEGIN}. @end deftypefun @deftypefun int yy_top_state () returns the top of the stack without altering the stack's contents. @end deftypefun @cindex memory, for start condition stacks 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 @code{%option stack} directive (@pxref{Scanner Options}). @node Multiple Input Buffers, EOF, Start Conditions, Top @chapter Multiple Input Buffers @cindex multiple input streams Some scanners (such as those which support ``include'' files) require reading from several input streams. As @code{flex} scanners do a large amount of buffering, one cannot control where the next input will be read from by simply writing a @code{YY_INPUT()} which is sensitive to the scanning context. @code{YY_INPUT()} is only called when the scanner reaches the end of its buffer, which may be a long time after scanning a statement such as an @code{include} statement which requires switching the input source. To negotiate these sorts of problems, @code{flex} provides a mechanism for creating and switching between multiple input buffers. An input buffer is created by using: @cindex memory, allocating input buffers @deftypefun YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size ) @end deftypefun which takes a @code{FILE} pointer and a size and creates a buffer associated with the given file and large enough to hold @code{size} characters (when in doubt, use @code{YY_BUF_SIZE} for the size). It returns a @code{YY_BUFFER_STATE} handle, which may then be passed to other routines (see below). @tindex YY_BUFFER_STATE The @code{YY_BUFFER_STATE} type is a pointer to an opaque @code{struct yy_buffer_state} structure, so you may safely initialize @code{YY_BUFFER_STATE} variables to @code{((YY_BUFFER_STATE) 0)} if you wish, and also refer to the opaque structure in order to correctly declare input buffers in source files other than that of your scanner. Note that the @code{FILE} pointer in the call to @code{yy_create_buffer} is only used as the value of @file{yyin} seen by @code{YY_INPUT}. If you redefine @code{YY_INPUT()} so it no longer uses @file{yyin}, then you can safely pass a NULL @code{FILE} pointer to @code{yy_create_buffer}. You select a particular buffer to scan from using: @deftypefun void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer ) @end deftypefun The above function switches the scanner's input buffer so subsequent tokens will come from @code{new_buffer}. Note that @code{yy_switch_to_buffer()} may be used by @code{yywrap()} to set things up for continued scanning, instead of opening a new file and pointing @file{yyin} at it. If you are looking for a stack of input buffers, then you want to use @code{yypush_buffer_state()} instead of this function. Note also that switching input sources via either @code{yy_switch_to_buffer()} or @code{yywrap()} does @emph{not} change the start condition. @cindex memory, deleting input buffers @deftypefun void yy_delete_buffer ( YY_BUFFER_STATE buffer ) @end deftypefun is used to reclaim the storage associated with a buffer. (@code{buffer} can be NULL, in which case the routine does nothing.) You can also clear the current contents of a buffer using: @cindex pushing an input buffer @cindex stack, input buffer push @deftypefun void yypush_buffer_state ( YY_BUFFER_STATE buffer ) @end deftypefun This function pushes the new buffer state onto an internal stack. The pushed state becomes the new current state. The stack is maintained by flex and will grow as required. This function is intended to be used instead of @code{yy_switch_to_buffer}, when you want to change states, but preserve the current state for later use. @cindex popping an input buffer @cindex stack, input buffer pop @deftypefun void yypop_buffer_state ( ) @end deftypefun This function removes the current state from the top of the stack, and deletes it by calling @code{yy_delete_buffer}. The next state on the stack, if any, becomes the new current state. @cindex clearing an input buffer @cindex flushing an input buffer @deftypefun void yy_flush_buffer ( YY_BUFFER_STATE buffer ) @end deftypefun This function discards the buffer's contents, so the next time the scanner attempts to match a token from the buffer, it will first fill the buffer anew using @code{YY_INPUT()}. @deftypefun YY_BUFFER_STATE yy_new_buffer ( FILE *file, int size ) @end deftypefun is an alias for @code{yy_create_buffer()}, provided for compatibility with the C++ use of @code{new} and @code{delete} for creating and destroying dynamic objects. @cindex YY_CURRENT_BUFFER, and multiple buffers Finally, the macro @code{YY_CURRENT_BUFFER} macro returns a @code{YY_BUFFER_STATE} handle to the current buffer. It should not be used as an lvalue. @cindex EOF, example using multiple input buffers Here are two examples of using these features for writing a scanner which expands include files (the @code{<>} feature is discussed below). This first example uses yypush_buffer_state and yypop_buffer_state. Flex maintains the stack internally. @cindex handling include files with multiple input buffers @example @verbatim /* the "incl" state is used for picking up the name * of an include file */ %x incl %% include BEGIN(incl); [a-z]+ ECHO; [^a-z\n]*\n? ECHO; [ \t]* /* eat the whitespace */ [^ \t\n]+ { /* got the include file name */ yyin = fopen( yytext, "r" ); if ( ! yyin ) error( ... ); yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE )); BEGIN(INITIAL); } <> { yypop_buffer_state(); if ( !YY_CURRENT_BUFFER ) { yyterminate(); } } @end verbatim @end example The second example, below, does the same thing as the previous example did, but manages its own input buffer stack manually (instead of letting flex do it). @cindex handling include files with multiple input buffers @example @verbatim /* the "incl" state is used for picking up the name * of an include file */ %x incl %{ #define MAX_INCLUDE_DEPTH 10 YY_BUFFER_STATE include_stack[MAX_INCLUDE_DEPTH]; int include_stack_ptr = 0; %} %% include BEGIN(incl); [a-z]+ ECHO; [^a-z\n]*\n? ECHO; [ \t]* /* eat the whitespace */ [^ \t\n]+ { /* got the include file name */ if ( include_stack_ptr >= MAX_INCLUDE_DEPTH ) { fprintf( stderr, "Includes nested too deeply" ); exit( 1 ); } include_stack[include_stack_ptr++] = YY_CURRENT_BUFFER; yyin = fopen( yytext, "r" ); if ( ! yyin ) error( ... ); yy_switch_to_buffer( yy_create_buffer( yyin, YY_BUF_SIZE ) ); BEGIN(INITIAL); } <> { if ( --include_stack_ptr 0 ) { yyterminate(); } else { yy_delete_buffer( YY_CURRENT_BUFFER ); yy_switch_to_buffer( include_stack[include_stack_ptr] ); } } @end verbatim @end example @anchor{Scanning Strings} @cindex strings, scanning strings instead of files 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 @code{YY_BUFFER_STATE} handle (which you should delete with @code{yy_delete_buffer()} when done with it). They also switch to the new buffer using @code{yy_switch_to_buffer()}, so the next call to @code{yylex()} will start scanning the string. @deftypefun YY_BUFFER_STATE yy_scan_string ( const char *str ) scans a NUL-terminated string. @end deftypefun @deftypefun YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len ) scans @code{len} bytes (including possibly @code{NUL}s) starting at location @code{bytes}. @end deftypefun Note that both of these functions create and scan a @emph{copy} of the string or bytes. (This may be desirable, since @code{yylex()} modifies the contents of the buffer it is scanning.) You can avoid the copy by using: @vindex YY_END_OF_BUFFER_CHAR @deftypefun YY_BUFFER_STATE yy_scan_buffer (char *base, yy_size_t size) which scans in place the buffer starting at @code{base}, consisting of @code{size} bytes, the last two bytes of which @emph{must} be @code{YY_END_OF_BUFFER_CHAR} (ASCII NUL). These last two bytes are not scanned; thus, scanning consists of @code{base[0]} through @code{base[size-2]}, inclusive. @end deftypefun If you fail to set up @code{base} in this manner (i.e., forget the final two @code{YY_END_OF_BUFFER_CHAR} bytes), then @code{yy_scan_buffer()} returns a NULL pointer instead of creating a new input buffer. @deftp {Data type} yy_size_t is an integral type to which you can cast an integer expression reflecting the size of the buffer. @end deftp @node EOF, Misc Macros, Multiple Input Buffers, Top @chapter End-of-File Rules @cindex EOF, explanation The special rule @code{<>} indicates actions which are to be taken when an end-of-file is encountered and @code{yywrap()} returns non-zero (i.e., indicates no further files to process). The action must finish by doing one of the following things: @itemize @item @findex YY_NEW_FILE (now obsolete) assigning @file{yyin} to a new input file (in previous versions of @code{flex}, after doing the assignment you had to call the special action @code{YY_NEW_FILE}. This is no longer necessary.) @item executing a @code{return} statement; @item executing the special @code{yyterminate()} action. @item or, switching to a new buffer using @code{yy_switch_to_buffer()} as shown in the example above. @end itemize <> rules may not be used with other patterns; they may only be qualified with a list of start conditions. If an unqualified <> rule is given, it applies to @emph{all} start conditions which do not already have <> actions. To specify an <> rule for only the initial start condition, use: @example @verbatim <> @end verbatim @end example These rules are useful for catching things like unclosed comments. An example: @cindex <>, use of @example @verbatim %x quote %% ...other rules for dealing with quotes... <> { error( "unterminated quote" ); yyterminate(); } <> { if ( *++filelist ) yyin = fopen( *filelist, "r" ); else yyterminate(); } @end verbatim @end example @node Misc Macros, User Values, EOF, Top @chapter Miscellaneous Macros @hkindex YY_USER_ACTION The macro @code{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 lower-case. When @code{YY_USER_ACTION} is invoked, the variable @code{yy_act} gives the number of the matched rule (rules are numbered starting with 1). Suppose you want to profile how often each of your rules is matched. The following would do the trick: @cindex YY_USER_ACTION to track each time a rule is matched @example @verbatim #define YY_USER_ACTION ++ctr[yy_act] @end verbatim @end example @vindex YY_NUM_RULES where @code{ctr} is an array to hold the counts for the different rules. Note that the macro @code{YY_NUM_RULES} gives the total number of rules (including the default rule), even if you use @samp{-s)}, so a correct declaration for @code{ctr} is: @example @verbatim int ctr[YY_NUM_RULES]; @end verbatim @end example @hkindex YY_USER_INIT The macro @code{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 call a routine to read in a data table or open a logging file. @findex yy_set_interactive The macro @code{yy_set_interactive(is_interactive)} can be used to control whether the current buffer is considered @dfn{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 @samp{-I} flag in @ref{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 @code{%option always-interactive} or @code{%option never-interactive} (@pxref{Scanner Options}). @code{yy_set_interactive()} must be invoked prior to beginning to scan the buffer that is (or is not) to be considered interactive. @cindex BOL, setting it @findex yy_set_bol The macro @code{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 rules anchored with @samp{^} active, while a zero argument makes @samp{^} rules inactive. @cindex BOL, checking the BOL flag @findex YY_AT_BOL The macro @code{YY_AT_BOL()} returns true if the next token scanned from the current buffer will have @samp{^} rules active, false otherwise. @cindex actions, redefining YY_BREAK @hkindex YY_BREAK In the generated scanner, the actions are all gathered in one large switch statement and separated using @code{YY_BREAK}, which may be redefined. By default, it is simply a @code{break}, to separate each rule's action from the following rule's. Redefining @code{YY_BREAK} allows, for example, C++ users to #define YY_BREAK to do nothing (while being very careful that every rule ends with a @code{break} or a @code{return}!) to avoid suffering from unreachable statement warnings where because a rule's action ends with @code{return}, the @code{YY_BREAK} is inaccessible. @node User Values, Yacc, Misc Macros, Top @chapter Values Available To the User This chapter summarizes the various values available to the user in the rule actions. @table @code @vindex yytext @item char *yytext holds the text of the current token. It may be modified but not lengthened (you cannot append characters to the end). @cindex yytext, default array size @cindex array, default size for yytext @vindex YYLMAX If the special directive @code{%array} appears in the first section of the scanner description, then @code{yytext} is instead declared @code{char yytext[YYLMAX]}, where @code{YYLMAX} is a macro definition that you can redefine in the first section if you don't like the default value (generally 8KB). Using @code{%array} results in somewhat slower scanners, but the value of @code{yytext} becomes immune to calls to @code{unput()}, which potentially destroy its value when @code{yytext} is a character pointer. The opposite of @code{%array} is @code{%pointer}, which is the default. @cindex C++ and %array You cannot use @code{%array} when generating C++ scanner classes (the @samp{-+} flag). @vindex yyleng @item int yyleng holds the length of the current token. @vindex yyin @item FILE *yyin is the file which by default @code{flex} reads from. It may be redefined but doing so only makes sense before scanning begins or after an EOF has been encountered. Changing it in the midst of scanning will have unexpected results since @code{flex} buffers its input; use @code{yyrestart()} instead. Once scanning terminates because an end-of-file has been seen, you can assign @file{yyin} at the new input file and then call the scanner again to continue scanning. @findex yyrestart @item void yyrestart( FILE *new_file ) may be called to point @file{yyin} at the new input file. The switch-over to the new file is immediate (any previously buffered-up input is lost). Note that calling @code{yyrestart()} with @file{yyin} as an argument thus throws away the current input buffer and continues scanning the same input file. @vindex yyout @item FILE *yyout is the file to which @code{ECHO} actions are done. It can be reassigned by the user. @vindex YY_CURRENT_BUFFER @item YY_CURRENT_BUFFER returns a @code{YY_BUFFER_STATE} handle to the current buffer. @vindex YY_START @item YY_START returns an integer value corresponding to the current start condition. You can subsequently use this value with @code{BEGIN} to return to that start condition. @end table @node Yacc, Scanner Options, User Values, Top @chapter Interfacing with Yacc @cindex yacc, interface @vindex yylval, with yacc One of the main uses of @code{flex} is as a companion to the @code{yacc} parser-generator. @code{yacc} parsers expect to call a routine named @code{yylex()} to find the next input token. The routine is supposed to return the type of the next token as well as putting any associated value in the global @code{yylval}. To use @code{flex} with @code{yacc}, one specifies the @samp{-d} option to @code{yacc} to instruct it to generate the file @file{y.tab.h} containing definitions of all the @code{%tokens} appearing in the @code{yacc} input. This file is then included in the @code{flex} scanner. For example, if one of the tokens is @code{TOK_NUMBER}, part of the scanner might look like: @cindex yacc interface @example @verbatim %{ #include "y.tab.h" %} %% [0-9]+ yylval = atoi( yytext ); return TOK_NUMBER; @end verbatim @end example @node Scanner Options, Performance, Yacc, Top @chapter Scanner Options @cindex command-line options @cindex options, command-line @cindex arguments, command-line The various @code{flex} options are categorized by function in the following menu. If you want to lookup a particular option by name, @xref{Index of Scanner Options}. @menu * Options for Specifying Filenames:: * Options Affecting Scanner Behavior:: * Code-Level And API Options:: * Options for Scanner Speed and Size:: * Debugging Options:: * Miscellaneous Options:: @end menu Even though there are many scanner options, a typical scanner might only specify the following options: @example @verbatim %option 8bit reentrant bison-bridge %option warn nodefault %option yylineno %option outfile="scanner.c" header-file="scanner.h" @end verbatim @end example 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 divided them.) @code{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 @code{%option} directives in the first section of the scanner specification. You can specify multiple options with a single @code{%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 @samp{no} (with no intervening whitespace) to negate their meaning. The names are the same as their long-option equivalents (but without the leading @samp{--} ). @code{flex} scans your rule actions to determine whether you use the @code{REJECT} or @code{yymore()} features. The @code{REJECT} and @code{yymore} options are available to override its decision as to whether you use the options, either by setting them (e.g., @code{%option reject)} to indicate the feature is indeed used, or unsetting them to indicate it actually is not used (e.g., @code{%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., @code{%option nounput}), results in the corresponding routine not appearing in the generated scanner: @example @verbatim 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 @end verbatim @end example (though @code{yy_push_state()} and friends won't appear anyway unless you use @code{%option stack)}. @node Options for Specifying Filenames, Options Affecting Scanner Behavior, Scanner Options, Scanner Options @section Options for Specifying Filenames @table @samp @anchor{option-header} @opindex ---header-file @opindex header-file @item --header-file=FILE, @code{%option header-file="FILE"} instructs flex to write a C header to @file{FILE}. This file contains 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 @code{yyIN_HEADER} is defined, where @samp{yy} is substituted with the appropriate prefix. The @samp{--header-file} option is not compatible with the @samp{--c++} option, since the C++ scanner provides its own header in @file{yyFlexLexer.h}. @anchor{option-outfile} @opindex -o @opindex ---outfile @opindex outfile @item -oFILE, --outfile=FILE, @code{%option outfile="FILE"} directs flex to write the scanner to the file @file{FILE} instead of @file{lex.yy.c}. If you combine @samp{--outfile} with the @samp{--stdout} option, then the scanner is written to @file{stdout} but its @code{#line} directives (see the @samp{-l} option above) refer to the file @file{FILE}. @anchor{option-stdout} @opindex -t @opindex ---stdout @opindex stdout @item -t, --stdout, @code{%option stdout} instructs @code{flex} to write the scanner it generates to standard output instead of @file{lex.yy.c}. @opindex ---skel @item -SFILE, --skel=FILE overrides the default skeleton file from which @code{flex} constructs its scanners. You'll never need this option unless you are doing @code{flex} maintenance or development. @opindex ---tables-file @opindex tables-file @item --tables-file=FILE 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}. @opindex ---tables-verify @opindex tables-verify @item --tables-verify 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. @end table @node Options Affecting Scanner Behavior, Code-Level And API Options, Options for Specifying Filenames, Scanner Options @section Options Affecting Scanner Behavior @table @samp @anchor{option-case-insensitive} @opindex -i @opindex ---case-insensitive @opindex case-insensitive @item -i, --case-insensitive, @code{%option case-insensitive} instructs @code{flex} to generate a @dfn{case-insensitive} scanner. The case of letters given in the @code{flex} input patterns will be ignored, and tokens in the input will be matched regardless of case. The matched text given in @code{yytext} will have the preserved case (i.e., it will not be folded). For tricky behavior, see @ref{case and character ranges}. @anchor{option-lex-compat} @opindex -l @opindex ---lex-compat @opindex lex-compat @item -l, --lex-compat, @code{%option lex-compat} turns on maximum compatibility with the original AT&T @code{lex} implementation. Note that this does not mean @emph{full} compatibility. Use of this option costs a considerable amount of performance, and it cannot be used with the @samp{--c++}, @samp{--full}, @samp{--fast}, @samp{-Cf}, or @samp{-CF} options. For details on the compatibilities it provides, see @ref{Lex and Posix}. This option also results in the name @code{YY_FLEX_LEX_COMPAT} being @code{#define}'d in the generated scanner. @anchor{option-batch} @opindex -B @opindex ---batch @opindex batch @item -B, --batch, @code{%option batch} instructs @code{flex} to generate a @dfn{batch} scanner, the opposite of @emph{interactive} scanners generated by @samp{--interactive} (see below). In general, you use @samp{-B} when you are @emph{certain} that your scanner will never be used interactively, and you want to squeeze a @emph{little} more performance out of it. If your goal is instead to squeeze out a @emph{lot} more performance, you should be using the @samp{-Cf} or @samp{-CF} options, which turn on @samp{--batch} automatically anyway. @anchor{option-interactive} @opindex -I @opindex ---interactive @opindex interactive @item -I, --interactive, @code{%option interactive} instructs @code{flex} to generate an @i{interactive} scanner. An interactive scanner is one that only looks ahead to decide what token has been matched if it absolutely must. It turns out that always looking one extra character ahead, even if the scanner has already seen enough text to disambiguate the current token, is a bit faster than only looking ahead when necessary. But scanners that always look ahead give dreadful interactive performance; for example, when a user types a newline, it is not recognized as a newline token until they enter @emph{another} token, which often means typing in another whole line. @code{flex} scanners default to @code{interactive} unless you use the @samp{-Cf} or @samp{-CF} table-compression options (@pxref{Performance}). That's because if you're looking for high-performance you should be using one of these options, so if you didn't, @code{flex} assumes you'd rather trade off a bit of run-time performance for intuitive interactive behavior. Note also that you @emph{cannot} use @samp{--interactive} in conjunction with @samp{-Cf} or @samp{-CF}. Thus, this option is not really needed; it is on by default for all those cases in which it is allowed. You can force a scanner to @emph{not} be interactive by using @samp{--batch} @anchor{option-7bit} @opindex -7 @opindex ---7bit @opindex 7bit @item -7, --7bit, @code{%option 7bit} instructs @code{flex} to generate a 7-bit scanner, i.e., one which can only recognize 7-bit characters in its input. The advantage of using @samp{--7bit} is that the scanner's tables can be up to half the size of those generated using the @samp{--8bit}. The disadvantage is that such scanners often hang or crash if their input contains an 8-bit character. Note, however, that unless you generate your scanner using the @samp{-Cf} or @samp{-CF} table compression options, use of @samp{--7bit} will save only a small amount of table space, and make your scanner considerably less portable. @code{Flex}'s default behavior is to generate an 8-bit scanner unless you use the @samp{-Cf} or @samp{-CF}, in which case @code{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 @samp{--verbose} output as described above. Note that if you use @samp{-Cfe} or @samp{-CFe} @code{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} @opindex -8 @opindex ---8bit @opindex 8bit @item -8, --8bit, @code{%option 8bit} instructs @code{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 @samp{-Cf} or @samp{-CF}, as otherwise flex defaults to generating an 8-bit scanner anyway. See the discussion of @samp{--7bit} above for @code{flex}'s default behavior and the tradeoffs between 7-bit and 8-bit scanners. @anchor{option-default} @opindex ---default @opindex default @item --default, @code{%option default} generate the default rule. @anchor{option-always-interactive} @opindex ---always-interactive @opindex always-interactive @item --always-interactive, @code{%option always-interactive} instructs flex to generate a scanner which always considers its input @emph{interactive}. Normally, on each new input file the scanner calls @code{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. @opindex ---never-interactive @item --never-interactive, @code{--never-interactive} instructs flex to generate a scanner which never considers its input interactive. This is the opposite of @code{always-interactive}. @anchor{option-posix} @opindex -X @opindex ---posix @opindex posix @item -X, --posix, @code{%option posix} turns on maximum compatibility with the POSIX 1003.2-1992 definition of @code{lex}. Since @code{flex} was originally designed to implement the POSIX definition of @code{lex} this generally involves very few changes in behavior. At the current writing the known differences between @code{flex} and the POSIX standard are: @itemize @item In POSIX and AT&T @code{lex}, the repeat operator, @samp{@{@}}, has lower precedence than concatenation (thus @samp{ab@{3@}} yields @samp{ababab}). Most POSIX utilities use an Extended Regular Expression (ERE) precedence that has the precedence of the repeat operator higher than concatenation (which causes @samp{ab@{3@}} to yield @samp{abbb}). By default, @code{flex} places the precedence of the repeat operator higher than concatenation which matches the ERE processing of other POSIX utilities. When either @samp{--posix} or @samp{-l} are specified, @code{flex} will use the traditional AT&T and POSIX-compliant precedence for the repeat operator where concatenation has higher precedence than the repeat operator. @end itemize @anchor{option-stack} @opindex ---stack @opindex stack @item --stack, @code{%option stack} enables the use of start condition stacks (@pxref{Start Conditions}). @anchor{option-stdinit} @opindex ---stdinit @opindex stdinit @item --stdinit, @code{%option stdinit} if set (i.e., @b{%option stdinit)} initializes @code{yyin} and @code{yyout} to @file{stdin} and @file{stdout}, instead of the default of @file{NULL}. Some existing @code{lex} programs depend on this behavior, even though it is not compliant with ANSI C, which does not require @file{stdin} and @file{stdout} to be compile-time constant. In a reentrant scanner, however, this is not a problem since initialization is performed in @code{yylex_init} at runtime. @anchor{option-yylineno} @opindex ---yylineno @opindex yylineno @item --yylineno, @code{%option yylineno} directs @code{flex} to generate a scanner that maintains the number of the current line read from its input in the global variable @code{yylineno}. This option is implied by @code{%option lex-compat}. In a reentrant C scanner, the macro @code{yylineno} is accessible regardless of the value of @code{%option yylineno}, however, its value is not modified by @code{flex} unless @code{%option yylineno} is enabled. @anchor{option-yywrap} @opindex ---yywrap @opindex yywrap @item --yywrap, @code{%option yywrap} if unset (i.e., @code{--noyywrap)}, makes the scanner not call @code{yywrap()} upon an end-of-file, but simply assume that there are no more files to scan (until the user points @file{yyin} at a new file and calls @code{yylex()} again). @end table @node Code-Level And API Options, Options for Scanner Speed and Size, Options Affecting Scanner Behavior, Scanner Options @section Code-Level And API Options @table @samp @anchor{option-ansi-definitions} @opindex ---option-ansi-definitions @opindex ansi-definitions @item --ansi-definitions, @code{%option ansi-definitions} instruct flex to generate ANSI C99 definitions for functions. This option is enabled by default. If @code{%option noansi-definitions} is specified, then the obsolete style is generated. @anchor{option-ansi-prototypes} @opindex ---option-ansi-prototypes @opindex ansi-prototypes @item --ansi-prototypes, @code{%option ansi-prototypes} instructs flex to generate ANSI C99 prototypes for functions. This option is enabled by default. If @code{noansi-prototypes} is specified, then prototypes will have empty parameter lists. @anchor{option-bison-bridge} @opindex ---bison-bridge @opindex bison-bridge @item --bison-bridge, @code{%option bison-bridge} instructs flex to generate a C scanner that is meant to be called by a @code{GNU bison} parser. The scanner has minor API changes for @code{bison} compatibility. In particular, the declaration of @code{yylex} is modified to take an additional parameter, @code{yylval}. @xref{Bison Bridge}. @anchor{option-bison-locations} @opindex ---bison-locations @opindex bison-locations @item --bison-locations, @code{%option bison-locations} instruct flex that @code{GNU bison} @code{%locations} are being used. This means @code{yylex} will be passed an additional parameter, @code{yylloc}. This option implies @code{%option bison-bridge}. @xref{Bison Bridge}. @anchor{option-noline} @opindex -L @opindex ---noline @opindex noline @item -L, --noline, @code{%option noline} instructs @code{flex} not to generate @code{#line} directives. Without this option, @code{flex} peppers the generated scanner with @code{#line} directives so error messages in the actions will be correctly located with respect to either the original @code{flex} input file (if the errors are due to code in the input file), or @file{lex.yy.c} (if the errors are @code{flex}'s fault -- you should report these sorts of errors to the email address given in @ref{Reporting Bugs}). @anchor{option-reentrant} @opindex -R @opindex ---reentrant @opindex reentrant @item -R, --reentrant, @code{%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 @pxref{Reentrant}). Because of the API difference between reentrant and non-reentrant @code{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 @samp{--c++} option. The option @samp{--reentrant} does not affect the performance of the scanner. @anchor{option-c++} @opindex -+ @opindex ---c++ @opindex c++ @item -+, --c++, @code{%option c++} specifies that you want flex to generate a C++ scanner class. @xref{Cxx}, for details. @anchor{option-array} @opindex ---array @opindex array @item --array, @code{%option array} specifies that you want yytext to be an array instead of a char* @anchor{option-pointer} @opindex ---pointer @opindex pointer @item --pointer, @code{%option pointer} specify that @code{yytext} should be a @code{char *}, not an array. This default is @code{char *}. @anchor{option-prefix} @opindex -P @opindex ---prefix @opindex prefix @item -PPREFIX, --prefix=PREFIX, @code{%option prefix="PREFIX"} changes the default @samp{yy} prefix used by @code{flex} for all globally-visible variable and function names to instead be @samp{PREFIX}. For example, @samp{--prefix=foo} changes the name of @code{yytext} to @code{footext}. It also changes the name of the default output file from @file{lex.yy.c} to @file{lex.foo.c}. Here is a partial list of the names affected: @example @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 @end verbatim @end example (If you are using a C++ scanner, then only @code{yywrap} and @code{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 @code{flex} programs into the same executable. Note, though, that using this option also renames @code{yywrap()}, so you now @emph{must} either provide your own (appropriately-named) version of the routine for your scanner, or use @code{%option noyywrap}, as linking with @samp{-lfl} no longer provides one for you by default. @anchor{option-main} @opindex ---main @opindex main @item --main, @code{%option main} directs flex to provide a default @code{main()} program for the scanner, which simply calls @code{yylex()}. This option implies @code{noyywrap} (see below). @anchor{option-nounistd} @opindex ---nounistd @opindex nounistd @item --nounistd, @code{%option nounistd} suppresses inclusion of the non-ANSI header file @file{unistd.h}. This option is meant to target environments in which @file{unistd.h} does not exist. Be aware that certain options may cause flex to generate code that relies on functions normally found in @file{unistd.h}, (e.g. @code{isatty()}, @code{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} @opindex ---yyclass @opindex yyclass @item --yyclass=NAME, @code{%option yyclass="NAME"} only applies when generating a C++ scanner (the @samp{--c++} option). It informs @code{flex} that you have derived @code{NAME} as a subclass of @code{yyFlexLexer}, so @code{flex} will place your actions in the member function @code{foo::yylex()} instead of @code{yyFlexLexer::yylex()}. It also generates a @code{yyFlexLexer::yylex()} member function that emits a run-time error (by invoking @code{yyFlexLexer::LexerError())} if called. @xref{Cxx}. @end table @node Options for Scanner Speed and Size, Debugging Options, Code-Level And API Options, Scanner Options @section Options for Scanner Speed and Size @table @samp @item -C[aefFmr] controls the degree of table compression and, more generally, trade-offs between small scanners and fast scanners. @table @samp @opindex -C @item -C A lone @samp{-C} specifies that the scanner tables should be compressed but neither equivalence classes nor meta-equivalence classes should be used. @anchor{option-align} @opindex -Ca @opindex ---align @opindex align @item -Ca, --align, @code{%option align} (``align'') instructs flex to trade off larger tables in the generated scanner for faster performance because the elements of the tables are better aligned for memory access and computation. On some RISC architectures, fetching and manipulating longwords is more efficient than with smaller-sized units such as shortwords. This option can quadruple the size of the tables used by your scanner. @anchor{option-ecs} @opindex -Ce @opindex ---ecs @opindex ecs @item -Ce, --ecs, @code{%option ecs} directs @code{flex} to construct @dfn{equivalence classes}, i.e., sets of characters which have identical lexical properties (for example, if the only appearance of digits in the @code{flex} input is in the character class ``[0-9]'' then the digits '0', '1', ..., '9' will all be put in the same equivalence class). Equivalence classes usually give dramatic reductions in the final table/object file sizes (typically a factor of 2-5) and are pretty cheap performance-wise (one array look-up per character scanned). @opindex -Cf @item -Cf specifies that the @dfn{full} scanner tables should be generated - @code{flex} should not compress the tables by taking advantages of similar transition functions for different states. @opindex -CF @item -CF specifies that the alternate fast scanner representation (described above under the @samp{--fast} flag) should be used. This option cannot be used with @samp{--c++}. @anchor{option-meta-ecs} @opindex -Cm @opindex ---meta-ecs @opindex meta-ecs @item -Cm, --meta-ecs, @code{%option meta-ecs} directs @code{flex} to construct @dfn{meta-equivalence classes}, which are sets of equivalence classes (or characters, if equivalence classes are not being used) that are commonly used together. Meta-equivalence classes are often a big win when using compressed tables, but they have a moderate performance impact (one or two @code{if} tests and one array look-up per character scanned). @anchor{option-read} @opindex -Cr @opindex ---read @opindex read @item -Cr, --read, @code{%option read} causes the generated scanner to @emph{bypass} use of the standard I/O library (@code{stdio}) for input. Instead of calling @code{fread()} or @code{getc()}, the scanner will use the @code{read()} system call, resulting in a performance gain which varies from system to system, but in general is probably negligible unless you are also using @samp{-Cf} or @samp{-CF}. Using @samp{-Cr} can cause strange behavior if, for example, you read from @file{yyin} using @code{stdio} prior to calling the scanner (because the scanner will miss whatever text your previous reads left in the @code{stdio} input buffer). @samp{-Cr} has no effect if you define @code{YY_INPUT()} (@pxref{Generated Scanner}). @end table The options @samp{-Cf} or @samp{-CF} and @samp{-Cm} do not make sense together - there is no opportunity for meta-equivalence classes if the table is not being compressed. Otherwise the options may be freely mixed, and are cumulative. The default setting is @samp{-Cem}, which specifies that @code{flex} should generate equivalence classes and meta-equivalence classes. This setting provides the highest degree of table compression. You can trade off faster-executing scanners at the cost of larger tables with the following generally being true: @example @verbatim slowest & smallest -Cem -Cm -Ce -C -C{f,F}e -C{f,F} -C{f,F}a fastest & largest @end verbatim @end example Note that scanners with the smallest tables are usually generated and compiled the quickest, so during development you will usually want to use the default, maximal compression. @samp{-Cfe} is often a good compromise between speed and size for production scanners. @anchor{option-full} @opindex -f @opindex ---full @opindex full @item -f, --full, @code{%option full} specifies @dfn{fast scanner}. No table compression is done and @code{stdio} is bypassed. The result is large but fast. This option is equivalent to @samp{--Cfr} @anchor{option-fast} @opindex -F @opindex ---fast @opindex fast @item -F, --fast, @code{%option fast} specifies that the @emph{fast} scanner table representation should be used (and @code{stdio} bypassed). This representation is about as fast as the full table representation @samp{--full}, and for some sets of patterns will be considerably smaller (and for others, larger). In general, if the pattern set contains both @emph{keywords} and a catch-all, @emph{identifier} rule, such as in the set: @example @verbatim "case" return TOK_CASE; "switch" return TOK_SWITCH; ... "default" return TOK_DEFAULT; [a-z]+ return TOK_ID; @end verbatim @end example then you're better off using the full table representation. If only the @emph{identifier} rule is present and you then use a hash table or some such to detect the keywords, you're better off using @samp{--fast}. This option is equivalent to @samp{-CFr}. It cannot be used with @samp{--c++}. @end table @node Debugging Options, Miscellaneous Options, Options for Scanner Speed and Size, Scanner Options @section Debugging Options @table @samp @anchor{option-backup} @opindex -b @opindex ---backup @opindex backup @item -b, --backup, @code{%option backup} Generate backing-up information to @file{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 @emph{all} backing-up states are eliminated and @samp{-Cf} or @code{-CF} is used, the generated scanner will run faster (see the @samp{--perf-report} flag). Only users who wish to squeeze every last cycle out of their scanners need worry about this option. (@pxref{Performance}). @anchor{option-debug} @opindex -d @opindex ---debug @opindex debug @item -d, --debug, @code{%option debug} makes the generated scanner run in @dfn{debug} mode. Whenever a pattern is recognized and the global variable @code{yy_flex_debug} is non-zero (which is the default), the scanner will write to @file{stderr} a line of the form: @example @verbatim -accepting rule at line 53 ("the matched text") @end verbatim @end example 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} @opindex -p @opindex ---perf-report @opindex perf-report @item -p, --perf-report, @code{%option perf-report} generates a performance report to @file{stderr}. The report consists of comments regarding features of the @code{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 @code{REJECT}, and variable trailing context (@pxref{Limitations}) entails a substantial performance penalty; use of @code{yymore()}, the @samp{^} operator, and the @samp{--interactive} flag entail minor performance penalties. @anchor{option-nodefault} @opindex -s @opindex ---nodefault @opindex nodefault @item -s, --nodefault, @code{%option nodefault} causes the @emph{default rule} (that unmatched scanner input is echoed to @file{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} @opindex -T @opindex ---trace @opindex trace @item -T, --trace, @code{%option trace} makes @code{flex} run in @dfn{trace} mode. It will generate a lot of messages to @file{stderr} concerning the form of the input and the resultant non-deterministic and deterministic finite automata. This option is mostly for use in maintaining @code{flex}. @anchor{option-nowarn} @opindex -w @opindex ---nowarn @opindex nowarn @item -w, --nowarn, @code{%option nowarn} suppresses warning messages. @anchor{option-verbose} @opindex -v @opindex ---verbose @opindex verbose @item -v, --verbose, @code{%option verbose} specifies that @code{flex} should write to @file{stderr} a summary of statistics regarding the scanner it generates. Most of the statistics are meaningless to the casual @code{flex} user, but the first line identifies the version of @code{flex} (same as reported by @samp{--version}), and the next line the flags used when generating the scanner, including those that are on by default. @anchor{option-warn} @opindex ---warn @opindex warn @item --warn, @code{%option warn} warn about certain things. In particular, if the default rule can be matched but no default rule has been given, the flex will warn you. We recommend using this option always. @end table @node Miscellaneous Options, , Debugging Options, Scanner Options @section Miscellaneous Options @table @samp @opindex -c @item -c A do-nothing option included for POSIX compliance. @opindex -h @opindex ---help @item -h, -?, --help generates a ``help'' summary of @code{flex}'s options to @file{stdout} and then exits. @opindex -n @item -n Another do-nothing option included for POSIX compliance. @opindex -V @opindex ---version @item -V, --version prints the version number to @file{stdout} and exits. @end table @node Performance, Cxx, Scanner Options, Top @chapter Performance Considerations @cindex performance, considerations The main design goal of @code{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 @samp{-C} options outlined above, there are a number of options/actions which degrade performance. These are, from most expensive to least: @cindex REJECT, performance costs @cindex yylineno, performance costs @cindex trailing context, performance costs @example @verbatim REJECT arbitrary trailing context pattern sets that require backing up %option yylineno %array %option interactive %option always-interactive ^ beginning-of-line operator yymore() @end verbatim @end example with the first two all being quite expensive and the last two being quite cheap. Note also that @code{unput()} is implemented as a routine call that potentially does quite a bit of work, while @code{yyless()} is a quite-cheap macro. So if you are just putting back some excess text you scanned, use @code{yyless()}. @code{REJECT} should be avoided at all costs when performance is important. It is a particularly expensive option. There is one case when @code{%option yylineno} can be expensive. That is when your patterns match long tokens that could @emph{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 @code{[^f]+}, which match very long tokens, including newlines, and may possibly match your entire file! A better approach is to separate @code{[^f]+} into two rules: @example @verbatim %option yylineno %% [^f\n]+ \n+ @end verbatim @end example The above scanner does not incur a performance penalty. @cindex patterns, tuning for performance @cindex performance, backing up @cindex backing up, example of eliminating 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 @samp{-b} flag to generate a @file{lex.backup} file. For example, on the input: @cindex backing up, eliminating @example @verbatim %% foo return TOK_KEYWORD; foobar return TOK_KEYWORD; @end verbatim @end example the file looks like: @example @verbatim State #6 is non-accepting - associated rule line numbers: 2 3 out-transitions: [ o ] jam-transitions: EOF [ \001-n p-\177 ] State #8 is non-accepting - associated rule line numbers: 3 out-transitions: [ a ] jam-transitions: EOF [ \001-` b-\177 ] State #9 is non-accepting - associated rule line numbers: 3 out-transitions: [ r ] jam-transitions: EOF [ \001-q s-\177 ] Compressed tables always back up. @end verbatim @end example The first few lines tell us that there's a scanner state in which it can make a transition on an 'o' but not on any other character, and that in that state the currently scanned text does not match any rule. The state occurs when trying to match the rules found at lines 2 and 3 in the input file. If the scanner is in that state and then reads something other than an 'o', it will have to back up to find a rule which is matched. With a bit of headscratching one can see that this must be the state it's in when it has seen @samp{fo}. When this has happened, if anything other than another @samp{o} is seen, the scanner will have to back up to simply match the @samp{f} (by the default rule). The comment regarding State #8 indicates there's a problem when @samp{foob} has been scanned. Indeed, on any character other than an @samp{a}, the scanner will have to back up to accept "foo". Similarly, the comment for State #9 concerns when @samp{fooba} has been scanned and an @samp{r} does not follow. The final comment reminds us that there's no point going to all the trouble of removing backing up from the rules unless we're using @samp{-Cf} or @samp{-CF}, since there's no performance gain doing so with compressed scanners. @cindex error rules, to eliminate backing up The way to remove the backing up is to add ``error'' rules: @cindex backing up, eliminating by adding error rules @example @verbatim %% foo return TOK_KEYWORD; foobar return TOK_KEYWORD; fooba | foob | fo { /* false alarm, not really a keyword */ return TOK_ID; } @end verbatim @end example Eliminating backing up among a list of keywords can also be done using a ``catch-all'' rule: @cindex backing up, eliminating with catch-all rule @example @verbatim %% foo return TOK_KEYWORD; foobar return TOK_KEYWORD; [a-z]+ return TOK_ID; @end verbatim @end example This is usually the best solution when appropriate. Backing up messages tend to cascade. With a complicated set of rules it's not uncommon to get hundreds of messages. If one can decipher them, though, it often only takes a dozen or so rules to eliminate the backing up (though it's easy to make a mistake and have an error rule accidentally match a valid token. A possible future @code{flex} feature will be to automatically add rules to eliminate backing up). It's important to keep in mind that you gain the benefits of eliminating backing up only if you eliminate @emph{every} instance of backing up. Leaving just one means you gain nothing. @emph{Variable} trailing context (where both the leading and trailing parts do not have a fixed length) entails almost the same performance loss as @code{REJECT} (i.e., substantial). So when possible a rule like: @cindex trailing context, variable length @example @verbatim %% mouse|rat/(cat|dog) run(); @end verbatim @end example is better written: @example @verbatim %% mouse/cat|dog run(); rat/cat|dog run(); @end verbatim @end example or as @example @verbatim %% mouse|rat/cat run(); mouse|rat/dog run(); @end verbatim @end example Note that here the special '|' action does @emph{not} provide any savings, and can even make things worse (@pxref{Limitations}). Another area where the user can increase a scanner's performance (and one that's easier to implement) arises from the fact that the longer the tokens matched, the faster the scanner will run. This is because with long tokens the processing of most input characters takes place in the (short) inner scanning loop, and does not often have to go through the additional work of setting up the scanning environment (e.g., @code{yytext}) for the action. Recall the scanner for C comments: @cindex performance optimization, matching longer tokens @example @verbatim %x comment %% int line_num = 1; "/*" BEGIN(comment); [^*\n]* "*"+[^*/\n]* \n ++line_num; "*"+"/" BEGIN(INITIAL); @end verbatim @end example This could be sped up by writing it as: @example @verbatim %x comment %% int line_num = 1; "/*" BEGIN(comment); [^*\n]* [^*\n]*\n ++line_num; "*"+[^*/\n]* "*"+[^*/\n]*\n ++line_num; "*"+"/" BEGIN(INITIAL); @end verbatim @end example Now instead of each newline requiring the processing of another action, recognizing the newlines is distributed over the other rules to keep the matched text as long as possible. Note that @emph{adding} rules does @emph{not} slow down the scanner! The speed of the scanner is independent of the number of rules or (modulo the considerations given at the beginning of this section) how complicated the rules are with regard to operators such as @samp{*} and @samp{|}. @cindex keywords, for performance @cindex performance, using keywords A final example in speeding up a scanner: suppose you want to scan through a file containing identifiers and keywords, one per line and with no other extraneous characters, and recognize all the keywords. A natural first approach is: @cindex performance optimization, recognizing keywords @example @verbatim %% asm | auto | break | ... etc ... volatile | while /* it's a keyword */ .|\n /* it's not a keyword */ @end verbatim @end example To eliminate the back-tracking, introduce a catch-all rule: @example @verbatim %% asm | auto | break | ... etc ... volatile | while /* it's a keyword */ [a-z]+ | .|\n /* it's not a keyword */ @end verbatim @end example Now, if it's guaranteed that there's exactly one word per line, then we can reduce the total number of matches by a half by merging in the recognition of newlines with that of the other tokens: @example @verbatim %% asm\n | auto\n | break\n | ... etc ... volatile\n | while\n /* it's a keyword */ [a-z]+\n | .|\n /* it's not a keyword */ @end verbatim @end example One has to be careful here, as we have now reintroduced backing up into the scanner. In particular, while @emph{we} know that there will never be any characters in the input stream other than letters or newlines, @code{flex} can't figure this out, and it will plan for possibly needing to back up when it has scanned a token like @samp{auto} and then the next character is something other than a newline or a letter. Previously it would then just match the @samp{auto} rule and be done, but now it has no @samp{auto} rule, only a @samp{auto\n} rule. To eliminate the possibility of backing up, we could either duplicate all rules but without final newlines, or, since we never expect to encounter such an input and therefore don't how it's classified, we can introduce one more catch-all rule, this one which doesn't include a newline: @example @verbatim %% asm\n | auto\n | break\n | ... etc ... volatile\n | while\n /* it's a keyword */ [a-z]+\n | [a-z]+ | .|\n /* it's not a keyword */ @end verbatim @end example Compiled with @samp{-Cf}, this is about as fast as one can get a @code{flex} scanner to go for this particular problem. A final note: @code{flex} is slow when matching @code{NUL}s, particularly when a token contains multiple @code{NUL}s. It's best to write rules which match @emph{short} amounts of text if it's anticipated that the text will often include @code{NUL}s. Another final note regarding performance: as mentioned in @ref{Matching}, dynamically resizing @code{yytext} 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 ``huge'' quantities, where the cutoff between the two is at about 8K characters per token. @node Cxx, Reentrant, Performance, Top @chapter Generating C++ Scanners @cindex c++, experimental form of scanner class @cindex experimental form of c++ scanner class @strong{IMPORTANT}: the present form of the scanning class is @emph{experimental} and may change considerably between major releases. @cindex C++ @cindex member functions, C++ @cindex methods, c++ @code{flex} provides two different ways to generate scanners for use with C++. The first way is to simply compile a scanner generated by @code{flex} using a C++ compiler instead of a C compiler. You should not encounter any compilation errors (@pxref{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 @file{yyin}, and default echoing is still done to @file{yyout}. Both of these remain @code{FILE *} variables and not C++ @emph{streams}. You can also use @code{flex} to generate a C++ scanner class, using the @samp{-+} option (or, equivalently, @code{%option c++)}, which is automatically specified if the name of the @code{flex} executable ends in a '+', such as @code{flex++}. When using this option, @code{flex} defaults to generating the scanner to the file @file{lex.yy.cc} instead of @file{lex.yy.c}. The generated scanner includes the header file @file{FlexLexer.h}, which defines the interface to two C++ classes. The first class in @file{FlexLexer.h}, @code{FlexLexer}, provides an abstract base class defining the general scanner class interface. It provides the following member functions: @table @code @findex YYText (C++ only) @item const char* YYText() returns the text of the most recently matched token, the equivalent of @code{yytext}. @findex YYLeng (C++ only) @item int YYLeng() returns the length of the most recently matched token, the equivalent of @code{yyleng}. @findex lineno (C++ only) @item int lineno() const returns the current input line number (see @code{%option yylineno)}, or @code{1} if @code{%option yylineno} was not used. @findex set_debug (C++ only) @item void set_debug( int flag ) sets the debugging flag for the scanner, equivalent to assigning to @code{yy_flex_debug} (@pxref{Scanner Options}). Note that you must build the scanner using @code{%option debug} to include debugging information in it. @findex debug (C++ only) @item int debug() const returns the current setting of the debugging flag. @end table Also provided are member functions equivalent to @code{yy_switch_to_buffer()}, @code{yy_create_buffer()} (though the first argument is an @code{istream&} object reference and not a @code{FILE*)}, @code{yy_flush_buffer()}, @code{yy_delete_buffer()}, and @code{yyrestart()} (again, the first argument is a @code{istream&} object reference). @tindex yyFlexLexer (C++ only) @tindex FlexLexer (C++ only) The second class defined in @file{FlexLexer.h} is @code{yyFlexLexer}, which is derived from @code{FlexLexer}. It defines the following additional member functions: @table @code @findex yyFlexLexer constructor (C++ only) @item yyFlexLexer( istream* arg_yyin = 0, ostream* arg_yyout = 0 ) @item yyFlexLexer( istream& arg_yyin, ostream& arg_yyout ) constructs a @code{yyFlexLexer} object using the given streams for input and output. If not specified, the streams default to @code{cin} and @code{cout}, respectively. @code{yyFlexLexer} does not take ownership of its stream arguments. It's up to the user to ensure the streams pointed to remain alive at least as long as the @code{yyFlexLexer} instance. @findex yylex (C++ version) @item virtual int yylex() performs the same role is @code{yylex()} does for ordinary @code{flex} scanners: it scans the input stream, consuming tokens, until a rule's action returns a value. If you derive a subclass @code{S} from @code{yyFlexLexer} and want to access the member functions and variables of @code{S} inside @code{yylex()}, then you need to use @code{%option yyclass="S"} to inform @code{flex} that you will be using that subclass instead of @code{yyFlexLexer}. In this case, rather than generating @code{yyFlexLexer::yylex()}, @code{flex} generates @code{S::yylex()} (and also generates a dummy @code{yyFlexLexer::yylex()} that calls @code{yyFlexLexer::LexerError()} if called). @findex switch_streams (C++ only) @item virtual void switch_streams(istream* new_in = 0, ostream* new_out = 0) @item virtual void switch_streams(istream& new_in, ostream& new_out) reassigns @code{yyin} to @code{new_in} (if non-null) and @code{yyout} to @code{new_out} (if non-null), deleting the previous input buffer if @code{yyin} is reassigned. @item int yylex( istream* new_in, ostream* new_out = 0 ) @item int yylex( istream& new_in, ostream& new_out ) first switches the input streams via @code{switch_streams( new_in, new_out )} and then returns the value of @code{yylex()}. @end table In addition, @code{yyFlexLexer} defines the following protected virtual functions which you can redefine in derived classes to tailor the scanner: @table @code @findex LexerInput (C++ only) @item virtual int LexerInput( char* buf, int max_size ) reads up to @code{max_size} characters into @code{buf} and returns the number of characters read. To indicate end-of-input, return 0 characters. Note that @code{interactive} scanners (see the @samp{-B} and @samp{-I} flags in @ref{Scanner Options}) define the macro @code{YY_INTERACTIVE}. If you redefine @code{LexerInput()} 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 @code{#ifdef} statements. @findex LexerOutput (C++ only) @item virtual void LexerOutput( const char* buf, int size ) writes out @code{size} characters from the buffer @code{buf}, which, while @code{NUL}-terminated, may also contain internal @code{NUL}s if the scanner's rules can match text with @code{NUL}s in them. @cindex error reporting, in C++ @findex LexerError (C++ only) @item virtual void LexerError( const char* msg ) reports a fatal error message. The default version of this function writes the message to the stream @code{cerr} and exits. @end table Note that a @code{yyFlexLexer} object contains its @emph{entire} scanning state. Thus you can use such objects to create reentrant scanners, but see also @ref{Reentrant}. You can instantiate multiple instances of the same @code{yyFlexLexer} class, and you can also combine multiple C++ scanner classes together in the same program using the @samp{-P} option discussed above. Finally, note that the @code{%array} feature is not available to C++ scanner classes; you must use @code{%pointer} (the default). Here is an example of a simple C++ scanner: @cindex C++ scanners, use of @example @verbatim // An example of using the flex C++ scanner class. %{ #include using namespace std; int mylineno = 0; %} %option noyywrap c++ string \"[^\n"]+\" ws [ \t]+ alpha [A-Za-z] dig [0-9] name ({alpha}|{dig}|\$)({alpha}|{dig}|[_.\-/$])* num1 [-+]?{dig}+\.?([eE][-+]?{dig}+)? num2 [-+]?{dig}*\.{dig}+([eE][-+]?{dig}+)? number {num1}|{num2} %% {ws} /* skip blanks and tabs */ "/*" { int c; while((c = yyinput()) != 0) { if(c == '\n') ++mylineno; else if(c == '*') { if((c = yyinput()) == '/') break; else unput(c); } } } {number} cout << "number " << YYText() << '\n'; \n mylineno++; {name} cout << "name " << YYText() << '\n'; {string} cout << "string " << YYText() << '\n'; %% // This include is required if main() is an another source file. //#include int main( int /* argc */, char** /* argv */ ) { FlexLexer* lexer = new yyFlexLexer; while(lexer->yylex() != 0) ; return 0; } @end verbatim @end example @cindex C++, multiple different scanners If you want to create multiple (different) lexer classes, you use the @samp{-P} flag (or the @code{prefix=} option) to rename each @code{yyFlexLexer} to some other @samp{xxFlexLexer}. You then can include @file{} in your other sources once per lexer class, first renaming @code{yyFlexLexer} as follows: @cindex include files, with C++ @cindex header files, with C++ @cindex C++ scanners, including multiple scanners @example @verbatim #undef yyFlexLexer #define yyFlexLexer xxFlexLexer #include #undef yyFlexLexer #define yyFlexLexer zzFlexLexer #include @end verbatim @end example if, for example, you used @code{%option prefix="xx"} for one of your scanners and @code{%option prefix="zz"} for the other. @node Reentrant, Lex and Posix, Cxx, Top @chapter Reentrant C Scanners @cindex reentrant, explanation @code{flex} has the ability to generate a reentrant C scanner. This is accomplished by specifying @code{%option reentrant} (@samp{-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 reentrant @code{flex} scanner without the need for synchronization with other threads. @menu * Reentrant Uses:: * Reentrant Overview:: * Reentrant Example:: * Reentrant Detail:: * Reentrant Functions:: @end menu @node Reentrant Uses, Reentrant Overview, Reentrant, Reentrant @section Uses for Reentrant Scanners However, there are other uses for a reentrant scanner. For example, you could scan two or more files simultaneously to implement a @code{diff} at the token level (i.e., instead of at the character level): @cindex reentrant scanners, multiple interleaved scanners @example @verbatim /* Example of maintaining more than one active scanner. */ do { int tok1, tok2; tok1 = yylex( scanner_1 ); tok2 = yylex( scanner_2 ); if( tok1 != tok2 ) printf("Files are different."); } while ( tok1 && tok2 ); @end verbatim @end example 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. @xref{Multiple Input Buffers}.) The following crude scanner supports the @samp{eval} command by invoking another instance of itself. @cindex reentrant scanners, recursive invocation @example @verbatim /* Example of recursive invocation. */ %option reentrant %% "eval(".+")" { yyscan_t scanner; YY_BUFFER_STATE buf; yylex_init( &scanner ); yytext[yyleng-1] = ' '; buf = yy_scan_string( yytext + 5, scanner ); yylex( scanner ); yy_delete_buffer(buf,scanner); yylex_destroy( scanner ); } ... %% @end verbatim @end example @node Reentrant Overview, Reentrant Example, Reentrant Uses, Reentrant @section An Overview of the Reentrant API @cindex reentrant, API explanation The API for reentrant scanners is different than for non-reentrant scanners. Here is a quick overview of the API: @itemize @code{%option reentrant} must be specified. @item All functions take one additional argument: @code{yyscanner} @item All global variables are replaced by their macro equivalents. (We tell you this because it may be important to you during debugging.) @item @code{yylex_init} and @code{yylex_destroy} must be called before and after @code{yylex}, respectively. @item Accessor methods (get/set functions) provide access to common @code{flex} variables. @item User-specific data can be stored in @code{yyextra}. @end itemize @node Reentrant Example, Reentrant Detail, Reentrant Overview, Reentrant @section Reentrant Example First, an example of a reentrant scanner: @cindex reentrant, example of @example @verbatim /* This scanner prints "//" comments. */ %option reentrant stack noyywrap %x COMMENT %% "//" yy_push_state( COMMENT, yyscanner); .|\n \n yy_pop_state( yyscanner ); [^\n]+ fprintf( yyout, "%s\n", yytext); %% int main ( int argc, char * argv[] ) { yyscan_t scanner; yylex_init ( &scanner ); yylex ( scanner ); yylex_destroy ( scanner ); return 0; } @end verbatim @end example @node Reentrant Detail, Reentrant Functions, Reentrant Example, Reentrant @section The Reentrant API in Detail Here are the things you need to do or know to use the reentrant C API of @code{flex}. @menu * Specify Reentrant:: * Extra Reentrant Argument:: * Global Replacement:: * Init and Destroy Functions:: * Accessor Methods:: * Extra Data:: * About yyscan_t:: @end menu @node Specify Reentrant, Extra Reentrant Argument, Reentrant Detail, Reentrant Detail @subsection Declaring a Scanner As Reentrant %option reentrant (--reentrant) must be specified. Notice that @code{%option reentrant} is specified in the above example (@pxref{Reentrant Example}. Had this option not been specified, @code{flex} would have happily generated a non-reentrant scanner without complaining. You may explicitly specify @code{%option noreentrant}, if you do @emph{not} want a reentrant scanner, although it is not necessary. The default is to generate a non-reentrant scanner. @node Extra Reentrant Argument, Global Replacement, Specify Reentrant, Reentrant Detail @subsection The Extra Argument @cindex reentrant, calling functions @vindex yyscanner (reentrant only) All functions take one additional argument: @code{yyscanner}. Notice that the calls to @code{yy_push_state} and @code{yy_pop_state} both have an argument, @code{yyscanner} , that is not present in a non-reentrant scanner. Here are the declarations of @code{yy_push_state} and @code{yy_pop_state} in the reentrant scanner: @example @verbatim static void yy_push_state ( int new_state , yyscan_t yyscanner ) ; static void yy_pop_state ( yyscan_t yyscanner ) ; @end verbatim @end example Notice that the argument @code{yyscanner} appears in the declaration of both functions. In fact, all @code{flex} functions in a reentrant scanner have this additional argument. It is always the last argument in the argument list, it is always of type @code{yyscan_t} (which is typedef'd to @code{void *}) and it is always named @code{yyscanner}. As you may have guessed, @code{yyscanner} is a pointer to an opaque data structure encapsulating the current state of the scanner. For a list of function declarations, see @ref{Reentrant Functions}. Note that preprocessor macros, such as @code{BEGIN}, @code{ECHO}, and @code{REJECT}, do not take this additional argument. @node Global Replacement, Init and Destroy Functions, Extra Reentrant Argument, Reentrant Detail @subsection Global Variables Replaced By Macros @cindex reentrant, accessing flex variables All global variables in traditional flex have been replaced by macro equivalents. Note that in the above example, @code{yyout} and @code{yytext} are not plain variables. These are macros that will expand to their equivalent lvalue. All of the familiar @code{flex} globals have been replaced by their macro equivalents. In particular, @code{yytext}, @code{yyleng}, @code{yylineno}, @code{yyin}, @code{yyout}, @code{yyextra}, @code{yylval}, and @code{yylloc} are macros. You may safely use these macros in actions as if they were plain variables. We only tell you this so you don't expect to link to these variables externally. Currently, each macro expands to a member of an internal struct, e.g., @example @verbatim #define yytext (((struct yyguts_t*)yyscanner)->yytext_r) @end verbatim @end example One important thing to remember about @code{yytext} and friends is that @code{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., @code{yyget_text}, to accomplish this. (See below). @node Init and Destroy Functions, Accessor Methods, Global Replacement, Reentrant Detail @subsection Init and Destroy Functions @cindex memory, considerations for reentrant scanners @cindex reentrant, initialization @findex yylex_init @findex yylex_destroy @code{yylex_init} and @code{yylex_destroy} must be called before and after @code{yylex}, respectively. @example @verbatim int yylex_init ( yyscan_t * ptr_yy_globals ) ; int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t * ptr_yy_globals ) ; int yylex ( yyscan_t yyscanner ) ; int yylex_destroy ( yyscan_t yyscanner ) ; @end verbatim @end example The function @code{yylex_init} must be called before calling any other function. The argument to @code{yylex_init} is the address of an uninitialized pointer to be filled in by @code{yylex_init}, overwriting any previous contents. The function @code{yylex_init_extra} may be used instead, taking as its first argument a variable of type @code{YY_EXTRA_TYPE}. See the section on yyextra, below, for more details. The value stored in @code{ptr_yy_globals} should thereafter be passed to @code{yylex} and @code{yylex_destroy}. Flex does not save the argument passed to @code{yylex_init}, so it is safe to pass the address of a local pointer to @code{yylex_init} so long as it remains in scope for the duration of all calls to the scanner, up to and including the call to @code{yylex_destroy}. The function @code{yylex} should be familiar to you by now. The reentrant version takes one argument, which is the value returned (via an argument) by @code{yylex_init}. Otherwise, it behaves the same as the non-reentrant version of @code{yylex}. Both @code{yylex_init} and @code{yylex_init_extra} returns 0 (zero) on success, or non-zero on failure, in which case errno is set to one of the following values: @itemize @item ENOMEM Memory allocation error. @xref{memory-management}. @item EINVAL Invalid argument. @end itemize The function @code{yylex_destroy} should be called to free resources used by the scanner. After @code{yylex_destroy} is called, the contents of @code{yyscanner} should not be used. Of course, there is no need to destroy a scanner if you plan to reuse it. A @code{flex} scanner (both reentrant and non-reentrant) may be restarted by calling @code{yyrestart}. Below is an example of a program that creates a scanner, uses it, then destroys it when done: @example @verbatim int main () { yyscan_t scanner; int tok; yylex_init(&scanner); while ((tok=yylex(scanner)) > 0) printf("tok=%d yytext=%s\n", tok, yyget_text(scanner)); yylex_destroy(scanner); return 0; } @end verbatim @end example @node Accessor Methods, Extra Data, Init and Destroy Functions, Reentrant Detail @subsection Accessing Variables with Reentrant Scanners @cindex reentrant, accessor functions Accessor methods (get/set functions) provide access to common @code{flex} variables. Many scanners that you build will be part of a larger project. Portions of your project will need access to @code{flex} values, such as @code{yytext}. In a non-reentrant scanner, these values are global, so there is no problem accessing them. However, in a reentrant scanner, there are no global @code{flex} values. You can not access them directly. Instead, you must access @code{flex} values using accessor methods (get/set functions). Each accessor method is named @code{yyget_NAME} or @code{yyset_NAME}, where @code{NAME} is the name of the @code{flex} variable you want. For example: @cindex accessor functions, use of @example @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'; } @end verbatim @end example The above code may be called from within an action like this: @example @verbatim %% .+\n { chop( yyscanner );} @end verbatim @end example You may find that @code{%option header-file} is particularly useful for generating prototypes of all the accessor functions. @xref{option-header}. @node Extra Data, About yyscan_t, Accessor Methods, Reentrant Detail @subsection Extra Data @cindex reentrant, extra data @vindex yyextra User-specific data can be stored in @code{yyextra}. In a reentrant scanner, it is unwise to use global variables to communicate with or maintain state between different pieces of your program. However, you may need access to external data or invoke external functions from within the scanner actions. Likewise, you may need to pass information to your scanner (e.g., open file descriptors, or database connections). In a non-reentrant scanner, the only way to do this would be through the use of global variables. @code{Flex} allows you to store arbitrary, ``extra'' data in a scanner. This data is accessible through the accessor methods @code{yyget_extra} and @code{yyset_extra} from outside the scanner, and through the shortcut macro @code{yyextra} from within the scanner itself. They are defined as follows: @tindex YY_EXTRA_TYPE (reentrant only) @findex yyget_extra @findex yyset_extra @example @verbatim #define YY_EXTRA_TYPE void* YY_EXTRA_TYPE yyget_extra ( yyscan_t scanner ); void yyset_extra ( YY_EXTRA_TYPE arbitrary_data , yyscan_t scanner); @end verbatim @end example In addition, an extra form of @code{yylex_init} is provided, @code{yylex_init_extra}. This function is provided so that the yyextra value can be accessed from within the very first yyalloc, used to allocate the scanner itself. By default, @code{YY_EXTRA_TYPE} is defined as type @code{void *}. You may redefine this type using @code{%option extra-type="your_type"} in the scanner: @cindex YY_EXTRA_TYPE, defining your own type @example @verbatim /* An example of overriding YY_EXTRA_TYPE. */ %{ #include #include %} %option reentrant %option extra-type="struct stat *" %% __filesize__ printf( "%ld", yyextra->st_size ); __lastmod__ printf( "%ld", yyextra->st_mtime ); %% void scan_file( char* filename ) { yyscan_t scanner; struct stat buf; FILE *in; in = fopen( filename, "r" ); stat( filename, &buf ); yylex_init_extra( buf, &scanner ); yyset_in( in, scanner ); yylex( scanner ); yylex_destroy( scanner ); fclose( in ); } @end verbatim @end example @node About yyscan_t, , Extra Data, Reentrant Detail @subsection About yyscan_t @tindex yyscan_t (reentrant only) @code{yyscan_t} is defined as: @example @verbatim typedef void* yyscan_t; @end verbatim @end example It is initialized by @code{yylex_init()} to point to an internal structure. You should never access this value directly. In particular, you should never attempt to free it (use @code{yylex_destroy()} instead.) @node Reentrant Functions, , Reentrant Detail, Reentrant @section Functions and Macros Available in Reentrant C Scanners The following Functions are available in a reentrant scanner: @findex yyget_text @findex yyget_leng @findex yyget_in @findex yyget_out @findex yyget_lineno @findex yyset_in @findex yyset_out @findex yyset_lineno @findex yyget_debug @findex yyset_debug @findex yyget_extra @findex yyset_extra @example @verbatim char *yyget_text ( yyscan_t scanner ); int yyget_leng ( yyscan_t scanner ); FILE *yyget_in ( yyscan_t scanner ); 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 ); void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t scanner ); @end verbatim @end example There are no ``set'' functions for yytext and yyleng. This is intentional. The following Macro shortcuts are available in actions in a reentrant scanner: @example @verbatim yytext yyleng yyin yyout yylineno yyextra yy_flex_debug @end verbatim @end example @cindex yylineno, in a reentrant scanner In a reentrant C scanner, support for yylineno is always present (i.e., you may access yylineno), but the value is never modified by @code{flex} unless @code{%option yylineno} is enabled. This is to allow the user to maintain the line count independently of @code{flex}. @anchor{bison-functions} The following functions and macros are made available when @code{%option bison-bridge} (@samp{--bison-bridge}) is specified: @example @verbatim YYSTYPE * yyget_lval ( yyscan_t scanner ); void yyset_lval ( YYSTYPE * yylvalp , yyscan_t scanner ); yylval @end verbatim @end example The following functions and macros are made available when @code{%option bison-locations} (@samp{--bison-locations}) is specified: @example @verbatim YYLTYPE *yyget_lloc ( yyscan_t scanner ); void yyset_lloc ( YYLTYPE * yyllocp , yyscan_t scanner ); yylloc @end verbatim @end example Support for yylval assumes that @code{YYSTYPE} is a valid type. Support for yylloc assumes that @code{YYSLYPE} is a valid type. Typically, these types are generated by @code{bison}, and are included in section 1 of the @code{flex} input. @node Lex and Posix, Memory Management, Reentrant, Top @chapter Incompatibilities with Lex and Posix @cindex POSIX and lex @cindex lex (traditional) and POSIX @code{flex} is a rewrite of the AT&T Unix @emph{lex} tool (the two implementations do not share any code, though), with some extensions and incompatibilities, both of which are of concern to those who wish to write scanners acceptable to both implementations. @code{flex} is fully compliant with the POSIX @code{lex} specification, except that when using @code{%pointer} (the default), a call to @code{unput()} destroys the contents of @code{yytext}, which is counter to the POSIX specification. In this section we discuss all of the known areas of incompatibility between @code{flex}, AT&T @code{lex}, and the POSIX specification. @code{flex}'s @samp{-l} option turns on maximum compatibility with the original AT&T @code{lex} implementation, at the cost of a major loss in the generated scanner's performance. We note below which incompatibilities can be overcome using the @samp{-l} option. @code{flex} is fully compatible with @code{lex} with the following exceptions: @itemize @item The undocumented @code{lex} scanner internal variable @code{yylineno} is not supported unless @samp{-l} or @code{%option yylineno} is used. @item @code{yylineno} should be maintained on a per-buffer basis, rather than a per-scanner (single global variable) basis. @item @code{yylineno} is not part of the POSIX specification. @item The @code{input()} routine is not redefinable, though it may be called to read characters following whatever has been matched by a rule. If @code{input()} encounters an end-of-file the normal @code{yywrap()} processing is done. A ``real'' end-of-file is returned by @code{input()} as @code{EOF}. @item Input is instead controlled by defining the @code{YY_INPUT()} macro. @item The @code{flex} restriction that @code{input()} cannot be redefined is in accordance with the POSIX specification, which simply does not specify any way of controlling the scanner's input other than by making an initial assignment to @file{yyin}. @item The @code{unput()} routine is not redefinable. This restriction is in accordance with POSIX. @item @code{flex} scanners are not as reentrant as @code{lex} scanners. In particular, if you have an interactive scanner and an interrupt handler which long-jumps out of the scanner, and the scanner is subsequently called again, you may get the following message: @cindex error messages, end of buffer missed @example @verbatim fatal flex scanner internal error--end of buffer missed @end verbatim @end example To reenter the scanner, first use: @cindex restarting the scanner @example @verbatim yyrestart( yyin ); @end verbatim @end example Note that this call will throw away any buffered input; usually this isn't a problem with an interactive scanner. @xref{Reentrant}, for @code{flex}'s reentrant API. @item Also note that @code{flex} C++ scanner classes @emph{are} reentrant, so if using C++ is an option for you, you should use them instead. @xref{Cxx}, and @ref{Reentrant} for details. @item @code{output()} is not supported. Output from the @b{ECHO} macro is done to the file-pointer @code{yyout} (default @file{stdout)}. @item @code{output()} is not part of the POSIX specification. @item @code{lex} does not support exclusive start conditions (%x), though they are in the POSIX specification. @item When definitions are expanded, @code{flex} encloses them in parentheses. With @code{lex}, the following: @cindex name definitions, not POSIX @example @verbatim NAME [A-Z][A-Z0-9]* %% foo{NAME}? printf( "Found it\n" ); %% @end verbatim @end example will not match the string @samp{foo} because when the macro is expanded the rule is equivalent to @samp{foo[A-Z][A-Z0-9]*?} and the precedence is such that the @samp{?} is associated with @samp{[A-Z0-9]*}. With @code{flex}, the rule will be expanded to @samp{foo([A-Z][A-Z0-9]*)?} and so the string @samp{foo} will match. @item Note that if the definition begins with @samp{^} or ends with @samp{$} then it is @emph{not} expanded with parentheses, to allow these operators to appear in definitions without losing their special meanings. But the @samp{}, @samp{/}, and @code{<>} operators cannot be used in a @code{flex} definition. @item Using @samp{-l} results in the @code{lex} behavior of no parentheses around the definition. @item The POSIX specification is that the definition be enclosed in parentheses. @item Some implementations of @code{lex} allow a rule's action to begin on a separate line, if the rule's pattern has trailing whitespace: @cindex patterns and actions on different lines @example @verbatim %% foo|bar { foobar_action();} @end verbatim @end example @code{flex} does not support this feature. @item The @code{lex} @code{%r} (generate a Ratfor scanner) option is not supported. It is not part of the POSIX specification. @item After a call to @code{unput()}, @emph{yytext} is undefined until the next token is matched, unless the scanner was built using @code{%array}. This is not the case with @code{lex} or the POSIX specification. The @samp{-l} option does away with this incompatibility. @item The precedence of the @samp{@{,@}} (numeric range) operator is different. The AT&T and POSIX specifications of @code{lex} interpret @samp{abc@{1,3@}} as match one, two, or three occurrences of @samp{abc}'', whereas @code{flex} interprets it as ``match @samp{ab} followed by one, two, or three occurrences of @samp{c}''. The @samp{-l} and @samp{--posix} options do away with this incompatibility. @item The precedence of the @samp{^} operator is different. @code{lex} interprets @samp{^foo|bar} as ``match either 'foo' at the beginning of a line, or 'bar' anywhere'', whereas @code{flex} interprets it as ``match either @samp{foo} or @samp{bar} if they come at the beginning of a line''. The latter is in agreement with the POSIX specification. @item The special table-size declarations such as @code{%a} supported by @code{lex} are not required by @code{flex} scanners.. @code{flex} ignores them. @item The name @code{FLEX_SCANNER} is @code{#define}'d so scanners may be written for use with either @code{flex} or @code{lex}. Scanners also include @code{YY_FLEX_MAJOR_VERSION}, @code{YY_FLEX_MINOR_VERSION} and @code{YY_FLEX_SUBMINOR_VERSION} indicating which version of @code{flex} generated the scanner. For example, for the 2.5.22 release, these defines would be 2, 5 and 22 respectively. If the version of @code{flex} being used is a beta version, then the symbol @code{FLEX_BETA} is defined. @item The symbols @samp{[[} and @samp{]]} in the code sections of the input may conflict with the m4 delimiters. @xref{M4 Dependency}. @end itemize @cindex POSIX comp;compliance @cindex non-POSIX features of flex The following @code{flex} features are not included in @code{lex} or the POSIX specification: @itemize @item C++ scanners @item %option @item start condition scopes @item start condition stacks @item interactive/non-interactive scanners @item yy_scan_string() and friends @item yyterminate() @item yy_set_interactive() @item yy_set_bol() @item YY_AT_BOL() <> @item <*> @item YY_DECL @item YY_START @item YY_USER_ACTION @item YY_USER_INIT @item #line directives @item %@{@}'s around actions @item reentrant C API @item multiple actions on a line @item almost all of the @code{flex} command-line options @end itemize The feature ``multiple actions on a line'' refers to the fact that with @code{flex} you can put multiple actions on the same line, separated with semi-colons, while with @code{lex}, the following: @example @verbatim foo handle_foo(); ++num_foos_seen; @end verbatim @end example is (rather surprisingly) truncated to @example @verbatim foo handle_foo(); @end verbatim @end example @code{flex} does not truncate the action. Actions that are not enclosed in braces are simply terminated at the end of the line. @node Memory Management, Serialized Tables, Lex and Posix, Top @chapter Memory Management @cindex memory management @anchor{memory-management} This chapter describes how flex handles dynamic memory, and how you can override the default behavior. @menu * The Default Memory Management:: * Overriding The Default Memory Management:: * A Note About yytext And Memory:: @end menu @node The Default Memory Management, Overriding The Default Memory Management, Memory Management, Memory Management @section The Default Memory Management 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 @code{yylex_destroy} @xref{faq-memory-leak}. Flex allocates dynamic memory for four purposes, listed below @footnote{The quantities given here are approximate, and may vary due to host architecture, compiler configuration, or due to future enhancements to flex.} @table @asis @item 16kB for the input buffer. Flex allocates memory for the character buffer used to perform pattern matching. Flex must read ahead from the input stream and store it in a large character buffer. This buffer is typically the largest chunk of dynamic memory flex consumes. This buffer will grow if necessary, doubling the size each time. Flex frees this memory when you call yylex_destroy(). The default size of this buffer (16384 bytes) is almost always too large. The ideal size for this buffer is the length of the longest token expected, in bytes, plus a little more. Flex will allocate a few extra bytes for housekeeping. Currently, to override the size of the input buffer you must @code{#define YY_BUF_SIZE} to whatever number of bytes you want. We don't plan to change this in the near future, but we reserve the right to do so if we ever add a more robust memory management API. @item 64kb for the REJECT state. This will only be allocated if you use REJECT. The size is large enough to hold the same number of states as characters in the input buffer. If you override the size of the input buffer (via @code{YY_BUF_SIZE}), then you automatically override the size of this buffer as well. @item 100 bytes for the start condition stack. Flex allocates memory for the start condition stack. This is the stack used for pushing start states, i.e., with yy_push_state(). It will grow if necessary. Since the states are simply integers, this stack doesn't consume much memory. This stack is not present if @code{%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}. @item 40 bytes for each YY_BUFFER_STATE. Flex allocates memory for each YY_BUFFER_STATE. The buffer state itself is about 40 bytes, plus an additional large character buffer (described above.) The initial buffer state is created during initialization, and with each call to yy_create_buffer(). You can't tune the size of this, but you can tune the character buffer as described above. Any buffer state that you explicitly create by calling yy_create_buffer() is @emph{NOT} destroyed automatically. You must call yy_delete_buffer() to free the memory. The exception to this rule is that flex will delete the current buffer automatically when you call yylex_destroy(). If you delete the current buffer, be sure to set it to NULL. That way, flex will not try to delete the buffer a second time (possibly crashing your program!) At the time of this writing, flex does not provide a growable stack for the buffer states. You have to manage that yourself. @xref{Multiple Input Buffers}. @item 84 bytes for the reentrant scanner guts Flex allocates about 84 bytes for the reentrant scanner structure when you call yylex_init(). It is destroyed when the user calls yylex_destroy(). @end table @node Overriding The Default Memory Management, A Note About yytext And Memory, The Default Memory Management, Memory Management @section Overriding The Default Memory Management @cindex yyalloc, overriding @cindex yyrealloc, overriding @cindex yyfree, overriding Flex calls the functions @code{yyalloc}, @code{yyrealloc}, and @code{yyfree} when it needs to allocate or free memory. By default, these functions are wrappers around the standard C functions, @code{malloc}, @code{realloc}, and @code{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: @enumerate @item Suppress the default implementations by specifying one or more of the following options: @itemize @opindex noyyalloc @item @code{%option noyyalloc} @item @code{%option noyyrealloc} @item @code{%option noyyfree}. @end itemize @item Provide your own implementation of the following functions: @footnote{It is not necessary to override all (or any) of the memory management routines. You may, for example, override @code{yyrealloc}, but not @code{yyfree} or @code{yyalloc}.} @example @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); @end verbatim @end example @end enumerate 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 @code{yyextra}. @cindex overriding the memory routines @example @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. */ } @end verbatim @end example @node A Note About yytext And Memory, , Overriding The Default Memory Management, Memory Management @section A Note About yytext And Memory @cindex yytext, memory considerations When flex finds a match, @code{yytext} points to the first character of the match in the input buffer. The string itself is part of the input buffer, and is @emph{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. @node Serialized Tables, Diagnostics, Memory Management, Top @chapter Serialized Tables @cindex serialization @cindex memory, serialized tables @anchor{serialization} A @code{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. @menu * Creating Serialized Tables:: * Loading and Unloading Serialized Tables:: * Tables File Format:: @end menu @node Creating Serialized Tables, Loading and Unloading Serialized Tables, Serialized Tables, Serialized Tables @section Creating Serialized Tables @cindex tables, creating serialized @cindex serialization of tables You may create a scanner with serialized tables by specifying: @example @verbatim %option tables-file=FILE or --tables-file=FILE @end verbatim @end example These options instruct flex to save the DFA tables to the file @var{FILE}. The tables will @emph{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 @code{--tables-file}, the tables will be saved to @file{lex.yy.tables}, where @samp{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: @cindex serialized tables, multiple scanners @example @verbatim $ flex --tables-file --prefix=cpp cpp.l $ flex --tables-file --prefix=c c.l $ cat lex.cpp.tables lex.c.tables > all.tables @end verbatim @end example The above example created two scanners, @samp{cpp}, and @samp{c}. Since we did not specify a filename, the tables were serialized to @file{lex.c.tables} and @file{lex.cpp.tables}, respectively. Then, we concatenated the two files together into @file{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). @node Loading and Unloading Serialized Tables, Tables File Format, Creating Serialized Tables, Serialized Tables @section Loading and Unloading Serialized Tables @cindex tables, loading and unloading @cindex loading tables at runtime @cindex tables, freeing @cindex freeing tables @cindex memory, serialized tables If you've built your scanner with @code{%option tables-file}, then you must load the scanner tables at runtime. This can be accomplished with the following function: @deftypefun int yytables_fload (FILE* @var{fp} [, yyscan_t @var{scanner}]) Locates scanner tables in the stream pointed to by @var{fp} and loads them. Memory for the tables is allocated via @code{yyalloc}. You must call this function before the first call to @code{yylex}. The argument @var{scanner} only appears in the reentrant scanner. This function returns @samp{0} (zero) on success, or non-zero on error. @end deftypefun The loaded tables are @strong{not} automatically destroyed (unloaded) when you call @code{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: @deftypefun int yytables_destroy ([yyscan_t @var{scanner}]) Unloads the scanner tables. The tables must be loaded again before you can scan any more data. The argument @var{scanner} only appears in the reentrant scanner. This function returns @samp{0} (zero) on success, or non-zero on error. @end deftypefun @strong{The functions @code{yytables_fload} and @code{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 @code{yylex}. After the tables are loaded, they are never written to, and no thread protection is required thereafter -- until you destroy them. @node Tables File Format, , Loading and Unloading Serialized Tables, Serialized Tables @section Tables File Format @cindex tables, file format @cindex file format, serialized tables This section defines the file format of serialized @code{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: @example @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_hilen; | | uint32 td_lolen; | | void td_data[]; | | uint8 td_pad64[]; | +-------------------------------+ Table 2 | | . . . . . . . . . . . . Table n | | +-------------------------------+ TABLE SET 2 . . . TABLE SET N @end verbatim @end example 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, @emph{all integer values are in network byte order}. @noindent Fields of a table header: @table @code @item th_magic Magic number, always 0xF13C57B1. @item th_hsize Size of this entire header, in bytes, including all fields plus any padding. @item th_ssize Size of this entire set, in bytes, including the header, all tables, plus any padding. @item th_flags Bit flags for this table set. Currently unused. @item th_version[] Flex version in NULL-terminated string format. e.g., @samp{2.5.13a}. This is the version of flex that was used to create the serialized tables. @item th_name[] Contains the name of this table set. The default is @samp{yytables}, and is prefixed accordingly, e.g., @samp{footables}. Must be NULL-terminated. @item th_pad64[] Zero or more NULL bytes, padding the entire header to the next 64-bit boundary as calculated from the beginning of the header. @end table @noindent Fields of a table: @table @code @item td_id Specifies the table identifier. Possible values are: @table @code @item YYTD_ID_ACCEPT (0x01) @code{yy_accept} @item YYTD_ID_BASE (0x02) @code{yy_base} @item YYTD_ID_CHK (0x03) @code{yy_chk} @item YYTD_ID_DEF (0x04) @code{yy_def} @item YYTD_ID_EC (0x05) @code{yy_ec } @item YYTD_ID_META (0x06) @code{yy_meta} @item YYTD_ID_NUL_TRANS (0x07) @code{yy_NUL_trans} @item YYTD_ID_NXT (0x08) @code{yy_nxt}. This array may be two dimensional. See the @code{td_hilen} field below. @item YYTD_ID_RULE_CAN_MATCH_EOL (0x09) @code{yy_rule_can_match_eol} @item YYTD_ID_START_STATE_LIST (0x0A) @code{yy_start_state_list}. This array is handled specially because it is an array of pointers to structs. See the @code{td_flags} field below. @item YYTD_ID_TRANSITION (0x0B) @code{yy_transition}. This array is handled specially because it is an array of structs. See the @code{td_lolen} field below. @item YYTD_ID_ACCLIST (0x0C) @code{yy_acclist} @end table @item td_flags Bit flags describing how to interpret the data in @code{td_data}. The data arrays are one-dimensional by default, but may be two dimensional as specified in the @code{td_hilen} field. @table @code @item YYTD_DATA8 (0x01) The data is serialized as an array of type int8. @item YYTD_DATA16 (0x02) The data is serialized as an array of type int16. @item YYTD_DATA32 (0x04) The data is serialized as an array of type int32. @item YYTD_PTRANS (0x08) The data is a list of indexes of entries in the expanded @code{yy_transition} array. Each index should be expanded to a pointer to the corresponding entry in the @code{yy_transition} array. We count on the fact that the @code{yy_transition} array has already been seen. @item YYTD_STRUCT (0x10) The data is a list of yy_trans_info structs, each of which consists of two integers. There is no padding between struct elements or between structs. The type of each member is determined by the @code{YYTD_DATA*} bits. @end table @item td_hilen If @code{td_hilen} is non-zero, then the data is a two-dimensional array. Otherwise, the data is a one-dimensional array. @code{td_hilen} contains the number of elements in the higher dimensional array, and @code{td_lolen} contains the number of elements in the lowest dimension. Conceptually, @code{td_data} is either @code{sometype td_data[td_lolen]}, or @code{sometype td_data[td_hilen][td_lolen]}, where @code{sometype} is specified by the @code{td_flags} field. It is possible for both @code{td_lolen} and @code{td_hilen} to be zero, in which case @code{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. @item td_lolen Specifies the number of elements in the lowest dimension array. If this is a one-dimensional array, then it is simply the number of elements in this array. The element size is determined by the @code{td_flags} field. @item td_data[] The table data. This array may be a one- or two-dimensional array, of type @code{int8}, @code{int16}, @code{int32}, @code{struct yy_trans_info}, or @code{struct yy_trans_info*}, depending upon the values in the @code{td_flags}, @code{td_hilen}, and @code{td_lolen} fields. @item td_pad64[] Zero or more NULL bytes, padding the entire table to the next 64-bit boundary as calculated from the beginning of this table. @end table @node Diagnostics, Limitations, Serialized Tables, Top @chapter Diagnostics @cindex error reporting, diagnostic messages @cindex warnings, diagnostic messages The following is a list of @code{flex} diagnostic messages: @itemize @item @samp{warning, rule cannot be matched} indicates that the given rule cannot be matched because it follows other rules that will always match the same text as it. For example, in the following @samp{foo} cannot be matched because it comes after an identifier ``catch-all'' rule: @cindex warning, rule cannot be matched @example @verbatim [a-z]+ got_identifier(); foo got_foo(); @end verbatim @end example Using @code{REJECT} in a scanner suppresses this warning. @item @samp{warning, -s option given but default rule can be matched} means 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 @samp{-s} was given, presumably this is not intended. @item @code{reject_used_but_not_detected undefined} or @code{yymore_used_but_not_detected undefined}. These errors can occur at compile time. They indicate that the scanner uses @code{REJECT} or @code{yymore()} but that @code{flex} failed to notice the fact, meaning that @code{flex} scanned the first two sections looking for occurrences of these actions and failed to find any, but somehow you snuck some in (via a #include file, for example). Use @code{%option reject} or @code{%option yymore} to indicate to @code{flex} that you really do use these features. @item @samp{flex scanner jammed}. a scanner compiled with @samp{-s} has encountered an input string which wasn't matched by any of its rules. This error can also occur due to internal problems. @item @samp{token too large, exceeds YYLMAX}. your scanner uses @code{%array} and one of its rules matched a string longer than the @code{YYLMAX} constant (8K bytes by default). You can increase the value by #define'ing @code{YYLMAX} in the definitions section of your @code{flex} input. @item @samp{scanner requires -8 flag to use the character 'x'}. Your scanner specification includes recognizing the 8-bit character @samp{'x'} and you did not specify the -8 flag, and your scanner defaulted to 7-bit because you used the @samp{-Cf} or @samp{-CF} table compression options. See the discussion of the @samp{-7} flag, @ref{Scanner Options}, for details. @item @samp{flex scanner push-back overflow}. you used @code{unput()} to push back so much text that the scanner's buffer could not hold both the pushed-back text and the current token in @code{yytext}. Ideally the scanner should dynamically resize the buffer in this case, but at present it does not. @item @samp{input buffer overflow, can't enlarge buffer because scanner uses REJECT}. the scanner was working on matching an extremely large token and needed to expand the input buffer. This doesn't work with scanners that use @code{REJECT}. @item @samp{fatal flex scanner internal error--end of buffer missed}. This can occur in a scanner which is reentered after a long-jump has jumped out (or over) the scanner's activation frame. Before reentering the scanner, use: @example @verbatim yyrestart( yyin ); @end verbatim @end example or, as noted above, switch to using the C++ scanner class. @item @samp{too many start conditions in <> construct!} you listed more start conditions in a <> construct than exist (so you must have listed at least one of them twice). @end itemize @node Limitations, Bibliography, Diagnostics, Top @chapter Limitations @cindex limitations of flex Some trailing context patterns cannot be properly matched and generate warning messages (@samp{dangerous trailing context}). These are patterns where the ending of the first part of the rule matches the beginning of the second part, such as @samp{zx*/xy*}, where the 'x*' matches the 'x' at the beginning of the trailing context. (Note that the POSIX draft states that the text matched by such patterns is undefined.) For some trailing context rules, parts which are actually fixed-length are not recognized as such, leading to the abovementioned performance loss. In particular, parts using @samp{|} or @samp{@{n@}} (such as @samp{foo@{3@}}) are always considered variable-length. Combining trailing context with the special @samp{|} action can result in @emph{fixed} trailing context being turned into the more expensive @emph{variable} trailing context. For example, in the following: @cindex warning, dangerous trailing context @example @verbatim %% abc | xyz/def @end verbatim @end example Use of @code{unput()} invalidates yytext and yyleng, unless the @code{%array} directive or the @samp{-l} option has been used. Pattern-matching of @code{NUL}s is substantially slower than matching other characters. Dynamic resizing of the input buffer is slow, as it entails rescanning all the text matched so far by the current (generally huge) token. Due to both buffering of input and read-ahead, you cannot intermix calls to @file{} routines, such as, @b{getchar()}, with @code{flex} rules and expect it to work. Call @code{input()} instead. The total table entries listed by the @samp{-v} flag excludes the number of table entries needed to determine what rule has been matched. The number of entries is equal to the number of DFA states if the scanner does not use @code{REJECT}, and somewhat greater than the number of states if it does. @code{REJECT} cannot be used with the @samp{-f} or @samp{-F} options. The @code{flex} internal algorithms need documentation. @node Bibliography, FAQ, Limitations, Top @chapter Additional Reading You may wish to read more about the following programs: @itemize @item lex @item yacc @item sed @item awk @end itemize The following books may contain material of interest: John Levine, Tony Mason, and Doug Brown, @emph{Lex & Yacc}, O'Reilly and Associates. Be sure to get the 2nd edition. M. E. Lesk and E. Schmidt, @emph{LEX -- Lexical Analyzer Generator} Alfred Aho, Ravi Sethi and Jeffrey Ullman, @emph{Compilers: Principles, Techniques and Tools}, Addison-Wesley (1986). Describes the pattern-matching techniques used by @code{flex} (deterministic finite automata). @node FAQ, Appendices, Bibliography, Top @unnumbered FAQ From time to time, the @code{flex} maintainer receives certain questions. Rather than repeat answers to well-understood problems, we publish them here. @menu * When was flex born?:: * How do I expand backslash-escape sequences in C-style quoted strings?:: * Why do flex scanners call fileno if it is not ANSI compatible?:: * Does flex support recursive pattern definitions?:: * How do I skip huge chunks of input (tens of megabytes) while using flex?:: * Flex is not matching my patterns in the same order that I defined them.:: * My actions are executing out of order or sometimes not at all.:: * How can I have multiple input sources feed into the same scanner at the same time?:: * Can I build nested parsers that work with the same input file?:: * How can I match text only at the end of a file?:: * How can I make REJECT cascade across start condition boundaries?:: * Why cant I use fast or full tables with interactive mode?:: * How much faster is -F or -f than -C?:: * If I have a simple grammar cant I just parse it with flex?:: * Why doesn't yyrestart() set the start state back to INITIAL?:: * How can I match C-style comments?:: * The period isn't working the way I expected.:: * Can I get the flex manual in another format?:: * Does there exist a "faster" NDFA->DFA algorithm?:: * How does flex compile the DFA so quickly?:: * How can I use more than 8192 rules?:: * How do I abandon a file in the middle of a scan and switch to a new file?:: * How do I execute code only during initialization (only before the first scan)?:: * How do I execute code at termination?:: * Where else can I find help?:: * Can I include comments in the "rules" section of the file?:: * I get an error about undefined yywrap().:: * How can I change the matching pattern at run time?:: * How can I expand macros in the input?:: * How can I build a two-pass scanner?:: * How do I match any string not matched in the preceding rules?:: * I am trying to port code from AT&T lex that uses yysptr and yysbuf.:: * Is there a way to make flex treat NULL like a regular character?:: * Whenever flex can not match the input it says "flex scanner jammed".:: * Why doesn't flex have non-greedy operators like perl does?:: * Memory leak - 16386 bytes allocated by malloc.:: * How do I track the byte offset for lseek()?:: * How do I use my own I/O classes in a C++ scanner?:: * How do I skip as many chars as possible?:: * deleteme00:: * Are certain equivalent patterns faster than others?:: * Is backing up a big deal?:: * Can I fake multi-byte character support?:: * deleteme01:: * Can you discuss some flex internals?:: * unput() messes up yy_at_bol:: * The | operator is not doing what I want:: * Why can't flex understand this variable trailing context pattern?:: * The ^ operator isn't working:: * Trailing context is getting confused with trailing optional patterns:: * Is flex GNU or not?:: * ERASEME53:: * I need to scan if-then-else blocks and while loops:: * ERASEME55:: * ERASEME56:: * ERASEME57:: * Is there a repository for flex scanners?:: * How can I conditionally compile or preprocess my flex input file?:: * Where can I find grammars for lex and yacc?:: * I get an end-of-buffer message for each character scanned.:: * unnamed-faq-62:: * unnamed-faq-63:: * unnamed-faq-64:: * unnamed-faq-65:: * unnamed-faq-66:: * unnamed-faq-67:: * unnamed-faq-68:: * unnamed-faq-69:: * unnamed-faq-70:: * unnamed-faq-71:: * unnamed-faq-72:: * unnamed-faq-73:: * unnamed-faq-74:: * unnamed-faq-75:: * unnamed-faq-76:: * unnamed-faq-77:: * unnamed-faq-78:: * unnamed-faq-79:: * unnamed-faq-80:: * unnamed-faq-81:: * unnamed-faq-82:: * unnamed-faq-83:: * unnamed-faq-84:: * unnamed-faq-85:: * unnamed-faq-86:: * unnamed-faq-87:: * unnamed-faq-88:: * unnamed-faq-90:: * unnamed-faq-91:: * unnamed-faq-92:: * unnamed-faq-93:: * unnamed-faq-94:: * unnamed-faq-95:: * unnamed-faq-96:: * unnamed-faq-97:: * unnamed-faq-98:: * unnamed-faq-99:: * unnamed-faq-100:: * unnamed-faq-101:: * What is the difference between YYLEX_PARAM and YY_DECL?:: * Why do I get "conflicting types for yylex" error?:: * How do I access the values set in a Flex action from within a Bison action?:: @end menu @node When was flex born? @unnumberedsec When was flex born? Vern Paxson took over the @cite{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 :-). @node How do I expand backslash-escape sequences in C-style quoted strings? @unnumberedsec How do I expand backslash-escape sequences in C-style quoted strings? A key point when scanning quoted strings is that you cannot (easily) write a single rule that will precisely match the string if you allow things like embedded escape sequences and newlines. If you try to match strings with a single rule then you'll wind up having to rescan the string anyway to find any escape sequences. 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 @code{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 @code{yytext}. In this way, @code{yytext} does not need to be modified at all. @node Why do flex scanners call fileno if it is not ANSI compatible? @unnumberedsec Why do flex scanners call fileno if it is not ANSI compatible? Flex scanners call @code{fileno()} in order to get the file descriptor corresponding to @code{yyin}. The file descriptor may be passed to @code{isatty()} or @code{read()}, depending upon which @code{%options} you specified. If your system does not have @code{fileno()} support, to get rid of the @code{read()} call, do not specify @code{%option read}. To get rid of the @code{isatty()} call, you must specify one of @code{%option always-interactive} or @code{%option never-interactive}. @node Does flex support recursive pattern definitions? @unnumberedsec Does flex support recursive pattern definitions? e.g., @example @verbatim %% block "{"({block}|{statement})*"}" @end verbatim @end example 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 @cite{GNU bison}. @node How do I skip huge chunks of input (tens of megabytes) while using flex? @unnumberedsec How do I skip huge chunks of input (tens of megabytes) while using flex? Use @code{fseek()} (or @code{lseek()}) to position yyin, then call @code{yyrestart()}. @node Flex is not matching my patterns in the same order that I defined them. @unnumberedsec Flex is not matching my patterns in the same order that I defined them. @code{flex} picks the rule that matches the most text (i.e., the longest possible input string). This is because @code{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.) A side-effect of this parallel matching is that when the input matches more than one rule, @code{flex} scanners pick the rule that matched the @emph{most} text. This is explained further in the manual, in the section @xref{Matching}. If you want @code{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: @example @verbatim data_.* yyless( 5 ); BEGIN BLOCKIDSTATE; @end verbatim @end example Another fix would be to make the second rule active only during the @code{} start condition, and make that start condition exclusive by declaring it with @code{%x} instead of @code{%s}. A final fix is to change the input language so that the ambiguity for @samp{data_} is removed, by adding characters to it that don't match the identifier rule, or by removing characters (such as @samp{_}) from the identifier rule so it no longer matches @samp{data_}. (Of course, you might also not have the option of changing the input language.) @node My actions are executing out of order or sometimes not at all. @unnumberedsec My actions are executing out of order or sometimes not at all. Most likely, you have (in error) placed the opening @samp{@{} of the action block on a different line than the rule, e.g., @example @verbatim ^(foo|bar) { <<<--- WRONG! } @end verbatim @end example @code{flex} requires that the opening @samp{@{} 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: @example @verbatim ^(foo|bar) { // CORRECT! } @end verbatim @end example @node How can I have multiple input sources feed into the same scanner at the same time? @unnumberedsec How can I have multiple input sources feed into the same scanner at the same time? If @dots{} @itemize @item your scanner is free of backtracking (verified using @code{flex}'s @samp{-b} flag), @item AND you run your scanner interactively (@samp{-I} option; default unless using special table compression options), @item AND you feed it one character at a time by redefining @code{YY_INPUT} to do so, @end itemize 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 @code{select()} at the point and only call @code{yylex()} for another token if @code{select()} indicates there's data available. That is, move the @code{select()} out from the input function to a point where it determines whether @code{yylex()} gets called for the next token. With this approach, you will still have problems if your input can arrive piecemeal; @code{select()} could inform you that the beginning of a token is available, you call @code{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 @code{YY_INPUT}. That is, whenever @code{YY_INPUT} is called, it @code{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 input is available.) I've used this technique in an interpreter I wrote that both reads keyboard input using a @code{flex} scanner and IPC traffic from sockets, and it works fine. @node Can I build nested parsers that work with the same input file? @unnumberedsec 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 @code{flex} block-buffers the input it reads from @code{yyin}. This means that the ``outermost'' @code{yylex()}, when called, will automatically slurp up the first 8K of input available on yyin, and subsequent calls to other @code{yylex()}'s won't see that input. You might be tempted to work around this problem by redefining @code{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. @node How can I match text only at the end of a file? @unnumberedsec 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 @code{YY_INPUT} to call your own routine which, if it sees an @samp{EOF}, returns the magic character first (and remembers to return a real @code{EOF} next time it's called). Then you could write: @example @verbatim (.|\n)*{EOF_CHAR} /* saw comment at EOF */ @end verbatim @end example @node How can I make REJECT cascade across start condition boundaries? @unnumberedsec How can I make REJECT cascade across start condition boundaries? You can do this as follows. Suppose you have a start condition @samp{A}, and after exhausting all of the possible matches in @samp{}, you want to try matches in @samp{}. Then you could use the following: @example @verbatim %x A %% rule_that_is_long ...; REJECT; rule ...; REJECT; /* shorter rule */ etc. ... .|\n { /* Shortest and last rule in , so * cascaded REJECTs 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); } @end verbatim @end example @node Why cant I use fast or full tables with interactive mode? @unnumberedsec 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 (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 of another input character possibly extending the length of the match. If not, the scanner halts. For non-interactive scanners, the end-of-token test is much simpler, basically a compare with 0, so no memory bus cycles. Since the test occurs in the innermost scanning loop, one would like to make it go as fast as possible. 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. @node How much faster is -F or -f than -C? @unnumberedsec How much faster is -F or -f than -C? Much faster (factor of 2-3). @node If I have a simple grammar cant I just parse it with flex? @unnumberedsec 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 better off using a parser/scanner rather than just trying to use a scanner alone. @node Why doesn't yyrestart() set the start state back to INITIAL? @unnumberedsec 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 beginning with @code{flex} version 2.4, use of @code{yyrestart()} is no longer required, so fixing the problem there doesn't solve the more general problem. @node How can I match C-style comments? @unnumberedsec How can I match C-style comments? You might be tempted to try something like this: @example @verbatim "/*".*"*/" // WRONG! @end verbatim @end example or, worse, this: @example @verbatim "/*"(.|\n)"*/" // WRONG! @end verbatim @end example The above rules will eat too much input, and blow up on things like: @example @verbatim /* a comment */ do_my_thing( "oops */" ); @end verbatim @end example Here is one way which allows you to track line information: @example @verbatim { "/*" BEGIN(IN_COMMENT); } { "*/" BEGIN(INITIAL); [^*\n]+ // eat comment in chunks "*" // eat the lone star \n yylineno++; } @end verbatim @end example @node The period isn't working the way I expected. @unnumberedsec The '.' isn't working the way I expected. Here are some tips for using @samp{.}: @itemize @item A common mistake is to place the grouping parenthesis AFTER an operator, when you really meant to place the parenthesis BEFORE the operator, e.g., you probably want this @code{(foo|bar)+} and NOT this @code{(foo|bar+)}. The first pattern matches the words @samp{foo} or @samp{bar} any number of times, e.g., it matches the text @samp{barfoofoobarfoo}. The second pattern matches a single instance of @code{foo} or a single instance of @code{bar} followed by one or more @samp{r}s, e.g., it matches the text @code{barrrr} . @item A @samp{.} inside @samp{[]}'s just means a literal@samp{.} (period), and NOT ``any character except newline''. @item Remember that @samp{.} matches any character EXCEPT @samp{\n} (and @samp{EOF}). If you really want to match ANY character, including newlines, then use @code{(.|\n)} Beware that the regex @code{(.|\n)+} will match your entire input! @item Finally, if you want to match a literal @samp{.} (a period), then use @samp{[.]} or @samp{"."} @end itemize @node Can I get the flex manual in another format? @unnumberedsec Can I get the flex manual in another format? The @code{flex} source distribution includes a texinfo manual. You are free to convert that texinfo into whatever format you desire. The @code{texinfo} package includes tools for conversion to a number of formats. @node Does there exist a "faster" NDFA->DFA algorithm? @unnumberedsec Does there exist a "faster" NDFA->DFA algorithm? There's no way around the potential exponential running time - it can take you exponential time just to enumerate all of the DFA states. In practice, though, the running time is closer to linear, or sometimes quadratic. @node How does flex compile the DFA so quickly? @unnumberedsec How does flex compile the DFA so quickly? There are two big speed wins that @code{flex} uses: @enumerate @item It analyzes the input rules to construct equivalence classes for those characters that always make the same transitions. It then rewrites the NFA using equivalence classes for transitions instead of characters. This cuts down the NFA->DFA computation time dramatically, to the point where, for uncompressed DFA tables, the DFA generation is often I/O bound in writing out the tables. @item It maintains hash values for previously computed DFA states, so testing whether a newly constructed DFA state is equivalent to a previously constructed state can be done very quickly, by first comparing hash values. @end enumerate @node How can I use more than 8192 rules? @unnumberedsec How can I use more than 8192 rules? @code{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 @code{flex} with the following changes in @file{flexdef.h}: @example @verbatim < #define YY_TRAILING_MASK 0x2000 < #define YY_TRAILING_HEAD_MASK 0x4000 -- > #define YY_TRAILING_MASK 0x20000000 > #define YY_TRAILING_HEAD_MASK 0x40000000 @end verbatim @end example This should work okay as long as your C compiler uses 32 bit integers. But you might want to think about whether using such a huge number of rules is the best way to solve your problem. The following may also be relevant: With luck, you should be able to increase the definitions in flexdef.h for: @example @verbatim #define JAMSTATE -32766 /* marks a reference to the state that always jams */ #define MAXIMUM_MNS 31999 #define BAD_SUBSCRIPT -32767 @end verbatim @end example 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... @node How do I abandon a file in the middle of a scan and switch to a new file? @unnumberedsec How do I abandon a file in the middle of a scan and switch to a new file? Just call @code{yyrestart(newfile)}. Be sure to reset the start state if you want a ``fresh start, since @code{yyrestart} does NOT reset the start state back to @code{INITIAL}. @node How do I execute code only during initialization (only before the first scan)? @unnumberedsec How do I execute code only during initialization (only before the first scan)? You can specify an initial action by defining the macro @code{YY_USER_INIT} (though note that @code{yyout} may not be available at the time this macro is executed). Or you can add to the beginning of your rules section: @example @verbatim %% /* Must be indented! */ static int did_init = 0; if ( ! did_init ){ do_my_init(); did_init = 1; } @end verbatim @end example @node How do I execute code at termination? @unnumberedsec How do I execute code at termination? You can specify an action for the @code{<>} rule. @node Where else can I find help? @unnumberedsec Where else can I find help? You can find the flex homepage on the web at @uref{http://flex.sourceforge.net/}. See that page for details about flex mailing lists as well. @node Can I include comments in the "rules" section of the file? @unnumberedsec Can I include comments in the "rules" section of the file? Yes, just about anywhere you want to. See the manual for the specific syntax. @node I get an error about undefined yywrap(). @unnumberedsec I get an error about undefined yywrap(). You must supply a @code{yywrap()} function of your own, or link to @file{libfl.a} (which provides one), or use @example @verbatim %option noyywrap @end verbatim @end example in your source to say you don't want a @code{yywrap()} function. @node How can I change the matching pattern at run time? @unnumberedsec 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. @node How can I expand macros in the input? @unnumberedsec How can I expand macros in the input? The best way to approach this problem is at a higher level, e.g., in the parser. However, you can do this using multiple input buffers. @example @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); } <> { 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(); } @end verbatim @end example You probably will want a stack of expansion buffers to allow nested macros. From the above though hopefully the idea is clear. @node How can I build a two-pass scanner? @unnumberedsec How can I build a two-pass scanner? One way to do it is to filter the first pass to a temporary file, then process the temporary file on the second pass. You will probably see a performance hit, due to all the disk I/O. When you need to look ahead far forward like this, it almost always means that the right solution is to build a parse tree of the entire input, then walk it after the parse in order to generate the output. In a sense, this is a two-pass approach, once through the text and once through the parse tree, but the performance hit for the latter is usually an order of magnitude smaller, since everything is already classified, in binary format, and residing in memory. @node How do I match any string not matched in the preceding rules? @unnumberedsec 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 @code{flex} input wins, e.g., @example @verbatim %% foo[a-zA-Z_]+ return FOO_ID; bar[a-zA-Z_]+ return BAR_ID; [a-zA-Z_]+ return GENERIC_ID; @end verbatim @end example Note that the rule @code{[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 @code{flex} scanner will pick the first rule listed in your scanner as the one to match. @node I am trying to port code from AT&T lex that uses yysptr and yysbuf. @unnumberedsec 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 @code{input()} and @code{unput()} functions. If so, what you need to do is analyze those functions to figure out what they're doing, and then replace @code{input()} with an appropriate definition of @code{YY_INPUT}. You shouldn't need to (and must not) replace @code{flex}'s @code{unput()} function. @node Is there a way to make flex treat NULL like a regular character? @unnumberedsec Is there a way to make flex treat NULL like a regular character? Yes, @samp{\0} and @samp{\x00} should both do the trick. Perhaps you have an ancient version of @code{flex}. The latest release is version @value{VERSION}. @node Whenever flex can not match the input it says "flex scanner jammed". @unnumberedsec Whenever flex can not match the input it says "flex scanner jammed". You need to add a rule that matches the otherwise-unmatched text, e.g., @example @verbatim %option yylineno %% [[a bunch of rules here]] . printf("bad input character '%s' at line %d\n", yytext, yylineno); @end verbatim @end example See @code{%option default} for more information. @node Why doesn't flex have non-greedy operators like perl does? @unnumberedsec Why doesn't flex have non-greedy operators like perl does? A DFA can do a non-greedy match by stopping the first time it enters an accepting state, instead of consuming input until it determines that no further matching is possible (a ``jam'' state). This is actually easier to implement than longest leftmost match (which flex does). But it's also much less useful than longest leftmost match. In general, when you find yourself wishing for non-greedy matching, that's usually a 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. You might have a separate start state once you've seen the @samp{BEGIN}. In that state, you might then have a regex that will match @samp{END} (to kick you out of the state), and perhaps @samp{(.|\n)} to get a single character within the chunk ... This approach also has much better error-reporting properties. @node Memory leak - 16386 bytes allocated by malloc. @unnumberedsec Memory leak - 16386 bytes allocated by malloc. @anchor{faq-memory-leak} UPDATED 2002-07-10: As of @code{flex} version 2.5.9, this leak means that you did not call @code{yylex_destroy()}. If you are using an earlier version of @code{flex}, then read on. The leak is about 16426 bytes. That is, (8192 * 2 + 2) for the read-buffer, and about 40 for @code{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 @code{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 @code{yylex()}. If you want to reclaim the memory when you are completely done scanning, then you might try this: @example @verbatim /* For non-reentrant C scanner only. */ yy_delete_buffer(YY_CURRENT_BUFFER); yy_init = 1; @end verbatim @end example Note: @code{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. @node How do I track the byte offset for lseek()? @unnumberedsec How do I track the byte offset for lseek()? @example @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 @end verbatim @end example While this is the right idea, it has two problems. The first is that it's possible that @code{flex} will request less than @code{YY_READ_BUF_SIZE} during an invocation of @code{YY_INPUT} (or that your input source will return less even though @code{YY_READ_BUF_SIZE} bytes were requested). The second problem is that when refilling its internal buffer, @code{flex} keeps some characters from the previous buffer (because usually it's in the middle of a match, and needs those characters to construct @code{yytext} for the match once it's done). Because of this, @code{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 @code{YY_USER_ACTION}. For example, @example @verbatim #define YY_USER_ACTION num_chars += yyleng; @end verbatim @end example (You need to be careful to update your bookkeeping if you use @code{yymore(}), @code{yyless()}, @code{unput()}, or @code{input()}.) @node How do I use my own I/O classes in a C++ scanner? @section How do I use my own I/O classes in a C++ scanner? When the flex C++ scanning class rewrite finally happens, then this sort of thing should become much easier. @cindex LexerOutput, overriding @cindex LexerInput, overriding @cindex overriding LexerOutput @cindex overriding LexerInput @cindex customizing I/O in C++ scanners @cindex C++ I/O, customizing You can do this by passing the various functions (such as @code{LexerInput()} and @code{LexerOutput()}) NULL @code{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 @code{LexerInput()} and @code{LexerOutput}, which then do whatever is necessary with them. @c faq edit stopped here @node How do I skip as many chars as possible? @unnumberedsec How do I skip as many chars as possible? 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 @emph{NOT} work correctly (do you see why not?) @example @verbatim /* INCORRECT SCANNER */ %x SKIP %% startskip BEGIN(SKIP); ... "endskip" BEGIN(INITIAL); .* ; @end verbatim @end example The problem is that the pattern .* will eat up the word "endskip." The simplest (but slow) fix is: @example @verbatim "endskip" BEGIN(INITIAL); . ; @end verbatim @end example The fix involves making the second rule match more, without making it match "endskip" plus something else. So for example: @example @verbatim "endskip" BEGIN(INITIAL); [^e]+ ; . ;/* so you eat up e's, too */ @end verbatim @end example @c TODO: Evaluate this faq. @node deleteme00 @unnumberedsec deleteme00 @example @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 :-). @end verbatim @end example @c TODO: Evaluate this faq. @node Are certain equivalent patterns faster than others? @unnumberedsec Are certain equivalent patterns faster than others? @example @verbatim To: Adoram Rogel 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 [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: > {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: > {and}{bb}/{ROMAN}[^A-Za-z] { BEGIN... > > to the next 2 rules: > {and}{bb}/{ROMAN}[A-Za-z] { ECHO;} > {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 @end verbatim @end example @c TODO: Evaluate this faq. @node Is backing up a big deal? @unnumberedsec Is backing up a big deal? @example @verbatim To: Adoram Rogel 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 > 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. @end verbatim @end example @c TODO: Evaluate this faq. @node Can I fake multi-byte character support? @unnumberedsec Can I fake multi-byte character support? @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node deleteme01 @unnumberedsec deleteme01 @example @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 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 @end verbatim @end example @c TODO: Evaluate this faq. @node Can you discuss some flex internals? @unnumberedsec Can you discuss some flex internals? @example @verbatim To: Johan Linde 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unput() messes up yy_at_bol @unnumberedsec unput() messes up yy_at_bol @example @verbatim To: Xinying Li 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 > "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 @end verbatim @end example @c TODO: Evaluate this faq. @node The | operator is not doing what I want @unnumberedsec The | operator is not doing what I want @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node Why can't flex understand this variable trailing context pattern? @unnumberedsec Why can't flex understand this variable trailing context pattern? @example @verbatim To: Gregory Margo 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node The ^ operator isn't working @unnumberedsec The ^ operator isn't working @example @verbatim To: Thomas Hadig 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node Trailing context is getting confused with trailing optional patterns @unnumberedsec Trailing context is getting confused with trailing optional patterns @example @verbatim To: Adoram Rogel 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node Is flex GNU or not? @unnumberedsec Is flex GNU or not? @example @verbatim To: Cameron MacKinnon 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node ERASEME53 @unnumberedsec ERASEME53 @example @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 > [: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 @end verbatim @end example @c TODO: Evaluate this faq. @node I need to scan if-then-else blocks and while loops @unnumberedsec I need to scan if-then-else blocks and while loops @example @verbatim To: "Mike Stolnicki" 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node ERASEME55 @unnumberedsec ERASEME55 @example @verbatim To: Colin Paul Adams 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 > #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 @end verbatim @end example @c TODO: Evaluate this faq. @node ERASEME56 @unnumberedsec ERASEME56 @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node ERASEME57 @unnumberedsec ERASEME57 @example @verbatim To: "Marty Leisner" 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 > %% > [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 @end verbatim @end example @c TODO: Evaluate this faq. @node Is there a repository for flex scanners? @unnumberedsec Is there a repository for flex scanners? Not that we know of. You might try asking on comp.compilers. @c TODO: Evaluate this faq. @node How can I conditionally compile or preprocess my flex input file? @unnumberedsec How can I conditionally compile or preprocess my flex input file? Flex doesn't have a preprocessor like C does. You might try using m4, or the C preprocessor plus a sed script to clean up the result. @c TODO: Evaluate this faq. @node Where can I find grammars for lex and yacc? @unnumberedsec Where can I find grammars for lex and yacc? In the sources for flex and bison. @c TODO: Evaluate this faq. @node I get an end-of-buffer message for each character scanned. @unnumberedsec I get an end-of-buffer message for each character scanned. 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. @c TODO: Evaluate this faq. @node unnamed-faq-62 @unnumberedsec unnamed-faq-62 @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-63 @unnumberedsec unnamed-faq-63 @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-64 @unnumberedsec unnamed-faq-64 @example @verbatim To: Enda Fadian 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-65 @unnumberedsec unnamed-faq-65 @example @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 > /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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-66 @unnumberedsec unnamed-faq-66 @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-67 @unnumberedsec unnamed-faq-67 @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-68 @unnumberedsec unnamed-faq-68 @example @verbatim To: "Bart Niswonger" 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-69 @unnumberedsec unnamed-faq-69 @example @verbatim To: "Boris Zinin" 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-70 @unnumberedsec unnamed-faq-70 @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-71 @unnumberedsec unnamed-faq-71 @example @verbatim To: Vladimir Alexiev 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-72 @unnumberedsec unnamed-faq-72 @example @verbatim To: Barbara Denny 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-73 @unnumberedsec unnamed-faq-73 @example @verbatim To: Maurice Petrie 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-74 @unnumberedsec unnamed-faq-74 @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-75 @unnumberedsec unnamed-faq-75 @example @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 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 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-76 @unnumberedsec unnamed-faq-76 @example @verbatim To: "Frescatore, David (CRD, TAD)" 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-77 @unnumberedsec unnamed-faq-77 @example @verbatim To: "Hans Dermot Doran" 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-78 @unnumberedsec unnamed-faq-78 @example @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 > %{ > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-79 @unnumberedsec unnamed-faq-79 @example @verbatim To: Adoram Rogel 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 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-80 @unnumberedsec unnamed-faq-80 @example @verbatim To: "Schmackpfeffer, Craig" 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-81 @unnumberedsec unnamed-faq-81 @example @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 ; 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 ; 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 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-82 @unnumberedsec unnamed-faq-82 @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-83 @unnumberedsec unnamed-faq-83 @example @verbatim To: Jan Kort 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 > %% > > "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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-84 @unnumberedsec unnamed-faq-84 @example @verbatim To: Patrick Krusenotto 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-85 @unnumberedsec unnamed-faq-85 @example @verbatim To: Henric Jungheim 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 > 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 .* // put back .*, eat magic character This is off the top of my head, not sure it'll work. Vern @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-86 @unnumberedsec unnamed-faq-86 @example @verbatim To: "Repko, Billy D" 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-87 @unnumberedsec unnamed-faq-87 @example @verbatim To: Erick Branderhorst 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-88 @unnumberedsec unnamed-faq-88 @example @verbatim To: "Guido Minnen" 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-90 @unnumberedsec unnamed-faq-90 @example @verbatim To: "Dmitriy Goldobin" 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 > 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 , 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-91 @unnumberedsec unnamed-faq-91 @example @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 ; 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" Message-ID: 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. @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-92 @unnumberedsec unnamed-faq-92 @example @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 > However, I couldn't figure out how to access current > buffer (yy_current_buffer). Derive your own subclass from yyFlexLexer. Vern @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-93 @unnumberedsec unnamed-faq-93 @example @verbatim To: "Stones, Darren" 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-94 @unnumberedsec unnamed-faq-94 @example @verbatim To: Petr Danecek 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-95 @unnumberedsec unnamed-faq-95 @example @verbatim To: Tielman Koekemoer 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-96 @unnumberedsec unnamed-faq-96 @example @verbatim To: Tielman Koekemoer 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-97 @unnumberedsec unnamed-faq-97 @example @verbatim To: Sumanth Kamenani 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-98 @unnumberedsec unnamed-faq-98 @example @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 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-99 @unnumberedsec unnamed-faq-99 @example @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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-100 @unnumberedsec unnamed-faq-100 @example @verbatim To: Martin Gallwey 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 > 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 @end verbatim @end example @c TODO: Evaluate this faq. @node unnamed-faq-101 @unnumberedsec unnamed-faq-101 @example @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 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 @end verbatim @end example @node What is the difference between YYLEX_PARAM and YY_DECL? @unnumberedsec What is the difference between YYLEX_PARAM and YY_DECL? YYLEX_PARAM is not a flex symbol. It is for Bison. It tells Bison to pass extra params when it calls yylex() from the parser. YY_DECL is the Flex declaration of yylex. The default is similar to this: @example @verbatim #define int yy_lex () @end verbatim @end example @node Why do I get "conflicting types for yylex" error? @unnumberedsec Why do I get "conflicting types for yylex" error? This is a compiler error regarding a generated Bison parser, not a Flex scanner. It means you need a prototype of yylex() in the top of the Bison file. Be sure the prototype matches YY_DECL. @node How do I access the values set in a Flex action from within a Bison action? @unnumberedsec How do I access the values set in a Flex action from within a Bison action? With $1, $2, $3, etc. These are called "Semantic Values" in the Bison manual. See @ref{Top, , , bison, the GNU Bison Manual}. @node Appendices, Indices, FAQ, Top @appendix Appendices @menu * Makefiles and Flex:: * Bison Bridge:: * M4 Dependency:: * Common Patterns:: @end menu @node Makefiles and Flex, Bison Bridge, Appendices, Appendices @appendixsec Makefiles and Flex @cindex Makefile, syntax In this appendix, we provide tips for writing Makefiles to build your scanners. In a traditional build environment, we say that the @file{.c} files are the sources, and the @file{.o} files are the intermediate files. When using @code{flex}, however, the @file{.l} files are the sources, and the generated @file{.c} files (along with the @file{.o} files) are the intermediate files. This requires you to carefully plan your Makefile. Modern @command{make} programs understand that @file{foo.l} is intended to generate @file{lex.yy.c} or @file{foo.c}, and will behave accordingly@footnote{GNU @command{make} and GNU @command{automake} are two such programs that provide implicit rules for flex-generated scanners.}@footnote{GNU @command{automake} may generate code to execute flex in lex-compatible mode, or to stdout. If this is not what you want, then you should provide an explicit rule in your Makefile.am}. The following Makefile does not explicitly instruct @command{make} how to build @file{foo.c} from @file{foo.l}. Instead, it relies on the implicit rules of the @command{make} program to build the intermediate file, @file{scan.c}: @cindex Makefile, example of implicit rules @example @verbatim # Basic Makefile -- relies on implicit rules # Creates "myprogram" from "scan.l" and "myprogram.c" # LEX=flex myprogram: scan.o myprogram.o scan.o: scan.l @end verbatim @end example For simple cases, the above may be sufficient. For other cases, you may have to explicitly instruct @command{make} how to build your scanner. The following is an example of a Makefile containing explicit rules: @cindex Makefile, explicit example @example @verbatim # Basic Makefile -- provides explicit rules # Creates "myprogram" from "scan.l" and "myprogram.c" # LEX=flex myprogram: scan.o myprogram.o $(CC) -o $@ $(LDFLAGS) $^ myprogram.o: myprogram.c $(CC) $(CPPFLAGS) $(CFLAGS) -o $@ -c $^ scan.o: scan.c $(CC) $(CPPFLAGS) $(CFLAGS) -o $@ -c $^ scan.c: scan.l $(LEX) $(LFLAGS) -o $@ $^ clean: $(RM) *.o scan.c @end verbatim @end example Notice in the above example that @file{scan.c} is in the @code{clean} target. This is because we consider the file @file{scan.c} to be an intermediate file. Finally, we provide a realistic example of a @code{flex} scanner used with a @code{bison} parser@footnote{This example also applies to yacc parsers.}. There is a tricky problem we have to deal with. Since a @code{flex} scanner will typically include a header file (e.g., @file{y.tab.h}) generated by the parser, we need to be sure that the header file is generated BEFORE the scanner is compiled. We handle this case in the following example: @example @verbatim # Makefile example -- scanner and parser. # Creates "myprogram" from "scan.l", "parse.y", and "myprogram.c" # LEX = flex YACC = bison -y YFLAGS = -d objects = scan.o parse.o myprogram.o myprogram: $(objects) scan.o: scan.l parse.c parse.o: parse.y myprogram.o: myprogram.c @end verbatim @end example In the above example, notice the line, @example @verbatim scan.o: scan.l parse.c @end verbatim @end example , which lists the file @file{parse.c} (the generated parser) as a dependency of @file{scan.o}. We want to ensure that the parser is created before the scanner is compiled, and the above line seems to do the trick. Feel free to experiment with your specific implementation of @command{make}. For more details on writing Makefiles, see @ref{Top, , , make, The GNU Make Manual}. @node Bison Bridge, M4 Dependency, Makefiles and Flex, Appendices @section C Scanners with Bison Parsers @cindex bison, bridging with flex @vindex yylval @vindex yylloc @tindex YYLTYPE @tindex YYSTYPE This section describes the @code{flex} features useful when integrating @code{flex} with @code{GNU bison}@footnote{The features described here are purely optional, and are by no means the only way to use flex with bison. We merely provide some glue to ease development of your parser-scanner pair.}. Skip this section if you are not using @code{bison} with your scanner. Here we discuss only the @code{flex} half of the @code{flex} and @code{bison} pair. We do not discuss @code{bison} in any detail. For more information about generating @code{bison} parsers, see @ref{Top, , , bison, the GNU Bison Manual}. A compatible @code{bison} scanner is generated by declaring @samp{%option bison-bridge} or by supplying @samp{--bison-bridge} when invoking @code{flex} from the command line. This instructs @code{flex} that the macro @code{yylval} may be used. The data type for @code{yylval}, @code{YYSTYPE}, is typically defined in a header file, included in section 1 of the @code{flex} input file. For a list of functions and macros available, @xref{bison-functions}. The declaration of yylex becomes, @findex yylex (reentrant version) @example @verbatim int yylex ( YYSTYPE * lvalp, yyscan_t scanner ); @end verbatim @end example If @code{%option bison-locations} is specified, then the declaration becomes, @findex yylex (reentrant version) @example @verbatim int yylex ( YYSTYPE * lvalp, YYLTYPE * llocp, yyscan_t scanner ); @end verbatim @end example Note that the macros @code{yylval} and @code{yylloc} evaluate to pointers. Support for @code{yylloc} is optional in @code{bison}, so it is optional in @code{flex} as well. The following is an example of a @code{flex} scanner that is compatible with @code{bison}. @cindex bison, scanner to be called from bison @example @verbatim /* Scanner for "C" assignment statements... sort of. */ %{ #include "y.tab.h" /* Generated by bison. */ %} %option bison-bridge bison-locations % [[:digit:]]+ { yylval->num = atoi(yytext); return NUMBER;} [[:alnum:]]+ { yylval->str = strdup(yytext); return STRING;} "="|";" { return yytext[0];} . {} % @end verbatim @end example As you can see, there really is no magic here. We just use @code{yylval} as we would any other variable. The data type of @code{yylval} is generated by @code{bison}, and included in the file @file{y.tab.h}. Here is the corresponding @code{bison} parser: @cindex bison, parser @example @verbatim /* Parser to convert "C" assignments to lisp. */ %{ /* Pass the argument to yyparse through to yylex. */ #define YYPARSE_PARAM scanner #define YYLEX_PARAM scanner %} %locations %pure_parser %union { int num; char* str; } %token STRING %token NUMBER %% assignment: STRING '=' NUMBER ';' { printf( "(setf %s %d)", $1, $3 ); } ; @end verbatim @end example @node M4 Dependency, Common Patterns, Bison Bridge, Appendices @section M4 Dependency @cindex m4 The macro processor @code{m4}@footnote{The use of m4 is subject to change in future revisions of flex. It is not part of the public API of flex. Do not depend on it.} must be installed wherever flex is installed. @code{flex} invokes @samp{m4}, found by searching the directories in the @code{PATH} environment variable. Any code you place in section 1 or in the actions will be sent through m4. Please follow these rules to protect your code from unwanted @code{m4} processing. @itemize @item Do not use symbols that begin with, @samp{m4_}, such as, @samp{m4_define}, or @samp{m4_include}, since those are reserved for @code{m4} macro names. If for some reason you need m4_ as a prefix, use a preprocessor #define to get your symbol past m4 unmangled. @item Do not use the strings @samp{[[} or @samp{]]} anywhere in your code. The former is not valid in C, except within comments and strings, but the latter is valid in code such as @code{x[y[z]]}. The solution is simple. To get the literal string @code{"]]"}, use @code{"]""]"}. To get the array notation @code{x[y[z]]}, use @code{x[y[z] ]}. Flex will attempt to detect these sequences in user code, and escape them. However, it's best to avoid this complexity where possible, by removing such sequences from your code. @end itemize @code{m4} is only required at the time you run @code{flex}. The generated scanner is ordinary C or C++, and does @emph{not} require @code{m4}. @node Common Patterns, ,M4 Dependency, Appendices @section Common Patterns @cindex patterns, common This appendix provides examples of common regular expressions you might use in your scanner. @menu * Numbers:: * Identifiers:: * Quoted Constructs:: * Addresses:: @end menu @node Numbers, Identifiers, ,Common Patterns @subsection Numbers @table @asis @item C99 decimal constant @code{([[:digit:]]@{-@}[0])[[:digit:]]*} @item C99 hexadecimal constant @code{0[xX][[:xdigit:]]+} @item C99 octal constant @code{0[01234567]*} @item C99 floating point constant @verbatim {dseq} ([[:digit:]]+) {dseq_opt} ([[:digit:]]*) {frac} (({dseq_opt}"."{dseq})|{dseq}".") {exp} ([eE][+-]?{dseq}) {exp_opt} ({exp}?) {fsuff} [flFL] {fsuff_opt} ({fsuff}?) {hpref} (0[xX]) {hdseq} ([[:xdigit:]]+) {hdseq_opt} ([[:xdigit:]]*) {hfrac} (({hdseq_opt}"."{hdseq})|({hdseq}".")) {bexp} ([pP][+-]?{dseq}) {dfc} (({frac}{exp_opt}{fsuff_opt})|({dseq}{exp}{fsuff_opt})) {hfc} (({hpref}{hfrac}{bexp}{fsuff_opt})|({hpref}{hdseq}{bexp}{fsuff_opt})) {c99_floating_point_constant} ({dfc}|{hfc}) @end verbatim See C99 section 6.4.4.2 for the gory details. @end table @node Identifiers, Quoted Constructs, Numbers, Common Patterns @subsection Identifiers @table @asis @item C99 Identifier @verbatim ucn ((\\u([[:xdigit:]]{4}))|(\\U([[:xdigit:]]{8}))) nondigit [_[:alpha:]] c99_id ([_[:alpha:]]|{ucn})([_[:alnum:]]|{ucn})* @end verbatim Technically, the above pattern does not encompass all possible C99 identifiers, since C99 allows for "implementation-defined" characters. In practice, C compilers follow the above pattern, with the addition of the @samp{$} character. @item UTF-8 Encoded Unicode Code Point @verbatim [\x09\x0A\x0D\x20-\x7E]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF]([\x80-\xBF]{2})|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF]([\x80-\xBF]{2})|[\xF1-\xF3]([\x80-\xBF]{3})|\xF4[\x80-\x8F]([\x80-\xBF]{2}) @end verbatim @end table @node Quoted Constructs, Addresses, Identifiers, Common Patterns @subsection Quoted Constructs @table @asis @item C99 String Literal @code{L?\"([^\"\\\n]|(\\['\"?\\abfnrtv])|(\\([0123456]@{1,3@}))|(\\x[[:xdigit:]]+)|(\\u([[:xdigit:]]@{4@}))|(\\U([[:xdigit:]]@{8@})))*\"} @item C99 Comment @code{("/*"([^*]|"*"[^/])*"*/")|("/"(\\\n)*"/"[^\n]*)} Note that in C99, a @samp{//}-style comment may be split across lines, and, contrary to popular belief, does not include the trailing @samp{\n} character. A better way to scan @samp{/* */} comments is by line, rather than matching possibly huge comments all at once. This will allow you to scan comments of unlimited length, as long as line breaks appear at sane intervals. This is also more efficient when used with automatic line number processing. @xref{option-yylineno}. @verbatim { "/*" BEGIN(COMMENT); } { "*/" BEGIN(0); [^*\n]+ ; "*"[^/] ; \n ; } @end verbatim @end table @node Addresses, ,Quoted Constructs, Common Patterns @subsection Addresses @table @asis @item IPv4 Address @verbatim dec-octet [0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5] IPv4address {dec-octet}\.{dec-octet}\.{dec-octet}\.{dec-octet} @end verbatim @item IPv6 Address @verbatim h16 [0-9A-Fa-f]{1,4} ls32 {h16}:{h16}|{IPv4address} IPv6address ({h16}:){6}{ls32}| ::({h16}:){5}{ls32}| ({h16})?::({h16}:){4}{ls32}| (({h16}:){0,1}{h16})?::({h16}:){3}{ls32}| (({h16}:){0,2}{h16})?::({h16}:){2}{ls32}| (({h16}:){0,3}{h16})?::{h16}:{ls32}| (({h16}:){0,4}{h16})?::{ls32}| (({h16}:){0,5}{h16})?::{h16}| (({h16}:){0,6}{h16})?:: @end verbatim See @uref{http://www.ietf.org/rfc/rfc2373.txt, RFC 2373} for details. Note that you have to fold the definition of @code{IPv6address} into one line and that it also matches the ``unspecified address'' ``::''. @item URI @code{(([^:/?#]+):)?("//"([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?} This pattern is nearly useless, since it allows just about any character to appear in a URI, including spaces and control characters. See @uref{http://www.ietf.org/rfc/rfc2396.txt, RFC 2396} for details. @end table @node Indices, , Appendices, Top @unnumbered Indices @menu * Concept Index:: * Index of Functions and Macros:: * Index of Variables:: * Index of Data Types:: * Index of Hooks:: * Index of Scanner Options:: @end menu @node Concept Index, Index of Functions and Macros, Indices, Indices @unnumberedsec Concept Index @printindex cp @node Index of Functions and Macros, Index of Variables, Concept Index, Indices @unnumberedsec Index of Functions and Macros This is an index of functions and preprocessor macros that look like functions. For macros that expand to variables or constants, see @ref{Index of Variables}. @printindex fn @node Index of Variables, Index of Data Types, Index of Functions and Macros, Indices @unnumberedsec Index of Variables This is an index of variables, constants, and preprocessor macros that expand to variables or constants. @printindex vr @node Index of Data Types, Index of Hooks, Index of Variables, Indices @unnumberedsec Index of Data Types @printindex tp @node Index of Hooks, Index of Scanner Options, Index of Data Types, Indices @unnumberedsec Index of Hooks This is an index of "hooks" that the user may define. These hooks typically correspond to specific locations in the generated scanner, and may be used to insert arbitrary code. @printindex hk @node Index of Scanner Options, , Index of Hooks, Indices @unnumberedsec Index of Scanner Options @printindex op @c A vim script to name the faq entries. delete this when faqs are no longer @c named "unnamed-faq-XXX". @c @c fu! Faq2 () range abort @c let @r=input("Rename to: ") @c exe "%s/" . @w . "/" . @r . "/g" @c normal 'f @c endf @c nnoremap 1G/@node\s\+unnamed-faq-\d\+mfww"wy5ezt:call Faq2() @bye flex-2.6.0/doc/Makefile.am0000644000175000017500000000116512620677716015551 0ustar srivastasrivastahelp2man = @HELP2MAN@ info_TEXINFOS = flex.texi dist_man_MANS = flex.1 dist_doc_DATA= flex.pdf CLEANFILES = \ flex.aux \ flex.cp \ flex.cps \ flex.fn \ flex.fns \ flex.hk \ flex.hks \ flex.ky \ flex.log \ flex.op \ flex.ops \ flex.pg \ flex.toc \ flex.tp \ flex.tps \ flex.vr \ flex.vrs $(dist_man_MANS): $(top_srcdir)/configure.ac $(top_srcdir)/src/flex.skl $(top_srcdir)/src/options.c $(top_srcdir)/src/options.h for i in $(dist_man_MANS) ; do \ $(help2man) --name='$(PACKAGE_NAME)' \ --section=`echo $$i | sed -e 's/.*\.\([^.]*\)$$/\1/'` \ $(top_srcdir)/src/flex$(EXEEXT) > $$i || rm -f $$i ; \ done flex-2.6.0/src/0002755000175000017500000000000012651103361013516 5ustar srivastasrivastaflex-2.6.0/src/scanopt.c0000644000175000017500000004741612620474534015354 0ustar srivastasrivasta/* flex - tool to generate fast lexical analyzers */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" #include "scanopt.h" /* Internal structures */ #ifdef HAVE_STRCASECMP #define STRCASECMP(a,b) strcasecmp(a,b) #else static int STRCASECMP PROTO ((const char *, const char *)); static int STRCASECMP (a, b) const char *a; const char *b; { while (tolower ((unsigned char)*a++) == tolower ((unsigned char)*b++)) ; return b - a; } #endif #define ARG_NONE 0x01 #define ARG_REQ 0x02 #define ARG_OPT 0x04 #define IS_LONG 0x08 struct _aux { int flags; /* The above hex flags. */ int namelen; /* Length of the actual option word, e.g., "--file[=foo]" is 4 */ int printlen; /* Length of entire string, e.g., "--file[=foo]" is 12 */ }; struct _scanopt_t { const optspec_t *options; /* List of options. */ struct _aux *aux; /* Auxiliary data about options. */ int optc; /* Number of options. */ int argc; /* Number of args. */ char **argv; /* Array of strings. */ int index; /* Used as: argv[index][subscript]. */ int subscript; char no_err_msg; /* If true, do not print errors. */ char has_long; char has_short; }; /* Accessor functions. These WOULD be one-liners, but portability calls. */ static const char *NAME PROTO ((struct _scanopt_t *, int)); static int PRINTLEN PROTO ((struct _scanopt_t *, int)); static int RVAL PROTO ((struct _scanopt_t *, int)); static int FLAGS PROTO ((struct _scanopt_t *, int)); static const char *DESC PROTO ((struct _scanopt_t *, int)); static int scanopt_err PROTO ((struct _scanopt_t *, int, int)); static int matchlongopt PROTO ((char *, char **, int *, char **, int *)); static int find_opt PROTO ((struct _scanopt_t *, int, char *, int, int *, int *opt_offset)); static const char *NAME (s, i) struct _scanopt_t *s; int i; { return s->options[i].opt_fmt + ((s->aux[i].flags & IS_LONG) ? 2 : 1); } static int PRINTLEN (s, i) struct _scanopt_t *s; int i; { return s->aux[i].printlen; } static int RVAL (s, i) struct _scanopt_t *s; int i; { return s->options[i].r_val; } static int FLAGS (s, i) struct _scanopt_t *s; int i; { return s->aux[i].flags; } static const char *DESC (s, i) struct _scanopt_t *s; int i; { return s->options[i].desc ? s->options[i].desc : ""; } #ifndef NO_SCANOPT_USAGE static int get_cols PROTO ((void)); static int get_cols () { char *env; int cols = 80; /* default */ #ifdef HAVE_NCURSES_H initscr (); endwin (); if (COLS > 0) return COLS; #endif if ((env = getenv ("COLUMNS")) != NULL) cols = atoi (env); return cols; } #endif /* Macro to check for NULL before assigning a value. */ #define SAFE_ASSIGN(ptr,val) \ do{ \ if((ptr)!=NULL) \ *(ptr) = val; \ }while(0) /* Macro to assure we reset subscript whenever we adjust s->index.*/ #define INC_INDEX(s,n) \ do{ \ (s)->index += (n); \ (s)->subscript= 0; \ }while(0) scanopt_t *scanopt_init (options, argc, argv, flags) const optspec_t *options; int argc; char **argv; int flags; { int i; struct _scanopt_t *s; s = (struct _scanopt_t *) malloc (sizeof (struct _scanopt_t)); s->options = options; s->optc = 0; s->argc = argc; s->argv = (char **) argv; s->index = 1; s->subscript = 0; s->no_err_msg = (flags & SCANOPT_NO_ERR_MSG); s->has_long = 0; s->has_short = 0; /* Determine option count. (Find entry with all zeros). */ s->optc = 0; while (options[s->optc].opt_fmt || options[s->optc].r_val || options[s->optc].desc) s->optc++; /* Build auxiliary data */ s->aux = (struct _aux *) malloc (s->optc * sizeof (struct _aux)); for (i = 0; i < s->optc; i++) { const Char *p, *pname; const struct optspec_t *opt; struct _aux *aux; opt = s->options + i; aux = s->aux + i; aux->flags = ARG_NONE; if (opt->opt_fmt[0] == '-' && opt->opt_fmt[1] == '-') { aux->flags |= IS_LONG; pname = (const Char *)(opt->opt_fmt + 2); s->has_long = 1; } else { pname = (const Char *)(opt->opt_fmt + 1); s->has_short = 1; } aux->printlen = strlen (opt->opt_fmt); aux->namelen = 0; for (p = pname + 1; *p; p++) { /* detect required arg */ if (*p == '=' || isspace ((unsigned char)*p) || !(aux->flags & IS_LONG)) { if (aux->namelen == 0) aux->namelen = p - pname; aux->flags |= ARG_REQ; aux->flags &= ~ARG_NONE; } /* detect optional arg. This overrides required arg. */ if (*p == '[') { if (aux->namelen == 0) aux->namelen = p - pname; aux->flags &= ~(ARG_REQ | ARG_NONE); aux->flags |= ARG_OPT; break; } } if (aux->namelen == 0) aux->namelen = p - pname; } return (scanopt_t *) s; } #ifndef NO_SCANOPT_USAGE /* these structs are for scanopt_usage(). */ struct usg_elem { int idx; struct usg_elem *next; struct usg_elem *alias; }; typedef struct usg_elem usg_elem; /* Prints a usage message based on contents of optlist. * Parameters: * scanner - The scanner, already initialized with scanopt_init(). * fp - The file stream to write to. * usage - Text to be prepended to option list. * Return: Always returns 0 (zero). * The output looks something like this: [indent][option, alias1, alias2...][indent][description line1 description line2...] */ int scanopt_usage (scanner, fp, usage) scanopt_t *scanner; FILE *fp; const char *usage; { struct _scanopt_t *s; int i, columns, indent = 2; usg_elem *byr_val = NULL; /* option indices sorted by r_val */ usg_elem *store; /* array of preallocated elements. */ int store_idx = 0; usg_elem *ue; int maxlen[2]; int desccol = 0; int print_run = 0; maxlen[0] = 0; maxlen[1] = 0; s = (struct _scanopt_t *) scanner; if (usage) { fprintf (fp, "%s\n", usage); } else { /* Find the basename of argv[0] */ const char *p; p = s->argv[0] + strlen (s->argv[0]); while (p != s->argv[0] && *p != '/') --p; if (*p == '/') p++; fprintf (fp, _("Usage: %s [OPTIONS]...\n"), p); } fprintf (fp, "\n"); /* Sort by r_val and string. Yes, this is O(n*n), but n is small. */ store = (usg_elem *) malloc (s->optc * sizeof (usg_elem)); for (i = 0; i < s->optc; i++) { /* grab the next preallocate node. */ ue = store + store_idx++; ue->idx = i; ue->next = ue->alias = NULL; /* insert into list. */ if (!byr_val) byr_val = ue; else { int found_alias = 0; usg_elem **ue_curr, **ptr_if_no_alias = NULL; ue_curr = &byr_val; while (*ue_curr) { if (RVAL (s, (*ue_curr)->idx) == RVAL (s, ue->idx)) { /* push onto the alias list. */ ue_curr = &((*ue_curr)->alias); found_alias = 1; break; } if (!ptr_if_no_alias && STRCASECMP (NAME (s, (*ue_curr)->idx), NAME (s, ue->idx)) > 0) { ptr_if_no_alias = ue_curr; } ue_curr = &((*ue_curr)->next); } if (!found_alias && ptr_if_no_alias) ue_curr = ptr_if_no_alias; ue->next = *ue_curr; *ue_curr = ue; } } #if 0 if (1) { printf ("ORIGINAL:\n"); for (i = 0; i < s->optc; i++) printf ("%2d: %s\n", i, NAME (s, i)); printf ("SORTED:\n"); ue = byr_val; while (ue) { usg_elem *ue2; printf ("%2d: %s\n", ue->idx, NAME (s, ue->idx)); for (ue2 = ue->alias; ue2; ue2 = ue2->next) printf (" +---> %2d: %s\n", ue2->idx, NAME (s, ue2->idx)); ue = ue->next; } } #endif /* Now build each row of output. */ /* first pass calculate how much room we need. */ for (ue = byr_val; ue; ue = ue->next) { usg_elem *ap; int len = 0; int nshort = 0, nlong = 0; #define CALC_LEN(i) do {\ if(FLAGS(s,i) & IS_LONG) \ len += (nlong++||nshort) ? 2+PRINTLEN(s,i) : PRINTLEN(s,i);\ else\ len += (nshort++||nlong)? 2+PRINTLEN(s,i) : PRINTLEN(s,i);\ }while(0) if (!(FLAGS (s, ue->idx) & IS_LONG)) CALC_LEN (ue->idx); /* do short aliases first. */ for (ap = ue->alias; ap; ap = ap->next) { if (FLAGS (s, ap->idx) & IS_LONG) continue; CALC_LEN (ap->idx); } if (FLAGS (s, ue->idx) & IS_LONG) CALC_LEN (ue->idx); /* repeat the above loop, this time for long aliases. */ for (ap = ue->alias; ap; ap = ap->next) { if (!(FLAGS (s, ap->idx) & IS_LONG)) continue; CALC_LEN (ap->idx); } if (len > maxlen[0]) maxlen[0] = len; /* It's much easier to calculate length for description column! */ len = strlen (DESC (s, ue->idx)); if (len > maxlen[1]) maxlen[1] = len; } /* Determine how much room we have, and how much we will allocate to each col. * Do not address pathological cases. Output will just be ugly. */ columns = get_cols () - 1; if (maxlen[0] + maxlen[1] + indent * 2 > columns) { /* col 0 gets whatever it wants. we'll wrap the desc col. */ maxlen[1] = columns - (maxlen[0] + indent * 2); if (maxlen[1] < 14) /* 14 is arbitrary lower limit on desc width. */ maxlen[1] = INT_MAX; } desccol = maxlen[0] + indent * 2; #define PRINT_SPACES(fp,n)\ do{\ int _n;\ _n=(n);\ while(_n-- > 0)\ fputc(' ',(fp));\ }while(0) /* Second pass (same as above loop), this time we print. */ /* Sloppy hack: We iterate twice. The first time we print short and long options. The second time we print those lines that have ONLY long options. */ while (print_run++ < 2) { for (ue = byr_val; ue; ue = ue->next) { usg_elem *ap; int nwords = 0, nchars = 0, has_short = 0; /* TODO: get has_short schtick to work */ has_short = !(FLAGS (s, ue->idx) & IS_LONG); for (ap = ue->alias; ap; ap = ap->next) { if (!(FLAGS (s, ap->idx) & IS_LONG)) { has_short = 1; break; } } if ((print_run == 1 && !has_short) || (print_run == 2 && has_short)) continue; PRINT_SPACES (fp, indent); nchars += indent; /* Print, adding a ", " between aliases. */ #define PRINT_IT(i) do{\ if(nwords++)\ nchars+=fprintf(fp,", ");\ nchars+=fprintf(fp,"%s",s->options[i].opt_fmt);\ }while(0) if (!(FLAGS (s, ue->idx) & IS_LONG)) PRINT_IT (ue->idx); /* print short aliases first. */ for (ap = ue->alias; ap; ap = ap->next) { if (!(FLAGS (s, ap->idx) & IS_LONG)) PRINT_IT (ap->idx); } if (FLAGS (s, ue->idx) & IS_LONG) PRINT_IT (ue->idx); /* repeat the above loop, this time for long aliases. */ for (ap = ue->alias; ap; ap = ap->next) { if (FLAGS (s, ap->idx) & IS_LONG) PRINT_IT (ap->idx); } /* pad to desccol */ PRINT_SPACES (fp, desccol - nchars); /* Print description, wrapped to maxlen[1] columns. */ if (1) { const char *pstart; pstart = DESC (s, ue->idx); while (1) { int n = 0; const char *lastws = NULL, *p; p = pstart; while (*p && n < maxlen[1] && *p != '\n') { if (isspace ((unsigned char)(*p)) || *p == '-') lastws = p; n++; p++; } if (!*p) { /* hit end of desc. done. */ fprintf (fp, "%s\n", pstart); break; } else if (*p == '\n') { /* print everything up to here then wrap. */ fprintf (fp, "%.*s\n", n, pstart); PRINT_SPACES (fp, desccol); pstart = p + 1; continue; } else { /* we hit the edge of the screen. wrap at space if possible. */ if (lastws) { fprintf (fp, "%.*s\n", (int)(lastws - pstart), pstart); pstart = lastws + 1; } else { fprintf (fp, "%.*s\n", n, pstart); pstart = p + 1; } PRINT_SPACES (fp, desccol); continue; } } } } } /* end while */ free (store); return 0; } #endif /* no scanopt_usage */ static int scanopt_err (s, is_short, err) struct _scanopt_t *s; int is_short; int err; { const char *optname = ""; char optchar[2]; if (!s->no_err_msg) { if (s->index > 0 && s->index < s->argc) { if (is_short) { optchar[0] = s->argv[s->index][s->subscript]; optchar[1] = '\0'; optname = optchar; } else { optname = s->argv[s->index]; } } fprintf (stderr, "%s: ", s->argv[0]); switch (err) { case SCANOPT_ERR_ARG_NOT_ALLOWED: fprintf (stderr, _ ("option `%s' doesn't allow an argument\n"), optname); break; case SCANOPT_ERR_ARG_NOT_FOUND: fprintf (stderr, _("option `%s' requires an argument\n"), optname); break; case SCANOPT_ERR_OPT_AMBIGUOUS: fprintf (stderr, _("option `%s' is ambiguous\n"), optname); break; case SCANOPT_ERR_OPT_UNRECOGNIZED: fprintf (stderr, _("Unrecognized option `%s'\n"), optname); break; default: fprintf (stderr, _("Unknown error=(%d)\n"), err); break; } } return err; } /* Internal. Match str against the regex ^--([^=]+)(=(.*))? * return 1 if *looks* like a long option. * 'str' is the only input argument, the rest of the arguments are output only. * optname will point to str + 2 * */ static int matchlongopt (str, optname, optlen, arg, arglen) char *str; char **optname; int *optlen; char **arg; int *arglen; { char *p; *optname = *arg = (char *) 0; *optlen = *arglen = 0; /* Match regex /--./ */ p = str; if (p[0] != '-' || p[1] != '-' || !p[2]) return 0; p += 2; *optname = (char *) p; /* find the end of optname */ while (*p && *p != '=') ++p; *optlen = p - *optname; if (!*p) /* an option with no '=...' part. */ return 1; /* We saw an '=' char. The rest of p is the arg. */ p++; *arg = p; while (*p) ++p; *arglen = p - *arg; return 1; } /* Internal. Look up long or short option by name. * Long options must match a non-ambiguous prefix, or exact match. * Short options must be exact. * Return boolean true if found and no error. * Error stored in err_code or zero if no error. */ static int find_opt (s, lookup_long, optstart, len, err_code, opt_offset) struct _scanopt_t *s; int lookup_long; char *optstart; int len; int *err_code; int *opt_offset; { int nmatch = 0, lastr_val = 0, i; *err_code = 0; *opt_offset = -1; if (!optstart) return 0; for (i = 0; i < s->optc; i++) { char *optname; optname = (char *) (s->options[i].opt_fmt + (lookup_long ? 2 : 1)); if (lookup_long && (s->aux[i].flags & IS_LONG)) { if (len > s->aux[i].namelen) continue; if (strncmp (optname, optstart, len) == 0) { nmatch++; *opt_offset = i; /* exact match overrides all. */ if (len == s->aux[i].namelen) { nmatch = 1; break; } /* ambiguity is ok between aliases. */ if (lastr_val && lastr_val == s->options[i].r_val) nmatch--; lastr_val = s->options[i].r_val; } } else if (!lookup_long && !(s->aux[i].flags & IS_LONG)) { if (optname[0] == optstart[0]) { nmatch++; *opt_offset = i; } } } if (nmatch == 0) { *err_code = SCANOPT_ERR_OPT_UNRECOGNIZED; *opt_offset = -1; } else if (nmatch > 1) { *err_code = SCANOPT_ERR_OPT_AMBIGUOUS; *opt_offset = -1; } return *err_code ? 0 : 1; } int scanopt (svoid, arg, optindex) scanopt_t *svoid; char **arg; int *optindex; { char *optname = NULL, *optarg = NULL, *pstart; int namelen = 0, arglen = 0; int errcode = 0, has_next; const optspec_t *optp; struct _scanopt_t *s; struct _aux *auxp; int is_short; int opt_offset = -1; s = (struct _scanopt_t *) svoid; /* Normalize return-parameters. */ SAFE_ASSIGN (arg, NULL); SAFE_ASSIGN (optindex, s->index); if (s->index >= s->argc) return 0; /* pstart always points to the start of our current scan. */ pstart = s->argv[s->index] + s->subscript; if (!pstart) return 0; if (s->subscript == 0) { /* test for exact match of "--" */ if (pstart[0] == '-' && pstart[1] == '-' && !pstart[2]) { SAFE_ASSIGN (optindex, s->index + 1); INC_INDEX (s, 1); return 0; } /* Match an opt. */ if (matchlongopt (pstart, &optname, &namelen, &optarg, &arglen)) { /* it LOOKS like an opt, but is it one?! */ if (!find_opt (s, 1, optname, namelen, &errcode, &opt_offset)) { scanopt_err (s, 0, errcode); return errcode; } /* We handle this below. */ is_short = 0; /* Check for short opt. */ } else if (pstart[0] == '-' && pstart[1]) { /* Pass through to below. */ is_short = 1; s->subscript++; pstart++; } else { /* It's not an option. We're done. */ return 0; } } /* We have to re-check the subscript status because it * may have changed above. */ if (s->subscript != 0) { /* we are somewhere in a run of short opts, * e.g., at the 'z' in `tar -xzf` */ optname = pstart; namelen = 1; is_short = 1; if (!find_opt (s, 0, pstart, namelen, &errcode, &opt_offset)) { return scanopt_err (s, 1, errcode); } optarg = pstart + 1; if (!*optarg) { optarg = NULL; arglen = 0; } else arglen = strlen (optarg); } /* At this point, we have a long or short option matched at opt_offset into * the s->options array (and corresponding aux array). * A trailing argument is in {optarg,arglen}, if any. */ /* Look ahead in argv[] to see if there is something * that we can use as an argument (if needed). */ has_next = s->index + 1 < s->argc && strcmp ("--", s->argv[s->index + 1]) != 0; optp = s->options + opt_offset; auxp = s->aux + opt_offset; /* case: no args allowed */ if (auxp->flags & ARG_NONE) { if (optarg && !is_short) { scanopt_err (s, is_short, errcode = SCANOPT_ERR_ARG_NOT_ALLOWED); INC_INDEX (s, 1); return errcode; } else if (!optarg) INC_INDEX (s, 1); else s->subscript++; return optp->r_val; } /* case: required */ if (auxp->flags & ARG_REQ) { if (!optarg && !has_next) return scanopt_err (s, is_short, SCANOPT_ERR_ARG_NOT_FOUND); if (!optarg) { /* Let the next argv element become the argument. */ SAFE_ASSIGN (arg, s->argv[s->index + 1]); INC_INDEX (s, 2); } else { SAFE_ASSIGN (arg, (char *) optarg); INC_INDEX (s, 1); } return optp->r_val; } /* case: optional */ if (auxp->flags & ARG_OPT) { SAFE_ASSIGN (arg, optarg); INC_INDEX (s, 1); return optp->r_val; } /* Should not reach here. */ return 0; } int scanopt_destroy (svoid) scanopt_t *svoid; { struct _scanopt_t *s; s = (struct _scanopt_t *) svoid; if (s) { if (s->aux) free (s->aux); free (s); } return 0; } /* vim:set tabstop=8 softtabstop=4 shiftwidth=4: */ flex-2.6.0/src/tblcmp.c0000644000175000017500000005536612620472752015171 0ustar srivastasrivasta/* tblcmp - table compression routines */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" /* declarations for functions that have forward references */ void mkentry PROTO ((int *, int, int, int, int)); void mkprot PROTO ((int[], int, int)); void mktemplate PROTO ((int[], int, int)); void mv2front PROTO ((int)); int tbldiff PROTO ((int[], int, int[])); /* bldtbl - build table entries for dfa state * * synopsis * int state[numecs], statenum, totaltrans, comstate, comfreq; * bldtbl( state, statenum, totaltrans, comstate, comfreq ); * * State is the statenum'th dfa state. It is indexed by equivalence class and * gives the number of the state to enter for a given equivalence class. * totaltrans is the total number of transitions out of the state. Comstate * is that state which is the destination of the most transitions out of State. * Comfreq is how many transitions there are out of State to Comstate. * * A note on terminology: * "protos" are transition tables which have a high probability of * either being redundant (a state processed later will have an identical * transition table) or nearly redundant (a state processed later will have * many of the same out-transitions). A "most recently used" queue of * protos is kept around with the hope that most states will find a proto * which is similar enough to be usable, and therefore compacting the * output tables. * "templates" are a special type of proto. If a transition table is * homogeneous or nearly homogeneous (all transitions go to the same * destination) then the odds are good that future states will also go * to the same destination state on basically the same character set. * These homogeneous states are so common when dealing with large rule * sets that they merit special attention. If the transition table were * simply made into a proto, then (typically) each subsequent, similar * state will differ from the proto for two out-transitions. One of these * out-transitions will be that character on which the proto does not go * to the common destination, and one will be that character on which the * state does not go to the common destination. Templates, on the other * hand, go to the common state on EVERY transition character, and therefore * cost only one difference. */ void bldtbl (state, statenum, totaltrans, comstate, comfreq) int state[], statenum, totaltrans, comstate, comfreq; { int extptr, extrct[2][CSIZE + 1]; int mindiff, minprot, i, d; /* If extptr is 0 then the first array of extrct holds the result * of the "best difference" to date, which is those transitions * which occur in "state" but not in the proto which, to date, * has the fewest differences between itself and "state". If * extptr is 1 then the second array of extrct hold the best * difference. The two arrays are toggled between so that the * best difference to date can be kept around and also a difference * just created by checking against a candidate "best" proto. */ extptr = 0; /* If the state has too few out-transitions, don't bother trying to * compact its tables. */ if ((totaltrans * 100) < (numecs * PROTO_SIZE_PERCENTAGE)) mkentry (state, numecs, statenum, JAMSTATE, totaltrans); else { /* "checkcom" is true if we should only check "state" against * protos which have the same "comstate" value. */ int checkcom = comfreq * 100 > totaltrans * CHECK_COM_PERCENTAGE; minprot = firstprot; mindiff = totaltrans; if (checkcom) { /* Find first proto which has the same "comstate". */ for (i = firstprot; i != NIL; i = protnext[i]) if (protcomst[i] == comstate) { minprot = i; mindiff = tbldiff (state, minprot, extrct[extptr]); break; } } else { /* Since we've decided that the most common destination * out of "state" does not occur with a high enough * frequency, we set the "comstate" to zero, assuring * that if this state is entered into the proto list, * it will not be considered a template. */ comstate = 0; if (firstprot != NIL) { minprot = firstprot; mindiff = tbldiff (state, minprot, extrct[extptr]); } } /* We now have the first interesting proto in "minprot". If * it matches within the tolerances set for the first proto, * we don't want to bother scanning the rest of the proto list * to see if we have any other reasonable matches. */ if (mindiff * 100 > totaltrans * FIRST_MATCH_DIFF_PERCENTAGE) { /* Not a good enough match. Scan the rest of the * protos. */ for (i = minprot; i != NIL; i = protnext[i]) { d = tbldiff (state, i, extrct[1 - extptr]); if (d < mindiff) { extptr = 1 - extptr; mindiff = d; minprot = i; } } } /* Check if the proto we've decided on as our best bet is close * enough to the state we want to match to be usable. */ if (mindiff * 100 > totaltrans * ACCEPTABLE_DIFF_PERCENTAGE) { /* No good. If the state is homogeneous enough, * we make a template out of it. Otherwise, we * make a proto. */ if (comfreq * 100 >= totaltrans * TEMPLATE_SAME_PERCENTAGE) mktemplate (state, statenum, comstate); else { mkprot (state, statenum, comstate); mkentry (state, numecs, statenum, JAMSTATE, totaltrans); } } else { /* use the proto */ mkentry (extrct[extptr], numecs, statenum, prottbl[minprot], mindiff); /* If this state was sufficiently different from the * proto we built it from, make it, too, a proto. */ if (mindiff * 100 >= totaltrans * NEW_PROTO_DIFF_PERCENTAGE) mkprot (state, statenum, comstate); /* Since mkprot added a new proto to the proto queue, * it's possible that "minprot" is no longer on the * proto queue (if it happened to have been the last * entry, it would have been bumped off). If it's * not there, then the new proto took its physical * place (though logically the new proto is at the * beginning of the queue), so in that case the * following call will do nothing. */ mv2front (minprot); } } } /* cmptmps - compress template table entries * * Template tables are compressed by using the 'template equivalence * classes', which are collections of transition character equivalence * classes which always appear together in templates - really meta-equivalence * classes. */ void cmptmps () { int tmpstorage[CSIZE + 1]; int *tmp = tmpstorage, i, j; int totaltrans, trans; peakpairs = numtemps * numecs + tblend; if (usemecs) { /* Create equivalence classes based on data gathered on * template transitions. */ nummecs = cre8ecs (tecfwd, tecbck, numecs); } else nummecs = numecs; while (lastdfa + numtemps + 1 >= current_max_dfas) increase_max_dfas (); /* Loop through each template. */ for (i = 1; i <= numtemps; ++i) { /* Number of non-jam transitions out of this template. */ totaltrans = 0; for (j = 1; j <= numecs; ++j) { trans = tnxt[numecs * i + j]; if (usemecs) { /* The absolute value of tecbck is the * meta-equivalence class of a given * equivalence class, as set up by cre8ecs(). */ if (tecbck[j] > 0) { tmp[tecbck[j]] = trans; if (trans > 0) ++totaltrans; } } else { tmp[j] = trans; if (trans > 0) ++totaltrans; } } /* It is assumed (in a rather subtle way) in the skeleton * that if we're using meta-equivalence classes, the def[] * entry for all templates is the jam template, i.e., * templates never default to other non-jam table entries * (e.g., another template) */ /* Leave room for the jam-state after the last real state. */ mkentry (tmp, nummecs, lastdfa + i + 1, JAMSTATE, totaltrans); } } /* expand_nxt_chk - expand the next check arrays */ void expand_nxt_chk () { int old_max = current_max_xpairs; current_max_xpairs += MAX_XPAIRS_INCREMENT; ++num_reallocs; nxt = reallocate_integer_array (nxt, current_max_xpairs); chk = reallocate_integer_array (chk, current_max_xpairs); zero_out ((char *) (chk + old_max), (size_t) (MAX_XPAIRS_INCREMENT * sizeof (int))); } /* find_table_space - finds a space in the table for a state to be placed * * synopsis * int *state, numtrans, block_start; * int find_table_space(); * * block_start = find_table_space( state, numtrans ); * * State is the state to be added to the full speed transition table. * Numtrans is the number of out-transitions for the state. * * find_table_space() returns the position of the start of the first block (in * chk) able to accommodate the state * * In determining if a state will or will not fit, find_table_space() must take * into account the fact that an end-of-buffer state will be added at [0], * and an action number will be added in [-1]. */ int find_table_space (state, numtrans) int *state, numtrans; { /* Firstfree is the position of the first possible occurrence of two * consecutive unused records in the chk and nxt arrays. */ int i; int *state_ptr, *chk_ptr; int *ptr_to_last_entry_in_state; /* If there are too many out-transitions, put the state at the end of * nxt and chk. */ if (numtrans > MAX_XTIONS_FULL_INTERIOR_FIT) { /* If table is empty, return the first available spot in * chk/nxt, which should be 1. */ if (tblend < 2) return 1; /* Start searching for table space near the end of * chk/nxt arrays. */ i = tblend - numecs; } else /* Start searching for table space from the beginning * (skipping only the elements which will definitely not * hold the new state). */ i = firstfree; while (1) { /* loops until a space is found */ while (i + numecs >= current_max_xpairs) expand_nxt_chk (); /* Loops until space for end-of-buffer and action number * are found. */ while (1) { /* Check for action number space. */ if (chk[i - 1] == 0) { /* Check for end-of-buffer space. */ if (chk[i] == 0) break; else /* Since i != 0, there is no use * checking to see if (++i) - 1 == 0, * because that's the same as i == 0, * so we skip a space. */ i += 2; } else ++i; while (i + numecs >= current_max_xpairs) expand_nxt_chk (); } /* If we started search from the beginning, store the new * firstfree for the next call of find_table_space(). */ if (numtrans <= MAX_XTIONS_FULL_INTERIOR_FIT) firstfree = i + 1; /* Check to see if all elements in chk (and therefore nxt) * that are needed for the new state have not yet been taken. */ state_ptr = &state[1]; ptr_to_last_entry_in_state = &chk[i + numecs + 1]; for (chk_ptr = &chk[i + 1]; chk_ptr != ptr_to_last_entry_in_state; ++chk_ptr) if (*(state_ptr++) != 0 && *chk_ptr != 0) break; if (chk_ptr == ptr_to_last_entry_in_state) return i; else ++i; } } /* inittbl - initialize transition tables * * Initializes "firstfree" to be one beyond the end of the table. Initializes * all "chk" entries to be zero. */ void inittbl () { int i; zero_out ((char *) chk, (size_t) (current_max_xpairs * sizeof (int))); tblend = 0; firstfree = tblend + 1; numtemps = 0; if (usemecs) { /* Set up doubly-linked meta-equivalence classes; these * are sets of equivalence classes which all have identical * transitions out of TEMPLATES. */ tecbck[1] = NIL; for (i = 2; i <= numecs; ++i) { tecbck[i] = i - 1; tecfwd[i - 1] = i; } tecfwd[numecs] = NIL; } } /* mkdeftbl - make the default, "jam" table entries */ void mkdeftbl () { int i; jamstate = lastdfa + 1; ++tblend; /* room for transition on end-of-buffer character */ while (tblend + numecs >= current_max_xpairs) expand_nxt_chk (); /* Add in default end-of-buffer transition. */ nxt[tblend] = end_of_buffer_state; chk[tblend] = jamstate; for (i = 1; i <= numecs; ++i) { nxt[tblend + i] = 0; chk[tblend + i] = jamstate; } jambase = tblend; base[jamstate] = jambase; def[jamstate] = 0; tblend += numecs; ++numtemps; } /* mkentry - create base/def and nxt/chk entries for transition array * * synopsis * int state[numchars + 1], numchars, statenum, deflink, totaltrans; * mkentry( state, numchars, statenum, deflink, totaltrans ); * * "state" is a transition array "numchars" characters in size, "statenum" * is the offset to be used into the base/def tables, and "deflink" is the * entry to put in the "def" table entry. If "deflink" is equal to * "JAMSTATE", then no attempt will be made to fit zero entries of "state" * (i.e., jam entries) into the table. It is assumed that by linking to * "JAMSTATE" they will be taken care of. In any case, entries in "state" * marking transitions to "SAME_TRANS" are treated as though they will be * taken care of by whereever "deflink" points. "totaltrans" is the total * number of transitions out of the state. If it is below a certain threshold, * the tables are searched for an interior spot that will accommodate the * state array. */ void mkentry (state, numchars, statenum, deflink, totaltrans) int *state; int numchars, statenum, deflink, totaltrans; { int minec, maxec, i, baseaddr; int tblbase, tbllast; if (totaltrans == 0) { /* there are no out-transitions */ if (deflink == JAMSTATE) base[statenum] = JAMSTATE; else base[statenum] = 0; def[statenum] = deflink; return; } for (minec = 1; minec <= numchars; ++minec) { if (state[minec] != SAME_TRANS) if (state[minec] != 0 || deflink != JAMSTATE) break; } if (totaltrans == 1) { /* There's only one out-transition. Save it for later to fill * in holes in the tables. */ stack1 (statenum, minec, state[minec], deflink); return; } for (maxec = numchars; maxec > 0; --maxec) { if (state[maxec] != SAME_TRANS) if (state[maxec] != 0 || deflink != JAMSTATE) break; } /* Whether we try to fit the state table in the middle of the table * entries we have already generated, or if we just take the state * table at the end of the nxt/chk tables, we must make sure that we * have a valid base address (i.e., non-negative). Note that * negative base addresses dangerous at run-time (because indexing * the nxt array with one and a low-valued character will access * memory before the start of the array. */ /* Find the first transition of state that we need to worry about. */ if (totaltrans * 100 <= numchars * INTERIOR_FIT_PERCENTAGE) { /* Attempt to squeeze it into the middle of the tables. */ baseaddr = firstfree; while (baseaddr < minec) { /* Using baseaddr would result in a negative base * address below; find the next free slot. */ for (++baseaddr; chk[baseaddr] != 0; ++baseaddr) ; } while (baseaddr + maxec - minec + 1 >= current_max_xpairs) expand_nxt_chk (); for (i = minec; i <= maxec; ++i) if (state[i] != SAME_TRANS && (state[i] != 0 || deflink != JAMSTATE) && chk[baseaddr + i - minec] != 0) { /* baseaddr unsuitable - find another */ for (++baseaddr; baseaddr < current_max_xpairs && chk[baseaddr] != 0; ++baseaddr) ; while (baseaddr + maxec - minec + 1 >= current_max_xpairs) expand_nxt_chk (); /* Reset the loop counter so we'll start all * over again next time it's incremented. */ i = minec - 1; } } else { /* Ensure that the base address we eventually generate is * non-negative. */ baseaddr = MAX (tblend + 1, minec); } tblbase = baseaddr - minec; tbllast = tblbase + maxec; while (tbllast + 1 >= current_max_xpairs) expand_nxt_chk (); base[statenum] = tblbase; def[statenum] = deflink; for (i = minec; i <= maxec; ++i) if (state[i] != SAME_TRANS) if (state[i] != 0 || deflink != JAMSTATE) { nxt[tblbase + i] = state[i]; chk[tblbase + i] = statenum; } if (baseaddr == firstfree) /* Find next free slot in tables. */ for (++firstfree; chk[firstfree] != 0; ++firstfree) ; tblend = MAX (tblend, tbllast); } /* mk1tbl - create table entries for a state (or state fragment) which * has only one out-transition */ void mk1tbl (state, sym, onenxt, onedef) int state, sym, onenxt, onedef; { if (firstfree < sym) firstfree = sym; while (chk[firstfree] != 0) if (++firstfree >= current_max_xpairs) expand_nxt_chk (); base[state] = firstfree - sym; def[state] = onedef; chk[firstfree] = state; nxt[firstfree] = onenxt; if (firstfree > tblend) { tblend = firstfree++; if (firstfree >= current_max_xpairs) expand_nxt_chk (); } } /* mkprot - create new proto entry */ void mkprot (state, statenum, comstate) int state[], statenum, comstate; { int i, slot, tblbase; if (++numprots >= MSP || numecs * numprots >= PROT_SAVE_SIZE) { /* Gotta make room for the new proto by dropping last entry in * the queue. */ slot = lastprot; lastprot = protprev[lastprot]; protnext[lastprot] = NIL; } else slot = numprots; protnext[slot] = firstprot; if (firstprot != NIL) protprev[firstprot] = slot; firstprot = slot; prottbl[slot] = statenum; protcomst[slot] = comstate; /* Copy state into save area so it can be compared with rapidly. */ tblbase = numecs * (slot - 1); for (i = 1; i <= numecs; ++i) protsave[tblbase + i] = state[i]; } /* mktemplate - create a template entry based on a state, and connect the state * to it */ void mktemplate (state, statenum, comstate) int state[], statenum, comstate; { int i, numdiff, tmpbase, tmp[CSIZE + 1]; Char transset[CSIZE + 1]; int tsptr; ++numtemps; tsptr = 0; /* Calculate where we will temporarily store the transition table * of the template in the tnxt[] array. The final transition table * gets created by cmptmps(). */ tmpbase = numtemps * numecs; if (tmpbase + numecs >= current_max_template_xpairs) { current_max_template_xpairs += MAX_TEMPLATE_XPAIRS_INCREMENT; ++num_reallocs; tnxt = reallocate_integer_array (tnxt, current_max_template_xpairs); } for (i = 1; i <= numecs; ++i) if (state[i] == 0) tnxt[tmpbase + i] = 0; else { transset[tsptr++] = i; tnxt[tmpbase + i] = comstate; } if (usemecs) mkeccl (transset, tsptr, tecfwd, tecbck, numecs, 0); mkprot (tnxt + tmpbase, -numtemps, comstate); /* We rely on the fact that mkprot adds things to the beginning * of the proto queue. */ numdiff = tbldiff (state, firstprot, tmp); mkentry (tmp, numecs, statenum, -numtemps, numdiff); } /* mv2front - move proto queue element to front of queue */ void mv2front (qelm) int qelm; { if (firstprot != qelm) { if (qelm == lastprot) lastprot = protprev[lastprot]; protnext[protprev[qelm]] = protnext[qelm]; if (protnext[qelm] != NIL) protprev[protnext[qelm]] = protprev[qelm]; protprev[qelm] = NIL; protnext[qelm] = firstprot; protprev[firstprot] = qelm; firstprot = qelm; } } /* place_state - place a state into full speed transition table * * State is the statenum'th state. It is indexed by equivalence class and * gives the number of the state to enter for a given equivalence class. * Transnum is the number of out-transitions for the state. */ void place_state (state, statenum, transnum) int *state, statenum, transnum; { int i; int *state_ptr; int position = find_table_space (state, transnum); /* "base" is the table of start positions. */ base[statenum] = position; /* Put in action number marker; this non-zero number makes sure that * find_table_space() knows that this position in chk/nxt is taken * and should not be used for another accepting number in another * state. */ chk[position - 1] = 1; /* Put in end-of-buffer marker; this is for the same purposes as * above. */ chk[position] = 1; /* Place the state into chk and nxt. */ state_ptr = &state[1]; for (i = 1; i <= numecs; ++i, ++state_ptr) if (*state_ptr != 0) { chk[position + i] = i; nxt[position + i] = *state_ptr; } if (position + numecs > tblend) tblend = position + numecs; } /* stack1 - save states with only one out-transition to be processed later * * If there's room for another state on the "one-transition" stack, the * state is pushed onto it, to be processed later by mk1tbl. If there's * no room, we process the sucker right now. */ void stack1 (statenum, sym, nextstate, deflink) int statenum, sym, nextstate, deflink; { if (onesp >= ONE_STACK_SIZE - 1) mk1tbl (statenum, sym, nextstate, deflink); else { ++onesp; onestate[onesp] = statenum; onesym[onesp] = sym; onenext[onesp] = nextstate; onedef[onesp] = deflink; } } /* tbldiff - compute differences between two state tables * * "state" is the state array which is to be extracted from the pr'th * proto. "pr" is both the number of the proto we are extracting from * and an index into the save area where we can find the proto's complete * state table. Each entry in "state" which differs from the corresponding * entry of "pr" will appear in "ext". * * Entries which are the same in both "state" and "pr" will be marked * as transitions to "SAME_TRANS" in "ext". The total number of differences * between "state" and "pr" is returned as function value. Note that this * number is "numecs" minus the number of "SAME_TRANS" entries in "ext". */ int tbldiff (state, pr, ext) int state[], pr, ext[]; { int i, *sp = state, *ep = ext, *protp; int numdiff = 0; protp = &protsave[numecs * (pr - 1)]; for (i = numecs; i > 0; --i) { if (*++protp == *++sp) *++ep = SAME_TRANS; else { *++ep = *sp; ++numdiff; } } return numdiff; } flex-2.6.0/src/flexint.h0000644000175000017500000000272612620472752015356 0ustar srivastasrivasta/* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have . Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ flex-2.6.0/src/nfa.c0000644000175000017500000004347612620472752014453 0ustar srivastasrivasta/* nfa - NFA construction routines */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" /* declare functions that have forward references */ int dupmachine PROTO ((int)); void mkxtion PROTO ((int, int)); /* add_accept - add an accepting state to a machine * * accepting_number becomes mach's accepting number. */ void add_accept (mach, accepting_number) int mach, accepting_number; { /* Hang the accepting number off an epsilon state. if it is associated * with a state that has a non-epsilon out-transition, then the state * will accept BEFORE it makes that transition, i.e., one character * too soon. */ if (transchar[finalst[mach]] == SYM_EPSILON) accptnum[finalst[mach]] = accepting_number; else { int astate = mkstate (SYM_EPSILON); accptnum[astate] = accepting_number; (void) link_machines (mach, astate); } } /* copysingl - make a given number of copies of a singleton machine * * synopsis * * newsng = copysingl( singl, num ); * * newsng - a new singleton composed of num copies of singl * singl - a singleton machine * num - the number of copies of singl to be present in newsng */ int copysingl (singl, num) int singl, num; { int copy, i; copy = mkstate (SYM_EPSILON); for (i = 1; i <= num; ++i) copy = link_machines (copy, dupmachine (singl)); return copy; } /* dumpnfa - debugging routine to write out an nfa */ void dumpnfa (state1) int state1; { int sym, tsp1, tsp2, anum, ns; fprintf (stderr, _ ("\n\n********** beginning dump of nfa with start state %d\n"), state1); /* We probably should loop starting at firstst[state1] and going to * lastst[state1], but they're not maintained properly when we "or" * all of the rules together. So we use our knowledge that the machine * starts at state 1 and ends at lastnfa. */ /* for ( ns = firstst[state1]; ns <= lastst[state1]; ++ns ) */ for (ns = 1; ns <= lastnfa; ++ns) { fprintf (stderr, _("state # %4d\t"), ns); sym = transchar[ns]; tsp1 = trans1[ns]; tsp2 = trans2[ns]; anum = accptnum[ns]; fprintf (stderr, "%3d: %4d, %4d", sym, tsp1, tsp2); if (anum != NIL) fprintf (stderr, " [%d]", anum); fprintf (stderr, "\n"); } fprintf (stderr, _("********** end of dump\n")); } /* dupmachine - make a duplicate of a given machine * * synopsis * * copy = dupmachine( mach ); * * copy - holds duplicate of mach * mach - machine to be duplicated * * note that the copy of mach is NOT an exact duplicate; rather, all the * transition states values are adjusted so that the copy is self-contained, * as the original should have been. * * also note that the original MUST be contiguous, with its low and high * states accessible by the arrays firstst and lastst */ int dupmachine (mach) int mach; { int i, init, state_offset; int state = 0; int last = lastst[mach]; for (i = firstst[mach]; i <= last; ++i) { state = mkstate (transchar[i]); if (trans1[i] != NO_TRANSITION) { mkxtion (finalst[state], trans1[i] + state - i); if (transchar[i] == SYM_EPSILON && trans2[i] != NO_TRANSITION) mkxtion (finalst[state], trans2[i] + state - i); } accptnum[state] = accptnum[i]; } if (state == 0) flexfatal (_("empty machine in dupmachine()")); state_offset = state - i + 1; init = mach + state_offset; firstst[init] = firstst[mach] + state_offset; finalst[init] = finalst[mach] + state_offset; lastst[init] = lastst[mach] + state_offset; return init; } /* finish_rule - finish up the processing for a rule * * An accepting number is added to the given machine. If variable_trail_rule * is true then the rule has trailing context and both the head and trail * are variable size. Otherwise if headcnt or trailcnt is non-zero then * the machine recognizes a pattern with trailing context and headcnt is * the number of characters in the matched part of the pattern, or zero * if the matched part has variable length. trailcnt is the number of * trailing context characters in the pattern, or zero if the trailing * context has variable length. */ void finish_rule (mach, variable_trail_rule, headcnt, trailcnt, pcont_act) int mach, variable_trail_rule, headcnt, trailcnt, pcont_act; { char action_text[MAXLINE]; add_accept (mach, num_rules); /* We did this in new_rule(), but it often gets the wrong * number because we do it before we start parsing the current rule. */ rule_linenum[num_rules] = linenum; /* If this is a continued action, then the line-number has already * been updated, giving us the wrong number. */ if (continued_action) --rule_linenum[num_rules]; /* If the previous rule was continued action, then we inherit the * previous newline flag, possibly overriding the current one. */ if (pcont_act && rule_has_nl[num_rules - 1]) rule_has_nl[num_rules] = true; snprintf (action_text, sizeof(action_text), "case %d:\n", num_rules); add_action (action_text); if (rule_has_nl[num_rules]) { snprintf (action_text, sizeof(action_text), "/* rule %d can match eol */\n", num_rules); add_action (action_text); } if (variable_trail_rule) { rule_type[num_rules] = RULE_VARIABLE; if (performance_report > 0) fprintf (stderr, _ ("Variable trailing context rule at line %d\n"), rule_linenum[num_rules]); variable_trailing_context_rules = true; } else { rule_type[num_rules] = RULE_NORMAL; if (headcnt > 0 || trailcnt > 0) { /* Do trailing context magic to not match the trailing * characters. */ char *scanner_cp = "YY_G(yy_c_buf_p) = yy_cp"; char *scanner_bp = "yy_bp"; add_action ("*yy_cp = YY_G(yy_hold_char); /* undo effects of setting up yytext */\n"); if (headcnt > 0) { if (rule_has_nl[num_rules]) { snprintf (action_text, sizeof(action_text), "YY_LINENO_REWIND_TO(%s + %d);\n", scanner_bp, headcnt); add_action (action_text); } snprintf (action_text, sizeof(action_text), "%s = %s + %d;\n", scanner_cp, scanner_bp, headcnt); add_action (action_text); } else { if (rule_has_nl[num_rules]) { snprintf (action_text, sizeof(action_text), "YY_LINENO_REWIND_TO(yy_cp - %d);\n", trailcnt); add_action (action_text); } snprintf (action_text, sizeof(action_text), "%s -= %d;\n", scanner_cp, trailcnt); add_action (action_text); } add_action ("YY_DO_BEFORE_ACTION; /* set up yytext again */\n"); } } /* Okay, in the action code at this point yytext and yyleng have * their proper final values for this rule, so here's the point * to do any user action. But don't do it for continued actions, * as that'll result in multiple YY_RULE_SETUP's. */ if (!continued_action) add_action ("YY_RULE_SETUP\n"); line_directive_out ((FILE *) 0, 1); } /* link_machines - connect two machines together * * synopsis * * new = link_machines( first, last ); * * new - a machine constructed by connecting first to last * first - the machine whose successor is to be last * last - the machine whose predecessor is to be first * * note: this routine concatenates the machine first with the machine * last to produce a machine new which will pattern-match first first * and then last, and will fail if either of the sub-patterns fails. * FIRST is set to new by the operation. last is unmolested. */ int link_machines (first, last) int first, last; { if (first == NIL) return last; else if (last == NIL) return first; else { mkxtion (finalst[first], last); finalst[first] = finalst[last]; lastst[first] = MAX (lastst[first], lastst[last]); firstst[first] = MIN (firstst[first], firstst[last]); return first; } } /* mark_beginning_as_normal - mark each "beginning" state in a machine * as being a "normal" (i.e., not trailing context- * associated) states * * The "beginning" states are the epsilon closure of the first state */ void mark_beginning_as_normal (mach) int mach; { switch (state_type[mach]) { case STATE_NORMAL: /* Oh, we've already visited here. */ return; case STATE_TRAILING_CONTEXT: state_type[mach] = STATE_NORMAL; if (transchar[mach] == SYM_EPSILON) { if (trans1[mach] != NO_TRANSITION) mark_beginning_as_normal (trans1[mach]); if (trans2[mach] != NO_TRANSITION) mark_beginning_as_normal (trans2[mach]); } break; default: flexerror (_ ("bad state type in mark_beginning_as_normal()")); break; } } /* mkbranch - make a machine that branches to two machines * * synopsis * * branch = mkbranch( first, second ); * * branch - a machine which matches either first's pattern or second's * first, second - machines whose patterns are to be or'ed (the | operator) * * Note that first and second are NEITHER destroyed by the operation. Also, * the resulting machine CANNOT be used with any other "mk" operation except * more mkbranch's. Compare with mkor() */ int mkbranch (first, second) int first, second; { int eps; if (first == NO_TRANSITION) return second; else if (second == NO_TRANSITION) return first; eps = mkstate (SYM_EPSILON); mkxtion (eps, first); mkxtion (eps, second); return eps; } /* mkclos - convert a machine into a closure * * synopsis * new = mkclos( state ); * * new - a new state which matches the closure of "state" */ int mkclos (state) int state; { return mkopt (mkposcl (state)); } /* mkopt - make a machine optional * * synopsis * * new = mkopt( mach ); * * new - a machine which optionally matches whatever mach matched * mach - the machine to make optional * * notes: * 1. mach must be the last machine created * 2. mach is destroyed by the call */ int mkopt (mach) int mach; { int eps; if (!SUPER_FREE_EPSILON (finalst[mach])) { eps = mkstate (SYM_EPSILON); mach = link_machines (mach, eps); } /* Can't skimp on the following if FREE_EPSILON(mach) is true because * some state interior to "mach" might point back to the beginning * for a closure. */ eps = mkstate (SYM_EPSILON); mach = link_machines (eps, mach); mkxtion (mach, finalst[mach]); return mach; } /* mkor - make a machine that matches either one of two machines * * synopsis * * new = mkor( first, second ); * * new - a machine which matches either first's pattern or second's * first, second - machines whose patterns are to be or'ed (the | operator) * * note that first and second are both destroyed by the operation * the code is rather convoluted because an attempt is made to minimize * the number of epsilon states needed */ int mkor (first, second) int first, second; { int eps, orend; if (first == NIL) return second; else if (second == NIL) return first; else { /* See comment in mkopt() about why we can't use the first * state of "first" or "second" if they satisfy "FREE_EPSILON". */ eps = mkstate (SYM_EPSILON); first = link_machines (eps, first); mkxtion (first, second); if (SUPER_FREE_EPSILON (finalst[first]) && accptnum[finalst[first]] == NIL) { orend = finalst[first]; mkxtion (finalst[second], orend); } else if (SUPER_FREE_EPSILON (finalst[second]) && accptnum[finalst[second]] == NIL) { orend = finalst[second]; mkxtion (finalst[first], orend); } else { eps = mkstate (SYM_EPSILON); first = link_machines (first, eps); orend = finalst[first]; mkxtion (finalst[second], orend); } } finalst[first] = orend; return first; } /* mkposcl - convert a machine into a positive closure * * synopsis * new = mkposcl( state ); * * new - a machine matching the positive closure of "state" */ int mkposcl (state) int state; { int eps; if (SUPER_FREE_EPSILON (finalst[state])) { mkxtion (finalst[state], state); return state; } else { eps = mkstate (SYM_EPSILON); mkxtion (eps, state); return link_machines (state, eps); } } /* mkrep - make a replicated machine * * synopsis * new = mkrep( mach, lb, ub ); * * new - a machine that matches whatever "mach" matched from "lb" * number of times to "ub" number of times * * note * if "ub" is INFINITE_REPEAT then "new" matches "lb" or more occurrences of "mach" */ int mkrep (mach, lb, ub) int mach, lb, ub; { int base_mach, tail, copy, i; base_mach = copysingl (mach, lb - 1); if (ub == INFINITE_REPEAT) { copy = dupmachine (mach); mach = link_machines (mach, link_machines (base_mach, mkclos (copy))); } else { tail = mkstate (SYM_EPSILON); for (i = lb; i < ub; ++i) { copy = dupmachine (mach); tail = mkopt (link_machines (copy, tail)); } mach = link_machines (mach, link_machines (base_mach, tail)); } return mach; } /* mkstate - create a state with a transition on a given symbol * * synopsis * * state = mkstate( sym ); * * state - a new state matching sym * sym - the symbol the new state is to have an out-transition on * * note that this routine makes new states in ascending order through the * state array (and increments LASTNFA accordingly). The routine DUPMACHINE * relies on machines being made in ascending order and that they are * CONTIGUOUS. Change it and you will have to rewrite DUPMACHINE (kludge * that it admittedly is) */ int mkstate (sym) int sym; { if (++lastnfa >= current_mns) { if ((current_mns += MNS_INCREMENT) >= maximum_mns) lerr(_ ("input rules are too complicated (>= %d NFA states)"), current_mns); ++num_reallocs; firstst = reallocate_integer_array (firstst, current_mns); lastst = reallocate_integer_array (lastst, current_mns); finalst = reallocate_integer_array (finalst, current_mns); transchar = reallocate_integer_array (transchar, current_mns); trans1 = reallocate_integer_array (trans1, current_mns); trans2 = reallocate_integer_array (trans2, current_mns); accptnum = reallocate_integer_array (accptnum, current_mns); assoc_rule = reallocate_integer_array (assoc_rule, current_mns); state_type = reallocate_integer_array (state_type, current_mns); } firstst[lastnfa] = lastnfa; finalst[lastnfa] = lastnfa; lastst[lastnfa] = lastnfa; transchar[lastnfa] = sym; trans1[lastnfa] = NO_TRANSITION; trans2[lastnfa] = NO_TRANSITION; accptnum[lastnfa] = NIL; assoc_rule[lastnfa] = num_rules; state_type[lastnfa] = current_state_type; /* Fix up equivalence classes base on this transition. Note that any * character which has its own transition gets its own equivalence * class. Thus only characters which are only in character classes * have a chance at being in the same equivalence class. E.g. "a|b" * puts 'a' and 'b' into two different equivalence classes. "[ab]" * puts them in the same equivalence class (barring other differences * elsewhere in the input). */ if (sym < 0) { /* We don't have to update the equivalence classes since * that was already done when the ccl was created for the * first time. */ } else if (sym == SYM_EPSILON) ++numeps; else { check_char (sym); if (useecs) /* Map NUL's to csize. */ mkechar (sym ? sym : csize, nextecm, ecgroup); } return lastnfa; } /* mkxtion - make a transition from one state to another * * synopsis * * mkxtion( statefrom, stateto ); * * statefrom - the state from which the transition is to be made * stateto - the state to which the transition is to be made */ void mkxtion (statefrom, stateto) int statefrom, stateto; { if (trans1[statefrom] == NO_TRANSITION) trans1[statefrom] = stateto; else if ((transchar[statefrom] != SYM_EPSILON) || (trans2[statefrom] != NO_TRANSITION)) flexfatal (_("found too many transitions in mkxtion()")); else { /* second out-transition for an epsilon state */ ++eps2; trans2[statefrom] = stateto; } } /* new_rule - initialize for a new rule */ void new_rule () { if (++num_rules >= current_max_rules) { ++num_reallocs; current_max_rules += MAX_RULES_INCREMENT; rule_type = reallocate_integer_array (rule_type, current_max_rules); rule_linenum = reallocate_integer_array (rule_linenum, current_max_rules); rule_useful = reallocate_integer_array (rule_useful, current_max_rules); rule_has_nl = reallocate_bool_array (rule_has_nl, current_max_rules); } if (num_rules > MAX_RULE) lerr (_("too many rules (> %d)!"), MAX_RULE); rule_linenum[num_rules] = linenum; rule_useful[num_rules] = false; rule_has_nl[num_rules] = false; } flex-2.6.0/src/yylex.c0000644000175000017500000001007712620472752015050 0ustar srivastasrivasta/* yylex - scanner front-end for flex */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include #include "flexdef.h" #include "parse.h" /* yylex - scan for a regular expression token */ extern char *yytext; int yylex (void) { int toktype; static int beglin = false; if (eofseen) toktype = EOF; else toktype = flexscan (); if (toktype == EOF || toktype == 0) { eofseen = 1; if (sectnum == 1) { synerr (_("premature EOF")); sectnum = 2; toktype = SECTEND; } else toktype = 0; } if (trace) { if (beglin) { fprintf (stderr, "%d\t", num_rules + 1); beglin = 0; } switch (toktype) { case '<': case '>': case '^': case '$': case '"': case '[': case ']': case '{': case '}': case '|': case '(': case ')': case '-': case '/': case '\\': case '?': case '.': case '*': case '+': case ',': (void) putc (toktype, stderr); break; case '\n': (void) putc ('\n', stderr); if (sectnum == 2) beglin = 1; break; case SCDECL: fputs ("%s", stderr); break; case XSCDECL: fputs ("%x", stderr); break; case SECTEND: fputs ("%%\n", stderr); /* We set beglin to be true so we'll start * writing out numbers as we echo rules. * flexscan() has already assigned sectnum. */ if (sectnum == 2) beglin = 1; break; case NAME: fprintf (stderr, "'%s'", nmstr); break; case CHAR: switch (yylval) { case '<': case '>': case '^': case '$': case '"': case '[': case ']': case '{': case '}': case '|': case '(': case ')': case '-': case '/': case '\\': case '?': case '.': case '*': case '+': case ',': fprintf (stderr, "\\%c", yylval); break; default: if (!isascii (yylval) || !isprint (yylval)) { if(trace_hex) fprintf (stderr, "\\x%02x", (unsigned int) yylval); else fprintf (stderr, "\\%.3o", (unsigned int) yylval); } else (void) putc (yylval, stderr); break; } break; case NUMBER: fprintf (stderr, "%d", yylval); break; case PREVCCL: fprintf (stderr, "[%d]", yylval); break; case EOF_OP: fprintf (stderr, "<>"); break; case OPTION_OP: fprintf (stderr, "%s ", yytext); break; case OPT_OUTFILE: case OPT_PREFIX: case CCE_ALNUM: case CCE_ALPHA: case CCE_BLANK: case CCE_CNTRL: case CCE_DIGIT: case CCE_GRAPH: case CCE_LOWER: case CCE_PRINT: case CCE_PUNCT: case CCE_SPACE: case CCE_UPPER: case CCE_XDIGIT: fprintf (stderr, "%s", yytext); break; case 0: fprintf (stderr, _("End Marker\n")); break; default: fprintf (stderr, _ ("*Something Weird* - tok: %d val: %d\n"), toktype, yylval); break; } } return toktype; } flex-2.6.0/src/tables_shared.h0000644000175000017500000001200012620472752016467 0ustar srivastasrivasta#ifdef FLEX_SCANNER /* dnl tables_shared.h - tables serialization header dnl dnl Copyright (c) 1990 The Regents of the University of California. dnl All rights reserved. dnl dnl This code is derived from software contributed to Berkeley by dnl Vern Paxson. dnl dnl The United States Government has rights in this work pursuant dnl to contract no. DE-AC03-76SF00098 between the United States dnl Department of Energy and the University of California. dnl dnl This file is part of flex. dnl dnl Redistribution and use in source and binary forms, with or without dnl modification, are permitted provided that the following conditions dnl are met: dnl dnl 1. Redistributions of source code must retain the above copyright dnl notice, this list of conditions and the following disclaimer. dnl 2. Redistributions in binary form must reproduce the above copyright dnl notice, this list of conditions and the following disclaimer in the dnl documentation and/or other materials provided with the distribution. dnl dnl Neither the name of the University nor the names of its contributors dnl may be used to endorse or promote products derived from this software dnl without specific prior written permission. dnl dnl THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR dnl IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED dnl WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR dnl PURPOSE. dnl dnl This file is meant to be included in both the skeleton and the actual dnl flex code (hence the name "_shared"). */ #ifndef yyskel_static #define yyskel_static static #endif #else #ifndef yyskel_static #define yyskel_static #endif #endif /* Structures and prototypes for serializing flex tables. The * binary format is documented in the manual. * * Design considerations: * * - The format allows many tables per file. * - The tables can be streamed. * - All data is stored in network byte order. * - We do not hinder future unicode support. * - We can lookup tables by name. */ /** Magic number for serialized format. */ #ifndef YYTBL_MAGIC #define YYTBL_MAGIC 0xF13C57B1 #endif /** Calculate (0-7) = number bytes needed to pad n to next 64-bit boundary. */ #ifndef yypad64 #define yypad64(n) ((8-((n)%8))%8) #endif #ifndef YYTABLES_TYPES #define YYTABLES_TYPES /** Possible values for td_id field. Each one corresponds to a * scanner table of the same name. */ enum yytbl_id { YYTD_ID_ACCEPT = 0x01, /**< 1-dim ints */ YYTD_ID_BASE = 0x02, /**< 1-dim ints */ YYTD_ID_CHK = 0x03, /**< 1-dim ints */ YYTD_ID_DEF = 0x04, /**< 1-dim ints */ YYTD_ID_EC = 0x05, /**< 1-dim ints */ YYTD_ID_META = 0x06, /**< 1-dim ints */ YYTD_ID_NUL_TRANS = 0x07, /**< 1-dim ints, maybe indices */ YYTD_ID_NXT = 0x08, /**< may be 2 dimensional ints */ YYTD_ID_RULE_CAN_MATCH_EOL = 0x09, /**< 1-dim ints */ YYTD_ID_START_STATE_LIST = 0x0A, /**< 1-dim indices into trans tbl */ YYTD_ID_TRANSITION = 0x0B, /**< structs */ YYTD_ID_ACCLIST = 0x0C /**< 1-dim ints */ }; /** bit flags for t_flags field of struct yytbl_data */ enum yytbl_flags { /* These first three are mutually exclusive */ YYTD_DATA8 = 0x01, /**< data is an array of type flex_int8_t */ YYTD_DATA16 = 0x02, /**< data is an array of type flex_int16_t */ YYTD_DATA32 = 0x04, /**< data is an array of type flex_int32_t */ /* These two are mutually exclusive. */ YYTD_PTRANS = 0x08, /**< data is a list of indexes of entries into the expanded `yy_transition' array. See notes in manual. */ YYTD_STRUCT = 0x10 /**< data consists of yy_trans_info structs */ }; /* The serialized tables header. */ struct yytbl_hdr { flex_uint32_t th_magic; /**< Must be 0xF13C57B1 (comes from "Flex Table") */ flex_uint32_t th_hsize; /**< Size of this header in bytes. */ flex_uint32_t th_ssize; /**< Size of this dataset, in bytes, including header. */ flex_uint16_t th_flags; /**< Currently unused, must be 0 */ char *th_version; /**< Flex version string. NUL terminated. */ char *th_name; /**< The name of this table set. NUL terminated. */ }; /** A single serialized table */ struct yytbl_data { flex_uint16_t td_id; /**< enum yytbl_id table identifier */ flex_uint16_t td_flags; /**< how to interpret this data */ flex_uint32_t td_hilen; /**< num elements in highest dimension array */ flex_uint32_t td_lolen; /**< num elements in lowest dimension array */ void *td_data; /**< table data */ }; #endif /** Extract corresponding data size_t from td_flags */ #ifndef YYTDFLAGS2BYTES #define YYTDFLAGS2BYTES(td_flags)\ (((td_flags) & YYTD_DATA8)\ ? sizeof(flex_int8_t)\ :(((td_flags) & YYTD_DATA16)\ ? sizeof(flex_int16_t)\ :sizeof(flex_int32_t))) #endif #ifdef FLEX_SCANNER %not-for-header #endif yyskel_static flex_int32_t yytbl_calc_total_len (const struct yytbl_data *tbl); #ifdef FLEX_SCANNER %ok-for-header #endif /* vim:set noexpandtab cindent tabstop=8 softtabstop=0 shiftwidth=8 textwidth=0: */ flex-2.6.0/src/flexdef.h0000644000175000017500000012467012620472752015325 0ustar srivastasrivasta /* flexdef - definitions file for flex */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #ifndef FLEXDEF_H #define FLEXDEF_H 1 #ifdef HAVE_CONFIG_H #include #endif /* AIX requires this to be the first thing in the file. */ #if !defined(__GNUC__) && !defined(__lint__) # if HAVE_ALLOCA_H # include # else # ifdef _AIX #pragma alloca # else # ifndef alloca /* predefined by HP cc +Olibcalls */ char *alloca (); # endif # endif # endif #endif #ifdef STDC_HEADERS #include #include #include #include #include #include #include #endif #ifdef HAVE_ASSERT_H #include #else #define assert(Pred) #endif #ifdef HAVE_LIMITS_H #include #endif #ifdef HAVE_UNISTD_H #include #endif #ifdef HAVE_NETINET_IN_H #include #endif #ifdef HAVE_SYS_PARAMS_H #include #endif #ifdef HAVE_SYS_WAIT_H #include #endif #ifdef HAVE_STDBOOL_H #include #else #define bool int #define true 1 #define false 0 #endif #ifdef HAVE_REGEX_H #include #endif #include "flexint.h" /* We use gettext. So, when we write strings which should be translated, we mark them with _() */ #ifdef ENABLE_NLS #ifdef HAVE_LOCALE_H #include #endif /* HAVE_LOCALE_H */ #include "gettext.h" #define _(String) gettext (String) #else #define _(STRING) STRING #endif /* ENABLE_NLS */ /* Always be prepared to generate an 8-bit scanner. */ #define CSIZE 256 #define Char unsigned char /* Size of input alphabet - should be size of ASCII set. */ #ifndef DEFAULT_CSIZE #define DEFAULT_CSIZE 128 #endif #ifndef PROTO #if defined(__STDC__) #define PROTO(proto) proto #else #define PROTO(proto) () #endif #endif #ifdef VMS #ifndef __VMS_POSIX #define unlink remove #define SHORT_FILE_NAMES #endif #endif #ifdef MS_DOS #define SHORT_FILE_NAMES #endif /* Maximum line length we'll have to deal with. */ #define MAXLINE 2048 #ifndef MIN #define MIN(x,y) ((x) < (y) ? (x) : (y)) #endif #ifndef MAX #define MAX(x,y) ((x) > (y) ? (x) : (y)) #endif #ifndef ABS #define ABS(x) ((x) < 0 ? -(x) : (x)) #endif /* ANSI C does not guarantee that isascii() is defined */ #ifndef isascii #define isascii(c) ((c) <= 0177) #endif #define unspecified -1 /* Special chk[] values marking the slots taking by end-of-buffer and action * numbers. */ #define EOB_POSITION -1 #define ACTION_POSITION -2 /* Number of data items per line for -f output. */ #define NUMDATAITEMS 10 /* Number of lines of data in -f output before inserting a blank line for * readability. */ #define NUMDATALINES 10 /* transition_struct_out() definitions. */ #define TRANS_STRUCT_PRINT_LENGTH 14 /* Returns true if an nfa state has an epsilon out-transition slot * that can be used. This definition is currently not used. */ #define FREE_EPSILON(state) \ (transchar[state] == SYM_EPSILON && \ trans2[state] == NO_TRANSITION && \ finalst[state] != state) /* Returns true if an nfa state has an epsilon out-transition character * and both slots are free */ #define SUPER_FREE_EPSILON(state) \ (transchar[state] == SYM_EPSILON && \ trans1[state] == NO_TRANSITION) \ /* Maximum number of NFA states that can comprise a DFA state. It's real * big because if there's a lot of rules, the initial state will have a * huge epsilon closure. */ #define INITIAL_MAX_DFA_SIZE 750 #define MAX_DFA_SIZE_INCREMENT 750 /* A note on the following masks. They are used to mark accepting numbers * as being special. As such, they implicitly limit the number of accepting * numbers (i.e., rules) because if there are too many rules the rule numbers * will overload the mask bits. Fortunately, this limit is \large/ (0x2000 == * 8192) so unlikely to actually cause any problems. A check is made in * new_rule() to ensure that this limit is not reached. */ /* Mask to mark a trailing context accepting number. */ #define YY_TRAILING_MASK 0x2000 /* Mask to mark the accepting number of the "head" of a trailing context * rule. */ #define YY_TRAILING_HEAD_MASK 0x4000 /* Maximum number of rules, as outlined in the above note. */ #define MAX_RULE (YY_TRAILING_MASK - 1) /* NIL must be 0. If not, its special meaning when making equivalence classes * (it marks the representative of a given e.c.) will be unidentifiable. */ #define NIL 0 #define JAM -1 /* to mark a missing DFA transition */ #define NO_TRANSITION NIL #define UNIQUE -1 /* marks a symbol as an e.c. representative */ #define INFINITE_REPEAT -1 /* for x{5,} constructions */ #define INITIAL_MAX_CCLS 100 /* max number of unique character classes */ #define MAX_CCLS_INCREMENT 100 /* Size of table holding members of character classes. */ #define INITIAL_MAX_CCL_TBL_SIZE 500 #define MAX_CCL_TBL_SIZE_INCREMENT 250 #define INITIAL_MAX_RULES 100 /* default maximum number of rules */ #define MAX_RULES_INCREMENT 100 #define INITIAL_MNS 2000 /* default maximum number of nfa states */ #define MNS_INCREMENT 1000 /* amount to bump above by if it's not enough */ #define INITIAL_MAX_DFAS 1000 /* default maximum number of dfa states */ #define MAX_DFAS_INCREMENT 1000 #define JAMSTATE -32766 /* marks a reference to the state that always jams */ /* Maximum number of NFA states. */ #define MAXIMUM_MNS 31999 #define MAXIMUM_MNS_LONG 1999999999 /* Enough so that if it's subtracted from an NFA state number, the result * is guaranteed to be negative. */ #define MARKER_DIFFERENCE (maximum_mns+2) /* Maximum number of nxt/chk pairs for non-templates. */ #define INITIAL_MAX_XPAIRS 2000 #define MAX_XPAIRS_INCREMENT 2000 /* Maximum number of nxt/chk pairs needed for templates. */ #define INITIAL_MAX_TEMPLATE_XPAIRS 2500 #define MAX_TEMPLATE_XPAIRS_INCREMENT 2500 #define SYM_EPSILON (CSIZE + 1) /* to mark transitions on the symbol epsilon */ #define INITIAL_MAX_SCS 40 /* maximum number of start conditions */ #define MAX_SCS_INCREMENT 40 /* amount to bump by if it's not enough */ #define ONE_STACK_SIZE 500 /* stack of states with only one out-transition */ #define SAME_TRANS -1 /* transition is the same as "default" entry for state */ /* The following percentages are used to tune table compression: * The percentage the number of out-transitions a state must be of the * number of equivalence classes in order to be considered for table * compaction by using protos. */ #define PROTO_SIZE_PERCENTAGE 15 /* The percentage the number of homogeneous out-transitions of a state * must be of the number of total out-transitions of the state in order * that the state's transition table is first compared with a potential * template of the most common out-transition instead of with the first * proto in the proto queue. */ #define CHECK_COM_PERCENTAGE 50 /* The percentage the number of differences between a state's transition * table and the proto it was first compared with must be of the total * number of out-transitions of the state in order to keep the first * proto as a good match and not search any further. */ #define FIRST_MATCH_DIFF_PERCENTAGE 10 /* The percentage the number of differences between a state's transition * table and the most similar proto must be of the state's total number * of out-transitions to use the proto as an acceptable close match. */ #define ACCEPTABLE_DIFF_PERCENTAGE 50 /* The percentage the number of homogeneous out-transitions of a state * must be of the number of total out-transitions of the state in order * to consider making a template from the state. */ #define TEMPLATE_SAME_PERCENTAGE 60 /* The percentage the number of differences between a state's transition * table and the most similar proto must be of the state's total number * of out-transitions to create a new proto from the state. */ #define NEW_PROTO_DIFF_PERCENTAGE 20 /* The percentage the total number of out-transitions of a state must be * of the number of equivalence classes in order to consider trying to * fit the transition table into "holes" inside the nxt/chk table. */ #define INTERIOR_FIT_PERCENTAGE 15 /* Size of region set aside to cache the complete transition table of * protos on the proto queue to enable quick comparisons. */ #define PROT_SAVE_SIZE 2000 #define MSP 50 /* maximum number of saved protos (protos on the proto queue) */ /* Maximum number of out-transitions a state can have that we'll rummage * around through the interior of the internal fast table looking for a * spot for it. */ #define MAX_XTIONS_FULL_INTERIOR_FIT 4 /* Maximum number of rules which will be reported as being associated * with a DFA state. */ #define MAX_ASSOC_RULES 100 /* Number that, if used to subscript an array, has a good chance of producing * an error; should be small enough to fit into a short. */ #define BAD_SUBSCRIPT -32767 /* Absolute value of largest number that can be stored in a short, with a * bit of slop thrown in for general paranoia. */ #define MAX_SHORT 32700 /* Declarations for global variables. */ /* Variables for flags: * printstats - if true (-v), dump statistics * syntaxerror - true if a syntax error has been found * eofseen - true if we've seen an eof in the input file * ddebug - if true (-d), make a "debug" scanner * trace - if true (-T), trace processing * nowarn - if true (-w), do not generate warnings * spprdflt - if true (-s), suppress the default rule * interactive - if true (-I), generate an interactive scanner * lex_compat - if true (-l), maximize compatibility with AT&T lex * posix_compat - if true (-X), maximize compatibility with POSIX lex * do_yylineno - if true, generate code to maintain yylineno * useecs - if true (-Ce flag), use equivalence classes * fulltbl - if true (-Cf flag), don't compress the DFA state table * usemecs - if true (-Cm flag), use meta-equivalence classes * fullspd - if true (-F flag), use Jacobson method of table representation * gen_line_dirs - if true (i.e., no -L flag), generate #line directives * performance_report - if > 0 (i.e., -p flag), generate a report relating * to scanner performance; if > 1 (-p -p), report on minor performance * problems, too * backing_up_report - if true (i.e., -b flag), generate "lex.backup" file * listing backing-up states * C_plus_plus - if true (i.e., -+ flag), generate a C++ scanner class; * otherwise, a standard C scanner * reentrant - if true (-R), generate a reentrant C scanner. * bison_bridge_lval - if true (--bison-bridge), bison pure calling convention. * bison_bridge_lloc - if true (--bison-locations), bison yylloc. * long_align - if true (-Ca flag), favor long-word alignment. * use_read - if true (-f, -F, or -Cr) then use read() for scanner input; * otherwise, use fread(). * yytext_is_array - if true (i.e., %array directive), then declare * yytext as a array instead of a character pointer. Nice and inefficient. * do_yywrap - do yywrap() processing on EOF. If false, EOF treated as * "no more files". * csize - size of character set for the scanner we're generating; * 128 for 7-bit chars and 256 for 8-bit * yymore_used - if true, yymore() is used in input rules * reject - if true, generate back-up tables for REJECT macro * real_reject - if true, scanner really uses REJECT (as opposed to just * having "reject" set for variable trailing context) * continued_action - true if this rule's action is to "fall through" to * the next rule's action (i.e., the '|' action) * in_rule - true if we're inside an individual rule, false if not. * yymore_really_used - whether to treat yymore() as really used, regardless * of what we think based on references to it in the user's actions. * reject_really_used - same for REJECT * trace_hex - use hexadecimal numbers in trace/debug outputs instead of octals */ extern int printstats, syntaxerror, eofseen, ddebug, trace, nowarn, spprdflt; extern int interactive, lex_compat, posix_compat, do_yylineno; extern int useecs, fulltbl, usemecs, fullspd; extern int gen_line_dirs, performance_report, backing_up_report; extern int reentrant, bison_bridge_lval, bison_bridge_lloc; extern bool ansi_func_defs, ansi_func_protos; extern int C_plus_plus, long_align, use_read, yytext_is_array, do_yywrap; extern int csize; extern int yymore_used, reject, real_reject, continued_action, in_rule; extern int yymore_really_used, reject_really_used; extern int trace_hex; /* Variables used in the flex input routines: * datapos - characters on current output line * dataline - number of contiguous lines of data in current data * statement. Used to generate readable -f output * linenum - current input line number * skelfile - the skeleton file * skel - compiled-in skeleton array * skel_ind - index into "skel" array, if skelfile is nil * yyin - input file * backing_up_file - file to summarize backing-up states to * infilename - name of input file * outfilename - name of output file * headerfilename - name of the .h file to generate * did_outfilename - whether outfilename was explicitly set * prefix - the prefix used for externally visible names ("yy" by default) * yyclass - yyFlexLexer subclass to use for YY_DECL * do_stdinit - whether to initialize yyin/yyout to stdin/stdout * use_stdout - the -t flag * input_files - array holding names of input files * num_input_files - size of input_files array * program_name - name with which program was invoked * * action_array - array to hold the rule actions * action_size - size of action_array * defs1_offset - index where the user's section 1 definitions start * in action_array * prolog_offset - index where the prolog starts in action_array * action_offset - index where the non-prolog starts in action_array * action_index - index where the next action should go, with respect * to "action_array" */ extern int datapos, dataline, linenum; extern FILE *skelfile, *yyin, *backing_up_file; extern const char *skel[]; extern int skel_ind; extern char *infilename, *outfilename, *headerfilename; extern int did_outfilename; extern char *prefix, *yyclass, *extra_type; extern int do_stdinit, use_stdout; extern char **input_files; extern int num_input_files; extern char *program_name; extern char *action_array; extern int action_size; extern int defs1_offset, prolog_offset, action_offset, action_index; /* Variables for stack of states having only one out-transition: * onestate - state number * onesym - transition symbol * onenext - target state * onedef - default base entry * onesp - stack pointer */ extern int onestate[ONE_STACK_SIZE], onesym[ONE_STACK_SIZE]; extern int onenext[ONE_STACK_SIZE], onedef[ONE_STACK_SIZE], onesp; /* Variables for nfa machine data: * maximum_mns - maximal number of NFA states supported by tables * current_mns - current maximum on number of NFA states * num_rules - number of the last accepting state; also is number of * rules created so far * num_eof_rules - number of <> rules * default_rule - number of the default rule * current_max_rules - current maximum number of rules * lastnfa - last nfa state number created * firstst - physically the first state of a fragment * lastst - last physical state of fragment * finalst - last logical state of fragment * transchar - transition character * trans1 - transition state * trans2 - 2nd transition state for epsilons * accptnum - accepting number * assoc_rule - rule associated with this NFA state (or 0 if none) * state_type - a STATE_xxx type identifying whether the state is part * of a normal rule, the leading state in a trailing context * rule (i.e., the state which marks the transition from * recognizing the text-to-be-matched to the beginning of * the trailing context), or a subsequent state in a trailing * context rule * rule_type - a RULE_xxx type identifying whether this a ho-hum * normal rule or one which has variable head & trailing * context * rule_linenum - line number associated with rule * rule_useful - true if we've determined that the rule can be matched * rule_has_nl - true if rule could possibly match a newline * ccl_has_nl - true if current ccl could match a newline * nlch - default eol char */ extern int maximum_mns, current_mns, current_max_rules; extern int num_rules, num_eof_rules, default_rule, lastnfa; extern int *firstst, *lastst, *finalst, *transchar, *trans1, *trans2; extern int *accptnum, *assoc_rule, *state_type; extern int *rule_type, *rule_linenum, *rule_useful; extern bool *rule_has_nl, *ccl_has_nl; extern int nlch; /* Different types of states; values are useful as masks, as well, for * routines like check_trailing_context(). */ #define STATE_NORMAL 0x1 #define STATE_TRAILING_CONTEXT 0x2 /* Global holding current type of state we're making. */ extern int current_state_type; /* Different types of rules. */ #define RULE_NORMAL 0 #define RULE_VARIABLE 1 /* True if the input rules include a rule with both variable-length head * and trailing context, false otherwise. */ extern int variable_trailing_context_rules; /* Variables for protos: * numtemps - number of templates created * numprots - number of protos created * protprev - backlink to a more-recently used proto * protnext - forward link to a less-recently used proto * prottbl - base/def table entry for proto * protcomst - common state of proto * firstprot - number of the most recently used proto * lastprot - number of the least recently used proto * protsave contains the entire state array for protos */ extern int numtemps, numprots, protprev[MSP], protnext[MSP], prottbl[MSP]; extern int protcomst[MSP], firstprot, lastprot, protsave[PROT_SAVE_SIZE]; /* Variables for managing equivalence classes: * numecs - number of equivalence classes * nextecm - forward link of Equivalence Class members * ecgroup - class number or backward link of EC members * nummecs - number of meta-equivalence classes (used to compress * templates) * tecfwd - forward link of meta-equivalence classes members * tecbck - backward link of MEC's */ /* Reserve enough room in the equivalence class arrays so that we * can use the CSIZE'th element to hold equivalence class information * for the NUL character. Later we'll move this information into * the 0th element. */ extern int numecs, nextecm[CSIZE + 1], ecgroup[CSIZE + 1], nummecs; /* Meta-equivalence classes are indexed starting at 1, so it's possible * that they will require positions from 1 .. CSIZE, i.e., CSIZE + 1 * slots total (since the arrays are 0-based). nextecm[] and ecgroup[] * don't require the extra position since they're indexed from 1 .. CSIZE - 1. */ extern int tecfwd[CSIZE + 1], tecbck[CSIZE + 1]; /* Variables for start conditions: * lastsc - last start condition created * current_max_scs - current limit on number of start conditions * scset - set of rules active in start condition * scbol - set of rules active only at the beginning of line in a s.c. * scxclu - true if start condition is exclusive * sceof - true if start condition has EOF rule * scname - start condition name */ extern int lastsc, *scset, *scbol, *scxclu, *sceof; extern int current_max_scs; extern char **scname; /* Variables for dfa machine data: * current_max_dfa_size - current maximum number of NFA states in DFA * current_max_xpairs - current maximum number of non-template xtion pairs * current_max_template_xpairs - current maximum number of template pairs * current_max_dfas - current maximum number DFA states * lastdfa - last dfa state number created * nxt - state to enter upon reading character * chk - check value to see if "nxt" applies * tnxt - internal nxt table for templates * base - offset into "nxt" for given state * def - where to go if "chk" disallows "nxt" entry * nultrans - NUL transition for each state * NUL_ec - equivalence class of the NUL character * tblend - last "nxt/chk" table entry being used * firstfree - first empty entry in "nxt/chk" table * dss - nfa state set for each dfa * dfasiz - size of nfa state set for each dfa * dfaacc - accepting set for each dfa state (if using REJECT), or accepting * number, if not * accsiz - size of accepting set for each dfa state * dhash - dfa state hash value * numas - number of DFA accepting states created; note that this * is not necessarily the same value as num_rules, which is the analogous * value for the NFA * numsnpairs - number of state/nextstate transition pairs * jambase - position in base/def where the default jam table starts * jamstate - state number corresponding to "jam" state * end_of_buffer_state - end-of-buffer dfa state number */ extern int current_max_dfa_size, current_max_xpairs; extern int current_max_template_xpairs, current_max_dfas; extern int lastdfa, *nxt, *chk, *tnxt; extern int *base, *def, *nultrans, NUL_ec, tblend, firstfree, **dss, *dfasiz; extern union dfaacc_union { int *dfaacc_set; int dfaacc_state; } *dfaacc; extern int *accsiz, *dhash, numas; extern int numsnpairs, jambase, jamstate; extern int end_of_buffer_state; /* Variables for ccl information: * lastccl - ccl index of the last created ccl * current_maxccls - current limit on the maximum number of unique ccl's * cclmap - maps a ccl index to its set pointer * ccllen - gives the length of a ccl * cclng - true for a given ccl if the ccl is negated * cclreuse - counts how many times a ccl is re-used * current_max_ccl_tbl_size - current limit on number of characters needed * to represent the unique ccl's * ccltbl - holds the characters in each ccl - indexed by cclmap */ extern int lastccl, *cclmap, *ccllen, *cclng, cclreuse; extern int current_maxccls, current_max_ccl_tbl_size; extern Char *ccltbl; /* Variables for miscellaneous information: * nmstr - last NAME scanned by the scanner * sectnum - section number currently being parsed * nummt - number of empty nxt/chk table entries * hshcol - number of hash collisions detected by snstods * dfaeql - number of times a newly created dfa was equal to an old one * numeps - number of epsilon NFA states created * eps2 - number of epsilon states which have 2 out-transitions * num_reallocs - number of times it was necessary to realloc() a group * of arrays * tmpuses - number of DFA states that chain to templates * totnst - total number of NFA states used to make DFA states * peakpairs - peak number of transition pairs we had to store internally * numuniq - number of unique transitions * numdup - number of duplicate transitions * hshsave - number of hash collisions saved by checking number of states * num_backing_up - number of DFA states requiring backing up * bol_needed - whether scanner needs beginning-of-line recognition */ extern char nmstr[MAXLINE]; extern int sectnum, nummt, hshcol, dfaeql, numeps, eps2, num_reallocs; extern int tmpuses, totnst, peakpairs, numuniq, numdup, hshsave; extern int num_backing_up, bol_needed; void *allocate_array PROTO ((int, size_t)); void *reallocate_array PROTO ((void *, int, size_t)); void *flex_alloc PROTO ((size_t)); void *flex_realloc PROTO ((void *, size_t)); void flex_free PROTO ((void *)); #define allocate_integer_array(size) \ (int *) allocate_array( size, sizeof( int ) ) #define reallocate_integer_array(array,size) \ (int *) reallocate_array( (void *) array, size, sizeof( int ) ) #define allocate_bool_array(size) \ (bool *) allocate_array( size, sizeof( bool ) ) #define reallocate_bool_array(array,size) \ (bool *) reallocate_array( (void *) array, size, sizeof( bool ) ) #define allocate_int_ptr_array(size) \ (int **) allocate_array( size, sizeof( int * ) ) #define allocate_char_ptr_array(size) \ (char **) allocate_array( size, sizeof( char * ) ) #define allocate_dfaacc_union(size) \ (union dfaacc_union *) \ allocate_array( size, sizeof( union dfaacc_union ) ) #define reallocate_int_ptr_array(array,size) \ (int **) reallocate_array( (void *) array, size, sizeof( int * ) ) #define reallocate_char_ptr_array(array,size) \ (char **) reallocate_array( (void *) array, size, sizeof( char * ) ) #define reallocate_dfaacc_union(array, size) \ (union dfaacc_union *) \ reallocate_array( (void *) array, size, sizeof( union dfaacc_union ) ) #define allocate_character_array(size) \ (char *) allocate_array( size, sizeof( char ) ) #define reallocate_character_array(array,size) \ (char *) reallocate_array( (void *) array, size, sizeof( char ) ) #define allocate_Character_array(size) \ (Char *) allocate_array( size, sizeof( Char ) ) #define reallocate_Character_array(array,size) \ (Char *) reallocate_array( (void *) array, size, sizeof( Char ) ) /* Used to communicate between scanner and parser. The type should really * be YYSTYPE, but we can't easily get our hands on it. */ extern int yylval; /* External functions that are cross-referenced among the flex source files. */ /* from file ccl.c */ extern void ccladd PROTO ((int, int)); /* add a single character to a ccl */ extern int cclinit PROTO ((void)); /* make an empty ccl */ extern void cclnegate PROTO ((int)); /* negate a ccl */ extern int ccl_set_diff (int a, int b); /* set difference of two ccls. */ extern int ccl_set_union (int a, int b); /* set union of two ccls. */ /* List the members of a set of characters in CCL form. */ extern void list_character_set PROTO ((FILE *, int[])); /* from file dfa.c */ /* Check a DFA state for backing up. */ extern void check_for_backing_up PROTO ((int, int[])); /* Check to see if NFA state set constitutes "dangerous" trailing context. */ extern void check_trailing_context PROTO ((int *, int, int *, int)); /* Construct the epsilon closure of a set of ndfa states. */ extern int *epsclosure PROTO ((int *, int *, int[], int *, int *)); /* Increase the maximum number of dfas. */ extern void increase_max_dfas PROTO ((void)); extern void ntod PROTO ((void)); /* convert a ndfa to a dfa */ /* Converts a set of ndfa states into a dfa state. */ extern int snstods PROTO ((int[], int, int[], int, int, int *)); /* from file ecs.c */ /* Convert character classes to set of equivalence classes. */ extern void ccl2ecl PROTO ((void)); /* Associate equivalence class numbers with class members. */ extern int cre8ecs PROTO ((int[], int[], int)); /* Update equivalence classes based on character class transitions. */ extern void mkeccl PROTO ((Char[], int, int[], int[], int, int)); /* Create equivalence class for single character. */ extern void mkechar PROTO ((int, int[], int[])); /* from file gen.c */ extern void do_indent PROTO ((void)); /* indent to the current level */ /* Generate the code to keep backing-up information. */ extern void gen_backing_up PROTO ((void)); /* Generate the code to perform the backing up. */ extern void gen_bu_action PROTO ((void)); /* Generate full speed compressed transition table. */ extern void genctbl PROTO ((void)); /* Generate the code to find the action number. */ extern void gen_find_action PROTO ((void)); extern void genftbl PROTO ((void)); /* generate full transition table */ /* Generate the code to find the next compressed-table state. */ extern void gen_next_compressed_state PROTO ((char *)); /* Generate the code to find the next match. */ extern void gen_next_match PROTO ((void)); /* Generate the code to find the next state. */ extern void gen_next_state PROTO ((int)); /* Generate the code to make a NUL transition. */ extern void gen_NUL_trans PROTO ((void)); /* Generate the code to find the start state. */ extern void gen_start_state PROTO ((void)); /* Generate data statements for the transition tables. */ extern void gentabs PROTO ((void)); /* Write out a formatted string at the current indentation level. */ extern void indent_put2s PROTO ((const char *, const char *)); /* Write out a string + newline at the current indentation level. */ extern void indent_puts PROTO ((const char *)); extern void make_tables PROTO ((void)); /* generate transition tables */ /* from file main.c */ extern void check_options PROTO ((void)); extern void flexend PROTO ((int)); extern void usage PROTO ((void)); /* from file misc.c */ /* Add a #define to the action file. */ extern void action_define PROTO ((const char *defname, int value)); /* Add the given text to the stored actions. */ extern void add_action PROTO ((const char *new_text)); /* True if a string is all lower case. */ extern int all_lower PROTO ((char *)); /* True if a string is all upper case. */ extern int all_upper PROTO ((char *)); /* Compare two integers for use by qsort. */ extern int intcmp PROTO ((const void *, const void *)); /* Check a character to make sure it's in the expected range. */ extern void check_char PROTO ((int c)); /* Replace upper-case letter to lower-case. */ extern Char clower PROTO ((int)); /* Returns a dynamically allocated copy of a string. */ extern char *copy_string PROTO ((const char *)); /* Returns a dynamically allocated copy of a (potentially) unsigned string. */ extern Char *copy_unsigned_string PROTO ((Char *)); /* Compare two characters for use by qsort with '\0' sorting last. */ extern int cclcmp PROTO ((const void *, const void *)); /* Finish up a block of data declarations. */ extern void dataend PROTO ((void)); /* Flush generated data statements. */ extern void dataflush PROTO ((void)); /* Report an error message and terminate. */ extern void flexerror PROTO ((const char *)); /* Report a fatal error message and terminate. */ extern void flexfatal PROTO ((const char *)); /* Report a fatal error with a pinpoint, and terminate */ #if HAVE_DECL___FUNC__ #define flex_die(msg) \ do{ \ fprintf (stderr,\ _("%s: fatal internal error at %s:%d (%s): %s\n"),\ program_name, __FILE__, (int)__LINE__,\ __func__,msg);\ FLEX_EXIT(1);\ }while(0) #else /* ! HAVE_DECL___FUNC__ */ #define flex_die(msg) \ do{ \ fprintf (stderr,\ _("%s: fatal internal error at %s:%d %s\n"),\ program_name, __FILE__, (int)__LINE__,\ msg);\ FLEX_EXIT(1);\ }while(0) #endif /* ! HAVE_DECL___func__ */ /* Convert a hexadecimal digit string to an integer value. */ extern int htoi PROTO ((Char[])); /* Report an error message formatted */ extern void lerr PROTO ((const char *, ...)) #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__format__(__printf__, 1, 2))) #endif ; /* Like lerr, but also exit after displaying message. */ extern void lerr_fatal PROTO ((const char *, ...)) #if defined(__GNUC__) && __GNUC__ >= 3 __attribute__((__format__(__printf__, 1, 2))) #endif ; /* Spit out a "#line" statement. */ extern void line_directive_out PROTO ((FILE *, int)); /* Mark the current position in the action array as the end of the section 1 * user defs. */ extern void mark_defs1 PROTO ((void)); /* Mark the current position in the action array as the end of the prolog. */ extern void mark_prolog PROTO ((void)); /* Generate a data statment for a two-dimensional array. */ extern void mk2data PROTO ((int)); extern void mkdata PROTO ((int)); /* generate a data statement */ /* Return the integer represented by a string of digits. */ extern int myctoi PROTO ((const char *)); /* Return character corresponding to escape sequence. */ extern Char myesc PROTO ((Char[])); /* Convert an octal digit string to an integer value. */ extern int otoi PROTO ((Char[])); /* Output a (possibly-formatted) string to the generated scanner. */ extern void out PROTO ((const char *)); extern void out_dec PROTO ((const char *, int)); extern void out_dec2 PROTO ((const char *, int, int)); extern void out_hex PROTO ((const char *, unsigned int)); extern void out_str PROTO ((const char *, const char *)); extern void out_str3 PROTO ((const char *, const char *, const char *, const char *)); extern void out_str_dec PROTO ((const char *, const char *, int)); extern void outc PROTO ((int)); extern void outn PROTO ((const char *)); extern void out_m4_define (const char* def, const char* val); /* Return a printable version of the given character, which might be * 8-bit. */ extern char *readable_form PROTO ((int)); /* Write out one section of the skeleton file. */ extern void skelout PROTO ((void)); /* Output a yy_trans_info structure. */ extern void transition_struct_out PROTO ((int, int)); /* Only needed when using certain broken versions of bison to build parse.c. */ extern void *yy_flex_xmalloc PROTO ((int)); /* Set a region of memory to 0. */ extern void zero_out PROTO ((char *, size_t)); /* from file nfa.c */ /* Add an accepting state to a machine. */ extern void add_accept PROTO ((int, int)); /* Make a given number of copies of a singleton machine. */ extern int copysingl PROTO ((int, int)); /* Debugging routine to write out an nfa. */ extern void dumpnfa PROTO ((int)); /* Finish up the processing for a rule. */ extern void finish_rule PROTO ((int, int, int, int, int)); /* Connect two machines together. */ extern int link_machines PROTO ((int, int)); /* Mark each "beginning" state in a machine as being a "normal" (i.e., * not trailing context associated) state. */ extern void mark_beginning_as_normal PROTO ((int)); /* Make a machine that branches to two machines. */ extern int mkbranch PROTO ((int, int)); extern int mkclos PROTO ((int)); /* convert a machine into a closure */ extern int mkopt PROTO ((int)); /* make a machine optional */ /* Make a machine that matches either one of two machines. */ extern int mkor PROTO ((int, int)); /* Convert a machine into a positive closure. */ extern int mkposcl PROTO ((int)); extern int mkrep PROTO ((int, int, int)); /* make a replicated machine */ /* Create a state with a transition on a given symbol. */ extern int mkstate PROTO ((int)); extern void new_rule PROTO ((void)); /* initialize for a new rule */ /* from file parse.y */ /* Build the "<>" action for the active start conditions. */ extern void build_eof_action PROTO ((void)); /* Write out a message formatted with one string, pinpointing its location. */ extern void format_pinpoint_message PROTO ((const char *, const char *)); /* Write out a message, pinpointing its location. */ extern void pinpoint_message PROTO ((const char *)); /* Write out a warning, pinpointing it at the given line. */ extern void line_warning PROTO ((const char *, int)); /* Write out a message, pinpointing it at the given line. */ extern void line_pinpoint PROTO ((const char *, int)); /* Report a formatted syntax error. */ extern void format_synerr PROTO ((const char *, const char *)); extern void synerr PROTO ((const char *)); /* report a syntax error */ extern void format_warn PROTO ((const char *, const char *)); extern void warn PROTO ((const char *)); /* report a warning */ extern void yyerror PROTO ((const char *)); /* report a parse error */ extern int yyparse PROTO ((void)); /* the YACC parser */ /* from file scan.l */ /* The Flex-generated scanner for flex. */ extern int flexscan PROTO ((void)); /* Open the given file (if NULL, stdin) for scanning. */ extern void set_input_file PROTO ((char *)); /* Wrapup a file in the lexical analyzer. */ extern int yywrap PROTO ((void)); /* from file sym.c */ /* Save the text of a character class. */ extern void cclinstal PROTO ((Char[], int)); /* Lookup the number associated with character class. */ extern int ccllookup PROTO ((Char[])); extern void ndinstal PROTO ((const char *, Char[])); /* install a name definition */ extern Char *ndlookup PROTO ((const char *)); /* lookup a name definition */ /* Increase maximum number of SC's. */ extern void scextend PROTO ((void)); extern void scinstal PROTO ((const char *, int)); /* make a start condition */ /* Lookup the number associated with a start condition. */ extern int sclookup PROTO ((const char *)); /* from file tblcmp.c */ /* Build table entries for dfa state. */ extern void bldtbl PROTO ((int[], int, int, int, int)); extern void cmptmps PROTO ((void)); /* compress template table entries */ extern void expand_nxt_chk PROTO ((void)); /* increase nxt/chk arrays */ /* Finds a space in the table for a state to be placed. */ extern int find_table_space PROTO ((int *, int)); extern void inittbl PROTO ((void)); /* initialize transition tables */ /* Make the default, "jam" table entries. */ extern void mkdeftbl PROTO ((void)); /* Create table entries for a state (or state fragment) which has * only one out-transition. */ extern void mk1tbl PROTO ((int, int, int, int)); /* Place a state into full speed transition table. */ extern void place_state PROTO ((int *, int, int)); /* Save states with only one out-transition to be processed later. */ extern void stack1 PROTO ((int, int, int, int)); /* from file yylex.c */ extern int yylex PROTO ((void)); /* A growable array. See buf.c. */ struct Buf { void *elts; /* elements. */ int nelts; /* number of elements. */ size_t elt_size; /* in bytes. */ int nmax; /* max capacity of elements. */ }; extern void buf_init PROTO ((struct Buf * buf, size_t elem_size)); extern void buf_destroy PROTO ((struct Buf * buf)); extern struct Buf *buf_append PROTO ((struct Buf * buf, const void *ptr, int n_elem)); extern struct Buf *buf_concat PROTO((struct Buf* dest, const struct Buf* src)); extern struct Buf *buf_strappend PROTO ((struct Buf *, const char *str)); extern struct Buf *buf_strnappend PROTO ((struct Buf *, const char *str, int nchars)); extern struct Buf *buf_strdefine PROTO ((struct Buf * buf, const char *str, const char *def)); extern struct Buf *buf_prints PROTO((struct Buf *buf, const char *fmt, const char* s)); extern struct Buf *buf_m4_define PROTO((struct Buf *buf, const char* def, const char* val)); extern struct Buf *buf_m4_undefine PROTO((struct Buf *buf, const char* def)); extern struct Buf *buf_print_strings PROTO((struct Buf * buf, FILE* out)); extern struct Buf *buf_linedir PROTO((struct Buf *buf, const char* filename, int lineno)); extern struct Buf userdef_buf; /* a string buffer for #define's generated by user-options on cmd line. */ extern struct Buf defs_buf; /* a char* buffer to save #define'd some symbols generated by flex. */ extern struct Buf yydmap_buf; /* a string buffer to hold yydmap elements */ extern struct Buf m4defs_buf; /* Holds m4 definitions. */ extern struct Buf top_buf; /* contains %top code. String buffer. */ /* For blocking out code from the header file. */ #define OUT_BEGIN_CODE() outn("m4_ifdef( [[M4_YY_IN_HEADER]],,[[") #define OUT_END_CODE() outn("]])") /* For setjmp/longjmp (instead of calling exit(2)). Linkage in main.c */ extern jmp_buf flex_main_jmp_buf; #define FLEX_EXIT(status) longjmp(flex_main_jmp_buf,(status)+1) /* Removes all \n and \r chars from tail of str. returns str. */ extern char *chomp (char *str); /* ctype functions forced to return boolean */ #define b_isalnum(c) (isalnum(c)?true:false) #define b_isalpha(c) (isalpha(c)?true:false) #define b_isascii(c) (isascii(c)?true:false) #define b_isblank(c) (isblank(c)?true:false) #define b_iscntrl(c) (iscntrl(c)?true:false) #define b_isdigit(c) (isdigit(c)?true:false) #define b_isgraph(c) (isgraph(c)?true:false) #define b_islower(c) (islower(c)?true:false) #define b_isprint(c) (isprint(c)?true:false) #define b_ispunct(c) (ispunct(c)?true:false) #define b_isspace(c) (isspace(c)?true:false) #define b_isupper(c) (isupper(c)?true:false) #define b_isxdigit(c) (isxdigit(c)?true:false) /* return true if char is uppercase or lowercase. */ bool has_case(int c); /* Change case of character if possible. */ int reverse_case(int c); /* return false if [c1-c2] is ambiguous for a caseless scanner. */ bool range_covers_case (int c1, int c2); /* * From "filter.c" */ /** A single stdio filter to execute. * The filter may be external, such as "sed", or it * may be internal, as a function call. */ struct filter { int (*filter_func)(struct filter*); /**< internal filter function */ void * extra; /**< extra data passed to filter_func */ int argc; /**< arg count */ const char ** argv; /**< arg vector, \0-terminated */ struct filter * next; /**< next filter or NULL */ }; /* output filter chain */ extern struct filter * output_chain; extern struct filter *filter_create_ext PROTO((struct filter * chain, const char *cmd, ...)); struct filter *filter_create_int PROTO((struct filter *chain, int (*filter_func) (struct filter *), void *extra)); extern bool filter_apply_chain PROTO((struct filter * chain)); extern int filter_truncate (struct filter * chain, int max_len); extern int filter_tee_header PROTO((struct filter *chain)); extern int filter_fix_linedirs PROTO((struct filter *chain)); /* * From "regex.c" */ extern regex_t regex_linedir, regex_blank_line; bool flex_init_regex(void); void flex_regcomp(regex_t *preg, const char *regex, int cflags); char *regmatch_dup (regmatch_t * m, const char *src); char *regmatch_cpy (regmatch_t * m, char *dest, const char *src); int regmatch_len (regmatch_t * m); int regmatch_strtol (regmatch_t * m, const char *src, char **endptr, int base); bool regmatch_empty (regmatch_t * m); /* From "scanflags.h" */ typedef unsigned int scanflags_t; extern scanflags_t* _sf_stk; extern size_t _sf_top_ix, _sf_max; /**< stack of scanner flags. */ #define _SF_CASE_INS 0x0001 #define _SF_DOT_ALL 0x0002 #define _SF_SKIP_WS 0x0004 #define sf_top() (_sf_stk[_sf_top_ix]) #define sf_case_ins() (sf_top() & _SF_CASE_INS) #define sf_dot_all() (sf_top() & _SF_DOT_ALL) #define sf_skip_ws() (sf_top() & _SF_SKIP_WS) #define sf_set_case_ins(X) ((X) ? (sf_top() |= _SF_CASE_INS) : (sf_top() &= ~_SF_CASE_INS)) #define sf_set_dot_all(X) ((X) ? (sf_top() |= _SF_DOT_ALL) : (sf_top() &= ~_SF_DOT_ALL)) #define sf_set_skip_ws(X) ((X) ? (sf_top() |= _SF_SKIP_WS) : (sf_top() &= ~_SF_SKIP_WS)) extern void sf_init(void); extern void sf_push(void); extern void sf_pop(void); #endif /* not defined FLEXDEF_H */ flex-2.6.0/src/libyywrap.c0000644000175000017500000000215612620472752015717 0ustar srivastasrivasta/* libyywrap - flex run-time support library "yywrap" function */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ int yywrap (void); int yywrap (void) { return 1; } flex-2.6.0/src/buf.c0000644000175000017500000001677512620472752014465 0ustar srivastasrivasta/* flex - tool to generate fast lexical analyzers */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" /* Take note: The buffer object is sometimes used as a String buffer (one * continuous string), and sometimes used as a list of strings, usually line by * line. * * The type is specified in buf_init by the elt_size. If the elt_size is * sizeof(char), then the buffer should be treated as string buffer. If the * elt_size is sizeof(char*), then the buffer should be treated as a list of * strings. * * Certain functions are only appropriate for one type or the other. */ /* global buffers. */ struct Buf userdef_buf; /**< for user #definitions triggered by cmd-line. */ struct Buf defs_buf; /**< for #define's autogenerated. List of strings. */ struct Buf yydmap_buf; /**< string buffer to hold yydmap elements */ struct Buf m4defs_buf; /**< m4 definitions. List of strings. */ struct Buf top_buf; /**< contains %top code. String buffer. */ struct Buf *buf_print_strings(struct Buf * buf, FILE* out) { int i; if(!buf || !out) return buf; for (i=0; i < buf->nelts; i++){ const char * s = ((char**)buf->elts)[i]; if(s) fprintf(out, "%s", s); } return buf; } /* Append a "%s" formatted string to a string buffer */ struct Buf *buf_prints (struct Buf *buf, const char *fmt, const char *s) { char *t; size_t tsz; t = flex_alloc (tsz = strlen (fmt) + strlen (s) + 1); if (!t) flexfatal (_("Allocation of buffer to print string failed")); snprintf (t, tsz, fmt, s); buf = buf_strappend (buf, t); flex_free (t); return buf; } /** Append a line directive to the string buffer. * @param buf A string buffer. * @param filename file name * @param lineno line number * @return buf */ struct Buf *buf_linedir (struct Buf *buf, const char* filename, int lineno) { char *dst, *t; const char *src; t = flex_alloc (strlen ("#line \"\"\n") + /* constant parts */ 2 * strlen (filename) + /* filename with possibly all backslashes escaped */ (int) (1 + log10 (abs (lineno))) + /* line number */ 1); /* NUL */ if (!t) flexfatal (_("Allocation of buffer for line directive failed")); for (dst = t + sprintf (t, "#line %d \"", lineno), src = filename; *src; *dst++ = *src++) if (*src == '\\') /* escape backslashes */ *dst++ = '\\'; *dst++ = '"'; *dst++ = '\n'; *dst = '\0'; buf = buf_strappend (buf, t); flex_free (t); return buf; } /** Append the contents of @a src to @a dest. * @param @a dest the destination buffer * @param @a dest the source buffer * @return @a dest */ struct Buf *buf_concat(struct Buf* dest, const struct Buf* src) { buf_append(dest, src->elts, src->nelts); return dest; } /* Appends n characters in str to buf. */ struct Buf *buf_strnappend (buf, str, n) struct Buf *buf; const char *str; int n; { buf_append (buf, str, n + 1); /* "undo" the '\0' character that buf_append() already copied. */ buf->nelts--; return buf; } /* Appends characters in str to buf. */ struct Buf *buf_strappend (buf, str) struct Buf *buf; const char *str; { return buf_strnappend (buf, str, strlen (str)); } /* appends "#define str def\n" */ struct Buf *buf_strdefine (buf, str, def) struct Buf *buf; const char *str; const char *def; { buf_strappend (buf, "#define "); buf_strappend (buf, " "); buf_strappend (buf, str); buf_strappend (buf, " "); buf_strappend (buf, def); buf_strappend (buf, "\n"); return buf; } /** Pushes "m4_define( [[def]], [[val]])m4_dnl" to end of buffer. * @param buf A buffer as a list of strings. * @param def The m4 symbol to define. * @param val The definition; may be NULL. * @return buf */ struct Buf *buf_m4_define (struct Buf *buf, const char* def, const char* val) { const char * fmt = "m4_define( [[%s]], [[%s]])m4_dnl\n"; char * str; size_t strsz; val = val?val:""; str = (char*)flex_alloc(strsz = strlen(fmt) + strlen(def) + strlen(val) + 2); if (!str) flexfatal (_("Allocation of buffer for m4 def failed")); snprintf(str, strsz, fmt, def, val); buf_append(buf, &str, 1); return buf; } /** Pushes "m4_undefine([[def]])m4_dnl" to end of buffer. * @param buf A buffer as a list of strings. * @param def The m4 symbol to undefine. * @return buf */ struct Buf *buf_m4_undefine (struct Buf *buf, const char* def) { const char * fmt = "m4_undefine( [[%s]])m4_dnl\n"; char * str; size_t strsz; str = (char*)flex_alloc(strsz = strlen(fmt) + strlen(def) + 2); if (!str) flexfatal (_("Allocation of buffer for m4 undef failed")); snprintf(str, strsz, fmt, def); buf_append(buf, &str, 1); return buf; } /* create buf with 0 elements, each of size elem_size. */ void buf_init (buf, elem_size) struct Buf *buf; size_t elem_size; { buf->elts = (void *) 0; buf->nelts = 0; buf->elt_size = elem_size; buf->nmax = 0; } /* frees memory */ void buf_destroy (buf) struct Buf *buf; { if (buf && buf->elts) flex_free (buf->elts); buf->elts = (void *) 0; } /* appends ptr[] to buf, grow if necessary. * n_elem is number of elements in ptr[], NOT bytes. * returns buf. * We grow by mod(512) boundaries. */ struct Buf *buf_append (buf, ptr, n_elem) struct Buf *buf; const void *ptr; int n_elem; { int n_alloc = 0; if (!ptr || n_elem == 0) return buf; /* May need to alloc more. */ if (n_elem + buf->nelts > buf->nmax) { /* exact amount needed... */ n_alloc = (n_elem + buf->nelts) * buf->elt_size; /* ...plus some extra */ if (((n_alloc * buf->elt_size) % 512) != 0 && buf->elt_size < 512) n_alloc += (512 - ((n_alloc * buf->elt_size) % 512)) / buf->elt_size; if (!buf->elts) buf->elts = allocate_array (n_alloc, buf->elt_size); else buf->elts = reallocate_array (buf->elts, n_alloc, buf->elt_size); buf->nmax = n_alloc; } memcpy ((char *) buf->elts + buf->nelts * buf->elt_size, ptr, n_elem * buf->elt_size); buf->nelts += n_elem; return buf; } /* vim:set tabstop=8 softtabstop=4 shiftwidth=4: */ flex-2.6.0/src/parse.c0000644000175000017500000024515012622651445015012 0ustar srivastasrivasta/* A Bison parser, made by GNU Bison 3.0.4. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.0.4" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 0 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Copy the first part of user declarations. */ #line 34 "parse.y" /* yacc.c:339 */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" #include "tables.h" int pat, scnum, eps, headcnt, trailcnt, lastchar, i, rulelen; int trlcontxt, xcluflg, currccl, cclsorted, varlength, variable_trail_rule; int *scon_stk; int scon_stk_ptr; static int madeany = false; /* whether we've made the '.' character class */ static int ccldot, cclany; int previous_continued_action; /* whether the previous rule's action was '|' */ #define format_warn3(fmt, a1, a2) \ do{ \ char fw3_msg[MAXLINE];\ snprintf( fw3_msg, MAXLINE,(fmt), (a1), (a2) );\ warn( fw3_msg );\ }while(0) /* Expand a POSIX character class expression. */ #define CCL_EXPR(func) \ do{ \ int c; \ for ( c = 0; c < csize; ++c ) \ if ( isascii(c) && func(c) ) \ ccladd( currccl, c ); \ }while(0) /* negated class */ #define CCL_NEG_EXPR(func) \ do{ \ int c; \ for ( c = 0; c < csize; ++c ) \ if ( !func(c) ) \ ccladd( currccl, c ); \ }while(0) /* While POSIX defines isblank(), it's not ANSI C. */ #define IS_BLANK(c) ((c) == ' ' || (c) == '\t') /* On some over-ambitious machines, such as DEC Alpha's, the default * token type is "long" instead of "int"; this leads to problems with * declaring yylval in flexdef.h. But so far, all the yacc's I've seen * wrap their definitions of YYSTYPE with "#ifndef YYSTYPE"'s, so the * following should ensure that the default token type is "int". */ #define YYSTYPE int #line 149 "parse.c" /* yacc.c:339 */ # ifndef YY_NULLPTR # if defined __cplusplus && 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 0 #endif /* In a future release of Bison, this section will be replaced by #include "y.tab.h". */ #ifndef YY_YY_PARSE_H_INCLUDED # define YY_YY_PARSE_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { CHAR = 258, NUMBER = 259, SECTEND = 260, SCDECL = 261, XSCDECL = 262, NAME = 263, PREVCCL = 264, EOF_OP = 265, OPTION_OP = 266, OPT_OUTFILE = 267, OPT_PREFIX = 268, OPT_YYCLASS = 269, OPT_HEADER = 270, OPT_EXTRA_TYPE = 271, OPT_TABLES = 272, CCE_ALNUM = 273, CCE_ALPHA = 274, CCE_BLANK = 275, CCE_CNTRL = 276, CCE_DIGIT = 277, CCE_GRAPH = 278, CCE_LOWER = 279, CCE_PRINT = 280, CCE_PUNCT = 281, CCE_SPACE = 282, CCE_UPPER = 283, CCE_XDIGIT = 284, CCE_NEG_ALNUM = 285, CCE_NEG_ALPHA = 286, CCE_NEG_BLANK = 287, CCE_NEG_CNTRL = 288, CCE_NEG_DIGIT = 289, CCE_NEG_GRAPH = 290, CCE_NEG_LOWER = 291, CCE_NEG_PRINT = 292, CCE_NEG_PUNCT = 293, CCE_NEG_SPACE = 294, CCE_NEG_UPPER = 295, CCE_NEG_XDIGIT = 296, CCL_OP_DIFF = 297, CCL_OP_UNION = 298, BEGIN_REPEAT_POSIX = 299, END_REPEAT_POSIX = 300, BEGIN_REPEAT_FLEX = 301, END_REPEAT_FLEX = 302 }; #endif /* Tokens. */ #define CHAR 258 #define NUMBER 259 #define SECTEND 260 #define SCDECL 261 #define XSCDECL 262 #define NAME 263 #define PREVCCL 264 #define EOF_OP 265 #define OPTION_OP 266 #define OPT_OUTFILE 267 #define OPT_PREFIX 268 #define OPT_YYCLASS 269 #define OPT_HEADER 270 #define OPT_EXTRA_TYPE 271 #define OPT_TABLES 272 #define CCE_ALNUM 273 #define CCE_ALPHA 274 #define CCE_BLANK 275 #define CCE_CNTRL 276 #define CCE_DIGIT 277 #define CCE_GRAPH 278 #define CCE_LOWER 279 #define CCE_PRINT 280 #define CCE_PUNCT 281 #define CCE_SPACE 282 #define CCE_UPPER 283 #define CCE_XDIGIT 284 #define CCE_NEG_ALNUM 285 #define CCE_NEG_ALPHA 286 #define CCE_NEG_BLANK 287 #define CCE_NEG_CNTRL 288 #define CCE_NEG_DIGIT 289 #define CCE_NEG_GRAPH 290 #define CCE_NEG_LOWER 291 #define CCE_NEG_PRINT 292 #define CCE_NEG_PUNCT 293 #define CCE_NEG_SPACE 294 #define CCE_NEG_UPPER 295 #define CCE_NEG_XDIGIT 296 #define CCL_OP_DIFF 297 #define CCL_OP_UNION 298 #define BEGIN_REPEAT_POSIX 299 #define END_REPEAT_POSIX 300 #define BEGIN_REPEAT_FLEX 301 #define END_REPEAT_FLEX 302 /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif extern YYSTYPE yylval; int yyparse (void); #endif /* !YY_YY_PARSE_H_INCLUDED */ /* Copy the second part of user declarations. */ #line 294 "parse.c" /* yacc.c:358 */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T # include /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE # if (defined __GNUC__ \ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ # endif #endif #ifndef YY_ATTRIBUTE_PURE # define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) #endif #ifndef YY_ATTRIBUTE_UNUSED # define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) #endif #if !defined _Noreturn \ && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) # if defined _MSC_VER && 1200 <= _MSC_VER # define _Noreturn __declspec (noreturn) # else # define _Noreturn YY_ATTRIBUTE ((__noreturn__)) # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 3 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 161 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 69 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 27 /* YYNRULES -- Number of rules. */ #define YYNRULES 97 /* YYNSTATES -- Number of states. */ #define YYNSTATES 140 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned by yylex, with out-of-bounds checking. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 302 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex, without out-of-bounds checking. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 49, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 63, 2, 57, 2, 2, 2, 64, 65, 55, 60, 56, 68, 62, 59, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 53, 48, 54, 61, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 66, 2, 67, 52, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 50, 58, 51, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 118, 118, 148, 155, 156, 157, 158, 162, 170, 173, 177, 180, 183, 187, 190, 191, 194, 199, 201, 203, 205, 207, 211, 213, 215, 219, 231, 267, 291, 314, 319, 322, 325, 343, 346, 348, 350, 354, 377, 433, 436, 479, 497, 503, 508, 535, 543, 546, 574, 588, 610, 617, 623, 629, 657, 671, 690, 724, 742, 752, 755, 758, 773, 774, 775, 780, 782, 789, 849, 867, 875, 883, 884, 885, 886, 887, 888, 889, 894, 895, 896, 897, 898, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 920, 928, 944 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 0 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "CHAR", "NUMBER", "SECTEND", "SCDECL", "XSCDECL", "NAME", "PREVCCL", "EOF_OP", "OPTION_OP", "OPT_OUTFILE", "OPT_PREFIX", "OPT_YYCLASS", "OPT_HEADER", "OPT_EXTRA_TYPE", "OPT_TABLES", "CCE_ALNUM", "CCE_ALPHA", "CCE_BLANK", "CCE_CNTRL", "CCE_DIGIT", "CCE_GRAPH", "CCE_LOWER", "CCE_PRINT", "CCE_PUNCT", "CCE_SPACE", "CCE_UPPER", "CCE_XDIGIT", "CCE_NEG_ALNUM", "CCE_NEG_ALPHA", "CCE_NEG_BLANK", "CCE_NEG_CNTRL", "CCE_NEG_DIGIT", "CCE_NEG_GRAPH", "CCE_NEG_LOWER", "CCE_NEG_PRINT", "CCE_NEG_PUNCT", "CCE_NEG_SPACE", "CCE_NEG_UPPER", "CCE_NEG_XDIGIT", "CCL_OP_DIFF", "CCL_OP_UNION", "BEGIN_REPEAT_POSIX", "END_REPEAT_POSIX", "BEGIN_REPEAT_FLEX", "END_REPEAT_FLEX", "'='", "'\\n'", "'{'", "'}'", "'^'", "'<'", "'>'", "'*'", "','", "'$'", "'|'", "'/'", "'+'", "'?'", "'.'", "'\"'", "'('", "')'", "'['", "']'", "'-'", "$accept", "goal", "initlex", "sect1", "sect1end", "startconddecl", "namelist1", "options", "optionlist", "option", "sect2", "initforrule", "flexrule", "scon_stk_ptr", "scon", "namelist2", "sconname", "rule", "re", "re2", "series", "singleton", "fullccl", "braceccl", "ccl", "ccl_expr", "string", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 61, 10, 123, 125, 94, 60, 62, 42, 44, 36, 124, 47, 43, 63, 46, 34, 40, 41, 91, 93, 45 }; # endif #define YYPACT_NINF -52 #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-52))) #define YYTABLE_NINF -27 #define yytable_value_is_error(Yytable_value) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { -52, 17, 103, -52, -52, 113, -52, -52, -52, -52, -52, 48, -52, 114, 6, -52, -52, 42, 7, 12, 58, 77, 88, 89, -52, 43, -52, 73, -52, 130, 131, 132, 133, 134, 135, 90, 91, -52, -1, -52, -52, -52, -52, -52, -52, -52, -52, -52, 40, -52, 44, -52, -52, -52, -52, 39, -52, -52, 39, 93, 97, -52, -12, 39, 49, 61, -31, -52, -52, 139, -52, -52, 1, -51, -52, 0, -52, -52, 39, -52, 75, 144, 61, 145, -52, -52, -52, 84, 84, -52, -52, -52, -52, 50, 83, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, 49, -52, -40, 10, -52, -52, -52, 149, -52, 9, -52, -3, -52, 108, -52, 107, -52, -52, -52 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 3, 0, 0, 1, 7, 0, 8, 9, 10, 16, 25, 0, 5, 14, 34, 13, 12, 4, 0, 0, 0, 0, 0, 0, 15, 31, 2, 26, 11, 0, 0, 0, 0, 0, 0, 0, 0, 25, 0, 17, 19, 20, 21, 18, 22, 33, 37, 38, 0, 36, 34, 30, 62, 59, 29, 0, 57, 97, 0, 71, 0, 28, 42, 0, 44, 47, 58, 65, 32, 0, 24, 27, 0, 0, 71, 0, 23, 41, 0, 45, 39, 0, 46, 0, 51, 52, 53, 0, 0, 35, 96, 60, 61, 0, 69, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83, 82, 84, 85, 86, 87, 88, 89, 94, 90, 91, 92, 95, 93, 66, 70, 43, 40, 0, 0, 63, 64, 67, 0, 50, 0, 56, 0, 68, 0, 49, 0, 55, 48, 54 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -52, -52, -52, -52, -52, -52, -52, -52, -52, -52, 118, 129, -52, -52, -52, -52, 92, 102, -48, -52, 80, -21, -52, 47, 85, -52, -52 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int8 yydefgoto[] = { -1, 1, 2, 5, 10, 11, 17, 12, 13, 24, 14, 26, 60, 36, 27, 48, 49, 61, 62, 63, 64, 65, 66, 67, 75, 120, 72 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_int16 yytable[] = { 51, 136, 52, 94, 90, 129, -26, 78, 53, 54, 73, 87, 88, 134, 92, 80, 130, 3, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 52, 82, 137, 77, 78, 79, 53, 15, 28, 55, 52, 94, 135, 29, 16, 131, 53, 25, 30, 56, 57, 58, 91, 59, 132, 119, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 46, 81, 68, 70, 69, 25, 35, 47, 82, 56, 57, 58, 4, 59, 31, 83, -6, -6, -6, 56, 57, 58, -6, 59, 84, 127, 6, 7, 8, 85, 86, 37, 9, 32, 18, 19, 20, 21, 22, 23, 122, 78, 125, 126, 33, 34, 39, 40, 41, 42, 43, 44, 45, 74, 76, 47, 123, 124, 59, 128, 133, 138, 139, 50, 38, 71, 121, 93, 0, 89 }; static const yytype_int8 yycheck[] = { 1, 4, 3, 3, 3, 45, 0, 58, 9, 10, 58, 42, 43, 4, 65, 63, 56, 0, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 3, 64, 47, 57, 58, 59, 9, 1, 8, 52, 3, 3, 45, 48, 8, 47, 9, 53, 48, 62, 63, 64, 63, 66, 56, 67, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 1, 44, 54, 51, 56, 53, 55, 8, 121, 62, 63, 64, 1, 66, 48, 46, 5, 6, 7, 62, 63, 64, 11, 66, 55, 67, 5, 6, 7, 60, 61, 50, 11, 48, 12, 13, 14, 15, 16, 17, 57, 58, 87, 88, 48, 48, 8, 8, 8, 8, 8, 8, 54, 52, 49, 8, 4, 4, 66, 68, 3, 45, 47, 37, 27, 55, 78, 74, -1, 69 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 70, 71, 0, 1, 72, 5, 6, 7, 11, 73, 74, 76, 77, 79, 1, 8, 75, 12, 13, 14, 15, 16, 17, 78, 53, 80, 83, 8, 48, 48, 48, 48, 48, 48, 55, 82, 50, 80, 8, 8, 8, 8, 8, 8, 54, 1, 8, 84, 85, 79, 1, 3, 9, 10, 52, 62, 63, 64, 66, 81, 86, 87, 88, 89, 90, 91, 92, 54, 56, 51, 86, 95, 87, 52, 93, 49, 57, 58, 59, 87, 44, 90, 46, 55, 60, 61, 42, 43, 85, 3, 63, 65, 93, 3, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 67, 94, 89, 57, 4, 4, 92, 92, 67, 68, 45, 56, 47, 56, 3, 4, 45, 4, 47, 45, 47 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 69, 70, 71, 72, 72, 72, 72, 73, 74, 74, 75, 75, 75, 76, 77, 77, 78, 78, 78, 78, 78, 78, 79, 79, 79, 80, 81, 81, 81, 81, 82, 83, 83, 83, 84, 84, 84, 85, 86, 86, 86, 86, 87, 87, 88, 89, 89, 89, 89, 89, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 91, 91, 91, 92, 92, 93, 93, 93, 93, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 95, 95 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 5, 0, 3, 2, 0, 1, 1, 1, 1, 2, 1, 1, 2, 2, 0, 3, 3, 3, 3, 3, 3, 5, 5, 0, 0, 2, 1, 1, 1, 0, 4, 3, 0, 3, 1, 1, 1, 2, 3, 2, 1, 3, 1, 2, 2, 1, 6, 5, 4, 2, 2, 2, 6, 5, 4, 1, 1, 1, 3, 3, 1, 3, 3, 1, 3, 4, 4, 2, 2, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 0 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*----------------------------------------. | Print this symbol's value on YYOUTPUT. | `----------------------------------------*/ static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) { FILE *yyo = yyoutput; YYUSE (yyo); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # endif YYUSE (yytype); } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) { YYFPRINTF (yyoutput, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule) { unsigned long int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) ); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, Rule); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T yystrlen (const char *yystr) { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) { YYUSE (yyvaluep); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YYUSE (yytype); YY_IGNORE_MAYBE_UNINITIALIZED_END } /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ YYSTYPE yylval; /* Number of syntax errors so far. */ int yynerrs; /*----------. | yyparse. | `----------*/ int yyparse (void) { int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 119 "parse.y" /* yacc.c:1646 */ { /* add default rule */ int def_rule; pat = cclinit(); cclnegate( pat ); def_rule = mkstate( -pat ); /* Remember the number of the default rule so we * don't generate "can't match" warnings for it. */ default_rule = num_rules; finish_rule( def_rule, false, 0, 0, 0); for ( i = 1; i <= lastsc; ++i ) scset[i] = mkbranch( scset[i], def_rule ); if ( spprdflt ) add_action( "YY_FATAL_ERROR( \"flex scanner jammed\" )" ); else add_action( "ECHO" ); add_action( ";\n\tYY_BREAK\n" ); } #line 1512 "parse.c" /* yacc.c:1646 */ break; case 3: #line 148 "parse.y" /* yacc.c:1646 */ { /* initialize for processing rules */ /* Create default DFA start condition. */ scinstal( "INITIAL", false ); } #line 1522 "parse.c" /* yacc.c:1646 */ break; case 7: #line 159 "parse.y" /* yacc.c:1646 */ { synerr( _("unknown error processing section 1") ); } #line 1528 "parse.c" /* yacc.c:1646 */ break; case 8: #line 163 "parse.y" /* yacc.c:1646 */ { check_options(); scon_stk = allocate_integer_array( lastsc + 1 ); scon_stk_ptr = 0; } #line 1538 "parse.c" /* yacc.c:1646 */ break; case 9: #line 171 "parse.y" /* yacc.c:1646 */ { xcluflg = false; } #line 1544 "parse.c" /* yacc.c:1646 */ break; case 10: #line 174 "parse.y" /* yacc.c:1646 */ { xcluflg = true; } #line 1550 "parse.c" /* yacc.c:1646 */ break; case 11: #line 178 "parse.y" /* yacc.c:1646 */ { scinstal( nmstr, xcluflg ); } #line 1556 "parse.c" /* yacc.c:1646 */ break; case 12: #line 181 "parse.y" /* yacc.c:1646 */ { scinstal( nmstr, xcluflg ); } #line 1562 "parse.c" /* yacc.c:1646 */ break; case 13: #line 184 "parse.y" /* yacc.c:1646 */ { synerr( _("bad start condition list") ); } #line 1568 "parse.c" /* yacc.c:1646 */ break; case 17: #line 195 "parse.y" /* yacc.c:1646 */ { outfilename = copy_string( nmstr ); did_outfilename = 1; } #line 1577 "parse.c" /* yacc.c:1646 */ break; case 18: #line 200 "parse.y" /* yacc.c:1646 */ { extra_type = copy_string( nmstr ); } #line 1583 "parse.c" /* yacc.c:1646 */ break; case 19: #line 202 "parse.y" /* yacc.c:1646 */ { prefix = copy_string( nmstr ); } #line 1589 "parse.c" /* yacc.c:1646 */ break; case 20: #line 204 "parse.y" /* yacc.c:1646 */ { yyclass = copy_string( nmstr ); } #line 1595 "parse.c" /* yacc.c:1646 */ break; case 21: #line 206 "parse.y" /* yacc.c:1646 */ { headerfilename = copy_string( nmstr ); } #line 1601 "parse.c" /* yacc.c:1646 */ break; case 22: #line 208 "parse.y" /* yacc.c:1646 */ { tablesext = true; tablesfilename = copy_string( nmstr ); } #line 1607 "parse.c" /* yacc.c:1646 */ break; case 23: #line 212 "parse.y" /* yacc.c:1646 */ { scon_stk_ptr = (yyvsp[-3]); } #line 1613 "parse.c" /* yacc.c:1646 */ break; case 24: #line 214 "parse.y" /* yacc.c:1646 */ { scon_stk_ptr = (yyvsp[-3]); } #line 1619 "parse.c" /* yacc.c:1646 */ break; case 26: #line 219 "parse.y" /* yacc.c:1646 */ { /* Initialize for a parse of one rule. */ trlcontxt = variable_trail_rule = varlength = false; trailcnt = headcnt = rulelen = 0; current_state_type = STATE_NORMAL; previous_continued_action = continued_action; in_rule = true; new_rule(); } #line 1634 "parse.c" /* yacc.c:1646 */ break; case 27: #line 232 "parse.y" /* yacc.c:1646 */ { pat = (yyvsp[0]); finish_rule( pat, variable_trail_rule, headcnt, trailcnt , previous_continued_action); if ( scon_stk_ptr > 0 ) { for ( i = 1; i <= scon_stk_ptr; ++i ) scbol[scon_stk[i]] = mkbranch( scbol[scon_stk[i]], pat ); } else { /* Add to all non-exclusive start conditions, * including the default (0) start condition. */ for ( i = 1; i <= lastsc; ++i ) if ( ! scxclu[i] ) scbol[i] = mkbranch( scbol[i], pat ); } if ( ! bol_needed ) { bol_needed = true; if ( performance_report > 1 ) pinpoint_message( "'^' operator results in sub-optimal performance" ); } } #line 1673 "parse.c" /* yacc.c:1646 */ break; case 28: #line 268 "parse.y" /* yacc.c:1646 */ { pat = (yyvsp[0]); finish_rule( pat, variable_trail_rule, headcnt, trailcnt , previous_continued_action); if ( scon_stk_ptr > 0 ) { for ( i = 1; i <= scon_stk_ptr; ++i ) scset[scon_stk[i]] = mkbranch( scset[scon_stk[i]], pat ); } else { for ( i = 1; i <= lastsc; ++i ) if ( ! scxclu[i] ) scset[i] = mkbranch( scset[i], pat ); } } #line 1700 "parse.c" /* yacc.c:1646 */ break; case 29: #line 292 "parse.y" /* yacc.c:1646 */ { if ( scon_stk_ptr > 0 ) build_eof_action(); else { /* This EOF applies to all start conditions * which don't already have EOF actions. */ for ( i = 1; i <= lastsc; ++i ) if ( ! sceof[i] ) scon_stk[++scon_stk_ptr] = i; if ( scon_stk_ptr == 0 ) warn( "all start conditions already have <> rules" ); else build_eof_action(); } } #line 1726 "parse.c" /* yacc.c:1646 */ break; case 30: #line 315 "parse.y" /* yacc.c:1646 */ { synerr( _("unrecognized rule") ); } #line 1732 "parse.c" /* yacc.c:1646 */ break; case 31: #line 319 "parse.y" /* yacc.c:1646 */ { (yyval) = scon_stk_ptr; } #line 1738 "parse.c" /* yacc.c:1646 */ break; case 32: #line 323 "parse.y" /* yacc.c:1646 */ { (yyval) = (yyvsp[-2]); } #line 1744 "parse.c" /* yacc.c:1646 */ break; case 33: #line 326 "parse.y" /* yacc.c:1646 */ { (yyval) = scon_stk_ptr; for ( i = 1; i <= lastsc; ++i ) { int j; for ( j = 1; j <= scon_stk_ptr; ++j ) if ( scon_stk[j] == i ) break; if ( j > scon_stk_ptr ) scon_stk[++scon_stk_ptr] = i; } } #line 1764 "parse.c" /* yacc.c:1646 */ break; case 34: #line 343 "parse.y" /* yacc.c:1646 */ { (yyval) = scon_stk_ptr; } #line 1770 "parse.c" /* yacc.c:1646 */ break; case 37: #line 351 "parse.y" /* yacc.c:1646 */ { synerr( _("bad start condition list") ); } #line 1776 "parse.c" /* yacc.c:1646 */ break; case 38: #line 355 "parse.y" /* yacc.c:1646 */ { if ( (scnum = sclookup( nmstr )) == 0 ) format_pinpoint_message( "undeclared start condition %s", nmstr ); else { for ( i = 1; i <= scon_stk_ptr; ++i ) if ( scon_stk[i] == scnum ) { format_warn( "<%s> specified twice", scname[scnum] ); break; } if ( i > scon_stk_ptr ) scon_stk[++scon_stk_ptr] = scnum; } } #line 1801 "parse.c" /* yacc.c:1646 */ break; case 39: #line 378 "parse.y" /* yacc.c:1646 */ { if ( transchar[lastst[(yyvsp[0])]] != SYM_EPSILON ) /* Provide final transition \now/ so it * will be marked as a trailing context * state. */ (yyvsp[0]) = link_machines( (yyvsp[0]), mkstate( SYM_EPSILON ) ); mark_beginning_as_normal( (yyvsp[0]) ); current_state_type = STATE_NORMAL; if ( previous_continued_action ) { /* We need to treat this as variable trailing * context so that the backup does not happen * in the action but before the action switch * statement. If the backup happens in the * action, then the rules "falling into" this * one's action will *also* do the backup, * erroneously. */ if ( ! varlength || headcnt != 0 ) warn( "trailing context made variable due to preceding '|' action" ); /* Mark as variable. */ varlength = true; headcnt = 0; } if ( lex_compat || (varlength && headcnt == 0) ) { /* variable trailing context rule */ /* Mark the first part of the rule as the * accepting "head" part of a trailing * context rule. * * By the way, we didn't do this at the * beginning of this production because back * then current_state_type was set up for a * trail rule, and add_accept() can create * a new state ... */ add_accept( (yyvsp[-1]), num_rules | YY_TRAILING_HEAD_MASK ); variable_trail_rule = true; } else trailcnt = rulelen; (yyval) = link_machines( (yyvsp[-1]), (yyvsp[0]) ); } #line 1860 "parse.c" /* yacc.c:1646 */ break; case 40: #line 434 "parse.y" /* yacc.c:1646 */ { synerr( _("trailing context used twice") ); } #line 1866 "parse.c" /* yacc.c:1646 */ break; case 41: #line 437 "parse.y" /* yacc.c:1646 */ { headcnt = 0; trailcnt = 1; rulelen = 1; varlength = false; current_state_type = STATE_TRAILING_CONTEXT; if ( trlcontxt ) { synerr( _("trailing context used twice") ); (yyval) = mkstate( SYM_EPSILON ); } else if ( previous_continued_action ) { /* See the comment in the rule for "re2 re" * above. */ warn( "trailing context made variable due to preceding '|' action" ); varlength = true; } if ( lex_compat || varlength ) { /* Again, see the comment in the rule for * "re2 re" above. */ add_accept( (yyvsp[-1]), num_rules | YY_TRAILING_HEAD_MASK ); variable_trail_rule = true; } trlcontxt = true; eps = mkstate( SYM_EPSILON ); (yyval) = link_machines( (yyvsp[-1]), link_machines( eps, mkstate( '\n' ) ) ); } #line 1912 "parse.c" /* yacc.c:1646 */ break; case 42: #line 480 "parse.y" /* yacc.c:1646 */ { (yyval) = (yyvsp[0]); if ( trlcontxt ) { if ( lex_compat || (varlength && headcnt == 0) ) /* Both head and trail are * variable-length. */ variable_trail_rule = true; else trailcnt = rulelen; } } #line 1931 "parse.c" /* yacc.c:1646 */ break; case 43: #line 498 "parse.y" /* yacc.c:1646 */ { varlength = true; (yyval) = mkor( (yyvsp[-2]), (yyvsp[0]) ); } #line 1940 "parse.c" /* yacc.c:1646 */ break; case 44: #line 504 "parse.y" /* yacc.c:1646 */ { (yyval) = (yyvsp[0]); } #line 1946 "parse.c" /* yacc.c:1646 */ break; case 45: #line 509 "parse.y" /* yacc.c:1646 */ { /* This rule is written separately so the * reduction will occur before the trailing * series is parsed. */ if ( trlcontxt ) synerr( _("trailing context used twice") ); else trlcontxt = true; if ( varlength ) /* We hope the trailing context is * fixed-length. */ varlength = false; else headcnt = rulelen; rulelen = 0; current_state_type = STATE_TRAILING_CONTEXT; (yyval) = (yyvsp[-1]); } #line 1975 "parse.c" /* yacc.c:1646 */ break; case 46: #line 536 "parse.y" /* yacc.c:1646 */ { /* This is where concatenation of adjacent patterns * gets done. */ (yyval) = link_machines( (yyvsp[-1]), (yyvsp[0]) ); } #line 1986 "parse.c" /* yacc.c:1646 */ break; case 47: #line 544 "parse.y" /* yacc.c:1646 */ { (yyval) = (yyvsp[0]); } #line 1992 "parse.c" /* yacc.c:1646 */ break; case 48: #line 547 "parse.y" /* yacc.c:1646 */ { varlength = true; if ( (yyvsp[-3]) > (yyvsp[-1]) || (yyvsp[-3]) < 0 ) { synerr( _("bad iteration values") ); (yyval) = (yyvsp[-5]); } else { if ( (yyvsp[-3]) == 0 ) { if ( (yyvsp[-1]) <= 0 ) { synerr( _("bad iteration values") ); (yyval) = (yyvsp[-5]); } else (yyval) = mkopt( mkrep( (yyvsp[-5]), 1, (yyvsp[-1]) ) ); } else (yyval) = mkrep( (yyvsp[-5]), (yyvsp[-3]), (yyvsp[-1]) ); } } #line 2023 "parse.c" /* yacc.c:1646 */ break; case 49: #line 575 "parse.y" /* yacc.c:1646 */ { varlength = true; if ( (yyvsp[-2]) <= 0 ) { synerr( _("iteration value must be positive") ); (yyval) = (yyvsp[-4]); } else (yyval) = mkrep( (yyvsp[-4]), (yyvsp[-2]), INFINITE_REPEAT ); } #line 2040 "parse.c" /* yacc.c:1646 */ break; case 50: #line 589 "parse.y" /* yacc.c:1646 */ { /* The series could be something like "(foo)", * in which case we have no idea what its length * is, so we punt here. */ varlength = true; if ( (yyvsp[-1]) <= 0 ) { synerr( _("iteration value must be positive") ); (yyval) = (yyvsp[-3]); } else (yyval) = link_machines( (yyvsp[-3]), copysingl( (yyvsp[-3]), (yyvsp[-1]) - 1 ) ); } #line 2063 "parse.c" /* yacc.c:1646 */ break; case 51: #line 611 "parse.y" /* yacc.c:1646 */ { varlength = true; (yyval) = mkclos( (yyvsp[-1]) ); } #line 2073 "parse.c" /* yacc.c:1646 */ break; case 52: #line 618 "parse.y" /* yacc.c:1646 */ { varlength = true; (yyval) = mkposcl( (yyvsp[-1]) ); } #line 2082 "parse.c" /* yacc.c:1646 */ break; case 53: #line 624 "parse.y" /* yacc.c:1646 */ { varlength = true; (yyval) = mkopt( (yyvsp[-1]) ); } #line 2091 "parse.c" /* yacc.c:1646 */ break; case 54: #line 630 "parse.y" /* yacc.c:1646 */ { varlength = true; if ( (yyvsp[-3]) > (yyvsp[-1]) || (yyvsp[-3]) < 0 ) { synerr( _("bad iteration values") ); (yyval) = (yyvsp[-5]); } else { if ( (yyvsp[-3]) == 0 ) { if ( (yyvsp[-1]) <= 0 ) { synerr( _("bad iteration values") ); (yyval) = (yyvsp[-5]); } else (yyval) = mkopt( mkrep( (yyvsp[-5]), 1, (yyvsp[-1]) ) ); } else (yyval) = mkrep( (yyvsp[-5]), (yyvsp[-3]), (yyvsp[-1]) ); } } #line 2122 "parse.c" /* yacc.c:1646 */ break; case 55: #line 658 "parse.y" /* yacc.c:1646 */ { varlength = true; if ( (yyvsp[-2]) <= 0 ) { synerr( _("iteration value must be positive") ); (yyval) = (yyvsp[-4]); } else (yyval) = mkrep( (yyvsp[-4]), (yyvsp[-2]), INFINITE_REPEAT ); } #line 2139 "parse.c" /* yacc.c:1646 */ break; case 56: #line 672 "parse.y" /* yacc.c:1646 */ { /* The singleton could be something like "(foo)", * in which case we have no idea what its length * is, so we punt here. */ varlength = true; if ( (yyvsp[-1]) <= 0 ) { synerr( _("iteration value must be positive") ); (yyval) = (yyvsp[-3]); } else (yyval) = link_machines( (yyvsp[-3]), copysingl( (yyvsp[-3]), (yyvsp[-1]) - 1 ) ); } #line 2161 "parse.c" /* yacc.c:1646 */ break; case 57: #line 691 "parse.y" /* yacc.c:1646 */ { if ( ! madeany ) { /* Create the '.' character class. */ ccldot = cclinit(); ccladd( ccldot, '\n' ); cclnegate( ccldot ); if ( useecs ) mkeccl( ccltbl + cclmap[ccldot], ccllen[ccldot], nextecm, ecgroup, csize, csize ); /* Create the (?s:'.') character class. */ cclany = cclinit(); cclnegate( cclany ); if ( useecs ) mkeccl( ccltbl + cclmap[cclany], ccllen[cclany], nextecm, ecgroup, csize, csize ); madeany = true; } ++rulelen; if (sf_dot_all()) (yyval) = mkstate( -cclany ); else (yyval) = mkstate( -ccldot ); } #line 2198 "parse.c" /* yacc.c:1646 */ break; case 58: #line 725 "parse.y" /* yacc.c:1646 */ { /* Sort characters for fast searching. */ qsort( ccltbl + cclmap[(yyvsp[0])], ccllen[(yyvsp[0])], sizeof (*ccltbl), cclcmp ); if ( useecs ) mkeccl( ccltbl + cclmap[(yyvsp[0])], ccllen[(yyvsp[0])], nextecm, ecgroup, csize, csize ); ++rulelen; if (ccl_has_nl[(yyvsp[0])]) rule_has_nl[num_rules] = true; (yyval) = mkstate( -(yyvsp[0]) ); } #line 2219 "parse.c" /* yacc.c:1646 */ break; case 59: #line 743 "parse.y" /* yacc.c:1646 */ { ++rulelen; if (ccl_has_nl[(yyvsp[0])]) rule_has_nl[num_rules] = true; (yyval) = mkstate( -(yyvsp[0]) ); } #line 2232 "parse.c" /* yacc.c:1646 */ break; case 60: #line 753 "parse.y" /* yacc.c:1646 */ { (yyval) = (yyvsp[-1]); } #line 2238 "parse.c" /* yacc.c:1646 */ break; case 61: #line 756 "parse.y" /* yacc.c:1646 */ { (yyval) = (yyvsp[-1]); } #line 2244 "parse.c" /* yacc.c:1646 */ break; case 62: #line 759 "parse.y" /* yacc.c:1646 */ { ++rulelen; if ((yyvsp[0]) == nlch) rule_has_nl[num_rules] = true; if (sf_case_ins() && has_case((yyvsp[0]))) /* create an alternation, as in (a|A) */ (yyval) = mkor (mkstate((yyvsp[0])), mkstate(reverse_case((yyvsp[0])))); else (yyval) = mkstate( (yyvsp[0]) ); } #line 2261 "parse.c" /* yacc.c:1646 */ break; case 63: #line 773 "parse.y" /* yacc.c:1646 */ { (yyval) = ccl_set_diff ((yyvsp[-2]), (yyvsp[0])); } #line 2267 "parse.c" /* yacc.c:1646 */ break; case 64: #line 774 "parse.y" /* yacc.c:1646 */ { (yyval) = ccl_set_union ((yyvsp[-2]), (yyvsp[0])); } #line 2273 "parse.c" /* yacc.c:1646 */ break; case 66: #line 780 "parse.y" /* yacc.c:1646 */ { (yyval) = (yyvsp[-1]); } #line 2279 "parse.c" /* yacc.c:1646 */ break; case 67: #line 783 "parse.y" /* yacc.c:1646 */ { cclnegate( (yyvsp[-1]) ); (yyval) = (yyvsp[-1]); } #line 2288 "parse.c" /* yacc.c:1646 */ break; case 68: #line 790 "parse.y" /* yacc.c:1646 */ { if (sf_case_ins()) { /* If one end of the range has case and the other * does not, or the cases are different, then we're not * sure what range the user is trying to express. * Examples: [@-z] or [S-t] */ if (has_case ((yyvsp[-2])) != has_case ((yyvsp[0])) || (has_case ((yyvsp[-2])) && (b_islower ((yyvsp[-2])) != b_islower ((yyvsp[0])))) || (has_case ((yyvsp[-2])) && (b_isupper ((yyvsp[-2])) != b_isupper ((yyvsp[0]))))) format_warn3 ( _("the character range [%c-%c] is ambiguous in a case-insensitive scanner"), (yyvsp[-2]), (yyvsp[0])); /* If the range spans uppercase characters but not * lowercase (or vice-versa), then should we automatically * include lowercase characters in the range? * Example: [@-_] spans [a-z] but not [A-Z] */ else if (!has_case ((yyvsp[-2])) && !has_case ((yyvsp[0])) && !range_covers_case ((yyvsp[-2]), (yyvsp[0]))) format_warn3 ( _("the character range [%c-%c] is ambiguous in a case-insensitive scanner"), (yyvsp[-2]), (yyvsp[0])); } if ( (yyvsp[-2]) > (yyvsp[0]) ) synerr( _("negative range in character class") ); else { for ( i = (yyvsp[-2]); i <= (yyvsp[0]); ++i ) ccladd( (yyvsp[-3]), i ); /* Keep track if this ccl is staying in * alphabetical order. */ cclsorted = cclsorted && ((yyvsp[-2]) > lastchar); lastchar = (yyvsp[0]); /* Do it again for upper/lowercase */ if (sf_case_ins() && has_case((yyvsp[-2])) && has_case((yyvsp[0]))){ (yyvsp[-2]) = reverse_case ((yyvsp[-2])); (yyvsp[0]) = reverse_case ((yyvsp[0])); for ( i = (yyvsp[-2]); i <= (yyvsp[0]); ++i ) ccladd( (yyvsp[-3]), i ); cclsorted = cclsorted && ((yyvsp[-2]) > lastchar); lastchar = (yyvsp[0]); } } (yyval) = (yyvsp[-3]); } #line 2351 "parse.c" /* yacc.c:1646 */ break; case 69: #line 850 "parse.y" /* yacc.c:1646 */ { ccladd( (yyvsp[-1]), (yyvsp[0]) ); cclsorted = cclsorted && ((yyvsp[0]) > lastchar); lastchar = (yyvsp[0]); /* Do it again for upper/lowercase */ if (sf_case_ins() && has_case((yyvsp[0]))){ (yyvsp[0]) = reverse_case ((yyvsp[0])); ccladd ((yyvsp[-1]), (yyvsp[0])); cclsorted = cclsorted && ((yyvsp[0]) > lastchar); lastchar = (yyvsp[0]); } (yyval) = (yyvsp[-1]); } #line 2372 "parse.c" /* yacc.c:1646 */ break; case 70: #line 868 "parse.y" /* yacc.c:1646 */ { /* Too hard to properly maintain cclsorted. */ cclsorted = false; (yyval) = (yyvsp[-1]); } #line 2382 "parse.c" /* yacc.c:1646 */ break; case 71: #line 875 "parse.y" /* yacc.c:1646 */ { cclsorted = true; lastchar = 0; currccl = (yyval) = cclinit(); } #line 2392 "parse.c" /* yacc.c:1646 */ break; case 72: #line 883 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(isalnum); } #line 2398 "parse.c" /* yacc.c:1646 */ break; case 73: #line 884 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(isalpha); } #line 2404 "parse.c" /* yacc.c:1646 */ break; case 74: #line 885 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(IS_BLANK); } #line 2410 "parse.c" /* yacc.c:1646 */ break; case 75: #line 886 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(iscntrl); } #line 2416 "parse.c" /* yacc.c:1646 */ break; case 76: #line 887 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(isdigit); } #line 2422 "parse.c" /* yacc.c:1646 */ break; case 77: #line 888 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(isgraph); } #line 2428 "parse.c" /* yacc.c:1646 */ break; case 78: #line 889 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(islower); if (sf_case_ins()) CCL_EXPR(isupper); } #line 2438 "parse.c" /* yacc.c:1646 */ break; case 79: #line 894 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(isprint); } #line 2444 "parse.c" /* yacc.c:1646 */ break; case 80: #line 895 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(ispunct); } #line 2450 "parse.c" /* yacc.c:1646 */ break; case 81: #line 896 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(isspace); } #line 2456 "parse.c" /* yacc.c:1646 */ break; case 82: #line 897 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(isxdigit); } #line 2462 "parse.c" /* yacc.c:1646 */ break; case 83: #line 898 "parse.y" /* yacc.c:1646 */ { CCL_EXPR(isupper); if (sf_case_ins()) CCL_EXPR(islower); } #line 2472 "parse.c" /* yacc.c:1646 */ break; case 84: #line 904 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(isalnum); } #line 2478 "parse.c" /* yacc.c:1646 */ break; case 85: #line 905 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(isalpha); } #line 2484 "parse.c" /* yacc.c:1646 */ break; case 86: #line 906 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(IS_BLANK); } #line 2490 "parse.c" /* yacc.c:1646 */ break; case 87: #line 907 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(iscntrl); } #line 2496 "parse.c" /* yacc.c:1646 */ break; case 88: #line 908 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(isdigit); } #line 2502 "parse.c" /* yacc.c:1646 */ break; case 89: #line 909 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(isgraph); } #line 2508 "parse.c" /* yacc.c:1646 */ break; case 90: #line 910 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(isprint); } #line 2514 "parse.c" /* yacc.c:1646 */ break; case 91: #line 911 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(ispunct); } #line 2520 "parse.c" /* yacc.c:1646 */ break; case 92: #line 912 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(isspace); } #line 2526 "parse.c" /* yacc.c:1646 */ break; case 93: #line 913 "parse.y" /* yacc.c:1646 */ { CCL_NEG_EXPR(isxdigit); } #line 2532 "parse.c" /* yacc.c:1646 */ break; case 94: #line 914 "parse.y" /* yacc.c:1646 */ { if ( sf_case_ins() ) warn(_("[:^lower:] is ambiguous in case insensitive scanner")); else CCL_NEG_EXPR(islower); } #line 2543 "parse.c" /* yacc.c:1646 */ break; case 95: #line 920 "parse.y" /* yacc.c:1646 */ { if ( sf_case_ins() ) warn(_("[:^upper:] ambiguous in case insensitive scanner")); else CCL_NEG_EXPR(isupper); } #line 2554 "parse.c" /* yacc.c:1646 */ break; case 96: #line 929 "parse.y" /* yacc.c:1646 */ { if ( (yyvsp[0]) == nlch ) rule_has_nl[num_rules] = true; ++rulelen; if (sf_case_ins() && has_case((yyvsp[0]))) (yyval) = mkor (mkstate((yyvsp[0])), mkstate(reverse_case((yyvsp[0])))); else (yyval) = mkstate ((yyvsp[0])); (yyval) = link_machines( (yyvsp[-1]), (yyval)); } #line 2572 "parse.c" /* yacc.c:1646 */ break; case 97: #line 944 "parse.y" /* yacc.c:1646 */ { (yyval) = mkstate( SYM_EPSILON ); } #line 2578 "parse.c" /* yacc.c:1646 */ break; #line 2582 "parse.c" /* yacc.c:1646 */ default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } #line 947 "parse.y" /* yacc.c:1906 */ /* build_eof_action - build the "<>" action for the active start * conditions */ void build_eof_action() { int i; char action_text[MAXLINE]; for ( i = 1; i <= scon_stk_ptr; ++i ) { if ( sceof[scon_stk[i]] ) format_pinpoint_message( "multiple <> rules for start condition %s", scname[scon_stk[i]] ); else { sceof[scon_stk[i]] = true; if (previous_continued_action /* && previous action was regular */) add_action("YY_RULE_SETUP\n"); snprintf( action_text, sizeof(action_text), "case YY_STATE_EOF(%s):\n", scname[scon_stk[i]] ); add_action( action_text ); } } line_directive_out( (FILE *) 0, 1 ); /* This isn't a normal rule after all - don't count it as * such, so we don't have any holes in the rule numbering * (which make generating "rule can never match" warnings * more difficult. */ --num_rules; ++num_eof_rules; } /* format_synerr - write out formatted syntax error */ void format_synerr( msg, arg ) const char *msg, arg[]; { char errmsg[MAXLINE]; (void) snprintf( errmsg, sizeof(errmsg), msg, arg ); synerr( errmsg ); } /* synerr - report a syntax error */ void synerr( str ) const char *str; { syntaxerror = true; pinpoint_message( str ); } /* format_warn - write out formatted warning */ void format_warn( msg, arg ) const char *msg, arg[]; { char warn_msg[MAXLINE]; snprintf( warn_msg, sizeof(warn_msg), msg, arg ); warn( warn_msg ); } /* warn - report a warning, unless -w was given */ void warn( str ) const char *str; { line_warning( str, linenum ); } /* format_pinpoint_message - write out a message formatted with one string, * pinpointing its location */ void format_pinpoint_message( msg, arg ) const char *msg, arg[]; { char errmsg[MAXLINE]; snprintf( errmsg, sizeof(errmsg), msg, arg ); pinpoint_message( errmsg ); } /* pinpoint_message - write out a message, pinpointing its location */ void pinpoint_message( str ) const char *str; { line_pinpoint( str, linenum ); } /* line_warning - report a warning at a given line, unless -w was given */ void line_warning( str, line ) const char *str; int line; { char warning[MAXLINE]; if ( ! nowarn ) { snprintf( warning, sizeof(warning), "warning, %s", str ); line_pinpoint( warning, line ); } } /* line_pinpoint - write out a message, pinpointing it at the given line */ void line_pinpoint( str, line ) const char *str; int line; { fprintf( stderr, "%s:%d: %s\n", infilename, line, str ); } /* yyerror - eat up an error message from the parser; * currently, messages are ignore */ void yyerror( msg ) const char *msg; { (void)msg; } flex-2.6.0/src/tables_shared.c0000644000175000017500000000424012620474534016471 0ustar srivastasrivasta#ifdef FLEX_SCANNER /* dnl tables_shared.c - tables serialization code dnl dnl Copyright (c) 1990 The Regents of the University of California. dnl All rights reserved. dnl dnl This code is derived from software contributed to Berkeley by dnl Vern Paxson. dnl dnl The United States Government has rights in this work pursuant dnl to contract no. DE-AC03-76SF00098 between the United States dnl Department of Energy and the University of California. dnl dnl This file is part of flex. dnl dnl Redistribution and use in source and binary forms, with or without dnl modification, are permitted provided that the following conditions dnl are met: dnl dnl 1. Redistributions of source code must retain the above copyright dnl notice, this list of conditions and the following disclaimer. dnl 2. Redistributions in binary form must reproduce the above copyright dnl notice, this list of conditions and the following disclaimer in the dnl documentation and/or other materials provided with the distribution. dnl dnl Neither the name of the University nor the names of its contributors dnl may be used to endorse or promote products derived from this software dnl without specific prior written permission. dnl dnl THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR dnl IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED dnl WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR dnl PURPOSE. dnl */ /* This file is meant to be included in both the skeleton and the actual * flex code (hence the name "_shared"). */ #ifndef yyskel_static #define yyskel_static static #endif #else #include "flexdef.h" #include "tables.h" #ifndef yyskel_static #define yyskel_static #endif #endif /** Get the number of integers in this table. This is NOT the * same thing as the number of elements. * @param tbl the table * @return the number of integers in the table */ yyskel_static flex_int32_t yytbl_calc_total_len (const struct yytbl_data *tbl) { flex_int32_t n; /* total number of ints */ n = tbl->td_lolen; if (tbl->td_hilen > 0) n *= tbl->td_hilen; if (tbl->td_id == YYTD_ID_TRANSITION) n *= 2; return n; } flex-2.6.0/src/scanflags.c0000644000175000017500000000434012620472752015633 0ustar srivastasrivasta/* scanflags - flags used by scanning. */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" scanflags_t* _sf_stk = NULL; size_t _sf_top_ix=0, _sf_max=0; void sf_push (void) { if (_sf_top_ix + 1 >= _sf_max) _sf_stk = (scanflags_t*) flex_realloc ( (void*) _sf_stk, sizeof(scanflags_t) * (_sf_max += 32)); // copy the top element _sf_stk[_sf_top_ix + 1] = _sf_stk[_sf_top_ix]; ++_sf_top_ix; } void sf_pop (void) { assert(_sf_top_ix > 0); --_sf_top_ix; } /* one-time initialization. Should be called before any sf_ functions. */ void sf_init (void) { assert(_sf_stk == NULL); _sf_stk = (scanflags_t*) flex_alloc ( sizeof(scanflags_t) * (_sf_max = 32)); if (!_sf_stk) lerr_fatal(_("Unable to allocate %zu of stack"), sizeof(scanflags_t)); _sf_stk[_sf_top_ix] = 0; } /* vim:set expandtab cindent tabstop=4 softtabstop=4 shiftwidth=4 textwidth=0: */ flex-2.6.0/src/version.h0000644000175000017500000000003512620472752015361 0ustar srivastasrivasta#define FLEX_VERSION VERSION flex-2.6.0/src/sym.c0000644000175000017500000001501212620472752014500 0ustar srivastasrivasta/* sym - symbol table routines */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" /* Variables for symbol tables: * sctbl - start-condition symbol table * ndtbl - name-definition symbol table * ccltab - character class text symbol table */ struct hash_entry { struct hash_entry *prev, *next; char *name; char *str_val; int int_val; }; typedef struct hash_entry **hash_table; #define NAME_TABLE_HASH_SIZE 101 #define START_COND_HASH_SIZE 101 #define CCL_HASH_SIZE 101 static struct hash_entry *ndtbl[NAME_TABLE_HASH_SIZE]; static struct hash_entry *sctbl[START_COND_HASH_SIZE]; static struct hash_entry *ccltab[CCL_HASH_SIZE]; /* declare functions that have forward references */ static int addsym PROTO ((char[], char *, int, hash_table, int)); static struct hash_entry *findsym PROTO ((const char *sym, hash_table table, int table_size)); static int hashfunct PROTO ((const char *, int)); /* addsym - add symbol and definitions to symbol table * * -1 is returned if the symbol already exists, and the change not made. */ static int addsym (sym, str_def, int_def, table, table_size) char sym[]; char *str_def; int int_def; hash_table table; int table_size; { int hash_val = hashfunct (sym, table_size); struct hash_entry *sym_entry = table[hash_val]; struct hash_entry *new_entry; struct hash_entry *successor; while (sym_entry) { if (!strcmp (sym, sym_entry->name)) { /* entry already exists */ return -1; } sym_entry = sym_entry->next; } /* create new entry */ new_entry = (struct hash_entry *) flex_alloc (sizeof (struct hash_entry)); if (new_entry == NULL) flexfatal (_("symbol table memory allocation failed")); if ((successor = table[hash_val]) != 0) { new_entry->next = successor; successor->prev = new_entry; } else new_entry->next = NULL; new_entry->prev = NULL; new_entry->name = sym; new_entry->str_val = str_def; new_entry->int_val = int_def; table[hash_val] = new_entry; return 0; } /* cclinstal - save the text of a character class */ void cclinstal (ccltxt, cclnum) Char ccltxt[]; int cclnum; { /* We don't bother checking the return status because we are not * called unless the symbol is new. */ (void) addsym ((char *) copy_unsigned_string (ccltxt), (char *) 0, cclnum, ccltab, CCL_HASH_SIZE); } /* ccllookup - lookup the number associated with character class text * * Returns 0 if there's no CCL associated with the text. */ int ccllookup (ccltxt) Char ccltxt[]; { return findsym ((char *) ccltxt, ccltab, CCL_HASH_SIZE)->int_val; } /* findsym - find symbol in symbol table */ static struct hash_entry *findsym (sym, table, table_size) const char *sym; hash_table table; int table_size; { static struct hash_entry empty_entry = { (struct hash_entry *) 0, (struct hash_entry *) 0, (char *) 0, (char *) 0, 0, }; struct hash_entry *sym_entry = table[hashfunct (sym, table_size)]; while (sym_entry) { if (!strcmp (sym, sym_entry->name)) return sym_entry; sym_entry = sym_entry->next; } return &empty_entry; } /* hashfunct - compute the hash value for "str" and hash size "hash_size" */ static int hashfunct (str, hash_size) const char *str; int hash_size; { int hashval; int locstr; hashval = 0; locstr = 0; while (str[locstr]) { hashval = (hashval << 1) + (unsigned char) str[locstr++]; hashval %= hash_size; } return hashval; } /* ndinstal - install a name definition */ void ndinstal (name, definition) const char *name; Char definition[]; { if (addsym (copy_string (name), (char *) copy_unsigned_string (definition), 0, ndtbl, NAME_TABLE_HASH_SIZE)) synerr (_("name defined twice")); } /* ndlookup - lookup a name definition * * Returns a nil pointer if the name definition does not exist. */ Char *ndlookup (nd) const char *nd; { return (Char *) findsym (nd, ndtbl, NAME_TABLE_HASH_SIZE)->str_val; } /* scextend - increase the maximum number of start conditions */ void scextend () { current_max_scs += MAX_SCS_INCREMENT; ++num_reallocs; scset = reallocate_integer_array (scset, current_max_scs); scbol = reallocate_integer_array (scbol, current_max_scs); scxclu = reallocate_integer_array (scxclu, current_max_scs); sceof = reallocate_integer_array (sceof, current_max_scs); scname = reallocate_char_ptr_array (scname, current_max_scs); } /* scinstal - make a start condition * * NOTE * The start condition is "exclusive" if xcluflg is true. */ void scinstal (str, xcluflg) const char *str; int xcluflg; { if (++lastsc >= current_max_scs) scextend (); scname[lastsc] = copy_string (str); if (addsym (scname[lastsc], (char *) 0, lastsc, sctbl, START_COND_HASH_SIZE)) format_pinpoint_message (_ ("start condition %s declared twice"), str); scset[lastsc] = mkstate (SYM_EPSILON); scbol[lastsc] = mkstate (SYM_EPSILON); scxclu[lastsc] = xcluflg; sceof[lastsc] = false; } /* sclookup - lookup the number associated with a start condition * * Returns 0 if no such start condition. */ int sclookup (str) const char *str; { return findsym (str, sctbl, START_COND_HASH_SIZE)->int_val; } flex-2.6.0/src/gettext.h0000644000175000017500000000507412620472752015370 0ustar srivastasrivasta/* Convenience header for conditional use of GNU . Copyright (C) 1995-1998, 2000-2002 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _LIBGETTEXT_H #define _LIBGETTEXT_H 1 /* NLS can be disabled through the configure --disable-nls option. */ #if ENABLE_NLS /* Get declarations of GNU message catalog functions. */ # include #else /* Disabled NLS. The casts to 'const char *' serve the purpose of producing warnings for invalid uses of the value returned from these functions. On pre-ANSI systems without 'const', the config.h file is supposed to contain "#define const". */ # define gettext(Msgid) ((const char *) (Msgid)) # define dgettext(Domainname, Msgid) ((const char *) (Msgid)) # define dcgettext(Domainname, Msgid, Category) ((const char *) (Msgid)) # define ngettext(Msgid1, Msgid2, N) \ ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) # define dngettext(Domainname, Msgid1, Msgid2, N) \ ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) # define dcngettext(Domainname, Msgid1, Msgid2, N, Category) \ ((N) == 1 ? (const char *) (Msgid1) : (const char *) (Msgid2)) # define textdomain(Domainname) ((const char *) (Domainname)) # define bindtextdomain(Domainname, Dirname) ((const char *) (Dirname)) # define bind_textdomain_codeset(Domainname, Codeset) ((const char *) (Codeset)) #endif /* A pseudo function call that serves as a marker for the automated extraction of messages, but does not call gettext(). The run-time translation is done at a different place in the code. The argument, String, should be a literal string. Concatenated strings and other string expressions won't work. The macro's expansion is not parenthesized, so that it is suitable as initializer for static 'char[]' or 'const char[]' variables. */ #define gettext_noop(String) String #endif /* _LIBGETTEXT_H */ flex-2.6.0/src/main.c0000644000175000017500000014251512620474534014625 0ustar srivastasrivasta/* flex - tool to generate fast lexical analyzers */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" #include "version.h" #include "options.h" #include "tables.h" static char flex_version[] = FLEX_VERSION; /* declare functions that have forward references */ void flexinit PROTO ((int, char **)); void readin PROTO ((void)); void set_up_initial_allocations PROTO ((void)); static char *basename2 PROTO ((char *path, int should_strip_ext)); /* these globals are all defined and commented in flexdef.h */ int printstats, syntaxerror, eofseen, ddebug, trace, nowarn, spprdflt; int interactive, lex_compat, posix_compat, do_yylineno, useecs, fulltbl, usemecs; int fullspd, gen_line_dirs, performance_report, backing_up_report; int C_plus_plus, long_align, use_read, yytext_is_array, do_yywrap, csize; int reentrant, bison_bridge_lval, bison_bridge_lloc; int yymore_used, reject, real_reject, continued_action, in_rule; int yymore_really_used, reject_really_used; int trace_hex = 0; int datapos, dataline, linenum; FILE *skelfile = NULL; int skel_ind = 0; char *action_array; int action_size, defs1_offset, prolog_offset, action_offset, action_index; char *infilename = NULL, *outfilename = NULL, *headerfilename = NULL; int did_outfilename; char *prefix, *yyclass, *extra_type = NULL; int do_stdinit, use_stdout; int onestate[ONE_STACK_SIZE], onesym[ONE_STACK_SIZE]; int onenext[ONE_STACK_SIZE], onedef[ONE_STACK_SIZE], onesp; int maximum_mns, current_mns, current_max_rules; int num_rules, num_eof_rules, default_rule, lastnfa; int *firstst, *lastst, *finalst, *transchar, *trans1, *trans2; int *accptnum, *assoc_rule, *state_type; int *rule_type, *rule_linenum, *rule_useful; int current_state_type; int variable_trailing_context_rules; int numtemps, numprots, protprev[MSP], protnext[MSP], prottbl[MSP]; int protcomst[MSP], firstprot, lastprot, protsave[PROT_SAVE_SIZE]; int numecs, nextecm[CSIZE + 1], ecgroup[CSIZE + 1], nummecs, tecfwd[CSIZE + 1]; int tecbck[CSIZE + 1]; int lastsc, *scset, *scbol, *scxclu, *sceof; int current_max_scs; char **scname; int current_max_dfa_size, current_max_xpairs; int current_max_template_xpairs, current_max_dfas; int lastdfa, *nxt, *chk, *tnxt; int *base, *def, *nultrans, NUL_ec, tblend, firstfree, **dss, *dfasiz; union dfaacc_union *dfaacc; int *accsiz, *dhash, numas; int numsnpairs, jambase, jamstate; int lastccl, *cclmap, *ccllen, *cclng, cclreuse; int current_maxccls, current_max_ccl_tbl_size; Char *ccltbl; char nmstr[MAXLINE]; int sectnum, nummt, hshcol, dfaeql, numeps, eps2, num_reallocs; int tmpuses, totnst, peakpairs, numuniq, numdup, hshsave; int num_backing_up, bol_needed; FILE *backing_up_file; int end_of_buffer_state; char **input_files; int num_input_files; jmp_buf flex_main_jmp_buf; bool *rule_has_nl, *ccl_has_nl; int nlch = '\n'; bool ansi_func_defs, ansi_func_protos; bool tablesext, tablesverify, gentables; char *tablesfilename=0,*tablesname=0; struct yytbl_writer tableswr; /* Make sure program_name is initialized so we don't crash if writing * out an error message before getting the program name from argv[0]. */ char *program_name = "flex"; #ifndef SHORT_FILE_NAMES static const char outfile_template[] = "lex.%s.%s"; static const char backing_name[] = "lex.backup"; static const char tablesfile_template[] = "lex.%s.tables"; #else static const char outfile_template[] = "lex%s.%s"; static const char backing_name[] = "lex.bck"; static const char tablesfile_template[] = "lex%s.tbl"; #endif #ifdef MS_DOS extern unsigned _stklen = 16384; #endif /* From scan.l */ extern FILE* yyout; static char outfile_path[MAXLINE]; static int outfile_created = 0; static char *skelname = NULL; static int _stdout_closed = 0; /* flag to prevent double-fclose() on stdout. */ const char *escaped_qstart = "[[]]M4_YY_NOOP[M4_YY_NOOP[M4_YY_NOOP[[]]"; const char *escaped_qend = "[[]]M4_YY_NOOP]M4_YY_NOOP]M4_YY_NOOP[[]]"; /* For debugging. The max number of filters to apply to skeleton. */ static int preproc_level = 1000; int flex_main PROTO ((int argc, char *argv[])); int main PROTO ((int argc, char *argv[])); int flex_main (argc, argv) int argc; char *argv[]; { int i, exit_status, child_status; /* Set a longjmp target. Yes, I know it's a hack, but it gets worse: The * return value of setjmp, if non-zero, is the desired exit code PLUS ONE. * For example, if you want 'main' to return with code '2', then call * longjmp() with an argument of 3. This is because it is invalid to * specify a value of 0 to longjmp. FLEX_EXIT(n) should be used instead of * exit(n); */ exit_status = setjmp (flex_main_jmp_buf); if (exit_status){ if (stdout && !_stdout_closed && !ferror(stdout)){ fflush(stdout); fclose(stdout); } while (wait(&child_status) > 0){ if (!WIFEXITED (child_status) || WEXITSTATUS (child_status) != 0){ /* report an error of a child */ if( exit_status <= 1 ) exit_status = 2; } } return exit_status - 1; } flexinit (argc, argv); readin (); skelout (); /* %% [1.5] DFA */ ntod (); for (i = 1; i <= num_rules; ++i) if (!rule_useful[i] && i != default_rule) line_warning (_("rule cannot be matched"), rule_linenum[i]); if (spprdflt && !reject && rule_useful[default_rule]) line_warning (_ ("-s option given but default rule can be matched"), rule_linenum[default_rule]); /* Generate the C state transition tables from the DFA. */ make_tables (); /* Note, flexend does not return. It exits with its argument * as status. */ flexend (0); return 0; /* keep compilers/lint happy */ } /* Wrapper around flex_main, so flex_main can be built as a library. */ int main (argc, argv) int argc; char *argv[]; { #if ENABLE_NLS #if HAVE_LOCALE_H setlocale (LC_MESSAGES, ""); setlocale (LC_CTYPE, ""); textdomain (PACKAGE); bindtextdomain (PACKAGE, LOCALEDIR); #endif #endif return flex_main (argc, argv); } /* check_options - check user-specified options */ void check_options () { int i; const char * m4 = NULL; if (lex_compat) { if (C_plus_plus) flexerror (_("Can't use -+ with -l option")); if (fulltbl || fullspd) flexerror (_("Can't use -f or -F with -l option")); if (reentrant || bison_bridge_lval) flexerror (_ ("Can't use --reentrant or --bison-bridge with -l option")); yytext_is_array = true; do_yylineno = true; use_read = false; } #if 0 /* This makes no sense whatsoever. I'm removing it. */ if (do_yylineno) /* This should really be "maintain_backup_tables = true" */ reject_really_used = true; #endif if (csize == unspecified) { if ((fulltbl || fullspd) && !useecs) csize = DEFAULT_CSIZE; else csize = CSIZE; } if (interactive == unspecified) { if (fulltbl || fullspd) interactive = false; else interactive = true; } if (fulltbl || fullspd) { if (usemecs) flexerror (_ ("-Cf/-CF and -Cm don't make sense together")); if (interactive) flexerror (_("-Cf/-CF and -I are incompatible")); if (lex_compat) flexerror (_ ("-Cf/-CF are incompatible with lex-compatibility mode")); if (fulltbl && fullspd) flexerror (_ ("-Cf and -CF are mutually exclusive")); } if (C_plus_plus && fullspd) flexerror (_("Can't use -+ with -CF option")); if (C_plus_plus && yytext_is_array) { warn (_("%array incompatible with -+ option")); yytext_is_array = false; } if (C_plus_plus && (reentrant)) flexerror (_("Options -+ and --reentrant are mutually exclusive.")); if (C_plus_plus && bison_bridge_lval) flexerror (_("bison bridge not supported for the C++ scanner.")); if (useecs) { /* Set up doubly-linked equivalence classes. */ /* We loop all the way up to csize, since ecgroup[csize] is * the position used for NUL characters. */ ecgroup[1] = NIL; for (i = 2; i <= csize; ++i) { ecgroup[i] = i - 1; nextecm[i - 1] = i; } nextecm[csize] = NIL; } else { /* Put everything in its own equivalence class. */ for (i = 1; i <= csize; ++i) { ecgroup[i] = i; nextecm[i] = BAD_SUBSCRIPT; /* to catch errors */ } } if (!ansi_func_defs) buf_m4_define( &m4defs_buf, "M4_YY_NO_ANSI_FUNC_DEFS", NULL); if (!ansi_func_protos) buf_m4_define( &m4defs_buf, "M4_YY_NO_ANSI_FUNC_PROTOS", NULL); if (extra_type) buf_m4_define( &m4defs_buf, "M4_EXTRA_TYPE_DEFS", extra_type); if (!use_stdout) { FILE *prev_stdout; if (!did_outfilename) { char *suffix; if (C_plus_plus) suffix = "cc"; else suffix = "c"; snprintf (outfile_path, sizeof(outfile_path), outfile_template, prefix, suffix); outfilename = outfile_path; } prev_stdout = freopen (outfilename, "w+", stdout); if (prev_stdout == NULL) lerr (_("could not create %s"), outfilename); outfile_created = 1; } /* Setup the filter chain. */ output_chain = filter_create_int(NULL, filter_tee_header, headerfilename); if ( !(m4 = getenv("M4"))) m4 = M4; filter_create_ext(output_chain, m4, "-P", 0); filter_create_int(output_chain, filter_fix_linedirs, NULL); /* For debugging, only run the requested number of filters. */ if (preproc_level > 0) { filter_truncate(output_chain, preproc_level); filter_apply_chain(output_chain); } yyout = stdout; /* always generate the tablesverify flag. */ buf_m4_define (&m4defs_buf, "M4_YY_TABLES_VERIFY", tablesverify ? "1" : "0"); if (tablesext) gentables = false; if (tablesverify) /* force generation of C tables. */ gentables = true; if (tablesext) { FILE *tablesout; struct yytbl_hdr hdr; char *pname = 0; int nbytes = 0; buf_m4_define (&m4defs_buf, "M4_YY_TABLES_EXTERNAL", NULL); if (!tablesfilename) { nbytes = strlen (prefix) + strlen (tablesfile_template) + 2; tablesfilename = pname = (char *) calloc (nbytes, 1); snprintf (pname, nbytes, tablesfile_template, prefix); } if ((tablesout = fopen (tablesfilename, "w")) == NULL) lerr (_("could not create %s"), tablesfilename); if (pname) free (pname); tablesfilename = 0; yytbl_writer_init (&tableswr, tablesout); nbytes = strlen (prefix) + strlen ("tables") + 2; tablesname = (char *) calloc (nbytes, 1); snprintf (tablesname, nbytes, "%stables", prefix); yytbl_hdr_init (&hdr, flex_version, tablesname); if (yytbl_hdr_fwrite (&tableswr, &hdr) <= 0) flexerror (_("could not write tables header")); } if (skelname && (skelfile = fopen (skelname, "r")) == NULL) lerr (_("can't open skeleton file %s"), skelname); if (reentrant) { buf_m4_define (&m4defs_buf, "M4_YY_REENTRANT", NULL); if (yytext_is_array) buf_m4_define (&m4defs_buf, "M4_YY_TEXT_IS_ARRAY", NULL); } if ( bison_bridge_lval) buf_m4_define (&m4defs_buf, "M4_YY_BISON_LVAL", NULL); if ( bison_bridge_lloc) buf_m4_define (&m4defs_buf, "", NULL); buf_m4_define(&m4defs_buf, "M4_YY_PREFIX", prefix); if (did_outfilename) line_directive_out (stdout, 0); if (do_yylineno) buf_m4_define (&m4defs_buf, "M4_YY_USE_LINENO", NULL); /* Create the alignment type. */ buf_strdefine (&userdef_buf, "YY_INT_ALIGNED", long_align ? "long int" : "short int"); /* Define the start condition macros. */ { struct Buf tmpbuf; buf_init(&tmpbuf, sizeof(char)); for (i = 1; i <= lastsc; i++) { char *str, *fmt = "#define %s %d\n"; size_t strsz; str = (char*)flex_alloc(strsz = strlen(fmt) + strlen(scname[i]) + (int)(1 + log10(i)) + 2); if (!str) flexfatal(_("allocation of macro definition failed")); snprintf(str, strsz, fmt, scname[i], i - 1); buf_strappend(&tmpbuf, str); free(str); } buf_m4_define(&m4defs_buf, "M4_YY_SC_DEFS", tmpbuf.elts); buf_destroy(&tmpbuf); } /* This is where we begin writing to the file. */ /* Dump the %top code. */ if( top_buf.elts) outn((char*) top_buf.elts); /* Dump the m4 definitions. */ buf_print_strings(&m4defs_buf, stdout); m4defs_buf.nelts = 0; /* memory leak here. */ /* Place a bogus line directive, it will be fixed in the filter. */ outn("#line 0 \"M4_YY_OUTFILE_NAME\"\n"); /* Dump the user defined preproc directives. */ if (userdef_buf.elts) outn ((char *) (userdef_buf.elts)); skelout (); /* %% [1.0] */ } /* flexend - terminate flex * * note * This routine does not return. */ void flexend (exit_status) int exit_status; { static int called_before = -1; /* prevent infinite recursion. */ int tblsiz; if (++called_before) FLEX_EXIT (exit_status); if (skelfile != NULL) { if (ferror (skelfile)) lerr (_("input error reading skeleton file %s"), skelname); else if (fclose (skelfile)) lerr (_("error closing skeleton file %s"), skelname); } #if 0 fprintf (header_out, "#ifdef YY_HEADER_EXPORT_START_CONDITIONS\n"); fprintf (header_out, "/* Beware! Start conditions are not prefixed. */\n"); /* Special case for "INITIAL" */ fprintf (header_out, "#undef INITIAL\n#define INITIAL 0\n"); for (i = 2; i <= lastsc; i++) fprintf (header_out, "#define %s %d\n", scname[i], i - 1); fprintf (header_out, "#endif /* YY_HEADER_EXPORT_START_CONDITIONS */\n\n"); /* Kill ALL flex-related macros. This is so the user * can #include more than one generated header file. */ fprintf (header_out, "#ifndef YY_HEADER_NO_UNDEFS\n"); fprintf (header_out, "/* Undefine all internal macros, etc., that do no belong in the header. */\n\n"); { const char * undef_list[] = { "BEGIN", "ECHO", "EOB_ACT_CONTINUE_SCAN", "EOB_ACT_END_OF_FILE", "EOB_ACT_LAST_MATCH", "FLEX_SCANNER", "FLEX_STD", "REJECT", "YYFARGS0", "YYFARGS1", "YYFARGS2", "YYFARGS3", "YYLMAX", "YYSTATE", "YY_AT_BOL", "YY_BREAK", "YY_BUFFER_EOF_PENDING", "YY_BUFFER_NEW", "YY_BUFFER_NORMAL", "YY_BUF_SIZE", "M4_YY_CALL_LAST_ARG", "M4_YY_CALL_ONLY_ARG", "YY_CURRENT_BUFFER", "YY_DECL", "M4_YY_DECL_LAST_ARG", "M4_YY_DEF_LAST_ARG", "M4_YY_DEF_ONLY_ARG", "YY_DO_BEFORE_ACTION", "YY_END_OF_BUFFER", "YY_END_OF_BUFFER_CHAR", "YY_EXIT_FAILURE", "YY_EXTRA_TYPE", "YY_FATAL_ERROR", "YY_FLEX_DEFINED_ECHO", "YY_FLEX_LEX_COMPAT", "YY_FLEX_MAJOR_VERSION", "YY_FLEX_MINOR_VERSION", "YY_FLEX_SUBMINOR_VERSION", "YY_FLUSH_BUFFER", "YY_G", "YY_INPUT", "YY_INTERACTIVE", "YY_INT_ALIGNED", "YY_LAST_ARG", "YY_LESS_LINENO", "YY_LEX_ARGS", "YY_LEX_DECLARATION", "YY_LEX_PROTO", "YY_MAIN", "YY_MORE_ADJ", "YY_NEED_STRLEN", "YY_NEW_FILE", "YY_NULL", "YY_NUM_RULES", "YY_ONLY_ARG", "YY_PARAMS", "YY_PROTO", "M4_YY_PROTO_LAST_ARG", "M4_YY_PROTO_ONLY_ARG void", "YY_READ_BUF_SIZE", "YY_REENTRANT", "YY_RESTORE_YY_MORE_OFFSET", "YY_RULE_SETUP", "YY_SC_TO_UI", "YY_SKIP_YYWRAP", "YY_START", "YY_START_STACK_INCR", "YY_STATE_EOF", "YY_STDINIT", "YY_TRAILING_HEAD_MASK", "YY_TRAILING_MASK", "YY_USER_ACTION", "YY_USE_CONST", "YY_USE_PROTOS", "unput", "yyTABLES_NAME", "yy_create_buffer", "yy_delete_buffer", "yy_flex_debug", "yy_flush_buffer", "yy_init_buffer", "yy_load_buffer_state", "yy_new_buffer", "yy_scan_buffer", "yy_scan_bytes", "yy_scan_string", "yy_set_bol", "yy_set_interactive", "yy_switch_to_buffer", "yypush_buffer_state", "yypop_buffer_state", "yyensure_buffer_stack", "yyalloc", "yyconst", "yyextra", "yyfree", "yyget_debug", "yyget_extra", "yyget_in", "yyget_leng", "yyget_lineno", "yyget_lloc", "yyget_lval", "yyget_out", "yyget_text", "yyin", "yyleng", "yyless", "yylex", "yylex_destroy", "yylex_init", "yylex_init_extra", "yylineno", "yylloc", "yylval", "yymore", "yyout", "yyrealloc", "yyrestart", "yyset_debug", "yyset_extra", "yyset_in", "yyset_lineno", "yyset_lloc", "yyset_lval", "yyset_out", "yytables_destroy", "yytables_fload", "yyterminate", "yytext", "yytext_ptr", "yywrap", /* must be null-terminated */ NULL}; for (i=0; undef_list[i] != NULL; i++) fprintf (header_out, "#undef %s\n", undef_list[i]); } /* undef any of the auto-generated symbols. */ for (i = 0; i < defs_buf.nelts; i++) { /* don't undef start conditions */ if (sclookup (((char **) defs_buf.elts)[i]) > 0) continue; fprintf (header_out, "#undef %s\n", ((char **) defs_buf.elts)[i]); } fprintf (header_out, "#endif /* !YY_HEADER_NO_UNDEFS */\n"); fprintf (header_out, "\n"); fprintf (header_out, "#undef %sIN_HEADER\n", prefix); fprintf (header_out, "#endif /* %sHEADER_H */\n", prefix); if (ferror (header_out)) lerr (_("error creating header file %s"), headerfilename); fflush (header_out); fclose (header_out); #endif if (exit_status != 0 && outfile_created) { if (ferror (stdout)) lerr (_("error writing output file %s"), outfilename); else if ((_stdout_closed = 1) && fclose (stdout)) lerr (_("error closing output file %s"), outfilename); else if (unlink (outfilename)) lerr (_("error deleting output file %s"), outfilename); } if (backing_up_report && backing_up_file) { if (num_backing_up == 0) fprintf (backing_up_file, _("No backing up.\n")); else if (fullspd || fulltbl) fprintf (backing_up_file, _ ("%d backing up (non-accepting) states.\n"), num_backing_up); else fprintf (backing_up_file, _("Compressed tables always back up.\n")); if (ferror (backing_up_file)) lerr (_("error writing backup file %s"), backing_name); else if (fclose (backing_up_file)) lerr (_("error closing backup file %s"), backing_name); } if (printstats) { fprintf (stderr, _("%s version %s usage statistics:\n"), program_name, flex_version); fprintf (stderr, _(" scanner options: -")); if (C_plus_plus) putc ('+', stderr); if (backing_up_report) putc ('b', stderr); if (ddebug) putc ('d', stderr); if (sf_case_ins()) putc ('i', stderr); if (lex_compat) putc ('l', stderr); if (posix_compat) putc ('X', stderr); if (performance_report > 0) putc ('p', stderr); if (performance_report > 1) putc ('p', stderr); if (spprdflt) putc ('s', stderr); if (reentrant) fputs ("--reentrant", stderr); if (bison_bridge_lval) fputs ("--bison-bridge", stderr); if (bison_bridge_lloc) fputs ("--bison-locations", stderr); if (use_stdout) putc ('t', stderr); if (printstats) putc ('v', stderr); /* always true! */ if (nowarn) putc ('w', stderr); if (interactive == false) putc ('B', stderr); if (interactive == true) putc ('I', stderr); if (!gen_line_dirs) putc ('L', stderr); if (trace) putc ('T', stderr); if (csize == unspecified) /* We encountered an error fairly early on, so csize * never got specified. Define it now, to prevent * bogus table sizes being written out below. */ csize = 256; if (csize == 128) putc ('7', stderr); else putc ('8', stderr); fprintf (stderr, " -C"); if (long_align) putc ('a', stderr); if (fulltbl) putc ('f', stderr); if (fullspd) putc ('F', stderr); if (useecs) putc ('e', stderr); if (usemecs) putc ('m', stderr); if (use_read) putc ('r', stderr); if (did_outfilename) fprintf (stderr, " -o%s", outfilename); if (skelname) fprintf (stderr, " -S%s", skelname); if (strcmp (prefix, "yy")) fprintf (stderr, " -P%s", prefix); putc ('\n', stderr); fprintf (stderr, _(" %d/%d NFA states\n"), lastnfa, current_mns); fprintf (stderr, _(" %d/%d DFA states (%d words)\n"), lastdfa, current_max_dfas, totnst); fprintf (stderr, _(" %d rules\n"), num_rules + num_eof_rules - 1 /* - 1 for def. rule */ ); if (num_backing_up == 0) fprintf (stderr, _(" No backing up\n")); else if (fullspd || fulltbl) fprintf (stderr, _ (" %d backing-up (non-accepting) states\n"), num_backing_up); else fprintf (stderr, _ (" Compressed tables always back-up\n")); if (bol_needed) fprintf (stderr, _(" Beginning-of-line patterns used\n")); fprintf (stderr, _(" %d/%d start conditions\n"), lastsc, current_max_scs); fprintf (stderr, _ (" %d epsilon states, %d double epsilon states\n"), numeps, eps2); if (lastccl == 0) fprintf (stderr, _(" no character classes\n")); else fprintf (stderr, _ (" %d/%d character classes needed %d/%d words of storage, %d reused\n"), lastccl, current_maxccls, cclmap[lastccl] + ccllen[lastccl], current_max_ccl_tbl_size, cclreuse); fprintf (stderr, _(" %d state/nextstate pairs created\n"), numsnpairs); fprintf (stderr, _(" %d/%d unique/duplicate transitions\n"), numuniq, numdup); if (fulltbl) { tblsiz = lastdfa * numecs; fprintf (stderr, _(" %d table entries\n"), tblsiz); } else { tblsiz = 2 * (lastdfa + numtemps) + 2 * tblend; fprintf (stderr, _(" %d/%d base-def entries created\n"), lastdfa + numtemps, current_max_dfas); fprintf (stderr, _ (" %d/%d (peak %d) nxt-chk entries created\n"), tblend, current_max_xpairs, peakpairs); fprintf (stderr, _ (" %d/%d (peak %d) template nxt-chk entries created\n"), numtemps * nummecs, current_max_template_xpairs, numtemps * numecs); fprintf (stderr, _(" %d empty table entries\n"), nummt); fprintf (stderr, _(" %d protos created\n"), numprots); fprintf (stderr, _(" %d templates created, %d uses\n"), numtemps, tmpuses); } if (useecs) { tblsiz = tblsiz + csize; fprintf (stderr, _ (" %d/%d equivalence classes created\n"), numecs, csize); } if (usemecs) { tblsiz = tblsiz + numecs; fprintf (stderr, _ (" %d/%d meta-equivalence classes created\n"), nummecs, csize); } fprintf (stderr, _ (" %d (%d saved) hash collisions, %d DFAs equal\n"), hshcol, hshsave, dfaeql); fprintf (stderr, _(" %d sets of reallocations needed\n"), num_reallocs); fprintf (stderr, _(" %d total table entries needed\n"), tblsiz); } FLEX_EXIT (exit_status); } /* flexinit - initialize flex */ void flexinit (argc, argv) int argc; char **argv; { int i, sawcmpflag, rv, optind; char *arg; scanopt_t sopt; printstats = syntaxerror = trace = spprdflt = false; lex_compat = posix_compat = C_plus_plus = backing_up_report = ddebug = fulltbl = false; fullspd = long_align = nowarn = yymore_used = continued_action = false; do_yylineno = yytext_is_array = in_rule = reject = do_stdinit = false; yymore_really_used = reject_really_used = unspecified; interactive = csize = unspecified; do_yywrap = gen_line_dirs = usemecs = useecs = true; reentrant = bison_bridge_lval = bison_bridge_lloc = false; performance_report = 0; did_outfilename = 0; prefix = "yy"; yyclass = 0; use_read = use_stdout = false; tablesext = tablesverify = false; gentables = true; tablesfilename = tablesname = NULL; ansi_func_defs = ansi_func_protos = true; sawcmpflag = false; /* Initialize dynamic array for holding the rule actions. */ action_size = 2048; /* default size of action array in bytes */ action_array = allocate_character_array (action_size); defs1_offset = prolog_offset = action_offset = action_index = 0; action_array[0] = '\0'; /* Initialize any buffers. */ buf_init (&userdef_buf, sizeof (char)); /* one long string */ buf_init (&defs_buf, sizeof (char *)); /* list of strings */ buf_init (&yydmap_buf, sizeof (char)); /* one long string */ buf_init (&top_buf, sizeof (char)); /* one long string */ { const char * m4defs_init_str[] = {"m4_changequote\n", "m4_changequote([[, ]])\n"}; buf_init (&m4defs_buf, sizeof (char *)); buf_append (&m4defs_buf, &m4defs_init_str, 2); } sf_init (); /* initialize regex lib */ flex_init_regex(); /* Enable C++ if program name ends with '+'. */ program_name = basename2 (argv[0], 0); if (program_name[0] != '\0' && program_name[strlen (program_name) - 1] == '+') C_plus_plus = true; /* read flags */ sopt = scanopt_init (flexopts, argc, argv, 0); if (!sopt) { /* This will only happen when flexopts array is altered. */ fprintf (stderr, _("Internal error. flexopts are malformed.\n")); FLEX_EXIT (1); } while ((rv = scanopt (sopt, &arg, &optind)) != 0) { if (rv < 0) { /* Scanopt has already printed an option-specific error message. */ fprintf (stderr, _ ("Try `%s --help' for more information.\n"), program_name); FLEX_EXIT (1); } switch ((enum flexopt_flag_t) rv) { case OPT_CPLUSPLUS: C_plus_plus = true; break; case OPT_BATCH: interactive = false; break; case OPT_BACKUP: backing_up_report = true; break; case OPT_DONOTHING: break; case OPT_COMPRESSION: if (!sawcmpflag) { useecs = false; usemecs = false; fulltbl = false; sawcmpflag = true; } for (i = 0; arg && arg[i] != '\0'; i++) switch (arg[i]) { case 'a': long_align = true; break; case 'e': useecs = true; break; case 'F': fullspd = true; break; case 'f': fulltbl = true; break; case 'm': usemecs = true; break; case 'r': use_read = true; break; default: lerr (_ ("unknown -C option '%c'"), arg[i]); break; } break; case OPT_DEBUG: ddebug = true; break; case OPT_NO_DEBUG: ddebug = false; break; case OPT_FULL: useecs = usemecs = false; use_read = fulltbl = true; break; case OPT_FAST: useecs = usemecs = false; use_read = fullspd = true; break; case OPT_HELP: usage (); FLEX_EXIT (0); case OPT_INTERACTIVE: interactive = true; break; case OPT_CASE_INSENSITIVE: sf_set_case_ins(true); break; case OPT_LEX_COMPAT: lex_compat = true; break; case OPT_POSIX_COMPAT: posix_compat = true; break; case OPT_PREPROC_LEVEL: preproc_level = strtol(arg,NULL,0); break; case OPT_MAIN: buf_strdefine (&userdef_buf, "YY_MAIN", "1"); do_yywrap = false; break; case OPT_NO_MAIN: buf_strdefine (&userdef_buf, "YY_MAIN", "0"); break; case OPT_NO_LINE: gen_line_dirs = false; break; case OPT_OUTFILE: outfilename = arg; did_outfilename = 1; break; case OPT_PREFIX: prefix = arg; break; case OPT_PERF_REPORT: ++performance_report; break; case OPT_BISON_BRIDGE: bison_bridge_lval = true; break; case OPT_BISON_BRIDGE_LOCATIONS: bison_bridge_lval = bison_bridge_lloc = true; break; case OPT_REENTRANT: reentrant = true; break; case OPT_NO_REENTRANT: reentrant = false; break; case OPT_SKEL: skelname = arg; break; case OPT_DEFAULT: spprdflt = false; break; case OPT_NO_DEFAULT: spprdflt = true; break; case OPT_STDOUT: use_stdout = true; break; case OPT_NO_UNISTD_H: //buf_strdefine (&userdef_buf, "YY_NO_UNISTD_H", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_UNISTD_H",0); break; case OPT_TABLES_FILE: tablesext = true; tablesfilename = arg; break; case OPT_TABLES_VERIFY: tablesverify = true; break; case OPT_TRACE: trace = true; break; case OPT_VERBOSE: printstats = true; break; case OPT_VERSION: printf (_("%s %s\n"), program_name, flex_version); FLEX_EXIT (0); case OPT_WARN: nowarn = false; break; case OPT_NO_WARN: nowarn = true; break; case OPT_7BIT: csize = 128; break; case OPT_8BIT: csize = CSIZE; break; case OPT_ALIGN: long_align = true; break; case OPT_NO_ALIGN: long_align = false; break; case OPT_ALWAYS_INTERACTIVE: buf_m4_define (&m4defs_buf, "M4_YY_ALWAYS_INTERACTIVE", 0); break; case OPT_NEVER_INTERACTIVE: buf_m4_define( &m4defs_buf, "M4_YY_NEVER_INTERACTIVE", 0); break; case OPT_ARRAY: yytext_is_array = true; break; case OPT_POINTER: yytext_is_array = false; break; case OPT_ECS: useecs = true; break; case OPT_NO_ECS: useecs = false; break; case OPT_HEADER_FILE: headerfilename = arg; break; case OPT_META_ECS: usemecs = true; break; case OPT_NO_META_ECS: usemecs = false; break; case OPT_PREPROCDEFINE: { /* arg is "symbol" or "symbol=definition". */ char *def; for (def = arg; *def != '\0' && *def != '='; ++def) ; buf_strappend (&userdef_buf, "#define "); if (*def == '\0') { buf_strappend (&userdef_buf, arg); buf_strappend (&userdef_buf, " 1\n"); } else { buf_strnappend (&userdef_buf, arg, def - arg); buf_strappend (&userdef_buf, " "); buf_strappend (&userdef_buf, def + 1); buf_strappend (&userdef_buf, "\n"); } } break; case OPT_READ: use_read = true; break; case OPT_STACK: //buf_strdefine (&userdef_buf, "YY_STACK_USED", "1"); buf_m4_define( &m4defs_buf, "M4_YY_STACK_USED",0); break; case OPT_STDINIT: do_stdinit = true; break; case OPT_NO_STDINIT: do_stdinit = false; break; case OPT_YYCLASS: yyclass = arg; break; case OPT_YYLINENO: do_yylineno = true; break; case OPT_NO_YYLINENO: do_yylineno = false; break; case OPT_YYWRAP: do_yywrap = true; break; case OPT_NO_YYWRAP: do_yywrap = false; break; case OPT_YYMORE: yymore_really_used = true; break; case OPT_NO_YYMORE: yymore_really_used = false; break; case OPT_REJECT: reject_really_used = true; break; case OPT_NO_REJECT: reject_really_used = false; break; case OPT_NO_ANSI_FUNC_DEFS: ansi_func_defs = false; break; case OPT_NO_ANSI_FUNC_PROTOS: ansi_func_protos = false; break; case OPT_NO_YY_PUSH_STATE: //buf_strdefine (&userdef_buf, "YY_NO_PUSH_STATE", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_PUSH_STATE",0); break; case OPT_NO_YY_POP_STATE: //buf_strdefine (&userdef_buf, "YY_NO_POP_STATE", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_POP_STATE",0); break; case OPT_NO_YY_TOP_STATE: //buf_strdefine (&userdef_buf, "YY_NO_TOP_STATE", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_TOP_STATE",0); break; case OPT_NO_UNPUT: //buf_strdefine (&userdef_buf, "YY_NO_UNPUT", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_UNPUT",0); break; case OPT_NO_YY_SCAN_BUFFER: //buf_strdefine (&userdef_buf, "YY_NO_SCAN_BUFFER", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_SCAN_BUFFER",0); break; case OPT_NO_YY_SCAN_BYTES: //buf_strdefine (&userdef_buf, "YY_NO_SCAN_BYTES", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_SCAN_BYTES",0); break; case OPT_NO_YY_SCAN_STRING: //buf_strdefine (&userdef_buf, "YY_NO_SCAN_STRING", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_SCAN_STRING",0); break; case OPT_NO_YYGET_EXTRA: //buf_strdefine (&userdef_buf, "YY_NO_GET_EXTRA", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_GET_EXTRA",0); break; case OPT_NO_YYSET_EXTRA: //buf_strdefine (&userdef_buf, "YY_NO_SET_EXTRA", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_SET_EXTRA",0); break; case OPT_NO_YYGET_LENG: //buf_strdefine (&userdef_buf, "YY_NO_GET_LENG", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_GET_LENG",0); break; case OPT_NO_YYGET_TEXT: //buf_strdefine (&userdef_buf, "YY_NO_GET_TEXT", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_GET_TEXT",0); break; case OPT_NO_YYGET_LINENO: //buf_strdefine (&userdef_buf, "YY_NO_GET_LINENO", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_GET_LINENO",0); break; case OPT_NO_YYSET_LINENO: //buf_strdefine (&userdef_buf, "YY_NO_SET_LINENO", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_SET_LINENO",0); break; case OPT_NO_YYGET_IN: //buf_strdefine (&userdef_buf, "YY_NO_GET_IN", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_GET_IN",0); break; case OPT_NO_YYSET_IN: //buf_strdefine (&userdef_buf, "YY_NO_SET_IN", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_SET_IN",0); break; case OPT_NO_YYGET_OUT: //buf_strdefine (&userdef_buf, "YY_NO_GET_OUT", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_GET_OUT",0); break; case OPT_NO_YYSET_OUT: //buf_strdefine (&userdef_buf, "YY_NO_SET_OUT", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_SET_OUT",0); break; case OPT_NO_YYGET_LVAL: //buf_strdefine (&userdef_buf, "YY_NO_GET_LVAL", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_GET_LVAL",0); break; case OPT_NO_YYSET_LVAL: //buf_strdefine (&userdef_buf, "YY_NO_SET_LVAL", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_SET_LVAL",0); break; case OPT_NO_YYGET_LLOC: //buf_strdefine (&userdef_buf, "YY_NO_GET_LLOC", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_GET_LLOC",0); break; case OPT_NO_YYSET_LLOC: //buf_strdefine (&userdef_buf, "YY_NO_SET_LLOC", "1"); buf_m4_define( &m4defs_buf, "M4_YY_NO_SET_LLOC",0); break; case OPT_HEX: trace_hex = 1; } /* switch */ } /* while scanopt() */ scanopt_destroy (sopt); num_input_files = argc - optind; input_files = argv + optind; set_input_file (num_input_files > 0 ? input_files[0] : NULL); lastccl = lastsc = lastdfa = lastnfa = 0; num_rules = num_eof_rules = default_rule = 0; numas = numsnpairs = tmpuses = 0; numecs = numeps = eps2 = num_reallocs = hshcol = dfaeql = totnst = 0; numuniq = numdup = hshsave = eofseen = datapos = dataline = 0; num_backing_up = onesp = numprots = 0; variable_trailing_context_rules = bol_needed = false; linenum = sectnum = 1; firstprot = NIL; /* Used in mkprot() so that the first proto goes in slot 1 * of the proto queue. */ lastprot = 1; set_up_initial_allocations (); } /* readin - read in the rules section of the input file(s) */ void readin () { static char yy_stdinit[] = "FILE *yyin = stdin, *yyout = stdout;"; static char yy_nostdinit[] = "FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;"; line_directive_out ((FILE *) 0, 1); if (yyparse ()) { pinpoint_message (_("fatal parse error")); flexend (1); } if (syntaxerror) flexend (1); /* If the user explicitly requested posix compatibility by specifing the * posix-compat option, then we check for conflicting options. However, if * the POSIXLY_CORRECT variable is set, then we quietly make flex as * posix-compatible as possible. This is the recommended behavior * according to the GNU Coding Standards. * * Note: The posix option was added to flex to provide the posix behavior * of the repeat operator in regular expressions, e.g., `ab{3}' */ if (posix_compat) { /* TODO: This is where we try to make flex behave according to * posiz, AND check for conflicting options. How far should we go * with this? Should we disable all the neat-o flex features? */ /* Update: Estes says no, since other flex features don't violate posix. */ } if (getenv ("POSIXLY_CORRECT")) { posix_compat = true; } if (backing_up_report) { backing_up_file = fopen (backing_name, "w"); if (backing_up_file == NULL) lerr (_ ("could not create backing-up info file %s"), backing_name); } else backing_up_file = NULL; if (yymore_really_used == true) yymore_used = true; else if (yymore_really_used == false) yymore_used = false; if (reject_really_used == true) reject = true; else if (reject_really_used == false) reject = false; if (performance_report > 0) { if (lex_compat) { fprintf (stderr, _ ("-l AT&T lex compatibility option entails a large performance penalty\n")); fprintf (stderr, _ (" and may be the actual source of other reported performance penalties\n")); } else if (do_yylineno) { fprintf (stderr, _ ("%%option yylineno entails a performance penalty ONLY on rules that can match newline characters\n")); } if (performance_report > 1) { if (interactive) fprintf (stderr, _ ("-I (interactive) entails a minor performance penalty\n")); if (yymore_used) fprintf (stderr, _ ("yymore() entails a minor performance penalty\n")); } if (reject) fprintf (stderr, _ ("REJECT entails a large performance penalty\n")); if (variable_trailing_context_rules) fprintf (stderr, _ ("Variable trailing context rules entail a large performance penalty\n")); } if (reject) real_reject = true; if (variable_trailing_context_rules) reject = true; if ((fulltbl || fullspd) && reject) { if (real_reject) flexerror (_ ("REJECT cannot be used with -f or -F")); else if (do_yylineno) flexerror (_ ("%option yylineno cannot be used with REJECT")); else flexerror (_ ("variable trailing context rules cannot be used with -f or -F")); } if (reject){ out_m4_define( "M4_YY_USES_REJECT", NULL); //outn ("\n#define YY_USES_REJECT"); } if (!do_yywrap) { if (!C_plus_plus) { if (reentrant) outn ("\n#define yywrap(yyscanner) (/*CONSTCOND*/1)"); else outn ("\n#define yywrap() (/*CONSTCOND*/1)"); } outn ("#define YY_SKIP_YYWRAP"); } if (ddebug) outn ("\n#define FLEX_DEBUG"); OUT_BEGIN_CODE (); if (csize == 256) outn ("typedef unsigned char YY_CHAR;"); else outn ("typedef char YY_CHAR;"); OUT_END_CODE (); if (C_plus_plus) { outn ("#define yytext_ptr yytext"); if (interactive) outn ("#define YY_INTERACTIVE"); } else { OUT_BEGIN_CODE (); /* In reentrant scanner, stdinit is handled in flex.skl. */ if (do_stdinit) { if (reentrant){ outn ("#ifdef VMS"); outn ("#ifdef __VMS_POSIX"); outn ("#define YY_STDINIT"); outn ("#endif"); outn ("#else"); outn ("#define YY_STDINIT"); outn ("#endif"); } outn ("#ifdef VMS"); outn ("#ifndef __VMS_POSIX"); outn (yy_nostdinit); outn ("#else"); outn (yy_stdinit); outn ("#endif"); outn ("#else"); outn (yy_stdinit); outn ("#endif"); } else { if(!reentrant) outn (yy_nostdinit); } OUT_END_CODE (); } OUT_BEGIN_CODE (); if (fullspd) outn ("typedef yyconst struct yy_trans_info *yy_state_type;"); else if (!C_plus_plus) outn ("typedef int yy_state_type;"); OUT_END_CODE (); if (lex_compat) outn ("#define YY_FLEX_LEX_COMPAT"); if (!C_plus_plus && !reentrant) { outn ("extern int yylineno;"); OUT_BEGIN_CODE (); outn ("int yylineno = 1;"); OUT_END_CODE (); } if (C_plus_plus) { outn ("\n#include "); if (!do_yywrap) { outn("\nint yyFlexLexer::yywrap() { return 1; }"); } if (yyclass) { outn ("int yyFlexLexer::yylex()"); outn ("\t{"); outn ("\tLexerError( \"yyFlexLexer::yylex invoked but %option yyclass used\" );"); outn ("\treturn 0;"); outn ("\t}"); out_str ("\n#define YY_DECL int %s::yylex()\n", yyclass); } } else { /* Watch out: yytext_ptr is a variable when yytext is an array, * but it's a macro when yytext is a pointer. */ if (yytext_is_array) { if (!reentrant) outn ("extern char yytext[];\n"); } else { if (reentrant) { outn ("#define yytext_ptr yytext_r"); } else { outn ("extern char *yytext;"); outn("#ifdef yytext_ptr"); outn("#undef yytext_ptr"); outn("#endif"); outn ("#define yytext_ptr yytext"); } } if (yyclass) flexerror (_ ("%option yyclass only meaningful for C++ scanners")); } if (useecs) numecs = cre8ecs (nextecm, ecgroup, csize); else numecs = csize; /* Now map the equivalence class for NUL to its expected place. */ ecgroup[0] = ecgroup[csize]; NUL_ec = ABS (ecgroup[0]); if (useecs) ccl2ecl (); } /* set_up_initial_allocations - allocate memory for internal tables */ void set_up_initial_allocations () { maximum_mns = (long_align ? MAXIMUM_MNS_LONG : MAXIMUM_MNS); current_mns = INITIAL_MNS; firstst = allocate_integer_array (current_mns); lastst = allocate_integer_array (current_mns); finalst = allocate_integer_array (current_mns); transchar = allocate_integer_array (current_mns); trans1 = allocate_integer_array (current_mns); trans2 = allocate_integer_array (current_mns); accptnum = allocate_integer_array (current_mns); assoc_rule = allocate_integer_array (current_mns); state_type = allocate_integer_array (current_mns); current_max_rules = INITIAL_MAX_RULES; rule_type = allocate_integer_array (current_max_rules); rule_linenum = allocate_integer_array (current_max_rules); rule_useful = allocate_integer_array (current_max_rules); rule_has_nl = allocate_bool_array (current_max_rules); current_max_scs = INITIAL_MAX_SCS; scset = allocate_integer_array (current_max_scs); scbol = allocate_integer_array (current_max_scs); scxclu = allocate_integer_array (current_max_scs); sceof = allocate_integer_array (current_max_scs); scname = allocate_char_ptr_array (current_max_scs); current_maxccls = INITIAL_MAX_CCLS; cclmap = allocate_integer_array (current_maxccls); ccllen = allocate_integer_array (current_maxccls); cclng = allocate_integer_array (current_maxccls); ccl_has_nl = allocate_bool_array (current_maxccls); current_max_ccl_tbl_size = INITIAL_MAX_CCL_TBL_SIZE; ccltbl = allocate_Character_array (current_max_ccl_tbl_size); current_max_dfa_size = INITIAL_MAX_DFA_SIZE; current_max_xpairs = INITIAL_MAX_XPAIRS; nxt = allocate_integer_array (current_max_xpairs); chk = allocate_integer_array (current_max_xpairs); current_max_template_xpairs = INITIAL_MAX_TEMPLATE_XPAIRS; tnxt = allocate_integer_array (current_max_template_xpairs); current_max_dfas = INITIAL_MAX_DFAS; base = allocate_integer_array (current_max_dfas); def = allocate_integer_array (current_max_dfas); dfasiz = allocate_integer_array (current_max_dfas); accsiz = allocate_integer_array (current_max_dfas); dhash = allocate_integer_array (current_max_dfas); dss = allocate_int_ptr_array (current_max_dfas); dfaacc = allocate_dfaacc_union (current_max_dfas); nultrans = (int *) 0; } /* extracts basename from path, optionally stripping the extension "\.*" * (same concept as /bin/sh `basename`, but different handling of extension). */ static char *basename2 (path, strip_ext) char *path; int strip_ext; /* boolean */ { char *b, *e = 0; b = path; for (b = path; *path; path++) if (*path == '/') b = path + 1; else if (*path == '.') e = path; if (strip_ext && e && e > b) *e = '\0'; return b; } void usage () { FILE *f = stdout; if (!did_outfilename) { snprintf (outfile_path, sizeof(outfile_path), outfile_template, prefix, C_plus_plus ? "cc" : "c"); outfilename = outfile_path; } fprintf (f, _("Usage: %s [OPTIONS] [FILE]...\n"), program_name); fprintf (f, _ ("Generates programs that perform pattern-matching on text.\n" "\n" "Table Compression:\n" " -Ca, --align trade off larger tables for better memory alignment\n" " -Ce, --ecs construct equivalence classes\n" " -Cf do not compress tables; use -f representation\n" " -CF do not compress tables; use -F representation\n" " -Cm, --meta-ecs construct meta-equivalence classes\n" " -Cr, --read use read() instead of stdio for scanner input\n" " -f, --full generate fast, large scanner. Same as -Cfr\n" " -F, --fast use alternate table representation. Same as -CFr\n" " -Cem default compression (same as --ecs --meta-ecs)\n" "\n" "Debugging:\n" " -d, --debug enable debug mode in scanner\n" " -b, --backup write backing-up information to %s\n" " -p, --perf-report write performance report to stderr\n" " -s, --nodefault suppress default rule to ECHO unmatched text\n" " -T, --trace %s should run in trace mode\n" " -w, --nowarn do not generate warnings\n" " -v, --verbose write summary of scanner statistics to stdout\n" " --hex use hexadecimal numbers instead of octal in debug outputs\n" "\n" "Files:\n" " -o, --outfile=FILE specify output filename\n" " -S, --skel=FILE specify skeleton file\n" " -t, --stdout write scanner on stdout instead of %s\n" " --yyclass=NAME name of C++ class\n" " --header-file=FILE create a C header file in addition to the scanner\n" " --tables-file[=FILE] write tables to FILE\n" "\n" "Scanner behavior:\n" " -7, --7bit generate 7-bit scanner\n" " -8, --8bit generate 8-bit scanner\n" " -B, --batch generate batch scanner (opposite of -I)\n" " -i, --case-insensitive ignore case in patterns\n" " -l, --lex-compat maximal compatibility with original lex\n" " -X, --posix-compat maximal compatibility with POSIX lex\n" " -I, --interactive generate interactive scanner (opposite of -B)\n" " --yylineno track line count in yylineno\n" "\n" "Generated code:\n" " -+, --c++ generate C++ scanner class\n" " -Dmacro[=defn] #define macro defn (default defn is '1')\n" " -L, --noline suppress #line directives in scanner\n" " -P, --prefix=STRING use STRING as prefix instead of \"yy\"\n" " -R, --reentrant generate a reentrant C scanner\n" " --bison-bridge scanner for bison pure parser.\n" " --bison-locations include yylloc support.\n" " --stdinit initialize yyin/yyout to stdin/stdout\n" " --noansi-definitions old-style function definitions\n" " --noansi-prototypes empty parameter list in prototypes\n" " --nounistd do not include \n" " --noFUNCTION do not generate a particular FUNCTION\n" "\n" "Miscellaneous:\n" " -c do-nothing POSIX option\n" " -n do-nothing POSIX option\n" " -?\n" " -h, --help produce this help message\n" " -V, --version report %s version\n"), backing_name, program_name, outfile_path, program_name); } flex-2.6.0/src/dfa.c0000644000175000017500000006514212620475500014425 0ustar srivastasrivasta/* dfa - DFA construction routines */ /* Copyright (c) 1990 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: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" #include "tables.h" /* declare functions that have forward references */ void dump_associated_rules PROTO ((FILE *, int)); void dump_transitions PROTO ((FILE *, int[])); void sympartition PROTO ((int[], int, int[], int[])); int symfollowset PROTO ((int[], int, int, int[])); /* check_for_backing_up - check a DFA state for backing up * * synopsis * void check_for_backing_up( int ds, int state[numecs] ); * * ds is the number of the state to check and state[] is its out-transitions, * indexed by equivalence class. */ void check_for_backing_up (ds, state) int ds; int state[]; { if ((reject && !dfaacc[ds].dfaacc_set) || (!reject && !dfaacc[ds].dfaacc_state)) { /* state is non-accepting */ ++num_backing_up; if (backing_up_report) { fprintf (backing_up_file, _("State #%d is non-accepting -\n"), ds); /* identify the state */ dump_associated_rules (backing_up_file, ds); /* Now identify it further using the out- and * jam-transitions. */ dump_transitions (backing_up_file, state); putc ('\n', backing_up_file); } } } /* check_trailing_context - check to see if NFA state set constitutes * "dangerous" trailing context * * synopsis * void check_trailing_context( int nfa_states[num_states+1], int num_states, * int accset[nacc+1], int nacc ); * * NOTES * Trailing context is "dangerous" if both the head and the trailing * part are of variable size \and/ there's a DFA state which contains * both an accepting state for the head part of the rule and NFA states * which occur after the beginning of the trailing context. * * When such a rule is matched, it's impossible to tell if having been * in the DFA state indicates the beginning of the trailing context or * further-along scanning of the pattern. In these cases, a warning * message is issued. * * nfa_states[1 .. num_states] is the list of NFA states in the DFA. * accset[1 .. nacc] is the list of accepting numbers for the DFA state. */ void check_trailing_context (nfa_states, num_states, accset, nacc) int *nfa_states, num_states; int *accset; int nacc; { int i, j; for (i = 1; i <= num_states; ++i) { int ns = nfa_states[i]; int type = state_type[ns]; int ar = assoc_rule[ns]; if (type == STATE_NORMAL || rule_type[ar] != RULE_VARIABLE) { /* do nothing */ } else if (type == STATE_TRAILING_CONTEXT) { /* Potential trouble. Scan set of accepting numbers * for the one marking the end of the "head". We * assume that this looping will be fairly cheap * since it's rare that an accepting number set * is large. */ for (j = 1; j <= nacc; ++j) if (accset[j] & YY_TRAILING_HEAD_MASK) { line_warning (_ ("dangerous trailing context"), rule_linenum[ar]); return; } } } } /* dump_associated_rules - list the rules associated with a DFA state * * Goes through the set of NFA states associated with the DFA and * extracts the first MAX_ASSOC_RULES unique rules, sorts them, * and writes a report to the given file. */ void dump_associated_rules (file, ds) FILE *file; int ds; { int i, j; int num_associated_rules = 0; int rule_set[MAX_ASSOC_RULES + 1]; int *dset = dss[ds]; int size = dfasiz[ds]; for (i = 1; i <= size; ++i) { int rule_num = rule_linenum[assoc_rule[dset[i]]]; for (j = 1; j <= num_associated_rules; ++j) if (rule_num == rule_set[j]) break; if (j > num_associated_rules) { /* new rule */ if (num_associated_rules < MAX_ASSOC_RULES) rule_set[++num_associated_rules] = rule_num; } } qsort (&rule_set [1], num_associated_rules, sizeof (rule_set [1]), intcmp); fprintf (file, _(" associated rule line numbers:")); for (i = 1; i <= num_associated_rules; ++i) { if (i % 8 == 1) putc ('\n', file); fprintf (file, "\t%d", rule_set[i]); } putc ('\n', file); } /* dump_transitions - list the transitions associated with a DFA state * * synopsis * dump_transitions( FILE *file, int state[numecs] ); * * Goes through the set of out-transitions and lists them in human-readable * form (i.e., not as equivalence classes); also lists jam transitions * (i.e., all those which are not out-transitions, plus EOF). The dump * is done to the given file. */ void dump_transitions (file, state) FILE *file; int state[]; { int i, ec; int out_char_set[CSIZE]; for (i = 0; i < csize; ++i) { ec = ABS (ecgroup[i]); out_char_set[i] = state[ec]; } fprintf (file, _(" out-transitions: ")); list_character_set (file, out_char_set); /* now invert the members of the set to get the jam transitions */ for (i = 0; i < csize; ++i) out_char_set[i] = !out_char_set[i]; fprintf (file, _("\n jam-transitions: EOF ")); list_character_set (file, out_char_set); putc ('\n', file); } /* epsclosure - construct the epsilon closure of a set of ndfa states * * synopsis * int *epsclosure( int t[num_states], int *numstates_addr, * int accset[num_rules+1], int *nacc_addr, * int *hashval_addr ); * * NOTES * The epsilon closure is the set of all states reachable by an arbitrary * number of epsilon transitions, which themselves do not have epsilon * transitions going out, unioned with the set of states which have non-null * accepting numbers. t is an array of size numstates of nfa state numbers. * Upon return, t holds the epsilon closure and *numstates_addr is updated. * accset holds a list of the accepting numbers, and the size of accset is * given by *nacc_addr. t may be subjected to reallocation if it is not * large enough to hold the epsilon closure. * * hashval is the hash value for the dfa corresponding to the state set. */ int *epsclosure (t, ns_addr, accset, nacc_addr, hv_addr) int *t, *ns_addr, accset[], *nacc_addr, *hv_addr; { int stkpos, ns, tsp; int numstates = *ns_addr, nacc, hashval, transsym, nfaccnum; int stkend, nstate; static int did_stk_init = false, *stk; #define MARK_STATE(state) \ do{ trans1[state] = trans1[state] - MARKER_DIFFERENCE;} while(0) #define IS_MARKED(state) (trans1[state] < 0) #define UNMARK_STATE(state) \ do{ trans1[state] = trans1[state] + MARKER_DIFFERENCE;} while(0) #define CHECK_ACCEPT(state) \ do{ \ nfaccnum = accptnum[state]; \ if ( nfaccnum != NIL ) \ accset[++nacc] = nfaccnum; \ }while(0) #define DO_REALLOCATION() \ do { \ current_max_dfa_size += MAX_DFA_SIZE_INCREMENT; \ ++num_reallocs; \ t = reallocate_integer_array( t, current_max_dfa_size ); \ stk = reallocate_integer_array( stk, current_max_dfa_size ); \ }while(0) \ #define PUT_ON_STACK(state) \ do { \ if ( ++stkend >= current_max_dfa_size ) \ DO_REALLOCATION(); \ stk[stkend] = state; \ MARK_STATE(state); \ }while(0) #define ADD_STATE(state) \ do { \ if ( ++numstates >= current_max_dfa_size ) \ DO_REALLOCATION(); \ t[numstates] = state; \ hashval += state; \ }while(0) #define STACK_STATE(state) \ do { \ PUT_ON_STACK(state); \ CHECK_ACCEPT(state); \ if ( nfaccnum != NIL || transchar[state] != SYM_EPSILON ) \ ADD_STATE(state); \ }while(0) if (!did_stk_init) { stk = allocate_integer_array (current_max_dfa_size); did_stk_init = true; } nacc = stkend = hashval = 0; for (nstate = 1; nstate <= numstates; ++nstate) { ns = t[nstate]; /* The state could be marked if we've already pushed it onto * the stack. */ if (!IS_MARKED (ns)) { PUT_ON_STACK (ns); CHECK_ACCEPT (ns); hashval += ns; } } for (stkpos = 1; stkpos <= stkend; ++stkpos) { ns = stk[stkpos]; transsym = transchar[ns]; if (transsym == SYM_EPSILON) { tsp = trans1[ns] + MARKER_DIFFERENCE; if (tsp != NO_TRANSITION) { if (!IS_MARKED (tsp)) STACK_STATE (tsp); tsp = trans2[ns]; if (tsp != NO_TRANSITION && !IS_MARKED (tsp)) STACK_STATE (tsp); } } } /* Clear out "visit" markers. */ for (stkpos = 1; stkpos <= stkend; ++stkpos) { if (IS_MARKED (stk[stkpos])) UNMARK_STATE (stk[stkpos]); else flexfatal (_ ("consistency check failed in epsclosure()")); } *ns_addr = numstates; *hv_addr = hashval; *nacc_addr = nacc; return t; } /* increase_max_dfas - increase the maximum number of DFAs */ void increase_max_dfas () { current_max_dfas += MAX_DFAS_INCREMENT; ++num_reallocs; base = reallocate_integer_array (base, current_max_dfas); def = reallocate_integer_array (def, current_max_dfas); dfasiz = reallocate_integer_array (dfasiz, current_max_dfas); accsiz = reallocate_integer_array (accsiz, current_max_dfas); dhash = reallocate_integer_array (dhash, current_max_dfas); dss = reallocate_int_ptr_array (dss, current_max_dfas); dfaacc = reallocate_dfaacc_union (dfaacc, current_max_dfas); if (nultrans) nultrans = reallocate_integer_array (nultrans, current_max_dfas); } /* ntod - convert an ndfa to a dfa * * Creates the dfa corresponding to the ndfa we've constructed. The * dfa starts out in state #1. */ void ntod () { int *accset, ds, nacc, newds; int sym, hashval, numstates, dsize; int num_full_table_rows=0; /* used only for -f */ int *nset, *dset; int targptr, totaltrans, i, comstate, comfreq, targ; int symlist[CSIZE + 1]; int num_start_states; int todo_head, todo_next; struct yytbl_data *yynxt_tbl = 0; flex_int32_t *yynxt_data = 0, yynxt_curr = 0; /* Note that the following are indexed by *equivalence classes* * and not by characters. Since equivalence classes are indexed * beginning with 1, even if the scanner accepts NUL's, this * means that (since every character is potentially in its own * equivalence class) these arrays must have room for indices * from 1 to CSIZE, so their size must be CSIZE + 1. */ int duplist[CSIZE + 1], state[CSIZE + 1]; int targfreq[CSIZE + 1] = {0}, targstate[CSIZE + 1]; /* accset needs to be large enough to hold all of the rules present * in the input, *plus* their YY_TRAILING_HEAD_MASK variants. */ accset = allocate_integer_array ((num_rules + 1) * 2); nset = allocate_integer_array (current_max_dfa_size); /* The "todo" queue is represented by the head, which is the DFA * state currently being processed, and the "next", which is the * next DFA state number available (not in use). We depend on the * fact that snstods() returns DFA's \in increasing order/, and thus * need only know the bounds of the dfas to be processed. */ todo_head = todo_next = 0; for (i = 0; i <= csize; ++i) { duplist[i] = NIL; symlist[i] = false; } for (i = 0; i <= num_rules; ++i) accset[i] = NIL; if (trace) { dumpnfa (scset[1]); fputs (_("\n\nDFA Dump:\n\n"), stderr); } inittbl (); /* Check to see whether we should build a separate table for * transitions on NUL characters. We don't do this for full-speed * (-F) scanners, since for them we don't have a simple state * number lying around with which to index the table. We also * don't bother doing it for scanners unless (1) NUL is in its own * equivalence class (indicated by a positive value of * ecgroup[NUL]), (2) NUL's equivalence class is the last * equivalence class, and (3) the number of equivalence classes is * the same as the number of characters. This latter case comes * about when useecs is false or when it's true but every character * still manages to land in its own class (unlikely, but it's * cheap to check for). If all these things are true then the * character code needed to represent NUL's equivalence class for * indexing the tables is going to take one more bit than the * number of characters, and therefore we won't be assured of * being able to fit it into a YY_CHAR variable. This rules out * storing the transitions in a compressed table, since the code * for interpreting them uses a YY_CHAR variable (perhaps it * should just use an integer, though; this is worth pondering ... * ###). * * Finally, for full tables, we want the number of entries in the * table to be a power of two so the array references go fast (it * will just take a shift to compute the major index). If * encoding NUL's transitions in the table will spoil this, we * give it its own table (note that this will be the case if we're * not using equivalence classes). */ /* Note that the test for ecgroup[0] == numecs below accomplishes * both (1) and (2) above */ if (!fullspd && ecgroup[0] == numecs) { /* NUL is alone in its equivalence class, which is the * last one. */ int use_NUL_table = (numecs == csize); if (fulltbl && !use_NUL_table) { /* We still may want to use the table if numecs * is a power of 2. */ int power_of_two; for (power_of_two = 1; power_of_two <= csize; power_of_two *= 2) if (numecs == power_of_two) { use_NUL_table = true; break; } } if (use_NUL_table) nultrans = allocate_integer_array (current_max_dfas); /* From now on, nultrans != nil indicates that we're * saving null transitions for later, separate encoding. */ } if (fullspd) { for (i = 0; i <= numecs; ++i) state[i] = 0; place_state (state, 0, 0); dfaacc[0].dfaacc_state = 0; } else if (fulltbl) { if (nultrans) /* We won't be including NUL's transitions in the * table, so build it for entries from 0 .. numecs - 1. */ num_full_table_rows = numecs; else /* Take into account the fact that we'll be including * the NUL entries in the transition table. Build it * from 0 .. numecs. */ num_full_table_rows = numecs + 1; /* Begin generating yy_nxt[][] * This spans the entire LONG function. * This table is tricky because we don't know how big it will be. * So we'll have to realloc() on the way... * we'll wait until we can calculate yynxt_tbl->td_hilen. */ yynxt_tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (yynxt_tbl, YYTD_ID_NXT); yynxt_tbl->td_hilen = 1; yynxt_tbl->td_lolen = num_full_table_rows; yynxt_tbl->td_data = yynxt_data = (flex_int32_t *) calloc (yynxt_tbl->td_lolen * yynxt_tbl->td_hilen, sizeof (flex_int32_t)); yynxt_curr = 0; buf_prints (&yydmap_buf, "\t{YYTD_ID_NXT, (void**)&yy_nxt, sizeof(%s)},\n", long_align ? "flex_int32_t" : "flex_int16_t"); /* Unless -Ca, declare it "short" because it's a real * long-shot that that won't be large enough. */ if (gentables) out_str_dec ("static yyconst %s yy_nxt[][%d] =\n {\n", long_align ? "flex_int32_t" : "flex_int16_t", num_full_table_rows); else { out_dec ("#undef YY_NXT_LOLEN\n#define YY_NXT_LOLEN (%d)\n", num_full_table_rows); out_str ("static yyconst %s *yy_nxt =0;\n", long_align ? "flex_int32_t" : "flex_int16_t"); } if (gentables) outn (" {"); /* Generate 0 entries for state #0. */ for (i = 0; i < num_full_table_rows; ++i) { mk2data (0); yynxt_data[yynxt_curr++] = 0; } dataflush (); if (gentables) outn (" },\n"); } /* Create the first states. */ num_start_states = lastsc * 2; for (i = 1; i <= num_start_states; ++i) { numstates = 1; /* For each start condition, make one state for the case when * we're at the beginning of the line (the '^' operator) and * one for the case when we're not. */ if (i % 2 == 1) nset[numstates] = scset[(i / 2) + 1]; else nset[numstates] = mkbranch (scbol[i / 2], scset[i / 2]); nset = epsclosure (nset, &numstates, accset, &nacc, &hashval); if (snstods (nset, numstates, accset, nacc, hashval, &ds)) { numas += nacc; totnst += numstates; ++todo_next; if (variable_trailing_context_rules && nacc > 0) check_trailing_context (nset, numstates, accset, nacc); } } if (!fullspd) { if (!snstods (nset, 0, accset, 0, 0, &end_of_buffer_state)) flexfatal (_ ("could not create unique end-of-buffer state")); ++numas; ++num_start_states; ++todo_next; } while (todo_head < todo_next) { targptr = 0; totaltrans = 0; for (i = 1; i <= numecs; ++i) state[i] = 0; ds = ++todo_head; dset = dss[ds]; dsize = dfasiz[ds]; if (trace) fprintf (stderr, _("state # %d:\n"), ds); sympartition (dset, dsize, symlist, duplist); for (sym = 1; sym <= numecs; ++sym) { if (symlist[sym]) { symlist[sym] = 0; if (duplist[sym] == NIL) { /* Symbol has unique out-transitions. */ numstates = symfollowset (dset, dsize, sym, nset); nset = epsclosure (nset, &numstates, accset, &nacc, &hashval); if (snstods (nset, numstates, accset, nacc, hashval, &newds)) { totnst = totnst + numstates; ++todo_next; numas += nacc; if (variable_trailing_context_rules && nacc > 0) check_trailing_context (nset, numstates, accset, nacc); } state[sym] = newds; if (trace) fprintf (stderr, "\t%d\t%d\n", sym, newds); targfreq[++targptr] = 1; targstate[targptr] = newds; ++numuniq; } else { /* sym's equivalence class has the same * transitions as duplist(sym)'s * equivalence class. */ targ = state[duplist[sym]]; state[sym] = targ; if (trace) fprintf (stderr, "\t%d\t%d\n", sym, targ); /* Update frequency count for * destination state. */ i = 0; while (targstate[++i] != targ) ; ++targfreq[i]; ++numdup; } ++totaltrans; duplist[sym] = NIL; } } numsnpairs += totaltrans; if (ds > num_start_states) check_for_backing_up (ds, state); if (nultrans) { nultrans[ds] = state[NUL_ec]; state[NUL_ec] = 0; /* remove transition */ } if (fulltbl) { /* Each time we hit here, it's another td_hilen, so we realloc. */ yynxt_tbl->td_hilen++; yynxt_tbl->td_data = yynxt_data = (flex_int32_t *) realloc (yynxt_data, yynxt_tbl->td_hilen * yynxt_tbl->td_lolen * sizeof (flex_int32_t)); if (gentables) outn (" {"); /* Supply array's 0-element. */ if (ds == end_of_buffer_state) { mk2data (-end_of_buffer_state); yynxt_data[yynxt_curr++] = -end_of_buffer_state; } else { mk2data (end_of_buffer_state); yynxt_data[yynxt_curr++] = end_of_buffer_state; } for (i = 1; i < num_full_table_rows; ++i) { /* Jams are marked by negative of state * number. */ mk2data (state[i] ? state[i] : -ds); yynxt_data[yynxt_curr++] = state[i] ? state[i] : -ds; } dataflush (); if (gentables) outn (" },\n"); } else if (fullspd) place_state (state, ds, totaltrans); else if (ds == end_of_buffer_state) /* Special case this state to make sure it does what * it's supposed to, i.e., jam on end-of-buffer. */ stack1 (ds, 0, 0, JAMSTATE); else { /* normal, compressed state */ /* Determine which destination state is the most * common, and how many transitions to it there are. */ comfreq = 0; comstate = 0; for (i = 1; i <= targptr; ++i) if (targfreq[i] > comfreq) { comfreq = targfreq[i]; comstate = targstate[i]; } bldtbl (state, ds, totaltrans, comstate, comfreq); } } if (fulltbl) { dataend (); if (tablesext) { yytbl_data_compress (yynxt_tbl); if (yytbl_data_fwrite (&tableswr, yynxt_tbl) < 0) flexerror (_ ("Could not write yynxt_tbl[][]")); } if (yynxt_tbl) { yytbl_data_destroy (yynxt_tbl); yynxt_tbl = 0; } } else if (!fullspd) { cmptmps (); /* create compressed template entries */ /* Create tables for all the states with only one * out-transition. */ while (onesp > 0) { mk1tbl (onestate[onesp], onesym[onesp], onenext[onesp], onedef[onesp]); --onesp; } mkdeftbl (); } flex_free ((void *) accset); flex_free ((void *) nset); } /* snstods - converts a set of ndfa states into a dfa state * * synopsis * is_new_state = snstods( int sns[numstates], int numstates, * int accset[num_rules+1], int nacc, * int hashval, int *newds_addr ); * * On return, the dfa state number is in newds. */ int snstods (sns, numstates, accset, nacc, hashval, newds_addr) int sns[], numstates, accset[], nacc, hashval, *newds_addr; { int didsort = 0; int i, j; int newds, *oldsns; for (i = 1; i <= lastdfa; ++i) if (hashval == dhash[i]) { if (numstates == dfasiz[i]) { oldsns = dss[i]; if (!didsort) { /* We sort the states in sns so we * can compare it to oldsns quickly. */ qsort (&sns [1], numstates, sizeof (sns [1]), intcmp); didsort = 1; } for (j = 1; j <= numstates; ++j) if (sns[j] != oldsns[j]) break; if (j > numstates) { ++dfaeql; *newds_addr = i; return 0; } ++hshcol; } else ++hshsave; } /* Make a new dfa. */ if (++lastdfa >= current_max_dfas) increase_max_dfas (); newds = lastdfa; dss[newds] = allocate_integer_array (numstates + 1); /* If we haven't already sorted the states in sns, we do so now, * so that future comparisons with it can be made quickly. */ if (!didsort) qsort (&sns [1], numstates, sizeof (sns [1]), intcmp); for (i = 1; i <= numstates; ++i) dss[newds][i] = sns[i]; dfasiz[newds] = numstates; dhash[newds] = hashval; if (nacc == 0) { if (reject) dfaacc[newds].dfaacc_set = (int *) 0; else dfaacc[newds].dfaacc_state = 0; accsiz[newds] = 0; } else if (reject) { /* We sort the accepting set in increasing order so the * disambiguating rule that the first rule listed is considered * match in the event of ties will work. */ qsort (&accset [1], nacc, sizeof (accset [1]), intcmp); dfaacc[newds].dfaacc_set = allocate_integer_array (nacc + 1); /* Save the accepting set for later */ for (i = 1; i <= nacc; ++i) { dfaacc[newds].dfaacc_set[i] = accset[i]; if (accset[i] <= num_rules) /* Who knows, perhaps a REJECT can yield * this rule. */ rule_useful[accset[i]] = true; } accsiz[newds] = nacc; } else { /* Find lowest numbered rule so the disambiguating rule * will work. */ j = num_rules + 1; for (i = 1; i <= nacc; ++i) if (accset[i] < j) j = accset[i]; dfaacc[newds].dfaacc_state = j; if (j <= num_rules) rule_useful[j] = true; } *newds_addr = newds; return 1; } /* symfollowset - follow the symbol transitions one step * * synopsis * numstates = symfollowset( int ds[current_max_dfa_size], int dsize, * int transsym, int nset[current_max_dfa_size] ); */ int symfollowset (ds, dsize, transsym, nset) int ds[], dsize, transsym, nset[]; { int ns, tsp, sym, i, j, lenccl, ch, numstates, ccllist; numstates = 0; for (i = 1; i <= dsize; ++i) { /* for each nfa state ns in the state set of ds */ ns = ds[i]; sym = transchar[ns]; tsp = trans1[ns]; if (sym < 0) { /* it's a character class */ sym = -sym; ccllist = cclmap[sym]; lenccl = ccllen[sym]; if (cclng[sym]) { for (j = 0; j < lenccl; ++j) { /* Loop through negated character * class. */ ch = ccltbl[ccllist + j]; if (ch == 0) ch = NUL_ec; if (ch > transsym) /* Transsym isn't in negated * ccl. */ break; else if (ch == transsym) /* next 2 */ goto bottom; } /* Didn't find transsym in ccl. */ nset[++numstates] = tsp; } else for (j = 0; j < lenccl; ++j) { ch = ccltbl[ccllist + j]; if (ch == 0) ch = NUL_ec; if (ch > transsym) break; else if (ch == transsym) { nset[++numstates] = tsp; break; } } } else if (sym == SYM_EPSILON) { /* do nothing */ } else if (ABS (ecgroup[sym]) == transsym) nset[++numstates] = tsp; bottom:; } return numstates; } /* sympartition - partition characters with same out-transitions * * synopsis * sympartition( int ds[current_max_dfa_size], int numstates, * int symlist[numecs], int duplist[numecs] ); */ void sympartition (ds, numstates, symlist, duplist) int ds[], numstates; int symlist[], duplist[]; { int tch, i, j, k, ns, dupfwd[CSIZE + 1], lenccl, cclp, ich; /* Partitioning is done by creating equivalence classes for those * characters which have out-transitions from the given state. Thus * we are really creating equivalence classes of equivalence classes. */ for (i = 1; i <= numecs; ++i) { /* initialize equivalence class list */ duplist[i] = i - 1; dupfwd[i] = i + 1; } duplist[1] = NIL; dupfwd[numecs] = NIL; for (i = 1; i <= numstates; ++i) { ns = ds[i]; tch = transchar[ns]; if (tch != SYM_EPSILON) { if (tch < -lastccl || tch >= csize) { flexfatal (_ ("bad transition character detected in sympartition()")); } if (tch >= 0) { /* character transition */ int ec = ecgroup[tch]; mkechar (ec, dupfwd, duplist); symlist[ec] = 1; } else { /* character class */ tch = -tch; lenccl = ccllen[tch]; cclp = cclmap[tch]; mkeccl (ccltbl + cclp, lenccl, dupfwd, duplist, numecs, NUL_ec); if (cclng[tch]) { j = 0; for (k = 0; k < lenccl; ++k) { ich = ccltbl[cclp + k]; if (ich == 0) ich = NUL_ec; for (++j; j < ich; ++j) symlist[j] = 1; } for (++j; j <= numecs; ++j) symlist[j] = 1; } else for (k = 0; k < lenccl; ++k) { ich = ccltbl[cclp + k]; if (ich == 0) ich = NUL_ec; symlist[ich] = 1; } } } } } flex-2.6.0/src/mkskel.sh0000755000175000017500000000215312620472752015353 0ustar srivastasrivasta#! /bin/sh # This file is part of flex. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. cat <rm_so < 0) return NULL; len = m->rm_eo - m->rm_so; str = (char *) flex_alloc ((len + 1) * sizeof (char)); if (!str) flexfatal(_("Unable to allocate a copy of the match")); strncpy (str, src + m->rm_so, len); str[len] = 0; return str; } /** Copy the match. * @param m A match as returned by regexec(). * @param dest The destination buffer. * @param src The source string that was passed to regexec(). * @return dest */ char *regmatch_cpy (regmatch_t * m, char *dest, const char *src) { if (m == NULL || m->rm_so < 0) { if (dest) dest[0] = '\0'; return dest; } snprintf (dest, regmatch_len(m), "%s", src + m->rm_so); return dest; } /** Get the length in characters of the match. * @param m A match as returned by regexec(). * @return The length of the match. */ int regmatch_len (regmatch_t * m) { if (m == NULL || m->rm_so < 0) { return 0; } return m->rm_eo - m->rm_so; } /** Convert a regmatch_t object to an integer using the strtol() function. * @param m A match as returned by regexec(). * @param src The source string that was passed to regexec(). * @param endptr Same as the second argument to strtol(). * @param base Same as the third argument to strtol(). * @return The converted integer or error (Return value is the same as for strtol()). */ int regmatch_strtol (regmatch_t * m, const char *src, char **endptr, int base) { int n = 0; #define bufsz 20 char buf[bufsz]; char *s; if (m == NULL || m->rm_so < 0) return 0; if (regmatch_len (m) < bufsz) s = regmatch_cpy (m, buf, src); else s = regmatch_dup (m, src); n = strtol (s, endptr, base); if (s != buf) free (s); return n; } /** Check for empty or non-existent match. * @param m A match as returned by regexec(). * @return false if match length is non-zero. * Note that reg_empty returns true even if match did not occur at all. */ bool regmatch_empty (regmatch_t * m) { return (m == NULL || m->rm_so < 0 || m->rm_so == m->rm_eo); } /* vim:set expandtab cindent tabstop=4 softtabstop=4 shiftwidth=4 textwidth=0: */ flex-2.6.0/src/gen.c0000644000175000017500000015564212620475500014451 0ustar srivastasrivasta/* gen - actual generation (writing) of flex scanners */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" #include "tables.h" /* declare functions that have forward references */ void gen_next_state PROTO ((int)); void genecs PROTO ((void)); void indent_put2s PROTO ((const char *, const char *)); void indent_puts PROTO ((const char *)); static int indent_level = 0; /* each level is 8 spaces */ #define indent_up() (++indent_level) #define indent_down() (--indent_level) #define set_indent(indent_val) indent_level = indent_val /* Almost everything is done in terms of arrays starting at 1, so provide * a null entry for the zero element of all C arrays. (The exception * to this is that the fast table representation generally uses the * 0 elements of its arrays, too.) */ static const char *get_int16_decl (void) { return (gentables) ? "static yyconst flex_int16_t %s[%d] =\n { 0,\n" : "static yyconst flex_int16_t * %s = 0;\n"; } static const char *get_int32_decl (void) { return (gentables) ? "static yyconst flex_int32_t %s[%d] =\n { 0,\n" : "static yyconst flex_int32_t * %s = 0;\n"; } static const char *get_state_decl (void) { return (gentables) ? "static yyconst yy_state_type %s[%d] =\n { 0,\n" : "static yyconst yy_state_type * %s = 0;\n"; } static const char *get_uint16_decl (void) { return (gentables) ? "static yyconst flex_uint16_t %s[%d] =\n { 0,\n" : "static yyconst flex_uint16_t * %s = 0;\n"; } static const char *get_uint32_decl (void) { return (gentables) ? "static yyconst flex_uint32_t %s[%d] =\n { 0,\n" : "static yyconst flex_uint32_t * %s = 0;\n"; } static const char *get_yy_char_decl (void) { return (gentables) ? "static yyconst YY_CHAR %s[%d] =\n { 0,\n" : "static yyconst YY_CHAR * %s = 0;\n"; } /* Indent to the current level. */ void do_indent (void) { int i = indent_level * 8; while (i >= 8) { outc ('\t'); i -= 8; } while (i > 0) { outc (' '); --i; } } /** Make the table for possible eol matches. * @return the newly allocated rule_can_match_eol table */ static struct yytbl_data *mkeoltbl (void) { int i; flex_int8_t *tdata = 0; struct yytbl_data *tbl; tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (tbl, YYTD_ID_RULE_CAN_MATCH_EOL); tbl->td_flags = YYTD_DATA8; tbl->td_lolen = num_rules + 1; tbl->td_data = tdata = (flex_int8_t *) calloc (tbl->td_lolen, sizeof (flex_int8_t)); for (i = 1; i <= num_rules; i++) tdata[i] = rule_has_nl[i] ? 1 : 0; buf_prints (&yydmap_buf, "\t{YYTD_ID_RULE_CAN_MATCH_EOL, (void**)&yy_rule_can_match_eol, sizeof(%s)},\n", "flex_int32_t"); return tbl; } /* Generate the table for possible eol matches. */ static void geneoltbl (void) { int i; outn ("m4_ifdef( [[M4_YY_USE_LINENO]],[["); outn ("/* Table of booleans, true if rule could match eol. */"); out_str_dec (get_int32_decl (), "yy_rule_can_match_eol", num_rules + 1); if (gentables) { for (i = 1; i <= num_rules; i++) { out_dec ("%d, ", rule_has_nl[i] ? 1 : 0); /* format nicely, 20 numbers per line. */ if ((i % 20) == 19) out ("\n "); } out (" };\n"); } outn ("]])"); } /* Generate the code to keep backing-up information. */ void gen_backing_up (void) { if (reject || num_backing_up == 0) return; if (fullspd) indent_puts ("if ( yy_current_state[-1].yy_nxt )"); else indent_puts ("if ( yy_accept[yy_current_state] )"); indent_up (); indent_puts ("{"); indent_puts ("YY_G(yy_last_accepting_state) = yy_current_state;"); indent_puts ("YY_G(yy_last_accepting_cpos) = yy_cp;"); indent_puts ("}"); indent_down (); } /* Generate the code to perform the backing up. */ void gen_bu_action (void) { if (reject || num_backing_up == 0) return; set_indent (3); indent_puts ("case 0: /* must back up */"); indent_puts ("/* undo the effects of YY_DO_BEFORE_ACTION */"); indent_puts ("*yy_cp = YY_G(yy_hold_char);"); if (fullspd || fulltbl) indent_puts ("yy_cp = YY_G(yy_last_accepting_cpos) + 1;"); else /* Backing-up info for compressed tables is taken \after/ * yy_cp has been incremented for the next state. */ indent_puts ("yy_cp = YY_G(yy_last_accepting_cpos);"); indent_puts ("yy_current_state = YY_G(yy_last_accepting_state);"); indent_puts ("goto yy_find_action;"); outc ('\n'); set_indent (0); } /** mkctbl - make full speed compressed transition table * This is an array of structs; each struct a pair of integers. * You should call mkssltbl() immediately after this. * Then, I think, mkecstbl(). Arrrg. * @return the newly allocated trans table */ static struct yytbl_data *mkctbl (void) { int i; struct yytbl_data *tbl = 0; flex_int32_t *tdata = 0, curr = 0; int end_of_buffer_action = num_rules + 1; buf_prints (&yydmap_buf, "\t{YYTD_ID_TRANSITION, (void**)&yy_transition, sizeof(%s)},\n", ((tblend + numecs + 1) >= INT16_MAX || long_align) ? "flex_int32_t" : "flex_int16_t"); tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (tbl, YYTD_ID_TRANSITION); tbl->td_flags = YYTD_DATA32 | YYTD_STRUCT; tbl->td_hilen = 0; tbl->td_lolen = tblend + numecs + 1; /* number of structs */ tbl->td_data = tdata = (flex_int32_t *) calloc (tbl->td_lolen * 2, sizeof (flex_int32_t)); /* We want the transition to be represented as the offset to the * next state, not the actual state number, which is what it currently * is. The offset is base[nxt[i]] - (base of current state)]. That's * just the difference between the starting points of the two involved * states (to - from). * * First, though, we need to find some way to put in our end-of-buffer * flags and states. We do this by making a state with absolutely no * transitions. We put it at the end of the table. */ /* We need to have room in nxt/chk for two more slots: One for the * action and one for the end-of-buffer transition. We now *assume* * that we're guaranteed the only character we'll try to index this * nxt/chk pair with is EOB, i.e., 0, so we don't have to make sure * there's room for jam entries for other characters. */ while (tblend + 2 >= current_max_xpairs) expand_nxt_chk (); while (lastdfa + 1 >= current_max_dfas) increase_max_dfas (); base[lastdfa + 1] = tblend + 2; nxt[tblend + 1] = end_of_buffer_action; chk[tblend + 1] = numecs + 1; chk[tblend + 2] = 1; /* anything but EOB */ /* So that "make test" won't show arb. differences. */ nxt[tblend + 2] = 0; /* Make sure every state has an end-of-buffer transition and an * action #. */ for (i = 0; i <= lastdfa; ++i) { int anum = dfaacc[i].dfaacc_state; int offset = base[i]; chk[offset] = EOB_POSITION; chk[offset - 1] = ACTION_POSITION; nxt[offset - 1] = anum; /* action number */ } for (i = 0; i <= tblend; ++i) { if (chk[i] == EOB_POSITION) { tdata[curr++] = 0; tdata[curr++] = base[lastdfa + 1] - i; } else if (chk[i] == ACTION_POSITION) { tdata[curr++] = 0; tdata[curr++] = nxt[i]; } else if (chk[i] > numecs || chk[i] == 0) { tdata[curr++] = 0; tdata[curr++] = 0; } else { /* verify, transition */ tdata[curr++] = chk[i]; tdata[curr++] = base[nxt[i]] - (i - chk[i]); } } /* Here's the final, end-of-buffer state. */ tdata[curr++] = chk[tblend + 1]; tdata[curr++] = nxt[tblend + 1]; tdata[curr++] = chk[tblend + 2]; tdata[curr++] = nxt[tblend + 2]; return tbl; } /** Make start_state_list table. * @return the newly allocated start_state_list table */ static struct yytbl_data *mkssltbl (void) { struct yytbl_data *tbl = 0; flex_int32_t *tdata = 0; flex_int32_t i; tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (tbl, YYTD_ID_START_STATE_LIST); tbl->td_flags = YYTD_DATA32 | YYTD_PTRANS; tbl->td_hilen = 0; tbl->td_lolen = lastsc * 2 + 1; tbl->td_data = tdata = (flex_int32_t *) calloc (tbl->td_lolen, sizeof (flex_int32_t)); for (i = 0; i <= lastsc * 2; ++i) tdata[i] = base[i]; buf_prints (&yydmap_buf, "\t{YYTD_ID_START_STATE_LIST, (void**)&yy_start_state_list, sizeof(%s)},\n", "struct yy_trans_info*"); return tbl; } /* genctbl - generates full speed compressed transition table */ void genctbl (void) { int i; int end_of_buffer_action = num_rules + 1; /* Table of verify for transition and offset to next state. */ if (gentables) out_dec ("static yyconst struct yy_trans_info yy_transition[%d] =\n {\n", tblend + numecs + 1); else outn ("static yyconst struct yy_trans_info *yy_transition = 0;"); /* We want the transition to be represented as the offset to the * next state, not the actual state number, which is what it currently * is. The offset is base[nxt[i]] - (base of current state)]. That's * just the difference between the starting points of the two involved * states (to - from). * * First, though, we need to find some way to put in our end-of-buffer * flags and states. We do this by making a state with absolutely no * transitions. We put it at the end of the table. */ /* We need to have room in nxt/chk for two more slots: One for the * action and one for the end-of-buffer transition. We now *assume* * that we're guaranteed the only character we'll try to index this * nxt/chk pair with is EOB, i.e., 0, so we don't have to make sure * there's room for jam entries for other characters. */ while (tblend + 2 >= current_max_xpairs) expand_nxt_chk (); while (lastdfa + 1 >= current_max_dfas) increase_max_dfas (); base[lastdfa + 1] = tblend + 2; nxt[tblend + 1] = end_of_buffer_action; chk[tblend + 1] = numecs + 1; chk[tblend + 2] = 1; /* anything but EOB */ /* So that "make test" won't show arb. differences. */ nxt[tblend + 2] = 0; /* Make sure every state has an end-of-buffer transition and an * action #. */ for (i = 0; i <= lastdfa; ++i) { int anum = dfaacc[i].dfaacc_state; int offset = base[i]; chk[offset] = EOB_POSITION; chk[offset - 1] = ACTION_POSITION; nxt[offset - 1] = anum; /* action number */ } for (i = 0; i <= tblend; ++i) { if (chk[i] == EOB_POSITION) transition_struct_out (0, base[lastdfa + 1] - i); else if (chk[i] == ACTION_POSITION) transition_struct_out (0, nxt[i]); else if (chk[i] > numecs || chk[i] == 0) transition_struct_out (0, 0); /* unused slot */ else /* verify, transition */ transition_struct_out (chk[i], base[nxt[i]] - (i - chk[i])); } /* Here's the final, end-of-buffer state. */ transition_struct_out (chk[tblend + 1], nxt[tblend + 1]); transition_struct_out (chk[tblend + 2], nxt[tblend + 2]); if (gentables) outn (" };\n"); /* Table of pointers to start states. */ if (gentables) out_dec ("static yyconst struct yy_trans_info *yy_start_state_list[%d] =\n", lastsc * 2 + 1); else outn ("static yyconst struct yy_trans_info **yy_start_state_list =0;"); if (gentables) { outn (" {"); for (i = 0; i <= lastsc * 2; ++i) out_dec (" &yy_transition[%d],\n", base[i]); dataend (); } if (useecs) genecs (); } /* mkecstbl - Make equivalence-class tables. */ struct yytbl_data *mkecstbl (void) { int i; struct yytbl_data *tbl = 0; flex_int32_t *tdata = 0; tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (tbl, YYTD_ID_EC); tbl->td_flags |= YYTD_DATA32; tbl->td_hilen = 0; tbl->td_lolen = csize; tbl->td_data = tdata = (flex_int32_t *) calloc (tbl->td_lolen, sizeof (flex_int32_t)); for (i = 1; i < csize; ++i) { ecgroup[i] = ABS (ecgroup[i]); tdata[i] = ecgroup[i]; } buf_prints (&yydmap_buf, "\t{YYTD_ID_EC, (void**)&yy_ec, sizeof(%s)},\n", "YY_CHAR"); return tbl; } /* Generate equivalence-class tables. */ void genecs (void) { int i, j; int numrows; out_str_dec (get_yy_char_decl (), "yy_ec", csize); for (i = 1; i < csize; ++i) { ecgroup[i] = ABS (ecgroup[i]); mkdata (ecgroup[i]); } dataend (); if (trace) { fputs (_("\n\nEquivalence Classes:\n\n"), stderr); numrows = csize / 8; for (j = 0; j < numrows; ++j) { for (i = j; i < csize; i = i + numrows) { fprintf (stderr, "%4s = %-2d", readable_form (i), ecgroup[i]); putc (' ', stderr); } putc ('\n', stderr); } } } /* Generate the code to find the action number. */ void gen_find_action (void) { if (fullspd) indent_puts ("yy_act = yy_current_state[-1].yy_nxt;"); else if (fulltbl) indent_puts ("yy_act = yy_accept[yy_current_state];"); else if (reject) { indent_puts ("yy_current_state = *--YY_G(yy_state_ptr);"); indent_puts ("YY_G(yy_lp) = yy_accept[yy_current_state];"); if(reject_really_used) outn ("find_rule: /* we branch to this label when backing up */"); indent_puts ("for ( ; ; ) /* until we find what rule we matched */"); indent_up (); indent_puts ("{"); indent_puts ("if ( YY_G(yy_lp) && YY_G(yy_lp) < yy_accept[yy_current_state + 1] )"); indent_up (); indent_puts ("{"); indent_puts ("yy_act = yy_acclist[YY_G(yy_lp)];"); if (variable_trailing_context_rules) { indent_puts ("if ( yy_act & YY_TRAILING_HEAD_MASK ||"); indent_puts (" YY_G(yy_looking_for_trail_begin) )"); indent_up (); indent_puts ("{"); indent_puts ("if ( yy_act == YY_G(yy_looking_for_trail_begin) )"); indent_up (); indent_puts ("{"); indent_puts ("YY_G(yy_looking_for_trail_begin) = 0;"); indent_puts ("yy_act &= ~YY_TRAILING_HEAD_MASK;"); indent_puts ("break;"); indent_puts ("}"); indent_down (); indent_puts ("}"); indent_down (); indent_puts ("else if ( yy_act & YY_TRAILING_MASK )"); indent_up (); indent_puts ("{"); indent_puts ("YY_G(yy_looking_for_trail_begin) = yy_act & ~YY_TRAILING_MASK;"); indent_puts ("YY_G(yy_looking_for_trail_begin) |= YY_TRAILING_HEAD_MASK;"); if (real_reject) { /* Remember matched text in case we back up * due to REJECT. */ indent_puts ("YY_G(yy_full_match) = yy_cp;"); indent_puts ("YY_G(yy_full_state) = YY_G(yy_state_ptr);"); indent_puts ("YY_G(yy_full_lp) = YY_G(yy_lp);"); } indent_puts ("}"); indent_down (); indent_puts ("else"); indent_up (); indent_puts ("{"); indent_puts ("YY_G(yy_full_match) = yy_cp;"); indent_puts ("YY_G(yy_full_state) = YY_G(yy_state_ptr);"); indent_puts ("YY_G(yy_full_lp) = YY_G(yy_lp);"); indent_puts ("break;"); indent_puts ("}"); indent_down (); indent_puts ("++YY_G(yy_lp);"); indent_puts ("goto find_rule;"); } else { /* Remember matched text in case we back up due to * trailing context plus REJECT. */ indent_up (); indent_puts ("{"); indent_puts ("YY_G(yy_full_match) = yy_cp;"); indent_puts ("break;"); indent_puts ("}"); indent_down (); } indent_puts ("}"); indent_down (); indent_puts ("--yy_cp;"); /* We could consolidate the following two lines with those at * the beginning, but at the cost of complaints that we're * branching inside a loop. */ indent_puts ("yy_current_state = *--YY_G(yy_state_ptr);"); indent_puts ("YY_G(yy_lp) = yy_accept[yy_current_state];"); indent_puts ("}"); indent_down (); } else { /* compressed */ indent_puts ("yy_act = yy_accept[yy_current_state];"); if (interactive && !reject) { /* Do the guaranteed-needed backing up to figure out * the match. */ indent_puts ("if ( yy_act == 0 )"); indent_up (); indent_puts ("{ /* have to back up */"); indent_puts ("yy_cp = YY_G(yy_last_accepting_cpos);"); indent_puts ("yy_current_state = YY_G(yy_last_accepting_state);"); indent_puts ("yy_act = yy_accept[yy_current_state];"); indent_puts ("}"); indent_down (); } } } /* mkftbl - make the full table and return the struct . * you should call mkecstbl() after this. */ struct yytbl_data *mkftbl (void) { int i; int end_of_buffer_action = num_rules + 1; struct yytbl_data *tbl; flex_int32_t *tdata = 0; tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (tbl, YYTD_ID_ACCEPT); tbl->td_flags |= YYTD_DATA32; tbl->td_hilen = 0; /* it's a one-dimensional array */ tbl->td_lolen = lastdfa + 1; tbl->td_data = tdata = (flex_int32_t *) calloc (tbl->td_lolen, sizeof (flex_int32_t)); dfaacc[end_of_buffer_state].dfaacc_state = end_of_buffer_action; for (i = 1; i <= lastdfa; ++i) { int anum = dfaacc[i].dfaacc_state; tdata[i] = anum; if (trace && anum) fprintf (stderr, _("state # %d accepts: [%d]\n"), i, anum); } buf_prints (&yydmap_buf, "\t{YYTD_ID_ACCEPT, (void**)&yy_accept, sizeof(%s)},\n", long_align ? "flex_int32_t" : "flex_int16_t"); return tbl; } /* genftbl - generate full transition table */ void genftbl (void) { int i; int end_of_buffer_action = num_rules + 1; out_str_dec (long_align ? get_int32_decl () : get_int16_decl (), "yy_accept", lastdfa + 1); dfaacc[end_of_buffer_state].dfaacc_state = end_of_buffer_action; for (i = 1; i <= lastdfa; ++i) { int anum = dfaacc[i].dfaacc_state; mkdata (anum); if (trace && anum) fprintf (stderr, _("state # %d accepts: [%d]\n"), i, anum); } dataend (); if (useecs) genecs (); /* Don't have to dump the actual full table entries - they were * created on-the-fly. */ } /* Generate the code to find the next compressed-table state. */ void gen_next_compressed_state (char_map) char *char_map; { indent_put2s ("YY_CHAR yy_c = %s;", char_map); /* Save the backing-up info \before/ computing the next state * because we always compute one more state than needed - we * always proceed until we reach a jam state */ gen_backing_up (); indent_puts ("while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )"); indent_up (); indent_puts ("{"); indent_puts ("yy_current_state = (int) yy_def[yy_current_state];"); if (usemecs) { /* We've arrange it so that templates are never chained * to one another. This means we can afford to make a * very simple test to see if we need to convert to * yy_c's meta-equivalence class without worrying * about erroneously looking up the meta-equivalence * class twice */ do_indent (); /* lastdfa + 2 is the beginning of the templates */ out_dec ("if ( yy_current_state >= %d )\n", lastdfa + 2); indent_up (); indent_puts ("yy_c = yy_meta[(unsigned int) yy_c];"); indent_down (); } indent_puts ("}"); indent_down (); indent_puts ("yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];"); } /* Generate the code to find the next match. */ void gen_next_match (void) { /* NOTE - changes in here should be reflected in gen_next_state() and * gen_NUL_trans(). */ char *char_map = useecs ? "yy_ec[YY_SC_TO_UI(*yy_cp)] " : "YY_SC_TO_UI(*yy_cp)"; char *char_map_2 = useecs ? "yy_ec[YY_SC_TO_UI(*++yy_cp)] " : "YY_SC_TO_UI(*++yy_cp)"; if (fulltbl) { if (gentables) indent_put2s ("while ( (yy_current_state = yy_nxt[yy_current_state][ %s ]) > 0 )", char_map); else indent_put2s ("while ( (yy_current_state = yy_nxt[yy_current_state*YY_NXT_LOLEN + %s ]) > 0 )", char_map); indent_up (); if (num_backing_up > 0) { indent_puts ("{"); gen_backing_up (); outc ('\n'); } indent_puts ("++yy_cp;"); if (num_backing_up > 0) indent_puts ("}"); indent_down (); outc ('\n'); indent_puts ("yy_current_state = -yy_current_state;"); } else if (fullspd) { indent_puts ("{"); indent_puts ("yyconst struct yy_trans_info *yy_trans_info;\n"); indent_puts ("YY_CHAR yy_c;\n"); indent_put2s ("for ( yy_c = %s;", char_map); indent_puts (" (yy_trans_info = &yy_current_state[(unsigned int) yy_c])->"); indent_puts ("yy_verify == yy_c;"); indent_put2s (" yy_c = %s )", char_map_2); indent_up (); if (num_backing_up > 0) indent_puts ("{"); indent_puts ("yy_current_state += yy_trans_info->yy_nxt;"); if (num_backing_up > 0) { outc ('\n'); gen_backing_up (); indent_puts ("}"); } indent_down (); indent_puts ("}"); } else { /* compressed */ indent_puts ("do"); indent_up (); indent_puts ("{"); gen_next_state (false); indent_puts ("++yy_cp;"); indent_puts ("}"); indent_down (); do_indent (); if (interactive) out_dec ("while ( yy_base[yy_current_state] != %d );\n", jambase); else out_dec ("while ( yy_current_state != %d );\n", jamstate); if (!reject && !interactive) { /* Do the guaranteed-needed backing up to figure out * the match. */ indent_puts ("yy_cp = YY_G(yy_last_accepting_cpos);"); indent_puts ("yy_current_state = YY_G(yy_last_accepting_state);"); } } } /* Generate the code to find the next state. */ void gen_next_state (worry_about_NULs) int worry_about_NULs; { /* NOTE - changes in here should be reflected in gen_next_match() */ char char_map[256]; if (worry_about_NULs && !nultrans) { if (useecs) snprintf (char_map, sizeof(char_map), "(*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : %d)", NUL_ec); else snprintf (char_map, sizeof(char_map), "(*yy_cp ? YY_SC_TO_UI(*yy_cp) : %d)", NUL_ec); } else strcpy (char_map, useecs ? "yy_ec[YY_SC_TO_UI(*yy_cp)] " : "YY_SC_TO_UI(*yy_cp)"); if (worry_about_NULs && nultrans) { if (!fulltbl && !fullspd) /* Compressed tables back up *before* they match. */ gen_backing_up (); indent_puts ("if ( *yy_cp )"); indent_up (); indent_puts ("{"); } if (fulltbl) { if (gentables) indent_put2s ("yy_current_state = yy_nxt[yy_current_state][%s];", char_map); else indent_put2s ("yy_current_state = yy_nxt[yy_current_state*YY_NXT_LOLEN + %s];", char_map); } else if (fullspd) indent_put2s ("yy_current_state += yy_current_state[%s].yy_nxt;", char_map); else gen_next_compressed_state (char_map); if (worry_about_NULs && nultrans) { indent_puts ("}"); indent_down (); indent_puts ("else"); indent_up (); indent_puts ("yy_current_state = yy_NUL_trans[yy_current_state];"); indent_down (); } if (fullspd || fulltbl) gen_backing_up (); if (reject) indent_puts ("*YY_G(yy_state_ptr)++ = yy_current_state;"); } /* Generate the code to make a NUL transition. */ void gen_NUL_trans (void) { /* NOTE - changes in here should be reflected in gen_next_match() */ /* Only generate a definition for "yy_cp" if we'll generate code * that uses it. Otherwise lint and the like complain. */ int need_backing_up = (num_backing_up > 0 && !reject); if (need_backing_up && (!nultrans || fullspd || fulltbl)) /* We're going to need yy_cp lying around for the call * below to gen_backing_up(). */ indent_puts ("char *yy_cp = YY_G(yy_c_buf_p);"); outc ('\n'); if (nultrans) { indent_puts ("yy_current_state = yy_NUL_trans[yy_current_state];"); indent_puts ("yy_is_jam = (yy_current_state == 0);"); } else if (fulltbl) { do_indent (); if (gentables) out_dec ("yy_current_state = yy_nxt[yy_current_state][%d];\n", NUL_ec); else out_dec ("yy_current_state = yy_nxt[yy_current_state*YY_NXT_LOLEN + %d];\n", NUL_ec); indent_puts ("yy_is_jam = (yy_current_state <= 0);"); } else if (fullspd) { do_indent (); out_dec ("int yy_c = %d;\n", NUL_ec); indent_puts ("yyconst struct yy_trans_info *yy_trans_info;\n"); indent_puts ("yy_trans_info = &yy_current_state[(unsigned int) yy_c];"); indent_puts ("yy_current_state += yy_trans_info->yy_nxt;"); indent_puts ("yy_is_jam = (yy_trans_info->yy_verify != yy_c);"); } else { char NUL_ec_str[20]; snprintf (NUL_ec_str, sizeof(NUL_ec_str), "%d", NUL_ec); gen_next_compressed_state (NUL_ec_str); do_indent (); out_dec ("yy_is_jam = (yy_current_state == %d);\n", jamstate); if (reject) { /* Only stack this state if it's a transition we * actually make. If we stack it on a jam, then * the state stack and yy_c_buf_p get out of sync. */ indent_puts ("if ( ! yy_is_jam )"); indent_up (); indent_puts ("*YY_G(yy_state_ptr)++ = yy_current_state;"); indent_down (); } } /* If we've entered an accepting state, back up; note that * compressed tables have *already* done such backing up, so * we needn't bother with it again. */ if (need_backing_up && (fullspd || fulltbl)) { outc ('\n'); indent_puts ("if ( ! yy_is_jam )"); indent_up (); indent_puts ("{"); gen_backing_up (); indent_puts ("}"); indent_down (); } } /* Generate the code to find the start state. */ void gen_start_state (void) { if (fullspd) { if (bol_needed) { indent_puts ("yy_current_state = yy_start_state_list[YY_G(yy_start) + YY_AT_BOL()];"); } else indent_puts ("yy_current_state = yy_start_state_list[YY_G(yy_start)];"); } else { indent_puts ("yy_current_state = YY_G(yy_start);"); if (bol_needed) indent_puts ("yy_current_state += YY_AT_BOL();"); if (reject) { /* Set up for storing up states. */ outn ("m4_ifdef( [[M4_YY_USES_REJECT]],\n[["); indent_puts ("YY_G(yy_state_ptr) = YY_G(yy_state_buf);"); indent_puts ("*YY_G(yy_state_ptr)++ = yy_current_state;"); outn ("]])"); } } } /* gentabs - generate data statements for the transition tables */ void gentabs (void) { int i, j, k, *accset, nacc, *acc_array, total_states; int end_of_buffer_action = num_rules + 1; struct yytbl_data *yyacc_tbl = 0, *yymeta_tbl = 0, *yybase_tbl = 0, *yydef_tbl = 0, *yynxt_tbl = 0, *yychk_tbl = 0, *yyacclist_tbl=0; flex_int32_t *yyacc_data = 0, *yybase_data = 0, *yydef_data = 0, *yynxt_data = 0, *yychk_data = 0, *yyacclist_data=0; flex_int32_t yybase_curr = 0, yyacclist_curr=0,yyacc_curr=0; acc_array = allocate_integer_array (current_max_dfas); nummt = 0; /* The compressed table format jams by entering the "jam state", * losing information about the previous state in the process. * In order to recover the previous state, we effectively need * to keep backing-up information. */ ++num_backing_up; if (reject) { /* Write out accepting list and pointer list. * First we generate the "yy_acclist" array. In the process, * we compute the indices that will go into the "yy_accept" * array, and save the indices in the dfaacc array. */ int EOB_accepting_list[2]; /* Set up accepting structures for the End Of Buffer state. */ EOB_accepting_list[0] = 0; EOB_accepting_list[1] = end_of_buffer_action; accsiz[end_of_buffer_state] = 1; dfaacc[end_of_buffer_state].dfaacc_set = EOB_accepting_list; out_str_dec (long_align ? get_int32_decl () : get_int16_decl (), "yy_acclist", MAX (numas, 1) + 1); buf_prints (&yydmap_buf, "\t{YYTD_ID_ACCLIST, (void**)&yy_acclist, sizeof(%s)},\n", long_align ? "flex_int32_t" : "flex_int16_t"); yyacclist_tbl = (struct yytbl_data*)calloc(1,sizeof(struct yytbl_data)); yytbl_data_init (yyacclist_tbl, YYTD_ID_ACCLIST); yyacclist_tbl->td_lolen = MAX(numas,1) + 1; yyacclist_tbl->td_data = yyacclist_data = (flex_int32_t *) calloc (yyacclist_tbl->td_lolen, sizeof (flex_int32_t)); yyacclist_curr = 1; j = 1; /* index into "yy_acclist" array */ for (i = 1; i <= lastdfa; ++i) { acc_array[i] = j; if (accsiz[i] != 0) { accset = dfaacc[i].dfaacc_set; nacc = accsiz[i]; if (trace) fprintf (stderr, _("state # %d accepts: "), i); for (k = 1; k <= nacc; ++k) { int accnum = accset[k]; ++j; if (variable_trailing_context_rules && !(accnum & YY_TRAILING_HEAD_MASK) && accnum > 0 && accnum <= num_rules && rule_type[accnum] == RULE_VARIABLE) { /* Special hack to flag * accepting number as part * of trailing context rule. */ accnum |= YY_TRAILING_MASK; } mkdata (accnum); yyacclist_data[yyacclist_curr++] = accnum; if (trace) { fprintf (stderr, "[%d]", accset[k]); if (k < nacc) fputs (", ", stderr); else putc ('\n', stderr); } } } } /* add accepting number for the "jam" state */ acc_array[i] = j; dataend (); if (tablesext) { yytbl_data_compress (yyacclist_tbl); if (yytbl_data_fwrite (&tableswr, yyacclist_tbl) < 0) flexerror (_("Could not write yyacclist_tbl")); yytbl_data_destroy (yyacclist_tbl); yyacclist_tbl = NULL; } } else { dfaacc[end_of_buffer_state].dfaacc_state = end_of_buffer_action; for (i = 1; i <= lastdfa; ++i) acc_array[i] = dfaacc[i].dfaacc_state; /* add accepting number for jam state */ acc_array[i] = 0; } /* Begin generating yy_accept */ /* Spit out "yy_accept" array. If we're doing "reject", it'll be * pointers into the "yy_acclist" array. Otherwise it's actual * accepting numbers. In either case, we just dump the numbers. */ /* "lastdfa + 2" is the size of "yy_accept"; includes room for C arrays * beginning at 0 and for "jam" state. */ k = lastdfa + 2; if (reject) /* We put a "cap" on the table associating lists of accepting * numbers with state numbers. This is needed because we tell * where the end of an accepting list is by looking at where * the list for the next state starts. */ ++k; out_str_dec (long_align ? get_int32_decl () : get_int16_decl (), "yy_accept", k); buf_prints (&yydmap_buf, "\t{YYTD_ID_ACCEPT, (void**)&yy_accept, sizeof(%s)},\n", long_align ? "flex_int32_t" : "flex_int16_t"); yyacc_tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (yyacc_tbl, YYTD_ID_ACCEPT); yyacc_tbl->td_lolen = k; yyacc_tbl->td_data = yyacc_data = (flex_int32_t *) calloc (yyacc_tbl->td_lolen, sizeof (flex_int32_t)); yyacc_curr=1; for (i = 1; i <= lastdfa; ++i) { mkdata (acc_array[i]); yyacc_data[yyacc_curr++] = acc_array[i]; if (!reject && trace && acc_array[i]) fprintf (stderr, _("state # %d accepts: [%d]\n"), i, acc_array[i]); } /* Add entry for "jam" state. */ mkdata (acc_array[i]); yyacc_data[yyacc_curr++] = acc_array[i]; if (reject) { /* Add "cap" for the list. */ mkdata (acc_array[i]); yyacc_data[yyacc_curr++] = acc_array[i]; } dataend (); if (tablesext) { yytbl_data_compress (yyacc_tbl); if (yytbl_data_fwrite (&tableswr, yyacc_tbl) < 0) flexerror (_("Could not write yyacc_tbl")); yytbl_data_destroy (yyacc_tbl); yyacc_tbl = NULL; } /* End generating yy_accept */ if (useecs) { genecs (); if (tablesext) { struct yytbl_data *tbl; tbl = mkecstbl (); yytbl_data_compress (tbl); if (yytbl_data_fwrite (&tableswr, tbl) < 0) flexerror (_("Could not write ecstbl")); yytbl_data_destroy (tbl); tbl = 0; } } if (usemecs) { /* Begin generating yy_meta */ /* Write out meta-equivalence classes (used to index * templates with). */ flex_int32_t *yymecs_data = 0; yymeta_tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (yymeta_tbl, YYTD_ID_META); yymeta_tbl->td_lolen = numecs + 1; yymeta_tbl->td_data = yymecs_data = (flex_int32_t *) calloc (yymeta_tbl->td_lolen, sizeof (flex_int32_t)); if (trace) fputs (_("\n\nMeta-Equivalence Classes:\n"), stderr); out_str_dec (get_yy_char_decl (), "yy_meta", numecs + 1); buf_prints (&yydmap_buf, "\t{YYTD_ID_META, (void**)&yy_meta, sizeof(%s)},\n", "YY_CHAR"); for (i = 1; i <= numecs; ++i) { if (trace) fprintf (stderr, "%d = %d\n", i, ABS (tecbck[i])); mkdata (ABS (tecbck[i])); yymecs_data[i] = ABS (tecbck[i]); } dataend (); if (tablesext) { yytbl_data_compress (yymeta_tbl); if (yytbl_data_fwrite (&tableswr, yymeta_tbl) < 0) flexerror (_ ("Could not write yymeta_tbl")); yytbl_data_destroy (yymeta_tbl); yymeta_tbl = NULL; } /* End generating yy_meta */ } total_states = lastdfa + numtemps; /* Begin generating yy_base */ out_str_dec ((tblend >= INT16_MAX || long_align) ? get_uint32_decl () : get_uint16_decl (), "yy_base", total_states + 1); buf_prints (&yydmap_buf, "\t{YYTD_ID_BASE, (void**)&yy_base, sizeof(%s)},\n", (tblend >= INT16_MAX || long_align) ? "flex_uint32_t" : "flex_uint16_t"); yybase_tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (yybase_tbl, YYTD_ID_BASE); yybase_tbl->td_lolen = total_states + 1; yybase_tbl->td_data = yybase_data = (flex_int32_t *) calloc (yybase_tbl->td_lolen, sizeof (flex_int32_t)); yybase_curr = 1; for (i = 1; i <= lastdfa; ++i) { int d = def[i]; if (base[i] == JAMSTATE) base[i] = jambase; if (d == JAMSTATE) def[i] = jamstate; else if (d < 0) { /* Template reference. */ ++tmpuses; def[i] = lastdfa - d + 1; } mkdata (base[i]); yybase_data[yybase_curr++] = base[i]; } /* Generate jam state's base index. */ mkdata (base[i]); yybase_data[yybase_curr++] = base[i]; for (++i /* skip jam state */ ; i <= total_states; ++i) { mkdata (base[i]); yybase_data[yybase_curr++] = base[i]; def[i] = jamstate; } dataend (); if (tablesext) { yytbl_data_compress (yybase_tbl); if (yytbl_data_fwrite (&tableswr, yybase_tbl) < 0) flexerror (_("Could not write yybase_tbl")); yytbl_data_destroy (yybase_tbl); yybase_tbl = NULL; } /* End generating yy_base */ /* Begin generating yy_def */ out_str_dec ((total_states >= INT16_MAX || long_align) ? get_int32_decl () : get_int16_decl (), "yy_def", total_states + 1); buf_prints (&yydmap_buf, "\t{YYTD_ID_DEF, (void**)&yy_def, sizeof(%s)},\n", (total_states >= INT16_MAX || long_align) ? "flex_int32_t" : "flex_int16_t"); yydef_tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (yydef_tbl, YYTD_ID_DEF); yydef_tbl->td_lolen = total_states + 1; yydef_tbl->td_data = yydef_data = (flex_int32_t *) calloc (yydef_tbl->td_lolen, sizeof (flex_int32_t)); for (i = 1; i <= total_states; ++i) { mkdata (def[i]); yydef_data[i] = def[i]; } dataend (); if (tablesext) { yytbl_data_compress (yydef_tbl); if (yytbl_data_fwrite (&tableswr, yydef_tbl) < 0) flexerror (_("Could not write yydef_tbl")); yytbl_data_destroy (yydef_tbl); yydef_tbl = NULL; } /* End generating yy_def */ /* Begin generating yy_nxt */ out_str_dec ((total_states >= INT16_MAX || long_align) ? get_uint32_decl () : get_uint16_decl (), "yy_nxt", tblend + 1); buf_prints (&yydmap_buf, "\t{YYTD_ID_NXT, (void**)&yy_nxt, sizeof(%s)},\n", (total_states >= INT16_MAX || long_align) ? "flex_uint32_t" : "flex_uint16_t"); yynxt_tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (yynxt_tbl, YYTD_ID_NXT); yynxt_tbl->td_lolen = tblend + 1; yynxt_tbl->td_data = yynxt_data = (flex_int32_t *) calloc (yynxt_tbl->td_lolen, sizeof (flex_int32_t)); for (i = 1; i <= tblend; ++i) { /* Note, the order of the following test is important. * If chk[i] is 0, then nxt[i] is undefined. */ if (chk[i] == 0 || nxt[i] == 0) nxt[i] = jamstate; /* new state is the JAM state */ mkdata (nxt[i]); yynxt_data[i] = nxt[i]; } dataend (); if (tablesext) { yytbl_data_compress (yynxt_tbl); if (yytbl_data_fwrite (&tableswr, yynxt_tbl) < 0) flexerror (_("Could not write yynxt_tbl")); yytbl_data_destroy (yynxt_tbl); yynxt_tbl = NULL; } /* End generating yy_nxt */ /* Begin generating yy_chk */ out_str_dec ((total_states >= INT16_MAX || long_align) ? get_int32_decl () : get_int16_decl (), "yy_chk", tblend + 1); buf_prints (&yydmap_buf, "\t{YYTD_ID_CHK, (void**)&yy_chk, sizeof(%s)},\n", (total_states >= INT16_MAX || long_align) ? "flex_int32_t" : "flex_int16_t"); yychk_tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (yychk_tbl, YYTD_ID_CHK); yychk_tbl->td_lolen = tblend + 1; yychk_tbl->td_data = yychk_data = (flex_int32_t *) calloc (yychk_tbl->td_lolen, sizeof (flex_int32_t)); for (i = 1; i <= tblend; ++i) { if (chk[i] == 0) ++nummt; mkdata (chk[i]); yychk_data[i] = chk[i]; } dataend (); if (tablesext) { yytbl_data_compress (yychk_tbl); if (yytbl_data_fwrite (&tableswr, yychk_tbl) < 0) flexerror (_("Could not write yychk_tbl")); yytbl_data_destroy (yychk_tbl); yychk_tbl = NULL; } /* End generating yy_chk */ flex_free ((void *) acc_array); } /* Write out a formatted string (with a secondary string argument) at the * current indentation level, adding a final newline. */ void indent_put2s (fmt, arg) const char *fmt, *arg; { do_indent (); out_str (fmt, arg); outn (""); } /* Write out a string at the current indentation level, adding a final * newline. */ void indent_puts (str) const char *str; { do_indent (); outn (str); } /* make_tables - generate transition tables and finishes generating output file */ void make_tables (void) { int i; int did_eof_rule = false; struct yytbl_data *yynultrans_tbl = NULL; skelout (); /* %% [2.0] - break point in skel */ /* First, take care of YY_DO_BEFORE_ACTION depending on yymore * being used. */ set_indent (1); if (yymore_used && !yytext_is_array) { indent_puts ("YY_G(yytext_ptr) -= YY_G(yy_more_len); \\"); indent_puts ("yyleng = (size_t) (yy_cp - YY_G(yytext_ptr)); \\"); } else indent_puts ("yyleng = (size_t) (yy_cp - yy_bp); \\"); /* Now also deal with copying yytext_ptr to yytext if needed. */ skelout (); /* %% [3.0] - break point in skel */ if (yytext_is_array) { if (yymore_used) indent_puts ("if ( yyleng + YY_G(yy_more_offset) >= YYLMAX ) \\"); else indent_puts ("if ( yyleng >= YYLMAX ) \\"); indent_up (); indent_puts ("YY_FATAL_ERROR( \"token too large, exceeds YYLMAX\" ); \\"); indent_down (); if (yymore_used) { indent_puts ("yy_flex_strncpy( &yytext[YY_G(yy_more_offset)], YY_G(yytext_ptr), yyleng + 1 M4_YY_CALL_LAST_ARG); \\"); indent_puts ("yyleng += YY_G(yy_more_offset); \\"); indent_puts ("YY_G(yy_prev_more_offset) = YY_G(yy_more_offset); \\"); indent_puts ("YY_G(yy_more_offset) = 0; \\"); } else { indent_puts ("yy_flex_strncpy( yytext, YY_G(yytext_ptr), yyleng + 1 M4_YY_CALL_LAST_ARG); \\"); } } set_indent (0); skelout (); /* %% [4.0] - break point in skel */ /* This is where we REALLY begin generating the tables. */ out_dec ("#define YY_NUM_RULES %d\n", num_rules); out_dec ("#define YY_END_OF_BUFFER %d\n", num_rules + 1); if (fullspd) { /* Need to define the transet type as a size large * enough to hold the biggest offset. */ int total_table_size = tblend + numecs + 1; char *trans_offset_type = (total_table_size >= INT16_MAX || long_align) ? "flex_int32_t" : "flex_int16_t"; set_indent (0); indent_puts ("struct yy_trans_info"); indent_up (); indent_puts ("{"); /* We require that yy_verify and yy_nxt must be of the same size int. */ indent_put2s ("%s yy_verify;", trans_offset_type); /* In cases where its sister yy_verify *is* a "yes, there is * a transition", yy_nxt is the offset (in records) to the * next state. In most cases where there is no transition, * the value of yy_nxt is irrelevant. If yy_nxt is the -1th * record of a state, though, then yy_nxt is the action number * for that state. */ indent_put2s ("%s yy_nxt;", trans_offset_type); indent_puts ("};"); indent_down (); } else { /* We generate a bogus 'struct yy_trans_info' data type * so we can guarantee that it is always declared in the skel. * This is so we can compile "sizeof(struct yy_trans_info)" * in any scanner. */ indent_puts ("/* This struct is not used in this scanner,"); indent_puts (" but its presence is necessary. */"); indent_puts ("struct yy_trans_info"); indent_up (); indent_puts ("{"); indent_puts ("flex_int32_t yy_verify;"); indent_puts ("flex_int32_t yy_nxt;"); indent_puts ("};"); indent_down (); } if (fullspd) { genctbl (); if (tablesext) { struct yytbl_data *tbl; tbl = mkctbl (); yytbl_data_compress (tbl); if (yytbl_data_fwrite (&tableswr, tbl) < 0) flexerror (_("Could not write ftbl")); yytbl_data_destroy (tbl); tbl = mkssltbl (); yytbl_data_compress (tbl); if (yytbl_data_fwrite (&tableswr, tbl) < 0) flexerror (_("Could not write ssltbl")); yytbl_data_destroy (tbl); tbl = 0; if (useecs) { tbl = mkecstbl (); yytbl_data_compress (tbl); if (yytbl_data_fwrite (&tableswr, tbl) < 0) flexerror (_ ("Could not write ecstbl")); yytbl_data_destroy (tbl); tbl = 0; } } } else if (fulltbl) { genftbl (); if (tablesext) { struct yytbl_data *tbl; tbl = mkftbl (); yytbl_data_compress (tbl); if (yytbl_data_fwrite (&tableswr, tbl) < 0) flexerror (_("Could not write ftbl")); yytbl_data_destroy (tbl); tbl = 0; if (useecs) { tbl = mkecstbl (); yytbl_data_compress (tbl); if (yytbl_data_fwrite (&tableswr, tbl) < 0) flexerror (_ ("Could not write ecstbl")); yytbl_data_destroy (tbl); tbl = 0; } } } else gentabs (); if (do_yylineno) { geneoltbl (); if (tablesext) { struct yytbl_data *tbl; tbl = mkeoltbl (); yytbl_data_compress (tbl); if (yytbl_data_fwrite (&tableswr, tbl) < 0) flexerror (_("Could not write eoltbl")); yytbl_data_destroy (tbl); tbl = 0; } } /* Definitions for backing up. We don't need them if REJECT * is being used because then we use an alternative backin-up * technique instead. */ if (num_backing_up > 0 && !reject) { if (!C_plus_plus && !reentrant) { indent_puts ("static yy_state_type yy_last_accepting_state;"); indent_puts ("static char *yy_last_accepting_cpos;\n"); } } if (nultrans) { flex_int32_t *yynultrans_data = 0; /* Begin generating yy_NUL_trans */ out_str_dec (get_state_decl (), "yy_NUL_trans", lastdfa + 1); buf_prints (&yydmap_buf, "\t{YYTD_ID_NUL_TRANS, (void**)&yy_NUL_trans, sizeof(%s)},\n", (fullspd) ? "struct yy_trans_info*" : "flex_int32_t"); yynultrans_tbl = (struct yytbl_data *) calloc (1, sizeof (struct yytbl_data)); yytbl_data_init (yynultrans_tbl, YYTD_ID_NUL_TRANS); if (fullspd) yynultrans_tbl->td_flags |= YYTD_PTRANS; yynultrans_tbl->td_lolen = lastdfa + 1; yynultrans_tbl->td_data = yynultrans_data = (flex_int32_t *) calloc (yynultrans_tbl->td_lolen, sizeof (flex_int32_t)); for (i = 1; i <= lastdfa; ++i) { if (fullspd) { out_dec (" &yy_transition[%d],\n", base[i]); yynultrans_data[i] = base[i]; } else { mkdata (nultrans[i]); yynultrans_data[i] = nultrans[i]; } } dataend (); if (tablesext) { yytbl_data_compress (yynultrans_tbl); if (yytbl_data_fwrite (&tableswr, yynultrans_tbl) < 0) flexerror (_ ("Could not write yynultrans_tbl")); } if (yynultrans_tbl != NULL) { yytbl_data_destroy (yynultrans_tbl); yynultrans_tbl = NULL; } /* End generating yy_NUL_trans */ } if (!C_plus_plus && !reentrant) { indent_puts ("extern int yy_flex_debug;"); indent_put2s ("int yy_flex_debug = %s;\n", ddebug ? "1" : "0"); } if (ddebug) { /* Spit out table mapping rules to line numbers. */ out_str_dec (long_align ? get_int32_decl () : get_int16_decl (), "yy_rule_linenum", num_rules); for (i = 1; i < num_rules; ++i) mkdata (rule_linenum[i]); dataend (); } if (reject) { outn ("m4_ifdef( [[M4_YY_USES_REJECT]],\n[["); /* Declare state buffer variables. */ if (!C_plus_plus && !reentrant) { outn ("static yy_state_type *yy_state_buf=0, *yy_state_ptr=0;"); outn ("static char *yy_full_match;"); outn ("static int yy_lp;"); } if (variable_trailing_context_rules) { if (!C_plus_plus && !reentrant) { outn ("static int yy_looking_for_trail_begin = 0;"); outn ("static int yy_full_lp;"); outn ("static int *yy_full_state;"); } out_hex ("#define YY_TRAILING_MASK 0x%x\n", (unsigned int) YY_TRAILING_MASK); out_hex ("#define YY_TRAILING_HEAD_MASK 0x%x\n", (unsigned int) YY_TRAILING_HEAD_MASK); } outn ("#define REJECT \\"); outn ("{ \\"); outn ("*yy_cp = YY_G(yy_hold_char); /* undo effects of setting up yytext */ \\"); outn ("yy_cp = YY_G(yy_full_match); /* restore poss. backed-over text */ \\"); if (variable_trailing_context_rules) { outn ("YY_G(yy_lp) = YY_G(yy_full_lp); /* restore orig. accepting pos. */ \\"); outn ("YY_G(yy_state_ptr) = YY_G(yy_full_state); /* restore orig. state */ \\"); outn ("yy_current_state = *YY_G(yy_state_ptr); /* restore curr. state */ \\"); } outn ("++YY_G(yy_lp); \\"); outn ("goto find_rule; \\"); outn ("}"); outn ("]])\n"); } else { outn ("/* The intent behind this definition is that it'll catch"); outn (" * any uses of REJECT which flex missed."); outn (" */"); outn ("#define REJECT reject_used_but_not_detected"); } if (yymore_used) { if (!C_plus_plus) { if (yytext_is_array) { if (!reentrant){ indent_puts ("static int yy_more_offset = 0;"); indent_puts ("static int yy_prev_more_offset = 0;"); } } else if (!reentrant) { indent_puts ("static int yy_more_flag = 0;"); indent_puts ("static int yy_more_len = 0;"); } } if (yytext_is_array) { indent_puts ("#define yymore() (YY_G(yy_more_offset) = yy_flex_strlen( yytext M4_YY_CALL_LAST_ARG))"); indent_puts ("#define YY_NEED_STRLEN"); indent_puts ("#define YY_MORE_ADJ 0"); indent_puts ("#define YY_RESTORE_YY_MORE_OFFSET \\"); indent_up (); indent_puts ("{ \\"); indent_puts ("YY_G(yy_more_offset) = YY_G(yy_prev_more_offset); \\"); indent_puts ("yyleng -= YY_G(yy_more_offset); \\"); indent_puts ("}"); indent_down (); } else { indent_puts ("#define yymore() (YY_G(yy_more_flag) = 1)"); indent_puts ("#define YY_MORE_ADJ YY_G(yy_more_len)"); indent_puts ("#define YY_RESTORE_YY_MORE_OFFSET"); } } else { indent_puts ("#define yymore() yymore_used_but_not_detected"); indent_puts ("#define YY_MORE_ADJ 0"); indent_puts ("#define YY_RESTORE_YY_MORE_OFFSET"); } if (!C_plus_plus) { if (yytext_is_array) { outn ("#ifndef YYLMAX"); outn ("#define YYLMAX 8192"); outn ("#endif\n"); if (!reentrant){ outn ("char yytext[YYLMAX];"); outn ("char *yytext_ptr;"); } } else { if(! reentrant) outn ("char *yytext;"); } } out (&action_array[defs1_offset]); line_directive_out (stdout, 0); skelout (); /* %% [5.0] - break point in skel */ if (!C_plus_plus) { if (use_read) { outn ("\terrno=0; \\"); outn ("\twhile ( (result = read( fileno(yyin), (char *) buf, max_size )) < 0 ) \\"); outn ("\t{ \\"); outn ("\t\tif( errno != EINTR) \\"); outn ("\t\t{ \\"); outn ("\t\t\tYY_FATAL_ERROR( \"input in flex scanner failed\" ); \\"); outn ("\t\t\tbreak; \\"); outn ("\t\t} \\"); outn ("\t\terrno=0; \\"); outn ("\t\tclearerr(yyin); \\"); outn ("\t}\\"); } else { outn ("\tif ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \\"); outn ("\t\t{ \\"); outn ("\t\tint c = '*'; \\"); outn ("\t\tsize_t n; \\"); outn ("\t\tfor ( n = 0; n < max_size && \\"); outn ("\t\t\t (c = getc( yyin )) != EOF && c != '\\n'; ++n ) \\"); outn ("\t\t\tbuf[n] = (char) c; \\"); outn ("\t\tif ( c == '\\n' ) \\"); outn ("\t\t\tbuf[n++] = (char) c; \\"); outn ("\t\tif ( c == EOF && ferror( yyin ) ) \\"); outn ("\t\t\tYY_FATAL_ERROR( \"input in flex scanner failed\" ); \\"); outn ("\t\tresult = n; \\"); outn ("\t\t} \\"); outn ("\telse \\"); outn ("\t\t{ \\"); outn ("\t\terrno=0; \\"); outn ("\t\twhile ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \\"); outn ("\t\t\t{ \\"); outn ("\t\t\tif( errno != EINTR) \\"); outn ("\t\t\t\t{ \\"); outn ("\t\t\t\tYY_FATAL_ERROR( \"input in flex scanner failed\" ); \\"); outn ("\t\t\t\tbreak; \\"); outn ("\t\t\t\t} \\"); outn ("\t\t\terrno=0; \\"); outn ("\t\t\tclearerr(yyin); \\"); outn ("\t\t\t} \\"); outn ("\t\t}\\"); } } skelout (); /* %% [6.0] - break point in skel */ indent_puts ("#define YY_RULE_SETUP \\"); indent_up (); if (bol_needed) { indent_puts ("if ( yyleng > 0 ) \\"); indent_up (); indent_puts ("YY_CURRENT_BUFFER_LVALUE->yy_at_bol = \\"); indent_puts ("\t\t(yytext[yyleng - 1] == '\\n'); \\"); indent_down (); } indent_puts ("YY_USER_ACTION"); indent_down (); skelout (); /* %% [7.0] - break point in skel */ /* Copy prolog to output file. */ out (&action_array[prolog_offset]); line_directive_out (stdout, 0); skelout (); /* %% [8.0] - break point in skel */ set_indent (2); if (yymore_used && !yytext_is_array) { indent_puts ("YY_G(yy_more_len) = 0;"); indent_puts ("if ( YY_G(yy_more_flag) )"); indent_up (); indent_puts ("{"); indent_puts ("YY_G(yy_more_len) = YY_G(yy_c_buf_p) - YY_G(yytext_ptr);"); indent_puts ("YY_G(yy_more_flag) = 0;"); indent_puts ("}"); indent_down (); } skelout (); /* %% [9.0] - break point in skel */ gen_start_state (); /* Note, don't use any indentation. */ outn ("yy_match:"); gen_next_match (); skelout (); /* %% [10.0] - break point in skel */ set_indent (2); gen_find_action (); skelout (); /* %% [11.0] - break point in skel */ outn ("m4_ifdef( [[M4_YY_USE_LINENO]],[["); indent_puts ("if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] )"); indent_up (); indent_puts ("{"); indent_puts ("yy_size_t yyl;"); do_indent (); out_str ("for ( yyl = %s; yyl < yyleng; ++yyl )\n", yymore_used ? (yytext_is_array ? "YY_G(yy_prev_more_offset)" : "YY_G(yy_more_len)") : "0"); indent_up (); indent_puts ("if ( yytext[yyl] == '\\n' )"); indent_up (); indent_puts ("M4_YY_INCR_LINENO();"); indent_down (); indent_down (); indent_puts ("}"); indent_down (); outn ("]])"); skelout (); /* %% [12.0] - break point in skel */ if (ddebug) { indent_puts ("if ( yy_flex_debug )"); indent_up (); indent_puts ("{"); indent_puts ("if ( yy_act == 0 )"); indent_up (); indent_puts (C_plus_plus ? "std::cerr << \"--scanner backing up\\n\";" : "fprintf( stderr, \"--scanner backing up\\n\" );"); indent_down (); do_indent (); out_dec ("else if ( yy_act < %d )\n", num_rules); indent_up (); if (C_plus_plus) { indent_puts ("std::cerr << \"--accepting rule at line \" << yy_rule_linenum[yy_act] <<"); indent_puts (" \"(\\\"\" << yytext << \"\\\")\\n\";"); } else { indent_puts ("fprintf( stderr, \"--accepting rule at line %ld (\\\"%s\\\")\\n\","); indent_puts (" (long)yy_rule_linenum[yy_act], yytext );"); } indent_down (); do_indent (); out_dec ("else if ( yy_act == %d )\n", num_rules); indent_up (); if (C_plus_plus) { indent_puts ("std::cerr << \"--accepting default rule (\\\"\" << yytext << \"\\\")\\n\";"); } else { indent_puts ("fprintf( stderr, \"--accepting default rule (\\\"%s\\\")\\n\","); indent_puts (" yytext );"); } indent_down (); do_indent (); out_dec ("else if ( yy_act == %d )\n", num_rules + 1); indent_up (); indent_puts (C_plus_plus ? "std::cerr << \"--(end of buffer or a NUL)\\n\";" : "fprintf( stderr, \"--(end of buffer or a NUL)\\n\" );"); indent_down (); do_indent (); outn ("else"); indent_up (); if (C_plus_plus) { indent_puts ("std::cerr << \"--EOF (start condition \" << YY_START << \")\\n\";"); } else { indent_puts ("fprintf( stderr, \"--EOF (start condition %d)\\n\", YY_START );"); } indent_down (); indent_puts ("}"); indent_down (); } /* Copy actions to output file. */ skelout (); /* %% [13.0] - break point in skel */ indent_up (); gen_bu_action (); out (&action_array[action_offset]); line_directive_out (stdout, 0); /* generate cases for any missing EOF rules */ for (i = 1; i <= lastsc; ++i) if (!sceof[i]) { do_indent (); out_str ("case YY_STATE_EOF(%s):\n", scname[i]); did_eof_rule = true; } if (did_eof_rule) { indent_up (); indent_puts ("yyterminate();"); indent_down (); } /* Generate code for handling NUL's, if needed. */ /* First, deal with backing up and setting up yy_cp if the scanner * finds that it should JAM on the NUL. */ skelout (); /* %% [14.0] - break point in skel */ set_indent (4); if (fullspd || fulltbl) indent_puts ("yy_cp = YY_G(yy_c_buf_p);"); else { /* compressed table */ if (!reject && !interactive) { /* Do the guaranteed-needed backing up to figure * out the match. */ indent_puts ("yy_cp = YY_G(yy_last_accepting_cpos);"); indent_puts ("yy_current_state = YY_G(yy_last_accepting_state);"); } else /* Still need to initialize yy_cp, though * yy_current_state was set up by * yy_get_previous_state(). */ indent_puts ("yy_cp = YY_G(yy_c_buf_p);"); } /* Generate code for yy_get_previous_state(). */ set_indent (1); skelout (); /* %% [15.0] - break point in skel */ gen_start_state (); set_indent (2); skelout (); /* %% [16.0] - break point in skel */ gen_next_state (true); set_indent (1); skelout (); /* %% [17.0] - break point in skel */ gen_NUL_trans (); skelout (); /* %% [18.0] - break point in skel */ skelout (); /* %% [19.0] - break point in skel */ /* Update BOL and yylineno inside of input(). */ if (bol_needed) { indent_puts ("YY_CURRENT_BUFFER_LVALUE->yy_at_bol = (c == '\\n');"); if (do_yylineno) { indent_puts ("if ( YY_CURRENT_BUFFER_LVALUE->yy_at_bol )"); indent_up (); indent_puts ("M4_YY_INCR_LINENO();"); indent_down (); } } else if (do_yylineno) { indent_puts ("if ( c == '\\n' )"); indent_up (); indent_puts ("M4_YY_INCR_LINENO();"); indent_down (); } skelout (); /* Copy remainder of input to output. */ line_directive_out (stdout, 1); if (sectnum == 3) { OUT_BEGIN_CODE (); (void) flexscan (); /* copy remainder of input to output */ OUT_END_CODE (); } } flex-2.6.0/src/options.c0000644000175000017500000001712712620472752015374 0ustar srivastasrivasta/* flex - tool to generate fast lexical analyzers */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "options.h" /* Be sure to synchronize these options with those defined in "options.h", * the giant switch() statement in "main.c", and the %option processing in * "scan.l". */ /* The command-line options, passed to scanopt_init() */ optspec_t flexopts[] = { {"-7", OPT_7BIT, 0} , {"--7bit", OPT_7BIT, 0} , /* Generate 7-bit scanner. */ {"-8", OPT_8BIT, 0} , {"--8bit", OPT_8BIT, 0} , /* Generate 8-bit scanner. */ {"--align", OPT_ALIGN, 0} , /* Trade off larger tables for better memory alignment. */ {"--noalign", OPT_NO_ALIGN, 0} , {"--always-interactive", OPT_ALWAYS_INTERACTIVE, 0} , {"--array", OPT_ARRAY, 0} , {"-b", OPT_BACKUP, 0} , {"--backup", OPT_BACKUP, 0} , /* Generate backing-up information to lex.backup. */ {"-B", OPT_BATCH, 0} , {"--batch", OPT_BATCH, 0} , /* Generate batch scanner (opposite of -I). */ {"--bison-bridge", OPT_BISON_BRIDGE, 0} , /* Scanner to be called by a bison pure parser. */ {"--bison-locations", OPT_BISON_BRIDGE_LOCATIONS, 0} , /* Scanner to be called by a bison pure parser. */ {"-i", OPT_CASE_INSENSITIVE, 0} , {"--case-insensitive", OPT_CASE_INSENSITIVE, 0} , /* Generate case-insensitive scanner. */ {"-C[aefFmr]", OPT_COMPRESSION, "Specify degree of table compression (default is -Cem)"}, {"-+", OPT_CPLUSPLUS, 0} , {"--c++", OPT_CPLUSPLUS, 0} , /* Generate C++ scanner class. */ {"-d", OPT_DEBUG, 0} , {"--debug", OPT_DEBUG, 0} , /* Turn on debug mode in generated scanner. */ {"--nodebug", OPT_NO_DEBUG, 0} , {"-s", OPT_NO_DEFAULT, 0} , {"--nodefault", OPT_NO_DEFAULT, 0} , /* Suppress default rule to ECHO unmatched text. */ {"--default", OPT_DEFAULT, 0} , {"-c", OPT_DONOTHING, 0} , /* For POSIX lex compatibility. */ {"-n", OPT_DONOTHING, 0} , /* For POSIX lex compatibility. */ {"--ecs", OPT_ECS, 0} , /* Construct equivalence classes. */ {"--noecs", OPT_NO_ECS, 0} , {"-F", OPT_FAST, 0} , {"--fast", OPT_FAST, 0} , /* Same as -CFr. */ {"-f", OPT_FULL, 0} , {"--full", OPT_FULL, 0} , /* Same as -Cfr. */ {"--header-file[=FILE]", OPT_HEADER_FILE, 0} , {"-?", OPT_HELP, 0} , {"-h", OPT_HELP, 0} , {"--help", OPT_HELP, 0} , /* Produce this help message. */ {"--hex", OPT_HEX, 0} , /* Use hexadecimals in debug/trace outputs */ {"-I", OPT_INTERACTIVE, 0} , {"--interactive", OPT_INTERACTIVE, 0} , /* Generate interactive scanner (opposite of -B). */ {"-l", OPT_LEX_COMPAT, 0} , {"--lex-compat", OPT_LEX_COMPAT, 0} , /* Maximal compatibility with original lex. */ {"-X", OPT_POSIX_COMPAT, 0} , {"--posix-compat", OPT_POSIX_COMPAT, 0} , /* Maximal compatibility with POSIX lex. */ {"--preproc=NUM", OPT_PREPROC_LEVEL, 0} , {"-L", OPT_NO_LINE, 0} , /* Suppress #line directives in scanner. */ {"--noline", OPT_NO_LINE, 0} , /* Suppress #line directives in scanner. */ {"--main", OPT_MAIN, 0} , /* use built-in main() function. */ {"--nomain", OPT_NO_MAIN, 0} , {"--meta-ecs", OPT_META_ECS, 0} , /* Construct meta-equivalence classes. */ {"--nometa-ecs", OPT_NO_META_ECS, 0} , {"--never-interactive", OPT_NEVER_INTERACTIVE, 0} , {"-o FILE", OPT_OUTFILE, 0} , {"--outfile=FILE", OPT_OUTFILE, 0} , /* Write to FILE (default is lex.yy.c) */ {"-p", OPT_PERF_REPORT, 0} , {"--perf-report", OPT_PERF_REPORT, 0} , /* Generate performance report to stderr. */ {"--pointer", OPT_POINTER, 0} , {"-P PREFIX", OPT_PREFIX, 0} , {"--prefix=PREFIX", OPT_PREFIX, 0} , /* Use PREFIX (default is yy) */ {"-Dmacro", OPT_PREPROCDEFINE, 0} , /* Define a preprocessor symbol. */ {"--read", OPT_READ, 0} , /* Use read(2) instead of stdio. */ {"-R", OPT_REENTRANT, 0} , {"--reentrant", OPT_REENTRANT, 0} , /* Generate a reentrant C scanner. */ {"--noreentrant", OPT_NO_REENTRANT, 0} , {"--reject", OPT_REJECT, 0} , {"--noreject", OPT_NO_REJECT, 0} , {"-S FILE", OPT_SKEL, 0} , {"--skel=FILE", OPT_SKEL, 0} , /* Use skeleton from FILE */ {"--stack", OPT_STACK, 0} , {"--stdinit", OPT_STDINIT, 0} , {"--nostdinit", OPT_NO_STDINIT, 0} , {"-t", OPT_STDOUT, 0} , {"--stdout", OPT_STDOUT, 0} , /* Write generated scanner to stdout. */ {"-T", OPT_TRACE, 0} , {"--trace", OPT_TRACE, 0} , /* Flex should run in trace mode. */ {"--tables-file[=FILE]", OPT_TABLES_FILE, 0} , /* Save tables to FILE */ {"--tables-verify", OPT_TABLES_VERIFY, 0} , /* Tables integrity check */ {"--nounistd", OPT_NO_UNISTD_H, 0} , /* Do not include unistd.h */ {"-v", OPT_VERBOSE, 0} , {"--verbose", OPT_VERBOSE, 0} , /* Write summary of scanner statistics to stdout. */ {"-V", OPT_VERSION, 0} , {"--version", OPT_VERSION, 0} , /* Report flex version. */ {"--warn", OPT_WARN, 0} , {"-w", OPT_NO_WARN, 0} , {"--nowarn", OPT_NO_WARN, 0} , /* Suppress warning messages. */ {"--noansi-definitions", OPT_NO_ANSI_FUNC_DEFS, 0} , {"--noansi-prototypes", OPT_NO_ANSI_FUNC_PROTOS, 0} , {"--yyclass=NAME", OPT_YYCLASS, 0} , {"--yylineno", OPT_YYLINENO, 0} , {"--noyylineno", OPT_NO_YYLINENO, 0} , {"--yymore", OPT_YYMORE, 0} , {"--noyymore", OPT_NO_YYMORE, 0} , {"--noyywrap", OPT_NO_YYWRAP, 0} , {"--yywrap", OPT_YYWRAP, 0} , {"--nounput", OPT_NO_UNPUT, 0} , {"--noyy_push_state", OPT_NO_YY_PUSH_STATE, 0} , {"--noyy_pop_state", OPT_NO_YY_POP_STATE, 0} , {"--noyy_top_state", OPT_NO_YY_TOP_STATE, 0} , {"--noyy_scan_buffer", OPT_NO_YY_SCAN_BUFFER, 0} , {"--noyy_scan_bytes", OPT_NO_YY_SCAN_BYTES, 0} , {"--noyy_scan_string", OPT_NO_YY_SCAN_STRING, 0} , {"--noyyget_extra", OPT_NO_YYGET_EXTRA, 0} , {"--noyyset_extra", OPT_NO_YYSET_EXTRA, 0} , {"--noyyget_leng", OPT_NO_YYGET_LENG, 0} , {"--noyyget_text", OPT_NO_YYGET_TEXT, 0} , {"--noyyget_lineno", OPT_NO_YYGET_LINENO, 0} , {"--noyyset_lineno", OPT_NO_YYSET_LINENO, 0} , {"--noyyget_in", OPT_NO_YYGET_IN, 0} , {"--noyyset_in", OPT_NO_YYSET_IN, 0} , {"--noyyget_out", OPT_NO_YYGET_OUT, 0} , {"--noyyset_out", OPT_NO_YYSET_OUT, 0} , {"--noyyget_lval", OPT_NO_YYGET_LVAL, 0} , {"--noyyset_lval", OPT_NO_YYSET_LVAL, 0} , {"--noyyget_lloc", OPT_NO_YYGET_LLOC, 0} , {"--noyyset_lloc", OPT_NO_YYSET_LLOC, 0} , {0, 0, 0} /* required final NULL entry. */ }; /* vim:set tabstop=8 softtabstop=4 shiftwidth=4: */ flex-2.6.0/src/options.h0000644000175000017500000000625512620472752015401 0ustar srivastasrivasta/* flex - tool to generate fast lexical analyzers */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #ifndef OPTIONS_H #define OPTIONS_H #include "scanopt.h" extern optspec_t flexopts[]; enum flexopt_flag_t { /* Use positive integers only, since they are return codes for scanopt. * Order is not important. */ OPT_7BIT = 1, OPT_8BIT, OPT_ALIGN, OPT_ALWAYS_INTERACTIVE, OPT_ARRAY, OPT_BACKUP, OPT_BATCH, OPT_BISON_BRIDGE, OPT_BISON_BRIDGE_LOCATIONS, OPT_CASE_INSENSITIVE, OPT_COMPRESSION, OPT_CPLUSPLUS, OPT_DEBUG, OPT_DEFAULT, OPT_DONOTHING, OPT_ECS, OPT_FAST, OPT_FULL, OPT_HEADER_FILE, OPT_HELP, OPT_HEX, OPT_INTERACTIVE, OPT_LEX_COMPAT, OPT_POSIX_COMPAT, OPT_MAIN, OPT_META_ECS, OPT_NEVER_INTERACTIVE, OPT_NO_ALIGN, OPT_NO_ANSI_FUNC_DEFS, OPT_NO_ANSI_FUNC_PROTOS, OPT_NO_DEBUG, OPT_NO_DEFAULT, OPT_NO_ECS, OPT_NO_LINE, OPT_NO_MAIN, OPT_NO_META_ECS, OPT_NO_REENTRANT, OPT_NO_REJECT, OPT_NO_STDINIT, OPT_NO_UNPUT, OPT_NO_WARN, OPT_NO_YYGET_EXTRA, OPT_NO_YYGET_IN, OPT_NO_YYGET_LENG, OPT_NO_YYGET_LINENO, OPT_NO_YYGET_LLOC, OPT_NO_YYGET_LVAL, OPT_NO_YYGET_OUT, OPT_NO_YYGET_TEXT, OPT_NO_YYLINENO, OPT_NO_YYMORE, OPT_NO_YYSET_EXTRA, OPT_NO_YYSET_IN, OPT_NO_YYSET_LINENO, OPT_NO_YYSET_LLOC, OPT_NO_YYSET_LVAL, OPT_NO_YYSET_OUT, OPT_NO_YYWRAP, OPT_NO_YY_POP_STATE, OPT_NO_YY_PUSH_STATE, OPT_NO_YY_SCAN_BUFFER, OPT_NO_YY_SCAN_BYTES, OPT_NO_YY_SCAN_STRING, OPT_NO_YY_TOP_STATE, OPT_OUTFILE, OPT_PERF_REPORT, OPT_POINTER, OPT_PREFIX, OPT_PREPROCDEFINE, OPT_PREPROC_LEVEL, OPT_READ, OPT_REENTRANT, OPT_REJECT, OPT_SKEL, OPT_STACK, OPT_STDINIT, OPT_STDOUT, OPT_TABLES_FILE, OPT_TABLES_VERIFY, OPT_TRACE, OPT_NO_UNISTD_H, OPT_VERBOSE, OPT_VERSION, OPT_WARN, OPT_YYCLASS, OPT_YYLINENO, OPT_YYMORE, OPT_YYWRAP }; #endif /* vim:set tabstop=8 softtabstop=4 shiftwidth=4 textwidth=0: */ flex-2.6.0/src/Makefile.in0000644000175000017500000010022012622651641015563 0ustar srivastasrivasta# Makefile.in generated by automake 1.15 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2014 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ bin_PROGRAMS = flex$(EXEEXT) subdir = src ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/gettext.m4 \ $(top_srcdir)/m4/iconv.m4 $(top_srcdir)/m4/intlmacosx.m4 \ $(top_srcdir)/m4/lib-ld.m4 $(top_srcdir)/m4/lib-link.m4 \ $(top_srcdir)/m4/lib-prefix.m4 $(top_srcdir)/m4/libtool.m4 \ $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ $(top_srcdir)/m4/nls.m4 $(top_srcdir)/m4/po.m4 \ $(top_srcdir)/m4/progtest.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(include_HEADERS) \ $(noinst_HEADERS) $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" \ "$(DESTDIR)$(includedir)" LTLIBRARIES = $(lib_LTLIBRARIES) libfl_la_LIBADD = am_libfl_la_OBJECTS = libmain.lo libyywrap.lo libfl_la_OBJECTS = $(am_libfl_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libfl_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libfl_la_LDFLAGS) $(LDFLAGS) -o $@ libfl_pic_la_LIBADD = am_libfl_pic_la_OBJECTS = libmain.lo libyywrap.lo libfl_pic_la_OBJECTS = $(am_libfl_pic_la_OBJECTS) libfl_pic_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libfl_pic_la_LDFLAGS) $(LDFLAGS) -o $@ PROGRAMS = $(bin_PROGRAMS) am_flex_OBJECTS = ccl.$(OBJEXT) dfa.$(OBJEXT) ecs.$(OBJEXT) \ scanflags.$(OBJEXT) gen.$(OBJEXT) main.$(OBJEXT) \ misc.$(OBJEXT) nfa.$(OBJEXT) parse.$(OBJEXT) scan.$(OBJEXT) \ skel.$(OBJEXT) sym.$(OBJEXT) tblcmp.$(OBJEXT) yylex.$(OBJEXT) \ options.$(OBJEXT) scanopt.$(OBJEXT) buf.$(OBJEXT) \ tables.$(OBJEXT) tables_shared.$(OBJEXT) filter.$(OBJEXT) \ regex.$(OBJEXT) flex_OBJECTS = $(am_flex_OBJECTS) flex_LDADD = $(LDADD) flex_DEPENDENCIES = ../lib/libcompat.la AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ depcomp = $(SHELL) $(top_srcdir)/build-aux/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = LEXCOMPILE = $(LEX) $(AM_LFLAGS) $(LFLAGS) LTLEXCOMPILE = $(LIBTOOL) $(AM_V_lt) $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(LEX) $(AM_LFLAGS) $(LFLAGS) AM_V_LEX = $(am__v_LEX_@AM_V@) am__v_LEX_ = $(am__v_LEX_@AM_DEFAULT_V@) am__v_LEX_0 = @echo " LEX " $@; am__v_LEX_1 = YLWRAP = $(top_srcdir)/build-aux/ylwrap am__yacc_c2h = sed -e s/cc$$/hh/ -e s/cpp$$/hpp/ -e s/cxx$$/hxx/ \ -e s/c++$$/h++/ -e s/c$$/h/ YACCCOMPILE = $(YACC) $(AM_YFLAGS) $(YFLAGS) LTYACCCOMPILE = $(LIBTOOL) $(AM_V_lt) $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(YACC) $(AM_YFLAGS) $(YFLAGS) AM_V_YACC = $(am__v_YACC_@AM_V@) am__v_YACC_ = $(am__v_YACC_@AM_DEFAULT_V@) am__v_YACC_0 = @echo " YACC " $@; am__v_YACC_1 = SOURCES = $(libfl_la_SOURCES) $(libfl_pic_la_SOURCES) $(flex_SOURCES) DIST_SOURCES = $(libfl_la_SOURCES) $(libfl_pic_la_SOURCES) \ $(flex_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(include_HEADERS) $(noinst_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \ $(LISP)config.h.in # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/config.h.in \ $(top_srcdir)/build-aux/depcomp $(top_srcdir)/build-aux/ylwrap \ parse.c parse.h scan.c DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ ALLOCA = @ALLOCA@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BISON = @BISON@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ GMSGFMT = @GMSGFMT@ GMSGFMT_015 = @GMSGFMT_015@ GREP = @GREP@ HELP2MAN = @HELP2MAN@ INDENT = @INDENT@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ INTLLIBS = @INTLLIBS@ INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ LD = @LD@ LDFLAGS = @LDFLAGS@ LEX = @LEX@ LEXLIB = @LEXLIB@ LEX_OUTPUT_ROOT = @LEX_OUTPUT_ROOT@ LIBICONV = @LIBICONV@ LIBINTL = @LIBINTL@ LIBOBJS = @LIBOBJS@ LIBS = @LIBINTL@ @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBICONV = @LTLIBICONV@ LTLIBINTL = @LTLIBINTL@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ M4 = @M4@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ MSGFMT = @MSGFMT@ MSGFMT_015 = @MSGFMT_015@ MSGMERGE = @MSGMERGE@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ POSUB = @POSUB@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHARED_VERSION_INFO = @SHARED_VERSION_INFO@ SHELL = @SHELL@ STRIP = @STRIP@ USE_NLS = @USE_NLS@ VERSION = @VERSION@ XGETTEXT = @XGETTEXT@ XGETTEXT_015 = @XGETTEXT_015@ XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ YACC = @YACC@ YFLAGS = @YFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = $(datadir)/locale localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_YFLAGS = -d AM_CPPFLAGS = -DLOCALEDIR=\"$(localedir)\" -I$(top_srcdir)/intl m4 = @M4@ lib_LTLIBRARIES = \ libfl.la \ libfl_pic.la flex_SOURCES = \ ccl.c \ dfa.c \ ecs.c \ scanflags.c \ gen.c \ main.c \ misc.c \ nfa.c \ parse.y \ scan.l \ skel.c \ sym.c \ tblcmp.c \ yylex.c \ options.c \ scanopt.c \ buf.c \ tables.c \ tables_shared.c \ filter.c \ regex.c LDADD = ../lib/libcompat.la libfl_la_SOURCES = \ libmain.c \ libyywrap.c libfl_la_LDFLAGS = -version-info @SHARED_VERSION_INFO@ libfl_pic_la_SOURCES = \ libmain.c \ libyywrap.c libfl_pic_la_LDFLAGS = -version-info @SHARED_VERSION_INFO@ noinst_HEADERS = \ flexdef.h \ flexint.h \ version.h \ options.h \ scanopt.h \ tables.h \ tables_shared.h include_HEADERS = \ FlexLexer.h EXTRA_DIST = \ flex.skl \ mkskel.sh \ gettext.h BUILT_SOURCES = \ skel.c MAINTAINERCLEANFILES = skel.c # Run GNU indent on sources. Don't run this unless all the sources compile cleanly. # # Whole idea: # 1. Check for .indent.pro, otherwise indent will use unknown # settings, or worse, the GNU defaults.) # 2. Check that this is GNU indent. # 3. Make sure to process only the NON-generated .c and .h files. # 4. Run indent twice per file. The first time is a test. # Otherwise, indent overwrites your file even if it fails! indentfiles = \ buf.c \ ccl.c \ dfa.c \ ecs.c \ scanflags.c \ filter.c \ flexdef.h \ gen.c \ libmain.c \ libyywrap.c \ main.c \ misc.c \ nfa.c \ options.c \ options.h \ regex.c \ scanopt.c \ scanopt.h \ sym.c \ tables.c \ tables.h \ tables_shared.c \ tables_shared.h \ tblcmp.c all: $(BUILT_SOURCES) config.h $(MAKE) $(AM_MAKEFLAGS) all-am .SUFFIXES: .SUFFIXES: .c .l .lo .o .obj .y $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu src/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): config.h: stamp-h1 @test -f $@ || rm -f stamp-h1 @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status src/config.h $(srcdir)/config.h.in: $(am__configure_deps) ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libfl.la: $(libfl_la_OBJECTS) $(libfl_la_DEPENDENCIES) $(EXTRA_libfl_la_DEPENDENCIES) $(AM_V_CCLD)$(libfl_la_LINK) -rpath $(libdir) $(libfl_la_OBJECTS) $(libfl_la_LIBADD) $(LIBS) libfl_pic.la: $(libfl_pic_la_OBJECTS) $(libfl_pic_la_DEPENDENCIES) $(EXTRA_libfl_pic_la_DEPENDENCIES) $(AM_V_CCLD)$(libfl_pic_la_LINK) -rpath $(libdir) $(libfl_pic_la_OBJECTS) $(libfl_pic_la_LIBADD) $(LIBS) install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list installcheck-binPROGRAMS: $(bin_PROGRAMS) bad=0; pid=$$$$; list="$(bin_PROGRAMS)"; for p in $$list; do \ case ' $(AM_INSTALLCHECK_STD_OPTIONS_EXEMPT) ' in \ *" $$p "* | *" $(srcdir)/$$p "*) continue;; \ esac; \ f=`echo "$$p" | \ sed 's,^.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/'`; \ for opt in --help --version; do \ if "$(DESTDIR)$(bindir)/$$f" $$opt >c$${pid}_.out \ 2>c$${pid}_.err &2; bad=1; fi; \ done; \ done; rm -f c$${pid}_.???; exit $$bad parse.h: parse.c @if test ! -f $@; then rm -f parse.c; else :; fi @if test ! -f $@; then $(MAKE) $(AM_MAKEFLAGS) parse.c; else :; fi flex$(EXEEXT): $(flex_OBJECTS) $(flex_DEPENDENCIES) $(EXTRA_flex_DEPENDENCIES) @rm -f flex$(EXEEXT) $(AM_V_CCLD)$(LINK) $(flex_OBJECTS) $(flex_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buf.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ccl.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dfa.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ecs.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/filter.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/gen.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libmain.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/libyywrap.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/main.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/misc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/nfa.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/options.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parse.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/regex.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/scan.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/scanflags.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/scanopt.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/skel.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sym.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tables.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tables_shared.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tblcmp.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/yylex.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< .l.c: $(AM_V_LEX)$(am__skiplex) $(SHELL) $(YLWRAP) $< $(LEX_OUTPUT_ROOT).c $@ -- $(LEXCOMPILE) .y.c: $(AM_V_YACC)$(am__skipyacc) $(SHELL) $(YLWRAP) $< y.tab.c $@ y.tab.h `echo $@ | $(am__yacc_c2h)` y.output $*.output -- $(YACCCOMPILE) mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-includeHEADERS: $(include_HEADERS) @$(NORMAL_INSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(includedir)'"; \ $(MKDIR_P) "$(DESTDIR)$(includedir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ done uninstall-includeHEADERS: @$(NORMAL_UNINSTALL) @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) check-am all-am: Makefile $(LTLIBRARIES) $(PROGRAMS) $(HEADERS) config.h install-binPROGRAMS: install-libLTLIBRARIES installdirs: for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(includedir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -rm -f parse.c -rm -f parse.h -rm -f scan.c -test -z "$(BUILT_SOURCES)" || rm -f $(BUILT_SOURCES) -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-binPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-hdr distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-includeHEADERS install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-libLTLIBRARIES install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: installcheck-binPROGRAMS maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-includeHEADERS \ uninstall-libLTLIBRARIES .MAKE: all check install install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \ clean-binPROGRAMS clean-generic clean-libLTLIBRARIES \ clean-libtool cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-hdr \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-binPROGRAMS \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-includeHEADERS install-info install-info-am \ install-libLTLIBRARIES install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installcheck-binPROGRAMS installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-includeHEADERS \ uninstall-libLTLIBRARIES .PRECIOUS: Makefile skel.c: flex.skl mkskel.sh flexint.h tables_shared.h sed 's/m4_/m4postproc_/g; s/m4preproc_/m4_/g' $(srcdir)/flex.skl | $(m4) -P -DFLEX_MAJOR_VERSION=`echo $(VERSION)|cut -f 1 -d .` -DFLEX_MINOR_VERSION=`echo $(VERSION)|cut -f 2 -d .` -DFLEX_SUBMINOR_VERSION=`echo $(VERSION)|cut -f 3 -d .` | sed 's/m4postproc_/m4_/g' | $(SHELL) $(srcdir)/mkskel.sh >skel.c # Explicitly describe dependencies. # You can recreate this with `gcc -I. -MM *.c' buf.o: buf.c flexdef.h flexint.h ccl.o: ccl.c flexdef.h flexint.h dfa.o: dfa.c flexdef.h flexint.h tables.h tables_shared.h ecs.o: ecs.c flexdef.h flexint.h scanflags.o: scanflags.c flexdef.h flexint.h gen.o: gen.c flexdef.h flexint.h tables.h tables_shared.h libmain.o: libmain.c libyywrap.o: libyywrap.c main.o: main.c flexdef.h flexint.h version.h options.h scanopt.h \ tables.h tables_shared.h misc.o: misc.c flexdef.h flexint.h tables.h tables_shared.h nfa.o: nfa.c flexdef.h flexint.h options.o: options.c options.h scanopt.h flexdef.h flexint.h parse.o: parse.c flexdef.h flexint.h tables.h tables_shared.h scan.o: scan.c flexdef.h flexint.h parse.h scanopt.o: scanopt.c flexdef.h flexint.h scanopt.h skel.o: skel.c flexdef.h flexint.h sym.o: sym.c flexdef.h flexint.h tables.o: tables.c flexdef.h flexint.h tables.h tables_shared.h tables_shared.o: tables_shared.c flexdef.h flexint.h tables.h \ tables_shared.h tblcmp.o: tblcmp.c flexdef.h flexint.h yylex.o: yylex.c flexdef.h flexint.h parse.h filter.o: filter.c flexdef.h flexint.h indent: if [ -f .indent.pro ] ; then \ for f in $(indentfiles);\ do\ echo indenting $$f ;\ $(indent) < $$f >/dev/null && indent $$f || echo $$f FAILED to indent ;\ done \ fi # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: flex-2.6.0/src/filter.c0000644000175000017500000002643712620474534015172 0ustar srivastasrivasta/* filter - postprocessing of flex output through filters */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" static const char * check_4_gnu_m4 = "m4_dnl ifdef(`__gnu__', ," "`errprint(Flex requires GNU M4. Set the PATH or set the M4 environment variable to its path name.)" " m4exit(2)')\n"; /** global chain. */ struct filter *output_chain = NULL; /* Allocate and initialize an external filter. * @param chain the current chain or NULL for new chain * @param cmd the command to execute. * @param ... a NULL terminated list of (const char*) arguments to command, * not including argv[0]. * @return newest filter in chain */ struct filter *filter_create_ext (struct filter *chain, const char *cmd, ...) { struct filter *f; int max_args; const char *s; va_list ap; /* allocate and initialize new filter */ f = (struct filter *) flex_alloc (sizeof (struct filter)); if (!f) flexerror (_("flex_alloc failed (f) in filter_create_ext")); memset (f, 0, sizeof (*f)); f->filter_func = NULL; f->extra = NULL; f->next = NULL; f->argc = 0; if (chain != NULL) { /* append f to end of chain */ while (chain->next) chain = chain->next; chain->next = f; } /* allocate argv, and populate it with the argument list. */ max_args = 8; f->argv = (const char **) flex_alloc (sizeof (char *) * (max_args + 1)); if (!f->argv) flexerror (_("flex_alloc failed (f->argv) in filter_create_ext")); f->argv[f->argc++] = cmd; va_start (ap, cmd); while ((s = va_arg (ap, const char *)) != NULL) { if (f->argc >= max_args) { max_args += 8; f->argv = (const char **) flex_realloc (f->argv, sizeof (char *) * (max_args + 1)); } f->argv[f->argc++] = s; } f->argv[f->argc] = NULL; va_end (ap); return f; } /* Allocate and initialize an internal filter. * @param chain the current chain or NULL for new chain * @param filter_func The function that will perform the filtering. * filter_func should return 0 if successful, and -1 * if an error occurs -- or it can simply exit(). * @param extra optional user-defined data to pass to the filter. * @return newest filter in chain */ struct filter *filter_create_int (struct filter *chain, int (*filter_func) (struct filter *), void *extra) { struct filter *f; /* allocate and initialize new filter */ f = (struct filter *) flex_alloc (sizeof (struct filter)); if (!f) flexerror (_("flex_alloc failed in filter_create_int")); memset (f, 0, sizeof (*f)); f->next = NULL; f->argc = 0; f->argv = NULL; f->filter_func = filter_func; f->extra = extra; if (chain != NULL) { /* append f to end of chain */ while (chain->next) chain = chain->next; chain->next = f; } return f; } /** Fork and exec entire filter chain. * @param chain The head of the chain. * @return true on success. */ bool filter_apply_chain (struct filter * chain) { int pid, pipes[2]; /* Tricky recursion, since we want to begin the chain * at the END. Why? Because we need all the forked processes * to be children of the main flex process. */ if (chain) filter_apply_chain (chain->next); else return true; /* Now we are the right-most unprocessed link in the chain. */ fflush (stdout); fflush (stderr); if (pipe (pipes) == -1) flexerror (_("pipe failed")); if ((pid = fork ()) == -1) flexerror (_("fork failed")); if (pid == 0) { /* child */ /* We need stdin (the FILE* stdin) to connect to this new pipe. * There is no portable way to set stdin to a new file descriptor, * as stdin is not an lvalue on some systems (BSD). * So we dup the new pipe onto the stdin descriptor and use a no-op fseek * to sync the stream. This is a Hail Mary situation. It seems to work. */ close (pipes[1]); clearerr(stdin); if (dup2 (pipes[0], fileno (stdin)) == -1) flexfatal (_("dup2(pipes[0],0)")); close (pipes[0]); fseek (stdin, 0, SEEK_CUR); /* run as a filter, either internally or by exec */ if (chain->filter_func) { int r; if ((r = chain->filter_func (chain)) == -1) flexfatal (_("filter_func failed")); exit (0); } else { execvp (chain->argv[0], (char **const) (chain->argv)); lerr_fatal ( _("exec of %s failed"), chain->argv[0]); } exit (1); } /* Parent */ close (pipes[0]); if (dup2 (pipes[1], fileno (stdout)) == -1) flexfatal (_("dup2(pipes[1],1)")); close (pipes[1]); fseek (stdout, 0, SEEK_CUR); return true; } /** Truncate the chain to max_len number of filters. * @param chain the current chain. * @param max_len the maximum length of the chain. * @return the resulting length of the chain. */ int filter_truncate (struct filter *chain, int max_len) { int len = 1; if (!chain) return 0; while (chain->next && len < max_len) { chain = chain->next; ++len; } chain->next = NULL; return len; } /** Splits the chain in order to write to a header file. * Similar in spirit to the 'tee' program. * The header file name is in extra. * @return 0 (zero) on success, and -1 on failure. */ int filter_tee_header (struct filter *chain) { /* This function reads from stdin and writes to both the C file and the * header file at the same time. */ const int readsz = 512; char *buf; int to_cfd = -1; FILE *to_c = NULL, *to_h = NULL; bool write_header; write_header = (chain->extra != NULL); /* Store a copy of the stdout pipe, which is already piped to C file * through the running chain. Then create a new pipe to the H file as * stdout, and fork the rest of the chain again. */ if ((to_cfd = dup (1)) == -1) flexfatal (_("dup(1) failed")); to_c = fdopen (to_cfd, "w"); if (write_header) { if (freopen ((char *) chain->extra, "w", stdout) == NULL) flexfatal (_("freopen(headerfilename) failed")); filter_apply_chain (chain->next); to_h = stdout; } /* Now to_c is a pipe to the C branch, and to_h is a pipe to the H branch. */ if (write_header) { fputs (check_4_gnu_m4, to_h); fputs ("m4_changecom`'m4_dnl\n", to_h); fputs ("m4_changequote`'m4_dnl\n", to_h); fputs ("m4_changequote([[,]])[[]]m4_dnl\n", to_h); fputs ("m4_define([[M4_YY_NOOP]])[[]]m4_dnl\n", to_h); fputs ("m4_define( [[M4_YY_IN_HEADER]],[[]])m4_dnl\n", to_h); fprintf (to_h, "#ifndef %sHEADER_H\n", prefix); fprintf (to_h, "#define %sHEADER_H 1\n", prefix); fprintf (to_h, "#define %sIN_HEADER 1\n\n", prefix); fprintf (to_h, "m4_define( [[M4_YY_OUTFILE_NAME]],[[%s]])m4_dnl\n", headerfilename ? headerfilename : ""); } fputs (check_4_gnu_m4, to_c); fputs ("m4_changecom`'m4_dnl\n", to_c); fputs ("m4_changequote`'m4_dnl\n", to_c); fputs ("m4_changequote([[,]])[[]]m4_dnl\n", to_c); fputs ("m4_define([[M4_YY_NOOP]])[[]]m4_dnl\n", to_c); fprintf (to_c, "m4_define( [[M4_YY_OUTFILE_NAME]],[[%s]])m4_dnl\n", outfilename ? outfilename : ""); buf = (char *) flex_alloc (readsz); if (!buf) flexerror (_("flex_alloc failed in filter_tee_header")); while (fgets (buf, readsz, stdin)) { fputs (buf, to_c); if (write_header) fputs (buf, to_h); } if (write_header) { fprintf (to_h, "\n"); /* write a fake line number. It will get fixed by the linedir filter. */ fprintf (to_h, "#line 4000 \"M4_YY_OUTFILE_NAME\"\n"); fprintf (to_h, "#undef %sIN_HEADER\n", prefix); fprintf (to_h, "#endif /* %sHEADER_H */\n", prefix); fputs ("m4_undefine( [[M4_YY_IN_HEADER]])m4_dnl\n", to_h); fflush (to_h); if (ferror (to_h)) lerr (_("error writing output file %s"), (char *) chain->extra); else if (fclose (to_h)) lerr (_("error closing output file %s"), (char *) chain->extra); } fflush (to_c); if (ferror (to_c)) lerr (_("error writing output file %s"), outfilename ? outfilename : ""); else if (fclose (to_c)) lerr (_("error closing output file %s"), outfilename ? outfilename : ""); while (wait (0) > 0) ; exit (0); return 0; } /** Adjust the line numbers in the #line directives of the generated scanner. * After the m4 expansion, the line numbers are incorrect since the m4 macros * can add or remove lines. This only adjusts line numbers for generated code, * not user code. This also happens to be a good place to squeeze multiple * blank lines into a single blank line. */ int filter_fix_linedirs (struct filter *chain) { char *buf; const int readsz = 512; int lineno = 1; bool in_gen = true; /* in generated code */ bool last_was_blank = false; if (!chain) return 0; buf = (char *) flex_alloc (readsz); if (!buf) flexerror (_("flex_alloc failed in filter_fix_linedirs")); while (fgets (buf, readsz, stdin)) { regmatch_t m[10]; /* Check for #line directive. */ if (buf[0] == '#' && regexec (®ex_linedir, buf, 3, m, 0) == 0) { char *fname; /* extract the line number and filename */ fname = regmatch_dup (&m[2], buf); if (strcmp (fname, outfilename ? outfilename : "") == 0 || strcmp (fname, headerfilename ? headerfilename : "") == 0) { char *s1, *s2; char filename[MAXLINE]; s1 = fname; s2 = filename; while ((s2 - filename) < (MAXLINE - 1) && *s1) { /* Escape the backslash */ if (*s1 == '\\') *s2++ = '\\'; /* Escape the double quote */ if (*s1 == '\"') *s2++ = '\\'; /* Copy the character as usual */ *s2++ = *s1++; } *s2 = '\0'; /* Adjust the line directives. */ in_gen = true; snprintf (buf, readsz, "#line %d \"%s\"\n", lineno + 1, filename); } else { /* it's a #line directive for code we didn't write */ in_gen = false; } free (fname); last_was_blank = false; } /* squeeze blank lines from generated code */ else if (in_gen && regexec (®ex_blank_line, buf, 0, NULL, 0) == 0) { if (last_was_blank) continue; else last_was_blank = true; } else { /* it's a line of normal, non-empty code. */ last_was_blank = false; } fputs (buf, stdout); lineno++; } fflush (stdout); if (ferror (stdout)) lerr (_("error writing output file %s"), outfilename ? outfilename : ""); else if (fclose (stdout)) lerr (_("error closing output file %s"), outfilename ? outfilename : ""); return 0; } /* vim:set expandtab cindent tabstop=4 softtabstop=4 shiftwidth=4 textwidth=0: */ flex-2.6.0/src/tables.h0000644000175000017500000000554212620472752015156 0ustar srivastasrivasta/* tables.h - tables serialization code * * Copyright (c) 1990 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. * * This file is part of flex. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. */ #ifndef TABLES_H #define TABLES_H #ifdef __cplusplus /* *INDENT-OFF* */ extern "C" { /* *INDENT-ON* */ #endif /* Tables serialization API declarations. */ #include "tables_shared.h" struct yytbl_writer { FILE *out; flex_uint32_t total_written; /**< bytes written so far */ fpos_t th_ssize_pos; /**< position of th_ssize */ }; /* These are used by main.c, gen.c, etc. * tablesext - if true, create external tables * tablesfilename - filename for external tables * tablesname - name that goes in serialized data, e.g., "yytables" * tableswr - writer for external tables * tablesverify - true if tables-verify option specified * gentables - true if we should spit out the normal C tables */ extern bool tablesext, tablesverify,gentables; extern char *tablesfilename, *tablesname; extern struct yytbl_writer tableswr; int yytbl_writer_init (struct yytbl_writer *, FILE *); int yytbl_hdr_init (struct yytbl_hdr *th, const char *version_str, const char *name); int yytbl_data_init (struct yytbl_data *tbl, enum yytbl_id id); int yytbl_data_destroy (struct yytbl_data *td); int yytbl_hdr_fwrite (struct yytbl_writer *wr, const struct yytbl_hdr *th); int yytbl_data_fwrite (struct yytbl_writer *wr, struct yytbl_data *td); void yytbl_data_compress (struct yytbl_data *tbl); struct yytbl_data *mkftbl (void); #ifdef __cplusplus /* *INDENT-OFF* */ } /* *INDENT-ON* */ #endif #endif /* vim:set expandtab cindent tabstop=4 softtabstop=4 shiftwidth=4 textwidth=0: */ flex-2.6.0/src/FlexLexer.h0000644000175000017500000001535012620476666015610 0ustar srivastasrivasta// -*-C++-*- // FlexLexer.h -- define interfaces for lexical analyzer classes generated // by flex // Copyright (c) 1993 The Regents of the University of California. // All rights reserved. // // This code is derived from software contributed to Berkeley by // Kent Williams and Tom Epperly. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. 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. // This file defines FlexLexer, an abstract class which specifies the // external interface provided to flex C++ lexer objects, and yyFlexLexer, // which defines a particular lexer class. // // If you want to create multiple lexer classes, you use the -P flag // to rename each yyFlexLexer to some other xxFlexLexer. You then // include in your other sources once per lexer class: // // #undef yyFlexLexer // #define yyFlexLexer xxFlexLexer // #include // // #undef yyFlexLexer // #define yyFlexLexer zzFlexLexer // #include // ... #ifndef __FLEX_LEXER_H // Never included before - need to define base class. #define __FLEX_LEXER_H #include # ifndef FLEX_STD # define FLEX_STD std:: # endif extern "C++" { struct yy_buffer_state; typedef int yy_state_type; class FlexLexer { public: virtual ~FlexLexer() { } const char* YYText() const { return yytext; } int YYLeng() const { return yyleng; } virtual void yy_switch_to_buffer( struct yy_buffer_state* new_buffer ) = 0; virtual struct yy_buffer_state* yy_create_buffer( FLEX_STD istream* s, int size ) = 0; virtual struct yy_buffer_state* yy_create_buffer( FLEX_STD istream& s, int size ) = 0; virtual void yy_delete_buffer( struct yy_buffer_state* b ) = 0; virtual void yyrestart( FLEX_STD istream* s ) = 0; virtual void yyrestart( FLEX_STD istream& s ) = 0; virtual int yylex() = 0; // Call yylex with new input/output sources. int yylex( FLEX_STD istream& new_in, FLEX_STD ostream& new_out ) { switch_streams( new_in, new_out ); return yylex(); } int yylex( FLEX_STD istream* new_in, FLEX_STD ostream* new_out = 0) { switch_streams( new_in, new_out ); return yylex(); } // Switch to new input/output streams. A nil stream pointer // indicates "keep the current one". virtual void switch_streams( FLEX_STD istream* new_in, FLEX_STD ostream* new_out ) = 0; virtual void switch_streams( FLEX_STD istream& new_in, FLEX_STD ostream& new_out ) = 0; int lineno() const { return yylineno; } int debug() const { return yy_flex_debug; } void set_debug( int flag ) { yy_flex_debug = flag; } protected: char* yytext; int yyleng; int yylineno; // only maintained if you use %option yylineno int yy_flex_debug; // only has effect with -d or "%option debug" }; } #endif // FLEXLEXER_H #if defined(yyFlexLexer) || ! defined(yyFlexLexerOnce) // Either this is the first time through (yyFlexLexerOnce not defined), // or this is a repeated include to define a different flavor of // yyFlexLexer, as discussed in the flex manual. #define yyFlexLexerOnce extern "C++" { class yyFlexLexer : public FlexLexer { public: // arg_yyin and arg_yyout default to the cin and cout, but we // only make that assignment when initializing in yylex(). yyFlexLexer( FLEX_STD istream& arg_yyin, FLEX_STD ostream& arg_yyout ); yyFlexLexer( FLEX_STD istream* arg_yyin = 0, FLEX_STD ostream* arg_yyout = 0 ); private: void ctor_common(); public: virtual ~yyFlexLexer(); void yy_switch_to_buffer( struct yy_buffer_state* new_buffer ); struct yy_buffer_state* yy_create_buffer( FLEX_STD istream* s, int size ); struct yy_buffer_state* yy_create_buffer( FLEX_STD istream& s, int size ); void yy_delete_buffer( struct yy_buffer_state* b ); void yyrestart( FLEX_STD istream* s ); void yyrestart( FLEX_STD istream& s ); void yypush_buffer_state( struct yy_buffer_state* new_buffer ); void yypop_buffer_state(); virtual int yylex(); virtual void switch_streams( FLEX_STD istream& new_in, FLEX_STD ostream& new_out ); virtual void switch_streams( FLEX_STD istream* new_in = 0, FLEX_STD ostream* new_out = 0 ); virtual int yywrap(); protected: virtual int LexerInput( char* buf, int max_size ); virtual void LexerOutput( const char* buf, int size ); virtual void LexerError( const char* msg ); void yyunput( int c, char* buf_ptr ); int yyinput(); void yy_load_buffer_state(); void yy_init_buffer( struct yy_buffer_state* b, FLEX_STD istream& s ); void yy_flush_buffer( struct yy_buffer_state* b ); int yy_start_stack_ptr; int yy_start_stack_depth; int* yy_start_stack; void yy_push_state( int new_state ); void yy_pop_state(); int yy_top_state(); yy_state_type yy_get_previous_state(); yy_state_type yy_try_NUL_trans( yy_state_type current_state ); int yy_get_next_buffer(); FLEX_STD istream yyin; // input source for default LexerInput FLEX_STD ostream yyout; // output sink for default LexerOutput // yy_hold_char holds the character lost when yytext is formed. char yy_hold_char; // Number of characters read into yy_ch_buf. int yy_n_chars; // Points to current character in buffer. char* yy_c_buf_p; int yy_init; // whether we need to initialize int yy_start; // start state number // Flag which is used to allow yywrap()'s to do buffer switches // instead of setting up a fresh yyin. A bit of a hack ... int yy_did_buffer_switch_on_eof; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ struct yy_buffer_state ** yy_buffer_stack; /**< Stack as an array. */ void yyensure_buffer_stack(void); // The following are not always needed, but may be depending // on use of certain flex features (like REJECT or yymore()). yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; yy_state_type* yy_state_buf; yy_state_type* yy_state_ptr; char* yy_full_match; int* yy_full_state; int yy_full_lp; int yy_lp; int yy_looking_for_trail_begin; int yy_more_flag; int yy_more_len; int yy_more_offset; int yy_prev_more_offset; }; } #endif // yyFlexLexer || ! yyFlexLexerOnce flex-2.6.0/src/parse.h0000644000175000017500000001002512622651445015006 0ustar srivastasrivasta/* A Bison parser, made by GNU Bison 3.0.4. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ #ifndef YY_YY_PARSE_H_INCLUDED # define YY_YY_PARSE_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { CHAR = 258, NUMBER = 259, SECTEND = 260, SCDECL = 261, XSCDECL = 262, NAME = 263, PREVCCL = 264, EOF_OP = 265, OPTION_OP = 266, OPT_OUTFILE = 267, OPT_PREFIX = 268, OPT_YYCLASS = 269, OPT_HEADER = 270, OPT_EXTRA_TYPE = 271, OPT_TABLES = 272, CCE_ALNUM = 273, CCE_ALPHA = 274, CCE_BLANK = 275, CCE_CNTRL = 276, CCE_DIGIT = 277, CCE_GRAPH = 278, CCE_LOWER = 279, CCE_PRINT = 280, CCE_PUNCT = 281, CCE_SPACE = 282, CCE_UPPER = 283, CCE_XDIGIT = 284, CCE_NEG_ALNUM = 285, CCE_NEG_ALPHA = 286, CCE_NEG_BLANK = 287, CCE_NEG_CNTRL = 288, CCE_NEG_DIGIT = 289, CCE_NEG_GRAPH = 290, CCE_NEG_LOWER = 291, CCE_NEG_PRINT = 292, CCE_NEG_PUNCT = 293, CCE_NEG_SPACE = 294, CCE_NEG_UPPER = 295, CCE_NEG_XDIGIT = 296, CCL_OP_DIFF = 297, CCL_OP_UNION = 298, BEGIN_REPEAT_POSIX = 299, END_REPEAT_POSIX = 300, BEGIN_REPEAT_FLEX = 301, END_REPEAT_FLEX = 302 }; #endif /* Tokens. */ #define CHAR 258 #define NUMBER 259 #define SECTEND 260 #define SCDECL 261 #define XSCDECL 262 #define NAME 263 #define PREVCCL 264 #define EOF_OP 265 #define OPTION_OP 266 #define OPT_OUTFILE 267 #define OPT_PREFIX 268 #define OPT_YYCLASS 269 #define OPT_HEADER 270 #define OPT_EXTRA_TYPE 271 #define OPT_TABLES 272 #define CCE_ALNUM 273 #define CCE_ALPHA 274 #define CCE_BLANK 275 #define CCE_CNTRL 276 #define CCE_DIGIT 277 #define CCE_GRAPH 278 #define CCE_LOWER 279 #define CCE_PRINT 280 #define CCE_PUNCT 281 #define CCE_SPACE 282 #define CCE_UPPER 283 #define CCE_XDIGIT 284 #define CCE_NEG_ALNUM 285 #define CCE_NEG_ALPHA 286 #define CCE_NEG_BLANK 287 #define CCE_NEG_CNTRL 288 #define CCE_NEG_DIGIT 289 #define CCE_NEG_GRAPH 290 #define CCE_NEG_LOWER 291 #define CCE_NEG_PRINT 292 #define CCE_NEG_PUNCT 293 #define CCE_NEG_SPACE 294 #define CCE_NEG_UPPER 295 #define CCE_NEG_XDIGIT 296 #define CCL_OP_DIFF 297 #define CCL_OP_UNION 298 #define BEGIN_REPEAT_POSIX 299 #define END_REPEAT_POSIX 300 #define BEGIN_REPEAT_FLEX 301 #define END_REPEAT_FLEX 302 /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef int YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif extern YYSTYPE yylval; int yyparse (void); #endif /* !YY_YY_PARSE_H_INCLUDED */ flex-2.6.0/src/misc.c0000644000175000017500000005130412620474534014627 0ustar srivastasrivasta/* misc - miscellaneous flex routines */ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" #include "tables.h" #define CMD_IF_TABLES_SER "%if-tables-serialization" #define CMD_TABLES_YYDMAP "%tables-yydmap" #define CMD_DEFINE_YYTABLES "%define-yytables" #define CMD_IF_CPP_ONLY "%if-c++-only" #define CMD_IF_C_ONLY "%if-c-only" #define CMD_IF_C_OR_CPP "%if-c-or-c++" #define CMD_NOT_FOR_HEADER "%not-for-header" #define CMD_OK_FOR_HEADER "%ok-for-header" #define CMD_PUSH "%push" #define CMD_POP "%pop" #define CMD_IF_REENTRANT "%if-reentrant" #define CMD_IF_NOT_REENTRANT "%if-not-reentrant" #define CMD_IF_BISON_BRIDGE "%if-bison-bridge" #define CMD_IF_NOT_BISON_BRIDGE "%if-not-bison-bridge" #define CMD_ENDIF "%endif" /* we allow the skeleton to push and pop. */ struct sko_state { bool dc; /**< do_copy */ }; static struct sko_state *sko_stack=0; static int sko_len=0,sko_sz=0; static void sko_push(bool dc) { if(!sko_stack){ sko_sz = 1; sko_stack = (struct sko_state*)flex_alloc(sizeof(struct sko_state)*sko_sz); if (!sko_stack) flexfatal(_("allocation of sko_stack failed")); sko_len = 0; } if(sko_len >= sko_sz){ sko_sz *= 2; sko_stack = (struct sko_state*)flex_realloc(sko_stack,sizeof(struct sko_state)*sko_sz); } /* initialize to zero and push */ sko_stack[sko_len].dc = dc; sko_len++; } static void sko_peek(bool *dc) { if(sko_len <= 0) flex_die("peek attempt when sko stack is empty"); if(dc) *dc = sko_stack[sko_len-1].dc; } static void sko_pop(bool* dc) { sko_peek(dc); sko_len--; if(sko_len < 0) flex_die("popped too many times in skeleton."); } /* Append "#define defname value\n" to the running buffer. */ void action_define (defname, value) const char *defname; int value; { char buf[MAXLINE]; char *cpy; if ((int) strlen (defname) > MAXLINE / 2) { format_pinpoint_message (_ ("name \"%s\" ridiculously long"), defname); return; } snprintf (buf, sizeof(buf), "#define %s %d\n", defname, value); add_action (buf); /* track #defines so we can undef them when we're done. */ cpy = copy_string (defname); buf_append (&defs_buf, &cpy, 1); } #ifdef notdef /** Append "m4_define([[defname]],[[value]])m4_dnl\n" to the running buffer. * @param defname The macro name. * @param value The macro value, can be NULL, which is the same as the empty string. */ static void action_m4_define (const char *defname, const char * value) { char buf[MAXLINE]; flexfatal ("DO NOT USE THIS FUNCTION!"); if ((int) strlen (defname) > MAXLINE / 2) { format_pinpoint_message (_ ("name \"%s\" ridiculously long"), defname); return; } snprintf (buf, sizeof(buf), "m4_define([[%s]],[[%s]])m4_dnl\n", defname, value?value:""); add_action (buf); } #endif /* Append "new_text" to the running buffer. */ void add_action (new_text) const char *new_text; { int len = strlen (new_text); while (len + action_index >= action_size - 10 /* slop */ ) { int new_size = action_size * 2; if (new_size <= 0) /* Increase just a little, to try to avoid overflow * on 16-bit machines. */ action_size += action_size / 8; else action_size = new_size; action_array = reallocate_character_array (action_array, action_size); } strcpy (&action_array[action_index], new_text); action_index += len; } /* allocate_array - allocate memory for an integer array of the given size */ void *allocate_array (size, element_size) int size; size_t element_size; { void *mem; size_t num_bytes = element_size * size; mem = flex_alloc (num_bytes); if (!mem) flexfatal (_ ("memory allocation failed in allocate_array()")); return mem; } /* all_lower - true if a string is all lower-case */ int all_lower (str) char *str; { while (*str) { if (!isascii ((Char) * str) || !islower ((Char) * str)) return 0; ++str; } return 1; } /* all_upper - true if a string is all upper-case */ int all_upper (str) char *str; { while (*str) { if (!isascii ((Char) * str) || !isupper ((Char) * str)) return 0; ++str; } return 1; } /* intcmp - compares two integers for use by qsort. */ int intcmp (const void *a, const void *b) { return *(const int *) a - *(const int *) b; } /* check_char - checks a character to make sure it's within the range * we're expecting. If not, generates fatal error message * and exits. */ void check_char (c) int c; { if (c >= CSIZE) lerr (_("bad character '%s' detected in check_char()"), readable_form (c)); if (c >= csize) lerr (_ ("scanner requires -8 flag to use the character %s"), readable_form (c)); } /* clower - replace upper-case letter to lower-case */ Char clower (c) int c; { return (Char) ((isascii (c) && isupper (c)) ? tolower (c) : c); } /* copy_string - returns a dynamically allocated copy of a string */ char *copy_string (str) const char *str; { const char *c1; char *c2; char *copy; unsigned int size; /* find length */ for (c1 = str; *c1; ++c1) ; size = (c1 - str + 1) * sizeof (char); copy = (char *) flex_alloc (size); if (copy == NULL) flexfatal (_("dynamic memory failure in copy_string()")); for (c2 = copy; (*c2++ = *str++) != 0;) ; return copy; } /* copy_unsigned_string - * returns a dynamically allocated copy of a (potentially) unsigned string */ Char *copy_unsigned_string (str) Char *str; { Char *c; Char *copy; /* find length */ for (c = str; *c; ++c) ; copy = allocate_Character_array (c - str + 1); for (c = copy; (*c++ = *str++) != 0;) ; return copy; } /* cclcmp - compares two characters for use by qsort with '\0' sorting last. */ int cclcmp (const void *a, const void *b) { if (!*(const Char *) a) return 1; else if (!*(const Char *) b) return - 1; else return *(const Char *) a - *(const Char *) b; } /* dataend - finish up a block of data declarations */ void dataend () { /* short circuit any output */ if (gentables) { if (datapos > 0) dataflush (); /* add terminator for initialization; { for vi */ outn (" } ;\n"); } dataline = 0; datapos = 0; } /* dataflush - flush generated data statements */ void dataflush () { /* short circuit any output */ if (!gentables) return; outc ('\n'); if (++dataline >= NUMDATALINES) { /* Put out a blank line so that the table is grouped into * large blocks that enable the user to find elements easily. */ outc ('\n'); dataline = 0; } /* Reset the number of characters written on the current line. */ datapos = 0; } /* flexerror - report an error message and terminate */ void flexerror (msg) const char *msg; { fprintf (stderr, "%s: %s\n", program_name, msg); flexend (1); } /* flexfatal - report a fatal error message and terminate */ void flexfatal (msg) const char *msg; { fprintf (stderr, _("%s: fatal internal error, %s\n"), program_name, msg); FLEX_EXIT (1); } /* htoi - convert a hexadecimal digit string to an integer value */ int htoi (str) Char str[]; { unsigned int result; (void) sscanf ((char *) str, "%x", &result); return result; } /* lerr - report an error message */ void lerr (const char *msg, ...) { char errmsg[MAXLINE]; va_list args; va_start(args, msg); vsnprintf (errmsg, sizeof(errmsg), msg, args); va_end(args); flexerror (errmsg); } /* lerr_fatal - as lerr, but call flexfatal */ void lerr_fatal (const char *msg, ...) { char errmsg[MAXLINE]; va_list args; va_start(args, msg); vsnprintf (errmsg, sizeof(errmsg), msg, args); va_end(args); flexfatal (errmsg); } /* line_directive_out - spit out a "#line" statement */ void line_directive_out (output_file, do_infile) FILE *output_file; int do_infile; { char directive[MAXLINE], filename[MAXLINE]; char *s1, *s2, *s3; static const char *line_fmt = "#line %d \"%s\"\n"; if (!gen_line_dirs) return; s1 = do_infile ? infilename : "M4_YY_OUTFILE_NAME"; if (do_infile && !s1) s1 = ""; s2 = filename; s3 = &filename[sizeof (filename) - 2]; while (s2 < s3 && *s1) { if (*s1 == '\\') /* Escape the '\' */ *s2++ = '\\'; *s2++ = *s1++; } *s2 = '\0'; if (do_infile) snprintf (directive, sizeof(directive), line_fmt, linenum, filename); else { snprintf (directive, sizeof(directive), line_fmt, 0, filename); } /* If output_file is nil then we should put the directive in * the accumulated actions. */ if (output_file) { fputs (directive, output_file); } else add_action (directive); } /* mark_defs1 - mark the current position in the action array as * representing where the user's section 1 definitions end * and the prolog begins */ void mark_defs1 () { defs1_offset = 0; action_array[action_index++] = '\0'; action_offset = prolog_offset = action_index; action_array[action_index] = '\0'; } /* mark_prolog - mark the current position in the action array as * representing the end of the action prolog */ void mark_prolog () { action_array[action_index++] = '\0'; action_offset = action_index; action_array[action_index] = '\0'; } /* mk2data - generate a data statement for a two-dimensional array * * Generates a data statement initializing the current 2-D array to "value". */ void mk2data (value) int value; { /* short circuit any output */ if (!gentables) return; if (datapos >= NUMDATAITEMS) { outc (','); dataflush (); } if (datapos == 0) /* Indent. */ out (" "); else outc (','); ++datapos; out_dec ("%5d", value); } /* mkdata - generate a data statement * * Generates a data statement initializing the current array element to * "value". */ void mkdata (value) int value; { /* short circuit any output */ if (!gentables) return; if (datapos >= NUMDATAITEMS) { outc (','); dataflush (); } if (datapos == 0) /* Indent. */ out (" "); else outc (','); ++datapos; out_dec ("%5d", value); } /* myctoi - return the integer represented by a string of digits */ int myctoi (array) const char *array; { int val = 0; (void) sscanf (array, "%d", &val); return val; } /* myesc - return character corresponding to escape sequence */ Char myesc (array) Char array[]; { Char c, esc_char; switch (array[1]) { case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; #if defined (__STDC__) case 'a': return '\a'; case 'v': return '\v'; #else case 'a': return '\007'; case 'v': return '\013'; #endif case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { /* \ */ int sptr = 1; while (isascii (array[sptr]) && isdigit (array[sptr])) /* Don't increment inside loop control * because if isdigit() is a macro it might * expand into multiple increments ... */ ++sptr; c = array[sptr]; array[sptr] = '\0'; esc_char = otoi (array + 1); array[sptr] = c; return esc_char; } case 'x': { /* \x */ int sptr = 2; while (isascii (array[sptr]) && isxdigit (array[sptr])) /* Don't increment inside loop control * because if isdigit() is a macro it might * expand into multiple increments ... */ ++sptr; c = array[sptr]; array[sptr] = '\0'; esc_char = htoi (array + 2); array[sptr] = c; return esc_char; } default: return array[1]; } } /* otoi - convert an octal digit string to an integer value */ int otoi (str) Char str[]; { unsigned int result; (void) sscanf ((char *) str, "%o", &result); return result; } /* out - various flavors of outputing a (possibly formatted) string for the * generated scanner, keeping track of the line count. */ void out (str) const char *str; { fputs (str, stdout); } void out_dec (fmt, n) const char *fmt; int n; { fprintf (stdout, fmt, n); } void out_dec2 (fmt, n1, n2) const char *fmt; int n1, n2; { fprintf (stdout, fmt, n1, n2); } void out_hex (fmt, x) const char *fmt; unsigned int x; { fprintf (stdout, fmt, x); } void out_str (fmt, str) const char *fmt, str[]; { fprintf (stdout,fmt, str); } void out_str3 (fmt, s1, s2, s3) const char *fmt, s1[], s2[], s3[]; { fprintf (stdout,fmt, s1, s2, s3); } void out_str_dec (fmt, str, n) const char *fmt, str[]; int n; { fprintf (stdout,fmt, str, n); } void outc (c) int c; { fputc (c, stdout); } void outn (str) const char *str; { fputs (str,stdout); fputc('\n',stdout); } /** Print "m4_define( [[def]], [[val]])m4_dnl\n". * @param def The m4 symbol to define. * @param val The definition; may be NULL. */ void out_m4_define (const char* def, const char* val) { const char * fmt = "m4_define( [[%s]], [[%s]])m4_dnl\n"; fprintf(stdout, fmt, def, val?val:""); } /* readable_form - return the the human-readable form of a character * * The returned string is in static storage. */ char *readable_form (c) int c; { static char rform[20]; if ((c >= 0 && c < 32) || c >= 127) { switch (c) { case '\b': return "\\b"; case '\f': return "\\f"; case '\n': return "\\n"; case '\r': return "\\r"; case '\t': return "\\t"; #if defined (__STDC__) case '\a': return "\\a"; case '\v': return "\\v"; #endif default: if(trace_hex) snprintf (rform, sizeof(rform), "\\x%.2x", (unsigned int) c); else snprintf (rform, sizeof(rform), "\\%.3o", (unsigned int) c); return rform; } } else if (c == ' ') return "' '"; else { rform[0] = c; rform[1] = '\0'; return rform; } } /* reallocate_array - increase the size of a dynamic array */ void *reallocate_array (array, size, element_size) void *array; int size; size_t element_size; { void *new_array; size_t num_bytes = element_size * size; new_array = flex_realloc (array, num_bytes); if (!new_array) flexfatal (_("attempt to increase array size failed")); return new_array; } /* skelout - write out one section of the skeleton file * * Description * Copies skelfile or skel array to stdout until a line beginning with * "%%" or EOF is found. */ void skelout () { char buf_storage[MAXLINE]; char *buf = buf_storage; bool do_copy = true; /* "reset" the state by clearing the buffer and pushing a '1' */ if(sko_len > 0) sko_peek(&do_copy); sko_len = 0; sko_push(do_copy=true); /* Loop pulling lines either from the skelfile, if we're using * one, or from the skel[] array. */ while (skelfile ? (fgets (buf, MAXLINE, skelfile) != NULL) : ((buf = (char *) skel[skel_ind++]) != 0)) { if (skelfile) chomp (buf); /* copy from skel array */ if (buf[0] == '%') { /* control line */ /* print the control line as a comment. */ if (ddebug && buf[1] != '#') { if (buf[strlen (buf) - 1] == '\\') out_str ("/* %s */\\\n", buf); else out_str ("/* %s */\n", buf); } /* We've been accused of using cryptic markers in the skel. * So we'll use emacs-style-hyphenated-commands. * We might consider a hash if this if-else-if-else * chain gets too large. */ #define cmd_match(s) (strncmp(buf,(s),strlen(s))==0) if (buf[1] == '%') { /* %% is a break point for skelout() */ return; } else if (cmd_match (CMD_PUSH)){ sko_push(do_copy); if(ddebug){ out_str("/*(state = (%s) */",do_copy?"true":"false"); } out_str("%s\n", buf[strlen (buf) - 1] =='\\' ? "\\" : ""); } else if (cmd_match (CMD_POP)){ sko_pop(&do_copy); if(ddebug){ out_str("/*(state = (%s) */",do_copy?"true":"false"); } out_str("%s\n", buf[strlen (buf) - 1] =='\\' ? "\\" : ""); } else if (cmd_match (CMD_IF_REENTRANT)){ sko_push(do_copy); do_copy = reentrant && do_copy; } else if (cmd_match (CMD_IF_NOT_REENTRANT)){ sko_push(do_copy); do_copy = !reentrant && do_copy; } else if (cmd_match(CMD_IF_BISON_BRIDGE)){ sko_push(do_copy); do_copy = bison_bridge_lval && do_copy; } else if (cmd_match(CMD_IF_NOT_BISON_BRIDGE)){ sko_push(do_copy); do_copy = !bison_bridge_lval && do_copy; } else if (cmd_match (CMD_ENDIF)){ sko_pop(&do_copy); } else if (cmd_match (CMD_IF_TABLES_SER)) { do_copy = do_copy && tablesext; } else if (cmd_match (CMD_TABLES_YYDMAP)) { if (tablesext && yydmap_buf.elts) outn ((char *) (yydmap_buf.elts)); } else if (cmd_match (CMD_DEFINE_YYTABLES)) { out_str("#define YYTABLES_NAME \"%s\"\n", tablesname?tablesname:"yytables"); } else if (cmd_match (CMD_IF_CPP_ONLY)) { /* only for C++ */ sko_push(do_copy); do_copy = C_plus_plus; } else if (cmd_match (CMD_IF_C_ONLY)) { /* %- only for C */ sko_push(do_copy); do_copy = !C_plus_plus; } else if (cmd_match (CMD_IF_C_OR_CPP)) { /* %* for C and C++ */ sko_push(do_copy); do_copy = true; } else if (cmd_match (CMD_NOT_FOR_HEADER)) { /* %c begin linkage-only (non-header) code. */ OUT_BEGIN_CODE (); } else if (cmd_match (CMD_OK_FOR_HEADER)) { /* %e end linkage-only code. */ OUT_END_CODE (); } else if (buf[1] == '#') { /* %# a comment in the skel. ignore. */ } else { flexfatal (_("bad line in skeleton file")); } } else if (do_copy) outn (buf); } /* end while */ } /* transition_struct_out - output a yy_trans_info structure * * outputs the yy_trans_info structure with the two elements, element_v and * element_n. Formats the output with spaces and carriage returns. */ void transition_struct_out (element_v, element_n) int element_v, element_n; { /* short circuit any output */ if (!gentables) return; out_dec2 (" {%4d,%4d },", element_v, element_n); datapos += TRANS_STRUCT_PRINT_LENGTH; if (datapos >= 79 - TRANS_STRUCT_PRINT_LENGTH) { outc ('\n'); if (++dataline % 10 == 0) outc ('\n'); datapos = 0; } } /* The following is only needed when building flex's parser using certain * broken versions of bison. */ void *yy_flex_xmalloc (size) int size; { void *result = flex_alloc ((size_t) size); if (!result) flexfatal (_ ("memory allocation failed in yy_flex_xmalloc()")); return result; } /* zero_out - set a region of memory to 0 * * Sets region_ptr[0] through region_ptr[size_in_bytes - 1] to zero. */ void zero_out (region_ptr, size_in_bytes) char *region_ptr; size_t size_in_bytes; { char *rp, *rp_end; rp = region_ptr; rp_end = region_ptr + size_in_bytes; while (rp < rp_end) *rp++ = 0; } /* Remove all '\n' and '\r' characters, if any, from the end of str. * str can be any null-terminated string, or NULL. * returns str. */ char *chomp (str) char *str; { char *p = str; if (!str || !*str) /* s is null or empty string */ return str; /* find end of string minus one */ while (*p) ++p; --p; /* eat newlines */ while (p >= str && (*p == '\r' || *p == '\n')) *p-- = 0; return str; } flex-2.6.0/src/ecs.c0000644000175000017500000001301412620472752014442 0ustar srivastasrivasta/* ecs - equivalence class routines */ /* Copyright (c) 1990 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. */ /* This file is part of flex */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" /* ccl2ecl - convert character classes to set of equivalence classes */ void ccl2ecl () { int i, ich, newlen, cclp, ccls, cclmec; for (i = 1; i <= lastccl; ++i) { /* We loop through each character class, and for each character * in the class, add the character's equivalence class to the * new "character" class we are creating. Thus when we are all * done, character classes will really consist of collections * of equivalence classes */ newlen = 0; cclp = cclmap[i]; for (ccls = 0; ccls < ccllen[i]; ++ccls) { ich = ccltbl[cclp + ccls]; cclmec = ecgroup[ich]; if (cclmec > 0) { ccltbl[cclp + newlen] = cclmec; ++newlen; } } ccllen[i] = newlen; } } /* cre8ecs - associate equivalence class numbers with class members * * fwd is the forward linked-list of equivalence class members. bck * is the backward linked-list, and num is the number of class members. * * Returned is the number of classes. */ int cre8ecs (fwd, bck, num) int fwd[], bck[], num; { int i, j, numcl; numcl = 0; /* Create equivalence class numbers. From now on, ABS( bck(x) ) * is the equivalence class number for object x. If bck(x) * is positive, then x is the representative of its equivalence * class. */ for (i = 1; i <= num; ++i) if (bck[i] == NIL) { bck[i] = ++numcl; for (j = fwd[i]; j != NIL; j = fwd[j]) bck[j] = -numcl; } return numcl; } /* mkeccl - update equivalence classes based on character class xtions * * synopsis * Char ccls[]; * int lenccl, fwd[llsiz], bck[llsiz], llsiz, NUL_mapping; * void mkeccl( Char ccls[], int lenccl, int fwd[llsiz], int bck[llsiz], * int llsiz, int NUL_mapping ); * * ccls contains the elements of the character class, lenccl is the * number of elements in the ccl, fwd is the forward link-list of equivalent * characters, bck is the backward link-list, and llsiz size of the link-list. * * NUL_mapping is the value which NUL (0) should be mapped to. */ void mkeccl (ccls, lenccl, fwd, bck, llsiz, NUL_mapping) Char ccls[]; int lenccl, fwd[], bck[], llsiz, NUL_mapping; { int cclp, oldec, newec; int cclm, i, j; static unsigned char cclflags[CSIZE]; /* initialized to all '\0' */ /* Note that it doesn't matter whether or not the character class is * negated. The same results will be obtained in either case. */ cclp = 0; while (cclp < lenccl) { cclm = ccls[cclp]; if (NUL_mapping && cclm == 0) cclm = NUL_mapping; oldec = bck[cclm]; newec = cclm; j = cclp + 1; for (i = fwd[cclm]; i != NIL && i <= llsiz; i = fwd[i]) { /* look for the symbol in the character class */ for (; j < lenccl; ++j) { int ccl_char; if (NUL_mapping && ccls[j] == 0) ccl_char = NUL_mapping; else ccl_char = ccls[j]; if (ccl_char > i) break; if (ccl_char == i && !cclflags[j]) { /* We found an old companion of cclm * in the ccl. Link it into the new * equivalence class and flag it as * having been processed. */ bck[i] = newec; fwd[newec] = i; newec = i; /* Set flag so we don't reprocess. */ cclflags[j] = 1; /* Get next equivalence class member. */ /* continue 2 */ goto next_pt; } } /* Symbol isn't in character class. Put it in the old * equivalence class. */ bck[i] = oldec; if (oldec != NIL) fwd[oldec] = i; oldec = i; next_pt:; } if (bck[cclm] != NIL || oldec != bck[cclm]) { bck[cclm] = NIL; fwd[oldec] = NIL; } fwd[newec] = NIL; /* Find next ccl member to process. */ for (++cclp; cclp < lenccl && cclflags[cclp]; ++cclp) { /* Reset "doesn't need processing" flag. */ cclflags[cclp] = 0; } } } /* mkechar - create equivalence class for single character */ void mkechar (tch, fwd, bck) int tch, fwd[], bck[]; { /* If until now the character has been a proper subset of * an equivalence class, break it away to create a new ec */ if (fwd[tch] != NIL) bck[fwd[tch]] = bck[tch]; if (bck[tch] != NIL) fwd[bck[tch]] = fwd[tch]; fwd[tch] = NIL; bck[tch] = NIL; } flex-2.6.0/src/libmain.c0000644000175000017500000000226112620474534015305 0ustar srivastasrivasta/* libmain - flex run-time support library "main" function */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ extern int yylex (void); int main (int argc, char *argv[]) { (void)argc; (void)argv; while (yylex () != 0) ; return 0; } flex-2.6.0/src/Makefile.am0000644000175000017500000000646312621435345015570 0ustar srivastasrivastaAM_YFLAGS = -d localedir = $(datadir)/locale AM_CPPFLAGS = -DLOCALEDIR=\"$(localedir)\" -I$(top_srcdir)/intl LIBS = @LIBINTL@ @LIBS@ m4 = @M4@ bin_PROGRAMS = flex lib_LTLIBRARIES = \ libfl.la \ libfl_pic.la flex_SOURCES = \ ccl.c \ dfa.c \ ecs.c \ scanflags.c \ gen.c \ main.c \ misc.c \ nfa.c \ parse.y \ scan.l \ skel.c \ sym.c \ tblcmp.c \ yylex.c \ options.c \ scanopt.c \ buf.c \ tables.c \ tables_shared.c \ filter.c \ regex.c LDADD = ../lib/libcompat.la libfl_la_SOURCES = \ libmain.c \ libyywrap.c libfl_la_LDFLAGS = -version-info @SHARED_VERSION_INFO@ libfl_pic_la_SOURCES = \ libmain.c \ libyywrap.c libfl_pic_la_LDFLAGS = -version-info @SHARED_VERSION_INFO@ noinst_HEADERS = \ flexdef.h \ flexint.h \ version.h \ options.h \ scanopt.h \ tables.h \ tables_shared.h include_HEADERS = \ FlexLexer.h EXTRA_DIST = \ flex.skl \ mkskel.sh \ gettext.h BUILT_SOURCES = \ skel.c MAINTAINERCLEANFILES = skel.c skel.c: flex.skl mkskel.sh flexint.h tables_shared.h sed 's/m4_/m4postproc_/g; s/m4preproc_/m4_/g' $(srcdir)/flex.skl | $(m4) -P -DFLEX_MAJOR_VERSION=`echo $(VERSION)|cut -f 1 -d .` -DFLEX_MINOR_VERSION=`echo $(VERSION)|cut -f 2 -d .` -DFLEX_SUBMINOR_VERSION=`echo $(VERSION)|cut -f 3 -d .` | sed 's/m4postproc_/m4_/g' | $(SHELL) $(srcdir)/mkskel.sh >skel.c # Explicitly describe dependencies. # You can recreate this with `gcc -I. -MM *.c' buf.o: buf.c flexdef.h flexint.h ccl.o: ccl.c flexdef.h flexint.h dfa.o: dfa.c flexdef.h flexint.h tables.h tables_shared.h ecs.o: ecs.c flexdef.h flexint.h scanflags.o: scanflags.c flexdef.h flexint.h gen.o: gen.c flexdef.h flexint.h tables.h tables_shared.h libmain.o: libmain.c libyywrap.o: libyywrap.c main.o: main.c flexdef.h flexint.h version.h options.h scanopt.h \ tables.h tables_shared.h misc.o: misc.c flexdef.h flexint.h tables.h tables_shared.h nfa.o: nfa.c flexdef.h flexint.h options.o: options.c options.h scanopt.h flexdef.h flexint.h parse.o: parse.c flexdef.h flexint.h tables.h tables_shared.h scan.o: scan.c flexdef.h flexint.h parse.h scanopt.o: scanopt.c flexdef.h flexint.h scanopt.h skel.o: skel.c flexdef.h flexint.h sym.o: sym.c flexdef.h flexint.h tables.o: tables.c flexdef.h flexint.h tables.h tables_shared.h tables_shared.o: tables_shared.c flexdef.h flexint.h tables.h \ tables_shared.h tblcmp.o: tblcmp.c flexdef.h flexint.h yylex.o: yylex.c flexdef.h flexint.h parse.h filter.o: filter.c flexdef.h flexint.h # Run GNU indent on sources. Don't run this unless all the sources compile cleanly. # # Whole idea: # 1. Check for .indent.pro, otherwise indent will use unknown # settings, or worse, the GNU defaults.) # 2. Check that this is GNU indent. # 3. Make sure to process only the NON-generated .c and .h files. # 4. Run indent twice per file. The first time is a test. # Otherwise, indent overwrites your file even if it fails! indentfiles = \ buf.c \ ccl.c \ dfa.c \ ecs.c \ scanflags.c \ filter.c \ flexdef.h \ gen.c \ libmain.c \ libyywrap.c \ main.c \ misc.c \ nfa.c \ options.c \ options.h \ regex.c \ scanopt.c \ scanopt.h \ sym.c \ tables.c \ tables.h \ tables_shared.c \ tables_shared.h \ tblcmp.c indent: if [ -f .indent.pro ] ; then \ for f in $(indentfiles);\ do\ echo indenting $$f ;\ $(indent) < $$f >/dev/null && indent $$f || echo $$f FAILED to indent ;\ done \ fi flex-2.6.0/src/scan.l0000644000175000017500000006330312620475500014625 0ustar srivastasrivasta/* scan.l - scanner for flex input -*-C-*- */ %{ /* Copyright (c) 1990 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. */ /* This file is part of flex. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* 1. Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* 2. 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. */ #include "flexdef.h" #include "parse.h" extern bool tablesverify, tablesext; extern int trlcontxt; /* Set in parse.y for each rule. */ extern const char *escaped_qstart, *escaped_qend; #define ACTION_ECHO add_action( yytext ) #define ACTION_IFDEF(def, should_define) \ { \ if ( should_define ) \ action_define( def, 1 ); \ } #define ACTION_ECHO_QSTART add_action (escaped_qstart) #define ACTION_ECHO_QEND add_action (escaped_qend) #define ACTION_M4_IFDEF(def, should_define) \ do{ \ if ( should_define ) \ buf_m4_define( &m4defs_buf, def, NULL);\ else \ buf_m4_undefine( &m4defs_buf, def);\ } while(0) #define MARK_END_OF_PROLOG mark_prolog(); #define YY_DECL \ int flexscan() #define RETURNCHAR \ yylval = (unsigned char) yytext[0]; \ return CHAR; #define RETURNNAME \ if(yyleng < MAXLINE) \ { \ strcpy( nmstr, yytext ); \ } \ else \ { \ synerr(_("Input line too long\n")); \ FLEX_EXIT(EXIT_FAILURE); \ } \ return NAME; #define PUT_BACK_STRING(str, start) \ for ( i = strlen( str ) - 1; i >= start; --i ) \ unput((str)[i]) #define CHECK_REJECT(str) \ if ( all_upper( str ) ) \ reject = true; #define CHECK_YYMORE(str) \ if ( all_lower( str ) ) \ yymore_used = true; #define YY_USER_INIT \ if ( getenv("POSIXLY_CORRECT") ) \ posix_compat = true; %} %option caseless nodefault noreject stack noyy_top_state %option nostdinit %x SECT2 SECT2PROLOG SECT3 CODEBLOCK PICKUPDEF SC CARETISBOL NUM QUOTE %x FIRSTCCL CCL ACTION RECOVER COMMENT ACTION_STRING PERCENT_BRACE_ACTION %x OPTION LINEDIR CODEBLOCK_MATCH_BRACE %x GROUP_WITH_PARAMS %x GROUP_MINUS_PARAMS %x EXTENDED_COMMENT %x COMMENT_DISCARD WS [[:blank:]]+ OPTWS [[:blank:]]* NOT_WS [^[:blank:]\r\n] NL \r?\n NAME ([[:alpha:]_][[:alnum:]_-]*) NOT_NAME [^[:alpha:]_*\n]+ SCNAME {NAME} ESCSEQ (\\([^\n]|[0-7]{1,3}|x[[:xdigit:]]{1,2})) FIRST_CCL_CHAR ([^\\\n]|{ESCSEQ}) CCL_CHAR ([^\\\n\]]|{ESCSEQ}) CCL_EXPR ("[:"^?[[:alpha:]]+":]") LEXOPT [aceknopr] M4QSTART "[[" M4QEND "]]" %% static int bracelevel, didadef, indented_code; static int doing_rule_action = false; static int option_sense; int doing_codeblock = false; int i, brace_depth=0, brace_start_line=0; Char nmdef[MAXLINE]; { ^{WS} indented_code = true; BEGIN(CODEBLOCK); ^"/*" ACTION_ECHO; yy_push_state( COMMENT ); ^#{OPTWS}line{WS} yy_push_state( LINEDIR ); ^"%s"{NAME}? return SCDECL; ^"%x"{NAME}? return XSCDECL; ^"%{".*{NL} { ++linenum; line_directive_out( (FILE *) 0, 1 ); indented_code = false; BEGIN(CODEBLOCK); } ^"%top"[[:blank:]]*"{"[[:blank:]]*{NL} { brace_start_line = linenum; ++linenum; buf_linedir( &top_buf, infilename?infilename:"", linenum); brace_depth = 1; yy_push_state(CODEBLOCK_MATCH_BRACE); } ^"%top".* synerr( _("malformed '%top' directive") ); {WS} /* discard */ ^"%%".* { sectnum = 2; bracelevel = 0; mark_defs1(); line_directive_out( (FILE *) 0, 1 ); BEGIN(SECT2PROLOG); return SECTEND; } ^"%pointer".*{NL} yytext_is_array = false; ++linenum; ^"%array".*{NL} yytext_is_array = true; ++linenum; ^"%option" BEGIN(OPTION); return OPTION_OP; ^"%"{LEXOPT}{OPTWS}[[:digit:]]*{OPTWS}{NL} ++linenum; /* ignore */ ^"%"{LEXOPT}{WS}.*{NL} ++linenum; /* ignore */ /* xgettext: no-c-format */ ^"%"[^sxaceknopr{}].* synerr( _( "unrecognized '%' directive" ) ); ^{NAME} { if(yyleng < MAXLINE) { strcpy( nmstr, yytext ); } else { synerr( _("Definition name too long\n")); FLEX_EXIT(EXIT_FAILURE); } didadef = false; BEGIN(PICKUPDEF); } {SCNAME} RETURNNAME; ^{OPTWS}{NL} ++linenum; /* allows blank lines in section 1 */ {OPTWS}{NL} ACTION_ECHO; ++linenum; /* maybe end of comment line */ } { "*/" ACTION_ECHO; yy_pop_state(); "*" ACTION_ECHO; {M4QSTART} ACTION_ECHO_QSTART; {M4QEND} ACTION_ECHO_QEND; [^*\n] ACTION_ECHO; {NL} ++linenum; ACTION_ECHO; } { /* This is the same as COMMENT, but is discarded rather than output. */ "*/" yy_pop_state(); "*" ; [^*\n] ; {NL} ++linenum; } { ")" yy_pop_state(); [^\n\)]+ ; {NL} ++linenum; } { \n yy_pop_state(); [[:digit:]]+ linenum = myctoi( yytext ); \"[^"\n]*\" { flex_free( (void *) infilename ); infilename = copy_string( yytext + 1 ); infilename[strlen( infilename ) - 1] = '\0'; } . /* ignore spurious characters */ } { ^"%}".*{NL} ++linenum; BEGIN(INITIAL); {M4QSTART} ACTION_ECHO_QSTART; {M4QEND} ACTION_ECHO_QEND; . ACTION_ECHO; {NL} { ++linenum; ACTION_ECHO; if ( indented_code ) BEGIN(INITIAL); } } { "}" { if( --brace_depth == 0){ /* TODO: Matched. */ yy_pop_state(); }else buf_strnappend(&top_buf, yytext, yyleng); } "{" { brace_depth++; buf_strnappend(&top_buf, yytext, yyleng); } {NL} { ++linenum; buf_strnappend(&top_buf, yytext, yyleng); } {M4QSTART} buf_strnappend(&top_buf, escaped_qstart, strlen(escaped_qstart)); {M4QEND} buf_strnappend(&top_buf, escaped_qend, strlen(escaped_qend)); [^{}\r\n] { buf_strnappend(&top_buf, yytext, yyleng); } <> { linenum = brace_start_line; synerr(_("Unmatched '{'")); yyterminate(); } } { {WS} /* separates name and definition */ {NOT_WS}[^\r\n]* { if(yyleng < MAXLINE) { strcpy( (char *) nmdef, yytext ); } else { format_synerr( _("Definition value for {%s} too long\n"), nmstr); FLEX_EXIT(EXIT_FAILURE); } /* Skip trailing whitespace. */ for ( i = strlen( (char *) nmdef ) - 1; i >= 0 && (nmdef[i] == ' ' || nmdef[i] == '\t'); --i ) ; nmdef[i + 1] = '\0'; ndinstal( nmstr, nmdef ); didadef = true; } {NL} { if ( ! didadef ) synerr( _( "incomplete name definition" ) ); BEGIN(INITIAL); ++linenum; } }