0% found this document useful (0 votes)
79 views52 pages

Modern Compiler Implementation in Java 2ed 2nd Edition Andrew W. Appel Instant Download

The document discusses the second edition of 'Modern Compiler Implementation in Java' by Andrew W. Appel, which covers all phases of compiler design, including lexical analysis, parsing, and code generation. It is structured for both introductory and advanced courses, featuring a redesigned compiler project that allows students to build a working compiler in Java. The book emphasizes practical programming techniques and modular interfaces, making it suitable for students familiar with object-oriented programming.

Uploaded by

dkakugiyb1353
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views52 pages

Modern Compiler Implementation in Java 2ed 2nd Edition Andrew W. Appel Instant Download

The document discusses the second edition of 'Modern Compiler Implementation in Java' by Andrew W. Appel, which covers all phases of compiler design, including lexical analysis, parsing, and code generation. It is structured for both introductory and advanced courses, featuring a redesigned compiler project that allows students to build a working compiler in Java. The book emphasizes practical programming techniques and modular interfaces, making it suitable for students familiar with object-oriented programming.

Uploaded by

dkakugiyb1353
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Modern Compiler Implementation in Java 2Ed 2nd

Edition Andrew W. Appel - Downloadable PDF 2025

https://ebookfinal.com/download/modern-compiler-implementation-in-
java-2ed-2nd-edition-andrew-w-appel/

Visit ebookfinal.com today to download the complete set of


ebooks or textbooks
Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Engineering a Compiler 2nd Edition Keith Cooper

https://ebookfinal.com/download/engineering-a-compiler-2nd-edition-
keith-cooper/

Pharmacogenetics 2ed Edition Weber W.

https://ebookfinal.com/download/pharmacogenetics-2ed-edition-weber-w/

Advanced ASIC chip synthesis using Synopsys Design


Compiler Physical Compiler and PrimeTime 2nd Edition
Himanshu Bhatnagar
https://ebookfinal.com/download/advanced-asic-chip-synthesis-using-
synopsys-design-compiler-physical-compiler-and-primetime-2nd-edition-
himanshu-bhatnagar/

An Introduction to Modern Cosmology 2nd ed Edition Andrew


Liddle

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/

Continuous Enterprise Development in Java Testable


Solutions with Arquillian First Edition Andrew Lee
Rubinger
https://ebookfinal.com/download/continuous-enterprise-development-in-
java-testable-solutions-with-arquillian-first-edition-andrew-lee-
rubinger/

Modern Construction Handbook 6th Edition Andrew Watts

https://ebookfinal.com/download/modern-construction-handbook-6th-
edition-andrew-watts/

Modern Political Ideologies 3rd Edition Andrew Vincent

https://ebookfinal.com/download/modern-political-ideologies-3rd-
edition-andrew-vincent/

Java in a nutshell 2nd ed Edition David Flanagan

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

with JENS PALSBERG


Purdue University

iii
         
The Pitt Building, Trumpington Street, Cambridge, United Kingdom

  


The Edinburgh Building, Cambridge CB2 2RU, UK
40 West 20th Street, New York, NY 10011-4211, USA
477 Williamstown Road, Port Melbourne, VIC 3207, Australia
Ruiz de Alarcón 13, 28014 Madrid, Spain
Dock House, The Waterfront, Cape Town 8001, South Africa

http://www.cambridge.org

© Cambridge University Press 2004

First published in printed format 2002

ISBN 0-511-03930-1 eBook (Adobe Reader)


ISBN 0-521-82060-X hardback
Contents

Preface ix

Part I Fundamentals of Compilation

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

5 Semantic Analysis 103


5.1 Symbol tables 103

v
CONTENTS

5.2 Type-checking MiniJava 111

6 Activation Records 116


6.1 Stack frames 118
6.2 Frames in the MiniJava compiler 126

7 Translation to Intermediate Code 136


7.1 Intermediate representation trees 137
7.2 Translation into trees 140
7.3 Declarations 155

8 Basic Blocks and Traces 162


8.1 Canonical trees 163
8.2 Taming conditional branches 169

9 Instruction Selection 176


9.1 Algorithms for instruction selection 179
9.2 CISC machines 187
9.3 Instruction selection for the MiniJava compiler 190

10 Liveness Analysis 203


10.1 Solution of dataflow equations 205
10.2 Liveness in the MiniJava compiler 214

11 Register Allocation 219


11.1 Coloring by simplification 220
11.2 Coalescing 223
11.3 Precolored nodes 227
11.4 Graph-coloring implementation 232
11.5 Register allocation for trees 241

12 Putting It All Together 249

Part II Advanced Topics

13 Garbage Collection 257


13.1 Mark-and-sweep collection 257
13.2 Reference counts 262
13.3 Copying collection 264

vi
CONTENTS

13.4 Generational collection 269


13.5 Incremental collection 272
13.6 Baker’s algorithm 274
13.7 Interface to the compiler 275

14 Object-Oriented Languages 283


14.1 Class extension 283
14.2 Single inheritance of data fields 284
14.3 Multiple inheritance 286
14.4 Testing class membership 289
14.5 Private fields and methods 292
14.6 Classless languages 293
14.7 Optimizing object-oriented programs 293

15 Functional Programming Languages 298


15.1 A simple functional language 299
15.2 Closures 301
15.3 Immutable variables 302
15.4 Inline expansion 308
15.5 Closure conversion 316
15.6 Efficient tail recursion 319
15.7 Lazy evaluation 321

16 Polymorphic Types 335


16.1 Parametric polymorphism 336
16.2 Polymorphic type-checking 339
16.3 Translation of polymorphic programs 344
16.4 Resolution of static overloading 347

17 Dataflow Analysis 350


17.1 Intermediate representation for flow analysis 351
17.2 Various dataflow analyses 354
17.3 Transformations using dataflow analysis 359
17.4 Speeding up dataflow analysis 360
17.5 Alias analysis 369

18 Loop Optimizations 376


18.1 Dominators 379
18.2 Loop-invariant computations 384

vii
CONTENTS

18.3 Induction variables 385


18.4 Array-bounds checks 391
18.5 Loop unrolling 395

19 Static Single-Assignment Form 399


19.1 Converting to SSA form 402
19.2 Efficient computation of the dominator tree 410
19.3 Optimization algorithms using SSA 417
19.4 Arrays, pointers, and memory 423
19.5 The control-dependence graph 425
19.6 Converting back from SSA form 428
19.7 A functional intermediate form 430

20 Pipelining and Scheduling 440


20.1 Loop scheduling without resource bounds 444
20.2 Resource-bounded loop pipelining 448
20.3 Branch prediction 456

21 The Memory Hierarchy 464


21.1 Cache organization 465
21.2 Cache-block alignment 468
21.3 Prefetching 470
21.4 Loop interchange 476
21.5 Blocking 477
21.6 Garbage collection and the memory hierarchy 480

Appendix: MiniJava Language Reference Manual 484


A.1 Lexical Issues 484
A.2 Grammar 484
A.3 Sample Program 486

Bibliography 487

Index 495

viii
Preface

This book is intended as a textbook for a one- or two-semester course in com-


pilers. Students will see the theory behind different components of a com-
piler, the programming techniques used to put the theory into practice, and
the interfaces used to modularize the compiler. To make the interfaces and
programming examples clear and concrete, we have written them in Java.
Another edition of this book is available that uses the ML language.

Implementation project. The “student project compiler” that we have out-


lined is reasonably simple, but is organized to demonstrate some important
techniques that are now in common use: abstract syntax trees to avoid tan-
gling syntax and semantics, separation of instruction selection from register
allocation, copy propagation to give flexibility to earlier phases of the com-
piler, and containment of target-machine dependencies. Unlike many “stu-
dent compilers” found in other textbooks, this one has a simple but sophisti-
cated back end, allowing good register allocation to be done after instruction
selection.
This second edition of the book has a redesigned project compiler: It uses
a subset of Java, called MiniJava, as the source language for the compiler
project, it explains the use of the parser generators JavaCC and SableCC, and
it promotes programming with the Visitor pattern. Students using this edition
can implement a compiler for a language they’re familiar with, using standard
tools, in a more object-oriented style.
Each chapter in Part I has a programming exercise corresponding to one
module of a compiler. Software useful for the exercises can be found at
http://uk.cambridge.org/resources/052182060X (outside North America);
http://us.cambridge.org/titles/052182060X.html (within North America).

Exercises. Each chapter has pencil-and-paper exercises; those marked with


a star are more challenging, two-star problems are difficult but solvable, and

ix
PREFACE

the occasional three-star exercises are not known to have a solution.

Course sequence. The figure shows how the chapters depend on each other.
Lexical Abstract Semantic
2. 3. Parsing 4. 5.

Quarter
Analysis Syntax Analysis

Activation Translation to Basic Blocks

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

Garbage Object-Oriented Memory


13. 14. 21.
Collection Languages Hierarchies

• 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.

Acknowledgments. Many people have provided constructive criticism or


helped us in other ways on this book. Vidyut Samanta helped tremendously
with both the text and the software for the new edition of the book. We would
also like to thank Leonor Abraido-Fandino, Scott Ananian, Nils Andersen,
Stephen Bailey, Joao Cangussu, Maia Ginsburg, Max Hailperin, David Han-
son, Jeffrey Hsu, David MacQueen, Torben Mogensen, Doug Morgan, Robert
Netzer, Elma Lee Noah, Mikael Petterson, Benjamin Pierce, Todd Proebsting,
Anne Rogers, Barbara Ryder, Amr Sabry, Mooly Sagiv, Zhong Shao, Mary
Lou Soffa, Andrew Tolmach, Kwangkeun Yi, and Kenneth Zadeck.

x
PART ONE
Fundamentals of
Compilation

1
2
1
Introduction

A compiler was originally a program that “compiled”


subroutines [a link-loader]. When in 1954 the combina-
tion “algebraic compiler” came into use, or rather into
misuse, the meaning of the term had already shifted into
the present one.

Bauer and Eickel [1975]

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

Relocatable Object Code


Register Assignment

Assembly Language
Interference Graph

Machine Language
Flow Graph
Assem

Control Data
Flow Flow Register Code Assembler Linker
Analysis Analysis Allocation Emission

FIGURE 1.1. Phases of a compiler, and interfaces between them.

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.

1.1 MODULES AND INTERFACES

Any large software system is much easier to understand and implement if


the designer takes care with the fundamental abstractions and interfaces. Fig-
ure 1.1 shows the phases in a typical compiler. Each phase is implemented as
one or more software modules.
Breaking the compiler into this many pieces allows for reuse of the compo-
nents. For example, to change the target machine for which the compiler pro-

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.

DESCRIPTION OF THE PHASES


Each chapter of Part I of this book describes one compiler phase, as shown in
Table 1.2
This modularization is typical of many real compilers. But some compil-
ers combine Parse, Semantic Analysis, Translate, and Canonicalize into one
phase; others put Instruction Selection much later than we have done, and
combine it with Code Emission. Simple compilers omit the Control Flow
Analysis, Data Flow Analysis, and Register Allocation phases.
We have designed the compiler in this book to be as simple as possible, but
no simpler. In particular, in those places where corners are cut to simplify the
implementation, the structure of the compiler allows for the addition of more
optimization or fancier semantics without violence to the existing interfaces.

1.2 TOOLS AND SOFTWARE

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

Chapter Phase Description


2 Lex Break the source file into individual words, or tokens.
3 Parse Analyze the phrase structure of the program.
4 Semantic Build a piece of abstract syntax tree corresponding to each
Actions phrase.
5 Semantic Determine what each phrase means, relate uses of variables to
Analysis their definitions, check types of expressions, request translation
of each phrase.
6 Frame Place variables, function-parameters, etc. into activation records
Layout (stack frames) in a machine-dependent way.
7 Translate Produce intermediate representation trees (IR trees), a nota-
tion that is not tied to any particular source language or target-
machine architecture.
8 Canonicalize Hoist side effects out of expressions, and clean up conditional
branches, for the convenience of the next phases.
9 Instruction Group the IR-tree nodes into clumps that correspond to the ac-
Selection tions of target-machine instructions.
10 Control Analyze the sequence of instructions into a control flow graph
Flow that shows all the possible flows of control the program might
Analysis follow when it executes.
10 Dataflow Gather information about the flow of information through vari-
Analysis ables of the program; for example, liveness analysis calculates
the places where each program variable holds a still-needed value
(is live).
11 Register Choose a register to hold each of the variables and temporary
Allocation values used by the program; variables not live at the same time
can share the same register.
12 Code Replace the temporary names in each machine instruction with
Emission machine registers.

TABLE 1.2. Description of compiler phases.

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

Stm → Stm ; Stm (CompoundStm)


ExpList → Exp , ExpList (PairExpList)
Stm → id := Exp (AssignStm)
ExpList → Exp (LastExpList)
Stm → print ( ExpList ) (PrintStm)
Binop →+ (Plus)
Exp → id (IdExp)
Binop →− (Minus)
Exp → num (NumExp)
Binop →× (Times)
Exp → Exp Binop Exp (OpExp)
Binop →/ (Div)
Exp → ( Stm , Exp ) (EseqExp)

GRAMMAR 1.3. A straight-line programming language.

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.

1.3 DATA STRUCTURES FOR TREE LANGUAGES

Many of the important data structures used in a compiler are intermediate


representations of the program being compiled. Often these representations
take the form of trees, with several node types, each of which has different
attributes. Such trees can occur at many of the phase-interfaces shown in
Figure 1.1.
Tree representations can be described with grammars, just like program-
ming languages. To introduce the concepts, we will show a simple program-
ming language with statements and expressions, but no loops or if-statements
(this is called a language of straight-line programs).
The syntax for this language is given in Grammar 1.3.
The informal semantics of the language is as follows. Each Stm is a state-
ment, each Exp is an expression. s1 ; s2 executes statement s1 , then statement
s2 . i :=e evaluates the expression e, then “stores” the result in variable i.

7
CHAPTER ONE. INTRODUCTION

print(e1 , e2 , . . . , en ) displays the values of all the expressions, evaluated


left to right, separated by spaces, terminated by a newline.
An identifier expression, such as i, yields the current contents of the vari-
able i. A number evaluates to the named integer. An operator expression
e1 op e2 evaluates e1 , then e2 , then applies the given binary operator. And
an expression sequence (s, e) behaves like the C-language “comma” opera-
tor, evaluating the statement s for side effects before evaluating (and returning
the result of) the expression e.
For example, executing this program
a := 5+3; b := (print(a, a-1), 10*a); print(b)

prints
8 7
80

How should this program be represented inside a compiler? One represen-


tation is source code, the characters that the programmer writes. But that is
not so easy to manipulate. More convenient is a tree data structure, with one
node for each statement (Stm) and expression (Exp). Figure 1.4 shows a tree
representation of the program; the nodes are labeled by the production labels
of Grammar 1.3, and each node has as many children as the corresponding
grammar production has right-hand-side symbols.
We can translate the grammar directly into data structure definitions, as
shown in Program 1.5. Each grammar symbol corresponds to an abstract
class in the data structures:
Grammar class
Stm Stm
Exp Exp
ExpList ExpList
id String
num int

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
Another Random Scribd Document
with Unrelated Content
The text on this page is estimated to be only 28.46%
accurate

me ; and following him were ten young men, each lacking


an eye — a thing which caused me great astonishment. They and
the old man saluted me, and asked me whence I came, whereupon I
told them my story, which they listened to with looks of wonder.
Then they invited me into the palace, and one of them said : " Be
welcome, O brother, but see to it that thou ask us not respecting our
condition, nor yet how it is we each lack an eye." Presently the old
man brought food and wine, and we ate and drank together,
conversing on many things until it was time to sleep. Then one of
them called to the old man to bring the materials for penance, and
he arose and placed before each a basin full of ashes and powdered
charcoal. One and all then bared their arms and blackened their
faces with the mixture, crying continually, "Once we were dwelling in
happiness, but now we are wretched ; and this is the result of our
idle curiosity." This they kept up till daybreak, when they washed
their faces and changed their clothes and slept. Next day, being
unable to cast off my curiosity regarding this strange behaviour, I
beseeched them to tell me the reason thereof, and one of them
replied: "O young man, ask not what doth not concern thee, lest
thou hear what may not please thee." But I was not content with
this answer, and continued to entreat them to tell me the reason of
their actions, and also the cause of each having lost an eye. " Nay,
be silent," said another ; "what the mind doth not know, the heart
doth not grieve." Yet I still pestered them with my questions, giving
them no peace. At length they lost patience, and, after conversing
together awhile, one of them said to me: "O young man, if thou dost
above all things desire to know the cause of these things, submit
thyself to our hands, and 2B I93 * i i : ifX 
The text on this page is estimated to be only 27.88%
accurate

\ .^:. thou shalt learn." And I answered, "I desire nothing


more than to know;" for my curiosity had become a fever. Then they
slaughtered a ram and flayed it, and, placing a knife in my hand,
sewed me up in the skin and carried me to a hilltop at a little
distance, where they left me. Presently I heard the flapping of giant
wings, and then the ram's skin, with me inside it, was seized by the
talons of a great bird and borne up and away. After a long flight, the
bird set me down upon a high plateau. Remembering the knife they
had placed in my hand, I ripped open the skin, and emerged. The
gigantic bird, on seeing me, flew off screaming. Far in the distance,
at the side of a hill, I saw a splendid palace, sparkling in the
sunlight. It was the only habitation that I could discern, so I made
my way towards it. After some hours' journey, I reached its gates,
and seeing them open, entered, and soon found myself in a great
chamber of indescribable splendour, where forty beautiful damsels,
each one like a goddess, welcomed me with cries of joy. "O our
Master and Prince," they said, "why hast thou tarried so long? We,
thy handmaids, have waited many weeks for thy coming." And they
set food and wine before me, and while I ate and drank, some sang
and others danced ; and they were so wildly beautiful that any one
of them would have melted the heart of an anchorite. Thus suddenly
was I launched into a life of pure delight, and I dwelt among these
rare and radiant damsels, their sole Lord and Master, in luxury and
joy. Thus it continued for a whole year, with never a shadow of
dulness in our days ; but, on the first morning of the new year, they
all came to me weeping, and bidding me farewell, as each in turn
clung to me with the sadness of 194 f f y- ' t ' -V- C ' ty ' Lr 1 I I « i
The text on this page is estimated to be only 27.09%
accurate

1 A 1 I M T f T T T I/ *•« ••« • •• »•• •'•-i ••«


^Jr.^x^^J^^jy^^^ - ^i* parting. "Wherefore this?" I cried. "Ye will
break my heart if ye leave me." And one replied, " Nay, O master ;
we love thee most of any on earth, but we must leave thee for a
time, and we fear to lose thee." And she fell to weeping afresh, and
the others added their tears to hers. "Tell me what this means," I
said to her. " O my master, if thou wouldst know," she replied, "we
are the daughters of kings, and for many years it has been our
practice to dwell in this palace, returning only to our fathers for forty
days at the beginning of each year. To-day we must go, and we fear
that, before we return, thou wilt disregard our directions, in which
case thou wilt be lost to us. Here are the keys, a hundred in number,
which will unlock a hundred doors for thee, admitting to gardens of
various kinds, in which thou wilt find a hundred different delights ;
but we do entreat thee, open not the door which is fashioned of
pure gold, for if thou dost, we shall never see thee again, and that is
what we fear." I took the keys, greatly wondering, and when I had
embraced them all, and said farewell, they departed, with sad looks,
leaving me alone in the palace. Many times I swore to myself that I
would never open the golden door, and even as I swore, the wish to
do it came uppermost. But I forced it down, saying : "There are
ninety-nine doors without this one : surely it is enough !" And that
evening, feeling sad and lonely, and longing for entertainment, I
took the keys, and, selecting one engraven with a character
corresponding to that on the first door, I opened and entered. Within
lay a garden like paradise, with running streams, and hanging fruits,
and birds that sang the praises of their Creator. Every kind of
delicate perfume breathed from the '95 M£B£^jHUCiJBMNLUMH-
xXMBK-IJHMKLL.MMK£JMB--uMH t 1 T ab-^-^ J-^-l5— :«— $
5^5^E^— r » V
The text on this page is estimated to be only 27.58%
accurate

\ -. Y rarest of flowers, and the bosom of the dreamy trees


moved in the soft wind as if langorous with love. Seeing this
wonderful place, I was impelled by curiosity to explore what lay
behind the second door. Accordingly, I opened it and entered. Here
was a large domain of forest and meadow, watered by a crystal
river. Uplands on which the sunlight slept, led up to mountain peaks
towering against the sides of heaven. I noted all this with wonder,
saying, "I will return, and enjoy this at my leisure; meanwhile, I die
to know what fresh joy is concealed by the third door." When I
entered the third place of delight, I found it to be a spacious aviary,
containing all the birds of song and of rare plumage that could be
found on earth. This vast place was paven with many-coloured
marble, and graced with patches of forest and greensward. The
birds drank from crystal fountains, and, flying off, sang gloriously.
The streams of these fountains were of different colours, and when I
drank of one, I found it was pure wine. So I wandered from one to
another sipping the rarest vintages I had ever known, until, coming
to a soft couch of moss, I reclined, and was lulled to sleep by the
songs of countless nightingales. When I awoke next morning, I
opened the fourth door and found beyond it a treasury passing the
imagination of kings. Jewels and precious stones there were beyond
reckoning. "These," I said, " are mine, and forty priceless damsels
are also mine : what Sultan can compare with me ? " That day, and
on the following days, I opened one door after another, rinding
within each the strangest and most wonderful things man ever
beheld ; until, on the thirty-ninth day, I had opened every door
except the last, — the one fashioned 196
The text on this page is estimated to be only 28.02%
accurate

1 1 1 ••* •-• r t t •• -M* 1 i IrJ of pure gold. Long I looked


at it, recalling my oath, and fortifying myself against temptation.
Many times I turned away from it, with the key in my hand, but
always the Devil drove me back again. Then, at last, my curiosity
became acute, and I could not refrain. I opened the door, and
passed within. I was met by an odour fragrant beyond conception,
which mastered my brain so that I fell in a faint. But I soon
recovered, and, rising to my feet, went on, treading on golden tiles
spread with saffron, and lighted on my way by golden lamps, from
which were wafted the odours of musk and ambergris. I soon saw
that the place was, in effect, a stable, though words fail to describe
its splendour. There, standing at a crystal manger full of choice
sesame, with a trough adjoining filled with rose-water, stood a
magnificent steed, as black as night. Never had I seen his equal. He
was saddled and bridled, and his trappings were of gold and thread-
of-gold, sparkling with gems. "This is the steed of my desire," I said,
and then, as I approached him, he turned his head towards me, and
neighed. Urged by the Devil, I led him forth and mounted him. But
when I jerked the reins, he stood stock still. I persuaded him with
my heels, but he did not move. Then I espied a whip deposited in
the saddle. I took this and struck him a violent blow. With a neigh
like thunder, he rose in the air, and soared up and up to a great
height. Then he flew with me over hills and valleys, until at last he
alighted on the roof of another palace. There he plunged and
reared, and finally shook me off behind him ; and, as I fell, a blow
from his tail struck out my eye. Leaving me thus, he soared up and
away, and was soon lost to sight. When I descended from the roof, I
found I was back in '97 • ^?r Vf i T ' ' f ^ • i~
The text on this page is estimated to be only 27.81%
accurate

\ M I T I T T- ~* t T t T t the Palace of the ten young men.


When they beheld me, and saw that my eye was gone, they cried
with one voice, " No welcome to thee, O curious one ! Thou art now
in like case with us, having been chastised for thine impertinent
curiosity. For know that we have all opened that golden door and
ridden that black horse, and that is why we do nightly penance for
our foolishness." I then begged them to receive me into their
company, but they refused, saying their number was complete. So I
went my way dejected, and wandered as a mendicant, ever on and
on towards Baghdad, the Abode of Peace, resolved to seek the
Khalifeh of the Lord of all Creatures and set my case before him. •*
" Verily," exclaimed Harun-er-Rashid as the Third Royal Calender
retired to his place, "this is the most astounding tale of all. Hear me
now, all of you. These men have suffered greatly, but Fate hath no
further trouble in store for them. By Allah ! my armies are great, and
I will restore each to his throne. As for you, O ladies," he continued,
turning to the three sisters, "my Seraglio is dull and lifeless without
you. Will you grace it with your presence?" "Yes, O Commander of
the Faithful," cried they all, laughing merrily and clapping their
hands, for they thought him a perfect impersonator; "we will come
to thee." "On the head and the eye?" "Yea, O King, on the head and
the eye is our promise given." At this the Khalifeh turned to his two
officials. "O Vizier," he said, "I call thee to witness; and thee also, O
Mesrur." And they answered smiling, for they liked the pretence of
his pretence, "King of the Age, we hear and obey." 198 *• • •-,.' *t*
• •• • •** »•• f
The text on this page is estimated to be only 27.54%
accurate

11i
The text on this page is estimated to be only 28.04%
accurate

->-;Y former evening, and their faces showed fear and


surprise, for they knew not why they had been thus summoned. The
Khalifeh spoke. "Know, O ye people, that I, Harun-erRashid, of the
house of Abbas, do not forget my promises. I promised Three Royal
Calenders that I would restore them to their thrones, and, by Allah !
this shall be done. Three beautiful ladies of Baghdad promised me
that they would come into my Seraglio, which thou didst witness, O
Ja'far ; and thou, too, O Mesrur." The two officials bowed low,
confirming this. "But," continued the Khalifeh, "I have since decided
to make them queens by bestowing them in marriage upon these
three kings." And he indicated the Calenders. Then, turning towards
the porter, he continued : " I also promised that a carrier of goods,
— a merry fellow, — should be my Wag. This shall be, and his first
duty will be to solve this riddle. Which is easier : for the Khalifeh to
play the merchant, or the merchant to play the Khalifeh ?
Meanwhile, do you all agree to what I have proposed?" They were
all dumbfounded as they realised that their actor of the previous
night had played his part so well, because he was indeed the
Khalifeh himself. For some moments no one spoke ; then they all
made obeisance to him and kissed the ground. "O King of the Age,"
said one of the ladies, "I answer for my sisters and myself. We will
obey thy commands willingly and with joy." Then one of the
Calenders added, "O Prince of the Faithful, we also hear and obey,
with equal willingness and equal joy." "And as for me, O King," said
the porter, " I, being a wag, and also a liar of some excellence, knew
that indeed thou wert the Khalifeh of the Lord of All Creatures, but I
was compelled to dissemble for fear of thine Executioner's sword.
Thus I 200 •5. V iY T
The text on this page is estimated to be only 24.50%
accurate

Abu-1-Hasan awakens in the bed of the Khalifeh. Page 206


The text on this page is estimated to be only 0.00%
accurate

IY
The text on this page is estimated to be only 26.47%
accurate

T •.*J. A. jr. */!.*. Jr. solve thy riddle, O King : The Khalifeh
played better than the merchant, whose play was equally good." The
Khalifeh smiled and, turning to Ja'far, said, "O Vizier, bestow upon
him the Robe of the Wag." Then the Khalifeh arose, and, descending
from his throne, placed the hands of the three ladies in those of the
Three Royal Calenders. The Kadi and witnesses were summoned and
the marriage contracts were signed and sealed. He then bestowed
upon each of the three wedded pairs a splendid palace and sufficient
money for their needs until such time as he had succeeded in
restoring them to their thrones. And so did Harun-er-Rashid draw
upon himself ten thousand blessings. 2 C d»-. . .«, "^fr ^Hk r
The text on this page is estimated to be only 11.24%
accurate

-<. t="" ._="">/< -H "^ ' ' Y- 'IT *¥• ' • •• •• • ••• >?• t f-
Y V- Jji Y- Y V- H **" ••• V? i I * t
The text on this page is estimated to be only 28.54%
accurate

•&. A-. THE SLEEPER AWAKENED IN the reign of Harun-er-


Rashid, a merchant of the city of Baghdad died, leaving his vast
fortune to his son Abu-1-Hasan, the Wag, who at once divided it into
two equal parts : one to be set aside, and the other to be spent.
Selecting a number of wealthy merchants' sons as his boon
companions, he lived a life of extravagance until every fraction of
that which was to be spent was exhausted. At this he called his boon
companions and laid his case before them, expecting at least
sympathy, if not offers of assistance. But one and all treated him
with the utmost unconcern and turned their backs on him. Sad at
heart he sought comfort of his mother, complaining of the injustice
of this treatment. " O, Abu-1-Hasan," said she, "it was ever thus;
when thou wast rich they were thy friends, but now thou art poor
they look the other way." And she wept with him, mingling her tears
with his. Then Abu-1-Hasan arose and at once took steps to
withdraw the other half of his fortune from the safe-keeping in which
he had placed it. Upon this he lived as befitted his condition in life,
for he was still a wealthy man. But, remembering the lesson he had
bought with the other half of his riches, he took an oath that
henceforth he would consort neither with relations nor friends nor
acquaintances, but only with strangers ; and, furthermore, that the
extent of his association with anyone person would be for one night
only, 203 I ; .:~
The text on this page is estimated to be only 27.64%
accurate

-: — -r-v t m •,r I the acquaintanceship ceasing entirely at


sunrise next morning. Every evening thereafter, when the purple
twilight fell upon Baghdad, Abu-1-Hasan would walk in the ways of
the city, saluting none, but at last waylaying a stranger, upon whom
he would press an invitation to good food and wine and
entertainment at his house. What stranger could refuse ? With the
guest in the place of honour Abu-1-Hasan drank deep with him till
morning, when the guest departed with the understanding that if
they ever met again they were not to recognise each other. This
went on night after night for a whole year, until one night an
illustrious stranger accepted Abu-1-Hasan's invitation. It was none
other than Harun-er-Rashid himself, who had wandered forth in
disguise to amuse himself, as was his wont at times. Little dreaming
that he was entertaining the Khalifeh unawares, Abu-1-Hasan led his
guest into his saloon — a most luxurious apartment where every
comfort was provided : streams of water murmuring through silver
channels ; golden fountains playing in cool grottoes, and, over all, an
amber light shed by a wonderful lamp, subduing the richness of the
place to a vague and dreaming glamour. Here they reclined, and
Abu-1-Hasan summoned a slave girl, lissom as the willow tendril,
and bade her sing to the music of her lute. Sweetly then she sang
these verses, inspired by the soft languor of the night : — Oh ! Love,
thy footsteps stray in lands afar, But here within my heart thou dost
abide. E'en though thou dwelt in yonder distant star No depths of
space our spirits could divide. Thou art my Love ! Thro' all eternity
Thou art my soul, and nothing is but thee. 204 W •! ,L .1; !?r* t t
The text on this page is estimated to be only 26.57%
accurate

V V 1 r . -A- . itr, -A . . -A- . . ^. . & . ft , *s . A . * . IT. * . A


, & . T. *• £ Er-Rashid marvelled greatly at the singer and her song,
and wondered in his heart what manner of man was Abu-1Hasan
that he could entertain on so magnificent a scale. "Tell me, young
man," he said, "what is thy name, that on a future occasion I may
return thy hospitality?" And Abu-1-Hasan told him, but added with a
smile : "Alas ! this night must end our acquaintance, for I have so
vowed it." Then he set forth the nature and the cause of his vow, at
which Er-Rashid laughed heartily and said, "By Allah ! brother; I do
not blame thee ! " After this came the slave girls and spread a
banquet before them, and they partook of it, Abu-1-Hasan giving the
choicest portions to the Khalifeh. When they had finished their
repast Abu-1-Hasan brought out his oldest and most fragrant wines,
laid the wine-cloth himself, and, having lighted some small lamps
and candles, filled a goblet and raised it to the Khalifeh. "Best of
boon companions," he said, "away with ceremony! Regard me as thy
faithful slave and may I never be compelled to grieve thy loss." With
this he drained the goblet, and, still acting the part of the Khalifeh's
servant, filled another for his master and handed it to him. This
pleased the Khalifeh greatly. He appreciated such delicate attention.
He took the goblet and drank, saying within himself, " By Allah ! a
good return will I make him for this." Abu-1-Hasan continued to wait
upon hisguest in humble fashion, and the Khalifeh enjoyed his
hospitality to the full. If his host had known him to be Er-Rashid
himself — which he did not — he could not have entertained him
better. At the hour of midnight the Khalifeh spoke to his host in
serious tones. "O, Abu-1-Hasan," said he, "tell me what thing thou
dost most desire." 205 T T
The text on this page is estimated to be only 27.79%
accurate

i t "Why, my master," replied Abu-1-Hasan, "if thou wouldst


know : my most constant prayer is that I may be rid of the incessant
annoyance imposed upon me by the Imam and the four Sheiks of
the neighbouring mosque. When they hear the sound of music and
revelry at night they inform against me, so that I am harassed by
heavy fines. By Allah ! if I had my way I would give each of them a
thousand lashes." " May Allah grant thy prayer ! " said Er-Rashid,
and, unobserved, he dropped a lozenge into his host's wine and
handed him the goblet, bidding him drink. Abu-1-Hasan did so and
speedily thereafter fell sound asleep. The Khalifeh at once
summoned his servants, who, having followed him at a little
distance, were waiting without. He commanded them to place Abu-
1-Hasan upon a mule and convey him to the Palace. This was soon
done. Later, when the Khalifeh had rested somewhat, he summoned
the most important officials of his Court, and, indicating the sleeping
figure of Abu-1-Hasan, said to them, "In the morning you will find
this young man upon the royal couch. When he awakes, see to it
that you obey his lightest wish as you would my own ; salute him as
the Khalifeh and make obeisance before him." To his women slaves
he gave similar instructions and ordered them to address Abu-1-
Hasan as the Prince of the Faithful. Then Er-Rashid retired to
another part of the Palace and slept. In the morning when Abu-1-
Hasan awoke upon the royal couch he stared in amazement at the
attendants making obeisance before him. " O, Prince of the Faithful !
it is the hour of morning prayer," said a beautiful slave girl, stepping
forward. Abu-1-Hasan laughed, for he knew not 206 \ i i t : r r ^ .A.
; i •} j T ' fs- f ^»v
The text on this page is estimated to be only 25.27%
accurate

t what to make of it. Then he rubbed his eyes and gazed


around upon the sumptuous magnificence of the apartment with its
gorgeous roof and walls, its rich silk hangings, its vessels of gold and
sparkling crystal, its jewelled furniture, ornaments and luxurious
carpets. "By Allah !" he gasped; "have I attained to the fragrant
Paradise, or do I dream?" With that he closed his eyes as if to hold
the dream in further slumber, but a eunuch advanced and kissed the
ground before the royal couch. " O, Prince of the Faithful ! " he said,
humbly ; " bethink thee of thy usual custom." At this Abu-1-Hasan,
sorely perplexed, opened his eyes again very slowly, and saw the
rich trappings of the couch whereon he lay. Little by little he opened
them until at last they were wide with wonder, for this was no dream
— the voice of the eunuch who had spoken, the faces and forms of
the attendants, the royal splendour of the place — all were as real as
he could wish ; and yet — yet — he raised his hand to his mouth
and bit one of his fingers — hard ; then cried out with sudden pain.
Angrily he raised himself on one elbow, and, addressing one of the
female slaves, " Come here !" he said. "My lord, I am always at thy
service," she answered, drawing near. " What is thy will, O Prince of
the Faithful ? " " Tell me," he said, " who am I, and where am I ? "
"Thou art the Prince of the Faithful," answered she. "Thou art in thy
palace and upon thy royal couch." "Nay, nay," said he ; "I sleep.
Methinks I dream, or — " he went on, half to himself, — "Can it be?
My guest — he bade me drink and — what subtle enchantment is
this? Am I now Abu-1-Hasan dreaming I am the Khalifeh, or was I,
last night and heretofore for many nights, the Khalifeh dreaming he
was Abu-1-Hasan ? " And the Khalifeh himself, observing 207 yTr
•,:> • * • a • * • • * - ijr ^ ^Y i. i A A i # [ * - 1 « I i .1— :-* SSL
The text on this page is estimated to be only 26.89%
accurate

\ 'M J, vf 't 'Y' Jf T -=— k .A.i.vk.n.Jh.A.-


A.A.^.TJf.^i.n.^.^.aL.. .^ him all the while from a sheltered nook,
revelled in the perplexity of his guest. At last Abu-1-Hasan called one
after another to him and questioned each in turn, asking if indeed
he were the Prince of the Faithful ; and in turn each showed
amazement that he should put the question and assured him that
indeed he was the Khalifeh of the Lord of all creatures. To the first
he said, hotly, "Thou liest ! " To the next: "Thou art n error To
others: "Impossible!" and "It cannot be!" Until at last he was fairly
beaten, and had to admit that he indeed was Er-Rashid himself, the
Prince of the Faithful. He asked the attendants to withdraw so that
he might give himself up to this new-found wonder and perplexity,
and accustom himself to the strange position in which he found
himself. The morning wore on and he was aroused from his reverie
by a eunuch who approached with a salutation and handed him a
pair of shoes of fine spun gold set with precious stones. Abu-1-
Hasan put these on. Then came female slaves with a golden basin
and a silver jug and they bathed his hands. On this being done, they
spread a praying carpet before him. Although he knew not well how
to pray, he made many protestations to Allah, earnestly entreating
that he might be convinced that this was not a dream. His prayers
dispelled the doubt, but it returned when the eunuchs brought him
priceless apparel in which to clothe himself, for, when he was
arrayed in these magnificent garments, and sat contemplating
himself, he muttered, "Surely, 'tis all a dream, and a trick of the Evil
One." This thought was heavy upon him when a memluk entered. "O
Prince of the Faithful!" he said, "the 208 __^ ' ¥ ' -V- ' /" *.i. ^*" V\*
*•** "** .!• V? t 1
The text on this page is estimated to be only 28.61%
accurate

Abu-1-Hasan orders that the Sheiks of the district should be


taken to be impaled on the back of a mangy camel. Page 209
The text on this page is estimated to be only 25.00%
accurate

i
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like