About this book
Compilers: Principles, Techniques, and Tools was published by Addison-Wesley in 1986. Its authors were Alfred V. Aho, Ravi Sethi and Jeffrey D. Ullman. Almost everyone who has studied it calls it the dragon book, because its cover shows a knight in armour facing a dragon. The knight carries a shield and a lance labelled with the tools of the trade, and the dragon is labelled with the difficulty of the task. The picture is a joke, but it is also a fair summary of the book's attitude. Building a compiler used to be a heroic and risky project. The book claims that with the right theory and the right techniques it becomes an engineering task that a trained person can carry out with confidence.
The question the book sets out to answer is simple to state. A programmer writes text in a language designed for people. A machine executes instructions designed for circuits. Something has to translate the first into the second, faithfully and efficiently, for every program anyone might write. How do you build that something so that it is correct, so that it can be understood and maintained, and so that the code it produces runs well? The book's answer is that translation can be broken into a series of well-defined stages, and that most of those stages rest on mathematical ideas solid enough to be automated.
The 1986 volume was not the first of its line. In 1977 Aho and Ullman had published Principles of Compiler Design, whose cover also showed a dragon, coloured green. The 1986 book is a rewriting and a large expansion of that earlier work, with Sethi joining as a third author. Readers began to speak of the green dragon and the red dragon to tell the editions apart. In 2006 a second edition of the 1986 book appeared with Monica S. Lam added as an author, and it is usually called the purple dragon. This study edition is about the 1986 book, though it mentions the later one where the difference matters.
The intended reader was a university student in computer science, typically in an advanced undergraduate or first graduate course, and the working programmer who wanted to understand the tools beneath their feet. The book assumes the reader can program, knows basic data structures, and is willing to work through formal definitions. It does not assume prior knowledge of automata theory or formal languages, though a reader who has met them will move faster. It was written in a particular moment: compilers had become routine products, Unix had made tools like Lex and Yacc widely available, and the theory of parsing had matured into a settled body of knowledge. The book gathers that settled knowledge and presents it as a whole.
It is worth being clear about what the book is not. It is not a manual for one compiler or one language. It is not a book about the design of programming languages, though it touches on design choices when they affect translation. It is not mainly about interpreters or virtual machines, which became far more important in later decades. It is a book about the translation pipeline as a whole, with special depth on the front end, where text is read and understood, and substantial coverage of the back end, where code is produced and improved.
The authors
Alfred Aho was born in 1941 in Timmins, Ontario, in Canada. He studied engineering physics at the University of Toronto and earned his doctorate at Princeton, with a thesis on indexed grammars, a class of formal grammars more powerful than the context-free ones. He then spent many years at Bell Laboratories, the research arm of the American telephone system, which in those years was also the home of Unix and C. At Bell Labs he wrote or co-wrote several tools that programmers still use without thinking. He wrote the original versions of egrep and fgrep, tools for searching text by pattern. He was one of the three authors of the AWK language, together with Peter Weinberger and Brian Kernighan; the language's name is made of their initials. With Margaret Corasick he devised the Aho-Corasick algorithm for finding many patterns in a text at once. He later became a professor at Columbia University.
Jeffrey Ullman was born in 1942. He also took his doctorate at Princeton, worked for a time at Bell Labs, taught at Princeton, and moved to Stanford University, where he spent most of his career. Ullman is one of the most prolific textbook authors in computer science. With John Hopcroft he wrote the standard text on automata and formal languages, which sits in this same bay of the shelf. He wrote widely used books on database systems and on data mining. His textbooks share a style: careful definitions, many worked examples, a steady path from theory to algorithm, and large sets of exercises. Many of his doctoral students went on to shape the field.
In 2020 Aho and Ullman jointly received the Turing Award, the highest honour in computer science. The citation recognised their work on the fundamental algorithms and theory underlying programming language implementation, and their books, which educated generations of computer scientists. It is unusual for the award to mention textbooks so directly. In their case the books were part of the contribution, because they turned a scattered research literature into a common curriculum.
Ravi Sethi was also at Bell Labs. His name is attached to the Sethi-Ullman algorithm, a method for generating code for arithmetic expressions that uses the fewest registers possible, by deciding which branch of an expression tree to evaluate first. He later wrote a well-known textbook on programming languages and held senior research management posts. His presence in the dragon book shows in its attention to semantics, type checking and code generation, areas where the 1977 book had been thinner.
The three authors shared an outlook formed partly by Bell Labs. That culture valued small tools that did one job well, clear specifications, and theory that paid its way in working programs. The dragon book carries that outlook. It treats a compiler not as a single mysterious program but as a pipeline of components, many of which can be generated from compact descriptions by other programs. That idea, that you can write a grammar and get a parser, was itself a product of the Unix environment the authors worked in.
The shape of the argument
The book is organised around the structure of a compiler. Early material gives an overview of the whole pipeline and a small, complete translator for simple expressions, so the reader sees every stage working together before any of them is studied in depth. The middle of the book is the front end: how characters become tokens, how tokens become structure, and how that structure is given meaning and checked. The later part of the book is the back end and its surroundings: how programs are laid out in memory while they run, how intermediate code is produced, how target code is generated, and how code is improved by analysis. The final material surveys real compilers and practical concerns.
The movement of the argument is from the most formal parts of the problem to the least formal. Lexical analysis rests on regular languages and finite automata, which are completely understood. Parsing rests on context-free grammars, which are well understood but already require care: some grammars are ambiguous, some cannot be parsed by simple methods, and the choice of method matters. Semantic analysis and translation are less uniform; they are organised by a device called syntax-directed translation, which hangs computations on the grammar so that the structure discovered by parsing drives the rest. Code generation and optimisation are the least clean. Here the problems are often provably hard, and the book offers heuristics, frameworks and careful engineering rather than complete solutions.
This shape is itself a teaching. The reader learns where the field has full mathematical control and where it has only good methods. In the front end, a correct specification can be turned mechanically into a correct program. In the back end, the best possible output usually cannot be computed in reasonable time, so the compiler writer chooses among approximations. Much of the book's value lies in showing that both kinds of knowledge are needed, and in showing how the formal parts make the informal parts manageable.
Running through the whole book is a second theme: the separation of a compiler into a front end that depends on the source language and a back end that depends on the target machine, joined by an intermediate representation that depends on neither. This separation is what allows one front end to serve many machines and one back end to serve many languages. The book does not invent the idea, but it builds its whole presentation on it, and later compiler infrastructures grew directly from it.
The book is also heavy with exercises. Many are routine checks of understanding; some are small research problems; some are marked as difficult. For many readers the exercises are where the learning actually happens. Constructing a parsing table by hand once, or computing a data-flow solution for a small graph on paper, teaches more than any amount of reading about it.
Idea one: translation in phases
The first idea is that translation should be split into phases, each with a narrow job and a clear interface to the next. A typical list runs as follows. The lexical analyser reads characters and groups them into tokens such as identifiers, numbers, keywords and operators. The syntax analyser, or parser, arranges tokens into a tree that reflects the grammar of the language. The semantic analyser checks that the tree makes sense, for example that variables are declared and that types match. An intermediate code generator turns the tree into a simpler, machine-independent form. An optimiser improves that form. A code generator turns it into instructions for a particular machine. Alongside all of these sit a symbol table, which records what is known about each name, and error handling, which tries to report problems clearly and continue.
An analogy helps. Think of translating a legal contract from one language to another. A careless translator reads a sentence and writes a sentence. A careful firm splits the work. One person transcribes the document cleanly, fixing smudges and settling what each word is. Another works out the grammatical structure of each clause. Another checks that defined terms are used consistently. Another drafts the translation in a neutral outline. Another polishes it for style and concision. Each person can be trained, checked and replaced independently. The cost is coordination. The benefit is that errors can be located and each job can be done well.
Phases are logical, not necessarily physical. A real compiler may run the lexer on demand whenever the parser asks for the next token, and it may perform semantic checks during parsing rather than afterwards. The book distinguishes phases, which are conceptual steps, from passes, which are actual traversals of the program or its representation. Early compilers on machines with little memory used many passes, writing intermediate results to tape. Later compilers could hold whole programs in memory and fuse phases freely. The conceptual separation survives regardless.
This idea is often confused with a claim that compilers must be built as a strict sequence of independent programs. That is not the claim. The claim is that thinking in phases makes the problem tractable, that each phase can be specified precisely, and that a good implementation respects the boundaries even when it interleaves the work. The idea leads directly to compiler generators, because once a phase has a precise specification, a program can often construct that phase automatically.
The symbol table and the cost of names
One component touches every phase: the symbol table. Each time the lexer meets a name, the compiler must find out whether it has seen that name before and, if so, what it knows about it: whether it is a variable or a function, what its type is, where it will be stored, in which block it was declared. The parser and semantic analyser add facts; the code generator reads them. Because these lookups happen constantly, the book discusses how to make them fast, typically with hash tables, and how to handle scopes, where the same name means different things in different blocks. A common method keeps a separate table for each scope and searches from the innermost outward, discarding a scope's table when the block ends.
This small matter carries a general lesson. In any system that translates between representations, the bookkeeping that connects the representations is as important as the transformations themselves. A compiler that parsed perfectly but lost track of which declaration a name referred to would produce nonsense. The symbol table is that bookkeeping, and the book's insistence on treating it as a first-class component, with its own data structures and its own design choices, reflects long practical experience.
Idea two: tokens, patterns and finite automata
The lexical analyser is the simplest phase and the most mechanical. It must decide, as it reads a stream of characters, where each token begins and ends and what kind of token it is. The book shows that the patterns describing tokens, such as an identifier being a letter followed by letters or digits, are naturally written as regular expressions. A regular expression is a small formula built from characters using three operations: concatenation, choice, and repetition. Every such formula describes a set of strings, called a regular language.
The central result is that regular expressions and finite automata describe exactly the same languages. A finite automaton is a machine with a fixed number of states that reads one character at a time and moves between states according to a table. Some states are accepting; if the machine is in one when a token ends, the token matches. The book shows how to turn a regular expression into a nondeterministic automaton, in which a state may have several possible next moves, and then how to turn that into a deterministic automaton, in which each state has exactly one next move per character. The second step is called the subset construction, because each state of the deterministic machine stands for a set of states of the nondeterministic one. It then shows how to minimise the result.
The practical upshot is that a lexer can be produced from a list of patterns and actions. This is what the Unix tool Lex does, and the book discusses it directly. You write a specification saying, in effect, when you see this pattern, return this kind of token. Lex builds the automaton and emits a program that runs it. Two rules settle ambiguities: take the longest possible match, and if two patterns match the same longest string, prefer the one listed first. These rules explain why a keyword like while is recognised as a keyword rather than an identifier, provided the keyword pattern comes first.
A useful example from everyday computing is searching text. When you type a pattern into a search tool and it scans a large file almost instantly, a similar construction is usually at work. The same theory that builds a lexer builds a fast text searcher. That is not a coincidence in this book's case: Aho's own tools for pattern search came from the same body of ideas. The reader who masters this chapter has learned something that applies far beyond compilers.
The common confusion here is to think that regular expressions as used in modern programming languages are the same thing as the regular expressions of theory. Many modern pattern libraries add features such as back-references, which let a pattern require that a later part repeat an earlier match. Those features take the patterns outside the class of regular languages, and they cannot always be matched by a finite automaton; matching them can become very slow. The theoretical regular expressions in this book have no such features, which is exactly why they can be compiled into fast, predictable machines.
Idea three: grammars and the shape of programs
Tokens alone do not capture the structure of a program. Expressions nest inside expressions; statements nest inside blocks; blocks nest inside functions. To describe this nesting the book uses context-free grammars. A grammar is a set of rules, each saying that a certain kind of phrase can be built from a sequence of smaller pieces. For example, a rule might say that an expression can be an expression, a plus sign, and a term. Applying rules repeatedly, starting from a start symbol, generates exactly the strings of the language. The structure of that generation, drawn as a tree, is the parse tree.
Grammars of this kind were first used to define a real programming language in the report on Algol 60, which used a notation now called Backus-Naur Form. Their mathematical study goes back to Noam Chomsky's work on the structure of natural languages in the 1950s. The dragon book takes both strands for granted and focuses on what a compiler writer needs: how to write grammars that say what you mean, how to recognise when they do not, and how to transform them into forms a parser can use.
Two problems receive particular care. The first is ambiguity. A grammar is ambiguous if some string has two different parse trees. The classic example is arithmetic: does one minus two minus three mean the first subtraction is done first or the second? A careless grammar allows both readings. The book shows how to rewrite grammars to encode precedence and associativity, so that multiplication binds tighter than addition and subtraction groups to the left. The second classic example is the dangling else: in a nested if statement with one else branch, which if does the else belong to? The book shows both how to rewrite the grammar to settle this and how parser generators can settle it by a rule instead.
The second problem is that some grammars, though unambiguous, are awkward for particular parsing methods. A rule whose right side begins with the same symbol as its left side, called left recursion, sends a naive top-down parser into an endless loop. The book gives a mechanical transformation that removes left recursion. Similarly, two rules that begin the same way confuse a parser that must choose between them by looking at one token; the remedy, called left factoring, pulls the common beginning out. These transformations are a recurring source of exercises, and they teach a lesson about formal descriptions generally: the same language can be described in many ways, and the choice of description matters to the machinery that uses it.
The idea is easily confused with the stronger claim that context-free grammars describe everything about a programming language. They do not. Whether a variable has been declared before use, or whether a function is called with the right number of arguments, cannot be expressed in a context-free grammar in any practical way. Those checks belong to semantic analysis. The grammar describes the skeleton; meaning is added later.
Idea four: two ways to parse
Once a grammar is in hand, the parser must discover, for a given sequence of tokens, the parse tree that the grammar assigns to it. There are two broad strategies, and the book treats both thoroughly. Top-down parsing starts from the start symbol and tries to grow the tree downward to match the input. Bottom-up parsing starts from the tokens and tries to assemble them upward into larger phrases until the start symbol is reached. The difference is like the difference between planning a journey from the destination backwards and building it step by step from where you stand.
Top-down and predictive parsing
The simplest top-down method is recursive descent. Each kind of phrase in the grammar becomes a function. The function for statements looks at the current token and decides which kind of statement it is facing, then calls the functions for the pieces of that statement in turn. When the decision can always be made by looking at a single upcoming token, the parser never needs to back up, and the grammar is called LL(1): the input is read left to right, the parser builds a leftmost derivation, and one token of lookahead suffices. The book shows how to compute two sets for each grammar symbol, usually called FIRST and FOLLOW, which tell the parser which tokens can begin a phrase and which can come after it. From these sets one can build a table that drives a general predictive parser, or check that a hand-written recursive descent parser will make correct choices.
Recursive descent has an enduring appeal. It is easy to write by hand, easy to read, and easy to extend with good error messages. Many production compilers today use hand-written recursive descent parsers for exactly these reasons. Its weakness is that it accepts a narrower class of grammars and requires the grammar to be massaged first, removing left recursion and factoring common prefixes.
Bottom-up and LR parsing
Bottom-up parsing, in the form the book develops most fully, is shift-reduce parsing. The parser keeps a stack. At each step it either shifts the next token onto the stack or recognises that the top of the stack matches the right side of some grammar rule and reduces it, replacing those symbols with the rule's left side. The hard question is when to shift and when to reduce, and which rule to reduce by. LR parsing answers it with a finite automaton that tracks, in its state, everything relevant about what has been seen so far. The idea of LR parsing is due to Donald Knuth, who introduced it in 1965 and showed that it handles a very large class of grammars deterministically.
The book develops three ways of building LR parsing tables, in increasing power and size. Simple LR, or SLR, is the easiest to construct and works for many grammars. Canonical LR is the most powerful but can produce enormous tables. LALR, which stands for lookahead LR, merges states of the canonical construction in a way that keeps tables about the size of SLR tables while handling most practical grammars. LALR is the method used by Yacc, the parser generator written by Stephen Johnson at Bell Labs, and the book explains how Yacc works and how to use it. When a grammar does not fit the method, the generator reports a conflict: a state in which it cannot decide between shifting and reducing, or between two reductions. Learning to read and resolve these conflicts is a practical skill the book teaches carefully.
A frequent misunderstanding is that bottom-up parsing is simply better because it is more powerful. Power is only one consideration. LR parsers are generated, so their behaviour is harder to inspect, and their error messages are harder to make friendly. Top-down parsers are written by people, so they can be shaped around the needs of the user. The book's thoroughness on LR methods reflects the state of the art in 1986, when parser generators were the obvious way to build a front end. Later practice swung partly back toward hand-written parsers, but the theory remains the clearest way to understand what any parser is doing.
Error recovery deserves a mention. A compiler that stops at the first error is unhelpful; one that produces a cascade of meaningless messages after the first error is worse. The book discusses panic-mode recovery, in which the parser skips tokens until it finds one, such as a semicolon, that is likely to start a fresh construct, and other strategies that try to repair the input locally. No method is perfect, because the parser cannot know what the programmer meant. The discussion is useful mainly for showing that error handling is a design problem in its own right, not an afterthought.
Idea five: syntax-directed translation
Parsing produces structure. A compiler needs more than structure; it needs to compute things from it: the type of each expression, the value of constants, the intermediate code for each statement. The book's central device for this is syntax-directed translation. The idea is to attach to each grammar symbol some attributes, which are values to be computed, and to attach to each grammar rule some semantic rules saying how to compute the attributes of that rule's symbols from one another.
Attributes come in two kinds. A synthesized attribute of a node is computed from the attributes of its children. The value of an arithmetic expression is synthesized: you compute the values of the parts and combine them. An inherited attribute of a node is computed from its parent or its siblings. The declared type in a declaration that lists several variables is naturally inherited: the type is written once at the front, and each variable in the list receives it from the context. A grammar with attributes and rules for computing them is called an attribute grammar, a notion introduced by Knuth in 1968.
The value of this device is that it ties meaning to form. Instead of writing a separate program that walks a tree and does ad hoc things, the compiler writer states, rule by rule, what each construct means. The order of evaluation follows from the dependencies among attributes. The book identifies restricted classes of definitions, such as those using only synthesized attributes, that can be evaluated during parsing itself, either in a bottom-up parser as reductions happen or in a top-down parser as functions return. This is how a compiler can build a syntax tree, check types and emit intermediate code in the same single pass that reads the source.
An everyday analogy is a spreadsheet. Each cell holds a formula referring to other cells. You never write the order in which cells are computed; the spreadsheet works it out from the references. Syntax-directed translation is a spreadsheet laid over a parse tree, where the formulas are attached to grammar rules and repeated wherever those rules are used. Like a spreadsheet, it fails if the formulas refer to one another in a circle, and the theory includes tests for such circularity.
Syntax-directed translation is often confused with the narrower idea of putting actions in a parser generator's input file. The actions in a Yacc specification are one implementation of it, but the idea is more general: it is a way of specifying a translation declaratively. Where it leads is to the view of a compiler as a series of attribute computations over trees, and to the many later tools that generate analysers and transformers from such specifications.
Idea six: meaning, types and the running program
Two subjects sit between understanding a program and producing code for it. The first is static checking, chiefly type checking. The second is the run-time environment: how the program's data and control will be arranged in memory when it runs. The book treats both, and each shows a different side of what a compiler must know.
Type checking
A type system assigns a type to each expression and rules out combinations that make no sense, such as adding a string to an array. The book presents type checking as a syntax-directed computation: the type of a larger expression is computed from the types of its parts by rules attached to the grammar. It discusses type expressions for structured types such as arrays, records, pointers and functions, and the question of when two types count as the same. Two answers are common. Under structural equivalence, two types are the same if they are built the same way. Under name equivalence, they are the same only if they have the same declared name. Real languages mix these rules, and the choice affects what programs are accepted.
The book also covers type conversions, which a compiler inserts automatically, such as turning an integer into a floating-point number before adding it to one, and overloading, where one symbol such as plus means different operations for different types. It introduces polymorphic functions, which work uniformly over many types, and the unification algorithm used to infer their types. This material links the compiler to the theory of programming languages and anticipates the later growth of type inference in languages descended from ML.
Run-time environments
A compiler must decide where every value will live while the program runs. Global data can be placed at fixed addresses. Local variables of a procedure need fresh storage for each call, because a procedure can be called again before an earlier call finishes, as in recursion. The standard solution is a stack of activation records, sometimes called frames: each call pushes a record holding its parameters, local variables, saved registers and return address, and each return pops it. Data that must outlive the call that created it goes on a heap.
The book explains how nested procedures, found in languages like Pascal, need extra machinery so that an inner procedure can reach the variables of the outer one. It describes access links and displays, two ways of finding the right frame. It explains different ways of passing parameters: by value, by reference, and by name, the last of which Algol 60 used and which behaves surprisingly. These matters seem far from the formal theory of parsing, but they are where language design meets the machine. A reader who understands activation records understands what a stack overflow is, why recursion has a cost, and why closures in modern languages need their environments stored on the heap.
Idea seven: intermediate code and code generation
Between the source program and the target machine stands an intermediate representation. The book favours three-address code, in which each instruction performs at most one operation on at most two operands and stores the result in a third location. A complicated expression is broken into a sequence of such simple steps, with temporary names for the intermediate results. Three-address code is easy to generate from syntax trees, easy to analyse, and close enough to real machines that the final translation is straightforward.
The book shows how to translate each kind of construct: expressions, assignments, array references, boolean expressions and control flow. Boolean expressions get special attention because they can be translated in two ways: as values computed like numbers, or as jumps that go one way if the condition holds and another if it does not. The jumping form allows short-circuit evaluation, in which the second half of an and is skipped if the first half is false. The book introduces backpatching, a technique for generating jumps whose targets are not yet known by leaving holes in the code and filling them in once the targets are fixed. It is a small idea, but it shows how a one-pass compiler can produce control flow without building a full tree.
Code generation proper turns the intermediate code into instructions for a real machine. Three problems dominate. Instruction selection chooses which machine instructions implement each intermediate operation; a machine often offers several ways to do the same thing, at different costs. Register allocation decides which values live in the processor's few fast registers and which must be kept in slower memory. Instruction ordering decides the sequence of operations, which affects how many registers are needed and, on pipelined machines, how fast the code runs. The book shows that doing these jobs optimally is hard in general, and presents practical methods: a simple code generator that tracks where each value currently lives, tree-based methods that find good code for expressions, the Sethi-Ullman numbering for register needs, and dynamic programming for instruction selection on expression trees.
The book also introduces basic blocks and flow graphs, which become the foundation for the optimisation chapters. A basic block is a straight run of instructions with one entry at the top and one exit at the bottom. A flow graph connects blocks by the possible jumps between them. Within a block, the book represents computations as a directed acyclic graph, which exposes common subexpressions directly: if the same operation is applied to the same operands twice, the graph shows one node used twice. Peephole optimisation, which slides a small window over the generated code looking for wasteful patterns such as a store followed immediately by a load of the same value, is presented as a cheap and effective final polish.
Idea eight: data-flow analysis and optimisation
The longest single topic in the book is code optimisation, and its heart is data-flow analysis. The word optimisation is a slight misnomer: compilers do not find optimal code, they improve it. The improvements are transformations that preserve the program's meaning while reducing its cost. Common examples include eliminating a computation whose result is already available, removing code whose result is never used, replacing an expensive operation with a cheaper one such as a multiplication with an addition inside a loop, and moving a computation whose value does not change out of a loop so that it is done once instead of many times.
Each transformation is safe only under certain conditions, and checking those conditions requires knowing facts about the program at every point. Is this variable's value used later? Which assignments might have produced the value of this variable here? Has this expression already been computed on every path that reaches this point? Data-flow analysis computes such facts systematically. For each basic block it describes how the block changes the facts, and then it propagates information around the flow graph until nothing changes. Liveness analysis runs backward from uses; reaching definitions and available expressions run forward from assignments.
The important insight, which the book presents in a general framework, is that all these analyses share one structure. The facts form a lattice, an ordered set in which any two elements have a well-defined combination. Each block applies a function to the facts. Where paths meet, facts are combined. If the functions behave well, an iterative algorithm is guaranteed to stop, and it computes a solution that is safe, meaning it never licenses a transformation that would change the program's behaviour. This framework goes back to work by Gary Kildall and by Frances Allen and John Cocke in the late 1960s and early 1970s; the book makes it teachable.
A small example shows the reasoning. Suppose a loop runs a thousand times and, inside it, computes the address of the start of an array by adding a fixed base to a fixed offset. Neither value changes inside the loop. A data-flow analysis can prove that, and the optimiser can move the addition before the loop, saving nine hundred and ninety-nine additions. Now suppose that somewhere in the loop there is a call to a function that might change the offset through a pointer. The analysis must take that into account, and if it cannot prove the function harmless, it must leave the code alone. Much of the subtlety of optimisation lies in this caution, and in the analysis of pointers and procedure calls, which the book discusses as harder problems.
The book also covers loops: how to find them in a flow graph using the notion of dominators, where one block dominates another if every path from the entry to the second passes through the first. Natural loops are identified by back edges, which jump to a dominator. Induction variables, which change by a fixed amount each time round a loop, are detected and simplified. These ideas are the classical toolkit of an optimising compiler, and every later book on optimisation starts from them.
Optimisation is often confused with making programs fast in general. A compiler can only improve the code it is given; it cannot change an inefficient algorithm into an efficient one. Replacing a slow sorting method with a fast one is the programmer's job, a matter for the algorithms textbook in this bay. The optimiser works at the level of individual computations and loops. The two kinds of improvement multiply, and neither substitutes for the other.
Idea nine: tools that build tools
A thread runs through the whole book that deserves its own chapter: the idea that parts of a compiler can be generated from specifications. Lex takes regular expressions and produces a lexer. Yacc takes a grammar with attached actions and produces a parser. The book also discusses, more briefly, the idea of generating code generators from descriptions of the target machine, and data-flow engines from descriptions of the analysis. The general name for such programs is compiler-compilers, or translator writing systems.
The reason this matters is leverage. A hand-written parser for a large language might run to thousands of lines, every one of which could contain a mistake. A grammar for the same language might run to a few hundred lines, each of which reads almost like the language manual. If the generator is correct, the parser is correct whenever the grammar is. The specification becomes the source of truth, and changing the language means changing the grammar, not hunting through code. The same reasoning lies behind many modern tools: database query planners generated from rules, protocol parsers generated from message descriptions, and the many domain-specific languages that companies build for configuration and data processing.
There is a further lesson. A compiler generator is itself a compiler: it reads a specification language and translates it into a program. Lex compiles regular expressions into automata; Yacc compiles grammars into tables. The techniques of the book apply to themselves. This reflexive quality is part of what makes the subject intellectually satisfying, and it connects to the deeper theme, explored in other books on this shelf, that programs can treat other programs as data.
The limits are also instructive. Generated components are only as good as their specifications, and some things resist specification. Good error messages, sensible recovery from mistakes, and fast incremental reparsing in an editor are all harder to get from a generator than from careful hand-written code. Generators also impose their own formalism: a language whose natural grammar does not fit LALR must be bent to fit. The book is honest about these trade-offs, though its overall stance favours generation.
The tradition around it
Compilers began in the 1950s. Grace Hopper's team built early systems that translated symbolic code, and John Backus led the IBM team that delivered the first Fortran compiler in 1957. That compiler was remarkable for the quality of its output; its authors knew that programmers would not accept a high-level language if the code it produced was much slower than hand-written assembly. From the start, then, compilers combined two problems: understanding the source and producing good code. The 1960s brought Algol and the formal description of syntax, the theory of context-free languages, and Knuth's LR parsing. The 1970s brought data-flow analysis, the Unix tools, and the first textbooks that tried to unify the field, including Aho and Ullman's own two-volume Theory of Parsing, Translation, and Compiling and their 1977 green dragon.
The dragon book of 1986 stands at the point where this material had settled into a curriculum. Its contemporaries included other compiler texts with more practical or more language-specific emphases, and Niklaus Wirth's short books on compiler construction, which showed how a small, carefully designed language could be compiled by a small, carefully written recursive descent compiler. Wirth's approach and the dragon book's approach make an instructive pair. Wirth asks what you can leave out; the dragon book asks what you need to know to handle anything.
After 1986 the field moved in directions the book only partly anticipated. Static single assignment form, introduced by researchers at IBM around 1989 to 1991, became the standard intermediate representation for optimising compilers, because it makes many data-flow facts explicit in the program text. Register allocation by graph colouring, developed by Gregory Chaitin and others in the early 1980s, became standard. Later textbooks such as Andrew Appel's Modern Compiler Implementation series, Steven Muchnick's Advanced Compiler Design and Implementation, and Keith Cooper and Linda Torczon's Engineering a Compiler covered these developments. The 2006 purple dragon added substantial material on instruction-level parallelism, parallelism across loops, locality of memory access and interprocedural analysis, reflecting the work of Monica Lam. Later still, open compiler infrastructures such as GCC and LLVM made the front-end, intermediate-representation, back-end split into a public platform used by many languages.
Within this bay of the shelf, the book has clear neighbours. Introduction to Automata Theory, Languages, and Computation by Hopcroft and Ullman supplies the formal theory of regular and context-free languages that the dragon book uses; the two books share an author and many habits. Introduction to the Theory of Computation by Michael Sipser covers the same theory more briskly. The Undecidable, edited by Martin Davis, collects the original papers that showed what no program can decide, which explains why optimisation can never be perfect: questions such as whether a piece of code is ever executed are undecidable in general. The C Programming Language by Kernighan and Ritchie describes a language whose compilers were built in the same Bell Labs culture. Structure and Interpretation of Computer Programs by Abelson and Sussman approaches the same subject from the opposite direction, through interpreters written in a small language, and ends with a compiler of its own. Computer Architecture: A Quantitative Approach by Hennessy and Patterson describes the machines that a back end targets, and explains why instruction scheduling and register use matter so much. Introduction to Algorithms by Cormen, Leiserson and Rivest supplies the graph algorithms and dynamic programming that the optimisation and code generation chapters draw on.
Further back, Gödel, Escher, Bach by Douglas Hofstadter plays with the idea of formal systems and self-reference that sits under every compiler that compiles itself. Code by Charles Petzold builds from switches and circuits up to the level where machine code begins, which is exactly where a compiler's work ends. Read together, these books trace the full path from a sentence written by a person to a voltage changing in a wire.
Questions and criticisms
The most common criticism is that the book spends too much time on parsing. In 1986 parsing was a central research achievement, and the book's detailed treatment of LR table construction reflects that. Today, most compiler engineers spend their time on intermediate representations, optimisation and code generation; parsing is seen as a solved problem, often handled by hand-written recursive descent. A student who reads the book in order can spend weeks on parsing tables and reach the back end exhausted. Many teachers now assign the parsing material selectively.
A related criticism is that the first edition predates several ideas now considered essential. It has no treatment of static single assignment form, which reshaped optimisation. Its treatment of register allocation is modest by later standards. It says little about the memory hierarchy, about caches, or about the instruction-level parallelism that came to dominate processor performance in the 1990s. It says little about just-in-time compilation, garbage collection in depth, or the compilation of object-oriented and functional languages, all of which became central. The second edition addressed some of these gaps but not all.
Some readers find the book dry and dense, and the notation heavy. This is partly a matter of taste. The book was written as a reference and a course text, and it assumes a reader willing to work with a pencil. Readers who want a gentler path often start elsewhere, with a short book that builds a whole working compiler for a small language, and come to the dragon book afterwards to understand why the methods work. Others find the book's precision a relief: nothing is waved away, and every algorithm can be traced by hand.
There is a fair objection about the relation between theory and practice. The book's front end is beautifully grounded in theory, but some of that theory solves problems that matter less than they once did. Meanwhile the hard practical problems of modern compilers, such as producing helpful diagnostics, compiling quickly enough for interactive use, and supporting tools like editors and debuggers, receive little attention. A modern reader should not mistake the book's proportions for the proportions of present-day compiler work.
What has held up is substantial. The phase structure, the use of finite automata for lexing, the theory of grammars and parsing, syntax-directed translation, three-address code, basic blocks and flow graphs, the data-flow framework, dominators and loops: these remain the vocabulary of the field. A reader who has worked through the dragon book can read the source of a modern compiler and recognise what each part is doing. Very few technical books from the 1980s can claim as much.
Why it is on this shelf
This shelf keeps books that explain how one kind of thing becomes another: how a principle becomes a practice, how a description becomes a working object. The dragon book is the clearest account we know of one such transformation, the passage from a text written in a human language to a sequence of operations carried out by a machine. Every program a reader of this shelf runs has passed through some descendant of the methods it describes.
For a reader who also studies Vedanta, the book offers a working model of layered description. A program exists as characters, as tokens, as a tree, as intermediate code and as machine instructions. Each level is real in its own terms, and each is a faithful transformation of the one before. The question of what the program really is, apart from all these forms, is not one the book asks, but its careful separation of levels gives exact material for thinking about the relation between name, form and function. For a reader of Jyotish, the book shows how a rule-governed symbolic system can be read mechanically and also interpreted with care, and how much depends on getting the grammar of the symbols right before computing anything from them.
For a reader of science and technology, the value is more direct. The ideas in this book appear wherever structured text must be understood by a program: in query languages, configuration formats, document processors, search tools, data validators and the many small languages built into larger systems. For a reader of economics, there is a quieter lesson about division of labour and standard interfaces: the intermediate representation is a contract that lets many front ends and many back ends be built independently, much as a common currency lets many producers and consumers trade. We keep it because it teaches precision, and because it shows that difficult problems can often be made routine by finding the right representation.
How to read it
On a first reading, do not try to read the book from cover to cover. Begin with the opening overview of the compiler and the chapter that builds a small translator for simple expressions. These give a complete picture in miniature, and everything later is a deepening of one part of it. Read them slowly, and if possible type in and run a version of the simple translator in a language you know.
Next, read lexical analysis. Work through the conversion of a regular expression into a nondeterministic automaton and then into a deterministic one, by hand, for at least two small examples. This is pencil work, and it is worth doing once properly. Then read syntax analysis, but be selective on the first pass. Learn grammars, ambiguity, left recursion and left factoring thoroughly. Learn recursive descent and the FIRST and FOLLOW sets thoroughly. For LR parsing, learn how a shift-reduce parser works, build one SLR table by hand, and understand what a conflict is. Skim canonical LR and LALR construction on a first pass, returning to them if you plan to write or debug a parser generator.
Then read syntax-directed translation and type checking together, since the second applies the first. Read the material on run-time environments with a debugger open: write a small recursive program, run it, and look at the stack frames as the book describes them. Read intermediate code generation, paying special attention to the translation of boolean expressions and to backpatching.
For the back end, read code generation for basic blocks and flow graphs, then the optimisation material up to and including the iterative data-flow framework, dominators and loops. Work at least one data-flow analysis by hand on a small flow graph until the solution stops changing. The later parts on more advanced optimisation can be left for a second reading. The final survey of real compilers is light and can be read whenever you like.
Throughout, the best companion is a small project. Choose a tiny language, perhaps arithmetic expressions, assignments, if statements and while loops, and build a compiler for it as you read, chapter by chapter. Have it emit three-address code, and then perhaps assembly or code for a simple stack machine. A pace of one major topic a week, with exercises, is realistic for a careful reader with a full-time occupation; the whole first pass then takes three to four months.
From this shelf, read Introduction to Automata Theory, Languages, and Computation alongside the early chapters if the formal material feels thin, or Sipser's Introduction to the Theory of Computation for a lighter version. Read Structure and Interpretation of Computer Programs afterwards for the interpreter's point of view. Read Computer Architecture: A Quantitative Approach to understand the machines your code generator targets. Keep Introduction to Algorithms nearby for the graph algorithms the optimisation chapters assume.
Questions to carry
- Why is it useful to separate a compiler into phases even when the implementation interleaves them?
- What exactly can a finite automaton not do, and why does that make it ideal for lexing but unfit for parsing?
- When two grammars describe the same language, what makes one better than the other for a given parser?
- Why do the longest-match and first-listed rules in a lexer generator settle every ambiguity between token patterns?
- What does an LR parser's state remember about the input it has already read?
- What do you gain and lose by writing a parser by hand instead of generating it?
- How does the spreadsheet analogy for attribute grammars break down, and where does it hold?
- Why do recursive procedures force a compiler to allocate local variables on a stack rather than at fixed addresses?
- What makes an intermediate representation good: closeness to the source, closeness to the machine, or ease of analysis?
- Why must data-flow analysis be conservative, and what does a compiler lose by being so?
- Since perfect optimisation is undecidable in general, how should a compiler writer decide which improvements are worth pursuing?
- Which parts of this book would you keep if you were writing a compiler course today, and which would you cut?
- How do the ideas of this book appear in tools that are not compilers, such as search engines, formatters or query planners?
Words to know
- Compiler: A program that translates a program in one language, usually a high-level one, into an equivalent program in another, usually machine code.
- Phase: A conceptual stage of compilation with a single job, such as lexical analysis or code generation.
- Pass: One actual traversal of the program or its representation; several phases may share a pass.
- Token: A unit of meaning produced by the lexer, such as an identifier, keyword, number or operator.
- Lexeme: The actual characters in the source that make up one token.
- Regular expression: A formula built from characters by concatenation, choice and repetition, describing a set of strings.
- Finite automaton: A machine with a fixed number of states that reads input one symbol at a time; deterministic if each move is unique.
- Subset construction: The method that turns a nondeterministic automaton into an equivalent deterministic one.
- Context-free grammar: A set of rules describing how phrases are built from smaller phrases, used to define the syntax of programming languages.
- Parse tree: A tree showing how a string is derived from a grammar's start symbol.
- Ambiguity: The property of a grammar under which some string has more than one parse tree.
- Left recursion: A grammar rule whose right side begins with its own left side; it defeats naive top-down parsers.
- LL(1): A class of grammars that can be parsed top-down, reading left to right, with one token of lookahead and no backtracking.
- LR parsing: Bottom-up parsing that reads left to right and builds a rightmost derivation in reverse, driven by a table of states.
- LALR: Lookahead LR, a compact form of LR parsing used by Yacc and similar parser generators.
- Shift-reduce conflict: A parser state in which the table cannot decide whether to read another token or to reduce by a rule.
- Attribute grammar: A grammar with values attached to symbols and rules for computing them, the basis of syntax-directed translation.
- Synthesized and inherited attributes: Values computed from a node's children, and values passed down from its parent or siblings.
- Activation record: The block of memory holding one procedure call's parameters, locals and return information, usually kept on a stack.
- Three-address code: An intermediate representation in which each instruction has at most one operator and three operands.
- Backpatching: Generating jumps with unknown targets and filling in the targets later, once they are known.
- Basic block: A maximal straight-line sequence of instructions with one entry and one exit.
- Flow graph: A directed graph whose nodes are basic blocks and whose edges are possible transfers of control.
- Data-flow analysis: The systematic computation of facts about a program at each point, such as which variables are live or which definitions reach.
- Dominator: A block that lies on every path from the entry of a flow graph to a given block; used to find loops.
A note on this edition
This is a study edition written for the shelf in our own words. It describes and comments on Compilers: Principles, Techniques, and Tools; it does not reproduce it, and it is no substitute for the book's own explanations, worked examples and exercises, which are where most of its value lies. The book itself is in copyright and is worth getting from a library or a bookshop, in the 1986 edition or in the 2006 second edition. Any errors in this companion are ours, not the authors'.