@Device(PostScript)
@Style(
	Hyphenation On,
	TopMargin 1 inch,
	BottomMargin 1.5 inch,
	Spread 1,
	WidowAction Force,
	Font TimesRoman,
	Size 12
)

@make (report)
@begin(titlepage)
@begin(titlebox)
@majorheading(@i(Foundation) Library)
@center[@value(date)]
@end(titlebox)
@copyrightnotice(Eric Nitzberg and William D. Cattey)
@begin(ResearchCredit)
@center(@b(Abstract))

@modify(heading, below 1)

@i(Foundation) is a library 
used to store, manipulate, and establish interdependencies
among data elements in arrays.  It maintains interdependencies when the
arrays change in content or size.
This document shows C programmers how to use the @i(Foundation) library
of data structures, macros, functions, and applications to create and manage
interdependencies among data.
@end(ResearchCredit)
@end(titlepage)

@chapter(Overview)

Originally, @i(Foundation) was to be a C library that would provide
data structures and management tools to simplify handling
interdependent character texts.  For example, if an author writes an
outline, then writes an article from the outline, and later decides to
switch the order of 2 sections of the outline, the article must also be
re-arranged.  The outline and the article are interdependent texts.  An
application could be written, using @i(Foundation), that would
@i(automatically) change the article if the outline were re-ordered.

Redisplay is an example of interdependency among texts--text in a
buffer, and text on the screen.  Changes in the character buffer must
be made on the screen.  In a windowing environment, newly 'exposed'
windows (windows that are raised to the top of a heap of overlapping
windows) must contain the proper text.  An editor program was written
using @i(Foundation) that allowed arbitrary combinations of displayed
fonts on the screen;  this showed @i(Foundation)'s power in managing
complex interdependencies.

As the @i(Foundation) library evolved, generality became more
important.  Data other than character text were supported.  Now,
@i(Foundation) handles interdependent data in general, allowing
programmers to establish and manage dependencies among data in arrays
of C language data types and structures, for example, bitmaps,
integers, coordinates, or lists.  This generality opens many
possibilities for applications.  Any application that requires
interdependency among arrays of data is ideal for @i(Foundation).

This document is intended for C programmers who want to know how to use
the @i(Foundation) library of data structures, macros, functions, and
applications to make their own applications. It also presents some of
the philosophy behind @i(Foundation).

@section(What constitutes interdependency?)

A dependency exists between 2 arrays when a change in one causes a
change in the other.  In the redisplay example, the contents of the
character buffer and the text on the screen are held in 2 separate
arrays.  Since changing the character buffer's contents means changing
what is displayed on the screen, the arrays are interdependent.

@i(Foundation) manages dependencies through the @i(propagator).  The
propagator communicates between dependent arrays.  If array X changes,
it calls the propagator which notifies array Y (dependent on X) of the
change, and runs array Y's @i(handler) (a C language program).  Array Y
then knows what changes to make, if any.


@section(Objectives of the @i(Foundation) library)


The following are the primary objectives of Foundation:

@begin (itemize)

To provide a library on which applications can be run that deal with
interdependent arrays.  Modifications made to one array will
automatically affect other arrays that dependent on it.

To give high enough performance so that all applications will run with
acceptable interactive response time.

To provide queueing and scheduling (with redundancy elimination) for
data propagation among the various data structures.

@end (itemize)

The queuing and scheduling objective has only been partially met in the 
current version of @i(Foundation).

@section(Organization of the library)

The @i(Foundation) library contains 4 main components:

@begin(description)

Data Structures@\The library defines some low level data structures that were 
designed for management of interdependencies.

Propagator@\The propagator notifies data structures of changes in shared data.

Arops@\@i(Array operators).  C language macros that provide means to manipulate
(create, widen, delete, etc.) interdependent arrays, maintaining their 
interdependencies.

Raw@\A way of encapsulating various data types so they can be manipulated
generically.  This allows common functions to work with various data types.
It also makes @i(Foundation) portable.

@end (description)




@Chapter(@b(Data structures))

@section{Introduction to @i(Foundation)'s data structures}

@i(Foundation)'s data structures are difficult to explain because they
are all defined in terms of one another.  To understand any of them,
one must know about all the others.  For this reason, short definitions
for the key data structures are listed below, before the more detailed
descriptions.  These data structures work together to provide a system
for managing interdependencies.

@begin (itemize)

Region:  A structure providing a view on an array of data.  Regions
help manage interdependencies and data propagation.  Regions can hold
data of varying forms including user defined data types.  Regions are
sometimes used to refer to other regions, creating a hierarchy.

Array:  The arrays used by @i(Foundation) are just like C arrays except
that they are always exactly the right size to hold their contents, and
are resized when elements are added or deleted.  An array is the data
component of a region, so arrays are accessed through the regions in
which they are contained.

Raw:  A data type that hides the specific format of data, allowing it
to be accessed generically.  This allows dependencies between character
text, bitmaps, tables, and other forms of data to be manipulated by
common functions.

Zone:  A structure that provides a way to look at part of the data in a
region, instead of all the data at once.  A zone defines a subset of a
region's data array.  It is the fundamental way of establishing a
dependency on the the data in a region.

Ref:  A structure that contains information used by the propagator to
determine which zones need to know about changes made in a certain
region.

@end (itemize)

@section(Arrays)

Conventional arrays are indexed collections of data elements.  In C,
for example, manipulating arrays is easy.  Space for the maximum
expected number of elements is allocated in memory (to hold the whole
array) using malloc, and simple C syntax is used to manipulate the
components of the array.  The size of a C array is fixed.

Unlike C arrays, @i(Foundation)'s arrays are always exactly the right
size to hold their contents.  This makes it easy to to iterate over the
contents of an array.  The implementation of arrays in @i(Foundation)
is done efficiently through @i(Foundation's) own customized version of
@b(malloc).

Managing @i(interdependent) dynamic arrays is complex.  For example, if
part of one array is changed, the array may change size, and references
to data at certain positions in the array must be offset.  This is made
even more difficult if the arrays are of different data types.

@i(Foundation) deals with this situation by putting each array in a
@i(region) that contains other data useful to managing the array, and
by defining some generic C macros called @i(arops) (short for array
operators) that make changes in arrays.  When arops make changes, they
automatically call the propagator which notifies dependent regions.
This provides a way of making certain that dependent arrays are
notified whenever changes are made.  The arops themselves are useful
routines for manipulating dynamic arrays.

By using the Raw type, @i(Foundation) supports many data types, and
allows user defined types.  Because Raw is such an important concept in
@i(Foundation's) arrays, this section has 2 parts:  one describing the
Raw type, and one describing arops.

@subsection(The @b(Raw) data type)

The @b(Raw) data type enables one set of generic array operators to handle
arrays of varying content type.  @b(Raw) is a C language union type.

@begin(fileexample)
typedef union Raw
{
   Ann_type *Raw_Ann_type;
   Char *Raw_Char;
   Handler *Raw_Handler;
   Region *Raw_Region;
   char *Raw_char;
   char *Raw_sanitycheck;
   fontI *Raw_fontI;
   int Raw_value;
   struct font *Raw_font;
   struct r_ref *Raw_r_ref;
   struct ref *Raw_ref;
   struct w_ref *Raw_w_ref;
   struct zone *Raw_zone;
} Raw;
@end(fileexample)

Most components of @b(Raw) are pointers to structures, and thus they are
not very large.  There is a @b(Raw) value that is int, and one called
@b(sanitycheck) that the programmer must make equal in size to the
largest type held in the @b(Raw) union.  The @b(sanitycheck) component is
used by the @i(Foundation) @b(Makefile) for error checking.  If a data type
in @b(Raw) is larger than @b(sanitycheck), the @b(Makefile) complains.

The @b(Raw) type prevents having to re-compile the whole system when a new
data type is supported, unless the new data type is larger than
@b(sanitycheck).  Because data types are always addressed through their
proper names, pointer arithmetic works without casting.

@subsection[Array operators (arops)]

Arops are macros that dynamically manipulate size and contents of
arrays while maintaining dependencies between them.  The file
@b(arops.gen) contains generic arops that manipulate @i(Foundation's)
arrays.  From that file, the @i(Foundation) @b(Makefile) knows how to
generate a set of specific arops for each type of data being managed.
These specific arops are put into a file called @b(TYPE).apub (where
@b(TYPE) is replaced by the actual data type).  The macros in the .apub
file can be used by any C program that manipulates data arrays of type
@b(TYPE).  Macros are used instead of functions for efficiency and
speed.  They also make it easier to add arops for new data types since
the macros can be included as a header file rather than separately
compiled.

The arops are described in the following paragraphs.  Remember that when
@i(Foundation) generates specific arops, @b(TYPE) is replaced with the
data type being managed.

It must be possible to create new, empty arrays, and to destroy arrays
that are no longer needed.  The @b(TYPE_new) and @b(TYPE_destroy) macros
perform these operations.

The @b(TYPE_dataof) macro provides an easy way to look at an array in a
region.  The @b(TYPE_allof) arop provides the body of a C 'for' loop
for iteration over an entire array.

To determine the size of an array, the @b(TYPE_size) arop is used.  The
@b(TYPE_end) macro returns the index of the last element of an array.
This helps programmers avoid fencepost errors.

Five arops handle resizing arrays. The most basic is @b(TYPE_realloc).
It resizes an array, and may also move the array to a new block of
memory.  The other resizing arops all use @b(realloc), thus they may, by
side effect, move the array being resized.  Enlarging arrays is done
with @b(TYPE_widen_pre) and @b(TYPE_widen_post).  The @b(TYPE_delete)
arop manages deleting sections of an array. The @b(TYPE_addh) arop is
used for adding a single new element to the high end of an array.

One other arop, @b(TYPE_split), makes one array into two.  This is
especially tricky because after the split, all references to the old
array must have been properly divided between the old and the new.

Here is a list of arops, and how they work.

@begin(itemize)

@b(TYPE_new)(@i(region))@\Puts a pointer to an empty array (given by
malloc) of the particular @b(TYPE) into the data component of
@i(region) (see section on regions).  Giving a null pointer as a region
is a @b(serious) programming error.  It causes an error message to be
displayed, and core to be dumped.

@b(TYPE_destroy)(@i(region))@\Frees the array held in @i(region) making
elements stored in the array inaccessible.

@b(TYPE_dataof)(@i(region))@\Returns a pointer to the first element of
the array in @i(region).  This arop is the used in the same way that
region->data.Raw_TYPE could be used to get a pointer to the array held
in the data component of region (data.Raw_TYPE refers to the specific
TYPE in the Raw union).  Standard C array reference by bracket notation
and pointer arithmetic is used with @b(TYPE_dataof) to manipulate the
elements of the array.

@b(TYPE_size)(@i(block))@\Where @i(block) is any dynamically allocated
block of data, its size is measured in bytes, and then divided by the
sizeof(@b(TYPE)).  Although @b(TYPE_size) is almost always applied to
the @b(data) component of a region, this arop remains as it was first
developed:  a way to find the size of any block returned by
@i(Foundation's) version of @b(malloc).  Perhaps in the future,
@b(TYPE_size) will be converted to take a region as its argument always
looking at the region's @b(data) component.  Currently, to find the
size of a region's array, use @b(TYPE_size(TYPE_dataof@i((region)))).

@b(TYPE_end)(@i(block))@\Similar to @b(TYPE_size) except that it
returns the index of the last element in @i(block).  If the block is
empty, it returns -1.

@b(TYPE_allof)(@i(region, count))@\The body of a C 'for' loop for
iteration over the entire array in @i(region), using @i(count) just as
a variable to count on.  The variable used as @i(count) must be
declared (as @b(int)) elsewhere.  @b(TYPE_allof) is used only in a
'for' loop in this way:

@end(itemize)

@begin(fileexample)
for (@b(TYPE_allof)(@i(region, count))) {...}
@end(fileexample)

@begin(itemize)

@b(TYPE_realloc)(@i(region, newsize))@\Calls the storage allocator to
resize the array in @i(region) to @i(newsize).  If the data component
of the region points to NULL, an array is created.  The @b(realloc)
macro is called by the higher level macros @b(delete, widen_pre,
widen_post,) and @b(addh).  The @b(realloc) operation may return having
copied the contents of the array into a different block of memory.
This means arrays must always be accessed through the regions that hold
them.  Saving pointers into the arrays themselves, therefore, is a big
mistake, because the arrays may move if they are resized!

@b(TYPE_widen_pre)(@i(region, element_number, count))@\Enlarges the array in
@i(region) by @i(count) elements, starting just before @i(element_number),
shifting the data down as necessary.  The new space is filled with zeros.

@b(TYPE_widen_post)(@i(region, element_number, count))@\Same as
@b(TYPE_widen_pre), but enlarges the array starting just after
@i(element_number).  The distinction between widen_pre and widen_post
is important if the array is broken into subsets (zones--described
fully below).  A @b(widen_post) after the last element in a subset means
the new space belongs to the same subset, @i(not) to the adjacent one.
If a @b(widen_pre) is done to the beginning of a subset, the new space
belongs to that same subset, @i(not) the subset just before.  The
ability to control in which subset a new element is placed is very
important to applications using dependencies.

@b(TYPE_delete)(@i(region, element_number, count))@\Removes @i(count)
elements from @i(region's) array, starting with (including)
@i(element_number), and resizes the array so it is smaller.

@b(TYPE_addh)(@i(region, new_element))@\Adds an element to the high end of
the array.  The @i(new_element) is stored after the element with the highest
index, becoming the new element of the highest index.

@b(TYPE_split)(@i(region, element_number))@\Splits the array contained
in @i(region) into two arrays.  The split occurs just before
@i(element_number).  A new region is created to hold the new array, and
the original region is resized smaller.  To truly understand how
@b(TYPE_split) works, a better knowledge of regions is necessary.
@b(TYPE_split) is described more fully later.

@end(itemize)

It was decided not to use generic functions for accessing or
overwriting data (get and set functions).  C provides a powerful and
fast way of manipulating data through pointers.  Array elements are
manipulated using C pointer arithmetic and bracket notation with the
@b(TYPE_dataof) arop.  For example, to set the third character of
region foo to 'b', use:

@example{char_dataof(foo)[3] = 'b';} or
@example{char_dataof(foo) + 3 = 'b';}

It is up to the programmer to keep track of array bounds, and avoid
accessing beyond them.  There are  no bounds checks in arops, but
@i(Foundation)'s own version of @b(malloc) has two debugging modes.  The
first, @b(rcheck), only looks at 1 word at the beginning and end of a
block.  The other, @b(scribblecheck), is more thorough, but is time
consuming.  The @b(rcheck) and @b(scribblecheck) functions are
described more fully in the chapter on storage allocation.


Because the actual C code that defines these arops provides the most
factual explanation, the code is included in appendix @ref(arops.gen).

@i(@b(NOTE:  Since arrays may be moved if they change size, they are
always accessed through the regions that hold them.  This means that
saving a pointer into an array, and accessing the array through the
pointer when the array can resize is a ghastly error!))

@section(Regions)

A @i(region) is C language structure that provides a view on @b(Raw)
data (any type in the @b(Raw union), and information about that data.
Regions are designed specifically to manage dependencies among data.
Since @b(Raw) encapsulates many data types, regions are used in several
different ways.  For example, some regions hold arrays of text, some
hold information that refers to other regions.  Because regions are
used in such varying ways, the first part of this section is devoted to
describing the region's structure.  Later parts explain how regions are
used with different kinds of data.

@subsection(The structure of a region)

Here is the definition of a region structure in C.

@begin(fileexample)
typedef struct region
{
   int    type;
   char * parms;
   struct region *  deps;
   Handler op;
   Raw     data;
} region;
@end(fileexample)

The @b(type) component determines three things: whether this region
needs data propagation, what type of data the region holds, and how the
region is used.  This information is very useful to the propagator, and
to applications that need to quickly find out specifics of a region.

The @b(type) is an @b(int) that is divided into two bitfields.  The three
lowest order bits determine if this region needs propagation.  If it
doesn't, the zero bit is set.  If it does, the one bit is set.  The two
bit is included in this bitfield for experimental reasons, and is
currently unused.  It remains for further expansion.

The symbolic representations used to set the zero, one or two bits are,
respectively, PROP_NULL, PROP_REGION, and PROP_FRAGMENT.  These are
defined in propagate.c, (see appendix @ref(propagate.c)) and are used
in masking operations to set the correct bit in the @b(type).

The other bitfield in @b(type) implicitly indicates how the region is
used, and what kind of data it holds.  At the time this document was
written, the following types of regions were defined:

@begin(fileexample)
TYPE_TEXT
TYPE_REF
TYPE_DOCUMENT
TYPE_WINDOW
TYPE_LINE
TYPE_FORMAT
TYPE_ANNOTATION
TYPE_KILL
TYPE_FILE
@end(fileexample)

Each @b(TYPE) of region differs from the rest in the way its components
are used.  Some hold different data types and others differ only in the
way their @b(parms), @b(op), or @b(deps) components are used.

Since regions have different uses, each supports its own set of
internal state parameters (like instance variables in Smalltalk
Objects) in the form of the @b(parms) component.  For example, if a
region's data is the text contained in a window, window parameters
(foreground color, window size, etc.) would be stored in @b(parms).
The @b(parms) component is a C language @b(char *) generic pointer that is
cast to the appropriate @b(struct *) when used.  To create parameters,
use the generic @b(New) macro (part of @i(Foundation's) version of
@b(malloc)).

@begin(fileexample)
New(TYPE)
@end(fileexample)

This returns a pointer@footnote(A pointer to data type @b(TYPE), as
opposed to a pointer to @b(char), @b(int), etc.) to a block of memory
that is the same size as @b(TYPE).  Here is an example of how @b(New)
can be used to create a @b(parms) component for a window-holding
region.

@begin(fileexample)
typedef struct window_parms 
{
   int foreground;     /* Foreground color */
   int background;     /* Background color */
   ...
} window_parms;

window_region->parms = (char *)New(window_parms);
@end(fileexample)

In this example, the @b(New) macro allocates one block in memory of
size @b(window_parms), and returns a pointer to that block.  That pointer
is put into in the @b(parms) component of window_region.  The ellipsis
indicate that any number of components may follow.  Only two are listed
here to simplify the example.

The macro @b(EXTRACT) is used for getting and setting components in the
@b(parms) of a region.  It can appear on either the left or right side of
an assignment.

@begin(fileexample)
#define EXTRACT(TYPE, REGION, PARM) \
	((TYPE)REGION->parms)->PARM
@end(fileexample)

Here is an example of the use of @b(EXTRACT).  The @b(reverse_video)
function switches the @b(foreground) and @b(background) components of the
window_parms struct that hangs off the @b(parms) component of
window_region.

@begin(fileexample)
typedef struct window_parms *Window_parms  /* Syntactic sugar
                                            * for casting.
                                            */
reverse_video(window_region)
Region window_region;        /* Example region */
{
   int temp;        /* Temporarily holds foreground color */

   temp = EXTRACT(Window_parms, window_parms, foreground);
   EXTRACT(Window_parms, window_region, foreground) =
   EXTRACT(Window_parms, window_region, background);
   EXTRACT(Window_parms, window_region, background) = temp;
}
@end(fileexample)


@b(Deps) is a pointer to another region called a @i(region of
dependencies).  It is described fully in the section about ref-holding
regions.

The next component of a region is @b(op). The @b(op) is of type
@b(Handler).  It points to a C procedure.

@begin(fileexample)
typedef int (*Handler)();
@end(fileexample)

Handlers are C routines called by the propagator to notify a region of
a change in the data of another region that it depends on.  Handlers
are discussed in more detail in the chapter on creating and using
dependencies.

The @b(data) component of a region holds the @b(Raw) data that the region
manages.

@subsection(Low-level regions)

Although all regions hold data of type @b(Raw), they can be used very
differently.  Some regions just hold the data being managed by an
application.  This might include character text, bitmaps, tables, or
other types.  Regions that serve to hold this kind of data are called
@i(low-level) regions.

@subsection(Zone-holding regions)

A @i(zone) points at a subset of the data in a region.  Thus, the
zone-holding region (a region containing an array of zones in its
@b(data) component) groups these subset into a new semantic view on the
data in several regions.

The zone is the fundamental expression of a dependency.  Each zone is
dependent on the data in some other region.  For example, if a
text-holding region contains a sentence, and a zone in a zone-holding
region points at a subset of that text (a phrase), if text is deleted,
the zone may need to be updated so that it still points to the right
place.  It is the propagator's first responsibility to keep zones
pointing to the right subset indices in the depended upon data.  This
is explained further in the section on the propagator.  Here is the C
structure of a zone.

@begin(fileexample)
typedef struct zone
{
   struct region *    region;
   int start;
   int length;
   Raw derived;
} zone;
@end(fileexample)

The @b(region) component is a pointer to the region in which this zone
defines a subset.  This can be a region of arbitrary type.  If it is a
low-level region containing text, the zone defines a subset in the
text.  If @b(region) is a zone-holding region, this zone points at a
subset of the array of zones in @b(region), thus creating a hierarchy.

Text, for example, could be broken down into low-level regions holding
words, zone-holding regions that look at groups of words (lines),
zone-holding regions that look at groups of lines (paragraphs), and
zone-holding regions that look at groups of paragraphs (the document).

The @b(start) is the index of the first element of the subset that this
zone defines within the @b(region).

The @b(length) is the number of elements that this zone encompasses.  

The @b(derived) component may be used to store information about this
zone.  For example, if this zone points at a subset of data in a
text-holding region, the @b(derived) might indicate the font type for
the text of this zone.  The @b(derived) is of type @b(Raw), so it can be
any type in the @b(Raw) union.

Zones obey all the arops, but the arops are implemented slightly
differently for zones than for other data.  Therefore, there is no
@b(zone.apub) file.  Instead, there is @b(zones.c) that contains arops
specially adapted for zone manipulation.

A @b(DOCUMENT) region is an example of a zone-holding region referring
to a char-holding region.  Every time a new char-holding region is
created, its data is divided into at least 1 zone that is added to the
array of zones in the @b(DOCUMENT) region.  One @b(DOCUMENT) region can
refer to any number of char-holding regions.  If each of the
char-holding regions contains a line of text, printing the whole
document is just a matter of following the zones of the @b(DOCUMENT)
region and printing the given subsets of the char-holding regions in
sequence.

@subsection(Ref-holding regions)

The @b(deps) component of each low-level region points to another
region called a @i(deps) region.  (A region of dependencies).  The
@b(deps) region contains, as its data, an array of structures called
@i(refs).  The ref array closes the circle of communication between
low-level regions and higher-level regions by enabling programs (like
the propagator) to quickly find all the zones that depend on a
low-level region.  Suppose char-holding region X points to deps region
Y.  Region Y would contain an array of refs, each ref containing
information about regions that depend on X.  A @b(DOCUMENT) region, for
example, would depend on region X because its own data depends on the
data of several char-holding regions, including region X.

@begin(fileexample)
typedef struct ref
{
   struct region * region;
   int start;
   int length;
} ref;
@end(fileexample)

The @b(region) component of each ref points to a zone-holding region
that depends on the low-level region (like a @b(DOCUMENT) region that
has zones depending on several char-holding regions).  The @b(start) is
the index of the first zone (in the dependent region's array of zones)
that cares about the low-level region.  The @b(length) is the number of
contiguous zones that depend on the low-level region's data.

@begin(figure)
@blankspace(5 inches)
@caption(Use of the deps region.)
@tag(deps.ps)
@end(figure)

Figure @ref(deps.ps) shows how the deps region makes links between low
and high-level regions.


@section(The TYPE_split arop)

Now it is possible to explain the @b(split) arop.  The @b(TYPE_split)
arop is used when a particular low-level array would otherwise become
too large for an application to handle conveniently.  The
@b(TYPE_split)(@i(region, element_number)) arop separates the array in
@i(region) into two pieces.  It begins the split just before element
@i(element_number).  A new region is created to hold the new array, and
the original region is resized smaller.  The difficulty in splitting a
region is that other regions may have zones that depend on it.  This
means that the list of dependencies in the deps region has to be
edited, and some of the refs must be mapped to the newly created
region.  All of the regions that are listed in the deps region (for
example, a @b(DOCUMENT) region) must also be re-mapped and re-indexed.
@b(TYPE_split) performs all this.

@begin(figure) 
@blankspace(4 inches) 
@caption[Before:  char_split(text_region, 28)] 
@tag(split_region_before.ps) 
@end(figure)

@begin(figure)
@blankspace(5 inches)
@caption[After:  char_split(text_region, 28)]
@tag(split_region_after.ps)
@end(figure)

Figures @ref(split_region_before.ps) and @ref(split_region_after.ps)
show a text-holding region with three different fonts before and after
a @b(split) operation.

There is no @b(merge) arop, although one may be added eventually.  A
merge would only happen when 2 adjacent zones with equal @b(derived)
components exist in regions of the same @b(TYPE).  It was deemed too
hard to write a generic routine that would handle comparing @b(derived)
components of regions, since the lengths and internal structure of all
possible @b(derived) components can't be known: they could be integers,
floats, chars, structs, etc.

@section(Example:  the editor built on @i(Foundation))

An editor has been written on @i(Foundation) that is a good example of
how the different uses for regions work together.  It uses the various
structures to allow arbitrary fonting within a line, and annotations
can be created that are 'attached' to any part of text.  Inserting and
deleting text happens very quickly, and doesn't cause annotations to be
misplaced.

Here is a simplified explanation of how the editor works.  Each line of
text is held in a char-holding region.  A higher-level region, a
@b(DOCUMENT) region, contains an array of zones.  Each zone points to
part, or all of the data in a char-holding region.  The font for each
zone hangs off the zone's @b(derived) component.  For each font change
along a line, a different zone exists referring to a continuous span of
characters having the same font.  The @b(derived) component of each
specifies the font type.  To print out the whole document with proper
fonting, one need only step sequentially through the zones in the
@b(DOCUMENT) region.  They point to the text in all of the relevant
char-holding regions.

The deps region for each char-holding region contains an array (of
refs) that indicates what other regions depend on it.  One region that
depends on it is the @b(DOCUMENT) region.  For example, if a character
is deleted from a line of text, the @b(length) component of a zone in the
@b(DOCUMENT) region must be shortened.

Another region that depends on the text-holding region is the
@b(ANNOTATION) region.  It is also a region of zones, like the
@b(DOCUMENT) region, but it only contains zones that are to be
annotated.  The annotation itself is accessible through the @b(parms)
component of an @b(ANNOTATION) region.

@begin(figure)
@blankspace (6 inches)
@caption(Internal workings of the @i(Foundation) editor.)
@tag(editor.ps)
@end(figure)

The editor is illustrated in figure @ref(editor.ps).  The word 'midnight'
is in bold font.  It is also annotated.

@section(Making new data types)

To make a new data type in @i(Foundation), the following steps must be
followed:

@begin(enumerate)

The new type must be be declared.

The C file that uses the type must be included in the @i(Foundation)
@b(Makefile).

The new type must be @b(#include)'ed in the C file that uses it.

@b(Raw.h) must be modified to include the new data type.

@end(enumerate)

For example, to make a new data type called @b(window), create a file
that defines the @b(window's) structure, like this:

@begin(fileexample)
typedef struct window {...} window;
@end(fileexample)

In practice, the structure can have any name, and any number of
components.  The declaration must be stored in a file whose name has
the suffix @b(.decl).  The @i(Foundation) @b(Makefile) will automatically
generate a set of specific arops of type @b(window)_@i(arop) when your
@b(.c) file is added and includes the line:

@begin(fileexample)
#include <window_type.apub>
@end(fileexample)

A line reading,

@begin(fileexample)
region *Raw_window;
@end(fileexample)

must be added to the union in the file @b(Raw.h).

After these  things have been done,  @i(Foundation) will handle the new
datatype in the same way that it handles any other data type in the @b(Raw)
union.

@chapter (Creating and using interdependencies)

This section describes the propagator, and how it works with the data
structures described earlier.  A more thorough understanding can be
gained by reading the C code for @b(propagate.c).  This is included in
appendix @ref(propagate.c).

@section (The propagator)

The propagator notifies regions of changes in data that they depend upon.
The array operators tell the propagator about the changes they make on
arrays.  When they make changes in arrays, arops use this call:

@begin(fileexample)
propagate(@i(region_that_changed, change_type, element_index, count))
@end(fileexample)

The @i(region_that_changed) is the region whose array was directly changed by 
an arop.

The @i(change_type) is the kind of change that the operator made.  This can
be one of 5 things:

@begin(itemize)

@b(P_TOUCH)@\A change in the content of an array has been made.

@b(P_WIDEN_PRE)@\The widen_pre arop has enlarged an array (beginning just
before @i(element_number) and has filled the new space with zeros.

@b(P_WIDEN_POST)@\The widen_post arop has enlarged an array (beginning just
after @i(element_number) and has filled the new space with zeros.

@b(P_DELETE)@\Element(s) have been deleted from the array in
@i(region_that_changed).  The array is smaller, and @i(count) elements
that were at @i(element_index) no longer exist.  This means that
anything needing to know what those elements were must keep an
independent copy of the array that can be compared with the
@i(region_that_changed).

@b(P_SPLIT)@\@i(region_that_changed) was split starting just before
@i(element_number).

@end(itemize)

The @i(element_index) is where in the array the change occurred.
The @i(count) is how many elements are affected.

Note that there is no @b(P_REALLOC message).  The @b(TYPE_realloc) arop
does not call the propagator.  There is no @b(P_ADDH) message;
@b(TYPE_addh) calls propagate twice.  Once with @b(P_WIDEN_PRE) and
once with @b(P_TOUCH).

Based on this information, the propagator knows which regions should be
changed, and how.  Since arrays are always manipulated using arops,
propagation occurs automatically.  An application program that modifies
the content of an array should call the propagator with the @b(P_TOUCH)
change type after making a set of changes.

@b[NOTE:  It is essential that an application that modifies an array
without using an arop calls the propagator with the @b(P_TOUCH) change
type after it has made changes.  This is because the are no get and set
arops.]

@section[The @b(add_prop) and @b(del_prop) functions]

The @b(add_prop) and @b(del_prop) functions establish and remove
dependencies between regions.  The word @i(prop) denotes that the
dependencies are for use by the propagator.  The syntax for
@b(add_prop) and @b(del_prop) is as follows:

@begin(fileexample)
add_prop(@i(region, dependent_region, zone_index))
@end(fileexample)

A call to @b(add_prop) adds a zone to the list of dependencies in the
@b(deps) component of @i(region).  If the zone added is next to one
that is already in a ref, the pre-existing ref's zone is widened to
include the new zone.  If the new zone is not next to any zones in
existing refs, a new ref is created.  This new ref contains a pointer
to the @i(dependent_region) that cares about @i(region).  The
@i(zone_index) indicates which specific zone in the dependent region
depends on @i(region).  The @b(del_prop) function uses the same syntax
to remove dependencies.

For example, to make the @b(DOCUMENT) region @b(doc_r) depend on
the char-holding region @b(text_r), use:

@begin(fileexample)
zone_addh(doc_r, text_r);
add_prop(text_r, doc_r, region_end(doc_r));
@end(fileexample)


@section(Handlers)

The @b(op) component of a region is of type @b(Handler).  The
@b(Handler) type is a pointer to a C language procedure, a
@i(handler).  Handlers allow each region to do a different operation on
its data when it is notified of changes in regions it depends on.  When
the propagator notifies a region that a zone it depends on has changed,
it calls the region's handler.  The handler for a region knows what to
do depending upon what kind of change was made.

For example, suppose a char-holding region holds a line of a document,
and an @b(ANNOTATION) region depends on a zone in that line.  When a
change is made in the text, the propagator is called.  It then calls
the handler of the @b(ANNOTATION) region.  It sends to the handler the
zone that was changed, and in what way (eg, deleted from, split, etc.)
The @b(ANNOTATION) region's handler knows what changes, if any, to make
on the annotation region's array of zones (for example, if all the
zones and all the text of an annotation dependency are deleted, the
handler can take care of destroying the annotation).  Not all regions
have handlers.  Some have NULL, or a pointer to @b(NULL_proc) as a handler,
if the region only needs bounds updating.

Handler looks like this:

@begin(fileexample)
typedef int (*Handler) ();
@end(fileexample)

A region called @i(prop) (created by the propagator) contains
information sent to handlers so they may do their work.  The prop
region is a zone-holding region.  To avoid defining another data type,
the existing structure for a zone is used by prop-regions, but the
components are used differently than they are in other zone-holding
regions such as @b(DOCUMENT) or @b(ANNOTATION) regions.  The @b(region)
component of the zone held in prop points to the zone-holding region
that cares about the low-level one that changed.  The zone's
@b(derived) component is used to tell which zone in @b(region) is
affected by the change.  The prop zone's @b(start) and @b(length)
components show where in the data array of the low-level region the
change began, and how many elements were affected.  Note that when
the propagator is called, the affected low-level region, @i(not) the zones
in the region that were affected, is sent as an argument.  The
propagator determines which zones within the region it is sent have
changed, and it makes a prop-region for each zone.

The propagator hangs a struct called @i(prop_parms) off of the @b(parms) 
component of a prop-region.  The prop_parms structure looks like this:

@begin(fileexample)
typedef struct prop_parms
{
   int type;
   int priority;
   Handler function;
}  prop_parms;
@end(fileexample)

The @b(type) contains the type of change made to the dependent region
(such as @b(DELETE), @b(SPLIT), etc.).  The @b(function) is the handler
to which this particular prop is sent.  The @b(priority) is currently
unused, but may someday be used to prioritize operations within a
queue.

@begin(figure)
@blankspace(4 inches)
@caption[Result of "propagate(text_region, P_DELETE, 10, 2)"]
@tag(prop_parms.ps)
@end(figure)

Figure @ref(prop_parms.ps) shows the prop-region created if the two
characters @i('t) (apostrophe tee) were removed from a text region
containing, "A @b(fish) can't swim."

Each prop is created, a prop_parms structure is hung off its @b(parms),
and a zone (one constructed as per above) is stored in the @b(data)
component.  A single prop can represent changes made to several zones
by having several zones in its data array.  Currently, @i(Foundation's)
propagator only generates single-zone prop-regions, but in the future,
the propagator will assemble the propagations into a multi-zone prop
region, for efficiency.  After each prop is created, it is added to the
end of the @i(prop_queue).  This guarantees that all bounds are correct and
that the handlers are called in a consistent order on consistent data.
When props have been enqueued for all zones that depend on the change
sent to the propagator, they are dequeued in @i(first in, first out
order), and their handlers are called.

Here is a possible format for a handler:

@begin(fileexample, free)
example_handler(prop)
register region *prop;
{
   int type;
   
   type = EXTRACT((struct prop_parms *), prop, type);
   
   switch(type)
      {
      case P_TOUCH:
         do_touch (ZONEOF(prop, 0, region),
                   ZONEOF(prop, 0, derived),
                   ZONEOF(prop, 0, start),
                   ZONEOF(prop, 0, length));    
         break;

      case P_DELETE:
         ...;
         ...;
         break;
 
     /* Etc. */
      }
}


do_touch (zh_region, zone_index, start, length)
   register region *zh_region;  /* Zone-holding region */
   register int zone_index;
   int start;
   int length;
{...}
@end(fileexample)

The @b(ZONEOF) macro is defined in @b(zones.c).  It looks like this:

@begin(fileexample, leftmargin -.2in)
#define ZONEOF(REGION,INDEX,PIECE) zone_dataof(REGION)[INDEX].PIECE
@end(fileexample)

The @b(ZONEOF) macro looks at one component of a specific zone in a
region.  The @b(REGION) argument is the region that contains the zone.
The @b(INDEX) argument the index of the zone in @b(REGION)'s array of
zones, and @b(PIECE) is the component (@b(region, start, length), or
@b(derived)) within the zone.  Here, @b(ZONEOF) is used to parse the
prop-region into its various components.  These components are then
sent as arguments to a function (@b(do_touch) in this example) that
takes action on the reported change.  The @b(INDEX) is zero in the
example above because only one zone is sent.  Case statements in the
above example would be included for all the possible operations:
@b(P_TOUCH, P_DELETE, P_SPLIT, P_WIDEN_PRE,) and @b(P_WIDEN_POST).  The
@b(do_touch) code above is included as a reminder of the meanings of
the prop-region's zone components.

@section(Defining new region types)

@i(Foundation) allows programmers to define new region types by 
following these steps:

@begin(enumerate)

Add the new @b(TYPE) in a @b(#define) statement in @b(propagate.c) (appendix
@ref(propagate.c)).

Define a parameters struct for the region, and store it in a @b(.decl) file.

Write a handler for the region (if it needs one).  The file that contains
the handler may be either a specific application, or a file to be
compiled with an application.

The file containing the handler must be added to the @i(Foundation)
@b(Makefile).

Re@b(make) @i(Foundation).

@end(enumerate)

Suppose you want to make a region that holds a paragraph.  No such region
type is currently defined, so you must define it.  To do so, 
you must first add this line to the @b(TYPE) definitions in propagate.c:

@begin(fileexample)
#define TYPE_PARAGRAPH ((9<<USER_BASE) | (PROP_REGION<<PROP_BASE))
@end(fileexample)

This macro sets up a two bitfield word for use in the @b(type) component
of a region.  The lower bitfield in this case indicates that this region
should receive propagation.  The higher bitfield contains the number nine
which distinguishes this TYPE from the others (zero through eight are
already used by currently defined region types).

The USER_BASE and PROP_BASE are symbolic representations of integers
used to break @b(type) into correctly sized bitfields.  Currently they
are equal to three and zero, respectively.  Therefore, the above
operation creates a word whose three lowest bits are used for
propagation codes, (in this case, indicating that the region should
receive propagation).  The rest of the bits are used to store an
integer that makes this type unique.


Next, define a struct that will hold the region's parameters:

@fileexample[typedef struct para_parms {...} para_parms;]

Put the structure (in this example, para_parms, for @i(paragraph region 
parameters)) into a file with the suffix @b(.decl) 
(@b(para_parms.decl)).

If @b(paragraph_r) is to have a handler, code for the handler should be 
included in the application that uses the new region.  See the section 
on handlers for details on writing handlers.  Add the file containing the
new region's handler to the @i(Foundation) @b(Makefile).


Finally, re@b(make) @i(Foundation):

@begin(fileexample)
make
make binary
@end(fileexample)

@section(Using regions)

To use a region whose type is defined, you must do the following:

@begin(enumerate)

Use the @b(region_new()) function in @b(region.c) (appendix @ref(region.c)).

Set the region's @b(type) using a macro defined in @b(propagate.c).

Store a pointer to the region's handler in the region's @b(op) component.

Allocate space for the region's parameters struct and store a pointer to 
it in the region's @b(parms) component.

Set the each of the region's parameters.


Use @b(add_prop) and @b(del_prop) to create and destroy dependencies 
between this and other regions.

@end(enumerate)

An application that uses the @b(TYPE_PARAGRAPH) type, for example, would
first need to declare a variable of type @b(region), and use @b(region_new)
in an assignment:

@begin(fileexample)
region *paragraph_r;       /* Paragraph region */

paragraph_r = region_new();
@end(fileexample)

The @b(region_new) function is defined in @b(region.c).  It allocates
space for one instance of a region by using the @b(New) macro, then it
stores zeros in the new region's components.  It returns a pointer to this
new region.

Next, to set @b(paragraph_r)'s @b(type), use @b(TYPE_PARAGRAPH) (the macro
in @b(propagate.c) as defined above):

@fileexample[paragraph_r->type = TYPE_PARAGRAPH;]

To set @b(paragraph_r)'s @b(parms), first, the structure for
@b(para_parms) (it could have any name) should be defined in a file
@b(para_parms.decl).  Using the @b(New) macro, allocate memory for one
instance of @b(para_parms), and hang it off of @b(paragraph_r)'s
@b(parms) component:

@begin(fileexample)
paragraph_r->parms = (char *)New(para_parms);
@end(fileexample)

Then set individual parameters.

@begin(fileexample)
(((struct para_parms *)paragraph_r->parms)->@i(parameter)) = @i(newvalue);
@end(fileexample)

This is simplified by using @b(EXTRACT):

@begin(fileexample)
EXTRACT ((struct para_parms *), paragraph_r, @i(parameter)) = @i(newvalue);
@end(fileexample)

Next, @b(paragraph_r)'s @b(op) must point to a handler (if the region has
one):

@fileexample(paragraph_r->op = paragraph_r_handler;)

The @b(add_prop) and @b(del_prop) functions can then be used to create 
dependencies between the new region and others (see section on @b(add_prop)
and @b(del_prop)).

Once the region has been made, macros and functions defined in @b(region.c) 
are used to manipulate it.  Some of the code in @b(region.c) is like the
code for arops.

There is a @b(region_new) function (see above).
The @b(region_destroy) function takes a region as an argument, and frees
the block of memory that the region uses.  The @b(region_size, region_end) and
@b(region_allof) macros are just like their arop counterparts, but they
perform their calculations on a region's data array.  Using
@fileexample[region_size(@i(region))] is equivalent to using
@fileexample{zone_end(zone_dataof(@i(region)))}

The @b(EXTRACT) macro, and two others, @b(COPY_BLOCK) and
@b(COPY_FIELD) are defined in region.c.  The @b(COPY_BLOCK) macro
copies a block of memory into a newly allocated block.  The
@b(COPY_FIELD) macro copies a field of a structure (like the @b(parms)
of a region structure) to a newly-allocated field.

There is also a @b(region_dup) function that takes a region as an
argument, and makes a copy of it, returning a pointer to the copy.
The contents of all the region's components are copied verbatim from 
the original, except the @b(op) which is made a null pointer.

A copy of @b(region.c) is included in appendix @ref(region.c).

@Chapter (@b(Storage allocation))

@i(Foundation) contains its own copies of @b(malloc), @b(free), and
@b(realloc).  They are called like the standard UNIX system calls of
the same names.  A particular version of @b(malloc.c) was modified and
incorporated into @i(Foundation).  It contains an additional function,
@b(m_blocksize), that takes a pointer to something obtained through
@b(malloc) and returns the number of bytes it was asked to contain (its
@i(given) size).  It was installed for quickly determining the sizes of
things.  There are two debugging modes: @b(rcheck), and
@b(scribblecheck).  The first one, @b(rcheck), is for checking the
range of arrays allocated, and verifying that writes do not go beyond
the allocated bounds.  The second, @b(scribblecheck), writes a known
pattern into the blocks and scans the pattern to make sure that nobody
wrote into the block when it was supposed to be inactive.  The
debugging modes have two side effects.  Firstly, they find common
errors like freeing unallocated data, referencing through freed data,
and fencepost errors on the start or end of data blocks.  Secondly,
core dumps (due to memory allocation problems) are more meaningful with
these debugging modes enabled, and usually occur close to the site of
the corruption.

The storage allocator allocates blocks in sizes that are powers of
two.  Space for the header of the block is taken out, and the remaining
free space is given in the @b(malloc) request.  Two numbers are kept on
the size, the actual size and the @i(given) size, the latter being the
size the user asked for.  When the block is @b(realloc)'ed the number
recorded for the given size is changed, until the given size becomes
larger than the actual size, or smaller than one quarter the actual
size.  Whenever the given size exceeds the actual size, a block of
double the old size is allocated and the old contents are copied.  When
the given size is less than a quarter the actual size, a new block of
one quarter the size is allocated and the contents are copied.  Having
two binary orders of magnitude in the resizing function adds hysteresis
and cuts down the amount of copying.  The code in @b(malloc.c) is
profusely commented.  In practice, any deep understanding of the
particular tricks of @b(malloc), beyond those given here, should come
from reading the code.


@appendix (arops.gen) @label(arops.gen)
@begin(fileexample, leftmargin -.5in, free)
@include(/mit/found/src/arops.gen)
@end(fileexample)

@appendix (region.c) @label(region.c)
@begin(fileexample, leftmargin -.5in, free)
@include(/mit/found/src/region.c)
@end(fileexample)

@appendix (propagate.c) @label(propagate.c)
@begin(fileexample, leftmargin -.5in, free)
@include(/mit/found/src/propagate.c)
@end(fileexample)
