Modern Compiler Implementation in Java 2Ed 2nd Edition Andrew W. Appel pdf download
Modern Compiler Implementation in Java 2Ed 2nd Edition Andrew W. Appel pdf download
https://ebookfinal.com/download/modern-compiler-implementation-
in-java-2ed-2nd-edition-andrew-w-appel/
https://ebookfinal.com/download/engineering-a-compiler-2nd-edition-
keith-cooper/
https://ebookfinal.com/download/pharmacogenetics-2ed-edition-weber-w/
https://ebookfinal.com/download/an-introduction-to-modern-
cosmology-2nd-ed-edition-andrew-liddle/
Learn Java for Web Development Modern Java Web Development
1st Edition Vishal Layka
https://ebookfinal.com/download/learn-java-for-web-development-modern-
java-web-development-1st-edition-vishal-layka/
https://ebookfinal.com/download/modern-construction-handbook-6th-
edition-andrew-watts/
https://ebookfinal.com/download/modern-political-ideologies-3rd-
edition-andrew-vincent/
https://ebookfinal.com/download/java-in-a-nutshell-2nd-ed-edition-
david-flanagan/
Modern Compiler Implementation in Java 2Ed 2nd
Edition Andrew W. Appel Digital Instant Download
Author(s): Andrew W. Appel
ISBN(s): 9780521820608, 052182060X
Edition: 2
File Details: PDF, 2.16 MB
Year: 2002
Language: english
This page intentionally left blank
Modern Compiler Implementation in Java
Second Edition
This textbook describes all phases of a compiler: lexical analysis, parsing, abstract syntax, semantic
actions, intermediate representations, instruction selection via tree matching, dataflow analysis, graph-
coloring register allocation, and runtime systems. It includes good coverage of current techniques in
code generation and register allocation, as well as the compilation of functional and object-oriented
languages, which is missing from most books. The most accepted and successful techniques are de-
scribed concisely, rather than as an exhaustive catalog of every possible variant. Detailed descriptions
of the interfaces between modules of a compiler are illustrated with actual Java classes.
The first part of the book, Fundamentals of Compilation, is suitable for a one-semester first course in
compiler design. The second part, Advanced Topics, which includes the compilation of object-oriented
and functional languages, garbage collection, loop optimization, SSA form, instruction scheduling, and
optimization for cache-memory hierarchies, can be used for a second-semester or graduate course.
This new edition has been rewritten extensively to include more discussion of Java and object-oriented
programming concepts, such as visitor patterns. A unique feature is the newly redesigned compiler
project in Java for a subset of Java itself. The project includes both front-end and back-end phases, so
that students can build a complete working compiler in one semester.
Andrew W. Appel is Professor of Computer Science at Princeton University. He has done research
and published papers on compilers, functional programming languages, runtime systems and garbage
collection, type systems, and computer security; he is also author of the book Compiling with Contin-
uations. He is a designer and founder of the Standard ML of New Jersey project. In 1998, Appel was
elected a Fellow of the Association for Computing Machinery for “significant research contributions
in the area of programming languages and compilers” and for his work as editor-in-chief (1993–97)
of the ACM Transactions on Programming Languages and Systems, the leading journal in the field of
compilers and programming languages.
Jens Palsberg is Associate Professor of Computer Science at Purdue University. His research inter-
ests are programming languages, compilers, software engineering, and information security. He has
authored more than 50 technical papers in these areas and a book with Michael Schwartzbach, Object-
oriented Type Systems. In 1998, he received the National Science Foundation Faculty Early Career
Development Award, and in 1999, the Purdue University Faculty Scholar award.
i
ii
Modern Compiler
Implementation
in Java
Second Edition
ANDREW W. APPEL
Princeton University
iii
The Pitt Building, Trumpington Street, Cambridge, United Kingdom
http://www.cambridge.org
Preface ix
1 Introduction 3
1.1 Modules and interfaces 4
1.2 Tools and software 5
1.3 Data structures for tree languages 7
2 Lexical Analysis 16
2.1 Lexical tokens 17
2.2 Regular expressions 18
2.3 Finite automata 21
2.4 Nondeterministic finite automata 24
2.5 Lexical-analyzer generators 30
3 Parsing 38
3.1 Context-free grammars 40
3.2 Predictive parsing 45
3.3 LR parsing 55
3.4 Using parser generators 68
3.5 Error recovery 76
4 Abstract Syntax 86
4.1 Semantic actions 86
4.2 Abstract parse trees 89
4.3 Visitors 93
v
CONTENTS
vi
CONTENTS
vii
CONTENTS
Bibliography 487
Index 495
viii
Preface
ix
PREFACE
Course sequence. The figure shows how the chapters depend on each other.
Lexical Abstract Semantic
2. 3. Parsing 4. 5.
Quarter
Analysis Syntax Analysis
Semester
6. 7. 8.
Records Intermediate Code and Traces
Instruction Putting it
1. Introduction 9. 12.
Selection All Together
Quarter
Liveness Register
10. 11.
Analysis Allocation
Static Single-
Dataflow Loop
17. 18. 19. Assignment
Analysis Optimizations
Form
Semester
Functional Polymorphic Pipelining,
15. 16. 20.
Languages Types Scheduling
• A one-semester course could cover all of Part I (Chapters 1–12), with students
implementing the project compiler (perhaps working in groups); in addition,
lectures could cover selected topics from Part II.
• An advanced or graduate course could cover Part II, as well as additional
topics from the current literature. Many of the Part II chapters can stand inde-
pendently from Part I, so that an advanced course could be taught to students
who have used a different book for their first course.
• In a two-quarter sequence, the first quarter could cover Chapters 1–8, and the
second quarter could cover Chapters 9–12 and some chapters from Part II.
x
PART ONE
Fundamentals of
Compilation
1
2
1
Introduction
This book describes techniques, data structures, and algorithms for translating
programming languages into executable code. A modern compiler is often or-
ganized into many phases, each operating on a different abstract “language.”
The chapters of this book follow the organization of a compiler, each covering
a successive phase.
To illustrate the issues in compiling real programming languages, we show
how to compile MiniJava, a simple but nontrivial subset of Java. Program-
ming exercises in each chapter call for the implementation of the correspond-
ing phase; a student who implements all the phases described in Part I of the
book will have a working compiler. MiniJava is easily extended to support
class extension or higher-order functions, and exercises in Part II show how
to do this. Other chapters in Part II cover advanced techniques in program
optimization. Appendix A describes the MiniJava language.
The interfaces between modules of the compiler are almost as important
as the algorithms inside the modules. To describe the interfaces concretely,
it is useful to write them down in a real programming language. This book
uses Java – a simple object-oriented language. Java is safe, in that programs
cannot circumvent the type system to violate abstractions; and it has garbage
collection, which greatly simplifies the management of dynamic storage al-
3
CHAPTER ONE. INTRODUCTION
Environ-
ments
Source Program
Abstract Syntax
Tables
Reductions
Translate
IR Trees
IR Trees
Tokens
Assem
Parsing Semantic Canon- Instruction
Lex Parse Actions Analysis Translate icalize Selection
Frame
Frame
Layout
Assembly Language
Interference Graph
Machine Language
Flow Graph
Assem
Control Data
Flow Flow Register Code Assembler Linker
Analysis Analysis Allocation Emission
location. Both of these properties are useful in writing compilers (and almost
any kind of software).
This is not a textbook on Java programming. Students using this book who
do not know Java already should pick it up as they go along, using a Java
programming book as a reference. Java is a small enough language, with
simple enough concepts, that this should not be difficult for students with
good programming skills in other languages.
4
1.2. TOOLS AND SOFTWARE
duces machine language, it suffices to replace just the Frame Layout and In-
struction Selection modules. To change the source language being compiled,
only the modules up through Translate need to be changed. The compiler
can be attached to a language-oriented syntax editor at the Abstract Syntax
interface.
The learning experience of coming to the right abstraction by several itera-
tions of think–implement–redesign is one that should not be missed. However,
the student trying to finish a compiler project in one semester does not have
this luxury. Therefore, we present in this book the outline of a project where
the abstractions and interfaces are carefully thought out, and are as elegant
and general as we are able to make them.
Some of the interfaces, such as Abstract Syntax, IR Trees, and Assem, take
the form of data structures: For example, the Parsing Actions phase builds an
Abstract Syntax data structure and passes it to the Semantic Analysis phase.
Other interfaces are abstract data types; the Translate interface is a set of
functions that the Semantic Analysis phase can call, and the Tokens interface
takes the form of a function that the Parser calls to get the next token of the
input program.
Two of the most useful abstractions used in modern compilers are context-
free grammars, for parsing, and regular expressions, for lexical analysis. To
make the best use of these abstractions it is helpful to have special tools,
5
CHAPTER ONE. INTRODUCTION
such as Yacc (which converts a grammar into a parsing program) and Lex
(which converts a declarative specification into a lexical-analysis program).
Fortunately, such tools are available for Java, and the project described in this
book makes use of them.
The programming projects in this book can be compiled using any Java
6
1.3. DATA STRUCTURES FOR TREE LANGUAGES
compiler. The parser generators JavaCC and SableCC are freely available on
the Internet; for information see the World Wide Web page
http://uk.cambridge.org/resources/052182060X (outside North America);
http://us.cambridge.org/titles/052182060X.html (within North America).
Source code for some modules of the MiniJava compiler, skeleton source
code and support code for some of the programming exercises, example Mini-
Java programs, and other useful files are also available from the same Web
address. The programming exercises in this book refer to this directory as
$MINIJAVA/ when referring to specific subdirectories and files contained
therein.
7
CHAPTER ONE. INTRODUCTION
prints
8 7
80
For each grammar rule, there is one constructor that belongs to the class
for its left-hand-side symbol. We simply extend the abstract class with a “con-
crete” class for each grammar rule. The constructor (class) names are indi-
cated on the right-hand side of Grammar 1.3.
Each grammar rule has right-hand-side components that must be repre-
sented in the data structures. The CompoundStm has two Stm’s on the right-
hand side; the AssignStm has an identifier and an expression; and so on.
8
Discovering Diverse Content Through
Random Scribd Documents
Mr. Camfield’s wound was much inflamd, by wading the streams, and
traveling. He receivd a shot in his side from a pistol, the ball still
remaining in the flesh.
Joseph was one of the first natives who gave evidence of a change
of heart, and united with the church 8 years ago, and had, up to this
time, with the exception of two or three slight deviations, exhibited a
good Christian character.
Here was an opportunity for religion to show itself, if there was any.
Never before had temptation come to Joseph and his native
brethren, in the ch. in this dress. But now it came, and his fall, as I
regard it, and that of some others, has given to the Christian world a
lesson that should be well studied, before it again places the lives
and property of missionaries at the mercy of lawless savages,
without a military force to keep them in awe.
103
THINGS IN OREGON.
CHAPTER XVI.
Arrival of Gov. Lane—Description of Port Astoria and vicinity—Narrow escape from
Shipwreck.
All is commotion here. Gov. Lane, from Indiana, arrivd in town the
first of this month, bringing the new government with him in his
pocket up the Willamet river in a skiff, over the Clackamas rapids. As
to whether he got out and helpd to pull the boat over the rapids or
not, I have not been informd. The big men of the place are brushing
up their boots and putting on their best clothes, as the Governor
passes the streets, hoping as he passes along, that his eye may fall
upon them placidly. I do not very well know what such things mean,
though I suppose that politicians do.
April 7th.—The first public mail arrivd in Oregon city, from the U.
States, by the mail steamer of San Francisco, to-day. This country
begins to be alive to maritime business—the first vessel ever built at
the Willamet falls in Oregon, is now on the stocks. Her owners say
her tunnage will be from 50 to 60 tuns burden.
* * * * * * * *
About 25 miles of the river from its mouth, is indented with bays by
various names, making a width of from 7 to 10 or 12 miles.
On the south side, higher up, at the entrance of Young into the
Lewis and Clark’s river, is Young’s bay.
Amongst other things that have fallen within my notice whilst 105
at Astoria, was the price of a few articles of produce brought
to this place to sell to passengers, whilst waiting for the readiness of
the ship. Potatoes were sold at one dollar per bushel, eggs at $1 per
dozen, butter at $1 per pound. Flour a little more moderate—its
price per barrel was only $10. During my stay at Astoria, a beef was
killd at Clatsap and brought here, and sold at 12 cents for the fore,
and 15 for the hind quarters, per pound.
27th.—On leaving Astoria, our ship was thrown on the beach, where
she remaind during the day, occasiond by the drunkenness of our
pilot.
Thursday, May 3d, we left Baker’s bay for the broad ocean, with a
fair wind and high hopes of crossing the sand-bar with pleasantness
and safety. The number of souls on board was about 130. We
proceeded gently along for three-fourths of an hour, when we arrivd
near the place where the ships Shark, Vancouver and Maine were
wreckd, and the wind nearly ceasd to blow. Our ship became
unmanageable, drifting by the strong tide which was then
unfavorable, and likely in a few minutes to carry us from the channel
and place us upon the sands, where the ship must inevitably have
become a wreck.
In this critical situation, with only 18 feet of water for a ship drawing
15, and the tide yet falling—by the energetic movement of our
officers and crew, they were enabld to stay the ship by immediately
casting anchor. After waiting more than 2 hours in this perilous
situation, the wind became of sufficient strength to justify an
attempt to make our escape by parting anchor.
The present head of navigation for sail ships, is a little cloth town
calld Stocton. Here were 8 or 10 more vessels lying disrobd of their
sails to make cloth houses of. This town is more than 100 miles up
from San Francisco. At this place, supplies are deposited for the
mines, which are carrid by wagons and pack animals, to the mining
district, a distance of 70 or 80 miles further, upon the tributaries of
the Saint Waukeen.
107
GOLD MANIA,
Or Yellow Fever, as some call it.
CHAPTER XVII.
Excitement in Oregon, relative to the discovery of Gold in California.
As late as the 10th of March, 1849, the fever continud with unabated
fury, increasing in its sanguinary features as the warm season
approachd, preying upon the heart and vitals of every human being
in Oregon.
From the 13th of Sept. last, which was the time I arrivd at 108
Oregon city, to the 10th of March following, not one day
passd, Sundays not excepted, without the mention by some one in
my presence, of the gold speculation.
During the remainder of my stay in Oregon city, tools of various
kinds were invented and being made at that place, ready for
departure to the mines, so soon as they might be profitably worked,
on the opening of the warm season.
The following description of the Gold Mania is taken from the Oregon
Spectator, as quoted from the Californian—
It appears that in the first part of February last, Messrs. Marshall and
Bennett were engagd with a party in erecting a saw-mill for Capt. J.
A. Sutter, on the American fork of the Sacramento river, about 40
miles above its mouth. In excavating the tail-race, they removd the
rock during the day, and let in the water during the night, in order to
wash out the loose dirt and sand. On the morning of the 10th, after
shutting off the water, Mr. Marshall discoverd the first gold, lying
upon decomposd granite, in the bottom of the race.
It would seem that but little doubt was entertaind of its being the
real simon pure, for operations immediately ceasd on the mill, and
all hands commencd searching for gold. It was soon found that gold
abounded along the American fork for a distance of 30 miles. For a
time the discoverers were the only ones aware of the fact, but the
news finally spread through the settlements. But little credit however
was gaind by the report, though occasionally a solitary “gold 109
hunter” might be seen stealing down to a launch with a pick
and shovel, more than half ashamd of his credulity.
Within the past month, many sick persons from the mines have
arrivd at this place, and scarcely a launch comes down the
Sacramento, without more or less sick persons on board,—while
some die on the river. The very natural inference drawn from this, by
those who have never been at the mines, is, that they lie in a sickly
section of the country, and those at work there, are in daily
expectation of being sick. In our opinion,—however, nothing can be
farther from the truth. As far as our experience goes, it is on the
large rivers only, where disease prevails, and in passing up and
down upon them, the person not in perfect health is almost
invariably the one to become sick.—We have observd but few, very
few cases of sickness in the immediate neighborhood of the 111
mines, but such as we believe would have occurd under
similar circumstances in any other climate. Let the miner pass the
Sacramento safely, (and we would almost insure any person’s doing
so that was perfectly regular and temperate in all his habits,)—let
him not, when he arrives at the mines, work as though he was
privilegd to operate for a limited time only, but poco poco, resting at
proper intervals,—let him abstain from the free use of intoxicating
drinks, living upon wholesome food,—avoiding, for instance, half
baked bread—let him sleep under the shelter of a tent, with warm
bedding,—and if, after following our advice in all these particulars,
the gold hunter becomes sick, why—we do not know anything about
the matter.
113
CALIFORNIA GOLD MINES
DESCRIBED.
CHAPTER XVIII.
Geography of the Gold District of Alta California.
The names of the tributaries of the St. Waukeen, beginning with the
most northern one, are as follows. Makelemas, which unites with the
Saint Waukeen, near its confluence with the Sacramento. Next
south, is Calaveras. South of this, is Stanislaus. The next important
river, is Twalamy. Still farther south, a distance of 20 or 25 miles, is a
considerable stream, calld Merced, or River of Mercy. South of
Merced, is another, calld Mereposa, though I believe this is dry part
of the year. These constitute the principal mountain streams,
tributary to the St. Waukeen.
The length from north to south, of the present gold district, 114
cannot well be computed at more than 400 miles, lying
within the latitudes of 36 and 42 deg. north. In its width, which is
mostly containd within a distance of from 20 to 30 miles, it traverses
the middle portion of the western declivity of the aforementiond
range of mountains, though miners assert that gold has been found
sparingly, high up some of the mountain streams, toward its axis.
The whole surface of the gold district presents one continud scene of
uneven country. Much of it, the hills soar far above the intervening
valleys below—and along some of the principal tributaries, for miles
in length, very deep kanions are formd.
The water of the large streams is very pure and healthy, being
mostly from the melted snows of the mountain. During the summer
season it seldom rains, and the rivers continue to fall, till quite along
into the winter season. After the rainy season commences, which is
most powerful toward the summit of the mountains, floods are often
witnessd low down the streams, where not a single drop of water
has fallen for months. These floods descend with a mighty rush, and
often surprise the miner before he is able to remove his mining
implements from the bed of a stream.
The mining district is coverd with a thin growth of scrub oaks and
yellow pine. The earth is divested of soil, except sparingly in some of
the valleys, being of a reddish color, by the decomposition of rocks
containing iron.
The climate is so dry during summer, that little grass grows in any
part of the mines. Nauseous exhalations are therefore excluded, and
the atmosphere is quite healthy. In some parts of the mines the
miners become sick, but it is mostly attributable to their treatment
with themselves. Through the summer months, the days are warm
but the nights are cool, and but few nights occur in which a man
does not need considerable night clothing toward morning.
115
CHAPTER XIX.
The Geology of the Gold District of California, with the probable cause of the
production of Gold to the surface of the earth.
* * * * * * * *
The inquiring mind may now be led to the subject of Quartz Rock,
containd among the slate rock of the gold district.
The quartz rock of the gold region is mostly white, though some of it
is of the carnelian order, whilst some is translucent, and other
specimens are entirely transparent. The carnelian appearance of
some of the quartz seems to have been nothing more than the
circulation of water containing the red oxide of iron, through the
cracks of the broken quartz, till the rock became tingd with it. The
transparent variety is crystalizd, and is found only sparingly.
To account for the formation of quartz and its occupying its present
position in the gold district, is to account also for the formation and
production of gold to the surface of the earth, as is satisfactorily
believd by all. It is hard to account for much of the works of nature.
If it be considerd, that the quartz veins of the gold district be of
aqueous origin, that is, formd by infiltration, or the percolation of
silicious water into unoccupied spaces, till they are completely filld
with silicious sediment, so as to become rock, we then have to
account for its existing there in a friable state, which is hard to
conceive, since a formation by aqueous agency would most likely
produce solid rock.
It has been asserted by some miners, that they have seen gold in a
state of formation, by the percolation of water over quartz rock.
Those men are probably such as believe that quartz is the mother of
gold—and by the way, I should like to have them tell me also what
the father was. They say that the yellow appearance of the mud and
other sedimentary matter, which they have seen passing through
quartz veins, is gold in a state of formation. Perhaps they might
allow of a correction in their minds on that subject, if they were told
that the yellow appearance they saw was nothing more than
decomposd iron—probably the chromate of it.
Some objections to this mode also naturally arise. One objection is,
that there are instances of quartz veins traversing the stratified slate
rock diagonally. Another is, that it cannot well be conceivd that so
thin layers, as is the case with some of the quartz rock, can well be
formd in a tabular way. And if the quartz had been formd by
alternate layers with the stratified slate, it must of necessity have
been of aqueous origin, and also the gold.
The last view I shall take of the quartz, as found interstratified with
the slate rock, is, that the slate rock is of aqueous origin, and the
quartz rock of igneous origin, intruded from beneath after the tilting
up of the slate.
If it be taken for fact, that the quartz of the mining district was
intruded in a melted state, it must also be considerd that gold was
intruded with it. To account for the friable state of the quartz,
moisture must be supposd to have been present, whilst the quartz
was in a heated state.
FIRST VARIETY.
SECOND VARIETY
The creeks and large rivers receive their gold from the 121
mouths of ravines and hills contiguous to the creeks and
rivers.
In some places along the creeks, the miner finds angular gold
deposited in the banks of the streams at the foot of a hill, where it
had not slidden down sufficiently far to reach the power of the
waters of the stream.
THIRD VARIETY.
Its form is that of very thin scales, which causes it to float in waters
that are highly agitated. Hence also, the names of scale, and floating
gold.
This gold is seldom found in pieces worth more than a dollar, and is
rounded off by attrition, the same as the creek-washd gold.
The several varieties here describd, were the same, only differing in
form, in the original rock—but the several agents of deposit, have
separated them into separate classes, according to the several
capacities of gold to receive the power of the several depositing
agents. Hence, the finest floating gold is found lowest down 122
the principal rivers, where it is deposited. Creek-washd gold,
being heavy, is never movd very far down the stream, from where it
was first deposited into it—and dry ravine gold, having still a little
different agent from the others, has never been movd but a very
short distance.
* * * * * * * *
But as the bottom and edges of streams are rough and uneven, very
frequent obstructions to water occur. Places so obstructed, are the
eddies or partial eddies, so commonly observable in streams of
running water.
When water passes over a reef of rock, that traverses entirely across
the stream, like a mill dam, the central waters or current cannot well
form an eddy immediately below the reef, on account of its
impetuous movement—though laterally, towards the banks, partial
quietness of the water may exist.
124
Mode of Searching for the First Variety.
The miner, in prospecting for the first variety, or dry ravine gold,
selects a situation where, judging from the appearance of the hills,
or the slope of the ravine likely to contain gold, it may be found
most abundant. He commences his excavation at the center of the
ravine, by digging downward till he arrives in most cases at the rock
on which the deposit was made, which varies from 2 to 10 or 15 feet
in depth. He then prospects outward toward the hills till he arrives at
the line of deposit, in case any deposit there exists.
Those creeks of intermediate size between dry ravines, and the large
rivers flowing down from the mountains, though dry or nearly so at
some seasons of the year, are powrful in times of heavy rains or the
rapid melting of snows, as is evident from the position of some
heavy rocks in those streams, which none other agent the powr of a
mighty stream could have placd there.
As the tilted rocks of the gold district have universally one 126
course, and as creeks meander across them in nearly every
possible direction, there are chances in many places for reefs of
rocks to traverse the beds of creeks, directly along their channels.
Under such circumstances, but little gold has been deposited. If the
miner continues his search along the creek downward, till he arrives
at a bend in it, where the water is forcd over such reefs, a little
outward from the channel, gold is often found in great abundance—
watching carefully whilst excavating the earth in such places, to
prospect the lower side of any reefs that may be found there.
Again, if a rock project from any portion of the stream, so high that
water cannot run over it but is forcd around it, an eddy is in such
case formd immediately below it, in which situation gold may be
expected to be found.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com