\section[Brief Guide to CLOS]{Brief Guide to CLOS\footnote{Written by   Jeff Dalton, and modified by  Bruno Haible}}

\begin{description}
\item[Notation:] {\tt thing*}
means zero or more occurrences of {\tt  thing}; {\tt thing+} means one
or more.   Curly brackets \verb+{+ and  \verb+}+ are used for grouping, as
in \verb-{a b}+-, which means {\tt a b}, {\tt a b a b}, {\tt a b a b a
b}, etc.

 \item[CLISP  specific note:]    Before using   CLOS,   you  need   to:\\
\verb+(use-package "CLOS")+
\end{description}

\subsection{Defining classes}

You define a class with {\tt defclass}:

\begin{verbatim}
   (defclass class-name (superclass-name*)
     (slot-description*)
     class-option*
   )
\end{verbatim}

For simple things, forget about class options.

A slot-description has the form \verb+(slot-name slot-option*)+, where each
option is a keyword followed by a name, expression, or whatever.  The
most useful slot options are

\begin{verbatim}
   :accessor function-name
   :initform expression
   :initarg symbol
\end{verbatim}

(Initargs are usually keywords.)

{\tt defclass} is similar to {\tt defstruct}.  The syntax is a bit different, and
you have more control over what things are called.  For instance,
consider the {\tt defstruct}:

\begin{verbatim}
   (defstruct person
     (name 'bill)
     (age 10)
   )
\end{verbatim}

{\tt defstruct} would  automatically define slots  with expressions to
compute    default  initial  values,   access-functions    like   {\tt
person-name} to get and set slot values, and  a {\tt make-person} that
took keyword initialization arguments (initargs) as in

\begin{verbatim}
   (make-person :name 'george :age 12)
\end{verbatim}

A {\tt defclass} that provided similar access functions, etc, would be:

\begin{verbatim}
   (defclass person ()
     ((name :accessor person-name
            :initform 'bill
            :initarg :name
      )
      (age :accessor person-age
           :initform 10
           :initarg :age
   ) ))
\end{verbatim}

Note that {\tt defclass} lets you control what things are called.  For
instance, you don't have to call  the accessor {\tt person-name}.  You
could call it {\tt name}.

In general, you should pick names that make sense for a group of
related classes rather than rigidly following the {\tt defstruct}
conventions.

You do not have to provide all options for every slot.
Maybe you don't want it to be possible to initialize a slot
when calling {\tt make-instance} (for which see below).  In that case,
don't provide an {\tt :initarg}.  Or maybe there isn't a meaningful
default value.  (Perhaps the meaningful values will always be
specified by a subclass.)  In that case, no {\tt :initform}.

Note that classes are objects.  To get the class object from its name,
use \verb+(find-class name)+.  Ordinarily, you won't need to do this.


\subsection{Instances}

You can make an  instance of a class  with {\tt  make-instance}.  It's
similar to the {\tt make-x}  functions defined by {\tt defstruct}  but
lets you pass the class to instantiate as an argument:

\begin{verbatim}
   (make-instance class {initarg value}*)
\end{verbatim}

Instead of the class object itself, you can use its name.
For example:

\begin{verbatim}
   (make-instance 'person :age 100)
\end{verbatim}

This person object would have age 100 and name {\tt bill}, the default.

It's often a good idea to define your own constructor functions,
rather than call {\tt make-instance} directly, because you can hide
implementation details and don't have to use keyword parameters
for everything.  For instance, you might want to define

\begin{verbatim}
  (defun make-person (name age)
    (make-instance 'person :name name :age age)
  )
\end{verbatim}

 \noindent if you  wanted the name and age  to be required, positional
parameters, rather than keyword parameters.

The accessor functions can be used to get and set slot values:

\begin{verbatim}
> (setq p1 (make-instance 'person :name 'jill :age 100))
#<person @ #x7bf826> 
> (person-name p1)
jill 
> (person-age p1)
100 
> (setf (person-age p1) 101)
101 
> (person-age p1)
101 
\end{verbatim}

Note that when you use {\tt defclass}, the instances are printed using
the \verb+#<...>+ notation, rather  than as \verb+#s(person :name jill
:age  100)+.  But  you  can change the way   instances are printed  by
defining methods on the generic function {\tt print-object}.

Slots can also  be  accessed by name using\\
\verb+(slot-value instance slot-name)+:

\begin{verbatim}
> (slot-value p1 'name)
jill 
> (setf (slot-value p1 'name) 'jillian)
jillian 
> (person-name p1)
jillian 
\end{verbatim}

You can find out various things about an instance by calling
{\tt describe}:

\begin{verbatim}
> (describe p1)
#<person @ #x7bf826> is an instance of class 
     #<clos:standard-class person @ #x7ad8ae>:
The following slots have :INSTANCE allocation:
age     101
name    jillian
\end{verbatim}


\subsection{Inheritance of slot options}

The class above had no superclass.  That's why there was a \verb+()+ after
\verb+defclass person+.  Actually, this means it has one superclass: the
class {\tt standard-object}.

When there are superclasses, a subclass can specify a slot that has
already been specified for a superclass.  When this happens, the
information in slot options has to be combined.  For the slot options
listed above, either the option in the subclass overrides the one in
the superclass or there is a union:

\begin{tabbing}
\tt :accessor  \=\tt --  \=union\\
\tt :initarg   \>\tt --  \>union\\
\tt :initform  \>\tt --  \>overrides
\end{tabbing}


This is what you should expect.  The subclass can {\it change} the
default initial value by overriding the {\tt :initform}, and can add
to the initargs and accessors.

However, the {\it union} for accessor is just a consequence of how
generic functions work.  If they can apply to instances of a
class {\tt C}, they can also apply to instances of subclasses of {\tt C}.

(Accessor functions are generic.  This may become clearer
once generic functions are discussed, below.)

Here are some subclasses:

\begin{verbatim}
> (defclass teacher (person)
       ((subject :accessor teacher-subject
                 :initarg :subject
     ) ))
#<clos:standard-class teacher @ #x7cf796> 
> (defclass maths-teacher (teacher)
       ((subject :initform "Mathematics"))
     )
#<clos:standard-class maths-teacher @ #x7d94be> 
> (setq p2 (make-instance 'maths-teacher
                 :name 'john
                 :age 34
     )        )
#<maths-teacher @ #x7dcc66> 
> (describe p2)
#<maths-teacher @ #x7dcc66> is an instance of
     class #<clos:standard-class maths-teacher @ #x7d94be>:
 The following slots have :INSTANCE allocation:
 age        34
 name       john
 subject    "Mathematics"
\end{verbatim}


Note that classes print like\\
\verb+#<clos:standard-class maths-teacher @ #x7d94be>+.
The \verb+#<...>+ notation usually has the form:

\medskip
\noindent\verb+   #<class-of-the-object ... +{\it more information}\verb+ ...>+

\medskip


So an instance of {\tt maths-teacher} prints as \verb+#<MATHS-TEACHER ...>+.
The notation for the classes above indicates that they are
instances of {\tt standard-class}. {\tt  defclass} defines standard classes.
{\tt defstruct} defines structure classes.


\subsection{Multiple inheritance}

A class can have more than one superclass.  With single inheritance
(one superclass), it's easy to order the superclasses from most to
least specific.  This is the rule:

\begin{description}
\item[\rm Rule 1:] Each class is more specific than its superclasses.

In multiple inheritance this is harder.  Suppose we have

\begin{verbatim}
  (defclass a (b c) ...)
\end{verbatim}

Class {\tt a} is more specific than {\tt b} or  {\tt c} (for instances
of {\tt a}), but  what if something (an {\tt  :initform}, or a method)
is specified by {\tt b} and {\tt c}?   Which overrides the other?  The
rule in CLOS is that the superclasses listed earlier are more specific
than those listed later.  So:

\item[\rm Rule 2:] For a given class, superclasses listed earlier are more
        specific than those listed later.
\end{description}

These rules are used to compute a linear order for a class and all its
superclasses, from most specific to least specific.  This order is the
{\it class precedence list} of the class.

The two rules are not always enough to determine a unique order,
however, so CLOS has an algorithm for breaking ties.  This ensures
that all implementations always produce the same order, but it's
usually considered a bad idea for programmers to rely on exactly
what the order is.  If the order for some superclasses is important,
it can be expressed directly in the class definition.


\subsection{Generic functions and methods}

Generic function in CLOS are the closest thing to {\it messages}.
Instead of writing

\begin{verbatim}
  (send instance operation-name arg*)
\end{verbatim}

you write

\begin{verbatim}
  (operation-name instance arg*)
\end{verbatim}

The operations/messages are generic functions ---functions whose
behavior can be defined for instances of particular classes by
defining methods.

\verb+(defgeneric function-name lambda-list)+ can be used to define a generic
function.   You don't have to call  {\tt defgeneric}, however, because
{\tt  defmethod} automatically defines the  generic function if it has
not been defined already.  On the  other hand, it's  often a good idea
to use {\tt defgeneric} as a declaration  that an operation exists and
has certain parameters.

Anyway, all of the interesting things happen in methods.  A method is
defined by:

\begin{verbatim}
   (defmethod generic-function-name specialized-lambda-list
     form*
   )
\end{verbatim}

This may look fairly cryptic, but compare it to {\tt defun} described in
a similar way:

\begin{verbatim}
   (defun function-name lambda-list form*)
\end{verbatim}

A {\tt lambda-list}  is just a list  of formal parameters, plus things
 like \verb+&optional+  or \verb+&rest+\footnote{I won't  say anything
 about {\tt \&optional}, {\tt\&rest}, or {\tt\&key} in methods.  The
 rules are  in {\it Common LISP:  the  Language}, if you  want to know
 them.}.    It's because  of   such complications  that   we  say {\tt
 lambda-list} instead   of \verb+(parameter*)+  when   describing  the
 syntax.

So a normal function has a {\tt lambda-list} like \verb+(var1 var2 ...)+.
A method has one in which each parameter can be {\it specialized}
to a particular class.  So it looks like:

\begin{verbatim}
  ((var1 class1) (var2 class2) ...)
\end{verbatim}

The specializer is optional.  Omitting it means that the method
can apply to instances of any class, including classes that were
not defined by {\tt defclass}.  For example:

\begin{verbatim}
   (defmethod change-subject ((teach teacher) new-subject)
     (setf (teacher-subject teach) new-subject)
   )
\end{verbatim}

Here the {\tt new-subject} could be any object.  If you want to restrict
it, you might do something like:

\begin{verbatim}
   (defmethod change-subject ((teach teacher) 
     (new-subject string))
     (setf (teacher-subject teach) new-subject)
   )
\end{verbatim}

Or you could define classes of subjects.

Methods in {\it classical} object-oriented programming specialize
only one parameter.  In CLOS, you can specialize more than one.
If you do, the method is sometimes called a multi-method.

A method defined for a class {\tt c} overrides any method defined
for a superclass of {\tt c}.  The method for {\tt c} is {\it more specific}
than the method for the superclass, because {\tt c} is more specific
that the classes it inherits from (eg, dog is more specific
than animal).

For multi-methods, the determination of which method is more
specific involves more than one parameter.  The parameters
are considered from left to right.

\begin{verbatim}
(defmethod test ((x number) (y number))
  '(num num)
)

(defmethod test ((i integer) (y number))
  '(int num)
)

(defmethod test ((x number) (j integer))
  '(num int)
)
\end{verbatim}

\begin{tabbing}
\verb+(test 1/2 1/2)  +\=$\Rightarrow$\ \ \=\kill
\verb+(test 1 1)+   \> $\Rightarrow$\>\tt  (int num), not (num int)\\
\verb+(test 1 1/2)+  \> $\Rightarrow$\>\tt   (int num) \\
\verb+(test 1/2 1)+  \> $\Rightarrow$\>\tt   (num int) \\
\verb+(test 1/2 1/2)+\> $\Rightarrow$\>\tt   (num num) 
\end{tabbing}



\subsection{Method combination}

When more than one class defines a method for a generic function, and
more than one method is applicable to a given set of arguments, the
applicable methods are combined into a single {\it effective method}.
Each individual method definition is then only part of the definition
of the effective method.

One kind of method combination is always supported by CLOS.  It is
called standard method combination.  It is also possible to define
new kinds of method combination.  Standard method combination
involves four kinds of methods:

\begin{itemize}

\item Primary methods form the main body of the effective method.
    Only the most specific primary method is called, but it can
    call the next most specific primary method by calling

\begin{verbatim}
      (call-next-method)
\end{verbatim}

\item {\tt :before} methods are all called before the primary method, with
    the most specific {\tt :before} method called first.

\item {\tt :after} methods are all called after the primary method, with
    the most specific {\tt :after} method called last.

\item {\tt :around} methods run before the other methods.  As with
    primary methods, only the most specific is called and the rest can
    be invoked  by  {\tt call-next-method}.   When the least  specific
    {\tt :around}  method calls \\{\tt  call-next-method}, what it calls
    is  the combination of   {\tt :before}, :{\tt after},  and primary
    methods.
\end{itemize}

{\tt :before},  {\tt :after}, and {\tt  :around} methods are indicated
by  putting  the corresponding  keyword as a  qualifier in  the method
definition.  {\tt :before} and {\tt :after} methods are the easiest to
use, and a simple example will show how they work:

\begin{verbatim}
(defclass food () ())

(defmethod cook :before ((f food))
  (print "A food is about to be cooked.")
)

(defmethod cook :after ((f food))
  (print "A food has been cooked.")
)

(defclass pie (food)
  ((filling :accessor pie-filling :initarg :filling 
    :initform 'apple))
)

(defmethod cook ((p pie))
  (print "Cooking a pie")
  (setf (pie-filling p) (list 'cooked (pie-filling p)))
)

(defmethod cook :before ((p pie))
  (print "A pie is about to be cooked.")
)

(defmethod cook :after ((p pie))
  (print "A pie has been cooked.")
)

(setq pie-1 (make-instance 'pie :filling 'apple))
\end{verbatim}

And now:

\begin{verbatim}
> (cook pie-1)
"A pie is about to be cooked." 
"A food is about to be cooked." 
"Cooking a pie" 
"A food has been cooked." 
"A pie has been cooked." 
(cooked apple)
\end{verbatim}


\subsection{Quick reference}

\begin{description}
\item[Notation:]
Square brackets  ({\tt[} and  {\tt]}) indicate optional   elements.  A
vertical bar (\verb+|+) indicates an alternative.  \verb+thing*+ means
zero or  more  occurrence of thing, \verb-thing+-  means   one or more
occurrence.
\verb+{+ and \verb+}+ are used for grouping.
\end{description}

\begin{description}
\item[\rm Defining a class:]\leavevmode

\begin{verbatim}
   (defclass class-name (superclass-name*)
     (slot-description*)
   )
\end{verbatim}


\item[\rm Slot descriptions:]\leavevmode

\begin{verbatim}
   (slot-name slot-option*)

   :accessor function-name
   :initform expression
   :initarg keyword-symbol
\end{verbatim}

\item[\rm Making instances:]\leavevmode

\begin{verbatim}
   (make-instance class {initarg value}*)
\end{verbatim}

\item[\rm Method definitions:]\leavevmode

\begin{verbatim}
   (defmethod generic-function-name [qualifier] 
     specialized-lambda-list
     form*
   )
\end{verbatim}

where

\begin{description}
\item[\tt generic-function-name] is a symbol;

 \item[\tt  qualifier] is {\tt :before},  {\tt :after}, {\tt :around},
or else omitted;

 \item[\tt   specialized-lambda-list] is \\
\verb+( {variable | (variable class-name)}* )+
\end{description}

\item[\rm Some functions:]\leavevmode

\begin{verbatim}
   (describe instance)
   (describe class)
\end{verbatim}

\bigskip

\noindent\verb+   (find-class class-name) +$\Rightarrow$ class

\bigskip

\noindent\verb+   (class-name class) +$\Rightarrow$ symbol

\bigskip

\noindent\verb+   (class-precedence-list class) +$\Rightarrow$ list of classes

   This is called \verb+(clos::class-precedence-list class)+ in CLISP.

\bigskip
\noindent\verb+   (class-direct-superclasses class) +$\Rightarrow$ list of classes

   This is called \verb+(clos::class-direct-superclasses class)+ in CLISP.

\bigskip

\noindent\verb+   (class-direct-subclasses class) +$\Rightarrow$ list of classes

   This isn't available in CLISP.

\end{description}
