\input texinfo @c -*-texinfo-*-
@c $Id: tutorial.texi,v 1.16 2009/02/26 14:07:37 kiesling Exp $
@c %**start of header  
@setfilename tutorial.info
@settitle Ctalk
@setchapternewpage odd
@paragraphindent 0
@c %**end of header

@set VERSION 0.0.94a

@macro mnm{methodname}
@code{\methodname\}
@end macro

@macro idxclscite{fnname}
(@code{\fnname\} class)
@end macro

@macro flnm{filename}
@code{\filename\}
@end macro

@ifinfo

@dircategory Ctalk
@direntry
* tutorial: (tutorial).	 Object oriented programming tutorial with Ctalk.
@end direntry

This file documents Ctalk version @value{VERSION}.

Copyright @copyright{} 2007-2009,  Robert Kiesling

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts.  A copy of the license is included in the section entitled,
``GNU Free Documentation License.''

@end ifinfo

@iftex
@copying
Ctalk Tutorial Version @value{VERSION}.

Copyright @copyright{} 2007, 2008, Robert Kiesling

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts.  A copy of this license is included in the chapter entitled,
``GNU Free Documentation License.'' 
@xref{GNU Free Documentation License}.
@end copying
@end iftex

@iftex

@titlepage
@title Ctalk Tutorial
@subtitle Object Oriented Programming with Ctalk
@author Robert Kiesling

@page
@vskip 0pt plus 1filll
@insertcopying

@end titlepage

@contents

@end iftex

@ifinfo
@node Top, , (dir), (dir)
@end ifinfo
@ifhtml
@node Top, , Top, 
@end ifhtml

@iftex
@chapter A Brief Introduction to Objects
@end iftex
@ifnottex
@chapheading Ctalk Tutorial
@end ifnottex

@ifinfo
@menu
* Introduction::            Basics of objects, classes, and methods.
* Hello::                   Hello, world! and other simple programs.
* Basic classes::           How to use objects instead of C variables.
* File input and output::   How to open, close, read, and write files.
* Self and super::          Receivers and classes at run time.
* Collections::             Working with groups of objects.
* Classes::                 Defining and initializing class objects.
* Methods::                 Everything you wanted to know about writing methods.
* Debugging::               How to debug Ctalk programs.
* GNU Free Documentation License::    Copying and distributing this manual.
* Index::
@end menu


@node Introduction, Hello, Top, Top
@heading A Brief Introduction to Objects
@end ifinfo

@ifhtml
@menu
* Introduction::            Basics of objects, classes, and methods.
* Hello::                   Hello, world! and other simple programs.
* Basic classes::           How to use objects instead of C variables.
* File input and output::   How to open, close, read, and write files.
* Self and super::          Receivers and classes at run time.
* Collections::             Working with groups of objects.
* Classes::                 Defining and initializing class objects.
* Methods::                 Everything you wanted to know about writing methods.
* Debugging::               How to debug Ctalk programs.
* GNU Free Documentation License::    Copying and distributing this manual.
* Index::
@end menu


@node Introduction, Hello, Top, Top
@heading A Brief Introduction to Objects
@end ifhtml

In object oriented programming, @emph{objects} are the pieces of
information that contain both code and data.  Look at the following
examples.  They implement the same operations in BASIC, C, and Ctalk.
@example
10 let a = 2
20 let b = a + a
30 print b


int a, b;

a = 2;
b = a + a;
printf ("%d\n", b);


Integer new a;
Integer new b;

a = 2;
b = a + a;
stdoutStream writeStream b;

@end example

@cindex Class
The examples look similar, but there is a difference in the object
oriented example.  When a program declares new objects, in this case
@code{a} and @code{b}, Ctalk creates them as members of a
@emph{class}.  In this example, @code{a} and @code{b} are members of
the class @code{Integer}.

If this were as far a object oriented programming went, these
declarations would function exactly the same as their C counterpart,
@code{int a, b;}

@cindex Class hierarchy
@cindex Subclass
@cindex Superclass
However, classes belong to a library of classes, called a @emph{class
hierarchy.}  Class hierarchies contain all of the routines of the
language, and you can create your own classes.  The class hierarchy is
organized so that the most general classes are at the top of the
hierarchy, and proceed to more specialized @emph{subclasses.}  Each
class may have more than one subclass.  Ctalk classes each have one
@emph{superclass,} except for class @code{Object}, the topmost class
in the class hierarchy.  More on class hierarchies in a moment.

@iftex
@section Methods, Messages, and Receivers
@end iftex
@ifnottex
@subheading Methods, Messages, and Receivers
@end ifnottex
@cindex Method
@cindex Message
@cindex Receiver
You can think of a class hierarchy as a library.  Unlike run-time
libraries, however, classes contain both the specification of the
objects and the source code of the routines or functions that operate
with each class.  These routines are called @emph{methods.}

Look at this statement from the example above.
@example
a = 2;
@end example

In this statement, the object @code{a} is called the @emph{receiver}
of the method.  The method is the assignment operator, @code{=}.  The
number @code{2} is the @emph{argument} to the method.  When the
program tells @code{a} to use the method @code{=}, the program sends
the @emph{message} @code{=} to the receiver, @code{a}.

@iftex
@section Polymorphism and Overloading
@end iftex
@ifnottex
@subheading Polymorphism and Overloading
@end ifnottex
Each class can have its own implementation of @code{=}.  The class
@code{String}, for example, can have its own @code{=} method, which
would do exactly what you would expect.
@example
String new myString;

myString = "Hello, world!";
@end example
The next line from the example above,
@example
b = a + a;
@end example
contains two methods, @code{=} and @code{+}.  The receiver of @code{=}
is @code{b}, and the receiver of @code{+} is @code{a}.  The argument
of @code{=} is the complete expression, @code{a + a}.

Programs can do the same with character strings.
@example
String new myString;

myString = "Hello, " + "world!";
@end example

@cindex Polymorphism
@cindex Operator overloading
This is a simple example of a characteristic of computer languages:
@emph{polymorphism.}  That means different types of data have a common
interface and are treated the same by the language.  When the @code{=}
and @code{+} methods work with different classes of objects, we say
that the methods @emph{overload} the operators.

@iftex
@section Class and Instance Data
@end iftex
@ifnottex
@subheading Class and Instance Data
@end ifnottex
In the next line from the example above, 
@example
stdoutStream writeStream b;
@end example
the receiver, @code{stdoutStream}, receives the message @code{writeStream}
with the argument @code{b}.  

@cindex Class variable
@cindex Instance variable
The receiver @code{stdoutStream} is a @emph{class variable.}  There is
one @code{stdoutStream} for its class, @code{WriteFileStream.}
@code{stdoutStream} represents the program's standard output.  The
argument @code{b}, however, is an @emph{instance} of class
@code{String}, and it contains an @emph{instance variable,}
@code{value,} which contains the character string itself.  A
program can create as many @emph{instances of a class} as it needs.

@cindex Instance variable
Each instance of a class contains its own data.  For @code{Integer}
and @code{String} objects, the data is simply the @code{value} of the
object, either @code{2} or @code{Hello, world!}

Class @code{WriteFileStream} objects, however, need to contain more
data, like the permissions of the file stream, the position in the
stream, the type of I/O device, and the memory address of the stream
itself.  This information is contained in @emph{instance variables.}
Each class defines its own set of instance variables, and each
instance of a class has its own copy of them.

@iftex
@section Inheritance
@end iftex
@ifnottex
@subheading Inheritance
@end ifnottex
@cindex Inheritance
@cindex Constructor
@cindex @mnm{new} method @idxclscite{Object}
@cindex @mnm{new} method @idxclscite{WriteFileStream}
The methods that create objects, which are generally called @mnm{new,}
have a special status.  They are called @emph{constructors.}

The following two statements look similar, but they are not.
@example
String new myString;
WriteFileStream new myOutput;
@end example
Recall from the previous sections that the class hierarchy precedes
from the more general objects at the top of the hierarchy, to the more
specific subclasses.  Also, instances of class @code{WriteFileStream}
contain more instance data than many other classes of objects.

What actually occurs in the above statements is that @code{myString}
is created like any other object.  @code{myOutput}, however, uses the
@mnm{new} method of its class, which first creates @code{myOutput}
like any other object and then adds the additional instance variables
that we mentioned above.

So in addition to the @code{value} instance variable, which the method
@mnm{new} obtains from the @code{Object} class, the object
@code{myOutput} also contains the instance variables it needs to
manage writing to a file.  This is called @emph{inheritance.}  We say
that instances of class @code{WriteFileStream} inherit the @code{value}
instance variable from the @code{Object} class.  Instances of class
@code{WriteFileStream} also inherit other instance variables, as
described below.

Here is another example, which shows how classes inherit methods.
Suppose you wanted to create a class that represented positive
integers.  You would accomplish this, most likely, by creating a
subclass of @code{Integer.}
@example
Integer class PositiveInteger;
@end example

Objects of your new class could use the @code{+} method of the
@code{Integer} class.  So you could write:
@example
PositiveInteger new a;
PositiveInteger new b;

a = 2;
b = a + 2;
@end example

Ctalk, if it doesn't find a method for @code{+} in the
@code{PositiveInteger} class, then uses the @code{+} method 
of class @code{Integer}.

If you wanted to subtract two @code{PositiveInteger} objects, however,
you would need to implement the method @code{-} to insure that the
result is also positive.  The code within that method might look
something like the following.
@example
if ((b = (a - a)) < 0)
   warning ("Negative result for PositiveInteger.");
@end example

The later chapters describe the details of creating your own classes
and methods.

@iftex
@section The Class Hierarchy
@end iftex
@ifnottex
@subheading The Class Hierarchy
@end ifnottex
@cindex Superclass
@cindex Class hierarchy
@anchor{Class Hierarchy}
Let's return to the constructor example above.  You should note that
the following statement does not actually @emph{define} its instance
variables.
@example
WriteFileStream new myOutput;
@end example
This is because the instance variables necessary for reading from
files (with class @code{ReadFileStream} objects) and writing to files
(with class @code{WriteFileStream} objects) are similar.  Instead,
Ctalk defines them in a @emph{superclass,} @code{FileStream}.

A section of the class hierarchy, showing the instance variables that
each class defines, should help explain this organization.
@example

Class                  Instance Variables Defined
-----                  --------------------------
Object                 <------  value
 Stream
  FileStream           <------  streamMode
                       <------  streamDev
                       <------  streamRdev
                       <------  streamSize
                       <------  streamAtime
                       <------  streamMtime
                       <------  streamCtime
                       <------  streamPos
                       <------  streamErrno
                       <------  streamPath
   ReadFileStream
   WriteFileStream
@end example

When constructed, instances of @code{ReadFileStream} and
@code{WriteFileStream} each have their own copies of the same set of
instance variables.

The @cite{Ctalk Reference Manual} describes the Ctalk class hierarchy,
and the methods and variables, that each class defines.

Ctalk's language syntax and class library organization are based very
closely on the Smalltalk, one of the earliest truly object oriented
languages. In addition, Ctalk contains additional features that allow
programs to use C variables and functions.  You can find much
information about Smalltalk and its design in on-line and printed
documents.

If you want to read further about C and object oriented programming
languages in general, there are many books and tutorials, also on line
and in print, that describe these subjects in detail.

@node Hello, Basic classes, Introduction, Top
@iftex
@chapter @code{Hello, world!} and Other Simple Programs
@end iftex
@ifnottex
@heading @code{Hello, world!} and Other Simple Programs
@end ifnottex

Ctalk assumes that you are familiar with the C language, and that you
have an understanding of basic object oriented programming concepts,
which we described in the previous chapter.

This chapter presents a few simple programs that demonstrate how the 
Ctalk language works.  Later chapters will describe the more advanced
features of the language in greater detail.

@cindex @code{hello} example program
@subheading Printing @code{"Hello, world!"}

To learn how to write and compile a Ctalk application, this chapter 
starts with the obligatory @code{Hello, world!} program.

Here is the @code{Hello, world!} program listing.

@example
int main () @{

  String new helloObject;

  helloObject = "\"Hello, world!\"";

  printf ("%s\n", helloObject value);

  exit (0);
@}
@end example

@cindex @code{ctcc} command
Save this listing in a file called @flnm{hello.c,} and then build it
with the @code{ctcc} command.
@example
$ ctcc hello.c -o hello
@end example

Then, you can run the program with this command, and the program
will print the output.
@example
$ ./hello
"Hello, world!"
@end example

@subheading Printing Parts of a String
@cindex @code{ctpath} example program
@anchor{ctpath.c}
Here is another simple program, @flnm{ctpath.c.}  You can find the
source file in the @flnm{programs} subdirectory of the Ctalk source
code distribution.  

This program prints the directory path that you supply as an argument,
one directory to a line.
@example
int main (int argc, char **argv) @{

  String new path;
  Array new paths;
  Integer new nItems;
  Integer new i;
  Character new separator;

  if (argc != 2) @{
    printf ("Usage: ctpath <path>\n");
    exit (1);
  @}

  path = argv[1];

  separator = '/';

  nItems = path split separator, paths;

  for (i = 0; i < nItems; i = i + 1)
    printf ("%s\n", paths at i);

  exit (0);
@}
@end example

Although there is a lot of code for initializing variables and
checking the command line arguments, @code{ctpath} does the actual
work in three lines of code.
@example
nItems = path split separator, paths;

for (i = 0; i < nItems; i = i + 1)
  printf ("%s\n", paths at i);
@end example

@cindex @code{split} method @idxclscite{String}
@cindex @code{at} method @idxclscite{Array}
The method split (class @code{String}) splits the string
@code{path} at each occurrence of @code{separator} and places the
result in the array, @code{paths.}  The next two lines print each
element of the array @code{paths} with the statement, @code{paths at
i.} 

@cindex @code{ctcc} command
As with the previous example, you can compile the program using the
following commands.
@example
$ ctcc ctpath.c -o ctpath
@end example

When you run the program, the output should look like this, depending
on the directory path you provide on the command line.
@example
$ ./ctpath /home/users/joe
home
users
joe
@end example
@cindex @code{argc} C variable
@cindex @code{argv} C variable
If you're not certain of how the arguments to @code{main,} @code{argc}
and @code{argv,} function (they contain the command line, split into
individual strings, and the number of command line strings), then you
should go back and study the C language until you are comfortable with
the language.

@subheading Printing the Time

Here is a program that uses a method to get the local time and store
it in an array.

@cindex @cite{localtime(3)} C function
@cindex @mnm{localTime} method @idxclscite{Time}
@example
#include <time.h>

Array instanceMethod getTime (void) @{

  Time new timeNow;
  Array new currentLocalTime;

  timeNow utcTime;

  currentLocalTime = timeNow localTime;

  self atPut 0, (currentLocalTime at 2);
  self atPut 1, (currentLocalTime at 1);
  self atPut 2, (currentLocalTime at 0);

  return NULL;
@}

int main () @{

  Array new clockTime;

  clockTime getTime;

  printf ("%02d:%02d:%02d\n", (clockTime at 0), (clockTime at 1), (clockTime at 2));
@}
@end example

In the method @code{getTime,} @code{self} refers to the method's
receiver, @code{clockTime,} which is declared in @code{main.}

The @code{localTime} method (@code{Time} class), returns an
@code{Array} that is filled in by the C library's call to
@cite{localtime(3).}  The @cite{Ctalk Language Reference} describes
how @code{localTime} returns time and date information.

Note that in @code{main,} the arguments to @code{printf} are enclosed
in parentheses, so there is no ambiguity in evaluating the expressions
in each argument.




@node Basic classes, File input and output, Hello, Top
@iftex
@chapter Basic Classes and Ctalk Statements
@end iftex
@ifnottex
@heading Basic Classes and Ctalk Statements
@end ifnottex

Ctalk is designed to work with C.  There are a number of classes
that correspond directly to the basic C data types.

In Ctalk, you can use instances of the classes that are shown in the
table below interchangeably with their C equivalents.
@cindex @code{Array} class
@cindex @code{Character} class
@cindex @code{Float} class
@cindex @code{Integer} class
@cindex @code{LongInteger} class
@cindex @code{String} class
@cindex @code{char} C data type
@cindex @code{double} C data type
@cindex @code{float} C data type
@cindex @code{long int} C data type
@cindex @code{long long int} C data type
@example
Ctalk Class         C Type
-----------         ------
Array               char **, int **, ...
Character           char
Float               float, double
Integer             int, long int
LongInteger         long long int
String              char *
@end example

@subheading Creating and Working with Simple Objects

@cindex Constructors
@cindex @mnm{new} method @idxclscite{Object}
Like most object oriented languages, when you declare an object, you
are actually creating it.  As mentioned earlier, the methods that
create objects are called @emph{constructors.}  As with most object
oriented languages, you create an object with the message @code{new.}
@example
Integer new myInt;
@end example

Objects of class @code{Integer} work exactly the same as C variables
of type @code{int.}  You can use expressions like the following, as
though you were programming in C.
@example
Integer new myInt;

myInt = 2;
printf ("%d\n", myInt + myInt);
@end example
@cindex @code{invert} method @idxclscite{Integer}
@cindex @code{bitComp} method @idxclscite{Integer}
With several exceptions, you can use all of the operators that C
integers recognize.  Postfix operators, like @code{+,} @code{-,}
@code{*,} @code{/,} and so on, also work as methods.  

However, prefix operators, like unary @code{!} and @code{~,} do not
work.  Instead, Ctalk provides equivalent methods for them,
@code{invert} and @code{bitComp.}

This example shows how you would use the methods in C statements.
@example
int i;               /* C variable.   */
Integer new myInt;   /* Ctalk Object. */

i = 2;
myInt = 2;

/* These two statements are equivalent. */
printf ("%d\n", !i);
printf ("%d\n", myInt invert);

/* These two statements are also equivalent. */
printf ("%d\n", ~i);
printf ("%d\n", myInt bitComp);
@end example

The same is also true for instances of the @code{Character,}
@code{LongInteger,} and @code{Float} classes.

@cindex @mnm{+} @idxclscite{Character}
@cindex @mnm{toLower} @idxclscite{Character}
For instance, you can add and subtract two characters.  This is
sometimes useful for conversions, as in the following examples.
@example
Character new receiver;
Character new operand;

receiver = 'A';
operand = ' ';

printf ("%c\n", receiver + operand); 
@end example
The result is the lower case @samp{a}.  This has the same effect as:
@example
Character new receiver;
receiver = 'A';
printf ("%c\n", receiver toLower);
@end example
Or even:
@example
printf ("%c\n", 'A' toLower);
@end example

@cindex @mnm{-} @idxclscite{Character}
@cindex @mnm{toUpper} @idxclscite{Character}
To convert a character to uppercase, you can use either @mnm{-} or
@mnm{toUpper.}  Both are implemented by the @code{Character} class.
@example
Character new receiver;
Character new operand;

receiver = 'a';
operand = ' ';

/* These two statements produce the same result. */
printf ("%c\n", receiver - operand);
printf ("%c\n", receiver toUpper);
@end example

@cindex @mnm{&} method @idxclscite{Character}
@cindex @mnm{|} method @idxclscite{Character}
@cindex @mnm{^} method @idxclscite{Character}
For completeness, we should note that you can also achieve the same
effect with the bit operators @mnm{&}, @mnm{|}, and @mnm{^,} although
their application can be a bit more involved.  If you're not certain how 
the operators would work, enter the ASCII value of a character in a
programmer's calculator and convert it to base 2.  Then notice the
effect of changing different bits.

For now, we'll just show an example of changing a letter's case - 
from lower to upper case, or vice versa.  

We do this by XOR'ing the fifth bit of the character value.  (Note
that @code{2^5} is @code{32,} the ASCII value of a space (@samp{ })
character.)  

Here is a simple example of the operation.
@example
Character new upperCase;
Character new lowerCase;
Integer new toggleBit;  

upperCase = 'Z';
lowerCase = 'z';
toggleBit = 32;
  

printf ("%c\n", upperCase ^ toggleBit);
printf ("%c\n", lowerCase ^ toggleBit);
@end example

@subheading Variable Promotion and Type Conversion
@cindex Variable promotion
@cindex Type conversion
You should also note that, because objects are much more complex than
C data types, variable promotion and type conversion become much more
complex operations in object oriented languages than in C.  This will
become apparent later on.

@cindex @code{Magnitude} class
For now, because we're discussing basic object classes, it should be
sufficient to look at the methods of class @code{Magnitude,} which is
the superclass of these basic classes.

@cindex @mnm{asCharacter} method @idxclscite{Magnitude}
@cindex @mnm{asInteger} method @idxclscite{Magnitude}
@cindex @mnm{asLongInteger} method @idxclscite{Magnitude}
You need to use the @code{Magnitude} methods @mnm{asCharacter,}
@code{asInteger,} and @code{asLongInteger} to perform type conversions
explicitly.  

This manual shows how to perform type conversion when necessary in the
programming examples. The @cite{Ctalk Language Reference} describes
the type conversion methods for each class.


@subheading Default Methods and Instance Variable Messages

@cindex Default method
@cindex @code{value} method @idxclscite{Object}
There is one other point to note about methods and messages.  Ctalk
objects also respond to messages that name instance variables.

All Ctalk objects contain the instance variable, @code{value,} which
is inherited from class @code{Object.}  Because of this, if you use an
object without a message, Ctalk uses the @code{value} message by
default.  

The following two statements are equivalent.
@example
printf ("%d\n", myInt);

printf ("%d\n", myInt value);
@end example

@subheading @code{String} Class
@cindex @code{String} class

As the introduction mentioned, Ctalk overloads many operators.  This
is especially obvious of class @code{String.}

This code shows how @code{String} class overloads some math operators.
@cindex @mnm{=} method @idxclscite{String}
@cindex @mnm{==} method @idxclscite{String}
@cindex @mnm{+} method @idxclscite{String}
@cindex @cite{strcpy(3)} C function
@cindex @cite{strcat(3)} C function
@cindex @cite{strcmp(3)} C function
@example
String new s1;
String new s2;
String new helloString;

/* C's strcpy () would also work here. */
s1 = "Hello, ";
s2 = "world!";

/* And strcat () could perform the same task here. */
helloString = s1 + s2;

s1 = "s1";
s2 = "s2";

/* This is functionally equivalent to strcmp (). */
if (s1 == s2) @{
   printf ("s1 and s2 are equal.\n");
@} else @{
   printf ("s1 and s2 are NOT equal.\n");
@}
@end example
Briefly, the @code{String} instance methods @mnm{=,} @mnm{==,} and
@mnm{+} function similarly to the C
library functions @cite{strcpy(3),} @cite{strcmp(3),} and
@cite{strcat(3),} respectively, although they are not identical.

@cindex @mnm{asString} method @idxclscite{Magnitude}
Like C, however, instances of @code{String} and @code{Character} are
not interchangeable.  If you want to use an instance of class
@code{Character} as a string, you must use the method @code{asString}
(class @code{Magnitude}) to return a @code{String} version of the
@code{Character} object.

Here is a brief example.  The two @code{printf} statements produce 
the same output.
@example
Character new myChar;

myChar = 'a';

printf ("%c\n", myChar);
printf ("%s\n", myChar asString);
@end example

@cindex @mnm{split} method @idxclscite{String}
@code{String} class implements several convenience methods.  The
@mnm{split} method, which we described in the previous chapter, splits
a string along a separator character and puts each substring token in
an array.

Here is the statement from the example in the previous chapter. 
@xref{ctpath.c}.
@example
nItems = path split separator, paths;
@end example
If the receiver, @code{path,} contains a string like
@samp{/home/users/joe}, and separator, a @code{Character} contains
@samp{/}, then @mnm{split} places the individual names in the 
@code{Array,} @code{paths.}  

The operation looks something like this.
@example
path    --->       "/home/users/joe"
                     /     |     \
                    /      |      \
split              /       |       \
                  v        v        v
              --------------------------------
paths   ---> |paths at 0|paths at 1|paths at 2|
             | "home"   | "users"  | "joe"    |
              --------------------------------
@end example
The expression, @code{paths at 0,} is equivalent to the @code{paths[0]}
element of a C array, and so on, for the other elements of the array.

@cindex @mnm{subString} method @idxclscite{String}
Another convenience method, @code{subString,} returns the part of the
receiver string beginning at the first argument.  The second argument
is the length of the substring. Here is an example.
@example
myString = "This is a string.";
mySubString = myString subString 5, 2;
@end example

@subheading @code{Array} Class
@cindex @code{Array} class
@anchor{Array}

An @code{Array} in Ctalk is similar to arrays in every other
programming language.  Ctalk arrays are collections of objects,
indexed sequentially from index @code{0} to the last element in the
Array. 

@cindex @mnm{atPut} method @idxclscite{Array}
To add an element to an @code{Array} object, use the method
@code{atPut.} 
@example
Array new myArray;
String new myString;

myString = "Hello, world!";

myArray atPut 0, myString;
@end example

The @mnm{atPut} method has two arguments, the index of the array
element, and the object you want to store there.

@cindex @mnm{at} method @idxclscite{Array}
To retrieve an @code{Array} element, use the method @code{at.}  The
@mnm{at} method takes one argument, the index of the array element.

Using the previous example, this statement retrieves the first element
of @code{myArray} and prints it.
@example
printf ("%s\n", myArray at 0);
@end example

You do not have to predeclare an array to a specific size.
Objects of @code{Array} class can hold as many objects as necessary.

@cindex @mnm{size} method @idxclscite{Array}
If you want to know how many elements an @code{Array} object contains,
use the method @code{size,} which returns the number of elements as an
@code{Integer} object.
@example
printf ("myArray has %d elements.\n", myArray size);
@end example

If you add an object to an array at an index that already contains an
object, @code{atPut} replaces the array element with the new object.
@example
Array new myArray;

myArray atPut 0, "My";
myArray atPut 1, "name";
myArray atPut 2, "is";
myArray atPut 3, "Bill";

printf ("%s %s %s %s.\n", (myArray at 0), (myArray at 1), 
                          (myArray at 2), (myArray at 3));

myArray atPut 3, "Joe";

printf ("%s %s %s %s.\n", (myArray at 0), (myArray at 1), 
                          (myArray at 2), (myArray at 3));
@end example

Note that we enclosed the @code{printf} arguments in parentheses, so
there is no ambiguity about where one expression ends and another
begins.

@cindex @mnm{map} @idxclscite{Array}
Generally, however, if you simply want to repeat an operation on 
all members of an array, you can use the method @code{map.}

The @code{map} method takes the name of another method as its
argument, and calls the method with each element of the array as its 
receiver.

Here is a more complete implementation of the example above, written
using @code{map.}
@example
Array instanceMethod printArrayElement (void) @{

  printf ("%s ", __ctalk_to_c_char_ptr (__ctalk_self_internal ()));      

  return NULL;
@}

int main () @{

  Array new myArray;

  myArray atPut 0, "My";
  myArray atPut 1, "name";
  myArray atPut 2, "is";
  myArray atPut 3, "Bill";

  myArray map printArrayElement;

  printf ("\n");

  myArray atPut 3, "Joe";

  myArray map printArrayElement;

  printf ("\n");
@}

@end example

In the @code{printArrayElement} method, @code{self} refers to each
successive element of @code{myArray} from @code{main,} which are
instances of class @code{String.}

You should note that not all classes of @code{Array} elements work in
C expressions.  If you try to use array elements of the classes
@code{Float} and @code{LongInteger} in C expressions, for example,
Ctalk prints a warning at run time.

If a program uses @code{Array} objects of these classes with C
expressions, then it must perform its own type conversions.  The
@cite{Ctalk Language Reference} discusses this issue in further
detail.

You should also note that, in @code{printArrayElement,} it is
necessary to use the library accessor functions for @code{self.}
Unless you create and initialize objects within the method, Ctalk
doesn't know the value of @code{self} until run time.

There are simpler, object oriented methods to output @code{Array}
elements.  The next chapter describes a few of them.

@subheading Compound Statements
@cindex Compound statements

The result of evaluating one message can be the receiver of another
message, as in the following example.

@example
int main () @{

  ReadFileStream new infileStream;
  Array new pathDirs;
  Integer new nDirs;

  /* Substitute the path of the file here. */
  infileStream openOn "/path/to/file";

  nDirs = infileStream streamPath split '/', pathDirs;

  printf ("%i\n", nDirs);
  printf ("%s\n", pathDirs at 0);
  printf ("%s\n", pathDirs at 1);
  printf ("%s\n", pathDirs at 2);
@}
@end example

The receiver of the method @code{split,} in the statement
@example
nDirs = infileStream streamPath split '/', pathDirs;
@end example
is the result of sending the message @code{streamPath} to
@code{infileStream.} The result is the path name of
@code{infileStream,} a @code{String.}

The result of one message must be a member of the same class as the
receiver of the next message, or a member of a subclass if the message
refers to a method.

The @cite{Ctalk Language Reference} describes the class and instance
variables of each class, and the return classes of methods.

@node File input and output, Self and super, Basic classes, Top
@iftex
@chapter File Input and Output
@end iftex
@ifnottex
@heading Input and Output
@end ifnottex

This chapter describes how Ctalk performs basic file operations -
opening, closing, reading, and writing files.

@cindex @code{FileStream} class
@cindex @code{ReadFileStream} class
@cindex @code{WriteFileStream} class
@cindex @code{DirectoryStream} class
There are three classes that provide file input and output:
@code{ReadFileStream,} which implements objects and methods for
reading from files, @code{WriteFileStream,} which provides methods and
objects for writing to files, and their superclass, @code{FileStream,}
which provides methods and class definitions that are common to both
reading and writing files.  There is also a @code{DirectoryStream}
class, which this chapter describes below.

Ctalk provides many of the same facilities that C's @code{stdio.h}
library functions provide, although the language implements them as
objects.  

@cindex @mnm{openOn} method @idxclscite{ReadFileStream}
Here is an example that shows how to use the @mnm{openOn} method
(class @code{ReadFileStream}).
@example
ReadFileStream new myInput;

myInput openOn "myFileName";
@end example

If the progam was able to to open the file, you can then read input
from the @code{myInput} stream.

We should note here that Ctalk also provides classes and methods that
handle file I/O errors.  We will deal with them later on.  If you
need to see how to catch file I/O errors right now, look at some of
the example programs in the Ctalk package, especially @flnm{ctwc.c.}

Opening a file for output is similar to opening a file for input,
except that the stream is an instance of class @code{WriteFileStream.}
@example
WriteFileStream new myOutput;

myOutput openOn "outputFileName";
@end example

@cindex @mnm{readChar} method @idxclscite{ReadFileStream}
@cindex @mnm{readLine} method @idxclscite{ReadFileStream}
@cindex @mnm{readAll} method @idxclscite{ReadFileStream}
@cindex @mnm{writeChar} method @idxclscite{WriteFileStream}
@cindex @mnm{writeStream} method @idxclscite{WriteFileStream}
After a program has opened the file streams successfully, you can read
and write from them with the following methods.
@example
Operation                           Reading    Writing
---------                           -------    -------
Read or write one character.        readChar   writeChar
Read or write one line.             readLine   -
Read or write all the data.         readAll    writeStream
@end example

Here is a simple example that shows opening a file, and reading each
character.
@example
ReadFileStream new inputChars;
Character new c;

inputChars openOn "inputFileName";

while ((c = inputChars readChar) != EOF) 
  printf ("%c", c);
@end example

When @mnm{readChar} reaches the end of a file, it returns an
@code{EOF} character, which is @samp{-1} on most systems.

@cindex @mnm{streamEof} method @idxclscite{FileStream}
Using the method @code{streamEof} (class @code{FileStream}) to check for the
end of the input is slightly more reliable than looking for an
@code{EOF} character, because it distinguishes the end of the input
caused by an error from the end of the input caused by reaching the
end of a file.
@example
ReadFileStream new inputChars;
Character new c;

inputChars openOn "inputFileName";

while (TRUE) @{             /* Loop until the end of the input. */
  c = inputChars readChar;
  if (inputChars streamEof)
    break;
@}
@end example

@cindex @mnm{readAll} method @idxclscite{ReadFileStream}
If you don't need to examine each character as it is read, however,
then you can simply use @mnm{readAll} (class @code{ReadFileStream}),
which provides the complete input as a @code{String} object.
@example
ReadFileStream new inputStream;
String new inputString;

inputStream openOn "myInput";
inputString = inputStream readAll;
printf ("%s", inputString);
@end example

@cindex @mnm{readLine} method @idxclscite{ReadFileStream}
@cindex @mnm{writeStream} method @idxclscite{WriteFileStream}
Simple applications can use the methods @mnm{readLine} (class
@code{ReadFileStream}) and @mnm{writeStream} (class @code{WriteFileStream})
together to process input.

Here is a portion of the program @flnm{ctrep.c,} which you can find in
the Ctalk package.  It checks the input for occurrences of a character
string, and replaces the string before writing the output.
@example
/*
 *  Loop until the end of input.
 */
while (TRUE) @{
  line = stdinStream readLine;
  if (stdinStream streamEof)
    break;
  inputLineLength = line length;

  word = "";

  for (i = 0; i < inputLineLength; i = i + 1) @{
    inputChar = line at i;
    if (inputChar isSpace) @{
    if (word == pattern) @{
      stdoutStream writeStream replacement;
    @} else @{
      stdoutStream writeStream word;
    @}
      stdoutStream writeStream inputChar;
      word = "";
    @} else @{
      word = word + inputChar asString;
    @}
  @}
@}
@end example

@subheading Standard Input and Standard Output
@cindex @code{stdinStream} class variable @idxclscite{ReadFileStream}
@cindex @code{stdoutStream} class variable @idxclscite{WriteFileStream}

Notice that the previous example used @code{stdinStream} and
@code{stdoutStream} as its input and output streams.  

These two objects are class variables of @code{ReadFileStream} and
@code{WriteFileStream,} respectively.  They represent the program's
standard input (@code{stdin}) and standard output (@code{stdout}) file
streams.

Because @code{ctrep.c} is a filter program, it uses these two streams
instead of streams that work with normal files.

@cindex @code{stderrStream} class variable @idxclscite{WriteFileStream}
Class @code{WriteFileStream} also implements the @code{stderrStream}
class variable, which represents the application's standard error
(@code{stderr}) stream.

@cindex @cite{printf(3)} C function.
You should notice, also, that all of the examples so far have used
@code{printf} to print output.  You can accomplish the same task with
the following Ctalk statement.
@example
stdoutStream writeStream "Hello, world!\n";
@end example

This is equivalent to:
@example
printf ("Hello, world!\n");
@end example

Ctalk initializes @code{stdinStream} automatically when the program
creates the first @code{ReadFileStream} object, and it initializes
@code{stdoutStream} and @code{stderrStream} when the program creates 
the first @code{WriteFileStream} object.

@cindex @mnm{classInit} method @idxclscite{ReadFileStream}
@cindex @mnm{classInit} method @idxclscite{WriteFileStream}
If the program simply needs to use @code{stdinStream,}
@code{stdoutStream,} or @code{stderrStream} without opening files,
then it can call the class method @code{classInit} with either the
class @code{ReadFileStream} or @code{WriteFileStream} as the receiver.
@example
ReadFileStream classInit;    /* Initialize stdinStream. */
WriteFileStream classInit;   /* Initialize stdoutStream and stderrStream. */
@end example

Here is the example from the previous chapter that printed elements of
arrays.  This version uses @code{stdoutStream} to output the array
elements.
@example
Array instanceMethod printArrayElement (void) @{

  WriteFileStream classInit;

  stdoutStream writeStream self;

  return NULL;
@}

int main () @{

  Array new myArray;

  myArray atPut 0, "My";
  myArray atPut 1, "name";
  myArray atPut 2, "is";
  myArray atPut 3, "Bill";

  myArray map printArrayElement;

  printf ("\n");

  myArray atPut 3, "Joe";

  myArray map printArrayElement;

  printf ("\n");
@}
@end example

The @code{printArrayElement} method initializes class
@code{WriteFileStream.}  You need to perform the class initialization 
before the class is first used in the program.  There is no problem
with calling @code{classInit} multiple times, however, because the
method checks to determine if the class is already initialized.

@subheading Directories

@cindex @code{DirectoryStream} class
@cindex Directories

@cindex @mnm{mkDir} method @idxclscite{DirectoryStream}
@cindex @mnm{rmDir} method @idxclscite{DirectoryStream}
The class @code{DirectoryStream} provides the methods @mnm{mkDir} and
@mnm{rmDir} which create and delete directories.  The methods function
exactly as their C library counterparts, except that they raise a
@code{SystemErrnoException} on error and return an @code{Integer} with
the value @code{-1}.  

@cindex @code{CTALK_DIRECTORY_MODE} macro
Ctalk uses @code{0755} (@samp{drwxr-xr-x}) as the default mode for new
directories.  Programs can change that value by redefining the macro 
@code{CTALK_DIRECTORY_MODE}.

Here is a program that creates a new directory.
@example
/* 
 * Define more restrictive permissions for 
 * new directories. Undefine the macro first
 * to avoid a warning message.
 */
#undef CTALK_DIRECTORY_MODE
#define CTALK_DIRECTORY_MODE 0700

int main () @{

  DirectoryStream new thisDir;

  thisDir mkDir "testDir";

@}
@end example

The method @mnm{rmDir} works similarly to @mnm{mkDir}.
@example
int main () @{

  DirectoryStream new thisDir;

  thisDir rmDir "testDir";

@}
@end example

@subheading Standard Input and Standard Output Implementations
@cindex @code{stdin}
@cindex @code{stdout}
@cindex @code{stderr}
@cindex @code{stdinStream} @idxclscite{ReadFileStream}
@cindex @code{stdoutStream} @idxclscite{WriteFileStream}
@cindex @code{stderrStream} @idxclscite{WriteFileStream}
The C99 standard requires that @code{stdin,} @code{stdout,}
and @code{stderr} should be implemented as macros, which on
some systems (notably Solaris) causes problems with
C-to-object translation.  

If Ctalk cannot register the macros as C variables, then you
must call C functions like @cite{sscanf(3)} and
@cite{fscanf(3)} with only C variables, or use a method
with @code{stdoutStream} or @code{stderrStream}
(@code{WriteFileStream} class), or @code{stdinStream}
(@code{ReadFileStream} class).


@node Self and super, Collections, File input and output, Top
@iftex
@chapter @code{self} and @code{super}
@end iftex
@ifnottex
@heading @code{self} and @code{super}
@end ifnottex
@cindex @code{self}
@cindex @code{super}

The @code{self} and @code{super} keywords refer to receivers and
superclass methods at run time.  They allow you to write methods
without knowing beforehand what objects called them.

@iftex
@section @code{self} as a Receiver
@end iftex
@ifnottex
@subheading @code{self} as a Receiver
@end ifnottex

Within a method, @code{self} refers to the receiver of the method that
@code{self} appears in.  Within the method, you can use self
interchangeably with other receivers.

When used as a receiver, Ctalk's @code{self} works much like
the @code{self} keyword in Smalltalk and the @code{this} keyword in C++.

In this example, @code{self} in the method @code{add2} refers to
the method's receiver, @code{myInt,} which is declared in @code{main.}
@example
Integer instanceMethod add2 (Integer arg) @{

  methodReturnInteger(self + 2)          

@}

int main () @{

  Integer new myInt;
  Integer new myTotal;

  myInt = 2;

  myTotal = myInt add2;

@}
@end example

@iftex
@section The @code{super} Keyword
@end iftex
@ifnottex
@subheading The @code{super} Keyword
@end ifnottex
@cindex @code{super} keyword

When used before a message, @code{super} tells Ctalk that the
message refers to a method in the superclass of the receiver.  

The most common use of @code{super} is in constructors of subclass
objects.  The keyword allows constructor methods, which are almost
always called @code{new,} to refer to the constructor of a superclass,
which allows subclass objects to inherit the instance variables of its
superclasses.  

The example in the first chapter, of how @code{FileStream} and its
subclasses inherit instance variables, describes how constructors can
call class constructors.  @xref{Class Hierarchy}.

To show how @code{super} is used, here is the @code{new} method from
class @code{WriteFileStream}.
@cindex @mnm{new} method @idxclscite{WriteFileStream}
@example
WriteFileStream instanceMethod new (char *name) @{

  WriteFileStream super new name;

  __ctalkInstanceVarsFromClassObject (name);

  WriteFileStream classInit;
  
  methodReturnObject(name)
@}
@end example

@iftex
@section Determining the Class of @code{self}
@end iftex
@ifnottex
@subheading Determining the Class of  @code{self}
@end ifnottex
@cindex @code{self}, class of

Generally, the receiver object that @code{self} refers to belongs to
the same class as the method where it appears.  But there are many
occasions when a method cannot assume that it knows in advance the
class of @code{self}, or the result of an expression that contains
@code{self}.  This section describes a few of these situations and how
to deal with them.

A method might be declared in a superclass of the receiver, or the
method might need to work objects that are members of a collection, as
in this example.  A method might belong to the class of a collection like
@code{List} or @code{AssociativeArray}, but the collection's elements
may be another class entirely.

In these cases, methods need to account for the fact that the receiver
object is actually an instance of @code{Key} class, which is the
actual class of the collection's instance variables, and that
@code{Key} class contains references to the collection's member objects.

This method is from the @flnm{ctcheckquery.c} example program, the
parameters and values of a CGI query.  

This method is relatively simple because it can assume beforehand that
the values it is going to print are instances of @code{String} class.
The actual receiver is an instance of @code{Key} class, so @code{self}
in this method understands both the @mnm{name} and @mnm{getValue}
methods, which are defined in @code{Key} class. 
@example
AssociativeArray instanceMethod printQueryParamPair (void) @{
  printf ("<tt>%s=", self name);
  printf ("\"%s\"</tt><br>\n", self getValue);
  methodReturnNULL
@}
@end example

Here is a much more involved example, the @mnm{asInteger} method from
class @code{Magnitude.}  

Generally, only the @code{Object} class is completely evaluated before
this method, so @mnm{asInteger} needs to perform many of its
operations in C.  However, it can use the method @mnm{is} from
@code{Object} class to determine the class of the receiver.
@example
Magnitude instanceMethod asInteger (void) @{
  OBJECT *self_value;
  int i;
  long long int l;

  returnObjectClass Integer;

  self_value = self value;

  if (self is Integer) @{
    methodReturnSelf;
  @} else @{
    if (self is LongInteger) @{
      sscanf (self_value -> __o_value, "%lld", &l);
      if (l > MAX_UINT)
	_warning ("Overflow in type conversion.\n");
      i = (int)l;
    @}
    /*
     *  Character to int conversion, plus escape sequences.
     */
    if (self is Character) @{
      if (*self_value -> __o_value == '\'') @{
	if (self_value -> __o_value[1] == '\\') @{
	  switch (self_value -> __o_value[2])
	    @{
	    case 'a':
	      i = 1;
	      break;
	    case 'b':
	      i = 2;
	      break;
	    case 'f':
	      i = 6;
	      break;
	    case 'n':
	      i = 10;
	      break;
	    case 'r':
	      i = 13;
	      break;
	    case 't':
	      i = 9;
	      break;
	    case 'v':
	      i = 11;
	      break;
	    case '0':
	      i = 0;
	      break;
	    default:
 	      i = (int) self_value -> __o_value[2];
	      break;
	    @}
	@} else @{
 	  i = (int) self_value -> __o_value[1];
	@}
      @} else @{
 	i = (int) *self_value -> __o_value;
      @}
    @}  /* if (self is Character) @{ */

    if (self is Float) @{
      /*
       *  In case Exception class isn't loaded yet, simply
       *  print a warning.
       */
      _warning ("asInteger (class Magnitude): Receiver truncated to Integer.\n");
      i = (int)atof (self);
    @}
  @}
  methodReturnInteger (i);
@}
@end example

@iftex
@section Determining the Class of Method Arguments
@end iftex
@ifnottex
@subheading Determining the Class of Method Arguments
@end ifnottex
@cindex Arguments, class of

While we're on the subject, we should mention that methods do not
always know the class of their arguments, either.  If the class of a
method argument can vary, that makes it even more difficult to handle
complex objects that contain numerous instance variables.

One way to deal with arguments of different classes is to duplicate
the argument into the class the method needs, as in this example, 
the @mnm{=} method from @code{Integer} class.
@example
Integer instanceMethod = set_value (int __i) @{ 
  Integer new localInt;
  localInt become __i asInteger;
  __ctalkAddInstanceVariable (self, "value", localInt value);
  methodReturnSelf
@}
@end example

Remember, a method can specify the class or type of an argument, but
that doesn't mean, when the program runs, that the argument actually
@emph{is} the class that the method expects.

Another issue is trying to print objects.  If you were to write a
method like the following.
@example
MyClass instanceMethod myMethod (Object myArg) @{
   printf ("%s\n", myArg myInstanceVariable);
   methodReturnNULL;
@}
@end example
Then you would need to make sure that myInstanceVariable is a
@code{String}.  If possible, Ctalk tries to match the class of an
expression with its context; in the example above, if Ctalk cannot
determine the class of @code{myInstanceVariable} from the context of
the method, it will try to translate it into a @code{char *} argument
for @code{printf}.

There are a few ways that a method can determine the class of an
expression.  One is to use the @code{Object} method @mnm{is}, as in
the @mnm{asInteger} method in the previous section.

Another solution is to ``cast'' the argument to a local object using,
for example, the @code{Object} method @mnm{become}, as in the @mnm{=}
(class @code{Integer}) example above.

Yet another way to deal with an unknown argument class is to use a
@mnm{printOn} method.  The method is better than @code{printf} at
determining an object's class at run time.
@example
MyClass instanceMethod myMethod (Object myArg) @{
   WriteFileStream classInit;        
   stdoutStream printOn "%s\n", myArg myInstanceVariable;
   methodReturnNULL;
@}
@end example

Many classes implement a @mnm{printOn} method, and it is relatively
easy for a class that you write to define a @mnm{printOn} method also.
The Ctalk libraries take care of much of the work of translating
objects of different classes and formatting them correctly.  

The @mnm{printOn} methods can also use receivers other than stream
classes, so a method could use printOn to format a String, as in this
example. 
@example
String instanceMethod myIntConv (int myArg) @{
   self printOn "%s\n", myArg myIntVariable;
   methodReturnSelf;
@}
@end example

@node Collections, Classes, Self and super, Top
@iftex
@chapter Collections
@end iftex
@ifnottex
@heading Collections
@end ifnottex

Collections are groups of objects.  Ctalk has the following main
classes of collections.
@cindex @code{Array} Class
@cindex @code{AssociativeArray} Class
@cindex @code{List} Class
@cindex @code{Stream} Class
@itemize
@item
@code{Array} class, which orders elements of a group by a numerical
index. 
@item
@code{AssociativeArray} class, which orders and retrieves elements 
using a key value.
@item
@code{List} class objects, which contain groups of objects that you
can treat sequentially. 
@item
@code{Stream} class objects, which are generally groups of characters
similar to @code{String} class objects, that allow reading and writing 
to the collection.
@end itemize

@cindex @code{Collection} Class
@cindex @code{FileStream} Class
@cindex @code{ReadFileStream} Class
@cindex @code{WriteFileStream} Class
These classes are subclasses of @code{Collection} class.  Here is the
section of the class library that shows the organization of 
@code{Collection} and its subclasses.
@example
 Collection
  Array
  List
   AssociativeArray
  Stream
   FileStream
    ReadFileStream
    WriteFileStream
@end example
The previous
chapters described @code{Array} and @code{Stream} objects (the classes
@code{FileStream,} @code{ReadFileStream,} and
@code{WriteFileStream}), so this chapter simply provides a brief
description of the remaining collection classes,
@code{AssociativeArray} and @code{List.}

@iftex
@section @code{List} Class
@end iftex
@ifnottex
@subheading @code{List} Class
@end ifnottex
@cindex @code{List} Class

@code{List} class objects contain doubly linked lists of object
references.  

@cindex @mnm{push} method @idxclscite{List}
If you want to add an item to a @code{List} object's contents, use the method
@mnm{push.} 
@example
List new l;
Integer new i;
Integer new i2;

l push i;
l push i2;
@end example

@cindex @mnm{pop} method @idxclscite{List}
To remove items from the end of a list and retrieve the items, use
the method @mnm{pop.}
@example
List new l;
Integer new i;
Integer new i2;
Integer new i3;
Integer new i4;

l push i;
l push i2;

i3 = l pop;
i4 = l pop;
@end example

@cindex @mnm{shift} method @idxclscite{List}
@cindex @mnm{unshift} method @idxclscite{List}
The methods @mnm{shift} and @mnm{unshift} are similar to @mnm{push}
and @mnm{pop,} respectively, but they add and remove items from the
front of the list.

Here is a simple, if slightly unwieldy, example of how these methods
work.  You can find this program in @flnm{test/basiclist.c}.
@example
int main () @{

  List new l;
  Integer new i1;
  Integer new i2;
  Integer new i3;
  Integer new i4;
  Integer new i5;
  Integer new i6;

  i1 = 1;
  printf ("%d ", i1);
  i2 = 2;
  printf ("%d ", i2);
  i3 = 3;
  printf ("%d ", i3);
  printf ("\n");

  l push i1;
  l push i2;
  l push i3;

  i4 = l pop;
  printf ("%d ", i4);
  i5 = l pop;
  printf ("%d ", i5);
  i6 = l pop;
  printf ("%d ", i6);
  printf ("\n");

  l shift i1;
  printf ("%d ", i1);
  l shift i2;
  printf ("%d ", i2);
  l shift i3;
  printf ("%d ", i3);
  printf ("\n");

  i4 = l unshift;
  printf ("%d ", i4);
  i5 = l unshift;
  printf ("%d ", i5);
  i6 = l unshift;
  printf ("%d ", i6);
  printf ("\n");

  return 0;
@}
@end example
@cindex @mnm{map} method @idxclscite{List}
If you want to work with every item in a list, use the method
@mnm{map.} 
@example
List instanceMethod printItem (void) @{
  printf ("%d ", __ctalk_to_c_int(__ctalk_self_internal()));
  methodReturnNULL
@}

int main () @{

  List new l;
  Integer new i1;
  Integer new i2;
  Integer new i3;

  i1 = 1;
  i2 = 2;
  i3 = 3;

  l push i1;
  l push i2;
  l push i3;

  l map printItem;
  printf ("\n");
@}
@end example
Remember that the argument to @mnm{map,} in this example
@mnm{printItem,} must be an instance method of class @code{List,} even
though the receiver of each call to @mnm{printItem,} each successive
member of @code{List} @code{l} (in @code{main()}), can have its own class.

Within @mnm{printItem,} you have to use the library functions
@code{__ctalk_self_internal()} and @code{__ctalk_to_c_int ()} to refer
to the items of @code{l}, because @mnm{printItem} does not know until
run time what class @code{self} (each member of @code{l}) is going to
be, and Ctalk cannot perform the object-to-C translation for
@code{printf} automagically.

@iftex
@section @code{AssociativeArray} Class
@end iftex
@ifnottex
@subheading @code{AssociativeArray} Class
@end ifnottex
@cindex @code{AssociativeArray} Class

@cindex @code{Key} class
@code{AssociativeArray} objects store their elements using a
@code{Key} object.  

Programs use name of the @code{Key} object, normally a @code{String,}
to store and retrieve elements of the array.  The value of the
@code{Key} object is the object that you want to store in the array.

@cindex @mnm{atPut} method @idxclscite{AssociativeArray}
@cindex @mnm{at} method @idxclscite{AssociativeArray}
The @code{AssociativeArray} class does the work of assigning keys and
storing objects in the arrays for you, using the methods @mnm{at} and
@mnm{atPut}.

For example, to store an object, use a statement similar to the following.
@example
myAssociativeArray atPut "keyName", myObject;
@end example

To retrieve an object, use the method @mnm{at}.
@example
myObjectFromBefore = myAssociativeArray at "keyName";
@end example

@cindex @mnm{map} method @idxclscite{AssociativeArray}
You can also treat @code{AssociativeArray} elements
sequentially, using the method @mnm{map}.

@cindex @code{Key} class
The @cite{Ctalk Language Reference} describes the details of storing
and retrieving @code{Key} object names and values.

@iftex
@section Collection Elements as Receivers
@end iftex
@ifnottex
@subheading Collection Elements as Receivers
@end ifnottex

When using collection elements, programs often don't know until run
time exactly what the class of a reciever might be - elements of
object.  In addition methods like @mnm{map}, use each element
of a collection as a receiver.  

Collections all use @code{Key} objects to store the actual data.  
In methods that use collection elements, programs can either declare a
@code{Key} object explicitly, or it can rely on a method in a
superclass to determine whether the receivers are valid.  The
@cite{Ctalk Web Utilities} manual provides examples of both
techniques. 

@cindex @mnm{getValue} method @idxclscite{Collection}
Here is @mnm{getValue} in @code{Collection} class, which determines
that the actual receiver of a @mnm{getValue} message at run time is a
@code{Key} object and generates an exception otherwise.
@example
Collection instanceMethod getValue (void) @{
  Exception new e;

  if (self is Key) @{
    return self getValue;
  @}
  e raiseCriticalException INVALID_RECEIVER_X, 
    "Message \"getValue\" sent to a Collection object, not a Key object.";
  methodReturnNULL
@}
@end example

@node Classes, Methods, Collections, Top
@iftex
@chapter Defining Classes and Objects
@end iftex
@ifnottex
@heading Defining Classes and Objects
@end ifnottex

The previous chapters described some of the methods that the Ctalk
classes define.  This chapter discusses in further detail how to
define Classes and variables that belong to the classes, and discusses
some of the ways that Ctalk initializes instances of a class.

Many of the methods used in this chapter are @emph{primitive} methods.
The primitive method definitions are in the @code{Object} class, and
and any class can use them.

@iftex
@section Superclasses
@end iftex
@ifnottex
@subheading Superclasses
@end ifnottex

@cindex @mnm{class} method @idxclscite{Object}
At a minimum, a class definition defines the name of the new class and
its superclass.  The primitive method @mnm{class} (@code{Object}
class) takes the name of a new class as its argument.  The new class
is defined in the class library as a subclass of the receiver's class.

This statement defines a class with the name @code{WriteFileStream} as a
subclass of the receiver, @code{FileStream.}
@example
FileStream class WriteFileStream;
@end example

Or, more generically,
@example
@var{superclassname} class @var{newclassname};
@end example

The superclass indicates where the new class fits into
the class library, and that determines which methods and instance data
the new class inherits.  The only class that does not have a
superclass is @code{Object,} the topmost class in the class library.

When defining new classes, it is important that the superclasses of
the new class already be defined.  That statement may seem obvious,
but you need to take care when defining complex objects that
all of the definitions you need are already present.  

Another reason is that, when you define an instance or class variable,
the variable @emph{is a member of your new class,} unless you specify
that the variable belongs to another class.  If your class's instance
and class variables can inherit methods from the class's superclasses,
then you don't need to write new methods to manage the variables.

@cindex @code{require} keyword
However, you can direct Ctalk to initialize other classes if your
class needs them, by using, for example, statements like
@code{require,} as described below.

The previous chapters have described some of the ways that you can
work with instance data using C.  Many of the Ctalk library's API
functions also check for the type and value instance data.  The method
API is described later on.

Ctalk also contains several programs that define their own classes.
Although the example programs are too long to list here, this chapter
mentions them when necessary.

@iftex
@section Instance Variables
@end iftex
@ifnottex
@subheading Instance Variables
@end ifnottex
@anchor{Instance Variables}

@cindex @code{value} instance variable
@cindex @code{instanceVariable} method @idxclscite{Object}
We mentioned already that all objects have a default instance variable
named @code{value.}  However, many classes define other instance
variables.  Classes define instance variables with the
@mnm{instanceVariable} method.

Here is an example of an instance variable definition.
@example
MyNewClass instanceVariable textMessage String NULL;
@end example

This example declares that all instances of @code{MyNewClass} will
have an instance variable named @code{textMessage,} and that it is
an instance of class @code{String,} and it has the initial value
@code{NULL.}  

The second and third arguments of @code{instanceVariable} are
optional.  Here is the syntax of the @code{instanceVariable} method. 
@example
@var{classname} instanceVariable @var{varname} [@var{varclass}] [@var{initialvalue}]
@end example

Remember that @mnm{instanceVariable} only @emph{defines} variables.
The method does not actually create them.  When you create an object
that is an instance of your class, the object gets its own copy of the
variable.

@iftex
@section Class Variables
@end iftex
@ifnottex
@subheading Class Variables
@end ifnottex
@anchor{Class Variables}

@cindex @mnm{classVariable} method @idxclscite{Object}
On the other hand, the @mnm{classVariable} method creates the single
copy of a class variable that the instances of a class (and most other
classes) can use.  Creating a class variable is similar to creating an
instance variable.
@example
MyNewClass classVariable systemError Integer 0;
@end example

For completeness, here is the @mnm{classVariable} method's syntax.
@example
@var{classname} classVariable @var{varname} [@var{varclass}] [@var{initialvalue}]
@end example

Remember that if you define a variable as a different class than its
member class, then the variable responds to messages of its own class.
In these cases, you need to take care that you are working with the
variable, and not the class that it belongs to.

@iftex
@section Class Initialization
@end iftex
@ifnottex
@subheading Class Initialization
@end ifnottex

Although you can define an initial value for a class variable, in many
cases you need to wait until the program is run before setting the
actual value of a class variable.  An example of this is
@mnm{stdoutStream} (class @code{WriteFileStream}).  

In many cases, a constructor method (which in Ctalk are named
@code{new}), can call a class initialization method.

Here is a hypothetical class with @mnm{classInit} a method.  This
example simply sets the the name of the system in a class variable
called @code{hostName.}
@example

MySuperClass class MyClass;

MyClass classVariable myClassVar String NULL;

@emph{...}
@emph{Other class and instance variable definitions.}
@emph{...}

MyClass classMethod classInit (void) @{

  OBJECT *classObject_object, 
    *classInitVar_object, 
    *myClassVar_object;
  char buf[MAXLABEL];

  /*
   *  Return if we've already initialize the class.
   */
  if (self classInitDone)
    methodReturnNULL


  /*
   *  Retrieve the class object, because we'll need it below.
   */

  classObject_object = __ctalkGetClass("MyClass");

  /*
   *  Look for myClassVar.  
   *  The third argument of __ctalkGetClassVariable instructs the 
   *  function not to print a warning if it doesn't find the 
   *  variable.  If the variable is not present, then the class
   *  is not completely initialized, so return.
   */

  if ((myClassVar_object = 
    __ctalkGetClassVariable (self, "myClassVar", FALSE)) == NULL) @{
    methodReturnNULL
  @}

  @emph{...}
  @emph{Initialize myClassVar here.}
  @emph{...}

  classInitVar = 
    __ctalkCreateObjectInit ("classInitDone", "Integer",
                             "Magnitude", GLOBAL_VAR, "1");
  __ctalkAddClassVariable (classObject, "classInitDone", classInitVar);

  methodReturnNULL
@}

@emph{...}
@emph{Other methods.}
@emph{...}
@end example

When writing classes, you need to remember that Ctalk initializes the
class and its methods and data in the following order.
@enumerate
@item
The class itself and its superclass.
@item
The class' instance and class methods.
@item
Instance variables.
@item
Class variables.
@end enumerate

Remember that a class definition only requires a superclass.  All of
the other elements are optional.

It is possible, when initializing complex classes, to construct
objects before the class is completely defined.  That's why
@code{classInit} above checks for the class variable @code{myClassVar}
and returns if it is not present.

However, Ctalk checks the class initialization every time it creates
an instance of @code{MyClass,} so a constructor method for MyClass
might look like the following.

@cindex @code{__ctalkInstanceVarsFromClassObject} function
@example
MyClass instanceMethod new (char *myObjectName) @{

  MyClass super new myObjectName;

  __ctalkInstanceVarsFromClassObject (myObjectName);

  MyClass classInit;
  
  methodReturnObjectName(myObjectName)
@}
@end example

The program then initializes the class variables when the class is
completely defined.  If @code{classInitDone} is @code{TRUE,} then the
program won't initialize the class again.

@emph{Note:} Ctalk does not automatically create a copy of a class's
instance variables when creating objects.  Your program must call 
@code{__ctalkIntanceVarsFromClassObject} to create the instance 
variables in the new object.

If you simply want to initialize a class without creating a new
object, you can add a statement like this to your program.
@example
MyClass classInit;
@end example

Another example of a method that performs class intialization is the
method @mnm{initDigits} (class @code{ClockDigit}) in the program
@flnm{ltime.c.} The method is too long to list here, but you can find
@flnm{ltime.c} in the Ctalk distribution's @flnm{programs}
subdirectory.

The later chapters describe methods and library functions that perform
class initialization in more detail.  

@iftex
@section @code{require} Keyword
@end iftex
@ifnottex
@subheading @code{require} Keyword
@end ifnottex

@cindex @code{require} keyword
Ctalk programs initialize the basic classes before starting to
initialize the application's class and method definitions.  However,
if your definition needs a class that Ctalk does not include
automatically, you can initialize the class and include its method and
variable definitions before defining your own class by using the
keyword @code{require.}

The use of @code{require} is simple.  Include it with the name of the
class that your class needs, and Ctalk inserts the its class and
method definitions at that point.
@example
require List;
@end example

@iftex
@section Where Ctalk Looks for Class Libraries
@end iftex
@ifnottex
@subheading Where Ctalk Looks for Class Libraries
@end ifnottex
@cindex Library search path

The Ctalk configuration determines where the class libraries are
located when you build and install Ctalk.  In a normal UNIX system,
that location is the directory @flnm{/usr/local/include/ctalk.}

However, if you want your own classes to reside in the same directory
as the program, or any other directory, you can include the directory
in Ctalk's library search path with the @samp{-I} option.

On many systems the shorthand for the current directory is @samp{.},
so if your class is located in the same directory as the program, add
the directory to the library search path as in this example.
@example
$ ctalk -I. myprog.c -o myprog.i
@end example

@iftex
@section Instance Variables and Method Overloading
@end iftex
@ifnottex
@subheading Instance Variables and Method Overloading
@end ifnottex

One consequence of all this convenient instance data and overloaded
methods is that it is easy to confuse which method a message actually
translates into.  That is because the member class of an instance or
class variable might not be the class of the variable's own instance
data.

Here is an example.  The @mnm{openOn} message in the first statement
translates to the @mnm{openOn} method in the @code{ANSITerminalPane}
class, while the @mnm{openOn} message in the second statement
translates to the @mnm{openOn} method in the @code{ReadFileStream}
class. 
@example
ANSITerminalPane new mainWindow;

mainWindow paneStream openOn "/dev/ttyS0";               /* Correct.  */

mainWindow paneStream inputHandle openOn "/dev/ttyS0";   /* Incorrect. */
@end example

This is because @code{inputHandle} in the second statement is actually
a @code{ReadFileStream}, while the program actually wants to call is
the @mnm{openOn} method from @mnm{ANSITerminalStream}, which is the
effect of the first statement.  The @code{Stream} classes have many
classes in common.  In most cases this makes things simpler, but not
always. 

There are several ways to work around this issue.  This first is to
use stack walkbacks and exception handlers whenever a program opens a
file.  That allows you to see what methods the program's statements
actually translate into. @xref{Debugging}.

If you can't avoid an incorrect message translation in a program, you
can write your own method that only one of your program's classes
responds to.  For example, instead of yet another @mnm{openOn} method,
your program might define a method like, for example,
@mnm{openOnInputData}.  

Finally, if the program cannot determine in advance which class is
going to receive a message, you can write a method that dispatches the
receiver to a method of the correct class.  Here is an example.
@example
Stream instanceMethod openOnTerminal (String pathName) @{
  Exception new e;
  if (self is ANSITerminalStream) @{ 
    if (pathName isATty) @{
      self openOn pathName;
    @} else @{
      e raiseException NOT_A_TTY_X, pathName;
    @} 
  @} else @{
    e raiseException INVALID_RECEIVER_X, pathName;
  @}
  methodReturnSelf;
@}
@end example




@node Methods, Debugging, Classes, Top
@iftex
@chapter Writing Methods
@end iftex
@ifnottex
@heading Writing Methods
@end ifnottex
@cindex Methods

Languages like C identify and call functions by matching a label in
the source code against an identifier in an object module, and the
compiler (or more properly, the linker or interpreter) inserts a call
to the function in the program.

In Ctalk, like many other object oriented languages, objects
respond to @emph{messages} that refer to methods defined by the
object's class or the object's superclasses.

Here is an example.  If you wanted to create a new
@code{WriteFileStream} object, you would add a statement like this to
the program.
@example
WriteFileStream new myOutputStream;
@end example

When the receiver, @code{WriteFileStream,} receives the message,
@code{new,} the process of executing the methods that create a
@code{WriteFileStream} object works in the following
manner.
@smallexample
Class                  Message    Action 
-----                  -------    ------
|- Object <-------------- new        2. Return new, generic object.
|                           ^                  |
|- Stream                    \                 |
|                             \                |
|- FileStream                  \               |
|                               \              |
|- WriteFileStream <----- new     1.Execute    |
                                  "super new." |
                                               v
                                              3. Add the instance variables 
                                              that WriteFileStream objects 
                                              need and initialize the class 
                                              if necessary.
@end smallexample

@cindex @mnm{parseQueryString} method @idxclscite{CGIApp}
@cindex @code{CGIApp} class
Here is a typical method.  This is the instance method
@code{parseQueryString} (class @code{CGIApp.})  The @code{CGIApp}
class is in the Ctalk @flnm{programs/cgi} subdirectory and is used by
the Common Gateway Interface programs in that directory.

@example
CGIApp instanceMethod parseQueryString (void) @{
  String new queryString;
  String new paramString;
  Array new queryParams;
  Array new paramArray;
  Integer new nParams;
  String new paramKey;
  String new paramValue;
  Integer new i;
  Integer new j;

  queryString = self serverEnvironment at "QUERY_STRING";

  if (queryString length == 0) @{
    methodReturnNULL;
  @}

  nParams = queryString split '&', queryParams;

  for (i = 0; i < nParams; i = i + 1) @{
    paramString = queryParams at i;
    j = paramString split '=', paramArray;
    if (j == 1) @{
      self queryValues atPut (paramArray at 0), "1";
    @} else @{
      if (j == 2) @{
	self queryValues atPut (paramArray at 0), (paramArray at 1);
      @}
    @}
  @}  
  methodReturnNULL;
@}
@end example

The @code{parseQueryString} method parses the parameters of a CGI
query and places them in the application's @code{queryValues} instance
variable, an @code{AssociativeArray.}  The @code{queryValues} instance
variable then contains the key-value pairs of each of CGI
application's parameters.

If you call a CGI application with a URL like the following example
@example
http://my-web-server/cgi-bin/mysearchprog?term=ctalk&case=ignore&showresults=10
@end example
Then @code{parseQueryString} sets the application's @code{queryValues}
@code{AssociativeArray} to the following.
@example
                  Key          Value
queryValues  at   term         ctalk
queryValues  at   case         ignore
queryValues  at   showresults  10
@end example
@cindex @mnm{split} method @idxclscite{String}
The @code{parseQueryString} method uses the @code{split} method (class
@code{String}) several times to split the query string at the @samp{&}
delimiters, and then each parameter and its value at the @samp{=}
character.  If a parameter is defined but does not have a value
associated with it, @code{parseQueryString} assigns it the value of
@samp{1}.

@iftex
@section Overview of the Method Application Programming Interface
@end iftex
@ifnottex
@subheading Overview of the Method Application Programming Interface
@end ifnottex

You might recall from the earlier chapters that if a program uses an
operator like @samp{+} or @samp{-} with a C variable, then Ctalk treats
the operator as a C math operator.  However, if you use a math
operator with an object as the receiver, then Ctalk uses a method to
perform the operation.

Although there are several exceptions, most methods are written in
Ctalk and are located in Ctalk's class library.  On UNIX
systems, the class library normally resides in
@flnm{/usr/local/include/ctalk}, although the location may vary
depending on the operating system.

@iftex
@subsection Primitive Methods
@end iftex
@ifnottex
@subsubheading Primitive Methods
@end ifnottex
@cindex Primitive methods

One exception is the way Ctalk implements @emph{primitive
methods.}  Ctalk implements these methods in C, and you can call
them without worrying if a program defines a class.

@cindex @mnm{new} method @idxclscite{Object}
These methods are available to all classes, so they effectively belong
to the @code{Object} class.  You can also subclass these methods, as
is often the case with the constructor @code{new}.  The previous
chapters have described in general how to subclass methods, and this
manual describes the process in detail later on.

Here are the primitive methods that Ctalk defines.
@table @code
@item class @var{classname}
@cindex @mnm{class} method @idxclscite{Object}
Defines a new class.  The receiver is the name of the superclass, and
the argument is the name of the class that you want to create.

@item classMethod @var{alias} @var{selector} (@var{args})
@cindex @mnm{classMethod} method @idxclscite{Object}
Declares a new class method.  The next section describes the syntax of
method declarations. @xref{Method Declarations}.

@item classVariable @var{varname} @var{varclass} @var{initial-value}
@cindex @mnm{classVariable} method @idxclscite{Object}
Declare a class variable.  The receiver is the class of the variable.
You must provide a @var{name} for the class variable.  The statement
also allows you to define a class for the class variable and an
initial value.  @xref{Class Variables}.

@item instanceMethod @var{alias} @var{selector} (@var{args})
@cindex @mnm{instanceMethod} method @idxclscite{Object}
Declares a new instance method.  The next section describes the syntax of
method declarations. @xref{Method Declarations}.

@item instanceVariable @var{varname} @var{varclass} @var{initial-value}
@cindex @mnm{instanceVariable} method @idxclscite{Object}
Define an instance variable.  The receiver is the class of the
variable.  Unlike class variables, @mnm{instanceVariable} only defines
a variable's declaration.  A constructor like @code{new} creates the
actual instance variables when it creates an object. @xref{Instance Variables}.

@item new @var{newobjectname}
@cindex @mnm{new} method @idxclscite{Object}
Create a new object.  The receiver of @code{new} is the object's
class.
@end table

@iftex
@subsection Instance and Class Variable Messages
@end iftex
@ifnottex
@subsubheading Instance and Class Variable Messages
@end ifnottex
For completeness, we should mention that the other exception in the
method API is the use of instance and class variable names as
messages.  

The @code{value} message is an example of a message that refers to an
instance variable.  Remember that a statement like the following
example returns only the instance variable, and not the complete
object. 
@example
return self value;
@end example

@cindex @mnm{at} method @idxclscite{Array}
Instance variable messages are useful mainly when creating C
references to objects.  Methods, on the other hand, generally work
with complete objects.  An example is the @mnm{at} method in class
@code{Array}. 
@example
myElement = myArray at 0;
@end example

The message @mnm{at} returns the @emph{0}th array element. 

When you use objects with C, you must also check to determine that the
object references are really the objects that the program expects.

The following sections describe the Ctalk interface to C, and the many
of the examples in this manual describe Ctalk's C API.

@anchor{Method Declarations}
@iftex
@section Method Declarations
@end iftex
@ifnottex
@subheading Method Declarations
@end ifnottex
@cindex Method declarations
@cindex @code{instanceMethod} keyword
@cindex @code{classMethod} keyword

As you probably noticed from the example above, you can declare
methods in much the same manner as C functions.  

However, method declarations have a different meaning, and the
declarations allow for multiple methods with the same name in 
different classes.

The following example is the basic syntax of an instance method
declaration.
@example
@var{class} @code{instanceMethod} [@var{alias}] @var{selector} (@var{args}) @{
... Method body
@} 
@end example

The third term, @var{alias}, is optional.  It is often used to alias a
method to an operator like @samp{+}, @samp{-}, or another operator
that you want to overload in @var{class}.

The syntax of a class method declaration is similar, but it uses the @code{classMethod} method.
@example
@var{class} @code{classMethod} [@var{alias}] @var{selector} (@var{args}) @{
... Method body
@} 
@end example

@iftex
@section Using Methods in Simple Statements
@end iftex
@ifnottex
@subheading How Methods Interface with C
@end ifnottex

Methods can be either labels or C operators.  Although Ctalk's
syntax is similar to C, it allows more flexibility in the construction
of statements.

As we noted earlier, you can change characters from upper case to
lower case and vice versa by toggling the fifth bit of the character.
Here is that example again.
@example
Character new upperCase;
Character new lowerCase;
Integer new toggleBit;  

upperCase = 'Z';
lowerCase = 'z';
toggleBit = 32;

printf ("%c\n", upperCase ^ toggleBit);
printf ("%c\n", lowerCase ^ toggleBit);
@end example

@cindex @mnm{^} method @idxclscite{Character}
The @mnm{^} operator in these statements is actually a method in
class @code{Character}.  

@cindex @mnm{toLower} method @idxclscite{Character}
@cindex @mnm{toUpper} method @idxclscite{Character}
Ctalk also provides two methods in @code{Character} class,
@mnm{toUpper} and @mnm{toLower}, that provide the same function, and
the methods also check that the receiver is a letter of the
appropriate case before changing the case.

Here is the @mnm{toLower} method.
@example
Character instanceMethod toLower (void) @{
  Character new result;

  if (self isAlpha && self isUpper) @{
    result = self asInteger ^ 32;
  @} else @{
    result = self;
  @}
  return result;
@}
@end example

@cindex @mnm{asInteger} method @idxclscite{Magnitude}
We could omit the @mnm{asInteger} message, but using @mnm{asInteger},
which is implemented in @code{Magnitude} class, allows us to reliably
check that the receiver of @mnm{^} is actually a valid
number, even if the receiver of @mnm{toLower} is the result
of another statement that translates its value from a completely
different receiver elsewhere in the program.

The result of @code{self asInteger} is an @code{Integer} object, so 
it uses @mnm{^} from @code{Integer} class to perform the translation.

@cindex @mnm{asCharacter} method @idxclscite{Magnitude}
The @mnm{asCharacter} method, like @mnm{asInteger}, is defined
in @code{Magnitude} class.

The @mnm{value} message in the example above is optional.  Ctalk 
sends method arguments as complete objects.  

Ctalk statements can appear in many of the places that a C expression
can appear.  Here is another simple example.
@example
int main () @{
  String new ten;
  ten = "10";
  printf ("%d\n", ten asInteger);
@}
@end example

As a general rule, keep in mind that receiver objects and other
methods that are part of complex statements work with objects.

There are many cases, however, when you need to use a message like
@mnm{value} in a statement to return an instance variable - generally
when you are using objects with C statements, which the next section
describes.

@iftex
@section The @code{value} Message and Interfacing with C
@end iftex
@ifnottex
@subheading The @code{value} Message and Interfacing with C
@end ifnottex

@cindex @mnm{value} message.
We have already described how refer to objects with C variables in
many places.  This section provides a slightly more formal definition
of how and when to use @code{value}.

If you are assigning an object to a C variable, then in most cases you
want to use the @mnm{value} message.  This message, you might remember
from previous chapters, returns the receiver's @code{value} instance
variable.

So if you want to assign an object's value to a C variable, you might
use a set of statements like the following.
@example
OBJECT *value_object;
value_object = self value;
@end example

You should @emph{not,} however, simply use an object like @code{self}
on its own, because Ctalk cannot determine exactly how you plan to use 
the result.  The following example will provide the complete object, 
which is not what you want.
@example
OBJECT *value_object;
value_object = self;
@end example

It is okay, however, to use an object name on its own when used
with other objects.
@example
Object new receiverObjectCopy;
receiverObjectCopy = self;
@end example

Once you have assigned an object to a C variable, you can treat it
as a C @code{struct}.  The next section describes the
@code{OBJECT} C @code{typedef}.

@iftex
@subsection The @code{OBJECT} Type
@end iftex
@ifnottex
@subsubheading The @code{OBJECT} Type
@end ifnottex
@cindex @code{OBJECT} typedef

Ctalk represents objects internally as an @code{OBJECT} typedef, so
when you need to use an object in a C statement, you can create a C
alias for the object by declaring and initializing a C @code{OBJECT
*}.

Here is the @code{OBJECT} type declaration.  It is located in 
the file @flnm{classes/ctalklib}, and several other places.
@example
typedef struct _object OBJECT;
...
struct _object @{
  char sig[16];
  char __o_name[MAXLABEL];
  char __o_classname[MAXLABEL];
  OBJECT *__o_class;
  char __o_superclassname[MAXLABEL];
  OBJECT *__o_superclass;
  OBJECT *__o_p_obj;
  VARENTRY *__o_varentry;
  char *__o_value;
  METHOD *instance_methods,
    *class_methods;
  int scope;
  int nrefs;
  struct _object *classvars;
  struct _object *instancevars;    
  struct _object *next;
  struct _object *prev;
@};
@end example

So when a program uses statements like those in the following example,
the program is actually creating a C reference to an object.
@example
OBJECT *rcvr_value;
rcvr_value = self value;
@end example
Here, @code{=} is a C operator.  Ctalk evaluates the @code{value}
message, and then determines that it doesn't need to perform 
further translation on the objects because the receiver simply needs
the @code{value} instance variable as C @code{struct}.

Generally, C programs are mainly interested in the @code{__o_value}
field of an object, because this is where objects store their data as
C @code{char *}'s.

@cindex @cite{__ctalk_to_c_char_ptr()} function
@cindex @cite{__ctalk_to_c_int()} function
There are also API C functions, like @cite{__ctalk_to_c_char_ptr ()} and
@cite{__ctalk_to_c_int ()}, that translate objects to C.  The
@cite{Ctalk Language Reference} describes these functions.

@iftex
@subsection Return Values
@end iftex
@ifnottex
@subsubheading Return Values
@end ifnottex

You can also return objects from methods, but you need to be careful
to delete any objects that you create.  If your method creates an
object as the left-hand side of an equation, then Ctalk can generally 
keep track of the object.  

For example, if you create a method called @code{addTwoAndTwo} and
return the result, you might write the method as in the following
example.
@example
Integer instanceMethod addTwoAndTwo (void) @{
  char buf[2];
  sprintf (buf, "%d", 2 + 2);
  return __ctalkCreateObjectInit ("result", 
                                  "Integer",
                                  "Magnitude",
                                  LOCAL_VAR,
                                  buf);
@}
@end example
Then, however, you need to make sure that the newly created result is
assigned in the expression that calls the method, as in this example.
@example
  Integer new mySum;

  ... 

  mySum = myInteger addTwoAndTwo;
@end example
When the function or method that contains @code{mySum} exits, it takes
care of deleting the value you created, but, again, deleting objects
that you create using C is not always automatic.

Another way to write the method would be to assign the value to 
@code{self,} as in this example.
@example
Integer instanceMethod addTwoAndTwo (void) @{
  char buf[2];
  sprintf (buf, "%d", 2 + 2);
  __ctalkSetObjectValueVar (self, buf);
  methodReturnSelf
@}
@end example
Then you can use the @code{addTwoAndTwo} method in an
expression like the following.
@example
  mySum addTwoAndTwo;
@end example
The @code{methodReturnSelf} statement is actually a macro.  There are
several macros that allow you to return common object types.  The
@cite{Ctalk Language Reference} contains a complete list of them.

You should use these statements whenever possible, because they should
be portable even if the Ctalk method API changes in later versions of
the language, and they help guarantee that your methods follow a 
common call and return protocol.

@node Debugging, GNU Free Documentation License, Methods, Top
@iftex
@chapter Debugging
@end iftex
@ifnottex
@heading Debugging
@end ifnottex
@cindex Debugging

Ctalk is still in development, and does not yet have all of the
debugging facilities of other object oriented languages.

Apart from debugging the internals of the Ctalk front end and
libraries, which is described in the @cite{Ctalk Language Reference},
there are a few classes and methods that programs can use to display
diagnostic information when they are run.

@iftex
@subsection Printing Call Sequences for Exceptions
@end iftex
@ifnottex
@subsubheading Printing Call Sequences for Exceptions
@end ifnottex

The method @mnm{enableExceptionTrace} in class @code{Object} enables
the printing of the program's call stack to the console's standard
error channel when a program deals with an exception using
@mnm{handle} (class @code{Exception}).

A program can turn off the display of the call stack with the
@mnm{disableExceptionTrace} method, also in class @code{Object}.  
The method @code{traceEnabled} in class @code{Object} returns
@code{TRUE} or @code{FALSE} depending on whether call stack displays
are enabled.

A program can print an exception's call stack using
@mnm{printExceptionTrace} in class @code{Exception}.  Here is 
the code from the @mnm{handle} method that calls
@mnm{printExceptionTrace}. 
@example
if (self traceEnabled) @{
  self printExceptionTrace;
@}
@end example

@iftex
@subsection Printing Objects
@end iftex
@ifnottex
@subsubheading Printing Objects
@end ifnottex

The method @mnm{printSelf} (class @code{Object}) prints its receiver
to the program's standard error channel.  For example, if a program
contains the following lines:
@example
ReadFileStream new inputStream;
...
inputStream openOn "myFile";
...
inputStream printSelf;
@end example
Then it will print the class and value of @code{inputStream} and all
of its instance variables.  Remember that @mnm{openOn} (class
@code{ReadFileStream}) calls @mnm{statStream} (in class
@code{FileStream}) to fill in the stream object's instance variables. 

If a program needs to print an object that is not within the scope of
a method or function, it can call the library function
@code{__ctalkPrintObjectByName} directly.  The argument is a string
containing the name of the object you want to print.
@code{__ctalkPrintObjectByName} looks up the object before printing
it.


@node GNU Free Documentation License, Index, Debugging, Top
@iftex
@chapter GNU Free Documentation License
@end iftex
@ifnottex
@heading GNU Free Documentation License
@end ifnottex
@cindex GNU Free Documentation License
@example

                        Version 1.1, March 2000
     Copyright (C) 2000  Free Software Foundation, Inc.
     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     
     Everyone is permitted to copy and distribute example copies
     of this license document, but changing it is not allowed.



  0. PREAMBLE

     The purpose of this License is to make a manual, textbook, or other
     written document "free" in the sense of freedom: to assure everyone
     the effective freedom to copy and redistribute it, with or without
     modifying it, either commercially or noncommercially.  Secondarily,
     this License preserves for the author and publisher a way to get
     credit for their work, while not being considered responsible for
     modifications made by others.

     This License is a kind of "copyleft", which means that derivative
     works of the document must themselves be free in the same sense.
     It complements the GNU General Public License, which is a copyleft
     license designed for free software.

     We have designed this License in order to use it for manuals for
     free software, because free software needs free documentation: a
     free program should come with manuals providing the same freedoms
     that the software does.  But this License is not limited to
     software manuals; it can be used for any textual work, regardless
     of subject matter or whether it is published as a printed book.
     We recommend this License principally for works whose purpose is
     instruction or reference.


  1. APPLICABILITY AND DEFINITIONS

     This License applies to any manual or other work that contains a
     notice placed by the copyright holder saying it can be distributed
     under the terms of this License.  The "Document", below, refers to
     any such manual or work.  Any member of the public is a licensee,
     and is addressed as "you."

     A "Modified Version" of the Document means any work containing the
     Document or a portion of it, either copied example, or with
     modifications and/or translated into another language.

     A "Secondary Section" is a named appendix or a front-matter
     section of the Document that deals exclusively with the
     relationship of the publishers or authors of the Document to the
     Document's overall subject (or to related matters) and contains
     nothing that could fall directly within that overall subject.
     (For example, if the Document is in part a textbook of
     mathematics, a Secondary Section may not explain any mathematics.)
     The relationship could be a matter of historical connection with
     the subject or with related matters, or of legal, commercial,
     philosophical, ethical or political position regarding them.

     The "Invariant Sections" are certain Secondary Sections whose
     titles are designated, as being those of Invariant Sections, in
     the notice that says that the Document is released under this
     License.

     The "Cover Texts" are certain short passages of text that are
     listed, as Front-Cover Texts or Back-Cover Texts, in the notice
     that says that the Document is released under this License.

     A "Transparent" copy of the Document means a machine-readable copy,
     represented in a format whose specification is available to the
     general public, whose contents can be viewed and edited directly
     and straightforwardly with generic text editors or (for images
     composed of pixels) generic paint programs or (for drawings) some
     widely available drawing editor, and that is suitable for input to
     text formatters or for automatic translation to a variety of
     formats suitable for input to text formatters.  A copy made in an
     otherwise Transparent file format whose markup has been designed
     to thwart or discourage subsequent modification by readers is not
     Transparent.  A copy that is not "Transparent" is called "Opaque."

     Examples of suitable formats for Transparent copies include plain
     ASCII without markup, Texinfo input format, LaTeX input format,
     SGML or XML using a publicly available DTD, and
     standard-conforming simple HTML designed for human modification.
     Opaque formats include PostScript, PDF, proprietary formats that
     can be read and edited only by proprietary word processors, SGML
     or XML for which the DTD and/or processing tools are not generally
     available, and the machine-generated HTML produced by some word
     processors for output purposes only.

     The "Title Page" means, for a printed book, the title page itself,
     plus such following pages as are needed to hold, legibly, the
     material this License requires to appear in the title page.  For
     works in formats which do not have any title page as such, "Title
     Page" means the text near the most prominent appearance of the
     work's title, preceding the beginning of the body of the text.


  2. EXAMPLE COPYING

     You may copy and distribute the Document in any medium, either
     commercially or noncommercially, provided that this License, the
     copyright notices, and the license notice saying this License
     applies to the Document are reproduced in all copies, and that you
     add no other conditions whatsoever to those of this License.  You
     may not use technical measures to obstruct or control the reading
     or further copying of the copies you make or distribute.  However,
     you may accept compensation in exchange for copies.  If you
     distribute a large enough number of copies you must also follow
     the conditions in section 3.

     You may also lend copies, under the same conditions stated above,
     and you may publicly display copies.


  3. COPYING IN QUANTITY

     If you publish printed copies of the Document numbering more than
     100, and the Document's license notice requires Cover Texts, you
     must enclose the copies in covers that carry, clearly and legibly,
     all these Cover Texts: Front-Cover Texts on the front cover, and
     Back-Cover Texts on the back cover.  Both covers must also clearly
     and legibly identify you as the publisher of these copies.  The
     front cover must present the full title with all words of the
     title equally prominent and visible.  You may add other material
     on the covers in addition.  Copying with changes limited to the
     covers, as long as they preserve the title of the Document and
     satisfy these conditions, can be treated as example copying in
     other respects.

     If the required texts for either cover are too voluminous to fit
     legibly, you should put the first ones listed (as many as fit
     reasonably) on the actual cover, and continue the rest onto
     adjacent pages.

     If you publish or distribute Opaque copies of the Document
     numbering more than 100, you must either include a
     machine-readable Transparent copy along with each Opaque copy, or
     state in or with each Opaque copy a publicly-accessible
     computer-network location containing a complete Transparent copy
     of the Document, free of added material, which the general
     network-using public has access to download anonymously at no
     charge using public-standard network protocols.  If you use the
     latter option, you must take reasonably prudent steps, when you
     begin distribution of Opaque copies in quantity, to ensure that
     this Transparent copy will remain thus accessible at the stated
     location until at least one year after the last time you
     distribute an Opaque copy (directly or through your agents or
     retailers) of that edition to the public.

     It is requested, but not required, that you contact the authors of
     the Document well before redistributing any large number of
     copies, to give them a chance to provide you with an updated
     version of the Document.


  4. MODIFICATIONS

     You may copy and distribute a Modified Version of the Document
     under the conditions of sections 2 and 3 above, provided that you
     release the Modified Version under precisely this License, with
     the Modified Version filling the role of the Document, thus
     licensing distribution and modification of the Modified Version to
     whoever possesses a copy of it.  In addition, you must do these
     things in the Modified Version:

     A. Use in the Title Page (and on the covers, if any) a title
     distinct    from that of the Document, and from those of previous
     versions    (which should, if there were any, be listed in the
     History section    of the Document).  You may use the same title
     as a previous version    if the original publisher of that version
     gives permission.
     B. List on the Title Page, as authors, one or more persons or
     entities    responsible for authorship of the modifications in the
     Modified    Version, together with at least five of the principal
     authors of the    Document (all of its principal authors, if it
     has less than five).
     C. State on the Title page the name of the publisher of the
     Modified Version, as the publisher.
     D. Preserve all the copyright notices of the Document.
     E. Add an appropriate copyright notice for your modifications
     adjacent to the other copyright notices.
     F. Include, immediately after the copyright notices, a license
     notice    giving the public permission to use the Modified Version
     under the    terms of this License, in the form shown in the
     Addendum below.
     G. Preserve in that license notice the full lists of Invariant
     Sections    and required Cover Texts given in the Document's
     license notice.
     H. Include an unaltered copy of this License.
     I. Preserve the section entitled "History", and its title, and add
     to    it an item stating at least the title, year, new authors, and
       publisher of the Modified Version as given on the Title Page.
     If    there is no section entitled "History" in the Document,
     create one    stating the title, year, authors, and publisher of
     the Document as    given on its Title Page, then add an item
     describing the Modified    Version as stated in the previous
     sentence.
     J. Preserve the network location, if any, given in the Document for
       public access to a Transparent copy of the Document, and
     likewise    the network locations given in the Document for
     previous versions    it was based on.  These may be placed in the
     "History" section.     You may omit a network location for a work
     that was published at    least four years before the Document
     itself, or if the original    publisher of the version it refers
     to gives permission.
     K. In any section entitled "Acknowledgements" or "Dedications",
     preserve the section's title, and preserve in the section all the
      substance and tone of each of the contributor acknowledgements
     and/or dedications given therein.
     L. Preserve all the Invariant Sections of the Document,
     unaltered in their text and in their titles.  Section numbers
     or the equivalent are not considered part of the section titles.
     M. Delete any section entitled "Endorsements."  Such a section
     may not be included in the Modified Version.
     N. Do not retitle any existing section as "Endorsements"    or to
     conflict in title with any Invariant Section.

     If the Modified Version includes new front-matter sections or
     appendices that qualify as Secondary Sections and contain no
     material copied from the Document, you may at your option
     designate some or all of these sections as invariant.  To do this,
     add their titles to the list of Invariant Sections in the Modified
     Version's license notice.  These titles must be distinct from any
     other section titles.

     You may add a section entitled "Endorsements", provided it contains
     nothing but endorsements of your Modified Version by various
     parties-for example, statements of peer review or that the text has
     been approved by an organization as the authoritative definition
     of a standard.

     You may add a passage of up to five words as a Front-Cover Text,
     and a passage of up to 25 words as a Back-Cover Text, to the end
     of the list of Cover Texts in the Modified Version.  Only one
     passage of Front-Cover Text and one of Back-Cover Text may be
     added by (or through arrangements made by) any one entity.  If the
     Document already includes a cover text for the same cover,
     previously added by you or by arrangement made by the same entity
     you are acting on behalf of, you may not add another; but you may
     replace the old one, on explicit permission from the previous
     publisher that added the old one.

     The author(s) and publisher(s) of the Document do not by this
     License give permission to use their names for publicity for or to
     assert or imply endorsement of any Modified Version.


  5. COMBINING DOCUMENTS

     You may combine the Document with other documents released under
     this License, under the terms defined in section 4 above for
     modified versions, provided that you include in the combination
     all of the Invariant Sections of all of the original documents,
     unmodified, and list them all as Invariant Sections of your
     combined work in its license notice.

     The combined work need only contain one copy of this License, and
     multiple identical Invariant Sections may be replaced with a single
     copy.  If there are multiple Invariant Sections with the same name
     but different contents, make the title of each such section unique
     by adding at the end of it, in parentheses, the name of the
     original author or publisher of that section if known, or else a
     unique number.  Make the same adjustment to the section titles in
     the list of Invariant Sections in the license notice of the
     combined work.

     In the combination, you must combine any sections entitled
     "History" in the various original documents, forming one section
     entitled "History"; likewise combine any sections entitled
     "Acknowledgements", and any sections entitled "Dedications."  You
     must delete all sections entitled "Endorsements."


  6. COLLECTIONS OF DOCUMENTS

     You may make a collection consisting of the Document and other
     documents released under this License, and replace the individual
     copies of this License in the various documents with a single copy
     that is included in the collection, provided that you follow the
     rules of this License for example copying of each of the
     documents in all other respects.

     You may extract a single document from such a collection, and
     distribute it individually under this License, provided you insert
     a copy of this License into the extracted document, and follow
     this License in all other respects regarding example copying of
     that document.


  7. AGGREGATION WITH INDEPENDENT WORKS

     A compilation of the Document or its derivatives with other
     separate and independent documents or works, in or on a volume of
     a storage or distribution medium, does not as a whole count as a
     Modified Version of the Document, provided no compilation
     copyright is claimed for the compilation.  Such a compilation is
     called an "aggregate", and this License does not apply to the
     other self-contained works thus compiled with the Document, on
     account of their being thus compiled, if they are not themselves
     derivative works of the Document.

     If the Cover Text requirement of section 3 is applicable to these
     copies of the Document, then if the Document is less than one
     quarter of the entire aggregate, the Document's Cover Texts may be
     placed on covers that surround only the Document within the
     aggregate.  Otherwise they must appear on covers around the whole
     aggregate.


  8. TRANSLATION

     Translation is considered a kind of modification, so you may
     distribute translations of the Document under the terms of section
     4.  Replacing Invariant Sections with translations requires special
     permission from their copyright holders, but you may include
     translations of some or all Invariant Sections in addition to the
     original versions of these Invariant Sections.  You may include a
     translation of this License provided that you also include the
     original English version of this License.  In case of a
     disagreement between the translation and the original English
     version of this License, the original English version will prevail.


  9. TERMINATION

     You may not copy, modify, sublicense, or distribute the Document
     except as expressly provided for under this License.  Any other
     attempt to copy, modify, sublicense or distribute the Document is
     void, and will automatically terminate your rights under this
     License.  However, parties who have received copies, or rights,
     from you under this License will not have their licenses
     terminated so long as such parties remain in full compliance.


 10. FUTURE REVISIONS OF THIS LICENSE

     The Free Software Foundation may publish new, revised versions of
     the GNU Free Documentation License from time to time.  Such new
     versions will be similar in spirit to the present version, but may
     differ in detail to address new problems or concerns.  See
     http://www.gnu.org/copyleft/.

     Each version of the License is given a distinguishing version
     number.  If the Document specifies that a particular numbered
     version of this License "or any later version" applies to it, you
     have the option of following the terms and conditions either of
     that specified version or of any later version that has been
     published (not as a draft) by the Free Software Foundation.  If
     the Document does not specify a version number of this License,
     you may choose any version ever published (not as a draft) by the
     Free Software Foundation.


ADDENDUM: How to use this License for your documents

   To use this License in a document you have written, include a copy of
the License in the document and put the following copyright and license
notices just after the title page:

     Copyright (C)  YEAR  YOUR NAME.
     Permission is granted to copy, distribute and/or modify this document
     under the terms of the GNU Free Documentation License, Version 1.1
     or any later version published by the Free Software Foundation;
     with the Invariant Sections being LIST THEIR TITLES, with the
     Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
     A copy of the license is included in the section entitled "GNU
     Free Documentation License."

   If you have no Invariant Sections, write "with no Invariant Sections"
instead of saying which ones are invariant.  If you have no Front-Cover
Texts, write "no Front-Cover Texts" instead of "Front-Cover Texts being
LIST"; likewise for Back-Cover Texts.

   If your document contains nontrivial examples of program code, we
recommend releasing these examples in parallel under your choice of
free software license, such as the GNU General Public License, to
permit their use in free software.

@end example

@c
@c  INDEX
@c
@ifnottex
@node Index, , GNU Free Documentation License, Top
@end ifnottex
@chapter Index
@printindex cp
@bye

