Writing a C Compiler Build a Real Programming Language from Scratch Nora Sandler
Writing a C Compiler Build a Real Programming Language from Scratch Nora Sandler
Writing a C Compiler Build a Real Programming Language from Scratch Nora Sandler
Writing a C Compiler Build a Real Programming Language from Scratch Nora Sandler
Writing a C Compiler Build a Real Programming Language from Scratch Nora Sandler
1.
Instant Ebook Access,One Click Away – Begin at ebookgate.com
Writing a C Compiler Build a Real Programming
Language from Scratch Nora Sandler
https://ebookgate.com/product/writing-a-c-compiler-build-a-
real-programming-language-from-scratch-nora-sandler/
OR CLICK BUTTON
DOWLOAD EBOOK
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Click here to visit ebookgate.com and download ebook now
2.
Instant digital products(PDF, ePub, MOBI) available
Download now and explore formats that suit you...
Build Your Own NET Language and Compiler 1st Edition
Edward G. Nilges (Auth.)
https://ebookgate.com/product/build-your-own-net-language-and-
compiler-1st-edition-edward-g-nilges-auth/
ebookgate.com
Head First C 2E A Learner s Guide to Real World
Programming with Visual C and NET Second Edition Andrew
Stellman
https://ebookgate.com/product/head-first-c-2e-a-learner-s-guide-to-
real-world-programming-with-visual-c-and-net-second-edition-andrew-
stellman/
ebookgate.com
Programming C 12 Build Cloud Web and Desktop Applications
1st Edition Ian Griffiths
https://ebookgate.com/product/programming-c-12-build-cloud-web-and-
desktop-applications-1st-edition-ian-griffiths/
ebookgate.com
Microcontrollers From Assembly Language to C Using the
PIC24 Family 2nd Edition Bryan A. Jones
https://ebookgate.com/product/microcontrollers-from-assembly-language-
to-c-using-the-pic24-family-2nd-edition-bryan-a-jones/
ebookgate.com
3.
Microsoft Visual C2005 Express Edition Build a Program
Now Patrice Pelland
https://ebookgate.com/product/microsoft-visual-c-2005-express-edition-
build-a-program-now-patrice-pelland/
ebookgate.com
Learn to Program with Scratch A Visual Introduction to
Programming with Games Art Science and Math 1st Edition
Majed Marji
https://ebookgate.com/product/learn-to-program-with-scratch-a-visual-
introduction-to-programming-with-games-art-science-and-math-1st-
edition-majed-marji/
ebookgate.com
Introduction to Compiler Construction in a Java World Bill
Campbell
https://ebookgate.com/product/introduction-to-compiler-construction-
in-a-java-world-bill-campbell/
ebookgate.com
A History of the English Language 5th Edition Albert C.
Baugh
https://ebookgate.com/product/a-history-of-the-english-language-5th-
edition-albert-c-baugh/
ebookgate.com
From Scratch Writings in Music Theory 1st Edition Edition
James Tenney
https://ebookgate.com/product/from-scratch-writings-in-music-
theory-1st-edition-edition-james-tenney/
ebookgate.com
6.
CONTENTS IN DETAIL
1.TITLE PAGE
2. COPYRIGHT
3. DEDICATION
4. ABOUT THE AUTHOR AND TECHNICAL REVIEWER
5. ACKNOWLEDGMENTS
6. INTRODUCTION
7.
Who This Book Is For
8.
Why Write a C Compiler?
9.
Compilation from 10,000 Feet
10.
What You’ll Build
11.
How to Use This Book
12.
The Test Suite
13.
Extra Credit Features
14.
Some Advice on Choosing an Implementation Language
15.
System Requirements
16.
Installing GCC and GDB on Linux
17.
Installing the Command Line Developer Tools on macOS
18.
Running on Apple Silicon
19.
Validating Your Setup
20.
Additional Resources
21.
Let’s Go!
7.
22. PART I:THE BASICS
23. 1
A MINIMAL COMPILER
24.
The Four Compiler Passes
25.
Hello, Assembly!
26.
The Compiler Driver
27.
The Lexer
28.
The Parser
29.
An Example Abstract Syntax Tree
30.
The AST Definition
31.
The Formal Grammar
32.
Recursive Descent Parsing
33.
Assembly Generation
34.
Code Emission
35.
Summary
36.
Additional Resources
37. 2
UNARY OPERATORS
38.
Negation and Bitwise Complement in Assembly
39.
The Stack
40.
The Lexer
41.
The Parser
42.
TACKY: A New Intermediate Representation
43.
Defining TACKY
8.
44.
Generating TACKY
45.
Generating Namesfor Temporary Variables
46.
Updating the Compiler Driver
47.
Assembly Generation
48.
Converting TACKY to Assembly
49.
Replacing Pseudoregisters
50.
Fixing Up Instructions
51.
Code Emission
52.
Summary
53.
Additional Resources
54. 3
BINARY OPERATORS
55.
The Lexer
56.
The Parser
57.
The Trouble with Recursive Descent Parsing
58.
The Adequate Solution: Refactoring the Grammar
59.
The Better Solution: Precedence Climbing
60.
Precedence Climbing in Action
61.
TACKY Generation
62.
Assembly Generation
63.
Doing Arithmetic in Assembly
64.
Converting Binary Operations to Assembly
65.
Replacing Pseudoregisters
66.
Fixing Up the idiv, add, sub, and imul Instructions
9.
67.
Code Emission
68.
Extra Credit:Bitwise Operators
69.
Summary
70.
Additional Resources
71. 4
LOGICAL AND RELATIONAL OPERATORS
72.
Short-Circuiting Operators
73.
The Lexer
74.
The Parser
75.
TACKY Generation
76.
Adding Jumps, Copies, and Comparisons to the TACKY IR
77.
Converting Short-Circuiting Operators to TACKY
78.
Generating Labels
79.
Comparisons and Jumps in Assembly
80.
Comparisons and Status Flags
81.
Conditional Set Instructions
82.
Jump Instructions
83.
Assembly Generation
84.
Replacing Pseudoregisters
85.
Fixing Up the cmp Instruction
86.
Code Emission
87.
Summary
88.
Additional Resources
10.
89. 5
LOCAL VARIABLES
90.
Variables,Declarations, and Assignment
91.
The Lexer
92.
The Parser
93.
The Updated AST and Grammar
94.
An Improved Precedence Climbing Algorithm
95.
Semantic Analysis
96.
Variable Resolution
97.
The --validate Option
98.
TACKY Generation
99.
Variable and Assignment Expressions
00.
Declarations, Statements, and Function Bodies
01.
Functions with No return Statement
02.
Extra Credit: Compound Assignment, Increment, and Decrement
03.
Summary
04. 6
IF STATEMENTS AND CONDITIONAL EXPRESSIONS
05.
The Lexer
06.
The Parser
07.
Parsing if Statements
08.
Parsing Conditional Expressions
09.
Variable Resolution
10.
TACKY Generation
11.
11.
Converting if Statementsto TACKY
12.
Converting Conditional Expressions to TACKY
13.
Extra Credit: Labeled Statements and goto
14.
Summary
15. 7
COMPOUND STATEMENTS
16.
The Scoop on Scopes
17.
The Parser
18.
Variable Resolution
19.
Resolving Variables in Multiple Scopes
20.
Updating the Variable Resolution Pseudocode
21.
TACKY Generation
22.
Summary
23. 8
LOOPS
24.
Loops and How to Escape Them
25.
The Lexer
26.
The Parser
27.
Semantic Analysis
28.
Extending Variable Resolution
29.
Loop Labeling
30.
Implementing Loop Labeling
31.
TACKY Generation
32.
break and continue Statements
12.
33.
do Loops
34.
while Loops
35.
forLoops
36.
Extra Credit: switch Statements
37.
Summary
38. 9
FUNCTIONS
39.
Declaring, Defining, and Calling Functions
40.
Declarations and Definitions
41.
Function Calls
42.
Identifier Linkage
43.
Compiling Libraries
44.
The Lexer
45.
The Parser
46.
Semantic Analysis
47.
Extending Identifier Resolution
48.
Writing the Type Checker
49.
TACKY Generation
50.
Assembly Generation
51.
Understanding Calling Conventions
52.
Calling Functions with the System V ABI
53.
Converting Function Calls and Definitions to Assembly
54.
Replacing Pseudoregisters
55.
Allocating Stack Space During Instruction Fix-Up
13.
56.
Code Emission
57.
Calling LibraryFunctions
58.
Summary
59. 10
FILE SCOPE VARIABLE DECLARATIONS AND
STORAGE-CLASS SPECIFIERS
60.
All About Declarations
61.
Scope
62.
Linkage
63.
Storage Duration
64.
Definitions vs. Declarations
65.
Error Cases
66.
Linkage and Storage Duration in Assembly
67.
The Lexer
68.
The Parser
69.
Parsing Type and Storage-Class Specifiers
70.
Distinguishing Between Function and Variable Declarations
71.
Semantic Analysis
72.
Identifier Resolution: Resolving External Variables
73.
Type Checking: Tracking Static Functions and Variables
74.
TACKY Generation
75.
Assembly Generation
76.
Generating Assembly for Variable Definitions
77.
Replacing Pseudoregisters According to Their Storage Duration
14.
78.
Fixing Up Instructions
79.
CodeEmission
80.
Summary
81. PART II: TYPES BEYOND INT
82. 11
LONG INTEGERS
83.
Long Integers in Assembly
84.
Type Conversions
85.
Static Long Variables
86.
The Lexer
87.
The Parser
88.
Semantic Analysis
89.
Adding Type Information to the AST
90.
Type Checking Expressions
91.
Type Checking return Statements
92.
Type Checking Declarations and Updating the Symbol Table
93.
TACKY Generation
94.
Tracking the Types of Temporary Variables
95.
Generating Extra Return Instructions
96.
Assembly Generation
97.
Tracking Assembly Types in the Backend Symbol Table
98.
Replacing Longword and Quadword Pseudoregisters
99.
Fixing Up Instructions
00.
Code Emission
15.
01.
Summary
02. 12
UNSIGNED INTEGERS
03.
TypeConversions, Again
04.
Converting Between Signed and Unsigned Types of the Same Size
05.
Converting unsigned int to a Larger Type
06.
Converting signed int to a Larger Type
07.
Converting from Larger to Smaller Types
08.
The Lexer
09.
The Parser
10.
The Type Checker
11.
TACKY Generation
12.
Unsigned Integer Operations in Assembly
13.
Unsigned Comparisons
14.
Unsigned Division
15.
Zero Extension
16.
Assembly Generation
17.
Replacing Pseudoregisters
18.
Fixing Up the Div and MovZeroExtend Instructions
19.
Code Emission
20.
Summary
21. 13
FLOATING-POINT NUMBERS
22.
IEEE 754, What Is It Good For?
16.
23.
The IEEE 754Double-Precision Format
24.
Rounding Behavior
25.
Rounding Modes
26.
Rounding Constants
27.
Rounding Type Conversions
28.
Rounding Arithmetic Operations
29.
Linking Shared Libraries
30.
The Lexer
31.
Recognizing Floating-Point Constant Tokens
32.
Matching the End of a Constant
33.
The Parser
34.
The Type Checker
35.
TACKY Generation
36.
Floating-Point Operations in Assembly
37.
Working with SSE Instructions
38.
Using Floating-Point Values in the System V Calling Convention
39.
Doing Arithmetic with SSE Instructions
40.
Comparing Floating-Point Numbers
41.
Converting Between Floating-Point and Integer Types
42.
Assembly Generation
43.
Floating-Point Constants
44.
Unary Instructions, Binary Instructions, and Conditional Jumps
45.
Type Conversions
46.
Function Calls
17.
47.
Return Instructions
48.
The CompleteConversion from TACKY to Assembly
49.
Pseudoregister Replacement
50.
Instruction Fix-Up
51.
Code Emission
52.
Formatting Floating-Point Numbers
53.
Labeling Floating-Point Constants
54.
Storing Constants in the Read-Only Data Section
55.
Initializing Static Variables to 0.0 or –0.0
56.
Putting It All Together
57.
Extra Credit: NaN
58.
Summary
59.
Additional Resources
60. 14
POINTERS
61.
Objects and Values
62.
Operations on Pointers
63.
Address and Dereference Operations
64.
Null Pointers and Type Conversions
65.
Pointer Comparisons
66.
& Operations on Dereferenced Pointers
67.
The Lexer
68.
The Parser
69.
Parsing Declarations
18.
70.
Parsing Type Names
71.
PuttingIt All Together
72.
Semantic Analysis
73.
Type Checking Pointer Expressions
74.
Tracking Static Pointer Initializers in the Symbol Table
75.
TACKY Generation
76.
Pointer Operations in TACKY
77.
A Strategy for TACKY Conversion
78.
Assembly Generation
79.
Replacing Pseudoregisters with Memory Operands
80.
Fixing Up the lea and push Instructions
81.
Code Emission
82.
Summary
83. 15
ARRAYS AND POINTER ARITHMETIC
84.
Arrays and Pointer Arithmetic
85.
Array Declarations and Initializers
86.
Memory Layout of Arrays
87.
Array-to-Pointer Decay
88.
Pointer Arithmetic to Access Array Elements
89.
Even More Pointer Arithmetic
90.
Array Types in Function Declarations
91.
Things We Aren’t Implementing
92.
The Lexer
19.
93.
The Parser
94.
Parsing ArrayDeclarators
95.
Parsing Abstract Array Declarators
96.
Parsing Compound Initializers
97.
Parsing Subscript Expressions
98.
The Type Checker
99.
Converting Arrays to Pointers
00.
Validating Lvalues
01.
Type Checking Pointer Arithmetic
02.
Type Checking Subscript Expressions
03.
Type Checking Cast Expressions
04.
Type Checking Function Declarations
05.
Type Checking Compound Initializers
06.
Initializing Static Arrays
07.
Initializing Scalar Variables with ZeroInit
08.
TACKY Generation
09.
Pointer Arithmetic
10.
Subscripting
11.
Compound Initializers
12.
Tentative Array Definitions
13.
Assembly Generation
14.
Converting TACKY to Assembly
15.
Replacing PseudoMem Operands
16.
Fixing Up Instructions
20.
17.
Code Emission
18.
Summary
19. 16
CHARACTERSAND STRINGS
20.
Character Traits
21.
String Literals
22.
Working with Strings in Assembly
23.
The Lexer
24.
The Parser
25.
Parsing Type Specifiers
26.
Parsing Character Constants
27.
Parsing String Literals
28.
Putting It All Together
29.
The Type Checker
30.
Characters
31.
String Literals in Expressions
32.
String Literals Initializing Non-static Variables
33.
String Literals Initializing Static Variables
34.
TACKY Generation
35.
String Literals as Array Initializers
36.
String Literals in Expressions
37.
Top-Level Constants in TACKY
38.
Assembly Generation
39.
Operations on Characters
21.
40.
Top-Level Constants
41.
The CompleteConversion from TACKY to Assembly
42.
Pseudo-Operand Replacement
43.
Instruction Fix-Up
44.
Code Emission
45.
Hello Again, World!
46.
Summary
47. 17
SUPPORTING DYNAMIC MEMORY ALLOCATION
48.
The void Type
49.
Memory Management with void *
50.
Complete and Incomplete Types
51.
The sizeof Operator
52.
The Lexer
53.
The Parser
54.
The Type Checker
55.
Conversions to and from void *
56.
Functions with void Return Types
57.
Scalar and Non-scalar Types
58.
Restrictions on Incomplete Types
59.
Extra Restrictions on void
60.
Conditional Expressions with void Operands
61.
Existing Validation for Arithmetic Expressions and Comparisons
62.
sizeof Expressions
22.
63.
TACKY Generation
64.
Functions withvoid Return Types
65.
Casts to void
66.
Conditional Expressions with void Operands
67.
sizeof Expressions
68.
The Latest and Greatest TACKY IR
69.
Assembly Generation
70.
Summary
71. 18
STRUCTURES
72.
Declaring Structure Types
73.
Structure Member Declarations
74.
Tag and Member Namespaces
75.
Structure Type Declarations We Aren’t Implementing
76.
Operating on Structures
77.
Structure Layout in Memory
78.
The Lexer
79.
The Parser
80.
Semantic Analysis
81.
Resolving Structure Tags
82.
Type Checking Structures
83.
TACKY Generation
84.
Implementing the Member Access Operators
85.
Converting Compound Initializers to TACKY
23.
86.
Structures in theSystem V Calling Convention
87.
Classifying Structures
88.
Passing Parameters of Structure Type
89.
Returning Structures
90.
Assembly Generation
91.
Extending the Assembly AST
92.
Copying Structures
93.
Using Structures in Function Calls
94.
Putting It All Together
95.
Replacing Pseudo-operands
96.
Code Emission
97.
Extra Credit: Unions
98.
Summary
99.
Additional Resources
00. PART III: OPTIMIZATIONS
01. 19
OPTIMIZING TACKY PROGRAMS
02.
Safety and Observable Behavior
03.
Four TACKY Optimizations
04.
Constant Folding
05.
Unreachable Code Elimination
06.
Copy Propagation
07.
Dead Store Elimination
08.
With Our Powers Combined …
24.
09.
Testing the OptimizationPasses
10.
Wiring Up the Optimization Stage
11.
Constant Folding
12.
Constant Folding for Part I TACKY Programs
13.
Supporting Part II TACKY Programs
14.
Control-Flow Graphs
15.
Defining the Control-Flow Graph
16.
Creating Basic Blocks
17.
Adding Edges to the Control-Flow Graph
18.
Converting a Control-Flow Graph to a List of Instructions
19.
Making Your Control-Flow Graph Code Reusable
20.
Unreachable Code Elimination
21.
Eliminating Unreachable Blocks
22.
Removing Useless Jumps
23.
Removing Useless Labels
24.
Removing Empty Blocks
25.
A Little Bit About Data-Flow Analysis
26.
Copy Propagation
27.
Reaching Copies Analysis
28.
Rewriting TACKY Instructions
29.
Supporting Part II TACKY Programs
30.
Dead Store Elimination
31.
Liveness Analysis
32.
Removing Dead Stores
25.
33.
Supporting Part IITACKY Programs
34.
Summary
35.
Additional Resources
36. 20
REGISTER ALLOCATION
37.
Register Allocation in Action
38.
Take One: Put Everything on the Stack
39.
Take Two: Register Allocation
40.
Take Three: Register Allocation with Coalescing
41.
Updating the Compiler Pipeline
42.
Extending the Assembly AST
43.
Converting TACKY to Assembly
44.
Register Allocation by Graph Coloring
45.
Detecting Interference
46.
Spilling Registers
47.
The Basic Register Allocator
48.
Handling Multiple Types During Register Allocation
49.
Defining the Interference Graph
50.
Building the Interference Graph
51.
Calculating Spill Costs
52.
Coloring the Interference Graph
53.
Building the Register Map and Rewriting the Function Body
54.
Instruction Fix-Up with Callee-Saved Registers
55.
Code Emission
26.
56.
Register Coalescing
57.
Updating theInterference Graph
58.
Conservative Coalescing
59.
Implementing Register Coalescing
60.
Summary
61.
Additional Resources
62. NEXT STEPS
63.
Add Some Missing Features
64.
Handle Undefined Behavior Safely
65.
Write More TACKY Optimizations
66.
Support Another Target Architecture
67.
Contribute to an Open Source Programming Language Project
68.
That’s a Wrap!
69. A
DEBUGGING ASSEMBLY CODE WITH GDB OR LLDB
70.
The Program
71.
Debugging with GDB
72.
Configuring the GDB UI
73.
Starting and Stopping the Program
74.
Printing Expressions
75.
Examining Memory
76.
Setting Conditional Breakpoints
77.
Getting Help
78.
Debugging with LLDB
27.
79.
Starting and Stoppingthe Program
80.
Displaying Assembly Code
81.
Printing Expressions
82.
Examining Memory
83.
Setting Conditional Breakpoints
84.
Getting Help
85. B
ASSEMBLY GENERATION AND CODE EMISSION
TABLES
86.
Part I
87.
Converting TACKY to Assembly
88.
Code Emission
89.
Part II
90.
Converting TACKY to Assembly
91.
Code Emission
92.
Part III
93. REFERENCES
94. INDEX
28.
WRITING A CCOMPILER
Build a Real Programming
Language from Scratch
by Nora Sandler
San Francisco
Copyeditor: Rachel Head
Proofreader:Audrey Doyle
Indexer: BIM Creatives, LLC
Figure 13-1, courtesy of Codekaizen via Wikimedia Commons,
has been reproduced under CC BY-SA 4.0,
https://creativecommons.org/licenses/by-sa/4.0. The original
image has been converted to grayscale, and fonts have been
modified.
Library of Congress Control Number: 2023058768
For customer service inquiries, please contact
info@nostarch.com. For information on distribution, bulk sales,
corporate sales, or translations: sales@nostarch.com. For
permission to translate this work: rights@nostarch.com. To
report counterfeit copies or piracy: counterfeit@nostarch.com.
No Starch Press and the No Starch Press logo are registered
trademarks of No Starch Press, Inc. Other product and company
names mentioned herein may be the trademarks of their
respective owners. Rather than use a trademark symbol with
every occurrence of a trademarked name, we are using the
names only in an editorial fashion and to the benefit of the
31.
trademark owner, withno intention of infringement of the
trademark.
The information in this book is distributed on an “As Is” basis,
without warranty. While every precaution has been taken in
the preparation of this work, neither the author nor No Starch
Press, Inc. shall have any liability to any person or entity with
respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in it.
About the Author
NoraSandler is a software engineer based in Seattle. She holds
a BS in computer science from the University of Chicago, where
she researched the implementation of parallel programming
languages. After several years as a penetration tester, she found
her way back to compilers. Most recently, she worked on
domain-specific languages at an endpoint security company.
You can read her blog about pranks, compilers, and other
computer science topics at https://norasandler.com.
About the Technical Reviewer
Stephen Kell is a researcher, educator, and consultant on the
design and implementation of programming languages and
systems. He has taught compilers and C programming in
various settings over the past 12 years, served on an ISO study
group on the evolution of the C language specification, and
published numerous research papers on the specification,
design, and implementation of C and its linking and debugging
tools. These continue to be a focus of the research that he leads
as an academic at King’s College London.
34.
ACKNOWLEDGMENTS
I was attendingthe Recurse Center in fall 2017 when I started
on the series of blog posts that eventually turned into this book.
I’m immensely grateful to the Recurse Center for giving me the
time and space to follow my own curiosity, in a community of
kind, brilliant people, without the pressure to produce
anything. Without them, I would never have attempted this
project.
I’m also grateful to everyone in the Recurse Center community
whose advice, encouragement, and pair programming sessions
shaped those initial blog posts. I’d particularly like to thank
Julian Squires for pointing me toward Abdulaziz Ghuloum’s “An
Incremental Approach to Compiler Construction,” the article
that served as the starting point for this project. I’d also like to
thank Raph Levien for teaching me about the precedence
climbing method for expression parsing.
Thanks to Stephen Kell, this book’s technical reviewer, whose
thoughtful comments made the book clearer and more
accurate. I’m particularly indebted to Stephen for undertaking
the monumental task of reviewing the accompanying test suite
and reference implementation. Alex Freed, who first reached
35.
out to meabout writing a book, provided invaluable editorial
guidance and encouragement, and Jill Franklin and Eva
Morrow shepherded the book through the final stages of
editing. James L. Barry provided the fabulous cover art. Thanks
also to Sydney Cromwell for overseeing the production process,
Rachel Head for copyediting, and the entire team at No Starch
Press for their hard work making this book a reality.
Thanks to all the readers who emailed me and filed GitHub
issues about earlier versions of this project, including the
original blog posts and Early Access version. Their suggestions
made the book better, and their enthusiasm for compilers
reminded me why I was writing it.
Thank you to my friend Haney Maxwell for his thorough,
insightful feedback on Chapter 13.
Last but never least, thanks to my partner, Brian, whose sound
advice and ear for language I often relied on, who gamely
agreed to “read this one paragraph and tell me whether it
makes sense” whenever I asked, and who has always supported
and believed in me.
36.
INTRODUCTION
When we talkabout how programming languages
work, we tend to borrow metaphors from fantasy
novels: compilers are magic, and the people who
work on them are wizards. Dragons may be
involved somehow. But in the day-to-day lives of
most programmers, compilers behave less like
magical artifacts and more like those universal translator
earpieces from science fiction. They aren’t flashy or dramatic;
they don’t demand a lot of attention. They just hum along in the
background, translating a language you speak (or type) fluently
into the alien language of machines.
For some reason, sci-fi characters rarely seem to wonder how
their translators work. But once you’ve been coding for a while,
it’s hard not to feel curious about what your compiler is doing.
A few years ago, this curiosity got the better of me, so I decided
to learn more about compilers by writing one of my own. It was
important to me to write a compiler for a real programming
language, one that I’d used myself. And I wanted my compiler to
generate assembly code that I could run without an emulator or
virtual machine. But when I looked around, I found that most
guides to compiler construction used toy languages that ran on
37.
idealized processors. Someof these guides were excellent, but
they weren’t quite what I was looking for.
I finally got unstuck when a friend pointed me toward a short
paper titled “An Incremental Approach to Compiler
Construction” by Abdulaziz Ghuloum (http://scheme2006.cs
.uchicago.edu/11-ghuloum.pdf). It explained how to compile
Scheme to x86 assembly, starting with the simplest possible
programs and adding one new language construct at a time. I
didn’t particularly want to write a compiler for Scheme, so I
adapted the paper to a language I was more interested in: C. As
I kept working on the project, I switched from x86 to its modern
counterpart, x64 assembly. I also built out support for a larger
subset of C and added a few optimization passes. By this point, I
had gone way beyond Ghuloum’s original scheme (pun
intended, sorry), but his basic strategy held up remarkably well:
focusing on one small piece of the language at a time made it
easy to stay on track and see that I was making progress. In this
book, you’ll tackle the same project. Along the way, you’ll gain a
deeper understanding of the code you write and the system it
runs on.
38.
Who This BookIs For
I wrote this book for programmers who are curious about how
compilers work. Many books about compiler construction are
written as textbooks for college or graduate-level classes, but
this one is meant to be accessible to someone exploring the
topic on their own. You won’t need any prior knowledge of
compilers, interpreters, or assembly code to complete this
project. A basic understanding of computer architecture is
helpful, but not essential; I’ll discuss important concepts as they
come up and occasionally point you to outside resources with
more background information. That said, this is not a book for
novice programmers. You should be comfortable writing
substantive programs on your own, and you should be familiar
with binary numbers, regular expressions, and basic data
structures like graphs and trees. You’ll need to know C well
enough to read and understand small C programs, but you don’t
need to be an expert C programmer. We’ll explore the ins and
outs of the language as we go.
Although this book is geared toward newcomers to the subject,
it will also be worthwhile for people who have some experience
with compilers already. Maybe you implemented a toy language
for a college class or personal project, and now you’d like to
work on something more realistic. Or maybe you’ve worked on
39.
interpreters in thepast, and you want to try your hand at
compiling programs down to machine code. If you’re in this
category, this book will cover some material you already know,
but it will provide plenty of new challenges too. At the very
least, I promise you’ll learn a few things about C.
Why Write a C Compiler?
I assume you’re already sold on the idea of writing a compiler—
you did pick up this book, after all. I want to talk a little bit
about why we’re writing a compiler for C in particular. The
short answer is that C is a (relatively) simple language, but not a
toy language. At its core, C is simple enough to implement even
if you’ve never written a compiler before. But it’s also a
particularly clear example of how programming languages are
shaped by the systems they run on and the people who use
them. Some aspects of C vary based on what hardware you’re
targeting; others vary between operating systems; still others
are left unspecified to give compiler writers more flexibility.
Some bits of the language are historical artifacts that have stuck
around to support legacy code, while others are more recent
attempts to make C safer and more reliable.
These messy parts of C are worth tackling for a couple of
reasons. First, you’ll develop a solid mental model of how your
40.
compiler fits inwith all the other pieces of your system. Second,
you’ll get a sense of the different perspectives that different
groups of people bring to the language, from the specification
authors trying to stamp out ambiguity and inconsistency, to
compiler implementers looking for performance
improvements, to ordinary programmers who just want their
code to work.
I hope this project will make you think about all programming
languages differently: not as fixed sets of rules enshrined in
language standards, but as ongoing negotiations between the
people who design, implement, and use them. Once you start
looking at programming languages this way, they become
richer, more interesting, and less frustrating to work with.
Compilation from 10,000 Feet
Before we go any further, let’s take a high-level look at how
source code turns into an executable and where the compiler
fits into the process. We’ll clear up some terminology and
review a tiny bit of computer architecture while we’re at it. A
compiler is a program that translates code from one
programming language to another. It’s just one part (though
often the most complex part) of the whole system that’s
responsible for getting your code up and running. We’re going
41.
to build acompiler that translates C programs into assembly
code, a textual representation of the instructions we want the
processor to run.
Different processors understand different instructions; we’ll
focus on the x64 instruction set, also called x86-64 or AMD64.
This is what most people’s computers run. (The other
instruction set you’re likely to encounter is ARM. Most
smartphones and tablets have ARM processors, and they’re
starting to show up in laptops too.)
The processor doesn’t understand text, so it can’t run our
assembly code as is. We need to convert it into object code, or
binary instructions that the processor can decode and execute.
For example, the assembly instruction ret corresponds to the
byte 0xc3. The assembler handles this conversion, taking in
assembly programs and spitting out object files. Finally, the
linker combines all the object files we need to include in our
final program, resolves any references to variables or functions
from other files, and adds some information about how to
actually start up the program. The end result is an executable
that we can run. This is a wildly oversimplified view of what
happens, but it’s good enough to get us started.
42.
Aside from thecompiler, assembler, and linker, compiling a C
program requires yet another tool: the preprocessor, which
runs right before the compiler. The preprocessor strips out
comments, executes preprocessor directives like #include, and
expands macros to produce preprocessed code that’s ready to
be compiled. The whole process looks something like Figure 1.
Figure 1: Transforming a source file into an executable Description
When you compile a program with a command like gcc or
clang, you’re actually invoking the compiler driver, a small
wrapper that’s responsible for calling the preprocessor,
compiler, assembler, and linker in turn. You’ll write your own
compiler and compiler driver, but you won’t write your own
preprocessor, assembler, or linker. Instead, you’ll use the
versions of these tools already installed on your system.
43.
What You’ll Build
Overthe course of this book, you’ll build a compiler for a large
subset of C. You can write your compiler in any programming
language you like; I’ll present key parts of the implementation
in pseudocode. The book is organized into three parts. In Part I,
The Basics, you’ll implement the core features of C: expressions,
variables, control-flow statements, and function calls.
Chapter 1: A Minimal Compiler In this chapter, you’ll build a
working compiler that can handle the simplest possible C
programs, which just return integer constants. You’ll learn
about the different stages of compilation, how to represent a C
program internally as an abstract syntax tree, and how to read
simple assembly programs.
Chapter 2: Unary Operators Next, you’ll start to expand your
compiler by implementing two unary operators: negation and
bitwise complement. This chapter introduces TACKY, a new
intermediate representation that bridges the gap between the
abstract syntax tree and assembly code. It also explains how to
perform negation and bitwise complement in assembly, and
how assembly programs store values in a region of memory
called the stack.
44.
Chapter 3: BinaryOperators In this chapter, you’ll
implement the binary operators that perform basic arithmetic,
like addition and subtraction. You’ll use a technique called
precedence climbing to parse arithmetic expressions with the
correct associativity and precedence, and you’ll learn how to do
arithmetic in assembly.
Chapter 4: Logical and Relational Operators Here, you’ll
add support for the logical AND, OR, and NOT operators and
relational operators like >, ==, and !=. This chapter introduces
several new kinds of assembly instructions, including
conditional instructions and jumps.
Chapter 5: Local Variables Next, you’ll extend your compiler
to support local variable declarations, uses, and assignments.
You’ll add a new compiler stage to perform semantic analysis in
this chapter. This stage detects programming errors like using
an undeclared variable.
Chapter 6: if Statements and Conditional Expressions In
this chapter, you’ll add support for if statements, your
compiler’s first control-flow structure, as well as conditional
expressions of the form a ? b : c. Using TACKY as an
intermediate representation will pay off here; you can
45.
implement both languageconstructs with existing TACKY
instructions, so you won’t need to touch later compiler stages.
Chapter 7: Compound Statements Here, you’ll add support
for compound statements, which group together statements
and declarations and control the scope of identifiers. You’ll take
a close look at C’s scoping rules and learn how to apply those
rules during semantic analysis.
Chapter 8: Loops This chapter covers while, do, and for
loops, as well as break and continue statements. You’ll write a
new semantic analysis pass to associate break and continue
statements with their enclosing loops.
Chapter 9: Functions In this chapter, you’ll implement
function calls and declarations of functions other than main.
You’ll have two major tasks here: writing a type checker to
detect semantic errors like calling functions with the wrong
number of arguments, and generating assembly code. You’ll
learn all the ins and outs of the calling conventions for Unix-like
systems, which dictate how function calls work in assembly. By
meticulously following these conventions, you’ll be able to
compile code that calls external libraries.
46.
Chapter 10: FileScope Variable Declarations and Storage-
Class Specifiers Next, you’ll add support for file scope
variable declarations and the extern and static specifiers. This
chapter discusses several properties of C identifiers, including
linkage and storage duration. It walks through how to
determine an identifier’s linkage and storage duration in the
semantic analysis stage and covers how those properties impact
the assembly you ultimately generate. It also introduces a new
region of memory, the data section, and describes how to define
and operate on values stored there.
In Part II, Types Beyond int, you’ll implement additional types.
This is where we’ll take the most in-depth look at the messy,
confusing, and surprising bits of C.
Chapter 11: Long Integers In this chapter, you’ll implement
the long type and lay the groundwork to add more types in
later chapters. You’ll learn how to infer the type of every
expression during type checking and how to operate on values
of different sizes in assembly.
Chapter 12: Unsigned Integers Here, you’ll implement the
unsigned integer types. This chapter dives into the C standard’s
rules on integer type conversions and covers a few new
47.
assembly instructions thatperform unsigned integer
operations.
Chapter 13: Floating-Point Numbers Next, you’ll add the
floating-point double type. This chapter describes the binary
representation of floating-point numbers and the perils of
floating-point rounding error. It introduces a new set of
assembly instructions for performing floating-point operations
and explains the calling conventions for passing floating-point
arguments and return values.
Chapter 14: Pointers In this chapter, you’ll implement pointer
types and the address and pointer dereference operators. You’ll
validate pointer operations in the type checker and add explicit
memory access instructions to the TACKY intermediate
representation.
Chapter 15: Arrays and Pointer Arithmetic This chapter
picks up where Chapter 14 left off by adding support for array
types and several related language features: the subscript
operator, pointer arithmetic, and compound initializers. It digs
into the relationship between arrays and pointers and lays out
how the type checker should analyze these types.
48.
Chapter 16: Charactersand Strings This chapter covers the
character types, character constants, and string literals. You’ll
learn about the different ways C programs use string literals,
and you’ll add new TACKY and assembly constructs to represent
string constants. At the end of the chapter, you’ll compile a
couple of example programs that perform input/output (I/O)
operations.
Chapter 17: Supporting Dynamic Memory Allocation In this
chapter, you’ll implement the void type and sizeof operator,
which will allow you to compile programs that call malloc and
the other memory management functions. The biggest
challenge here is handling void in the type checker. Because
void is a type with no values, the type checker will treat it very
differently from the other types you’ve implemented so far.
Chapter 18: Structures Structures, along with the . and ->
member access operators, are the last language features you’ll
add in this book. To implement them, you’ll need all the skills
you learned in earlier chapters. In the semantic analysis stage,
you’ll resolve structure tags according to C’s scoping rules and
analyze structure type declarations to determine how they’re
laid out in memory. When you generate TACKY, you’ll translate
member access operators into sequences of simple memory
access instructions. And when you generate assembly, you’ll
49.
follow the callingconventions for passing structures as
arguments and return values.
In Part III, Optimizations, you won’t add any new language
features. Instead, you’ll implement several classic compiler
optimizations to generate more efficient assembly code. Part III
is quite different from Parts I and II because these
optimizations aren’t specific to C; they work just as well for
programs written in any language.
Chapter 19: Optimizing TACKY Programs In this chapter,
you’ll add an optimization stage targeting TACKY programs.
This stage will include four different optimizations: constant
folding, unreachable code elimination, dead store elimination,
and copy propagation. These four optimizations work together,
making each one more effective than it would be by itself. This
chapter introduces several tools for understanding a program’s
behavior, including control-flow graphs and data-flow analysis.
You’ll use these tools to discover ways to optimize programs
without changing their behavior.
Chapter 20: Register Allocation To cap off this project, you’ll
write a register allocator, which figures out how to store values
in the assembly program in registers instead of memory. You’ll
use graph coloring to find a valid mapping from values to
gods will notbe angry with him.” The gods, it seems, could not
pardon the inquisitive mortal who deliberately pried into their
secrets. Amidst the ornaments with which Athens was decorated
during the free working of her democracy, the glories of Marathon of
course occupied a conspicuous place. The battle was painted on one
of the compartments of the portico called Pœkilê, wherein, amidst
several figures of gods and heroes,—Athênê, Hêraklês, Theseus,
Echetlus, and the local patron of Marathon,—were seen honored and
prominent the polemarch Kallimachus and the general Miltiadês,
while the Platæans were distinguished by their Bœotian leather
casques.[671] And the sixth of the month Boëdromion, the
anniversary of the battle, was commemorated by an annual
ceremony, even down to the time of Plutarch.[672]
Two thousand Spartans, starting from their city, immediately after
the full moon, reached the frontier of Attica, on the third day of their
march,—a surprising effort, when we consider that the total distance
from Sparta to Athens was about one hundred and fifty miles. They
did not arrive, however, until the battle had been fought, and the
Persians departed; but curiosity led them to the field of Marathon to
behold the dead bodies of the Persians, after which they returned
home, bestowing well-merited praise on the victors.
Datis and Artaphernês returned across the Ægean with their
Eretrian prisoners to Asia; stopping for a short time at the island of
Mykonos, where discovery was made of a gilt image of Apollo carried
off as booty in a Phenician ship. Datis went himself to restore it to
Dêlos, requesting the Delians to carry it back to the Delium, or
temple of Apollo, on the eastern coast of Bœotia: the Delians,
however, chose to keep the statue until it was reclaimed from them
twenty years afterwards by the Thebans. On reaching Asia, the
Persian generals conducted their prisoners up to the court of Susa,
and into the presence of Darius. Though he had been vehemently
incensed against them, yet when he saw them in his power, his
wrath abated, and he manifested no desire to kill or harm them.
They were planted at a spot called Arderikka, in the Kissian territory,
52.
one of theresting-places on the road from Sardis to Susa, and about
twenty-six miles distant from the latter place: Herodotus seems
himself to have seen their descendants there on his journey between
the two capitals, and to have had the satisfaction of talking to them
in Greek,—which we may well conceive to have made some
impression upon him, at a spot distant by nearly three months’
journey from the coast of Ionia.[673]
Happy would it have been for Miltiadês if he had shared the
honorable death of the polemarch Kallimachus,—“animam exhalasset
opimam,”—in seeking to fire the ships of the defeated Persians at
Marathon. The short sequel of his history will be found in melancholy
contrast with the Marathonian heroism.
His reputation had been great before the battle, and after it the
admiration and confidence of his countrymen knew no bounds: it
appears, indeed, to have reached such a pitch that his head was
turned, and he lost both his patriotism and his prudence. He
proposed to his countrymen to incur the cost of equipping an
armament of seventy ships, with an adequate armed force, and to
place it altogether at his discretion; giving them no intimation
whither he intended to go, but merely assuring them that, if they
would follow him, he would conduct them to a land where gold was
abundant, and thus enrich them. Such a promise, from the lips of
the recent victor of Marathon, was sufficient, and the armament was
granted, no man except Miltiadês knowing what was its destination.
He sailed immediately to the island of Paros, laid siege to the town,
and sent in a herald to require from the inhabitants a contribution of
one hundred talents, on pain of entire destruction. His pretence for
this attack was, that the Parians had furnished a trireme to Datis for
the Persian fleet at Marathon; but his real motive, so Herodotus
assures us,[674] was vindictive animosity against a Parian citizen
named Lysagoras, who had exasperated the Persian general
Hydarnês against him. The Parians amused him at first with
evasions, until they had procured a little delay to repair the defective
portions of their wall, after which they set him at defiance; and
53.
Miltiadês in vainprosecuted hostilities against them for the space of
twenty-six days: he ravaged the island, but his attacks made no
impression upon the town.[675] Beginning to despair of success in his
military operations, he entered into some negotiation—such at least
was the tale of the Parians themselves—with a Parian woman named
Timô, priestess or attendant in the temple of Dêmêtêr, near the
town-gates. This woman, promising to reveal to him a secret which
would place Paros in his power, induced him to visit by night a
temple to which no male person was admissible. He leaped the
exterior fence, and approached the sanctuary; but on coming near,
was seized with a panic terror and ran away, almost out of his
senses: on leaping the same fence to get back, he strained or
bruised his thigh badly, and became utterly disabled. In this
melancholy state he was placed on ship-board; the siege being
raised, and the whole armament returning to Athens.
Vehement was the indignation both of the armament and of the
remaining Athenians against Miltiadês on his return;[676] and
Xanthippus, father of the great Periklês, became the spokesman of
this feeling. He impeached Miltiadês before the popular judicature as
having been guilty of deceiving the people, and as having deserved
the penalty of death. The accused himself, disabled by his injured
thigh, which even began to show symptoms of gangrene, was
unable to stand, or to say a word in his own defence: he lay on his
couch before the assembled judges, while his friends made the best
case they could in his behalf. Defence, it appears, there was none;
all they could do, was to appeal to his previous services: they
reminded the people largely and emphatically of the inestimable
exploit of Marathon, coming in addition to his previous conquest of
Lemnos. The assembled dikasts, or jurors, showed their sense of
these powerful appeals by rejecting the proposition of his accuser to
condemn him to death; but they imposed on him the penalty of fifty
talents “for his iniquity.”
Cornelius Nepos affirms that these fifty talents represented the
expenses incurred by the state in fitting out the armament; but we
54.
may more probablybelieve, looking to the practice of the Athenian
dikastery in criminal cases, that fifty talents was the minor penalty
actually proposed by the defenders of Miltiadês themselves, as a
substitute for the punishment of death. In those penal cases at
Athens, where the punishment was not fixed beforehand by the
terms of the law, if the person accused was found guilty, it was
customary to submit to the jurors, subsequently and separately, the
question as to amount of punishment: first, the accuser named the
penalty which he thought suitable; next, the accused person was
called upon to name an amount of penalty for himself, and the jurors
were constrained to take their choice between these two,—no third
gradation of penalty being admissible for consideration.[677] Of
course, under such circumstances, it was the interest of the accused
party to name, even in his own case, some real and serious penalty,
—something which the jurors might be likely to deem not wholly
inadequate to his crime just proved; for if he proposed some penalty
only trifling, he drove them to prefer the heavier sentence
recommended by his opponent. Accordingly, in the case of Miltiadês,
his friends, desirous of inducing the jurors to refuse their assent to
the punishment of death, proposed a fine of fifty talents as the self-
assessed penalty of the defendant; and perhaps they may have
stated, as an argument in the case, that such a sum would suffice to
defray the costs of the expedition. The fine was imposed, but
Miltiadês did not live to pay it; his injured limb mortified, and he
died, leaving the fine to be paid by his son Kimon.
According to Cornelius Nepos, Diodorus, and Plutarch, he was
put in prison, after having been fined, and there died.[678] But
Herodotus does not mention this imprisonment, and the fact appears
to me improbable: he would hardly have omitted to notice it, had it
come to his knowledge. Immediate imprisonment of a person fined
by the dikastery, until his fine was paid, was not the natural and
ordinary course of Athenian procedure, though there were particular
cases in which such aggravation was added. Usually, a certain time
was allowed for payment,[679] before absolute execution was
resorted to, but the person under sentence became disfranchised
55.
and excluded fromall political rights, from the very instant of his
condemnation as a public debtor, until the fine was paid. Now in the
instance of Miltiadês, the lamentable condition of his wounded thigh
rendered escape impossible,—so that there would be no special
motive for departing from the usual practice, and imprisoning him
forthwith: moreover, if he was not imprisoned forthwith, he would
not be imprisoned at all, since he cannot have lived many days after
his trial.[680] To carry away the suffering general in his couch,
incapable of raising himself even to plead for his own life, from the
presence of the dikasts to a prison, would not only have been a
needless severity, but could hardly have failed to imprint itself on the
sympathies and the memory of all the beholders; so that Herodotus
would have been likely to hear and mention it, if it had really
occurred. I incline to believe therefore that Miltiadês died at home:
all accounts concur in stating that he died of the mortal bodily hurt
which already disabled him even at the moment of his trial, and that
his son Kimon paid the fifty talents after his death. If he could pay
them, probably his father could have paid them also. And this is an
additional reason for believing that there was no imprisonment,—for
nothing but non-payment could have sent him to prison; and to
rescue the suffering Miltiadês from being sent thither, would have
been the first and strongest desire of all sympathizing friends.
Thus closed the life of the conqueror of Marathon. The last act of
it produces an impression so mournful, and even shocking,—his
descent from the pinnacle of glory to defeat, mean tampering with a
temple-servant, mortal bodily hurt, undefended ignominy, and death
under a sentence of heavy fine, is so abrupt and unprepared,—that
readers, ancient and modern, have not been satisfied without finding
some one to blame for it: we must except Herodotus, our original
authority, who recounts the transaction without dropping a single
hint of blame against any one. To speak ill of the people, as
Machiavel has long ago observed,[681] is a strain in which every one
at all times, even under a democratical government, indulges with
impunity and without provoking any opponent to reply; and in this
instance, the hard fate of Miltiadês has been imputed to the vices of
56.
the Athenians andtheir democracy,—it has been cited in proof,
partly of their fickleness, partly of their ingratitude. But however
such blame may serve to lighten the mental sadness arising from a
series of painful facts, it will not be found justified if we apply to
those facts a reasonable criticism.
What is called the fickleness of the Athenians on this occasion is
nothing more than a rapid and decisive change in their estimation of
Miltiadês; unbounded admiration passing at once into extreme
wrath. To censure them for fickleness is here an abuse of terms;
such a change in their opinion was the unavoidable result of his
conduct. His behavior in the expedition of Paros was as
reprehensible as at Marathon it had been meritorious, and the one
succeeded immediately after the other: what else could ensue
except an entire revolution in the Athenian feelings? He had
employed his prodigious ascendency over their minds to induce
them to follow him without knowing whither, in the confidence of an
unknown booty: he had exposed their lives and wasted their
substance in wreaking a private grudge: in addition to the shame of
an unprincipled project, comes the constructive shame of not having
succeeded in it. Without doubt, such behavior, coming from a man
whom they admired to excess, must have produced a violent and
painful revulsion in the feelings of his countrymen. The idea of
having lavished praise and confidence upon a person who forthwith
turns it to an unworthy purpose, is one of the greatest torments of
the human bosom; and we may well understand that the intensity of
the subsequent displeasure would be aggravated by this reactionary
sentiment, without accusing the Athenians of fickleness. If an officer,
whose conduct has been such as to merit the highest encomiums,
comes on a sudden to betray his trust, and manifests cowardice or
treachery in a new and important undertaking confided to him, are
we to treat the general in command as fickle, because his opinion as
well as his conduct undergoes an instantaneous revolution,—which
will be all the more vehement in proportion to his previous esteem?
The question to be determined is, whether there be sufficient
57.
ground for sucha change; and in the case of Miltiadês, that question
must be answered in the affirmative.
In regard to the charge of ingratitude against the Athenians, this
last-mentioned point—sufficiency of reason—stands tacitly admitted.
It is conceded that Miltiadês deserved punishment for his conduct in
reference to the Parian expedition, but it is nevertheless maintained
that gratitude for his previous services at Marathon ought to have
exempted him from punishment. But the sentiment upon which,
after all, this exculpation rests, will not bear to be drawn out and
stated in the form of a cogent or justifying reason. For will any one
really contend, that a man who has rendered great services to the
public, is to receive in return a license of unpunished misconduct for
the future? Is the general, who has earned applause by eminent skill
and important victories, to be recompensed by being allowed the
liberty of betraying his trust afterwards, and exposing his country to
peril, without censure or penalty? This is what no one intends to
vindicate deliberately; yet a man must be prepared to vindicate it,
when he blames the Athenians for ingratitude towards Miltiadês. For
if all that be meant is, that gratitude for previous services ought to
pass, not as a receipt in full for subsequent crime, but as an
extenuating circumstance in the measurement of the penalty, the
answer is, that it was so reckoned in the Athenian treatment of
Miltiadês.[682] His friends had nothing whatever to urge, against the
extreme penalty proposed by his accuser, except these previous
services,—which influenced the dikasts sufficiently to induce them to
inflict the lighter punishment instead of the heavier. Now the whole
amount of punishment inflicted consisted in a fine which certainly
was not beyond his reasonable means of paying, or of prevailing
upon friends to pay for him, since his son Kimon actually did pay it.
And those who blame the Athenians for ingratitude,—unless they are
prepared to maintain the doctrine that previous services are to pass
as full acquittal for future crime,—have no other ground left except
to say that the fine was too high; that instead of being fifty talents,
it ought to have been no more than forty, thirty, twenty, or ten
talents. Whether they are right in this, I will not take upon me to
58.
pronounce. If theamount was named on behalf of the accused
party, the dikastery had no legal power of diminishing it; but it is
within such narrow limits that the question actually lies, when
transferred from the province of sentiment to that of reason. It will
be recollected that the death of Miltiadês arose neither from his trial
nor his fine, but from the hurt in his thigh.
The charge of ingratitude against the Athenian popular juries
really amounts to this,—that, in trying a person accused of present
crime or fault, they were apt to confine themselves too strictly and
exclusively to the particular matter of charge, either forgetting, or
making too little account of, past services which he might have
rendered. Whoever imagines that such was the habit of Athenian
dikasts, must have studied the orators to very little purpose. Their
real defect was the very opposite: they were too much disposed to
wander from the special issue before them, and to be affected by
appeals to previous services and conduct.[683] That which an
accused person at Athens usually strives to produce is, an
impression in the minds of the dikasts favorable to his general
character and behavior. Of course, he meets the particular allegation
of his accuser as well as he can, but he never fails also to remind
them emphatically, how well he has performed his general duties of
a citizen,—how many times he has served in military expeditions,—
how many trierarchies and liturgies he has performed, and
performed with splendid efficiency. In fact, the claim of an accused
person to acquittal is made to rest too much on his prior services,
and too little upon innocence or justifying matter as to the particular
indictment. When we come down to the time of the orators, I shall
be prepared to show that such indisposition to confine themselves to
a special issue was one of the most serious defects of the assembled
dikasts at Athens. It is one which we should naturally expect from a
body of private, non-professional citizens assembled for the
occasion, and which belongs more or less to the system of jury-trial
everywhere; but it is the direct reverse of that ingratitude, or
habitual insensibility to prior services, for which they have been so
often denounced.
59.
The fate ofMiltiadês, then, so far from illustrating either the
fickleness or the ingratitude of his countrymen, attests their just
appreciation of deserts. It also illustrates another moral, of no small
importance to the right comprehension of Grecian affairs; it teaches
us the painful lesson, how perfectly maddening were the effects of a
copious draught of glory on the temperament of an enterprising and
ambitious Greek. There can be no doubt, that the rapid transition, in
the course of about one week, from Athenian terror before the battle
to Athenian exultation after it, must have produced demonstrations
towards Miltiadês such as were never paid towards any other man in
the whole history of the commonwealth. Such unmeasured
admiration unseated his rational judgment, so that his mind became
abandoned to the reckless impulses of insolence, and antipathy, and
rapacity;—that distempered state, for which (according to Grecian
morality) the retributive Nemesis was ever on the watch, and which,
in his case, she visited with a judgment startling in its rapidity, as
well as terrible in its amount. Had Miltiadês been the same man
before the battle of Marathon as he became after it, the battle might
probably have turned out a defeat instead of a victory.
Dêmosthenês, indeed,[684] in speaking of the wealth and luxury of
political leaders in his own time, and the profuse rewards bestowed
upon them by the people, pointed in contrast to the house of
Miltiadês as being noway more splendid than that of a private man.
But though Miltiadês might continue to live in a modest
establishment, he received from his countrymen marks of admiration
and deference such as were never paid to any citizen before or after
him; and, after all, admiration and deference constitute the precious
essence of popular reward. No man except Miltiadês ever dared to
raise his voice in the Athenian assembly, and say: “Give me a fleet of
ships: do not ask what I am going to do with them, but only follow
me, and I will enrich you.” Herein we may read the unmeasured
confidence which the Athenians placed in their victorious general,
and the utter incapacity of a leading Greek to bear it without mental
depravation; while we learn from it to draw the melancholy
inference, that one result of success was to make the successful
leader one of the most dangerous men in the community. We shall
60.
presently be calledupon to observe the same tendency in the case
of the Spartan Pausanias, and even in that of the Athenian
Themistoklês. It is, indeed, fortunate that the reckless aspirations of
Miltiadês did not take a turn more noxious to Athens than the
comparatively unimportant enterprise against Paros. For had he
sought to acquire dominion and gratify antipathies against enemies
at home, instead of directing his blow against a Parian enemy, the
peace and security of his country might have been seriously
endangered.
Of the despots who gained power in Greece, a considerable
proportion began by popular conduct, and by rendering good service
to their fellow-citizens: having first earned public gratitude, they
abused it for purposes of their own ambition. There was far greater
danger, in a Grecian community, of dangerous excess of gratitude
towards a victorious soldier, than of deficiency in that sentiment:
hence the person thus exalted acquired a position such that the
community found it difficult afterwards to shake him off. Now there
is a disposition almost universal among writers and readers to side
with an individual, especially an eminent individual, against the
multitude; and accordingly those who under such circumstances
suspect the probable abuse of an exalted position, are denounced as
if they harbored an unworthy jealousy of superior abilities. But the
truth is, that the largest analogies of the Grecian character justified
that suspicion, and required the community to take precautions
against the corrupting effects of their own enthusiasm. There is no
feature which more largely pervades the impressible Grecian
character, than a liability to be intoxicated and demoralized by
success: there was no fault from which so few eminent Greeks were
free: there was hardly any danger, against which it was at once so
necessary and so difficult for the Grecian governments to take
security,—especially the democracies, where the manifestations of
enthusiasm were always the loudest. Such is the real explanation of
those charges which have been urged against the Grecian
democracies, that they came to hate and ill-treat previous
61.
benefactors; and thehistory of Miltiadês illustrates it in a manner no
less pointed than painful.
I have already remarked that the fickleness, which has been so
largely imputed to the Athenian democracy in their dealings with
him, is nothing more than a reasonable change of opinion on the
best grounds. Nor can it be said that fickleness was in any case an
attribute of the Athenian democracy. It is a well-known fact, that
feelings, or opinions, or modes of judging, which have once obtained
footing among a large number of people, are more lasting and
unchangeable than those which belong only to one or a few;
insomuch that the judgments and actions of the many admit of
being more clearly understood as to the past, and more certainly
predicted as to the future. If we are to predicate any attribute of the
multitude, it will rather be that of undue tenacity than undue
fickleness; and there will occur nothing in the course of this history
to prove that the Athenian people changed their opinions on
insufficient grounds more frequently than an unresponsible one or
few would have changed.
But there were two circumstances in the working of the Athenian
democracy which imparted to it an appearance of greater fickleness,
without the reality: First, that the manifestations and changes of
opinion were all open, undisguised, and noisy: the people gave
utterance to their present impression, whatever it was, with perfect
frankness; if their opinions were really changed, they had no shame
or scruple in avowing it. Secondly,—and this is a point of capital
importance in the working of democracy generally,—the present
impression, whatever it might be, was not merely undisguised in its
manifestations, but also had a tendency to be exaggerated in its
intensity. This arose from their habit of treating public affairs in
multitudinous assemblages, the well-known effect of which is, to
inflame sentiment in every man’s bosom by mere contact with a
sympathizing circle of neighbors. Whatever the sentiment might be,
—fear, ambition, cupidity, wrath, compassion, piety, patriotic
devotion, etc,[685]—and whether well-founded or ill-founded, it was
62.
constantly influenced moreor less by such intensifying cause. This is
a defect which of course belongs in a certain degree to all exercise
of power by numerous bodies, even though they be representative
bodies,—especially when the character of the people, instead of
being comparatively sedate and slow to move, like the English, is
quick, impressible, and fiery, like Greeks or Italians; but it operated
far more powerfully on the self-acting Dêmos assembled in the Pnyx.
It was in fact the constitutional malady of the democracy, of which
the people were themselves perfectly sensible,—as I shall show
hereafter from the securities which they tried to provide against it,—
but which no securities could ever wholly eradicate. Frequency of
public assemblies, far from aggravating the evil, had a tendency to
lighten it. The people thus became accustomed to hear and balance
many different views as a preliminary to ultimate judgment; they
contracted personal interest and esteem for a numerous class of
dissentient speakers; and they even acquired a certain practical
consciousness of their own liability to error. Moreover, the diffusion
of habits of public speaking, by means of the sophists and the
rhetors, whom it has been so much the custom to disparage, tended
in the same direction,—to break the unity of sentiment among the
listening crowd, to multiply separate judgments, and to neutralize
the contagion of mere sympathizing impulse. These were important
deductions, still farther assisted by the superior taste and
intelligence of the Athenian people: but still, the inherent malady
remained,—excessive and misleading intensity of present sentiment.
It was this which gave such inestimable value to the ascendency of
Periklês, as depicted by Thucydidês: his hold on the people was so
firm, that he could always speak with effect against excess of the
reigning tone of feeling. “When Periklês (says the historian) saw the
people in a state of unseasonable and insolent confidence, he spoke
so as to cow them into alarm; when again they were in groundless
terror, he combated it, and brought them back to confidence.”[686]
We shall find Dêmosthenês, with far inferior ascendency, employed
in the same honorable task: the Athenian people often stood in need
of such correction, but unfortunately did not always find statesmen,
at once friendly and commanding, to administer it.
63.
These two attributes,then, belonged to the Athenian democracy;
first, their sentiments of every kind were manifested loudly and
openly; next, their sentiments tended to a pitch of great present
intensity. Of course, therefore, when they changed, the change of
sentiment stood prominent, and forced itself upon every one’s
notice,—being a transition from one strong sentiment past to
another strong sentiment present.[687] And it was because such
alterations, when they did take place, stood out so palpably to
remark, that the Athenian people have drawn upon themselves the
imputation of fickleness: for it is not at all true, I repeat, that
changes of sentiment were more frequently produced in them by
frivolous or insufficient causes, than changes of sentiment in other
governments.
64.
CHAPTER XXXVII.
IONIC PHILOSOPHERS.— PYTHAGORAS. —
KROTON AND SYBARIS.
The history of the powerful Grecian cities in Italy and Sicily,
between the accession of Peisistratus and the battle of Marathon, is
for the most part unknown to us. Phalaris, despot of Agrigentum in
Sicily, made for himself an unenviable name during this obscure
interval. His reign seems to coincide in time with the earlier part of
the rule of Peisistratus (about 560-540 B. C.), and the few and vague
statements which we find respecting it,[688] merely show us that it
was a period of extortion and cruelty, even beyond the ordinary
licence of Grecian despots. The reality of the hollow bull of brass,
which Phalaris was accustomed to heat in order to shut up his
victims in it and burn them, appears to be better authenticated than
the nature of the story would lead us to presume: for it is not only
noticed by Pindar, but even the actual instrument of this torture, the
brazen bull itself,[689]—which had been taken away from Agrigentum
as a trophy by the Carthaginians when they captured the town, was
restored by the Romans, on the subjugation of Carthage, to its
original domicile. Phalaris is said to have acquired the supreme
command, by undertaking the task of building a great temple[690] to
Zeus Polieus on the citadel rock; a pretence whereby he was enabled
to assemble and arm a number of workmen and devoted partisans,
whom he employed, at the festival of the Thesmophoria, to put
down the authorities. He afterwards disarmed the citizens by a
stratagem, and committed cruelties which rendered him so
abhorred, that a sudden rising of the people, headed by Têlemachus
65.
(ancestor of thesubsequent despot, Thêro), overthrew and slew
him. A severe revenge was taken on his partisans after his fall.[691]
During the interval between 540-500 B. C., events of much
importance occurred among the Italian Greeks,—especially at Kroton
and Sybaris,—events, unhappily, very imperfectly handed down.
Between these two periods fall both the war between Sybaris and
Kroton, and the career and ascendency of Pythagoras. In connection
with this latter name, it will be requisite to say a few words
respecting the other Grecian philosophers of the sixth century B. C.
I have, in a former chapter, noticed and characterized those
distinguished persons called the Seven Wise Men of Greece, whose
celebrity falls in the first half of this century,—men not so much
marked by scientific genius as by practical sagacity and foresight in
the appreciation of worldly affairs, and enjoying a high degree of
political respect from their fellow-citizens. One of them, however, the
Milesian Thalês, claims our notice, not only on this ground, but also
as the earliest known name in the long line of Greek scientific
investigators. His life, nearly contemporary with that of Solon,
belongs seemingly to the interval about 640-550 B. C.: the stories
mentioned in Herodotus—perhaps borrowed in part from the
Milesian Hekatæus—are sufficient to show that his reputation for
wisdom, as well as for science, continued to be very great, even a
century after his death, among his fellow-citizens. And he marks an
important epoch in the progress of the Greek mind, as having been
the first man to depart both in letter and spirit from the Hesiodic
Theogony, introducing the conception of substances with their
transformations and sequences, in place of that string of persons
and quasi-human attributes which had animated the old legendary
world. He is the father of what is called the Ionic philosophy, which
is considered as lasting from his time down to that of Sokratês; and
writers, ancient as well as modern, have professed to trace a
succession of philosophers, each one the pupil of the preceding,
between these two extreme epochs. But the appellation is, in truth,
undefined, and even incorrect, since nothing entitled to the name of
66.
a school, orsect, or succession,—like that of the Pythagoreans, to
be noticed presently,—can be made out. There is, indeed, a certain
general analogy in the philosophical vein of Thalês, Hippo,
Anaximenês, and Diogenês of Apollonia, whereby they all stand
distinguished from Xenophanês of Elea, and his successors, the
Eleatic dialecticians, Parmenidês and Zeno; but there are also
material differences between their respective doctrines,—no two of
them holding the same. And if we look to Anaximander, the person
next in order of time to Thalês, as well as to Herakleitus, we find
them departing, in a great degree, even from that character which
all the rest have in common, though both the one and the other are
usually enrolled in the list of Ionic philosophers.
Of the old legendary and polytheistic conception of nature, which
Thalês partially discarded, we may remark that it is a state of the
human mind in which the problems suggesting themselves to be
solved, and the machinery for solving them, bear a fair proportion
one to the other. If the problems be vast, indeterminate, confused,
and derived rather from the hopes, fears, love, hatred,
astonishment, etc., of men, than from any genuine desire of
knowledge,—so also does the received belief supply invisible agents
in unlimited number, and with every variety of power and inclination.
The means of explanation are thus multiplied and diversified as
readily as the phenomena to be explained. And though no future
events or states can be predicted on trustworthy grounds, in such
manner as to stand the scrutiny of subsequent verification,—yet
there is little difficulty in rendering a specious and plausible account
of matters past, of any and all things alike; especially as, at such a
period, matters of fact requiring explanation are neither collated nor
preserved with care. And though no event or state, which has not
yet occurred, can be predicted, there is little difficulty in rendering a
plausible account of everything which has occurred in the past.
Cosmogony, and the prior ages of the world, were conceived as a
sort of personal history, with intermarriages, filiation, quarrels, and
other adventures, of these invisible agents; among whom some one
or more were assumed as unbegotten and self-existent,—the latter
67.
assumption being adifficulty common to all systems of cosmogony,
and from which even this flexible and expansive hypothesis is not
exempt.
Now when Thalês disengaged Grecian philosophy from the old
mode of explanation, he did not at the same time disengage it from
the old problems and matters propounded for inquiry. These he
retained, and transmitted to his successors, as vague and vast as
they were at first conceived; and so they remained, though with
some transformations and modifications, together with many new
questions equally insoluble, substantially present to the Greeks
throughout their whole history, as the legitimate problems for
philosophical investigation. But these problems, adapted only to the
old elastic system of polytheistic explanation and omnipresent
personal agency, became utterly disproportioned to any impersonal
hypotheses such as those of Thalês and the philosophers after him,
—whether assumed physical laws, or plausible moral and
metaphysical dogmas, open to argumentative attack, and of course
requiring the like defence. To treat the visible world as a whole, and
inquire when and how it began, as well as into all its past changes,
—to discuss the first origin of men, animals, plants, the sun, the
stars, etc.,—to assign some comprehensive reason why motion or
change in general took place in the universe,—to investigate the
destinies of the human race, and to lay down some systematic
relation between them and the gods,—all these were topics
admitting of being conceived in many different ways, and set forth
with eloquent plausibility, but not reducible to any solution either
resting on scientific evidence, or commanding steady adherence
under a free scrutiny.[692]
At the time when the power of scientific investigation was scanty
and helpless, the problems proposed were thus such as to lie out of
the reach of science in its largest compass. Gradually, indeed,
subjects more special and limited, and upon which experience, or
deductions from experience, could be brought to bear, were added
to the list of quæsita, and examined with great profit and
68.
instruction: but theold problems, with new ones, alike
unfathomable, were never eliminated, and always occupied a
prominent place in the philosophical world. Now it was this
disproportion, between questions to be solved and means of
solution, which gave rise to that conspicuous characteristic of
Grecian philosophy,—the antagonist force of suspensive skepticism,
passing in some minds into a broad negation of the attainability of
general truth,—which it nourished from its beginning to its end;
commencing as early as Xenophanês, continuing to manifest itself
seven centuries afterwards in Ænesidêmus and Sextus Empiricus,
and including in the interval between these two extremes some of
the most powerful intellects in Greece. The present is not the time
for considering these Skeptics, who bear an unpopular name, and
have not often been fairly appreciated; the more so, as it often
suited the purpose of men, themselves essentially skeptical, like
Sokratês and Plato, to denounce professed skepticism with
indignation. But it is essential to bring them into notice at the first
spring of Grecian philosophy under Thalês, because the
circumstances were then laid which so soon afterwards developed
them.
Though the celebrity of Thalês in antiquity was great and
universal, scarcely any distinct facts were known respecting him: it is
certain that he left nothing in writing. Extensive travels in Egypt and
Asia are ascribed to him, and as a general fact these travels are
doubtless true, since no other means of acquiring knowledge were
then open. At a time when the brother of the Lesbian Alkæus was
serving in the Babylonian army, we may easily conceive that an
inquisitive Milesian would make his way to that wonderful city
wherein stood the temple-observatory of the Chaldæan priesthood;
nor is it impossible that he may have seen the still greater city of
Ninus, or Nineveh, before its capture and destruction by the Medes.
How great his reputation was in his lifetime, the admiration
expressed by his younger contemporary, Xenophanês, assures us;
and Herakleitus, in the next generation, a severe judge of all other
philosophers, spoke of him with similar esteem. To him were traced,
69.
by the Grecianinquirers of the fourth century B. C., the first
beginnings of geometry, astronomy, and physiology in its large and
really appropriate sense, the scientific study of nature: for the Greek
word denoting nature (φύσις), first comes into comprehensive use
about this time (as I have remarked in an earlier chapter),[693] with
its derivatives physics and physiology, as distinguished from the
theology of the old poets. Little stress can be laid on those
elementary propositions in geometry which are specified as
discovered, or as first demonstrated, by Thalês,—still less upon the
solar eclipse respecting which, according to Herodotus, he
determined beforehand the year of occurrence.[694] But the main
doctrine of his physiology,—using that word in its larger Greek
sense,—is distinctly attested. He stripped Oceanus and Tethys,
primeval parents of the gods in the Homeric theogony, of their
personality,—and laid down water, or fluid substance, as the single
original element from which everything came, and into which
everything returned.[695] The doctrine of one eternal element,
remaining always the same in its essence, but indefinitely variable in
its manifestations to sense, was thus first introduced to the
discussion of the Grecian public. We have no means of knowing the
reasons by which Thalês supported this opinion, nor could even
Aristotle do more than conjecture what they might have been; but
one of the statements urged on behalf of it,—that the earth itself
rested on water,[696]—we may safely refer to the Milesian himself, for
it would hardly have been advanced at a later age. Moreover, Thalês
is reported to have held, that everything was living and full of gods;
and that the magnet, especially, was a living thing. Thus the gods,
as far as we can pretend to follow opinions so very faintly
transmitted, are conceived as active powers, and causes of
changeful manifestation, attached to the primeval substance:[697]
the universe being assimilated to an organized body or system.
Respecting Hippo,—who reproduced the theory of Thalês under a
more generalized form of expression, substituting, in place of water,
moisture, or something common to air and water,[698]—we do not
know whether he belonged to the sixth or the fifth century B. C. But
70.
Anaximander, Xenophanês, andPherekydês belong to the latter half
of the sixth century. Anaximander, the son of Praxiadês, was a native
of Milêtus,—Xenophanês, a native of Kolophon; the former, among
the earliest expositors of doctrine in prose,[699] while the latter
committed his opinions to the old medium of verse. Anaximander
seems to have taken up the philosophical problem, while he
materially altered the hypothesis of his predecessor Thalês. Instead
of the primeval fluid of the latter, he supposed a primeval principle,
without any actual determining qualities whatever, but including all
qualities potentially, and manifesting them in an infinite variety from
its continually self-changing nature,—a principle, which was nothing
in itself, yet had the capacity of producing any and all
manifestations, however contrary to each other,[700]—a primeval
something, whose essence it was to be eternally productive of
different phenomena,—a sort of mathematical point, which counts
for nothing in itself, but is vigorous in generating lines to any extent
that may be desired. In this manner, Anaximander professed to give
a comprehensive explanation of change in general, or generation, or
destruction,—how it happened that one sensible thing began and
another ceased to exist,—according to the vague problems which
these early inquirers were in the habit of setting to themselves.[701]
He avoided that which the first philosophers especially dreaded, the
affirmation that generation could take place out of Nothing; yet the
primeval Something, which he supposed was only distinguished from
nothing by possessing this very power of generation.
In his theory, he passed from the province of physics into that of
metaphysics. He first introduced into Grecian philosophy that
important word which signifies a beginning or a principle,[702] and
first opened that metaphysical discussion, which was carried on in
various ways throughout the whole period of Grecian philosophy, as
to the one and the many—the continuous and the variable—that
which exists eternally, as distinguished from that which comes and
passes away in ever-changing manifestations. His physiology, or
explanation of nature, thus conducted the mind into a different route
from that suggested by the hypothesis of Thalês, which was built
71.
upon physical considerations,and was therefore calculated to
suggest and stimulate observations of physical phenomena for the
purpose of verifying or confuting it,—while the hypothesis of
Anaximander admitted only of being discussed dialectically, or by
reasonings expressed in general language; reasonings sometimes,
indeed, referring to experience for the purpose of illustration, but
seldom resting on it, and never looking out for it as a necessary
support. The physical explanation of nature, however, once
introduced by Thalês, although deserted by Anaximander, was taken
up by Anaximenês and others afterwards, and reproduced with
many divergences of doctrine,—yet always more or less entangled
and perplexed with metaphysical additions, since the two
departments were never clearly parted throughout all Grecian
philosophy. Of these subsequent physical philosophers I shall speak
hereafter: at present, I confine myself to the thinkers of the sixth
century B. C., among whom Anaximander stands prominent, not as
the follower of Thalês, but as the author of an hypothesis both new
and tending in a different direction.
It was not merely as the author of this hypothesis, however, that
Anaximander enlarged the Greek mind and roused the powers of
thought: we find him also mentioned as distinguished in astronomy
and geometry. He is said to have been the first to establish a sun-
dial in Greece, to construct a sphere, and to explain the obliquity of
the ecliptic;[703] how far such alleged authorship really belongs to
him, we cannot be certain,—but there is one step of immense
importance which he is clearly affirmed to have made. He was the
first to compose a treatise on the geography of the land and sea
within his cognizance, and to construct a chart or map founded
thereupon,—seemingly a tablet of brass. Such a novelty, wondrous
even to the rude and ignorant, was calculated to stimulate
powerfully inquisitive minds, and from it may be dated the
commencement of Grecian rational geography,—not the least
valuable among the contributions of this people to the stock of
human knowledge.
72.
Xenophanês of Kolophon,somewhat younger than Anaximander,
and nearly contemporary with Pythagoras (seemingly from about
570-480 B. C.), migrated from Kolophon[704] to Zanklê and Katana in
Sicily and Elea in Italy, soon after the time when Ionia became
subject to the Persians, (540-530 B. C.) He was the founder of what is
called the Eleatic school of philosophers,—a real school, since it
appears that Parmenidês, Zeno, and Melissus, pursued and
developed, in a great degree, the train of speculation which had
been begun by Xenophanês,—doubtless with additions and
variations of their own, but especially with a dialectic power which
belongs to the age of Periklês, and is unknown in the sixth century
B. C. He was the author of more than one poem of considerable
length, one on the foundation of Kolophon and another on that of
Elea; besides his poem on Nature, wherein his philosophical
doctrines were set forth.[705] His manner appears to have been
controversial and full of asperity towards antagonists; but what is
most remarkable is the plain-spoken manner in which he declared
himself against the popular religion, and in which he denounced as
abominable the descriptions of the gods given by Homer and Hesiod.
[706]
He is said to have controverted the doctrines both of Thalês and
Pythagoras: this is probable enough; but he seems to have taken his
start from the philosophy of Anaximander,—not, however, to adopt
it, but to reverse it,—and to set forth an opinion which we may call
its contrary. Nature, in the conception of Anaximander, consisted of a
Something having no other attribute except the unlimited power of
generating and cancelling phenomenal changes: in this doctrine, the
something or substratum existed only in and for those changes, and
could not be said to exist at all in any other sense: the permanent
was thus merged and lost in the variable,—the one in the many.
Xenophanês laid down the exact opposite: he conceived Nature as
one unchangeable and indivisible whole, spherical, animated,
endued with reason, and penetrated by or indeed identical with God:
he denied the objective reality of all change, or generation, or
destruction, which he seems to have considered as only changes or
73.
modifications in thepercipient, and perhaps different in one
percipient and another. That which exists, he maintained, could not
have been generated, nor could it ever be destroyed: there was
neither real generation nor real destruction of anything; but that
which men took for such, was the change in their own feelings and
ideas. He thus recognized the permanent without the variable,[707]—
the one without the many. And his treatment of the received
religious creed was in harmony with such physical or metaphysical
hypothesis; for while he held the whole of Nature to be God, without
parts or change, he at the same time pronounced the popular gods
to be entities of subjective fancy, imagined by men after their own
model: if oxen or lions were to become religious, he added, they
would in like manner provide for themselves gods after their
respective shapes and characters.[708] This hypothesis, which
seemed to set aside altogether the study of the sensible world as a
source of knowledge, was expounded briefly, and as it should seem,
obscurely and rudely, by Xenophanês; at least we may infer thus
much from the slighting epithet applied to him by Aristotle.[709] But
his successors, Parmenidês and Zeno, in the succeeding century,
expanded it considerably, supported it with extraordinary acuteness
of dialectics, and even superadded a second part, in which the
phenomena of sense—though considered only as appearances, not
partaking in the reality of the one Ens—were yet explained by a new
physical hypothesis; so that they will be found to exercise great
influence over the speculations both of Plato and Aristotle. We
discover in Xenophanês, moreover, a vein of skepticism, and a
mournful despair as to the attainability of certain knowledge,[710]
which the nature of his philosophy was well calculated to suggest,
and in which the sillograph Timon of the third century B. C., who
seems to have spoken of Xenophanês better than of most of the
other philosophers, powerfully sympathized.
The cosmogony of Pherekydês of Syrus, contemporary of
Anaximander and among the teachers of Pythagoras, seems,
according to the fragments preserved, a combination of the old
legendary fancies with Orphic mysticism,[711] and probably exercised
74.
little influence overthe subsequent course of Grecian philosophy. By
what has been said of Thalês, Anaximander, and Xenophanês, it will
be seen that the sixth century B. C. witnessed the opening of several
of those roads of intellectual speculation which the later
philosophers pursued farther, or at least from which they branched
off. Before the year 500 B. C. many interesting questions were thus
brought into discussion, which Solon, who died about 558 B. C., had
never heard of,—just as he may probably never have seen the map
of Anaximander. But neither of these two distinguished men—
Anaximander or Xenophanês—was anything more than a speculative
inquirer. The third eminent name of this century, of whom I am now
about to speak,—Pythagoras, combined in his character disparate
elements which require rather a longer development.
Pythagoras was founder of a brotherhood, originally brought
together by a religious influence, and with observances approaching
to monastic peculiarity,—working in a direction at once religious,
political, and scientific, and exercising for some time a real political
ascendency,—but afterwards banished from government and state
affairs into a sectarian privacy with scientific pursuits, not without,
however, still producing some statesmen individually distinguished.
Amidst the multitude of false and apocryphal statements which
circulated in antiquity respecting this celebrated man, we find a few
important facts reasonably attested and deserving credence. He was
a native of Samos,[712] son of an opulent merchant named
Mnêsarchus,—or, according to some of his later and more fervent
admirers, of Apollo; born, as far as we can make out, about the 50th
Olympiad, or 580 B. C. On the many marvels recounted respecting his
youth, it is unnecessary to dwell. Among them may be numbered his
wide-reaching travels, said to have been prolonged for nearly thirty
years, to visit the Arabians, the Syrians, the Phenicians, the
Chaldæans, the Indians, and the Gallic Druids. But there is reason to
believe that he really visited Egypt[713]—perhaps also Phenicia—and
Babylon, then Chaldæan and independent. At the time when he saw
Egypt, between 560-540 B. C., about one century earlier than
Herodotus, it was under Amasis, the last of its own kings, with its
75.
peculiar native characteryet unimpaired by foreign conquest, and
only slightly modified by the admission during the preceding century
of Grecian mercenary troops and traders. The spectacle of Egyptian
habits, the conversation of the priests, and the initiation into various
mysteries or secret rites and stories not accessible to the general
public, may very naturally have impressed the mind of Pythagoras,
and given him that turn for mystic observance, asceticism, and
peculiarity of diet and clothing,—which manifested itself from the
same cause among several of his contemporaries, but which was not
a common phenomenon in the primitive Greek religion. Besides
visiting Egypt, Pythagoras is also said to have profited by the
teaching of Thalês, of Anaximander, and of Pherekydês of Syros.[714]
Amidst the towns of Ionia, he would, moreover, have an opportunity
of conversing with many Greek navigators who had visited foreign
countries, especially Italy and Sicily. His mind seems to have been
acted upon and impelled by this combined stimulus,—partly towards
an imaginative and religious vein of speculation, with a life of mystic
observance,—partly towards that active exercise, both of mind and
body, which the genius of an Hellenic community so naturally tended
to suggest.
Of the personal doctrines or opinions of Pythagoras, whom we
must distinguish from Philolaus and the subsequent Pythagoreans,
we have little certain knowledge, though doubtless the first germ of
their geometry, arithmetic, astronomy, etc. must have proceeded
from him. But that he believed in the metempsychosis or
transmigration of the souls of deceased men into other men, as well
as into animals, we know, not only by other evidence, but also by
the testimony of his contemporary, the philosopher Xenophanês of
Elea. Pythagoras, seeing a dog beaten, and hearing him howl,
desired the striker to desist, saying: “It is the soul of a friend of
mine, whom I recognized by his voice.” This—together with the
general testimony of Hêrakleitus, that Pythagoras was a man of
extensive research and acquired instruction, but artful for mischief
and destitute of sound judgment—is all that we know about him
from contemporaries. Herodotus, two generations afterwards, while
76.
he conceives thePythagoreans as a peculiar religious order,
intimates that both Orpheus and Pythagoras had derived the
doctrine of the metempsychosis from Egypt, but had pretended to it
as their own without acknowledgment.[715]
Pythagoras combines the character of a sophist (a man of large
observation, and clever, ascendent, inventive mind,—the original
sense of the word Sophist, prior to the polemics of the Platonic
school, and the only sense known to Herodotus[716]) with that of an
inspired teacher, prophet, and worker of miracles,—approaching to
and sometimes even confounded with the gods,—and employing all
these gifts to found a new special order of brethren, bound together
by religious rites and observances peculiar to themselves. In his
prominent vocation, analogous to that of Epimenidês, Orpheus, or
Melampus, he appears as the revealer of a mode of life calculated to
raise his disciples above the level of mankind, and to recommend
them to the favor of the gods; the Pythagorean life, like the Orphic
life,[717] being intended as the exclusive prerogative of the
brotherhood,—approached only by probation and initiatory
ceremonies which were adapted to select enthusiasts rather than to
an indiscriminate crowd,—and exacting entire mental devotion to the
master.[718] In these lofty pretensions the Agrigentine Empedoklês
seems to have greatly copied him, though with some varieties, about
half a century afterwards.[719] While Aristotle tells us that the
Krotoniates identified Pythagoras with the Hyperborean Apollo, the
satirical Timon pronounced him to have been “a juggler of solemn
speech, engaged in fishing for men.”[720] This is the same character,
looked at from the different points of view of the believer and the
unbeliever. There is, however, no reason for regarding Pythagoras as
an impostor, because experience seems to show, that while in
certain ages it is not difficult for a man to persuade others that he is
inspired, it is still less difficult for him to contract the same belief
himself.
Looking at the general type of Pythagoras, as conceived by
witnesses in and nearest to his own age,—Xenophanês, Hêrakleitus,
77.
Herodotus, Plato, Aristotle,Isokratês,[721]—we find in him chiefly the
religious missionary and schoolmaster, with little of the politician. His
efficiency in the latter character, originally subordinate, first becomes
prominent in those glowing fancies which the later Pythagoreans
communicated to Aristoxenus and Dikæarchus. The primitive
Pythagoras inspired by the gods to reveal a new mode of life,[722]—
the Pythagorean life,—and to promise divine favor to a select and
docile few, as the recompense of strict ritual obedience, of austere
self-control, and of laborious training, bodily as well as mental. To
speak with confidence of the details of his training, ethical or
scientific, and of the doctrines which he promulgated, is impossible;
for neither he himself nor any of his disciples anterior to Philolaus—
who was separated from him by about one intervening generation—
left any memorials in writing.[723] Numbers and lines, studied partly
in their own mutual relations, partly under various symbolizing
fancies, presented themselves to him as the primary constituent
elements of the universe, and as a sort of magical key to
phenomena, physical as well as moral. And these mathematical
tendencies in his teaching, expanded by Pythagoreans, his
successors, and coinciding partly also, as has been before stated,
with the studies of Anaximander and Thalês, acquired more and
more development, so as to become one of the most glorious and
profitable manifestations of Grecian intellect. Living as Pythagoras
did at a time when the stock of experience was scanty, the license of
hypothesis unbounded, and the process of deduction without rule or
verifying test,—he was thus fortunate enough to strike into that
track of geometry and arithmetic, in which, from data of experience
few, simple, and obvious, an immense field of deductive and
verifiable investigation may be travelled over. We must at the same
time remark, however, that in his mind this track, which now seems
so straightforward and well defined, was clouded by strange fancies
which it is not easy to understand, and from which it was but
partially cleared by his successors. Of his spiritual training much is
said, though not upon very good authority. We hear of his memorial
discipline, his monastic self-scrutiny, his employment of music to
soothe disorderly passions,[724] his long novitiate of silence, his
78.
knowledge of physiognomy,which enabled him to detect even
without trial unworthy subjects, his peculiar diet, and his rigid care
for sobriety as well as for bodily vigor. He is also said to have
inculcated abstinence from animal food, and this feeling is so
naturally connected with the doctrine of the metempsychosis, that
we may well believe him to have entertained it, as Empedoklês also
did after him.[725] It is certain that there were peculiar observances,
and probably a certain measure of self-denial embodied in the
Pythagorean life; but on the other hand, it seems equally certain
that the members of the order cannot have been all subjected to the
same diet, or training, or studies. For Milo the Krotoniate was among
them,[726] the strongest man and the unparalleled wrestler of his
age,—who cannot possibly have dispensed with animal food and
ample diet (even setting aside the tales about his voracious
appetite), and is not likely to have bent his attention on speculative
study. Probably Pythagoras did not enforce the same bodily or
mental discipline on all, or at least knew when to grant
dispensations. The order, as it first stood under him, consisted of
men different both in temperament and aptitude, but bound
together by common religious observances and hopes, common
reverence for the master, and mutual attachment as well as pride in
each other’s success; and it must thus be distinguished from the
Pythagoreans of the fourth century B. C., who had no communion
with wrestlers, and comprised only ascetic, studious men, generally
recluse, though in some cases rising to political distinction.
The succession of these Pythagoreans, never very numerous,
seems to have continued until about 300 B. C., and then nearly died
out; being superseded by other schemes of philosophy more suited
to cultivated Greeks of the age after Sokratês. But during the time of
Cicero, two centuries afterwards, the orientalizing tendency—then
beginning to spread over the Grecian and Roman world, and
becoming gradually stronger and stronger—caused the Pythagorean
philosophy to be again revived. It was revived too, with little or none
of its scientific tendencies, but with more than its primitive religious
and imaginative fanaticism,—Apollonius of Tyana constituting himself
79.
a living copyof Pythagoras. And thus, while the scientific elements
developed by the disciples of Pythagoras had become disjoined from
all peculiarity of sect, and passed into the general studious world,—
the original vein of mystic and ascetic fancy belonging to the master,
without any of that practical efficiency of body and mind which had
marked his first followers, was taken up anew into the pagan world,
along with the disfigured doctrines of Plato. Neo-Pythagorism,
passing gradually into Neo-Platonism, outlasted the other more
positive and masculine systems of pagan philosophy, as the
contemporary and rival of Christianity. A large proportion of the false
statements concerning Pythagoras come from these Neo-
Pythagoreans, who were not deterred by the want of memorials
from illustrating, with ample latitude of fancy, the ideal character of
the master.
That an inquisitive man like Pythagoras, at a time when there
were hardly any books to study, would visit foreign countries, and
converse with all the Grecian philosophical inquirers within his reach,
is a matter which we should presume, even if no one attested it; and
our witnesses carry us very little beyond this general presumption.
What doctrines he borrowed, or from whom, we are unable to
discover. But, in fact, his whole life and proceedings bear the stamp
of an original mind, and not of a borrower,—a mind impressed both
with Hellenic and with non-Hellenic habits and religion, yet capable
of combining the two in a manner peculiar to himself; and above all,
endued with those talents for religion and personal ascendency over
others, which told for much more than the intrinsic merit of his
ideas. We are informed that after extensive travels and inquiries he
returned to Samos, at the age of about forty: he then found his
native island under the despotism of Polykratês, which rendered it
an unsuitable place either for free sentiments or for marked
individuals. Unable to attract hearers, or found any school or
brotherhood, in his native island, he determined to expatriate. And
we may presume that at this period (about 535-530 B. C.) the recent
subjugation of Ionia by the Persians was not without influence on his
determination. The trade between the Asiatic and the Italian Greeks,
80.
—and even theintimacy between Milêtus and Knidus on the one
side, and Sybaris and Tarentum on the other,—had been great and
of long standing, so that there was more than one motive to
determine him to the coast of Italy; in which direction also his
contemporary Xenophanês, the founder of the Eleatic school of
philosophy, emigrated, seemingly, about the same time,—from
Kolophon to Zanklê, Katana, and Elea.[727]
Kroton and Sybaris were at this time in their fullest prosperity,—
among the first and most prosperous cities of the Hellenic name. To
the former of the two Pythagoras directed his course. A council of
one thousand persons, taken from among the heirs and
representatives of the principal proprietors at its first foundation,
was here invested with the supreme authority: in what manner the
executive offices were filled, we have no information. Besides a
great extent of power, and a numerous population, the large mass of
whom had no share in the political franchise, Kroton stood at this
time distinguished for two things,—the general excellence of the
bodily habit of the citizens, attested, in part, by the number of
conquerors furnished to the Olympic games,—and the superiority of
its physicians, or surgeons.[728] These two points were, in fact,
greatly connected with each other. For the therapeutics of the day
consisted not so much of active remedies as of careful diet and
regimen; while the trainer, who dictated the life of an athlete during
his long and fatiguing preparation for an Olympic contest, and the
professional superintendent of the youths who frequented the public
gymnasia, followed out the same general views, and acted upon the
same basis of knowledge, as the physician who prescribed for a
state of positive bad health.[729] Of medical education properly so
called, especially of anatomy, there was then little or nothing. The
physician acquired his knowledge from observation of men sick as
well as healthy, and from a careful notice of the way in which the
human body was acted upon by surrounding agents and
circumstances: and this same knowledge was not less necessary for
the trainer; so that the same place which contained the best men in
the latter class was also likely to be distinguished in the former. It is
81.
not improbable thatthis celebrity of Kroton may have been one of
the reasons which determined Pythagoras to go thither; for among
the precepts ascribed to him, precise rules as to diet and bodily
regulation occupy a prominent place. The medical or surgical
celebrity of Dêmokêdês (son-in-law of the Pythagorean Milo), to
whom allusion has been made in a former chapter, is
contemporaneous with the presence of Pythagoras at Kroton; and
the medical men of Magna Græcia maintained themselves in credit,
as rivals of the schools of the Asklepiads at Kôs and Knidus,
throughout all the fifth and fourth centuries B. C.
The biographers of Pythagoras tell us that his arrival there, his
preaching, and his conduct, produced an effect almost electric upon
the minds of the people, with an extensive reform, public as well as
private. Political discontent was repressed, incontinence disappeared,
luxury became discredited, and the women, hastened to exchange
their golden ornaments for the simplest attire. No less than two
thousand persons were converted at his first preaching; and so
effective were his discourses to the youth, that the Supreme Council
of One Thousand invited him into their assembly, solicited his advice,
and even offered to constitute him their prytanis, or president, while
his wife and daughter were placed at the head of the religious
processions of females.[730] Nor was his influence confined to
Kroton. Other towns in Italy and Sicily,—Sybaris, Metapontum,
Rhêgium, Katana, Himera, etc., all felt the benefit of his
exhortations, which extricated some of them even from slavery. Such
are the tales of which the biographers of Pythagoras are full.[731]
And we see that even the disciples of Aristotle, about the year 300
B. C.,—Aristoxenus, Dikæarchus, Herakleidês of Pontus, etc., are
hardly less charged with them than the Neo-Pythagoreans of three
or four centuries later: they doubtless heard them from their
contemporary Pythagoreans,[732] the last members of a declining
sect, among whom the attributes of the primitive founder passed for
godlike, but who had no memorials, no historical judgment, and no
means of forming a true conception of Kroton as it stood in 530 B. C.
[733]
82.
Welcome to OurBookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com