\name{BasicClasses}
\docType{class}
\alias{character-class}
\alias{complex-class}
\alias{double-class}
\alias{expression-class}
\alias{externalptr-class}
\alias{integer-class}
\alias{list-class}
\alias{logical-class}
\alias{numeric-class}
\alias{single-class}
\alias{vector-class}
\alias{NULL-class}
\alias{function-class}
\alias{ANY-class}
\alias{VIRTUAL-class}
\alias{missing-class}
\title{Classes Corresponding to Basic Data Types }
\description{
  Formal classes exist corresponding to the basic R data types, allowing
  these types to be used in method signatures, as slots in class
  definitions, and to be extended by new classes.}
\usage{
### The following are all basic vector classes.
### They can appear as class names in method signatures,
### in calls to as(), is(), and new().
"character"
"complex"
"double"
"expression"
"integer"
"list"
"logical"
"numeric"
"single"

### the class
"vector"
### is a virtual class, extended by all the above

### The following are additional basic classes
"NULL"     #  NULL objects
"function" #  function objects, including primitives
"externalptr" # raw external pointers for use in C code

"ANY"  # virtual classes used by the methods package itself
"VIRTUAL"
"missing"
}
\section{Objects from the Classes}{
  Objects can be created by calls of the form \code{new(Class, ...)},
  where \code{Class} is the quoted class name, and the remaining
  arguments if any are objects to be interpreted as vectors of this
  class.  Multiple arguments will be concatenated.

  The class \code{"expression"} is slightly odd, in that the \dots
  arguments will \emph{not} be evaluated; therefore, don't enclose them
  in a call to \code{quote()}.
}
\section{Extends}{
  Class \code{"vector"}, directly.
}
\section{Methods}{
  \describe{
    \item{coerce}{Methods are defined to coerce arbitrary objects to
      these classes, by calling the corresponding basic function, for
      example, \code{as(x, "numeric")} calls \code{as.numeric(x)}. }
  }
}
\keyword{classes}
\eof
\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 \dQuote{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}
\eof
\name{Documentation}
\alias{Documentation}
\alias{Documentation-class}
\alias{Documentation-methods}
\title{Using and Creating On-line Documentation for Classes and
  Methods}
\description{Special documentation can be supplied to describe the
  classes and methods that are created by the software in the methods
  package.  Techniques to access this documentation and to create it
  in R help files are described here.}
\section{Getting documentation on classes and methods}{
  You can ask for on-line help for class definitions, for specific
  methods for a generic function, and for general discussion of
  methods for a generic function.  These requests use the \code{?}
  operator (see \code{\link[base]{help}} for a general description of
  the operator).  Of course, you are at the mercy of the implementer
  as to whether there \emph{is} any documentation on the corresponding
  topics.

  Documentation on a class uses the argument \code{class} on the left
  of the \code{?}, and the name of the class on the right; for
  example,

\code{class ? genericFunction}

to ask for documentation on the class \code{"genericFunction"}.

When you want documentation for the methods defined for a particular
function, you can ask either for a general discussion of the methods
or for documentation of a particular method (that is, the method that
would be selected for a particular set of actual arguments).

Overall methods documentation is requested by
calling the \code{?} operator with \code{methods} as the left-side
argument and the name of the function as the right-side argument. For
example,

\code{methods ? initialize}

asks for documentation on the methods for the \code{\link{initialize}}
function.

Asking for documentation on a particular method is done by giving a
function call expression as the right-hand argument to the \code{"?"}
operator.  There are two forms, depending on whether you prefer to
give the class names for the arguments or expressions that you intend
to use in the actual call.

If you planned to evaluate a function call, say \code{myFun(x, sqrt(wt))}
and wanted to find out something about the method that would be used
for this call, put the call on the right of the \code{"?"} operator:

\code{?myFun(x, sqrt(wt))}

A method will be selected, as it would be for the call itself, and
documentation for that method will be requested.  If \code{myFun} is
not a generic function, ordinary documentation for the function will
be requested.

If you know the actual classes for which you would like method
documentation, you can supply these explicitly in place of the
argument expressions.  In the example above, if you want method
documentation for the first argument having class \code{"maybeNumber"}
and the second \code{"logical"}, call the \code{"?"} operator, this
time with a left-side argument \code{method}, and with a function call
on the right using the class names as arguments:

\code{method ? myFun("maybeNumber", "logical")}

Once again, a method will be selected, this time corresponding to the
specified classes, and method documentation will be requested.  This
version only works with generic functions.

The two forms each have advantages.  The version with actual arguments
doesn't require you to figure out (or guess at) the classes of the
arguments.
On the other hand, evaluating the arguments may take some time,
depending on the example.
The version with class names does require you to pick classes, but
it's otherwise unambiguous.  It has a subtler advantage, in that the
classes supplied may be virtual classes, in which case no actual
argument will have specifically this class.  The class
\code{"maybeNumber"}, for example, might be a class union (see the
example for \code{\link{setClassUnion}}).

In either form, methods will be selected as they would be in actual
computation, including use of inheritance and group generic
functions.  See \code{\link{selectMethod}} for the details, since it is
the function used to find the appropriate method.

}
\section{Writing Documentation for Methods}{
The on-line documentation for methods and classes uses some extensions
to the R documentation format to implement the requests for class and
method documentation described above.  See the document \emph{Writing
  R Extensions} for the available markup commands (you should
have consulted this document already if you are at the stage of
documenting your software).

In addition to the specific markup commands to be described, you can
create an initial, overall file with a skeleton of documentation for
the methods defined for a particular generic function:

\code{promptMethods("myFun")}

will create a file, \file{myFun-methods.Rd} with a skeleton of
documentation for the methods defined for function \code{myFun}.
The output from \code{promptMethods} is suitable if you want to
describe all or most of the methods for the function in one file,
separate from the documentation of the generic function itself.
Once the file has been filled in and moved to the \file{man}
subdirectory of your source package, requests for methods
documentation will use that file, both for specific methods
documentation as described above, and for overall documentation
requested by

\code{methods ? myFun}

You are not required to use \code{promptMethods}, and if you do, you
may not want to use the entire file created:
\itemize{
\item If you want to document the methods in the file containing the
    documentation for the generic function itself, you can
    cut-and-paste to move the \code{\\alias} lines and the
    \code{Methods} section from the file created by
    \code{promptMethods} to the existing file.

\item On the other hand, if these are auxiliary methods, and you only
    want to document the added or modified software, you should strip
    out all but the relevant \code{\\alias} lines for the methods of
    interest, and remove all but the corresponding \code{\\item}
    entries in the  \code{Methods} section. Note that in this case you
    will usually remove the first  \code{\\alias} line as well, since
    that is the marker for general methods documentation on this
    function (in the example, \code{\\alias\{myfun-methods\}}).
}

If you simply want to direct documentation for one or more methods to
a particular R documentation file, insert the appropriate alias.
}
\keyword{programming}
\keyword{methods}
\keyword{classes}
\keyword{documentation}
\eof
\name{EmptyMethodsList-class}
\docType{class}
\alias{EmptyMethodsList-class}
\title{Internal Class representing Empty Methods List }
\description{
  Objects from class \code{"EmptyMethodsList"} are generated during
  method selection to indicate failed search (forcing backtracking).
  Other classes described here are used internally in method dispatch.
  All these are for internal use.}
\usage{
## class described below
"EmptyMethodsList"

### Other, virtual classes used in method dispatch
"OptionalMethods"
"PossibleMethod"
}
\section{Slots}{
  \describe{
    \item{\code{argument}:}{Object of class \code{"name"} the argument
      names being selected on.}
    \item{\code{sublist}:}{Object of class \code{"list"} (unused, and
      perhaps to be dropped in a later version.) }
  }
}

\section{Methods}{
  No methods defined with class \code{"EmptyMethodsList"} in the
  signature.
}
\seealso{
  Function \code{\link{MethodsListSelect}} uses the objects;
  see \code{\link{MethodsList-class}} for the non-empty methods list
  objects.
}
\keyword{classes}
\keyword{internal}
\eof
\name{environment-class}
\docType{class}
\alias{environment-class}
\title{Class "environment" }
\description{ A formal class for R environments.}
\section{Objects from the Class}{
Objects can be created by calls of the form \code{new("environment", ...)}.
The arguments in \dots, if any, should be named and will be assigned to
the newly created environment.
}


\section{Methods}{
  \describe{
    \item{coerce}{\code{signature(from = "ANY", to = "environment")}:
      calls \code{\link{as.environment}}. }
    \item{initialize}{\code{signature(object = "environment")}:
      Implements the assignments in the new environment.  Note that the
      \code{object} argument is ignored; a new environment is
      \emph{always} created, since environments are not protected by copying. }
  }
}
\seealso{ \code{\link{new.env}} }

\keyword{classes}
\eof
\name{GenericFunctions}
\alias{GenericFunctions}
\alias{isGeneric}
\alias{isGroup}
\alias{removeGeneric}
\alias{standardGeneric}
\alias{getGenerics}
\alias{allGenerics}
\alias{dumpMethod}
\alias{findFunction}
\alias{dumpMethods}
\alias{removeMethods}
\alias{signature}
\alias{setReplaceMethod}
\alias{callGeneric}
\title{Tools for Managing Generic Functions}
\description{
  The functions documented here manage collections of methods associated
  with a generic function, as well as providing information about the
  generic functions themselves.
}
\synopsis{
isGeneric(f, where, fdef, getName = FALSE)
isGroup(f, where, fdef)
removeGeneric(f, where)
dumpMethod(f, signature, file, where, def)
findFunction(f, generic=TRUE, where)
dumpMethods(f, file, signature, methods, where)
signature(\dots)
removeMethods(f, where, all)
setReplaceMethod(f, \dots, where)
getGenerics(where, searchForm = FALSE)
allGenerics(where, searchForm = FALSE)
callGeneric(\dots)
}
\usage{
isGeneric(f, where, fdef, getName = FALSE)

isGroup(f, where, fdef)

removeGeneric(f, where)

standardGeneric(f)

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

findFunction(f, generic=TRUE)

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

signature(\dots)

removeMethods(f, where)

setReplaceMethod(f, \dots)

getGenerics(where, searchForm = FALSE)

allGenerics(where, searchForm = FALSE)

callGeneric(\dots)

}
\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, anywhere in the
      current search list, or in the specified position \code{where}.  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}, \code{removeMethods}:}{ 
      Remove the all the methods for the generic function of this
      name.  In addition, \code{removeGeneric} removes the function
      itself; \code{removeMethods} restores the non-generic function
      which was the default method.   If there was no default method,
      \code{removeMethods} leaves a generic function with no methods.
    }
    \item{\code{standardGeneric}:}{ 
      Dispatches a method from the current function call for the generic
      function \code{f}.  It is an error to call
      \code{standardGeneric} anywhere except in the body of the
      corresponding generic function.
    }
    \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{findFunction}:}{ 
      return a list of either the positions on the search list, or the
      current top-level environment, on which a function object
      for \code{name} exists.  The returned value is \emph{always} a
      list, use the first element to access the first visible version
      of the function.  See the example.

      \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.  Also,
      \code{findFunction} works correctly in the code for a package
      when attaching the package via a call to \code{\link{library}}.
    }
    \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.

      \code{f} = the name of the generic function, \code{signature} is
      the signature of classes to match to the arguments of \code{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{getGenerics}:}{ Returns the names of the generic
          functions that have methods defined on \code{where}; this
          argument can be an environment or an index into the search
          list.  By default, the whole search list is used.

          The methods definitions are stored with
          package qualifiers; for example, methods for function
          \code{"initialize"} might refer to two different functions
          of that name, on different packages.  The package names
          corresponding to the method list object are contained in the
           slot \code{package} of the returned object.  The form of
           the returned name can be plain (e.g., \code{"base"}), or in
           the form used in the search list (\code{"package:base"})
           according to the value of \code{searchForm}}
    \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}{ The environment, namespace, or search-list position
  from which to search for objects.  By default, start at the
  top-level environment of the calling function, typically the global
  environment (i.e., use the search list), or the namespace of a
  package from which the call came.  It is important to supply this
  argument when calling any of these functions indirectly.  With
  package namespaces, the default is likely to be wrong in such calls.}

  \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).
  }
  \item{searchForm}{In \code{getGenerics}, if  \code{TRUE}, the
      \code{package} slot of the returned result is in the form used
      by \code{search()}, otherwise as the simple package name (e.g,
      \code{"package:base"} vs \code{"base"}). }
  
}

\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 \code{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 \code{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 \code{f}.  If
      not named, the signature is assumed to apply to the arguments of
      \code{f} in order.

      If \code{mustFind} is \code{TRUE}, an error results if there is no
      method (or no unique method) corresponding to this signature.
      Otherwise may return \code{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, the generic function remains but with no methods (so
      any call to it will generate an error).  In either case, a
      following call to \code{setMethod} will consistently
      re-establish the same generic function as before.
    }
  }
}
\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes
  and methods in the book \emph{Programming with Data} (John
  M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8,
  and chapters 7 and 8.

  While the programming interface for the methods package follows the reference,
  the R software is an original implementation, so details in
  the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page 
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\seealso{
  \code{\link{setGeneric}},
  \code{\link{setClass}},
  \code{\link{showMethods}}
}
\examples{
\dontrun{
  ## get the function "myFun" -- throw an error if 0 or > 1 versions visible
  allF <- findFunction("myFun")
  if(length(allF) == 0)
    stop("No versions of myFun visible")
  else if(length(allF) > 1)
    stop("myFun is ambiguous: ", length(allF), " versions")
  else
    fdef <- get("myFun", allF[[1]])
}
  
\dontshow{
## because nosegfault runs standardGeneric w/o the methods package, nothing
## really gets tested.  The following check that it catches some errors
mustDie <- function(expr) stopifnot(is(trySilent(expr), "try-error"))

mustDie(standardGeneric()) # 3 tests of requiring a single string
mustDie(standardGeneric(NULL))
mustDie(standardGeneric(""))
mustDie(standardGeneric("notAGenericFunction"))
mustDie(standardGeneric("show"))  # a generic, but not called from its body

}
}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\eof
\name{language-class}
\docType{class}
\alias{language-class}
\alias{(-class}
\alias{<--class}
\alias{call-class}
\alias{for-class}
\alias{if-class}
\alias{repeat-class}
\alias{while-class}
\alias{name-class}
\alias{{-class}

\title{Classes to Represent Unevaluated Language Objects }
\description{  The virtual class \code{"language"} and the specific
  classes that extend it represent unevaluated objects, as produced for
  example by the parser or by functions such as \code{\link{quote}}.
}
\usage{
### each of these classes corresponds to an unevaluated object
### in the S language.  The class name can appear in method signatures,
### and in a few other contexts (such as some calls to as()).

"("
"<-"
"call"
"for"
"if"
"repeat"
"while"
"name"
"\{"

### Each of the classes above extends the virtual class

"language"



}
\section{Objects from the Class}{
  \code{"language"} is a virtual class; no objects may be created from
  it.

Objects from the other classes can be generated by a call to
\code{new(Class, ...)}, where \code{Class} is the quoted class name, and
the \dots arguments are either empty or a \emph{single} object that is
from this class (or an extension).}


\section{Methods}{
  \describe{
    \item{coerce}{\code{signature(from = "ANY", to = "call")}.  A method
      exists for \code{as(object, "call")}, calling \code{as.call()}. }
  }

}
\keyword{classes}
\eof
\name{LinearMethodsList-class}
\docType{class}
\alias{LinearMethodsList-class}
\title{Class "LinearMethodsList"}
\description{
  A version of methods lists that has been \dQuote{linearized}
  for producing summary information.  The actual objects from class
  \code{"MethodsList"} used for method dispatch are defined recursively
  over the arguments involved.
}
\section{Objects from the Class}{
  The function \code{\link{linearizeMlist}} converts an ordinary methods
  list object into the linearized form.
}
\section{Slots}{
  \describe{
    \item{\code{methods}:}{Object of class \code{"list"}, the method
      definitions.}
    \item{\code{arguments}:}{Object of class \code{"list"}, the
      corresponding formal arguments. }
    \item{\code{classes}:}{Object of class \code{"list"}, the
      corresponding classes in the signatures. }
    \item{\code{fromClasses}:}{Object of class \code{"list"} }
  }
}

\section{Future Note}{
  The current version of \code{linearizeMlist} does not take advantage of
  the \code{MethodDefinition} class, and therefore does more work for less
  effect than it could.  In particular, we may move to redefine both the
  function and the class to take advantage of the stored signatures.
  Don't write code depending precisely on the present form, although all
  the current information will be obtainable in the future.
}
\seealso{ Function \code{\link{linearizeMlist}} for the computation,
  and \code{\link{MethodsList-class}} for the original, recursive form.
}

\keyword{classes}
\eof
\name{MethodDefinition-class}
\docType{class}
\alias{MethodDefinition-class}
\alias{SealedMethodDefinition-class}
\title{Classes to Represent Method Definitions}
\description{
  These classes extend the basic class \code{"function"} when
  functions are to be stored and used as method definitions.
}
\section{Objects from the Class}{
  The action of setting a method by a call to \code{\link{setMethod}} creates an object of this class.  It's
  unwise to create them directly.

  The class \code{"SealedMethodDefinition"} is created by a call to
  \code{\link{setMethod}} with argument \code{sealed = TRUE}.  It has
  the same representation as \code{"MethodDefinition"}.
}
\section{Slots}{
  \describe{
    \item{\code{.Data}:}{Object of class \code{"function"}; the data
        part of the definition. }
    \item{\code{target}:}{Object of class \code{"signature"}; the
        signature for which the method was wanted. }
    \item{\code{defined}:}{Object of class \code{"signature"}; the
        signature for which a method was found.  If the method was
        inherited, this will not be identical to \code{target}. }
  }
}
\section{Extends}{
  Class \code{"function"}, from data part.\cr
  Class \code{"PossibleMethod"}, directly.\cr
  Class \code{"OptionalMethods"}, by class \code{"function"}.
}
\details{
  Method definition objects are functions with additional information
  defining how the function is being used as a method.  The
  \code{target} slot is the class signature for which the method will
  be dispatched, and the \code{defined} slot the signature for which
  the method was orignally specified (that is, the one that appeared
  in some call to \code{\link{setMethod}}).
}
\seealso{class \code{\link{MethodsList-class}} for the objects
  defining sets of methods associated with a particular generic
  function.  The individual method definitions stored in these objects
  are from class \code{MethodDefinition}, or an extension.
  \code{\link{MethodWithNext-class}} for an extension used by
  \code{\link{callNextMethod}}.
}
\keyword{classes}
\eof
\name{MethodSupport}
\alias{.conflicts.OK}
\alias{OldEvalSelectedMethod}
\alias{getMethodsForDispatch}
\alias{cacheMethod}
\alias{resetGeneric}
\title{Additional (Support) Functions for Methods}
\description{
  These are support routines for computations on formal methods.
}
\usage{
getMethodsForDispatch(f, fdef)

cacheMethod(f, sig, def, args, fdef)

resetGeneric(f, fdef, mlist, where, deflt)
}
\section{Summary of Functions}{
  \describe{
    \item{\code{resetGeneric}:}{ 
      reset the currently defined methods for this generic to the
      currently visible methods, looking from environment \code{where}.  Returns \code{TRUE}
      or \code{FALSE} according to whether information for the function
      was found in the metadata.

      Normally not called directly, since changes to methods,
    attaching and detaching packages all generate a call automatically.
    }
    \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 \code{f}, merged from the various packages 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}
\eof
\name{MethodWithNext-class}
\docType{class}
\alias{MethodWithNext-class}
\title{Class MethodWithNext }
\description{ Class of method definitions set up for callNextMethod }
\section{Objects from the Class}{
  Objects from this class are generated as a side-effect of calls to
  \code{\link{callNextMethod}}.
}
\section{Slots}{
  \describe{
    \item{\code{.Data}:}{Object of class \code{"function"}; the actual
      function definition.}
    \item{\code{nextMethod}:}{Object of class \code{"PossibleMethod"}
      the method to use in response to a \code{\link{callNextMethod}()}
      call.}
    \item{\code{excluded}:}{Object of class \code{"list"}; one or more
      signatures excluded in finding the next method. }
    \item{\code{target}:}{Object of class \code{"signature"}, from class
      \code{"MethodDefinition"}}
    \item{\code{defined}:}{Object of class \code{"signature"}, from
      class \code{"MethodDefinition"}} 
  }
}
\section{Extends}{
  Class \code{"MethodDefinition"}, directly.\cr
  Class \code{"function"}, from data part.\cr
  Class \code{"PossibleMethod"}, by class \code{"MethodDefinition"}.\cr
  Class \code{"OptionalMethods"}, by class \code{"MethodDefinition"}.
}
\section{Methods}{
  \describe{
    \item{findNextMethod}{\code{signature(method = "MethodWithNext")}:
      used internally by method dispatch. }
    \item{loadMethod}{\code{signature(method = "MethodWithNext")}: used
      internally by method dispatch. }
    \item{show}{\code{signature(object = "MethodWithNext")} }
  }
}

\seealso{  \code{\link{callNextMethod}}, and 
 \code{\link{MethodDefinition-class}}. }

\keyword{classes}
\eof
\name{Methods}
\alias{Methods}
\title{General Information on Methods}
\description{
  This documentation section covers some general topics on how methods
  work and how the \pkg{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 \pkg{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 \dQuote{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 anywhere on the
    current search list.  These are merged so that methods in an
    environment 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 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 on all methods 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 contains.  (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"}.
When all the superclasses are needed, as they are for dispatching
methods, they are ordered by how direct they are:  first, the direct
classes contained directly in the definition of this class, then the
superclasses of these classes, etc.

The S language has an additional, explicit mechanism for defining superclasses, the
\code{\link{setIs}} mechanism.
This mechanism allows a class to extend another even though they do
not have the same representation.  The extension is made possible by
defining explicit methods to \code{coerce} an object to its superclass
and to \code{replace} the data in the object corresponding to the
superclass.  The \code{\link{setIs}} mechanism will be used less often
and only when directly including the superclass does not make sense,
but once defined, the superclass acts just as directly contained
classes as far as method selection is concerned.

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.


  The generic, \code{f} say,  has a signature, which by default
  is all its formal arguments, except \dots (see
  \code{\link{setGeneric}}). For each of the formal arguments in that
  signature, in order, the class of the actual argument is matched
  against available methods.  A missing argument corresponds to class
  \code{"missing"}.  If no method corresponds to the class of the
  argument, the evaluator looks for a method corresponding to the
  the superclasses (the other classes that the actual class
  extends, always including
  \code{"ANY"}).  If no match is found, the dispatch fails, with an
  error.  (But if there is a default method, that will always match.)

  If the match succeeds, it can find either a single method, or a
  methods list.  In the first case, the search is over, and returns
  the method.  In the second case, the search proceeds, with the
  next argument in the signature of the generic.  \emph{That} search
  may succeed or fail.  If it fails, the dispatch will try again with
  the next best match for the current argument, if there is one.
  The last match always corresponds to class \code{"ANY"}.

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.

}

\section{Changes with the Methods Package}{
  The \pkg{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 \pkg{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
      \pkg{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 \dQuote{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 \pkg{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 \pkg{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.
    }
  }
}
\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes
  and methods in the book \emph{Programming with Data} (John
  M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8,
  and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page 
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\seealso{
  \code{\link{setGeneric}},
  \code{\link{setClass}}
}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\eof
\name{MethodsList-class}
\alias{MethodsList-class}
\alias{body<-,MethodDefinition-method}
\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{Slots}{\describe{

  \item{\code{argument}:}{Object of class \code{"name"}.  The name of the
    argument being used for dispatch at this level. }
  \item{\code{methods}:}{A named list of the methods (and method lists)
    defined \emph{explicitly} for this argument, with the names being
    the classes for which the methods have been defined. }
  \item{\code{allMethods}:}{A named list, which may be empty if this
    object has not been used in dispatch yet.  Otherwise, it contains
    all the directly defined methods from the \code{methods} slot, plus
    any inherited methods. }
}}


\section{Extends}{
Class \code{"OptionalMethods"}, directly.
}
\keyword{classes}
\keyword{methods}
\eof
\name{MethodsList}
\alias{MethodsList}
\alias{makeMethodsList}
\alias{SignatureMethod}
\alias{insertMethod}
\alias{inheritedSubMethodLists}
\alias{showMlist}
\alias{print.MethodsList}
\alias{emptyMethodsList}
\alias{insertMethodInEmptyList}
\alias{listFromMlist}
\alias{linearizeMlist}
\alias{finalDefaultMethod}
\alias{mergeMethods}
\alias{loadMethod}
\alias{loadMethod-methods}
\alias{loadMethod,ANY-method}
\alias{loadMethod,MethodDefinition-method}
\alias{loadMethod,MethodWithNext-method}
\title{MethodsList Objects}
\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.
}
\usage{
MethodsList(.ArgName, ...)

makeMethodsList(object, level=1)

SignatureMethod(names, signature, definition)

insertMethod(mlist, signature, args, def, cacheOnly)

inheritedSubMethodLists(object, thisClass, mlist, ev)

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

\method{print}{MethodsList}(x, ...)

listFromMlist(mlist, prefix = list())

linearizeMlist(mlist, inherited = TRUE)

finalDefaultMethod(mlist, fname = "NULL")

mergeMethods(m1, m2, genericLabel)

loadMethod(method, fname, envir)

}

\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
      \code{signature[[1]]} is the match for the first argument,
      \code{signature[[2]]} for the second argument, and so on.  The
      string \code{"missing"} means a match for a missing argument, and
      \code{"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{"methods"}, but \code{cacheOnly=TRUE} inserts
      it into the \code{"allMethods"} slot (used for dispatch but not saved).
    }

    \item{\code{inheritedSubMethodLists}:}{
      Utility function to match the object  or the class (if the object
      is \code{NULL}) 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).  If
      \code{mlist} is null, returns the function called \code{fname}, or
      \code{NULL} if there is no such 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}}.  For a primitive function,
      \code{genericLabel} is supplied as the name of the generic.
    }

    \item{\code{loadMethod}:}{
      Called, if necessary, just before a call to \code{method} is
      dispatched in the frame \code{envir}.  The function exists so that
      methods can be defined for special classes of objects.  Usually
      the point is to assign or modify information in the frame
      environment to be used evaluation.  For example, the standard
      class \code{MethodDefinition} has a method that stores the target
      and defined signatures in the environment.  Class
      \code{MethodWithNext} has a method taking account of the
      mechanism for storing the method to be used in a call to
      \code{\link{callNextMethod}}.

      Any methods defined for \code{loadMethod} must return the function
      definition to be used for this call; typically, this is just the
      \code{method} argument.
    }
  }
}
\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 R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\keyword{internal}

\eof
\name{callNextMethod}
\alias{callNextMethod}
\title{Call an Inherited Method}
\description{
  A call to \code{callNextMethod} can only appear inside a method
  definition.  It then results in a call to the first inherited method
  after the current method, with the arguments to the current method
  passed down to the next method.  The value of that method call is the
  value of \code{callNextMethod}.
}
\usage{
callNextMethod(...)
}
\arguments{
  \item{\dots}{
Optionally, the arguments to the function in its next call
(but note that the dispatch is as in the detailed description below;
the arguments have no effect on selecting the next method.) 

If no arguments are included in the call to \code{callNextMethod}, the
    effect is to call the method with the current arguments.
    See the detailed description for what this really means.

Calling with no arguments is often the natural way to use
    \code{callNextMethod}; see the examples.
    }
}
\details{
  The \dQuote{next} method (i.e., the first inherited method) is defined to
    be that method
  which \emph{would} have been called if the current method did not
  exist.
  This is more-or-less literally what happens: The current method is
  deleted from a copy of the methods for the current generic, and
  \code{\link{selectMethod}} is called to find the next method (the
  result is cached in a special object, so the search only typically
  happens once per session per combination of argument classes).

  It is also legal, and often useful, for the method called by
  \code{callNextMethod} to itself have a call to
  \code{callNextMethod}. This generally works as you would expect, but
  for completeness be aware that it is possible to have ambiguous
  inheritance in the S structure, in the sense that the same two
  classes can appear as superclasses \emph{in the opposite order} in
  two other class definitions.  In this case the effect of a nested
  instance of \code{callNextMethod} is not well defined.  Such
  inconsistent class hierarchies are both rare and nearly always the
  result of bad design, but they are possible, and currently undetected.

  The statement that the method is called with the current arguments is
  more precisely as follows.  Arguments that were missing in the current
  call are still missing (remember that \code{"missing"} is a valid
  class in a method signature).  For a formal argument, say \code{x}, that
  appears in the original call, there is a corresponding argument in the
  next method call equivalent to \dQuote{\code{x = x}}.  In effect, this
  means that the next method sees the same actual arguments, but
  arguments are evaluated only once.
}
\value{
  The value returned by the selected method.
}
\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes
  and methods in the book \emph{Programming with Data} (John
  M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8,
  and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming 
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page 
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\seealso{\link{Methods} for the general behavior of method dispatch}

\examples{

## some class definitions with simple inheritance
setClass("B0" , representation(b0 = "numeric"))

setClass("B1", representation(b1 = "character"), contains = "B0")

setClass("B2", representation(b2 = "logical"), contains = "B1")

## and a rather silly function to illustrate callNextMethod

f <- function(x) class(x)

setMethod("f", "B0", function(x) c(x@b0^2, callNextMethod()))
setMethod("f", "B1", function(x) c(paste(x@b1,":"), callNextMethod()))
setMethod("f", "B2", function(x) c(x@b2, callNextMethod()))

b1 <- new("B1", b0 = 2, b1 = "Testing")

b2 <- new("B2", b2 = FALSE, b1 = "More testing", b0 = 10)

f(b2)

f(b1)

\dontshow{

stopifnot(identical(f(b2), c(b2@b2, paste(b2@b1,":"), b2@b0^2, "B2")))

## a version of the example with 1 more layer of nesting

## next methods calling next methods, with arguments; using group generics
setMethod("Ops", "B2",
    function(e1, e2) callNextMethod())
setMethod("Ops", c("B0","numeric"),
    function(e1, e2) callNextMethod(e1@b0, e2))

b2 + 1 # 11

b1 == 2 # TRUE

removeClass("B2"); removeClass("B1"); removeClass("B0")

removeGeneric("f")

removeMethods("Ops")

## tests of multiple callNextMethod
setClass("m1", representation(count = "numeric"), contains = "matrix",
         prototype = prototype(count = 0))
mm1 <- new("m1", matrix(1:12, 3,4))
setMethod("[", "m1", function(x, i, j, ..., drop) callNextMethod())

setClass("m2", representation(sum = "numeric"), contains = "m1")

setMethod("Ops", c("m1", "m1"), function(e1, e2) {
    as(e1, "matrix") <- callNextMethod()
    e1@count <- max(e1@count, e2@count)+1
    e1})

mm2 <- new("m2", matrix(1:12, 3, 4), sum = sum(1:12))

stopifnot(identical(mm2[,2], 4:6))

setClass("m3", representation(rowtags = "character"),contains = "m2")

setMethod("[", signature(x="m3", i = "character", j = "missing", drop = "missing"),
          function(x, i,j, ..., drop) {
              xx <- callNextMethod(x, match(i, x@rowtags),)
              x@.Data <- xx
              x@rowtags <- x@rowtags[match(i, x@rowtags)]
              x})

tm = matrix(1:12, 4, 3)

mm3 = new("m3", tm, rowtags = letters[1:4])

mmm = mm3[c("b", "d")]

stopifnot(identical(mmm, new("m3", tm[c(2, 4),], rowtags = c("b", "d"))))

removeClass("m3")
removeClass("m2")
removeClass("m1")

removeMethods("[")

}

}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\eof
\name{ObjectsWithPackage-class}
\docType{class}
\alias{ObjectsWithPackage-class}
\title{A Vector of Object Names, with associated Package Names }
\description{
  This class of objects is used to represent ordinary character string
  object names, extended with a \code{package} slot naming the package
  associated with each object.
}
\section{Objects from the Class}{
  The function \code{\link{getGenerics}} returns an object of this class.
}
\section{Slots}{
  \describe{
    \item{\code{.Data}:}{Object of class \code{"character"}: the
      object names.}
    \item{\code{package}:}{Object of class \code{"character"} the
      package names.}
  }
}
\section{Extends}{
  Class \code{"character"}, from data part.\cr
  Class \code{"vector"}, by class \code{"character"}.
}
\seealso{ \code{Methods} for general background. }
\keyword{classes}
\eof
\name{RClassUtils}
%% FIXME the following are undocumented utilities (Sep 23/02)
\alias{completeSubclasses}
\alias{newClassRepresentation}
\alias{print.classRepresentation}
\alias{setExtendsMetaData}
\alias{setSubclassMetaData}
\alias{subclassesMetaName}
\alias{extendsMetaName}
\alias{classPrototypeDef-class}
\alias{trySilent}
%%
\alias{testVirtual}
\alias{makePrototypeFromClassDef}
\alias{newEmptyObject}
\alias{completeClassDefinition}
\alias{getSlots}
\alias{getAllSuperClasses}
\alias{superClassDepth}
\alias{isVirtualClass}
\alias{assignClassDef}
\alias{newBasic}
\alias{makeExtends}
\alias{reconcilePropertiesAndPrototype}
\alias{tryNew}
\alias{empty.dump}
\alias{showClass}
\alias{showExtends}
\alias{possibleExtends}
\alias{completeExtends}
\alias{classMetaName}
\alias{methodsPackageMetaName}
\alias{metaNameUndo}
\alias{requireMethods}
\alias{checkSlotAssignment}
\alias{defaultPrototype}
\alias{isClassDef}
\alias{validSlotNames}
\alias{getDataPart}
\alias{setDataPart}
%% not explicitly documented here
\alias{.BasicClasses}
\alias{.BasicVectorClasses}
\alias{.InitBasicClasses}
\alias{.InitMethodsListClass}
\alias{.setCoerceGeneric}

\title{Utilities for Managing Class Definitions}
\description{
  These are various functions to support the definition and use of
  formal classes.  Most of them are rarely suitable to be called
  directly.
}

\usage{
testVirtual(properties, extends, prototype)

makePrototypeFromClassDef(slots, ClassDef, extends)

newEmptyObject()

completeClassDefinition(Class, ClassDef, where, doExtends)

getSlots(x, complete = TRUE)

getAllSuperClasses(ClassDef, simpleOnly = TRUE)

superClassDepth(ClassDef, soFar, simpleOnly = TRUE)

isVirtualClass(Class, where)

newBasic(Class, ...)

makeExtends(Class, to, coerce, test, replace, by, package, slots,
                 classDef1, classDef2)

reconcilePropertiesAndPrototype(name, properties, prototype,
       superClasses, where)

tryNew(Class)

trySilent(expr)

empty.dump()

showClass(Class, complete=TRUE, propertiesAreCalled="Slots")

showExtends(ext, printTo = stdout())

possibleExtends(class1, class2)

completeExtends(ClassDef, class2, extensionDef, where)

classMetaName(name)

methodsPackageMetaName(prefix, name)

metaNameUndo(strings, prefix = "M", searchForm = FALSE)

requireMethods(functions, signature, message)

checkSlotAssignment(obj, name, value)

defaultPrototype()

isClassDef(object)

validSlotNames(names)

getDataPart(object)
setDataPart(object, value)

}

\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 \code{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 in \code{ClassDef}, if there is one, is used instead (but it must be
      coercible to the class of the slot). This includes the data part
      (\code{".Data"} slot) if there is one.

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

      If there is a non-virtual superclass (a class in the
      extends list), then its prototype is used.  The data part is
      extracted if needed (it is allowed to have two superclasses
      with a data part; the first is used and a warning issued on any others).

      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 \code{"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 \code{Class}, relative to the class
      definitions visible from environment \code{where}.  If
      \code{doExtends} is \code{TRUE}, complete the super- and
      sub-class information.

      This function is called when a class is defined or re-defined.
    }

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




    \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{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{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{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
      \code{Class="NULL"} (disallowed because \code{NULL} can't have
      attributes).  For all cases except \code{"NULL"}, the class of the
      result will be set to \code{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 \code{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 \code{complete} is \code{TRUE}, include the indirect
      information about extensions.
    }

    \item{\code{showExtends}:}{
      Print the elements of the list of extensions.

      (Used also by \code{\link{promptClass}} to get the list of what
      and how for the extensions.)
    }


    \item{\code{possibleExtends}:}{
      Find the information that says whether class1 extends class2,
      directly or indirectly.

      This can be either a logical value or an object of class
      \code{\link{SClassExtension-class}} 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.

      If \code{class2} and \code{extensionDef} are included, this
      class relation is to be added.  Otherwise just use the current
      \code{ClassDef}.

      Both the \code{contains} and \code{subclasses} slots are
      completed with any indirect relations visible.
    }

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

    \item{\code{methodsPackageMetaName}:}{
      a name mangling device to hide metadata defining method and
      class information.
    }
  \item{metaNameUndo}{ As its name implies, this function undoes the
      name-mangling used to produce meta-data object names, and
      returns a object of class \code{\link{ObjectsWithPackage-class}}.
      }

    \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{\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?
    }

    \item{\code{validSlotNames}:}{
      Returns \code{names} unless one of the names is reserved, in which
      case there is an error.  (As of writing, \code{"class"} is the
      only reserved slot name.)
    }
  \item{\code{getDataPart}, \code{setDataPart}:}{ Utilities called from the base C code
      to implement \code{object@.Data}.
      }

  }
}
\keyword{internal}
\eof
\name{RMethodUtils}
%% FIXME:  undocumented utilities (Sep. 23/02)
\alias{asMethodDefinition}
\alias{standardGeneric-class}
\alias{standardGenericWithTrace-class}
\alias{nonstandardGeneric-class}
\alias{nonstandardGenericFunction-class}
\alias{nonstandardGroupGenericFunction-class}
\alias{OptionalFunction-class}
\alias{PossibleMethod-class}
\alias{derivedDefaultMethod-class}
%%
\alias{substituteFunctionArgs}
\alias{makeGeneric}
\alias{makeStandardGeneric}
\alias{generic.skeleton}
\alias{defaultDumpName}
\alias{getAllMethods}
\alias{doPrimitiveMethod}
\alias{conformMethod}
\alias{getGeneric}
\alias{getGroup}
\alias{getMethodsMetaData}
\alias{assignMethodsMetaData}
\alias{matchSignature}
\alias{mlistMetaName}
\alias{removeMethodsObject}
\alias{findUnique}
\alias{MethodAddCoerce}
\alias{is.primitive}
\alias{.saveImage}
\alias{cacheMetaData}
\alias{cacheGenericsMetaData}
\alias{setPrimitiveMethods}
\alias{missingArg}
\alias{balanceMethodsList}
\alias{sigToEnv}
\alias{rematchDefinition}
\alias{unRematchDefinition}
\alias{addNextMethod,MethodDefinition-method}
\alias{addNextMethod,MethodWithNext-method}
\alias{addNextMethod}
alias{.valueClassTest}
%% Not for the user to know about!
\alias{.ShortPrimitiveSkeletons} %% used from C code
\alias{.EmptyPrimitiveSkeletons}
\title{RMethodUtils}
\description{
  Utility functions to support the definition and use of formal
  methods.  Most of these functions will not normally be called directly
  by the user.
}
\usage{
getGeneric(f, mustFind=FALSE, where)

getGroup(fdef, recursive, where)

getMethodsMetaData(f, where)
assignMethodsMetaData (f, value, fdef, where, deflt)
mlistMetaName (name, package)

makeGeneric(f, fdef, fdefault, group=list(), valueClass=character(),
            package, signature = NULL, genericFunction = NULL)

makeStandardGeneric(f, fdef)

generic.skeleton(name, fdef, fdefault)

defaultDumpName(generic, signature)

getAllMethods(f, fdef, where)

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

conformMethod(signature, mnames, fnames, f)

matchSignature(signature, fun, where)

removeMethodsObject(f, where)

findUnique(what, message, where)

MethodAddCoerce(method, argName, thisClass, methodClass)

is.primitive(fdef)

cacheMetaData(where, attach = TRUE, searchWhere)

cacheGenericsMetaData(f, fdef, attach = TRUE, where, package, methods)

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

missingArg(symbol, envir = parent.frame(), eval)

balanceMethodsList(mlist, args, check = TRUE)

sigToEnv(signature, genericSig)

rematchDefinition(definition, generic, mnames, fnames, signature)
unRematchDefinition(definition)

asMethodDefinition(def, signature, sealed = FALSE)

addNextMethod(method, f, mlist, optional, envir)
}
\section{Summary of Functions}{

  \describe{

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

      If no definition is found, throws an
      error or returns \code{NULL} according to the value of
      \code{mustFind}.  By default, searches in the top-level
      environment (normally the global environment, but adjusted to
      work correctly when package code is evaluated from the function \code{\link{library}}.

      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, searching from
      environment \code{where} (the global environment normally by default).

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

    \item{\code{getMethodsMetaData},
      \code{assignMethodsMetaData},
      \code{mlistMetaName}:}{
      Utilities to get (\code{getMethodsMetaData}) and assign  (\code{assignMethodsMetaData}) the metadata object recording the
      methods defined in a particular package, or to return the
      mangled name for that object  (\code{mlistMetaName}).

      The assign function should not be used directly.  The get
    function may be useful if you want explicitly only the outcome of
    the methods assigned in this package.  Otherwise, use \code{\link{getMethods}}.
    }

    \item{\code{matchSignature}:}{
      Matches the signature object (a partially or completely named
      subset of the signature arguments of the generic function object
      \code{fun}), and return a vector of all the classes in the order
      specified by \code{fun@signature}.  The classes not specified by
      \code{signature} will be \code{"ANY"} in the value, but extra
      trailing \code{"ANY"}'s are removed.  When the input signature is
      empty, the returned signature is a single \code{"ANY"} matching
      the first formal argument (so the returned value is always
      non-empty).

      Generates an error if any of the supplied signature names are
      not legal; that is, not in the signature slot of the generic
      function.

      If argument \code{where} is supplied, a warning will be issued
      if any of the classes does not have a formal definition visible
      from \code{where}.
    }

    \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{removeMethodsObject}:}{
      remove the metadata object containing methods for \code{f}.
    }

    \item{\code{findUnique}:}{
      Return the list of environments (or equivalent) having an object named
      \code{what}, using environment \code{where} and its parent
      environments.  If more than one is found, a warning message is
      generated, using \code{message} to identify what was being
      searched for, unless \code{message} is the empty string.
    }

    \item{\code{cacheMetaData},
      \code{cacheGenericsMetaData},
      \code{setPrimitiveMethods}:}{
      Utilities for ensuring that the internal 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 package is attached or
      detached).  Required primarily because primitive functions are
      dispatched in C code, rather than by the official model.

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

    \item{\code{missingArg}:}{
      Returns \code{TRUE} if the symbol supplied is missing \emph{from
        the call} corresponding to the environment supplied (by default,
      environment of the call to \code{missingArg}).  If \code{eval} is
      true, the argument is evaluated to get the name of the symbol to
      test.  Note that \code{missingArg} is closer to the
      \dQuote{blue-book} sense of the \code{\link{missing}} function,
      not that of the current R base package implementation.  But beware
      that it works reliably only if no assignment has yet been made to
      the argument.  (For method dispatch this is fine, because
      computations are done at the begining of the call.)
    }

    \item{\code{balanceMethodsList}:}{
      Called from \code{\link{setMethod}} to ensure that all nodes in
      the list have the same depth (i.e., the same number of levels of
      arguments).  Balance is needed to ensure that all necessary
      arguments are examined when inherited methods are being found and
      added to the \code{allMethods} slot.  No actual recomputation is
      needed usually except when a new method uses a longer signature
      than has appeared before.

      Balance requires that \emph{all} methods be added to the generic
      via \code{setMethod} (how else could you do it?) or by the initial
      \code{setGeneric} call converting the ordinary function.
    }

    \item{\code{sigToEnv}:}{
      Turn the signature (a named vector of classes) into an environment
      with the classes assigned to the names.  The environment is then
      suitable for calling \code{\link{MethodsListSelect}}, with
      \code{evalArgs=FALSE}, to select a method corresponding to the
      signature.  Usually not called directly: see
      \code{\link{selectMethod}}.
    }

    \item{\code{.saveImage}:}{
      Flag, used in dynamically initializing the methods package from
      \code{.First.lib}
    }

    \item{\code{rematchDefinition},
      \code{unRematchDefinition}:}{
      If the specified method in a call to \code{\link{setMethod}}
      specializes the argument list (by replacing \dots), then
      \code{rematchDefinition} constructs the actual method stored.
      Using knowledge of how \code{rematchDefinition} works,
      \code{unRematchDefinition} reverses the procedure; if given a
      function or method definition that does not correspond to this
      form, it just returns its argument.
    }

    \item{\code{asMethodDefinition}:}{
      Turn a function definition into a
      \code{\link{MethodDefinition-class}} object, corresponding to the
      given \code{signature} (by default generates a default method
      with empty signature).  The definition is sealed according to
      the \code{sealed} argument.
    }

    \item{\code{addNextMethod}:}{
      A generic function that finds the next method in \code{mlist}
      corresponding the method definition \code{method}  and adds the
      method to the methods list, which it then returns.  It uses
      methods defined suitably for ordinary methods and for methods with
      calls to \code{\link{callNextMethod}}.
    }
  }

    \item{\code{makeGeneric}:}{
      Makes a generic function object corresponding to the given
      function name, optional definition and optional default method.
      Other arguments supply optional elements for the slots of
      \code{\link{genericFunction-class}}.
    }

    \item{\code{makeStandardGeneric}:}{
      a utility function that makes a valid function calling
      \code{standardGeneric} for name \code{f}.  Works (more or less)
      even if the actual definition, \code{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 function name, \code{f} is supplied for error
      messages.

      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 methods defined for this generic starting from environment
      \code{where}, including all parent environments.  By default,
      uses the global environment (and therefore all packages on the
      search list).  This function exists largely
      to re-compute the full set of methods when a change to the
      available methods occurs.  Since all such recomputations are
      supposed to be automatic, direct calls to \code{getAllMethods}
      should not be needed.

      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 \code{"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).
    }

}
\keyword{internal}
\eof
\name{SClassExtension-class}
\docType{class}
\alias{SClassExtension-class}
\title{Class to Represent Inheritance (Extension) Relations }
\description{  An object from this class represents a single \dQuote{is}
  relationship; lists of these objects are used to represent all the
  extensions (superclasses) and subclasses for a given class.  The
  object contains information about how the relation is defined and
  methods to coerce, test, and replace correspondingly. }
\section{Objects from the Class}{
  Objects from this class are generated by \code{\link{setIs}}, both
  from direct calls .
}
\section{Slots}{
  \describe{
    \item{\code{subClass,superClass}:}{The classes being extended:
    corresponding to the \code{from}, and \code{to} arguments to \code{\link{setIs}}. }
    \item{\code{package}:}{The package to which that class belongs. }
    \item{\code{coerce}:}{A function to carry out the as() computation
    implied by the relation.  Note that these functions should
    \emph{not} be used directly.  They only deal with the
    \code{strict=TRUE} calls to the \code{\link{as}} function, with
    the full method constructed from this mechanically. }
    \item{\code{test}:}{The function that would test whether the
    relation holds.  Except for explicitly specified \code{test}
    arguments to \code{\link{setIs}}, this function is trivial. }
    \item{\code{replace}:}{The method used to implement \code{as(x,
    Class) <- value}.}
    \item{\code{simple}:}{A \code{"logical"} flag, \code{TRUE} if this
    is a simple relation, either because one class is contained in the
    definition of another, or because a class has been explicitly
    stated to extend a virtual class.  For simple extensions, the
    three methods are generated automatically.}
    \item{\code{by}:}{If this relation has been constructed
    transitively, the first intermediate class from the subclass. }
    \item{\code{dataPart}:}{A \code{"logical"} flag, \code{TRUE} if
  the extended class is in fact the data part of the subclass.  In
  this case the extended class is a basic class (i.e., a type). }
  }
}

\section{Methods}{
  No methods defined with class \code{"SClassExtension"} in the
  signature.
}
\seealso{
  \code{\link{is}},
  \code{\link{as}}, and
  \code{\link{classRepresentation-class}}.
}
\keyword{classes}
\eof
\name{Session}
\alias{sessionData}
\alias{traceOn}
\alias{traceOff}
\alias{browseAll}
\title{Deprecated:  Session Data and Debugging Tools}
\description{
  The functions \code{traceOn} and \code{traceOff} have been replaced by
  extended versions of the functions \code{\link{trace}} and
  \code{\link{untrace}}, and should not be used.
}
\usage{
sessionData()

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

traceOff(what)

browseAll()

}
\details{
  \describe{
    \item{\code{sessionData}:}{
      return the index of the session data in the search list,
      attaching it if it is not attached.
    }

    \item{\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.
    }
  
    \item{\code{traceOff}:}{
      turn off tracing of this function.
    }
  
    \item{\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 \code{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.
}
\keyword{internal}
\eof
\name{StructureClasses}
\docType{class}
\alias{structure-class}
\alias{matrix-class}
\alias{array-class}
\alias{ts-class}
\title{Classes Corresponding to Basic Structures }
\description{  The virtual class \code{structure} and classes that
  extend it are formal classes analogous to S language structures such
  as arrays and time-series}
\usage{
## The folowing class names can appear in method signatures,
## as the class in as() and is() expressions, and, except for
## the classes commented as VIRTUAL, in calls to new()

"matrix"
"array"
"ts"

"structure" ## VIRTUAL
}
\section{Objects from the Classes}{
  Objects can be created by calls of the form \code{new(Class, ...)},
  where \code{Class} is the quoted name of the specific class (e.g.,
  \code{"matrix"}), and the other arguments, if any, are interpreted as
  arguments to the corresponding function, e.g., to function
  \code{matrix()}.  There is no particular advantage over calling those
  functions directly, unless you are writing software designed to work
  for multiple classes, perhaps with the class name and the arguments
  passed in.
}
\section{Extends}{
  The specific classes all extend class \code{"structure"}, directly, and
  class \code{"vector"}, by class \code{"structure"}.
}
\section{Methods}{
  \describe{
    \item{coerce}{Methods are defined to coerce arbitrary objects to
      these classes, by calling the corresponding basic function, for
      example, \code{as(x, "matrix")} calls \code{as.matrix(x)}. }
  }
}
\keyword{classes}
\eof
\name{TraceClasses}
\docType{class}
\alias{traceable-class}
\alias{functionWithTrace-class}
\alias{MethodDefinitionWithTrace-class}
\alias{MethodWithNextWithTrace-class}
\alias{genericFunctionWithTrace-class}
\alias{groupGenericFunctionWithTrace-class}
%% private
\alias{.untracedFunction}
\alias{.makeTracedFunction}
\alias{.doTracePrint}
\alias{.InitTraceFunctions}
\title{Classes Used Internally to Control Tracing }
\description{ The classes described  here are used by the R function
  \code{\link{trace}} to create versions of functions and methods
  including browser calls, etc., and also to \code{\link{untrace}} the
  same objects.}
\section{Objects from the Class}{
  Objects will be created from these classes by calls to \code{trace}.
  (There is an \code{\link{initialize}} method for class
  \code{"traceable"}, but you are unlikely to need it directly.)
}
\usage{
### Objects from the following classes are generated
### by calling trace() on an object from the corresponding
### class without the "WithTrace" in the name.

"functionWithTrace"
"MethodDefinitionWithTrace"
"MethodWithNextWithTrace"
"genericFunctionWithTrace"
"groupGenericFunctionWithTrace"

### the following is a virtual class extended by each of the
### classes above

"traceable"
}
\section{Slots}{
  \describe{
    \item{\code{.Data}:}{The data part, which will be \code{"function"}
      for class \code{"functionWithTrace"}, and similarly for the other
      classes.}
    \item{\code{original}:}{Object of the original class; e.g.,
      \code{"function"} for class \code{"functionWithTrace"}. }
  }
}
\section{Extends}{
  Each of the classes extends the corresponding untraced class, from the
  data part; e.g., \code{"functionWithTrace"} extends \code{"function"}.
  Each of the specific classes extends \code{"traceable"}, directly,
  and class \code{"VIRTUAL"}, by class \code{"traceable"}.
}
\section{Methods}{
  The point of the specific classes is that objects generated from them,
  by function \code{trace()}, remain callable or dispatchable, in
  addition to their new trace information.
}
\seealso{ function \code{\link{trace}} }
\keyword{classes}
\eof
\name{as}
\alias{as}
\alias{as<-}
\alias{coerce}
\alias{coerce<-}
\alias{setAs}
\alias{coerce-methods}
\alias{coerce,ANY,array-method}
\alias{coerce,ANY,call-method}
\alias{coerce,ANY,character-method}
\alias{coerce,ANY,complex-method}
\alias{coerce,ANY,environment-method}
\alias{coerce,ANY,expression-method}
\alias{coerce,ANY,function-method}
\alias{coerce,ANY,integer-method}
\alias{coerce,ANY,list-method}
\alias{coerce,ANY,logical-method}
\alias{coerce,ANY,matrix-method}
\alias{coerce,ANY,name-method}
\alias{coerce,ANY,numeric-method}
\alias{coerce,ANY,single-method}
\alias{coerce,ANY,ts-method}
\alias{coerce,ANY,vector-method}
\alias{coerce,ANY,NULL-method}
\title{Force an Object to Belong to a Class}
\description{
  These functions manage the relations that allow coercing an object to
  a given class.
}
\usage{
as(object, Class, strict=TRUE)

as(object, Class) <- value

setAs(from, to, def, replace, where = topenv(parent.frame()))

}
\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 \code{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{strict}{ A logical flag.  If \code{TRUE}, the returned object
  must be strictly from the target class (unless that class is a
  virtual class, in which case the object will be from the closest
  actual class (often the original object, if that class extends the
  virtual class directly).

  If \code{strict = FALSE}, any simple extension of the target class
  will be returned, without further change.  A simple extension is,
  roughly, one that just adds slots to an existing class.

      }
  \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 position or environment in which to store the
    resulting method for \code{coerce}.}
  %% FIXME: ; by default, the ... 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 \dQuote{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 supplied as
  \code{def} can have one argument (interpreted as an object to be
  coerced) or two arguments (the \code{from} object and the \code{to}
  class).  Either way, \code{setAs} constructs a function of two
  arguments, with the second defaulting to the name of the \code{to}
  class.  The method will be called from \code{as} with the object
  as the only argument:  The default for the
  second argument is provided so the method can know the intended
  \code{to} class.

  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 \dQuote{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.
  }

\section{Basic Coercion Methods}{
Methods are pre-defined for coercing any object to one of the basic
datatypes.  For example, \code{as(x, "numeric")} uses the existing
\code{as.numeric} function.  These built-in methods can be listed by
\code{showMethods("coerce")}.
}

\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes
  and methods in the book \emph{Programming with Data} (John
  M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8,
  and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\examples{
## using the definition of class "track" from \link{Classes}

\dontshow{
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, to )new(to, a=from@b, id = from@id))

as(CB, "numeric")

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

}

}

\keyword{programming}
\keyword{classes}
\keyword{methods}
\eof
\name{classRepresentation-class}
\docType{class}
\alias{classRepresentation-class}
\title{Class Objects }
\description{  These are the objects that hold the definition of
  classes of objects.  They are constructed and stored as meta-data by
  calls to the function \code{\link{setClass}}.  Don't manipulate them
  directly, except perhaps to look at individual slots. }

\section{Slots}{
  \describe{
    \item{\code{slots}:}{A named list of the slots in this class; the
      elements of the list are the classes to which the slots must
      belong (or extend), and the names of the list gives the
      corresponding slot names.}
    \item{\code{contains}:}{A named list of the classes this class
      \dQuote{contains}; the elements of the list are objects of
      \code{\link{SClassExtension-class}}. The list may be only the
      direct extensions or all the currently known extensions (see the
      details).}
    \item{\code{virtual}:}{Logical flag, set to \code{TRUE} if this is
      a virtual class.}
    \item{\code{prototype}:}{The object that represents the standard
      prototype for this class; i.e., the data and slots returned by a
      call to \code{\link{new}} for this class with no special
      arguments.  Don't mess with the prototype object directly.}
    \item{\code{validity}:}{Optionally, a function to be used to test
      the validity of objects from this class.
      See \code{\link{validObject}}.}
    \item{\code{access}:}{Access control information.  Not currently used.}
    \item{\code{className}:}{The character string name of the class.}
    \item{\code{package}:}{The character string name of the package to
      which the class belongs.  Nearly always the package on which the
      metadata for the class is stored, but in operations such as
      constructing inheritance information, the internal package name
      rules.} 
    \item{\code{subclasses}:}{A named list of the classes known to
      extend this class'; the elements of the list are objects of
      \code{\link{SClassExtension-class}}.  The list is currently only
      filled in when completing the class definition (see the details).}
    \item{\code{versionKey}:}{Object of class \code{"externalptr"};
      eventually will perhaps hold some versioning information, but not
      currently used. }
    \item{\code{sealed}:}{Object of class \code{"logical"}; is this
      class sealed?  If so, no modifications are allowed. }
  }
}
\details{
  Class definitions are stored as metadata in various packages.
  Additional metadata supplies information on inheritance (the result of
  calls to \code{\link{setIs}}).  Inheritance information implied by the
  class definition itself (because the class contains one or more other
  classes) is also constructed automatically.

  When a class is to be used in an R session, this information is
  assembled to complete the class definition.  The completion is a
  second object of class \code{"classRepresentation"}, cached for the
  session or until something happens to change the information.  A call
  to \code{\link{getClass}} returns the completed definition of a class;
  a call to \code{\link{getClassDef}} returns the stored definition
  (uncompleted).

  In particular, completion fills in the upward- and downward-pointing
  inheritance information for the class, in slots \code{contains} and
  \code{subclasses} respectively.  It's in principle important to note
  that this information can depend on which packages are installed,
  since these may define additional subclasses or superclasses.
}
\seealso{
  See function \code{\link{setClass}} to supply the information in the
  class definition.
  See \link{Classes} for a more basic discussion of class information.
}
\keyword{classes}
\eof
\name{genericFunction-class}
\docType{class}
\alias{genericFunction-class}
\alias{groupGenericFunction-class}
\title{Generic Function Objects }
\description{
  Generic functions (objects from or extending class
  \code{genericFunction}) are extended function objects,
  containing information used in creating and dispatching methods for
  this function.  They also identify the package associated with the
  function and its methods.
}
\section{Objects from the Class}{
  Generic functions are created and assigned by
  \code{\link{setGeneric}} or \code{\link{setGroupGeneric}} and, indirectly, by
  \code{\link{setMethod}}.

  As you might expect \code{\link{setGeneric}} and
  \code{\link{setGroupGeneric}} create objects of class
  \code{"genericFunction"} and \code{"groupGenericFunction"} respectively.
}
\section{Slots}{
  \describe{
    \item{\code{.Data}:}{Object of class \code{"function"}, the
        function definition of the generic, usually created
        automatically as a call to \code{\link{standardGeneric}}. }
    \item{\code{generic}:}{Object of class \code{"character"}, the
        name of the generic function. }
    \item{\code{package}:}{Object of class \code{"character"}, the
        name of the package to which the function definition belongs
        (and \emph{not} necessarily where the generic function is
        stored). If the package is not specified explicitly in the
        call to \code{setGeneric}, it is usually the package on which
        the corresponding non-generic function exists. }
    \item{\code{group}:}{Object of class \code{"list"}, the group or
        groups to which this generic function belongs.  Empty by default. }
    \item{\code{valueClass}:}{Object of class \code{"character"}; if
        not an empty character vector, identifies one or more classes.  It is
        asserted that all methods for this function return objects
        from these class (or from classes that extend them). }
    \item{\code{signature}:}{Object of class \code{"character"}, the
        vector of formal argument names that can appear in the
        signature of methods for this generic function.  By default,
        it is all the formal arguments, except for \dots.  Order
        matters for efficiency:  the most commonly used arguments in
        specifying methods should come first. }
    \item{\code{default}:}{Object of class \code{"OptionalMethods"},
        the default method for this function.  Generated
        automatically and used to initialize method dispatch. }
    \item{\code{skeleton}:}{Object of class \code{"call"}, a slot used
        internally in method dispatch.  Don't expect to use it
        directly.}
  }
}
\section{Extends}{
  Class \code{"function"}, from data part.\cr
  Class \code{"OptionalMethods"}, by class \code{"function"}.\cr
  Class \code{"PossibleMethod"}, by class \code{"function"}.
}
\section{Methods}{
  Generic function objects are used in the creation and dispatch of
  formal methods; information from the object is used to create methods
  list objects and to merge or update the existing methods for this
  generic.
}
\keyword{classes}
\eof
\name{getClass}
\alias{getClass}
\alias{getClassDef}
\title{Get Class Definition }
\description{
  Get the definition of a class.
}
\usage{
getClass(Class, .Force = FALSE, where)
getClassDef(Class, where, package)
}
\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}{ environment from which to begin the search for the definition; by default,
    start at the top-level (global) environment and proceed through
    the search list.}
  \item{package}{ the name of the package asserted to hold the
      definition.  Supplied instead of \code{where}, with the
      distinction that the package need not be currently attached.}
}
\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 the environment \code{where}, unadorned.  It's usually \code{getClass}
  you want.

  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 R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the methods package follows the
  reference, the R software is an original implementation, so details in
  the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page 
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\seealso{
  \link{Classes},
  \code{\link{setClass}},
  \code{\link{isClass}}.
}
\examples{
getClass("numeric") ## a built in class

\dontshow{
getClass("thisIsAnUndefinedClass", .Force = TRUE) ## returns NULL
try(getClass("thisIsAnUndefinedClass")) ## generates an error
try(getClassDef("thisIsAnUndefinedClass")) ## generates an error
}
}
\keyword{programming}
\keyword{classes}
\eof
\name{getMethod}
\alias{getMethod}
\alias{findMethod}
\alias{existsMethod}
\alias{getMethods}
\alias{selectMethod}
\alias{hasMethod}
\alias{MethodsListSelect}
\title{ Get or Test for the Definition of a Method }
\description{
  The functions \code{getMethod} and \code{selectMethod} get the
  definition of a particular method; the functions \code{existsMethod}
  and \code{hasMethod} test for the existence of a method.  In both
  cases the first function only gets direct definitions and the second
  uses inheritance.
  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.

  The other functions are support functions: see the details below.
}
\usage{
getMethod(f, signature=character(), where, optional=FALSE, mlist)

findMethod(f, signature, where)

getMethods(f, where)

existsMethod(f, signature = character(), where)

hasMethod(f, signature=character(), where)

selectMethod(f, signature, optional = FALSE, useInherited = TRUE,
             mlist = (if (is.null(fdef)) NULL else getMethods(fdef)),
             fdef = getGeneric(f, !optional))

MethodsListSelect(f, env, mlist, fEnv, finalDefault, evalArgs,
                  useInherited, fdef, resetAllowed)

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

    }
  \item{signature}{ The signature of classes to match to the arguments
    of \code{f}.  See the details below.

    For \code{selectMethod}, the signature can optionally be an
    environment with classes assigned to the names of the corresponding
    arguments.  Note:  the names correspond to the names of the classes, \emph{not}
    to the objects supplied in a call to the generic function.  (You
    are not likely to find this approach convenient, but it is used
    internally and is marginally more efficient.)
  }
  \item{where}{ The position or environment in which to look for the method(s):  by default,
      anywhere in
    the current 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}{Optionally, the list of methods in which to search.  By
    default, the function finds the methods for the corresponding
    generic function.  To restrict the search to a particular package
    or environment, e.g., supply this argument as
    \code{getMethodsMetaData(f,where)}.  For \code{selectMethod}, see
    the discussion of argument \code{fdef}.
    }

  \item{fdef}{In \code{selectMethod}, the \code{MethodsList} object
    and/or the generic function 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, resetAllowed}{ Internal-use
    arguments for the function's environment, the method to use as
    the overall default, whether to evaluate arguments, which
    arguments should use inheritance, and whether the cached methods
    are allowed to be reset.}
}
\details{
  The \code{signature} argument specifies classes, in an extended
    sense, corresponding to formal arguments of the generic function.
    As supplied, the argument may be a vector of strings identifying
    classes, and may be named or not.  Names, if supplied, match the
    names of those formal arguments included in the signature of the
    generic.  That signature is normally all the arguments except
    \dots.  However, generic functions can be specified with only a
    subset of the arguments permitted, or with the signature taking
    the arguments in a different order.

    It's a good idea to name the arguments in the signature to avoid
    confusion, if you're dealing with a generic that does something
    special with its signature.   In any case, the elements of the
    signature are matched to the formal signature by the same rules
    used in matching arguments in function calls (see
    \code{\link{match.call}}).

    The strings in the signature may be class names, \code{"missing"}
    or \code{"ANY"}.  See \link{Methods} for the meaning of these in
    method selection.  Arguments not supplied in the signature
    implicitly correspond to class \code{"ANY"}; in particular, giving
    an empty signature means to look for the default method.

  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{selectMethod} also looks for a method given the
  function and signature, but makes full use of the method dispatch
  mechanism; i.e., inherited methods and group generics are taken into
  account just as they would be in dispatching a method for the
  corresponding signature, with the one exception that conditional
  inheritance is not used.  Like \code{getMethod}, \code{selectMethod}
  returns \code{NULL} or generates an error if
  the method is not found, depending on the argument \code{optional}.

  The functions \code{existsMethod} and \code{hasMethod} return
  \code{TRUE} or \code{FALSE} according to whether a method is found,
  the first corresponding to \code{getMethod} (no inheritance) and the
  second to \code{selectMethod}.

  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.  Note that it gets \emph{all} the visible
  methods for the specified functions.  If you want only the methods
  defined explicitly in a particular environment, use the function
  \code{\link{getMethodsMetaData}} instead.

  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.)


}
\value{
  The call to \code{selectMethod} or \code{getMethod} returns a
  \code{\link{MethodDefinition-class}} object, the selected method, if
  a unique selection exists.
  (This class extends \code{function}, so you can use the result
  directly as a function if that is what you want.)
  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 R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes
  and methods in the book \emph{Programming with Data} (John
  M. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8,
  and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\examples{
setGeneric("testFun", function(x)standardGeneric("testFun"))
setMethod("testFun", "numeric", function(x)x+1)
hasMethod("testFun", "numeric")
\dontrun{[1] TRUE}
hasMethod("testFun", "integer") #inherited
\dontrun{[1] TRUE}
existsMethod("testFun", "integer")
\dontrun{[1] FALSE}
hasMethod("testFun") # default method
\dontrun{[1] FALSE}
hasMethod("testFun", "ANY")
\dontrun{[1] FALSE}
\dontshow{
stopifnot(isGeneric("testFun"))
stopifnot(hasMethod("testFun", "numeric"))
stopifnot(hasMethod("testFun", "integer"))
stopifnot(!existsMethod("testFun", "integer"))
stopifnot(!hasMethod("testFun"))
stopifnot(!hasMethod("testFun", "ANY"))
removeGeneric("testFun")
}
}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\eof
\name{getPackageName}
\alias{getPackageName}
\alias{setPackageName}
\alias{packageSlot}
\alias{packageSlot<-}
\title{ The name associated with a given package }
\description{
  The functions below produce the package associated with a particular
  environment or position on the search list, or of the package containing a particular
  function.  They are primarily used to support computations that need
  to differentiate objects on multiple packages.
}
\usage{
getPackageName(where)

packageSlot(object)
packageSlot(object) <- value
}
\arguments{
  \item{where}{ The environment or position on the search list
      associated with the desired package. }

  \item{object}{An object providing a character string name, plus the
 package in which this object is to be found.}
\item{value}{the name of the package.}
 }
\details{
  Package names are normally installed during loading of the package,
  by the \link{INSTALL} script or by the \code{\link{library}}
  function.  (Currently, the name is stored as the object
  \code{.packageName} but don't trust this for the future.)
}
\value{
   \code{packageName} return the character-string name of the package
  (without the extraneous \code{"package:"} found in the search list).

  \code{packageSlot} returns or sets the package name slot (currently
 an attribute, not a formal slot, but this will likely change).
}

\seealso{ \code{\link{search}} }

\examples{
## both the following usually return "base"
getPackageName(length(search()))

}
\keyword{ programming }% at least one, from doc/KEYWORDS
\eof
\name{hasArg}
\alias{hasArg}
\title{Look for an Argument in the Call}
\description{
  Returns \code{TRUE} is \code{name} corresponds to an argument in the
  call, either a formal argument to the function, or a component of
  \code{...}, and \code{FALSE} otherwise.
}
\usage{
hasArg(name)
}
\arguments{
  \item{name}{The unquoted name of a potential argument.}
}
\details{
  The expression \code{hasArg(x)}, for example, is similar to
  \code{!missing(x)}, with two exceptions.  First,  \code{hasArg} will look for
  an argument named \code{x} in the call if \code{x} is not a formal
  argument to the calling function, but \code{...} is.  Second,
  \code{hasArg} never generates an error if given a name as an argument,
  whereas \code{missing(x)} generates an error if \code{x} is not a
  formal argument.
}
\value{
  Always \code{TRUE} or \code{FALSE} as described above.
}
\seealso{ \code{\link{missing}} }

\examples{
ftest <- function(x1, ...) c(hasArg(x1), hasArg(y2))

ftest(1) ## c(TRUE, FALSE)
ftest(1, 2)  ## c(TRUE, FALSE)
ftest(y2=2)   ## c(FALSE, TRUE)
ftest(y=2)    ## c(FALSE, FALSE) (no partial matching)
ftest(y2 = 2, x=1)  ## c(TRUE, TRUE) partial match x1


}
\keyword{ programming }
\eof
\name{initialize-methods}
\docType{methods}
\title{Methods to Initialize New Objects from a Class}
\alias{initialize-methods}
\alias{initialize,ANY-method}
\alias{initialize,traceable-method}
\alias{initialize,signature-method}
\alias{initialize,environment-method}
\description{The arguments to function \code{\link{new}} to create an
object from a particular class can be interpreted specially for that
class, by the definition of a method for function \code{initialize}
for the class.  This documentation describes some existing
methods, and also outlines how to write new ones.
}
\section{Methods}{\describe{

\item{.Object = "ANY"}{The default method for \code{initialize} takes
    either named or unnamed arguments.  Argument names must be the
    names of slots in this class definition, and the corresponding
    arguments must be valid objects for the slot (that is, have the
    same class as specified for the slot, or some superclass of that
    class). If the object comes from a superclass, it is not coerced
    strictly, so normally it will retain its current class (specifically,
    \code{\link{as}(object, Class, strict = FALSE)}).

    Unnamed arguments must be objects of this class, of one of its
    superclasses, or one of its subclasses (from the class, from a
    class this class extends, or from a class that extends this
    class). If the object is from a superclass, this normally defines
    some of the slots in the object.  If the object is from a
    subclass, the new object is that argument, coerced to the current
    class.

    Unnamed arguments are processed first, in the order they appear.
    Then named arguments are processed.  Therefore, explicit values
    for slots always override any values inferred from superclass or
    subclass arguments.
}

\item{.Object = "traceable"}{ Objects of a class that extends
 \code{traceable} are used to implement debug tracing (see
 \link{traceable-class} and \code{\link[base]{trace}}).

The \code{initialize} method for these classes takes special arguments
\code{def, tracer, exit, at, print}.  The first of these is the object
to use as the original definition (e.g., a function).  The others
correspond to the arguments to \code{\link[base]{trace}}.
 }

\item{.Object = "environment"}{The \code{initialize} method for
    environments takes a named list of objects to be used to
    initialize the environment. }

\item{.Object = "signature"}{ This is a method for internal use only.
 It takes an optional \code{functionDef} argument to provide a generic
 function with a \code{signature} slot to define the argument names.
 See \link{Methods} for details.
 }


}}
\section{Writing Initialization Methods}{Initialization methods
  provide a general mechanism corresponding to generator functions in
  other languages.

  The arguments to \code{\link{initialize}} are \code{.Object} and
  \dots. Nearly always, \code{initialize} is called from \code{new},
  not directly.  The \code{.Object} argument is then the
  prototype object from the class.

  Two techniques are often appropriate for \code{initialize} methods:
  special argument names and \code{callNextMethod}.

  You may want argument names that are more natural to your users than
  the (default) slot names.  These will be the formal arguments to
  your method definition, in addition to \code{.Object} (always) and
  \dots (optionally).  For example, the method for class
  \code{"traceable"} documented above would be created by a call to
  \code{\link{setMethod}} of the form:

\code{setMethod("initialize", "traceable",}
\cr
\code{    function(.Object, def, tracer, exit, at, print) } \dots
\cr
\code{)}

In this example, no other arguments are meaningful, and the resulting
method will throw an error if other names are supplied.

When your new class extends another class, you may want to call the
initialize method for this superclass (either a special method or the
default).  For example, suppose you want to define a method for your
class, with special argument \code{x}, but you also want users to be
able to set slots specifically.  If you want \code{x} to override the
slot information, the beginning of your method definition might look
something like this:

\code{function(.Object, x, ...) \{}
\cr
\code{    Object <- callNextMethod(.Object, ...) }
\cr
\code{    if(!missing(x)) \{ # do something with x }

You could also choose to have the inherited method override, by first
interpreting \code{x}, and then calling the next method.

}
\keyword{methods}
\keyword{programming}
\eof
\name{is}
\alias{is}
\alias{extends}
\alias{setIs}
\title{Is an Object from a Class}
\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 \code{class1} to be an extension of \code{class2}.
}
\usage{
is(object, class2)

extends(class1, class2, maybe=TRUE, fullInfo = FALSE)

setIs(class1, class2, test=NULL, coerce=NULL, replace=NULL,
      by = character(), where = topenv(parent.frame()), classDef =,
      extensionObject = NULL, doComplete = TRUE)
}
\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, fullInfo}{
      In a call to \code{extends}, \code{maybe} is a flag to
      include/exclude conditional relations, and \code{fullInfo} is a
      flag, which if \code{TRUE} causes object(s) of class
      \code{classExtension} to be returned, rather than just the
      names of the classes or a logical value.  See the details
      below.}

  \item{extensionObject}{ alternative to the \code{test, coerce,
    replace, by} arguments; an object from class
    \code{SClassExtension} describing the relation.  (Used in internal calls.)
    }

  \item{doComplete}{when \code{TRUE}, the class definitions will be
  augmented with indirect relations as well.  (Used in internal calls.)}


  \item{test, coerce, replace}{
    In a call to \code{setIs}, 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{by}{
    In a call to \code{setIs}, the name of an intermediary class.  Coercion will proceed by first
    coercing to this class and from there to the target class.  (The
    intermediate coercions have to be valid.)}
  \item{where}{
    In a call to \code{setIs}, where to store the metadata defining the relationship. Default is
    the global environment.}
  \item{classDef}{
    Optional class definition for \code{class} , required internally
    when \code{setIs} is called during the initial definition of the
    class by a call to \code{\link{setClass}}. \emph{Don't} use this
    argument, unless you really know why you're doing so.}
}

\details{
\describe{
  \item{\code{extends}:}{

  Given two class names, \code{extends} by default says whether the
  first class extends the second; that is, it does for class names
  what \code{is} does for an object and a class.  Given one class
  name, it returns all the classes that class extends (the
  \dQuote{superclasses} of that class), including the class itself.  If
  the flag \code{fullInfo} is \code{TRUE}, the result is a list, each
  element of which is an object describing the relationship;
  otherwise, and by default, the value returned is only the names of
  the classes.}

  \item{\code{setIs}: }{

    This function establishes an inheritance relation between two
    classes, by some means other than having one class contain the
    other.  It should \emph{not} be used for ordinary relationships:
    either include the second class in the \code{contains=} argument
    to \code{\link{setClass}} if the class is contained in the usual
    way, or consider \code{setClassUnion} to define a virtual class
    that is extended by several ordinary classes.  A call to
    \code{setIs} makes sense, for example, if one class ought to be
    automatically convertible into a second class, but they have
    different representations, so that the conversion must be done by
    an explicit computation, not just be inheriting slots, for
    example.  In this case, you will typically need to provide both a
    \code{coerce=} and \code{replace=} argument to \code{setIs}.


  The \code{coerce}, \code{replace}, and \code{by} arguments behave as
  described for the \code{\link{setAs}} function.  It's unlikely you
  would use the \code{by} argument directly, but it is used in defining
  cached information about classes.  The value returned (invisibly) by
  \code{setIs} is the extension information, as a list.

  The  \code{coerce} argument is a function that turns a
  \code{class1} object into a \code{class2} object.  The
  \code{replace} argument is a function of two arguments that modifies a \code{class1}
  object (the first argument) to replace the part of it that
  corresponds to \code{class2} (supplied as \code{value}, the second
  argument).  It then returns the modified object as the value of the
  call.  In other words, it acts as a replacement method to
  implement the expression \code{as(object, class2) <- value}.

  The easiest way to think of the  \code{coerce} and \code{replace}
  functions is by thinking of the case that  \code{class1}
  contains \code{class2} in the usual sense, by including the slots of
  the second class.  (To repeat, in this situation you would not call
  \code{setIs}, but the analogy shows what happens when you do.)

  The \code{coerce} function in this case would just make a
  \code{class2} object by extracting the corresponding slots from the
  \code{class1} object. The \code{replace} function would replace in
  the \code{class1} object the slots corresponding to \code{class2},
  and return the modified object as its value.


  The relationship can also be conditional, if a function is supplied as the
  \code{test} argument.  This should be a function of one argument
  that returns \code{TRUE} or \code{FALSE} according to whether the
  object supplied satisfies the relation \code{is(object, class2)}.
  If you worry about such things, conditional relations between
  classes are slightly deprecated because they cannot be implemented
  as efficiently as ordinary relations and because they sometimes can
  lead to confusion (in thinking about what methods are dispatched for
  a particular function, for example).  But they can correspond to
  useful distinctions, such as when two classes have the same representation,
  but only one of them obeys certain additional constraints.

  Because only global environment information is saved, it rarely makes
  sense to give a value other than the default for argument
  \code{where}.  One exception is \code{where=0}, which modifies the
  cached (i.e., session-scope) information about the class.  Class
  completion computations use this version, but don't use it yourself
  unless you are quite sure you know what you're doing.
}
}
}
\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\examples{
\dontshow{
## 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)))
## Automatically convert an object from class "trackCurve" into
## "trackMultiCurve", by making the y, smooth slots into 1-column matrices
setIs("trackCurve",
      "trackMultiCurve",
      coerce = function(obj) {
        new("trackMultiCurve",
            x = obj@x,
            y = as.matrix(obj@y),
            curve = as.matrix(obj@smooth))
      },
      replace = function(obj, value) {
        obj@y <- as.matrix(value@y)
        obj@x <- value@x
        obj@smooth <- as.matrix(value@smooth)
        obj})

## Automatically convert the other way, but ONLY
## if the y data is one variable.
setIs("trackMultiCurve",
      "trackCurve",
      test = function(obj) {ncol(obj@y) == 1},
      coerce = function(obj) {
        new("trackCurve",
            x = slot(obj, "x"),
            y = as.numeric(obj@y),
            smooth = as.numeric(obj@smooth))
      },
      replace = function(obj, value) {
        obj@y <- matrix(value@y, ncol=1)
        obj@x <- value@x
        obj@smooth <- value@smooth
        obj})
\dontshow{
removeClass("trackMultiCurve")
removeClass("trackCurve")
removeClass("track")
}
}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\eof
\name{isSealedMethod}
\alias{isSealedMethod}
\alias{isSealedClass}
\title{ Check for a Sealed Method or Class }
\description{
  These functions check for either a method or a class that has been
  \dQuote{sealed} when it was defined, and which therefore cannot be
  re-defined.
}
\usage{
isSealedMethod(f, signature, fdef, where)
isSealedClass(Class, where)
}
\arguments{
  \item{f}{ The quoted name of the generic function. }
  \item{signature}{ The class names in the method's signature, as
  they would be supplied to \code{\link{setMethod}}. }
  \item{fdef}{ Optional, and usually omitted:  the generic function
      definition for \code{f}. }
  \item{Class}{The quoted name of the class.}

  \item{where}{where to search for the method or class definition.  By
    default, searches from the top environment of the call to
    \code{isSealedMethod} or \code{isSealedClass}, typically the
    global environment or the namespace of a package containing a call
    to one of the functions.}
}
\details{
  In the R implementation of classes and methods, it is possible to
  seal the definition of either a class or a method.  The basic
  classes (numeric and other types of vectors, matrix and array data)
  are sealed.  So also are the methods for the primitive functions on
  those data types.  The effect is that programmers cannot re-define
  the meaning of these basic data types and computations.  More
  precisely, for primitive functions that depend on only one data
  argument, methods cannot be specified for basic classes.  For
  functions (such as the arithmetic operators) that depend on two
  arguments, methods can be specified if \emph{one} of those arguments
  is a basic class, but not if both are.

  Programmers can seal other class and method definitions by using the
  \code{sealed} argument to \code{\link{setClass}} or \code{\link{setMethod}}.
}
\value{
  The functions return \code{FALSE} if the method or class is not
  sealed (including the case that it is not defined); \code{TRUE} if
  it is.
}
\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page 
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\examples{
## these are both TRUE
isSealedMethod("+", c("numeric", "character"))
isSealedClass("matrix")

setClass("track",
            representation(x="numeric", y="numeric"))
## but this is FALSE
isSealedClass("track")
## and so is this
isSealedClass("A Name for an undefined Class")
## and so are these, because only one of the two arguments is basic
isSealedMethod("+", c("track", "numeric"))
isSealedMethod("+", c("numeric", "track"))

\dontshow{
removeClass("track")
}
}
\keyword{programming}
\keyword{classes}
\keyword{classes}
\keyword{methods}
\eof
\name{languageEl}
\alias{languageEl}
\alias{languageEl<-}
\alias{isGrammarSymbol}
\title{Elements of Language Objects}
\description{
  Internal routines to support some operations on language objects.
}
\usage{
languageEl(object, which)

isGrammarSymbol(symbol)

}
\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{\code{isGrammarSymbol}:}{
      Checks whether the symbol is part of the grammar.
      Don't use this function directly.
    }
  }
}
\keyword{internal}
\eof
\name{methodUtilities}
\alias{functionBody}
\alias{functionBody<-}
\alias{allNames}
\alias{getFunction}
\alias{existsFunction}
\alias{el}
\alias{elNamed}
\alias{el<-}
\alias{elNamed<-}
\alias{formalArgs}
\alias{Quote}
\alias{message}
\alias{showDefault}
\alias{initMethodDispatch}
\title{Utility Functions for Methods and S-Plus Compatibility}
\description{
  These are utilities, currently in the \pkg{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.
}
\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, oldMethods = TRUE)

initMethodDispatch()
}
\section{Summary of Functions}{
  \describe{
    \item{\code{allNames}:}{ 
      the character vector of names (unlike \code{names()}, never
      returns \code{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} is
      \code{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}).
 
  { Argument \code{oldMethods} controls whether old-style print
    methods are used for this
    object.  It is  \code{TRUE} by default if called directly, but \code{FALSE}
    when called from the \pkg{methods} package for automatic printing (to
    avoid potential recursion).
    }
    \item{\code{initMethodDispatch}:}{
        Turn on the internal method dispatch code.  Called on
        attaching the package.  Also, if dispatch has been turned off
        (by calling \code{.isMethodsDispatchOn(FALSE)}---a very gutsy
        thing to do), calling this function should turn dispatch back
        on again.
      }
    }
  }
}
\keyword{internal}
\eof
\name{new}
\alias{new}
\alias{initialize}
\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, ...)

initialize(.Object, ...)
}
\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{.Object}{ An object:  see the Details section.}
}
\details{
  The function \code{new} begins by copying the prototype object from
  the class definition.  Then information is inserted according to the
  \code{\dots} arguments, if any.

  The interpretation of the \code{\dots} arguments can be specialized to
  particular classes, if an appropriate method has been defined for the
  generic function \code{"initialize"}.  The \code{new} function calls
  \code{initialize} with the object generated from the prototype as the
  \code{.Object} argument to \code{initialize}.

  By default, unnamed arguments in the \code{\dots} are interpreted as
  objects from a superclass, and named arguments are interpreted as
  objects to be assigned into the correspondingly named slots.  Thus,
  explicit slots override inherited information for the same slot,
  regardless of the order in which the arguments appear.

  The \code{initialize} methods do not have to have \code{\dots} as
  their second argument (see the examples), and generally it is better
  design \emph{not} to have \code{\dots} as a formal argument, if only a
  fixed set of arguments make sense.

  For examples of \code{initialize} methods, see
  \code{\link{initialize-methods}} for existing methods for
  classes \code{"traceable"} and \code{"environment"}, among others.

  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.
}
\seealso{ \link{Classes} }

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

\dontshow{
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)

### define a method for initialize, to ensure that new objects have
### equal-length x and y slots.

setMethod("initialize",
          "track",
          function(.Object, x = numeric(0), y = numeric(0)) {
            if(nargs() > 1) {
              if(length(x) != length(y))
                stop("specified x and y of different lengths")
              .Object@x <- x
              .Object@y <- y
            }
            .Object
          })

### the next example will cause an error (x will be numeric(0)),
### because we didn't build in defaults for x,
### although we could with a more elaborate method for initialize

try(new("track", y = sort(rnorm(10))))

## a better way to implement the previous initialize method.
## Why?  By using callNextMethod to call the default initialize method
## we don't inhibit classes that extend "track" from using the general
## form of the new() function.  In the previous version, they could only
## use x and y as arguments to new, unless they wrote their own
## intialize method.

setMethod("initialize", "track", function(.Object, ...) {
    .Object <- callNextMethod()
    if(length(.Object@x) != length(.Object@y))
     stop("specified x and y of different lengths")
    .Object
  })

}
\keyword{programming}
\keyword{classes}
\eof
\name{oldGet}
\alias{getAccess}
\alias{getClassName}
\alias{getClassPackage}
\alias{getExtends}
\alias{getProperties}
\alias{getPrototype}
\alias{getSubclasses}
\alias{getValidity}
\alias{getVirtual}
\title{Old functions to access slots in a class definition }
\description{
Expect these functions to become deprecated in the near future.

 They do nothing but access a slot in a class definition, and don't
 even do this consistently  with the right name (they date back to the
 early implementation of the \pkg{methods} package).
 Higher-level functions for the useful operations (e.g.,
 \code{\link{extends}} for \code{getExtends}) should be used instead.

}
\usage{
getAccess(ClassDef) 

getClassName(ClassDef) 

getClassPackage(ClassDef) 

getExtends(ClassDef) 

getProperties(ClassDef) 

getPrototype(ClassDef) 

getSubclasses(ClassDef) 

getValidity(ClassDef) 

getVirtual(ClassDef) 

}
%- maybe also 'usage' for other objects documented here.
\arguments{
  \item{ClassDef}{ the class definition object }
}
\details{
  The functions should be replaced by direct access to the slots, or
  by use of higher-level alternatives.

The functions and corresponding slots are: 
\tabular{ll}{
\code{getAccess} \tab \code{"access"} \cr
\code{getClassName} \tab \code{"className"} \cr
\code{getClassPackage} \tab \code{"package"} \cr
\code{getExtends} \tab \code{"contains"} \cr
\code{getProperties} \tab \code{"slots"} \cr
\code{getPrototype} \tab \code{"prototype"} \cr
\code{getSubclasses} \tab \code{"subclasses"} \cr
\code{getValidity} \tab \code{"validity"} \cr
\code{getVirtual} \tab \code{"virtual"}
}

}
\seealso{ \code{\link{classRepresentation-class}} }
\keyword{internal}
\eof
\name{promptClass}
\alias{promptClass}
\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 QC facilities at present.
}
\usage{
promptClass(clName, filename = NULL, type = "class",
            keywords = "classes", where = topenv(parent.frame()))
}
\arguments{
  \item{clName}{a character string naming the class to be documented.}
  \item{filename}{usually, a connection or a character string giving the
    name of the file to which the documentation shell should be written.
    The default corresponds to a file whose name is the topic name for
    the class documentation, followed by \code{".Rd"}.  Can also be
    \code{NA} (see below).}
  \item{type}{the documentation type to be declared in the output file.}
  \item{keywords}{the keywords to include in the shell of the
    documentation.  The keyword \code{"classes"} should be one of
    them.}
  \item{where}{where to look for the definition of the class and of
    methods that use it.
    %%FIXME: By default, anywhere in the current search list.
  }
}
\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 in the same environment 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, unless \code{filename} is
  \code{NA}, the documentation shell is written to a file, and a message
  about this is given.  The file 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.

  If \code{filename} is \code{NA}, a list-style representation of the
  documentation shell is created and returned.  Writing the shell to a
  file amounts to \code{cat(unlist(x), file = filename, sep = "\\n")},
  where \code{x} is the list-style representation.
}
\value{
  If \code{filename} is \code{NA}, a list-style representation of the
  documentation shell.  Otherwise, the name of the file written to is
  returned invisibly.
}
\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 \file{man}
  subdirectory of a package.
}
\examples{
\dontshow{
## 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}
\eof
\name{promptMethods}
\alias{promptMethods}
\title{ Generate a Shell for Documentation of Formal Methods }
\description{
  Generates a shell of documentation for the methods of a generic
  function.
}
\usage{
promptMethods(f, filename = NULL, methods)
}
\arguments{
  \item{f}{a character string naming the generic function whose methods
    are to be documented.}
  \item{filename}{usually, a connection or a character string giving the
    name of the file to which the documentation shell should be written.
    The default corresponds to the coded topic name for these methods
    (currently, \code{f} followed by \code{"-methods.Rd"}).  Can also be
    \code{FALSE} or \code{NA} (see below).}
  \item{methods}{Optional methods list object giving the methods to be
    documented.  By default, the first methods object for this generic
    is used (for example, if the current global environment has some
    methods for \code{f}, these would be documented).

    If this argument is supplied, it is likely to be
    \code{getMethods(f, where)}, with \code{where} some package
    containing methods for \code{f}.}
}
\value{
  If \code{filename} is \code{FALSE}, the text generated;
  if \code{filename} is \code{NA}, a list-style representation of the
  documentation shell.
  Otherwise, the name of the file written to is returned invisibly.
}
\details{
  If \code{filename} is \code{FALSE}, the text created is returned,
  presumably to be inserted some other documentation file, such as the
  documentation of the generic function itself (see
  \code{\link{prompt}}). 

  If \code{filename} is \code{NA}, a list-style representation of the
  documentation shell is created and returned.  Writing the shell to a
  file amounts to \code{cat(unlist(x), file = filename, sep = "\\n")},
  where \code{x} is the list-style representation.

  Otherwise, the documentation shell is written to the file specified by
  \code{filename}.
}
\seealso{
  \code{\link{prompt}} and
  \code{\link{promptClass}}
}
\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page 
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\keyword{programming}
\keyword{methods}
\eof
\name{representation}
\alias{representation}
\alias{prototype}
\title{ Construct a  Representation or a Prototype for a Class Definition}
\description{
  In calls to
  \code{\link{setClass}}, these two functions construct,
  respectively, the \code{representation} and \code{prototype}
  arguments.  They do various checks and handle special cases.  You're
  encouraged to use them when defining classes that, for
  example, extend other classes as a data part or have multiple
  superclasses, or that combine extending a class and slots.
}
\usage{
representation(...)
prototype(...)
}
\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.
   
    In the call to \code{prototype}, if an unnamed argument is
    supplied, it unconditionally forms the basis for the prototype
    object.  Remaining arguments are taken to correspond to slots of
    this object.  It is an error to supply more than one unnamed argument.
}
}
\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.

  The arguments to \code{prototype} are usually named initial values
  for slots, plus an optional first argument that gives the object
  itself.  The unnamed argument is typically useful if there is a data
  part to the definition (see the examples below).
}
\value{
  The value pf \code{representation}  is just the list of arguments, after these have been checked
  for validity.

  The value of \code{prototype} is the object to be used as the
  prototype.  Slots will have been set consistently with the
  arguments, but the construction does \emph{not} use the class
  definition to test validity of the contents (it hardly can, since
  the prototype object is usually supplied to create the definition).
}
\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page 
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\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")
\dontshow{
prev <- getClassDef("class3")
setClass("class1", representation(a="numeric", b = "character"))
setClass("class2", representation(a2 = "numeric", b = "numeric"))
try(setClass("class3", representation("class1", "class2")))
{if(is.null(prev))
  stopifnot(!isClass("class3"))
else
  stopifnot(identical(getClassDef("class3"), prev))}
}

setClass("Character",representation("character"))
setClass("TypedCharacter",representation("Character",type="character"),
          prototype(character(0),type="plain"))
ttt <- new("TypedCharacter", "foo", type = "character")
\dontshow{
stopifnot(identical(as(ttt, "character"), "foo"))
}

setClass("num1", representation(comment = "character"),
         contains = "numeric",
         prototype = prototype(pi, comment = "Start with pi"))

\dontshow{
stopifnot(identical(new("num1"), new("num1", pi, comment = "Start with pi")))
for(cl in c("num1", "TypedCharacter", "Character", "class2", "class1"))
    removeClass(cl)
}

}
\keyword{programming}
\keyword{classes}

\eof
\name{setClass}
\alias{setClass}
\alias{removeClass}
\alias{resetClass}
\alias{isClass}
\alias{getClasses}
\alias{findClass}
\alias{sealClass}
\title{Create a Class Definition}
\description{
  Functions to create (\code{setClass}) and manipulate class definitions.
}
\usage{
setClass(Class, representation, prototype, contains=character(),
         validity, access, where, version, sealed, package)

removeClass(Class, where)

isClass(Class, formal=TRUE, where)

getClasses(where, inherits = missing(where))

findClass(Class, where, unique = "")

resetClass(Class, classDef, where)

sealClass(Class, where)

}
\arguments{
  \item{Class}{ character string name for the class.  Other than
  \code{setClass}, the functions will usually take a class definition
  instead of the string (allowing the caller to identify the class uniquely). }
  \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}{ For \code{setClass} and \code{removeClass}, the
    environment in which to store or remove the
    definition.  Defaults to the top-level environment of the calling function
    (the global environment for ordinary computations, but the
    environment or namespace of a package when loading that package).

    For other functions, \code{where} defines where to do the search
    for the class definition, and the default is to search from the top-level
    environment or namespace of the caller to this function.
    }
  \item{unique}{if \code{findClass} expects a unique location for the
    class, \code{unique} is a character string explaining the purpose
    of the search (and is used in warning and error messages).  By
    default, multiple locations are possible and the function always
    returns a list.
    }
  \item{inherits}{in a call to \code{getClasses}, should the value
    returned include all parent environments of \code{where}, or that
    environment only?  Defaults to \code{TRUE} if \code{where} is
    omitted, and to \code{FALSE} otherwise.
    }
  \item{validity}{ if supplied, should be a validity-checking method
  for objects from this class (a function that returns \code{TRUE} if
  its argument is a valid object of this class and one or more strings
  describing the failures otherwise).  See \code{\link{validObject}}
  for details.  }
\item{access}{Access list for the class.  Saved in the definition, but
  not currently used.}
\item{version}{A version indicator for this definition. Saved in the
    definition, but not currently used.}
  \item{sealed}{ If \code{TRUE}, the class definition will be sealed,
    so that another call to \code{setClass} will fail on this class name.
    }
  \item{package}{ An optional package name for the class.  By default
  (and usually) the package where the class definition is assigned
  will be used.
    }
  \item{formal}{ Should a formal definition be required? }


  \item{classDef}{ For \code{removeClass}, the optional class
    definition (but usually it's better for \code{Class} to be the
    class definition, and to omit \code{classDef}).
    }


}
\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 \code{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, from the environment
      \code{where} if this argument is supplied; if not,
      \code{removeClass} will search for a definition, starting in the
      top-level environment of the call to \code{removeClass}, and
      remove the (first) definition found.
    }
  
    \item{\code{isClass}:}{ 
      Is this a the name of a formally defined class? (Argument
      \code{formal} is for compatibility and is ignored.)
    }


    \item{\code{getClasses}:}{
      The names of all the classes formally defined on \code{where}.  If
      called with no argument, all the classes visible from the
      calling function (if called from the top-level, all the classes
      in any of the environments on the search list).  The
      \code{inherits} argument can be used to search a particular
      environment and all its parents, but usually the default setting
      is what you want.
    }
    \item{\code{findClass}:}{
        The list of environments or positions on the search list in
        which a class definition of \code{Class} is found.  If
        \code{where} is supplied, this is an environment (or
        namespace) from which the search takes place; otherwise the
        top-level environment of the caller is used.  If \code{unique} is supplied
        as a character string, \code{findClass} returns a single
        environment or position.  By default, it always returns a
        list.  The calling function should select, say, the first element
        as a position or environment for functions such as
        \code{\link{get}}.

        If \code{unique} is supplied as a character string, \code{findClass} will
        warn if there is more than one definition visible (using the
        string to identify the purpose of
        the call), and will generate an error if no definition can be found.

    }
    
    \item{\code{resetClass}:}{
      Reset the internal definition of a class.  Causes the complete
      definition of the class to be re-computed, from the
      representation and superclasses specified in the original
      call to \code{\link{setClass}}.

      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).

    }

  \item{sealClass}{ Seal the current definition of the specified
    class, to prevent further changes.  It is possible to seal a class
    in the call to \code{setClass}, but sometimes further changes have
    to be made (e.g., by calls to \code{setIs}).  If so, call
    \code{sealClass} after all the relevant changes have been made.
    }
  }
}
\section{Inheritance and Prototypes}{
  Defining new classes that inherit from (\dQuote{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 R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\examples{
\dontshow{
if(isClass("trackMultiCurve"))
  removeClass("trackMultiCurve")
if(isClass("trackCurve"))
  removeClass("trackCurve")
if(isClass("track"))
  removeClass("track")
}
## 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")))
  })
\dontshow{
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))
### tests of the C macros MAKE_CLASS and NEW
### FIXME:  there should be a separate man page for the C-level macros
### and the tests below should be there.
stopifnot(identical(.Call("R_methods_test_MAKE_CLASS", "trackCurve", PACKAGE = "methods"),
                    getClass("trackCurve")))

stopifnot(identical(.Call("R_methods_test_NEW", "track", PACKAGE = "methods"),
                    new("track")))


## The following should not be needed.  But make check removes all files
## between example files, in a crude way that does not cause the class
## information to be reset.  There seems no way to detect this, so we
## have to remove classes ourselves

removeClass("withId")
removeClass("maybeNumber")
removeClass("xNum")
removeClass("myMatrix")
resetClass("integer")
resetClass("numeric")
resetClass("logical")
removeClass("trackMultiCurve")
removeClass("trackCurve")
removeClass("track")
}
}
\seealso{
  \code{\link{setClassUnion}},
  \code{\link{Methods}},
  \code{\link{makeClassRepresentation}}}
\keyword{programming}
\keyword{classes}
\keyword{methods}
\eof
\name{setClassUnion}
\alias{setClassUnion}
\alias{isClassUnion}
\alias{ClassUnionRepresentation-class}
\title{Classes Defined as the Union of Other Classes}
\description{
  A class may be defined as the \emph{union} of other classes; that
  is, as a virtual class defined as a superclass of several other
  classes. Class unions are useful in method signatures or as slots in
  other classes, when we want to allow one of several classes to be supplied.
}
\usage{
setClassUnion(name, members, where)
isClassUnion(Class)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
  \item{name}{ the name for the new union class. }
  \item{members}{ the classes that should be members of this union.}
  \item{where}{ where to save the new class definition; by default,
      the environment of the package in which the \code{setClassUnion}
      call appears, or the global environment if called outside of the
      source of a package.}


  \item{Class}{ the name or definition of a class.
    }
}
\details{
  The classes in \code{members} must be defined before creating the
      union.  However, members can be added later on to an existing
      union, as shown in the example below. Class unions can be
      members of other class unions.

  Class unions are the only way to create a class that is extended by
      a class whose definition is sealed (for example, the
      basic datatypes or other classes defined in the base or methods
      package in R are sealed).  You cannot say \code{setIs("function", "other")}
      unless \code{"other"} is a class union.  In general, a
      \code{setIs} call of this form changes the definition of the
      first class mentioned (adding \code{"other"} to the list of
      superclasses contained in the definition of \code{"function"}).

      Class unions get around this by not modifying the first class
  definition, relying instead on storing information in the subclasses
  slot of the class union.  In order for this technique to work, the
  internal computations for expressions such as
  \code{\link{extends}(class1, class2)} work
  differently for class unions than for regular classes; specifically,
  they test whether any class is in common between the superclasses of
  \code{class1} and the subclasses of \code{class2}.

  The different behavior for class unions is made possible because the
  class definition object for class unions has itself a special class,
  \code{"ClassUnionRepresentation"}, an extension of
  \code{"classRepresentation"} (see \link{classRepresentation-class}).
  }

\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}

\examples{

## a class for either numeric or logical data
setClassUnion("maybeNumber", c("numeric", "logical"))

## use the union as the data part of another class
setClass("withId", representation("maybeNumber", id = "character"))

w1 <- new("withId", 1:10, id = "test 1")
w2 <- new("withId", sqrt(w1)\%\%1 < .01, id = "Perfect squares")

## add class "complex" to the union "maybeNumber"
setIs("complex", "maybeNumber")

w3 <- new("withId", complex(real = 1:10, imaginary = sqrt(1:10)))

## a class union containing the existing class  union "OptionalFunction"
setClassUnion("maybeCode",
    c("expression", "language", "OptionalFunction"))

is(quote(sqrt(1:10)), "maybeCode")  ## TRUE
\dontshow{
## The following test is less trivial than it looks.
## It depends on the assignment of the data part NOT performing a
## strict coerce to "numeric" on the way to satisfying
## is(ttt, "maybeNumber").
stopifnot(identical(w1@.Data, 1:10))
}

}
\keyword{programming}
\keyword{classes}
\eof
\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.  Typically, an existing non-generic
  function becomes the default method, but there is much optional
  control.  See the details section.
}
\usage{
setGeneric(name, def= , group=list(), valueClass=character(), where= ,
           package= , signature= , useAsDefault= , genericFunction= )

setGroupGeneric(name, def= , group=list(), valueClass=character(),
                knownMembers=list(), package= , where= )
}
\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}.  You
    can also supply this argument if you want the generic function to
    do something other than just dispatch methods (an advanced topic
    best left alone unless you are sure you want it).

    Note that \code{def} is \emph{not} the default method; use argument
    \code{useAsDefault} if you want to specify the default separately.
  }
  \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 vector or unevaluated
      expression.  The value returned by the generic function must
      have (or extend) this class, or one of the classes; otherwise,
      an error is generated.  See the
      details section for supplying an expression.
   }
  \item{package}{ The name of the package with which this function is
      associated.  Usually determined automatically (as the package
      containing the non-generic version if there is one, or else the
      package where this generic is to be saved).
      }
  \item{where}{ Where to store the resulting initial methods definition,
    and possibly the generic function; by
    default, stored into the top-level environment.
  }
  \item{signature}{
      Optionally, the signature of arguments in the function that can
      be used in methods for this generic.  By default, all arguments
      other than \code{...} can be used.  The signature argument can
      prohibit methods from using some arguments.  The argument, if
      provided, is a vector of formal argument names.
  }
  \item{genericFunction}{ The object to be used as a (nonstandard)
  generic function definition. Supply this explicitly \emph{only} if
  you know what you are doing!
  }
  \item{useAsDefault}{
    Override the usual choice of default argument (an existing
    non-generic function or no default if there is no such function).
    Argument \code{useAsDefault} can be supplied,
    either as a function to use for the default, or as a logical value.
    \code{FALSE} says not to have a default method at all, so that an
    error occurs if there is not an explicit or inherited method for a
    call.
    \code{TRUE} says to use the existing function as default,
    unconditionally (hardly ever needed as an explicit argument).
    See the section on details.
    }

  \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
  preparation for defining some methods for that function.

  The simplest and most common situation is that \code{name} is already
  an ordinary non-generic function, and you now want to turn this
  function into a generic.
  In this
  case 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.

  A second situation is that you want to create a new, generic
  function, unrelated to any existing function.  In this case, you
  need to supply a skeleton of the function definition, to define the
  arguments for the function.  The body of a generic function is
  usually a standard form, \code{standardGeneric(name)} where
  \code{name} is the quoted name of the generic function.

  When calling \code{setGeneric} in this form, you would normally
  supply the \code{def} argument as a function of this form.  If not
  told otherwise, \code{setGeneric} will try to find a non-generic
  version of the function to use as a default.  If you don't want this
  to happen, supply the argument \code{useAsDefault}.  That argument
  can be the function you want to be the default method.  You can supply
  the argument as \code{FALSE} to force no default (i.e., to cause an error if
  there is not direct or inherited method on call to the function).

  The same no-default situation occurs if there is no non-generic form of the function, and
  \code{useAsDefault=FALSE}.  Remember, though, you can
  also just assign the default you want (even one that generates an
  error) rather than relying on the prior situation.

  You cannot (and never need to) create an explicit generic for the
  primitive functions in the base library.  These are dispatched from
  C code for efficiency and are not to be redefined
  in any case.

  As mentioned, the body of a generic function usually does nothing
  except for dispatching methods by a call to \code{standardGeneric}.
  Under some circumstances you might just want to do some additional
  computation in the generic function itself.  As long as your
  function eventually calls \code{standardGeneric} that is permissible
  (though perhaps not a good idea, in that it makes the behavior of
  your function different from the usual S model).  If your explicit
  definition of the generic function
  does \emph{not} call \code{standardGeneric} you are in trouble,
  because none of the methods for the function will ever be
  dispatched.

      By default, the generic function can return any object.
   If \code{valueClass} is supplied, it should be a vector of
   class names; the value returned by a method is then required to
   satisfy \code{is(object, Class)} for one of the specified classes.
   An empty (i.e., zero length) vector of classes means anything is
   allowed.
   Note that more complicated requirements on the result can be
   specified explicitly, by defining a non-standard generic function.

  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.
}
\section{Generic Functions and Primitive Functions}{
  A number of the basic R functions are specially implemented as
  primitive functions, to be evaluated directly in the underlying C
  code rather than by evaluating an S language definition.  Primitive
  functions are eligible to have methods, but are handled differently
  by \code{setGeneric} and \code{setGroupGeneric}.  A call to
  \code{setGeneric} for a primitive function does not create a new
  definition of the function, and the call is allowed only to
  \dQuote{turn on} methods for that function.

  A call to \code{setGeneric} for a primitive causes the evaluator to
  look for methods for that generic; a call to \code{setGroupGeneric}
  for any of the groups that include primitives (\code{"Arith", "Logic",
  "Compare", "Ops", "Math", "Math2", "Summary",} and \code{"Complex"})
  does the same for each of the functions in that group.

  You usually only need to use either function if the methods are
  being defined only for the group generic.  Defining a method for a
  primitive function, say \code{"+"}, by a call to \code{setMethod}
  turns on method dispatch for that function.  But in R defining a
  method for the corresponding group generic, \code{"Arith"}, does not
  currently turn on method dispatch (for efficiency reasons).  If
  there are no non-group methods for the functions, you have two
  choices.

  You can turn on method dispatch for \emph{all} the functions in the
  group by calling \code{setGroupGeneric("Arith")}, or you can turn on
  method dispatch for only some of the functions by calling
  \code{setGeneric("+")}, etc.  Note that in either case you should
  give the name of the generic function as the only argument.
}
\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 R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\examples{
\dontshow{
setClass("track",
            representation(x="numeric", y="numeric"))
}

###   A non-standard generic function.  It insists that the methods
###   return a non-empty character vector (a stronger requirement than
###    valueClass = "character" in the call to setGeneric)

setGeneric("authorNames",
    function(text) {
      value <- standardGeneric("authorNames")
      if(!(is(value, "character") && any(nchar(value)>0)))
        stop("authorNames methods must return non-empty strings")
      value
      })

\dontshow{

setMethod("authorNames", "character", function(text)text)

stopifnot(identical(authorNames(c("me", "you")), c("me", "you")))

stopifnot(is(trySilent(authorNames(character())), "try-error")) # empty value

stopifnot(is(trySilent(authorNames(NULL)), "try-error")) # no default method

stopifnot(is(trySilent(setGeneric("[", function(x,...)standardGeneric("["))),
           "try-error")) # trying setGeneric on a primitive

}

## An example of group generic methods, using the class
## "track"; see the documentation of setClass for its definition

#define a method for the Arith group

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

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

# now arithmetic operators  will dispatch methods:

t1 <- new("track", x=1:10, y=sort(rnorm(10)))

t1 - 100

1/t1

\dontshow{
removeGeneric("authorNames")
removeClass("track")
removeMethods("Arith")
}
}
\seealso{
  \code{\link{Methods}} for a discussion of other functions to specify
  and manipulate the methods of generic functions.
}
\keyword{ programming }
\keyword{ methods }
\eof
\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= topenv(parent.frame()),
          valueClass = NULL, sealed = FALSE)

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; % FIXME: by default, the ... 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.) }
  \item{sealed}{ If \code{TRUE}, the method so defined cannot be
      redefined by another call to \code{setMethod} (although it can
      be removed and then re-assigned).  Note that this argument is an
      extension to the definition of \code{setMethod} in the reference.}
}
\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}}.  The effect of calling
  \code{setMethod} is to store \code{definition}  in a \code{MethodsList}
  object on database \code{where}.   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.  This is equivalent to the programmer calling
  \code{\link{setGeneric}} for the same function; it's better practice
  to do the call explicitly, since it shows that you intend to turn
  \code{f} into a generic function.

  Methods are stored in a hierarchical structure:  see
  \link{Methods} for how the objects are used to select a method, and
  \code{\link{MethodsList}} for functions that manipulate the objects.

 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.  Old-style (\dQuote{S3})
  classes can also be used, if you need compatibility with these, but
  you should definitely declare these classes by calling
  \code{\link{setOldClass}} if you want S3-style inheritance to work.


  While \code{f} can correspond to methods defined on several packages
  or environments, 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 methods list.  When \code{f}
  is called and a method is \dQuote{dispatched}, the evaluator matches the
  classes of the actual arguments to the signatures of the available
  methods.  When a match is found, the body of the corresponding
  method is evaluated (in R, the body is evaluated in the lexical
  context of the method), but without rematching the arguments to
  \code{f}.

  It is possible, however, to have some differences between the
  formal arguments to a method supplied to \code{setMethod} and those
  of the generic. Roughly, if the generic has \dots as one of its
  arguments, then the method may have extra formal arguments, which
  will be matched from the arguments matching \dots in the call to
  \code{f}.  (What actually happens is that a local function is
  created inside the method, with its formal arguments, and the method
  is re-defined to call that local function.)

  Method dispatch tries to match the class of the actual arguments in a
  call to the available methods collected for \code{f}.  Roughly, for
  each formal argument in turn, we look for the best match (the exact
  same class or the nearest element in the value of
  \code{\link{extends}} for that class) for which there is any
  possible method matching the remaining arguments.  See
  \link{Methods} for more details.

}
\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\examples{
\dontshow{  require(modreg)
  setClass("track",
    representation(x="numeric", y = "numeric"))
  setClass("trackCurve", representation("track",
    smooth = "numeric"))
  setClass("trackMultiCurve", representation(x="numeric", y="matrix", smooth="matrix"),
          prototype = list(x=numeric(), y=matrix(0,0,0), smooth=
  matrix(0,0,0)))
}

## 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, and of conforming method arguments
## (note the dotCurve argument in the method, which will be pulled out
## of ... in the generic.
setMethod("plot", c("trackCurve", "missing"),
function(x, y, dotCurve = FALSE, ...) {
  plot(as(x, "track"))
  if(length(slot(x, "smooth") > 0))
    lines(slot(x, "x"), slot(x, "smooth"),
         lty = if(dotCurve) 2 else 1)
  }
)
## the plot of tc1 alone has an added curve; other uses of tc1
## are treated as if it were a "track" object.
plot(tc1, dotCurve = TRUE)
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>")

\dontshow{

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)

## group methods

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


t1  - 100.

t1/2


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

## test the .Generic mechanism

setMethod("Compare", signature("track", "track"),
  function(e1,e2) {
  switch(.Generic,
   "==" = e1@y == e2@y,
  NA)
 })

#stopifnot(all(t1==t1))
#stopifnot(identical(t1<t1, NA))


## A test of nested calls to "[" with matrix-style arguments
## applied to data.frames (S3 methods)

setMethod("[", c("trackMultiCurve", "numeric", "numeric"), function(x, i, j, ..., drop) {
### FIXME:  a better version has only 1st arg in signature
### and uses callNextMethod, when this works with primitives.
    x@y <- x@y[i, j, drop=FALSE]
    x@x <- x@x[i]
    x
})


"testFunc" <-
function(cur) {
    sorted <- cur[order(cur[,1]),]
    sorted[ !is.na(sorted[,1]), ]
}

Nrow <- 1000 # at one time, values this large triggered a bug in gc/protect
## the loop here was a trigger for the bug
Niter <- 10
for(i in 1:Niter)  {
    yy <- matrix(rnorm(10*Nrow), 10, Nrow)
    tDF <- as.data.frame(yy)
    testFunc(tDF)
}


tMC <- new("trackMultiCurve", x=seq(length=Nrow), y = yy)
## not enough functions have methods for this class to use testFunc

stopifnot(identical(tMC[1:10, 1:10]@y, yy[1:10, 1:10]))


## verify we can remove methods and generic

removeMethods("-")
removeMethod("length", "track")
removeMethods("Arith")
removeMethods("Compare")

## repeat the test one more time on the primitives

length(ISOdate(1990, 12, 1)- ISOdate(1980, 12, 1))

## methods for %*%, which isn't done by the same C code as other ops

setClass("foo", representation(m="matrix"))
m1 <- matrix(1:12,3,4)
f1 = new("foo", m=m1)
f2 = new("foo", m=t(m1))

setMethod("\%*\%", c("foo", "foo"),
 function(x,y)callGeneric(x@m, y@m))

stopifnot(identical(f1\%*\%f2, m1\%*\% t(m1)))

removeMethods("\%*\%")

removeMethods("plot")

stopifnot(existsFunction("plot", FALSE) && !isGeneric("plot", 1))

## 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
removeGeneric("plotData")

stopifnot(!exists("plotData", 1))

##  Tests of method inheritance & multiple dispatch
setClass("A0", representation(a0 = "numeric"))

setClass("A1", representation("A0", a1 = "character"))

setClass("B0" ,representation(b0 = "numeric"))

setClass("B1", "B0")

setClass("B2", representation("B1", b2 = "logical"))

setClass("AB0", representation("A1", "B2", ab0 = "matrix"))

f1 <- function(x,  y)"ANY"

setGeneric("f1")

setMethod("f1", c("A0", "B1"), function(x, y)"A0 B1")
setMethod("f1", c("B1", "A0"), function(x, y)"B1 A0")

a0 <- new("A0")
a1 <- new("A1")
b0 <- new("B0")
b1 <- new("B1")
b2 <- new("B2")

deparseText <- function(expr)
    paste(deparse(expr), collapse = "\\  ")

mustEqual <- function(e1, e2){
    if(!identical(e1, e2))
        stop(paste("!identical(", deparseText(substitute(e1)),
                   ", ", deparseText(substitute(e2)), ")", sep=""))
}

mustEqual(f1(a0, b0), "ANY")
mustEqual(f1(a1,b0), "ANY")
mustEqual(f1(a1,b1), "A0 B1")
mustEqual(f1(b1,a1), "B1 A0")
mustEqual(f1(b1,b1), "ANY")

## remove classes:  order matters so as not to undefine earlier classes
for(.cl in c("AB0", "A1", "A0", "B2", "B1", "B0"))
    removeClass(.cl)

removeGeneric("f1")

## test of nonstandard generic definition

setGeneric("doubleAnything", function(x) {
  methodValue <- standardGeneric("doubleAnything")
  c(methodValue, methodValue)
})

setMethod("doubleAnything", "ANY", function(x)x)

setMethod("doubleAnything", "character",
function(x)paste("<",x,">",sep=""))

mustEqual(doubleAnything(1:10), c(1:10, 1:10))
mustEqual(doubleAnything("junk"), rep("<junk>",2))

removeGeneric("doubleAnything")


}
}

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

\keyword{programming}
\keyword{classes}
\keyword{classes}
\keyword{methods}
\eof
\name{setOldClass}
\alias{setOldClass}
\alias{.setOldIs}
\alias{POSIXct-class}
\alias{POSIXlt-class}
\alias{POSIXt-class}
\alias{aov-class}
\alias{maov-class}
\alias{anova-class}
\alias{anova.glm-class}
\alias{anova.glm.null-class}
\alias{data.frame-class}
\alias{density-class}
\alias{dump.frames-class}
\alias{factor-class}
\alias{formula-class}
\alias{glm-class}
\alias{glm.null-class}
\alias{hsearch-class}
\alias{integrate-class}
\alias{libraryIQR-class}
\alias{lm-class}
\alias{logLik-class}
\alias{mlm-class}
\alias{mtable-class}
\alias{mts-class}
\alias{ordered-class}
\alias{packageIQR-class}
\alias{packageInfo-class}
\alias{recordedplot-class}
\alias{rle-class}
\alias{socket-class}
\alias{summary.table-class}
\alias{oldClass-class}
\alias{.OldClassesList}
\alias{table-class}
\title{ Specify Names for Old-Style Classes }
\description{
  Register an old-style (a.k.a. `S3') class as a formally defined
  class. The \code{Classes} argument is the character vector used as
  the \code{class} attribute; in particular, if there is more than one string,  old-style
  class inheritance is mimiced.  Registering via \code{setOldClass}
  allows S3 classes to appear as slots or in method signatures.
}
\usage{
setOldClass(Classes, where, test = FALSE)
}
\arguments{
  \item{Classes}{ A character vector, giving the names for old-style
  classes, as they would appear on the right side of an assignment of
  the \code{class} attribute. }
    \item{where}{ Where to store the class definitions, the global or
        top-level environment by default.  (When either function is called in the source
        for a package, the class definitions will be included in the package's environment
        by default.)}

    \item{test}{flag, if \code{TRUE}, inheritance must be tested
        explicitly for each object, needed if the S3 class can have a
        different set of class strings, with the same first string.
        See the details below.}
}
\details{
  Each of the names will be defined as a virtual class, extending the
  remaining classes in \code{Classes}, and the class
  \code{oldClass}, which is the \dQuote{root} of all old-style classes.
  See \link{Methods} for the details of method dispatch and
  inheritance. See the section \bold{Register or Convert?} for
  comments on the alternative of defining \dQuote{real} S4 classes
  rather than using \code{setOldClass}.

  S3 classes have no formal definition, and some of them cannot be
  represented as an ordinary combination of S4 classes and
  superclasses.  It is still possible to register the classes as S4
  classes, but now the inheritance has to be verified for each
  object, and you must call \code{setOldClass} with argument
  \code{test=TRUE}.

  For example, ordered factors \emph{always} have the S3
  class \code{c("ordered", "factor")}.  This is proper behavior, and
  maps simply into two S4 classes, with \code{"ordered"} extending
  \code{"factor"}.

  But objects whose class attribute has \code{"POSIXt"} as the first
  string may have either (or neither) of \code{"POSIXct"} or
  \code{"POSIXlt"} as the second string.  This behavior can be mapped
  into S4 classes but now to evaluate \code{is(x, "POSIXlt")}, for
  example, requires checking the S3 class attribute on each object.
  Supplying the \code{test=TRUE} argument to \code{setOldClass} causes
  an explicit test to be included in the class definitions.  It's
  never wrong to have this test, but since it adds significant
  overhead to methods defined for the inherited classes, you should
  only supply this argument if it's known that object-specific tests
  are needed.

   The list \code{.OldClassesList} contains the old-style classes that
  are defined by the methods package.  Each element of the list is an
  old-style list, with multiple character strings if inheritance is
  included.
  Each element of the list was passed to \code{setOldClass} when
  creating the \pkg{methods} package; therefore, these classes can be used
  in \code{\link{setMethod}} calls, with the inheritance as implied by
  the list.
}

\section{Register or Convert?}{
A call to \section{setOldClass} creates formal classes corresponding
to S3 classes, allows these to be used as slots in other classes or in
a signature in \code{\link{setMethod}}, and mimics the S3 inheritance.

However, all such classes are created as virtual classes, meaning that
you cannot generally create new objects from the class by calling
\code{\link{new}}, and that objects cannot be coerced automatically
from or to these classes.  All these restrictions just reflect the
fact that nothing is inherently known about the \dQuote{structure} of
S3 classes, or whether in fact they define a consistent set of
attributes that can be mapped into slots in a formal class definition.

\emph{If} your class does in fact have a consistent structure, so that
every object from the class has the same structure, you may prefer to
take some extra time to write down a specific definition in a call to
\code{\link{setClass}} to convert the class to a fully functional
formal class.  On the other hand, if the actual contents of the class
vary from one object to another, you may have to redesign most of the
software using the class, in which case converting it may not be worth
the effort.  You should still register the class via
\code{setOldClass}, unless its class attribute is hopelessly unpredictable.

An S3 class has consistent structure if each object has the same set
of attributes, both the names and the classes of the attributes being
the same for every object in the class.  In practice, you can convert
classes that are slightly less well behaved.  If a few attributes
appear in some but not all objects, you can include these optional
attributes as slots that \emph{always} appear in the objects, if you
can supply a default value that is equivalent to the attribute being
missing.  Sometimes \code{NULL} can be that value: A slot (but not an
attribute) can have the value \code{NULL}.  If \code{version}, for
example, was an optional attribute, the old test
\code{is.null(attr(x,"version")} for a missing version attribute could
turn into \code{is.null(x@version)} for the formal class.

The requirement that slots have a fixed class can be satisfied
indirectly as well.  Slots \emph{can} be specified with class
\code{"ANY"}, allowing an arbitrary object.  However, this eliminates
an important benefit of formal class definitions; namely, automatic
validation of objects assigned to a slot.  If just a few different
classes are possible, consider using \code{\link{setClassUnion}} to
define valid objects for a slot.
}

\seealso{
  \code{\link{setClass}}, \code{\link{setMethod}}
}

\examples{
setOldClass(c("mlm", "lm"))
setGeneric("dfResidual", function(model)standardGeneric("dfResidual"))
setMethod("dfResidual", "lm", function(model)model$df.residual)

## dfResidual will work on mlm objects as well as lm objects
myData <- data.frame(time = 1:10, y = (1:10)^.5)
myLm <- lm(cbind(y, y^3)  ~ time, myData)

\dontshow{
stopifnot(identical(dfResidual(myLm), myLm$df.residual))}

rm(myData, myLm)
removeGeneric("dfResidual")
}
\keyword{ programming }
\keyword{ methods }
\eof
\name{makeClassRepresentation}
\alias{makeClassRepresentation}
\title{Create a Class Definition}
\description{
  Constructs a \code{\link{classRepresentation-class}} object to
  describe a particular class.  Mostly a utility function, but you can
  call it to create a class definition without assigning it, as
  \code{\link{setClass}} would do.
}
\usage{
makeClassRepresentation(name, slots=list(), superClasses=character(),
                        prototype=NULL, package, validity, access,
                        version, sealed, virtual=NA, where)
}
\arguments{
  \item{name}{character string name for the class}
  \item{slots}{named list of slot classes as would be supplied to
    \code{setClass}, but \emph{without} the unnamed arguments for
    superClasses if any.}
  \item{superClasses}{what classes does this class extend}
  \item{prototype}{an object providing the default data for the class,
    e.g, the result of a call to \code{\link{prototype}}.}
  \item{package}{The character string name for the package in which
    the class will be stored; see \code{\link{getPackageName}}.}
  \item{validity}{Optional validity method.  See
    \code{\link{validObject}}, and the discussion of validity methods in
    the reference.}
  \item{access}{Access information.  Not currently used.}
  \item{version}{Optional version key for version control.  Currently
    generated, but not used.}
  \item{sealed}{Is the class sealed? See \code{\link{setClass}}.}
  \item{virtual}{Is this known to be a virtual class?}

  \item{where}{The environment from which to look for class
      definitions needed (e.g., for slots or superclasses). See the
      discussion of this argument under \link{GenericFunctions}.}
}
\references{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\seealso{
  \code{\link{setClass}}
}
\keyword{programming}
\keyword{classes}
\eof
\name{show}
\alias{show}
\alias{show-methods}
\alias{show,ANY-method}
\alias{show,traceable-method}
\alias{show,ObjectsWithPackage-method}
\alias{show,MethodDefinition-method}
\alias{show,MethodWithNext-method}
\alias{show,genericFunction-method}
\alias{show,classRepresentation-method}
\title{Show an Object}
\description{
  Display the object, by printing, plotting or whatever suits its
  class.  This function exists to be specialized by methods.  The
  default method calls \code{\link{showDefault}}.

  Formal methods for \code{show} will
  usually be invoked for automatic printing (see the details).
}
\usage{
show(object)
}
\arguments{
  \item{object}{Any R object}
   }
}
\value{
  \code{show} returns an invisible \code{NULL}.
}
\details{
  The \pkg{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}
\eof
\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 = topenv(parent.frame()), classes = NULL,
            includeDefs = FALSE, inherited = TRUE, printTo = stdout())
}
\arguments{
  \item{f}{one or more function names.  If omitted, all functions
    will be examined. }
  \item{where}{If \code{where} is supplied, the methods definition from
    that position will be used; otherwise, the current definition is
    used (which will include inherited methods that have arisen so far
    in the session). If \code{f} is omitted, \code{where} controls
    where to look for generic functions.}
  \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. Note that an inherited method
    will not usually appear until it has been used in this session.
    See \code{\link{selectMethod}} if you want to know what method is
    dispatched for particular classes of arguments.}
  \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 R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\seealso{
  \code{\link{setMethod}}, and \code{\link{GenericFunctions}}
  for other tools involving methods;
  \code{\link{selectMethod}} will show you the method dispatched for a
  particular function and signature of classes for the arguments.
}
\examples{
\dontshow{
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}
\eof
\name{signature-class}
\docType{class}
\alias{signature-class}
\title{Class "signature" For Method Definitions}
\description{This class represents the mapping of some of the formal
  arguments of a function onto the names of some classes.  It is used as
  one of two slots in the \code{\link{MethodDefinition-class}}.
}
\section{Objects from the Class}{
  Objects can be created by calls of the form \code{new("signature",
    functionDef, ...)}.  The \code{functionDef} argument, if it is
  supplied as a function object, defines the formal names.  The other
  arguments define the classes.
}
\section{Slots}{
  \describe{
    \item{\code{.Data}:}{Object of class \code{"character"} the classes. }
    \item{\code{names}:}{Object of class \code{"character"} the
      corresponding argument names. }
  }
}
\section{Extends}{
Class \code{"character"}, from data part.
Class \code{"vector"}, by class "character".
}
\section{Methods}{
  \describe{
    \item{initialize}{\code{signature(object = "signature")}: see the
      discussion of objects from the class, above. }
  }
}
\seealso{
 \code{\link{MethodDefinition-class}} for the use of this class }

\keyword{classes}
\eof
\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, check = TRUE) <- 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.}
  \item{check}{If \code{TRUE}, check the assigned value for validity
    as the value of this slot.  You should never set this to
    \code{FALSE} in normal use, since the result can create invalid objects.
    }
    
  }
\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{
  The R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page 
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\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}
\eof
\name{substituteDirect}
\alias{substituteDirect}
\title{SubstituteDirect}
\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}}.
}
\usage{
substituteDirect(object, frame, cleanFunction=TRUE)
}
\keyword{internal}
\eof
\name{validObject}
\alias{validObject}
\alias{setValidity}
\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 function \code{setValidity}  sets
  the validity method of a class (but more normally, this method will
  be supplied as the \code{validity} argument to \code{\link{setClass}}).  The method should be a function of one
  object that returns \code{TRUE} or a description of the non-validity.
}
\usage{
validObject(object, test)

 setValidity(Class, method, where = topenv(parent.frame()) )
}
\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{Class}{the name or class definition 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.
   }
   \item{where}{the modified class definition will be stored in this
     environment.}

   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 \dQuote{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 \dQuote{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 R package \pkg{methods} implements, with a few exceptions, the
  programming interface for classes and methods in the book
  \emph{Programming with Data} (John M. Chambers, Springer, 1998), in
  particular sections 1.6, 2.7, 2.8, and chapters 7 and 8.

  While the programming interface for the \pkg{methods} package follows
  the reference, the R software is an original implementation, so
  details in the reference that reflect the S4 implementation may appear
  differently in R.  Also, there are extensions to the programming
  interface developed more recently than the reference.  For a
  discussion of details and ongoing development, see the web page
  \url{http://developer.r-project.org/methodsPackage.html} and the
  pointers from that page.
}
\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
\dontrun{try(validObject(t1))}
\dontshow{stopifnot(is(try(validObject(t1)), "try-error"))}
}

\keyword{programming}
\keyword{classes}
\eof
\name{.BasicFunsList}
\alias{.BasicFunsList}
\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 packages, 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 }
\eof
