\name{BasicFunctions}
\alias{Ops}
\alias{Arith}
\alias{Math}
\alias{Math2}
\alias{Summary}
\alias{Compare}
\alias{Complex}
\alias{.makeBasicFunsList}

%- Also NEED an `\alias' for EACH other topic documented here.
\title{ Group Generic Functions }
\description{
  These are group generic functions.  Methods defined for them will be
  used for any of the specific functions belonging to the particular
  group, provided no specific methods override.

  These functions should never be called directly (a suitable error
  message will result if they are).
}
\usage{
Arith(e1, e2)
Compare(e1, e2)
Ops(e1, e2)

Math(x)
Math2(x, digits)

Summary(x, ..., na.rm = FALSE)

Complex(z)

}
%- maybe also `usage' for other objects documented here.
\arguments{
  \item{e1, e2}{ Arguments to the various binary operators. }

  \item{x}{ The argument to the \code{Math} or  \code{Summary} groups
      of functions.}
}
\details{

  The functions belonging to the various groups are as follows:
  \describe{
    \item{\code{Arith}}{\code{"+", "-", "*", "^", "\%\%", "\%/\%", "/"}}
    \item{\code{Compare}}{\code{"==", ">", "<", "!=", "<=", ">="}}
    \item{\code{Ops}}{\code{"Arith", "Compare"}}

   \item{\code{Math}}{\code{"log", "sqrt", "log10", "cumprod", "abs",
       "acos", "acosh", "asin", "asinh", "atan", "atanh", "ceiling",
       "cos", "cosh", "cumsum", "exp", "floor", "gamma", "lgamma",
       "sin", "sinh", "tan", "tanh", "trunc"}}
   \item{\code{Math2}}{\code{"round", "signif"}}

   \item{\code{Summary}}{\code{"max", "min", "range", "prod", "sum",
       "any", "all"}}

   \item{\code{Complex}}{\code{"Arg", "Conj", "Im", "Mod", "Re"}}
  }

All the functions in these groups (other than the group generics
themselves) are basic functions in R.  They are not by default generic
functions, and many of them are defined as primitives, meaning that
they do not have formal arguments.  However, you can still define
methods for them.  The effect of doing so is to create a generic
function with the appropriate arguments, in the environment where the
method definition is to be stored.  It all works more or less as you
might expect, admittedly via a bit of trickery in the background.  
  
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\keyword{internal}
\name{Classes}
\alias{Classes}
\alias{__ClassMetaData}
\title{Class Definitions}
\description{
Class definitions are objects that contain the formal definition of a
class of R objects.
}

\details{

When a class is defined, an object is stored that contains the
information about that class, including:

\describe{
\item{slots}{Each slot is a component object.  Like elements of a list
    these may be extracted (by name) and set.  However, they differ
    from list components in important ways.

    All the objects from a particular class have the same set of slot
    names; specifically, the slot names that are contained in the
    class definition.  Each slot in each object always has the same
    class; again, this is defined by the overall class definition.

    Classes don't need to have any slots, and many useful classes do
    not.  These objects usually extend other, simple objects, such as
    numeric or character vectors.  Finally, classes can have no data
    at all---these are known as \emph{virtual} classes and are in fact
    very important programming tools.  They are used to group together
    ordinary classes that want to share some programming behavior,
    without necessarily restricting how the behavior is implemented.
    }
  \item{extends}{The names of the classes that this class extends.  A
      class \code{Fancy}, say, extends a class \code{Simple} if an
      object from the \code{Fancy} class has all the capabilities of
      the \code{Simple} class (and probably some more as well).  In
      particular, and very usefully, any method defined to work for a
      \code{Simple} object can be applied to a \code{Fancy} object as
      well.

      In other programming languages, this relationship is sometimes
      expressed by saying that \code{Simple} is a superclass of
      \code{Fancy}, or that \code{Fancy} is a subclass of
      \code{Simple}.

      The actual class definition object contains the names of all the
      classes this class extends.  But those classes can themselves
      extend other classes also, so the complete extension can only be
      known by obtaining all those class definitions.

      Class extension is usually defined when the class itself is
      defined, by including the names of superclasses as unnamed
      elements in the representation argument to \code{\link{setClass}}.

      An object from a given class will then have all the slots
      defined for its own class \emph{and} all the slots defined for
      its superclasses as well.

      Note that \code{extends} relations can be defined in other ways
      as well, by using the \code{\link{setIs}} function.
      }
    \item{prototype}{Each class definition contains a prototype object
        from the class.  This must have all the slots, if any, defined by the
        class definition.

        The prototype most commonly just consists of the prototypes of
        all its slots.  But that need not be the case:  the definition
        of the class can specify any valid object for any of the
        slots.

        There are a number of ``basic'' classes, corresponding to the
        ordinary kinds of data occurring in R.  For example,
        \code{"numeric"} is a class corresponding to numeric vectors.
        These classes are predefined and can then be used as slots or
        as superclasses for any other class definitions.  The
        prototypes for the vector classes are vectors of length 0 of
        the corresponding type.

        There are also a few basic virtual classes, the most important
        being \code{"vector"}, grouping together all the vector
        classes; and \code{"language"}, grouping together all the
        types of objects making up the R language.
        }
}

}

\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\seealso{\code{\link{Methods}}, \code{\link{setClass}}, \code{\link{is}} \code{\link{as}} \code{\link{new}} \code{\link{slot}}}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\name{GenericFunctions}
\alias{GenericFunctions}
\alias{isGeneric}
\alias{isGroup}
\alias{removeGeneric}
\alias{standardGeneric}
\alias{getGenerics}
\alias{allGenerics}
\alias{dumpMethod}
\alias{existsFunction}
\alias{findFunction}
\alias{dumpMethods}
\alias{removeMethods}
\alias{signature}
\alias{setReplaceMethod}
\alias{callGeneric}
\title{Tools for Managing Generic Functions}
\synopsis{
isGeneric(f, where, fdef, getName = FALSE)
isGroup(f, where, fdef)
removeGeneric(f, where)
dumpMethod(f, signature, file, where, def)
existsFunction(f, generic = TRUE, where)
findFunction(f, generic=TRUE)
dumpMethods(f, file, signature, methods, where)
signature(\dots)
removeMethods(f, where)
setReplaceMethod(f, \dots)
getGenerics(where)
allGenerics(where)
callGeneric(\dots)
}
\usage{
isGeneric(f, where, fdef, getName = FALSE)

isGroup(f, where, fdef)

removeGeneric(f, where)

standardGeneric(f)

dumpMethod(f, signature, file, where, def)

existsFunction(f, generic = TRUE, where)

findFunction(f, generic=TRUE)

dumpMethods(f, file, signature, methods, where)

signature(\dots)

removeMethods(f, where)

setReplaceMethod(f, \dots)

getGenerics(where)

allGenerics(where)

callGeneric(\dots)

}

\description{
The functions documented here manage collections of methods associated
with a generic function, as well as providing information about the
generic functions themselves.
}

\section{Summary of Functions}{

\describe{
  \item{\code{isGeneric}:}{ 
    Is there a function named \code{f}, and if so, is it a generic?

    The \code{getName} argument allows a function to find the name from
    a function definition.  If it is \code{TRUE} then the name of the
    generic is returned, or \code{FALSE} if this is not a generic
    function definition.

    The behavior of \code{isGeneric} and \code{\link{getGeneric}} for
    primitive functions is slightly different.  These functions don't
    exist as formal function objects (for efficiency and historical
    reasons), regardless of whether methods have been defined for them.
    A call to \code{isGeneric} tells you whether methods have been
    defined for this primitive function, either on database \code{where}
    or anywhere in the current search list.  In contrast, a call to
    \code{\link{getGeneric}} will return what the generic for that
    function would be, even if no methods have been currently defined
    for it.
  
  }
  
  \item{\code{removeGeneric}:}{ 
  Remove the generic function of this name.  
  }
  \item{\code{standardGeneric}:}{ 
  Dispatches a method from the current function call for the generic function \code{fname}.  
  
  }
  \item{\code{getMethods}:}{ 
  The list of methods for the specified generic.  
  
  }

  \item{\code{dumpMethod}:}{ 
  Dump the method for this generic function and signature.  
  
  }
  \item{\code{existsFunction}:}{ 
  Is there a function of this name. If \code{generic==FALSE}, generic functions are not counted.

  
  }
  \item{\code{findFunction}:}{ 
  return all the elements of the search list on which a function
  definition for \code{name} exists.

  \emph{NOTE:} Use this rather than \code{\link{find}} with
  \code{mode="function"}, which is not as meaningful, and has a few subtle bugs from its use of
  regular expressions.
  
  }
  \item{\code{selectMethod}:}{ 
  Returns the method (a function) that R would use to evaluate a call to this generic,
with arguments corresponding to the specified signature.

f = the name of the generic function
sig = the signature of classes to match to the arguments of f.  
  
  }
  \item{\code{dumpMethods}:}{ 
  Dump all the methods for this generic.  
  }
  \item{\code{signature}:}{ 
  Returns a named list of classes to be matched to arguments of a
  generic function.
 
  }
  \item{\code{callGeneric}:}{ 
  In the body of a method, this function will make a call to the current
  generic function.  If no arguments are passed to \code{callGeneric},
  the arguments to the current call are passed down; otherwise, the arguments
  are interpreted as in a call to the generic function.
 
  }
}
}

\arguments{
  \item{f}{ The character string naming the function. }
  \item{where}{ Where on the search list of attached packages to look
    for functions or methods.  By default, use the whole search list to
    find the relevant object(s).  }

  \item{signature}{ The class signature of the relevant method.  A
    signature is a named or unnamed vector of character strings.  If
    named, the names must be formal argument names for the generic
    function.  If \code{signature} is unnamed, the default is to use
    the first \code{length(signature)} formal arguments of the
    function. }
  
  \item{file}{ The file on which to dump method definitions. }

  \item{def}{ The function object defining the method; if omitted, the
    current method definition corresponding to the signature. }

  \item{\dots}{Named or unnamed arguments to form a signature.}

  \item{generic}{In testing or finding functions, should generic
    functions be included.  Supply as \code{FALSE} to get only
    non-generic functions.}

  \item{fdef}{Optional, the generic function definition.

   Usually omitted in calls to \code{isGeneric}}
  
  \item{getName}{If \code{TRUE}, \code{isGeneric} returns the name of
    the generic.  By default, it returns \code{TRUE}. }
  \item{methods}{
    The methods object containing the methods to be dumped.  By default,
    the methods defined for this generic (optionally on the specified
    \code{where} location).
  }
  
}

\section{Details}{
  \describe{
  
  \item{\code{setGeneric}:}{ 
  

If there is already a non-generic function of this name, it will be used
to define the generic unless \code{def} is supplied, and the current function will
become the default method for the generic.

If \code{def} is supplied, this defines the generic function, and no default method
will exist (often a good feature, if the function should only be available for
a meaningful subset of all objects).

Arguments \code{group} and \code{valueClass} are retained for consistency with S-Plus, but
are currently not used.

  
  }
  \item{\code{isGeneric}:}{ 
  

If the \code{fdef} argument is supplied, take this as the definition of the
generic, and test whether it is really a generic, with \code{f} as the name of
the generic.  (This argument is not available in S-Plus.)

  
  }
  \item{\code{removeGeneric}:}{ 
  

If \code{where} supplied, just remove the version on this element of the search list;
otherwise, removes the first version encountered.

  
  }
  \item{\code{standardGeneric}:}{ 
  
Generic functions should usually have a call to \code{standardGeneric} as their entire
body.  They can, however, do any other computations as well.

The usual \code{setGeneric} (directly or through calling
\code{setMethod}) creates a function with a call to
\code{standardGeneric}.

  
  }
  \item{\code{getMethods}:}{ 
  If the function is not
a generic function, returns NULL.  
The \code{f} argument can be either the character string name of the generic
or the object itself

The \code{where} argument optionally says where to look for the function, if
\code{f} is given as the name.

  
  }
  \item{\code{dumpMethod}:}{ 
   
The resulting source file will recreate the method.

  
  }
  \item{\code{findFunction}:}{ 
  If \code{generic} is FALSE, ignore generic
functions.

  
  }
  \item{\code{selectMethod}:}{ 
  The vector of strings
for the classes can be named or not.  If named, the names must match formal
argument names of f.  If not named, the signature is assumed to apply to the
arguments of f in order.
mustFind = If TRUE, an error results if there is no method (or no unique method)
corresponding to this signature.  Otherwise may return NULL or a MethodsList
object.

  
  }
  \item{\code{dumpMethods}:}{ 
  

If \code{signature} is supplied only the methods matching this initial signature
are dumped.  (This feature is not found in S-Plus:  don't use it if you want
compatibility.)

  }
  \item{\code{signature}:}{ 
  The advantage
of using \code{signature} is to provide a check on which arguments you meant, as well
as clearer documentation in your method specification.  In addition, \code{signature}
checks that each of the elements is a single character string.

  }

  \item{\code{removeMethods}:}{ 
  Returns \code{TRUE} if
  \code{f} was a generic function, \code{FALSE} (silently) otherwise.
  
  If there is a default method, the function will be re-assigned as
  a simple function with this definition; otherwise, it will be removed.  The
  assignment or removal can be controlled by optional argument \code{where}, which
  defaults to the first element of the search list having a function called \code{f}.
}
}
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\seealso{\code{\link{setGeneric}}, \code{\link{setClass}}, \code{\link{showMethods}}}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\name{MethodSupport}
\alias{.conflicts.OK}
\alias{OldEvalSelectedMethod}
\alias{getMethodsForDispatch}
\alias{cacheMethod}
\alias{hasMethod}
\alias{resetGeneric}
\title{Additional (Support) Functions for Methods}
\usage{

getMethodsForDispatch(f)

cacheMethod(f, sig, def, args = names(sig))

hasMethod(f, signature=character())

resetGeneric(f)
}
\description{
  These are support routines for computations on formal methods.
}

\section{Summary of Functions}{
  
\describe{

\item{\code{hasMethod}:}{ 
  returns \code{TRUE} if \code{f} is the name of a generic function with an (explicit) method for
this signature.

  
  }
\item{\code{resetGeneric}:}{ 
  reset the currently defined methods for this generic by removing the
  corresponding definition from the methods metadata (to be remerged
  when the function is next called).  Returns \code{TRUE} or
  \code{FALSE} according to whether information for the function was
  found in the metadata.

  You \emph{must} call this function when you change relevant inheritance information during a
session, to guarantee that the new information is used if this generic has already been
called.
}

\item{\code{cacheMethod}:}{Store the definition for this function and
  signature in the method metadata for the function.  Used to store
  extensions of coerce methods found through inheritance.

  No persistent effect, since the method metadata is session-scope only.
}

\item{\code{getMethodsForDispatch}:}{Get the current methods list object
  representing the methods for function f, merged from the various
  libraries and with any additional caching information stored in the
  \code{allMethods} slot.

  If methods have not yet been merged, calling
  \code{getMethodsForDispatch} will cause the merge to take place.
  }
  
}
}
\keyword{internal}
\name{Methods}
\alias{Methods}
\alias{plot}
\title{General Information on Methods}
\non_function{}
\description{

This documentation section covers some general topics on how methods work
and how the methods package interacts with the rest of R.
The information is usually not needed to get started with methods and
classes, but may be helpful for moderately ambitious projects, or when
something doesn't work as expected.

The section \bold{How Methods Work} 
describes the underlying mechanism; \bold{Class Inheritance and Method
  Selection} provides more details on how class definitions determine
which methods are used.

The section \bold{Changes with the Methods Package} outlines possible
effects on other computations when running with package
\code{methods}.

  
}
\section{How Methods Work}{

A generic function is a function that has
associated with it a
collection of other functions(the methods), all of which agree in
formal arguments with the generic.
In R, the ``collection'' is an object of class
\code{"\link{MethodsList}"}, which contains a named list of methods
(the \code{methods} slot),
and the name of one of the formal arguments to the function (the
\code{argument} slot).
The names of the methods are the names of classes, and the corresponding element
defines the method or methods to be used if the corresponding argument
has that class.
For example, suppose a function \code{f} has formal arguments
\code{x} and \code{y}.
The methods list object for that function has the object
\code{as.name("x")} as its \code{argument} slot.
An element of the methods named \code{"track"} is selected if the
actual argument corresponding to \code{x} is an object of class
\code{"track"}.
If there is such an element, it can generally be either a function or
another methods list object.

In the first case, the function defines the method to use for any call
in which \code{x} is of class
\code{"track"}.
In the second case, the new methods list object defines the selection
of methods depending on the remaining formal arguments,
in this example, \code{y}.
The same selection process takes place, recursively, using the new
methods list.
Eventually, the selection returns either a function or \code{NULL},
meaning that no method matched the actual arguments.

Each method selected corresponds conceptually to a \emph{signature};
that is a named list of classes, with names corresponding to some or
all of the formal arguments.
In the previous example, if selecting class \code{"track"} for
\code{x}, finding that the selection was another methods list and then
selecting class \code{"numeric"} for \code{y} would produce a method
associated with the signature \code{
   x = "track", y = "numeric"
}

The actual selection is done recursively, but you can see the methods
arranged by signature by calling the function
\code{\link{showMethods}}, and objects with the methods arranged
this way (in two different forms) are returned by the functions
\code{\link{listFromMlist}} and \code{\link{linearizeMlist}}.

In an R session, each generic function has a single methods list
object defining all the currently available methods.
The session methods list object is created the first time the function is called
by merging all the relevant method definitions currently visible.
Whenever something happens that
might change the definitions (such as attaching or detaching a package
with methods for this function, or explicitly defining or removing methods), the merged
methods list object is removed.  The next call to the function will
recompute the merged definitions.

When methods list are merged, they can come from two sources:
\enumerate{
\item {
Methods list objects for the same function on one or more currently
attached databases.
These are merged so that methods in a database earlier in the search
list override methods for the same function later in the search list.
A method overrides only another method for the same signature.  See
the comments on class \code{"ANY"} in the section on \bold{Inheritance}.
}
\item {Methods list objects corresponding to the
    generic function itself and to the group generic functions, if
    any, for this function.
    Any generic function can be defined to belong to a group generic.
    The methods for the group generic are available as methods for
    this function.  The group generic can itself be defined as belong
    to a group; as a result there is a list of group generic
    functions.  A method defined for a function and a particular
    signature overrides a method for the same signature for that
    function's group generic
}
}
Merging is done first over databases for a particular function, and
then over the generic and its group generics.

The result is a single methods list object that contains all the
methods \emph{directly} defined for this function.
As calls to the function occur, this information may be supplemented
by \emph{inherited} methods, which we consider next.
}
\section{Class Inheritance and Method Selection}{
If no method is found directly for the actual arguments in a call to a
generic function, an attempt is made to match the available methods to
the arguments by using \emph{inheritance}.

Each class definition potentially includes the names of one or more
classes that the new class extends.  (These are sometimes called the
\emph{superclasses} of the new class.)  These classes themselves may
extend other classes.  Putting all this information together produces
the full list of superclasses for this class. (You can see this list
for any class \code{"A"} from the expression \code{extends("A")}.)
In addition, any class implicitly extends class \code{"ANY"}.

A method will be selected by inheritance if we can find a method in
the methods list for a signature corresponding to any
combination of superclasses for each of the relevant arguments.
The search for such a method is performed by the function
\code{\link{MethodsListSelect}}, working as follows.

For the first formal argument of the function, a list of classes is
made up from the class itself, all its superclasses, and class
\code{"ANY"}.
For each of these, the selection computation looks for an element of
the methods with the corresponding name.  Each time it finds one, it
then calls the selection process recursively if necessary to select a
method directly or by inheritance for the remaining arguments.

Each one of these recursive calls can fail or it can return a function
(the method).  As long as the calls fail, the selection process moves
on to the next superclass and tries again.
The last step corresponds to class \code{"ANY"}, the default method
defined at this level.

The effect of this definition of the selection process is to order all
possible inherited methods, first by the superclasses for the first
argument, then within this by the superclasses for the second
argument, and so on.
Superclasses are ordered by how direct they are:  first, the direct
superclasses, then the superclasses of these classes.
}
\section{Changes with the Methods Package}{
The methods package is designed to leave other computations in R
unchanged.  There are, however, a few areas where the default
functions and behavior are overridden when running with the methods
package attached.
This section outlines those known to have some possible effect.

\describe{

\item{\code{class}:}{
    The methods package enforces the notion that every object has a
    class; in particular, \code{class(x)} is never \code{NULL}, as it
    would be for basic vectors, for example, when not using methods.

    In addition, when assigning a class, the value is required to be a
    single string.  (However, objects can have multiple class names if
    these were generated by old-style class computations.  The methods
    package does not hide the ``extra'' class names.)

    Computations using the notion of \code{NULL} class attributes or
    of class attributes with multiple class names are not really
    compatible with the ideas in the methods package.  Formal classes
    and class inheritance are designed to give more flexible and
    reliable implementations of similar ideas.

    If you do have to mix the two approaches, any operations that use
    class attributes in the old sense should be written in terms of
    \code{attr(x, "class")}, not \code{class(x)}.  In particular, test
    for no class having been assigned with \code{is.null(attr(x, "class"))}.
}

\item{Printing}{
    To provide appropriate printing   automatically for
    objects with formal class definitions, the methods package
    overrides \code{print.default}, to look for methods for the
    generic function \code{show}, and to use a default method for
    objects with formal class definitions.

    The revised version of \code{print.default} is intended to produce
    identical printing to the original version for any object that
    does \emph{not} have a formally defined class, including honoring
    old-style print methods.  So far, no exceptions are known.
  }

  \item{\code{plot}}{
    A version of the \code{plot} function is included in the current
    methods package, differing from the one in the base package in that
    it has a \code{y} argument (necessary if methods for plot are to be
    defined for the \code{y} data; see the examples for
    \link{setMethod}).
    This version will move into base as soon as it is tested. 
    }

}

}

\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\seealso{\code{\link{setGeneric}}, \code{\link{setClass}}}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\name{MethodsList-class}
\alias{MethodsList-class}
\doctype{class}
\title{Class MethodsList, Representation of Methods for a Generic Function }
\description{ Objects from this class are generated and revised by the
  definition of methods for a generic function.}
\section{Creating Objects}{\code{
  new('MethodsList',
     methods     = ...., # Object of class list
     argument    = ...., # Object of class name
     allMethods  = ...., # Object of class list
     fromClass   = ...., # Object of class character
  )}}
\section{Slots}{\describe{

  \item{\code{methods}:}{Object of class "list" ~~ }
  \item{\code{argument}:}{Object of class "name" ~~ }
  \item{\code{allMethods}:}{Object of class "list" ~~ }
  \item{\code{fromClass}:}{Object of class "character" ~~ }
}}


\section{Extends}{
Class "OptionalMethods" directly.
}
\keyword{methods}\name{MethodsList}
\alias{MethodsList}
\alias{makeMethodsList}
\alias{SignatureMethod}
\alias{insertMethod}
\alias{matchArg}
\alias{matchArgClass}
\alias{showMlist}
\alias{print.MethodsList}
\alias{emptyMethodsList}
\alias{insertMethodInEmptyList}
\alias{listFromMlist}
\alias{linearizeMlist}
\alias{finalDefaultMethod}
\alias{mergeMethods}
\title{MethodsList Objects}
\usage{
MethodsList(.ArgName, ...)

makeMethodsList(object, level=1)

SignatureMethod(names, signature, definition)

insertMethod(mlist, signature, args, def, whichMethods, fromClass, envir)

matchArg(object, thisClass, mlist, ev)

matchArgClass(Class, classes, methods)

showMlist(mlist, includeDefs = TRUE, inherited = TRUE,
   classes, useArgNames, printTo = stdout() )

print.MethodsList(x, ...)

listFromMlist(mlist, prefix = list())

linearizeMlist(mlist, inherited = TRUE)

finalDefaultMethod(mlist, fname = "")

mergeMethods(m1, m2)

}

\description{
  
These functions create and manipulate \code{MethodsList} objects, the
objects used in R to store methods for dispatch.
You should not call any of these functions from code that you want to
port to S-Plus.  Instead, use the functions described in the
references.

  }

\section{Details}{

\describe{
  
  \item{\code{MethodsList}:}{ 
  Create a MethodsList object out of the arguments.

Conceptually, this object is a named collection of methods to be dispatched
when the (first) argument in a function call matches the class corresponding to
one of the names.  A final, unnamed element (i.e., with name \code{""}) corresponds
to the default method.

The elements can be either a function, or another MethodsList.  In the second case,
this list implies dispatching on the second argument to the function using that
list, given a selection of this element on the first argument.  Thus, method dispatching
on an arbitrary number of arguments is defined.

MethodsList objects are used primarily to dispatch OOP-style methods and, in R,
to emulate S4-style methods.

  
  }
\item{\code{SignatureMethod}:}{ 
  construct a MethodsList object containing (only) this method, corresponding
to the signature; i.e., such that signature[[1]] is the match for the first
argument, signature[[2]] for the second argument, and so on.  The string
"missing" means a match for a missing argument, and "ANY" means use this as the
default setting at this level.

The first argument is the argument names to be used for dispatch corresponding to
the signatures.

  
  }
\item{\code{insertMethod}:}{ 
  insert the definition \code{def} into the MethodsList object, \code{mlist}, corresponding to
the signature. By default, insert it in the slot \code{which="methods"},
but \code{\link{cacheMethod}} inserts it into the
\code{which="allMethods"}} slot (used for dispatch but not saved).

  
  }

\item{\code{matchArg, matchArgClass}:}{ 
  Utility functions to match the object  or the class to the elements of
  a methods list.
  Used in finding inherited methods, and not meant to be called directly.

  }
\item{\code{showMlist}:}{ 
  Prints the contents of the MethodsList.  If \code{includeDefs} the signatures and the
corresonding definitions will be printed; otherwise, only the signatures.

The function calls itself recursively.  \code{prev} is the previously
selected classes.
}
\item{\code{listFromMlistForPrint}:}{
  Undo the recursive nature of the methods list, making a list of function
  defintions, with the names of the list being the corresponding signatures
  (designed for printing; for looping over the methods, use \code{\link{listFromMlist}} instead).
  
  The function calls itself recursively:  \code{prev} is the previously
  selected classes.
  }

  \item{\code{finalDefaultMethod}}{
    The true default method for the methods list object \code{mlist}
    (the method that matches class \code{"ANY"} for as many arguments as
    are used in methods matching for this generic function).}

  \item{\code{mergeMethods}}{
    Merges the methods in the second MethodsList object into the first,
    and returns the merged result.  Called from
    \code{\link{getAllMethods}}.
    }
}

}
\details{
  Note that \code{MethodsList} objects represent methods only in the \R
  implementation.  You can use them to find or manipulate information about
  methods, but avoid doing so if you want your code to port to S-Plus.
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\examples{
}
\keyword{internal}

\name{ClassUtils}
\alias{testVirtual}
\alias{SessionClassMetaData}
\alias{makePrototypeFromClassDef}
\alias{newEmptyObject}
\alias{completeClassDefinition}
\alias{getFromClassDef}
\alias{setInClassDef}
\alias{synchronizeClassDef}
\alias{getProperties}
\alias{setProperties}
\alias{getSlots}
\alias{getExtends}
\alias{getAccess}
\alias{getAllSuperClasses}
\alias{superClassDepth}
\alias{setExtends}
\alias{getPrototype}
\alias{setPrototype}
\alias{getVirtual}
\alias{isVirtualClass}
\alias{setVirtual}
\alias{getSubclasses}
\alias{setSubclasses}
\alias{getClassName}
\alias{setClassName}
\alias{assignClassDef}
\alias{newClassEnvironment}
\alias{newBasic}
\alias{makeExtends}
\alias{reconcilePropertiesAndPrototype}
\alias{tryNew}
\alias{empty.dump}
\alias{showClass}
\alias{showExtends}
\alias{showNonVector}
\alias{print.classRepEnvironment}
\alias{print.environment}
\alias{getFromClassMetaData}
\alias{assignToClassMetaData}
\alias{removeFromClassMetaData}
\alias{extendsCoerce}
\alias{extendsReplace}
\alias{findExtends}
\alias{completeExtends}
\alias{classMetaName}
\alias{methodsMetaName}
\alias{as.data.frame}
\alias{requireMethods}
\alias{checkSlotAssignment}
\alias{defaultPrototype}
\alias{isClassDef}
%% not explicitly documented here
\alias{.BasicClasses}
\alias{.BasicVectorClasses}
\alias{.InitBasicClasses}
\alias{.InitMethodsListClass}
\alias{.setCoerceGeneric}

\title{Utilities for Managing Class Definitions}
\usage{
testVirtual(properties, extends, prototype)

makePrototypeFromClassDef(properties, prototype, extends)

newEmptyObject()

completeClassDefinition(Class, ClassDef)

getFromClassDef(ClassDef, what)

setInClassDef(ClassDef, what, value, synchronize=TRUE)

synchronizeClassDef(ClassDef)

getProperties(ClassDef)

setProperties(ClassDef, value)

getSlots(x, complete = TRUE)

getExtends(ClassDef)

getAccess(ClassDef)

getAllSuperClasses(ClassDef)

superClassDepth(ClassDef, soFar)

setExtends(ClassDef, value)

getPrototype(ClassDef)

setPrototype(ClassDef, value)

getVirtual(ClassDef)

isVirtualClass(Class)

setVirtual(ClassDef, value)

getSubclasses(ClassDef)

setSubclasses(ClassDef, value)

getClassName(ClassDef)

setClassName(ClassDef, value)

assignClassDef(Class, def, where=.GlobalEnv)

newClassEnvironment(name, properties, extends, prototype, subclasses,
                 virtual, validity, access)

newBasic(Class, ..., .Force=FALSE)

makeExtends(extends)

reconcilePropertiesAndPrototype(name, properties, prototype, extends)

tryNew(Class)

empty.dump()

showClass(Class, complete=TRUE, printTo=stdout(),
         propertiesAreCalled="Properties")

showExtends(ext, printTo = stdout())

print.classRepEnvironment(x, ...)

print.environment(x, ...)

getFromClassMetaData(name)

assignToClassMetaData(name, value)

removeFromClassMetaData(name)

extendsCoerce(fromClass, Class, formFunction)

extendsReplace(fromClass, Class)

findExtends(class1, class2)

completeExtends(ClassDef, soFar)

classMetaName(name)

methodsMetaName(prefix, name)

as.data.frame(x, row.names=NULL, optional=FALSE)

requireMethods(functions, signature, message)

checkSlotAssignment(obj, name, value)

defaultPrototype()

isClassDef(object)

}
\description{

These are various functions to support the definition and use of
formal classes.  Most of them are rarely suitable to be called directly.
}

\section{Summary of Functions}{
\describe{
\item{\code{testVirtual}:}{ 
  Test for a Virtual Class.
Figures out, as well as possible, whether the class with these properties,
extension, and prototype is a virtual class.
Can be forced to be virtual by extending "VIRTUAL".  
  
  Otherwise, a class is
virtual only if it has no slots, extends no non-virtual classes, and has a
NULL Prototype

  
  }
\item{\code{makePrototypeFromClassDef}:}{ 
  Makes the prototype implied by
the class definition.

The following three rules are applied in this order.

If the class has slots, then the prototype for each
slot is used by default, but a corresponding element in the explicitly supplied
prototype, if there is one, is used instead (but it must be coercible to the
class of the slot).

If there are no slots but a non-null prototype was specified, this is returned.

If there is a single non-virtual superclass (a class in the extends list),
then its prototype is used.

If all three of the above fail, the prototype is \code{NULL}.

  
  }
\item{\code{newEmptyObject}:}{ 
  Utility function to create an empty object into which slots can be
set.  
  
  Currently just creates an empty list with class "NULL"

Later version should create a special object reference that marks an
object currently with no slots and no data.

  }
\item{\code{completeClassDefinition}:}{ 
  Completes the definition of Class, relative to the current session.

The completed definition is stored in the session's class metadata,
to be retrieved the next time that getClass is called on this class,
and is returned as the value of the call.

If \code{ClassDef} is omitted, the initial definition is obtained from
the first package having a meta-object for this class.

  }
\item{\code{getFromClassDef}:}{ 
  Extracts one of the intrinsically defined class definition properties
(".Poperties", etc.)  Strictly a utility function

  
  }
\item{\code{setInClassDef}:}{ 
  Set Property in Class Definition
set one of the intrinsically defined class definition properties
(".Poperties", etc.)  Strictly a utility function

  
  }
\item{\code{synchronizeClassDef}:}{ 
  Does whatever is needed to synchronize information in the class definition.

Basically computes derived information used to make object manipulations more efficient
but that need to be revised if information changes.

(Nothing at the moment)

  
  }
\item{\code{getProperties}:}{ 
  Extracts the class's Properties information from the class representation (only, not from
the name of the class).

  
  }
\item{\code{setProperties}:}{ 
  Sets the class's Properties information given the class representation (only, not from
the name of the class)

  
  }
  \item{\code{getSlots}:}{
    Returns a named character vector.  The names are the names of the
    slots, the values are the classes of the corresponding slots.  If
    \code{complete} is \code{TRUE}, all slots from all superclasses will
    be included.  The argument \code{x} can either be the name of a
    class or an object having that class.
  }

  \item{\code{getExtends}:}{ 
  Extracts the class's Extends information from the class representation (only, not from
the name of the class)

Contrast with the \code{findExtends} and \code{is} functions, both of which use indirect
information as well.

  
  }
\item{\code{getAllSuperClasses}, \code{superClassDepth}:}{ 
  Get the names of all the classes that this class definition extends.

\code{getAllSuperClasses} is a utility function used to complete a class definition.  
  It returns all the
superclasses reachable from this class, in breadth-first order (which is the order
used for matching methods); that is, the first direct superclass followed by all its
superclasses, then the next, etc.  (The order is relevant only in the case that
some of the superclasses have multiple inheritance.)

\code{superClassDepth}, which is called from \code{getAllSuperClasses},
returns the same information, but as a list with
components \code{label} and \code{depth}, the latter for the number of
generations back each class is in the inheritance tree.  The argument
\code{soFar} is used to avoid loops in the network of class relationships.
  
  
  }
\item{\code{setExtends}:}{ 
  set the class's Extends information given the class representation (only, not from
the name of the class)

  
  }
\item{\code{getPrototype}:}{ 
  extract the class's Prototype information from the class representation (only, not from
the name of the class)

\item{\code{getAccess}:}{ 
  extract the class's Access information from the class representation (only, not from
the name of the class)

  
  }
\item{\code{setPrototype}:}{ 
  set the class's Prototype information given the class representation (only, not from
the name of the class)

  
  }
\item{\code{getVirtual}:}{ 
  extract the class's Virtual information from the class representation (only, not from
the name of the class)

  
  }
\item{\code{isVirtualClass}:}{ 
  Is the named class a virtual class?  
  
  A class is virtual if explicitly declared to
be, and also if the class is not formally defined.

   }
\item{\code{setVirtual}:}{ 
  set the class's Virtual information given the class representation (only, not from
the name of the class)

  
  }
\item{\code{getSubclasses}:}{ 
  extract the class's Subclasses information from the class representation (only, not from
the name of the class)

  
  }
\item{\code{setSubclasses}:}{ 
  set the class's Subclasses information given the class representation (only, not from
the name of the class)

  
  }
\item{\code{getClassName}:}{ 
  The internal property in the class definition for the class name.

  
  }
\item{\code{setClassName}:}{ 
  set the name of the class inside the class definition

  
  }
\item{\code{assignClassDef}:}{ 
  assign the definition of the class to the specially named object

  
  }
\item{\code{newBasic}:}{ 
  the implementation of the function \code{new} for basic classes that don't have
a formal definition.  
  
  Any of these could have a formal definition, except for
Class="NULL" (disallowed because NULL can't have attributes).  For all cases except
"NULL", the class of the result will be set to Class.

See \code{new} for the interpretation of the arguments.

   }
\item{\code{makeExtends}:}{ 
  convert the argument to a list defining the extension mechanism.

  
  }
\item{\code{reconcilePropertiesAndPrototype}:}{ 
  makes a list or a structure look like a prototype for the given class.

Specifically, returns a structure with attributes corresponding to the slot
names in properties and values taken from prototype if they exist there, from
\code{new(classi)} for the class, \code{classi} of the slot if that succeeds, and \code{NULL}
otherwise.

The prototype may imply slots not in the properties list, since properties does not
include inherited slots (these are left unresolved until the class is used in a
session).

  
  }
\item{\code{tryNew}:}{ 
  Tries to generate a new element from this class, but if the attempt fails
(as, e.g., when the class is undefined or virtual) just returns NULL.

This is inefficient and also not a good idea when actually generating objects,
but is useful in the initial definition of classes.

  
  }
\item{\code{showClass}:}{ 
  Print the information about a class definition.  
  
  If complete==TRUE, include the
indirect information about extensions.

  
  }
\item{\code{showExtends}:}{ 
  Print the elements of the list of extensions.  
  
  Also used to print
extensions recorded in the opposite direction, via a subclass list

  }
\item{\code{print.environment, showNonVector}:}{ 
  These routines provide a default printing mechanism for objects from
  non-vector classes, implemented as environments.  The
  \code{print.environment} function exists to intercept printing based
  on S3-style methods; it calls \code{showNonVector} to do the work.

  }
\item{\code{extendsCoerce}, \code{extendsReplace}:}{ 
  Returns the function to perform coercion or replacement,
  respectivelyl, based on the \code{is} relation
between two classes.  
  
  A method may be explicitly stored in the metadata or
inferred.  If the latter, a function will always be constructed if
explicit test and/or coerce methods (in a call to setIs) were
encountered, or if \code{formFunction=TRUE}.  If
\code{formFunction=FALSE}, the purpose of the call is to determine if
the relation is explicit or intrinsic (according to whether a function
object is returned).


  
  }
\item{\code{findExtends}:}{ 
  Find the information that says whether class1 extends class2,
directly or indirectly.  
  
  This can be either a logical value or
an object containing various functions to test and/or coerce the relationship.

  
   }
\item{\code{completeExtends}:}{ 
  complete the extends information in the class definition, by following
transitive chains.

Elements in the immediate extends list may be added and current elements may be
replaced, either by replacing a conditional relation with an unconditional
one, or by adding indirect relations.

The resulting extends list is presented in depth-first order; that is, the
first immediate superclass followed by all the indirect relations through it,
then the next immediate superclass, etc.  
  
  Depth first order is required for
consistent elaboration of inherited methods during dispatch, because the
method dispatcher stores the inherited method under the immediate class name.
Under rather obscure situations of multiple inheritance, the result could be
ambiguous (depending on the order in which signatures are seen by the dispatcher
for a particular generic function), unless searching is done depth
first.

Used recursively, with \code{soFar} defining what has been included in
previous calls at this level.

  }
\item{\code{classMetaName}:}{ 
  a name for the object storing this class's definition

  
  }
\item{\code{methodsMetaName}:}{ 
  a name mangling device to simulate the meta-data in S4

  
  }

\item{\code{requireMethods}:}{ 
  Require a subclass to implement methods for the generic functions, for this signature.

For each generic, \code{setMethod} will be called to define a method that throws an error,
with the supplied message.

The \code{requireMethods} function allows virtual classes to require actual classes that
extend them to implement methods for certain functions, in effect creating an API
for the virtual class.  

  Otherwise, default methods for the corresponding function would
be called, resulting in less helpful error messages or (worse still) silently incorrect
results.

}
\item{\code{checkSlotAssignment}:}{
    Check that the value provided is allowed for this slot, by
    consulting the definition of the class.  Called from the C code
    that assigns slots.

    For privileged slots (those that can only be set by accesor functions
    defined along with the class itself), the class designer may
    choose to improve efficiency by validating the value to be
    assigned in the accessor function and then calling \code{slot<-} with
    the argument \code{check=FALSE}, to prevent the call to \code{checkSlotAssignment}.
}
\item{\code{defaultPrototype:}{
    The prototype for a class which will have slots, is not a virtual
    class, and does not extend one of the basic classes.  In future
    releases, this will likely be a non-vector R object type, but none
    of the current types (as of release 1.4) is suitable.
  }
}
\item{SessionClassMetaData:}{ Contains the name of the special table in which
    class information is cached during the session.}
}
\item{\code{.InitBasicClasses}, \code{.InitMethodsListClass},
  \code{.setCoerceGeneric}:}{
  These functions perform part of the initialization of classes and
  methods, and are called (only!) from \code{.First.lib}.
  }
\item{\code{isClassDef}:}{ Is \code{object} a representation of a class?}
}
}
\keyword{internal}

\name{RMethodUtils}
\alias{makeGeneric}
\alias{makeStandardGeneric}
\alias{getAllMethods}
\alias{generic.skeleton}
\alias{defaultDumpName}
\alias{getAllMethods}
\alias{setAllMethodsSlot}
\alias{doPrimitiveMethod}
\alias{conformMethod}
\alias{getGeneric}
\alias{getGroup}
\alias{getGroupMembers}
\alias{setGroupMembers}
\alias{getMethodsMetaData}
\alias{assignMethodsMetaData}
\alias{matchSignature}
\alias{mlistMetaName}
\alias{assignToMethodMetaData}
\alias{getFromMethodMetaData}
\alias{removeMethodsObject}
\alias{findUnique}
\alias{removeFromMethodMetaData}
\alias{MethodAddCoerce}
\alias{is.primitive}
\alias{.saveImage}
\alias{cacheMetaData}
\alias{cacheGenericsMetaData}
\alias{setPrimitiveMethods}
\alias{copyEnvironment}
\alias{printNoClass}
\alias{print.default}
%% Not for the user to know about!
\alias{.ShortPrimitiveSkeletons} %% used from C code
\alias{.EmptyPrimitiveSkeletons}
\alias{__MethodMetaData}
\title{RMethodUtils}
\usage{
makeGeneric(f, fdef, keepMethods=TRUE, useAsDefault=NA, group=character(), valueClass=character())

makeStandardGeneric(f, fdef)

generic.skeleton(name, fdef, fdefault)

defaultDumpName(generic, signature)

getAllMethods(f, libs=search())

setAllMethodsSlot(mlist)

doPrimitiveMethod(name, def, call=sys.call(-1), ev=sys.frame(-2))

conformMethod(signature, mnames, fnames)

getGeneric(f, mustFind=FALSE)

getGroup(fdef, recursive=FALSE)

getGroupMembers(f, fdef = getGeneric(f))
setGroupMembers(f, members, fdef = getGeneric(f))

matchSignature(names, signature, fun)

## manage method metadata
getFromMethodMetaData(name)

assignToMethodMetaData(name, value)

removeFromMethodMetaData(name)

removeMethodsObject(f, where)

findUnique(what, doFind, message)

MethodAddCoerce(method, argName, thisClass, methodClass)

is.primitive(fdef)

copyEnvironment(object, exceptions)

cacheMetaData(envir, attach = TRUE)

cacheGenericsMetaData(generics, attach = TRUE, envir)

setPrimitiveMethods(f, fdef, code, generic, mlist)

printNoClass(x, digits, quote, na.print, print.gap, right, ...)

print.default(x, ...)

}
\description{
 These are utility functions to support the definition and use of
 formal methods.  Most of them will not normally be called directly by
 the user.
 
\describe{
\item{\code{makeGeneric}:}{ 
  Makes a generic function object corresponding to the given function name.
and optional definition.

  
  }
\item{\code{makeStandardGeneric}:}{ 
  a utility function that makes a valid function calling standardGeneric for name f
Works (more or less) even if the actual definition, fdef, is not a proper function,
that is, it's a primitive or internal

  
  }
\item{\code{conformMethod}:}{
    If the formal arguments, \code{mnames}, are not identical to the
    formal arguments to the function, \code{fnames},
    \code{conformMethod} determines whether the signature and the two
    sets of arguments conform, and returns the signature, possibly
    extended.

    The method assignment conforms if either method and function have
    identical formal argument lists.  It can also conform if the
    method omits some of the formal arguments of the function but: (1)
    the non-omitted arguments are a subset of the function arguments,
    appearing in the same order; (2) there are no arguments to the
    method that are not arguments to the function; and (3) the omitted
    formal arguments do not appear as explicit classes in the signature.
}
\item{\code{defaultDumpName}:}{ 
  the default name to be used for dumping a method.

  
  }
\item{\code{getAllMethods}:}{ 
  a generic function (with methods) representing the merge of all the versions
of \code{f} on the specified packages (anything on the current search path by default).

If the generic \code{f} has a group generic, methods for this group generic (and further
generations of group generics, if any) are also merged.  
  
  The merging rule is as follows:
each generic is merged across packages, and the group generics are then merged, finally
adding the directly defined methods of \code{f}.

The effect of the merging rule is that any method directly defined for \code{f} on any
included package overrides a method for the same signature defined for the group generic;
similarly for the group generic and its group, if any, etc.

For \code{f} or for a specific group generic, methods override in the order of the packages
being searched.  A method for a particular signature on a particular package overrides
any methods for the same signature on packages later on in the list of packages being
searched.

The slot "allMethods" of the merged methods list is set to a copy of the methods slot;
this is the slot where inherited methods are stored.

  }
\item{\code{doPrimitiveMethod}:}{ 
  do a primitive call to builtin function \code{name} the definition and call
provided, and carried out in the environment \code{ev}.

A call to \code{doPrimitiveMethod} is used when the actual method is a .Primitive.
(because primitives don't behave correctly as ordinary functions,
not having either formal arguments nor a function body).

  
  }
\item{\code{getGeneric}:}{ 
  return the definition of the function named f as a generic.

If there is no definition in the current search list, throws an error or returns
NULL according to the value of mustFind.

Primitive functions are dealt with specially, since there is never a
formal generic definition for them.  The value returned is the formal
definition used for assigning methods to this primitive.  Not all
primitives can have methods; if this one can't, then \code{getGeneric}
returns \code{NULL} or throws an error.

  
  }
\item{\code{getGroup}:}{ 
  return the groups to which this generic belongs.  

  If \code{recursive=TRUE}, also all the
  group(s) of these groups.
}

\item{\code{getGroupMembers}, \code{setGroupMembers}:}{
  Get or set the known members of the group generic function \code{f}.
  }

\item{\code{matchSignature}}{
    Matches the signature object (a partially or completely named subset of the
   arguments of \code{fun}), and return a vector of all the classes in the order specified
   by \code{names}.  The classes not specified by `signature' will be \code{"ANY"} in the
   value.
  
   The formal arguments of \code{fun} must agree with \code{names} (usually the formal arguments
   of the generic function) as well, and \code{matchSignature} checks
   this.
}



\item{\code{getMethodsMetaData}, \code{assignMethodsMetaData},
  \code{mlistMetaName}:}{
  utilities to manage methods list objects in a particular database.
  Not to be called directly.
  }
\item{\code{getFromMethodMetaData, assignToMethodMetaData,
      removeFromMethodMetaData}}{
      Functions to manage the session metadata for methods.  Don't
      call these directly.}
    
    \item{\code{MethodAddCoerce}}{
      Possibly modify one or more methods to explicitly coerce this
      argument to \code{methodClass}, the class for which the method is
      explicitly defined.  Only modifies the method if an explicit
      coerce is required to coerce from \code{thisClass} to \code{methodClass}.
    }
    
    \item{\code{is.primitive}}{
      Is this object a primitive function (either a builtin or special)?
    }
\item{\code{getFromMethodMetaData, assignToMethodMetaData,
      removeFromMethodMetaData}}{
      Functions to manage the session metadata for methods.  Don't
      call these directly.}
    
    \item{\code{is.primitive}}{
      Is this object a primitive function (either a builtin or special)?
    }
 \item{\code{removeMethodsObject}:}{
  remove the metadata object containing methods for \code{f}.
  }
 \item{\code{findUnique}:}{
  Find the first position on the search list containing object
  \code{what}; if more than one is found, a warning message is
  generated, using \code{message} to identify what was being searched
  for.
  If \code{doFind} is supplied, it's the version of \code{find} used to
  do the search (e.g., \code{findFunction}.
  }
  
    \item{\code{cacheMetaData, cacheGenericsMetaData, setPrimitiveMethods}:}{
      Utilities for ensuring that the session-scope information about
      class and method definitions is up to date.  Should normally be
      called automatically whenever needed (for example, when a method
      or class definition changes, or when a database is attached or
      detached.

      The \code{environment} must be one of the environments on the
      current search list; note in particular that even on detaching
      (\code{attach=FALSE}), the environment will normally still be on
      the search list.

      The \code{setPrimitiveMethods} function resets the caching
      information for a particular primitive function.  Don't call it directly.
      }

      \item{\code{printNoClass},\code{print.default} :}{
        \code{printNoClass} is equivalent to the version of \code{print.default} in the base
        package.  The methods package overrides the latter function to provide
        meaningful printing for formally defined classes, and
        \code{printNoClass} is used to get the original default printing.
      }
}
\item{\code{.saveImage}:}{Flag, used in dynamically initializing the
    methods package from \code{.First.lib}}
}
}
\keyword{internal}
\name{Session}
\alias{sessionData}
\alias{traceOn}
\alias{traceOff}
\alias{browseAll}
\title{Session Data and Debugging Tools}
\usage{
sessionData()

traceOn(what, tracer=browseAll, exit=NULL)

traceOff(what)

browseAll()

}

\description{
  The function \code{sessionData} provides a work-around in R for the absence of a
  session database (what you get in S with the argument \code{where=0}
  to functions such as \code{get} and \code{assign}).

  The functions \code{traceOn}, \code{traceOff} and \code{browseAll} are
  debugging tools with roughly similar functionality to \code{trace}, \code{untrace} and
      \code{browser} as described in the reference.  Calling
      \code{traceOn} creates a new version of a function with arbitrary
      code inserted at the beginning of the call and/or on exit.
      Calling \code{traceOff} undoes the change.  The function
      \code{browseAll} is a useful interactive call to insert for
      tracing.  It behaves basically like \code{\link{debugger}}.

Note:  use \code{traceOn} only for testing functions in a library,
\emph{not} for functions defined in the global environment.  Because
the session data is in position 2 on the search list, the temporary
versions stored there will not override functions in the global environment.

  A more
  satisfactory version of these  facilities is likely to be provided
  in the future.  Use the current versions but don't write code that
  depends on them.
}
\arguments{
  \item{what}{
    The object to be traced or untraced.
  }
  \item{tracer, exit}{
    The code to use at the entrance or exit trace.  Either a function
    (which will be called with no arguments) or an expression (typically
    constructed from \code{link{quote}} or \code{\link{substitute}}) to
    be evaluated.
    }
  }
\details{
  
  \code{sessionData}: 
  return the index of the session data in the search list,
attaching it if it is not attached

  
  \code{traceOn}: 
  initialize tracing on calls to function \code{what}.  The function or expression
\code{tracer} is called on entry, and the function or expression \code{exit} on exit.

  
  \code{traceOff}: 
  turn off tracing of this function

  
  \code{browseAll}: 
  browse the current stack of function calls.

Uses the function \code{debugger} to set up browser calls
on the frames.  On exit from that function, computation
continues after the call to browseAll.  Computations done
in the frames will have no effect.

}
\references{
See   \emph{Programming with Data} (John M. Chambers, Springer, 1998) for the equivalent
functions.
}
\author{
  John Chambers
}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\name{as}
\alias{as}
\alias{as<-}
\alias{coerce}
\alias{coerce<-}
\alias{setAs}
\title{Force an Object to Belong to a Class}
\usage{
as(object, Class, coerceFlag=TRUE)

as(object, Class, coerceFlag=TRUE) <- value

setAs(from, to, def, replace, where = 1)

}
\description{
  These functions manage the relations that allow coercing an object to
  a given class.
  }
\section{Summary of Functions}{
\describe{
  \item{\code{as}:}{
  Returns the version of this object coerced to be the given \code{Class}.  
  
  
If the corresponding \code{is} relation is true, it will be used.  In particular,
if the relation has a coerce method, the method will be invoked on \code{object}.

If the \code{is} relation is FALSE, and \code{coerceFlag} is \code{TRUE},
the coerce function will be called (which will throw an error if there is
no valid way to coerce the two objects).  Otherwise, \code{NULL} is
returned.

Coerce methods are pre-defined for basic classes (including all the types of
vectors, functions and a few others).  The object \code{asFunctions}
contains the list of such pre-defined relations:
\code{names(asFunctions)} gives the names of all the classes.

Beyond these two sources of  methods, further methods are defined by
calls to the \code{setAs} function.
}

  \item{\code{coerce}:}{
    Coerce \code{from} to be of the same class as \code{to}.

    Not a function you should usually
    call explicitly.  The function \code{\link{setAs}} creates
    methods for \code{coerce} for the \code{as} function to use.
}

  \item{\code{setAs}:}{
  The function supplied as the third argument is to be called to
  implement \code{as(x, to)} when \code{x} has class \code{from}.
  Need we add that the function should return a suitable object with
  class \code{to}.
}
}
}
\arguments{
  \item{object}{ Any object. }
  \item{Class}{ The name of the class to which \code{object} should be coerced. }
  \item{coerceFlag}{ A logical flag.  If \code{FALSE},  only inheritance
  relations will be used; i.e., \code{is(object, Class)} must be
  \code{TRUE}, and if not, \code{NULL} is returned.

  If the flag is \code{TRUE}, however, coerce methods will be called if
  inheritance is not true (and an error will result if coercion fails).
}
  \item{value}{The value to use to modify \code{object} (see the
    discussion below).  You should supply an object with class
    \code{Class}; some coercion is done, but you're unwise to rely on
    it.
    }

\item{from, to}{ The classes between which \code{def} performs coercion.

  (In the case of the \code{coerce} function these are objects from the
  classes, not the names of the classes, but you're not expected to call \code{coerce} directly.)
}
  \item{def}{ A function of one argument.  It will get an object from
    class \code{from} and had better return an object of class
    \code{to}. (If you want to save \code{setAs} a little work, make
    the name of the argument \code{from}, but don't worry about it,
    \code{setAs} will do the conversion.) }
  \item{replace}{If supplied, the function to use as a replacement
    method.
    }
  \item{where}{ The database on which to store the resulting method for
    \code{coerce}; by default, the global environment. }

}
%% <FIXME>
%% Currently Rdconv cannot deal with markup in section titles.
%% \section{How Functions \code{as} and \code{setAs} Work}{
\section{How Functions `as' and `setAs' Work}{
  %% </FIXME>
  The function \code{as} contrives to turn \code{object} into an object
  with class \code{Class}.  In doing so, it uses information about
  classes and methods, but in a somewhat special way.  Keep in mind
  that objects from one class can turn into objects from another class
  either automatically or by an explicit call to the \code{as}
  function. Automatic conversion is special, and comes from the
  designer of one class of objects asserting that this class extends a
  another class  (see \code{\link{setClass}} and \code{\link{setIs}}).

  Because inheritance is a powerful assertion, it should be used
  sparingly (otherwise your computations may produce unexpected, and
  perhaps incorrect, results).  But objects can also be converted
  explicitly, by calling \code{as}, and that conversion is designed to
  use any inheritance information, as well as explicit methods.

  As a first step in conversion, the \code{as} function determines
  whether \code{is(object, Class)} is \code{TRUE}.  This can be the case
  either because the class definition of \code{object} includes
  \code{Class} as a ``super class'' (directly or indirectly), or because
  a call to \code{\link{setIs}} established the relationship.

  Either way, the inheritance relation defines a method to coerce
  \code{object} to \code{Class}.  In the most common case, the method
  is just to extract from \code{object} the slots needed for
  \code{Class}, but it's also possible to specify a method explicitly in
  a \code{\link{setIs}} call.

  So, if inheritance applies, the \code{as} function calls the
  appropriate method.  If inheritance does not apply, and
  \code{coerceFlag} is \code{FALSE}, \code{NULL} is returned.

  By default, \code{coerceFlag} is \code{TRUE}.  In this case the
  \code{as} function goes on to look for a method for the function
  \code{coerce} for the signature \code{c(from = class(object), to =
    Class)}.

  Method selection is used in the \code{as} function in two special
  ways.
  First,  inheritance is
  applied for the argument \code{from} but not for the argument
  \code{to} (if you think about it, you'll probably agree that you
  wouldn't want the result to be from some class other than the
  \code{Class} specified).
  Second, the function tries to use inheritance information to convert
  the object indirectly, by first converting it to an inherited class.
  It does this by examining the classes that the \code{from} class
  extends, to see if any of them has an explicit conversion method.
  Suppose class \code{"by"} does:  Then the \code{as} function
  implicitly computes \code{as(as(object, "by"), Class)}.

  With this explanation as background, the function \code{setAs} does a
  fairly obvious computation:  It constructs and sets a method for the function
  \code{coerce} with signature \code{c(from, to)}, using the \code{def}
  argument to define the body of the method.  The function \code{coerce}
  exists almost entirely as a repository for such methods, to be
  selected as desribed above by the \code{as} function.  In fact, it
  would usually be a bad idea to call \code{coerce} directly, since then
  you would get inheritance on the \code{to} argument; as mentioned,
  this is not likely to be what you want.
}

%% <FIXME>
%% Currently Rdconv cannot deal with markup in section titles.
%% \section{The Function \code{as} Used in Replacements}{
\section{The Function `as' Used in Replacements}{
  %% </FIXME>    
  When \code{as} appears on the left of an assignment, the intuitive
  meaning is ``Replace the part of \code{object} that was inherited from
  \code{Class} by the \code{value} on the right of the assignment.''

  This usually has a straightforward interpretation, but you can control
  explicitly what happens, and sometimes you should to avoid possible
  corruption of objects.

  When \code{object} inherits from \code{Class} in the usual way, by
  including the slots of \code{Class}, the default \code{as} method is
  to set the corresponding slots in \code{object} to those in
  \code{value}.

  The default computation may be reasonable, but usually only if all
  \emph{other} slots in \code{object} are unrelated to the slots being
  changed.  Often, however, this is not the case.  The class of
  \code{object} may have extended \code{Class} with a new slot whose
  value depends on the inherited slots.  In this case, you may want to
  define a method for replacing the inherited information that
  recomputes all the dependent information.  Or, you may just want to
  prohibit replacing the inherited information directly .

  The way to control such replacements is through the \code{replace}
  argument to function \code{setIs}.  This argument is a method that
  function \code{as} calls when used for replacement.  It can do
  whatever you like, including calling \code{stop} if you want to
  prohibit replacements.  It should return a modified object with the
  same class as the \code{object} argument to \code{as}.

  In R, you can also explicitly supply a replacement method, even in the
  case that inheritance does not apply, through the \code{replace}
  argument to \code{setAs}.  It works essentially the same way, but in
  this case by constructing a method for \code{"coerce<-"}.  (Replace
  methods for coercion without inheritance are not in the original
  description and so may not be compatible with S-Plus, at least not
  yet.)

  When inheritance does apply, coerce and replace methods can be
  specified through either \code{setIs} or \code{setAs}; the effect is
  essentially the same.
  }

\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}

\examples{
## using the definition of class "track" from \link{Classes}

\testonly{
setClass("track",
            representation(x="numeric", y="numeric"))
setClass("trackCurve",
            representation("track", smooth = "numeric"))
}

setAs("track", "numeric", function(from)from@y)

t1 <- new("track", x=1:20, y=(1:20)^2)

as(t1, "numeric")

## The next example shows:
##  1. A virtual class to define setAs for
##     several classes at once.
##  2. as() using inherited information

setClass("ca", representation(a = "character", id = "numeric"))

setClass("cb", representation(b = "character", id = "numeric"))


setClass("id")
setIs("ca", "id")
setIs("cb", "id")


setAs("id", "numeric", function(from) from@id)

CA <- new("ca", a ="A", id = 1)

CB <- new("cb", b = "B", id = 2)

setAs("cb", "ca", function(from)new("ca", a=from@b, id = from@id))

as(CB, "numeric")

\testonly{
## should generate an error (should have been a function of one argument)
try(setAs("track", "numeric", function(x, ...)x@y))

}

}

\author{
  John Chambers
}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\name{class}
\alias{class}
\alias{class<-}
\title{Class of an Object}
\usage{
class(object)

class(object) <- value
}
\description{

Returns the name of the object's class as a character string.

In contrast to the version of this function in the base package, this
version of \code{class} never
returns \code{NULL}.  For objects that do not have a formal class
definition, and do not have the \code{"class"} attribute set, the
value returned is effectively the same as \code{data.class}.

The replacement version of the function sets the class to the value
provided.  For classes that have a formal definition, directly
replacing the class this way is strongly deprecated.  The expression
\code{as(object, value)} is the way to coerce an object to a
particular class.
  
}
\arguments{
\item{object}{
Any R object (including basic objects for which no class is currently
defined).  When assigning the class, however, it must be possible to
coerce the object to the specified class:  the semantics of assigning
a class to \code{object} are equivalent to \code{object <- as(object, value)}.
}
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\seealso{\code{\link{as}}}
\keyword{programming}
\keyword{classes}
\name{getClass}
\alias{getClass}
\alias{getClassDef}
\title{Get Class Definition }
\description{
  Get the definition of a class.
}
\usage{
getClass(Class, .Force = FALSE)
getClassDef(Class, where=-1)
}
\arguments{
  \item{Class}{ the character-string name of the class.}

  \item{.Force}{ if \code{TRUE}, return \code{NULL} if the class is
    undefined; otherwise, an undefined class results in an error.
    }

  \item{where} { where to search for the definition; by default,
    anywhere on the current search list.}
}
\details{
  
  A call to \code{getClass} returns the complete definition of the class supplied as a string,
including all slots, etc. in classes that this class extends. A call to
\code{getClassDef} returns  the definition of the class from that
database, unadorned.  It's usually \code{getClass} you want.

The statement that \code{getClass} fails if the class is undefined is
not quite true at the moment.  A few special vector types and informally
defined classes are allowed, and \code{getClass} returns \code{NULL} for
these. But don't count on it; eventually these holes in the class system
should be plugged.

In any case, if you really want to know whether a class is formally
defined, call \code{\link{isClass}}.


  
}
\value{
  The object defining the class.  This is an object of class
  \code{"classRepEnvironment"}.  However, \emph{do not} deal with the
  contents of the object directly unless you are very sure you know what
  you're doing.  Even then, it is nearly always better practice to use
  functions such as \code{\link{setClass}} and \code{\link{setIs}}.
  Messing up a class object will cause great confusion.
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}

\seealso{ \link{Classes}, \code{\link{setClass}}, \code{\link{isClass}}. }

\examples{
getClass("numeric") ## a built in class

\testonly{
getClass("thisIsAnUndefinedClass", .Force = TRUE) ## returns NULL
try(getClass("thisIsAnUndefinedClass")) ## generates an error
try(getClassDef("thisIsAnUndefinedClass")) ## generates an error
}
}
\keyword{programming}
\keyword{classes}
\name{getMethod}
\alias{getMethod}
\alias{findMethod}
\alias{getMethods}
\alias{selectMethod}
\alias{MethodsListSelect}
\title{ Get the Definition of a Method }
\description{
  A call to \code{getMethod} returns the method
  corresponding a particular generic function and signature (set
  classes for formal arguments). The functions \code{MethodsListSelect}
  and \code{selectMethod} select methods using an environment in which
  arguments to the function have been assigned (they differ in the
  treatment of inheritance).  Neither is intended to be called directly,
  except perhaps in debugging. The function
  \code{getMethods} returns \emph{all} the methods for the generic
  function.

  The function \code{findMethod} returns the package(s) in the search
  list (or in the packages specified by the \code{where} argument) that
  contain a method for this function and signature.
}
\usage{
getMethod(f, signature=character(), where, optional=FALSE)

findMethod(f, signature, where)

getMethods(f, where=-1)

MethodsListSelect(f, env, mlist, fEnv, finalDefault, evalArgs, useInherited)
selectMethod(f, env, optional=False, useInherited, mlist=getMethods(f))

}
\arguments{
  \item{f}{ The character-string name of the generic function.

  In \code{getMethods} only, this argument may be a function definition,
in which case the special methods list object, if any, stored in the environment of the function is
returned.  (This usage is largely for internal purposes; you aren't
likely to have such a function definition for direct use.)}
  \item{signature}{ The signature of classes to match to the arguments of \code{f}.  The vector of strings
      for the classes can be named or not.  If named, the names must match formal
      argument names of \code{f}.  If not named, the signature is assumed to apply to the
      arguments of \code{f} in order.
 }
  \item{where}{ Where to look for the method.  By default, looks in
      all the currently attached databases (i.e., the complete search list). }
  \item{optional}{ If the selection does not produce a unique result,
      an error is generated, unless this argument is \code{TRUE}.  In
      that case, the value returned is either a \code{MethodsList}
      object, if more than one method matches this signature, or
      \code{NULL} if no method matches.}

  \item{mlist}{In \code{selectMethod}, the \code{MethodsList} object
      can be explicitly supplied.  (Unlikely to be used, except in the
      recursive call that finds matches to more than one argument.)}

  \item{env}{The environment in which argument evaluations are done in
    \code{MethodsListSelect}.  Currently must be supplied, but should
    usually be \code{sys.frame(sys.parent())} when calling the function explicitly
    for debugging purposes.}
  \item{fEnv, finalDefault, evalArgs, useInherited}{ Internal-use
      arguments for the function's environment, the method to use as
      the overall default, whether to evaluate arguments, and which
      arguments should use inheritance.}

}
\details{
  A call to \code{getMethod} returns the method for a particular
  function and signature.  As with other \code{get} functions,
  argument \code{where} controls where the function looks (by default
  anywhere in the search list) and argument \code{optional} controls
  whether the function returns \code{NULL} or generates an error if
  the method is not found.  The search for the method makes no use of
  inheritance.

  The function \code{getMethods} returns all the methods for a
  particular generic (in the form of a generic function with the
  methods information in its environment).  The function is called
  from the evaluator to merge method information, and is not intended
  to be called directly.

  The function \code{MethodsListSelect} performs a full search
  (including all inheritance and group generic information: see the
  \link{Methods} documentation page for details on how this works).
  The call returns a possibly revised methods list object,
  incorporating any method found as part of the \code{allMethods}
  slot.

  Normally you won't call \code{MethodsListSelect} directly, but it is
  possible to use it for debugging purposes (only for distinctly
  advanced users!).

  Note that the statement that \code{MethodsListSelect} corresponds to the
  selection done by the evaluator is a fact, not an assertion, in the
  sense that the evaluator code constructs and executes a call to
  \code{MethodsListSelect} when it does not already have a cached method
  for this generic function and signature.  (The value returned is
  stored by the evaluator so that the search is not required next
  time.)

  The \code{selectMethod} function is similar to
  \code{MethodsListSelect} (and calls it) but differs in that it
  is intended to be used with control over which arguments are allowed
  to use inheritance.  The restriction is needed to make sensible
  method selection for coerce methods (the \code{\link{as}} function).
}
\value{
  The call to \code{selectMethod} or \code{getMethod} returns a
  function object, the selected method, if a unique selection exists.
  Otherwise an error is thrown if \code{optional} is \code{FALSE}.  If
  \code{optional} is \code{TRUE}, the value returned is \code{NULL} if
  no method matched, or a \code{MethodsList} object if multiple
  methods matched.

  The call to \code{getMethods} returns the \code{MethodsList} object
  containing all the methods requested.  If there are none,
  \code{NULL} is returned: \code{getMethods} does not generate an
  error in this case.
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package implement a facility for classes and
methods as described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\examples{

}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\name{is}
\alias{is}
\alias{extends}
\alias{setIs}
\title{Is an Object from a Class}
\usage{
is(object, class2)

extends(class1, class2, maybe=TRUE)

setIs(class1, class2, test=NULL, coerce=NULL, replace=NULL, where=-1)

}
\description{
  
  \code{is}: 
  With two arguments, tests whether \code{object} can be treated as from \code{class2}.

With one argument, returns all the super-classes of this object's class.

  
  \code{extends}: 
  Does the first class extend the second class?
Returns \code{maybe} if the extension includes a test.

  
  \code{setIs}: 
  Defines class1 to be an extension of class2.  
}
\arguments{
  \item{object}{Any R object.}
  \item{class1, class2}{
    The names of the classes between which \code{is} relations are to be defined.
  }
  \item{maybe}{What value to return if the relationship is conditional.
  }
  \item{test, coerce, replace}{
    Functions optionally supplied to test whether the relation is
    defined, to coerce the object to \code{class2}, and to alter the
    object so that \code{is(object, class2)} is identical to \code{value}.
  }
  \item{where}{
    Where to store the metadata defining the relationship. Default is
    the global environment.
  }
  
}

\details{
  
  \code{setIs}: 
  
The relationship can be conditional, if a function is supplied as the \code{test}
argument.  If a function is supplied as the \code{coerce} argument, this function will
be applied to any \code{class1} object in order to turn it into a \code{class2} object.

Extension may imply that a \code{class1} object contains a \code{class2} object.  The default
sense of containing is that all the slots of the simpler class are found in the
more elaborate one.  If the \code{replace} argument is supplied as an S replacement
function, this function will be used to implement \code{as(obj, class2) <- value}.

}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\examples{
\testonly{
if(isClass("track"))
  removeClass("track")
if(isClass("trackCurve"))
  removeClass("trackCurve")
if(isClass("trackMultiCurve"))
  removeClass("trackMultiCurve")
## A simple class with two slots
setClass("track",
            representation(x="numeric", y="numeric"))
## A class extending the previous, adding one more slot
}
## a class definition (see \link{setClass} for the example)
setClass("trackCurve",
            representation("track", smooth = "numeric"))
## A class similar to "trackCurve", but with different structure
## allowing matrices for the "y" and "smooth" slots
setClass("trackMultiCurve", representation(x="numeric", y="matrix", smooth="matrix"),
          prototype = structure(list(), x=numeric(), y=matrix(0,0,0), smooth= matrix(0,0,0)))
## Define a multi-curve to extend a single curve ONLY
## if the y data is one variable.
setIs("trackMultiCurve", "trackCurve", test = function(obj) {ncol(slot(obj, "y")) == 1},
      coerce = function(obj) { new("trackCurve", x = slot(obj, "x"),
        y = as.numeric(slot(obj,"y")), curve = as.numeric(slot(obj, "curve")))})

}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\name{languageEl}
\alias{languageEl}
\alias{languageEl<-}
\alias{isGrammarSymbol}
\title{Elements of Language Objects}
\usage{
languageEl(object, which)

isGrammarSymbol(symbol)

}
\description{
  Internal routines to support some operations on language objects.
}
\section{Summary of Functions}{
\describe{  
  \item{\code{languageEl}:}{ 
  extract an element of a language object, consistently
for different kinds of objects.

The 1st., etc. elements of a function are the corresponding
formal arguments, with the default expression if any as value.

The first element of a call is the name or the function object being
called.  

  The 2nd, 3rd, etc. elements are the 1st, 2nd, etc. arguments expressions.
Note that the form of the extracted name is different for R and S-Plus.
When the name (the first element) of a call is replaced, the languageEl replacement
function coerces a character string to the internal form for each system.

The 1st, 2nd, 3rd elements of an \code{if} expression are the test, first, and second branch.

The 1st element of a \code{for} object is the name (symbol) being used in the loop,
the second is the expression for the range of the loop, the third is the body of the loop.

The first element of a \code{while} object is the loop test, and the second the body of
the loop.
}
\item{isGrammarSymbol:}{Checks whether the symbol is part of the
    grammar.  Don't use this function directly.}
}
}
\keyword{internal}
\name{methodUtilities}
\alias{functionBody}
\alias{functionBody<-}
\alias{allNames}
\alias{getFunction}
\alias{el}
\alias{elNamed}
\alias{el<-}
\alias{elNamed<-}
\alias{formalArgs}
\alias{Quote}
\alias{message}
\alias{showDefault}
\title{Utility Functions for Methods and S-Plus Compatibility}
\usage{
functionBody(fun=sys.function(sys.parent()))

allNames(x)

getFunction(name, generic=TRUE, mustFind=TRUE, where)

el(object, where)

elNamed(x, name, mustFind=FALSE)

formalArgs(def)

Quote()

message(...)

showDefault(object, printTo = stdout(), oldMethods = TRUE)

}
\description{
These are utilities, currently in the methods package, that either
provide some functionality needed by the package (e.g., element
matching by name), or add compatibility with S-Plus, or both.
}

\section{Summary of Functions}{
\describe{
  \item{\code{allNames}:}{ 
  the character vector of names (unlike names(), never returns NULL)
}
  
  \item{\code{getFunction}:}{ 
  find the object as a function.
}
  
  \item{\code{elNamed}:}{ 
  get the element of the vector corresponding to name.  Unlike the
  \code{[}, \code{[[}, and \code{$} operators, this function requires %]}}$
  \code{name} to match the element name exactly (no partial matching).
  }
  \item{\code{formalArgs}:}{ 
  Returns the names of the formal arguments of this function.
}
  
  \item{\code{existsFunction}:}{ 
  Is there a function of this name? If \code{generic==FALSE}, generic functions are not counted.
}
  
  \item{\code{findFunction}:}{ 
  return all the indices of the search list on which a function
definition for \code{name} exists.  

  If \code{generic} is \code{FALSE}, ignore generic
functions.
  }
  \item{\code{message}:}{ 
  Output all the arguments, pasted together with no intervening spaces.
}
  \item{\code{showDefault}:}{ 
  Utility, used to enable \code{show} methods to be called by the
  automatic printing (via \code{print.default}).
}
}
}

\keyword{internal}
\name{new}
\alias{new}
%- Also NEED an `\alias' for EACH other topic documented here.
\title{ Generate an Object from a Class }
\description{
  Given the the name or the definition of a class, plus optionally
  data to be included in the object, \code{new} returns an object from that class.
}
\usage{
new(Class, ..., .Force=FALSE)
}
%- maybe also `usage' for other objects documented here.
\arguments{
  \item{Class}{ Either the name of a class (the usual case) or the
    object describing the class (e.g., the value returned by \code{getClass}). }
  \item{\dots}{ Data to include in the new object.  Named arguments
    correspond to slots in the class definition. Unnamed arguments must
    be objects from classes that this class extends.}
  \item{.Force}{ Normally, an attempt to apply \code{new} to a virtual
    or an undefined class generates an error.  If \code{.Force} is
    \code{TRUE}, an ``empty'' object is returned instead.  Users are
    very unlikely to need this argument. }
}
\details{
  The function begins by copying the prototype object from the class
  definition.  Then information is inserted according to the \dots
  arguments, if any, first from the superclasses (the unnamed arguments)
  then from the named slots.  Thus, explicit slots override inherited
  information for the same slot, regardless of the order in which the
  arguments appear.

  Note that the basic vector classes, \code{"numeric"}, etc. are implicitly defined,
  so one can use \code{new} for these classes.

}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}

\seealso{ \link{Classes} }

\examples{
## using the definition of class "track" from \link{Classes}

\testonly{
setClass("track",
            representation(x="numeric", y="numeric"))
setClass("trackCurve",
            representation("track", smooth = "numeric"))

ydata <- rnorm(10); ysmooth <- 1:10}

## a new object with two slots specified
t1 <- new("track", x = seq(along=ydata), y = ydata)

# a new object including an object from a superclass, plus a slot
t2 <- new("trackCurve", t1, smooth = ysmooth)
}
\keyword{programming}
\keyword{classes}
\name{promptClass}
\alias{promptClass}
%- Also NEED an `\alias' for EACH other topic documented here.
\title{ Generate a Shell for Documentation of a Formal Class}
\description{
assembles all relevant slot and method information for a class,
with minimal markup for Rd processing; no QA facilities at present
}
\usage{
promptClass(clName, filename, type = "class", where)
}
%- maybe also `usage' for other objects documented here.
\arguments{
  \item{clName}{ character string naming the class to be documented }
  \item{filename}{ Usually, the filename on which the documentation
    shell should be written.  By
      default it is the topic name for the class documentation,
      followed by ".Rd". See the example below.  The argument can also be any writable \link{connection}.}
  \item{type}{The documentation type to be declared in the output file.}
    \item{where}{
      where to look for the definition of the class and of methods that
      use it.  By default, the function searches for the class
      definition on the currently attached databases.
    }
}
\details{
The class definition is found on the search list.  Using that
definition, information about classes extended and slots is
determined.

In addition, the currently available generics with methods for this
class are found (using \code{\link{getGenerics}}).  Note that these
methods need not be on the same database as the class definition; in
particular, this part of the output may depend on which
packages are currently in the search list.

As with other prompt-style functions, the documentation shell is
written to a file, which will need editing to give information about
the \emph{meaning} of the class.  The output of \code{promptClass} can
only contain information from the metadata about the formal definition
and how it is used.
}
\value{
  The name of the file to which the shell is written (the value is
  \code{\link{invisible}}).
  A message is also printed notifying
  the user about the file.
}
\author{ VJ Carey, \email{stvjc@channing.harvard.edu} and John Chambers }
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\seealso{\code{\link{prompt}} for documentation of functions, 
  \code{\link{promptMethods}} for documentation of method definitions.

  For processing of the edited documentation, either use \code{R cmd
    \link{Rdconv}}, or include the edited file in the \code{man}
  subdirectory of a package.
}
\examples{
\testonly{
## from setClass
## A simple class with two slots
setClass("track",
            representation(x="numeric", y="numeric"))
## A class extending the previous, adding one more slot
setClass("trackCurve",
            representation("track", smooth = "numeric"))
## A class similar to "trackCurve", but with different structure
## allowing matrices for the "y" and "smooth" slots
setClass("trackMultiCurve", representation(x="numeric", y="matrix", smooth="matrix"),
          prototype = list(x=numeric(), y=matrix(0,0,0), smooth= matrix(0,0,0)))

setIs("trackMultiCurve", "trackCurve",
  test = function(obj) {ncol(slot(obj, "y")) == 1},
  coerce = function(obj) { new("trackCurve", x = slot(obj, "x"),
        y = as.numeric(slot(obj,"y")), smooth = as.numeric(slot(obj, "smooth")))})

## from setMethod

setMethod("plot", "track",
 function(x, y, ...) plot(slot(x, "y"), y,  ...)
)
setMethod("plot", c("trackCurve", "missing"),
function(x, y, ...) {
  plot(as(x, "track"))
  if(length(slot(x, "smooth") > 0))
    lines(slot(x, "x"), slot(x, "smooth"))
  }
)

promptClass("trackMultiCurve", stdout())

promptClass("track", stdout())
}
\dontrun{> promptClass("track")
A shell of class documentation has been written to the 
file "track-class.Rd".
}}

\keyword{programming}
\keyword{classes}\name{promptMethods}
\alias{promptMethods}
%- Also NEED an `\alias' for EACH other topic documented here.
\title{ Generate a Shell for Documentation of Formal Methods }
\description{
  Generates a shell of documentation for the methods of a generic
  function, with
}
\usage{
promptMethods(f, filename, addTo = FALSE, inherited=FALSE, type = "methods")
}
\arguments{
  \item{f}{ The name of the generic function whose methods are to be documented.  }
  \item{filename}{ Optional file on which to write the documentation shell.
    If \code{FALSE}, the text is returned, presumably to be used in the
    documentation of the generic function itself (see
    \code{\link{prompt}}).  By default, this is the same as the coded
    topic name for these methods (currently \code{"NAME-methods.Rd"},
    where \code{NAME} is the function name, argument \code{f}).
  }
  \item{addTo}{
    Optionally, text to add to the shell.  This would typically be part
    of the contents of the documentation file for the generic function,
    if you want the generic and the methods documented together.
    }
  \item{inherited}{ Should inherited methods be included?  Default
    \code{FALSE}. }
  \item{type}{The documentation type to be declared in the output file.}
}
\value{
  If \code{filename} is \code{FALSE}, the text generated; otherwise, the
  name of the file written.
}
\seealso{  \code{\link{prompt}} and  \code{\link{promptClass}}  }

\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\keyword{programming}
\keyword{methods}
\name{recover}
\alias{recover}
\title{Browsing on an Error }
\description{
  This function allows the user to browse directly on any of the
  currently active function calls, and is suitable as an error option.
  The expression \code{options(error=recover)} will make this
  the error option.
}
\usage{
recover()
}
\details{
  When called, \code{recover} prints the list of current calls, and
  prompts the user to select one of them.  The standard R
  \code{\link{browser}} is then invoked from the corresponding
  environment; the user can type ordinary S language expressions to be
  evaluated in that environment.

  When finished browsing in this call, type \code{c} to return to
  \code{recover} from the browser.  Type another frame number to browse
  some more, or type \code{0} to exit \code{recover}.

  \emph{WARNING}: Do not use the special \code{Q} command to go directly
  from the browser to the prompt level of the evaluator.  This currently
  interacts with \code{recover} to effectively turn off the error option
  for the next error (on subsequent errors, \code{recover} will be called normally)
  }
\value{
 Nothing useful is returned.  However, you \emph{can} invoke
 \code{recover} directly from a function, rather than through the error option shown
 the usage section.  In this case, execution continues after you type
 \code{0} to exit \code{recover}.
}

\section{Compatibility Note}{
  The R \code{recover} function can be used in the same way as the
  S-Plus function of the same name; therefore, the error option shown is
  a compatible way to specify the error action.  However, the actual
  functions are essentially unrelated and interact quite differently
  with the user.
}

\references{\emph{Programming with Data}, (John M. Chambers, Springer,
  1998).  See the compatibility note above, however.}

\seealso{ See \code{\link{dump.frames}} and \code{\link{debugger}} for
  the more traditional approach to error recovery.}

\keyword{programming}
\name{representation}
\alias{representation}
\title{ Describe A Class Representation }
\description{
  Constructs a description of a class (without verifying the validity of
  the description).  A convenience function in calls to \code{\link{setClass}}.
}
\usage{
representation(...)
}
\arguments{
  \item{...}{
The call to representation takes arguments that are single character
  strings.  Unnamed arguments are classes that a newly defined class
  extends; named arguments name the explicit slots in the new class, and
  specify what class each slot should have.    
    }
  }
\details{
  The \code{representation} function applies tests for the validity of
  the arguments.  Each must specify the name of a class.

  The classes named don't have to exist when \code{representation} is
  called, but if they do, then the function will check for any duplicate
  slot names introduced by each of the inherited classes.
}
\value{
  The value is just the list of arguments, after these have been checked
  for validity.
}
\references{
  The web page \url{http://www.omegahat.org/RSMethods/index.html}
  is the primary documentation.

  The functions in this package emulate the facility for classes
  and methods described in
  \emph{Programming with Data}, (John M. Chambers, Springer, 1998).
  See this book for further details and examples.
}
\author{
  John Chambers
}
\seealso{ \code{\link{setClass}} }

\examples{
## representation for a new class with a directly define slot "smooth"
## which should be a "numeric" object, and extending class "track"
representation("track", smooth ="numeric")
\testonly{
setClass("class1", representation(a="numeric", b = "character"))
setClass("class2", representation(a2 = "numeric", b = "numeric"))
try(setClass("class3", representation("class1", "class2")))

}
}
\keyword{programming}
\keyword{classes}

\name{setClass}
\alias{setClass}
\alias{removeClass}
\alias{resetClass}
\alias{isClass}
\alias{getClasses}
\title{Create a Class Definition}
\description{
Create a formally defined class with specified slots and/or
relationships to other classes.  Also functions to remove a class
definition, to test whether a
class has been defined, to test whether an object is a class definition,
and to reset the internal definition of a class.}
\usage{
setClass(Class, representation, prototype,
         contains=character(), validity, access, where=1, version=FALSE)

removeClass(Class, where=-1)

isClass(Class, formal=TRUE)
isClassDef(object)

getClasses(where)

resetClass(Class)

}
\arguments{
  \item{Class}{ character string name for the class }
  \item{representation}{ the slots that the new class should have
      and/or other classes that this class extends.  Usually a call to
      the \code{\link{representation}} function. }
  \item{prototype}{ an object (usually a list) providing the default
    data for the slots specified in the representation. }
  \item{contains}{ what classes does this class extend?  (These are
      called \emph{superclasses} in some languages.)  When these
      classes have slots, all their slots will be contained in the new
      class as well. }
  \item{where}{ What environment to use to store or remove the definition (as metadata).
    By default, uses the global environment for \code{setClass} and
    searches for a definition to remove, for \code{removeClass}. }
  \item{validity, access, version}{ Control arguments included for
      compatibility with the S-Plus API, but not currently used.  }

    \item{x}{an arbitrary object.}

    \item{formal}{
      Should a formal definition be required?
    }

    \item{object}{
      any R object.
    }
    
}

\details{

  These are the functions that create and manipulate formal class
  definitions.  Brief documentation is provided below.  See the
  references for an introduction and for more details.
 
  \describe{ 
    \item{\code{setClass}:}{ 
      Define Class to be an S-style class.  The effect is to create an
      object, of class \code{"classRepEnvironment"}, and store this
      (hidden) in the specified environment or database.  Objects can be
      created from the class (e.g., by calling \code{\link{new}}),
      manipulated (e.g., by accessing the object's slots), and methods
      may be defined including the class name in the signature (see
      \code{\link{setMethod}}).
    }

    \item{\code{removeClass}:}{ 
      Remove the definition of this class.  Calling this \emph{always}
      resets the version of the class cached for the session.  If
      \code{where=0}, that's all it does.  Otherwise, it removes the
      version from the specified environment or database (from the global
      environment by default).
    }
  
    \item{\code{isClass}:}{ 
      Is this a the name of a formally defined class? (Argument \code{formal} is for
      compatibility and is ignored.)
    }

    \item{\code{isClassDef}:}{ 
      Is this object a class definition (it will be, for example, if it
      is the value of a call to \code{\link{getClass}}, the complete
      definition of a class with its extensions, or to \code{\link{getClassDef}}, the local
      definition  of the class).
    }

    \item{\code{getClasses}:}{
      The names of all the classes formally defined on `where'.
      If called with no argument, all the classes currently known in the session
      (which does not include classes that may be defined on one of the attached
      libraries, but have not yet been used in the session).
    }

    \item{\code{unclass}:}{
      Returns the object containing the values of all the slots in this object's
      class definition (specifically, ithe returned object has attributes corresponding
      to each slot), in the case that the object's class is formally defined with slots.  
      
      For classes that extend a single other class (e.g., a basic class
      such as \code{"numeric"}) the result is an object of that class.
    }
    \item{\code{resetClass}:}{
      Reset the internal definition of a class.  The effect is that
      the next time the definition of this class is needed, it will be
      recomputed from the information on the attached databases.

      This function is called when aspects of the class definition are
      changed.  You would need to call it explicitly if you changed the
      definition of a class that this class extends (but doing that in
      the  middle of a session is living dangerously, since it may
      invalidate existing objects).
      }
  }
}
\section{Inheritance and Prototypes}{
  Defining new classes that inherit from (``extend'') other classes is a
  powerful technique, but has to be used carefully and not over-used.
  Otherwise, you will often get unintended results when you start to
  compute with objects from the new class.

  As shown in the examples below, the simplest and safest form of
  inheritance is to start with an explicit class, with some slots, that
  does not extend anything else.  It only does what we say it does.

  Then extensions will add some new slots and new behavior.

  Another variety of extension starts with one of the basic classes,
  perhaps with the intension of modifying R's standard behavior for that
  class.  Perfectly legal and sometimes quite helpful, but you may need
  to be more careful in this case:  your new class will inherit much of
  the behavior of the basic (informally defined) class, and the results
  can be surprising.  Just proceed with caution and plenty of testing.

  As an example, the class \code{"matrix"} is included in the
  pre-defined classes, to behave essentially as matrices do without
  formal class definitions.  Suppose we don't like all of this; in
  particular, we want the default matrix to have 0 rows and columns (not
  1 by 1 as it is now).
  
  \code{setClass("myMatrix", "matrix", prototype = matrix(0,0,0))}
  
  The arguments above illustrate two short-cuts relevant to such
  examples.  We abbreviated the \code{representation} argument to the
  single superclass, because the new class doesn't add anything to the
  representation of class \code{"matrix"}.  Also, we provided an object
  from the superclass as the prototype, not a list of slots.
}

\references{
  The web page \url{http://www.omegahat.org/RSMethods/index.html}
  is the primary documentation.

  The functions in this package emulate the facility for classes
  and methods described in
  \emph{Programming with Data}, (John M. Chambers, Springer, 1998).
  See this book for further details and examples.
}
\author{
  John Chambers
}
\examples{
\testonly{
if(isClass("track"))
  removeClass("track")
if(isClass("trackCurve"))
  removeClass("trackCurve")
if(isClass("trackMultiCurve"))
  removeClass("trackMultiCurve")
}
## A simple class with two slots
setClass("track",
            representation(x="numeric", y="numeric"))
## A class extending the previous, adding one more slot
setClass("trackCurve",
            representation("track", smooth = "numeric"))
## A class similar to "trackCurve", but with different structure
## allowing matrices for the "y" and "smooth" slots
setClass("trackMultiCurve", representation(x="numeric", y="matrix", smooth="matrix"),
          prototype = list(x=numeric(), y=matrix(0,0,0), smooth= matrix(0,0,0)))
##
## Suppose we want  trackMultiCurve to be like trackCurve when there's only
## one column
## First, the wrong way. 
try(setIs("trackMultiCurve", "trackCurve",
  test = function(obj) {ncol(slot(obj, "y")) == 1}))

## why didn't that work?  You can only override the slots "x", "y", and "smooth"
## if you provide an explicit coerce function to correct any inconsistencies:

setIs("trackMultiCurve", "trackCurve",
  test = function(obj) {ncol(slot(obj, "y")) == 1},
  coerce = function(obj) { new("trackCurve", x = slot(obj, "x"),
        y = as.numeric(slot(obj,"y")), smooth = as.numeric(slot(obj, "smooth")))})
\testonly{
tMC <- new("trackMultiCurve")
is.matrix(slot(tMC, "y"))
is.matrix(slot(tMC, "smooth"))
setClass("myMatrix", "matrix", prototype = matrix(0,0,0))
nrow(new("myMatrix")) # 0
nrow(new("matrix")) # 1
## simple test of prototype data
xxx <- rnorm(3)
setClass("xNum", representation(x = "numeric"), prototype = list(x = xxx))
stopifnot(identical(new("xNum")@x, xxx))



}


}

\seealso{\code{\link{Methods}}, \code{\link{setSClass}}}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\name{setGeneric}
\alias{setGeneric}
\alias{setGroupGeneric}
\title{Define a New Generic Function}
\description{
 Create a new generic function of the given name, for which formal methods can
 then be defined.
}
\usage{
setGeneric(name, def, group=NULL, valueClass=NULL, where=1, doAssign)

setGroupGeneric(name, def, group=NULL, valueClass=NULL, knownMembers, where=1)
}
\arguments{
  \item{name}{ The character string name of the generic function.  In
    the simplest and most common case, a function of this name is
    already defined.  The existing function may be non-generic or
    already a generic (see the details).
  }
  \item{def}{ An optional function object, defining the generic.  This
    argument is usually only needed (and is then required) if there is
    no current function of this name. In that case, the formal arguments
    and default values for the generic are taken from \code{def}.  See
    also argument \code{useAsDefault}.
  }
  \item{group}{ Optionally, a character string giving the group of
    generic functions to which this function belongs.  Methods can be
    defined for the corresponding group generic, and these will then
    define methods for this specific generic function, if no method has
    been explicitly defined for the corresponding signature.  See the
    references for more discussion.
  }
  \item{valueClass}{ An optional character string defining the class to
    asserted to be given to the value returned by this generic
    function. By default, the generic function can return any object.
    (At the moment, the assertion supplied in this argument is not
    enforced or checked.)
   }
  \item{where}{ Where to store the resulting initial methods definition,
    and possibly the generic function; by
    default, stored into the global environment.
  }
  \item{doAssign}{ Should a new generic version of the function be
    assigned?  The default action depends on whether a generic version
    currently exists.  If not, one will be assigned to \code{where},
    except that primitive functions in the base package are never turned
    into explicit generic functions (they are dispatched from the
    internal code in the evaluator).

    You can supply \code{doAssign} as \code{TRUE} to force assigning a
    generic function even if one already exists, or as \code{FALSE} to
    prevent assigning the generic in any case (for example, because you
    know one exists on another package).  But the rule of not assigning
    generics for primitives cannot be overriden by setting
    \code{doAssign} to \code{TRUE}.
  }

  \item{knownMembers}{
    (For \code{setGroupGeneric} only)  The names of functions that are known to be
    members of this group.  This information is used to reset cached
    definitions of the member generics when information about the group
    generic is changed.
    }
}
\details{
  The \code{setGeneric} function is called to initialize a generic
  function in an environment (usually the global environment), as
  prepartion for defining some methods for that function.

  The simplest and most common situation is that \code{name} is already
  a function, either an ordinary non-generic function or else a generic
  function in another environment.  In the second case, essentially all
  you will be doing is to make a copy of the existing generic, without
  its methods, in the current environment.  \emph{Only} the \code{name}
  argument will be used.  The new generic \emph{must} agree with the
  current one in essentially everything except for the methods defined.

  The other simple and common situation is that you already have a
  non-generic function (probably in the same place you plan to save the
  generic), and now want to turn this function into a generic.  In this
  case, too, you will most often supply only \code{name}.  The existing
  function becomes the default method, and the special \code{group} and
  \code{valueClass} properties remain unspecified.

  The \code{setGroupGeneric} function behaves like \code{setGeneric} except that
  it constructs a group generic function, differing in two ways from an
  ordinary generic function.  First,
  this function cannot be called directly, and the body of the function
  created will contain a stop call with this information.  Second, the
  group generic function contains information about the known members of
  the group, used to keep the members up to date when the group
  definition changes, through changes in the search list or direct
  specification of methods, etc.
}
\value{
  The \code{setGeneric} function exists for its side effect:  saving the
  generic function to allow methods to be specified later.  It returns \code{name}.
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}

\author{
  John Chambers
}

\seealso{
  \code{\link{Methods}} for a discussion of other functions to
  specify and manipulate the methods of generic functions.
}

\keyword{ programming }
\keyword{ methods }
\name{setMethod}
\alias{setMethod}
\alias{removeMethod}
\title{ Create and Save a Method }
\description{
  Create and save a formal method for a given function and list of classes.
}
\usage{
setMethod(f, signature=character(), definition, where=1, valueClass)

removeMethod(f, signature, where)
}
\arguments{
  \item{f}{ The character-string name of the generic function. }
  \item{signature}{ A match of formal argument names for \code{f} with
      the character-string names of corresponding classes.  This
      argument can also just be the vector of class names, in which case
      the first name corresponds to the first formal argument, the
      next to the second formal argument, etc.}
  \item{definition}{ A function definition, which will become the method
      called when the arguments in a call to \code{f} match the
      classes in \code{signature}, directly or through inheritance. }
  \item{where}{ The database in which to store the definition of the
    method; by default, the current global environment.

  For \code{removeMethod}, the default is the location of the (first)
  instance of the method for this signature.}
  \item{valueClass}{ If supplied, this argument asserts that the
      method will return a value of this class.  (At present this
      argument is stored but not explicitly used.) }
}
\value{

These functions exist for their side-effect, in setting or removing a
method in the object defining methods for the specified generic.

The value returned by \code{removeMethod} is \code{TRUE} if a method
was found to be removed.
}
\details{
  R methods for a particular generic function are stored in an object
  of class \code{\link{MethodsList}}, which in turn is stored with the
  definition of the generic function.  The effect of calling
  \code{setMethod} is to store \code{definition}  in a \code{MethodsList}
  object in a definition of the generic function on database
  \code{where}.   If no such function exists (on that database) one
  will be created, by copying the generic function from where it is
  found in the current search list.  Finally, if \code{f} doesn't
  exist as a generic function, but there is an ordinary function of
  the same name and the same formal arguments, a new generic function
  is created, and the previous non-generic version of \code{f} becomes
  the default method.

  Methods are stored in a hierarchical structure, by formal arguments
  to \code{f}:  see \code{\link{MethodsList}} for details.  The class
  names in the signature can be any formal class, plus predefined basic
  classes such as \code{"numeric"}, \code{"character"}, and
  \code{"matrix"}.  Two additional special class names can appear:
  \code{"ANY"}, meaning that this argument can have any class at all;
  and \code{"missing"}, meaning that this argument \emph{must not}
  appear in the call in order to match this signature.  Don't confuse
  these two:  if an argument isn't mentioned in a signature, it
  corresponds implicitly to class \code{"ANY"}, not to
  \code{"missing"}.  See the example below.

  While \code{f} can correspond to methods defined on several packages
  or databases, the underlying model is that these together make up
  the definition for a single generic function.  When R proceeds to
  select and evaluate methods for \code{f}, the methods on the current
  search list are merged to form a single generic.  In particular, all
  the versions of \code{f} and all the methods must correspond to the
  same formal arguments (including, in the present definition, the
  same default expressions for the arguments).  For compatibility with
  S-Plus, the current implementation enforces this partly with a
  warning and a reconstruction of a method that fails to match, but
  don't count on this for the future:  Make the formal arguments of
  \code{definition} match those of the generic..
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\examples{
\testonly{  library(modreg)
  setClass("track",
    representation(x="numeric", y = "numeric"))
  setClass("trackCurve", representation("track",
    smooth = "numeric"))
}

## methods for plotting track objects (see the example for \link{setClass})
##
## First, with only one object as argument:
setMethod("plot", signature(x="track", y="missing"),
  function(x,  y, ...) plot(slot(x, "x"), slot(x, "y"), ...)
)
## Second, plot the data from the track on the y-axis against anything
## as the x data.
setMethod("plot", signature(y = "track"),
 function(x, y, ...) plot(x, slot(y, "y"), ...)
)
## and similarly with the track on the x-axis (using the short form of
## specification for signatures)
setMethod("plot", "track",
 function(x, y, ...) plot(slot(x, "y"), y,  ...)
)
t1 <- new("track", x=1:20, y=(1:20)^2)
tc1 <- new("trackCurve", t1)
slot(tc1, "smooth") <- smooth.spline(slot(tc1, "x"), slot(tc1, "y"))$y #$
plot(t1)
plot(qnorm(ppoints(20)), t1)
## An example of inherited methods.
setMethod("plot", c("trackCurve", "missing"),
function(x, y, ...) {
  plot(as(x, "track"))
  if(length(slot(x, "smooth") > 0))
    lines(slot(x, "x"), slot(x, "smooth"))
  }
)
## the plot of tc1 alone has an added curve; other uses of tc1
## are treated as if it were a "track" object.
plot(tc1)
plot(qnorm(ppoints(20)), tc1)

## defining methods for a special function.
## Although "[" and "length" are not ordinary functions
## methods can be defined for them.
setMethod("[", "track",
  function(x, i, j, ..., drop) {
    x@x <- x@x[i]; x@y <- x@y[i]
    x
  })
plot(t1[1:15])

setMethod("length", "track", function(x)length(x@y))
length(t1)

## methods can be defined for missing arguments as well
setGeneric("summary") ## make the function into a generic

## A method for summary()
## The method definition can include the arguments, but
## if they're omitted, class "missing" is assumed.

setMethod("summary", "missing", function() "<No Object>")

\testonly{

stopifnot(identical(summary(), "<No Object>"))

## for the primitives
## inherited methods

length(tc1)
tc1[-1]

## make sure old-style methods still work.
t11 <- t1[1:15]
identical(t1@y[1:15], t11@y)

## S3 methods, with nextMethod
form <- y ~ x
form[1]

## S3 arithmetic methods
ISOdate(1990, 12, 1)- ISOdate(1980, 12, 1)

## arithmetic:  switch to an "Arith" method when this automatically
## generates methods for its member functions.

setMethod("-", c("track", "numeric"), function(e1, e2){e1@y <- e1@y -e2; e1})

t1  - 100.

## check it hasn't screwed up S3 methods
ISOdate(1990, 12, 1)- ISOdate(1980, 12, 1)

## verify we can remove methods and generic

stopifnot(removeMethods("-"))
stopifnot(removeMethods("length"))
stopifnot(removeMethods("plot"))

## methods for plotData
plotData <- function(x, y, ...) plot(x, y, ...)

setGeneric("plotData")

setMethod("plotData", signature(x="track", y="missing"),
  function(x,  y, ...) plot(slot(x, "x"), slot(x, "y"), ...)
)
## and now remove the whole generic
stopifnot(removeGeneric("plotData"))
stopifnot(!exists("plotData", 1))

}
}

\seealso{ \link{Methods}, \code{\link{MethodsList}} for details of the
  implementation}

\keyword{programming}
\keyword{classes}
\keyword{classes}
\keyword{methods}
\name{setSClass}
\alias{setSClass}
\title{ Low-level Class definition }
\description{
 This is the lower-level version of \code{\link{setClass}}.  Unless you
 really know why you are calling it, use \code{setClass} instead.
}
\usage{
setSClass(name, properties=list(), extends=character(),
   prototype=NULL, generatorFunction, where=1,
   subclasses=character(), virtual=NA, validity, access)
}

\arguments{
  \item{name}{ character string name for the class }
  \item{properties}{ the \code{representation} argument to \code{setClass} }
  \item{extends}{ what classes does this class extend }
  \item{prototype}{ an object (usually a list) providing the default
    data for the slots specified in the representation. }
  \item{generatorFunction}{ an optional function to use in generating
    new objects from the class }
  \item{where}{ where to store the resulting definition (as metadata).
    By default, uses the global environment. }
  \item{subclasses}{ Classes that extend \emph{this} class.  }
  \item{virtual}{ Is this known to be a virtual class? }
  \item{validity, access}{Optional arguments for validity method and
    access restrictions.  At the time of writing, these are included for
    compatibility and are not used.  In the future, however, the validity method
    is likely to be relevant.  See \emph{Programming with Data} for its interpretation.}
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\seealso{ \code{\link{setClass}} }
\keyword{programming}
\keyword{classes}

\name{show}
\alias{show}
\title{Show an Object}
\usage{
show(object)

showDefault(object, printTo = stdout(), oldMethods = TRUE)
}
\description{
  Display the object, by printing, plotting or whatever suits its class.

The function \code{show} exists to be specialized by methods; the
default method calls \code{showDefault}.  

With library \code{methods} attached, methods for \code{show} will
usually be invoked for automatic printing (see the details).

The function \code{showDefault} allows redirection of output and
optional use of old-style print methods, but normally will not be called directly.

}
\arguments{
  \item{object}{Any R object}
  
\item{printTo}{Either a file or \link{connection}, or else
    \code{FALSE}.  In the latter case, the lines of text that would
    have been printed are returned as the value of the call (in a
    character vector with one element per line of output).
  }
  \item{oldMethods}{Should old-style print methods be used for this
    object?  \code{TRUE} by default if called directly, but \code{FALSE}
    when called from the methods package for automatic printing (to
    avoid potential recursion; see the
    details below).
}
}
\value{ \code{show} returns an invisible \code{NULL}.

  For \code{showDefault}, if \code{printTo} is
  \code{FALSE}, the value is a character vector containing the lines that would
  otherwise have been printed.
}
\details{
  The \code{methods} package overrides the base definition of
  \code{print.default} to arrange for automatic printing to honor
  methods for the function \code{show}.  This does not quite manage to
  override old-style printing methods, since the automatic printing in
  the evaluator will look first for the old-style method.

  If you have a class \code{myClass} and want to define a method for
  \code{show}, all will be well unless there is already a function named
  \code{print.myClass}.  In that case, to get your method dispatched for
  automatic printing, it will have to be a method for \code{print}.  A
  slight cheat is to override the function \code{print.myClass} yourself,
  and then call that function also in the method for \code{show}
  with signature \code{"myClass"}.
}
\seealso{ \code{\link{showMethods}} prints all the methods for one or
  more functions;  \code{\link{showMlist}} prints individual methods lists;
  \code{\link{showClass}} prints class definitions.  Neither of
  the latter two normally needs to be called directly.
}
\examples{
## following the example shown in the setMethod documentation ...
setClass("track",
         representation(x="numeric", y="numeric"))
setClass("trackCurve", 
         representation("track", smooth = "numeric"))

t1 <- new("track", x=1:20, y=(1:20)^2)

tc1 <- new("trackCurve", t1)

setMethod("show", "track",
  function(object)print(rbind(x = object@x, y=object@y))
)
## The method will now be used for automatic printing of t1

t1

\dontrun{  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
x    1    2    3    4    5    6    7    8    9    10    11    12
y    1    4    9   16   25   36   49   64   81   100   121   144
  [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
x    13    14    15    16    17    18    19    20
y   169   196   225   256   289   324   361   400
}
## and also for tc1, an object of a class that extends "track"
tc1

\dontrun{  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
x    1    2    3    4    5    6    7    8    9    10    11    12
y    1    4    9   16   25   36   49   64   81   100   121   144
  [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20]
x    13    14    15    16    17    18    19    20
y   169   196   225   256   289   324   361   400
}
}
\keyword{programming}
\name{showMethods}
\alias{showMethods}
\title{ Show all the methods for the specified function(s)}
\description{
  Show a summary of the methods for one or more generic functions,
  possibly restricted to those involving specified classes.
}
\usage{
showMethods(f=character(), where=-1, classes=NULL, includeDefs=FALSE, 
    inherited=TRUE, printTo = stdout())
}
%- maybe also `usage' for other objects documented here.
\arguments{
  \item{f}{ One or more function names.  If omitted, all the functions
    on database \code{where} will be examined.
    }
  \item{where}{If \code{where} is supplied, the methods definition from that database will be used; otherwise,
the current definition is used (which will include inherited methods that have arisen so
far in the session).  }
  \item{classes}{ If argument \code{classes} is supplied, it is a vector of class names
that restricts the displayed
results to those methods whose signatures include one or more of those
classes. }
  \item{includeDefs}{ If \code{includeDefs} is \code{TRUE}, include the definitions of the
    individual methods in the printout. }
  \item{inherited}{ If \code{inherits} is \code{TRUE}, then methods that have been found by inheritance, so
far in the session, will be included and marked as inherited. }
\item{printTo}{The connection on which the printed information will be
    written.  If \code{printTo} is \code{FALSE}, the output will be
    collected as a character vector and returned as the value of the
    call to \code{showMethod}.   See \code{\link{show}}.
    }
}
\details{
 The output style is different from S-Plus in that it does not show the database
from which the definition comes, but can optionally include the method definitions.

}
\value{
  If \code{printTo} is \code{FALSE}, the character vector that would
  have been printed is returned; otherwise the value is the connection or filename. 
}
\references{
The web page \url{http://www.omegahat.org/RSMethods/index.html} is the primary documentation.

The functions in this package emulate the facility for classes and methods described in
\emph{Programming with Data}, (John M. Chambers, Springer, 1998).  See this book
for further details and examples.
}
\author{
  John Chambers
}
\seealso{\code{\link{setMethod}}, and \code{\link{GenericFunctions}}
  for other tools involving methods; \code{\link{show}} for }
\examples{
\testonly{
setClass("track",
            representation(x="numeric", y="numeric"))
## First, with only one object as argument:
setMethod("plot", signature(x="track", y="missing"),
  function(x,  y, ...) plot(slot(x, "x"), slot(x, "y"), ...)
)
## Second, plot the data from the track on the y-axis against anything
## as the x data.
setMethod("plot", signature(y = "track"),
 function(x, y, ...) plot(x, slot(y, "y"), ...)
)
setMethod("plot", "track",
 function(x, y, ...) plot(slot(x, "y"), y,  ...)
)
}
## assuming the methods for plot
## are set up as in the documentation for setMethod,
## print (without definitions) the methods that involve
## class "track"
showMethods("plot", classes = "track")
\dontrun{
Function "plot":
x = ANY, y = track
x = track, y = missing
x = track, y = ANY}
}
\keyword{methods}
\name{slot}
\alias{slot}
\alias{slot<-}
\alias{@<-}
\alias{slotNames}
\title{ The Slots in an Object from a Formal Class }
\description{
  These functions return or set information about the individual slots
  in an object.
}
\usage{

object@name
object@name <- value

slot(object, name)
slot(object, name) <- value

slotNames(x)
}
\arguments{
  \item{object}{ An object from a formally defined class.}
  \item{name}{ The character-string name of the slot. The name must be a valid
    slot name:  see Details below.}
  \item{value} { A new value for the named slot.  The value must be
    valid for this slot in this object's class.}

  \item{x}{Either the name of a class or an object from that class. Print
    \code{\link{getClass}(class)} to see the full description of the slots.} 
}
\details{
  The \code{"@"} operator and the \code{slot} function extract or
  replace the formally defined slots for the object.  The operator
  takes a fixed name, which can be unquoted if it is syntactically a
  name in the language.  A slot name can be any non-empty string, but
  if the name is not made up of letters, numbers, and \code{"."}, it
  needs to be quoted.

  In the case of the \code{slot} function, the slot name can be any
  expression that evaluates to a valid slot in the class definition.
  Generally, the only reason to use the functional form rather than
  the simpler operator is \emph{because} the slot name has to be computed.
  
  The definition of the class contains the names of all slots diretly
  and indirectly defined.  Each slot has a name and an associated
  class.  Extracting a slot returns an object from that class.  Setting
  a slot first coerces the value to the specified slot and then stores
  it.

  Unlike attributes, slots are not partially matched, and asking for (or
  trying to set) a slot with an invalid name for that class generates an
  error.
}
\references{
  Chambers, J. M. (1998)
  \emph{Programming with Data}, Springer.
  
  The web page \url{http://www.omegahat.org/RSMethods/index.html}
  is the primary documentation.
}
\author{
  John Chambers
}

\seealso{
  \code{\link{@}}, \code{\link{Classes}}, \code{\link{Methods}},
  \code{\link{getClass}} }

\examples{
\dontrun{
  slot(myTrack, "x")
  slot(myTrack, "y") <- log(slot(myTrack, "x"))

  slotNames("track")
}}
\keyword{programming}
\keyword{classes}

\name{substituteDirect}
\alias{substituteDirect}
\title{SubstituteDirect}
\usage{
substituteDirect(object, frame, cleanFunction=T)
}
\description{
  Substitute for the variables named in the second argument the corresponding
objects, substituting into \code{object}.  The argument \code{frame}
is a named list; if omitted, the environment of the caller is used.

This function differs from the ordinary \code{substitute} in that it treats its first argument
in the standard S way, by evaluating it.  In contrast, \code{substitute} does
not evaluate its first argument.

The goal is to replace this with an \code{eval=} argument to \code{\link{substitute}}.

}
\examples{
}
\keyword{internal}
\name{validObject}
\alias{validObject}
\alias{setValidity}
\alias{getValidity}
\title{ Test the Validity of an Object }
\description{
  The validity of \code{object} related to its class definition is
  tested.  If the object is valid, \code{TRUE} is returned; otherwise,
  either a vector of strings describing validity failures is returned,
  or an error is generated (according to whether \code{test} is
  \code{TRUE}).

  The functions \code{getValidity} and \code{setValidity} get and set
  the validity method of a class.  This method is a function of one
  object that returns \code{TRUE} or a description of the non-validity.
}
\usage{
validObject(object, test)

getValidity(ClassDef)
setValidity(ClassDef, method)
}
\arguments{
  \item{object}{ Any object, but not much will happen unless the
    object's class has a formal definition.}
  \item{test}{ If \code{test} is \code{TRUE}, and validity fails the
    function returns a vector of strings describing the problems.  If
    \code{test} is \code{FALSE} (the default) validity failure generates
    an error.}

  \item{ClassDef}{The name of the class whose validity method is to be set.}
  \item{method}{A validity method;  that is, either \code{NULL} or a function of one argument
    (the \code{object}).  Like \code{validObject}, the function should return
    \code{TRUE} if the object is valid, and one or more descriptive
    strings if any problems are found.  Unlike \code{validObject}, it
    should never generate an error.

    Note that validity methods do not have to check validity of any
    slots or superclasses:  the logic of \code{validObject} ensures
    these tests are done once only.  As a consequence, if one validity
    method wants to use another, it should extract and call the method from the
    other definition of the other class by calling
    \code{\link{getValidity}}:  it should \emph{not} call \code{validObject}.}
}
\details{
  Validity testing takes place ``bottom up'':  first the validity of the
  object's slots, if any, is tested.  Then for each of the classes that
  this class extends (the ``superclasses''), the explicit validity
  method of that class is called, if one exists.  Finally, the validity
  method of \code{object}'s class is called, if there is one.

  Testing generally stops at the first stage of finding an error, except
  that all the slots will be examined even if a slot has failed its
  validity test.
}
\value{
  \code{validObject} returns \code{TRUE} if the object is valid.  Otherwise a vector of strings
  describing problems found, except that if \code{test} is \code{FALSE},
  validity failure generates an error, with the corresponding strings
  in the error message.
}
\references{
  The web page \url{http://www.omegahat.org/RSMethods/index.html}
  is the primary documentation.

  The functions in this package emulate the facility for classes
  and methods described in
  \emph{Programming with Data}, (John M. Chambers, Springer, 1998).
  See this book for further details and examples.
}
\author{
  John Chambers
}

\seealso{ \code{\link{setClass}}. }

\examples{
  setClass("track",
    representation(x="numeric", y = "numeric"))
  t1 <- new("track", x=1:10, y=sort(rnorm(10)))
  ## A valid "track" object has the same number of x, y values
  validTrackObject <- function(x){
    if(length(x@x) == length(x@y)) TRUE
    else paste("Unequal x,y lengths: ", length(x@x), ", ", length(x@y),
    sep="")
  }
  ## assign the function as the validity method for the class
  setValidity("track", validTrackObject)
  ## t1 should be a valid "track" object
  validObject(t1)
  ## Now we do something bad
  t1@x <- 1:20
  ## This should generate an error
  try(validObject(t1))
}

\keyword{programming}
\keyword{classes}
\name{.BasicFunsList}
\alias{.BasicFunsList}
\non_function{}
\title{List of Builtin and Special Functions}
\description{
  A named list providing instructions for turning builtin and special
  functions into generic functions.

  Functions in R that are defined as \code{.Primitive(<name>)} are not
  suitable for formal methods, because they lack the basic reflectance
  property.  You can't find the argument list for these functions by
  examining the function object itself.

  Future versions of R may fix this by attaching a formal argument list
  to the corresponding function.  While generally the names of arguments
  are not checked by the internal code implementing the function, the
  number of arguments frequently is.

  In any case, some definition of a formal argument list is needed if
  users are to define methods for these functions.  In particular, if
  methods are to be merged from multiple libraries, the different sets
  of methods need to agree on the formal arguments.

  In the absence of reflectance, this list provides the relevant
  information  via a dummy function associated with each of the known
  specials for which methods are allowed.

  At the same, the list flags those specials for which methods are
  meaningless (e.g., \code{for}) or just a very bad idea (e.g.,
  \code{.Primitive}).

  A generic function created via \code{\link{setMethod}}, for
  example, for one of these special functions will have the argument
  list from \code{.BasicFunsList}.  If no entry exists, the argument
  list \code{(x, ...)}  is assumed.
}
\keyword{ programming }
\keyword{ methods }
