LEX(1P)
๐ธ LEX(1P) โ the lex manual, but make it cute ๐ธ
okay bestie, listen UP ๐ this is lex, from the POSIX Programmer's Manual, section 1P. It generates programs for lexical tasks, and it's in the DEVELOPMENT category, so it's giving "build tool main character energy" the whole way through. ๐
โจ PROLOG โจ
real talk first: this manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ โ so if you're on Linux, go consult the corresponding Linux manual page for the deets on Linux behavior. Or the interface may not be implemented on Linux at all. ๐ญ Both are possible, and that's just how it is.
๐ NAME ๐
lex โ generate programs for lexical tasks (DEVELOPMENT) ๐
๐ฆ SYNOPSIS ๐ฆ
lex [-t] [-n|-v] [file...]
That's it. That's the whole vibe. โญ
๐ DESCRIPTION ๐
So here's the tea, bestie. The lex utility shall generate C programs to be used in lexical processing of character input, and those programs can be used as an interface to yacc. Slay. ๐ฅ
The C programs shall be generated from lex source code and shall conform to the ISO C standard, without depending on any undefined, unspecified, or implementation-defined behavior โ except in cases where the code is copied directly from the supplied source, or in cases that are documented by the implementation. (iykyk, sometimes you gotta hand over the raw stuff as-is. ๐)
Usually, the lex utility shall write the program it generates to the file lex.yy.c. Heads up though: the state of this file is unspecified if lex exits with a non-zero exit status. So if it flops, don't come for lex.yy.c's contents. ๐
For the complete description of the lex input language, go read the EXTENDED DESCRIPTION section. It's right down there. โฌ๏ธ
๐ OPTIONS ๐
The lex utility shall conform to the Base Definitions volume of POSIX.1โ2017, Section 12.2, Utility Syntax Guidelines โ except for Guideline 9. Yes, one single guideline is being skipped and I need you to know that. ๐
The following options shall be supported:
-nโ Suppress the summary of statistics usually written with the-voption. And check this: if no table sizes are specified in thelexsource code and the-voption is not specified, then-nis implied. It just happens. Automatically. Periodt. โจ-tโ Write the resulting program to standard output instead oflex.yy.c. ๐ซถ-vโ Write a summary oflexstatistics to the standard output. (See the discussion oflextable sizes in Definitions in lex.) Now here's the fine print: if the-toption is specified and-nis not specified, this report shall be written to standard error. And if table sizes are specified in thelexsource code, and if the-noption is not specified, the-voption may be enabled. ๐ธ
๐ OPERANDS ๐
The following operand shall be supported:
fileโ A pathname of an input file. If more than one such file is specified, all files shall be concatenated to produce a singlelexprogram. (They're a unit, bestie. ๐) If nofileoperands are specified, or if afileoperand is'-', the standard input shall be used.
๐ง STDIN ๐ง
The standard input shall be used if no file operands are specified, or if a file operand is '-'. See INPUT FILES. โฌ๏ธ
โญ INPUT FILES โญ
The input files shall be text files containing lex source code, as described in the EXTENDED DESCRIPTION section. ๐
๐ ENVIRONMENT VARIABLES ๐
The following environment variables shall affect the execution of lex:
LANGโ Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.1โ2017, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)LC_ALLโ If set to a non-empty string value, override the values of all the other internationalization variables. She's the boss. ๐LC_COLLATEโ Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions. Careful: if this variable is not set to the POSIX locale, the results are unspecified. ๐ญLC_CTYPEโ Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files), and the behavior of character classes within regular expressions. Again: if this variable is not set to the POSIX locale, the results are unspecified. ๐LC_MESSAGESโ Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.NLSPATHโ Determine the location of message catalogs for the processing ofLC_MESSAGES.
๐ธ ASYNCHRONOUS EVENTS ๐ธ
Default. That's the whole section. Nothing to see here, she's unbothered. ๐
โจ STDOUT โจ
If the -t option is specified, the text file of C source code output of lex shall be written to standard output. ๐ซถ
If the -t option is not specified:
- Implementation-defined informational, error, and warning messages concerning the contents of
lexsource code input shall be written to either the standard output or standard error. (Yeah, either. Implementation-defined. It's a vibe. ๐) - If the
-voption is specified and the-noption is not specified,lexstatistics shall also be written to either the standard output or standard error, in an implementation-defined format. These statistics may also be generated if table sizes are specified with a'%'operator in the Definitions section, as long as the-noption is not specified.
๐ญ STDERR ๐ญ
If the -t option is specified, implementation-defined informational, error, and warning messages concerning the contents of lex source code input shall be written to the standard error.
If the -t option is not specified:
- Implementation-defined informational, error, and warning messages concerning the contents of
lexsource code input shall be written to either the standard output or standard error. - If the
-voption is specified and the-noption is not specified,lexstatistics shall also be written to either the standard output or standard error, in an implementation-defined format. These statistics may also be generated if table sizes are specified with a'%'operator in the Definitions section, as long as the-noption is not specified.
๐ OUTPUT FILES ๐
A text file containing C source code shall be written to lex.yy.c, or to the standard output if the -t option is present. โจ
๐ฅ EXTENDED DESCRIPTION ๐ฅ
okay this is the big one, get comfy ๐ฆ
Each input file shall contain lex source code, which is a table of regular expressions with corresponding actions in the form of C program fragments. ๐
When lex.yy.c is compiled and linked with the lex library (using the -l l operand with c99), the resulting program shall read character input from the standard input and shall partition it into strings that match the given expressions. ๐
When an expression is matched, these actions shall occur:
- The input string that was matched shall be left in
yytextas a null-terminated string;yytextshall either be an external character array or a pointer to a character string. As explained in Definitions in lex, the type can be explicitly selected using the%arrayor%pointerdeclarations, but the default is implementation-defined. ๐ - The external
int yylengshall be set to the length of the matching string. - The expression's corresponding program fragment, or action, shall be executed. ๐ฅ
During pattern matching, lex shall search the set of patterns for the single longest possible match. And among rules that match the same number of characters, the rule given first shall be chosen. (Longest wins, ties go to the earliest. That's the rule, bestie. ๐)
The general format of lex source shall be:
Definitions %% Rules %% UserSubroutines
The first "%%" is required to mark the beginning of the rules (regular expressions and actions); the second "%%" is required only if user subroutines follow.
Any line in the Definitions section beginning with a <blank> shall be assumed to be a C program fragment and shall be copied to the external definition area of the lex.yy.c file. Similarly, anything in the Definitions section included between delimiter lines containing only "%{" and "%}" shall also be copied unchanged to the external definition area of the lex.yy.c file. ๐
Any such input (beginning with a <blank> or within "%{" and "%}" delimiter lines) appearing at the beginning of the Rules section before any rules are specified shall be written to lex.yy.c after the declarations of variables for the yylex() function and before the first line of code in yylex(). So user variables local to yylex() can be declared here, as well as application code to execute upon entry to yylex(). ๐ฏ
DANGER ZONE: The action taken bylexwhen encountering any input beginning with a<blank>or within"%{"and"%}"delimiter lines appearing in the Rules section but coming after one or more rules is undefined. ๐ฑ The presence of such input may result in an erroneous definition of theyylex()function. Do not do this. I'm serious. ๐
C-language code in the input shall not contain C-language trigraphs. And the C-language code within "%{" and "%}" delimiter lines shall not contain any lines consisting only of "%}", or only of "%%". ๐ซ
๐ Definitions in lex ๐
Definitions appear before the first "%%" delimiter. Any line in this section not contained between "%{" and "%}" lines and not beginning with a <blank> shall be assumed to define a lex substitution string. The format of these lines shall be:
name substitute
If a name does not meet the requirements for identifiers in the ISO C standard, the result is undefined. ๐ The string substitute shall replace the string {name} when it is used in a rule. The name string shall be recognized in this context only when the braces are provided and when it does not appear within a bracket expression or within double-quotes.
In the Definitions section, any line beginning with a <percent-sign> ('%') character and followed by an alphanumeric word beginning with either 's' or 'S' shall define a set of start conditions. Any line beginning with a '%' followed by a word beginning with either 'x' or 'X' shall define a set of exclusive start conditions. โจ
Here's how those two act, and it matters:
- When the generated scanner is in a
%sstate, patterns with no state specified shall also be active. - In a
%xstate, such patterns shall not be active.
The rest of the line, after the first word, shall be considered to be one or more <blank>-separated names of start conditions. Start condition names shall be constructed in the same way as definition names. Start conditions can be used to restrict the matching of regular expressions to one or more states as described in Regular Expressions in lex. ๐
Implementations shall accept either of the following two mutually-exclusive declarations in the Definitions section:
%arrayโ Declare the type ofyytextto be a null-terminated character array.%pointerโ Declare the type ofyytextto be a pointer to a null-terminated character string.
The default type of yytext is implementation-defined. ๐ If an application refers to yytext outside of the scanner source file (that is, via an extern), the application shall include the appropriate %array or %pointer declaration in the scanner source file. No skipping this, bestie. ๐
Implementations shall accept declarations in the Definitions section for setting certain internal table sizes. The declarations are shown in the following table. ๐
๐ The Table Size Declarations Table (yes bestie, it's a whole vibe) ๐
%p nโ Number of positions โ minimum value 2500%n nโ Number of states โ minimum value 500%a nโ Number of transitions โ minimum value 2000%e nโ Number of parse tree nodes โ minimum value 1000%k nโ Number of packed character classes โ minimum value 1000%o nโ Size of the output array โ minimum value 3000
So in that table, n is a positive decimal integer, and it has to be preceded by one or more <blank> characters. No cap. โจ
The exact meaning of these table size numbers is implementation-defined. The implementation shall document how these numbers affect the lex utility and how they are related to any output that may be generated by the implementation should limitations be encountered during the execution of lex. And it shall be possible to determine from this output which of the table size values needs to be modified to permit lex to successfully generate tables for the input language. The values in the column Minimum Value represent the lowest values conforming implementations shall provide. So like, those numbers are the floor, not the ceiling, iykyk ๐
๐ Rules in lex ๐
The rules in lex source files are a table where the left column has regular expressions and the right column has actions (C program fragments) that get executed when the expressions are recognized. It's giving very much:
ERE action
ERE action
...
The extended regular expression (ERE) portion of a row shall be separated from action by one or more <blank> characters. And a regular expression containing <blank> characters shall be recognized under one of these conditions:
- The entire expression appears within double-quotes.
- The
<blank>characters appear within double-quotes or square brackets. - Each
<blank>is preceded by a<backslash>character.
๐ฆ User Subroutines in lex ๐ฆ
Anything in the user subroutines section shall be copied to lex.yy.c following yylex(). Simple as that, bestie. Copy-paste behavior, iconic. ๐
โจ Regular Expressions in lex โจ
The lex utility shall support the set of extended regular expressions (see the Base Definitions volume of POSIX.1โ2017, Section 9.4, Extended Regular Expressions), with the following additions and exceptions to the syntax:
"..."โ Any string enclosed in double-quotes shall represent the characters within the double-quotes as themselves, except that<backslash>-escapes (which appear in the following table) shall be recognized. Any<backslash>-escape sequence shall be terminated by the closing quote. For example,"\01""1"represents a single string: the octal value 1 followed by the character'1'.<state>r,<state1,state2,...>rโ The regular expression r shall be matched only when the program is in one of the start conditions indicated by state, state1, and so on; see Actions in lex. (As an exception to the typographical conventions of the rest of this volume of POSIX.1โ2017, in this case<state>does not represent a metavariable, but the literal angle-bracket characters surrounding a symbol.) The start condition shall be recognized as such only at the beginning of a regular expression.r/xโ The regular expression r shall be matched only if it is followed by an occurrence of regular expression x (x is the instance of trailing context, further defined below). The token returned inyytextshall only match r. If the trailing portion of r matches the beginning of x, the result is unspecified. The r expression cannot include further trailing context or the'$'(match-end-of-line) operator; x cannot include the'^'(match-beginning-of-line) operator, nor trailing context, nor the'$'operator. That is, only one occurrence of trailing context is allowed in alexregular expression, and the'^'operator only can be used at the beginning of such an expression.{name}โ When name is one of the substitution symbols from the Definitions section, the string, including the enclosing braces, shall be replaced by the substitute value. The substitute value shall be treated in the extended regular expression as if it were enclosed in parentheses. No substitution shall occur if{name}occurs within a bracket expression or within double-quotes.
Within an ERE, a <backslash> character shall be considered to begin an escape sequence as specified in the table in the Base Definitions volume of POSIX.1โ2017, Chapter 5, File Format Notation ('\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v'). In addition, the escape sequences in the following table shall be recognized.
A literal <newline> cannot occur within an ERE; the escape sequence '\n' can be used to represent a <newline>. And a <newline> shall not be matched by a period operator. Noted. ๐
๐ Escape Sequences in lex ๐
\digitsโ A<backslash>character followed by the longest sequence of one, two, or three octal-digit characters (01234567). If all of the digits are0(that is, representation of the NUL character), the behavior is undefined. Meaning: the character whose encoding is represented by the one, two, or three-digit octal integer. Multi-byte characters require multiple, concatenated escape sequences of this type, including the leading<backslash>for each byte.\xdigitsโ A<backslash>character followed by the longest sequence of hexadecimal-digit characters (01234567abcdefABCDEF). If all of the digits are0(that is, representation of the NUL character), the behavior is undefined. Meaning: the character whose encoding is represented by the hexadecimal integer.\cโ A<backslash>character followed by any character not described in this table or in the table in the Base Definitions volume of POSIX.1โ2017, Chapter 5, File Format Notation ('\\','\a','\b','\f','\n','\r','\t','\v'). Meaning: the character'c', unchanged.
Note: If a'\x'sequence needs to be immediately followed by a hexadecimal digit character, a sequence such as"\x1""1"can be used, which represents a character containing the value 1, followed by the character'1'. ๐ซถ
The order of precedence given to extended regular expressions for lex differs from that specified in the Base Definitions volume of POSIX.1โ2017, Section 9.4, Extended Regular Expressions. The order of precedence for lex shall be as shown in the following table, from high to low. ๐
Note: The escaped characters entry is not meant to imply that these are operators, but they are included in the table to show their relationships to the true operators. The start condition, trailing context, and anchoring notations have been omitted from the table because of the placement restrictions described in this section; they can only appear at the beginning or ending of an ERE.
- collation-related bracket symbols โ
[= =][: :][. .] - escaped characters โ
\<special character> - bracket expression โ
[ ] - quoting โ
"..." - grouping โ
( ) - definition โ
{name} - single-character RE duplication โ
*+? - concatenation โ (that's it, justโฆ smooshing things next to each other)
- interval expression โ
{m,n} - alternation โ
|
Okay so plot twist: the ERE anchoring operators ^ and $ are not in that list at all ๐
. And with lex regular expressions they're on a leash: ^ can only go at the very start of an entire regular expression, and $ only at the very end. They apply to the whole regular expression, bestie, not to some little piece of it. So for example the pattern "(^abc)|(def$)" is undefined โ like, do not do that ๐ญ. You'd instead write it as two separate rules, one with the regular expression "^abc" and one with "def$", and they can share a common action via that special | action (more on that below ๐). If you wrote it as "^abc|def$" instead, it would match either "abc" or "def" on a line by itself.
And here's the tea โ: unlike the general ERE rules, embedded anchoring is not allowed by most historical lex implementations. Embedded anchoring is stuff like "(^| )foo( |$)" โ trying to match "foo" when it shows up as a complete word. But you can absolutely get that functionality with lex features you already have:
^foo/[ \n] |
" foo"/[ \n] /* Found foo as a separate word. */
Also lowkey important: $ is a form of trailing context (it's literally equivalent to "/\n"), and because of that it cannot be used with regular expressions that contain another instance of that operator โ see the trailing context discussion earlier ๐ซถ.
The trailing-context operator / can chill as an ordinary character if you do one of these:
- put it inside double quotes โ
"/" - precede it with a
<backslash>โ"\/" - put it inside a bracket expression โ
"[/]"
And the start-condition < and > operators are only special in a start condition at the beginning of a regular expression. Anywhere else in the regular expression? They're just ordinary characters, no cap ๐.
โจ Actions in lex โจ
When an ERE gets matched, the action that fires can be either a C program fragment or one of the special actions listed below. That C fragment can hold one or more C statements, and can even include special actions too. The empty C statement ; shall be a valid action โ so any string in the lex.yy.c input that matches the pattern portion of that rule just gets effectively ignored, skipped, ghosted ๐. But the absence of an action shall not be valid, and what lex does in that situation is undefined. So like. Always write an action, bestie.
Your action spec โ C statements and special actions both โ can span multiple lines if you wrap it in braces:
ERE <one or more blanks> { program statement
program statement }
Those program statements shall not contain unbalanced curly brace preprocessing tokens ๐.
Default action time: if a string in the input to a lex.yy.c program isn't matched by any expression, the default is to copy that string to the output. And because the default behavior of a lex-generated program is read input โ copy to output, a minimal lex source program that's literally just "%%" shall generate a C program that copies the input to the output, unchanged. Iconic, honestly ๐.
Four special actions shall be available:
| ECHO; REJECT; BEGIN
|โ means the action for the next rule is the action for this rule. But unlike the other three,|cannot be enclosed in braces and cannot be<semicolon>-terminated. The application shall ensure it's specified alone, with no other actions. Periodt.ECHO;โ writes the contents of the stringyytexton the output.REJECT;โ usually only a single expression is matched by a given string in the input.REJECTmeans "continue to the next expression that matches the current input", and it shall cause whatever rule was the second choice after the current rule to be executed for the same input. So multiple rules can be matched and executed for one input string, or for overlapping input strings ๐ฆ. Example: given the regular expressions"xyz"and"xy"and the input"xyz", usually only"xyz"would match, and the next attempted match would start after thez. But if the last action in the"xyz"rule isREJECT, then both that rule and the"xy"rule get executed. Heads up though:REJECTmay be implemented in such a fashion that flow of control does not continue after it, as if it were equivalent to agototo another part ofyylex(). And usingREJECTmay result in somewhat larger and slower scanners ๐ญ (worth it sometimes tho).BEGINโ the action:
BEGIN newstate;
switches the state (start condition) to newstate. If the string newstate hasn't been declared previously as a start condition in the Definitions section, the results are unspecified. The initial state is indicated by the digit 0 or the token INITIAL.
The functions and macros below are accessible to user code included in the lex input. It is unspecified whether they appear in the C code output of lex, or are accessible only through the -l l operand to c99 (the lex library) ๐.
int yylex(void)โ performs lexical analysis on the input; this is the primary function generated by the lex utility. It shall return zero when the end of input is reached; otherwise it shall return non-zero values (tokens) determined by the actions that are selected.int yymore(void)โ when called, indicates that when the next input string is recognized, it's to be appended to the current value ofyytextrather than replacing it; the value inyylengshall be adjusted accordingly โจ.int yyless(int n)โ retains n initial characters inyytext, NUL-terminated, and treats the remaining characters as if they had not been read; the value inyylengshall be adjusted accordingly.int input(void)โ returns the next character from the input, or zero on end-of-file. It shall obtain input from the stream pointeryyin, although possibly via an intermediate buffer. So once scanning has begun, the effect of altering the value ofyyinis undefined ๐. The character read shall be removed from the input stream of the scanner without any processing by the scanner.int unput(int c)โ returns the character c to the input;yytextandyylengare undefined until the next expression is matched. The result of usingunput()for more characters than have been input is unspecified.
The following functions shall appear only in the lex library accessible through the -l l operand; they can therefore be redefined by a conforming application:
int yywrap(void)โ called byyylex()at end-of-file; the defaultyywrap()shall always return1. If the application requiresyylex()to continue processing with another source of input, then the application can include a functionyywrap(), which associates another file with the external variableFILE * yyinand shall return a value of zero.int main(int argc, char *argv[])โ callsyylex()to perform lexical analysis, then exits. The user code can containmain()to perform application-specific operations, callingyylex()as applicable.
And except for input(), unput(), and main(), all external and static names generated by lex shall begin with the prefix yy or YY ๐ซถ. That's the naming convention, respect it.
โจ EXIT STATUS โจ
The following exit values shall be returned:
0โ successful completion ๐>0โ an error occurred ๐ญ
๐ CONSEQUENCES OF ERRORS ๐
Default.
The following sections are informative.
๐ธ APPLICATION USAGE ๐ธ
Conforming applications are warned that in the Rules section, an ERE without an action is not acceptable โ but it need not be detected as erroneous by lex ๐. Which means it may result in compilation or runtime errors. So, you know. Don't.
The purpose of input() is to take characters off the input stream and discard them as far as the lexical analysis is concerned. A common use is to discard the body of a comment once the beginning of a comment is recognized ๐ (very main character of it).
The lex utility is not fully internationalized in its treatment of regular expressions in the lex source code or the generated lexical analyzer. Like, it would seem desirable to have the lexical analyzer interpret the regular expressions given in the lex source according to the environment specified when the lexical analyzer is executed, but this is not possible with the current lex technology ๐ง. And honestly, the very nature of the lexical analyzers produced by lex must be closely tied to the lexical requirements of the input language being described, which is frequently locale-specific anyway. (For example, writing an analyzer that's used for French text is not automatically useful for processing other languages.) No cap.
โจ EXAMPLES โจ
okay bestie, here's a whole lil' lex program that implements a rudimentary scanner for a Pascal-like syntax. it's giving "baby's first lexer" and honestly? iconic. ๐
%{
/* Need this for the call to atof() below. */
#include <math.h>
/* Need this for printf(), fopen(), and stdin below. */
#include <stdio.h>
%}
DIGIT [0-9]
ID [a-z][a-z0-9]*
%%
{DIGIT}+ {
printf("An integer: %s (%d)\n", yytext,
atoi(yytext));
}
{DIGIT}+"."{DIGIT}* {
printf("A float: %s (%g)\n", yytext,
atof(yytext));
}
if|then|begin|end|procedure|function {
printf("A keyword: %s\n", yytext);
}
{ID} printf("An identifier: %s\n", yytext);
"+"|"-"|"*"|"/" printf("An operator: %s\n", yytext);
"{"[^}\n]*"}" /* Eat up one-line comments. */
[ \t\n]+ /* Eat up white space. */
. 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();
}
๐ญ RATIONALE ๐ญ
Even though the -c option and references to the C language are retained in this description, lex may be generalized to other languages, as was done at one time for EFL, the Extended FORTRAN Language. Since the lex input specification is essentially language-independent, versions of this utility could be written to produce Ada, Modula-2, or Pascal code, and there are known historical implementations that do so. periodt. โจ
The current description of lex bypasses the issue of dealing with internationalized EREs in the lex source code or generated lexical analyzer. If it follows the model used by awk (the source code is assumed to be presented in the POSIX locale, but input and output are in the locale specified by the environment variables), then the tables in the lexical analyzer produced by lex would interpret EREs specified in the lex source in terms of the environment variables specified when lex was executed. The desired effect would be to have the lexical analyzer interpret the EREs given in the lex source according to the environment specified when the lexical analyzer is executed, but this is not possible with the current lex technology. ๐ญ
The description of octal and hexadecimal-digit escape sequences agrees with the ISO C standard use of escape sequences.
Earlier versions of this standard allowed for implementations with bytes other than eight bits, but this has been modified in this version.
There is no detailed output format specification. The observed behavior of lex under four different historical implementations was that none of these implementations consistently reported the line numbers for error and warning messages. Furthermore, there was a desire that lex be allowed to output additional diagnostic messages. Leaving message formats unspecified avoids these formatting questions and problems with internationalization.
Although the %x specifier for exclusive start conditions is not historical practice, it is believed to be a minor change to historical implementations and greatly enhances the usability of lex programs since it permits an application to obtain the expected functionality with fewer statements.
The %array and %pointer declarations were added as a compromise between historical systems. The System V-based lex copies the matched text to a yytext array. The flex program, supported in BSD and GNU systems, uses a pointer. In the latter case, significant performance improvements are available for some scanners. Most historical programs should require no change in porting from one system to another because the string being referenced is null-terminated in both cases. (The method used by flex in its case is to null-terminate the token in place by remembering the character that used to come right after the token and replacing it before continuing on to the next scan.) Multi-file programs with external references to yytext outside the scanner source file should continue to operate on their historical systems, but would require one of the new declarations to be considered strictly portable.
The description of EREs avoids unnecessary duplication of ERE details because their meanings within a lex ERE are the same as that for the ERE in this volume of POSIX.1-2017.
The reason for the undefined condition associated with text beginning with a <blank> or within "%{" and "%}" delimiter lines appearing in the Rules section is historical practice. Both the BSD and System V lex copy the indented (or enclosed) input in the Rules section (except at the beginning) to unreachable areas of the yylex() function (the code is written directly after a break statement). In some cases, the System V lex generates an error message or a syntax error, depending on the form of indented input.
The intention in breaking the list of functions into those that may appear in lex.yy.c versus those that only appear in libl.a is that only those functions in libl.a can be reliably redefined by a conforming application.
The descriptions of standard output and standard error are somewhat complicated because historical lex implementations chose to issue diagnostic messages to standard output (unless -t was given). POSIX.1-2008 allows this behavior, but leaves an opening for the more expected behavior of using standard error for diagnostics. Also, the System V behavior of writing the statistics when any table sizes are given is allowed, while BSD-derived systems can avoid it. The programmer can always precisely obtain the desired results by using either the -t or -n options.
The OPERANDS section does not mention the use of - as a synonym for standard input; not all historical implementations support such usage for any of the file operands.
A description of the translation table was deleted from early proposals because of its relatively low usage in historical applications.
The change to the definition of the input() function that allows buffering of input presents the opportunity for major performance gains in some applications.
The following examples clarify the differences between lex regular expressions and regular expressions appearing elsewhere in this volume of POSIX.1-2017. For regular expressions of the form "r/x", the string matching r is always returned; confusion may arise when the beginning of x matches the trailing portion of r. For example, given the regular expression "a*b/cc" and the input "aaabcc", yytext would contain the string "aaab" on this match. But given the regular expression "x*/xy" and the input "xxxy", the token xxx, not xx, is returned by some implementations because xxx matches "x*".
In the rule "ab*/bc", the "b*" at the end of r extends r's match into the beginning of the trailing context, so the result is unspecified. If this rule were "ab/bc", however, the rule matches the text "ab" when it is followed by the text "bc". In this latter case, the matching of r cannot extend into the beginning of x, so the result is specified.
๐ฎ FUTURE DIRECTIONS ๐ฎ
None. literally none, bestie. that's the whole section. ๐
๐ SEE ALSO ๐
c99edyacc
The Base Definitions volume of POSIX.1-2017, Chapter 5, File Format Notation, Chapter 8, Environment Variables, Chapter 9, Regular Expressions, Section 12.2, Utility Syntax Guidelines
๐ COPYRIGHT ๐
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
okay bestie, that's the whole page! this one came from IEEE/The Open Group, 2017, for LEX(1P). now go write a scanner that slays. mwah ๐โจ
๐ฆ where this page comes from
- alpine 3.22: man-pages-posix 2017a-r0 ยท custom
- alpine 3.23: man-pages-posix 2017a-r0 ยท custom
- alpine 3.24: man-pages-posix 2017a-r0 ยท custom
- arch rolling: man-pages 6.19-1
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages-posix 2017a
- opensuse-leap 16.0: man-pages-posix 2017a-160000.4.1 ยท SUSE-IEEE
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms