Scanners
local graph
Chapter 2 — Scanners
Section titled “Chapter 2 — Scanners”ABSTRACT
Section titled “ABSTRACT”The scanner’s task is to transform a stream of characters into a stream of words in the input language. Each word must be classified into a syntactic category, or “part of speech.” The scanner is the only pass in the compiler to touch every character in the input program. Compiler writers place a premium on speed in scanning, in part, because the scanner’s input is larger, in some measure, than that of any other pass, and, in part, because highly efficient techniques for scanning are easy to understand and to implement.
This chapter introduces regular expressions, a notation used to describe the set of valid words in a programming language. It develops the formal mechanisms to generate scanners from regular expressions, either manually or automatically.
KEYWORDS
Section titled “KEYWORDS”Scanner, Finite Automaton, Regular Expression, Fixed-Point Algorithm
2.1 INTRODUCTION
Section titled “2.1 INTRODUCTION”Scanning is the first stage of the three-part process that the compiler’s front end uses to understand the input program. The scanner, or lexical analyzer, reads a stream of characters and produces a stream of words. The parser, or syntax analyzer, fits that stream of words to a grammatical model of the input language. The parser, in turn, invokes semantic elaboration routines to perform deeper analysis and to build structures that model the input program’s actual meaning.
The scanner aggregates characters into words. For each word, it determines if the word is valid in the source language. For each valid word, it assigns the word a syntactic category, or part of speech.
The scanner is the only pass in the compiler that manipulates every character of the input program. Because scanners perform a relatively simple task, grouping characters together to form words and punctuation in the source language, they lend themselves to fast implementations. Automatic tools for scanner generation are common. These tools process a mathematical description of the language’s lexical syntax and produce a fast recognizer.
Syntactic category a classification of words according to their grammatical usage
In a practical sense, these categories correspond to terminal symbols in the language’s grammar (see Section 3.2.2).
Nonetheless, many compilers use hand-crafted scanners because they are easily written and the resulting scanners can be fast and robust.
Conceptual Roadmap
Section titled “Conceptual Roadmap”To translate a program, the compiler must understand both its lexical structure-the spellings of the words in the program-and its syntactic structure-the grammatical way that words fit together to form statements and programs. This chapter describes the mathematical tools and programming techniques that are commonly used to construct scanners-programs that analyze the lexical structure of code.
Scanner construction has a strong foundation in formal language theory. Scanners are based on recognizers that simulate deterministic finite automata. The compiler writer specifies the lexical structure of the input language using a set of regular expressions(REs). A series of constructions convert that specification into a scanner that reads a stream of characters and produces a stream of words, each tagged with its syntactic category from the programming language’s grammar.
The technology to automate scanner construction has widespread application, from compilers to editors to filters for URLs in a web browser. Readily available tools use the well-developed theory of finite automata to build efficient recognizers from simple specifications.
Overview
Section titled “Overview”A compiler’s scanner reads the input stream and produces, as output,a stream of words, each labeled with its syntactic category-equivalent to a word’s part of speech in English. Each time it is called, the scanner produces a pair, lexeme, category), where lexeme is the spelling of the word and category is its syntactic category. This pair is sometimes called a token.
To find and classify words, the scanner applies a set of rules that describe the lexical structure of the input programming language, sometimes called its microsyntax. Microsyntax specifies how to group characters into words and, conversely, how to separate words that run together.(In the context of scanning, punctuation marks and other symbols are treated as separate words.)
Western languages, such as English, have simple microsyntax. Adjacent alphabetic letters are grouped together, left to right, to form a word.A blank space terminates a word, as do most nonalphabetic symbols.(The word-building algorithm can treat a hyphen in the midst of a word as if it were an alphabetic character.) Once a group of characters has been
Recognizer
a program that identifies specific words in a stream of characters
Lexeme
the actual text for a word recognized by a scanner
Microsyntax
the lexical structure of a language aggregated together to form a potential word, the word-building algorithm can determine its validity and its potential parts of speech with a dictionary lookup.
Most programming languages have equally simple microsyntax. Characters are aggregated into words. In most languages, blanks and punctuation marks terminate a word. For example, ALGOL-60 and its descendants define an identifier as a single alphabetic character followed by zero or more alphanumeric characters. The identifier ends with the first nonalphanumeric character. Thus, fee and f1e are valid identifiers, but 12fum is not. Notice that the set of valid words is specified by rules rather than by enumeration in a dictionary.
In a typical programming language, some words, called keywords or reserved words, match the rule for an identifier but have special meanings. Both while and static are keywords in both C and JAVA. Keywords (and punctuation marks) form their own syntactic categories. Even though static matches the rule for an identifier, the scanner in a C or JAVA compiler would undoubtedly classify it into a category that has only one element, the keyword static. The techniques used to implement a scanner must be capable of distinguishing individual words, such as keywords, without compromising the efficiency of recognizing the larger classes that contain them.
The simple lexical structure of programming languages lends itself to efficient scanners. The compiler writer starts from a specification of the language’s microsyntax. She either encodes the microsyntax into a notation accepted by a scanner generator, which then constructs an executable scanner, or she uses that specification to build a hand-crafted scanner. Both generated and hand-crafted scanners can be implemented to require just O(1) time per character, so they run in time proportional to the number of characters in the input stream.
This chapter begins, in Section 2.2, by introducing a model for recognizers, programs that identify words in a stream of characters. Section 2.3 describes a formal notation, regular expressions, for specifying both syntax and recognizers. Section 2.4 shows how to automate construction of an executable recognizer from an RE. Finally, Section 2.5 examines practical issues in scanner implementation, for both generated and hand-crafted scanners.
A Few Words About Time
Section titled “A Few Words About Time”Chapter 2 focuses on the design and implementation of a compiler’s scanner. As such, it deals with issues that arise at three different times: design time, build time, and compile time.
Keyword a word that is reserved for a particular syntactic purpose and, thus, cannot be used as an identifier
At design time, the compiler writer creates specifications for the microsyn-tax of the programming language(the spelling of words). The compiler writer chooses an implementation method and writes any code that is needed.
At build time, the compiler writer invokes tools that build the actual executable scanner. For a specification-driven scanner, this process will include the use of tools to convert the specification into code and the use of a compiler to turn that code into an executable image.
At compile time, the end user invokes the compiler to translate application code into executable code. The compiler includes the scanner; it uses the scanner to convert the application code from a string of characters into a string of words, and to classify each of those words into a syntactic category or part of speech.
2.2 RECOGNIZING WORDS
Section titled “2.2 RECOGNIZING WORDS”A character-by-character algorithm to recognize words is simple and un-derstandable. The structure of the code can provide some insight into the underlying problem. Consider the problem of recognizing the keyword new, as shown in Fig. 2.1(a). The code assumes the presence of a routine NextChar that returns successive characters. The code tests for n, then e, then w. At each step, failure to match the appropriate character causes the code to reject the string and try something else. If the sole purpose of the program was to recognize the “new,” then it should report an error. Because scanners rarely recognize only one word, we will leave this error path deliberately vague at this point.
The code fragment performs one test per character. We can represent the code fragment using the simple transition diagram shown in panel(b). The transition diagram represents the recognizer. Each labeled circle represents an abstract state in the computation. The initial state, or start state, is s0.State s3 is an accepting state; the recognizer reaches s3 only when the input is “new.” The double circle denotes s3 as an accepting state.
Arrows represent transitions from state to state based on input characters. If the recognizer starts in s0 and reads the characters n, e, and w, the transitions take us to s3. What happens on any other input, such as n, o, and t? The letter n takes the recognizer to s1. The letter o does not match any edge leaving s1. In the code, cases that do not match new execute try something else. The recognizer takes a transition to the error state. When we draw the transition diagram of a recognizer, we usually omit transitions to the error state. Each state has an implicit transition to the error state on each unspecified input.
We assume that, once NextChar reaches the end of the input file, it always returns eof.
ror state
s a nonaccepting state with a transition ck to itself on any character.
any character
c ← NextChar(); if (c = ‘n’) then c ← NextChar(); if (c = ‘e’) then c ← NextChar(); if (c = ‘w’) then report success; else try something else; else try something else; else try something else; end (a) Code (b) Recognizer
Using this same approach to build a recognizer for while would produce the following transition diagram:
s0 w s1 h s2 i s3 l s4 e s5 If the recognizer runs from s0 to s5, it has found the word while. The corresponding code would use five nested if-then-else constructs.
To recognize multiple words, the recognizer can have multiple edges that leave a given state. (In the code, these would become else if clauses.) The straightforward recognizer for both new and not is:
s0 n s1 e s2 w s3 The recognizer uses a common test for n that takes it from s0 to s1, denoted s0→n s1. If the next character is e, it takes the transition s1→e s2. If, instead, the next character is o, it makes the move s1→o s4. Finally, a w in s2 causes the transition s2→w s3, and a t in s4 produces s4→t s5. State s3 indicates that the input was new while s5 indicates that it was not. The recognizer takes one transition per input character.
We can combine the recognizer for new or not with the one for while by merging their initial states and relabeling all the states.
State has transitions for n and w. The recognizer has three accepting states, , and If any state encounters an input character that does not match one of its transitions, the recognizer moves to the implicit error state,
The recognizer takes one transition for each input character. Assuming that we implement the recognizer efficiently, we should expect it to run in time proportional to the length of the input string.
2.2.1 A Formalism for Recognizers
Section titled “2.2.1 A Formalism for Recognizers”Finite automaton
a formalism for recognizers that has a finite set of states, an alphabet, a transition function, a start state, and one or more accepting states
Transition diagrams serve as abstractions of the code that would be required to implement them. They can also be viewed as formal mathematical objects, called finite automata, that specify recognizers. Formally, a finite automaton(FA) is a five-tuple , where
-
S is the finite set of states in the recognizer, including
-
is the finite alphabet used by the recognizer. Typically, is the union of the edge labels in the transition diagram.
-
is the recognizer’s transition function. It maps each state and each character into some next state. In state with input character c, the FA takes the transition
-
is the designated start state.
-
is the set of accepting states, Each state in appears as a double circle in the transition diagram.
Putting the FA for new or not or while into this formalism yields:
delta is only partially specified. For all other combinations of state and input character c, we define , where is the error state. This quintuple is equivalent to the transition diagram; given one, we can easily recreate the other.
An FA accepts a string x if and only if, starting in , the sequence of characters in x takes the FA through a series of transitions that leaves it in an accepting state when the entire string has been consumed. This corresponds to our intuition for the transition diagram. For the string new, our example recognizer runs through the transitions , and . Since , and no input remains, the FA accepts new. For the input string nut, the behavior is different. On the letter n, the FA takes . On u, it takes . Once the FA enters , it stays in until it exhausts the input stream.
More formally, if the string x consists characters then the FA accepts x if and only if
Intuitively, this definition corresponds to a repeated application of to a pair composed of some state s and input symbol The base case, ,represents the FA’s initial transition out of the start state, , on the character The state is then used as input to , along with , which yields the next state, and so on, until all the input has been consumed. The result of the final application of is, again, a state. If that state is an accepting state, then the FA accepts
The FA can encounter a lexical error in the input. Some character might take it into the error state Entry into occurs because is not a valid prefix for any word in the language accepted by the FA. Alternatively, the FA can reach the end of its input while in a nonaccepting state. Either case indicates that the input string is not a word in the language.
Consider a string that causes an FA to halt in a nonaccepting state. If the FA passes through an accepting state on the way, then the string contains a prefix that is a valid word. As we will see in Section 2.4.5, scanners use this observation to find word boundaries.
2.2.2 Recognizing More Complex Words
Section titled “2.2.2 Recognizing More Complex Words”The character-by-character model shown in the original recognizer for not extends easily to handle arbitrary collections of fully specified words. How Chapter 2 Scanners
We will denote a range of characters with the first and last element, connected by an ellipsis, “…”, as in 0…9. Some systems and authors use a dash rather than an ellipsis. We use the ellipsis to avoid confusion with the minus sign.
could we recognize a number with such a recognizer? A specific number, such as 113.4, is easy.
To be useful, however, we need a transition diagram (and the corresponding code fragment) that can recognize any number. For simplicity’s sake, we will limit the discussion to unsigned integers. In general, an integer is either zero, or it is a series of one or more digits where the first digit is from one to nine, and the subsequent digits are from zero to nine. (This definition rules out leading zeros.) How would we draw a transition diagram for this definition?
The transition handles the case for the digit zero. The other path, , handles the case for a digit greater than zero. This path, however, violates the stipulation that is finite.
Notice that all of the states on the path beginning with are equivalent, that is, they have the same labels on their output transitions and they are all accepting states. If we allow the transition diagram to have cycles, we can replace the path that starts at with a single transition from back to itself, as shown in the margin.
This cyclic transition diagram makes sense as an FA. From an implementation perspective, however, it is more complex than the acyclic transition diagrams shown earlier. We cannot translate this directly into a set of nested if-then-else constructs. The introduction of a cycle in the transition graph creates the need for cyclic control flow. We can implement this with a while loop, as shown in the code in Fig. 2.2(a). We can specify efficiently using a table:
| $\delta$ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Other |
| $s_{0}$ | $s_{1}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{e}$ |
| $s_{1}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ |
| $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{2}$ | $s_{e}$ |
| $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ | $s_{e}$ |
state←S0;S={S0,S1,S2,Se}
char← NextChar();
while(state≠Se and char≠ eof) do
state←δ(state, char);
char← NextChar();
end;
if(state∈S_{A}) then
report acceptance;
else report failure;
(a) Code to Interpret State Table
(b) Formal Definition of the FA
FIGURE 2.2 A Recognizer for Unsigned Integers.
Changing the table allows the same basic code skeleton to implement other recognizers. Notice that this table has ample opportunity for compression. The columns for the digits 1 through 9 are identical, so they could be represented once, reducing the table to three columns:0,[1…9],and other. The code skeleton reports failure as soon as it enters se, so the table row for s_e is never used. If we elide the row for s_e, the table can be represented with three rows and three columns.
We can develop similar FAs for signed integers, real numbers, and complex numbers. A simplified version of the rule that governs identifier names in Algol-like languages, such as C or JAVA, might be:
an identifier consists of an alphabetic character followed by zero or more alphanumeric characters.
This definition allows an infinite set of identifiers. It can be specified with the simple two-state FA shown in the margin. Many languages include designated special characters, such as_ and&, in the set of alphabetic characters.
FAs can be viewed as specifications for a recognizer. However, they are not particularly concise specifications. To simplify scanner construction, we need a concise notation to specify the lexical structure of words, and a way to turn such a specification into an FA and into code to implement the FA.The remaining sections of this chapter develop precisely those ideas.
The FA for unsigned integers raises the distinction between a syntactic category, such as “unsigned integers,” and a specific word, such as 113. The category is a set of one or more words; for example, both 12 and 113 might be members of the category “unsigned integer.”
FA for Identifiers SECTION REVIEW Recognizing and classifying words is a fundamental part of understanding the syntax of a program. For a given word, or a collection of words, the compiler writer can create a character-by-character recognizer. Such recognizers correspond to transition diagrams, which, in turn, correspond to finite automata. Any finite set of words can be encoded in an acyclic transition diagram. Certain infinite sets of words, such as the set of integers or the set of identifiers in JAVA, can be encoded as well; they give rise to cyclic transition diagrams.
REVIEW QUESTIONS
- Construct an FA for identifiers that consist of an alphabetic character followed by up to five alphanumeric characters.
- Construct an FA for a PASCAL comment, which consists of an open brace, {, followed by zero or more characters drawn from the set Σ - }, followed by a close brace, }.
2.3 REGULAR EXPRESSIONS
Section titled “2.3 REGULAR EXPRESSIONS”The set of words accepted by a finite automaton, F, forms a language, denoted L(F). The transition diagram of F specifies, in precise detail, how to spell every word in that language. Transition diagrams can be complex and nonintuitive. Thus, most systems use a notation called a regular expression (RE) to describe spelling. Any language described by an RE is considered a regular language. REs are equivalent to the FAs described in the previous section. (We will prove this with a construction in Section 2.4.) Simple recognizers have simple RE specifications. ■ The language consisting of the single word bow can be described by an RE written as bow. Writing two characters next to each other implies that they are expected to appear in that order. ■ The language consisting of the two words bow or row can be written as bow or row. To avoid possible misinterpretation of or, we write this using the symbol | to mean or. Thus, we write the RE as bow | row. We refer to | as an alternation. For any given language, there may exist multiple REs that specify the language. For example, bow|row and (b|r) ow both specify the same language. The different REs, in turn, suggest different FAs, as shown below. The FAs shown in panels (a) and (b) accept the same language.
Alternation is commutative, so bow|row describes the same language as row|bow or (r|b) ow.
To make this discussion concrete, consider some examples that occur in most programming languages. Punctuation marks, such as colons, semicolons, and various brackets, are represented by their character representations. Their REs have the same “spelling” as the punctuation marks themselves. Thus, the following REs might occur in the lexical specification for a programming language:
: ; ? => ( ) [ ] + //
Similarly, keywords have simple REs.
if while this integer instanceof
To model syntactic categories that have large numbers of words, such as integers or identifiers, we need a way to denote an FA’s cyclic edge.
The FA for an unsigned integer, shown in the margin, has three states: an initial state s0, an accepting state s1 for the unique integer zero, and another accepting state s2 for all other integers. The key to this FA’s power is the transition s2→s2 that occurs on each additional digit. State s2 creates a rule to derive a new unsigned integer from an existing one: add another digit to the right end of the existing number. Another way of stating this rule is:
an unsigned integer is either a zero, or a nonzero digit followed by zero or more digits.
To capture the essence of this FA, we need a notation for this notion of “zero or more occurrences” of an RE. For the RE x, we write this as x*, with the meaning “zero or more occurrences of x.” We call the * operator Kleene closure
The RE x* designates zero or more occurrences of x.
FA for Unsigned Integers
Kleene closure The RE x* designates zero or more occurrences of x. closure, or closure for short. Using the closure operator, we can write an RE for this FA:
0|(1|2|3|4|5|6|7|8|9) (0|1|2|3|4|5|6|7|8|9)*.
Of course, we can write this RE more concisely as 0|([1…9])([0…9])*.
2.3.1 Formalizing the Notation
Section titled “2.3.1 Formalizing the Notation”To work with REs in a rigorous way, we need a formal definition. Assume that we have an alphabet, . An RE describes a set of strings over the characters in , plus an additional character that represents the empty string. The set of strings defined by an RE is called a language. We denote the language described by some RE r as L(r).
An RE is built up from three basic operations:
-
Alternation The alternation, or union, of two sets of REs, r and s, denoted r|s, is .
-
Concatenation The concatenation of two REs r and s, denoted rs, contains all strings formed by prepending a string from L(r) onto one from L(s), or .
-
Closure The Kleene closure of r, denoted is contains all strings that consist of zero or more words from L(r).
For convenience, we sometimes use a finite closure. The notation ,denotes from one to i occurrences of r. A finite closure can always be replaced with an enumeration of the possibilities; for example, is just The positive closure, denoted , is just and consists of one or more occurrences of r. Since the finite and positive closures can be rewritten in terms of alternation, concatenation, and Kleene closure, we ignore them in the discussion that follows.
Using alternation, concatenation, and Kleene closure, we can define the set of REs over an alphabet as follows:
-
If , then a is an RE denoting the set , and is a.
-
If r and s are REs, denoting sets L(r) and L(s), respectively, then is an RE denoting the alternation of L(r) and L(s);rs is an RE denoting the concatenation of L(r) and L(s); and is an RE denoting the Kleene closure of L(r).
-
is an RE denoting the set that only contains the empty string.
To eliminate ambiguities, parentheses have highest precedence, followed by closure, concatenation, and alternation, in that order.
2.3.2 Examples of Regular Expressions
Section titled “2.3.2 Examples of Regular Expressions”The goal of this chapter is to show how we can use formal techniques to automate the construction of high-quality scanners and how we can encode the microsyntax of programming languages into that formalism. Before proceeding further, some examples from real programming languages are in order.
- The rule given earlier for identifiers in Algol-like languages, an alphabetic character followed by zero or more alphanumeric characters, is just([A…Z]|[a…z])([A…Z]|[a…z]|[0…9])*.
Most languages also allow a few special characters, such as_,%, $, or&in identifiers.
If the language limits the length of an identifier, we can use a finite closure, as in([A…Z]|[a…z])([A…Z]|[a…z]|[0…9])5 for a six-character identifier.
-
An unsigned integer can be described as either zero or a nonzero digit followed by zero or more digits. The RE 0|[1…9][0…9]* is more concise. The simpler specification[0…9]+ admits integers with leading zeroes such as 001.
-
Unsigned real numbers are more complex than integers. One possible RE might be (0|[1…9][0…9])(\epsilon|[0…9]). The first part is just the RE for an integer. The rest generates either the empty string or a decimal point followed by zero or more digits.
Programming languages often admit scientific notation, as in:
This RE describes a real number, followed by an E, followed by an integer to specify the exponent.
- Quoted character strings have their own complexity. In most languages,a string can contain any character. While we can write an RE for strings using only the basic operators, it is our first example where a complement operator simplifies the RE. Using complement, a character string in C or JAVA can be described as “(^”)*”.
C and C++ do not allow a string to span multiple lines-that is, if the scanner reaches the end of a line while inside a string, it terminates the string and issues an error message. If we represent newline with the escape sequence\n, in the C style, then the RE“(^(”|\n))*” will recognize a correctly formed C or C++ string and will take an error transition on a string that includes a newline.
Complement
Section titled “Complement”The RE^c specifies the set|∑-c|, the complement of c with respect to\Sigma.
Complement has higher precedence than*,|, or+.
Escape sequence
Section titled “Escape sequence”Two or more characters that the scanner translates into another character. Escape sequences are used for characters that lack a glyph, such as newline or tab, and for ones that occur in the syntax, such as an open or close quote.
REGULAR EXPRESSIONS IN VIRTUAL LIFE
Section titled “REGULAR EXPRESSIONS IN VIRTUAL LIFE”Regular expressions are used in many applications to specify patterns in character strings. Some of the early work on translating REs into code was done to provide a flexible way of specifying strings in the “find” command of the QED text editor. From that early genesis, the notation has crept into many applications.
Unix and other operating systems use the asterisk as a wildcard to match substrings against file names. Here, * is a shorthand for the RE Σ*, specifying zero or more characters drawn from the entire alphabet of legal characters. (Since few keyboards have a Σ key, the shorthand has stayed with us.) Many systems use ? as a wildcard that matches a single character.
The grep family of tools, and their kin in non-Unix systems, implement regular expression pattern matching. (grep is an acronym for global regular-expression pattern match and print.)
Regular expressions have found widespread use because they are easily written and easily understood. They are one of the techniques of choice when a program must recognize a fixed vocabulary. They work well for languages that fit within their limited rules. They are easily translated into an executable form, and the resulting recognizer is fast.
- Comments appear in a number of forms. C++ and JAVA offer two ways of writing a comment. The delimiter // indicates a comment that runs to the end of the current input line. The RE for this style of comment is straightforward: //(^\n)*\n.
Multiline comments in C, C++, and JAVA begin with the delimiter /* and end with /. If we could disallow * in a comment, the RE would be simple: /(^)**/. With , the RE is more complex: /(^|*+^/)**/. An FA that implements this RE follows.
The relationship between the RE for multiline comments and its FA is less obvious than in many of the earlier examples.
The complexity of the RE and FA for multiline comments arises from the use of multicharacter delimiters. The transition from S₂ to S₃ encodes the fact that the recognizer has seen an * so that it can handle either the appearance of a / or the lack thereof correctly.
By contrast, PASCAL used single-character comment delimiters: { and }, so a PASCAL comment is just { ^}*. In many cases, tighter specifications lead to more complex REs. Consider, for example, the register specifier in a typical assembly language. It consists of the letter r followed immediately by a small integer. In ILOC, which admits an unlimited set of register names, the RE might be r[0…9]+, which corresponds to the FA shown in the margin. The FA accepts r29 and rejects s29. It also accepts r99999 even though no modern processor has 100,000 registers.
On a typical processor, the set of register names is severely limited—say, to 32, 64, 128, or 256 registers. With a more complex RE, the scanner can check the validity of a register name. For example, the RE
specifies a much smaller language. It limits register numbers to the range [0,31] and allows an optional leading zero on single-digit register names. Thus, it accepts r0, r00, r01, and r31, but rejects r001, r32, and r99999. The corresponding FA looks like:
Which FA is better? They both make a single transition on each input character. Thus, they have the same cost, even though the second FA checks a more complex specification. The more complex FA has more states and transitions, so its representation requires more space. However, their operating costs are the same.
This point is critical: the cost of operating an FA is proportional to the length of the input, not to the complexity of the RE or the number of states in the FA. More states need more space, but not more time. The build-time cost of generating the FA for a more complex RE may be larger, but the cost of operation remains one transition per character. A good implementation will have O(1) cost per transition.
FA for Register Names
An alternative, of course, is to use the RE r[0…9][0…9] and to test the register number as an integer.
Can we improve the RE for a register name? The previous RE is both complex and counterintuitive. A simpler alternative might be:
r0|r00|r1|r01|r2|r02|r3|r03|r4|r04|r5|r05|r6|r06|r7| r07|r8|r08|r9|r09|r10|r11|r12|r13|r14|r15|r16|r17|r18| r19|r20|r21|r22|r23|r24|r25|r26|r27|r28|r29|r30|r31
This RE is conceptually simpler, but much longer than the previous version. The resulting FA still requires one transition per input symbol. Thus, if we can control the growth in the number of states, we might prefer this version of the RE because it is clear and obvious. However, when processors suddenly have 256 or 384 registers, enumeration may become tedious, too.
2.3.3 Closure Properties of REs
Section titled “2.3.3 Closure Properties of REs”Regular languages
Any language that can be specified by a regular expression is called a regular language.
REs and the languages that they generate have been the subject of extensive study. They have many interesting and useful properties. Some of these properties play a critical role in the constructions that build recognizers from REs.
REs are closed under many operations-that is, if we apply the operation to an RE or a collection of REs, the result is an RE. Obvious examples are concatenation, union, and closure. The concatenation of two REs x and y is just xy. Their union is x|y. The Kleene closure of x is just x*. From the definition of an RE, all of these expressions are also REs.
These closure properties play a critical role in the use of REs to build scanners. Assume that we have an RE for each syntactic category in the source language, a0,a1,a2,…,an. Then, to construct an RE for all the valid words in the language, we can join them with alternation as a0|a1|a2|…|an. Since REs are closed under union, the result is an RE. Anything that we can do to an RE for a single syntactic category will be equally applicable to the RE for all the valid words in the language.
URL-filtering software relies on this property to build fast FA-based recognizers.
Closure under union implies that any finite language is a regular language. We can construct an RE for any finite collection of words by listing them in a large alternation. Closure ensures that the alternation is an RE and that the corresponding language is regular.
Closure under concatenation lets us build complex REs from simpler ones by concatenating them. This property seems obvious. It lets us piece together REs in systematic ways. Closure ensures that ab is an RE as long as both a and b are REs. Thus, any technique that applies to either a or b applies to ab.
PROGRAMMING VERSUS NATURAL LANGUAGES
Section titled “PROGRAMMING VERSUS NATURAL LANGUAGES”Lexical analysis highlights one of the subtle ways in which programming languages differ from natural languages, such as English or Portuguese. In natural languages, the relationship between a word’s representation—its spelling or its pictogram—and its meaning is not obvious. In English, are is a verb while art is a noun, even though they differ only in the final character. Furthermore, not all combinations of characters are legitimate words. For example, arz differs minimally from are and art, but does not occur as a word in normal English usage.
A scanner for English could use FA-based techniques to recognize potential words, since all English words are drawn from a restricted alphabet. After that, however, it must look up the prospective word in a dictionary to determine if it is, in fact, a word. If the word has a unique part of speech, dictionary lookup will also resolve that issue. However, many English words can be classified with several parts of speech. Examples include buoy and stress; both can be either a noun or a verb. For these words, the part of speech depends on the surrounding context. In some cases, understanding the grammatical context suffices to classify the word. In other cases, it requires an understanding of meaning, for both the word and its context.
By contrast, the words in a programming language are almost always specified lexically. Thus, any string in [1…9][0…9]* is a positive integer. The RE [a…z] ([a…z] | [0…9])* defines a subset of the Algol identifiers; arz, are and art are all identifiers, with no lookup needed to establish the fact. To be sure, some identifiers may be reserved as keywords. However, these exceptions can be specified lexically, as well. No context is required.
This property results from a deliberate decision in programming language design. The choice to make spelling imply a unique part of speech simplifies scanning, simplifies parsing, and, apparently, gives up little in the expressiveness of the language. Some languages have allowed words with dual parts of speech—for example, PL/I has no reserved keywords. The fact that more recent languages abandoned the idea suggests that the complications outweighed any benefits of the extra flexibility.
REs are also closed under both Kleene closure and the finite closures. This property lets us specify particular kinds of large, or even infinite, sets with finite patterns. Kleene closure lets us specify infinite sets with concise finite patterns; examples include the integers and unbounded-length identifiers. Finite closures let us specify large but finite sets with equal ease.
The next section shows a sequence of constructions that build an FA from an RE. Section 2.6 shows an algorithm that builds an RE from an FA. Together, these algorithms establish the equivalence of REs and FAs. The fact that REs
Complete FA an FA that explicitly includes all error transitions
are closed under alternation, concatenation, and closure is critical to these constructions. The equivalence between REs and FAs also suggests other closure properties. For example, given a complete FA, we can construct an FA that recognizes all words w that are not in L(FA), called the complement of L(FA). To build the FA for the complement, we can swap the designation of accepting and nonaccepting states in the original FA. Since FAs and REs are equivalent, this result shows that REs are closed under complement. Indeed, many systems that use REs include a complement operator, such as the ^ operator in lex and flex.
SECTION REVIEW
Section titled “SECTION REVIEW”Regular expressions are a concise and powerful notation for specifying the microsyntax of programming languages. REs build on three basic operations over finite alphabets: alternation, concatenation, and Kleene closure. Other convenient operators, such as finite closures, positive closure, and complement, derive from the three basic operations. Regular expressions and finite automata are equivalent; any RE can be realized in an FA and the language accepted by any FA can be described with an RE. The next section formalizes that relationship.
REVIEW QUESTIONS
Section titled “REVIEW QUESTIONS”- A six-character identifier might be specified with a finite closure: ((A…Z]|[a…z])([A…Z]|[a…z]|[0…9])^5 Rewrite the specification using only the three basic RE operations: alternation, concatenation, and Kleene closure.
- In PL/I, strings start and end with a quotation mark, ”. In between are zero or more characters drawn from some alphabet, ∑. To represent ”, the programmer writes two of them in a row. The string The quotation mark, ”, should be typeset in italics. would be written in a PL/I program as “The quotation mark, "", should be typeset in italics.” Design an RE and an FA to recognize PL/I strings.
FIGURE 2.3 The Cycle of Constructions.
Section titled “FIGURE 2.3 The Cycle of Constructions.”2.4 FROM REGULAR EXPRESSION TO SCANNER
Section titled “2.4 FROM REGULAR EXPRESSION TO SCANNER”The goal of our work with finite automata is to automate the derivation of scanners from a set of REs. This section develops the constructions to transform an RE into an FA. The constructions rely on both nondeterministic FAs, or NFAs, and deterministic FAs, or DFAs. Kleene’s construction, sketched in Section 2.6.1, builds an RE from any FA. Together, these constructions form a cycle, shown in Fig. 2.3.
The cycle of constructions demonstrates that REs and FAs have equivalent expressive power. That is, an RE can express any language recognizable with an FA, and an FA can recognize any language that can be specified with an RE.
Section 2.4.1 explains the differences between an NFA and a DFA. Sec-tion 2.4.2 presents Thompson’s construction, which builds an NFA directly from an RE. Section 2.4.3 presents the subset construction, which builds a DFA to simulate an NFA. Section 2.4.4 presents Hopcroft’s algorithm for DFA minimization; an alternative minimization algorithm by Brzozowski appears in Section 2.6.3.
2.4.1 Nondeterministic Finite Automata
Section titled “2.4.1 Nondeterministic Finite Automata”Recall from the definition of an RE that we designated the empty string, ,as an RE. None of the FAs that we built by hand included , but some of the REs did. What role does play in an FA? We can use transitions on to combine FAs and to simplify construction of FAs from REs. For example, assume that we have FAs for m and n, called and .
-transition
Section titled “ϵ\epsilonϵ -transition”a transition on the empty string, , that does not advance the input
We can build an FA for mn by adding a transition on from the accepting state of FAm to the initial state of FAn, renumbering the states, and using FAn’s accepting state as the accepting state for the new FA.
With an -transition, the definition of acceptance must change slightly to allow one or more -transitions between any two characters in the input string. For example, in state n1, the FA takes the transition n1→n2 without consuming an input character. The change is minor and intuitive. It does, however, mean that an FA with -transitions can take multiple transitions per input character.
Merging two FAs with an -transition can complicate our model of how FAs work. Consider the FAs for the languages and ab.
We can combine them with an -transition to form an FA for .
The -transition, in effect, gives the FA two distinct transitions out of on the letter a. It can take the transition , or it can take the two transitions and . Which transition is correct? Consider the strings aab and ab. The FA should accept both strings. For aab, it should move: , and . For ab, it should move: , and .
Nondeterministic FA
Section titled “Nondeterministic FA”an FA where the transition function can be multivalued and can include -transitions
Deterministic FA
Section titled “Deterministic FA”where the transition function is
gle-valued and does not include -sitions
As these two strings show, the correct transition out of on a depends on the characters that follow the a. At each step, an FA examines the current character. Its state encodes the left context, that is, the characters that it has already processed. Because the FA must make a transition before examining the next character, a state such as violates our notion of the behavior of a sequential algorithm. An FA that includes states such as that have multiple transitions on a single character is called a nondeterministic finite automaton(NFA). By contrast, an FA with unique character transitions in each state is called a deterministic finite automaton(DFA). To make sense of an NFA, we need a set of rules that describe its behavior. Historically, two distinct models have been given for the behavior of an NFA.
-
Each time the NFA must make a nondeterministic choice, it follows the transition that leads to an accepting state for the input string, if such a transition exists. This model, using an omniscient NFA, is appealing because it maintains (on the surface) the well-defined accepting mechanism of the DFA. In essence, the NFA guesses the correct transition at each point.
-
Each time the NFA must make a nondeterministic choice, the NFA clones itself to pursue each possible transition. Thus, for a given input character, the NFA and its clones are in some set of states. In this model, the NFA pursues all paths concurrently.
At any point, we call the specific set of states in which the NFA is active its configuration. When the NFA reaches a configuration in which it has exhausted the input and one or more of the clones has reached an accepting state, the NFA accepts the string.
In either model, the NFA () accepts an input string if and only if there exists at least one path through the transition diagram that starts in and ends in some such that the edge labels along the path match the input string, omitting ‘s. In other words, the ith edge label must be . This definition is consistent with either model of the NFA’s behavior.
Equivalence of NFAs and DFAs
Section titled “Equivalence of NFAs and DFAs”NFAs and DFAs are equivalent in their expressive power. Any DFA is a special case of an NFA. Thus, an NFA is at least as powerful as a DFA. Any NFA can be simulated by a DFA. The intuition behind this idea is simple; the construction, in Section 2.4.3, is a little more complex.
Consider the state of an NFA when it has reached some point in the input string. Under the second model of NFA behavior, the NFA has some finite set of operating clones. The set of states that those clones occupy form a configuration of the NFA. Each configuration is a subset of N, the set of states of the NFA. The number of such subsets is finite. Thus, an NFA with N states produces at most configurations.
To simulate the behavior of the NFA, we need a DFA with a state for each valid configuration of the NFA. The resulting DFA may have exponentially more states than the NFA. Still, the number of configurations and, therefore,DFA states is finite. The DFA still makes one transition per input symbol, so it runs in time proportional to the length of the input string. Thus, the
Configuration of an NFA
Section titled “Configuration of an NFA”the set of simultaneously active states of the NFA
Powerset of N
Section titled “Powerset of N”the set of all subsets of N, denoted
(a) NFA for a (b) NFA for b (c) NFA for ab (d) NFA for a|b (e) NFA for a*
Figure 2.4 Trivial NFAs for Regular Expression Operators.
To put Thompson’s construction in context, see the digression on page 718 in Section 14.2.
DFA for aa*b
simulation of an NFA on a DFA has a potential space problem, but not a time problem.
Since NFAs and DFAs are equivalent, we can construct a DFA that recognizes aab. The NFA that we saw earlier had two transitions out of no on a. The obvious way to avoid this nondeterministic transition is to observe that aab is equivalent to aa*b. That RE suggests the DFA shown in the margin. The subset construction automates the transformation of an NFA into a DFA(see Section 2.4.3).
2.4.2 RE to NFA: Thompson’s Construction
Section titled “2.4.2 RE to NFA: Thompson’s Construction”The first step in deriving a scanner from an RE constructs an NFA from the RE with Thompson’s construction. The construction uses a simple, template-driven process to build up an NFA from smaller NFAs. It builds NFAs for individual symbols, , in the RE and applies transformations on the resulting NFAs to model the effects of concatenation, alternation, and closure. Fig. 2.4 shows the trivial NFAs for a and b, as well as the transformations to form ab,a|b, and a* from NFAs for a and b. The transformations apply to arbitrary NFAs.
Fig. 2.5 shows the steps that Thompson’s construction takes to build an NFA from the RE a(b|c). First, the construction builds trivial NFAs for each character in the RE, shown in panel(a). It then applies the operators in precedence order. It builds an NFA for the parenthetic expression,(b|c),shown in panel(b). The closure is next, as shown in panel(c). Finally, it concatenates the NFA for a onto the front of the NFA for(b|c), shown in panel(d). This simple process produces an NFA for an RE written in terms of the three basic operators. ■ FIGURE 2.5 Applying Thompson’s Construction to a(b|c)*.
The NFAs derived from Thompson’s construction have several specific properties that simplify an implementation. Each NFA has one start state and one accepting state. No transition, other than the initial transition, enters the start state. No transition leaves the accepting state. Finally, each state has at most two entering and two exiting ε-moves, and at most one entering and one exiting move on a symbol in the alphabet. Together, these properties simplify the representation and manipulation of the NFAs.
Fig. 2.5(d) shows the NFA that Thompson’s construction builds for a(b|c)*. The combination of the subset construction and DFA minimization should transform the NFA from Fig. 2.5(d) into a DFA similar to the one shown in the margin.
2.4.3 NFA to DFA: The Subset Construction
Section titled “2.4.3 NFA to DFA: The Subset Construction”Thompson’s construction produces an NFA to recognize the language specified by an RE. Because DFA execution is much easier to simulate than NFA execution, the next step in building a recognizer from an RE converts the
while(WorkList≠∅) do
remove q from WorkList
for each character c∈∑ do
if temp≠∅ then
if temp≠Q then
add temp to both Q and WorkList
■ FIGURE 2.6 The Subset Construction.
NFA into an equivalent DFA. The algorithm to construct a DFA from an NFA is called the subset construction.
The subset construction takes as input an NFA,(N,∑,δN,n0,NA). It builds a model that captures all of the valid configurations that the NFA can enter in response to input strings. Each configuration contains one or more NFA states, all of which are reachable from the same collection of input strings. The model consists of two sets, Q and T. Each element of Q is a set of NFA states that represents a valid configuration of the original NFA. T models the transitions between configurations that were discovered as the algorithm built Q.
To construct a DFA from the model, we create a DFA state for each .The DFA transitions follow directly from the transitions recorded in T. If the construction built by considering how the NFA, in configuration , would move on character c, then T contains the transition and should be
Fig. 2.6 shows the algorithm. It starts with a single configuration, , constructed from It adds to Q and places it on WorkList. It uses WorkList to track which must still be processed. The algorithm repeatedly removes a configuration, , from the worklist. Then, for each , it computes the valid configuration, temp, reached by following transitions out of on character c. If , it adds temp to both Q and WorkList. It records the transition from to temp in T. The algorithm halts when it exhausts the worklist.
Each set contains a set of core states and zero or more noncore states. The noncore states are reachable from a core state by following one or more -transitions. The model’s initial configuration, , has only one core state
the NFA’s initial state no. To form qo, the algorithm adds all of the NFA states that no implies-that is, those reachable along paths of e-transitions. In the algorithm, the function FollowEpsilon(s) expands a set s with its non-core elements.
To compute the NFA configuration reachable from qi on c, the algorithm applies to each The function computes the core of a new configuration from s and c. If and is not the error state, then is a core state in the new configuration. The algorithm uses FollowEpsilon to add the implied noncore elements.
When the construction halts, Q contains all of the valid configurations of the NFA and T records all of the legal transitions between those configurations. Together, they represent a DFA that simulates the original NFA. To instantiate the DFA, we create a state d; for each set . If contains an accepting state of the NFA-that is, some such that -then the d, that represents is an accepting state-that is, . The DFA’s transition function is built directly from T by mapping the sets in Q to their DFA states. Finally, qo, the set constructed from no, becomes do, the DFA’s initial state.
Notice that Q grows monotonically. The while loop adds sets to Q but never removes them. Since the number of configurations of the NFA is bounded-each qi is a subset of 2N(the powerset of N)-and each qi appears on the worklist exactly once, the while loop must halt.
Q can become large-as large as|2N| distinct states. The amount of nonde-terminism found in the NFA determines how much state expansion occurs. Recall, however, that the result is a DFA, so that it makes exactly one transition per input character, independent of the number of states in the DFA.Thus, any expansion introduced by the subset construction does not affect the asymptotic running time of the DFA. If the data structures used to represent the DFA become sufficiently large, memory locality may become an issue that affects runtime performance. Fortunately, DFA minimization and table compression can mitigate these effects(see Sections 2.4.4 and 2.5.4).
Example
Section titled “Example”Fig. 2.7(a) shows the NFA that Thompson’s construction built for a(b|c)*with its states renumbered to read left-to-right. The table in Fig. 2.7(b)sketches the steps of the subset construction on that NFA. The first column shows the name of the set in Q being processed in a given iteration of the while loop. The second column shows the name of the corresponding state in the new DFA. The third column shows the set of NFA states contained in the current set from Q. The final three columns show the result of applying FollowEpsilon(Delta(qi,x)) to the current set and each character .
(a) Original NFA
| Set Name | DFA State | NFA States | a | b | c |
|---|---|---|---|---|---|
| q₀ | d₀ | {n₀} | {n₁, n₂, n₃, n₄, n₆, n₉} | -none | -none |
| q₁ | d₁ | {n₁, n₂, n₃, n₄, n₆, n₉} | -none | {n₅, n₈, n₉, n₃, n₄, n₆} | {n₇, n₈, n₉, n₃, n₄, n₆} |
| q₂ | d₂ | {n₅, n₈, n₉, n₃, n₄, n₆} | -none | q₂ | q₃ |
| q₃ | d₃ | {n₇, n₈, n₉, n₃, n₄, n₆} | -none | q₂ | q₃ |
(b) Iterations of the Subset Construction
(c) Resulting DFA
Figure 2.7 Applying the Subset Construction to the NFA from Fig. 2.5.
The algorithm takes the following steps:
-
The initialization sets q0 to FollowEpsilon((n0)), which is(n0).
-
The first iteration applies Delta and FollowEpsilon to q0 with a,b, and c. Using a yields q1, which contains six NFA states. Using b and c both produce the empty set.
-
The second iteration of the while loop examines q1. Using a produces the empty set, while b yields q2 and c yields q3.
-
The third iteration of the while loop examines q2. Using a produces the empty set, while b and c reconstruct q2 and q3.
-
The fourth iteration of the while loop examines q3. It again reconstructs q2 and q3. The algorithm halts because WorkList is empty.
Fig. 2.7(c) shows the resulting DFA. The DFA states correspond to the sets in Q; the table and the transitions are taken from T. Each of q1,q2, and q3 is an accepting state in the DFA because each contains n9, the NFA’s accepting state.
Fixed-Point Computations
Section titled “Fixed-Point Computations”The subset construction is an example of a fixed-point computation, a particular style of computation that arises regularly in many areas of computer science. These computations are characterized by the iterated application of a monotone function to some collection of sets drawn from a domain whose structure is known. These computations terminate when they reach a state where further iteration produces the same answer-a “fixed point” in the space of successive iterates. Fixed-point computations play an important and recurring role in compiler construction.
Termination arguments for fixed-point algorithms usually depend on known properties of the domain. For the subset construction, the domain D is the set of subsets of N. The construction builds up the set Q, where each is a subset of N. Since N is finite, 2N is finite and the number of distinct elements in Q is bounded.
The while loop functions as a monotone increasing function operating on Q.It adds elements to Q, so the successive iterations produce successively larger approximations to Q. If the i th approximation to Q is Q, then the algorithm ensures that . Because Q has, at most elements, the while loop can iterate at most|2N| times. It may, of course, reach a fixed point and halt more quickly than that.
A concern with fixed-point algorithms is the uniqueness of their results. For example, does the order in which the algorithm selects q from the worklist affect the final set Q? In this algorithm, the monotone function
Monotone function
a function f on domain D is monotone if.
applies the union operator to sets. Because set union is both commutative(a\cup b=b\cup a) and associative((a\cup b)\cup c=a\cup(b\cup c)), the order in which the loop adds sets to Q does not change the final result. The subscripts assigned to specific may change with different orders of removal from the worklist, but the final Q will always contain the same sets of valid NFA configurations. The different possibilities for Q differ, at most, by the names of the q; sets.
2.4.4 DFA to Minimal DFA
Section titled “2.4.4 DFA to Minimal DFA”As the final step in the RE→DFA construction, we can employ an algorithm to minimize the number of states in the automaton. The subset construction can produce a DFA that has a large set of states. While the size of the DFA does not affect its asymptotic complexity, it does determine the recognizer’s footprint in memory. On modern computers, the speed of memory accesses often governs the speed of computation. A smaller recognizer may fit better into the processor’s lowest level of cache memory, producing faster average accesses.
To reduce the number of states in the DFA, the scanner generator can apply a DFA minimization algorithm. The best known and asymptotically fastest algorithm, Hopcroft’s algorithm, constructs a minimal DFA from an arbitrary DFA by grouping together states into sets that are equivalent. Two DFA states are equivalent when they produce the same behavior on any input string. The algorithm finds the largest possible sets of equivalent states;each set becomes a state in the minimal DFA.
Set partition
Section titled “Set partition”A partition of S is a collection of disjoint, nonempty subsets of S whose union is exactly S.
The algorithm constructs a set partition, P={p1,p2,p3,…,pm} of the DFA states. Each p; contains a set of equivalent DFA states. More formally, it constructs a partition with the smallest number of sets, subject to the following two rules:
-
, if ; and ; then .
-
If and , then .
Rule 1 mandates that two states in the same set must, for every character , transition to states that are, themselves, members of a single set in the partition. Rule 2 states that any single set contains either accepting states or nonaccepting states, but not both.
These two properties not only constrain the final partition, P, but they also lead to a construction for P. The algorithm starts with the coarsest partition on behavior,PO={DA,{D-DA}}}.It then iteratively “refines” the partition until both properties hold true for each set in P. To refine the partition, the algorithm splits sets based on the transitions out of DFA states in the set.
divides D into accepting and nonac-cepting states, a fundamental difference in behavior specified by rule 2.
(a) a Does Not Split p1
(b) a Splits p1
(c) Sets from Panel b After the Split
FIGURE 2.8 Splitting a Set Around a.
Fig. 2.8 shows how the algorithm uses transitions to split sets in the partition. In panel(a), all three DFA states in set p1 have transitions to DFA states in p2 on the input character a. Specifically, , and .Since , and , sets and conform to rule 1.Thus, the states in p1 are behaviorally equivalent on a, so a does not induce the algorithm to split p1.
By contrast, panel(b) shows a situation where the character a induces a split in set p1.As before, , and , but while p3.This situation violates rule 1, so a induces the algorithm to split p1 into two sets, and , shown in panel(c).
The algorithm, shown in Fig. 2.9, builds on these ideas. Given a DFA, it constructs an initial partition of the DFA’s states. It starts with the coarsest partition consistent with rule 2,{DA},{D-D_{A}}}.
This choice of the initial partition has two consequences. First, since each set in the final partition is constructed by splitting a set in an earlier approximation, it ensures that no set in the final partition will contain both accepting and nonaccepting states. Second, by choosing the largest sets consistent with rule 2, it imposes the minimum constraints on the splitting process which, in turn, can lead to larger sets in the final partition.(Larger sets means fewer states in the final DFA.)
The algorithm operates from a worklist of states, starting with the initial partition{D_{A},{D-D_{A}}}}. It repeatedly picks a set s from the worklist and uses that set to refine Partition by splitting sets based on their transitions into s.
To identify states that must split because of a transition into set s on some character c, the algorithm inverts the transition function. It computes Image
Starting with the largest possible sets and splitting them is an optimistic approach to building the sets. Optimism is discussed in Section 9.3.6 or[359].
Partition←{D_{A},{D-D_{A}}}
Worklist←{D_{A},{D-D_{A}}}
while(Worklist≠∅) do
select a set s from Worklist and remove it
for each character c∈∑ do
Image←{x|δ(x,c)∈s}
for each set q∈ Partition that has a state in Image do
q1←q∩Image
q2←q-q1
if q2≠∅ then// split q around s and c
remove q from Partition
Partition←Partition∪q1∪q2
if q∈ Worklist then// and update the Worklist
remove q from Worklist
WorkList←WorkList∪q1∪q2
else if|q1|≤|q2| then
WorkList←Worklist∪q1
else WorkList←WorkList∪q2
if s=q then// need another s
break
■ FIGURE 2.9 DFA Minimization Algorithm.
Section titled “■ FIGURE 2.9 DFA Minimization Algorithm.”as the set of DFA states that can reach a state in s on a transition labeled c. It then systematically examines each set q that has a state in Image to see if Image induces a split in q. If Image divides q into nonempty sets q1 and q2,it replaces q in Partition with q1 and q2.
All that remains, in processing q with respect to c, is to update the worklist. If q is on the worklist, then the algorithm replaces q with both q1 and q2.The rationale is simple: q was on the worklist for some potential effect; that effect might be from some character other than c, so all of the DFA states in q need to be represented on the worklist.
If, on the other hand, q is not on the worklist, then the only effect that splitting q can have on other sets is to split them. Assume that some set r has transitions on letter e into q. Dividing q might create the need to split r into sets that transition to q1 and q2. In this case, either of q1 or q2 will induce the split, so the algorithm can choose between them. Using the smaller set will lead to faster execution; for example, computing Image takes time proportional to the size of the set.
Figure 2.10 Applying the DFA Minimization Algorithm.
Panel (a) shows iterations of Hopcroft’s algorithm on the original DFA for fee | fie. The table tracks the step, partition on entry, worklist, splitter state, character, image, successor partitions, and action. It splits p1 into p2, p3, then splits p3 into p4, p5; remaining transitions require no further split.
Original DFA for fee | fie:
s0 --f--> s1 --e--> s2 --e--> s3* \ --i--> s4 --e--> s5*
Minimal DFA:
d0 --f--> d1 --e,i--> d2 --e--> d3*To construct the new DFA from the final partition, create a state to represent each set p_i in Partition and add transitions between the new representative states as needed. The construction ensures that, if d_j --c--> d_k where d_j is in p_m and d_k is in p_n, then every state in p_m has a similar transition on c to a state in p_n. If this condition did not hold, the algorithm would have split p_m around the transitions on c. The resulting DFA is minimal.
Examples
Section titled “Examples”As a first example, consider the DFA for fee | fie shown in Fig. 2.10(b). Panel (a) shows the progress of Hopcroft’s algorithm on this DFA.
(a) Original DFA (b) Initial Partition
■ FIGURE 2.11 DFA for a (b|c)*.
The first line shows the algorithm’s initial configuration. Partition and Worklist each contain two sets: {D_A, {D - D_A}}. D_A is labeled p₀ while {D - D_A} is labeled p₁.
The algorithm enters the while loop and removes p₀ from Worklist; it becomes s. The algorithm iterates over the characters in Σ, in the order e, f, and i. For e, p₀ splits p₁ into two sets: p₂: {s₀,s₁} and p₃: {s₂,s₄}. The algorithm removes p₁ from Partition and adds p₂ and p₃. Next, it removes p₁ from Worklist and adds p₂ and p₃. For f and i, no edges enter p₀. Thus, Image is empty and no splits occur.
The second iteration proceeds in a similar fashion. It chooses p₂. The character e splits p₃ and causes an update to both Partition and Worklist. For f, the Image set is empty. For i, the Image set contains s₁. Because the algorithm already split p₃ around e, this situation does not cause a split. It will, however, add a transition to the final DFA.
The third iteration chooses p₄ from the worklist. Both e and i produce empty Image sets. With f, the Image set contains s₀. Because p₅, which contains s₀, is a singleton set, it cannot be split. This situation, however, will add a transition to the final DFA.
The final iteration takes p₅ from the worklist. For each of e, f, and i, the Image set is empty. Thus, the iteration splits no sets, adds no transitions, and empties the worklist. Panel (c) shows the minimal DFA.
As a second example, consider the DFA for a(b|c)* produced by Thompson’s construction and the subset construction, shown in Fig. 2.11(a). The initial partition is {p₀:{s₁,s₂,s₃},p₁:{s₀}}.
The algorithm first selects p₀ and examines each of a, b, and c. For a, Image contains s₀ which is in a singleton set, p₁. Thus, a introduces a transition for the final DFA, but no split. For both b and c, Image is {s₁,s₂,s₃}, which is exactly p₀. Thus, q₂ is empty and no splits occur.
Next the algorithm removes p1 and examines each of a,b, and c. Since no transitions enter p1, the Image set is empty for each letter. No further splits occur. The original two set partition is the final partition. The final DFA has two states, as shown in the margin. Recall that this is the DFA that we suggested a human would derive. After minimization, the automatic techniques produce the same result.
2.4.5 Using a DFA as a Scanner
Section titled “2.4.5 Using a DFA as a Scanner”The tools in the three previous sections provide an algorithmic path from an RE to a minimal DFA. As we saw in Fig. 2.2, a DFA can be simulated with a simple table-driven skeleton. Taken together, these suggest that we can automate scanner construction by taking REs for all of the words in a programming language, combining them into a single RE, and using the resulting DFA to build a scanner. Reality, however, is more complex. Scanners and DFAs differ in two critical ways that affect how we formulate and build RE-based scanners.
Model of Execution
Section titled “Model of Execution”A DFA reads all of its input and accepts the input if its last state is a final state. That is, a DFA tries to find one word. By contrast, a scanner reads enough input to find the next word in the input stream. The scanner leaves the input stream in a state from which it can find the next word.
This difference necessitates a new model of execution. Rather than ex-hausting the input stream, the scanner simulates the DFA until it hits an error-that is, until it is in some state with input character c such that , the error state. We also define
If is an accepting state, , the scanner has found a word. If is not an accepting state, the scanner may have passed through such a state on its way to d. To determine if it did, the scanner must back up, one character at a time until it either reaches an accepting state or it exhausts the lexeme.
This scheme adds some work to the implementation. The scanner must either record states or invertδ. Either approach takes time proportional to the number of scanned characters. A character may be scanned multiple times; Section 2.5.1 shows a method for avoiding the worst case of this behavior.
Finding Syntactic Categories
Section titled “Finding Syntactic Categories”A DFA returns a binary answer: it either accepts or rejects the input. By contrast, a scanner returns a token,<lexeme, category>, that gives the spelling
IDENTIFYING KEYWORDS
Section titled “IDENTIFYING KEYWORDS”Most programming languages reserve the keywords that identify critical parts of the syntax, words such as if, then, and whi1e. In a typical scanner and parser, each keyword has a unique syntactic category with just one lexeme. The compiler writer faces a choice: specify each keyword with its own rule, or fold keywords into the rule for identifiers and recognize them with some other mechanism. Either approach works and can lead to an efficient scanner.
With a separate rule for each keyword, the scanner can return the appropriate category using the same mechanism used for other categories, such as number or identifier. The extra rules may add minor cost to scanner generation and the DFA may have more states. However, since the process produces a DFA, the resulting scanner will still require O(1) time per character.
As an alternative, most scanners build a table of all identifier names. This table serves as a start on the compiler’s symbol table and as a way to map identifier names into small integers so that they can be represented and compared efficiently(see Section 4.5). If the compiler writer preloads the symbol table with the keywords and their syntactic categories, the scanner will find the keywords as previously seen and categorized identifiers, and will return the appropriate category for each.
and syntactic category of the next word. If the scanner encounters an error, it can return an invalid token.
d,∈DA maps uniquely to a category, but one category may map to multiple d,s. If we construct the DFA so that each final state maps to a single category, then the scanner can find the category with a simple table lookup. How-ever, this scheme requires that we build the DFA in a way that preserves the mapping of final states to categories.
Most scanner generators take, as input, a list of REs, r1, r2,…,rk, each of which defines the spelling of some category. The obvious way to build a single DFA is to construct a single RE,(r1|r2|…|rk), and construct a DFA from this RE. However, Thompson’s construction will immediately unify the final states, destroying the mapping from to categories.
To preserve the mapping from final states to unique categories, the scanner generator can build a distinct NFA for each rule, using Thompson’s construction. It can join those NFAs into a single DFA, with a new start state and e-transitions, and use the subset construction to build a DFA that simulates the NFA. The resulting DFA may have more states, but each final state corresponds to a single rule and, therefore, one syntactic category.
If two rules overlap, the subset construction will merge their final states. When the subset construction merges final states, the scanner generator must decide which syntactic category it will return for that final state. In practice, scanner generators let the compiler writer specify a precedence among syntactic categories. The scanner generator assigns to the final state the category with the highest precedence.
Minimization poses another challenge. Hopcroft’s algorithm immediately combines all of the final states into a single partition, destroying the property that final states map to syntactic categories. If, however, the scanner generator constructs an initial partition that places the final states for each syntactic category in a distinct set in the initial partition, then the rest of the algorithm will maintain that property.
The resulting DFA may be larger than the minimal DFA that results from grouping all final states into the same partition. However, the larger DFA has the property that the compiler needs: each final state maps to a specific syntactic category.
The Role of Whitespace
Section titled “The Role of Whitespace”Programmers often refer to blanks and tabs, when used to format code, as whitespace. In most languages, whitespace has no intrinsic meaning. Scan-ners for these languages typically recognize and discard whitespace. The primary impact of whitespace arises from its absence in the REs that define words in the language.
For example, the fact that the RE for an identifier or keyword name does not include a blank or tab forces an RE-based scanner to separate do and i in a sentence such as:
For similar reasons, the RE for an identifier does not contain+,-,,or/.This fact ensures that “ab” scans the same as “a*b”.
FORTRAN 66
Section titled “FORTRAN 66”In FORTRAN 66, blanks are not significant. That is,“n a m e” and “name”refer to the same identifier. This rule complicates scanning. The header of a FORTRAN do loop might read:
This situation reveals an ambiguity in the specification. For example, a keyword such as then may also match the rule for an identifier.
Both flex and flex assign higher precedence to the rule that appears first in the list of rules.
Hopcroft’s algorithm splits partitions but never combines them.
where 10 is the label of the last statement in the loop body, i is the loop’s index variable, and i’s value runs from 1 to 100. (The increment defaults to one unless specified.)
Of course, do10i is a valid variable name. To differentiate between these two statements:
do 10 i = 1 do 10 i = 1,100
a scanner must read beyond the = and 1 to the comma. The comma proves that the second statement is a loop header, and the scanner can separate do10i into three words, do, 10, and i. Few, if any languages, have followed FORTRAN’s example.
PYTHON
Section titled “PYTHON”PYTHON takes the opposite approach: not only are blanks significant, but the number of blanks at the start of a line determines the meaning of a PYTHON program. Rather than using bracket constructs, such as { and } or begin and end, to indicate block structure, PYTHON relies on changes in indentation.
A simple way of handling leading blanks in PYTHON is to add a rule that recognizes an end-of-line followed by zero or more blanks. The scanner can then test the length of the lexeme. If its length is identical to the previous token in this category, it returns the result of calling the scanner again. If its length differs, the scanner can return a category indicating the start of a block or the end of a block, as appropriate.
SECTION REVIEW
Section titled “SECTION REVIEW”Given a regular expression, we can derive a DFA to recognize the language specified by the RE in a two-step process: (1) apply Thompson’s construction to build an NFA for the RE and (2) use the subset construction to construct a DFA that simulates the NFA. The resulting DFA will be both fast and efficient.
To build a scanner that recognizes multiple categories of words, each specified by an RE, we can use the two-step process to build a minimal RE for each category, and then combine those DFAs into a single NFA by adding a new start state that has ε-transitions to the start states of the individual minimal DFAs. The subset construction will convert that NFA to a DFA that has distinct final states for each category. REVIEW QUESTIONS
- Consider the RE who | what | where. Use Thompson’s construction to build an NFA from the RE. Use the subset construction to build a DFA from the NFA. Minimize the DFA.
- Minimize the DFA shown in the margin.
2.5 IMPLEMENTING SCANNERS
Section titled “2.5 IMPLEMENTING SCANNERS”Scanner generators apply the theory of formal languages directly to the problem of creating efficient tokenizers for programming languages. Using the techniques outlined in the previous section, these tools build DFA models of a programming language’s microsyntax and convert those models into executable code.
This section discusses three implementation strategies for converting a DFA into executable code. The first two, table-driven scanners and direct-coded scanners, rely on scanner generators to translate a set of REs into a scanner. The third strategy has the compiler writer craft a custom scanner by hand. Each approach can lead to a robust and efficient scanner.
Generated scanners operate by simulating a DFA, as described in Section 2.4.5. They begin in the initial state and take a series of transitions based on the current state and input character. When the current state has no valid transition for the input character, the scanner backs up until it finds an accepting state. If it cannot find an accepting state, it reports a lexical error.
The next three subsections discuss implementation differences between table-driven, direct-coded, and hand-coded scanners. The strategies differ in how they model the DFA’s transition structure and how they simulate its operation. Each approach can produce a scanner that uses O(1) time per character; the differences, however, can affect the constants in the complexity equation. The final subsection looks at two different approaches for handling reserved keywords.
2.5.1 Table-Driven Scanners
Section titled “2.5.1 Table-Driven Scanners”The table-driven approach uses a skeleton scanner for control and a set of generated tables to encode language-specific knowledge. Typically, table-driven scanners come from scanner generators. At design time, the compiler writer creates a set of REs. At build time, the scanner generator creates a set of tables to implement the DFA and compiles the tables with the skeleton scanner.
state ← S0; lexeme ← ""; clear stack; push(bad);
while (state ≠ S_e) do char ← NextChar(); lexeme ← lexeme + char; if state ∈ S_A then clear stack; push(bad); push(state); col ← CharClass[char]; state ← δ[state, col]; while (state ≠ S_A and state ≠ bad) do state ← pop(); if state ≠ bad then truncate lexeme; RollBack(); if state ∈ S_A then return Type[state]; else return invalid;
(a) Code to Interpret the Tables
■ FIGURE 2.12 A Table-Driven Scanner for Register Names.
Conceptually, the process looks like:
Fig. 2.12 shows a table-driven scanner for the RE r[0…9]+, introduced in Section 2.3.2. Panel (a) shows the code for the skeleton scanner. Panels (b), (c), and (d) show the tables that encode the DFA, which is shown in panel (e). The code is more detailed than that shown in Fig. 2.2 on page 35, but the basic operation is similar.
In the table, the entries for 0…9 have been combined into a single column. Section 2.5.4 discusses table compression.
The skeleton scanner divides into four sections: initializations, a scanning loop to model the DFA’s behavior, a roll back loop to find a final state, and a final section to interpret and report the results. The scanning loop repeats 2.5 Implementing Scanners 65 the two basic actions of a scanner: read a character and take a transition. The loop halts when the DFA enters the error state, . The transition table represents the DFA’s transition diagram. Identical columns in have been combined, so the scanner uses the table CharClass to map an input character into a column index inδ. The roll back loop uses a stack of states to revert the scanner to its most recent accepting state.
The function NextChar returns the next character in the input stream. A corresponding function, RollBack, moves the input stream back by one character(see Section 2.5.4).
When the scanning loop halts, state is , the error state. The scanner backs up until it either finds an accepting state or it proves that none exists. In most languages, the amount of such roll back will be limited. We can construct REs that will require quadratic roll back on specific inputs. If the scanner must handle such an RE, an alternative implementation, such as the one described in the next subsection, should be used. In most programming languages, however, the amount of roll back should be small.
Avoiding Excess Roll Back
Section titled “Avoiding Excess Roll Back”Some REs can cause the scanner in Fig. 2.12(a) to need quadratic roll back. The problem arises from the desire to have the scanner return the longest word that is a prefix of the input stream.
Consider the RE ab|(ab)*c. The corresponding DFA, shown in the margin recognizes either ab or any number of occurrences of ab followed by a final c. On the input string ababababc, a scanner built from the DFA will read all the characters and return the entire string as a single word. If, however, the input is abababab, it must scan all of the characters before it can determine that the longest prefix is ab. On the next invocation, it will scan ababab to return ab. The third call will scan abab to return ab, and the final call will simply return ab without any roll back. In the worst case, roll back can create behavior.
The maximal munch scanner avoids this kind of pathological behavior by marking dead-end transitions as they are popped from the stack. Thus, over time, it records specific〈state, input position〉 pairs that cannot lead to an accepting state. Inside the scanning loop, the code tests each〈state, input position) pair and breaks out of the scanning loop whenever a failed transition is attempted.
DFA for ab|(ab)*c state ← S0; lexeme ← ""; clear stack; push((bad, -1));
while (state ≠ S_e) do if Failed[state, InputPos] then (state, InputPos) ← pop(); truncate lexeme; break; char ← Input[InputPos]; lexeme ← lexeme + char; if state ∈ S_A then clear stack; push((bad, -1)); push((state, InputPos)); col ← CharClass[char]; state ← δ[state, col]; InputPos ← InputPos + 1;
while (state ≠ S_A and state ≠ bad) do if state ≠ S_e then Failed[state, InputPos] ← true; (state, InputPos) ← pop(); if state ≠ bad then truncate lexeme; if state ∈ S_A then return TokenType[state]; else return invalid; end end
■ FIGURE 2.13 The Maximal Munch Scanner.
Fig. 2.13 shows the maximal munch scanner. The scanner keeps a global counter, InputPos, to record position in the input stream. It uses a bit-array, Failed, to record dead-end transitions. Failed has a row for each state and a column for each character in the input stream. When the scanner must roll back the input, it marks the appropriate transitions in Failed to prevent it from taking the same dead-end path on subsequent invocations.
The code in Fig. 2.13 runs on each call to the scanner. Before the first call to the scanner, both Failed and InputPos must be initialized. Every bit in Failed is set to false. InputPos is set to one. Minor optimizations can reduce the size of Failed. For example, if the scanner uses a finite input buffer(see Section 2.5.4), the number of columns in Failed can be reduced to the size of the input buffer.
Most programming languages have simple enough microsyntax that this kind of quadratic roll back cannot occur. If, however, you are building a scanner for a language that has this problem, these techniques can avoid it for a small additional overhead per character.
2.5.2 Direct-Coded Scanners
Section titled “2.5.2 Direct-Coded Scanners”To improve the performance of a table-driven scanner, we must reduce the cost of one or both of its basic actions: read a character and compute the next DFA transition. Direct-coded scanners reduce the cost of computing DFA transitions by replacing the explicit representation of the DFA’s state and transition function with an implicit one. The implicit representation simplifies the two-step, table-lookup computation. It eliminates the memory references entailed in that computation and allows other specializations. The resulting scanner has the same functionality as the table-driven scanner, but with a lower overhead per character. A direct-coded scanner is no harder to generate than the equivalent table-driven scanner.
The table-driven scanner spends most of its time inside the central while loop; thus, the heart of a direct-coded scanner is an alternative implementation of that while loop. With some detail abstracted, that loop performs the following actions:
while(state≠s) do
char← NextChar();
col← CharClass[char];
state←δ[state, col];
Here, state explicitly represents the DFA’s current state andδ is a two dimensional array that represents the DFA’s transition function. Identical columns inδ have been combined(see Section 2.5.4). CharClass is a vector that maps an input character to a column index inδ.
Reducing the Overhead of Table Lookup
Section titled “Reducing the Overhead of Table Lookup”For each character, the table-driven scanner accesses two arrays:δ and CharClass. While both lookups take O(1) time, these table lookups have
| δ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Other |
|---|---|---|---|---|---|---|---|---|---|---|---|
| S0 | S1 | S2 | S2 | S2 | S2 | S2 | S2 | S2 | S2 | S2 | Se |
| S1 | Se | Se | Se | Se | Se | Se | Se | Se | Se | Se | Se |
| S2 | S2 | S2 | S2 | S2 | S2 | S2 | S2 | S2 | S2 | S2 | Se |
| Se | Se | Se | Se | Se | Se | Se | Se | Se | Se | Se | Se |
(a) The Full Transition Table for 0|[1…9][0…9]*
(b) The Compressed Table
Figure 2.16 Transition-Table Compression Example.
mentation is sufficiently simple to be expanded inline. Initialize simply provides a known and consistent starting state.
As a consequence of using finite buffers, RollBack has a limited history in the input stream. To keep it from decrementing the pointer beyond the start of that context, NextChar and RollBack cooperate. The pointer Fence always indicates the start of the valid context. NextChar sets Fence each time it fills a buffer. RollBack checks Fence each time it tries to decrement the Input pointer.
After a long series of NextChar operations, say, more than n of them where n is the buffer size, RollBack can always back up at least n characters. However, a sequence of calls to NextChar and RollBack that work forward and backward in the buffer can create a situation where the distance between Input and Fence is less than n. Larger values of n decrease the likelihood of this situation arising.
If n is chosen to make the I/O efficient, say 2,048 or 4,096 bytes for each half of the buffer, that should provide enough rollback for real programs. The amount of rollback required by any particular input is bounded by the longest sequence of whitespace-free characters. Few programs contain identifiers with more than 2,048 characters.
Compressing the Transition Table
The transition table for a DFA contains |states|·|Σ| entries. For a real programming language, both |states| and |Σ| can be large. When the table size grows larger than the size of the first-level cache, it may cause performance problems.
The transition table for a programming language scanner often contains identical columns. (If the DFA is minimal, its rows cannot be identical.) Consider, for example, the DFA for 0|[1…9][0…9]*, introduced in Section 2.2.2 and repeated in the margin. Fig. 2.16(a) shows the naive representation of the table. Panel (b) of that figure shows the same table, with
DFA for 0|[1…9][0…9]* for i←1 to NumCols do MapTo[i]←i for i←1 to NumCols - 1 do if MapTo[i]=i then for j←i + 1 to NumCols do if MapTo[j]=j then same ← true for k←1 to NumRows if δ(k,i)≠δ(k,j) then same ← false break if same then MapTo[j]←i
Figure 2.17 Finding Identical Columns in the Transition Table δ.
the columns for the characters 1 through 9 compressed into a single column. The code skeletons in Sections 2.12 and 2.13 create one more opportunity:the row for se cannot be referenced and, thus, need not be represented.
To use a compressed table, the scanner must map actual characters into columns in the transition table. A simple and efficient way to implement this translation is with a classification table that maps an input character to a column index. The fundamental loop in a scanner can be abstracted to the code shown on the left, below.
while (state ≠ se) do char ← NextChar(); state ← δ[state, char]; while (state ≠ se) do char ← NextChar(); col ← CharClass[char]; state ← δ[state, col];
The corresponding code, with classification, is shown on the right. It adds one memory reference from CharClass; in return, the scanner can use a much smaller table representation.
Of course, the scanner generator must generate both the classifier and the compressed table. Fig. 2.17 shows the obvious algorithm to find identical columns. It assumes a transition table,δ with NumCols columns and Num-Rows rows. When it finishes, if MapTo[i]=j, for i≠j, then rows i and j are identical and can be compressed to a single row. We leave the construction of the classifier table and the compressed version of δ as an exercise for the reader(see Exercise 2.13).
The algorithm, as shown, performs O(|Σ|2) comparisons in the worst case. Each comparison costs O(|states|) time. We can reduce the quadratic term
by keeping, for each column of δ, a population count of the nonerror states in the column. Since identical columns must have identical counts, the algorithm can construct an index set and radix sort it based on the population count. Then, it need only compare two columns if the radix sort puts them in the same category. This strategy should lead to multiple groups, each of which requires O(n²) comparisons; however, each n should be smaller than |Σ|.
The count of nonerror states is a simple signature for the column. More complex, and possibly more expensive, signatures can be implemented. In the best case, they reduce the cost of the comparisons to O(1). There is, however, a direct tradeoff between the cost of the comparison and the cost of computing the signature—an issue for the careful implementor to consider.
SECTION REVIEW Automated techniques can easily build scanners from minimal DFAs. The scanner generator can adopt either a table-driven approach, with a generic skeleton scanner and language-specific tables, or a direct-coded scanner that threads together DFA states with explicit branches. In general, direct-coded scanners have a lower overhead per character than table-driven scanners.
Despite the fact that all DFA-based scanners have small constant costs per character, many compiler writers choose to hand code a scanner. This approach lends itself to careful implementation of the interfaces between the scanner and the I/O system and between the scanner and the parser.
REVIEW QUESTIONS
- Given the DFA shown in the margin, complete the following: a. Build the transition table, based on the transition diagram and your character classifier. b. Write an equivalent direct-coded scanner.
- An alternative implementation might use a DFA for (a|b|c) (a|b|c) (a|b|c), followed by a lookup in a table that contains the three words abc, bca, and cab. a. Sketch the DFA for this language. b. Contrast the cost of this approach with using the DFA from question one above.
2.6 ADVANCED TOPICS
Section titled “2.6 ADVANCED TOPICS”This section expands on the material in Section 2.4. The combination of Thompson’s construction and the subset construction demonstrates that DFAs can express any computation that can be expressed as an RE. To complete the cycle and show that an RE can express any computation embodied by a DFA, we need a construction to create an RE that represents the set of words accepted by an arbitrary DFA. Section 2.6.1 sketches that construction, often called Kleene’s algorithm.
Section 2.6.2 looks at an interesting subcase of the RE to DFA problem: closure-free REs. The DFA for a closure-free RE is acyclic. Section 2.6.2 sketches an algorithm to build such a DFA directly and incrementally.
Finally, Section 2.4.4 presented Hopcroft’s algorithm for DFA minimization. Section 2.6.3 describes an alternative algorithm by Brzozowski that reuses the subset construction.
2.6.1 DFA to Regular Expression
Section titled “2.6.1 DFA to Regular Expression”The final step in the cycle of constructions, shown in Fig. 2.3, is to build an RE from a DFA. The combination of Thompson’s construction and the subset construction provides a constructive proof that DFAs are at least as powerful as REs. This section presents Kleene’s construction, which builds an RE to describe the set of strings accepted by an arbitrary DFA. This algorithm establishes that REs are at least as powerful as DFAs. Together, they show that REs and DFAs are equivalent.
Consider the transition diagram of a DFA as a graph with labeled edges. The problem of deriving an RE that describes the language accepted by the DFA corresponds to a path problem over the DFA’s transition diagram. The set of strings in L(DFA) consists of the set of edge labels for every path from to For any DFA with a cyclic transition graph, the set of such paths is infinite. Fortunately, REs have the Kleene closure operator to handle this case and summarize the complete set of subpaths created by a cycle.
Fig. 2.18 shows one algorithm to compute this path expression. It assumes that the DFA has states numbered from 0 to|D|-1, with d0 as the start state. It generates an expression that represents the labels along all paths between two nodes, for each pair of nodes in the transition diagram. As a final step, it combines the expressions for each path that leaves and reaches some accepting state, . It constructs the path expressions for all paths by iterating over i,j, and k.
for i=0 to |D| - 1 do for j=0 to |D| - 1 do R_{ij}^{-1} ← {a | δ(d_i,a) = d_j} if (i=j) then R_{ij}^{-1} ← R_{ij}^{-1} | {ϵ} for k=0 to |D| - 1 do for i=0 to |D| - 1 do for j=0 to |D| - 1 do R_{ij}^{k} ← R_{ik}^{k-1} (R_{kk}^{k-1}) * R_{kj}^{k-1} | R_{ij}^{k-1} L ← |d_j∈D_A R_{0j}^{|D|-1}
■ FIGURE 2.18 Deriving a Regular Expression from a DFA.
Traditional statements of this algorithm assume that node names range from 1 to n, rather than from 0 to n - 1. Thus, they place the direct paths in R_{ij}^O.
We use the notation R_{ij}^k to represent the RE that describes all paths from d_i to d_j that do not pass through a state numbered higher than d_k. Here, through means that the path both enters and leaves a state numbered higher than d_k. In a DFA with a transition d_1→d_16, the RE R_1,16^2 would be nonempty because the path enters d_16 but does not pass through it.
Initially, the algorithm places all of the direct paths from d_i to d_j in R_{ij}^{-1}. It adds {ϵ} to each expression where i=j. Over successive iterations, it builds up longer paths; it computes R_{ij}^k from R_{ij}^{k-1} by adding those paths that pass through d_k on their way from d_i to d_j. The algorithm computes this additional component as (1) the set of paths from d_i to d_k that pass through no state numbered higher than k-1, concatenated with (2) any paths from d_k to itself that pass through no state numbered higher than k-1, concatenated with (3) the set of paths from d_k to d_j that pass through no state numbered higher than k-1. The assignment in the inner loop
R_{ij}^k ← R_{ik}^{k-1} (R_{kk}^{k-1}) * R_{kj}^{k-1} | R_{ij}^{k-1}
captures those paths and uses alternation to add them to the RE for the paths from R_{ij}^{k-1}. In this way, each iteration of the inner loop adds the paths that pass through d_k to R_{ij}^{k-1} to form R_{ij}^k.
When the k loop terminates, the various R_{ij}^k expressions account for all paths through the graph. The final step computes the set of paths that start with d_0 and end in some accepting state, d_j∈D_A, as the alternation of the path expressions.
2.6.2 Closure-Free Regular Expressions
Section titled “2.6.2 Closure-Free Regular Expressions”One subclass of regular languages that has practical application beyond scanning is the set of languages described by closure-free REs. Such REs have the form , where the individual words, , are just concatenations of characters in the alphabet, . These REs have the property that they produce DFAs with acyclic transition graphs.
These simple regular languages are of interest for two reasons. First, many pattern recognition problems can be described with a closure-free RE. Examples include words in a dictionary, URLs that should be filtered, and keys to a hash table. Second, the DFA for a closure-free RE can be built in a particularly efficient way.
To build the DFA for a closure-free RE, begin with a start state . To add a word to the existing DFA, the algorithm follows the path for the new word until it either exhausts the pattern or finds a transition to . In the former case, it designates the final state for the new word as an accepting state. In the latter, it adds a path for the new word’s remaining suffix. The resulting DFA can be encoded in tabular form or in direct-coded form (see Section 2.5.2). Either way, the recognizer uses constant time per character in the input stream.
In this algorithm, the cost of adding a new word to an existing DFA is proportional to the length of the new word. The algorithm also works incrementally; an application can easily add new words to a DFA that is in use. This property makes the acyclic DFA an interesting alternative for implementing a perfect hash function. For a small set of keys, this technique produces an efficient recognizer. As the number of states grows (in a direct-coded recognizer) or as key length grows (in a table-driven recognizer), the implementation may slow down due to cache-size constraints. At some point, the impact of cache misses will make an efficient implementation of a more traditional hash function more attractive than incremental construction of the acyclic DFA.
The DFAs produced in this way are not guaranteed to be minimal. Consider the acyclic DFA that it would produce for the REs deed, feed, and seed, shown in the margin. It has three distinct paths that each recognize the suffix eed. Clearly, those paths can be combined to reduce the number of states and transitions in the DFA. The algorithm will build a DFA that is minimal with regard to prefixes of words in the language, similar to those produced by the subset construction (see Section 2.4.3). A complete minimization would combine the suffixes, as well, to produce a smaller DFA.
DFA for deed | feed | seed (a) Original DFA (b) NFA from Reverse of Panel a (c) Subset of NFA in Panel b (d) Reverse of DFA in Panel c (e) Final DFA
■ FIGURE 2.19 Applying Brzozowski’s Algorithm to the DFA for a (b | c)*.
2.6.3 An Alternative DFA Minimization Algorithm
Section titled “2.6.3 An Alternative DFA Minimization Algorithm”The subset construction converted an NFA to a DFA by systematically eliminating ε-transitions and combining paths in the NFA’s transition diagram. If we apply the subset construction to an NFA that has multiple paths from the start state for some prefix, the construction combines those paths into a single path. The resulting DFA has no duplicate prefixes. Brzozowski used this observation to devise an alternative minimization algorithm that directly constructs the minimal DFA from either an NFA or a DFA.
For NFAs built with Thompson’s construction, reachability is not an issue. It can arise minimizing an arbitrary NFA.
For an NFA n, let reverse(n) be the NFA obtained by reversing the direction of all the transitions, making the initial state into a final state, adding a new initial state, and connecting it to all of the states that were final states in n. Further, let reachable(n) be a function that returns the set of states and transitions in n that are reachable from its initial state. Finally, let subset(n) be the DFA produced by applying the subset construction to n.
Now, given an NFA n, the minimal equivalent DFA is just
reachable( subset( reverse( reachable( subset( reverse(n))) )).
The inner application of subset and reverse eliminates duplicate suffixes in the original NFA. Next, reachable discards any states and transitions that are no longer interesting. Finally, the outer application of the triple, reachable, subset, and reverse, eliminates any duplicate prefixes in the NFA. (Applying reverse to a DFA can produce an NFA.)
Fig. 2.19 shows the steps that the algorithm takes to minimize the DFA for a (b | c)* produced in the previous two subsections. Panel (a) repeats the (a) NFA for a(b|c)*
(b) Subset of Reverse of Panel a
(c) Subset of Reverse of Panel b
■ FIGURE 2.20 Brzozowski’s Algorithm Applied to the NFA from Fig. 2.5.
DFA from Fig. 2.7. Applying reverse to this DFA produces the NFA shown in panel (b). Next, the algorithm applies subset to this NFA, to produce the DFA shown in panel (c). Reverse applied to panel (c) yields the NFA in panel (d). Applying subset to this NFA produces the final DFA shown in panel (e), which is minimal. Note that reachability did not play a role in this example.
Brzozowski’s algorithm can be expensive because of the potential for the subset construction to build an exponentially large set of states. Hopcroft’s algorithm has a lower asymptotic complexity: O(|N||Σ| log₂(|N|)), where N is the set of states in the input FA.
The tradeoff between the two algorithms is not straightforward. Studies of the running times of various FA minimization techniques suggest, however, that the actual running times depend on specific properties of the FA. In practice, Brzozowski’s algorithm appears to perform reasonably well.
Furthermore, the implementation of Brzozowski’s algorithm will almost certainly be simpler than that of Hopcroft’s algorithm. Since Brzozowski’s algorithm produces a DFA, it can be applied directly to the output of Thompson’s construction, eliminating an extra application of the subset construction.
Fig. 2.20 shows the steps that the algorithm takes when applied directly to the NFA that Thompson’s construction built for a(b|c)*. Panel (a) shows The first application of subset is, effectively, free. Scanners the original NFA. Panel(b) shows the DFA constructed by applying reverse and then subset to the NFA. Panel c shows the final DFA. The two reversed NFAs are left as an exercise for the reader.
Use in a Scanner Generator
Section titled “Use in a Scanner Generator”Because Brzozowski’s algorithm uses the subset construction, its first step combines all of the final states into a single representative state. As described in Section 2.4.5, the scanner needs a DFA where each final state maps to one syntactic category. We can modify Hopcroft’s algorithm to maintain this map; Brzozowski’s algorithm has no similar fix.
Applying Brzozowski’s algorithm to an NFA will produce a DFA.
To use Brzozowski’s algorithm in a scanner generator, the tool would need to build an NFA for each rule and apply Brzozowski’s algorithm to the individual NFAs. It could then combine those DFAs with transitions and use the subset construction to produce a final DFA. As before, if this application of the subset construction merges final states, it must assign the new final state the syntactic category of the higher priority rule. The resulting DFA will not be minimal. It will, however, be smaller than the DFA produced without minimization.
2.7 SUMMARY AND PERSPECTIVE
Section titled “2.7 SUMMARY AND PERSPECTIVE”The widespread use of REs for searching and scanning is one of the success stories of modern computer science. These ideas were developed as an early part of the theory of formal languages and automata. They are routinely applied in tools ranging from text editors to web filtering engines to compilers as a means of concisely specifying groups of strings that happen to be regular languages. Whenever a finite collection of words must be recognized, DFA-based recognizers deserve serious consideration.
The theory of REs and finite automata has developed techniques that allow the recognition of regular languages in time proportional to the length of the input stream. Techniques for automatic derivation of DFAs from REs and for DFA minimization have allowed the construction of robust tools that generate DFA-based recognizers. Both generated and hand-crafted scanners are used in well-respected modern compilers. In either case, a careful implementation should run in time proportional to the length of the input stream, with a small overhead per character.
CHAPTER NOTES
Section titled “CHAPTER NOTES”Originally, the separation of lexical analysis, or scanning, from syntax analysis, or parsing, was justified with an efficiency argument. Since the cost Chapter Notes 81 of scanning grows linearly with the number of characters, and the constant costs are low, pushing lexical analysis from the parser into a separate scanner lowered the cost of compiling. The advent of efficient parsing techniques weakened this argument, but the practice of building scanners persists because it provides a clean separation of concerns between lexical structure and syntactic structure.
Because scanner construction plays a small role in building an actual compiler, we have tried to keep this chapter brief. Thus, the chapter omits many theorems on regular languages and finite automata that the ambitious reader might enjoy. The many good texts on this subject can provide a much deeper treatment of finite automata and REs, and their many useful properties[206,241,327].
Kleene[235] established the equivalence of REs and FAs. Both the Kleene closure and the DFA to RE algorithm bear his name. McNaughton and Yamada showed one construction that relates REs to NFAs[270]. The construction shown in this chapter is patterned after Thompson’s work[345]; to add regular-expression search to the QED text editor, he built a small compiler that translated an RE into native code for the IBM 7094. Johnson was the first to describe the application of these ideas to automate scanner construction[218]. The subset construction derives from Definition 11 in Rabin and Scott[302].
Hopcroft published his DFA minimization algorithm, presented in Section 2.4.4 in 1971[205]. It has found application to a variety of problems, including detecting when two program variables always have the same value[23]. The alternative algorithm in Section 2.6.3 was published by Brzozowski in 1962[66]. Several authors have compared DFA minimization techniques and their performance[340,355]. Several authors have looked at the construction and minimization of acyclic DFAs[122,356,357].
The maximal munch scanner is due to Reps[307]. The idea of generating code rather than tables, to produce a direct-coded scanner, appears to originate in work by Waite[353] and Heuring[201]. They report a factor of five improvement over table-driven implementations. Ngassam et al. describe experiments that characterize the speedups possible in hand-coded scanners[283]. Several authors have examined tradeoffs in scanner implementation. Jones[219] advocates direct coding but argues for a structured approach to control flow rather than the spaghetti code shown in Section 2.5.2. Brouwer et al. compare the speed of 12 different scanner implementations; they discovered a factor of 70 difference between the fastest and slowest implementations[65].
EXERCISES
Section titled “EXERCISES”Section 2.2
Section titled “Section 2.2”- Describe informally the languages accepted by the following FAs:
a. S₀ → S₁ (a, b) S₀ → S₂ (a, b) S₀ → S₃ (0, 1)
b. S₀ → S₁ (0, 1) S₀ → S₂ (1, 0) S₀ → S₃ (1, 1)
c. S₀ → S₁ (b, a) S₀ → S₂ (a, b) S₀ → S₃ (a, b) S₀ → S₄ (a, b) S₀ → S₅ (a, b) S₀ → S₆ (a, b)
- Construct an FA accepting each of the following languages:
a. {w ∈ {a, b}* | w starts with “a” and contains “baba” as a substring} b. {w ∈ {0, 1}* | w contains “111” as a substring and does not contain “00” as a substring} c. {w ∈ {a, b, c}* | the number of a’s modulo 2 in a word in w equal to the number of b’s modulo 3 in the same word}
-
Create FAs to recognize (a) strings that represent complex numbers and (b) strings that represent decimal numbers written in scientific notation.
-
Different programming languages use different notations to represent integers. Construct a regular expression for each one of the following:
a. Nonnegative integers in C represented in bases 10 and 16. b. Nonnegative integers in VHDL that may include underscores (an underscore cannot occur as the first or last character). c. Currency, in dollars, represented as a positive decimal number rounded to the nearest one-hundredth. Such numbers begin with the character 8,937.43 and $7,777,777.77. 5. Write a regular expression for each of the following languages: a. Given an alphabet Σ={0,1}, L is the set of all strings of alternating pairs of 0s and pairs of 1s. b. Given an alphabet Σ={0,1}, L is the set of all strings of 0s and 1s that contain an even number of 0s or an even number of 1s. c. Given the lowercase English alphabet, L is the set of all strings in which the letters appear in ascending lexicographical order.
-
Write a regular expression to describe each of the following programming language constructs: a. Any sequence of tabs and blanks (e.g., whitespace) b. Comments in the programming language C c. String constants (without escape characters) d. Floating-point numbers
-
Consider the three regular expressions: (ab | ac)* (0 | 1)* 1100 1* (01 | 10 | 00)* 11
a. Use Thompson’s construction to construct an NFA for each RE. b. Convert the NFAs to DFAs. c. Minimize the DFAs.
-
Apply Hopcroft’s minimization algorithm to the DFA shown below.
-
Show that the set of regular languages is closed under intersection.
-
Construct a DFA for each of the following C language constructs, and then build the corresponding table for a table-driven implementation for each of them: a. Integer constants b. Identifiers c. Comments
-
For each DFA in the previous exercise, write a direct-coded scanner.
-
This chapter describes several ways to implement a DFA. Another alternative would use mutually recursive functions to implement a scanner. Discuss the advantages and disadvantages of such an implementation.
-
Fig. 2.17 shows an algorithm that discovers identical columns in the transition function, δ. Give an algorithm that constructs the character classifier, a map from characters to column numbers, and the reduced form of δ. Assume that column i of δ corresponds to the ith character in the alphabet, Σ, denoted Σi.
-
Apply Brzozowski’s algorithm to the following NFA:
| S0 | ε | S1 | a | S2 | b | S3 | c | S4 |
|---|---|---|---|---|---|---|---|---|
| S0 | ε | S5 | b | S6 | c | S7 | ||
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| S8 | ε | S9 | d | S10 |
Section 2.6
← node-book_engineering-a-compiler_chapter-01-overview-of-compilation | node-book_engineering-a-compiler | node-book_engineering-a-compiler_chapter-03-parsers →