Skip to content
ImagineWorld

Parsers

node_idnode-book_engineering-a-compiler_chapter-03-parsers
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleParsers
pillar_membershipF — compiler_trinity
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

The parser’s task is to determine if the input program, represented by the stream of classified words produced by the scanner, is a valid sentence in the programming language. To do so, the parser attempts to build a derivation for the input program, in a grammar that describes the programming language.

This chapter introduces context-free grammars to specify programming language syntax. It develops both top-down and bottom-up parsing techniques. It describes ways to automate the construction of both of these types of parsers. Finally, it explores a number of practical issues that arise in parser construction.

Parsing, Grammar, LL(1), LR(1), Recursive Descent

Parsing is the second stage of the compiler’s front end. The parser works with the program as tokenized by the scanner; it sees a stream of words annotated with their syntactic categories (analogous to their parts of speech). The parser derives a syntactic structure for the program, fitting the words into a grammatical model of the source programming language. If the parser determines that the input stream is a valid program, it builds a concrete model of the program, an intermediate representation, for use by the rest of the compiler. If the parser finds errors, it reports both the problem and its location to the user.

Parsing and scanning are similar. Like scanning, parsing has been studied extensively; modern-day parsers build on that theoretical basis. Speed matters; all of the techniques that we will study take time proportional to the size of the program and its representation. Low-level detail affects performance; the same implementation tradeoffs arise in parsing as in scanning. The techniques in this chapter are amenable to implementation as table-driven parsers, direct-coded parsers, and hand-coded parsers. Unlike scanners, where hand-coding is common, tool-generated parsers are more common than hand-coded parsers.

The parser’s primary task is to determine whether or not the input program is a syntactically valid sentence in the source language. Before we can build parsers to answer this question, we need both a formal mechanism to specify the source language’s syntax and a systematic way to determine membership in this formally specified language. By restricting the form of the source language to a set of languages called context-free languages, we can ensure an efficient algorithm to answer the membership question. Context-free grammars(CFGs) are the notation used to specify context-free languages.

Many algorithms have been proposed to answer the membership question for CFGs. This chapter examines two different approaches to the problem: top-down parsers and bottom-up parsers. The two styles of parsers differ significantly in their approach and implementation. Both styles, however, handle a large class of grammars that includes most of the programming language constructs that occur in modern languages. Equally important tools are widely available to assist the compiler writer in building either a top-down parser or a bottom-up parser. This chapter explores both the parsing techniques and the methods used to automate parser construction.

A compiler’s parser has the primary responsibility for recognizing syntax-that is, for determining if the program being compiled is a valid sentence in the syntactic model of the programming language. That model is expressed as a formal grammar G; if some string of words s is in the language defined by G we say that G derives s. For a stream of words s and a grammar G, the parser tries to build a constructive proof that s can be derived in G-a process called parsing.

Parsing algorithms fall into two general categories. Top-down parsers try to match the input stream against the productions of the grammar by predicting the next word(at each point). For a limited class of grammars, such prediction can be both accurate and efficient. Section 3.3 explores the details of how top-down parsers work and the techniques used to create them. It explores the construction of both recursive-descent and LL(1) parsers. Bottom-up parsers work from low-level detail-the actual sequence of words-and accumulate context until the derivation is apparent. Again, there exists a restricted class of grammars for which we can generate efficient bottom-up parsers. Section 3.4 examines one particular kind of bottom-up parser,a table-driven LR(1) parser, along with the techniques used generate these highly efficient parsers. The final sections explore a number of practical issues that arise in parser construction.

Given a stream s of words and a grammar G, find a derivation in G that produces s.

Recursive-descent parsers are hand-coded, top-down parsers. They can be compact and efficient.

LL(1) parsers are table-driven, top-down parsers. They recognize a class of grammars that include most interesting program-mming language features.

LR(1) parsers are table-driven, bottom-up parsers. They recognize a larger class of parsers than do the LL(1) parsers.

Designing, building, and using a parser spans the entire continuum of compilation. At design time, the compiler writer chooses a parsing method and toolset. She then creates a CFG for the source language in the input format of the tools that she has chosen.

At build time, the compiler writer’s development tools construct an executable parser. In a hand-written parser, the code is compiled directly. In a generated parser, the process invokes a parser generator to build the parser from the CFG and its annotations; that code is then compiled to create the executable parser.

Finally, at compile-time, the parser analyzes the tokenized version of the source program. It maps the stream of classified words into the CFG and identifies mismatches, if any, between the source program and the CFG. If the input program is correct, it generates an intermediate representation for the rest of the compiler to use. If the input contains errors, the parser reports them back to the programmer.

The task of the parser is to determine whether or not some stream of words fits into the syntax of the parser’s intended source language. Implicit in this description is the notion that we can describe syntax and check it; in practice, we need a notation to describe the syntax of languages that people might use to program computers. In Chapter 2, we worked with one such notation, regular expressions. RE’s provide a concise notation for describing limited kinds of syntax. RE descriptions lead to efficient recognizers. Unfortunately, REs lack the power to describe the full syntax of most programming languages.

For most programming languages, syntax is expressed with a CFG. This section introduces CFGs and explores their use in syntax-checking. It shows how to encode meaning into syntax and structure. Finally, it introduces the ideas that underlie the efficient parsing techniques described in later sections.

To motivate CFGs, consider the problem of recognizing algebraic expressions over names and the operators+,-,x, and+. We can define “name”as any string that matches the REa…z*, a simplified,

The regular expression for an Algol-style identifier can be extended into a regular expression for simple arithmetic expressions:

[a…z]([a…z]∣[0…9])∗((+∣−∣×∣÷)[a…z]([a…z]∣[0…9])∗)∗[a \ldots z]([a \ldots z] \mid [0 \ldots 9])^*((+ \mid - \mid \times \mid \div)[a \ldots z]([a \ldots z] \mid [0 \ldots 9])^*)^*

This expression matches strings such as a+bxc and e/f*g, but it says nothing about operator precedence. Standard algebra gives multiplication and division precedence over addition and subtraction, while regular expressions do not naturally encode that structure.

Adding parentheses with a simple regular expression also fails. A first attempt can permit an optional opening parenthesis before the initial identifier and an optional closing parenthesis after later identifiers, but it still allows only restricted parenthesized forms. A more permissive expression can match examples such as a+bxc and (a+b)*c, but it also matches syntactically incorrect expressions because it cannot require balanced parentheses.

Balanced constructs such as begin/end or then/else pairs are not regular languages. The inability to match balanced brackets is one motivation for moving beyond regular expressions to context-free grammars.

To describe programming language syntax, we need a more powerful notation than regular expressions, while still retaining efficient recognizers. Context-free grammars provide that notation.

The traditional notation used by computer scientists to represent a context-free grammar is called Backus-Naur form, or BNF. In BNF, nonterminal symbols were wrapped in angle brackets, as in (SheepNoise). Terminal symbols were underlined, as in baa. The symbol ::= meant “derives,” and the symbol | meant “also derives.” Writing the sheep noise grammar in BNF yields:

(SheepNoise) ::= baa (SheepNoise) | baa

BNF had its origins in the late 1950s and early 1960s [282]. The syntactic conventions of angle brackets, underlining, ::=, and | arose from the limited typographic options available to compiler writers at the time. (For example, see David Gries’ book Compiler Construction for Digital Computers [181].) Throughout this book, we use a typographically updated form of BNF. Nonterminal symbols are written in a slanted sans-serif font. Terminal symbols are set in a typewriter font. When the change in font is difficult to see, as with ), we underline the character as well, ). We use the symbol → for “derives” and | for “also derives.”

traditional solution is to use a CFG. Fortunately, large subclasses of the CFGs have the property that they lead to efficient recognizers.

A CFG, G, is a set of rules, or productions, that describe how to form sentences. The collection of sentences that derive from G is called the language defined by G, denoted L(G). The set of languages defined by all possible CFGs is called the set of context-free languages. An example may help. Consider the following grammar, which we call SN:

1 SheepNoise → baa SheepNoise 2 | baa

The first rule, or production, reads “SheepNoise can derive the word baa followed by another SheepNoise.” Here SheepNoise is a syntactic variable representing the set of strings that can be derived from the grammar. We call such a syntactic variable a nonterminal symbol. Each word in the language, such as baa, is a terminal symbol in the grammar. The second rule reads “SheepNoise can also derive the word baa.”

To understand the relationship between the SN grammar and L(SN), we need to specify how to apply rules in SN to derive sentences in L(SN). To begin, we must identify the start symbol of SN. It represents the set of all strings

Production Each rule in a CFG is called a production.

Sentence a string of symbols that can be derived from the rules of a grammar

Nonterminal symbol a syntactic variable used in a grammar’s productions

Terminal symbol a word that can occur in a sentence

A word consists of a lexeme and its syntactic category. Words are represented in a grammar by their syntactic category.

Formally, a context-free grammar G is a quadruple(T,NT,S,P) where:

T is the set of terminal symbols, or words, in the language L(G). Terminal symbols correspond to syntactic categories returned by the scanner.

NT is the set of nonterminal symbols. They are syntactic variables introduced to provide abstraction and structure in the productions of G.

S is a nonterminal symbol designated as the start symbol or goal symbol of the grammar. S represents the set of sentences in L(G).

P is the set of productions or rewrite rules in G. Each rule in P has the formNT→(T∪NT)+NT\rightarrow(T\cup NT)^{+} ; that is, it replaces a single nonterminal with a string of one or more grammar symbols.

The sets T and NT can be derived directly from the productions. The start symbol may be unambiguous, as in the SheepNoise grammar, or it may not be obvious, as in the following grammar:

Paren→(Bracket)Bracket→[Paren]

In this case, the choice of start symbol determines the outer brackets. Starting with Paren ensures that the outer brackets are parentheses, while starting with Bracket forces square brackets on the outside. To allow either, the compiler writer can add a new nonterminal symbol S and the two productions S→Paren|Bracket.

Some tools that manipulate grammars require that S not appear on the right-hand side of any production, which makes S easy to discover.

in L(SN). As such, it cannot be one of the words in the language. Instead, it must be one of the nonterminal symbols introduced to add structure and abstraction to the language. Since SN has only one nonterminal, SheepNoise is the start symbol.

a sequence of rewriting steps that begins with the grammar’s start symbol and ends with a sentence in the language

To derive a sentence, we start with a prototype string that contains just the start symbol. We then repeat the following process:(1) pick a nontermin-nal symbol,α,in the prototype string;(2) choose a grammar rule, α→β\alpha\rightarrow\beta ;and (3) rewrite α\alpha with β\beta . When the prototype string contains only terminal symbols, the derivation halts. The prototype string has been rewritten into a sentence in the language.

n of symbols that occurs as one step alid derivation

At each point in the derivation, the prototype string consists of a sequence of terminal and nonterminal symbols. When such a string occurs as a step in a valid derivation, it is a sentential form. Any sentential form can be derived from the start symbol in zero or more steps. Similarly, from any sentential form we can derive a valid sentence in zero or more steps. Thus, if we begin with SheepNoise and apply successive rewrites using the two rules, at each step in the process the string is a sentential form. When we have reached the point where the string contains only terminal symbols, the string is a sentence in L(SN).

To derive a sentence in SN, we start with the string that consists of one symbol, SheepNoise. We can rewrite SheepNoise with either rule 1 or rule 2. If we rewrite SheepNoise with rule 2, the string becomes baa and has no further opportunities for rewriting. The rewrite shows that baa is a valid sentence in L(SN). The other choice, rewriting the initial string with rule 1, leads to a string with two symbols: baa SheepNoise. This string has one remaining nonterminal; rewriting it with rule 2 leads to the string baa baa, which is a sentence in L(SN). We can write these derivations in tabular form:

RuleSentential Form
SheepNoise
2 baa
SheepNoise
1 baa SheepNoise
2 baa baa
Rewrite with Rule 2Rewrite with Rule 1 Then 2

As a notational convenience, we will use →+ to mean “derives in one or more steps.” Thus, SheepNoise →+ baa and SheepNoise →+ baa baa.

Rule 1 lengthens the sentential form while rule 2 eliminates the nonterminal SheepNoise. (The sentential form never contains more than one instance of SheepNoise.) All derivations in SN begin with zero or more applications of rule 1, and end with rule 2. Applying rule 1 k times followed by rule 2 generates a string with k + 1 baas.

Notice that L(SN) can be specified with an RE as (baa)+. L(SN) is a regular language—a member of the subset of CFGs that can be specified by an RE (see “Classes of Context-Free Grammars” on page 135).

The SheepNoise grammar is too simple to exhibit the power and complexity of CFGs. Instead, let us revisit the example that showed the shortcomings of REs: the language of expressions with parentheses.

1 Expr→(Expr) 2|Expr Op Expr 3|name 4 Op→+ 5| 6| 7|

a graph that represents a derivation; also called a syntax tree

Beginning with the start symbol, Expr, the grammar generates two kinds of subterms: parenthesized subterms, with rule 1, or plain subterms, with rule 2. To generate the sentence(a+b)xc, we can use the rewrite sequence (2,3,6,1,2,3,4,3) as shown in Fig. 3.1(a). Panel(b) shows the parse tree,a graphical representation of the derivation.

This simple CFG for expressions cannot generate a sentence with unbalanced or improperly nested parentheses. Only rule 1 can generate a(. The same rule also generates the matching). Thus, it cannot generate strings such as a+(bxc or a+b)xc), and a parser built from the grammar will not accept such strings.(The best RE in Section 3.2.1 matched both of these strings.)Clearly,CFGs have the ability to specify constructs that REs do not.

a derivation that rewrites, at each step, the rightmost nonterminal

The derivation of(a+b)xc in Fig. 3.1(a) rewrote, at each step, the rightmost remaining nonterminal symbol. This systematic behavior was a choice;other choices are possible. One obvious alternative is to rewrite the leftmost nonterminal at each step. Using leftmost choices would produce a different derivation sequence for the same sentence. Panels(c) and(d) in Fig. 3.1 show the leftmost derivation.

a derivation that rewrites, at each step, the leftmost nonterminal

The leftmost and rightmost derivations use the same set of rules; they apply those rules in a different order. Because a syntax tree represents the rules applied, but not the order of their application, the parse trees for the two derivations are identical.

A grammar G is ambiguous if some sentence in L(G) has more than one rightmost(or leftmost) derivation.

From the compiler’s perspective, it is important that each sentence in the language defined by a CFG has a unique rightmost(or leftmost) derivation. If multiple rightmost(or leftmost) derivations exist for some sentence, then, at some point in the derivation, multiple distinct rewrites of the rightmost(or leftmost) nonterminal lead to the same sentence. A grammar in which multiple rightmost(or leftmost) derivations exist for a sentence is called an ambiguous grammar. An ambiguous grammar can produce multiple derivations and multiple parse trees.

Alternatively, a grammar G is ambiguous if some sentence in L(G) has more than one parse tree.

For an ambiguous grammar, some inputs can produce multiple derivations and multiple meanings. A program must have a single meaning; otherwise, the compiler cannot know what code to generate. Thus, ambiguity is a bad property in a programming language.

Expr 2 Expr Op Expr 3 Expr Op name 6 Expr x name 1 (Expr) x name 2 (Expr Op Expr) x name 3 (Expr Op name) x name 4 (Expr + name) x name 3 (name + name) x name

(a) Rightmost Derivation of (a+b)xc

(b) Corresponding Rightmost Parse Tree

Expr 2 Expr Op Expr 1 (Expr) Op Expr 2 (Expr Op Expr) Op Expr 3 (name Op Expr) Op Expr 4 (name + Expr) Op Expr 3 (name + name) Op Expr 6 (name + name) x Expr 3 (name + name) x name

(c) Leftmost Derivation of (a+b)xc

(d) Corresponding Leftmost Parse Tree

The classic example of an ambiguous grammar for a programming language construct is the if-then-else construct of many Algol-like languages. The straightforward grammar for if-then-else might be

1Stmt→if Expr then Stmt
2if Expr then Stmt else Stmt
3Other

where Other represents all the statements that can appear in a list of statements, other than an if-then or an if-then-else. The grammar shows that the else clause is optional. Unfortunately, the sentence

if Expr1 then if Expr2 then Other1 else Other2

has two distinct rightmost derivations. The difference between them is sim-

The first derivation has Other2 controlled by the inner if, so Other2 executes when Expr1 is true and Expr2 is false:

Stmt
`- if Expr1 then Stmt
`- if Expr2 then Stmt else Stmt
`- Other1 `- Other2

The second derivation associates the else clause with the first if, so Other2 executes when Expr1 is false, independent of the value of Expr2:

Stmt
`- if Expr1 then Stmt else Stmt
| `- Other2
`- if Expr2 then Stmt
`- Other1

These two derivations produce two distinctly different meanings.

To remove this ambiguity, the grammar must encode a rule that determines which if controls an else. The classic solution to the if-then-else ambiguity rewrites the grammar as:

Stmt -> if Expr then Stmt
| if Expr then WithElse else Stmt
| Other
WithElse -> if Expr then WithElse else WithElse
| Other

This grammar accepts the same set of sentences as the original grammar, but ensures that each else has an unambiguous match to a specific if. It encodes the rule that each else binds to the innermost unmatched if. Rule Sentential Form

  1. if Expr then Stmt
  2. if Expr then if Expr then WithElse else Stmt
  3. if Expr then if Expr then WithElse else Other
  4. if Expr then if Expr then Other else Other

The rewritten grammar eliminates the ambiguity. The if-then-else ambiguity arises from a shortcoming in the original grammar. The solution resolves the ambiguity by imposing a rule that the programmer can easily remember. In Section 3.5.3, we will look at other kinds of ambiguity and systematic ways of handling them.

The if-then-else ambiguity points out the relationship between meaning and grammatical structure. However, ambiguity is not the only situation where meaning and grammatical structure interact. Consider the parse tree that would be built from a rightmost derivation of the simple expression a+b×c.

Rule Sentential Form 2. Expr Op Expr 3. Expr Op name 6. Expr × name 2. Expr Op Expr × name 3. Expr Op name × name 4. Expr + name × name 3. name + name × name

Derivation of a+b×c Corresponding Parse Tree

One natural way to evaluate the expression is with a simple postorder tree-walk. It would first compute a+b and then multiply that result by c to produce the result (a+b)×c. This evaluation order contradicts the classic rules of algebraic precedence, which would evaluate it as a+(b×c). Since the ultimate point of parsing the expression is to produce code that will implement it, the expression grammar should have the property that it builds a tree whose “natural” treewalk evaluation produces the correct result.

0Goal→Expr5Term + Factor
1Expr→Expr + Term6Factor
2Expr - Term7Factor →(Expr)
3Term8num
4Term→Term × Factor9name

Figure 3.2 The Classic Expression Grammar.

The real problem lies in the structure of the grammar on page 92. It treats all the arithmetic operators in the same way, ignoring precedence. A rightmost derivation of a+b×c generates a different parse tree than does a leftmost derivation of the same string. The grammar is ambiguous.

The example in Fig. 3.1 showed a string with parentheses. The parentheses forced the leftmost and rightmost derivations into the same parse tree. That extra production in the grammar added a level to the parse tree that, in turn, forces the same evaluation order independent of derivation order.

We can use this effect to encode levels of precedence into the grammar. First, we must decide how many levels of precedence are required. The simple expression grammar needs three precedence levels: highest precedence for ( ), medium precedence for × and ÷, and lowest precedence for + and -. Next, we group the operators at distinct levels and use a nonterminal to isolate that part of the grammar. Fig. 3.2 shows the resulting grammar; it adds a start symbol, Goal and a production for the terminal symbol num.

In the classic expression grammar, Expr forms a level for + and -, Term forms a level for × and ÷, and Factor forms a level for ( ). The modified grammar derives a parse tree for a+b×c that models standard algebraic precedence.

Rule Sentential Form

0Expr
1Expr + Term
4Expr + Term × Factor
9Expr + Term × name
6Expr + Factor × name
9Expr + name × name
3Term + name × name
6Factor + name × name
9name + name × name

Corresponding Parse Tree

Thompson’s construction must apply its three transformations in an order that is consistent with the precedence of the operators in the regular expression. To represent that order, an implementation of Thompson’s construction can build a tree that represents the regular expression and its internal precedence. The RE a(b|c)* produces the following tree:

where+ represents concatenation,| represents alternation, and* represents closure. The parentheses are folded into the structure of the tree and, thus, have no explicit representation.

The construction applies the individual transformations in a postorder walk over the tree. Since transformations correspond to operations, the postorder walk builds the following sequence of NFAs: a,b,c,b|c,(b|c), and, finally,a(b|c). Section 5.3 discusses a mechanism to build expression trees.

A postorder treewalk over this parse tree will first evaluate bxc and then add the result to a. The grammar enforces the standard rules of arithmetic precedence. This grammar is unambiguous; the leftmost derivation produces the same parse tree.

The changes affect derivation lengths and parse tree sizes. The new nonterminals that enforce precedence add steps to the derivation and interior nodes to the tree. At the same time, moving the operators inline eliminated one production and one node per operator.

Other operations require high precedence. For example, array subscripts should be applied before standard arithmetic operations. This ensures, for example, that a+b[i] evaluates b[i] to a value before adding it to a, as opposed to treating i as a subscript on some array whose location is computed as a+b. Similarly, operations that change the type of a value, known as type casts in languages such as C or JAVA, have higher precedence than arithmetic operations but lower precedence than parentheses or subscript operations.

If the language allows assignment inside expressions, the assignment operator should have low precedence. This ensures that the code completely

evaluates both the left-hand side and the right-hand side of the assignment before performing the assignment. If assignment(←) had the same precedence as addition, for example, a left-to-right evaluation of a←b+c would assign b’s value to a rather than evaluating b+c and then assigning that result to a.

3.2.5 Discovering a Derivation for an Input String

Section titled “3.2.5 Discovering a Derivation for an Input String”

We have seen how to use a CFG G as a rewrite system to generate sentences that are in L(G). By contrast, a parser takes a given input string, alleged to be in L(G), and finds a derivation. The process of constructing a derivation from a specific input sentence is called parsing.

The parser sees the program as it emerges incrementally from the scanner:a stream of words annotated with their syntactic categories. Thus, the parser would see a+bxc as〈name,a〉+〈name,b〉x〈name,c〉. As output, the parser needs to produce either a derivation of the input program or an error message that indicates an invalid program.

The parse tree and derivation are equivalent for an unambiguous grammar. It is useful to visualize the parser as building a parse tree. The parse tree’s root is known; it represents the grammar’s start symbol. The leaves of the parse tree are known; they match the stream of words returned by the scanner. The hard part of parsing lies in finding the connection between the leaves and the root. Two distinct and opposite approaches for constructing the tree suggest themselves:

  1. Top-Down Parsers begin with the root and grow the tree toward the leaves. At each step, a top-down parser selects a node for some nonterminal on the lower fringe of the partially built tree and extends it with a subtree that represents the right-hand side of a production that rewrites the nonterminal.

  2. Bottom-Up Parsers begin with the leaves and grow the tree toward the root. At each step, a bottom-up parser finds a substring of the partially built parse tree’s upper fringe that matches the right-hand side of some production; it then builds a node for the rule’s left-hand side and connects it into the tree.

In either scenario, the parser makes a series of choices about which productions to apply. Most of the intellectual complexity in parsing lies in the mechanisms for making these choices. Section 3.3 explores the top-down parsing, while Section 3.4 examines bottom-up parsing.

SECTION REVIEW Language designers and compiler writers use context-free grammars to express programming-language syntax. These grammars allow specification of structure and form. They have shown themselves capable of expressing almost all of the programming language features that have proven useful. This section defined context-free grammars and showed how they can be used to encode useful structure, such as blocking and precedence. It introduced ambiguity and the classic example of an ambiguity, the if-then-else grammar. Finally, it introduced the dual notions of derivations and parses—the subject of the rest of this chapter.

REVIEW QUESTIONS

  1. Write a CFG to describe Backus-Naur Form.
  2. Consider the classic expression grammar. What properties of the grammar and the input program govern the length of a derivation?

A top-down parser begins with the root of the parse tree and systematically extends the tree downward until the leaves match the words returned by the scanner. At each point, the process considers the partially built parse tree. It picks a nonterminal symbol on the tree’s lower fringe and extends the fringe with children that correspond to the right-hand side of some production for that nonterminal. It cannot extend the frontier from a terminal symbol. This process continues until either: a. the fringe of the parse tree contains only terminal symbols, and the input stream has been exhausted, or b. a clear mismatch occurs between the fringe of the partially built parse tree and the input stream.

In the first case, the parse succeeds. In the second case, two situations are possible. The parser may have selected the wrong production at some earlier step in the process, in which case it can backtrack, systematically reconsidering earlier decisions. For an input string that is a valid sentence, backtracking will eventually lead the parser to a correct sequence of choices and let it construct a correct parse tree. Alternatively, if the input string is not a valid sentence, backtracking will fail and the parser should report the syntax error to the user. root ← node for the start symbol, S focus ← root push null onto the stack word ← NextWord() while (true) do if (focus is a nonterminal) then pick next rule to expand focus, say A → β₁β₂β₃…βₙ build nodes for β₁β₂β₃…βₙ as children of focus push βₙ, βₙ-1, βₙ-2, … β₂ onto the stack focus ← β₁ else if (word matches focus) then word ← NextWord() focus ← pop from the stack else if (word = eof and focus = null) then accept the input and return root else backtrack

■ FIGURE 3.3 A Leftmost, Top-Down Parsing Algorithm.

One key insight makes top-down parsing efficient: a large subset of the context-free grammars can be parsed without backtracking. Section 3.3.1 shows transformations that can often convert an arbitrary grammar into one suitable for backtrack-free top-down parsing. The subsequent sections introduce two kinds of top-down parsers: hand-coded recursive-descent parsers and generated LL(1) parsers.

The top-down parser builds a leftmost derivation to match the scanner’s left-to-right scan of the input.

To make this discussion concrete, Fig. 3.3 sketches a high-level algorithm for a top-down parser that constructs a leftmost derivation. It builds a parse tree, anchored at the variable root. It uses a stack to track the unmatched portion of the lower fringe of the partially built parse tree.

The body of the parser consists of a while loop that examines the leftmost unmatched symbol on the partially built parse tree’s lower fringe—stored in focus. If focus holds a nonterminal symbol, the parser expands the tree downward; it picks a production, builds the tree for the right-hand side, and assigns the leftmost symbol from this tree to focus. If focus is a terminal symbol, it compares focus against the next word in the input. A match moves focus to the next symbol on the fringe and gets the next word.

If focus is a terminal symbol, but it does not match the input, the parser must backtrack. The parser sets focus to its parent in the partially built parse tree, disconnects its children, and discards them. If an untried rule remains with focus on its left-hand side, the parser expands focus by that rule. It builds children for each symbol on the right-hand side, pushes those symbols onto the stack in right-to-left order, and sets focus to point at the first child. If no untried rule remains, the parser moves up another level and tries again. When it runs out of possibilities, it reports a syntax error and quits. Backtracking increases the asymptotic cost of parsing; in practice, it is an expensive way to find syntax errors.

When it backtracks, the parser must also rewind the input stream. Fortunately, the partial parse tree encodes enough information to make this action efficient. The parser must place each matched terminal in the discarded production back into the input stream, an action it can take as it disconnects them from the parse tree in a traversal of the discarded children.

The efficiency of a top-down parser depends critically on its ability to pick the correct production each time that it expands a nonterminal. If the parser always chooses correctly, top-down parsing is efficient. If it chooses poorly, the cost of parsing rises. This section examines structural issues that can make a CFGs unsuitable for a top-down parser. It presents transformations that the compiler writer can apply to the grammar to avoid these problems.

As an initial exercise, consider the behavior of the parser from Fig. 3.3 with the classic expression grammar in Fig. 3.2 when applied to the string a+bxc. For the moment, assume that the parser has an oracle that picks the correct production at each point in the parse. With oracular choice, it might proceed as shown in Fig. 3.4. The right column shows the input string, with a marker↑ to indicate the parser’s current position in the string. The symbol→in the rule column represents a step in which the parser matches a terminal symbol against the input string and advances the input. At each step, the sentential form represents the lower fringe of the partially built parse tree. For a+bxc, the parser applied eight rules and matched five words.

Notice, however, that oracular choice was inconsistent choice. In the first two steps, focus held the nonterminal Expr. In the first step, it applied rule 1,Expr→Expr+Term. The second step still had Expr as focus and name as the lookahead symbol. This time, it applied rule 3, Expr→Term. The oracle was similarly inconsistent in matching names, using the sequence (6,9) to match a from a Term, and then using the sequence (4,6,9) to match b from a Term. It would be difficult to make the top-down parser work well with consistent, algorithmic choice for this version of the expression grammar. To facilitate finding the “next” rule, the parser can store the rule number in a nonterminal’s node when it expands that node.

Lookahead symbol the word that the parser is trying to match In Fig. 3.4, the lookahead symbol is the word that immediately follows the↑.

RuleSentential FormInput
Expr
1Expr + Term↑ name + name × name
3Term + Term↑ name + name × name
6Factor + Term↑ name + name × name
9name + Term↑ name + name × name
→name + Termname ↑ + name × name
→name + Termname + ↑ name × name
4name + Term × Factorname + ↑ name × name
6name + Factor × Factorname + ↑ name × name
9name + name × Factorname + ↑ name × name
→name + name × Factorname + name ↑ × name
→name + name × Factorname + name × ↑ name
9name + name × namename + name × ↑ name
→name + name × namename + name × name ↑

■ FIGURE 3.4 Leftmost, Top-Down Parse of a + b × c with Oracular Choice.

Left recursion A CFG is left recursive if, for some A ∈ NT and β ∈ (T ∪ NT)*, A →+ Aβ. That is, in one or more steps, the grammar can derive a sentential form from A that begins with A. Direct left recursion occurs in one derivation step. Indirect left recursion takes more than one step.

Eliminating Left Recursion The classic expression grammar has multiple problems that arise when used with a leftmost, top-down parser. Perhaps the most difficult problem arises from the fact that it employs left recursion. That is, it has productions, such as Expr → Expr + Term, whose right-hand sides begin with the nonterminal symbol from their left-hand sides. Consider how the top-down parser would behave on the input a + b × c if it always applied productions in their order of appearance in the grammar. Its first several actions would be:

RuleSentential FormInput
Expr
1Expr + Term↑ name + name × name
1Expr + Term + Term↑ name + name × name
1…↑ name + name × name

It starts with Expr and tries to match a. It applies rule 1 to create the sentential form Expr + Term on the fringe. Now, it faces the nonterminal Expr and the input word a, again. By consistent choice, it applies rule 1 to replace Expr with Expr + Term. Of course, it still faces Expr and the input word a. With this grammar and consistent choice, the parser will continue to expand the fringe indefinitely. The underlying problem is that the expansion by Expr+Term never generates a leading terminal symbol.

This problem arises from the use of left-recursion in productions 1 and 2.The same issue occurs in productions 4 and 5. With a left-recursive grammar, the top-down parser can expand the frontier indefinitely without generating a leading terminal symbol that the parser can either match or reject. To fix this problem, a compiler writer can convert the left-recursive grammar so that it uses only right-recursion.

The translation from left recursion to right recursion is mechanical. The example shown below illustrates the transformation with a direct left recursion. The left side contains a simple left-recursive grammar. The right side shows the grammar after transformation; the new grammar defines the same language as the original grammar.

Fee→ Fee α Fee→β Fee’ |β Fee’→α Fee’ |ε

The transformation introduces a new nonterminal, Fee’. It rewrites the first production to create a left-recursion on Fee’ rewrites the second production to generate Fee’ afterβ. It uses a production Fee’→ε, whereε represents the empty string, to terminate the recursion. Such a production is called an ε-production.

In the classic expression grammar, direct left recursion appears in the productions for both Expr and Term.

Original Grammar Transformed Grammar Expr→Expr+Term Expr→Term Expr’ |Expr-Term Expr’→+Term Expr’ |Term -Term Expr’ |ε Term→Term x Factor Term→Factor Term’ |Term÷Factor Term’→x Factor Term’ |Factor ÷ Factor Term’ |ε

Plugging the transformed sequences back into the original grammar yields a right-recursive grammar that specifies the same language as the original grammar. Fig. 3.5 shows the right-recursive grammar.

Note that we did not simply rewrite Expr→Expr+Term as Expr→Term+Expr. That change would effectively change the associativity of addition(see Section 5.7.1).

0 Goal→Expr 6 Term’→x Factor Term’ 1 Expr→Term Expr’ 7 2 Expr’→+ Term Expr’ 8 3 | - Term Expr’ 9 Factor→(Expr) 4 |∈ 10 5 Term→Factor Term’ 11 | name

■ FIGURE 3.5 Right-Recursive Variant of the Classic Expression Grammar.

The transformation eliminates direct left recursion. Left recursion can also occur indirectly as α→+αδ\alpha\rightarrow{}^{+\alpha\delta} , through a chain of rules such as α→β,β→γ\alpha\rightarrow\beta,\beta\rightarrow\gamma ,and γ→αδ\gamma\rightarrow\alpha\delta . Indirect left recursion is not always obvious; it can be obscured by a long chain of productions.

To eliminate all left recursion, we need a systematic approach. The algorithm in Fig. 3.6 eliminates all left recursion from a grammar by thorough application of two techniques: forward substitution to convert indirect left recursion into direct left recursion and conversion of direct left recursion to right recursion with the transformation, as before. The algorithm, as stated, assumes that the original grammar has no cycles(A→+A) and noϵ-productions.\epsilon\text{-productions}.

The algorithm imposes an arbitrary order on the nonterminals in the grammar. The outer loop cycles through the nonterminals in that order. The inner loop looks for any production that expands AiA_{i} into a right-hand side that begins with As, for s<i. Such an expansion may lead to an indirect left recursion. To avoid this, the algorithm replaces the occurrence of As with all the alternative right-hand sides for As. This process eventually converts each indirect left recursion into a direct left recursion. The final step in the outer loop converts any direct left recursion on AiA_{i} to right recursion using the simple transformation shown earlier. Because new nonterminals are added at the end and only involve right recursion, the loop can ignore them-they do not need to be checked and converted.

Considering the loop invariant for the outer loop may make this clearer. At the start of the i th outer loop iteration

∀ k<i, no production expanding Ak has As in its rhs, for s<k.\forall\,k<i,\,no\,production\,expanding\,A_{k}\,has\,A_{s}\,in\,its\,rhs,\,for\,s<k.

At the end of this process,(i=n), all indirect left recursion has been eliminated through forward substitution, and all direct left recursion has been eliminated with the transformation for direct left recursion. impose an order on the nonterminals, A0,A1,…,Ai

for i←0 to n do

for s←0 to i-1 do

replace each production Ai→AsA_{i}\rightarrow A_{s} γ\gamma with Ai→δ1γA_{i}\rightarrow\delta_{1}\gamma ∣δ2γ∣…∣δkγ\mid\delta_{2}\gamma\mid\ldots\mid\delta_{k}\gamma ,where Ai→δ1A_{i}\rightarrow\delta_{1} ∣δ2\mid\delta_{2} ∣…∣δk\mid\ldots\mid\delta_{k} are the current productions for AiA_{i}

eliminate any direct left recursion on A, using the transformation

FIGURE 3.6 Algorithm for Removal of Indirect Left Recursion.

Consider the simple left-recursive grammar shown in the margin. Subscripts on the nonterminal symbols indicate the order used by the algorithm. The algorithm proceeds as follows:

i=0 The algorithm does not enter the inner loop. No rule of the form Goal0→Goal1γ found.

i=1 The algorithm looks for a rule with the form A1→Goal0γA_{1}\rightarrow Goal_{0}\gamma . No s=0 such rule exists.

i=2 The algorithm looks for a rule with the form B2→Goal0γB_{2}\rightarrow Goal_{0}\gamma . No s=0 such rule exists.

i=2 The algorithm looks for a rule with the form B2→A1γB_{2}\rightarrow A_{1}\gamma . It finds s=1 rule 3 and rewrites it as B2→B2B_{2}\rightarrow B_{2} a b| a b.

It then applies the transformation for direct left recursion to these new rules. This process produces rules 3,4, and 5 in the final grammar. It introduces the new symbol C3.

The technique for eliminating left recursion introduced e-productions. The top-down parser, from Fig. 3.3, does not understand e-productions. For-tunately, the extension to handle them is minor. When the parser picks a production whose right-hand side is ϵ\epsilon , it should simply set focus←pop().This simple action advances its attention to the next node, terminal or nonterminal, on the fringe.

The major source of inefficiency in the top-down parser shown in Fig. 3.3 is that it may need to backtrack. As written, it has no mechanism to pick the correct production by which to expand the lower fringe of the partially built parse tree. (The algorithm simply says “pick the next rule…”.) A correct pick leads to an efficient parse. An incorrect pick leads to a mismatch between the fringe and the input, followed by a cycle of retracting and reexpanding the fringe until it finds the right pick or discovers, exhaustively, that no correct pick exists.

To make top-down parsing efficient, the algorithm needs a mechanism that determines, in one step, either the correct expansion or the fact that no correct expansion exists. It must, in some sense, implement oracular choice.

Consider the rules to expand Factor in the expression grammar, repeated in the margin. The top-down parser, trying to expand Factor to match a name must pick rule 11. Any consistent ordering among rules 9, 10, and 11 will produce the wrong choice (and backtrack) on at least two of the symbols: (, num, or name. The solution seems obvious: the parser should use the next input symbol—the lookahead symbol—to inform its choice. In this case, the combination of the current focus and the lookahead symbol let it pick the correct production.

We can modify the top-down parser from Fig. 3.3 so that it always picks the correct production in the grammar for Factor. Does this mechanism generalize to other grammars?

The top-down parser can pick the correct production if, at every step in the derivation, the grammar has the property that the lookahead symbol uniquely specifies the correct choice.

Backtrack-free grammar a CFG for which a leftmost, top-down parser can always predict the correct rule with bounded lookahead A backtrack-free grammar is sometimes called a predictive grammar.

For such a grammar, the top-down parser can disambiguate all of the choices with the combination of the current focus and a one-symbol lookahead. We call such a grammar backtrack free and note that it requires a one-symbol lookahead. A large subset of the CFGs are backtrack free.

To make efficient deterministic choices, the parser must know, for each possible expansion of a nonterminal A, the set of terminal symbols that can occur as the first symbol in a string derived from that expansion. If A→γ1∣γ2∣…∣γnA\rightarrow\gamma_{1}\mid\gamma_{2}\mid\ldots\mid\gamma_{n}, the parser needs to know which terminal symbols can occur at the start of a sentential form derived from each of the γi\gamma_{i}. If, for each pair of right-hand sides, the sets of such symbols are disjoint, then the top-down parser can always choose the correct expansion for A.

The intuition is clear. In the grammar for Factor, each right-hand side starts with a unique terminal symbol, so the disambiguating sets each contain one terminal. If, however, some right-hand side starts with a nonterminal, the construction of those sets is more difficult. for each a∈(T∪eof∪a) do FIRST(a)←a

for each A∈NT do FIRST(A)←A

while(FIRST sets are still changing) do for each p∈P, of the form A→β1β2…βk do rhs←FIRST(β1)-(a) trailing←true for i←1 to k-1 do if a∈FIRST(βi) then rhs←rhs∪(FIRST(βi+1)-(a)) else trailing←false break if trailing and a∈FIRST(βk) then rhs←rhs∪(a) FIRST(A)←FIRST(A)∪rhs

■FIGURE 3.7 Computing FIRST Sets for Symbols in a Grammar.

For each grammar symbol a, define the set FIRST(a) as the set of terminal symbols that can appear as the first word in some sentential form derived from a. The domain of FIRST is {NT∪T∪a∪eof}, the set of all grammar symbols. Its range is {T∪a∪eof}, the set of grammar symbols, minus the nonterminal symbols. (Note that {T∪eof} is the set of words that the scanner returns.) If a∈{T∪a∪eof}, then FIRST(a)={a}. For a nonter-minal A, FIRST(A) contains the complete set of terminal symbols that can appear as the leading symbol in a sentential form derived from A.

We defined FIRST sets over single grammar symbols. It is convenient to extend that definition of FIRST from a single grammar symbol to a string of symbols. For a string of symbols, s=β1β2β3…βk, we define FIRST(s) as the union of the FIRST sets for β1β2β3…βi, where βi is the first symbol whose FIRST set does not contain a. Further, a∈FIRST(s) if and only if it is in FIRST(βi) for each βi, 1≤i≤k.

Fig. 3.7 shows an algorithm to compute FIRST sets. As its initial step, the algorithm fills in the FIRST sets for the terminal symbols, a, and eof. For the right-recursive expression grammar shown in Fig. 3.5, that initial step produces the following FIRST sets:

FIRST set For a grammar symbol a, FIRST(a) is the set of terminals that can appear at the left end of a sentential form derived from a.

num name + - x + ( ) eof ε FIRST num name + - x + ( ) eof ε

Next, the algorithm iterates over the productions. For each production, A→β, it computes FIRST(β), using the extension from single symbol to string of symbols. The algorithm computes the FIRST set of the entire right-hand side into rhs and then adds rhs to the FIRST set of the nonterminal symbol on the production’s left-hand side. This process halts when it reaches a fixed point. For the right-recursive expression grammar, the FIRST sets of the nonterminals are:

Expr Expr’ Term Term’ Factor FIRST (, name, num +,-,ε (, name, num x,+ ,ε (, name, num

Conceptually, FIRST sets simplify implementation of a top-down parser. In the subgrammar for Factor, for example, the FIRST sets make obvious the correct choice among the productions.

Productions FIRST Set 9 Factor → (Expr) { ( } 10 | num { num } 11 | name { name }

For the Term’ subgrammar, however, the choice is less clear.

Productions FIRST Set 6 Term’ → x Factor Term’ {x} 7 | ÷ Factor Term’ {÷} 8 | ε { ε }

For rules 6 and 7, the choices are clear. Rule 8 poses a harder problem. FIRST(ε) does not match any word returned by the scanner.

Intuitively, the parser should apply the ε production when the lookahead symbol is not a member of the FIRST set of any of the other alternative productions—in this case, when the lookahead symbol is neither “x” nor “÷”. However, the parser should not accept just any word; some words will lead to derivations while others lead to syntax errors. To differentiate between these cases, the set used for rule 8 should contain any word that can for each A∈NT do FOLLOW(A)←A FOLLOW(S)←{eof} while(FOLLOW sets are still changing) do for each p∈P of the form A→β1β2β3…βk do TRAILER←FOLLOW(A) for i←k down to 1 do if βi∈NT then FOLLOW(βi)←FOLLOW(βi)∪TRAILER if∈FIRST(βi) then TRAILER←TRAILER∪(FIRST(βi)−ε) else TRAILER←FIRST(βi) else TRAILER←{βi}//βi∈T

Figure 3.8 Computing FOLLOW Sets for Nonterminal Symbols.

appear as the leading symbol after a valid application of rule 8-the set of words that can follow a Term’.

To capture that knowledge of the grammar’s structure, we define the set FOLLOW(A) to contain all of the words that can occur to the immediate right of a string derived from A. The domain of FOLLOW is NT and its range is TU{eof}. Fig. 3.8 presents an algorithm that computes the FOLLOW sets for a grammar; it uses the FIRST sets.

The FOLLOW set algorithm is more subtle than the FIRST set algorithm. To begin, it sets each FOLLOW set to the empty set. It then sets the start symbol’s FOLLOW set to {eof}. The main part of the algorithm iterates over the individual productions, refining FOLLOW sets. It halts when those sets reach a fixed point.

The construction uses adjacency in the right-hand side to update the FOL-LOW sets of nonterminals in that right-hand side. Ifβiβi+1 appears in some right-hand side, then FOLLOW(βi) should contain FIRST(βi+1). Rules with∈ complicate matters. If∈FIRST(βi+1), then FOLLOW(βi) should also contain the symbols that can followβi+1.

To capture this effect, the algorithm iterates over the right-hand side of each production,A→β1β2…βk fromβk toβ1. For each suffix,

βk;βk-1βk;…;β1β2…βk

it constructs the FIRST set. The variable TRAILER holds those FIRST sets;if someβi can derive∈,TRAILER carries forward the right context. Ifβi

FOLLOW set For a nonterminal α, FOLLOW(α) contains the set of words that can occur immediately after α in a sentence.

ProductionSTART Set
Goal → Expr { _, name, num }
Expr → Term Expr’ { _, name, num }
Expr’ → + Term Expr’ { + }
- Term Expr’ { - }
ε { eof, }
Term → Factor Term’ { _, name, num }
Term’ → × Factor Term’ { × }
÷ Factor Term’ { ÷ }
ε { eof, +, -, }
Factor → { Expr } { }
num { num }
name { name }

■ FIGURE 3.9 START Sets for the Right-Recursive Expression Grammar.

cannot derive ϵ\epsilon , the algorithm truncates that right context and sets TRAILER to FIRST(βi).

The FOLLOW sets for the right-recursive expression grammar are:

ExprExpr’TermTerm’Factor
FOLLOWeof,eof,eof, +,-,eof, +,-,eof, +,-,x,÷,

We introduced FOLLOW sets to allow the parser to make correct expansions of ϵ\epsilon productions, such as the subgrammar for Term’. The parser must choose between three right-hand sides for Term’.

FIRST(x Factor Term’)=(x) The FIRST sets make the choice clear for a lookahead of either x or÷. The difficult choice arises when the lookahead is neither x nor÷. Does the parser expand by ϵ\epsilon or does it throw a syntax error?

FOLLOW sets let the parser make this decision. If the lookahead symboll∈FOLLOW(Term′)l\in FOLLOW(Term') , the parser should expand by ϵ\epsilon . If l is not x or÷ andl∉FOLLOW(Term′)l\notin FOLLOW(Term') , then the input contains a syntax error.

The combination of FIRST and FOLLOW let us define precisely the correct behavior for the parser. For some production A→βA\rightarrow\beta :

START(A→β)={FIRST(β), if ϵ∉FIRST(β)(FIRST(β)−ϵ)∪FOLLOW(A), otherwise.START(A\rightarrow\beta)=\begin{cases} FIRST(\beta),\,if\,\epsilon\notin FIRST(\beta)\\(FIRST(\beta)-\epsilon)\cup FOLLOW(A),\,otherwise.\end{cases}

Fig. 3.9 shows the START sets for the right-recursive expression grammar.A top-down parser can use START sets to pick the correct expansion for any nonterminal A by comparing the lookahead symbol to the START sets of the alternative right-hand sides for A.

This observation leads to a simple and effective test to determine whether or not a grammar can be parsed, left-to-right, with a top-down parser without the need to backtrack. A grammar is backtrack free if and only if, for any nonterminal A with multiple right-hand sides, A→β1|β2|…|βn:

START(A→βi)∩START(A→βj)=∅, ∀  1≤i,j≤n,  i≠j.START(A\rightarrow\beta_{i})\cap START(A\rightarrow\beta_{j})=\emptyset,\,\forall\,\,1\leq i,j\leq n,\,\,i\neq j.

If a grammar has this property, a top-down parser can alway choose the correct expansion for a nonterminal A with a single lookahead symbol. This property is known as the LL(1) condition, because grammars that meet this condition can be parsed with an LL(1) parser(see Section 3.3.3).

Not all grammars are backtrack free. For example, consider extending the expression grammar to include function calls, denoted with([ and),and array-element references, denoted with[ and]. We can expand Factor→ name into three rules, plus appropriate productions to describe the argument lists.

Factor→ name is rule 11 in Fig. 3.5.

Because rules 11,12, and 13 all begin with name, their START sets are identical. When the parser tries to expand an instance of Factor with a lookahead of name, it has no basis to choose among 11,12, and 13. Single-word looka-head is not enough to resolve the choice. In this case, we can rewrite the grammar to create disjoint START sets.

A two-word lookahead would handle this case. However, for any finite lookahead, we can devise a grammar where that lookahead is insufficient.

Left factoring

the process of extracting and isolating common prefixes in a set of productions

11Factor→name Arguments12Arguments→[ArgList]13∣[ArgList]14∣ϵ\begin{array}{llll}\text{11}&\text{Factor}&\rightarrow&\text{name Arguments}\\\text{12}&\text{Arguments}&\rightarrow&[\text{ArgList}]\\\text{13}&&\mid&[\text{ArgList}]\\\text{14}&&\mid&\epsilon\end{array}

This rewrite, called left factoring, breaks the derivation of Factor into two steps. The first step matches the common prefix of the original rules 11,12, word ← NextWord() push eof onto Stack push the start symbol, S, onto Stack

while(true) do focus ← top of Stack if (focus = eof and word = eof) then report success and break from the loop else if (focus ∈ T or focus = eof) then if focus matches word then pop Stack word ← NextWord() else report an error looking for the symbol in focus else // focus is a nonterminal if Table[focus, word] is A → β₁ β₂… βₖ then pop Stack for i ← k to 1 by -1 do if (βᵢ ≠ ε) then push βᵢ onto Stack else report an error expanding focus

■ FIGURE 3.11 The Skeleton LL(1) Parser.

based on the START sets of their right-hand sides. For each right-hand side, the code tests directly for any further symbols.

To test for the presence of a nonterminal, say A, the code invokes the procedure that corresponds to A. To test for a terminal symbol, such as name, it performs a direct comparison and, if successful, advances the input stream by calling the scanner, NextWord(). If it matches an ε-production, the code does not call NextWord(). Fig. 3.10 shows pseudocode for a recursive descent parser for expressions. Look at the implementation of TermPrime in the upper right corner; it follows this scheme with explicit tests against the symbols in the various START sets. It combines the code for rules 6 and 7.

The strategy for constructing a complete recursive-descent parser is clear. For each nonterminal, we construct a procedure to recognize its alternative right-hand sides. These procedures call one another to recognize nonterminals. They recognize terminals by direct matching. Each routine returns an indicator of success or it calls Fail. eof+ x+ num name

Goal

Expr

Expr’

Term

Term’

Factor

0 1 4 5 8 9 10 11

■ FIGURE 3.12 LL(1) Parse Table for the Right-Recursive Expression Grammar.

Section titled “■ FIGURE 3.12 LL(1) Parse Table for the Right-Recursive Expression Grammar.”

For a small grammar, a compiler writer can quickly craft a recursive-descent parser. A recursive-descent parser can produce accurate, informative error messages. The natural location for generating those messages is when the parser fails to find an expected terminal symbol-inside ExprPrime, TermPrime, and Factor in the example.

Given START sets, we can automate generation of top-down parsers for backtrack-free grammars. To do so, we build a tool, a parser generator, that constructs FIRST, FOLLOW, and START sets, and then uses the START sets to construct a top-down parser.

One scheme to build top-down parsers creates table-driven LL(1) parsers. Any backtrack-free grammar is usable in an LL(1) parser. The name LL(1)derives from the fact that these parsers scan their input Left to right, discover a Leftmost derivation, and use a 1 symbol lookahead.

To build an LL(1) parser, the compiler writer creates a right-recursive, backtrack-free grammar. A parser generator constructs the actual parser. Most LL(1) parser generators use a table-driven skeleton parser, such as the one shown in Fig. 3.11. The parser generator constructs the table. Fig. 3.12 shows the LL(1) table for the right-recursive expression grammar.

In the skeleton parser, the variable focus holds the next grammar symbol that must be matched on the partially built parse tree’s lower fringe-the same role it played in the top-down parser from Fig. 3.3. The LL(1) table maps pairs of nonterminals and lookahead symbols(terminals or eof) into productions. Given a nonterminal A and a lookahead symbol w, Table[A,w]specifies the correct expansion.

The example in Fig. 3.13(a) shows the actions of the LL(1) expression parser for the input string a+bxc. The central column shows the contents of the parser’s stack, which holds the partially built lower fringe of the parse tree. The parse concludes successfully when it pops Expr’ from the stack, leaving eof exposed on the stack and eof, implicitly, as the lookahead symbol.

Parser generator

a tool that builds a parser from specifications, usually a BNF-like grammar

Backtrack-free grammars are often called LL(1) grammars.

RuleStackInput
—eof Goal↑ name + name × name
0eof Expr↑ name + name × name
1eof Expr’ Term↑ name + name × name
5eof Expr’ Term’ Factor↑ name + name × name
11eof Expr’ Term’ name↑ name + name × name
→eof Expr’ Term’name ↑ + name × name
8eof Expr’name ↑ + name × name
2eof Expr’ Term +name ↑ + name × name
→eof Expr’ Termname + ↑ name × name
5eof Expr’ Term’ Factorname + ↑ name × name
11eof Expr’ Term’ namename + ↑ name × name
→eof Expr’ Term’name + name ↑ × name
6eof Expr’ Term’ Factor ×name + name ↑ × name
→eof Expr’ Term’ Factorname + name × ↑ name
11eof Expr’ Term’ namename + name × ↑ name
→eof Expr’ Term’name + name × name ↑
8eof Expr’name + name × name ↑
4eofname + name × name ↑

(a) Actions of the LL(1) Parser on a + b × c

RuleStackInput
—eof Goal↑ name + ÷ name
0eof Expr↑ name + ÷ name
1eof Expr’ Term↑ name + ÷ name
5eof Expr’ Term’ Factor↑ name + ÷ name
11eof Expr’ Term’ name↑ name + ÷ name
→eof Expr’ Term’name ↑ + ÷ name
8eof Expr’name ↑ + ÷ name
2eof Expr’ Term +name ↑ + ÷ name
syntax error→eof Expr’ Term

(b) Actions of the LL(1) Parser on x + ÷ y for each nonterminal A do Table[A,eof]←error for each terminal w do Table[A,w]←error for each production p of the form A→β do for each terminal w∈START(A→β) do Table[A,w]←p if eof∈START(A→β) then Table[A,eof]←p

Figure 3.14 LL(1) Table-Construction Algorithm.

As Fig. 3.13(a) shows, the LL(1) parser is efficient. It takes time proportional to the size of the derivation. It shifts every grammar symbol in the derivation onto the stack and later pops each of them off the stack. We cannot expect a parser to construct a derivation in fewer steps.

Now consider the actions of the LL(1) parser on the illegal input string x+y, shown in Fig. 3.13(b). It recognizes the first name and the +. At that point, it has Term at the top of the stack and a lookahead symbol of +. The corresponding table entry contains error.

Table has a row for each nonterminal symbol and a column for each terminal symbol. The algorithm to fill the table is straightforward. It assumes that START sets are available for the grammar.

The construction. shown in Fig. 3.14, assigns each production an ordinal number and initializes each table entry to error. Next, for each production A→β and each symbol w∈START(A→β), it sets the table entry for row A and column w to contain the production’s number. For the right-recursive expression grammar, this produces the table shown in Fig. 3.12.

For a grammar that meets the LL(1) condition(see page 111), this construction will produce a correct table in O(|P|×|T|) time, where P is the set of productions and T is the set of terminals.

If the construction assigns multiple production numbers to Table[A,w], then multiple right-hand sides for A have w in their START sets, violating the LL(1) condition. Since Table is initialized to error, the table builder can test before each assignment and report a problem if the entry is not set to error.

As an alternative to the table-driven parser, an LL(1) parser generator could simply emit a recursive-descent parser. The process would be similar to that used to construct a table-driven LL(1) parser. First, the parser generator would build FIRST, FOLLOW, and START sets. Next, it would iterate over the nonterminal symbols from the left-hand sides of the grammar rules. For each such nonterminal, it would emit a small procedure to recognize its var-ous right-hand sides. The code would use the START sets to make decisions. Such a system could combine the speed and locality of a recursive-desce parser with the convenience of a grammar-based generator.

Top-down parsers are simple, compact, and efficient. They can be implemented in a number of ways, including hand-coded, recursive-descent parsers and generated LL(1) parsers. Because these parsers know, at each point in the parse, the set of words that can occur as the next symbol in a valid input string, they can produce accurate and useful error messages.

Most programming-language constructs can be expressed in a backtrack-free grammar. Thus, these techniques have widespread application. The restriction that alternate right-hand sides for a nonterminal have disjoint START sets does not seriously limit the utility of LL(1) grammars. The primary drawback of top-down, predictive parsers lies in their inability to handle left recursion.

  1. To build an efficient top-down parser, the compiler writer must express the source language in a somewhat constrained form. Explain the restrictions on the source-language grammar that are required to make it amenable to efficient top-down parsing.
  2. Name two potential advantages of a hand-coded recursive-descent parser over a generated, table-driven LL(1) parser, and two advantages of the LL(1) parser over a recursive-descent implementation.

Bottom-up parsers discover a derivation by working from the words in the program toward the start symbol, S. We can think of this process as building the parse tree starting from its leaves and working toward its root. For a derivation:

Start = γ0 → γ1 → γ2 → … → γn-1 → γn = sentence

a bottom-up parser repeatedly discovers, from γi and the grammar, the production A → β and the location k in γi such that replacing the occurrence of β that ends at position k in γi with A produces γi-1. push INVALID on to the stack word ← NextWord() repeat until (top of stack = S and word = eof) do if the top of stack is a handle A → β then // reduce β to A pop |β| symbols off the stack push A onto the stack else if (word ≠ eof) then // shift word onto the stack push word onto the stack word ← NextWord() else // parser needs to shift, but is out of input throw a syntax error report success

■ FIGURE 3.15 A Simple Shift-Reduce Parser.

The pair ⟨A → β,k⟩ describes this transition from γᵢ to γᵢ₋₁. We call this pair a handle. The parser repeatedly finds a handle in the frontier and rewrites β with A. In a valid derivation from an unambiguous grammar, each γᵢ should have exactly one handle, for all 0<i ≤ n.

A bottom-up parser operates by finding the series of handles that define a legal derivation for the input program. Fig. 3.15 shows a high-level algorithm for a shift-reduce parser.

The parser repeats a simple process. It repeatedly shifts words-⟨lexeme, category⟩ pairs from the scanner—onto a stack until it finds a handle on the stack. The handle will appear with its right-end at the top of the stack. When it finds a handle for A → β, it pops the stack entries for β from the stack and pushes an entry for A onto the stack—a reduce action in the terminology of bottom-up parsing.

The parser continues shifting and reducing until either:

  1. The parser finds the grammar’s start symbol, S, on top of the stack. If the parser finds S on top of the stack and the lookahead word is eof, then the parse succeeds. If the lookahead word is not eof, then more input remains to be processed.

  2. The scanner returns eof and the parser does not reduce the stack to S. In this case, it has consumed all of the input without finding a legal derivation. The parser should report a syntax error—that is, the input program contains one or more errors.

Handle A handle of a sentential form γᵢ is a pair. ⟨A → β,k⟩, such that β appears in the sen-tential form with its right end at position k and replacing β with A produces the prior step in the derivation, γᵢ₋₁.

This error-finding mechanism does not localize the error. LR(1) parsers detect errors where they occur. The key to practical bottom-up parsing is the ability to recognize handles efficiently. The LR(1) parsers implement a particularly efficient handle-finding mechanism. We will return to the subject of handles and handle-finding throughout Section 3.4. First, however, we will finish our high-level description of bottom-up parsers.

Consider an extension of the shift-reduce parser that builds an actual parse tree. Each shift action constructs a leaf node to represent the lookahead symbol, then advances the lookahead symbol by calling the scanner. Each reduce action adds a node that represents a nonterminal on top of the partially built parse tree. These interior nodes for nonterminals record the grammatical structure discovered in the derivation of the input string.

At any stage in the parse, the partially built parse tree represents the state of the parse. Each leaf node represents a word; reading the leaves left-to-right shows a prefix of the input program. Interior nodes, above the leaves, encode those parts of the derivation that the parser has found. The parser works along the upper frontier of this partially built parse tree; that frontier corresponds to the current sentential form in the derivation being built by the parser.

To extend the frontier upward, the parser finds a handle, ⟨A→β,k⟩. Thus, β occurs on the frontier with its right end at position k, and the parser knows that replacing β with A will create, along the frontier, the previous sentential form in the derivation. (If the frontier represents γi, then the reduced frontier will represent γi-1.) This process constructs the derivation in reverse—that is, from the sentence to the start symbol rather than from the start symbol to the sentence.

Our conceptual parser builds a rightmost derivation, in reverse order. This order reconciles the scanner’s left-to-right scan with the parser’s rightmost derivation. In a rightmost derivation, the leftmost leaf is considered last. Reversing that order leads to the desired behavior: leftmost leaf first and rightmost leaf last.

At each point, the shift-reduce parser operates on the frontier of the partially built parse tree; the contents of the stack, read bottom-to-top, are a prefix of the corresponding sentential form in the derivation. Because each sentential form occurs in a rightmost derivation, the unexamined suffix—that part beyond the top of the stack—consists entirely of terminal symbols. When the parser needs more right context, it calls the scanner.

With an unambiguous grammar, the rightmost derivation is unique. For a large class of unambiguous grammars, γi-1 can be determined directly from γi (the parse tree’s upper frontier) and a limited lookahead into the input push(INVALID,INVALID) onto the stack

push(start symbol, s0) onto the stack

word← NextWord()

while(true) do

state← state from pair at top of stack

if Action[state, word]=“reduce A→β” then

pop|β| pairs from the stack

state← state from pair at top of stack

push(A,Goto[state,A]) onto the stack

else if Action[state, word]=“shift s,” then

push(word,s,) onto the stack

word← NextWord()

else if Action[state, word]=“accept” and word=eof

then break

else throw a syntax error

report success/* executed the “accept” case*/

Figure 3.16 The Skeleton LR(1) Parser.

stream. In other words, given a frontier γi\gamma_{i} and a limited amount of looka-head, the parser can find, efficiently and deterministically, the handle that takes γi\gamma_{i} to γi−1.\gamma_{i-1}.

LR(1) parsers are a particularly efficient implementation of these handle-finding, shift-reduce parsers. An LR(1) parser scans the input from left to right to build a rightmost derivation in reverse. At each step, it makes decisions based on the history of the parse and a lookahead of, at most, one symbol. The name LR(1) derives from these properties: Left-to-right scan, Reverse rightmost derivation, and 1 symbol of lookahead. Tools that build LR(1) parsers are widely available.

Informally, we will say that a language has the LR(1) property if it can be parsed in a single left-to-right scan to build a reverse-rightmost derivation using just one symbol of lookahead to determine parsing actions. In practice, the simplest test to determine if a grammar has the LR(1) property is to let a parser generator try to build the LR(1) parser. If it fails, the grammar is not an LR(1) grammar.

The remainder of this section presents a detailed introduction to the theory of LR(1) parsing. Section 3.4.1 introduces LR(1) parsers and their operation. Section 3.4.2 presents an algorithm to build the tables that encode an LR(1)parser. Finally, Section 3.4.3 shows what happens when the construction is applied to a non-LR(1) grammar.

StateAction TableGoto Table
0s 31
1acc4
2r 3
3s 75
4r 2
5Pair9
6s 710
7s 711
8r 5
9r 2
10r 4
11s 713
12r 5
13r 4

(a) Parentheses Grammar (b) Action and Goto Tables for Parentheses Grammar

■ FIGURE 3.17 The Parentheses Grammar.

The critical step in a bottom-up parser, such as a table-driven LR(1) parser, is to find the next handle. Efficient handle discovery is the key to efficient bottom-up parsing. An LR(1) parser uses a handle-finding automaton, encoded into two tables, traditionally called Action and Goto. Fig. 3.16 shows a simple table-driven LR(1) parser.

The skeleton LR(1) parser interprets the Action and Goto tables to find successive handles in the reverse rightmost derivation of the input. When it finds a handle ⟨A→β,k⟩, it reduces β at k to A in the current sentential form—the upper frontier of the partially built parse tree. Rather than build an explicit parse tree, the skeleton parser keeps a prefix of the tree’s upper frontier on a stack. Each stack entry is a pair ⟨A,s⟩ where A is a grammar symbol and s is a parser state. The states thread together the reductions into a parse. The variable word holds the lookahead symbol—the first word beyond the stack’s contents.

To find the next handle, the LR(1) parser shifts symbols onto the stack until the automaton finds the right end of a handle at the stack top. Once it has a

IterationStateWordStackHandleAction
0-((Goal0)(Goal0)-none--
10((Goal0)(Goal0)-none-shift 3
23((Goal0)((3)(Goal0)\quad((3)-none-shift 8
38eof(Goal0)((3)(8)(Goal0)\quad((3)\quad (8)(reduce 5
42eof(Goal0)(Pair2)(Goal0)\quad(Pair2)Pairreduce 3
51eof(Goal0)(List1)(Goal0)\quad(List1)Listaccept

■ FIGURE 3.18 States of the LR(1) Parser on().

handle, A→β, the parser reduces, replacingβ with A. It pops the symbols inβ and their associated states from the stack and pushes A and its new state onto the stack. The Action and Goto tables thread together actions(shifts and reduces) and states in a grammar-driven sequence to find a rightmost derivation, if one exists.

To make this concrete, consider the grammar from Fig. 3.17(a), which describes the language of properly nested parentheses. Panel(b) shows the Action and Goto tables for this grammar. They encode the handle-finding automaton for the parentheses language.

Fig. 3.18 shows the sequence of actions that the parser takes on the input string “()”. Each line shows one iteration of the parser; the first line shows the parser’s initial state. The final column shows the parsing action dictated by the table in that iteration.

At the start of the first iteration, the stack lacks a handle. The Action table tells the parser to shift( onto the stack and move to state 3. At the start of the second iteration, the stack still lacks a handle; the Action table causes the parser to shift) onto the stack and move to state 8.

In the third iteration, the stack contains the handle Pair→( ); its right end lies at the stack top. The Action table directs the parser to reduce() to Pair. Using the state beneath Pair on the stack, 0, and Pair, the parser moves to state Goto[0,Pair]=2.

In the fourth iteration, Pair is atop the stack. The parser finds the handle List→Pair, reduces, and moves to state Goto[0,List]=1. Finally, in state 1,the parser finds the handle Goal→List and accepts.

For the input(), the parser used two shifts, two reduces, and one accept. In general, LR(1) parsers take time proportional to the length of the input(one shift per word) and the length of the derivation(one reduce per derivation step). Thus, derivation length is a lower bound on parsing time.

Using a stack lets the LR(1) parser make the position, k, in the handle be constant and implicit.

This simplification makes the set of handles finite and recognizable by a DFA.

The symbol S on the stack represents the pair(INVALID,INVALID).

The chain of handles,(5,3,1), shows rightmost derivation in reverse order.

The accept action is a special action that signals a reduction to the goal symbol with lookahead eof.

IterationStateWordStackHandleAction
0—($ (Goal 0)-none-—
10($ (Goal 0)-none-shift 3
23($ (Goal 0) ⟨( 3)-none-shift 7
37)$ (Goal 0) ⟨( 3) ⟨( 7)-none-shift 12
412)$ (Goal 0) ⟨( 3) ⟨( 7) ⟨( 12)( )reduce 5
56)$ (Goal 0) ⟨( 3) ⟨Pair 6⟩Pairreduce 3
65)$ (Goal 0) ⟨( 3) ⟨List 5⟩-none-shift 10
710($ (Goal 0) ⟨( 3) ⟨List 5⟩ ⟨( 10)( List )reduce 4
82($ (Goal 0) ⟨Pair 2⟩Pairreduce 3
91($ (Goal 0) ⟨List 1⟩-none-shift 3
103)$ (Goal 0) ⟨List 1⟩ ⟨( 3)-none-shift 8
118eof$ (Goal 0) ⟨List 1⟩ ⟨( 3) ⟨( 8)( )reduce 5
124eof$ (Goal 0) ⟨List 1⟩ ⟨Pair 4⟩List Pairreduce 2
131eof$ (Goal 0) ⟨List 1⟩Listaccept

■ FIGURE 3.19 States of the LR(1) Parser on ( ( ) ( ) ( ).

Fig. 3.19 shows the parser’s behavior for the input “( ( ) ( ) ( ).” The parser performs six shifts, six reduces, and one accept. Fig. 3.20 shows the state of the partially built parse tree at the end of each iteration, from 1 to 12. The accept action could add a node for the Goal symbol if needed. The top of each drawing shows an iteration number and a gray bar that contains the partial parse tree’s upper frontier—the symbols on the stack in an LR(1) parser.

Handle Finding

The LR(1) parser’s ability to find handles on the stack is the key to its operation. Consider the parser’s actions on the string “( )”, shown in Fig. 3.18. Iterations 1 and 2 have no handle on top of the stack, so it shifts. In each of iterations 3, 4, and 5, it finds a handle atop the stack.

Iteration 3 (state 8): The stack top ( ) forms the handle for rule 5. Action[8,eof] = Action[8,() = reduce 5.

Iteration 4 (state 2): The stack top Pair forms the handle for rule 3. Action[2,eof] = Action[2,() = reduce 3.

Iteration 5 (state 1): The stack top List forms the handle for rule 1 if the lookahead is eof. Action[1,eof] = accept. With other lookaheads, List is not a handle. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

Between these two examples, the parser recognized () as a handle three times. Each case behaved differently, based on the prior left context encoded in the state under () on the stack. Comparing these three situations exposes how the stacked states encode left context and control the future direction of the parse.

With the first example, in Fig. 3.18, the parser was in state 8 when it found the handle (), with a lookahead of eof. The state underneath the handle was 0, and Goto[0,Pair] = 2. In state 2, a lookahead of eof led to a reduction by rule 3 followed by an accept.

If, instead of eof, the lookahead in state 2 had been ), the parser would have thrown an error. A lookahead of ( would have led to a reduction by rule 3—setting up to recognize more nested parentheses.

The second example, in Fig. 3.19, finds a handle for () twice. The first handle occurs in iteration 4. The parser is in state 12 with a lookahead of ). It has previously shifted (, (, and ) onto the stack. Action[12,) = reduce 5. The state below () is 3, and Goto[3,Pair] = 6, a state in which further )‘s are legal. The handle () also occurs in iteration 11. Here, state 1 is beneath () on the stack and Goto[1,Pair] = 4. In state 4, a lookahead of either eof or ( triggers a reduction of List Pair to List, while a lookahead of ) is an error.

The Action and Goto tables, along with the stack, cause the parser to track prior left context and let it take different actions based on that context. This context, in turn, lets the parser handle correctly each of the three instances in which it found a handle for (). We will revisit this issue when we examine the construction of Action and Goto.

To see how an LR(1) parser discovers a syntax error, consider the sequence of actions that it takes on the string “()”.

IterationStateWordStackHandleAction
0—($ <Goal 0>-none-—
10($ <Goal 0>-none-shift 3
23)$ <Goal 0> ⟨( 3)-none-shift 8
38)$ <Goal 0> ⟨( 3) ⟨( 8)-none-error

The initial state and the first two iterations of the parse match the first example, “()”. The parser shifts ( and ). In the third iteration of the while loop, the parser reads Action[8.)] and finds an invalid entry. The invalid entry causes the parser to throw an error.

The LR(1) parser detects syntax errors with a simple mechanism: it finds an invalid table entry. It detects the error as soon as possible, before it reads a word beyond those needed to prove the input erroneous. This property localizes the error to a specific point in the input. Using the available context and knowledge of the grammar, an LR(1) parser can provide good diagnostic error messages.

Error localization is a particular strength of LR(1) parsers.

The key to LR parsing lies in the construction of the Action and Goto tables. The tables encode all of the legal reduction sequences that can arise in a reverse rightmost derivation for the given grammar. While the number of such sequences is huge, the grammar itself constrains the order in which reductions can occur.

The compiler writer can build Action and Goto tables by hand. However, the table-construction algorithm requires scrupulous bookkeeping; it is a prime example of the kind of task that should be automated and relegated to a computer. Programs that automate this construction are widely available. The next section presents one algorithm that can be used to construct LR(1)parse tables.

With an LR(1) parser generator, the compiler writer’s role is to define the grammar and to ensure that the grammar has the LR(1) property. In practice, the parser generator identifies the productions that introduce ambiguity or that need more than a one word lookahead to distinguish a shift action from a reduce action. As we study the table-construction algorithm, we will see how those problems arise, how to cure them, and how to understand the kinds of diagnostic information that LR(1) parser generators produce.

The ideas that underlie LR(1) parsers actually define a family of parsers that vary in the amount of lookahead that they use. An LR(k) parser uses, at most, k lookahead symbols. Additional lookahead allows an LR(2) parser to recognize a larger set of grammars than an LR(1) parser. Almost para-doxically, the added lookahead does not increase the set of languages that these parsers can recognize. LR(1) parsers accept the same set of languages as LR(k) parsers for k> 1. The LR(1) grammar for a language may be more complex than an LR(2) or LR(3) grammar.

To construct the Action and Goto tables for a grammar, an LR(1) parser generator builds a model of the handle-recognizing automaton and uses that model to fill in the tables. The model, called the canonical collection of sets of LR(1) items, represents all of the possible states of the parser, as well as the transitions between those states. The process is reminiscent of the subset construction from Section 2.4.3.

The Parentheses Grammar

1 Goal→ List

2 List→ List Pair

3|Pair

4 Pair→(List)

5|()

To illustrate the table-construction algorithm, we will use two examples. The first is the parentheses grammar from Fig. 3.17(a), repeated in the margin. It is small enough to use as a running example, but large enough to exhibit some of the complexities of the process. The second example, in Section 3.4.3, is an abstracted version of the classic if-then-else ambiguity. The construction fails on this grammar because the grammar is ambiguous. The example highlights the situations that lead to failures in the table-construction process.

In an LR(1) parser, the Action and Goto tables encode information about handles and potential handles at each step in the parse. The table-construction algorithm uses LR(1) items to represent handles, potential handles, and the associated lookahead symbols. An LR(1) item[A→β·y,a] consists of a production A→βy; a placeholder,●, that indicates the position of the stack-top in the production’s right-hand side; and a specific terminal symbol, a, as a lookahead symbol.

[ A→β ∙ γ,a]A\rightarrow\beta\,\bullet\,\gamma,a] where A→βγA\rightarrow\beta\gamma is a grammar production,● represents the position of the parser’s stacktop, and a is a terminal symbol in the grammar

The table-construction algorithm builds the canonical collection of sets of LR(1) items, CC={CC0,CC1,CC2,…,CCn}. Each CC1∈CC represents a valid configuration of the LR(1) parser, or a state of the parser. It contains one or more LR(1) items that represent handles or potential handles that correspond to the parse state. Before we delve into the table construction, more explanation of LR(1) items is needed.

For a production A→βγA\rightarrow\beta\gamma and a lookahead symbol a, the placeholder can generate three distinct items, each with its own interpretation. In each case, the presence of the item in some set CCiCC_{i} in the canonical collection indicates input that the parser has seen is consistent with the occurrence of an A followed by an a in the grammar. The position of● in the item distinguishes between the three cases.

1.[A→βy,a] indicates that an A would be valid and that recognizing aβ next would be one step toward discovering an A. We call such an item a possibility; it represents a possible completion for the input already seen.

Figure 3.21 LR(1) Items for the Parentheses Grammar.

The figure enumerates LR(1) items for the parentheses grammar, including items for Goal, List, and Pair productions with lookahead symbols such as eof, (, and ). Items place the dot at different positions to show parser progress through each production.

[A -> beta dot gamma, a] indicates that the parser has progressed from [A -> dot beta gamma, a] by recognizing beta; one valid next step would be to recognize gamma. We call such an item partially complete.

[A -> beta gamma dot, a] indicates that the parser has found beta gamma in a context where an A followed by an a would be valid. If the lookahead symbol is a, then the item is a handle and the parser can reduce beta gamma to A. We call such an item complete.

In an LR(1) item, the symbols to the left of the placeholder represent left context. The lookahead symbol provides right context. When the parser finds itself in a state that includes [A -> beta gamma dot, a] and the lookahead is a, it has a handle and should reduce beta gamma to A.

Fig. 3.21 shows the complete set of LR(1) items generated by the parentheses grammar. The first two items in the upper left corner deserve particular notice: [Goal -> dot List, eof] represents the parser’s initial state, and [Goal -> List dot, eof] represents the desired final state.

To build the canonical collection of sets of LR(1) items, CC, a parser generator starts from the parser’s initial state,[Goal→●List, eof], and construct a model of all the potential transitions that can occur. The algorithm represents each possible configuration, or state, of the parser as a set of LR(1)items. The algorithm applies two operations to these sets of LR(1) items.taking a closure and computing a transition.

■ The closure function completes a state; given some core set of items, it adds to that set any related LR(1) items that they imply. For ex.ample, anywhere that Goal→List is legal, the productions that derive a List are legal, too. Thus, the item[Goal→●List, eof] implies both[List→●List Pair, eof] and[List→●Pair, eof]. Closure finds all such items and adds them to the state.

■ The goto function models the effect of a transition from some state s on a grammar symbol x. To do so, the algorithm examines the set of LR(1)items in s. It finds each item where● precedes x, moves the● past the x, and places this new item into the set that goto returns as its result. Finally, it uses closure to complete the new state.

To make the start symbol easy to find, we require that the grammar have a unique start symbol that does not appear on the right-hand side of any production. In the parentheses grammar, that symbol is Goal.

The item[Goal→●List, eof] represents the parser’s initial state for the parentheses grammar; every valid parse recognizes Goal followed by eof. This item forms the core of CC0, the first state in CC.

To compute the complete initial state of the parser, CC0, from its core, the algorithm must add to the core all of the items implied by the items in the core. Fig. 3.22(a) shows the algorithm, closure, for this computation. It iterates over all the items in set s. If the placeholder● in an item immediately precedes some nonterminal C, then closure must add one or more items for each production that can derive C. Closure places the● at the initial position of each item that it builds this way.

Here,β andδ represent possible symbols before or after follow C. Eitherβ orδ may be empty.

The rationale for closure is clear. If[A→β●Cδ,a]∈s and the parser recognizes a C followed byδa, it should reduceβCδ to A. Closure adds an item to s for each such possibility.

In our experience, this use of FIRST(δa)is the point in the LR(1) table construction where a human is most to likely make a mistake. For some production C→y, closure builds an item for each each terminal symbol in FIRST(δa). It inserts the placeholder symbol● before y and adds the appropriate lookahead symbol.

closure(s)

while(s is still changing) do

for each item[A→β●C8,a]∈S do

lookahead←8a

for each production C→y∈P do

for each b∈FIRST(lookahead) do

s←s U{(C→y,b)|}

return s

(a) The Closure Function

goto(s,x)

t←n

for each item i∈s do

if i is[a→β·x8,a] then

t←t U{[a→βx·8,a]}

return closure(t)

(b) The Goto Function

FIGURE 3.22 Support Functions for the LR(1) Table Construction.

For the parentheses grammar, the construction creates CC0 by building a set with the initial item,{[Goal→●List, eof]},and computing its closure:

CC_{0}=\left\{\begin{aligned}&{[Goal\rightarrow\,\bullet\,List,\,eof],\,[List\rightarrow\,\bullet\,List\,Pair,\,eof],\\ &{[List\rightarrow\,\bullet\,List\,Pair,\,\underline{]},\,[List\rightarrow\,\bullet\,Pair,\,eof],\\ &{[List\rightarrow\,\bullet\,Pair,\,\underline{]},\,[Pair\rightarrow\,\bullet\,(\underline{}\,List\,),\,eof],\\ &{[Pair\rightarrow\,\bullet\,(\underline{}\,List\,),\,\underline{]},\,[Pair\rightarrow\,\bullet\,(\underline{}\,),\,eof],\\ &{[Pair\rightarrow\,\bullet\,(\underline{}\,),\,\underline{]}\end{aligned}\right\}

Closure is another example of a fixed-point computation. The triply-nested loop either adds items to s or leaves s intact. It never removes an item from s. Since the set of LR(1) items is finite, this loop must halt. The triply nested loop looks expensive. However, close examination reveals that each item in s needs to be processed only once. A worklist version of the algorithm can capitalize on that fact.

The second key operation in the construction is the function goto. Goto takes as input a set that models a parser state, one of the Cci∈CC, and a grammar symbol x. From CCi and x, it computes a model of the parser state that would result from recognizing an x in the state Cci.

The goto function, shown in Fig. 3.22(b), takes a set of LR(1) items s and a grammar symbol x and returns a new set of LR(1) items. It iterates over the items in s. When it finds an item in which the immediately precedes x, it creates a new item by moving the rightward past x. This new item represents the parser’s configuration after recognizing x. Goto places these new items in a new set, takes its closure to complete the parser state, and returns that new state.

Given CC0, shown earlier, the construction can derive the state that the parser will reach after an initial( by computing goto(CC0,().The inner loop in goto cc0 ← 0 for each production of the form Goal → α do cc0 ← cc0 ∪ { [Goal → α, eof] } cc0 ← closure(cc0) CC ← { cc0 } while (new sets are still being added to CC) do for each unmarked set cci ∈ CC do mark cci as processed for each x following a • in an item in cci do temp ← goto(cci, x) if temp ≠ CC then CC ← CC ∪ {temp} record transition from cci to temp on x

■ FIGURE 3.23 The Algorithm to Build the Canonical Collection of Sets of LR(1) Items.

finds four items that contain “•_”. From each of those items, goto creates a new item with the • moved past the _. These items form the core of the new set—the first four items. Goto then invokes closure to complete the set. In the construction, this set becomes CC3.

cc3 = { [Pair → (• List), eof] [Pair → (• List), _] [Pair → (•), eof] [Pair → (•), _] [List → • List Pair, _] [List → • List Pair, _] [List → • Pair, _] [List → • Pair, _] [Pair → • (List), _] [Pair → (• (List), _)] [Pair → (•), _] [Pair → (•), _] } Goto created the first four items directly. Closure added the rest.

The Algorithm

To construct the canonical collection of sets of LR(1) items, CC, the algorithm computes the initial set, cc0, and then systematically finds sets that represent each possible parser state reachable from cc0. It repeats this process with each new set, until it has built the set of all reachable parser states. Fig. 3.23 shows the algorithm.

To compute the initial state, the algorithm constructs an LR(1) item that represents each production that has the goal symbol on its left-hand side. It computes cc0 as the closure of the union of these items.

To find all the states reachable from cc0, the algorithm finds each symbol x that follows the placeholder in an item in cc0. For each such x, it computes goto(cc0,x). If that set is not already in CC, it adds the set to CC. It also records the transition on x from cc0 to goto(cc0,x).

IterationSetGoalListPair()
1CC00CC1CC2CC30
2CC100CC4CC30
CC200000
CC30CC5CC6CC7CC8
3CC400000
CC500CC9CC7CC10
CC600000
CC70CC11CC6CC7CC12
CC800000
4CC900000
CC1000000
CC1100CC9CC7CC13
CC1200000
5CC1300000

■ FIGURE 3.24 Trace of the LR(1) Construction on the Parentheses Grammar.

To build the complete canonical collection, the algorithm repeats this process with each successive set in the collection, CC. The process is reminiscent of the subset construction(see Section 2.6). To ensure that the algorithm processes each set CCi exactly once, it uses a simple marking scheme. It creates each set in an unmarked condition and marks the set as it is processed, which drastically reduces the number of times that it invokes goto and closure.

This construction is a fixed-point computation. The canonical collection CC is a subset of the powerset of the LR(1) items. The while loop is monotonic in the size of CC; it adds new sets to CC but never removes one. If the set of LR(1) items has n elements, then CC can grow no larger than 2n items. Since 2n is finite, the computation must halt.

This upper bound on the size of the canonical collection is quite loose. For example, the parentheses grammar has 38 LR(1) items, but it produces a CC that has only 14 sets. The upper bound would be 238, a much larger number. For more complex grammars, the size of CC is a concern, primarily because the Action and Goto tables grow with|CC|. As described in Section 3.6, both the compiler writer and the parser-generator writer can take steps to reduce the size of those tables.

A worklist formulation would achieve the same effect.

CC0 = { [Goal → • List, eof] [List → • List Pair, eof] [List → • List Pair, ( )] [List → • Pair, eof] [List → • Pair, ( )] [Pair → • ( List ), eof] [Pair → • ( List ), ( )] [Pair → • ( ), eof] [Pair → • ( ), ( )]

CC1 = { [Goal → List •, eof] [List → List • Pair, eof] [List → List • Pair, ( )] [Pair → • ( List ), eof] [Pair → • ( List ), ( )] [Pair → • ( ), eof] [Pair → • ( ), ( )]

CC2 = { [List → Pair •, eof] [List → Pair •, ( ) }

CC3 = { [Pair → ( • List ), eof] [Pair → ( • List ), ( )] [Pair → ( • ), eof] [Pair → ( • ), ( )] [List → • List Pair, ( )] [List → • List Pair, ( )] [List → • Pair, ( )] [List → • Pair, ( )] [Pair → • ( List ), ( )] [Pair → • ( List ), ( )] [Pair → • ( ), ( )] [Pair → • ( ), ( )]

CC4 = { [List → List Pair •, eof] [List → List Pair •, ( ) }

CC5 = { [List → List • Pair, ( )] [List → List • Pair, ( )] [Pair → ( List • ), eof] [Pair → ( List • ), ( )] [Pair → • ( List ), ( )] [Pair → • ( List ), ( )] [Pair → • ( ), ( )] [Pair → • ( ), ( )]

CC6 = { [List → Pair •, ( )] [List → Pair •, ( )]

CC7 = { [Pair → ( • List ), ( )] [Pair → ( • List ), ( )] [Pair → ( • ), ( )] [Pair → ( • ), ( )] [List → • List Pair, ( )] [List → • List Pair, ( )] [List → • Pair, ( )] [List → • Pair, ( )] [Pair → • ( List ), ( )] [Pair → • ( List ), ( )] [Pair → • ( ), ( )] [Pair → • ( ), ( )]

CC8 = { [Pair → ( ) •, eof] [Pair → ( ) •, ( ) }

CC9 = { [List → List Pair •, ( )] [List → List Pair •, ( )]

CC10 = { [Pair → ( List ) •, eof] [Pair → ( List ) •, ( ) }

CC11 = { [List → List • Pair, ( )] [List → List • Pair, ( )] [Pair → ( List • ), ( )] [Pair → ( List • ), ( )] [Pair → • ( List ), ( )] [Pair → • ( List ), ( )] [Pair → • ( ), ( )] [Pair → • ( ), ( )]

CC12 = { [Pair → ( ) •, ( )] [Pair → ( ) •, ( )]

CC13 = { [Pair → ( List ) •, ( )] [Pair → ( List ) •, ( )]

■ FIGURE 3.25 The Canonical Collection of Sets of LR(1) Items for the Parentheses Grammar.

Building the Canonical Collection

As a first complete example, consider the problem of building CC for the parentheses grammar. Fig. 3.24 summarizes the steps the algorithm takes. Fig. 3.25 shows the individual sets that it creates.

The algorithm first computes closure([Goal → • List, eof]), which becomes CC0. It then begins to build possible parser configurations. From iteration 1 in Fig. 3.24, we see that goto(CC0,List) creates CC1, goto(CC0,Pair) creates

We can partition the universe of context-free grammars into a hierarchy based on the difficulty of parsing the grammars. This chapter distinguishes between four kinds of grammars: arbitrary CFGs, LR(1) grammars, LL(1) grammars, and regular grammars(RGs). These sets nest as shown below.

Arbitrary CFGs require more time to parse than do the more restricted LR(1) or LL(1) grammars. Earley’s algorithm, for example, parses arbitrary CFGs, but it has a worst case time bound of O(n3)O(n^{3}) , where n is the number of words in the input. Historically, compiler writers have considered Earley’s algorithm too expensive for use in practical applications.

The set of LR(1) grammars includes a large subset of the unambiguous CFGs.LR(1) grammars can be parsed, bottom-up, in a linear, left-to-right scan, with a one-word lookahead. Tools that build LR(1) parsers are widely available.

The set of LL(1) grammars is an important subset of the LR(1) grammars. LL(1)grammars can be parsed, top-down, in a linear, left-to-right scan, with a one-word lookahead. Many tools exist to build LL(1) parsers; the grammars are also suitable for hand-coded recursive-descent parsers. Many programming languages can be specified with an LL(1) grammar.

Regular grammars(RGs) are a subset of CFGs where the form of productions is restricted to either A→ a or A→ a B, with A,B∈NT and a∈T. Regular grammars encode precisely the same languages as regular expressions.

Almost all programming-language constructs can be written in LR(1) or LL(1)form. Thus, most compilers use a parser based on one of these two classes of CFGs. Some constructs fall in the gap between LR(1) and LL(1); they do not appear to be particularly useful.(See Waite’s grammar in Exercise 3.10.)

CC2CC_{2} , and goto(CC0,() creates CC3. The other grammar symbols, Goal and),produce an empty set. In each set CCiCC_{i} shown in Fig. 3.25, the first line contains the core items; subsequent lines contain the items added by closure.

Later iterations fill in the rest of CC, as shown in Figs. 3.24 and 3.25. The construction halts when it fails to add new sets to CC.

Given the canonical collection, CC, for a grammar, the parser generator can fill in the Action and Goto tables by iterating over the CCi∈CCCC_{i}\in CC . Each CCiCC_{i}becomes a parser state. Its items dictate where shifts and reduces appear in

for each cc,∈ CC do for each item l∈ cc, do if l is[A→β·cγ, a] and goto(cc, c)= cc, then Action[i,c]←“shift j” else if l is[A→β·, a] then Action[i,a]←“reduce A→β” else if l is[Goal→β·, eof] then Action[i, eof]←“accept” for each n∈ NT do if goto(cc, n)= cc, then Goto[i, n]←j

■ FIGURE 3.26 LR(1) Table-Filling Algorithm.

the corresponding Action table row. The state transitions in Action and Goto come from the transitions recorded during construction of the canonical co.lection, as shown in Fig. 3.24.

Three kinds of items generate entries in the Action table:

As before, eitherβ orδ, or both, can be empty.

  1. An item of the form[A→β·cδ,a] indicates that finding the terminal symbol c would be a valid next step in finding the nonterminal A. It generates a shift item in the column for c in the current state. It finds the recognizer’s next state in the trace under CCi and c.

  2. An item of the form[A→β·,a] indicates that the parser has found aβ.If the lookahead is a, then the item is a handle. Thus, it generates a reduce item for the production A→β in the column for a in the current state.

  3. An item of the form[Goal→β·,eof], where Goal is the start symbol indicates an accepting state. The parser has reduced the input stream to Goal and the lookahead symbol is eof. This item generates an accept action in eof’s column in the current state.

The table-filling actions can be integrated into the construction of CC.

The algorithm in Fig. 3.26 makes this concrete. For an LR(1) grammar, in should uniquely define the entries in the Action and Goto tables.

To fill in the Goto table, the algorithm does not need to recompute goto(cc,i,n). Instead, it can consult the transitions that it recorded during the construction of CC. For the example, that information is recorded in the trace shown in Fig. 3.24.

The table-filling algorithm ignores items where the· precedes a nonterminal symbol. Shift actions are generated when· precedes a terminal. Reduce and accept actions are generated when· is at the right end of the production. What if CC; contains an item[A→β·yδ, a], where y∈NT? This item does not generate any table entries, but its presence in the set forces closure

to include items that generate table entries. When closure finds a● that immediately precedes a nonterminal symbol y, it adds productions that have y as their left-hand side, with a● preceding their right-hand sides. This process instantiates FIRST(y) in CCi. Closure will find each x∈ FIRST(y) and add the items into CC; to generate shift items for each such x.

The tables produced for the parentheses grammar are shown in Fig. 3.17(b)on page 122. Those tables, plus the skeleton LR(1) parser, constitute a working parser for the parentheses language.

In practice, an LR(1) parser generator must produce other tables needed by the skeleton LR(1) parser. For example, when the skeleton parser reduces by A→β, it pops|β| pairs from the stack and pushes A onto the stack. The table generator must produce data structures that map a production from the reduce entry in the Action table, say A→β, into both|β| and A. Other tables, such as a map from the integer representing a grammar symbol into its textual name, are needed for debugging and for diagnostic messages.

LR(1) parsers derive their efficiency from a fast handle-finding mechanism embedded in the Action and Goto tables. The canonical collection, CC, represents a handle-finding DFA for the grammar. Fig. 3.27 shows the DFA for our example, the parentheses grammar.

How can the LR(1) parser use a DFA to find the handles, when we know that the language of parentheses is not a regular language? The LR(1) parser relies on a simple observation: the set of handles is finite. The set of handles is precisely the set of complete LR(1) items-those with the placeholder●at the right end of the item’s production. Any language with a finite set of sentences can be recognized by a DFA. Since the number of productions and the number of lookahead symbols are both finite, the number of complete items is finite, and the language of handles is a regular language.

When the LR(1) parser executes, it interleaves two kinds of actions: shifts and reduces. The shift actions simulate steps in the handle-finding DFA. As the parser shifts each word in the input stream onto the parse stack, it also changes state in the DFA as dictated by the word’s syntactic category. The reduce actions occur when the DFA reaches a final state. At that point, the skeleton parser pops the handle, and its DFA states, off the stack to reveal the state of the DFA before it began looking for the current handle. That state sits on the stack below the handle’s left end.

The reduce action uses the handle’s left-hand side nonterminal to take a transition in the DFA. It finds that transition in the Goto table, using the The LR(1) parser makes the handle’s position implicit, at stacktop. This decision greatly reduces the number of possible handles.

Transitions made on nonterminal symbols appear in gray in Fig. 3.27.

Figure 3.27 Handle-Finding DFA for the Parentheses Grammar.

revealed state and the nonterminal; pushes that new state on the stack; and then pushes the nonterminal. In effect, the LR(1) skeleton parser uses the reduce state actions to simulate recursive invocations of the handle-finding DFA for each new subgoal in the parse.

The LR(1) parser alternates between handle-finding phases and reduce actions. It shifts items onto the stack until it reaches a final state in the DFA.It then reduces the handle to its left-hand side nonterminal. The reduce actions tie together successive handle-finding phases. They use the left context encoded in the revealed state to restart the handle-finding DFA in a state that reflects the just-recognized nonterminal. In the parse of()()() shown in Fig. 3.19, the parser stacks different states for the first than it does when a follows another(. Those stacked states allow it to find the correct handles.

The handle-finding DFA is encoded directly in the Action and Goto tables. Each dark edge corresponds to a shift action; shift 3 in Action[1,()] produces an edge from CC1 to CC3 labeled with(. Each gray edge corresponds to a reduce action. If i is the revealed state and Goto[i,x]=j, then the DFA contains a gray transition from CC to CCj labeled with the nonterminal x. Thus, the DFA in Fig. 3.27 can be read directly from the Action and Goto tables in Fig. 3.17(b).

As a second example of the LR(1) table construction, consider the ambiguous grammar for the classic if-then-else construct, shown in the margin. To keep the size of CC manageable, we have replaced the “if Expr then”portion of rules 2 and 3 with a single terminal symbol, ifthen. All of the other statements are abstracted into a single terminal symbol, assign. The resulting grammar retains the fundamental ambiguity of the original grammar, shown on page 93.

Goal→ Stmt

Stmt→ifthen Stmt
ifthen Stmt else Stmt
assign

Simplified if-then-else Grammar

IterationItemGoalStmtifthenelseassign
1CC00CC1CC20CC3
2CC100000
CC20CC4CC50CC6
CC300000
3CC4000CC70
CC50CC8CC50CC6
CC600000
4CC70CC9CC20CC3
CC8000CC100
5CC900000
CC100CC11CC50CC6
6CC1100000

■ FIGURE 3.28 Trace of the LR(1) Construction on the if-then-else Grammar.

The construction of the canonical collection begins by computing CC0 as closure([Goal→·Stmt, eof]). Fig. 3.28 shows a trace of the full construction. Fig. 3.29 shows resulting canonical collection of sets of LR(1) items. Close examination of the canonical collection for this grammar shows how the table construction algorithm manifests errors and how the table-filling algorithm discovers those errors.

The table-filling algorithm proceeds normally until it reaches CC8:

CC_{8}=\left\{\begin{array}[]{ll}1.&[\,Stmt\rightarrow\,ifthen\,Stmt\,\bullet\,eof\,]\\ 2.&[\,Stmt\rightarrow\,ifthen\,Stmt\,\bullet\,else\,]\\ 3.&[\,Stmt\rightarrow\,ifthen\,Stmt\,\bullet\,else\,Stmt,\,eof\,]\\ 4.&[\,Stmt\rightarrow\,ifthen\,Stmt\,\bullet\,else\,Stmt,\,else\,]\end{array}\right\}

Each of those items generates an entry in the Action table. Unfortunately, they multiply define entries in the Action table. Action[8,else] is set to “reduce 2” by item 2 and to “shift 10” by item 4. Similarly, Action[8,eof] is set to “reduce 2” by item 1 and to “shift 10” by item 3. These multiple entries cause the table construction to fail.

The multiply-defined locations are the manifestation of an ambiguous grammar. It has two distinct rightmost derivations for some valid sentence, as evidenced by the fact that, in some valid contexts, the parser can either shift or reduce on the same lookahead symbol.

CC₀ = { [Goal → • Stmt, eof] [Stmt → • ifthen Stmt, eof] [Stmt → • ifthen Stmt else Stmt, eof] [Stmt → • assign, eof] }

CC₁ = { [Goal → Stmt •, eof] }

CC₂ = { [Stmt → • ifthen Stmt, eof] [Stmt → • ifthen Stmt, else] [Stmt → ifthen • Stmt, eof] [Stmt → • ifthen Stmt else Stmt, eof] [Stmt → • ifthen Stmt else Stmt, else] [Stmt → ifthen • Stmt else Stmt, eof] [Stmt → • assign, eof] [Stmt → • assign, else] }

CC₃ = { [Stmt → assign •, eof] }

CC₄ = { [Stmt → ifthen Stmt •, eof] [Stmt → ifthen Stmt • else Stmt, eof] }

CC₅ = { [Stmt → • ifthen Stmt, eof] [Stmt → • ifthen Stmt, else] [Stmt → ifthen • Stmt, eof] [Stmt → ifthen • Stmt, else] [Stmt → • ifthen Stmt else Stmt, eof] [Stmt → • ifthen Stmt else Stmt, else] [Stmt → ifthen • Stmt else Stmt, eof] [Stmt → ifthen • Stmt else Stmt, else] [Stmt → • assign, eof] [Stmt → • assign, else] }

CC₆ = { [Stmt → assign •, eof] [Stmt → assign •, else] }

CC₇ = { [Stmt → • ifthen Stmt, eof] [Stmt → • ifthen Stmt else Stmt, eof] [Stmt → ifthen Stmt else • Stmt, eof] [Stmt → • assign, eof] }

CC₈ = { [Stmt → ifthen Stmt •, eof] [Stmt → ifthen Stmt •, else] [Stmt → ifthen Stmt • else Stmt, eof] [Stmt → ifthen Stmt • else Stmt, else] }

CC₉ = { [Stmt → ifthen Stmt else Stmt •, eof] }

CC₁₀ = { [Stmt → • ifthen Stmt, eof] [Stmt → • ifthen Stmt, else] [Stmt → • ifthen Stmt else Stmt, eof] [Stmt → • ifthen Stmt else Stmt, else] [Stmt → ifthen Stmt else • Stmt, eof] [Stmt → ifthen Stmt else • Stmt, else] [Stmt → • assign, eof] [Stmt → • assign, else] }

CC₁₁ = { [Stmt → ifthen Stmt else Stmt •, eof] [Stmt → ifthen Stmt else Stmt •, else] }

■ FIGURE 3.29 The Canonical Collection of Sets of LR(1) Items for the if-then-else Grammar.

Shift-reduce error An error that arises when the LR(1) table construction tries to define one entry in the Action table as both a shift and a reduce. This particular kind of conflict is called a shift-reduce conflict. It arises because rule 2 in the grammar is a prefix of rule 3. The compiler writer needs to disambiguate the grammar, as shown in Section 3.2.3. When the parser generator encounters such a conflict, the construction fails. The parser generator should report the problem back to the compiler writer. It is difficult to write that error message without reference to the LR(1) items. Thus, most parser generators settle for a simple message such as “shift-reduce error” and provide a way for the user (presumably a compiler writer) to see the specific LR(1) items that were involved.

As an alternative, an LR(1) parser generator can simply resolve shift-reduce conflicts in favor of the shift action. This choice forces the parser to recognize the longer production. In the case of the if-then-else grammar, that decision binds each else to the innermost unmatched if-then precisely the rule that the disambiguated grammar from Section 3.2.3 enforces.

An ambiguous grammar can also give rise to a reduce-reduce conflict. Such a conflict occurs if the grammar contains two productions with the same right-hand side, A→γδ and B→γδ. If some state CCi contains both[A→γδ·,a] and [B→γδ·,a], then it will generate two conflicting reduce actions for Action[i,a]. Again, this conflict reflects a fundamental ambiguity in the underlying grammar that the compiler writer must eliminate (see Section 3.5.3).

Manually determining that a grammar has the LR(1) property is tedious and error-prone. LR(1) parser generators are widely available. Thus, the method of choice for determining if a given grammar has the LR(1) property is to invoke an LR(1) parser generator on it. If the process succeeds, the grammar has the LR(1) property.

LR(1) parsers are widely used in compilers built in both industry and academia. These parsers accept a large class of languages. They use time proportional to the size of the derivation that they construct. Tools that generate an LR(1) parser are widely available in many implementation languages.

The LR(1) table-construction algorithm is an elegant application of theory to practice. It systematically builds a model of the handle-recognizing DFA and encodes it into the Action and Goto tables. The construction requires painstaking attention to detail. It is precisely the kind of task that should be automated-parser generators are better at following these computations than are humans. That notwithstanding, a skilled compiler writer should understand the algorithms because they provide insight into how the parsers work, what kinds of errors the parser generator can encounter, how those errors arise, and how they can be fixed.

An ambiguity that causes the algorithm to assign two different reductions to a single Action table entry SheepNoise → baa SheepNoise | baa

REVIEW QUESTIONS

  1. Show the steps that the skeleton LR(1) parser, with the tables for the parentheses grammar, would take on the input string “(( ( ) ( ) ( ) )”.
  2. Build the canonical collection of sets of LR(1) items for the SheepNoise grammar, shown in the margin. Use the canonical collection to build Action and Goto tables. Show the resulting parser’s actions on the input “baa baa baa.”

Despite the advent of high-quality parser generators, the compiler writer needs to understand a myriad of practical issues in order to build a quality parser. This section addresses several issues that arise in practice and have a significant impact on compiler usability.

Programmers often compile code that contains syntax errors. In fact, compilers are widely accepted as the fastest way to discover such errors. In this application, the compiler must find as many syntax errors as possible in a single attempt at parsing the code. Thus, the compiler writer wants to build the parser so that it can move from an error state to one in which it can continue parsing.

The example parsers shown in this chapter all have the same behavior when they find a syntax error: they report the problem and halt. This behavior prevents the compiler from wasting more time on an incorrect program. However, it ensures that the compiler finds at most one syntax error per compilation. Finding all the syntax errors in a file of code with such a compiler could be a long and painful process.

A parser should find as many syntax errors as possible in each compilation. The parser needs a mechanism that lets it “recover” from an error—that is, move to a state where it can continue parsing. A common way to achieve this goal is to select one or more words that the parser can use to synchronize the input with its internal state. When the parser encounters an error, it discards input symbols until it finds a synchronizing word and then resets its internal state to one consistent with having recognized that word.

In an Algol-like language, with semicolons as statement separators, the semicolon is often used as a synchronizing word. When an error occurs, the parser calls the scanner repeatedly until it finds a semicolon. It then changes state to one that would have resulted from successful recognition of a complete statement, say the nonterminal Stmt, rather than an error.

In a recursive-descent parser, the code can simply discard words until it finds a semicolon. At that point, it can return control to the point where the routine that parses statements reports success. This may involve manipulating the runtime stack or using a nonlocal jump like C’s setjmp and longjmp.

In an LR(1) parser, this kind of resynchronization is more complex. The parser discards input until it finds a semicolon. Next, it scans backward down the parse stack until it finds a state s such that Goto[s, Stmt] is a valid, nonerror entry. The first such state on the stack represents the statement that contains the error. The error recovery routine then discards entries on the stack down to that state, pushes the state given by Goto[s, Stmt] onto the stack, and resumes normal parsing.

In a table-driven parser, either LL(1) or LR(1), the compiler writer needs a way to tell the parser generator where to synchronize. This can be done using an error production-a production whose right-hand side includes a reserved word that indicates an error synchronization point and one or more synchronizing tokens. With such a construct, the parser generator can implement the desired behavior.

Of course, the compiler should not try to generate and optimize code for a syntactically invalid program. This requires simple handshaking between the error-recovery apparatus and the driver that invokes the compiler’s various passes in order to halt after an unsuccessful parse.

The classic expression grammar includes only binary operators. Algebraic notation, however, includes unary operators, such as unary minus and absolute value. Other unary operators arise in programming languages, including autoincrement, autodecrement, address-of, dereference, boolean complement, and typecasts. Adding such operators to the expression grammar requires some care.

Consider adding a unary absolute-value operator,||, to the classic expression grammar. Absolute value should have higher precedence than either x or÷. However, it needs a lower precedence than Factor to force evaluation of parenthetic expressions before application of||. One way to write this grammar is shown in Fig. 3.30(a). With these additions, the grammar is still LR(1). It lets the programmer form the absolute value of any Factor.

Fig. 3.30(b) shows the parse tree for the string||x-3. It correctly shows that the code must evaluate||x before performing the subtraction. The grammar

0Goal→Expr
1Expr→Expr + Term
2Expr - Term
3Term
4Term→Term x Value
5Term ÷ Value
6Value
7Value→
8
9Factor→(Expr)
10num
11name

(a) The Grammar

(b) Parse Tree for ||x-3

■ FIGURE 3.30 Adding Unary Absolute Value to the Classic Expression Grammar.

prevents the programmer from writing |||| x, as that makes little mathematical sense. It does, however, allow ||(||x), which makes as little sense as ||||x.

The inability to write ||||x hardly limits the expressiveness of the language. With other unary operators, however, the issue seems more serious. For example, a C programmer might need to writep to dereference a variable declared as charp;. We can add a dereference production for Value as well: Value→Value. The resulting grammar is still an LR(1) grammar, even if we replace the x operator in Term→Term x Value with, overloading the operator “*” in the way that C does. This same approach works for unary minus.

3.5.3 Handling Context-Sensitive Ambiguity

Section titled “3.5.3 Handling Context-Sensitive Ambiguity”

Using one word to represent two distinct meanings can create a syntactic ambiguity. One example of this problem arose in several early programming languages, including FORTRAN, PL/I, and ADA. These languages used parentheses to enclose both the subscript expressions of an array reference and the argument list of a subroutine or function. Given a textual reference, such as fee(i,j), the grammar has two derivations: one as a two-dimensional array and the other as a procedure call. Differentiating between these two cases requires knowledge of fee’s declared type-information that is not syntactically obvious. The scanner undoubtedly classifies fee as a name in either case. Neither of these constructs appears in the classic expression grammar. We can add productions that derive them from Factor.

9Factor → (Expr)
10
11
12
13
14Subscript → name (ArgList)
15Call → name (ArgList)

Since rules 14 and 15 expand to identical right-hand sides, this grammar is ambiguous. An LR(1) table builder will report a reduce-reduce conflict between these two productions.

Resolving this ambiguity requires extra-syntactic knowledge. In a top-down, recursive-descent parser, the compiler writer can combine the code for Subscript and Call and add the extra code required to check the name’s declared type. In a table-driven parser built with a parser generator, the solution must work within the framework provided by the tools.

Two different approaches have been used to solve this problem. The compiler writer can combine both the function invocation and the array reference into one production. This scheme defers the issue until later translation, when it can be resolved with type information derived from the declarations. The parser must construct a representation that preserves all the information needed by either resolution; some later step will rewrite the reference as either an array reference or a function invocation.

Alternatively, the scanner can classify identifiers based on their declared types, rather than their microsyntax. This scheme requires handshaking between the scanner and the parser; it is not hard to arrange as long as the language has a define-before-use rule. The declaration is parsed before the use occurs. The parser can provide the scanner with access to it internal symbol table to resolve identifiers into distinct categories, such as variable-name and function-name. These categories then appear in the grammar as distinct nonterminal symbols. The relevant productions become:

14Subscript → variable-name (ArgList)
15Call → function-name (ArgList)

Rewritten in this way, the grammar is unambiguous. The scanner returns a distinct syntactic category in each case and the parser can distinguish them.

In Section 3.3.1, we saw that using different brackets for Subscript and Call will also resolve the ambiguity.

For a top-down parser, the compiler writer will also need to left-factor the occurrences of name.

Define-before-use Many programming languages require that each name be declared before it is used in the code.

Of course, the language designer can avoid this kind of ambiguity. Languages such as C and BCPL use different syntax for function calls and array element references, which eliminates the ambiguity.

Error localization, error messages, and error recovery are all critical to the compiler user’s experience. The compiler writer needs to ensure that the compiler finds as many errors as it can and that it reports the causes of those errors as clearly as it can. Unary operators and ambiguous constructs introduce complications into programming language grammars. The compiler writer can manage these issues by manipulating the grammar, by changing the parser-scanner interaction, or by some combination of both approaches.

  1. The programming language C uses square brackets to indicate an array subscript and parentheses to indicate a procedure or function call. How does this simplify the construction of a parser for C?
  2. The grammar for unary absolute value introduced a new terminal symbol for the unary operator. Consider adding unary minus to the classic expression grammar. Does the fact that the same terminal symbol occurs in two distinct roles introduce complications? Justify your answer.

To build a satisfactory parser, the compiler writer must understand the basics of engineering both a grammar and a parser. Given a working parser, there are often ways of improving its performance. This section looks at two specific issues in parser construction. First, we examine transformations on the grammar that reduce the length of a derivation to produce a faster parse. These ideas apply to both top-down and bottom-up parsers. Second, we discuss transformations on the grammar and the Action and Goto tables that reduce table size. These techniques apply only to LR parsers.

While syntax analysis no longer consumes a major share of compile time, the compiler should not waste undue time in parsing. The actual form of a (a) The Classic Expression Grammar (b) Parse Tree for a + 2 x b

grammar has a direct effect on the amount of work required to parse it. Both top-down and bottom-up parsers construct derivations. A top-down parser performs an expansion for every production in the derivation. A bottom-up parser performs a reduction for every production in the derivation. A grammar that produces shorter derivations takes less time to parse.

The compiler writer can often rewrite the grammar to reduce the parse tree height. This reduces the number of expansions in a top-down parser and the number of reductions in a bottom-up parser. Optimizing the grammar cannot change the parser’s asymptotic behavior; after all, the parse tree must have a leaf node for each symbol in the input stream. Still, reducing the constants in heavily used portions of the grammar, such as the expression grammar, can make enough difference to justify the effort.

Consider, again, the classic left-recursive expression grammar, shown in Fig. 3.31(a). Its LR(1) tables appear in Fig. 3.33. This grammar produces rather large parse trees, even for simple expressions. For example, the parse tree for a + 2 x b, has 14 nodes, as shown in Fig. 3.31(b). Five of these nodes are leaves that we cannot eliminate; changing the grammar cannot shorten the input program. The number and placement of the interior nodes, however, depend completely on the derivation.

Any interior node that has only one child is a candidate for optimization. The sequence of nodes Expr→Term→Factor→(name, a) uses four nodes for a single word in the input stream. We can eliminate at least one layer, the layer of Factor nodes, by folding the alternative expansions for Factor into Term, as shown in Fig. 3.32(a). It multiplies by three the number of alternatives for Term, but shrinks the parse tree by one layer, shown in Fig. 3.32(b).

(a) New Productions for Term

4 Term→Termx(Expr)

5| Term x name

6| Term x num

7| Term÷(Expr)

8| Term÷name

9| Term÷num

10|Expr

11| num

12| name

(b) Parse Tree for a+2xb

+Expr

Term

(name,a)

Term

(num,2)

■FIGURE 3.32 Replacement Productions for Term.

In an LR(1) parser, this change eliminates three of nine reduce actions, and leaves the five shifts intact. In a top-down, recursive-descent parser for an equivalent predictive grammar, it would eliminate 3 of 14 procedure calls.

In general, any production that has a right-hand side with one symbol can be folded away. We call such productions useless. Sometimes, useless productions serve a purpose-making the grammar more compact and, perhaps, more readable, or forcing the derivation to assume a particular shape.(Re-call that the simplest of our expression grammars accepts a+2xb but does not encode any notion of precedence into the parse tree.)

In Section 5.3, we will discuss methods to tie computations to particular points in the parse. In that context, a production that is useless in the syntax may play a critical role in the translation by creating a point in the derivation where a particular action can be performed.

Folding away useless productions has its costs. In an LR(1) parser, it can make the tables larger. In our example, eliminating Factor removes one column from the Goto table, but the extra productions for Term increase the size of CC from 32 sets to 46 sets. Thus, the tables have one fewer column, but an extra 14 rows. The resulting parser performs fewer reductions(and runs faster), but has larger tables.

In a hand-coded, recursive-descent parser, the larger grammar may increase the number of alternatives that must be compared before expanding some left-hand side. The compiler writer can sometimes compensate for the increased cost by combining cases. For example, in our recursive-descent parser in Fig. 3.10, the code in routine ExprPrime for the words+ and-was combined because the parser takes the same actions in either case.

Unfortunately, the LR(1) tables generated for even small grammars can be large. Fig. 3.33 on page 150 shows the Action and Goto tables for the classic expression grammar. Many techniques exist for reducing LR(1) table sizes. This section describes three such approaches.

The compiler writer can often recode the grammar to reduce the number of productions. Fewer productions usually lead to smaller tables. For example, in the classic expression grammar, the distinction between a number and an identifier is irrelevant to the productions for Goal, Expr, Term, and Factor. Replacing the two productions Factor→num and Factor→name with a single production Factor→val shrinks the grammar by a production. In the Action table, each terminal symbol has its own column. Folding num and name into a single symbol, val, removes one of those columns. Of course, the scanner must then return the same syntactic category, or word, for both num and name.

Similar arguments can be made for combining x and+ into a terminal muldiv, and for combining+ and- into a terminal addsub. Each of these replacements removes a terminal symbol and a production. These three changes produce the reduced expression grammar shown in Fig. 3.34(a).This grammar produces a smaller CC, removing rows from the table. Be-cause the grammar has fewer terminal symbols, the table has fewer columns as well.

The resulting Action and Goto tables are shown in Fig. 3.34(b). The Action table contains 132 entries and the Goto table contains 66 entries, for a total of 198 entries. This compares favorably with the tables for the original grammar, with their 384 entries. Changing the grammar produced a 48 percent reduction in table size.

Other considerations may limit the compiler writer’s ability to combine productions. In particular, two similar productions may need different syntax-driven translation schemes, which would make combining them impractical(see Section 5.3).

Shrinking the grammar can produce a significant reduction in the size of the Action and Goto tables. The resulting tables may still present opportunities for improvement. Consider the tables in Fig. 3.34(b), for example. The Ac-tion table rows for states 0,6, and 7 are identical, as are the rows for states 4,11,15, and 17. The table generator can combine rows, or columns, that are

Combining+ and- into one category has the same effect as combining cases in the top-down, recursive-descent parser, discussed in Section 3.6.1.

Stateeof+-x+( )numnameExprTermFactor
0s 4s 5s 6123
1accs 7s 8
2r 4r 4r 4s 9s 10
3r 7r 7r 7r 7r 7s 14s 15s 16111213
4
5r 9r 9r 9r 9r 9
6r 10r 10r 10r 10r 10
7s 4s 5s 6173
8s 4s 5s 6183
9s 4s 5s 619
10s 4s 5s 620
11s 21s 22
12r 4r 4s 24s 25r 4261213
13r 7r 7r 7r 7r 7s 15s 16
14s 14
15r 9r 9r 9r 9r 9
16r 10r 10r 10r 10r 10
17r 2r 2r 2s 9s 10
18r 3r 3r 3s 9s 10
19r 5r 5r 5r 5r 5
20r 6r 6r 6r 6r 6s 14s 15s 162713
21s 14s 15s 162813
22s 14
23r 8r 8r 8r 8r 8s 14s 15s 1629
24s 14s 15s 1630
25s 14s 15s 16
26s 21s 22s 31
27r 2r 2s 24s 25r 2
28r 3r 3s 24s 25r 3
29r 5r 5r 5r 5r 5
30r 6r 6r 6r 6r 6
31r 8r 8r 8r 8r 8

■ FIGURE 3.33 Action and Goto Tables for the Classic Expression Grammar.

1 Goal → Expr 2 Expr → Expr addsub Term 3 | Term 4 Term → Term muldiv Factor 5 | Factor 6 Factor → (Expr) 7 | val

(a) The Reduced Expression Grammar

(b) Action and Goto Tables for the Reduced Expression Grammar

■ FIGURE 3.34 The Reduced Expression Grammar and Its Tables.

Together, the techniques reduced the table from 288 to 102 entries, or 65 percent.identical and remap the states accordingly. Combining the identical rows in the two sets above would further reduce the Action table in Fig. 3.340 from 132 entries to 102 entries, an additional 23 percent reduction.

To use the resulting table, the skeleton parser would need a mapping from a parser state to a row index in the Action table. The table generator can combine identical columns in the analogous way. A separate inspection of the Goto table will yield a different set of state combinations-in particular, all of the rows containing only zeros should condense to a single row.

In some cases, the table generator can prove that two rows or two columns differ only in cases where one of the two has an “error” entry(denoted by a blank in our figures). In Fig. 3.33, the columns for eof and for num differ only where one or the other has a blank. Combining such columns produces the same behavior on correct inputs. It does change the parser’s behavior on erroneous inputs and may impede the parser’s ability to provide accurate and helpful error messages.

The mechanics of combining rows and columns is similar to the technique discussed for shrinking the transition-function table of a DFA, discussed in Section 2.5.4. These techniques produce a direct reduction in table size. If this space reduction adds an extra indirection to every table access, the cost of those memory operations must trade off directly against the savings in memory. The table generator could also use other techniques to represent sparse matrices-again, the implementor must consider the tradeoff of memory size against any increase in access costs.

As a final improvement, the parser generator can abandon the table-driven skeleton parser in favor of a direct-coded implementation. Each state becomes a small case statement or a collection of if-then-else statements that tests the type of the next symbol and either shifts, reduces, accepts, or reports an error. The Action and Goto tables are replaced with code.(We saw a similar transformation for scanners in Section 2.5.2.)

The resulting parser avoids directly representing all of the “don’t care” states in the Action and Goto tables, shown as blanks in the figures. This space savings may be offset by larger code size, since each state now requires code. The new parser, however, has no parse table, performs no table lookups, and lacks the outer loop found in the skeleton parser. While its structure makes it almost unreadable by humans, it should execute more quickly than the corresponding table-driven parser. With appropriate code-layout techniques, the resulting parser can exhibit strong locality in both cache and virtual memory. For example, the compiler writer should place routines for the expression grammar together on a single page in virtual memory, so that they cannot conflict with one another in the code cache.

Several other algorithms to construct LR-style parsers exist. Among these techniques are the SLR(1) construction, for simple LR(1), and the LALR(1)construction, for lookahead LR(1). Both of these constructions produce smaller tables than the canonical LR(1) algorithm.

The SLR(1) algorithm accepts a smaller class of grammars than the canonical LR(1) construction. The SLR(1) grammars are restricted so that the table-filling algorithm can distinguish between shift entries and reduce entries using the FOLLOW sets. This restriction eliminates the need for lookahead symbols in the items. The resulting canonical collection of sets of items has fewer states, so the table has fewer rows. This technique accepts many grammars of practical interest.

The LALR(1) algorithm relies on the observation that the core items in the set representing a state are critical and that the remaining items can be added to a set by computing its closure. The LALR(1) table construction uses the core items to compute the canonical collection and computes their closure after reaching the fixed point. It produces a canonical collection similar in size to the one produced by the SLR(1) construction. The details differ, but the table sizes are similar.

The canonical LR(1) construction presented earlier in the chapter is the most general of these table-construction algorithms. It produces the largest tables, but accepts the largest class of grammars. With appropriate table reduction techniques, the LR(1) tables can approximate the size of those produced by the more limited techniques.

The SLR(1) construction accepts a smaller class of grammars than the LALR(1) construction. In turn, the LALR(1) construction accepts a smaller class of grammars than does the canonical LR(1) construction. However, in a mildly counterintuitive result, any language that has an LR(1) grammar also has both an SLR(1) grammar and an LALR(1) grammar. The grammars for these more restrictive construction algorithms must be shaped in ways that let the algorithms differentiate between shift actions and reduce actions.

Almost every compiler contains a parser. For many years, parsing was a subject of intense research interest. This led to the development of many different techniques for building efficient parsers. The LR(1) family of

Recall that the core items of a set are those produced by the goto functions. The items added by closure are not core items.

Section 3.3 4. The following grammar is not suitable for a top-down predictive parse. Identify the problem and correct it by rewriting the grammar. Show that your new grammar satisfies the LL(1) condition.

  1. Grammars that can be parsed top-down, in a linear scan from left to right, with a k word lookahead are called LL(k) grammars. In the text the LL(1) condition is described in terms of FIRST sets. How would you define the FIRST sets necessary to describe an LL(k) condition?

  2. Suppose an elevator is controlled by two commands: ↑ to move the elevator up one floor and ↓ to move the elevator down one floor. Assume that the building is arbitrarily tall and that the elevator starts at floor x. Write an LL(1) grammar that generates arbitrary command sequences that (1) never cause the elevator to go below floor x and (2) always return the elevator to floor x at the end of the sequence. For example, ↑↑↓↓ and ↑↓↑↓ are valid command sequences, but ↑↓↑↑ and ↑.. are not. The null sequence is valid. Prove that your grammar is LL(1).

  3. Top-down and bottom-up parsers build parse trees in different orders. Write a pair of programs, Topdown and Bottomup. that take a parse tree and print out the nodes in order of construction. Topdown should display the order for a top-down parser, while Bottomup should show the order for a bottom-up parser.

  4. The ClockNoise language (CN) is represented by the following grammar

a. What are the LR(1) items of CN? b. What are the FIRST sets of CN? c. Construct the Canonical Collection of Sets of LR(1) Items for CN. d. Derive the Action and Goto tables. 9. Consider the following grammar:

1 Start → S 2 S → A a 3 A → B C 4 | B C f 5 B → b 6 C → c

a. Construct the canonical collection of sets of LR(1) items for this grammar. b. Derive the Action and Goto tables. c. Is the grammar LR(1)?

  1. The following grammar has no known LL(1) equivalent:

1 Start → A 2 | B 3 A → ( A ) 4 | a 5 B → ( B ) 6 | b

Show that the grammar is LR(1).

  1. Write a grammar for expressions that includes binary operators (+ and ×), unary minus (-), autoincrement (++), and autodecrement (—) with their customary precedence. Assume that repeated unary minuses are not allowed, but that repeated autoincrement and autodecrement operators are allowed.

  2. Consider the task of building a parser for the programming language SCHEME. Contrast the effort required for a top-down recursive-descent parser with that needed for a table-driven LR(1) parser. (Assume that you already have an LR(1) table generator.)

Section 3.6 Section 3.7


← node-book_engineering-a-compiler_chapter-02-scanners | node-book_engineering-a-compiler | node-book_engineering-a-compiler_chapter-04-intermediate-representations →