how to use self 2.0

Upload: pablomarx

Post on 03-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 How to Use SELF 2.0

    1/50

    1

    How to Use SELF 2.0

    Ole Agesen

    Lars Bak

    Craig ChambersBay-Wei Chang

    Urs Hlzle

    John Maloney

    Randall B. Smith

    David Ungar

    Welcome to SELF 2.0. This manual, How to Use SELF 2.0, is designed to take you through the

    steps needed to install and start using SELF. It has three parts:

    Getting Started

    Exploring SELF

    Programming and Debugging

    We hope you enjoy using SELF. Good luck! The SELF Group

    Copyright (c) 1992, Sun Microsystems, Inc. and Stanford University. All Rights Reserved.

    Sun Microsystems, Inc

    2550 Garcia Avenue

    Mountain View, CA 94043 USA

    RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the government is subject to restrictions as

    set forth in subparagraph (c) (1) (ii) of the Rights in Technical Data and Computer Software Clause at DFARS

    252.227-7013 (Oct. 1988) and FAR 52.227-19(c) (June 1987).

    SOFTWARE LICENSE: The software described in this manual may be used internally, modified, copied and distrib-

    uted to third parties, provided each copy of the software contains both the copyright notice set forth above and the dis-

    claimer below.

    DISCLAIMER: Sun Microsystems, Inc. makes no representations about the suitability of this software for any pur-

    pose. It is provided to you "AS IS", without express or implied warranties of any kind. Sun Microsystems, Inc. dis-

    claims all implied warranties of merchantability, fitness for a particular purpose and non-infringement of third party

    rights. Sun Microsystems, Inc.'s liability for claims relating to the software shall be limited to the amount, if any of the

    fees paid by you for the software. In no event will Sun Microsystems, Inc. be liable for any special, indirect, inciden-

    tal, consequential or punitive damages in connection with or arising out of this license (including loss of profits, use,

    data, or other economic advantage), however it arises, whether for breach of warranty or in tort, even if Sun Microsys-

    tems, Inc. has been advised of the possibility of such damage.

  • 7/28/2019 How to Use SELF 2.0

    2/50

    2

    How to Use SELF 2.0

    Part I

    Getting Started

    To get started, you must install the SELF system from the distribution files, configure it for your

    computer, learn how to start and stop the SELF virtual machine, and create a SELF snapshot.

  • 7/28/2019 How to Use SELF 2.0

    3/50

    3

    How to Use SELF 2.0 How to Install SELF

    1 How to Install SELF

    The SELF system can be installed from either tape or ftp. Installation consists of three steps: get-

    ting the archive files, performing the site installation, and setting up the working environment for

    an individual user.

    1.1 Getting the Archive Files

    The easiest way to get the SELF system is to use anonymous ftp to retrieve the files from

    self.stanford.edu. Archive files for the two supported platforms, Sun-4 and Sun-3, reside inthe directories /pub/Self-release-2.0/sun4 and /pub/Self-release-2.0/sun3 re-spectively.

    If you do not have access to the internet, a tape can be obtained by sending email to

    [email protected]. There may be a small fee to cover handling and media costs.

    Create a temporary directory to hold the archive files and retrieve README, Install, andSelf.tar.Z into this directory. The other three files, Optional.Snapshot.tar.Z,Optional.Glue.tar.Z, and Optional.VM.tar.Z are optional.

    1.2 Site Installation

    Once you have obtained the archive files you must execute the shell script Install to perform thesite installation. Install prompts you for the directory where the SELF site installation should re-side and then unpacks the archive files. The default installation directory is /usr/local/lib.

    Prior to running Install, you should be sure there is sufficient disk space. The disk space re-quirements for the unpacked archive files are:

    Self.tar.Z 4 Mb

    Archive file Contents

    README Describes how to install the system (similar to this chapter).

    Install Shell script to perform the installation.

    Self.tar.Z Archive containing the basic SELF system: the SELF virtualmachine and SELF source files describing the SELF world.

    Optional.Snapshot.tar.Z Contains a snapshot of the SELF world after reading in me-

    dium.self. An equivalent snapshot can be generated from

    the SELF source files in Self.tar.Z.

    Optional.VM.tar.Z Contains source code for the SELF virtual machine, roughly85,000 lines of C++. An installation of GNU g++ version 2.1

    is required to compile this code. This file is only necessary if

    you want to study or change the virtual machine or use the

    glue (see section 25 of the Reference Manual).

  • 7/28/2019 How to Use SELF 2.0

    4/50

    4

    How to Use SELF 2.0 How to Install SELF

    Optional.Snapshot.tar.Z 4 Mb

    Optional.VM.tar.Z 2 Mb

    Type in the following to execute the Install script.

    % sh Install

    The archive files can be deleted when the site installation is complete.

    1.3 Running SelfUserSetup

    Before using SELF, each user must execute the script SelfUserSetup to configure the system forhis or her own use. SelfUserSetupwill do the following:

    Check your machine configuration and calculate the optimal setup for your machine.

    If the script tells you to add swap space please read section 1.4.

    Add a set of environment variable definitions to your ~/.cshrc file, based on the result ofthe previous calculation.

    Make a local copy of the SELF source files if requested.

    Create the .selfrc file in your home directory.

    The environment variable definitions added to the .cshrc file will not take effect until the next time

    a shell is created. To apply these definitions to the current shell, execute the Unix command:

    % source ~/.cshrc

    Installation of SELF is now complete.

    1.4 Adding Swap Space

    If the SelfUserSetup script tells you to extend the size of the virtual memory additional swapspace must be added to your system. Follow the instructions to add swap space.

    First check the size of your machines swap space:

    % pstat -s30640k allocated + 11944k reserved = 42584k used, 47552k available

    The available number is the amount of swap space available for SELF.

    1. Now, subtract that number from the amount of swap space that the configure script said you

    need for SELF. The difference is the amount of swap space you must add.

    2. Find a disk with enough free space to hold the additional swap file. (You can use the Unix df

    command for this.)

    3. Login as super user.

  • 7/28/2019 How to Use SELF 2.0

    5/50

    5

    How to Use SELF 2.0 How to Start the SELF Virtual Machine

    4. Create a swap file of the desired size:

    #mkfile 12m /u1/mySwapFile(The example creates a 12MB file named mySwapFile on the disk /u1. Any name may be

    chosen for the swap file. Remember to put this file on the disk you found in step 3.)

    5. Edit /etc/fstab, adding the following line:

    /mySwapFile swap swap rw,noquota 0 0(Assuming that your swap file is named /mySwapFile.)

    6. Make the new swap file available to the system:

    # swapon -a

    2 How to Start the SELF Virtual Machine

    You are now ready to run SELF. This section describes what youll encounter in the bare SELF

    world; a later section will tell you how to create a default worldof objects, a much more hospitable

    working environment.

    To start the SELF virtual machine, type Self at the Unix prompt:

    % SelfSelf Virtual Machine Version 2.0, Apr 30 1992 08:50:12Copyright 1989-92: The Self Group (type _Credits for credits)

    reading ~/.selfrcVM#

    Upon entering SELF, you are greeted by the prompt VM#, indicating that the system is ready to ac-cept input. You can now enter a SELF expression. This expression will be evaluated in the context

    of an object called the lobby, i.e., as if the expression were a method invoked with the lobby object

    as the receiver. SELF will evaluate the expression and print the result.

    The bare SELF world has only a very few predefined objectsthe ones that are absolutely neces-

    sary for bootstrapping the system, like true and the prototypical string object (see section 23 ofthe Reference Manual). Thus, even basic methods like integer + are not defined:

    The lobby objects special status as the receiver of messages evaluated in the root context makes it desirable to putthe lobby in a central place in the SELF inheritance graph, and in fact, most objects in the default world inherit fromthe lobby. See the SELF World manual.

  • 7/28/2019 How to Use SELF 2.0

    6/50

    6

    How to Use SELF 2.0 How to Run the Spy

    VM# 3 + 4A lookup error happened: 3 did not understand the message "+".The receiver also did not understand the lookup error message"undefinedSelector:Type:Delegatee:MethodHolder:Arguments:" which

    was subsequently sent to it. -- Self VM

    #0 (:1): + = ( | _ self* = 3. _ :arg1 = 5. |"undefined selector error;this method automatically generated by the VM.")

    #1 doIt = ( | _ self* = lobby. | 3 + 5 )

    #2 (:1): printIt = ( | _ self* = lobby. | doIt_Print )

    VM#

    Ignore the details of the error message for the moment; they will be described in a later section.

    You only need to understand that the + message is not defined at this point.

    However, there are numerous primitives defined by the system, such as_IntAdd: for integer ad-dition:

    VM# 3 _IntAdd: 47: ( | ^ parent* = . | )

    Normally, you will not work with the system in this crude, initial state; rather, youll use more

    comfortable worlds created by reading in scripts or snapshots. Later sections explain how to do

    these things.

    3 How to Run the Spy

    The SELF system contains a system monitor, or spy, which displays information about the inter-

    nal workings of the system such as memory management and compilation. It can be turned on or

    off by evaluating_Spy: true or_Spy: false (the return value is theprevious state of the op-

    tion.) When the spy is active, it takes over the bottom portion of your screen with the following dis-

    play:

    The indicators in the left part of the display correspond to various internal activities and events.

    The bars on the right show how memory is being used. To understand how to interpret this display,

    VM activity VM memory object memory code cache

  • 7/28/2019 How to Use SELF 2.0

    7/50

    7

    How to Use SELF 2.0 How to Interrupt Programs and Exit SELF

    see Appendix G of the Reference Manual. The spy can be useful simply to reassure you that SELF

    is still running during the longish pauses that sometimes occur when a large method is compiled or

    when the garbage collector runs. We suggest that you start the spy now.

    By default, the spy displays on /dev/fb, the console framebuffer on the computer on which the virtual machine isrunning. It writes directly to the framebuffer, bypassing any window system. If you run S ELF on a remote computer

    (e.g., via rlogin), the system monitor will write to the screen of the remote machine, not your own. If your computerhas several screens, you can use the _SpyFramebufferName: option to specify the framebuffer on which thesystem monitor should appear, for example, /dev/cgsix0.

    4 How to Interrupt Programs and Exit SELF

    Before going on, it is important to know how to exit from the virtual machine, interrupt a long

    computation, and stop and start the SELF process scheduler.

    4.1 How to Exit the SELF Virtual Machine

    Table 1 summarizes the various ways to exit the SELF virtual machine. The first way forcefully ex-

    its the virtual machine no matter what it is currently doing and returns to the Unix shell.

    4.2 How to Interrupt a SELF Program

    There are two ways to interrupt a running SELF program, Control-C and Control-\. The second

    way works even if the SELF process scheduler is not running.

    In response to the interrupt, you will see one of two things. If the SELF scheduler is not running,

    you will be returned directly to the VM# prompt. If the scheduler is running, you will be presentedwith a list of SELF processes (the process menu):

    Table 1 How to exit SELF

    If SELF prompts you with Type

    anything or nothing Control-Z, then kill -9 % to the Unix shell

    VM# Control-D or _Quit

    Self 17> two Control-Ds or _Quit

  • 7/28/2019 How to Use SELF 2.0

    8/50

    8

    How to Use SELF 2.0 How to Interrupt Programs and Exit SELF

    Self 9> 100000 * 100000 do: []^C----------------Interrupt-----------------Ready:

    scheduling process{ 100000 * 100000 do: [] }Waiting:

    waiting process{ inputLoop }------------------------------------------Select a process (or q to quit scheduler): 25Select | [a]bort, |

    | [b]ackground, || [s]uspend, || [r]esume, || [p]rint stack, |

    or | [n]o action | for process 25: aProcess 25 aborted.------------------------------------------

    Self 10>

    In this example, the loop was interrupted by typing Control-C, and the process menu was used to

    abort the process. If the user had typed q to quit the scheduler, all current processes would have

    been aborted along with the scheduler itself:

    ...------------------------------------------Select a process (or q to quit scheduler): qScheduler shut down.------------------------------------------

    prompt

    VM#

    The scheduler has been stopped, returning the user to the VM# prompt. The command promptstart restarts the scheduler:

    VM# prompt startSelf 11>

    Although the VM# prompt can be used to evaluate expressions directly, the scheduler supportsmuch nicer error messages and debugging, so it is usually best to run the scheduler. (The scheduler

    is started automatically when the default world is created.)

  • 7/28/2019 How to Use SELF 2.0

    9/50

    9

    How to Use SELF 2.0 How to Build and Save the World

    4.3 Summary

    Certain virtual machine operations like garbage collection, reading a snapshot, and compilation

    cannot be interrupted; interrupts during these operations will be deferred until the operation is

    complete. As a last resort (e.g., if the system appears to be hung), you can force an abort by

    pressing Control-\five times in a row.

    5 How to Build and Save the World

    You probably already know that there are two parts to SELF: a virtual machine (VM) that executes

    SELF programs, and a world of SELF objects (including programs) that live in the memory of the

    virtual machine. The world of objects can be saved into and later restored from a special kind of

    file, called a snapshot. A snapshot captures the state of the object world: that is, all the objects and

    methods, but not the state of currently running processes. This section describes how to create a

    default object world by reading in the SELF source code provided with your distribution and how

    to save this world as a snapshot. (If you already have a snapshot, you can skip this section for now.)

    5.1 Creating the World

    To create the default object world:

    1. Start SELF:

    % SelfSelf Virtual Machine Version 2.0, Apr 30 1992 08:50:12Copyright 1989-92: The Self Group (type _Credits for credits)reading ~/.selfrcVM#

    2. Check the directory path that SELF will use to find source files:

    Table 2 Interrupting and Exiting SELF

    Control-C Control-\ Control-D _Quit

    Interruptscurrent SELF

    process via

    SELF scheduler

    Interruptscurrent SELF

    process

    directly

    Signals end-of-filewhen reading

    standard input

    VM quitprimitive

    The current prompt is

    Self17>(the SELF scheduler is

    running)

    At prompt process menu process menu exits scheduler (goes

    to VM# prompt)exits VM

    Running

    SELF code

    process menu process menu no effect no effect

    The current prompt is

    VM#(the SELF scheduler is

    notrunning)

    At prompt no effect no effect exits VM exits VM

    Running

    SELF code

    no effect returns to

    VM# prompt

    no effect no effect

  • 7/28/2019 How to Use SELF 2.0

    10/50

    10

    How to Use SELF 2.0 How to Build and Save the World

    VM#_DirPath'~/self/self' : ( | ^ parent* = . | byte array: {126, 47,115, 101, 108, 102, 47, 115, 101, 108, 102} )

    The result string is a list of directories, separated by colons. Ignore the output starting with :;

    this is just a different way of printing the string. A zero-length directory name is an abbreviation for the

    current directory. In particular, if_DirPath is the empty string, then the path includes just thecurrent directory. Paths may also include the tilde character (~), which is expanded as it is in

    the Unix C-shell.

    3. If the directory containing your source files is not in the path, then change the path:

    VM#_DirPath: 'myDirectory'

    You can define a default value for_DirPath by including a line like_DirPath: '.:/tmp:~smith/self'

    in a file named .selfrc in your login directory.

    4. (Optional, but recommended.) If you are running on the console screen of your workstation,

    start the spy so you can watch the world fill up with objects:

    VM#_Spy: true

    5. Read in the default world. To do this, ask SELF to read expressions from the file all.self:

    VM# 'all' _RunScript

    Unless you have asked SELF not to print script names, you should see something like:

    reading mydir/all...reading mydir/all-core...reading mydir/init...

    . . .6. After all the files have been read in, SELF will start the process scheduler, initialize its cache of

    path names of well-known objects, and print:

    refilling path cache...done.Self 0>

    That last line is the SELF prompt indicating that the virtual machine is ready to read and evalu-

    ate expressions.

    Congratulations! You are now ready to explore the world of SELF objects. But, first you should

    save the world.

    5.2 Saving the World

    To save the world, you need to write a snapshot file. This file consumes over 5Mb of disk space, so

    be sure to put it on a disk with enough free space. If the snapshot file name doesnt start with a

    slash, tilde, or dot, SELF will put it in the first directory in your DirPath (see step 2 above). Often,

    you will just name the file Snapshot and put it in the current directory:

  • 7/28/2019 How to Use SELF 2.0

    11/50

    11

    How to Use SELF 2.0 How to Build and Save the World

    Self 1> './Snapshot' _WriteSnapshot'./Snapshot' this string is the value returned by _WriteSnapshotSelf 2>

    The next time you start SELF, you can just read in this snapshot and start working; you will not

    need to rebuild the default world.

  • 7/28/2019 How to Use SELF 2.0

    12/50

    12

    How to Use SELF 2.0 How to Build and Save the World

    Part II

    Exploring SELF

    Now that you have built yourself a default SELF world, you are ready to read in your snapshot and

    explore this world using either text-based interactions or the graphical object browser.

  • 7/28/2019 How to Use SELF 2.0

    13/50

    13

    How to Use SELF 2.0 How to Read a Snapshot

    6 How to Read a Snapshot

    Start SELF if you are not already running it. Then, type the name of your snapshot file in single

    quotes followed by _ReadSnapshot.

    VM# 'Snapshot' _ReadSnapshotSelf 0>

    When the Self 0> prompt appears, you are ready to type in SELF expressions and explore the

    SELF world. The snapshot file name can be a relative or absolute path name, and tildes will be ex-

    panded as they are in the Unix C-shell. If the first component in the file name is not the root, tilde,

    or the current directory, then SELF will search the sequence of directories set by_DirPath: for a

    file of the given name.

    As a shortcut, you can just type the name of the snapshot to the Unix shell as if it were a command; Unix will run

    whatever version of the SELF virtual machine it finds in your search path and then read the snapshot.

    7 How to Use the .selfrc File

    When SELF is first started, the virtual machine looks for the file .selfrc in your login directoryand, if it finds the file, evaluates all SELF expressions contained therein. This mechanism allows

    you to customize your SELF environment. For example, you can define custom shortcuts for fre-

    quently typed expressions. The .selfrcfile can also set virtual machine options such as _Dir-Path. Here is an annotated example:

    _DirPath: '~/mySelfDirectory' set the VMs search path_SnapshotCode: true VM option to save compiled code with snapshot

    shell _AddSlotsIfAbsent: ( |Command shortcuts added to the shell object:

    spyOn = ( _Spy: true ). turn spy onspyOff = ( _Spy: false ). turn spy offgc = ( _GarbageCollect ). run garbage collectorquit = ( _Quit ). quit

    | )

    The .selfrcfile is executed immediately after SELF starts up. If you are starting up a snapshot,the .selfrcfile is executed before the snapshot is read in. Thus, any command shortcuts or otherchanges to the SELF world made by the .selfrcfile are overwritten when the snapshot is read in.However, virtual machine settings like_DirPath: and_SnapshotCode: survive.

    8 How to Evaluate Expressions

    Arbitrary SELF expressions can be typed at the SELF prompt. Each expression is evaluated and the

    result printed by the SELF read-eval-print loop. Here are some examples:

    Self 0> 3 + 47 The system reads the expression, evaluates it, and prints the result.

  • 7/28/2019 How to Use SELF 2.0

    14/50

    14

    How to Use SELF 2.0 How to Evaluate Expressions

    Self 1> 20 factorial2432902008176640000

    Note that the system prints a prompt string such as Self 0> to indicate that it is ready to accept

    an expression. The number in the prompt string is an index into the command history (discussed in

    the next section). The value of the evaluated expression is always printed, even if the expression

    performs explicit output. For example, in the following example, the final 10 printed is the value

    of the do: expression:

    Self 2> 10 do: [| :i | (i * 2) print. print]0 2 4 6 8 10 12 14 16 18 10

    Multi-line expressions can also be entered. If the read-eval-print loop discovers that the expression

    typed so far has open (unbalanced) parentheses or brackets, it provides a continuation prompt (>>),allowing the expression to be continued on the next line. One can enclose a sequence of expressions in an

    extra set of parentheses to force the parser to read input lines until the final closing parenthesis. This handling of

    multiple line expressions is also used by the parser when evaluating expressions in script files (see

    section 16). For example:

    self 3> 4 do: [| :i |>> (i printString, ! = , i factorial printString)>> printLine ]

    0! = 11! = 12! = 23! = 64

    Sometimes an input expression contains an error. For example:

    Self 3> snortNo snort slot found in shell.## Stack trace for process ##___Rcvr__Selector/Block_________File:line______Method-holder...#5 snort :1 shell

    The first line of the error explains the cause of the error. In this case, the message snort was notunderstood by the implicit receiver shell (the shell object is discussed in the next section). Sec-

    tion 13 describes all the kinds of errors that can arise in SELF programs.

    8.1 The shell object

    In order for a SELF expression to be evaluated, the meaning of self must be defined. When an

    expression is evaluated by the read-eval-print loop, the shell object plays the role of self:

    Self 5> selfshell

    The shell is a child of the lobby:

  • 7/28/2019 How to Use SELF 2.0

    15/50

    15

    How to Use SELF 2.0 How to Evaluate Expressions

    Self 6> shell parentlobby

    The lobby is a common parent of many objects in the system and therefore provides a kind of lin-

    guistic common ground for the language. In particular, many useful objects such as true and all

    the prototype objects are accessible from the lobby. When the virtual machine evaluates the ex-

    pressions you type, messages implicitly sent to self get looked up first in the shell object, then in

    the lobby, then in the lobbys parents, and so on.

    The actual details of the read-eval-print loop is as follows: an expression is read from the standard input. The input is

    treated as if it were defining the body of a method in the doIt slot of the lobby. If the input is syntactically correct,the system installs the generated bytecodes as the doIt method and creates a new process which sends printIt tothe lobby. printIt is a SELF method (modifiable by the user) which calls doIt and then prints the result.

    Expressions read from afi

    le by the_RunScript primitive, however, are handled slightly differ-ently: they are evaluated in the context of the lobby itself, not the shell object. This arrangementkeeps the lobby free of temporary slots added by the user, preventing accidental name clashes. The

    programmer can thus safely augment the shell object with slots to store temporary results and

    shortcuts to reduce typing (i.e., methods playing the role of macros). For example:

    Self 7>_AddSlots: ( | s | ) Adds the slot s to the shell.shell

    Self 8> s: screenBitmap Puts the screenBitmap into the s slot.shell

    Self 9> s xorRect: 0@0 To: 30@30 Tell s to draw a rectangle on the screen.

    Self 10>_AddSlots: ( | makeBox = ( s xorRect: 0@0 To: 30@30 ) | )shell

    Self 11>makeBox Shortcut to draw the rectangle s on the screen.shell

    The shell has another parent in addition to the lobby: the enter parent. The enter slot normally

    points to an empty object. This slot is called enter because you can type enter: 3@4 and you

    Many objects inherit

    from the lobby.

    ...

    lobby

    shell

    parentsof thelobby.

    In the expressions you

    type in, a message sent

    to self gets sent to the

    shell object, and meth-

    od lookup passes on

    from there through par-

    ent links.

  • 7/28/2019 How to Use SELF 2.0

    16/50

    16

    How to Use SELF 2.0 How to Use the Command History

    expressions typed by the user will be lexically inside the point 3@4. That is, subsequent messag-es sent to self will be looked up in the point object because it is now a parent of the shell. Using the

    enter slot can reduce typing when you find an object you wish to understand better. For example:

    Self 12> enter: 3@4 A point object is made the shells enter parent.shell

    Self 13> x The x message finds a matching slot in the point.3

    Self 14> x: 7 Change the value ofx from within the object (x: is a private slot).shell

    Self 15> enter Remember, enter is just the name of a slot in the shell.

    7@4The shells enter slot has higher priority than its parent slot. Thus, messages to self by the input expression willbe looked up first in the shell itself, then in the shells enter parent and other higher-priority parents, and then in theshells parent parent (a lower-priority parent, the lobby).

    9 How to Use the Command History

    You may notice that each time you type an expression to the SELF prompt, the number in the

    prompt string advances. That is because each command you type is recorded in a command history

    object, along with its result. The number in the prompt string is a history number that can later be

    used to refer to a given command in order to examine the result of the command or to redo thecommand. Only the most recent N entries are saved. The value of N can be changed with historykeep: n.

    . . .

    lobby

    shell

    Using multiple parent

    slots, the shell object in-

    herits from both from the

    lobby and some other ob-

    ject. The shell slot that al-

    ways points to the lobby

    is called parent. The

    other parent slot is called

    enter.

  • 7/28/2019 How to Use SELF 2.0

    17/50

    17

    How to Use SELF 2.0 How to Inspect and Print Objects

    You can view the most recent entries by typing history printRecords. The resulting outputwill look something like this:

    Self 5> history printRecords[0] 20 factorial[1] 3@4[2] ui start[3] ui add: 3@4[4] 17 parent

    You can use the history object to get the result of a command or to redo it:

    Self 6> history getResult: 4traits smallInt

    Self 7> history execute: 02432902008176640000

    Self 8> history getPrefix: '20 fac'[0] 20 factorial

    Self 9> history executePrefix: '17 par'traits smallInt

    These are verbose expressions: you will probably want to define shortcuts for the history opera-

    tions you use most frequently. You can add these shortcuts to your .selfrcfile so that they areautomatically added to shell object each time you start SELF. Some suggested shortcuts for his-

    tory operations are given in history.self.

    10 How to Inspect and Print ObjectsThere are various ways to examine and print objects, several that depend on parts of the default

    world being functional and one that does not.

    10.1 Using inspect:

    The inspect:method attempts to print the contents of each slot in its argument. It also prints thedefinitions of methods contained in slots of the inspected object.

    Self 0> inspect: 3@4( | _ parent* = traits point.

    _ thisObjectPrints = true.^_ x

  • 7/28/2019 How to Use SELF 2.0

    18/50

    18

    How to Use SELF 2.0 How to Inspect and Print Objects

    ^_, indicating that the accessing slots x and y are public but the corresponding assignment slotsx: and y: are private. Here is a somewhat longer example:

    Self 1> inspect: traits point

    ( | _ parent* = traits pair.

    ^ separator = @.^ copyX: x Y: y = ( (clone x: x) y: y ).^ xAxisReflect = ( copy y: y negate ).^ yAxisReflect = ( copy x: x negate ).^ restrictTo: rect = ( | xr rect bottom ifTrue: [ yr: rect bottom ].xr @ yr ).

    ^ alignToGrid: s = (((x / s width ) * s width ) @((y / s height) * s height) ).

    ^ # pt = ( rectangle from: self To: pt ).^ ## sz = ( rectangle from: self To: + sz maxPoint ). | )

    traits point result printed by read-eval-print loop

    10.2 How objects are printed

    This section briefly discusses how objects are printed by the read-eval-print loop in the default

    world. For additional details, see the SELF Style Manual.

    Object-centric printing. Many objects in the default world understand messages that cause them

    to print themselves in an object-specific manner. The convention in the default world is for such

    methods to be invoked by sending print or printLine (which includes a newline after printing)to the object:

    Self 17> (3 @ 4) printLine3@4 This output is the result of sending the printLine message.3@4 This is the result printed by the read-eval-print loop.

    The message printString (and variations thereof) is used to get an objects printString without

    printing it:

    Self 18> (3 @ 4) printString'3@4' The result is a string object, printed by the read-eval-print loop.Self 19> (3 @ 4) printString size3 The printString is 3 characters long.

    The read-eval-print loop. As previously mentioned, SELF sends printIt to the lobby when anexpression is typed at the prompt, after first installing the expression into the doIt slot in the shell.printIt attempts to print the result ofdoIt in an intelligent manner. It does this by invoking the

  • 7/28/2019 How to Use SELF 2.0

    19/50

    19

    How to Use SELF 2.0 How to Inspect and Print Objects

    name inferencer, a SELF-level mechanism that asks objects to print themselves if they know how,

    or tries to infer a name based on the objects location in the world otherwise. (This is not the case

    in the bare world, the minimal collection of objects you get when you start the SELF VM without

    reading in a snapshot or script files. In this case, printIt simply sends the_Print primitive, de-

    scribed in the next section, to the result ofdoIt.) The name inferencer uses thepath cache, a SELF

    object that caches paths from the lobby to objects in the world. Objects that are reachable from thelobby (and thus appear in the path cache) are considered well-known. Here are some examples

    illustrating the name inferencer in the read-eval-print loop:

    Self 1> 3 @ 43@4 The name inferencer uses the printString method for points.

    Self 2> 17 parenttraits smallInt The name inferencer named this object based

    on its location in the world of objects.

    The name inferencer often generates a name that is actually a sequence of message sends that eval-

    uates to the named object. For example:Self 3> traits pointtraits point This name is an expression you can evaluate to get the object.

    The name traits point is a short version of the full path from the lobby to the traits for point ob-

    jects, traits graphics point.

    The name for well-known objects that also respond intelligently to printString is a combination of

    the path name and the printString. For example, the prototype point object has both a location part

    and a name part:

    Self 4> point

    0@0 This name has both a location part (point) and a printString part (0@0).

    In this case, the name part is short for prototypes graphics point.

    10.3 Primitive Printing and Object Reference Numbers

    The object printing and inspection mechanisms just discussed assume that certain basic facilities

    of the SELF world are working (e.g., string concatenation). This raises a bootstrapping question:

    what happens if these basic facilities themselves are broken and you need to debug them? The an-

    swer is to use the virtual machine primitives_Print and_AsObject.

    10.3.1 Object Reference Numbers

    _Print refers to objects by assigning them object reference numbers. An object reference numberis a small integer provided by the virtual machine as an object handle. One could use memory addresses

    for this but addresses can be large numbers that are cumbersome to remember and type. Besides, the address of an ob-

    ject may change after a memory scavenge or garbage collection; in contrast, object reference numbers remain invari-

    ant. Object reference numbers are printed as an integer surrounded by angle brackets, for example

  • 7/28/2019 How to Use SELF 2.0

    20/50

    20

    How to Use SELF 2.0 How to Inspect and Print Objects

    . The user can turn a reference number (an integer) into an object by sending it the_AsOb-ject primitive. For example:

    Self 5> 6 _AsObject3@4 The object reference number 6 refers to the point 3@4.

    The virtual machine only keeps track of the last n objects assigned reference numbers, where n is a configuration pa-

    rameter controlled by the_NumObjectsIDs option (default:_NumObjectIDs: 1000). A given reference num-ber is valid as long as it is within the last n reference numbers assigned. After this, it is forgotten and sending it the

    _AsObject primitive will fail. However, reference numbers are not recycled during a SELF session, so an invalid his-

    tory number will not later be assigned to some other object; doing that could be very confusing!

    10.3.2 The_Print Primitive

    The_Print primitive is a basic object printing function implemented entirely in the virtual ma-chine._Print prints its receiver and returns nil as the result. The output of the_Print primitive

    always lists at least the object reference number and slots of the receiver. It may also contain addi-

    tional information for certain kinds of objects. The following sections describe the output of the_Print primitive in greater detail.

    Plain objects. Ordinary objects respond to _Print by printing their reference number and a list

    of their slots._Print is a shallow operation: it does not recursively send_Print to the contentsof its slots. Instead, the contents of a slot is printed as follows:

    its literal form if the slot contains an integer, a float, or a string,

    true, false, nil, or lobby if the slot contains one of these objects,

    (3 @ 4) _Print: ( | _ parent* = . _ thisObjectPrints = true. ^ x = 3. _x: =

  • 7/28/2019 How to Use SELF 2.0

    21/50

    21

    How to Use SELF 2.0 How to Inspect and Print Objects

    Self 1> (5 @ 7) _Print: ( | _ parent* = . _ thisObjectPrints = true. ^ x = 5. _x: = someVector _Print: ( | ^ parent* = . | object array: {true, , 2.45} )nil

    Integers and floats. Integers and floats are not assigned history numbers since their values can be

    directly printed and typed so easily.

    Self 4> 1.3 _Print1.3: ( | ^ parent* = . | ) The output of_Print. The float 1.3 has one parent slot.

    nil

    Self 5> 16r2f _Print A hexadecimal number (2F radix 16).47: ( | ^ parent* = . | ) Integers always_Print in decimal.nil

    Strings, special objects, processes, and mirrors. Strings and the true, false, nil, and lobbyobjects print their conventional form before their reference number and slot lists. Process objects

    print the special keyword process before their reference number and slot lists. Mirror objects(see the SELF World manual) print the short form of their reflectee in addition to the reference

    number and slots of the mirror.

    Self 6> 'tree' _Print'tree' : ( | ^ parent* = . | byte array: {116, 114, 101,101} ) Strings are surrounded by single quotes.nil

    Self 7> true _Printtrue : ( | _ parent* = . ^ printString = true. ^ifTrue:False: = . ^ || = . ^ && = .^ ^^ = . ^ not = false. ^ asInteger = 1. | )nil

  • 7/28/2019 How to Use SELF 2.0

    22/50

    22

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    Self 8> (reflect: 2@3) _Print Create a mirror on 2@3 and sends_Print to it.mirror : ( | ^ parent* = . _ thisObjectPrints = true. | )nil

    11 How to Use the SELF Graphical User Interface

    The SELF graphical user interface is a prototype browser for SELF. This prototype (hereafter re-

    ferred to as the ui) serves as an inspector, allowing the user to explore the SELF object world by

    pointing and clicking. The ui currently does not support editing, and has only rudimentary object

    modification and message sending capabilities. It was developed to explore some ideas in user in-

    terfaces for object-oriented programming environments and is not intended to serve as a full-

    fledged environment for SELF.

    11.1 Requirements

    The ui will work with either a monochrome or an 8-bit color framebuffer. However, a GX frame-

    buffer is recommended for color operation; the ui may have poor performance on less powerful

    color frame buffers.

    The ui can run under OpenWindows (in certain configurations; see below) or on the console direct-

    ly, with no window system running. In both versions, the ui uses Suns Pixrect graphics library,

    which draws directly into the framebuffer independent of any running window system. Therefore,

    the OpenWindows version of the ui has certain requirements beyond that of a normal X applica-

    tion.

    OpenWindows

    The preferred way to run the ui is under OpenWindows, Suns window system supporting X

    and NeWS. The window manager must be olwm or olvwm, the Open Look window manager

    that is standard with OpenWindows. A monochrome or color monitor may be used; however,

    for the color OpenWindows version the ui requires a GX framebuffer (or better).

    The OpenWindows version of the ui uses X-based primitives for opening the window and col-

    lecting user input events, but, as mentioned above, the graphics primitives in this version of

    SELF are based on Pixrect, not X, so the ui cannot run on remote window servers: it must be

    run on the local machine.

    Console

    The ui can also run outside any window system, on the console of the machine that SELF is

    running on. A monochrome or color framebuffer may be used. Normal printing to the console

    is not suppressed and may temporarily disturb the screen.

    The Pixrect/X combination requires the use of certain window manager dependent code; in this case, the OpenWin-dows color version requires a hardware cursor, which is provided by OpenWindows, olwm, and the GX.

  • 7/28/2019 How to Use SELF 2.0

    23/50

    23

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    11.2 Configuring the UI

    Two slots in the preferences miscellaneous object determine the physical screen uponwhich the ui runs: xDisplay (defaults to :0.0) and framebuffer (defaults to /dev/fb).

    For a multi-headed machine (having more than one screen), these slots can be set to other namesas appropriate. After changing the contents of these slots you must evaluate the expression:

    graphicsInit initialize

    to make the prototypical screen object refer to the correct physical screen. The framebuffer and the

    X display must refer to the same physical screen so that the X window and the Pixrect graphics will

    be drawn together. If you start the ui and the X window appears on one screen and the graphics ap-

    pear on another, check the contents of the xDisplay and framebuffer slots in preferencesmiscellaneous, and make sure you have sent the message graphicsInit initialize.

    When the ui starts it automatically configures itself to its environment. It will configure itself as ei-

    ther the OpenWindows version or the console version, as appropriateif the DISPLAY environ-ment variable is defined, it will configure for OpenWindows; if it is not defined, it will configure

    for the console. It will also configure itself for monochrome or color operation, depending on the

    depth of the chosen framebuffer. It will use large fonts if the framebuffer is high-resolution. Final-

    ly, it will size itself to leave room for the spy if the spy is running on the same framebuffer.

    11.3 Starting the UI

    It is recommended that you start the spy (the SELF system monitor) before starting the ui. Start the

    spy by sending the message_Spy: true. The spy will let you know whether pauses are due to

    SELF code being executed, the system dynamically compiling SELF code or, perhaps, a garbagecollection taking place.

    To start the ui, simply send the message ui start. This puts a single object into the ui, the lobby.

    To start the ui with a different object visible, use ui startWith: obj.

    In the OpenWindows version, you can resize the ui window, move it anywhere on the screen, or

    iconify it.

    Because the ui is not a full-fledged X application, it must rely on the X events it receives to determine these chang-es. Occasionally it will update its screen after the window has changed size or placement or has been iconi fied, butbefore it finds out about the change. In these cases, the Pixrect graphics primitives will draw over other windows inOpenWindows and you may need to do invoke the Refresh command from the OpenWindows desktop menu.

  • 7/28/2019 How to Use SELF 2.0

    24/50

    24

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    11.4 Summary of Mouse Button Functions

    The ui primarily relies on the mouse for its operation, although it also uses several function keys.

    The following sections describe the operation of the ui in detail, but for starters, here is a short

    summary of the mouse button functions.

    11.5 Manipulating Objects in the UI

    The ui presents SELF objects as three-dimensional boxes floating in their own artificial reality. The

    slots of an object are depicted as wide slabs on the face of the object, and the contents of each slot

    are smaller slabs on the faces of the slots. The relationship between objects and the slots that con-

    tain (i.e., refer to) them is shown by arrows pointing from the slots to the objects. Objects can be

    moved about on the screen, the contents of their slots can be examined, and they can be removed

    from the screen.

    Moving objects. Objects can be picked up and moved about on the screen by pointing to the face

    of the object (or the face of one of its slots), pressing down and holding the left mouse button, and

    moving the mouse. Letting go of the left mouse button drops the object.

    Examining slots. Pressing down the left mouse button on the contents of a slot (the contentsbox) causes the object in the slot to display itself on the screen (sprout), connected to the slot

    by an arrow. Sprouting is simply a special case of grabbing; after sprouting an object, the object is

    in hand and can be moved immediately as long as the mouse button is held down. Navigating in

    the ui is performed by traversing slots to reach the desired object (the lobby object is a good start-

    ing point).

    Removing objects from the screen. Clicking the right mouse button on the body of an object (not

    one of its slots) removes that object from the screen.

    Hiding and showing slots. Clicking the right mouse button on a slot will hide that slot. Hidden

    slots do not show on the face of the object. When some of an objects slots are hidden, a long barcalled the hidden-slots bar appears across its bottom. Pressing the left mouse button on the hidden-

    slots bar yields a pop-up menu that lists all the hidden slots. Selecting an item from this menu

    Table 1 Mouse button functions in the ui

    Mouse button Function Examples

    left grabbing sprouting contents, moving objects, popping up menu

    middle (color changing) (color version only; shift key must be down to initiate)

    right removing remove boxes from screen, hide slots, desprout arrows

  • 7/28/2019 How to Use SELF 2.0

    25/50

    25

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    makes the slot appear in the object. In addition to the hidden slots, this menu may include some

    of the special entries described in the table below.

    Except for theAll item, which is always present in the hidden slots menu, special menu items ap-

    pear only when there is at least one slot (or pseudo-slot) in that object matching that category.

    Hiding all slots (iconification). Clicking the right mouse button on the hidden-slots bar on the

    bottom of the box will hide all slots, effectively iconifying the object. If the object currently has no

    hidden slots, you can make the hidden-slots bar appear by clicking on some slot with the right button to hide it, then

    right-click the hidden-slots bar to hide the rest of the slots.

    Hiding links between objects. Clicking the right mouse button on a sprouted contents box simply

    removes the arrow between the slot and the object contained in the slot.

    Menus do not reflect the philosophy of concreteness we espouse for the ui (see [CU90]). They have been added tothe ui as an expediency, to make this prototype more practical in the interim before a full-fledged user interface isconstructed.

    Table 2 Special items in the hidden slots menu

    Menu item Effect

    All Shows all slots

    Parents Shows only parent slots

    Public Shows only public slots

    Indexable Shows only the elements of the

    vector or byte vector part

    Well-known

    indexable

    Shows only those elements of the

    vector part that are well-known

    (i.e., recorded in the path cache)

    Sendable Shows only send pseudo-slots

  • 7/28/2019 How to Use SELF 2.0

    26/50

    26

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    Pseudo-slots. The ui permits access to certain parts of vectors, methods, and mirrors by way of

    pseudo-slots. For example, object vectors and byte vectors show their elements as pseudo-slots,

    in addition to showing their regular slots. Pseudo-slots have names enclosed in angle brackets.

    Send pseudo-slots. Objects may appear in the ui with pseudo-slots that send a single unary

    message to that object. (See below for how to add objects with send pseudo-slots.) Clicking on the

    contents portion of a send pseudo-slot (labelled ) sends the message to the object.

    The object returned by the message send will appear in the ui.

    Table 3 Objects that have pseudo-slots in the ui

    Kind of object Pseudo-slots

    process process stack

    mirror the object that the mirror reflects (its reflectee)

    vector vector elements (the element indices are the names of the pseudo-slots)

    byte vector byte vector elements (the element indices are the names of the pseudo-slots)

    method byte code array, literal array, file name, file line number, source string

    block lexical parent

    generic activation receiver, expression stack, byte code position, plus all method pseudo-slots

    method activation selector, method holder, sender, plus all generic activation pseudo-slots

    block activation selector, lexical parent, sender, plus all generic activation pseudo-slots

  • 7/28/2019 How to Use SELF 2.0

    27/50

    27

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    Enumeration buttons. The ui can find objects with certain relationships to a given object. These

    enumerations are requested by pressing an enumeration button with the left mouse button. There

    are five kinds of enumerations, as depicted in the diagram below and explained in the table below.

    Enumeration results appear in the ui as vectors with only the interesting elements showing. If

    there are no objects satisfying the enumeration, an object appears saying so.

    Changing the contents of objects by grabbing arrows. [This is potentially a hazardous operation.]

    By setting allowArrowGrabbing to true in the preferences object (see below), the ui will allowthe contents of a slot to be changed by grabbing the head of its outgoing arrow with the left mouse

    button and dropping it over another object. When the arrowhead is grabbed, it changes into asquare, indicating that it is waiting for a target. Dropping the square onto another object makes the

    arrow to point to that object, thereby changing the contents of the slot that the arrow is coming

    from. (Be sure to drop the square onto the target object, not merely near it.)

    Some arrow redirections are not currently permitted by the ui. These include moving an arrow for

    a pseudo-slot and moving an arrow to a method object that takes a different number of arguments

    than the original contents of the slot. In these cases, a warning is printed in the SELF shell and no

    change is made. Dropping an arrow over empty space aborts the operation.

    Table 4 Enumeration buttons

    Enumeration Description

    references all references to this object

    children all children of this object (a subset of all references to this object,

    in which the references are through parent slots)

    senders all senders of messages whose selector is the name of this slot

    implementors all implementors of this message (the name of the slot)

    messages all messages sent in this method (appears only on method slots)

    r - references

    c - children

    m - messages

    i - implementors

    s - senders

  • 7/28/2019 How to Use SELF 2.0

    28/50

    28

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    Be careful! Indiscriminately changing objects on which the rest of the system depends can break

    parts of the system, and redirecting arrows in the ui is tantamount to altering the running system.

    If the ui and other parts of the SELF system begin behaving strangely (many errors and stack

    dumps), it may be because a crucial part of the system was changed unintentionally. In this case,

    quit SELF and start anew.

    Function key operations (OpenWindows version only). Objects in the ui and the ui itself also re-

    spond to certain key press events from the keyboard. The relevant object is the object under the

    cursor at the time of the key press. If the cursor is on the background (i.e., not on any object), the

    key press generates a message to the ui itself.

    It is fairly easy to extend this functionality: the ui sends keyPress: keyCode to the object under the cursor.

    User interface objects inherit keyPress: methods. The keyPress methods are in traits screenBox,traits baseBox, and in their common parent, traits nestedBox. (See the corresponding .self files.)

    11.6 Manipulating Objects from the Prompt

    Operations in the ui can be carried out from the prompt by sending messages to the ui object. Themost useful of these messages is add:; the expression:

    ui add: obj

    Table 5 Function key operations

    Key Effect

    Stop (L1) On the background, quits the ui.

    Props (L3) Adds a mirror on the object into the ui.

    Cut (L10) Removes the object from the ui, but retains a reference to the object in a hidden

    clipboard.

    Copy (L6) Puts a reference to the object into the clipboard.

    Paste (L8) On the background, puts the object in the clipboard into the ui.

    On an object, adds the slots of the object in the clipboard to the given object.

    Find (L9) sends enter: thisObject to the shell object. This means that the givenobject will be made a parent of the type-in shell. This allows you to evaluate

    expressions that are interpreted as if they are inside the given object.

    F1 Adds to the ui the display object to which you are pointing. For example, if you

    point to the senders button on an object and hit F1, the sendersBox object thatimplements the button will appear in the ui.

    F2 Finds the nontrivial parents of an object. Point to an object and press F2 to find

    any parents of the object which themselves have parents.

    F3 Traces the ancestry of an object. Point to an object, (move it to the lower left-

    hand corner of the screen), and press F3 to see all the objects ancestors which

    themselves contain parent slots. (Ancestors without parent slots are ignored in

    order to avoid cluttering things up with mere category objects.) F3 stops at the

    lobby, but you can go on by pointing to the lobby and pressing F3.

  • 7/28/2019 How to Use SELF 2.0

    29/50

    29

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    makes the given object obj appear in the ui. To add the object to the ui with a send pseudo-slotfor the unary message foo, use:

    ui add: obj With: foo

    The ui also responds to add:With:With:, add:With:With:With:, and add:WithMessag-es: (which takes a list of strings) to add the object with multiple send pseudo-slots.

    Nearly all the operations that can be carried out with the mouse in the ui can also be achieved by

    sending messages to ui. For details, see clientRequests in the file ui.self.

    11.7 Customizing the UI

    There are a number of ways to customize the way objects look and behave in the ui.

    Animation. The monochrome version of the ui has no animation beyond that of grabbing and

    moving the boxes. The color version of the ui, by default, does have animation (sprouting boxes,

    entering and exiting boxes, arrow sprouting, menu sprouting). To turn off this animation in the

    color version, send the message animator beDummy. To turn it back on, send the messageanimator beReal.

    OpenWindows icon. If the ui finds a file with the name specified in preferences (see below; by de-

    fault, a file in the current directory named ui.icon), it will use that file for its icon when it is ico-

    nified. The icon file is an X bitmap format file. If no icon file is found, the ui uses the default

    OpenWindows icon.

    Colors. If the ui finds a file with the name specified in preferences (see below; by default, a file

    in the current directory named ui.colors), it will use that file for the initial color scheme. To cre-

    ate a color file, see section 12.8.

    Preferences. The ui uses the preferences object to control various options. To change a prefer-

    ence, set the appropriate slot of the preferences object to the desired value. For example, to enable

  • 7/28/2019 How to Use SELF 2.0

    30/50

    30

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    arrow grabbing, evaluate preferences allowArrowGrabbing: true. The ui preferenceslots are summarized in the following table:

    Box blueprints. The ui has a facility to customize the way an object first appears on the screen

    which slots are showing and what send pseudo-slots are shown. It does this by consulting a dic-

    tionary ofblueprints for objects, keyed on the structure of the object (the names of all its slots). If

    a blueprint is found, the ui uses that to determine which slots are shown and which are hidden, and

    what send pseudo-slots to add to the object. If no blueprint is found, a default policy is used. You

    can add your own blueprints to this dictionary; see the file boxBlueprint.self.

    11.8 Changing Colors

    On a system with a color framebuffer, pressing down and holding the middle mouse button while

    simultaneously holding down the shift key causes the cursor to enter color space. Once color space

    has been entered, the shift key may be released, but the middle button must remain pressed during the entire color

    changing operation.

    Color space allows the colors of the ui to be changed interactively. Whatever the cursor is pointing

    at when color space is entered is whats color will be changed. (This includes, for example, the

    background, the boxes, the text on the boxes, and the arrows. In the case of arrows, point to theround tail of the arrow to change its color.) Entering color space transports the cursor to the abso-

    lute location of the current color in the ui window. In color space, the horizontal axis measures hue

    and the vertical axis measures brightness. Pressing the left button down in while in color space

    (while keeping the middle button down) switches the vertical axis from brightness to saturation.

    In the console version of the ui, it is not necessary to hold down the shift key to enter color space.

    Table 6 UI preferences

    Slot Name Description Default

    allowArrowGrabbing If true, allow arrowheads to be grabbed and dropped on other

    objects. Color version only.

    false

    blurArrows If true, enable experimental motion blur for arrows. Color

    version only.

    false

    blurBoxes If true, enable experimental motion blur for boxes. Color ver-

    sion only.

    true

    colorFile File name to use for initial color scheme. Color version only. ui.colors

    grabAfterSprout If true, hold on to the box after it has been sprouted if the

    mouse button is still down.

    true

    iconFile File name to use for the ui icon. File should be in X bitmap

    format. OpenWindows version only.

    ui.icon

    useBigFonts If true, use a bigger font and format for boxes. (The ui will

    always use big fonts for a high-resolution framebuffer.)

    false

  • 7/28/2019 How to Use SELF 2.0

    31/50

    31

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    Moving the cursor in color space interactively changes the color of the target elements. Releasing

    the middle button leaves color space.

    The color scheme for the ui is automatically saved after color changing. A file is created to hold the

    color information. This files name is defined by the preferences object (the default is ui.colors).

    The ui checks for thisfi

    le when it starts up and, if itfi

    nds it, uses the given colors. Otherwise, ituses the default colors.

    11.9 Leaving the UI

    The expression ui quit always aborts the ui. Under OpenWindows, you can also leave the ui by

    going to the border of the X window, popping up the Window menu, and selecting Quit; or by

    pressing function key L1 (labelled Stop on many keyboards).

  • 7/28/2019 How to Use SELF 2.0

    32/50

    32

    How to Use SELF 2.0 How to Use the SELF Graphical User Interface

    Part III

    Programming and Debugging

    Here is the heart of the matter: writing and debugging your own SELF programs.

  • 7/28/2019 How to Use SELF 2.0

    33/50

    33

    How to Use SELF 2.0 How to Debug SELF Programs

    12 How to Debug SELF Programs

    The default world contains a tty-based debugger. The debugger allows the user to control the exe-

    cution of a process and to examine the process stack. As described in [HCU92], the SELF system

    provides full source-level debugging with dynamic deoptimization. Debugging optimized code is

    therefore completely transparent to the user. Limited undocumented debugging facilities are alsoprovided by the graphical user interface; see process.self. This section assumes that the SELFprocess scheduler is running. If the current prompt is VM#, you can type prompt start to startthe scheduler:

    VM# prompt startSelf 1>

    12.1 Examining an Error

    When an error occurs, the scheduler suspends the active process and prints out an appropriate error

    message. (A complete list of possible error messages is given in section 14.) If the error messageis too vague to discover the bug, you can attach the erroneous process to the debugger and explore

    the stack.

    A new process is created for each expression evaluated by the read-eval-print loop. When an error occurs, the process

    is suspended and the debugger can be used to explore its stack.

    Suppose you typed the following erroneous expression at the prompt:

    Self 1> | i attach attaches the process that most recently encountered an errorNo i slot found in .Sending method holder is shell.shell doIt = (| i

  • 7/28/2019 How to Use SELF 2.0

    34/50

    34

    How to Use SELF 2.0 How to Debug SELF Programs

    In this example, the highlighting shows that the message i is being sent to a block object. This ex-plains the problem: the expression needed a period after the block to separate the expression into

    two statements.

    12.2 Setting Breakpoints

    Breakpoints can be added to a program by inserting halt statements (assuming that the receiver

    inherits from defaultBehavior). When a halt statement is executed, the currently executing pro-cess is suspended with a message indicating that a halt has occurred. The user can then examine

    the stack and control the execution of that process. Lets single step a typed in expression by set-

    ting a breakpoint as the first statement:

    Self 3> halt. 6 printLineHalt: running process{ halt. 6 printLine}

    Self 4> attach: 7 attach to the process with history number 7shell doIt = (halt. 6 printLine) the current byte code position is halt

    Process , suspended, activation: 5 in [0,5].File: shell

    Self 5> step single step by one byte codeshell doIt = (halt. 6 printLine)Process , suspended, activation: 5 in [0,5].File: shell

    ... etc ...

    As shown, breakpoints are explicit inserted in the source code. Setting a breakpoint in a method

    defined in a script file involves editing the script file and then reading it in. We hope to eliminate

    this inconvenience when a better programming environment is available.

    Caution: inserting halt in a method used by the core system can result in unexpected behavior(e.g., the debugger itself might break). This problem can be solved by using conditional break-

    points to restrict breakpoints to specific processes. The method break is an example of a condi-tional breakpoint that breaks the process only if the process is currently attached to a debugger.

    break = (process this isDebugged ifTrue: [ halt ])

    12.3 Interrupting a Running Process

    A runaway process can be suspended (by typing control-C) and then attached to the debugger.

    Lets execute an infinite loop where the value of slot i is incremented in each iteration:

    Self 11> | i

  • 7/28/2019 How to Use SELF 2.0

    35/50

    35

    How to Use SELF 2.0 How to Debug SELF Programs

    ^C----------------Interrupt-----------------Ready: scheduling process{ | i attach: 0 upshell doIt = (| i

  • 7/28/2019 How to Use SELF 2.0

    36/50

    36

    How to Use SELF 2.0 How to Debug SELF Programs

    To see more message sends, turn off inline caching during tracing. Send_InlineCache:false to turn it off, followed by_FlushInlineCache to flush all entries that have already beencached. To see every message send, turn off inlining with_Inline: false followed by_Flushto flush the code cache, eliminating previously inlined code. This will generate a lotof output!

    Caution:_Trace is not very useful when the scheduler is running (the usual case) since tracing isnot restricted to a single SELF process. Tracing when the scheduler is running results in mixedtrace output from all currently executing SELF processes.

    12.6 Finding Objects

    The browse object implements an enumeration facility that allows you to find all the objects in thesystem with specific properties. The result of any browsing operation is a vector of mirrors.

    Example: find all objects having the selector upLex:

    Self 15> browse implementorsOf: upLex

    vector{mirror on (traits debugger inspecting)}

    Example: find all methods sending the message debugger:

    Self 16> browse sendersOf: debuggervector{mirror on (connectDebugger = ( enter: debugger copy ))}

    Example: find all objects referring to the object shortcuts:.

    Self 17> browse referencesTo: shortcutsvector{..., mirror on (shell)}

    Example: find all the objects in the system:

    Self 18> browse all... result intentionally omitted to save paper!

    12.7 Summary of Debugger Commands

    The following table summarizes the debugger commands.

    See the VM Reference Manual.

    Command Description

    attach attach the process that most recently generated an error

    attach: n attach the process with object reference number n

    detach detach the debugged process

    step single step one byte code

    next step to next byte code in the current activation

  • 7/28/2019 How to Use SELF 2.0

    37/50

    37

    How to Use SELF 2.0 How to Interpret Error Messages

    13 How to Interpret Error Messages

    Five kinds of errors can occur during the execution of a SELF program: lookup errors, primitive

    errors, programmer defined errors, non-recoverable errors, and fatal VM errors. This section de-

    scribes the various errors in each category. For each category, the general layout of error messages

    in that category will be explained along with the format of the stack trace. Then a rogues gallery

    of the errors in that category will be shown.

    By default, errors are handled by a set of methods defined in errorHandling.self. For all er-rors except non-recoverable and fatal VM errors, an object can handle errors in its own way by de-

    fining its own error handling methods. If the object in which an error occurs neither inherits nordefines error handling behavior, the VM prints out a low-level error message and a stack trace. The

    system will also resort to this low-level message and trace if an error is encountered while trying

    to handle an error.

    13.1 An Example

    Here is an expression that produces an error in the current system:

    Self 7> 100000 factorial

    The stack has grown too big.

    (Self 2.0 limits stack sizes, and cannot resume processes with stack overflows.)## Stack trace for process ##___Rcvr__Selector/Block__________File:line______Method-holder/location____#0 asSmallInteger smallInt:132 traits smallInt coercions#1

  • 7/28/2019 How to Use SELF 2.0

    38/50

    38

    How to Use SELF 2.0 How to Interpret Error Messages

    }*309#930 doIt :1 shell

    The error arose because the recursive method factorial exceeded the size allocated for the process

    stack which resulted in a stack overflow. The virtual machine currently allocates a fixed-size stack to each pro-

    cess and does not extend the stack on demand.

    The first two lines of the output describe the error. These lines are followed by a stack trace of the

    erroneous process. Each line in the stack trace denotes a method or block activation and is divided

    into several fields:

    #0 the number of the stack frame. #0 is the most recent frame, i.e. the one that causedthe stack overflow. The number of the last frame (#930) indicates the stack depth

    at the time of the error.

    the receiver of the message in this frame has object reference number 10. You can

    type inspect: 10 _AsObject to examine the receiver object.

    asSmallInteger

    the methods selector name. If the frame is a block activation frame, the source

    code is shown in this field (as shown in frame #3 of this example).

    smallInt:132the name and line number of the source file where this method is defined.

    traits smallInt coercions

    the methodholder of the method being executed. If the frame is a block activation,

    this is the frame method in which the block is defined (e.g., the block in frame #3

    is defined in the method factorial).

    A sequence of recursive calls is presented as a folded structure. In the above example the notation

    { ... }* 309 represent 309 occurrences of a sequence of activations with the same structure as

    activations #3, #4, and #5. One can explore the stack in greater detail using the debugger, as dis-

    cussed in section 12.

    13.2 Lookup Errors

    Lookup errors occur when an object does not understand a message that is send to it. How the ac-

    tual message lookup is done is described in the Language Reference Manual.

    No foo slot found in shell .The lookup found no slot matching the selector foo.

    More than one system slot was found in shell .The matching slots are: oddballs and prototypes .

    The lookup found two matching systemslots which means the message is ambig-uous. The error message also says where the matching slots were found.

    Ambiguities can often be solved by changing parent priorities.

    No fish delegatee slot was found in .The lookup found no parent slot fish, which was explicitly specified as the dele-gatee of the message.

  • 7/28/2019 How to Use SELF 2.0

    39/50

    39

    How to Use SELF 2.0 How to Interpret Error Messages

    No public c slot was found in .Sending method holder is traits processErrors noPublicSelector .Private slots were found in: and .

    The lookup found no public slot c but found two private slots. Changing a private

    slot to a public slot will solve the problem.

    13.3 Programmer Defined Errors

    These errors are explicitly raised in the SELF program to report errors, e.g. sending the message

    first to an empty list will cause such an error.

    Error: first is absent.Receiver is: list .

    Use the selectors error: and error:Arguments: to raise a programmer defined error.

    13.4 Primitive Errors

    Primitive failures occur when a primitive cannot perform the requested operation, for example, be-

    cause of a missing or invalid argument. Appendix H of the Reference Manual describes how prim-

    itive failures are handled.

    badTypeError: the _IntAdd: primitive failed.Its receiver was shell .

    The primitive failed with badTypeError.

    The selector 12 could not be sent to shell because it is not a string.The primitive_Performexpects a string as its first argument.

    The selector add: could not be sent to shell because it does nottake 2 arguments.

    The primitive_Performreceived the wrong number of arguments.

    There are many other kinds of possible primitive errors (see Appendix H of the Reference Manu-

    al).

    13.5 Non-Recoverable Process Errors

    Errors that hinder the process to continue its execution are referred to as non-recoverable errors.

    The stack has grown too big.

    (Self 2.0 limits stack sizes, and cannot resume processes with stackoverflows.)

    A stack overflow error occurs because the current version of SELF allocates a

    fixed size stack for each process, and the stack cannot be expanded.

    Self 2.0 cannot run a block after its enclosing method has returned.(Self cannot resume this process, either.)

    This error occurs if a block is executed after its lexically enclosing method has re-

    turned. This is call a non-LIFO block. Non-LIFO blocks are not supported by

    the current version of SELF.

  • 7/28/2019 How to Use SELF 2.0

    40/50

    40

    How to Use SELF 2.0 How to Manipulate SELF Objects

    13.6 Fatal Errors

    In rare cases, the virtual machine may encounter a fatal error (e.g., a resource limit is exceeded or

    an internal error is discovered). When this happens, a short menu is displayed:

    Internal error: signal 11 code 3 addr 4 pc 0x1ac768.

    Do you want to:1) Quit Self2) Try to print the Self stack3) Try to return to the Self prompt4) Force a core dump5) Loop foreverYour choice:

    The first line helps the SELF implementors locate the problem. Printing the SELF stack may pro-

    vide more information about the problem but does not always work. Returning to the SELF prompt

    is usually successful, but the system integrity may have been compromised as a result of the error.

    Execute the primitive_Verify to verify the virtual machines integrity; see Table 22 in AppendixH of the Reference Manual).

    Since fatal errors usually arise from a bug in the virtual machine, please send the SELF group a bug

    report as described in section I-2.5, and include a copy of the error message if possible. If the error

    is reproducible please describe how to reproduce it.

    14 How to Manipulate SELF Objects

    This section explains how to change objects by adding, redefining, and removing slots. The funda-

    mental functionality for altering objects at this level is made available through mirrors. A mirroron a SELF object provides structural reflection facilities for that object (see section 16 of the Ref-

    erence Manual). In particular, mirrors implement methods for adding and removing slots to their

    object (reflectee). The two basic methods are addSlots: and removeSlot:. All programmingtasks in SELF can be built on top of these two methods. If you were to build a program manipula-

    tion facility, you would implement it using mirrors.

    However, when the system starts from a bare world, mirrors do not yet exist, so they cannot be

    used to build up the initial world of objects. Instead, the underlying primitives are used to directly

    modify objects. Actually, after the script defining mirrors has been processed, we could use mirrors the define and

    add slots to objects in all subsequent scripts. This is currently not done simply because it is somewhat faster to call the

    primitives directly. The primitives corresponding to the two mirror methods previously mentionedare:

    _AddSlots: and_RemoveSlot:

    Two other primitives are also provided:

    _AddSlotsIfAbsent: and_Define:.

  • 7/28/2019 How to Use SELF 2.0

    41/50

    41

    How to Use SELF 2.0 How to Manipulate SELF Objects

    The current implementation does not allow integers, floats, canonical strings, or blocks as the receiver of or argument

    to the programming primitives. Of course, their parent objects may be used.

    14.1 Adding Slots

    Both the addSlots:method of mirrors and the_AddSlots: primitive add all the slots of the ar-gument object (typically an object literal) to the receiver. If a slot already exists,_AddSlots: justassigns it a new value. The contents of read-only slots can be changed this way. Slots in the receiv-

    er but not in the argument object are left alone. Here are some examples:

    Self 0> (reflect: shell) addSlots: ( | x = ( | | ) | )Ask a mirror to add a slot called x to the shell whose contents is an empty object.

    mirror on (shell)

    Self 1> inspect: x( | | )

    Self 2> x _AddSlots: ( | Use the _AddSlots: primitive to add...>> a > b. An assignable slot initialized to nil.>> c = 3. A constant slot.>> h = ( history printRecords ). A method slot.>> q = ( | a. b > ^_ p > | ) (all other slots in this example are

    undeclared and have public semantics).

    Self 3> inspect: x

    ( | a

  • 7/28/2019 How to Use SELF 2.0

    42/50

    42

    How to Use SELF 2.0 How to Manipulate SELF Objects

    Self 5> x _Print: ( | b = nil. c = 3. h = . q = . ^ p = nil.b: = inspect: p Inspect p.( | _ parent* = traits point.

    _ thisObjectPrints = true.^_ x inspect: p( | _ parent* = traits point.

    _ thisObjectPrints = true.^_ x

  • 7/28/2019 How to Use SELF 2.0

    43/50

    43

    How to Use SELF 2.0 How to Write a Program

    Self 12> x _Print Object x from the preceding example.: ( | b = nil. c = 3. hello = . q = . ^ p = nil.b: =

  • 7/28/2019 How to Use SELF 2.0

    44/50

    44

    How to Use SELF 2.0 How to Write a Program

    creates some initial objects. Then, as bugs are discovered, the script file is modified with a text ed-

    itor and read in again to update the existing objects.

    This mode offile-based programming is supported by the object manipulation primitives previous-

    ly discussed plus one additional primitive. The primitive_AddSlotsIfAbsent: adds to the re-

    ceiver only those slots of its argument object (usually an object literal) that the receiver does notalready contain. After performing this primitive, the receiver may contain some new slots, but all

    slots that previously existed in the receiver are unaffected. This primitive allows script files to be

    made idempotent: that is, reading them in multiple times has the same affect as reading them in ex-

    actly once.

    The use of_AddSlotsIfAbsent: and_Define: to build objects in script files usually follows

    the following pattern. The argument to_AddSlotsIfAbsent: is an object literal containing aslot initialized to an empty object. A subsequent_Define: modifies this newly-created object tocontain the appropriate slots. This pattern allows the programer to repeatedly edit and test an object

    definition. The first time the script file is read in, the object to be defined doesnt exist, and the

    _AddSlotsIfAbsent: creates a new empty object which_Define:fi

    lls in. When the scriptfi

    leis subsequently edited and read in again, the_AddSlotsIfAbsent: has no effect (since the slot

    containing the object already exists) but the_Define: replaces the old version of the object withits new definition._Define: is used instead of_AddSlots: so that obsolete slots are removed.The combination of_AddSlotsIfAbsent: and_Define: is used instead of a single

    _AddSlots: operation so that the identity of the edited object is preserved. That is, all referencesto the old object now point to the new object. For example, if a traits object is rede fined, then the

    parent pointers in all clones of its prototype see the behavior defined in the new traits object.

    Suppose the following definition of a simple point is found in the file point.self:

    _AddSlotsIfAbsent: ( | ^ pointTraits = () | ) Define the initial point traits.pointTraits _Define: ( |

    ^ clone = ( _Clone ).| )

    _AddSlotsIfAbsent: ( | ^ pointProto = () | ) Define the prototype.pointProto _Define: ( |

    _ parent* = pointTraits.^ x _AddSlots: ( | p1 | )shell

    Self 5> p1: ((pointProto clone) x: 5) y: 10

  • 7/28/2019 How to Use SELF 2.0

    45/50

    45

    How to Use SELF 2.0 How to Write a Program

    This picture shows the objects that have been created:

    Now, suppose the definition of the point traits in the file point.self is changed to:

    _AddSlotsIfAbsent: ( | ^ pointTraits = () | )pointTraits _Define: ( | Redefined point traits.

    ^ clone = ( _Clone ).^ print = ( x print. @ print. y print. ).^ + p = ( (pointProto clone x: x + p x) y: y + p y ).

    | )

    _AddSlotsIfAbsent: ( | ^ pointProto = () | ) Define the prototype.pointProto _Define: ( |

    _ parent* = pointTraits.^ x

  • 7/28/2019 How to Use SELF 2.0

    46/50

    46

    How to Use SELF 2.0 How to Write a Program

    This picture shows the resulting object changes:

    Reading in the edited script file modified the original pointTraitsobject in place, instead of cre-ating a new pointTraits object. This allows the new behavior to apply to existing clones of thepoint prototype such as p1. We can use_Print: to verify this:

    Self 7> pointTraits _Print: ( | ^ clone = . ^ print = . ^ + = . | )nil

    Self 8> p1 _Print: ( | _ parent* = . ^ x = 5. ^ x: =

  • 7/28/2019 How to Use SELF 2.0

    47/50

    47

    How to Use SELF 2.0 How to Write a Program

    The notebook object contains both state (notes) and behavior (e.g., printNotes). It inherits some of

    its behavior from traits oddball.

    After the notebook object has been created, it can be used to record unstructured notes in the form

    of strings:

    Self 9> notebook addNote: 'This is a short note.'

    Note that addNote: returns the notebook object. This initially prints as becausethe notebook object is not in the pathCache. This problem can be corrected by updating the path-

    Cache:

    Self 10> pathCache refillrefilling path cache...done.'1642 entries'

    Self 11> notebook addNote: 'SELF is fun!'notebook

    Self 12> notebook addNote: 'This is a longer note. It goes on forseveral sentences and may print as multiple lines. Long notes makeit difficult to quickly scan a list of notes.'notebook

    In the last example, the string was typed without carriage returns and allowed to wrap around. If a

    carriage return were typed in the middle of this string, the parser would consider the expression

    complete and complain that the string literal is missing its trailing quote mark.

    The contents of the notebook can be displayed at any time:

    Self 13> notebook printNotesThis is a short note.SELF is fun!This is a longer note. It goes on for several sentences and mayprint as multiple lines. Long notes make it difficult to quicklyscan a list of notes.notebook

    The notebook can be improved by having it store structured note objects rather than strings. In par-

    ticular, note objects can be given short titles to be printed when the user wants to quickly scan the

    contents of the notebook. Here are the appropriate object definitions:

  • 7/28/2019 How to Use SELF 2.0

    48/50

    48

    How to Use SELF 2.0 How to Write a Program

    traits applications _AddSlotsIfAbsent: ( | note = () | )traits note _Define: ( |

    parent* = traits clonable.printString = ( '*** ', title, ' ***\n', contents, '\n' ).

    | )

    prototypes applications _AddSlotsIfAbsent: ( | note = () | )note _Define: ( |

    _ parent* = traits note._ thisObjectPrints = true.^ title notebook addTitle: 'Structured Note' Contents: 'this is astructured note'notebook

  • 7/28/2019 How to Use SELF 2.0

    49/50

    49

    How to Use SELF 2.0 How to Write a Program

    Self 15> notebook printNotesThis is a short note.SELF is fun!This is a longer note. It goes on for several sentences and mayprint as multiple lines. Long notes make it difficult to quicklyscan a list of notes.*** Structured Note ***this is a structured note

    notebook

    Self 16> notebook printTitlesNo 'title' slot found in 'This is a short note.'.Sending method holder is notebook .## Stack trace for process ...

    The last expression, which was meant to print a list of note titles, produced an error because the

    notebook still contains some old, unstructured notesthat is, simple strings that do not understand

    the message title. These notes (the first three added to the notebook) can be removed by manipu-

    lating the notebook objects note list directly. The notebook object is first entered to make its

    notes slot visible to expressions typed at the prompt (see section 10.2):

    Self 17> enter: notebookshell

    Self 18> notes removeFirst'This is a short note.'

    Self 19> notes removeFirst'SELF is fun!'

    Self 20> notes removeFirst'This is a longer note. It goes on for several sentences and mayprint as multiple lines. Long notes make it difficult to quicklyscan a list of notes.'

    Now printTitlesworks correctly:

    Self 21> notebook printTitlesStructured Note

    notebook

    Self 22> notebook addTitle: 'Feature: searching' Contents: 'allowthe user to find all notes containing a given substring'notebook

    Self 53> notebook addTitle: 'Feature: deleting' Contents: 'allowthe user to delete a note or a set of notes'notebook

  • 7/28/2019 How to Use SELF 2.0

    50/50

    How to Use SELF 2.0 How to Write a Program

    Self 54> notebook printNotes*** Structured Note ***this is a structured note

    *** Feature: searching ***allow the user to find all notes containing a given substring

    *** Feature: deleting ***allow the user to delete a note or a set of notes

    notebook

    Self 55> notebook printTitlesStructured NoteFeature: searchingFeature: deletingnotebook

    You might want to view the structure of this program graphically. To do so, type:

    Self 56> ui startinitializing ui...creating colormap series . . . . . . . . . done.done.uiX

    Self 57> ui add: notebookuiX

    Self 58> ui add: note copyuiX

    The previous commands start the graphical user interface and make the notebook and a note object

    appear in it. Position the cursor over one of the these objects and press the function key F3. This

    will cause the inheritance hierarchy for the given object to be sprouted and arranged on the screen,

    as described in section 11.

    The last two notes in the notebook suggest some possible ways to extend and improve this pro-

    gram. You will probably think of many more. Happy hacking!