Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code and documentation must retain the above
copyright notice, this list of conditions and the following
disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed or owned by Caldera
International, Inc. Neither the name of Caldera International, Inc.
nor the names of other contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA
INTERNATIONAL, INC. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL CALDERA INTERNATIONAL, INC. BE LIABLE
FOR ANY DIRECT, INDIRECT INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
.nr tm 0 Bell Laboratories, Murray Hill, NJ 07974. .. .EH 'PSD:16-%''Lex - A Lexical Analyzer Generator' .OH 'Lex - A Lexical Analyzer Generator''PSD:16-%' .hc ~ .bd I 2
.ul 0 .... .de PT
.if \\n%>1 'tl ''\s7LEX\s0\s9-%\s0''
.if \\n%>1 'sp
..
.ND July 21, 1975 .RP
.TM 75-1274-15 39199 39199-11
Lex - A Lexical Analyzer ~Generator~ .AU ``MH 2C-569'' 6377 M. E. Lesk and E. Schmidt .AI .MH .AB NOTE: This document describes the historical Unix version of lex. FreeBSD is supplied with flex\| which is a compatible replacement. See the extensive documentation in flex(1)\| for details. .bd I 2 .nr PS 8
.nr VS 9
.ps 8
.vs 9p
Lex helps write programs whose control flow is directed by instances of regular expressions in the input stream. It is well suited for editor-script type transformations and for segmenting input in preparation for a parsing routine.
Lex source is a table of regular expressions and corresponding program fragments. The table is translated to a program which reads an input stream, copying it to an output stream and partitioning the input into strings which match the given expressions. As each such string is recognized the corresponding program fragment is executed. The recognition of the expressions is performed by a deterministic finite automaton generated by Lex. The program fragments written by the user are executed in the order in which the corresponding regular expressions occur in the input stream.
The lexical analysis programs written with Lex accept ambiguous specifications and choose the longest match possible at each input point. If necessary, substantial look~ahead is performed on the input, but the input stream will be backed up to the end of the current partition, so that the user has general freedom to manipulate it.
Lex can generate analyzers in either C or Ratfor, a language
which can be translated automatically to portable Fortran.
It is available on the PDP-11 UNIX, Honeywell GCOS,
and IBM OS systems.
This manual, however, will only discuss generating analyzers
in C on the UNIX system, which is the only supported
form of Lex under UNIX Version 7.
Lex is designed to simplify
interfacing with Yacc, for those
with access to this compiler-compiler system.
.nr PS 9
.nr VS 11
.AE
.2C
Lex is a program generator designed for lexical processing of character input streams. It accepts a high-level, problem oriented specification for character string matching, and produces a program in a general purpose language which recognizes regular expressions. The regular expressions are specified by the user in the source specifications given to Lex. The Lex written code recognizes these expressions in an input stream and partitions the input stream into strings matching the expressions. At the bound~aries between strings program sections provided by the user are executed. The Lex source file associates the regular expressions and the program fragments. As each expression appears in the input to the program written by Lex, the corresponding fragment is executed.
The user supplies the additional code beyond expression matching needed to complete his tasks, possibly including code written by other generators. The program that recognizes the expressions is generated in the general purpose programming language employed for the user's program fragments. Thus, a high level expression language is provided to write the string expressions to be matched while the user's freedom to write actions is unimpaired. This avoids forcing the user who wishes to use a string manipulation language for input analysis to write processing programs in the same and often inappropriate string handling language.
Lex is not a complete language, but rather a generator representing a new language feature which can be added to different programming languages, called ``host languages.'' Just as general purpose languages can produce code to run on different computer hardware, Lex can write code in different host languages. The host language is used for the output code generated by Lex and also for the program fragments added by the user. Compatible run-time libraries for the different host languages are also provided. This makes Lex adaptable to different environments and different users. Each application may be directed to the combination of hardware and host language appropriate to the task, the user's background, and the properties of local implementations. At present, the only supported host language is C, although Fortran (in the form of Ratfor [2] has been available in the past. Lex itself exists on UNIX, GCOS, and OS/370; but the code generated by Lex may be taken anywhere the appropriate compilers exist.
Lex turns the user's expressions and actions
(called
.ul
source
in this memo) into the host general-purpose language;
the generated program is named
.ul
yylex.
The
.ul
yylex
program
will recognize expressions
in a stream
(called
.ul
input
in this memo)
and perform the specified actions for each expression as it is detected.
See Figure 1.
.GS
Source \(-> Lex \(-> yylex |
Input \(-> yylex \(-> Output |
An overview of Lex |
Figure 1 |
For a trivial example, consider a program to delete from the input all blanks or tabs at the ends of lines.
%% |
[ \et]+$ ; |
%% |
[ \et]+$ ; |
[ \et]+ printf(" "); |
Lex can be used alone for simple transformations, or
for analysis and statistics gathering on a lexical level.
Lex can also be used with a parser generator
to perform the lexical analysis phase; it is particularly
easy to interface Lex and Yacc [3].
Lex programs recognize only regular expressions;
Yacc writes parsers that accept a large class of context free grammars,
but require a lower level analyzer to recognize input tokens.
Thus, a combination of Lex and Yacc is often appropriate.
When used as a preprocessor for a later parser generator,
Lex is used to partition the input stream,
and the parser generator assigns structure to
the resulting pieces.
The flow of control
in such a case (which might be the first half of a compiler,
for example) is shown in Figure 2.
Additional programs,
written by other generators
or by hand, can
be added easily to programs written by Lex.
.BS 2
.vs 11
lexical grammar |
rules rules |
\(da \(da |
Lex Yacc |
\(da \(da |
Input \(-> yylex \(-> yyparse \(-> Parsed input |
Lex with Yacc |
Figure 2 |
Yacc users will realize that the name .ul yylex is what Yacc expects its lexical analyzer to be named, so that the use of this name by Lex simplifies interfacing.
Lex generates a deterministic finite automaton from the regular expressions in the source [4]. The automaton is interpreted, rather than compiled, in order to save space. The result is still a fast analyzer. In particular, the time taken by a Lex program to recognize and partition an input stream is proportional to the length of the input. The number of Lex rules or the complexity of the rules is not important in determining speed, unless rules which include forward context require a significant amount of re~scanning. What does increase with the number and complexity of rules is the size of the finite automaton, and therefore the size of the program generated by Lex.
In the program written by Lex, the user's fragments (representing the .ul actions to be performed as each regular expression is found) are gathered as cases of a switch. The automaton interpreter directs the control flow. Opportunity is provided for the user to insert either declarations or additional statements in the routine containing the actions, or to add subroutines outside this action routine.
Lex is not limited to source which can be interpreted on the basis of one character look~ahead. For example, if there are two rules, one looking for ab and another for abcdefg , and the input stream is abcdefh , Lex will recognize ab and leave the input pointer just before "cd. . ." Such backup is more costly than the processing of simpler languages. .2C
Lex Source.The general format of Lex source is:
{definitions} |
%% |
{rules} |
%% |
{user subroutines} |
%% |
In the outline of Lex programs shown above, the rules .R represent the user's control decisions; they are a table, in which the left column contains regular expressions .R (see section 3) and the right column contains actions, .R program fragments to be executed when the expressions are recognized. Thus an individual rule might appear
integer printf("found keyword INT"); |
colour printf("color"); |
mechanise printf("mechanize"); |
petrol printf("gas"); |
The definitions of regular expressions are very similar to those in QED [5]. A regular expression specifies a set of strings to be matched. It contains text characters (which match the corresponding characters in the strings being compared) and operator characters (which specify repetitions, choices, and other features). The letters of the alphabet and the digits are always text characters; thus the regular expression
integer |
a57D |
Operators. .R The operator characters are
" \e [ ] ^ - ? . \(** + | ( ) $ / { } % < > |
xyz"++" |
"xyz++" |
An operator character may also be turned into a text character by preceding it with \e as in
xyz\e+\e+ |
Character classes. .R Classes of characters can be specified using the operator pair [\|]. The construction [abc] matches a single character, which may be a , b , or c . Within square brackets, most operator meanings are ignored. Only three characters are special: these are \e - and ^. The - character indicates ranges. For example,
[a-z0-9<>_] |
[-+0-9] |
In character classes, the ^ operator must appear as the first character after the left bracket; it indicates that the resulting string is to be complemented with respect to the computer character set. Thus
[^abc] |
[^a-zA-Z] |
Arbitrary character. .R To match almost any character, the operator character
. |
[\e40-\e176] |
Optional expressions. .R The operator ? indicates an optional element of an expression. Thus
ab?c |
Repeated expressions. .R Repetitions of classes are indicated by the operators \(** and + .
\f2a\(**\f1 |
a+ |
[a-z]+ |
[A-Za-z][A-Za-z0-9]\(** |
Alternation and Grouping. .R The operator | indicates alternation:
(ab\||\|cd) |
ab\||\|cd |
(ab\||\|cd+)?(ef)\(** |
Context sensitivity. .R Lex will recognize a small amount of surrounding context. The two simplest operators for this are ^ and $ . If the first character of an expression is ^ , the expression will only be matched at the beginning of a line (after a newline character, or at the beginning of the input stream). This can never conflict with the other meaning of ^ , complementation of character classes, since that only applies within the [\|] operators. If the very last character is $ , the expression will only be matched at the end of a line (when immediately followed by newline). The latter operator is a special case of the / operator character, which indicates trailing context. The expression
ab/cd |
ab$ |
ab/\en |
<x> |
<ONE> |
Repetitions and Definitions. .R The operators {} specify either repetitions (if they enclose numbers) or definition expansion (if they enclose a name). For example
{digit} |
a{1,5} |
Finally, initial % is special, being the separator for Lex source segments. .2C
Lex Actions.When an expression written as above is matched, Lex executes the corresponding action. This section describes some features of Lex which aid in writing actions. Note that there is a default action, which consists of copying the input to the output. This is performed on all strings not otherwise matched. Thus the Lex user who wishes to absorb the entire input, without producing any output, must provide rules to match everything. When Lex is being used with Yacc, this is the normal situation. One may consider that actions are what is done instead of copying the input to the output; thus, in general, a rule which merely copies can be omitted. Also, a character combination which is omitted from the rules and which appears as input is likely to be printed on the output, thus calling attention to the gap in the rules.
One of the simplest things that can be done is to ignore the input. Specifying a C null statement, ; as an action causes this result. A frequent rule is
[ \et\en] ; |
Another easy way to avoid writing actions is the action character |, which indicates that the action for this rule is the action for the next rule. The previous example could also have been written
" "#| |
"\et"#| |
"\en"#; |
In more complex actions, the user will often want to know the actual text that matched some expression like [a-z]+ . Lex leaves this text in an external character array named yytext. .R Thus, to print the name found, a rule like
[a-z]+ printf("%s", yytext); |
[a-z]+ ECHO; |
Sometimes it is more convenient to know the end of what has been found; hence Lex also provides a count yyleng .R of the number of characters matched. To count both the number of words and the number of characters in words in the input, the user might write
[a-zA-Z]+ {words++; chars += yyleng;} |
yytext[yyleng-1] |
Occasionally, a Lex action may decide that a rule has not recognized the correct span of characters. Two routines are provided to aid with this situation. First, yymore() .R can be called to indicate that the next input expression recognized is to be tacked on to the end of this input. Normally, the next input string would overwrite the current entry in yytext. .R Second, yyless (n) .R may be called to indicate that not all the characters matched by the currently successful expression are wanted right now. The argument n .R indicates the number of characters in yytext .R to be retained. Further characters previously matched are returned to the input. This provides the same sort of look~ahead offered by the / operator, but in a different form.
Example: .R Consider a language which defines a string as a set of characters between quotation (") marks, and provides that to include a " in a string it must be preceded by a \e. The regular expression which matches that is somewhat confusing, so that it might be preferable to write
\e"[^"]\(** { |
if (yytext[yyleng-1] == \(fm\e\e\(fm) |
yymore(); |
else |
... normal user processing |
} |
The function yyless() .R might be used to reprocess text in various circumstances. Consider the C problem of distinguishing the ambiguity of ``=-a''. Suppose it is desired to treat this as ``=- a'' but print a message. A rule might be .vs 11
=-[a-zA-Z] { |
printf("Op (=-) ambiguous\en"); |
yyless(yyleng-1); |
... action for =- ... |
} |
=-[a-zA-Z] { |
printf("Op (=-) ambiguous\en"); |
yyless(yyleng-2); |
... action for = ... |
} |
=-/[A-Za-z] |
=/-[A-Za-z] |
=-/[^ \et\en] |
In addition to these routines, Lex also permits access to the I/O routines it uses. They are:
By default these routines are provided as macro definitions, but the user can override them and supply private versions. These routines define the relationship between external files and internal characters, and must all be retained or modified consistently. They may be redefined, to cause input or output to be transmitted to or from strange places, including other programs or internal memory; but the character set used must be consistent in all routines; a value of zero returned by input .R must mean end of file; and the relationship between unput .R and input .R must be retained or the Lex look~ahead will not work. Lex does not look ahead at all if it does not have to, but every rule ending in + \(** ? or $ or containing / implies look~ahead. Look~ahead is also necessary to match an expression that is a prefix of another expression. See below for a discussion of the character set used by Lex. The standard Lex library imposes a 100 character limit on backup.
Another Lex library routine that the user will sometimes want to redefine is yywrap() .R which is called whenever Lex reaches an end-of-file. If yywrap .R returns a 1, Lex continues with the normal wrapup on end of input. Sometimes, however, it is convenient to arrange for more input to arrive from a new source. In this case, the user should provide a yywrap .R which arranges for new input and returns 0. This instructs Lex to continue processing. The default yywrap .R always returns 1.
This routine is also a convenient place to print tables, summaries, etc. at the end of a program. Note that it is not possible to write a normal rule which recognizes end-of-file; the only access to this condition is through yywrap. .R In fact, unless a private version of input() .R is supplied a file containing nulls cannot be handled, since a value of 0 returned by input .R is taken to be end-of-file.
.2C
Ambiguous Source Rules.Lex can handle ambiguous specifications. When more than one expression can match the current input, Lex chooses as follows:
Thus, suppose the rules
integer keyword action ...; |
[a-z]+ identifier action ...; |
The principle of preferring the longest match makes rules containing expressions like .\(** dangerous. For example,
\(fm.\(**\(fm |
\(fmfirst\(fm quoted string here, \(fmsecond\(fm here |
\(fmfirst\(fm quoted string here, \(fmsecond\(fm |
\(fm[^\(fm\en]\(**\(fm |
Note that Lex is normally partitioning the input stream, not searching for all possible matches of each expression. This means that each character is accounted for once and only once. For example, suppose it is desired to count occurrences of both she and he in an input text. Some Lex rules to do this might be
she s++; |
he h++; |
\en | |
. ; |
Sometimes the user would like to override this choice. The action REJECT means ``go do the next alternative.'' It causes whatever rule was second choice after the current rule to be executed. The position of the input pointer is adjusted accordingly. Suppose the user really wants to count the included instances of he:
she {s++; REJECT;} |
he {h++; REJECT;} |
\en | |
. ; |
Consider the two rules
a[bc]+ { ... ; REJECT;} |
a[cd]+ { ... ; REJECT;} |
In general, REJECT is useful whenever the purpose of Lex is not to partition the input stream but to detect all examples of some items in the input, and the instances of these items may overlap or include each other. Suppose a digram table of the input is desired; normally the digrams overlap, that is the word the is considered to contain both th and he . Assuming a two-dimensional array named .ul digram to be incremented, the appropriate source is
%% |
[a-z][a-z] { |
digram[yytext[0]][yytext[1]]++; |
REJECT; |
} |
. ; |
\en ; |
Remember the format of the Lex source:
{definitions} |
%% |
{rules} |
%% |
{user routines} |
Remember that Lex is turning the rules into a program. Any source not intercepted by Lex is copied into the generated program. There are three classes of such things.
Definitions intended for Lex are given before the first %% delimiter. Any line in this section not contained between %{ and %}, and begining in column 1, is assumed to define Lex substitution strings. The format of such lines is
name translation |
D#[0-9] |
E#[DEde][-+]?{D}+ |
%% |
{D}+#printf("integer"); |
{D}+"."{D}\(**({E})?#| |
{D}\(**"."{D}+({E})?#| |
{D}+{E}#printf("real"); |
[0-9]+/"."EQ printf("integer"); |
The definitions section may also contain other commands, including the selection of a host language, a character set table, a list of start conditions, or adjustments to the default size of arrays within Lex itself for larger source programs. These possibilities are discussed below under ``Summary of Source Format,'' section 12. .2C
Usage.There are two steps in compiling a Lex source program. First, the Lex source must be turned into a generated program in the host general purpose language. Then this program must be compiled and loaded, usually with a library of Lex subroutines. The generated program is on a file named lex.yy.c . The I/O library is defined in terms of the C standard library [6].
The C programs generated by Lex are slightly different on OS/370, because the OS compiler is less powerful than the UNIX or GCOS compilers, and does less at compile time. C programs generated on GCOS and UNIX are the same.
UNIX. .R The library is accessed by the loader flag -ll . So an appropriate set of commands is .KS lex source cc lex.yy.c -ll .KE The resulting program is placed on the usual file a.out .R for later execution. To use Lex with Yacc see below. Although the default Lex I/O routines use the C standard library, the Lex automata themselves do not do so; if private versions of input, output .R and unput are given, the library can be avoided.
.2C
Lex and Yacc.If you want to use Lex with Yacc, note that what Lex writes is a program named yylex(), .R the name required by Yacc for its analyzer. Normally, the default main program on the Lex library calls this routine, but if Yacc is loaded, and its main program is used, Yacc will call yylex(). .R In this case each Lex rule should end with
return(token); |
# include "lex.yy.c" |
yacc good |
lex better |
cc y.tab.c -ly -ll |
As a trivial problem, consider copying an input file while adding 3 to every positive number divisible by 7. Here is a suitable Lex source program
%% |
int k; |
[0-9]+ { |
k = atoi(yytext); |
if (k%7 == 0) |
printf("%d", k+3); |
else |
printf("%d",k); |
} |
%% |
int k; |
-?[0-9]+ { |
k = atoi(yytext); |
printf("%d", |
k%7 == 0 ? k+3 : k); |
} |
-?[0-9.]+ ECHO; |
[A-Za-z][A-Za-z0-9]+ ECHO; |
For an example of statistics gathering, here is a program which histograms the lengths of words, where a word is defined as a string of letters.
int lengs[100]; |
%% |
[a-z]+ lengs[yyleng]++; |
. | |
\en ; |
%% |
.T& |
l s. |
yywrap() |
{ |
int i; |
printf("Length No. words\en"); |
for(i=0; i<100; i++) |
if (lengs[i] > 0) |
printf("%5d%10d\en",i,lengs[i]); |
return(1); |
} |
As a larger example, here are some parts of a program written by N. L. Schryer to convert double precision Fortran to single precision Fortran. Because Fortran does not distinguish upper and lower case letters, this routine begins by defining a set of classes including both cases of each letter:
a [aA] |
b [bB] |
c [cC] |
... |
z [zZ] |
W [ \et]\(** |
{d}{o}{u}{b}{l}{e}{W}{p}{r}{e}{c}{i}{s}{i}{o}{n} { |
printf(yytext[0]==\(fmd\(fm? "real" : "REAL"); |
} |
^" "[^ 0] ECHO; |
[0-9]+{W}{d}{W}[+-]?{W}[0-9]+ | |
[0-9]+{W}"."{W}{d}{W}[+-]?{W}[0-9]+ | |
"."{W}[0-9]+{W}{d}{W}[+-]?{W}[0-9]+ { |
/\(** convert constants \(**/ |
for(p=yytext; \(**p != 0; p++) |
{ |
if (\(**p == \(fmd\(fm || \(**p == \(fmD\(fm) |
\(**p=+ \(fme\(fm- \(fmd\(fm; |
ECHO; |
} |
{d}{s}{i}{n} | |
{d}{c}{o}{s} | |
{d}{s}{q}{r}{t} | |
{d}{a}{t}{a}{n} | |
... |
{d}{f}{l}{o}{a}{t} printf("%s",yytext+1); |
{d}{l}{o}{g} | |
{d}{l}{o}{g}10 | |
{d}{m}{i}{n}1 | |
{d}{m}{a}{x}1 { |
yytext[0] =+ \(fma\(fm - \(fmd\(fm; |
ECHO; |
} |
{d}1{m}{a}{c}{h}#{yytext[0] =+ \(fmr\(fm - \(fmd\(fm; |
#ECHO; |
#} |
[A-Za-z][A-Za-z0-9]\(** | |
[0-9]+ | |
\en | |
. ECHO; |
.2C
Left Context Sensitivity.Sometimes it is desirable to have several sets of lexical rules to be applied at different times in the input. For example, a compiler preprocessor might distinguish preprocessor statements and analyze them differently from ordinary statements. This requires sensitivity to prior context, and there are several ways of handling such problems. The ^ operator, for example, is a prior context operator, recognizing immediately preceding left context just as $ recognizes immediately following right context. Adjacent left context could be extended, to produce a facility similar to that for adjacent right context, but it is unlikely to be as useful, since often the relevant left context appeared some time earlier, such as at the beginning of a line.
This section describes three means of dealing with different environments: a simple use of flags, when only a few rules change from one environment to another, the use of start conditions .R on rules, and the possibility of making multiple lexical analyzers all run together. In each case, there are rules which recognize the need to change the environment in which the following input text is analyzed, and set some parameter to reflect the change. This may be a flag explicitly tested by the user's action code; such a flag is the simplest way of dealing with the problem, since Lex is not involved at all. It may be more convenient, however, to have Lex remember the flags as initial conditions on the rules. Any rule may be associated with a start condition. It will only be recognized when Lex is in that start condition. The current start condition may be changed at any time. Finally, if the sets of rules for the different environments are very dissimilar, clarity may be best achieved by writing several distinct lexical analyzers, and switching from one to another as desired.
Consider the following problem: copy the input to the output, changing the word magic to first on every line which began with the letter a, changing magic to second on every line which began with the letter b, and changing magic to third on every line which began with the letter c. All other words and all other lines are left unchanged.
These rules are so simple that the easiest way to do this job is with a flag:
int flag; |
%% |
^a {flag = \(fma\(fm; ECHO;} |
^b {flag = \(fmb\(fm; ECHO;} |
^c {flag = \(fmc\(fm; ECHO;} |
\en {flag = 0 ; ECHO;} |
magic { |
switch (flag) |
{ |
case \(fma\(fm: printf("first"); break; |
case \(fmb\(fm: printf("second"); break; |
case \(fmc\(fm: printf("third"); break; |
default: ECHO; break; |
} |
} |
To handle the same problem with start conditions, each start condition must be introduced to Lex in the definitions section with a line reading
%Start name1 name2 ... |
<name1>expression |
BEGIN name1; |
BEGIN 0; |
<name1,name2,name3> |
The same example as before can be written:
%START AA BB CC |
%% |
^a {ECHO; BEGIN AA;} |
^b {ECHO; BEGIN BB;} |
^c {ECHO; BEGIN CC;} |
\en {ECHO; BEGIN 0;} |
<AA>magic printf("first"); |
<BB>magic printf("second"); |
<CC>magic printf("third"); |
The programs generated by Lex handle character I/O only through the routines input, output, .R and unput. .R Thus the character representation provided in these routines is accepted by Lex and employed to return values in yytext. .R For internal use a character is represented as a small integer which, if the standard library is used, has a value equal to the integer value of the bit pattern representing the character on the host computer. Normally, the letter a is represented as the same form as the character constant \(fma\(fm . If this interpretation is changed, by providing I/O routines which translate the characters, Lex must be told about it, by giving a translation table. This table must be in the definitions section, and must be bracketed by lines containing only ``%T''. The table contains lines of the form
{integer} {character string} |
%T |
1 Aa |
2 Bb |
... |
26 Zz |
27 \en |
28 + |
29 - |
30 0 |
31 1 |
... |
39 9 |
%T |
1
Sample character table.
.GE
maps the lower and upper case letters together into the integers 1 through 26,
newline into 27, + and - into 28 and 29, and the
digits into 30 through 39.
Note the escape for newline.
If a table is supplied, every character that is to appear either
in the rules or in any valid input must be included
in the table.
No character
may be assigned the number 0, and no character may be
assigned a bigger number than the size of the hardware character set.
.2C
The general form of a Lex source file is:
{definitions} |
%% |
{rules} |
%% |
{user subroutines} |
%{ |
code |
%} |
%S name1 name2 ... |
%T |
number space character-string |
... |
%T |
%x\0\0nnn |
Letter Parameter |
p positions |
n states |
e tree nodes |
a transitions |
k packed character classes |
o output array size |
Lines in the rules section have the form ``expression action'' where the action may be continued on succeeding lines by using braces to delimit it.
Regular expressions in Lex use the following operators:
x the character "x" |
"x" an "x", even if x is an operator. |
\ex an "x", even if x is an operator. |
[xy] the character x or y. |
[x-z] the characters x, y or z. |
[^x] any character but x. |
. any character but newline. |
^x an x at the beginning of a line. |
<y>x an x when Lex is in start condition y. |
x$ an x at the end of a line. |
x? an optional x. |
x\(** 0,1,2, ... instances of x. |
x+ 1,2,3, ... instances of x. |
x|y an x or a y. |
(x) an x. |
x/y an x but only if followed by y. |
{xx} the translation of xx from the |
definitions section. |
x{m,n} m through n occurrences of x |
There are pathological expressions which produce exponential growth of the tables when converted to deterministic machines; fortunately, they are rare.
REJECT does not rescan the input; instead it remembers the results of the previous scan. This means that if a rule with trailing context is found, and REJECT executed, the user must not have used .ul unput to change the characters forthcoming from the input stream. This is the only restriction on the user's ability to manipulate the not-yet-processed input.
.2C
Acknowledgments.As should be obvious from the above, the outside of Lex is patterned on Yacc and the inside on Aho's string matching routines. Therefore, both S. C. Johnson and A. V. Aho are really originators of much of Lex, as well as debuggers of it. Many thanks are due to both.
The code of the current version of Lex was designed, written, and debugged by Eric Schmidt. .2C
References.