Docsity

Compiler Construction - Niklaus Wirth, Manuais, Projetos, Pesquisas de Automação

Pré-visualização parcial do texto

Baixe Compiler Construction - Niklaus Wirth e outras Manuais, Projetos, Pesquisas em PDF para Automação, somente na Docsity!

Compiler Construction

Niklaus Wirth

This is a slightly revised version of the book published by Addison-Wesley in 1996

ISBN 0-201-40353-

Zürich, November 2005

Theory and Techniques of Compiler Construction

An Introduction

Niklaus Wirth

Preface

This book has emerged from my lecture notes for an introductory course in compiler design at ETH Zürich. Several times I have been asked to justify this course, since compiler design is considered a somewhat esoteric subject, practised only in a few highly specialized software houses. Because nowadays everything which does not yield immediate profits has to be justified, I shall try to explain why I consider this subject as important and relevant to computer science students in general.

It is the essence of any academic education that not only knowledge, and, in the case of an engineering education, know-how is transmitted, but also understanding and insight. In particular, knowledge about system surfaces alone is insufficient in computer science; what is needed is an understanding of contents. Every academically educated computer scientist must know how a computer functions, and must understand the ways and methods in which programs are represented and interpreted. Compilers convert program texts into internal code. Hence they constitute the bridge between software and hardware.

Now, one may interject that knowledge about the method of translation is unnecessary for an understanding of the relationship between source program and object code, and even much less relevant is knowing how to actually construct a compiler. However, from my experience as a teacher, genuine understanding of a subject is best acquired from an in-depth involvement with both concepts and details. In this case, this involvement is nothing less than the construction of an actual compiler.

Of course we must concentrate on the essentials. After all, this book is an introduction, and not a reference book for experts. Our first restriction to the essentials concerns the source language. It would be beside the point to present the design of a compiler for a large language. The language should be small, but nevertheless it must contain all the truly fundamental elements of programming languages. We have chosen a subset of the language Oberon for our purposes. The second restriction concerns the target computer. It must feature a regular structure and a simple instruction set. Most important is the practicality of the concepts taught. Oberon is a general-purpose, flexible and powerful language, and our target computer reflects the successful RISC-architecture in an ideal way. And finally, the third restriction lies in renouncing sophisticated techniques for code optimization. With these premisses, it is possible to explain a whole compiler in detail, and even to construct it within the limited time of a course.

Chapters 2 and 3 deal with the basics of language and syntax. Chapter 4 is concerned with syntax analysis, that is the method of parsing sentences and programs. We concentrate on the simple but surprisingly powerful method of recursive descent, which is used in our exemplary compiler. We consider syntax analysis as a means to an end, but not as the ultimate goal. In Chapter 5, the transition from a parser to a compiler is prepared. The method depends on the use of attributes for syntactic constructs.

After the presentation of the language Oberon-0, Chapter 7 shows the development of its parser according to the method of recursive descent. For practical reasons, the handling of syntactically erroneous sentences is also discussed. In Chapter 8 we explain why languages which contain declarations, and which therefore introduce dependence on context, can nevertheless be treated as syntactically context free.

Up to this point no consideration of the target computer and its instruction set has been necessary. Since the subsequent chapters are devoted to the subject of code generation, the specification of a target becomes unavoidable (Chapter 9). It is a RISC architecture with a small instruction set and a set of registers. The central theme of compiler design, the generation of instruction sequences, is thereafter distributed over three chapters: code for expressions and assignments to variables (Chapter 10), for

Contents

Preface

  1. Introduction
  2. Language and Syntax 2.1. Exercises
  3. Regular Languages
  4. Analysis of Context-free Languages 4.1. The method of recursive descent 4.2. Table-driven top-down parsing 4.3. Bottom-up parsing 4.4. Exercises
  5. Attributed Grammars and Semantics 5.1. Type rules 5.2. Evaluation rules 5.3. Translation rules 5.4. Exercises
  6. The Programming Language Oberon-
  7. A Parser for Oberon- 7.1. The scanner 7.2. The parser 7.3. Coping with syntactic errors 7.4. Exercises
  8. Consideration of Context Specified by Declarations 8.1. Declarations 8.2. Entries for data types 8.3. Data representation at run-time 8.4. Exercises
  9. A RISC Architecture as Target
  10. Expressions and Assignments 10.1. Straight code generation according to the stack principle 10.2. Delayed code generation 10.3. Indexed variables and record fields 10.4. Exercises
  11. Conditional and Repeated Statements and Boolean Epressions 11.1. Comparisons and jumps 11.2. Conditional and repeated statements 11.3. Boolean operations 11.4. Assignments to Boolean variables 11.5. Exercises
  12. Procedures and the Concept of Locality 12.1. Run-time organization of the store 12.2. Addressing of variables 12.3. Parameters 12.4. Procedure declarations and calls 12.5. Standard procedures 12.6. Function procedures 12.7. Exercises
  1. Elementary Data Types 13.1. The types REAL and LONGREAL 13.2. Compatibility between numeric data types 13.3. The data type SET 13.4. Exercises
  2. Open Arrays, Pointers and Procedure Types 14.1. Open arrays 14.2. Dynamic data structures and pointers 14.3. Procedure types 14.5. Exercises
  3. Modules and Separate Compilation 15.1. The principle of information hiding 15.2. Separate compilation 15.3. Implementation of symbol files 15.4. Addressing external objects 15.5. Checking configuration consistency 15.6. Exercises
  4. Code Optimizations and the Frontend/backend Structure 16.1. General considerations 16.2. Simple optimizations 16.3. Avoiding repeated evaluations 16.4. Register allocation 16.5. The frontend/backend compiler structure 16.6. Exercises

Appendix A: Syntax A.1. Oberon- A.2. Oberon A.3. Symbol files

Appendix B: The ASCII character set

Appendix C: The Oberon-0 compiler C.1. The scanner C.2. The parser C.3. The code generator

References

Figure 1.1. Multipass compilation.

Modern computers with their apparently unlimited stores make it feasible to avoid intermediate storage on disk. And with it, the complicated process of serializing a data structure for output, and its reconstruction on input can be discarded as well. With single-pass compilers , increases in speed by factors of several thousands are therefore possible. Instead of being tackled one after another in strictly sequential fashion, the various parts (tasks) are interleaved. For example, code generation is not delayed until all preparatory tasks are completed, but it starts already after the recognition of the first sentential structure of the source text.

A wise compromise exists in the form of a compiler with two parts, namely a front end and a back end. The first part comprises lexical and syntax analyses and type checking, and it generates a tree representing the syntactic structure of the source text. This tree is held in main store and constitutes the interface to the second part which handles code generation. The main advantage of this solution lies in the independence of the front end of the target computer and its instruction set. This advantage is inestimable if compilers for the same language and for various computers must be constructed, because the same front end serves them all.

The idea of decoupling source language and target architecture has also led to projects creating several front ends for different languages generating trees for a single back end. Whereas for the implementation of m languages for n computers m * n compilers had been necessary, now m front ends and n back ends suffice (Figure 1.2).

Figure 1.2. Front ends and back ends.

This modern solution to the problem of porting a compiler reminds us of the technique which played a significant role in the propagation of Pascal around 1975 (Wirth, 1971). The role of the structural tree was assumed by a linearized form, a sequence of commands of an abstract computer. The back end consisted of an interpreter program which was implementable with little effort, and the linear instruction sequence was called P-code. The drawback of this solution was the inherent loss of efficiency common to interpreters.

Frequently, one encounters compilers which do not directly generate binary code, but rather assembler text. For a complete translation an assembler is also involved after the compiler. Hence, longer translation times are inevitable. Since this scheme hardly offers any advantages, we do not recommend this approach.

Pascal Modula Oberon

MIPS SPARC ARM

Syntax tree

lexical analysis

syntax analysis

code generation

Increasingly, high-level languages are also employed for the programming of microcontrollers used in embedded applications. Such systems are primarily used for data acquisition and automatic control of machinery. In these cases, the store is typically small and is insufficient to carry a compiler. Instead, software is generated with the aid of other computers capable of compiling. A compiler which generates code for a computer different from the one executing the compiler is called a cross compiler. The generated code is then transferred - downloaded - via a data transmission line.

In the following chapters we shall concentrate on the theoretical foundations of compiler design, and thereafter on the development of an actual single-pass compiler.

Figure 2.1. Structure of expressions

Let us now formulate the concepts presented above more rigorously:

A language is defined by the following:

  1. The set of terminal symbols. These are the symbols that occur in its sentences. They are said to be terminal, because they cannot be substituted by any other symbols. The substitution process stops with terminal symbols. In our first example this set consists of the elements a, b, c and d. The set is also called vocabulary.
  2. The set of nonterminal symbols. They denote syntactic classes and can be substituted. In our first example this set consists of the elements S, A and B.
  3. The set of syntactic equations (also called productions ). These define the possible substitutions of nonterminal symbols. An equation is specified for each nonterminal symbol.
  4. The start symbol. It is a nonterminal symbol, in the examples above denoted by S.

A language is, therefore, the set of sequences of terminal symbols which, starting with the start symbol, can be generated by repeated application of syntactic equations, that is, substitutions.

We also wish to define rigorously and precisely the notation in which syntactic equations are specified. Let nonterminal symbols be identifiers as we know them from programming languages, that is, as sequences of letters (and possibly digits), for example, expression, term. Let terminal symbols be character sequences enclosed in quotes (strings), for example, "=", "|". For the definition of the structure of these equations it is convenient to use the tool just being defined itself:

syntax = production syntax | ∅. production = identifier "=" expression ".". expression = term | expression "|" term. term = factor | term factor. factor = identifier | string. identifier = letter | identifier letter | identifier digit. string = stringhead """. stringhead = """ | stringhead character.

a * b + c a + b * c (a+b)*(c+d)

A

a b

c

A

b c

a

A
( A ) ( A )

a b

c d

letter = "A" | ... | "Z". digit = "0" | ... | "9".

This notation was introduced in 1960 by J. Backus and P. Naur in almost identical form for the formal description of the syntax of the language Algol 60. It is therefore called Backus Naur Form (BNF) (Naur, 1960). As our example shows, using recursion to express simple repetitions is rather detrimental to readability. Therefore, we extend this notation by two constructs to express repetition and optionality. Furthermore, we allow expressions to be enclosed within parentheses. Thereby an extension of BNF called EBNF (Wirth, 1977) is postulated, which again we immediately use for its own, precise definition:

syntax = {production}. production = identifier "=" expression ".". expression = term {"|" term}. term = factor {factor}. factor = identifier | string | "(" expression ")" | "[" expression "]" | "{" expression "}". identifier = letter {letter | digit}. string = """ {character} """. letter = "A" | ... | "Z". digit = "0" | ... | "9".

A factor of the form {x} is equivalent to an arbitrarily long sequence of x, including the empty sequence. A production of the form

A = AB | ∅.

is now formulated more briefly as A = {B}. A factor of the form [x] is equivalent to "x or nothing", that is, it expresses optionality. Hence, the need for the special symbol ∅ for the empty sequence vanishes.

The idea of defining languages and their grammar with mathematical precision goes back to N. Chomsky. It became clear, however, that the presented, simple scheme of substitution rules was insufficient to represent the complexity of spoken languages. This remained true even after the formalisms were considerably expanded. In contrast, this work proved extremely fruitful for the theory of programming languages and mathematical formalisms. With it, Algol 60 became the first programming language to be defined formally and precisely. In passing, we emphasize that this rigour applied to the syntax only, not to the semantics.

The use of the Chomsky formalism is also responsible for the term programming language , because programming languages seemed to exhibit a structure similar to spoken languages. We believe that this term is rather unfortunate on the whole, because a programming language is not spoken, and therefore is not a language in the true sense of the word. Formalism or formal notation would have been more appropriate terms.

One wonders why an exact definition of the sentences belonging to a language should be of any great importance. In fact, it is not really. However, it is important to know whether or not a sentence is well formed. But even here one may ask for a justification. Ultimately, the structure of a (well formed) sentence is relevant, because it is instrumental in establishing the sentence's meaning. Owing to the syntactic structure, the individual parts of the sentence and their meaning can be recognized independently, and together they yield the meaning of the whole.

Let us illustrate this point using the following, trivial example of an expression with the addition symbol. Let E stand for expression, and N for number:

E = N | E "+" E. N = "1" | "2" | "3" | "4".

Evidently, "4 + 2 + 1" is a well-formed expression. It may even be derived in several ways, each corresponding to a different structure, as shown in Figure 2.2.

-x ÷ y a + b < c + d a + b < c ∨ d ≠ e ∧ ¬ f ⊃ g > h ≡ i × j = k ↑ l ∨ m - n + p ≤ q

2.2. The following productions also are part of the original definition of Algol 60. They contain ambiguities which were eliminated in the Revised Report.

forListElement = arithmeticExpression | arithmeticExpression "STEP" arithmeticExpression "UNTIL" arithmeticExpression | arithmeticExpression "WHILE" BooleanExpression. forList = forListElement | forList "," forListElement. forClause = "FOR" variable ":=" forList "DO". forStatement = forClause statement. compoundTail = statement "END" | statement ";" compoundTail. compoundStatement = "BEGIN" compoundTail. unconditional Statement = basicStatement | forStatement | compoundStatement | .... ifStatement = "IF" BooleanExpression "THEN" unconditionalStatement. conditionalStatement = ifStatement | ifStatement "ELSE" statement. statement = unconditionalStatement | conditionalStatement.

Find at least two different structures for the following expressions and statements. Let A and B stand for "basic statements".

IF a THEN b ELSE c = d IF a THEN IF b THEN A ELSE B IF a THEN FOR ... DO IF b THEN A ELSE B

Propose an alternative syntax which is unambiguous.

2.3. Consider the following constructs and find out which ones are correct in Algol, and which ones in Oberon (see Appendix A.2):

a + b = c + d a * -b a < b & c < d

Evaluate the following expressions:

5 * 13 DIV 4 = 13 DIV 5*4 =

3. Regular Languages

Syntactic equations of the form defined in EBNF generate context-free languages. The term "context- free" is due to Chomsky and stems from the fact that substitution of the symbol left of = by a sequence derived from the expression to the right of = is always permitted, regardless of the context in which the symbol is embedded within the sentence. It has turned out that this restriction to context freedom (in the sense of Chomsky) is quite acceptable for programming languages, and that it is even desirable. Context dependence in another sense, however, is indispensible. We will return to this topic in Chapter 8.

Here we wish to investigate a subclass rather than a generalization of context-free languages. This subclass, known as regular languages, plays a significant role in the realm of programming languages. In essence, they are the context-free languages whose syntax contains no recursion except for the specification of repetition. Since in EBNF repetition is specified directly and without the use of recursion, the following, simple definition can be given:

A language is regular , if its syntax can be expressed by a single EBNF expression.

The requirement that a single equation suffices also implies that only terminal symbols occur in the expression. Such an expression is called a regular expression.

Two brief examples of regular languages may suffice. The first defines identifiers as they are common in most languages; and the second defines integers in decimal notation. We use the nonterminal symbols letter and digit for the sake of brevity. They can be eliminated by substitution, whereby a regular expression results for both identifier and integer.

identifier = letter {letter | digit}. integer = digit {digit}. letter = "A" | "B" | ... | "Z". digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9".

The reason for our interest in regular languages lies in the fact that programs for the recognition of regular sentences are particularly simple and efficient. By "recognition" we mean the determination of the structure of the sentence, and thereby naturally the determination of whether the sentence is well formed, that is, it belongs to the language. Sentence recognition is called syntax analysis.

For the recognition of regular sentences a finite automaton, also called a state machine , is necessary and sufficient. In each step the state machine reads the next symbol and changes state. The resulting state is solely determined by the previous state and the symbol read. If the resulting state is unique, the state machine is deterministic, otherwise nondeterministic. If the state machine is formulated as a program, the state is represented by the current point of program execution.

The analysing program can be derived directly from the defining syntax in EBNF. For each EBNF construct K there exists a translation rule which yields a program fragment Pr(K). The translation rules from EBNF to program text are shown below. Therein sym denotes a global variable always representing the symbol last read from the source text by a call to procedure next. Procedure error terminates program execution, signalling that the symbol sequence read so far does not belong to the language.

K Pr(K) "x" IF sym = "x" THEN next ELSE error END (exp) Pr(exp) [exp] IF sym IN first(exp) THEN Pr(exp) END {exp} WHILE sym IN first(exp) DO Pr(exp) END fac0 fac1 ... facn Pr(fac0); Pr(fac1); ... Pr(facn term0 | term1 | ... | termn CASE sym OF first(term0): Pr(term0) | first(term1): Pr(term1) ...

As an example we show a scanner for a parser of EBNF. Its terminal symbols and their definition in terms of characters are

symbol = {blank} (identifier | string | "(" | ")" | "[" | "]" | "{" | "}" | "|" | "=" | "."). identifier = letter {letter | digit}. string = """ {character} """.

From this we derive the procedure GetSym which, upon each call, assigns a numeric value representing the next symbol read to the global variable sym. If the symbol is an identifier or a string, the actual character sequence is assigned to the further global variable id. It must be noted that typically a scanner also takes into account rules about blanks and ends of lines. Mostly these rules say: blanks and ends of lines separate consecutive symbols, but otherwise are of no significance. Procedure GetSym , formulated in Oberon, makes use of the following declarations.

CONST IdLen = 32; ident = 0; literal = 2; lparen = 3; lbrak = 4; lbrace = 5; bar = 6; eql = 7; rparen = 8; rbrak = 9; rbrace = 10; period = 11; other = 12; TYPE Identifier = ARRAY IdLen OF CHAR; VAR ch: CHAR; sym: INTEGER; id: Identifier; R: Texts.Reader;

Note that the abstract reading operation is now represented by the concrete call Texts.Read(R, ch). R is a globally declared Reader specifying the source text. Also note that variable ch must be global, because at the end of GetSym it may contain the first character belonging to the next symbol. This must be taken into account upon the subsequent call of GetSym.

PROCEDURE GetSym; VAR i: INTEGER; BEGIN WHILE ~R.eot & (ch <= " ") DO Texts.Read(R, ch) END ; (skip blanks) CASE ch OF "A" .. "Z", "a" .. "z": sym := ident; i := 0; REPEAT id[i] := ch; INC(i); Texts.Read(R, ch) UNTIL (CAP(ch) < "A") OR (CAP(ch) > "Z"); id[i] := 0X | 22X: (quote) Texts.Read(R, ch); sym := literal; i := 0; WHILE (ch # 22X) & (ch > " ") DO id[i] := ch; INC(i); Texts.Read(R, ch) END ; IF ch <= " " THEN error(1) END ; id[i] := 0X; Texts.Read(R, ch) | "=" : sym := eql; Texts.Read(R, ch) | "(" : sym := lparen; Texts.Read(R, ch) | ")" : sym := rparen; Texts.Read(R, ch) | "[" : sym := lbrak; Texts.Read(R, ch) | "]" : sym := rbrak; Texts.Read(R, ch) | "{" : sym := lbrace; Texts.Read(R, ch) | "}" : sym := rbrace; Texts.Read(R, ch) | "|" : sym := bar; Texts.Read(R, ch) | "." : sym := period; Texts.Read(R, ch) ELSE sym := other; Texts.Read(R, ch) END END GetSym

3.1. Exercise

Sentences of regular languages can be recognized by finite state machines. They are usually described by transistion diagrams. Each node represents a state, and each edge a state transition. The edge is labelled by the symbol that is read by the transition. Consider the following diagrams and describe the syntax of the corresponding languages in EBNF.

a (^ x^ )

o

a +

b

. c *

we recognize that the requirement is violated, simply because b is a start symbol of A (b IN first(A)), and because therefore first(A"a") and first("b") are not disjoint. "b" is the common element.

The simple consequence is: left recursion can and must be replaced by repetition. In the example above A = A "a" | "b" is replaced by A = "b" {"a"}.

Another way to look at our step from the state machine to its generalization is to regard the latter as a set of state machines which call upon each other and upon themselves. In principle, the only new condition is that the state of the calling machine is resumed after termination of the called state machine. The state must therefore be preserved. Since state machines are nested, a stack is the appropriate form of store. Our extension of the state machine is therefore called a pushdown automaton. Theoretically relevant is the fact that the stack (pushdown store) must be arbitrarily deep. This is the essential difference between the finite state machine and the infinite pushdown automaton.

The general principle which is suggested here is the following: consider the recognition of the sentential construct which begins with the start symbol of the underlying syntax as the uppermost goal. If during the pursuit of this goal, that is, while the production is being parsed, a nonterminal symbol is encountered, then the recognition of a construct corresponding to this symbol is considered as a subordinate goal to be pursued first, while the higher goal is temporarily suspended. This strategy is therefore also called goal-oriented parsing. If we look at the structural tree of the parsed sentence we recognize that goals (symbols) higher in the tree are tackled first, lower goals (symbols) thereafter. The method is therefore called top-down parsing (Knuth, 1971; Aho and Ullman, 1977). Moreover, the presented implementation of this strategy based on recursive procedures is known as recursive descent parsing.

Finally, we recall that decisions about the steps to be taken are always made on the basis of the single, next input symbol only. The parser looks ahead by one symbol. A lookahead of several symbols would complicate the decision process considerably, and thereby also slow it down. For this reason we will restrict our attention to languages which can be parsed with a lookahead of a single symbol.

As a further example to demonstrate the technique of recursive descent parsing, let us consider a parser for EBNF, whose syntax is summarized here once again:

syntax = {production}. production = identifier "=" expression ".". expression = term {"|" term}. term = factor {factor}. factor = identifier | string | "(" expression ")" | "[" expression "]" | "{" expression "}".

By application of the given translation rules and subsequent simplification the following parser results. It is formulated as an Oberon module:

MODULE EBNF; IMPORT Viewers, Texts, TextFrames, Oberon; CONST IdLen = 32; ident = 0; literal = 2; lparen = 3; lbrak = 4; lbrace = 5; bar = 6; eql = 7; rparen = 8; rbrak = 9; rbrace = 10; period = 11; other = 12; TYPE Identifier = ARRAY IdLen OF CHAR; VAR ch: CHAR; sym: INTEGER; lastpos: LONGINT; id: Identifier; R: Texts.Reader; W: Texts.Writer; PROCEDURE error(n: INTEGER); VAR pos: LONGINT; BEGIN pos := Texts.Pos(R); IF pos > lastpos+4 THEN (avoid spurious error messages)

Texts.WriteString(W, " pos"); Texts.WriteInt(W, pos, 6); Texts.WriteString(W, " err"); Texts.WriteInt(W, n, 4); lastpos := pos; Texts.WriteString(W, " sym "); Texts.WriteInt(W, sym, 4); Texts.WriteLn(W); Texts.Append(Oberon.Log, W.buf) END END error; PROCEDURE GetSym; BEGIN ... (see Chapter 3) END GetSym; PROCEDURE expression; PROCEDURE term; PROCEDURE factor; BEGIN IF sym = ident THEN record(T0, id, 1); GetSym ELSIF sym = literal THEN record(T1, id, 0); GetSym ELSIF sym = lparen THEN GetSym; expression; IF sym = rparen THEN GetSym ELSE error(2) END ELSIF sym = lbrak THEN GetSym; expression; IF sym = rbrak THEN GetSym ELSE error(3) END ELSIF sym = lbrace THEN GetSym; expression; IF sym = rbrace THEN GetSym ELSE error(4) END ELSE error(5) END END factor; BEGIN (term) factor; WHILE sym < bar DO factor END END term; BEGIN (expression) term; WHILE sym = bar DO GetSym; term END END expression; PROCEDURE production; BEGIN (sym = ident) GetSym; IF sym = eql THEN GetSym ELSE error(7) END ; expression; IF sym = period THEN GetSym ELSE error(8) END END production; PROCEDURE syntax; BEGIN WHILE sym = ident DO production END END syntax; PROCEDURE Compile ; BEGIN (set R to the beginning of the text to be compiled*) lastpos := 0; Texts.Read(R, ch); GetSym; syntax; Texts.Append(Oberon.Log, W.buf) END Compile;

BEGIN Texts.OpenWriter(W) END EBNF.