McGRAW-HILL INTERNATIONAL EDITION Don't forget to check out the website, www.mhhe.com/tucker, for additional resources/ * * * Insti·uctors and sh1dents using Programming Languages: Principles and Paradigms, Second Edition by Allen B. Tucker and Robert E. Noonan, will tlnd a wide variety of resources available at the website, www.mhhe.com/tucker. INSTRUCTOR RESOURCES Instmctors can access the following resources by contacting their McGraw-Hill Rep- resentative for a secure password. · PowerPoint slides. Contain figures from the book along with lecture notes. Solutions Manual. Password-protected solutions are provided. PageOut. A free tool that helps you create your own course website. STUDENT RESOURCES The student resources are available to those students using the book. Once you have accessed the website, you'll see "Student Resources" listed. This section of the site has a wealth of materials to help you review the various aspects of programming languages. Inc1uded are: • Chapter Summaries. Quick summaries provide an essential review of major ideas and concepts covered in each chapter. • Glossary. Defines key terms presented in the book. PowerPoint slides. Contain helpful lecture notes to review important points. Web linl<s. Connect students to additional resources available online. Downloadable programs. The programs from the book are downloadable in multiple languages: C, Ada, Perl, Java, Smalltalk, Python, Scheme, Haskell, Prolog, etc. Downloadable Clite interpreter software. Can use for many of the hands-on exercises. r I es Principles and Paradigms Allen B. Tucker Bowdoin College Robert E. Noonan College of William and Mary Boston Burr Ridge, IL Dubuque, lA Madison, WI New York San Francisco St. Louis Bangkok Bogota Caracas Kuala Lumpur Lisbon London Madrid Mexico City Milan Montreal New Delhi Santiago Seoul Singapore Sydney Taipei Toronto The McGraw·Hlfl Compamg ~= PROGRAMMING LANGUAGES: PRINCIPLES AND PARADIGMS, SECOND EDITION International Edition 2007 Exclusive rights by McGraw-Hill Education (Asia), for manufacture and export. This book cannot be re-exported from the country to which it is sold by McGraw-Hill. The International Edition is not available in North America. Published by McGraw-Hill, a business unit of The McGraw-Hill Companies, Inc., 1221 Avenue of the Americas, New York, NY 10020. Copyright© 2007 by The McGraw-Hill Companies, Inc. All rights reserved. No part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written consent of The McGraw-Hill Companies, Inc., including, but not limited to, in any network or other electronic storage or transmission, or broadcast for distance learning. Some ancillaries, including electronic and print components, may not be available to customers outside the United States. 10 09 08 07 06 05 04 03 02 01 20 09 08 07 06 CTF BlE When ordering this title, use ISBN-13: 978-007-125439-7 or ISBN-10: 007-125439-0 Printed in Singapore www.rnhhe.com To Maida. Allen Tucker To Debbie and Paul. Robert Noonan Preface The study of programming languages has evolved rapidly since we began developing the first edition of this book in 1999. For instance, Java has become the dominant lan- guage in computer science curricula, beginning with CS 1. Agile progra:mming has emerged as a coherent approach to software design, and its language preferences are different from those of traditional programming. The use of formal methods in software design has begun to creep into the mainstream, and its importance is now significant. In response to these and other recent events, this edition hopes to capture the excitement and new challenges that accompany the design of today's and tomorrow's programming languages. For instance, this edition has a broader and deeper coverage of all four programming paradigms and the languages that accompany them. Language Coverage Paradigm First Edition This Edition Imperative c (Chapter 12) Ada Perl Object-Oriented Java Java (Chapter 13) Small talk Python Functional Scheme Scheme (Chapter 14) Haskell Haskell Logic Pro log Pro log (Chapter 15) The second major change in this edition is that the discussion of language design principles in the early chapters (2-11) has been greatly expanded. We have added new examples from contemporary languages (like Python and Perl), using an informal style of presentation. Moreover, we have eliminated most coverage of older languages that are no longer in widespread use (such as Pascal and Modula). The core principles of programming languages-syntax, names, types, semantics, and functions-are the subjects of Chapters 2, 4, 5, 7, and 9, respectively. These chap- ters provide a hands-on study of those principles using a broader and deeper selection of languages and examples than the first edition. Readers who prefer an implementation-based treatment of syntax, type systems, semantics, functions, and memory management will find this material in the companion Chapters 3, 6, 8, 10, and 11. These chapters can be used selectively to enrich the core principles with which they are related. For example, the study of syntax in Chapter 2 vii viii Preface can be enriched by studying the lexical and syntactic phases of a compiler in Chapter 3. We emphasize that any or all of these companion chapters may be skipped, espe- cially in a first course on programming languages. Three companion chapters include optional sections with more formal mathemat- ical treatments. These optional sections are marked with the same marginal graphic as this paragraph to indicate that they are optionaL Appendix B provides a review of the key discrete mathematics topics and notations underlying these sections for students who need a quick refresher. Finally, the special topics chapters (16, 17, and 18) provide detailed introductions to the study of event-handling, concurrency, and program conectness. The first edi- tion had covered two of these (event-handling and concurrency), but the chapter on correctness is new to this edition. Overall, this new edition contains a broad and deep coverage of the plinciples, paradigms, and special topics in programming languages. The book now has 18 chapters. Since individual instructors have different views on what should be emphasized in a programming languages course, this book provides a variety of options. EMPHASIS This text emphasizes a thorough, hands-on treatment of the key issues in programming language design. It provides instructors and students with a mixture of explanatory- based and implementation-based experiences. The implementation-based experiences includes hands-on experimentation with the design and implementation of a modest subset of C, called Clite, which is fully defined in Appendix A for easy reference. As noted above, this edition has an expanded treatment of the major program- ming paradigms. We believe that to master a paradigm, students must actively use that paradigm to solve a programming problem. If, for example, your students have no experience with functional programming, we recommend that they learn enough Scheme or Haskell to complete a reasonable programming project. To paraphrase one reviewer's comments: To understand a paradigm you must become the paradigm. If, on the other hand, your introductory, discrete mathematics, or AI course already includes functional programming, you might choose to skip this chapter and empha- size another paradigm or special topic instead. COURSE ORGANIZATION Figure 1 shows how the text divides into three major sections: Principles Paradigms Special Topics Tn the first section, Chapters 2, 4, 5, 7, and 9 cover five core principles-Syntax, Names, Types, Semantics, and Functions. Parts of the remaining chapters (3, 6, 8, 10, and 1 1) in this section can be added to provide a deeper level of topic coverage. On Chapter Introduction Syntactic Analysis 3 Type Systems 6 Semantic Interpretation 8 Pre far Function Interpretation 10 2 L 4 ~ 5 L 7 L 9 L 11 Syntax Names Types Semantics the Principles \ the Paradigms ( 16 the Special Topics 17 18 Event-Handling Concurrency Conectness Functions Memory Management 12 Imperative Programming 13 Object-Oriented Programming 14 Functional Programming 15 Logic Programming I Figure 1 Content dependencies among the chapters. the other hand, advanced or graduate courses may include several of these topics, while de-emphasizing material in the later chapters. The second section of the text covers the four major programming paradigms: Imperative programming Object-oriented programming Functional programming Logic programming These chapters are relatively independent of each other and can be studied in any order. However, a one~semester course will normally include one or two of these chapters, in addition to the principles. The choice of paradigms, of course, may vary with the preferences of the instructor and the content of other courses in the cunicu- lum. For instance, if the cuniculum regularly offers a course in object-oriented design, Chapter 13 can be skipped. Chapter 12 is completely new to this edition; it demonstrates the key features of imperative programming in each of three different languages: C, Ada, and Perl. C was chosen because it illustrates the problems caused by weak typing. In contrast, Ada is I " X ~· Preface strongly typed, thus providing an interesting compadson with C. Finally, Perl was chosen because it illustrates a dynamically typed scripting language. For instructors who include Chapter 12, we recommend that at least one language unfamiliar to stu- dents be covered in enough depth to assign an interesting programming project. Chapter 13 has undergone a major rewrite from the first edition. Now, the fea- tures of an object-oriented language are explored using Java, Smalltalk, and Python. Sma11talk is included because of its simplicity, Java because of its dominance, and Python because of its agility in scripting applications. Students who have had an introductory sequence in Java, but no course in object-oriented design and program- ming, may benefit from learning one of the other two languages. The object-oriented paradigm will continue to be important in the future. The functional and logic programming paradigms (Chapters 14 and 15) continue to be distinctive in their applications and respective programming styles. Our treat- ment of functional programming includes parallel Scheme and Haskell discussions, so that students can master the ideas of functional programming by studying either lan- guage and omitting the other. The third section of the text covers three special topics: • Event-handling • Concurrency • Correctness An undergraduate programming languages course will normally not have time to cover more than one of these topics. The fact that some of these topics appear else- where in the cuniculum can help instructors decide which one(s) to include in the programming languages course. Chapters 16 and 17, Event-Handling and Concurrency, represent unusual control issues that can be well-treated in a study of programming languages. Both are seeing increasing visibility in programming applications, especially in scientific computing and embedded systems. Key topics that students need to cover in these areas include communication, deadlocks, message passing, nondetenninism, event-handling, inter- process communication, and a sampling of the many and varied applications (e.g., operating systems, GUI interactions, and home alarm systems) in which these topics regularly appear. Finally, we are excited about the new Chapter 18 on Correctness, which discusses recent developments in programming language support for formal methods. For exam- ple, the developers of Spark Ada report 100 times fewer bugs with 3-5 times higher productivity rates using a technique called correctness by construction [Barnes, 2003]. Because we believe that the support for more formal approaches to software design will be increasingly important to programming languages in the future (much like object-oriented programming is very important now), we hope that instmctors will consider including this chapter in their programming languages courses. Chapter 18 begins with a review of axiomatic semantics [Hoare, 1969] and its use in the verification of imperative programs. It expands this theory by covering the concept of design by contract [Meyer, 1988] in object-oriented languages, and its application using the Java Modeling Language (JML). This chapter also covers the Preface xi concept of structural induction and its use to prove the correctness of functional programs. It can be argued that some of the topics in the latter chapters belong in other courses, rather than in a study of programming languages and paradigms. For example, the study of concurrency, event-driven programming, and program correctness can each be viewed as a separate course. Moreover, much of the material in Chapters 3, 6, 8, 10, and 11 can·be viewed as the basis for a separate compiler course. Because many under- graduate programs do not offer such separate courses in these topics, this text provides an opportunity to introduce them in the setting of a programming languages course. PREREQUISITES AND OTHER GUIDANCE Students entering this course should have completed at least an introductory course and a data structures course. In the data structures course, students should have become familiar with linked lists, stacks, flexible arrays, and hash tables. Moreover, knowledge of Java is a prerequisite if the course includes any of the following implementation-oriented chapters: 3, 6, 8, 16, and 17. Without knowledge of Java, students should have experience with C, C++, or C# from their data struc- tures course. We recommend that students also have access to a good Java tutorial, reference manual, and programming environment. Such tutorials and references are readily available on the Web (see, for example, http://java.sun.com/docs!books/tutorial/). Some of our discussions depend strictly on features that have been introduced in Java 1.4 and 1.5. These features are clearly noted in the text. We also hope that students will have some modest mathematical skills, as would be found in an elementary discrete mathematics or discrete structures course. While this is not a strict prerequisite, it is essential for students who engage the mathemati- cally miented sections in some of the chapters (3, 6, 8, 10, and 18). A review of the basic ideas of functions, sets, logic, and proof is provided in Appendix B. This text is consistent with the recommendations of Computing Curricula 2001 [CC2001, 2001]. It also covers all the topics in the Programming Languages course described in the Liberal Arts Model Curriculum [Walker and Schneider, 1996J, and its newer 2005 draft version (www.lacs.edu). With regard to Computing Curricula 2001, the material in this text covers all of the topics (PLJ through PL11) in the Programming Languages section of the core body of knowledge. It also covers other topics in that core body of knowledge, such as event-dliven and concurrent programming (PF6), memory management (OSS), func- tional and logic programming (IS), and software engineeling (SE). This text treats each topic in greater depth than that suggested by Computing Curricula 2001. LANGUAGE RESOURCES AND WEBSITE The software for this text can be used with any implementation of Java 1.5 or higher. We have implemented the Java software for this book using Sun's Java 1.5. Here is a list of Web-based sources that we recommend for tutorial and other information on the major languages covered in this book. xii Preface Language Web Source Ada gnu.org C,C++ gnu.org Haskell haskell.org Java 1.5 java.sun.com Perl perl.com Prolog swi-prolog.org Python python.org Scheme drscheme.org Small talk squeak.org A suite of software and other support to accompany this text is available at the website www.mhhe.com/tucker. It contains the following materials: • A complete Java implementation of the syntax, type system, and semantics of Clite. • A downloadable set of all the runnable programs discussed in this text. A set of PowerPoint slides to support course lectures. Answers to the exercises (available to instructors via a secure password). Acknowledgments Many persons have helped guide us in the development of this text. James Lu was a key collaborator in the early conceptualization of the first edition. Bill Bynum at the College of William and Mary and Laurie King at the College of the Holy Cross con- tributed to Chapters 4 and 8, respectively. David Coppit at William and Mary intro- duced us to the use of proof trees, which appear in Chapter 18. Students at Bowdoin and William and Mary contributed to the first edition and early versions of this edi- tion. Notably, Doug Vail developed solutions to some of the more challenging prob- lems. Wyatt Dumas helped rewrite the software for the second edition and made sig- nificant contributions to the content of two chapters.We thank all of our reviewers: Phil Ventura Aaron Keen John Donald Tia Watts Ron Olsson Thomas D. Rethard Alex Thornton Gerald Baumgartner Ken Slonneger David R. Falconer TaeW. Ryu University of Buffalo, SUNY California Polytechnic State University, San Luis Obispo San Diego State University Sonoma State University University of California, Davis University of Texas, Arlington University of California, Irvine Ohio State University University of Iowa California State University, Fullerton California State University, Fullerton Qi Cheng Rainey Little Jay-Evan J. Tevis John Hannan Neelarn Soundarajan Robert van Engelen Shannon Tauro Gloria Melara Amer Diwan Susan Gauch Henri Casanova Cristina V. Lopes Salih Yurttas Roman W. Swiniarksi Arnar Rahej a Franck Xia Rajendra K. Raj Randall D. Beer Robert M. Cubert Liang Cheng David Hemmendinger University of Oklahoma Mississippi State University Auburn University Pennsylvania State University Ohio State University Florida State University University of California, Irvine Cal~'fomia State University, Northridge University of Colorado, Boulder University of Kansas University of California, San Diego University of California, Irvine Texas A&M University San Diego State University Preface xiii Cal{fomia State Polytechnic University, Pomona University of Missouri, Rolla Rochester Institute of Technology Case Western Reserve University University of Florida Lehigh University Union College for their careful reading and constructive comments throughout the development of the first and second editions of this text, which are greatly improved by their collec- tive insight. The authors offer a special thanks to David Hemmendinger of Union Col- lege for his careful editing and extensive suggestions, most of which have been incor- porated into this edition. Finally, we would like to thank our editors, Rebecca Olson and Alan Apt, for their vision, guidance, and support. They have guided the development of the second edition with extraordinary skill. Allen B. Thcker Bowdoin College Robert E. Noonan College of William and Mary Brief Contents Overview 2 Syntax 23 3 lexical and Syntactic Analysis 57 4 Names 85 5 Types 101 6 Type Systems 135 7 Semantics 153 8 Semantic Interpretation 197 9 Functions 225 10 Function Implementation 243 11 Memory Management 263 12 Imperative Programming 277 13 Object-Oriented Programming 309 14 Functional Programming 361 15 logic Programming 413 16 Event-Driven Programming 447 17 Concurrent Programming 483 18 Program Correctness 519 XV r··· .... ·.· .. ·.! ','' ' ! '