Chapter 5. A Reference for Flex Specifications

In this chapter we describe the syntax of flex programs, along with the various options and support functions available. POSIX lex is almost an exact subset of flex, so we note which parts of flex are extensions beyond what POSIX requires.

After the section on the structure of a lex program, the sections in this chapter are in alphabetical order by feature.

Structure of a Flex Specification

A flex program consists of three parts: the definition section, the rules section, and the user subroutines.

...definition section ...
... rules section ...
... user subroutines ...

The parts are separated by lines consisting of two percent signs. The first two parts are required, although a part may be empty. The third part and the preceding %% line may be omitted.

Definition Section

The definition section can include options, the literal block, definitions, start conditions, and translations. (There is a section on each in this reference.) Lines that start with whitespace are copied verbatim to the C file. Typically this is used to include comments enclosed in /* and */, preceded by whitespace.

Rules Section

The rules section contains pattern lines and C code. Lines that start with whitespace, or material enclosed in %{ and %}, are C code that is copied verbatim to yylex(). C code at the beginning of the rules section will be at the beginning of yylex() and can include declarations of variables used in the scanner, and code to run each time yylex() ...

Get flex & bison now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.