Docsity

Programming Language Processors in Java, Manuais, Projetos, Pesquisas de Engenharia Informática

Toggle sidebar
bg1
Programming Language
Processors in Java
COMPILERS AND INTERPRETERS
DAVID
A
WATT
University of Glasgow, Scotland
and
DERYCK
F
BROWN
The
Robert Gordon University, Scotland
An
imprint
of
Pearson
Education
Harlow, England
.
London
.
New York
.
Reading, Massachusetts
.
San Francisco
.
Toronto
.
Don Mills, Ontario
.
Sydney
Tokyo
.
Singapore
.
Hong Kong
.
Seoul
.
Taipei
.
Cape Town
.
Madrid
.
Mexico City
.
Amsterdam
.
Munich
.
Paris
.
Milan
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe Programming Language Processors in Java e outras Manuais, Projetos, Pesquisas em PDF para Engenharia Informática, somente na Docsity!

Programming Language

Processors in Java

COMPILERS AND INTERPRETERS

DAVID A WATT

University of Glasgow, Scotland
and
DERYCK F BROWN
The Robert Gordon University, Scotland

An imprint of Pearson Education Harlow, England. London. New York. Reading, Massachusetts. San Francisco. Toronto. Don Mills, Ontario. Sydney Tokyo. Singapore. Hong Kong. Seoul. Taipei. Cape Town. Madrid. Mexico City. Amsterdam. Munich. Paris. Milan

Pearson Education Limited Edinburgh Gate Harlow Essex, CM20 2JE England

and Associated Companies throughout the world

Visit us on the World Wide Web at: http://www.pearsoneduc.com

First published 2000

0 Pearson Education Limited 2000

The rights of David A Watt and Deryck F Brown to be identified as authors of this Work have been asserted by them in accordance with the Copyright, Designs and Patents Act 1988.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either the prior written permission of the Publishers or a licence permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd., 90 Tottenham Court Road London W l P OLP.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Pearson Education Limited has made every attempt to supply trademark information about manufacturers and their products mentioned in this book. A list of the trademark designations and their owners appears on page x.

ISBN 0 130 25786 9

British Library Cataloguing in Publication Data A catalogue record for this book is available from the British Library.

Library of'Congrrss Cutaloging-in-Publication Data Watt, David A. (David Anthony) Programming language processors in Java : compilers and interpreters / David A. Watt and Deryck F. Brown p. cm. Includes bibliographical references. ISBN 0-1 3425786-9 (case)

  1. Java (Computer program language) 2. Compilers (Computer programs) 3. Interpreters (Computer programs) 1. Brown, Deryck F. 11. Title.

Typeset by 7 Printed an bound in Great Britain by Biddles Ltd, www.biddles.co.uk

vi Programming Language Processors in Java

3.2.1 Multi-pass compilation 3.2.2 One-pass compilation 3.2.3 Compiler design issues 3.3 Case study: the Triangle compiler 3.4 Further reading Exercises

4 Syntactic Analysis

4.1 Subphases of syntactic analysis 4.1.1 Tokens 4.2 Grammars revisited 4.2.1 Regular expressions 4.2.2 Extended BNF 4.2.3 Grammar transformations 4.2.4 Starter sets 4.3 Parsing 4.3.1 The bottom-up parsing strategy 4.3.2 The top-down parsing strategy 4.3.3 Recursive-descent parsing 4.3.4 Systematic development of a recursive-descent parser 4.4 Abstract syntax trees 4.4.1 Representation 4.4.2 Construction 4.5 Scanning 4.6 Case study: syntactic analysis in the Triangle compiler 4.6.1 Scanning 4.6.2 Abstract syntax trees 4.6.3 Parsing 4.6.4 Error handling 4.7 Further reading Exercises

5 Contextual Analysis
5.1 Identification

5.1.1 Monolithic block structure 5.1.2 Flat block structure 5.1.3 Nested block structure 5.1.4 Attributes 5.1.5 Standard environment 5.2 Typechecking 5.3 A contextual analysis algorithm 5.3.1 Decoration 5.3.2 Visitor classes and objects 5.3.3 Contextual analysis as a visitor object 5.4 Case study: contextual analysis in the Triangle compiler

Contents vii

5.4.1 Identification 5.4.2 Type checking 5.4.3 Standard environment 5.5 Further reading Exercises

6 Run-Time Organization

6.1 Data representation 6.1.1 Primitive types 6.1.2 Records 6.1.3 Disjoint unions 6.1.4 Static arrays 6.1.5 Dynamic arrays 6.1.6 Recursive types 6.2 Expression evaluation 6.3 Static storage allocation 6.4 Stack storage allocation 6.4.1 Accessing local and global variables 6.4.2 Accessing nonlocal variables 6.5 Routines 6.5.1 Routine protocols 6.5.2 Static links 6.5.3 Arguments 6.5.4 Recursion 6.6 Heap storage allocation 6.6.1 Heap management 6.6.2 Explicit storage deallocation 6.6.3 Automatic storage deallocation and garbage collection 6.7 Run-time organization for object-oriented languages 6.8 Case study: the abstract machine TAM 6.9 Further reading Exercises

7 Code Generation 7.1 Code selection 7.1.1 Code templates 7.1.2 Special-case code templates 7.2 A code generation algorithm 7.2.1 Representation of the object program 7.2.2 Systematic development of a code generator 7.2.3 Control structures 7.3 Constants and variables 7.3.1 Constant and variable declarations 7.3.2 Static storage allocation 7.3.3 Stack storage allocation

Contents ix

Answers 7
Answers 8
Answers 9
B Informal Specification^ of the Programming Language Triangle

B. 1 Introduction B.2 Commands B.3 Expressions B.4 Value-or-variable names B.5 Declarations B.6 Parameters B.7 Type-denoters B.8 Lexicon B.9 Programs

C Description of the Abstract Machine^ TAM

C. 1 Storage and registers C.2 Instructions C.3 Routines

D Class Diagrams for the Triangle Compiler

D.l Compiler D.2 Abstract syntax trees D.2.1 Commands D.2.2 Expressions D.2.3 Value-or-variable names D.2.4 Declarations D.2.5 Parameters D.2.6 Type-denoters D.2.7 Terminals D.3 Syntactic analyzer D.4 Contextual analyzer

D.5 Code generator
Bibliography

xii Programming Language Processors in Java

and reusability. Secondly, Java itself has experienced a prodigious growth in popularity since its appearance as recently as 1994, and that for good technical reasons: Java is simple, consistent, portable, and equipped with an extremely rich class library. Soon we can expect all computer science students to have at least some familiarity with Java.

A programming languages series

This is the fourth of a series of books on programming languages:

Programming Language Concepts and Paradigms Programming Language Syntax and Semantics Programming Language Processors Programming Language Processors in Java Programming Language Concepts and Paradigms studies the concepts underlying pro- gramming languages, and the major language paradigms that use these concepts in different ways; in other words, it is about language design. Programming Language Syntax and Semantics shows how we can formally specify the syntax (form) and seman- tics (meaning) of programming languages. Programming Language Processors studies the implementation of programming languages, examining language processors such as compilers and interpreters, and using Pascal as the implementation language. Program- ming Language Processors in Java likewise studies the implementation of programming languages, but now using Java as the implementation language and object-oriented design as the engineering principle; moreover, it introduces basic techniques for imple- menting object-oriented languages. This series attempts something that has not previously been achieved, as far as we know: a broad study of all aspects of programming languages, using consistent termi- nology, and emphasizing connections likely to be missed by books that deal with these aspects separately. For example, the concepts incorporated in a language must be defined precisely in the language's semantic specification. Conversely, a study of semantics helps us to discover and refine elegant and powerful new concepts, which can be incorporated in future language designs. A language's syntax underlies analysis of source programs by language processors; its semantics underlies object code generation and interpretation. Implementation is an important consideration for the language designer, since a language that cannot be implemented with acceptable efficiency will not be used. The books may be read as a series, but each book is sufficiently self-contained to be read on its own, if the reader prefers.

Content of this book

Chapter 1 introduces the topic of the book. It reviews the concepts of high-level pro- gramming languages, and their syntax, contextual constraints, and semantics. It explains what a language processor is, with examples from well-known programming systems.

Preface xiii

Chapter 2 introduces the basic terminology of language processors: translators, compilers, interpreters, source and target languages, and real and abstract machines. It goes on to study interesting ways of using language processors: interpretive compilers, portable compilers, and bootstrapping. In this chapter we view language processors as 'black boxes'. In the following chapters we look inside these black boxes. Chapter 3 looks inside compilers. It shows how compilation can be decomposed into three principal phases: syntactic analysis, contextual analysis, and code generation. It also compares different ways of designing compilers, leading to one-pass and multi- pass compilation.

Chapter 4 studies syntactic analysis in detail. It decomposes syntactic analysis into scanning, parsing, and abstract syntax tree construction. It introduces recursive-descent parsing, and shows how a parser and scanner can be systematically constructed from the source language's syntactic specification.

Chapter 5 studies contextual analysis in detail, assuming that the source language exhibits static bindings and is statically typed. The main topics are identification, which is related to the language's scope rules, and type checking, which is related to the lan- guage's type rules.

Chapter 6 prepares for code generation by discussing the relationship between the source language and the target machine. It shows how target machine instructions and storage must be marshaled to support the higher-level concepts of the source language. The topics covered include data representation, expression evaluation, storage allocation, routines and their arguments, garbage collection, and the run-time organization of simple object-oriented languages.

Chapter 7 studies code generation in detail. It shows how to organize the translation from source language to object code. It relates the selection of object code to the seman- tics of the source language. As this is an introductory textbook, only code generation for a stack-based target machine is covered. (The more difficult topics of code generation for a register-based machine, and code transformations are left to more advanced textbooks.)

Chapter 8 looks inside interpreters. It gives examples of interpreters for both low- level and high-level languages.

Chapter 9 concludes the book. It places the implementation of a programming lan- guage in the context of the language's life cycle, along with design and specification. It also discusses quality issues, namely error reporting and efficiency.

There are several possible orders for studying the main topics of this book. The chapter on interpretation can be read independently of the chapters on compilation. Within the latter, the chapters on syntactic analysis, contextual analysis, and code gen- eration can be read in any order. The following diagram summarizes the dependencies between chapters.

Preface xv

Although Triangle is a model language, it is rich enough to write interesting programs and to illustrate basic methods of specification and implementation. Finally, it can readily be extended in various ways (such as adding new types, new control structures, or packages), and such extensions are a basis for a variety of projects.

Educational software

A Triangle language processor is available for educational use in conjunction with this textbook. The Triangle language processor consists of: a compiler for Triangle, which generates code for TAM (Triangle Abstract Machine); an interpreter for TAM; and a disassembler for TAM. The tools are written entirely in Java, and will run on any computer equipped with a JVM (Java Virtual Machine). You can download the Triangle language processor from our Web site:

Exercises and projects

Each chapter of this book is followed by a number of relevant exercises. These vary from short exercises, through longer ones (marked *), up to truly demanding ones (marked **) that could be treated as projects. A typical exercise is to apply the methods of the chapter to a very small toy language, or a minor extension of Triangle. A typical project is to implement some substantial extension to Triangle. Most of the projects are gathered together at the end of Chapter 9; they require modifications to several parts of the Triangle compiler, and should be undertaken only after reading up to Chapter 7 at least.

Readership

This book and its companions are aimed at junior, senior, and graduate students of com- puter science and information technology, all of whom need some understanding of the fundamentals of programming languages. The books should also be of interest to profes- sional software engineers, especially project leaders responsible for language evaluation and selection, designers and implementors of language processors, and designers of new languages and extensions to existing languages. The basic prerequisites for this textbook are courses in programming and data struc- tures, and a course in programming languages that covers at least basic language con- cepts and syntax. The reader should be familiar with Java, and preferably at least one other high-level language, since in studying implementation of programming languages it is important not to be unduly influenced by the idiosyncrasies of a particular language. All the algorithms in this textbook are expressed in Java. The ability to read a programming language specification critically is an essential skill. A programming language implementor is forced to explore the entire language, including its darker corners. (The ordinary programmer is wise to avoid these dark

xvi Programming Language Processors in Java

corners!) The reader of this textbook will need a good knowledge of syntax, and ideally some knowledge of semantics; these topics are briefly reviewed in Chapter 1 for the benefit of readers who might lack such knowledge. Familiarity with BNF and EBNF (which are commonly used in language specifications) is essential, because in Chapter 4 we show how to exploit them in syntactic analysis. No knowledge of formal semantics is assumed.

The reader should be comfortable with some elementary concepts from discrete mathematics - sets and recursive functions - as these help to sharpen understanding of, for example, parsing algorithms. Discrete mathematics is essential for a deeper under- standing of compiler theory; however, only a minimum of compiler theory is presented in this book.

This book and its companions attempt to cover all the most important aspects of a large subject. Where necessary, depth has been sacrificed for breadth. Thus the really serious student will need to follow up with more advanced studies. Each book has an extensive bibliography, and each chapter closes with pointers to further reading on the topics covered by the chapter.

Acknowledgments

Most of the methods described in this textbook have long since passed into compiler folklore, and are almost impossible to attribute to individuals. Instead, we shall mention people who have particularly influenced us personally.

For providing a stimulating environment in which to think about programming lan- guage issues, we are grateful to colleagues in the Department of Computing Science at the University of Glasgow, in particular Malcolm Atkinson, Muffy Calder, Quintin Cutts, Peter Dickman, Bill Findlay, John Hughes, John Launchbury, Hermano Moura, John Patterson, Simon Peyton Jones, Fermin Reig, Phil Trinder, and Phil Wadler. We have also been strongly influenced, in many different ways, by the work of Peter Buneman, Luca Cardelli, Edsger Dijkstra, Jim Gosling, Susan Graham, Tony Hoare, Jean Ichbiah, Mehdi Jazayeri, Robin Milner, Peter Mosses, Atsushi Ohori, Bob Tennent, Jim Welsh, and Niklaus Wirth.

We wish to thank the reviewers for reading and providing valuable comments on an earlier draft of this book. Numerous cohorts of undergraduate students taking the Programming Languages 3 module at the University of Glasgow made an involuntary but essential contribution by class-testing the Triangle language processor, as have three cohorts of students taking the Compilers module at the Robert Gordon University.

We are particularly grateful to Tony Hoare, editor of the Prentice Hall International Series in Computer Science, for his encouragement and advice, freely and generously offered when these books were still at the planning stage. If this book is more than just another compiler textbook, that is partly due to his suggestion to emphasize the connec- tions between compilation, interpretation, and semantics. Glasgow and Aberdeen July, 1999

D.A.W. D.F.B.

2 Programming Language Processors in Java

Once written, a program could simply be loaded into the machine and run. Clearly, machine-code programs are extremely difficult to read, write, and edit. The programmer must keep track of the exact address of each item of data and each instruc- tion in storage, and must encode every single instruction as a bit string. For small pro- grams (consisting of thousands of instructions) this task is onerous; for larger programs the task is practically infeasible. Programmers soon began to invent symbolic notations to make programs easier to read, write, and edit. The above instructions might be written, respectively, as follows:

LOAD x

ADD R1 R

JUMPZ h

where LOAD,ADD,and JUMPZ are symbolic names for operations, R1 and R2 are sym- bolic names for registers, x is a symbolic name for the address of a particular item of data, and h is a symbolic name for the address of a particular instruction. Having written a program like this on paper, the programmer would prepare it to be run by manually translating each instruction into machine code. This process was called assembling the program. The obvious next step was to make the machine itself assemble the program. For this process to work, it is necessary to standardize the symbolic names for operations and registers. (However, the programmer should still be free to choose symbolic names for data and instruction addresses.) Thus the symbolic notation is formalized, and can now be termed an assembly language. Even when writing programs in an assembly language, the programmer is still work- ing in terms of the machine's instruction set. A program consists of a large number of very primitive instructions. The instructions must be written individually, and put to- gether in the correct sequence. The algorithm in the mind of the programmer tends to be swamped by details of registers, jumps, and so on. To take a very simple example, con- sider computing the area of a triangle with sides a, b, and c, using the formula: d(s x (S- a) x (s - b) x (s - c))

where s = (a + b + c) I 2

Written in assembly language, the program must be expressed in terms of individual arithmetic operations, and in terms of the registers that contain intermediate results:

LOAD R1 a; ADD R1 b; ADD R1 c; DIV R1 # 2 ;

LOAD R2 R1; LOAD R3 R1; SUB R3 a; MULT R2 R3; LOAD R3 R1; SUB R3 b; MULT R2 R3;

Introduction 3

LOAD R3 R1; SUB R3 c; MULT R2 ~ 3 ; LOAD RO R2; CALL sqrt

Programming is made very much easier if we can use notation similar to the familiar mathematical notation:

let s = (a+b+c) / 2

in sqrt (s(s-a) (s-b)* (s-c))

Today the vast majority of programs are written in programming languages of this

kind. These are called high-level languages, by contrast with machine languages and
assembly languages, which are low-level languages. Low-level languages are so called

because they force algorithms to be expressed in terms of primitive instructions, of the kind that can be performed directly by electronic hardware. High-level languages are so called because they allow algorithms to be expressed in terms that are closer to the way in which we conceptualize these algorithms in our heads. The following are typical of concepts that are supported by high-level languages, but are supported only in a rudi- mentary form or not at all by low-level languages:

Expressions: An expression is a rule for computing a value. The high-level language programmer can write expressions similar to ordinary mathematical notation, using

operators such as '+', '-', '*', and '/'.

Data types: Programs manipulate data of many types: primitive types such as truth values, characters, and integers, and composite types such as records and arrays. The high-level language programmer can explicitly define such types, and declare con- stants, variables, functions, and parameters of these types. Control structures: Control structures allow the high-level language programmer to program selective computation ( e g , by if- and case-commands) and iterative compu- tation (e.g., by while- and for-commands). Declarations: Declarations allow the high-level language programmer to introduce identifiers to denote entities such as constant values, variables, procedures, functions, and types. Abstraction: An essential mental tool of the programmer is abstraction, or separation of concerns: separating the notion of what computation is to be performed from the details of how it is to be performed. The programmer can emphasize this separation by use of named procedures and functions. Moreover, these can be parameterized with respect to the entities on which they operate. Encapsulation (or data abstraction): Packages and classes allow the programmer to group together related declarations, and selectively to hide some of them. A particu- larly important usage of this concept is to group hidden variables together with oper- ations on these variables, which is the essence of object-oriented programming.

Section 1.5 suggests further reading on the concepts of high-level programming lan-

guages.

Introduction 5

If the program fails to compile, or misbehaves when run, the user reinvokes the editor to modify the program; then reinvokes the compiler; and so on. Thus program development is an edit-compile-run cycle. There is no direct communication between these language processors. If the program fails to compile, the compiler will generate one or more error reports, each indicating the position of the error. The user must note these error reports, and on reinvoking the editor must find the errors and correct them. This is very inconvenient, especially in the early stages of program development when errors might be numerous.

The essence of the 'software tools' philosophy is to provide a small number of com- mon and simple tools, which can be used in various combinations to perform a large variety of tasks. Thus only a single editor need be provided, one that can be used to edit programs in a variety of languages, and indeed other textual documents too. What we have described is the 'software tools' philosophy in its purest form. In practice, the philosophy is compromised in order to make program development easier. The editor might have a facility that allows the user to compile the program (or indeed issue any system command) without leaving the editor. Some compilers go further: if the program fails to compile, the editor is automatically reinvoked and positioned at the first error. These are ad hoc solutions. A fresh approach seems preferable: a fully integrated language processor, designed specifically to support the edit-compile-run cycle.

Example 1.2 Integrated language processor

Borland JBuilder is a fully integrated language processor for Java, consisting of an editor, a compiler, and other facilities. The user issues commands to open, edit, compile, and run the program. These commands may be selected from pull-down menus, or from the keyboard. The editor is tailored to Java. It assists with the program layout using indentation, and it distinguishes between Java keywords, literals and comments using color. The editor is also fully integrated with the visual interface construction facilities of JBuilder. The compiler is integrated with the editor. When the user issues the 'compile' com- mand, and the program is found to contain a compile-time error, the erroneous phrase is highlighted, ready for immediate editing. If the program contains several errors, then the compiler will list all of them, and the user can select a particular error message and have the relevant phrase highlighted. The object program is also integrated with the editor. If the program fails at run- time, the failing phrase is highlighted. (Of course, this phrase is not necessarily the one that contains the logical error. But it would be unreasonable to expect the language processor to debug the program automatically !)