the newtonscript programming language

Upload: pablomarx

Post on 02-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 The NewtonScript Programming Language

    1/212

    The NewtonScriptProgramming Language

  • 7/27/2019 The NewtonScript Programming Language

    2/212

    Apple Computer, Inc. 1993, 1994, Apple Computer, Inc.All rights reserved.No part of this publication or thesoftware described in it may bereproduced, stored in a retrievalsystem, or transmitted, in any formor by any means, mechanical,electronic, photocopying,recording, or otherwise, withoutprior written permission of AppleComputer, Inc., except in the normaluse of the software or to make a

    backup copy of the software. Thesame proprietary and copyrightnotices must be affixed to anypermitted copies as were affixed tothe original. This exception does notallow copies to be made for others,whether or not sold, but all of thematerial purchased (with all

    backup copies) may be sold, given,or loaned to another person. Underthe law, copying includestranslating into another language orformat. You may use the software onany computer owned by you, butextra copies cannot be made for thispurpose.Printed in the United States ofAmerica.

    The Apple logo is a registeredtrademark of Apple Computer, Inc.Use of the keyboard Apple logo(Option-Shift-K) for commercialpurposes without the prior writtenconsent of Apple may constitutetrademark infringement and unfaircompetition in violation of federaland state laws.No licenses, express or implied, aregranted with respect to any of thetechnology described in this book.Apple retains all intellectualproperty rights associated with thetechnology described in this book.This book is intended to assistapplication developers to develop

    applications only for licensedNewton platforms.

    Apple Computer, Inc.20525 Mariani AvenueCupertino, CA 95014408-996-1010

    Apple, the Apple logo, APDA,AppleLink, LaserWriter,Macintosh, and Newton aretrademarks of Apple Computer,Inc., registered in the United Statesand other countries.The light bulb logo, MessagePad,NewtonScript, and Newton Toolkitare trademarks of Apple Computer,Inc.

    Adobe Illustrator and PostScriptare trademarks of Adobe SystemsIncorporated, which may beregistered in certain jurisdictions.FrameMaker is a registeredtrademark of Frame TechnologyCorporation.Helvetica and Palatino areregistered trademarks of LinotypeCompany.ITC Zapf Dingbats is a registeredtrademark of InternationalTypeface Corporation.

    Simultaneously published in theUnited States and Canada.

    LIMITED WARRANTY ON MEDIA

    AND REPLACEMENT

    If you discover physical defects in the

    manual or in the media on which a

    software product is distributed, APDA

    will replace the media or manual at no

    charge to you provided you return the

    item to be replaced with proof of

    purchase to APDA.

    ALL IMPLIED WARRANTIES ON

    THIS MANUAL, INCLUDING

    IMPLIED WARRANTIES OF

    MERCHANTABILITY AND FITNESS

    FOR A PARTICULAR PURPOSE, ARE

    LIMITED IN DURATION TO NINETY

    (90) DAYS FROM THE DATE OF THE

    ORIGINAL RETAIL PURCHASE OF

    THIS PRODUCT.

    Even though Apple has reviewed this

    manual, APPLE MAKES NO

    WARRANTY OR REPRESENTATION,

    EITHER EXPRESS OR IMPLIED,

    WITH RESPECT TO THIS MANUAL,

    ITS QUALITY, ACCURACY,

    MERCHANTABILITY, OR FITNESSFOR A PARTICULAR PURPOSE. AS A

    RESULT, THIS MANUAL IS SOLD

    AS IS, AND YOU, THE

    PURCHASER, ARE ASSUMING THE

    ENTIRE RISK AS TO ITS QUALITY

    AND ACCURACY.

    IN NO EVENT WILL APPLE BE

    LIABLE FOR DIRECT, INDIRECT,

    SPECIAL, INCIDENTAL, OR

    CONSEQUENTIAL DAMAGES

    RESULTING FROM ANY DEFECT OR

    INACCURACY IN THIS MANUAL,

    even if advised of the possibility of

    such damages.

    THE WARRANTY AND REMEDIES

    SET FORTH ABOVE ARE EXCLUSIVEAND IN LIEU OF ALL OTHERS,

    ORAL OR WRITTEN, EXPRESS OR

    IMPLIED. No Apple dealer, agent, or

    employee is authorized to make any

    modification, extension, or addition to

    this warranty.

    Some states do not allow the exclusion

    or limitation of implied warranties or

    liability for incidental or consequential

    damages, so the above limitation or

    exclusion may not apply to you. This

    warranty gives you specific legal rights,

    and you may also have other rights

    which vary from state to state.

  • 7/27/2019 The NewtonScript Programming Language

    3/212

    PREFACE

    xi

    About This Book

    The NewtonScript Programming Language, is the definitive referencefor anyone learning the NewtonScript programming language.If you are planning to begin developing applications for theNewton platform, you should read this book first. After youare familiar with the NewtonScript language you should readtheNewton Programmers Guide for implementation details and theNewton Toolkit Users Guide to learn how to install and use NewtonToolkit, which is the development environment for writingNewtonScript programs for the Newton platform.

    About the Audience

    This book is for programmers who have experience with highlevel programming languages, like C or Pascal, and who alreadyunderstand object-oriented programming concepts.

    If you are not familiar with the concepts of object-oriented

    programming there are many books available on the subjectavailable at your local computer bookstore.

    Related Books

    This book is one in a set of books included with Newton Toolkit,the Newton development environment. Youll also need to refer tothese other books in the set:

    n Newton Programmers Guide. This book is the definitive guideand reference for Newton programming. This book explains

    how to write Newton programs and describes the systemsoftware routines that you can use to do so.

  • 7/27/2019 The NewtonScript Programming Language

    4/212

    PREFACE

    xii

    n Newton Toolkit Users Guide. This book introduces the Newtondevelopment environment and shows how to develop Newtonapplications using Newton Toolkit. You may want to read thisbook first if you are a new Newton application developer.

    n Newton Book Maker Users Guide. This book describes how touse Newton Book Maker and Newton Toolkit to make Newtondigital books and to add online help to Newton applications.This book is included only if you purchased the NewtonToolkit package that includes Book Maker.

    n Newton Human Interface Guidelines. This book contains guide-

    lines to help you design Newton applications that optimize theinteraction between people and Newton devices.

    Sample Code

    The Newton Toolkit product includes many sample code projects.You can examine these samples, learn from them, experiment withthem, and use them as a starting point for your own applications.These sample code projects illustrate most of the topics covered inthis book. They are an invaluable resource for understanding the

    topics discussed in this book and for making your journey into theworld of Newton programming an easier one.

    The PIE Developer Technical Support team continually revises theexisting samples and creates new sample code. You can find thelatest collection of sample code in the Newton developer area onAppleLink. You can gain access to the sample code by participat-ing in the PIE developer support program. For information abouthow to contact Apple regarding the PIE developer supportprogram, see the section Developer Products and Support, onpage xiv.

  • 7/27/2019 The NewtonScript Programming Language

    5/212

  • 7/27/2019 The NewtonScript Programming Language

    6/212

    PREFACE

    xiv

    Developer Products and Support

    APDA is Apples worldwide source for a large number ofdevelopment tools, technical resources, training products, andinformation for anyone interested in developing applications onApple platforms. Every four months, customers receive theAPDATools Catalog featuring all current versions of Apple and the mostpopular third-party development tools. Ordering is easy; there areno membership fees, and application forms are not required formost of our products. APDA offers convenient payment and

    shipping options, including site licensing.To order product or to request a complimentary copy of theAPDATools Catalog:

    APDAApple Computer, Inc.P.O. Box 319Buffalo, NY 14207-0319

    {choose|one} A group of words, separated by vertical bars(|) and grouped with curly brackets, indicatesan either/or choice.

    []* An asterik (*) indicates that the precedingitem(s), which is enclosed in square brackets,can be repeated zero or more times.

    []+ A plus sign (+) indicates that the precedingitem(s), which is enclosed in square brackets,can be repeated one or more times.

    Telephone 1-800-282-2732 (United States)1-800-637-0029 (Canada)716-871-6555 (International)

    Fax 716-871-6511

    AppleLink APDA

  • 7/27/2019 The NewtonScript Programming Language

    7/212

  • 7/27/2019 The NewtonScript Programming Language

    8/212

    iii

    Contents

    Figures, Tables, and Lisings ix

    Preface xi

    About the Audience xiRelated Books xiSample Code xiiConventions Used in This Book xiii

    Special Fonts in Text xiiiSyntax Conventions xiii

    Developer Products and Support xiv

    Chapter 1 Overview 1-1

    Introduction 1-1

    Semantic Overview 1-2Expressions 1-2The Object Model 1-2Data Types and Classes 1-3Scope 1-4Extent 1-6Garbage Collection 1-6How Is NewtonScript Dynamic? 1-7

    Basic Syntax 1-8Semicolon Separators 1-8In-Line Object Syntax 1-9Character Set 1-9

    Comments 1-10A Code Example 1-10

  • 7/27/2019 The NewtonScript Programming Language

    9/212

  • 7/27/2019 The NewtonScript Programming Language

    10/212

    v

    Chapter 3 Flow of Control 3-1

    Compound Expressions 3-1IfThenElse 3-2Iterators 3-3

    For 3-4Foreach 3-6Loop 3-10While 3-11Repeat 3-12Break 3-12

    Exception Handling 3-13Working with Exceptions 3-14

    Defining Exceptions 3-15Exception Symbol Parts 3-16Exception Frames 3-16

    The Try Statement 3-18Throwing Exceptions 3-18

    Throwing an Exception to Another Handler 3-20Catching Exceptions 3-20Responding to Exceptions 3-22

    Chapter 4 Functions and Methods 4-1

    About Functions and Methods 4-1Func Definition 4-2Return 4-2

    Messages 4-3Message-Send Operators 4-3

    Function Invocations 4-7Call With 4-7Global Function Invocation 4-8Global Function Definition 4-8

    Passing Parameters 4-9Function Objects 4-9

  • 7/27/2019 The NewtonScript Programming Language

    11/212

    vi

    Function Context 4-10The Lexical Environment 4-10The Message Environment 4-11An Example Function Object 4-12Using Function Objects in Advanced Ways 4-13

    Chapter 5 Inheritance and Lookup 5-1

    Inheritance 5-1Prototype Inheritance 5-2

    Creating Prototype Frames 5-2Prototype Inheritance Rules 5-3

    Parent Inheritance 5-4Creating Parent Frames 5-4Parent Inheritance Rules 5-5

    Combining Prototype and Parent Inheritance 5-5Inheritance Rules for Setting Slot Values 5-7An Object-Oriented Example 5-8

    Chapter 6 Built-In Functions 6-1

    Object System Functions 6-2String Functions 6-8Bitwise Functions 6-13Array Functions 6-13Integer Math Functions 6-20Floating Point Math Functions 6-22

    Managing the Floating Point Environment 6-35Financial Function 6-38Exception Functions 6-38Message Sending Functions 6-40Data Extraction Functions 6-42Data Stuffing Functions 6-46

    Miscellaneous Functions 6-50Summary of Functions and Methods 6-53

  • 7/27/2019 The NewtonScript Programming Language

    12/212

    vii

    Appendix A Reserved Words A-1

    Appendix B Special Character Codes B-1

    Appendix C Class-Based Programming C-1

    What Are Classes Good For? C-1Classes: A Brief Reminder C-2Inheritance in NewtonScript C-3The Basic Idea C-3Practical Issues C-6Class Variables C-7Superclasses C-9Using Classes to Encapsulate Soup Entries C-10ROM Instance Prototypes C-10Leaving Instances Behind C-11Conclusion C-11

    Appendix D NewtonScript Syntax Definition D-1

    About the Grammar D-1Phrasal Grammar D-2Lexical Grammar D-6Operator Precedence D-7

    Appendix E Quick Reference Card E-1

  • 7/27/2019 The NewtonScript Programming Language

    13/212

    viii

    Glossary GL-1

    Index GL-1

  • 7/27/2019 The NewtonScript Programming Language

    14/212

    ix

    Figures, Tables, and Listings

    Chapter 1 Overview 1-1

    Figure 1-1 A sample data structure 1-4

    Listing 1-1 A simple frame 1-3

    Listing 1-2 A dynamic example 1-11

    Chapter 2 Objects, Expressions, and Operators 2-1

    Figure 2-1 NewtonScript built-in classes 2-3

    Figure 2-2 C code example 2-22

    Figure 2-3 A NewtonScript code sample 2-23

    Table 2-1 Characters with special meanings 2-4

    Table 2-2 Codes for specifying special characterswithin strings 2-8

    Table 2-3 Special slot names and their specifications 2-13

    Table 2-4 Constant substitution work-arounds 2-18

    Table 2-5 Operator precedence and associativity 2-32

    Chapter 3 Flow of Control 3-1

    Figure 3-1 Data objects and their relationships 3-9

    Table 3-1 Result comparison for the iterator foreach andforeachdeeply 3-10

    Table 3-2 Exception frame data slot name and contents 3-16

    Table 3-3 Exception frame examples 3-17

    Listing 3-1 Exception symbol 3-15

    Listing 3-2 The Throw function 3-19

    Listing 3-3 Several onexception clauses orderedimproperly 3-21

  • 7/27/2019 The NewtonScript Programming Language

    15/212

    x

    Listing 3-4 The onexception clauses properly ordered 3-22

    Listing 3-5 Handling a soup store exception 3-22

    Listing 3-6 An exception handler checking the exceptionframe 3-23

    Chapter 4 Functions and Methods 4-1

    Figure 4-1 The parts of a function object. 4-10

    Figure 4-2 A run-time function object snapshot 4-13

    Chapter 5 Inheritance and Lookup 5-1

    Figure 5-1 A prototype frame 5-2

    Figure 5-2 A prototype chain 5-3

    Figure 5-3 Parent-child relationship 5-4

    Figure 5-4 Prototype and parent inheritance interactionorder 5-6

    Figure 5-5 An inheritance structure 5-9

    Chapter 6 Built-In Functions 6-1

    Table 6-1 Floating point exceptions 6-35

    Table 6-2 Exception frame data slot name and contents 6-39

    Appendix B Special Character Codes B-1

    Table B-1 Character codes sorted by Macintoshcharacter code B-1

    Table B-2 Character codes sorted by Unicode B-7

  • 7/27/2019 The NewtonScript Programming Language

    16/212

    Introduction 1-1

    CHAPTER1

    Overview

    NewtonScript is a state-of-the-art, dynamic, object-oriented programminglanguage; developed for the Newton platform.

    Introduction

    In creating NewtonScript, the overriding goal was to enable developers toeasily create fast, smart applications. Therefore the language had to be

    n effective; for its intended use of writing Newton applications

    n expressive and flexible; to make it straightforward to use

    n consistent; to allow reuse of concepts and structures

    n portable; to allow exploration of different architectures

    n small; to allow it to work with limited RAM

    The constraints of the Newton system required a language that couldproduce reusable code libraries, had both efficient use of memory andautomatic garbage collection.

  • 7/27/2019 The NewtonScript Programming Language

    17/212

    CHAPTER 1

    Overview

    1-2 Semantic Overview

    The language worked with principles that were used first in languages likeSmalltalk and LISP. NewtonScript was further inspired by work done on thelanguage Self, at Stanford University.

    Semantic Overview

    This section briefly introduces some of the special features of theNewtonScript language.

    Expressions

    NewtonScript is an expression-based language. Almost everythingin NewtonScript returns a value. Therefore, we talk about expressionsrather than statements in this manual.

    The Object Model

    NewtonScript has an underlying object system upon which it is built. Alldata is stored as objectsor typed pieces of data. This is different from otherobject-oriented languages like C++ or Object Pascal, where data consists of ahybrid of objects and regular data types.

    NewtonScript is also different from Smalltalk, which also represents all dataas objects. Only one kind of NewtonScript object, the frame, can receivemessages.

    The Newton object model structures data by using two kinds of 32-bit valuesto represent objects. They are

    n immediatesin which the 32 bits contain immutable data

    n referencesin which the 32 bits refer indirectly to an object

    For more information about NewtonScript objects see Chapter 2, Objects,

    Expressions, and Operators.

  • 7/27/2019 The NewtonScript Programming Language

    18/212

    CHAPTER 1

    Overview

    Semantic Overview 1-3

    Data Types and Classes

    NewtonScript uses a class as a semantic type as opposed to a typical datatype. The Newton platform uses classes to let parts of the system, like theIntelligent Assistant (which is described in the Newton Programmers Guide)determine things about an object at run time. Thus it can treat particulartypes of objects in interesting and different ways.

    For instance, you can set up a data object containing personal data as shownin Listing 1-1. Note that he curly braces surrounding Listing 1-1 denote aframe object which contains placesor slotsfor objects that have the

    identifiers: name, company, and phones.

    Listing 1-1 A simple frame

    { name: "Walter Smith",

    company: "Apple Computer",

    phones: ["408-996-1010", "408-123-4566"] }

    In the Newton system, objects can be typed further. For instance, the valuesofname andcompany are plain strings. However, phones could be furtherdefined as being of type workPhone andfaxPhone. These user-defined

    objects could then be manipulated by the Newton system in different ways.For instance, when the person using your application chooses to send a faxphone number, a set of actions different from those for a work phone numberare initiated.

    The data object constructed in Listing 1-1 is shown inFigure 1-1.

    The facility that lets the system know about the type of an object is knownas latent typing. Types are associated with objects. This means that avariable can hold any kind of object and can hold different types of objects atdifferent times.

    For more information about specific NewtonScript objects see Chapter 2,Objects, Expressions, and Operators.

  • 7/27/2019 The NewtonScript Programming Language

    19/212

  • 7/27/2019 The NewtonScript Programming Language

    20/212

  • 7/27/2019 The NewtonScript Programming Language

    21/212

    CHAPTER 1

    Overview

    1-6 Semantic Overview

    When you send the message,bar, with a parameter value of ten, to theaFrame object, in the expression

    aFrame:bar(10)

    a value of 42 is returned. The same message with a parameter value ofnegative five

    aFrame:bar(-5)

    returns nil. See also Accessing Functions to learn more about messagesending.

    Extent

    The extent of a variable refers to the period of time in which a variable maybe used. In many languages, the scope of a variable is the same thing as itsextent. However, in NewtonScript a variable has data storage space allocatedfor it while it is referenced anywhere in executing code.

    Automatic garbage collection occurs only after an object is no longerreferenced anywhere. Therefore, storage allocated for data structures isavailable until no references to the structure exist.

    You should make sure not to leave any references to large data structuresyouve allocated after youre done using them. If you do, NewtonScript willnot reclaim the associated memory.

    One example on the Newton platform of where you might think about this iswhen you close an applicationyou can set slots to nil in the applicationsbase frame.

    Garbage Collection

    In NewtonScript, garbage collectionthat is, reclaiming the storage of objectsthat are no longer usedis carried out automatically by the system. Thus theprogrammer does not need to worry about memory management. In fact, its

  • 7/27/2019 The NewtonScript Programming Language

    22/212

    CHAPTER 1

    Overview

    Semantic Overview 1-7

    impossible to have dangling pointers, which often cause the mostinsidious and hard to find bugs in an application.

    If youve had to do garbage disposal manually in another language you canrelax; the Newton system reclaims memory for you sometime after the lastreference to an object goes away. Setting the value of all slots and variablesreferring to an object to nil allows the Newton garbage collector to reclaimthe memory used by the object.

    Automatic garbage collection is triggered every time the system runs out ofmemory. Theres not really any reason to invoke garbage collection manually.However, if you must do so, you can call the global function GC. (SeeChapter 6, Built-in functions.

    How Is NewtonScript Dynamic?

    In general, the term dynamic refers to the ability of the language to changethings at run time. Therefore, the NewtonScript dynamic model is usefulwhen you want to change an object at run time. For instance, if you neededto change an object to another kind of object in response to a users actionswhile the application is running, you can.

    You can also add new data to objects while an application is in use. Forinstance, you can write NewtonScript code which dynamically adds a new

    variable to an executing object at run time and uses it, then adds a method tothe same object and uses it, and finally changes the inheritance structure ofthe object by adding a special reference to another object. (This shows as

    _parent in Listing 1-2 on page 1-11). The object can now use a method itinherits from the parent frame.

    All of these operations are impossible in a static language, and they require agreat deal of thought and discipline in dynamic languages. Though thispowerful feature enables you to interactively program in a way that isimpossible in static languages, it should be used sparingly and with caution.

  • 7/27/2019 The NewtonScript Programming Language

    23/212

    CHAPTER 1

    Overview

    1-8 Basic Syntax

    Basic Syntax

    Rather than invent yet an entirely new syntax, NewtonScript wasdesigned with Pascal in mind. Wherever possible, the syntax is modeledclosely after Pascal.

    Semicolon Separators

    The semicolon (;) is used to separate lines, not to terminate them. Thoughsemicolons are not required at the end of a line, you may spread oneexpression over several lines or enter multiple expressions on a single lineby using the semi-colon.

    Expressions can be entered in a free-form manner, but we recommend thatstandard indentation be used for enhanced readability, as in this example:

    if expression then

    expression

    else

    another expression;

    Note that you may use as much whitespace as you wish; it is ignored.

    Note

    If you forget to add an important semicolon at the end of aNewtonscript expression, the interpreter uses whatever is onthe next line as it tries to interpret a larger statement thanintended, thus causing unusual error reports. For anexample, see the code in the Note on page 4-6. u

  • 7/27/2019 The NewtonScript Programming Language

    24/212

    CHAPTER 1

    Overview

    Basic Syntax 1-9

    In-Line Object Syntax

    NewtonScript has two syntax features, object literals and object constructors,that make it easy to create objects.

    The object literal syntax lets you put a complex object into your program aseasily as an integer. This syntactic mode is entered by writing a single quote,as shown in this simple example of a frame containing two strings:

    x := '{name: "xxx", phone: "yyy"};

    The object is constructed at compile time, and a reference to the same object

    results each time the object literal is evaluated.The object constructor syntax makes it easy to construct objects at run time.The syntax is similar to object literals, but without the quote. In the objectconstructor syntax the slot value positions are evaluated expressions ratherthan nested literals. Each time the constructor is evaluated, a new object iscreated, and its slots are filled in with the results of the slot expressions. Anobject constructor is much easier to read than the equivalent operationwritten without it, as shown in the following two examples.

    First, the example with a constructor:

    x := {name: first && last, tax: wage * taxRate};

    Finally, the equivalent operation without the object constructor:

    x := {};

    x.name := first && last;

    x.tax := wage * taxRate;

    Character Set

    NewtonScript uses the standard 7-bit ASCII character set rather than theenhanced ASCII character set used by Macintosh computers. This ensuresthat your code will work in any Newton development environment.

  • 7/27/2019 The NewtonScript Programming Language

    25/212

    CHAPTER 1

    Overview

    1-10 A Code Example

    Comments

    NewtonScript uses the same convention for delineating comments as is usedin the C++ programming language. Multi-line comment text needs to besurrounded by an opening right slash, asterisk (/*) and a matching asterisk,

    right slash (*/) at the end. For example

    /* This is an example of

    a comment. It can be on one line

    or as many lines as you need. */

    If your comment is short enough to stay on one line, you can use two rightslashes (//) before the text to signal that the rest of the line is a comment andshould be ignored. This is often useful for putting a comment on the sameline as a line of code as in this example:

    x:= 5 ; //This is a single-line comment.

    Note that nested multi-line comments are not allowed. However, within a /*... */ comment block, comments using the // notation are allowed.

    A Code Example

    If you like to try to understand code before you read the manual, continue onthrough this section, otherwise stop here and go to the next chapter.

    Note that in the code the curly brackets ({}) denote a frame object and thecolon-equal (:=) is the assignment operator, and the colon (:) is themessage-send operator, which sends the message following it to the frameexpression appearing before it.

    The code shown in Listing 1-2 is described in How Is NewtonScriptDynamic? beginning on page 1-7.

  • 7/27/2019 The NewtonScript Programming Language

    26/212

    CHAPTER 1

    Overview

    A Code Example 1-11

    Listing 1-2 A dynamic example

    y := { YMethod: func () print("Y method"), yVar: 14 };

    x := { Demo: func () begin

    self.newVar := 37;

    print(newVar);

    self.NewMethod := func () print("hello");

    self:NewMethod();

    self._parent := y;

    print(yVar);

    self:YMethod();

    end

    };

    x:Demo();

  • 7/27/2019 The NewtonScript Programming Language

    27/212

  • 7/27/2019 The NewtonScript Programming Language

    28/212

  • 7/27/2019 The NewtonScript Programming Language

    29/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Objects and the Class System 2-3

    Figure 2-1 NewtonScript built-in classes

    Character

    $ { nonEscapeCharacter|\ { \ | n | t | uhexDigithexDigit |uhexDigithexDigit hexDigit hexDigit} }

    Characters in the standard character set are specified in your code by thedollar sign ($) and

    n a backslash escape character (\) followed by a special characterspecification such as, n, t, u, or 2 hexadecimal digits.

    n a backslash escape character (\) followed by u (for unicode) and fourhexadecimal digits.

    n a non-escape character.

  • 7/27/2019 The NewtonScript Programming Language

    30/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-4 Objects and the Class System

    The character set in Newton is stored as Unicode, in two bytes, to facilitateinternational conversions. By design, the first 128 characters match the first128 characters of the Macintosh standard character set. You must useUnicode character codes to specify special characters other than the ASCIIcharacter set.

    Characters are immediate objects. (For more information about immediateobjects see The Object Model beginning on page 1-2.)

    nonEscapeCharacter Consists of any ASCII character with code 32127 exceptthe back slash (\).

    hexDigit Consists of: {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9| a |b| c | d | e | f | A| B | C | D | E | F}

    For example, $a or $7 represent the characters a and 7, respectively.

    Special characters like must be specified as Unicode (16-bit) charactersby using the four-digit hex character code preceded by $\u. For example, the

    Unicode equivalent of is: $\uF7FF

    You specify a new line by imbedding the code $\n in a string. Specialcharacter codes are summarized in Table 2-1.

    See Appendix C, Special Character Codes for a list of the special charactersand their Unicode equivalents.

    Table 2-1 Characters with special meanings

    Character code Meaning

    $\n newline character$\t tab character$\\ backslash character$\ hexDigit hexDigit hexadecimal$\u hexDigit hexDigit hexDigit hexDigit Unicode

  • 7/27/2019 The NewtonScript Programming Language

    31/212

  • 7/27/2019 The NewtonScript Programming Language

    32/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-6 Objects and the Class System

    Real

    [-] [digit ]+.[ digit ]* [ { e | E } [ - ] [ digit ]+

    A real number consists of one or more digits followed by a decimal pointwith zero or more additional digits. The optional minus (-) at the startindicates a negative number. You can specify scientific notation by placingthe letter e (upper or lower case) directly after the last digit and followingit with a negative or positive digit in the range of -308 to +308.

    digit Consists of: {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}

    NewtonScript floating point real numbers are represented internally indouble precision; 64 bits. They have approximately 15 decimal digits ofprecision. Some examples of real numbers include:

    -0.587 123.9 3.141592653589

    Here are some examples of exponential notation used to representreal numbers:

    763.112e4 87.3789E-45 -34.2e6 69.e-5

    Real numbers are stored as binary objects and have the class Real.

    Symbol

    { { alpha |_} [ { alpha | digit |_} ]* |'|' [ { symbolChar|\ { '|' | \ } ]* '|'}

    A symbol is an object used as an identifier. NewtonScript uses symbols toname variables, classes, messages, and frame slots. You can also use symbolsas simple identifying values, as you would use enumerated types in otherlanguages.

    Symbol names may be up to 254 characters and may include any printableASCII character; for instance, |Weird%Symbol!| is valid. A symbol can bewritten by itself, without being enclosed in vertical bars, if it begins with analphabetic character or an underscore and contains only alphabetic

    characters, underscores, and digits. NewtonScript is case insensitive, thoughit preserves case.

  • 7/27/2019 The NewtonScript Programming Language

    33/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Objects and the Class System 2-7

    alpha Consists of: {0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}.

    digit Consists of: {AZ andaz}.

    symbolChar Consists of any ASCII character with code 32127 except| or \.

    One place where the Newton system requires symbols is in exceptionhandling. An example of an exception symbol is: |evt.ex.fr.intrp|Note that vertical bars are required because of the dots in the symbol. Youcan read more about them in Defining Exceptions beginning on page 3-15.

    Symbols appearing in expressions are normally evaluated as variable

    references. You can prevent this by preceding the symbol with a single quote('). The quoted symbol evaluates to the symbol itself. See also QuotedConstant beginning on page 2-18.

    String

    " [ { stringChar | escSeq } ]* [ truncEscape ] ] "

    A string constant is written as a sequence of characters enclosed indouble-quotation marks.

    stringChar Consists of a tab character or any ASCII character withcode 32127 except the double quote (") or backslash (\).

    escSeq Consists of either a special character specificationsequence or a unicode specification sequence.The specialcharacter specification sequence is: backslash (\)followed by a quote ("), backslash (\), the letter n orthe letter t. The escape sequence for specifying Unicodebegins with backslash-u (\u), is followed by any number

    of groups of four hexDigits, and ends with backslash-u(\u).

    truncEscape Consists of the shortened unicode specificationsequence. It is: backslash-u (\u), is followed by

    any number of groups of four hexDigits.

  • 7/27/2019 The NewtonScript Programming Language

    34/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-8 Objects and the Class System

    Here are some simple examples of strings:

    "pqr" "Now is the time" ""

    Within strings you can include Unicode characters that are not in thestandard character set by inserting the escape code, \u, to toggle on theUnicode hex mode. Follow the \u with any number of groups of four-number codes specifying the special character. You can add another \u totoggle the Unicode hex mode off and return to the regular character set,though, you are not required to toggle the hex mode off. (See Appendix B,Special Character Codes, for a list of these characters.)

    For example, you could specify the French phrase, Garon, laddition, silvous plat!, by embedding Unicode in the string to specify the specialcharacters as follows:

    "Gar\u00e7\uon, laddition, sil vous pla\u00ee\ut!"

    Other codes you use within strings to specify special characters aresummarized in Table 2-2.

    Table 2-2 Codes for specifying special characters within strings

    Character code Meaning

    \n newline character\t tab character\u toggles Unicode on and off\\ backslash character\" double quote character

  • 7/27/2019 The NewtonScript Programming Language

    35/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Objects and the Class System 2-9

    Array

    [ [ symbol: ] [ object [ ,object]* [, ] ] ]

    An array is a collection of zero or more objects enclosed in square brackets([]) and separated by commas. The user-defined class for the array mayoptionally be specified by beginning the array with a symbol followed by acolon (:).

    symbol Consists of a identifier that is, syntactically, a symbol. Ifpresent, sets a user-specified class for the array. See thesection Symbol beginning on page 2-6, for more

    information about their syntax.object May consist of any NewtonScript object. NewtonScript

    numbers the elements in an array by beginning withzero for the first element. Objects are separated bycommas if there are more than one in the array.

    Note

    The syntax [symbol:object()] is ambiguous; the firstsymbol could be either a class for an array, or a variable to beused as the receiver for a message send. NewtonScript usesthe first interpretation. u

    Semantically, the array is an ordered collection of objects which are indexednumerically, beginning with zero. As with frames, the array can hold anytype of object, including methods, frames, and arrays. Like othernon-immediate objects, arrays can have a user-specified class, and can havetheir size changed dynamically.

    Here is a simple example of an array literal:[1,2,3]

    You can specify a class name for an array by preceding the first array elementwith any arbitrary identifier that specifies a class and a trailing colon, asshown here:

    [RandomData: [1,2,3], "Last element"]

  • 7/27/2019 The NewtonScript Programming Language

    36/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-10 Objects and the Class System

    Note that this array holds a mixture of objects. It contains another array as itsfirst element, the number zero and a string as the second element.

    Note

    NewtonScript allows an optional trailing comma after thelast array element. The trailing comma can be useful if youare going to add more elements to the array. u

    Array Accessor

    arrayExpression [ indexEpression ]

    Array elements are accessed with an expression, that evaluates to an array,and an index expression, that evaluates to an integer and is enclosed insquare brackets.

    arrayExpression An expression that evaluates to an array.

    indexEpression An expression that evaluates to an integer. TheindexExpression corresponds to the element of the arrayyou wish to access. Note that arrays are indexed startingwith zero.

    For example, with the array myArray, which is defined as

    myArray := [123, [4,5,6], "Alice's Restaurant"];

    you access the first element in the array by using the expression:

    myArray[1];

    This expression evaluates to [4,5,6]; returning the contents of the secondelement of the array rather than the first. This is because array indexes arenumbered beginning at zero.

    Note that array accessors are actually operators and are included here foryour convenience. The rest of the NewtonScript operators are documented inOperators beginning on page 2-19.

  • 7/27/2019 The NewtonScript Programming Language

    37/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Objects and the Class System 2-11

    Frame

    { [ symbol :value[,symbol:value]* [ , ] ] }

    A frame is a collection of zero or more slots enclosed in curly brackets andseparated by commas. A slot consists of a symbol followed by a colon (:)and a slot expression. The symbol refers to the value of the slot expression.

    symbol A symbol giving the name of the slot. Note that slotsymbols beginning with the underscore character (_) arereserved for system use; do not begin your slot symbolwith the underscore character.

    value Can be any object, including another frame or method.

    A frame is an unordered collection of slots which consist of a name andvalue pair. As with arrays, the value of a slot can be any type of object,including methods and even other frames and arrays.

    Frames can be used as repositories for data, like records in Pascal and structsin C, but can also be used as objects which respond to messages. As such, theframe is the basic programming unit in NewtonScript.

    A simple record-like frame containing names and phone numbers mightappear as

    {name:"Joe Bob", phone:"4-5678", employee:12345}

    Here is an example frame that contains integers in the first three slots, and amethod in the fourth slot:

    Jupiter := {size:491,

    distance:8110,

    speed: 34,

    position: func(foo) speed*foo/3.1416}

  • 7/27/2019 The NewtonScript Programming Language

    38/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-12 Objects and the Class System

    You may specify an optional class name for a frame by using the slot nameclass. Inserting the class slot:

    class : 'planet

    into the Jupiter frame gives it an appropriate class name. Just as for arrayclasses, the class of a frame gives it a type, not special properties. However, ifyou wanted to give all objects of class planet special characteristics andfunctionality you could use the NewtonScript inheritance structure to set uprelationships that allow objects to inherit data from other objects. (SeeChapter 5, Inheritance and Lookup.)

    You specify these relationships to other frames by referencing them fromslots named_proto and_parent. The relationships these slots establishallow you to take advantage of the NewtonScript double inheritance schemeto construct object-oriented applications. Chapter 5, Inheritance andLookup, describes these concepts.

    There are several slot names which are recognized by the system and usedfor special purposes. All these slots are optional. They are described inTable 2-3.

    Frame Accessor

    frameExpr. {symbol| (pathExpr)}

    Frame values are accessed with an expressionthat evaluates to a frameandeither a symbol, or an expression enclosed in parentheses, that evaluates to apath expression.

    A frame accessor expression returns the contents of the specified slot, or ifthe slot does not exist the expression evaluates to nil.

    frameExpr Any expression that evaluates to a frame.

    symbol A symbol reference to a slot. See Symbol beginning onpage 2-6 for the syntax of symbols.

    pathExpr Any expression that evaluates to a path expressionobject. ThepathExpr corresponds to the slot of the frameyou wish to access. Note that arrays are indexed startingwith zero.

  • 7/27/2019 The NewtonScript Programming Language

    39/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Objects and the Class System 2-13

    Slots in a particular frame can be accessed by using a dot followed by asymbol. For example, the expression:

    myFrame.name;

    returns the contents of the name slot from the frame referenced by thevariable myFrame.

    If the slot is not found in the specified frame using this syntax, the search forthe slot continues through the inheritance chain. The next placeNewtonScript looks is in the prototype frame and then in any of theprototype frames prototypes until the end of the prototype chain is reached.If the slot is not found, the search stops; it does not continue up through theparent frames. If the slot does not exist the expression evaluates to nil.

    The built-in functions GetVariable andGetSlot provide similar kinds ofslot access but with different inheritance behavior. For more information see

    Chapter 6, Built-In Functions.

    Table 2-3 Special slot names and their specifications

    Slot Name Specification

    class: identifier You use the special slot name class to specify asemantic type for your frame. The class of yourobject must be a symbol.

    _parent:frame You use the special slot name_parent to designateanotherframe as a parent frame to this frame. You canrepeat this process, as necessary with other frames, toconstruct a parent inheritance chain. For information

    about inheritance see Chapter 5, Inheritance andLookup.

    _proto:frame You use the special slot name_proto to designateanotherframe as a prototype frame to this frame.Repeat this process, as necessary with other frames,to construct a prototype inheritance chain. Forinformation about inheritance see Chapter 5,Inheritance and Lookup.

  • 7/27/2019 The NewtonScript Programming Language

    40/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-14 Expressions

    For more information about the inheritance mechanism see Chapter 5,Inheritance and Lookup.

    Note that frame accessors are actually operators; they are included here foryour convenience. The rest of the NewtonScript operators are documented inOperators beginning on page 2-19.

    You can also access frame slots by using a path expression. Read about thesein the section Path Expression beginning on page 2-29.

    ExpressionsA simple expression consists of values and an operator, as shown in the code:

    12 + 3;

    The values (12 and3) and the infix operator plus (+), that appears in the linebetween them, are evaluated to return the value 15.

    Variables are often used in expressions as named containers in which to storevalues. For example, you can use a variable on the left side of an assignmentexpression, as in

    currentScore := 12;to store a value. The variablecurrentScore then becomes the identifier forthe value. For more information about the assignment operator (:=), see the

    section Operators, in this chapter.

    Variables

    A variable is named by a symbol. You can use this symbol to refer to anykind of value; from numbers to frames.

    When a method is executing and a variable reference is encountered, thesystem evaluates the value of the variable. This is done following the

    variable lookup rules of NewtonScripts double inheritance scheme. Variablelookup is discussed in Chapter 5, Inheritance and Lookup.

  • 7/27/2019 The NewtonScript Programming Language

    41/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Expressions 2-15

    The next section discusses the use of the local keyword to declarelocal variables.

    Local

    localvarSymbol [:=expression][,var2Symbol:=expression]*

    The local declaration consists of the keyword local, any number ofinitialization clausessymbol, assignment operator (:=), and expression.

    varSymbol Consists of an identifier that is, syntactically, a symbol.The symbol names a variable that may be initialized

    with the optional expression. For more information onsymbols see the section Symbol beginning onpage 2-6.

    expression Consists of any valid NewtonScript expression.

    You can ensure that the value of a variable is determined in a function (i.e.that the variable is local to that function) by using a local expression todeclare the variable. You should be sure to declare all local variables, toavoid hard-to-find bugs.

    The scope of a local variable is restricted to the function definition in which itis declared. You can refer to it only within that function.

    You may use the local expression to identify a variable as local withoutinitializing it as in the example:

    myFunc: func (x)

    begin

    local myVar, counter;

    ...

    end

    This example declares the variables myVar and counter as local variables andinitializes them to nil. Then, each time the function definition for myFunc isexecuted, new local variables are created that are unique to that function.

  • 7/27/2019 The NewtonScript Programming Language

    42/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-16 Expressions

    You may optionally use a local expression with one or multiple assignmentclauses to assign a value to a variable or variables, as shown in theexpression:

    local x:=3, y:=2+2, z;

    This expression creates three local variables, x,y, andz, and initializes themto the values of3, 4, and nil, respectively.

    The declaration of the local variable is processed at compile time but thevalues are assigned at run time, when the expression is encountered. Forexample, the expressions

    x := 10;

    local x, y := 20;

    result in a value of 10 for x and a value of 20 for y. This works becauselocal definitions work anywhere in the function.

    By contrast, you can produce a run-time error by attempting to access thevalue of an uninitialized variable. For example, the expressions

    x := y + 10;

    local x, y := 20;

    result in a value of 10 for x and a value of 20 for y. This works becauselocal definitions work anywhere in the function.

    Constants

    There are several ways to get unchangeable objects in NewtonScript. You can:

    n use the keyword constant

    n put a single quote character (') before an object literal

    n initialize a variable to a literal value

  • 7/27/2019 The NewtonScript Programming Language

    43/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Expressions 2-17

    Constant

    constant constSymbol:=expression[,constSymbol:=expression ]*

    The constant declaration consists of the keyword constant and one ormore initialization clauses consisting of a symbol, assignment operator (:=),and expression.

    constSymbol Consists of an identifier that is, syntactically, a symbol.For more information see the section Symbolbeginning on page 2-6.

    expression Any expression consisting of operators and constants.

    The value of this expression becomes the value ofconstSymbol.

    When a constants is used as a value, NewtonScript effectively substitutesliteral values for the constant.This means that if you declare a constant as inthe expression

    constant kConst := 32;

    then when you use thisConstant as a value in your code, NewtonScriptautomatically substitutes the value 32. So that if you write

    sum := kConst + 10;

    its exactly as if you had writtensum := 32 + 10;

    However, if you use the same identifier as anything other than a value, as inthe expressions:

    x:kConst(42);

    kConst(42);

    x.kConst;

    the value you defined is not substituted. This can be a problem if you definea constant to have a function or method as its value. For these cases there are

    built-in functions you can use as work-arounds, as shown in Table 2-4.

  • 7/27/2019 The NewtonScript Programming Language

    44/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-18 Expressions

    You should also note that the constant value you assign does not getsubstituted when used in a quoted expressions like:

    '{foo: kConst};

    '[kConst];

    See the next section to learn more about the single quote syntax.

    s WARNING

    You can create local constants by putting the declaration in afunction. Since they are in the same name space of thecompiler as local variables, a local variable with the samename can override constants and vice versa. s

    Quoted Constant

    'object

    The single quote character (') begins a kind of expression called aquoted constant.

    You use the quote to create a literal object. The object is constructed atcompile time, and a reference to the same object results each time the objectliteral is evaluated.

    Here are several examples of literal objects formed with the quotedconstant syntax:

    '{name: "Joe Bob", income: yearTotal};

    'myFrame.someSlot;'[foo, 1234, "a string"];

    Table 2-4 Constant substitution work-arounds

    No Substitution Work-around

    x:kConst(42); Perform(x,kConst,[42]);

    kConst(42); call kConst with (42);

    x.kConst; x.(kConst);

  • 7/27/2019 The NewtonScript Programming Language

    45/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Operators 2-19

    When a quote appears outside of the brackets or braces, it applies to everyelement in the array or frame, and symbols within the array or frame do notneed individual quotes. For instance, if you try to create this seeminglycorrect frame:

    storyFrame := {Bear1: Mama, Bear2: Papa, Bear3: Baby};

    you find that an error is caused when the value Mama gets interpreted as anundefined variable. One way to fix this is to put quotes before each name, ormore simply to put one quote before the whole frame, as shown in theexpression:

    storyFrame := '{Bear1: Mama, Bear2: Papa, Bear3:Baby};

    You can pass a quoted frame literal as a parameter to apply the object asneeded.

    Operators

    The NewtonScript operators are:

    n assignment

    n arithmetic

    n boolean

    n equality

    n relational

    n unary

    n message-send

    n array and frame accessors

    All NewtonScript operators, except the message-send operators and arrayand frame accessors are discussed in this section. The message-sendoperators are described in Chapter 4, Functions and Methods. The access

    operators are described in Frame Accessor beginning on page 2-12 andArray Accessor beginning on page 2-10.

  • 7/27/2019 The NewtonScript Programming Language

    46/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-20 Operators

    Assignment Operator

    lvalue:= expression

    In an assignment expression, the symbol, frame accessor, or array accessorthat is the left-hand value for the assignment operator (:=), is assigned thevalue of the expression appearing to the right of assignment operator.

    lvalue Consists of a symbol, a reference to an array element, ora reference to a frame slot.

    expression Consists of any valid NewtonScript expression.

    You use assignment expressions to change the value of variables and slots. Asimple assignment expression looks like this:

    a := 10;

    However, you can use any NewtonScript expression on the right-hand sideof an assignment expression; when it is evaluated its value is assigned to thelvalue. For example, the variable x is set to refer to the value of the ifexpression in this assignment expression:

    x := (if a > b then a else b);

    Here is an example of the assignment of a frame to a variable:

    myFrame := {name: "", phone: "123-4567"}

    Now you can refer to the name slot in another assignment expression andchange its value, like this:

    myFrame.name := "Julia"

    Note that the NewtonScript inheritance rules affect the ultimate behavior ofassignment expressions in frames. For more information about inheritanceand setting slot values see Inheritance Rules for Setting Slot Values, inChapter 5.

    You can assign values to array slots in a similar manner. The second line ofthis code fragment changes the value 789 to 987.

    myArray := [123, 456, 789, "a string"];

    myArray [2] := 987;

  • 7/27/2019 The NewtonScript Programming Language

    47/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Operators 2-21

    Note

    If you accidentally write an assignment expression as=rather than :=, your expression becomes a simple relationalexpression. For example, the expressionx = 5;evaluates to true or nil and leaves the value ofxunchanged. u

    Immediate and Reference Values

    We can see an example of how NewtonScript handles values by comparingassignment expressions in C and NewtonScript.

    Most NewtonScript data consists of references to heap objects rather than toimmediate values (like the integer 1.) When the value of a variable is anreferences and this value is saved in another variable, as in the expression

    b = a;

    then both variables end up referring to the same memory location,rather than having both refer to separate copies of the same value, asyou might expect.

    This becomes clearer when you compare a C code example with anequivalent NewtonScript example. Consider the C code

    struct foo {int x,y;

    };

    foo a;

    foo b;

    a.x = 1;

    a.y = 3;

    b = a;

    a.x = 2;

    // at this point b.x = 1

  • 7/27/2019 The NewtonScript Programming Language

    48/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-22 Operators

    In the example there are two structs, a andb. Each struct contains aninteger x. The integer a.x is assigned the value 1. The value ofstructb issaved in structa anda.x then is set to 2. As you would expect, the valueofb.x is unchanged at this point (it is still 1.) The results of this codeexample are shown in Figure 2-2.

    Figure 2-2 C code example

    The equivalent code in NewtonScript gives a very different outcome:

    local a := {x: 1, y: 3};local b := a;

    a.x := 2;

    // at this point b.x = 2

    The first assignment expression constructs a frame, with two slotsnamed xand ywith values of 1 and 3, respectively. Both refer to the same frame.

    When the value ofa is assigned to the local variable b, in the expression

    local b := a;

    NewtonScript makes b refer to that frame. Both local variables, a andb, nowrefer to the same frame.

  • 7/27/2019 The NewtonScript Programming Language

    49/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Operators 2-23

    The expression:

    a.x := 2;

    changes the value of the x slot. Since both variables, a andb, refer to thesame frame, the value ofb.x is also changed to two, though, it was not

    explicitly assigned. You can see these results in Figure 2-3.

    Figure 2-3 A NewtonScript code sample

    Note

    Assignments of arrays and strings in C are handledin the same manner as assignments of references inNewtonScript. u

  • 7/27/2019 The NewtonScript Programming Language

    50/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-24 Operators

    Arithmetic Operators

    { + | - | * | / | div | mod | > }

    NewtonScript provides the standard set of binary arithmetic operators. Theyare: the addition (+) and subtraction (-) operators, the multiplication (*) anddivision (/) operators, the truncating operatorsdiv andmod, and the bitwiseshift operators, bitwise left shift ().

    + The plus operator adds the two numbers it appearsbetween.

    - The minus operator subtracts the number to its rightfrom the number to its left. Note that minus can also beused as a unary operator to negate an expression. SeeUnary Operators beginning on page 2-27.

    * The multiply operator multiplies the two numbers itappears between.

    / The division operator divides the number to its left bythe number to its right.

    div The divide and truncate operator divides the number toits left by the number to its right and truncates theremainder so that a whole number is returned.

    mod The modulo operator divides the number to its left bythe number to its right and returns only the remainder.

    The bitwise shift right operator is an infix operator. Inthe expression:

    x >> y ;

    x is shifted right by y bits. The most significant bit is

    duplicated in the shift operation.

  • 7/27/2019 The NewtonScript Programming Language

    51/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Operators 2-25

    See Table 2-5 on page 2-32 for a summary of operator precedence.

    Equality and Relational Operators

    { = | | < | > | =}

    NewtonScript provides the standard set of binary equality and relationaloperators. The equality operators are: equal (=) and not equal (). Therelational operators are less than (), less than or equal to(=).

    =

    The equal operator tests the value of immediates andreals, and the identity of references; returning true ifthey are equal and nil if they are not equal.

    The not equal operator tests the value of immediatesand reals, and the identity of references; returning trueif they not equal and nil if they are equal.

    < The less than operator compares the values of numbers,characters, and strings; returning true if the operand

    on the left of the operator is less than the operand on itsright and nil otherwise. An error is signalled if you tryto compare arrays or frames.

    > The greater than operator compares the values ofnumbers, characters, and strings; returning true if theoperand on the left of the operator is greater than theoperand on its right and nil otherwise. An error issignalled if you try to compare arrays or frames.

  • 7/27/2019 The NewtonScript Programming Language

    52/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-26 Operators

    = The less than or equal to operator compares the valuesof numbers, characters, and strings; returning true ifthe operand on the left of the operator is greater than orequal to the operand on its right and nil otherwise. An

    error is signalled if you try to compare arrays or frames.

    This expression tests the identity of two reference objects:

    "abc" [1, 2];

    It evaluates to true because the two objects are not the same object.

    Likewise, the equal (=) operator, when applied to two frame objects,compares their identity, as shown when you execute the code:

    [1,2] = [1,2];

    This expression evaluates to nil even though at first glance it looks as

    though it should be true.

    The relational operators work with numbers, characters, and strings. If youtry to use these operators with arguments that are arrays or frames, an erroris signalled.

    Boolean Operators

    { and | or }

    The Boolean operators, and andor, are binary logical operators thatcompare two expressions.

    and The and operator tests the logical truth of its twooperands; returning true if both expressions are true

    and nil otherwise.

  • 7/27/2019 The NewtonScript Programming Language

    53/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Operators 2-27

    or The or operator tests the logical truth of its twooperands; returning true if either expression is trueand nil if both expressions are false.

    Expressions involving the Boolean operators, andandor, like theircounterparts, || and&&, in the C programming language, short circuit orstop evaluation as soon as the truth of an expression is determined. Forinstance, if

    x < length(someArray)

    evaluates to nil in a conditional expression like

    if x > 0 and someArray[x]

    then doSomething

    else doSomethingElse;

    processing is stopped immediately and goes on to theelse clause. If onepart of an and operation is not true, the whole and expression is not true.Therefore, it is not necessary to evaluate the second half of the andexpression when the first half is not true. When this occurs it is said thatexecution is short-circuited.

    The return value of an expression using any of the logical operators is eithernil

    , which is false, or anything other thannil

    , which is true.

    Unary Operators

    {- | not }

    The unary prefix operators, minus (-) andnot, precede any singleexpression.

    - The minus (-) operator returns the additive inverse ofthe expression it precedes.

    not The not operator is used before an expression toperform a logical negation of that expression.

  • 7/27/2019 The NewtonScript Programming Language

    54/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-28 Operators

    Here are some examples of these operators in use:

    -x; not x; -(1 + 5);

    not(a and -f(12) > 3);

    Exists is another NewtonScript unary (but postfix) operator. It is describedin the sectionExists beginning on page 2-30.

    String Operators

    string1 {& | &&

    } string2The two string operators, && and&, create a new string from the contents oftwo strings you provide. The single & operator creates a new string that hasno spaces between the two objects, while the double && operator adds aspace between the two strings in the new string.

    If you use an object that is not a string in an && or & expression, NewtonScriptconverts the object to a string and uses it to construct a new string. This worksfor symbols, characters, and numbers.

    An & and&& expression returns a new string.

    & An & expression concatenates the string yielded by theexpression on its left to the string yielded by theexpression on its right.

    && An && expression creates a new string by concatenating,with a space, the string yielded by the expression on itsleft to the string yielded by the expression on its right.

    The single & operator concatenates the two strings by leaving no space, in the

    new string, between what was the second string and the first string. Forinstance, the expression:

    "foo" & 17

    creates the new string:

    "foo17"

  • 7/27/2019 The NewtonScript Programming Language

    55/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Operators 2-29

    In contrast, the && operator creates a new string by copying the first string,adding a space, and then copying the second string, as you can see, in thefollowing expression and its result:

    "happy" && "days"

    "happy days"

    Path Expression

    symbol [ .symbol]+

    A path expression is a way of encapsulating an access path through a set ofobjects. It may be a symbol, an integer, or an array of class pathExpr whichcontains symbols and integerssymbols represent frame slot accesses andintegers represent array slot accesses. Path expressions containing onlysymbols may be written as object literals consisting of a series of symbolsseparated by dots.

    symbol Consists of a symbol that evaluates to a frame or array.

    pathExpression Consists of any valid NewtonScript expression thatevaluates to a symbol

    You can access data in a frame by using a path expression like this:

    myFrame.(pathExpression);

    The expressionmyFrame evaluates to a frame andpathExpression evaluatesto a path expression object. This example constructs a slot path expression:

    myFrame:={Kind:"Cat",Type:{Hair:"long",Color:"black"}};

    myFrame.('Type.color);

    The value it returns is the string "black".

    Since a path expression is represented internally as an array of classpathExpr, the expression('Type.color) creates the array[pathExpr:'Type,'color].

  • 7/27/2019 The NewtonScript Programming Language

    56/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-30 Operators

    You could rewrite the previous example using array syntax for the pathexpression, as shown in these expressions:

    myFrame:={Kind:"Cat",Type:{Hair:"long",Color:"black"}};

    slotPath := '[pathExpr: Type, color];

    myFrame.(slotPath);

    Like frame slots, array elements can also be accessed using path expressions.The path to an array element is simply the array index of the element. Here isan example:

    myframe:={name:"Matt",info:{grade:"B",tests:[87,96,73]}};

    mypath:='[pathExpr: info,tests,1];

    myframe.(mypath);

    The expressionmyFrame.(mypath) evaluates to 96.

    Note that you can also use path expressions to set the value of a slot. Forinstance, to upgrade the third test score above, use an expression like:

    myframe.(mypath):= 98;

    Exists

    lValueexists

    Exists is a special postfix operator that follows a single symbol, frameaccess expression, or message send.

    The exists operator is used to check for the existence of variables, slots, ormethods. When you apply the exists operator to an identifier, such as avariable, it returns true if the variable is defined in the current context andnil otherwise. (For more information about the scope of variables seeScope beginning on page 1-4.)

    lValue Consists of an expression that evaluates to a symbol,frame accessor, or a message-send.

  • 7/27/2019 The NewtonScript Programming Language

    57/212

    CHAPTER 2

    Objects, Expressions, and Operators

    Operator Precedence 2-31

    All of these are legal forms for an exists expression to take:

    x exists;

    x.y exists;

    x.(y) exists;

    x:m exists;

    Here is an example of a simple ifthen structure that uses exists:

    if myVar exists then myVar else 0;

    When you apply exists to a frame accessor, exists returns true if theslot exists in the frame or in any of its prototype frames, and nil otherwise.(For more information about prototype frames and inheritance, seeChapter 5, Inheritance and Lookup.) Ifthen expressions are describedin Chapter 3, Flow of Control.

    This operator can be particularly useful if you want to check for the existenceof a slot that may or may not be in a prototype frame:

    if myFrame.aSlot exists then

    if not hasSlot(myFrame, 'aSlot) then

    print("'aSlot slot is in a prototype of myFrame")

    The built-in function hasSlot provides similar functionality to the exists

    operator though they differ in the type of inheritance that is used to searchfor slots. See also Chapter 5, Inheritance and Lookup, and Chapter 6,Built-In Functions.

    Operator Precedence

    In case it is not inherently apparent in an expression, a set of ratings tells thecompiler which operator to evaluate first (or which operator takesprecedence). Table 2-5 lists the order of precedence of all the NewtonScript

    operators in order from top to bottom. Note that operators grouped togetherin the table are of equal precedence.

  • 7/27/2019 The NewtonScript Programming Language

    58/212

    CHAPTER 2

    Objects, Expressions, and Operators

    2-32 Operator Precedence

    Table 2-5 Operator precedence and associativity

    Operator Action Associativity

    . slot access left-to-right

    ::?

    message sendconditional message send

    left-to-right

    [] array element left-to-right

    - unary minus left-to-right

    >

    left shift

    right shift

    left-to-right

    */divmod

    multiplyfloat divisioninteger divisionremainder

    left-to-right

    +-

    addsubtract

    left-to-right

    &

    &&

    concatenate (string copyof expression value)concatenate with 1 spacebetween

    left-to-right

    exists variable & slot existence none==

    less thanless than or equalgreater thangreater than or equalequalnot equal

    left-to-right

    not logical not left-to-right

    andor

    logical andlogical or

    left-to-right

    := assignment right-to-left

  • 7/27/2019 The NewtonScript Programming Language

    59/212

    Compound Expressions 3-1

    CHAPTER3

    Flow of Control

    This chapter discusses the syntax and semantics of the standardflow-of-control mechanisms including: compound expressions, conditionalexpressions and iterators.

    Also included is a discussion of the non-standard flow-of-control mechanismcalled exception handling that NewtonScript uses to control exceptionalsituations or errors.

    Compound Expressions

    beginexpression1;

    expression2;

    expressionN[;]end

    The keywordsbegin andend are used to group expressions, not to create

    structured blocks that define the scope of variables, as they are in somelanguages.

  • 7/27/2019 The NewtonScript Programming Language

    60/212

    CHAPTER 3

    Flow of Control

    3-2 IfThenElse

    This construct is useful in conditional expressions, in any of the loopingexpressions, and in function definitions. In fact, anywhere the syntaxspecifies a single expression, you can use a compound expression instead.

    The compound expression returns the result of the last expression.

    expression Consists of any valid NewtonScript expression; it mustbe separated from the next expression by a semicolon,unless it is the last expression in the compoundexpression. In this case, the keyword end separates itfrom any following expressions.

    If you want to execute more than one expression in a conditional expression,use the keywordsbegin andend to group the expressions as shown in thisexample:

    if x=length(myArray) then

    begin

    result := self:read(x);

    print(result)

    end

    IfThenElseiftestExpression thenexpression [;]

    [elsealternateExpression]

    The ifthenelse construct allows you to dictate programmatic flow ofcontrol using test conditions.

    As is standard in other programming languages, you use an if expression tocarry out one set of operations, when the condition you set up in a testexpression is true, and another set of operations when the text expressionevaluates to nil.

  • 7/27/2019 The NewtonScript Programming Language

    61/212

    CHAPTER 3

    Flow of Control

    Iterators 3-3

    Theif expression returns the value ofits expression or alternateExpression.clause, unless the test condition is not true and there is no else clause. Inthat case, nil is returned.

    testExpression Consists of an expression that tests for the truth of acondition. If the test expression evaluates to anythingother than nil, the expression following it is executed.

    expression Consists of any valid NewtonScript expression. Acompound expression may be substituted. (For moreinformation see the section Compound Expressions.)

    This expression is executed if the test is true; its value isreturned as the value of the if expression.

    alternateExpression Consists of any valid NewtonScript expression. Acompound expression may be substituted. (For moreinformation see the section Compound Expressions.)

    Theelse clause, along with the alternateExpressionthat

    follows it, is executed if the test expression evaluatesto nil.

    IteratorsNewtonScript includes these iterators:

    n For

    n Foreach

    n Loop

    n While

    n Repeat

    n Break

  • 7/27/2019 The NewtonScript Programming Language

    62/212

    CHAPTER 3

    Flow of Control

    3-4 Iterators

    Note

    Loops do not work outside of a function because localvariables must be declared within a function and iteratorsrequire local variables to control the number of iterationsexecuted. This is a problem you might encounter this whiletrying out code in the Inspector window of the NewtonToolkit.

    For more information about local variables see Localbeginning on page 2-15. For more information aboutfunctions see Chapter 4, Functions and Methods. u

    For

    for counter :=initialValue to finalValue [byincrValue]doexpression

    The for loop performs a set of expressions repeatedly, until a loop countervariable equals or exceeds a specified final value or a Break expression isreached. A counter variable keeps track of the number of times the loop hasexecuted. You specify the initial value and final value of the counter variable.If you choose not to specify the amount to increase (or decrease) the counterby using the optional keyword by followed with an incremental value, thecounter gets incremented by the default value of 1.

    A for loop expression returnsnil

    (or the argument of abreak

    expression, ifone is used to terminate the loop.)

    counter This symbol is set to the value of the initialValueexpression when afor loop starts.After each repetitionof the loop, the counter variable is incremented by thevalue ofincrValue. or by the default value of 1 if anincremental value is not specified.

    On loop exit the value ofcounter is undefined. It is anerror to change its value from within the loop body. Ifyou do so, loop behavior is undefined.

  • 7/27/2019 The NewtonScript Programming Language

    63/212

    CHAPTER 3

    Flow of Control

    Iterators 3-5

    initialValue This expression must evaluate to an integer. It isevaluated once before the loop starts and is used as theinitial value of the counter.

    finalValue This expression must evaluate to an integer. It isevaluated once before the loop starts and is used as thefinal value of the counter.

    incrValue This expression follows the keyword by. It is evaluatedonce before the loop starts and used throughout theloop execution to increment (or decrement) the countervariable.

    The incremental value expression must evaluate to aninteger (either positive or negative); a value of zerogenerates a run-time error. If you do not specify anincremental expression, after the keyword by, a defaultvalue of 1 is used to increment the counter.

    expression Consists of any valid NewtonScript expression. Acompound expression may be substituted. (For moreinformation see the section Compound Expressions.)

    Here is an example of a for loop.

    for x:=1 to 10 by 2 do print(x);

    1

    3

    5

    7

    9

  • 7/27/2019 The NewtonScript Programming Language

    64/212

    CHAPTER 3

    Flow of Control

    3-6 Iterators

    Foreach

    foreach [slot,] value [deeply]inframe| array collect | doexpression

    Using the foreach iterator is one way you can access data stored in framesor arrays. This iterator executes once for each element in an array or frameallowing you to either iterate an expression over each value stored in anarray or frame, or to collect data during each iteration.

    In an array, iteration begins with the first element of the array, element[0]. Ina frame the starting point and susbsequent order of iteration is unpredictablebecause frame slots are not stored in any particular order.

    This iterator also has a special option, deeply, for frame iteration overvalues in the target frame and in its proto chain of frames as well. Forinformation on prototype inheritance see Chapter 5, Inheritance andLookup.

    Aforeach expression returns nil (or the argument of a break expression,if one is used to terminate the loop.)

    slot This symbol is set to the name or index of the next sloton each loop iteration over the elements of an array orframe. The value of this variable is undefined on loopexit. Using the slot variable is optional. If you specify

    just one variable of the slot,value pair, its assumed tobe as the value..

    value Set to the value of the next array element or frame sloton each loop iteration over the elements of an array orframe. The value of this variable is undefined on loopexit. Using the value variable is mandatory. If youspecify just one variable, of the slot,value pair, its valueis assigned as the element value.

    array An expression that evaluates to an array.

    frame An expression that evaluates to a frame.

  • 7/27/2019 The NewtonScript Programming Language

    65/212

    CHAPTER 3

    Flow of Control

    Iterators 3-7

    expression Consists of any valid NewtonScript expression. Acompound expression may be substituted. (For moreinformation see the section Compound Expressions.)

    deeply Specifies the option that iteration occurs over values inthe immediate frame first and then in the_protoframe(s). (For information on prototype inheritance seeChapter 5, Inheritance and Lookup.) If you specifythe deeply option and the frame you are concernedwith does not have a_proto frame, no error isproduced. Instead, the slot values evaluate to those of

    the current frame.You use foreach to access data stored in a frame that functions like a Pascalrecord or a C struct. The data used in the following example is thenameFrame frame, defined as:

    nameFrame := { name:"Carol",

    office:"San Diego",

    phone:"123-4567"};

    You can use the foreachdo loop to access and print the slot names andvalues stored in a nameFrame by writing a method like reportIt:

    report:= { reportIt: func(frameName)

    begin

    foreach slot, value in frameName do

    begin

    display(slot);

    display(":");

    print(value);

    end

    end }

  • 7/27/2019 The NewtonScript Programming Language

    66/212

    CHAPTER 3

    Flow of Control

    3-8 Iterators

    When you send the message reportIt with the argument nameFrame tothe report object, as shown here:

    report:reportIt(nameFrame);

    This is the output produced:

    "Carol"

    "San Diego"

    "123-4567"

    Usingcollect

    with theforeach

    iterator makes it easy to collect the dataand manipulate it. Consider a dataFrame which is defined as:

    dataFrame := {1,3,5,7,9}

    You can collect the squares of each value in dataFrame and print the results,with the code shown here:

    result := foreach value in dataFrame collect value*value;

    print(result);

    The values are collected in an array, as shown in the output:

    ["Carol", "San Diego", "123-4567"]

    If you want the foreach iterator to look up slot values in the prototypeframe in addition to the current frame, use the deeply option. To make useof the deeply option with this iterator, your data set must include a framethat references a prototype frame. For purposes of example we can use thedata defined here as:

    x := {one:1, two:2, three:3};

    y := {four:4, five:5, combo:x};

    z := {six:6, _proto:y};

  • 7/27/2019 The NewtonScript Programming Language

    67/212

    CHAPTER 3

    Flow of Control

    Iterators 3-9

    You can consult the picture of this data, shown in Figure 3-1, while looking atthe different results, produced by using foreach alone and with thedeeply option that are shown in the accompanying table, Table 3-1.

    Figure 3-1 Data objects and their relationships

    Table 3-1 allows you to compare the results produced by two functions,normalList anddeeplyList, as applied to the data in Figure 3-1.

  • 7/27/2019 The NewtonScript Programming Language

    68/212

    CHAPTER 3

    Flow of Control

    3-10 Iterators

    Table 3-1 Result comparison for the iterator foreach and foreachdeeply

    Loop

    loopexpression

    This mechanism simply repeats any expressions that occur within the loopexpression until a break expression is encountered; if no break expressionis reached the loop never ends.

    The loop expression returns the argument of the break expression that isused to terminate the loop.

    expression Consists of any valid NewtonScript expression. Acompound expression may be substituted. (For more

    foreach foreach deeply

    normallist := func (param) begin

    foreach tempItem in param

    collect tempItem;

    end;

    deeplylist := func (param) begin

    foreach tempItem deeply in param

    collect tempItem;

    end;

    :normallist(x)

    #4413441 [1, 2, 3]

    :deeplylist(x)

    #44137D9 [1, 2, 3]

    :normallist(y) // same

    #4413A11 [4,

    5,

    {One: 1,

    two: 2,

    three: 3}]

    :deeplylist(y)

    #4413C49 [4,

    5,

    {One: 1,

    two: 2,

    three: 3}]

    :normallist(z)

    #4416E29 [6,

    {four: 4,

    five: 5,

    combo: {#4415D79}}]

    :deeplylist(z)

    #4416FE1 [6,

    4,

    5,

    {One: 1,

    two: 2,

    three: 3}]

  • 7/27/2019 The NewtonScript Programming Language

    69/212

    CHAPTER 3

    Flow of Control

    Iterators 3-11

    information see the section Compound Expressions.)This expression is evaluated during each loop iteration.

    This example prints the value of the variable x until it reaches the value of 0and the break expression is executed.

    local x:=4;

    loop if x = 0 then break

    else

    begin

    print(x);

    x:=x-1

    end

    4

    3

    2

    1

    While

    whilecondition doexpression

    The while loop evaluates the conditional expression first. If it evaluates to anon-nil value (true or any other value that is not nil) the expression afterthe keyword do executes. This sequence repeats until the conditionalexpression evaluates to nil and ends loop execution.

    Awhile expression returns nil (or the argument of a break expression, ifone is used to terminate the loop.)

    condition Consists of an expression that tests for the truth of acondition. If the test expression evaluates to nil, loopexecution ends.

    expression Consists of any valid NewtonScript expression. Acompound expression may be substituted. (For more

    information see the section Compound Expressions.)This expression is evaluated during each loop iteration.

  • 7/27/2019 The NewtonScript Programming Language

    70/212

    CHAPTER 3

    Flow of Control

    3-12 Iterators

    Repeat

    repeat

    expression

    until condition

    The repeat loop executes the expression(s) inside the loop first and thenevaluates the test expression. If the expression at the end of the loopevaluates to nil, the expressions repeat and the test expression is evaluatedagain. This continues until the expression evaluates to non-nil, at whichpoint the loop ends.

    Arepeat expression returns nil (or the argument of a break expression, ifone is used to terminate the loop.)

    condition Consists of an expression that tests for the truth of acondition. If the conditional expression evaluates toanything other than nil, loop execution ends.

    expression Consists of any valid NewtonScript expression. Acompound expression may be substituted. (For moreinformation see the section Compound Expressions.)This expression is evaluated during each loop iteration.

    Break

    break [expression ];

    While not an iterator itself, the Break expression interrupts the execution ofany of the iterative structures. You must use the Break expression to stopthe simple Loop structure, which has no built-in constructs to stop it.

    If a expression follows Break, it is evaluated and returned as the value of theloop. If you use the Break with no expression following it, the loop returnsthe value nil.

    expression Consists of any valid NewtonScript expression. Acompound expression may be substituted. (For moreinformation see the section Compound Expressions.)

    The value of this expression is returned as the value ofthe Break expression.

  • 7/27/2019 The NewtonScript Programming Language

    71/212

    CHAPTER 3

    Flow of Control

    Exception Handling 3-13

    Exception Handling

    NewtonScript exception handling allows you to respond to exceptionalconditions that arise during the execution of your program. An exceptionalcondition, or exception, is a condition that either the Newton systemsoftware or your own code raises when something unexpected or erroneoushappens at run time.

    When an exception is raised at run time, the system can transfer control to anexception handler, which is a block of code that attempts to handle thecondition gracefully, rather than allowing the application to crash. Anexception handler can respond by displaying an error message, reverting thestate of a computation, or taking some other action or actions.

    The act of raising an exception is known as throwing an exception. Anexception handler catches the exception and responds in some manner. Eachexception has a unique name and each exception handler responds to aspecific exception or class of exceptions.

    Newton system software throws and catches a number of built-in exceptions.You can define, throw, and catch your own exceptions, and you can alsocatch and handle the built-in exceptions.

    This section describes exception handling in NewtonScript. Exceptionhandling is a non-standard flow of control mechanism that NewtonScriptinherited from Newton system software.

    NewtonScript exception handling allows you to respond to exceptionalconditions that arise during the execution of your program. An exceptionalcondition, or exception, is a condition that either the Newton systemsoftware or your own code raises when something unexpected or erroneoushappens at run time.

    When an exception is raised at run time, NewtonScript can transfer control toan exception handler, which is a block of code that attempts to handle thecondition gracefully, rather than allowing the application to crash. An

    exception handler can respond by displaying an error message, reverting thestate of a computation, or taking some other action or actions.

  • 7/27/2019 The NewtonScript Programming Language

    72/212

    CHAPTER 3

    Flow of Control

    3-14 Exception Handling

    In NewtonScript, the act of raising an exception is known as throwing anexception. An exception handler catches the exception and responds insome manner. Each exception has a unique name and each exception handlerresponds to a specific exception or class of exceptions.

    Newton system software throws and catches a number of built-in exceptions.You can define, throw, and catch your own exceptions, as well as the built-inexceptions by using the try, throw, and catch built-in exception-handlingfunctions.

    Working with ExceptionsWorking with exceptions in NewtonScript involves a number of entities. Youcan perform the following actions to work with exceptions:

    n define an exception symbol for a specific exception or class of exceptions

    n enclose a list of statements within a try statement to catch any exceptionsthat occur during execution of those statements

    n catch a specific exception or class of exceptions with an onexceptionstatement

    n use the CurrentException function to examine the frame associatedwith the exception that you are handling

    n throw an exception when you detect a condition that request handlingn rethrow an exception from within your exception-handling code to allow

    the next handler for the exception to respond to it

    You can provide exception handling for any list of statements in yourNewtonScript programs. You can also nest an exception-handling blockof code inside of another exception-handling block of code to provide ahierarchical chain of exception handlers.

    Each exception handler can specify which exception or class of exceptions itprocesses by naming the symbol or symbol prefix that it handles. Anexception handler can also re