Though originally distributed as proprietary software, some versions of Lex are now open source. Open source versions of Lex, based on the original proprietary code, are now distributed with open source operating systems such as OpenSolaris and Plan 9 from Bell Labs. One popular open source version of Lex, called flex, or the "fast lexical analyzer", is not derived from proprietary coding.
The structure of a Lex file is intentionally similar to that of a yacc file; files are divided into three sections, separated by lines that contain only two percent signs, as follows:
The definition section defines macros and imports header files written in C. It is also possible to write any C code here, which will be copied verbatim into the generated source file.
The rules section associates regular expression patterns with C statements. When the lexer sees text in the input matching a given pattern, it will execute the associated C code.
The C code section contains C statements and functions that are copied verbatim to the generated source file. These statements presumably contain code called by the rules in the rules section. In large programs it is more convenient to place this code in a separate file linked in at compile time.
Example of a Lex file
The following is an example Lex file for the flex version of Lex. It recognizes strings of numbers in the input, and simply prints them out. /*** Definition section ***/ /* This tells flex to read only one input file */ %option noyywrap %% /*** Rules section ***/ /* + matches a string of one or more digits */ + .|\n %% /*** C Code section ***/ int main
If this input is given to flex, it will be converted into a C file,. This can be compiled into an executable which matches and outputs strings of integers. For example, given the input: abc123z.!&*2gj6 the program will print: Saw an integer: 123 Saw an integer: 2 Saw an integer: 6
Lex and parser generators, such as Yacc or Bison, are commonly used together. Parser generators use a formal grammar to parse an input stream, something which Lex cannot do using simple regular expressions. It is typically preferable to have a parser be fed a token-stream as input, rather than having it consume the input character-stream directly. Lex is often used to produce such a token-stream. Scannerless parsing refers to parsing the input character-stream directly, without a distinct lexer.
Lex and make
is a utility that can be used to maintain programs involving Lex. Make assumes that a file that has an extension of .l is a Lex source file. The make internal macro LFLAGS can be used to specify Lex options to be invoked automatically by make.