.\" @(#)lex.ms 6.1 (Berkeley) %G%
.EH 'PS1:16-%''Lex \- A Lexical Analyzer Generator'
.OH 'Lex \- A Lexical Analyzer Generator''PS1:16-%'
.\".if \\n%>1 'tl ''\s7LEX\s0\s9\(mi%\s0''
.\".TM 75-1274-15 39199 39199-11
Lex \- A Lexical Analyzer ~Generator~
M. E. Lesk and E. Schmidt
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
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
The program fragments written by the user are executed in the order in which the
corresponding regular expressions occur in the input stream.
programs written with Lex accept ambiguous specifications
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,
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.
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,
produces a program in a general purpose language which recognizes
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
provided by the user are executed.
The Lex source file associates the regular expressions and the
As each expression appears in the input to the program written by Lex,
the corresponding fragment is executed.
Bell Laboratories, Murray Hill, NJ 07974.
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
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
This makes Lex adaptable to different environments and
may be directed to the combination of hardware and host language appropriate
to the task, the user's background, and the properties of local
At present, the only supported host language is C,
although Fortran (in the form of Ratfor [2] has been available
Lex itself exists on UNIX, GCOS, and OS/370; but the
code generated by Lex may be taken anywhere the appropriate
Lex turns the user's expressions and actions
in this memo) into the host general-purpose language;
the generated program is named
will recognize expressions
and perform the specified actions for each expression as it is detected.
Source \(-> Lex \(-> yylex
Input \(-> yylex \(-> Output
For a trivial example, consider a program to delete
all blanks or tabs at the ends of lines.
contains a %% delimiter to mark the beginning of the rules, and
This rule contains a regular expression
which matches one or more
instances of the characters blank or tab
(written \et for visibility, in accordance with the C language convention)
just prior to the end of a line.
The brackets indicate the character
class made of blank and tab; the + indicates ``one or more ...'';
and the $ indicates ``end of line,'' as in QED.
so the program generated by Lex (yylex) will ignore these characters.
Everything else will be copied.
string of blanks or tabs to a single blank,
The finite automaton generated for this
source will scan for both rules at once,
the termination of the string of blanks or tabs
whether or not there is a newline character, and executing
The first rule matches all strings of blanks or tabs
at the end of lines, and the second
rule all remaining strings of blanks or tabs.
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
in such a case (which might be the first half of a compiler,
for example) is shown in Figure 2.
written by other generators
be added easily to programs written by Lex.
Input \(-> yylex \(-> yyparse \(-> Parsed input
will realize that the name
is what Yacc expects its lexical analyzer to be named,
so that the use of this name by Lex simplifies
Lex generates a deterministic finite automaton from the regular expressions
The automaton is interpreted, rather than compiled, in order
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
In the program written by Lex, the user's fragments
to be performed as each regular expression
The automaton interpreter directs the control flow.
Opportunity is provided for the user to insert either
declarations or additional statements in the routine containing
add subroutines outside this action routine.
Lex is not limited to source which can
be interpreted on the basis of one character
if there are two rules, one looking for
the input pointer just before
Such backup is more costly
than the processing of simpler languages.
The general format of Lex source is:
where the definitions and the user subroutines
is optional, but the first is required
to mark the beginning of the rules.
The absolute minimum Lex program is thus
(no definitions, no rules) which translates into a program
which copies the input to the output unchanged.
In the outline of Lex programs shown above, the
represent the user's control
decisions; they are a table, in which the left column
and the right column contains
program fragments to be executed when the expressions
Thus an individual rule might appear
integer printf("found keyword INT");
print the message ``found keyword INT'' whenever it appears.
In this example the host procedural language is C and
is used to print the string.
of the expression is indicated by the first blank or tab character.
If the action is merely a single C expression,
it can just be given on the right side of the line; if it is
compound, or takes more than a line, it should be enclosed in
As a slightly more useful example, suppose it is desired to
change a number of words from British to American spelling.
mechanise printf("mechanize");
would be a start. These rules are not quite enough,
with this will be described later.
The definitions of regular expressions are very similar to those
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
The operator characters are
" \e [ ] ^ \- ? . \(** + | ( ) $ / { } % < >
and if they are to be used as text characters, an escape
The quotation mark operator (")
indicates that whatever is contained between a pair of quotes
is to be taken as text characters.
when it appears. Note that a part of a string may be quoted.
It is harmless but unnecessary to quote an ordinary
text character; the expression
is the same as the one above.
Thus by quoting every non-alphanumeric character
being used as a text character, the user can avoid remembering
the list above of current
operator characters, and is safe should further extensions to Lex
An operator character may also be turned into a text character
by preceding it with \e as in
is another, less readable, equivalent of the above expressions.
Another use of the quoting mechanism is to get a blank into
an expression; normally, as explained above, blanks or tabs end
Any blank character not contained within [\|] (see below) must
Several normal C escapes with \e
are recognized: \en is newline, \et is tab, and \eb is backspace.
To enter \e itself, use \e\e.
Since newline is illegal in an expression, \en must be used;
required to escape tab and backspace.
Every character but blank, tab, newline and the list above is always
Classes of characters can be specified using the operator pair [\|].
single character, which may be
most operator meanings are ignored.
Only three characters are special:
these are \e \(mi and ^. The \(mi character
indicates ranges. For example,
indicates the character class containing all the lower case letters,
the angle brackets, and underline.
Ranges may be given in either order.
Using \(mi between any pair of characters which are
not both upper case letters, both lower case letters, or both digits
is implementation dependent and will get a warning message.
(E.g., [0\-z] in ASCII is many more characters
If it is desired to include the
character \(mi in a character class, it should be first or
matches all the digits and the two signs.
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.
matches all characters except a, b, or c, including
all special or control characters; or
is any character which is not a letter.
The \e character provides the usual escapes within
character class brackets.
To match almost any character, the operator character
is the class of all characters except newline.
Escaping into octal is possible although non-portable:
matches all printable characters in the ASCII character set, from octal
40 (blank) to octal 176 (tilde).
an optional element of an expression.
Repetitions of classes are indicated by the operators
is any number of consecutive
characters, including zero; while
is one or more instances of
is all strings of lower case letters.
[A\(miZa\(miz][A\(miZa\(miz0\(mi9]\(**
indicates all alphanumeric strings with a leading
This is a typical expression for recognizing identifiers in
Alternation and Grouping.
Note that parentheses are used for grouping, although
not necessary on the outside level;
can be used for more complex expressions:
Lex will recognize a small amount of surrounding
context. The two simplest operators for this are
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
This can never conflict with the other meaning of
of character classes, since that only applies within
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
which indicates trailing context.
Left context is handled in Lex by
as explained in section 10. If a rule is only to be executed
when the Lex automaton interpreter is in start condition
the rule should be prefixed by
using the angle bracket operator characters.
If we considered ``being at the beginning of a line'' to be
Start conditions are explained more fully later.
Repetitions and Definitions.
either repetitions (if they enclose numbers)
definition expansion (if they enclose a name). For example
looks for a predefined string named
at that point in the expression.
The definitions are given in the first part of the Lex
looks for 1 to 5 occurrences of
is special, being the separator
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
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, \fI;\fR as an action
causes this result. A frequent rule is
which causes the three spacing characters (blank, tab, and newline)
Another easy way to avoid writing actions is the action character
|, which indicates that the action for this rule is the action
The previous example could also have been written
with the same result, although in different style.
The quotes around \en and \et are not required.
In more complex actions, the user
often want to know the actual text that matched some expression
Lex leaves this text in an external character
Thus, to print the name found,
[a\-z]+ printf("%s", yytext);
accepts a format argument and data to be printed;
in this case, the format is ``print string'' (% indicating
and the data are the characters
it may be written as ECHO:
is the same as the above.
Since the default action is just to
print the characters found, one might ask why
give a rule, like this one, which merely specifies
Such rules are often required
to avoid matching some other rule
which is not desired. For example, if there is a rule
it will normally match the instances of
This is explained further below.
Sometimes it is more convenient to know the end of what
has been found; hence Lex also provides a count
of the number of characters matched.
of words and the number of characters in words in the input, the user might write
[a\-zA\-Z]+ {words++; chars += yyleng;}
of characters in the words recognized.
The last character in the string matched can
action may decide that a rule has not recognized the correct
Two routines are provided to aid with this situation.
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
may be called to indicate that not all the characters matched
by the currently successful expression are wanted right now.
indicates the number of characters
Further characters previously matched
returned to the input. This provides the same sort of
look~ahead offered by the / operator,
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
if (yytext[yyleng\-1] == \(fm\e\e\(fm)
... normal user processing
which will, when faced with a string such as
cause the next part of the string,
Note that the final quote terminating the string should be picked
up in the code labeled ``normal processing''.
might be used to reprocess
text in various circumstances. Consider the C problem of distinguishing
the ambiguity of ``=\(mia''.
Suppose it is desired to treat this as ``=\(mi a''
but print a message. A rule might be
printf("Op (=\(mi) ambiguous\en");
which prints a message, returns the letter after the
operator to the input stream, and treats the operator as ``=\(mi''.
Alternatively it might be desired to treat this as ``= \(mia''.
To do this, just return the minus
sign as well as the letter to the input:
printf("Op (=\(mi) ambiguous\en");
will perform the other interpretation.
Note that the expressions for the two cases might more easily
no backup would be required in the rule action.
It is not necessary to recognize the whole identifier
to observe the ambiguity.
possibility of ``=\(mi3'', however, makes
In addition to these routines, Lex also permits
access to the I/O routines
which returns the next input character;
which writes the character
back onto the input stream to be read later by
By default these routines are provided as macro definitions,
but the user can override them and supply private versions.
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
must mean end of file; and
or the Lex look~ahead will not work.
Lex does not look ahead at all if it does not have to,
Look~ahead is also necessary to match an expression that is a prefix
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
which is called whenever Lex reaches an end-of-file.
returns a 1, Lex continues with the normal wrapup on end of input.
Sometimes, however, it is convenient to arrange for more
In this case, the user should provide
arranges for new input and
returns 0. This instructs Lex to continue processing.
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
In fact, unless a private version of
since a value of 0 returned by
is taken to be end-of-file.
Lex can handle ambiguous specifications.
When more than one expression can match the
current input, Lex chooses as follows:
The longest match is preferred.
Among rules which matched the same number of characters,
the rule given first is preferred.
integer keyword action ...;
[a\-z]+ identifier action ...;
to be given in that order. If the input is
it is taken as an identifier, because
matches 8 characters while
both rules match 7 characters, and
the keyword rule is selected because it was given first.
Anything shorter (e.g. \fIint\fR\|) will
and so the identifier interpretation is used.
The principle of preferring the longest
match makes rules containing
might seem a good way of recognizing
a string in single quotes.
But it is an invitation for the program to read far
ahead, looking for a distant
\&\(fmfirst\(fm quoted string here, \(fmsecond\(fm here
the above expression will match
\&\(fmfirst\(fm quoted string here, \(fmsecond\(fm
which is probably not what was wanted.
A better rule is of the form
which, on the above input, will stop
of errors like this are mitigated by the fact
operator will not match newline.
Don't try to defeat this with expressions like
the Lex generated program will try to read
the entire input file, causing
internal buffer overflows.
Note that Lex is normally partitioning
the input stream, not searching for all possible matches
This means that each character is accounted for
For example, suppose it is desired to
count occurrences of both \fIshe\fR and \fIhe\fR in an input text.
Some Lex rules to do this might be
where the last two rules ignore everything besides \fIhe\fR and \fIshe\fR.
Remember that . does not include newline.
Since \fIshe\fR includes \fIhe\fR, Lex will normally
the instances of \fIhe\fR included in \fIshe\fR,
since once it has passed a \fIshe\fR those characters are gone.
Sometimes the user would like to override this choice. The action
means ``go do the next alternative.''
It causes whatever rule was second choice after the current
The position of the input pointer is adjusted accordingly.
Suppose the user really wants to count the included instances of \fIhe\fR:
these rules are one way of changing the previous example
After counting each expression, it is rejected; whenever appropriate,
the other expression will then be counted. In this example, of course,
the user could note that \fIshe\fR includes \fIhe\fR but not
vice versa, and omit the REJECT action on \fIhe\fR;
in other cases, however, it
would not be possible a priori to tell
only the first rule matches,
matches the first rule for four characters
and then the second rule for three characters.
the second rule for four characters and then the first
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
Assuming a two-dimensional array named
to be incremented, the appropriate
digram[yytext[0]][yytext[1]]++;
where the REJECT is necessary to pick up
a letter pair beginning at every character, rather than at every
Remember the format of the Lex
So far only the rules have been described. The user needs
though, to define variables for use in his program and for use
These can go either in the definitions section
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
Any line which is not part of a Lex rule or action
which begins with a blank or tab is copied into
the Lex generated program.
Such source input prior to the first %% delimiter will be external
to any function in the code; if it appears immediately after the first
it appears in an appropriate place for declarations
in the function written by Lex which contains the actions.
This material must look like program fragments,
and should precede the first Lex rule.
As a side effect of the above, lines which begin with a blank
or tab, and which contain a comment,
are passed through to the generated program.
This can be used to include comments in either the Lex source or
the generated code. The comments should follow the host
Anything included between lines containing
copied out as above. The delimiters are discarded.
This format permits entering text like preprocessor statements that
or copying lines that do not look like programs.
Anything after the third %% delimiter, regardless of formats, etc.,
is copied out after the Lex output.
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
causes the string given as a translation to
be associated with the name.
must be separated by at least one blank or tab, and the name must begin with a letter.
The translation can then be called out
by the {name} syntax in a rule.
Using {D} for the digits and {E} for an exponent field,
for example, might abbreviate rules to recognize numbers:
Note the first two rules for real numbers;
both require a decimal point and contain
an optional exponent field,
but the first requires at least one digit before the
decimal point and the second requires at least one
digit after the decimal point.
To correctly handle the problem
posed by a Fortran expression such as
which does not contain a real number, a context-sensitive
[0\-9]+/"."EQ printf("integer");
could be used in addition to the normal rule for integers.
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.
are discussed below under ``Summary of Source Format,''
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 I/O library is defined in terms of the C standard
The C programs generated by Lex are slightly different
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.
The library is accessed by the loader flag
The resulting program is placed on the usual file
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;
are given, the library can be avoided.
If you want to use Lex with Yacc, note that what Lex writes is a program
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
In this case each Lex rule should end with
where the appropriate token value is returned.
An easy way to get access
to Yacc's names for tokens is to
compile the Lex output file as part of
the Yacc output file by placing the line
in the last section of Yacc input.
Supposing the grammar to be
named ``good'' and the lexical rules to be named ``better''
the UNIX command sequence can just be:
The Yacc library (\-ly) should be loaded before the Lex library,
to obtain a main program which invokes the Yacc parser.
The generations of Lex and Yacc programs can be done in
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
The rule [0\-9]+ recognizes strings of digits;
converts the digits to binary
The operator % (remainder) is used to check whether
is divisible by 7; if it is,
it is incremented by 3 as it is written out.
It may be objected that this program will alter such
Furthermore, it increments the absolute value
of all negative numbers divisible by 7.
To avoid this, just add a few more rules after the active one,
[A-Za-z][A-Za-z0-9]+ ECHO;
Numerical strings containing
a ``.'' or preceded by a letter will be picked up by
one of the last two rules, and not changed.
a C conditional expression to save space;
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.
printf("Length No. words\en");
printf("%5d%10d\en",i,lengs[i]);
accumulates the histogram, while producing no output. At the end
of the input it prints the table.
indicates that Lex is to perform wrapup. If
it implies that further input is available
to continue reading and processing.
returns true causes an infinite loop.
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:
An additional class recognizes white space:
``double precision'' to ``real'', or ``DOUBLE PRECISION'' to ``REAL''.
{d}{o}{u}{b}{l}{e}{W}{p}{r}{e}{c}{i}{s}{i}{o}{n} {
printf(yytext[0]==\(fmd\(fm? "real" : "REAL");
Care is taken throughout this program to preserve the case
The conditional operator is used to
select the proper form of the keyword.
The next rule copies continuation card indications to
avoid confusing them with constants:
In the regular expression, the quotes surround the
``beginning of line, then five blanks, then
anything but blank or zero.''
Note the two different meanings of
There follow some rules to change double precision
constants to ordinary floating constants.
[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;
After the floating point constant is recognized, it is
.I \(fme\(fm\-\(fmd\(fm ,
it to the next letter of the alphabet.
The modified constant, now single-precision,
There follow a series of names which must be respelled to remove
the same action suffices for all the names (only a sample of
a rather long list is given here).
{d}{f}{l}{o}{a}{t} printf("%s",yytext+1);
Another list of names must have initial \fId\fR changed to initial \fIa\fR:
yytext[0] =+ \(fma\(fm \- \(fmd\(fm;
must have initial \fId\fR changed to initial \fIr\fR:
{d}1{m}{a}{c}{h} {yytext[0] =+ \(fmr\(fm \- \(fmd\(fm;
To avoid such names as \fIdsinx\fR being detected as instances
of \fIdsin\fR, some final rules pick up longer words as identifiers
and copy some surviving characters:
[A\-Za\-z][A\-Za\-z0\-9]\(** |
Note that this program is not complete; it
does not deal with the spacing problems in Fortran or
with the use of keywords as identifiers.
Left Context Sensitivity.
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.
to prior context, and there are several ways of handling
The \fI^\fR operator, for example, is a prior context operator,
recognizing immediately preceding left context just as \fI$\fR 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,
and the possibility of making multiple lexical analyzers all run
In each case, there are rules which recognize the need to change 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,
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
The current start condition may be changed at any time.
Finally, if the sets of rules for the different environments
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 \fImagic\fR to \fIfirst\fR on every line which began
with the letter \fIa\fR, changing \fImagic\fR to \fIsecond\fR on every line
which began with the letter \fIb\fR, and changing
\fImagic\fR to \fIthird\fR on every line which began
with the letter \fIc\fR. All other words and all other lines
These rules are so simple that the easiest way
to do this job is with a flag:
^a {flag = \(fma\(fm; ECHO;}
^b {flag = \(fmb\(fm; ECHO;}
^c {flag = \(fmc\(fm; ECHO;}
case \(fma\(fm: printf("first"); break;
case \(fmb\(fm: printf("second"); break;
\11\11 case \(fmc\(fm: printf("third"); break;
To handle the same problem with start conditions, each
start condition must be introduced to Lex in the definitions section
where the conditions may be named in any order.
The word \fIStart\fR may be abbreviated to \fIs\fR or \fIS\fR.
The conditions may be referenced at the
head of a rule with the <> brackets:
is a rule which is only recognized when Lex is in the
start condition \fIname1\fR.
To enter a start condition,
execute the action statement
which changes the start condition to \fIname1\fR.
To resume the normal state,
resets the initial condition
of the Lex automaton interpreter.
A rule may be active in several
is a legal prefix. Any rule not beginning with the
<> prefix operator is always active.
The same example as before can be written:
<AA>magic printf("first");
<BB>magic printf("second");
<CC>magic printf("third");
where the logic is exactly the same as in the previous
method of handling the problem, but Lex does the work
rather than the user's code.
The programs generated by Lex handle
character I/O only through the routines
Thus the character representation
provided in these routines
is accepted by Lex and employed to return
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.
is represented as the same form as the character constant
If this interpretation is changed, by providing I/O
routines which translate the characters,
it, by giving a translation table.
This table must be in the definitions section,
and must be bracketed by lines containing only
The table contains lines of the form
{integer} {character string}
which indicate the value associated with each character.
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
may be assigned the number 0, and no character may be
assigned a bigger number than the size of the hardware character set.
Summary of Source Format.
The general form of a Lex source file is:
The definitions section contains
Definitions, in the form ``name space translation''.
Included code, in the form ``space code''.
Included code, in the form
Start conditions, given in the form
Character set tables, in the form
number space character-string
Changes to internal array sizes, in the form
where \fInnn\fR is a decimal integer representing an array size
and \fIx\fR selects the parameter as follows:
k packed character classes
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
"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\(** 0,1,2, ... instances of x.
x+ 1,2,3, ... instances of x.
x/y an x but only if followed by y.
{xx} the translation of xx from the
x{m,n} \fIm\fR through \fIn\fR 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
to change the characters forthcoming
This is the only restriction on the user's ability to manipulate
the not-yet-processed input.
be obvious from the above, the outside of Lex
on Yacc and the inside on Aho's string matching routines.
Therefore, both S. C. Johnson and A. V. Aho
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.
B. W. Kernighan and D. M. Ritchie,
The C Programming Language,
Prentice-Hall, N. J. (1978).
Ratfor: A Preprocessor for a Rational Fortran,
Software \- Practice and Experience,
\fB5\fR, pp. 395-496 (1975).
Yacc: Yet Another Compiler Compiler,
Computing Science Technical Report No. 32,
.if \n(tm (also TM 75-1273-6)
A. V. Aho and M. J. Corasick,
Efficient String Matching: An Aid to Bibliographic Search,
B. W. Kernighan, D. M. Ritchie and K. L. Thompson,
Computing Science Technical Report No. 5,
Computing Science Technical Report No. 31,
.if \n(tm (also TM 75-1274-11)