




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































ISBN: 978-1-565-92000-
lex & yacc, 2nd Edition by
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
Revision History for the :
See http://oreilly.com/catalog/errata.csp?isbn=9781565920002 for release details.
Preface....................................................................... xi — What’s New in the Second Edition................................ xi — Scope of This Book............................................ xii — Availability of Lex and Yacc.................................... xiii — Sample Programs............................................. xiv — Conventions Used in This Handbook............................. xv — Acknowledgments............................................ xvi
1. Lex and Yacc................................................................ 1 — The Simplest Lex Program.................................... 2 — Recognizing Words with Lex.................................. 2 — Symbol Tables............................................... 8 — Grammars................................................. 13 — Parser-Lexer Communication................................ 13 — The Parts of Speech Lexer.................................... 14 — A Yacc Parser............................................... 16 — The Rules Section........................................... 17 — Running Lex and Yacc....................................... 20 — Lex vs. Hand-written Lexers.................................. 21 — Exercises................................................... 23 2. Using Lex.................................................................. 25 — Regular Expressions......................................... 26 — Examples of Regular Expressions.............................. 28 — A Word Counting Program.................................. 30 — Parsing a Command Line.................................... 36 — Start States................................................. 39
iii
Lex and yacc are tools designed for writers of compilers and interpreters, although they are also useful for many applications that will interest the noncompiler writer. Any application that looks for patterns in its input, or has an input or command language is a good candidate for lex and yacc. Furthermore, they allow for rapid application pro‐ totyping, easy modification, and simple maintenance of programs. To stimulate your imagination, here are a few things people have used lex and yacc to develop:
We have made extensive revisions in this new second edition. Major changes include:
xi
Chapter 1, Lex and Yacc , gives an overview of how and why lex and yacc are used to create compilers and interpreters, and demonstrates some small lex and yacc applica‐ tions. It also introduces basic terms we use throughout the book.
Chapter 2, Using Lex , describes how to use lex. It develops lex applications that count words in files, analyze program command switches and arguments, and compute sta‐ tistics on C programs.
Chapter 3, Using Yacc , gives a full example using lex and yacc to develop a fully functional desktop calculator.
Chapter 4, A Menu Generation Language , demonstrates how to use lex and yacc to develop a menu generator.
Chapter 5, Parsing SQL , develops a parser for the full SQL relational data base language. First we use the parser as a syntax checker, then extend it into a simple preprocessor for SQL embedded in C programs.
Chapter 6, A Reference for Lex Specifications , and Chapter 7, A Reference for Yacc Gram‐ mars , provide detailed descriptions of the features and options available to the lex and yacc programmer. These chapters and the two that follow provide technical information for the now experienced lex and yacc programmer to use while developing new lex and yacc applications.
Chapter 8, Yacc Ambiguities and Conflicts , explains yacc ambiguities and conflicts, which are problems that keep yacc from parsing a grammar correctly. It then develops methods that can be used to locate and correct such problems.
Chapter 9, Error Reporting and Recovery , discusses techniques that the compiler or interpreter designer can use to locate, recognize, and report errors in the compiler input.
Appendix A, AT&T Lex , describes the command-line syntax of AT&T lex and the error messages it reports and suggests possible solutions.
Appendix B, AT&T Yacc , describes the command-line syntax of AT&T yacc and lists errors reported by yacc. It provides examples of code which can cause such errors and suggests possible solutions.
xii | Preface
BSD and GNU Project also distribute flex (Fast Lexical Analyzer Generator), “a rewrite of lex intended to right some of that tool’s deficiencies,” according to its reference page. Flex was originally written by Jef Poskanzer; Vern Paxson and Van Jacobson have con‐ siderably improved it and Vern currently maintains it. Appendix E covers topics specific to flex.
There are at least two versions of lex and yacc available for MS-DOS and OS/2 machines. MKS (Mortice Kern Systems Inc.), publishers of the MKS Toolkit, offers lex and yacc as a separate product that supports many PC C compilers. MKS lex and yacc comes with a very good manual. Appendix F covers MKS lex and yacc. Abraxas Software publishes PCYACC, a version of lex and yacc which comes with sample parsers for a dozen widely used programming languages. Appendix G covers Abraxas’ version lex and yacc.
The programs in this book are available free from UUNET (that is, free except for UUNET’s usual connect-time charges). If you have access to UUNET, you can retrieve the source code using UUCP or FTP. For UUCP, find a machine with direct access to UUNET, and type the following command:
uucp uunet!~/nutshell/lexyacc/progs.tar.Z yourhost!˜/yourname/
The backslashes can be omitted if you use the Bourne shell (sh) instead of the C shell (csh). The file should appear some time later (up to a day or more) in the directory /usr/ spool/uucppublic/ yourname. If you don’t have an account but would like one so that you can get electronic mail, then contact UUNET at 703-204-8000.
To use ftp, find a machine with direct access to the Internet. Here is a sample session, with commands in boldface.
% ftp ftp.oreilly.com Connected to ftp.oreilly.com. 220 FTP server (Version 5.99 Wed May 23 14:40:19 EDT 1990) ready. Name (ftp.oreilly.com:yourname): anonymous 331 Guest login ok, send ident as password. Password: [email protected] (use your user name and host here) 230 Guest login ok, access restrictions apply. ftp> cd published/oreilly/nutshell/lexyacc 250 CWD command successful. ftp> binary ( you must specify binary transfer for compressed files ) 200 Type set to I. ftp> get progs.tar.Z 200 PORT command successful. 150 Opening BINARY mode data connection for progs.tar.Z.
xiv | Preface
226 Transfer complete. ftp> quit 221 Goodbye. %
The file is a compressed tar archive. To extract files once you have retrieved the archive, type:
% zcat progs.tar.Z | tar xf -
System V systems require the following tar command instead:
% zcat progs.tar.Z | tar xof -
The following conventions are used in this book:
Bold is used for statements and functions, identifiers, and program names.
Italic is used for file, directory, and command names when they appear in the body of a paragraph as well as for data types and to emphasize new terms and concepts when they are introduced.
Constant Width is used in examples to show the contents of files or the output from commands.
Constant Bold is used in examples to show command lines and options that you type literally.
Quotes are used to identify a code fragment in explanatory text. System messages, signs, and symbols are quoted as well.
% is the Shell prompt.
[] surround optional elements in a description of program syntax. (Don’t type the brackets themselves.)
Preface | xv
CHAPTER 1
Lex and yacc help you write programs that transform structured input. This includes an enormous range of applications—anything from a simple text search program that looks for patterns in its input file to a C compiler that transforms a source program into optimized object code.
In programs with structured input, two tasks that occur over and over are dividing the input into meaningful units, and then discovering the relationship among the units. For a text search program, the units would probably be lines of text, with a distinction between lines that contain a match of the target string and lines that don’t. For a C program, the units are variable names, constants, strings, operators, punctuation, and so forth. This division into units (which are usually called tokens) is known as lexical analysis, or lexing for short. Lex helps you by taking a set of descriptions of possible tokens and producing a C routine, which we call a lexical analyzer, or a lexer, or a scanner for short, that can identify those tokens. The set of descriptions you give to lex is called a lex specification.
The token descriptions that lex uses are known as regular expressions, extended versions of the familiar patterns used by the grep and egrep commands. Lex turns these regular expressions into a form that the lexer can use to scan the input text extremely fast, independent of the number of expressions that it is trying to match. A lex lexer is almost always faster than a lexer that you might write in C by hand.
As the input is divided into tokens, a program often needs to establish the relationship among the tokens. A C compiler needs to find the expressions, statements, declarations, blocks, and procedures in the program. This task is known as parsing and the list of rules that define the relationships that the program understands is a grammar. Yacc takes a concise description of a grammar and produces a C routine that can parse that grammar, a parser. The yacc parser automatically detects whenever a sequence of input tokens matches one of the rules in the grammar and also detects a syntax error whenever its
1
input doesn’t match any of the rules. A yacc parser is generally not as fast as a parser you could write by hand, but the ease in writing and modifying the parser is invariably worth any speed loss. The amount of time a program spends in a parser is rarely enough to be an issue anyway.
When a task involves dividing the input into units and establishing some relationship among those units, you should think of lex and yacc. (A search program is so simple that it doesn’t need to do any parsing so it uses lex but doesn’t need yacc. We’ll see this again in Chapter 2, where we build several applications using lex but not yacc.)
By now, we hope we’ve whetted your appetite for more details. We do not intend for this chapter to be a complete tutorial on lex and yacc, but rather a gentle introduction to their use.
This lex program copies its standard input to its standard output:
%% .|\n ECHO; %%
It acts very much like the UNIX cat command run with no arguments.
Lex automatically generates the actual C program code needed to handle reading the input file and sometimes, as in this case, writing the output as well.
Whether you use lex and yacc to build parts of your program or to build tools to aid you in programming, once you master them they will prove their worth many times over by simplifying difficult input handling problems, providing more easily maintainable code base, and allowing for easier “tinkering” to get the right semantics for your program.
Let’s build a simple program that recognizes different types of English words. We start by identifying parts of speech (noun, verb, etc.) and will later extend it to handle mul‐ tiword sentences that conform to a simple English grammar.
We start by listing a set of verbs to recognize:
is am are were was be beingbeen do does did will wouldshouldcan could has have had go
2 | Chapter 1: Lex and Yacc