Concepts Of Programming Languages, Eleventh Edition .

Transcription

GlobaleditionConcepts ofProgramming LanguagesELEVENTH editionRobert W. Sebesta

digital resources for studentsYour new textbook provides 12-month access to digital resources that may include VideoNotes(step-by-step video tutorials on programming concepts), source code, web chapters, quizzes,and more. Refer to the preface in the textbook for a detailed list of resources.Follow the instructions below to register for the Companion Website for Robert Sebesta’sConcepts of Programming Languages, Eleventh Edition, Global Edition.1. Go to www.pearsonglobaleditions.com/Sebesta2. Click Companion Website3. Click Register and follow the on-screen instructions to create a login name and passwordUse a coin to scratch off the coating and reveal your access code.Do not use a sharp knife or other sharp object as it may damage the code.Use the login name and password you created during registration to start using thedigital resources that accompany your textbook.Important:This access code can only be used once. This subscription is valid for 12 months upon activationand is not transferable. If the access code has already been revealed it may no longer be valid.For technical support go to http://247pearsoned.custhelp.com

This page intentionally left blank

Concepts ofProgramming LanguagesEleventh EditionGLOBAL Edition

This page intentionally left blank

Concepts ofProgramming LanguagesEleventh EditionGLOBAL EditionR o b ert W. S eb estaUniversity of Colorado at Colorado SpringsGlobal Edition contributions bySoumen MukherjeeRCC Institute of Information TechnologyArup Kumar BhattacharjeeRCC Institute of Information TechnologyBoston Columbus Indianapolis New York San Francisco HobokenAmsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal TorontoDelhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo

Editorial Director: Marcia HortonExecutive Editor: Matt GoldsteinEditorial Assistant: Kelsey LoanesVP of Marketing: Christy LeskoDirector of Field Marketing: Tim GalliganProduct Marketing Manager: Bram van KempenField Marketing Manager: Demetrius HallMarketing Assistant: Jon BryantDirector of Product Management: Erin GreggTeam Lead Product Management: Scott DisannoProgram Manager: Carole SnyderProduction Project Manager: Pavithra Jayapaul,Jouve IndiaProcurement Manager: Mary FischerSenior Specialist, Program Planning and Support: Maura Zaldivar-GarciaAssistant Acquisitions Editor, Global Edition:Aditee AgarwalProject Editor, Global Edition: Amrita NaskarManager, Media Production, Global Edition:Vikram KumarSenior Manufacturing Controller, Production,Global Edition: Trudy KimberCover Designer: Lumina Datamatics Ltd.Manager, Rights Management: Rachel YoudelmanSenior Project Manager, Rights Management:Timothy NichollsCover Art: Viachaslau Kraskouski/ShutterstockFull-Service Project Management: MahalatchoumySaravanan, Jouve IndiaPearson Education LimitedEdinburgh GateHarlowEssex CM20 2JEEnglandand Associated Companies throughout the worldVisit us on the World Wide Web at:www.pearsonglobaleditions.com Pearson Education Limited 2016The rights of Robert W. Sebesta to be identified as the author of this work have been asserted by him inaccordance with the Copyright, Designs and Patents Act 1988.Authorized adaptation from the United States edition, entitled Concepts of Programming Languages, 11th edition,ISBN 978-0-13-394302-3, by Robert W. Sebesta, published by Pearson Education 2016.All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, ortransmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise,without either the prior written permission of the publisher or a license permitting restricted copying in theUnited Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, LondonEC 1N 8TS.All trademarks used herein are the property of their respective owners.The use of any trademark in t histext does not vest in the author or publisher any trademark ownership rights in such trademarks, nor doesthe use of such trademarks imply any affiliation with or endorsement of this book by such owners.Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademarkclaim, the designations have been printed in initial caps or all caps.ISBN 10: 1-292-10055-9ISBN 13: 978-1-292-10055-5British Library Cataloguing-in-Publication DataA catalogue record for this book is available from the British Library10 9 8 7 6 5 4 3 2 1Typeset in Janson Text LT Std 10/12 by AptaraPrinted and bound by Vivar in Malaysia

Changes for the Eleventh Editionof Concepts of Programming Languages Chapter 6: Deleted the discussions of Ada’s subrange types, array initialization, records,union types, pointers, and strong typing Chapter 7: Deleted the discussions of Ada operator associativity and mixed-mode expressions Chapter 8: Expanded the paragraph on F# selection statements in Section 8.2.1.5Deleted the discussion of the Ada for statement Chapter 9: Added three design issues for subprograms in Section 9.3Deleted the discussions of Ada and Fortran multidimensional parameters Chapter 10: Replaced example program Main 2, written in Ada, with an equivalent program written in JavaScript in Section 10.4.2Changed Figure 10.9 to reflect this new JavaScript example Chapter 11: Deleted the discussions of Ada abstract data types, generic procedures,and packagesAdded a new paragraph to Section 11.4.3 (Abstract Data Types in Java) Chapter 12: Added a paragraph to Section 12.2.2 (Inheritance) that discusses accesscontrolExpanded the discussion of class variables in Section 12.2.2Added a paragraph to Section 12.4.4 that discusses final classes in Objective-CReorganized Sections 12.5 to 12.9 into a single sectionAdded Table 12.1 on language design choices to Section 12.4.6.4Added a new section, Section 6 (Reflection), including example programs in Java and C# Chapter 13: Deleted the discussions of Ada task termination and task priorities Chapter 14: Deleted exception handling in AdaAdded a new section, 14.4 (Exception Handling in Python and Ruby)

This page intentionally left blank

PrefaceChanges for the Eleventh EditionThe goals, overall structure, and approach of this eleventh edition ofConcepts of Programming Languages remain the same as those of the tenearlier editions. The principal goals are to introduce the fundamentalconstructs of contemporary programming languages and to provide the readerwith the tools necessary for the critical evaluation of existing and future programming languages. A secondary goal is to prepare the reader for the study ofcompiler design, by providing an in-depth discussion of programming languagestructures, presenting a formal method of describing syntax, and introducingapproaches to lexical and syntactic analysis.The eleventh edition evolved from the tenth through several differentkinds of changes. To maintain the currency of the material, much of the discussion of older programming languages, particularly Ada and Fortran, hasbeen removed. For example, the descriptions of Ada’s records, union types, andpointers were removed from Chapter 6. Likewise, the description of Ada’s forstatement was removed from Chapter 8 and the discussion of Ada’s abstractdata types was removed from Chapter 11.On the other hand, a section on reflection that includes two completeprogram examples was added to Chapter 12, a section on exception handlingin Python and Ruby was added to Chapter 14, and a table of the design choicesof a few common languages for support for object-oriented programming wasadded to Chapter 12.In some cases, material has been moved. For example, Section 9.10 wasmoved backward to become the new Section 9.8.In one case, example program MAIN 2 in Chapter 10 was rewritten inJavaScript, previously having been written in Ada.Chapter 12 was substantially revised, with several new paragraphs, two newsections, and numerous other changes to improve clarity.The VisionThis book describes the fundamental concepts of programming languages bydiscussing the design issues of the various language constructs, examining thedesign choices for these constructs in some of the most common languages,and critically comparing design alternatives.7

8      PrefaceAny serious study of programming languages requires an examination ofsome related topics, among which are formal methods of describing the syntaxand semantics of programming languages, which are covered in Chapter 3.Also, implementation techniques for various language constructs must be considered: Lexical and syntax analysis are discussed in Chapter 4, and implementation of subprogram linkage is covered in Chapter 10. Implementation ofsome other language constructs is discussed in various other parts of the book.The following paragraphs outline the contents of the eleventh edition.Chapter OutlinesChapter 1 begins with a rationale for studying programming languages. It thendiscusses the criteria used for evaluating programming languages and languageconstructs. The primary influences on language design, common design tradeoffs, and the basic approaches to implementation are also examined.Chapter 2 outlines the evolution of the languages that are discussed inthis book. Although no attempt is made to describe any language completely,the origins, purposes, and contributions of each are discussed. This historicaloverview is valuable, because it provides the background necessary to understanding the practical and theoretical basis for contemporary language design.It also motivates further study of language design and evaluation. Because noneof the remainder of the book depends on Chapter 2, it can be read on its own,independent of the other chapters.Chapter 3 describes the primary formal method for describing the syntaxof programming language—BNF. This is followed by a description of attributegrammars, which describe both the syntax and static semantics of languages.The difficult task of semantic description is then explored, including briefintroductions to the three most common methods: operational, denotational,and axiomatic semantics.Chapter 4 introduces lexical and syntax analysis. This chapter is targeted tothose Computer Science departments that no longer require a compiler designcourse in their curricula. Similar to Chapter 2, this chapter stands alone andcan be studied independently of the rest of the book, except for Chapter 3, onwhich it depends.Chapters 5 through 14 describe in detail the design issues for the primaryconstructs of programming languages. In each case, the design choices for several example languages are presented and evaluated. Specifically, Chapter 5covers the many characteristics of variables, Chapter 6 covers data types, andChapter 7 explains expressions and assignment statements. Chapter 8 describescontrol statements, and Chapters 9 and 10 discuss subprograms and their implementation. Chapter 11 examines data abstraction facilities. Chapter 12 providesan in-depth discussion of language features that support object-oriented programming (inheritance and dynamic method binding), Chapter 13 discussesconcurrent program units, and Chapter 14 is about exception handling, alongwith a brief discussion of event handling.

Preface     9Chapters 15 and 16 describe two of the most important alternative programming paradigms: functional programming and logic programming.However, some of the data structures and control constructs of functionalprogramming languages are discussed in Chapters 6 and 8. Chapter 15 presents an introduction to Scheme, including descriptions of some of its primitive functions, special forms, and functional forms, as well as some examplesof simple functions written in Scheme. Brief introductions to ML, Haskell,and F# are given to illustrate some different directions in functional languagedesign. Chapter 16 introduces logic programming and the logic programminglanguage, Prolog.To the InstructorIn the junior-level programming language course at the University of Coloradoat Colorado Springs, the book is used as follows: We typically cover Chapters 1and 3 in detail, and though students find it interesting and beneficial reading,Chapter 2 receives little lecture time due to its lack of hard technical content.Because no material in subsequent chapters depends on Chapter 2, as notedearlier, it can be skipped entirely, and because we require a course in compilerdesign, Chapter 4 is not covered.Chapters 5 through 9 should be relatively easy for students with extensiveprogramming experience in C , Java, or C#. Chapters 10 through 14 are morechallenging and require more detailed lectures.Chapters 15 and 16 are entirely new to most students at the junior level.Ideally, language processors for Scheme and Prolog should be available forstudents required to learn the material in these chapters. Sufficient material isincluded to allow students to dabble with some simple programs.Undergraduate courses will probably not be able to cover all of the materialin the last two chapters. Graduate courses, however, should be able to completely discuss the material in those chapters by skipping over some parts ofthe early chapters on imperative languages.Supplemental MaterialsThe following supplements are available to all readers of this book at www.pearsonglobaleditions.com/Sebesta. A set of lecture note slides. PowerPoint slides are available for each chapterin the book. All of the figures from the book.A companion Web site to the book is available at www.pearsonglobaleditions.com/Sebesta. This site contains mini-manuals (approximately 100-page tutorials) ona handful of languages. These assume that the student knows how to program

10      Prefacein some other language, giving the student enough information to completethe chapter materials in each language. Currently the site includes manuals forC , C, Java, and Smalltalk.Solutions to many of the problem sets are available to qualified instructorsin our Instructor Resource Center at www.pearsonglobaleditions.com/Sebesta.Language Processor AvailabilityProcessors for and information about some of the programming languagesdiscussed in this book can be found at the following Web sites:C, C , Fortran, and Adagcc.gnu.orgC# and uby-lang.orgJavaScript is included in virtually all browsers; PHP is included in virtually allWeb servers.All this information is also included on the companion Web site.

AcknowledgmentsThe suggestions from outstanding reviewers contributed greatly to this book’spresent form and contents. In alphabetical order, they are:Aaron RababaahAmar RahejaAmer DiwanBob NeufeldBruce R. MaximCharles NicholasCristian Videira LopesCurtis MeadowDavid E. GoldschmidtDonald KraftDuane J. JarcEuripides MontagneFrank J. MitropoulosGloria MelaraHossein SaiedianI-ping ChuIan BarlandK. N. KingKarina AssiterMark LlewellynMatthew Michael BurkeMichael PrenticeNancy TinkhamNeelam SoundarajanNigel GweePamela CutterPaul M. JackowitzPaul TymannRichard M. OsborneRichard MinRobert McCloskeyRyan StansiferSalih YurttasSaverio PeruginiSerita NelesenSimon H. LinUniversity of Maryland at Eastern ShoreCalifornia State Polytechnic University–PomonaUniversity of ColoradoWichita State UniversityUniversity of Michigan–DearbornUniversity of Maryland–Baltimore CountyUniversity of California–IrvineUniversity of MaineLouisiana State UniversityUniversity of Maryland, University CollegeUniversity of Central FloridaNova Southeastern UniversityCalifornia State University–NorthridgeUniversity of KansasDePaul UniversityRadford UniversityGeorgia State UniversityWentworth Institute of TechnologyUniversity of Central FloridaSUNY BuffaloRowan UniversityOhio State UniversitySouthern University–Baton RougeKalamazoo CollegeUniversity of ScrantonRochester Institute of TechnologyUniversity of Colorado–DenverUniversity of Texas at DallasUniversity of ScrantonFlorida Institute of TechnologyTexas A&M UniversityUniversity of DaytonCalvin CollegeCalifornia State University–Northridge11

12      AcknowledgmentsStephen EdwardsStuart C. ShapiroSumanth YenduriTeresa ColeThomas TurnerTim R. NortonTimothy HenryWalter PharrXiangyan ZengVirginia TechSUNY BuffaloUniversity of Southern MississippiBoise State UniversityUniversity of Central OklahomaUniversity of Colorado–Colorado SpringsUniversity of Rhode IslandCollege of CharlestonFort Valley State UniversityNumerous other people provided input for the previous editions of Concepts of Programming Languages at various stages of its development. All of theircomments were useful and greatly appreciated. In alphabetical order, they are:Vicki Allan, Henry Bauer, Carter Bays, Manuel E. Bermudez, Peter Brouwer,Margaret Burnett, Paosheng Chang, Liang Cheng, John Crenshaw, CharlesDana, Barbara Ann Griem, Mary Lou Haag, John V. Harrison, Eileen Head,Ralph C. Hilzer, Eric Joanis, Leon Jololian, Hikyoo Koh, Jiang B. Liu, MeiliuLu, Jon Mauney, Robert McCoard, Dennis L. Mumaugh, Michael G. M urphy,Andrew Oldroyd, Young Park, Rebecca Parsons, Steve J. Phelps, JefferyPopyack, Steven Rapkin, Hamilton Richard, Tom Sager, Raghvinder Sangwan,Joseph Schell, Sibylle Schupp, Mary Louise Soffa, Neelam Soundarajan, RyanStansifer, Steve Stevenson, Virginia Teller, Yang Wang, John M. Weiss, FranckXia, and Salih Yurnas.Matt Goldstein, editor; Kelsey Loanes, editorial assistant; Team Lead Product Management, Scott Disanno; Pavithra Jayapaul, and MahalatchoumySaravanan, all deserve my gratitude for their efforts to produce the eleventh edition both quickly and carefully.The publishers would like to thank the following for reviewing the GlobalEdition:Sandeep B. L., M. S. Ramaiah Institute of TechnologyKoushik S., M. S. Ramaiah Institute of TechnologySheena V. M., Don Bosco College

About the AuthorRobert Sebesta is an Associate Professor Emeritus in the Computer ScienceDepartment at the University of Colorado–Colorado Springs. ProfessorSebesta received a BS in applied mathematics from the University of Coloradoin Boulder and MS and PhD degrees in computer science from PennsylvaniaState University. He has taught computer science for more than 40 years. Hisprofessional interests are the design and evaluation of programming languagesand Web programming.13

This page intentionally left blank

ContentsChapter 1Preliminaries251.1Reasons for Studying Concepts of Programming Languages.261.2Programming Domains.291.3Language Evaluation Criteria.301.4Influences on Language Design.411.5Language Categories.441.6Language Design Trade-Offs.451.7Implementation Methods.461.8Programming Environments.53Summary Review Questions Problem Set.54Chapter 2Evolution of the Major Programming Languages572.1Zuse’s Plankalkül.602.2Pseudocodes.612.3The IBM 704 and Fortran.642.4Functional Programming: Lisp.692.5The First Step Toward Sophistication: ALGOL 60.742.6Computerizing Business Records: COBOL.802.7The Beginnings of Timesharing: Basic.85Interview: Alan Cooper—User Design and Language Design. 882.8Everything for Everybody: PL/I.902.9Two Early Dynamic Languages: APL and SNOBOL.932.10 The Beginnings of Data Abstraction: SIMULA 67.942.11 Orthogonal Design: ALGOL 68.952.12 Some Early Descendants of the ALGOLs.9715

16      Contents2.13 Programming Based on Logic: Prolog.1012.14 History’s Largest Design Effort: Ada.1032.15 Object-Oriented Programming: Smalltalk.1072.16 Combining Imperative and Object-Oriented Features: C .1092.17 An Imperative-Based Object-Oriented Language: Java.1122.18 Scripting Languages.1152.19 The Flagship .NET Language: C#.1222.20 Markup-Programming Hybrid Languages.124Summary Bibliographic Notes Review Questions Problem Set Programming Exercises.126Chapter 3Describing Syntax and Semantics1333.1Introduction.1343.2The General Problem of Describing Syntax.1353.3Formal Methods of Describing Syntax.1373.4Attribute Grammars.152History Note.1523.5Describing the Meanings of Programs: Dynamic Semantics.158History Note.166Summary Bibliographic Notes Review Questions Problem Set.179Chapter 4Lexical and Syntax Analysis1854.1Introduction.1864.2Lexical Analysis.1874.3The Parsing Problem.1954.4Recursive-Descent Parsing.1994.5Bottom-Up Parsing.207Summary Review Questions Problem Set Programming Exercises.215Chapter 5Names, Bindings, and Scopes2215.1Introduction.2225.2Names.223

Contents     17History Note.2235.3Variables.2245.4The Concept of Binding.2275.5Scope.2355.6Scope and Lifetime.2465.7Referencing Environments.2475.8Named Constants.248Summary Review Questions Problem Set Programming Exercises.251Chapter 6Data Types2596.1Introduction.2606.2Primitive Data Types.2626.3Character String Types.266History Note.2676.4Enumeration Types.2716.5Array Types.274History Note.275History Note.2756.6Associative Arrays.285Interview: ROBERTO IERUSALIMSCHY—Lua. 2866.7Record Types.2896.8Tuple Types.2926.9List Types.2946.10 Union Types.2966.11 Pointer and Reference Types.299History Note.3026.12 Type Checking.3116.13 Strong Typing.3126.14 Type Equivalence.3136.15 Theory and Data Types.317Summary Bibliographic Notes Review Questions Problem Set Programming Exercises.319

18      ContentsChapter 7Expressions and Assignment Statements3257.1Introduction.3267.2Arithmetic Expressions.3267.3Overloaded Operators.3357.4Type Conversions.337History Note.3397.5Relational and Boolean Expressions.340History Note.3407.6Short-Circuit Evaluation.3427.7Assignment Statements.343History Note.3477.8Mixed-Mode Assignment.348Summary Review Questions Problem Set Programming Exercises. 348Chapter 8Statement-Level Control Structures3538.1Introduction.3548.2Selection Statements.3568.3Iterative Statements.3678.4Unconditional Branching.379History Note.3798.5Guarded Commands.3808.6Conclusions.382Summary Review Questions Problem Set Programming Exercises. 383Chapter 9Subprograms3899.1Introduction.3909.2Fundamentals of Subprograms.3909.3Design Issues for Subprograms.3989.4Local Referencing Environments.3999.5Parameter-Passing Methods.401History Note.409

Contents     19History Note.4099.6Parameters That Are Subprograms.417History Note.4199.7Calling Subprograms Indirectly.4199.8Design Issues for Functions.4219.9Overloaded Subprograms.4239.10 Generic Subprograms.4249.11 User-Defined Overloaded Operators.4309.12 Closures.

(step-by-step video tutorials on programming concepts), source code, web chapters, quizzes, and more. Refer to the preface in the textbook for a detailed list of resources. Follow the instructions below to register for the Companion Website for Robert Sebesta’s Concepts of Programming