Clean up doc on class redefinition and instance class changing
[bpt/guile.git] / doc / ref / goops.texi
CommitLineData
d99832a2
NJ
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
3@c Copyright (C) 2008, 2009
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
a0e07ba4
NJ
7@macro goops
8GOOPS
9@end macro
10
11@macro guile
12Guile
13@end macro
14
eb12b401
NJ
15@node GOOPS
16@chapter GOOPS
a0e07ba4 17
a0e07ba4
NJ
18@goops{} is the object oriented extension to @guile{}. Its
19implementation is derived from @w{STk-3.99.3} by Erick Gallesio and
56664c08 20version 1.3 of Gregor Kiczales' @cite{Tiny-Clos}. It is very close in
b997e7f5
NJ
21spirit to CLOS, the Common Lisp Object System, but is adapted for the
22Scheme language.
23
24@goops{} is a full object oriented system, with classes, objects,
25multiple inheritance, and generic functions with multi-method
26dispatch. Furthermore its implementation relies on a meta object
27protocol --- which means that @goops{}'s core operations are themselves
28defined as methods on relevant classes, and can be customised by
29overriding or redefining those methods.
a0e07ba4 30
f60a8353
NJ
31To start using @goops{} you first need to import the @code{(oop goops)}
32module. You can do this at the Guile REPL by evaluating:
33
34@lisp
35(use-modules (oop goops))
36@end lisp
37@findex (oop goops)
38
769be03f 39@menu
b65ff721 40* Copyright Notice::
f60a8353
NJ
41* Class Definition::
42* Instance Creation::
43* Slot Options::
44* Slot Description Example::
45* Methods and Generic Functions::
46* Inheritance::
62d7cba3 47* Introspection::
12fe9fcf 48* GOOPS Error Handling::
2cb8cf04 49* GOOPS Object Miscellany::
0b452f2c 50* The Metaobject Protocol::
c34d74ff
NJ
51* Redefining a Class::
52* Changing the Class of an Instance::
769be03f
NJ
53@end menu
54
b65ff721
NJ
55@node Copyright Notice
56@section Copyright Notice
57
58The material in this chapter is partly derived from the STk Reference
59Manual written by Erick Gallesio, whose copyright notice is as follows.
60
61Copyright © 1993-1999 Erick Gallesio - I3S-CNRS/ESSI <eg@@unice.fr>
62Permission to use, copy, modify, distribute,and license this
63software and its documentation for any purpose is hereby granted,
64provided that existing copyright notices are retained in all
65copies and that this notice is included verbatim in any
66distributions. No written agreement, license, or royalty fee is
67required for any of the authorized uses.
68This software is provided ``AS IS'' without express or implied
69warranty.
70
71The material has been adapted for use in Guile, with the author's
72permission.
73
74
f60a8353
NJ
75@node Class Definition
76@section Class Definition
e946b0b9 77
f60a8353 78A new class is defined with the @code{define-class} syntax:
8445eb1d 79
f60a8353
NJ
80@findex define-class
81@cindex class
82@lisp
83(define-class @var{class} (@var{superclass} @dots{})
84 @var{slot-description} @dots{}
85 @var{class-option} @dots{})
86@end lisp
a0e07ba4 87
f60a8353
NJ
88@var{class} is the class being defined. The list of @var{superclass}es
89specifies which existing classes, if any, to inherit slots and
90properties from. @dfn{Slots} hold per-instance@footnote{Usually --- but
91see also the @code{#:allocation} slot option.} data, for instances of
92that class --- like ``fields'' or ``member variables'' in other object
93oriented systems. Each @var{slot-description} gives the name of a slot
94and optionally some ``properties'' of this slot; for example its initial
95value, the name of a function which will access its value, and so on.
b0fc1b9f
NJ
96Class options, slot descriptions and inheritance are discussed more
97below.
f60a8353 98@cindex slot
a0e07ba4 99
a9bf12c2
NJ
100@deffn syntax define-class name (super @dots{}) slot-definition @dots{} . options
101Define a class called @var{name} that inherits from @var{super}s, with
102direct slots defined by @var{slot-definition}s and class options
103@var{options}. The newly created class is bound to the variable name
104@var{name} in the current environment.
a0e07ba4 105
a9bf12c2
NJ
106Each @var{slot-definition} is either a symbol that names the slot or a
107list,
a0e07ba4 108
a9bf12c2
NJ
109@example
110(@var{slot-name-symbol} . @var{slot-options})
111@end example
a0e07ba4 112
a9bf12c2
NJ
113where @var{slot-name-symbol} is a symbol and @var{slot-options} is a
114list with an even number of elements. The even-numbered elements of
115@var{slot-options} (counting from zero) are slot option keywords; the
116odd-numbered elements are the corresponding values for those keywords.
a0e07ba4 117
a9bf12c2
NJ
118@var{options} is a similarly structured list containing class option
119keywords and corresponding values.
120@end deffn
a0e07ba4 121
f60a8353
NJ
122As an example, let us define a type for representing a complex number
123in terms of two real numbers.@footnote{Of course Guile already
124provides complex numbers, and @code{<complex>} is in fact a predefined
125class in GOOPS; but the definition here is still useful as an
126example.} This can be done with the following class definition:
a0e07ba4 127
f60a8353
NJ
128@lisp
129(define-class <my-complex> (<number>)
130 r i)
131@end lisp
a0e07ba4 132
f60a8353
NJ
133This binds the variable @code{<my-complex>} to a new class whose
134instances will contain two slots. These slots are called @code{r} and
135@code{i} and will hold the real and imaginary parts of a complex
136number. Note that this class inherits from @code{<number>}, which is a
137predefined class.@footnote{@code{<number>} is the direct superclass of
138the predefined class @code{<complex>}; @code{<complex>} is the
139superclass of @code{<real>}, and @code{<real>} is the superclass of
140@code{<integer>}.}
a0e07ba4 141
b0fc1b9f
NJ
142Slot options are described in the next section. The possible class
143options are as follows.
144
145@deffn {class option} #:metaclass metaclass
146The @code{#:metaclass} class option specifies the metaclass of the class
147being defined. @var{metaclass} must be a class that inherits from
148@code{<class>}. For the use of metaclasses, see @ref{Metaobjects and
149the Metaobject Protocol} and @ref{Metaclasses}.
150
151If the @code{#:metaclass} option is absent, GOOPS reuses or constructs a
152metaclass for the new class by calling @code{ensure-metaclass}
153(@pxref{Class Definition Protocol,, ensure-metaclass}).
154@end deffn
155
156@deffn {class option} #:name name
157The @code{#:name} class option specifies the new class's name. This
158name is used to identify the class whenever related objects - the class
159itself, its instances and its subclasses - are printed.
160
161If the @code{#:name} option is absent, GOOPS uses the first argument to
162@code{define-class} as the class name.
163@end deffn
a0e07ba4 164
a0e07ba4 165
f60a8353
NJ
166@node Instance Creation
167@section Instance Creation and Slot Access
a0e07ba4 168
f60a8353
NJ
169An instance (or object) of a defined class can be created with
170@code{make}. @code{make} takes one mandatory parameter, which is the
171class of the instance to create, and a list of optional arguments that
172will be used to initialize the slots of the new instance. For instance
173the following form
174
175@findex make
176@cindex instance
177@lisp
178(define c (make <my-complex>))
179@end lisp
180
181@noindent
182creates a new @code{<my-complex>} object and binds it to the Scheme
183variable @code{c}.
184
185@deffn generic make
186@deffnx method make (class <class>) . initargs
187Create and return a new instance of class @var{class}, initialized using
188@var{initargs}.
189
190In theory, @var{initargs} can have any structure that is understood by
191whatever methods get applied when the @code{initialize} generic function
192is applied to the newly allocated instance.
193
194In practice, specialized @code{initialize} methods would normally call
195@code{(next-method)}, and so eventually the standard GOOPS
196@code{initialize} methods are applied. These methods expect
197@var{initargs} to be a list with an even number of elements, where
198even-numbered elements (counting from zero) are keywords and
199odd-numbered elements are the corresponding values.
200
201GOOPS processes initialization argument keywords automatically for slots
202whose definition includes the @code{#:init-keyword} option (@pxref{Slot
203Options,, init-keyword}). Other keyword value pairs can only be
204processed by an @code{initialize} method that is specialized for the new
205instance's class. Any unprocessed keyword value pairs are ignored.
206@end deffn
207
208@deffn generic make-instance
209@deffnx method make-instance (class <class>) . initargs
210@code{make-instance} is an alias for @code{make}.
211@end deffn
212
213The slots of the new complex number can be accessed using
214@code{slot-ref} and @code{slot-set!}. @code{slot-set!} sets the value
215of an object slot and @code{slot-ref} retrieves it.
216
217@findex slot-set!
218@findex slot-ref
219@lisp
220@group
221(slot-set! c 'r 10)
222(slot-set! c 'i 3)
223(slot-ref c 'r) @result{} 10
224(slot-ref c 'i) @result{} 3
225@end group
226@end lisp
227
228The @code{(oop goops describe)} module provides a @code{describe}
229function that is useful for seeing all the slots of an object; it prints
230the slots and their values to standard output.
231
232@lisp
233(describe c)
234@print{}
235#<<my-complex> 401d8638> is an instance of class <my-complex>
236Slots are:
237 r = 10
238 i = 3
239@end lisp
a0e07ba4 240
a0e07ba4
NJ
241
242@node Slot Options
f60a8353
NJ
243@section Slot Options
244
245When specifying a slot (in a @code{(define-class @dots{})} form),
246various options can be specified in addition to the slot's name. Each
247option is specified by a keyword. The list of possible keywords is
248as follows.
a0e07ba4 249
a0e07ba4
NJ
250@deffn {slot option} #:init-value init-value
251@deffnx {slot option} #:init-form init-form
252@deffnx {slot option} #:init-thunk init-thunk
253@deffnx {slot option} #:init-keyword init-keyword
254These options provide various ways to specify how to initialize the
f60a8353
NJ
255slot's value at instance creation time.
256@cindex default slot value
257
258@var{init-value} specifies a fixed initial slot value (shared across all
259new instances of the class).
260
261@var{init-thunk} specifies a thunk that will provide a default value for
262the slot. The thunk is called when a new instance is created and should
263return the desired initial slot value.
264
265@var{init-form} specifies a form that, when evaluated, will return
266an initial value for the slot. The form is evaluated each time that
267an instance of the class is created, in the lexical environment of the
268containing @code{define-class} expression.
269
270@var{init-keyword} specifies a keyword that can be used to pass an
271initial slot value to @code{make} when creating a new instance.
5695ccd4
NJ
272
273Note that, since an @code{init-value} value is shared across all
274instances of a class, you should only use it when the initial value is
275an immutable value, like a constant. If you want to initialize a slot
276with a fresh, independently mutable value, you should use
277@code{init-thunk} or @code{init-form} instead. Consider the following
278example.
279
280@example
281(define-class <chbouib> ()
282 (hashtab #:init-value (make-hash-table)))
283@end example
284
285@noindent
286Here only one hash table is created and all instances of
287@code{<chbouib>} have their @code{hashtab} slot refer to it. In order
288to have each instance of @code{<chbouib>} refer to a new hash table, you
289should instead write:
290
291@example
292(define-class <chbouib> ()
293 (hashtab #:init-thunk make-hash-table))
294@end example
295
296@noindent
297or:
298
299@example
300(define-class <chbouib> ()
301 (hashtab #:init-form (make-hash-table)))
302@end example
a0e07ba4
NJ
303
304If more than one of these options is specified for the same slot, the
305order of precedence, highest first is
306
307@itemize @bullet
308@item
309@code{#:init-keyword}, if @var{init-keyword} is present in the options
310passed to @code{make}
311
312@item
313@code{#:init-thunk}, @code{#:init-form} or @code{#:init-value}.
314@end itemize
315
316If the slot definition contains more than one initialization option of
317the same precedence, the later ones are ignored. If a slot is not
318initialized at all, its value is unbound.
319
320In general, slots that are shared between more than one instance are
321only initialized at new instance creation time if the slot value is
322unbound at that time. However, if the new instance creation specifies
323a valid init keyword and value for a shared slot, the slot is
324re-initialized regardless of its previous value.
325
326Note, however, that the power of GOOPS' metaobject protocol means that
327everything written here may be customized or overridden for particular
328classes! The slot initializations described here are performed by the least
329specialized method of the generic function @code{initialize}, whose
330signature is
331
332@example
333(define-method (initialize (object <object>) initargs) ...)
334@end example
335
336The initialization of instances of any given class can be customized by
337defining a @code{initialize} method that is specialized for that class,
338and the author of the specialized method may decide to call
339@code{next-method} - which will result in a call to the next less
340specialized @code{initialize} method - at any point within the
341specialized code, or maybe not at all. In general, therefore, the
342initialization mechanisms described here may be modified or overridden by
343more specialized code, or may not be supported at all for particular
344classes.
345@end deffn
346
8445eb1d
NJ
347@deffn {slot option} #:getter getter
348@deffnx {slot option} #:setter setter
349@deffnx {slot option} #:accessor accessor
350Given an object @var{obj} with slots named @code{foo} and @code{bar}, it
351is always possible to read and write those slots by calling
352@code{slot-ref} and @code{slot-set!} with the relevant slot name; for
353example:
354
355@example
356(slot-ref @var{obj} 'foo)
357(slot-set! @var{obj} 'bar 25)
358@end example
359
360The @code{#:getter}, @code{#:setter} and @code{#:accessor} options, if
361present, tell GOOPS to create generic function and method definitions
362that can be used to get and set the slot value more conveniently.
363@var{getter} specifies a generic function to which GOOPS will add a
364method for getting the slot value. @var{setter} specifies a generic
365function to which GOOPS will add a method for setting the slot value.
366@var{accessor} specifies an accessor to which GOOPS will add methods for
367both getting and setting the slot value.
368
369So if a class includes a slot definition like this:
370
371@example
372(c #:getter get-count #:setter set-count #:accessor count)
373@end example
374
375GOOPS defines generic function methods such that the slot value can be
376referenced using either the getter or the accessor -
377
378@example
379(let ((current-count (get-count obj))) @dots{})
380(let ((current-count (count obj))) @dots{})
381@end example
382
383- and set using either the setter or the accessor -
384
385@example
386(set-count obj (+ 1 current-count))
387(set! (count obj) (+ 1 current-count))
388@end example
389
390Note that
391
392@itemize @bullet
393@item
394with an accessor, the slot value is set using the generalized
395@code{set!} syntax
396
397@item
398in practice, it is unusual for a slot to use all three of these options:
399read-only, write-only and read-write slots would typically use only
400@code{#:getter}, @code{#:setter} and @code{#:accessor} options
401respectively.
402@end itemize
403
f60a8353
NJ
404The binding of the specified names is done in the environment of the
405@code{define-class} expression. If the names are already bound (in that
406environment) to values that cannot be upgraded to generic functions,
407those values are overwritten when the @code{define-class} expression is
408evaluated. For more detail, see @ref{Generic Function Internals,,
8445eb1d
NJ
409ensure-generic}.
410@end deffn
411
412@deffn {slot option} #:allocation allocation
413The @code{#:allocation} option tells GOOPS how to allocate storage for
414the slot. Possible values for @var{allocation} are
415
416@itemize @bullet
417@item @code{#:instance}
418
f60a8353 419@findex #:instance
8445eb1d 420Indicates that GOOPS should create separate storage for this slot in
f60a8353
NJ
421each new instance of the containing class (and its subclasses). This is
422the default.
8445eb1d
NJ
423
424@item @code{#:class}
425
f60a8353 426@findex #:class
8445eb1d
NJ
427Indicates that GOOPS should create storage for this slot that is shared
428by all instances of the containing class (and its subclasses). In other
429words, a slot in class @var{C} with allocation @code{#:class} is shared
430by all @var{instance}s for which @code{(is-a? @var{instance} @var{c})}.
f60a8353
NJ
431This permits defining a kind of global variable which can be accessed
432only by (in)direct instances of the class which defines the slot.
8445eb1d
NJ
433
434@item @code{#:each-subclass}
435
f60a8353 436@findex #:each-subclass
8445eb1d
NJ
437Indicates that GOOPS should create storage for this slot that is shared
438by all @emph{direct} instances of the containing class, and that
439whenever a subclass of the containing class is defined, GOOPS should
440create a new storage for the slot that is shared by all @emph{direct}
441instances of the subclass. In other words, a slot with allocation
442@code{#:each-subclass} is shared by all instances with the same
443@code{class-of}.
444
445@item @code{#:virtual}
446
f60a8353
NJ
447@findex #:slot-set!
448@findex #:slot-ref
449@findex #:virtual
8445eb1d
NJ
450Indicates that GOOPS should not allocate storage for this slot. The
451slot definition must also include the @code{#:slot-ref} and
452@code{#:slot-set!} options to specify how to reference and set the value
f60a8353 453for this slot. See the example below.
8445eb1d
NJ
454@end itemize
455
8445eb1d
NJ
456Slot allocation options are processed when defining a new class by the
457generic function @code{compute-get-n-set}, which is specialized by the
458class's metaclass. Hence new types of slot allocation can be
459implemented by defining a new metaclass and a method for
460@code{compute-get-n-set} that is specialized for the new metaclass. For
461an example of how to do this, see @ref{Customizing Class Definition}.
462@end deffn
463
464@deffn {slot option} #:slot-ref getter
465@deffnx {slot option} #:slot-set! setter
466The @code{#:slot-ref} and @code{#:slot-set!} options must be specified
467if the slot allocation is @code{#:virtual}, and are ignored otherwise.
468
469@var{getter} should be a closure taking a single @var{instance} parameter
470that returns the current slot value. @var{setter} should be a closure
471taking two parameters - @var{instance} and @var{new-val} - that sets the
472slot value to @var{new-val}.
473@end deffn
474
f60a8353
NJ
475@node Slot Description Example
476@section Illustrating Slot Description
8445eb1d 477
f60a8353
NJ
478To illustrate slot description, we can redefine the @code{<my-complex>}
479class seen before. A definition could be:
8445eb1d 480
f60a8353
NJ
481@lisp
482(define-class <my-complex> (<number>)
483 (r #:init-value 0 #:getter get-r #:setter set-r! #:init-keyword #:r)
484 (i #:init-value 0 #:getter get-i #:setter set-i! #:init-keyword #:i))
485@end lisp
8445eb1d 486
f60a8353
NJ
487@noindent
488With this definition, the @code{r} and @code{i} slots are set to 0 by
489default, and can be initialised to other values by calling @code{make}
490with the @code{#:r} and @code{#:i} keywords. Also the generic functions
491@code{get-r}, @code{set-r!}, @code{get-i} and @code{set-i!} are
492automatically defined to read and write the slots.
8445eb1d 493
f60a8353
NJ
494@lisp
495(define c1 (make <my-complex> #:r 1 #:i 2))
496(get-r c1) @result{} 1
497(set-r! c1 12)
498(get-r c1) @result{} 12
499(define c2 (make <my-complex> #:r 2))
500(get-r c2) @result{} 2
501(get-i c2) @result{} 0
502@end lisp
8445eb1d 503
f60a8353
NJ
504Accessors can both read and write a slot. So, another definition of the
505@code{<my-complex>} class, using the @code{#:accessor} option, could be:
a0e07ba4 506
f60a8353
NJ
507@findex set!
508@lisp
509(define-class <my-complex> (<number>)
510 (r #:init-value 0 #:accessor real-part #:init-keyword #:r)
511 (i #:init-value 0 #:accessor imag-part #:init-keyword #:i))
512@end lisp
a0e07ba4 513
f60a8353
NJ
514@noindent
515With this definition, the @code{r} slot can be read with:
516@lisp
517(real-part c)
518@end lisp
519@noindent
520and set with:
521@lisp
522(set! (real-part c) new-value)
523@end lisp
a0e07ba4 524
f60a8353
NJ
525Suppose now that we want to manipulate complex numbers with both
526rectangular and polar coordinates. One solution could be to have a
527definition of complex numbers which uses one particular representation
528and some conversion functions to pass from one representation to the
529other. A better solution is to use virtual slots, like this:
a0e07ba4 530
f60a8353
NJ
531@lisp
532(define-class <my-complex> (<number>)
533 ;; True slots use rectangular coordinates
534 (r #:init-value 0 #:accessor real-part #:init-keyword #:r)
535 (i #:init-value 0 #:accessor imag-part #:init-keyword #:i)
536 ;; Virtual slots access do the conversion
537 (m #:accessor magnitude #:init-keyword #:magn
538 #:allocation #:virtual
539 #:slot-ref (lambda (o)
540 (let ((r (slot-ref o 'r)) (i (slot-ref o 'i)))
541 (sqrt (+ (* r r) (* i i)))))
542 #:slot-set! (lambda (o m)
543 (let ((a (slot-ref o 'a)))
544 (slot-set! o 'r (* m (cos a)))
545 (slot-set! o 'i (* m (sin a))))))
546 (a #:accessor angle #:init-keyword #:angle
547 #:allocation #:virtual
548 #:slot-ref (lambda (o)
549 (atan (slot-ref o 'i) (slot-ref o 'r)))
550 #:slot-set! (lambda(o a)
551 (let ((m (slot-ref o 'm)))
552 (slot-set! o 'r (* m (cos a)))
553 (slot-set! o 'i (* m (sin a)))))))
a0e07ba4 554
f60a8353 555@end lisp
a0e07ba4 556
ecb87335 557In this class definition, the magnitude @code{m} and angle @code{a}
f60a8353 558slots are virtual, and are calculated, when referenced, from the normal
679cceed 559(i.e.@: @code{#:allocation #:instance}) slots @code{r} and @code{i}, by
f60a8353
NJ
560calling the function defined in the relevant @code{#:slot-ref} option.
561Correspondingly, writing @code{m} or @code{a} leads to calling the
562function defined in the @code{#:slot-set!} option. Thus the
563following expression
a0e07ba4 564
f60a8353
NJ
565@findex #:slot-set!
566@findex #:slot-ref
567@lisp
568(slot-set! c 'a 3)
569@end lisp
570
571@noindent
572permits to set the angle of the @code{c} complex number.
573
574@lisp
575(define c (make <my-complex> #:r 12 #:i 20))
576(real-part c) @result{} 12
577(angle c) @result{} 1.03037682652431
578(slot-set! c 'i 10)
579(set! (real-part c) 1)
580(describe c)
581@print{}
582#<<my-complex> 401e9b58> is an instance of class <my-complex>
583Slots are:
584 r = 1
585 i = 10
586 m = 10.0498756211209
587 a = 1.47112767430373
588@end lisp
589
590Since initialization keywords have been defined for the four slots, we
591can now define the standard Scheme primitives @code{make-rectangular}
592and @code{make-polar}.
a0e07ba4 593
f60a8353
NJ
594@lisp
595(define make-rectangular
596 (lambda (x y) (make <my-complex> #:r x #:i y)))
597
598(define make-polar
599 (lambda (x y) (make <my-complex> #:magn x #:angle y)))
600@end lisp
a0e07ba4 601
f60a8353
NJ
602
603@node Methods and Generic Functions
604@section Methods and Generic Functions
605
606A GOOPS method is like a Scheme procedure except that it is specialized
607for a particular set of argument classes, and will only be used when the
608actual arguments in a call match the classes in the method definition.
609
610@lisp
611(define-method (+ (x <string>) (y <string>))
612 (string-append x y))
613
614(+ "abc" "de") @result{} "abcde"
615@end lisp
616
617A method is not formally associated with any single class (as it is in
618many other object oriented languages), because a method can be
619specialized for a combination of several classes. If you've studied
620object orientation in non-Lispy languages, you may remember discussions
621such as whether a method to stretch a graphical image around a surface
622should be a method of the image class, with a surface as a parameter, or
623a method of the surface class, with an image as a parameter. In GOOPS
624you'd just write
625
626@lisp
627(define-method (stretch (im <image>) (sf <surface>))
628 ...)
629@end lisp
630
631@noindent
632and the question of which class the method is more associated with does
633not need answering.
634
68f4fee1
NJ
635There can simultaneously be several methods with the same name but
636different sets of specializing argument classes; for example:
637
638@lisp
639(define-method (+ (x <string>) (y <string)) ...)
640(define-method (+ (x <matrix>) (y <matrix>)) ...)
ecb87335 641(define-method (+ (f <fish>) (b <bicycle>)) ...)
68f4fee1
NJ
642(define-method (+ (a <foo>) (b <bar>) (c <baz>)) ...)
643@end lisp
644
645@noindent
646A generic function is a container for the set of such methods that a
647program intends to use.
648
649If you look at a program's source code, and see @code{(+ x y)} somewhere
650in it, conceptually what is happening is that the program at that point
651calls a generic function (in this case, the generic function bound to
652the identifier @code{+}). When that happens, Guile works out which of
653the generic function's methods is the most appropriate for the arguments
654that the function is being called with; then it evaluates the method's
655code with the arguments as formal parameters. This happens every time
656that a generic function call is evaluated --- it isn't assumed that a
657given source code call will end up invoking the same method every time.
658
659Defining an identifier as a generic function is done with the
660@code{define-generic} macro. Definition of a new method is done with
661the @code{define-method} macro. Note that @code{define-method}
662automatically does a @code{define-generic} if the identifier concerned
663is not already a generic function, so often an explicit
664@code{define-generic} call is not needed.
665@findex define-generic
666@findex define-method
667
668@deffn syntax define-generic symbol
669Create a generic function with name @var{symbol} and bind it to the
670variable @var{symbol}. If @var{symbol} was previously bound to a Scheme
671procedure (or procedure-with-setter), the old procedure (and setter) is
672incorporated into the new generic function as its default procedure (and
673setter). Any other previous value, including an existing generic
674function, is discarded and replaced by a new, empty generic function.
675@end deffn
676
677@deffn syntax define-method (generic parameter @dots{}) . body
678Define a method for the generic function or accessor @var{generic} with
679parameters @var{parameter}s and body @var{body}.
680
681@var{generic} is a generic function. If @var{generic} is a variable
682which is not yet bound to a generic function object, the expansion of
683@code{define-method} will include a call to @code{define-generic}. If
684@var{generic} is @code{(setter @var{generic-with-setter})}, where
685@var{generic-with-setter} is a variable which is not yet bound to a
686generic-with-setter object, the expansion will include a call to
687@code{define-accessor}.
688
689Each @var{parameter} must be either a symbol or a two-element list
690@code{(@var{symbol} @var{class})}. The symbols refer to variables in
691the @var{body} that will be bound to the parameters supplied by the
692caller when calling this method. The @var{class}es, if present,
693specify the possible combinations of parameters to which this method
694can be applied.
695
696@var{body} is the body of the method definition.
697@end deffn
698
699@code{define-method} expressions look a little like Scheme procedure
700definitions of the form
701
702@example
703(define (name formals @dots{}) . body)
704@end example
705
706The important difference is that each formal parameter, apart from the
707possible ``rest'' argument, can be qualified by a class name:
708@code{@var{formal}} becomes @code{(@var{formal} @var{class})}. The
709meaning of this qualification is that the method being defined
710will only be applicable in a particular generic function invocation if
711the corresponding argument is an instance of @code{@var{class}} (or one of
712its subclasses). If more than one of the formal parameters is qualified
713in this way, then the method will only be applicable if each of the
714corresponding arguments is an instance of its respective qualifying class.
715
716Note that unqualified formal parameters act as though they are qualified
717by the class @code{<top>}, which GOOPS uses to mean the superclass of
718all valid Scheme types, including both primitive types and GOOPS classes.
719
720For example, if a generic function method is defined with
721@var{parameter}s @code{(s1 <square>)} and @code{(n <number>)}, that
722method is only applicable to invocations of its generic function that
723have two parameters where the first parameter is an instance of the
724@code{<square>} class and the second parameter is a number.
f60a8353
NJ
725
726@menu
68f4fee1
NJ
727* Accessors::
728* Extending Primitives::
729* Merging Generics::
f60a8353 730* Next-method::
68f4fee1
NJ
731* Generic Function and Method Examples::
732* Handling Invocation Errors::
f60a8353
NJ
733@end menu
734
f60a8353 735
68f4fee1
NJ
736@node Accessors
737@subsection Accessors
f60a8353 738
68f4fee1
NJ
739An accessor is a generic function that can also be used with the
740generalized @code{set!} syntax (@pxref{Procedures with Setters}). Guile
741will handle a call like
f60a8353 742
68f4fee1
NJ
743@example
744(set! (@code{accessor} @code{args}@dots{}) @code{value})
745@end example
f60a8353 746
68f4fee1
NJ
747@noindent
748by calling the most specialized method of @code{accessor} that matches
749the classes of @code{args} and @code{value}. @code{define-accessor} is
750used to bind an identifier to an accessor.
f60a8353 751
68f4fee1
NJ
752@deffn syntax define-accessor symbol
753Create an accessor with name @var{symbol} and bind it to the variable
754@var{symbol}. If @var{symbol} was previously bound to a Scheme
755procedure (or procedure-with-setter), the old procedure (and setter) is
756incorporated into the new accessor as its default procedure (and
757setter). Any other previous value, including an existing generic
758function or accessor, is discarded and replaced by a new, empty
759accessor.
760@end deffn
f60a8353 761
f60a8353 762
68f4fee1
NJ
763@node Extending Primitives
764@subsection Extending Primitives
765
766Many of Guile's primitive procedures can be extended by giving them a
767generic function definition that operates in conjunction with their
768normal C-coded implementation. When a primitive is extended in this
769way, it behaves like a generic function with the C-coded implementation
770as its default method.
771
772This extension happens automatically if a method is defined (by a
773@code{define-method} call) for a variable whose current value is a
774primitive. But it can also be forced by calling
775@code{enable-primitive-generic!}.
776
777@deffn {primitive procedure} enable-primitive-generic! primitive
778Force the creation of a generic function definition for
779@var{primitive}.
780@end deffn
781
782Once the generic function definition for a primitive has been created,
783it can be retrieved using @code{primitive-generic-generic}.
784
785@deffn {primitive procedure} primitive-generic-generic primitive
786Return the generic function definition of @var{primitive}.
f60a8353 787
68f4fee1
NJ
788@code{primitive-generic-generic} raises an error if @var{primitive}
789is not a primitive with generic capability.
790@end deffn
791
792@node Merging Generics
793@subsection Merging Generics
794
795GOOPS generic functions and accessors often have short, generic names.
796For example, if a vector package provides an accessor for the X
797coordinate of a vector, that accessor may just be called @code{x}. It
798doesn't need to be called, for example, @code{vector:x}, because
799GOOPS will work out, when it sees code like @code{(x @var{obj})}, that
800the vector-specific method of @code{x} should be called if @var{obj} is
801a vector.
802
803That raises the question, though, of what happens when different
804packages define a generic function with the same name. Suppose we work
805with a graphical package which needs to use two independent vector
806packages for 2D and 3D vectors respectively. If both packages export
807@code{x}, what does the code using those packages end up with?
808
809@ref{Creating Guile Modules,,duplicate binding handlers} explains how
810this is resolved for conflicting bindings in general. For generics,
811there is a special duplicates handler, @code{merge-generics}, which
812tells the module system to merge generic functions with the same name.
813Here is an example:
f60a8353
NJ
814
815@lisp
68f4fee1
NJ
816(define-module (math 2D-vectors)
817 #:use-module (oop goops)
818 #:export (x y ...))
819
820(define-module (math 3D-vectors)
821 #:use-module (oop goops)
822 #:export (x y z ...))
823
824(define-module (my-module)
825 #:use-module (math 2D-vectors)
826 #:use-module (math 3D-vectors)
827 #:duplicates merge-generics)
f60a8353
NJ
828@end lisp
829
68f4fee1
NJ
830The generic function @code{x} in @code{(my-module)} will now incorporate
831all of the methods of @code{x} from both imported modules.
832
833To be precise, there will now be three distinct generic functions named
834@code{x}: @code{x} in @code{(math 2D-vectors)}, @code{x} in @code{(math
8353D-vectors)}, and @code{x} in @code{(my-module)}; and these functions
836share their methods in an interesting and dynamic way.
837
838To explain, let's call the imported generic functions (in @code{(math
8392D-vectors)} and @code{(math 3D-vectors)}) the @dfn{ancestors}, and the
840merged generic function (in @code{(my-module)}), the @dfn{descendant}.
841The general rule is that for any generic function G, the applicable
842methods are selected from the union of the methods of G's descendant
843functions, the methods of G itself and the methods of G's ancestor
844functions.
845
846Thus ancestor functions effectively share methods with their
847descendants, and vice versa. In the example above, @code{x} in
848@code{(math 2D-vectors)} will share the methods of @code{x} in
849@code{(my-module)} and vice versa.@footnote{But note that @code{x} in
850@code{(math 2D-vectors)} doesn't share methods with @code{x} in
851@code{(math 3D-vectors)}, so modularity is still preserved.} Sharing is
852dynamic, so adding another new method to a descendant implies adding it
853to that descendant's ancestors too.
854
f60a8353
NJ
855@node Next-method
856@subsection Next-method
857
858When you call a generic function, with a particular set of arguments,
859GOOPS builds a list of all the methods that are applicable to those
860arguments and orders them by how closely the method definitions match
861the actual argument types. It then calls the method at the top of this
862list. If the selected method's code wants to call on to the next method
863in this list, it can do so by using @code{next-method}.
864
865@lisp
866(define-method (Test (a <integer>)) (cons 'integer (next-method)))
867(define-method (Test (a <number>)) (cons 'number (next-method)))
868(define-method (Test a) (list 'top))
869@end lisp
870
871With these definitions,
872
873@lisp
874(Test 1) @result{} (integer number top)
875(Test 1.0) @result{} (number top)
876(Test #t) @result{} (top)
877@end lisp
878
879@code{next-method} is always called as just @code{(next-method)}. The
880arguments for the next method call are always implicit, and always the
881same as for the original method call.
882
883If you want to call on to a method with the same name but with a
884different set of arguments (as you might with overloaded methods in C++,
885for example), you do not use @code{next-method}, but instead simply
886write the new call as usual:
887
888@lisp
889(define-method (Test (a <number>) min max)
890 (if (and (>= a min) (<= a max))
891 (display "Number is in range\n"))
892 (Test a))
893
894(Test 2 1 10)
895@print{}
896Number is in range
897@result{}
898(integer number top)
899@end lisp
900
901(You should be careful in this case that the @code{Test} calls do not
902lead to an infinite recursion, but this consideration is just the same
903as in Scheme code in general.)
904
68f4fee1
NJ
905@node Generic Function and Method Examples
906@subsection Generic Function and Method Examples
907
908Consider the following definitions:
f60a8353 909
68f4fee1
NJ
910@lisp
911(define-generic G)
912(define-method (G (a <integer>) b) 'integer)
913(define-method (G (a <real>) b) 'real)
914(define-method (G a b) 'top)
915@end lisp
916
917The @code{define-generic} call defines @var{G} as a generic function.
918The three next lines define methods for @var{G}. Each method uses a
919sequence of @dfn{parameter specializers} that specify when the given
920method is applicable. A specializer permits to indicate the class a
921parameter must belong to (directly or indirectly) to be applicable. If
922no specializer is given, the system defaults it to @code{<top>}. Thus,
923the first method definition is equivalent to
924
925@cindex parameter specializers
926@lisp
927(define-method (G (a <integer>) (b <top>)) 'integer)
928@end lisp
929
930Now, let's look at some possible calls to the generic function @var{G}:
931
932@lisp
933(G 2 3) @result{} integer
934(G 2 #t) @result{} integer
935(G 1.2 'a) @result{} real
936@c (G #3 'a) @result{} real @c was {\sharpsign}
937(G #t #f) @result{} top
938(G 1 2 3) @result{} error (since no method exists for 3 parameters)
939@end lisp
940
941The methods above use only one specializer per parameter list. But in
942general, any or all of a method's parameters may be specialized.
943Suppose we define now:
944
945@lisp
946(define-method (G (a <integer>) (b <number>)) 'integer-number)
947(define-method (G (a <integer>) (b <real>)) 'integer-real)
948(define-method (G (a <integer>) (b <integer>)) 'integer-integer)
949(define-method (G a (b <number>)) 'top-number)
950@end lisp
951
952@noindent With these definitions:
953
954@lisp
955(G 1 2) @result{} integer-integer
956(G 1 1.0) @result{} integer-real
957(G 1 #t) @result{} integer
958(G 'a 1) @result{} top-number
959@end lisp
960
961As a further example we shall continue to define operations on the
4431a337
NJ
962@code{<my-complex>} class. Suppose that we want to use it to implement
963complex numbers completely. For instance a definition for the addition
68f4fee1 964of two complex numbers could be
f60a8353
NJ
965
966@lisp
967(define-method (new-+ (a <my-complex>) (b <my-complex>))
968 (make-rectangular (+ (real-part a) (real-part b))
969 (+ (imag-part a) (imag-part b))))
970@end lisp
971
4431a337
NJ
972To be sure that the @code{+} used in the method @code{new-+} is the
973standard addition we can do:
f60a8353
NJ
974
975@lisp
976(define-generic new-+)
977
978(let ((+ +))
979 (define-method (new-+ (a <my-complex>) (b <my-complex>))
980 (make-rectangular (+ (real-part a) (real-part b))
981 (+ (imag-part a) (imag-part b)))))
982@end lisp
983
984The @code{define-generic} ensures here that @code{new-+} will be defined
985in the global environment. Once this is done, we can add methods to the
986generic function @code{new-+} which make a closure on the @code{+}
987symbol. A complete writing of the @code{new-+} methods is shown in
4431a337 988@ref{fig:newplus}.
a0e07ba4 989
4431a337 990@float Figure,fig:newplus
f60a8353
NJ
991@lisp
992(define-generic new-+)
993
994(let ((+ +))
995
996 (define-method (new-+ (a <real>) (b <real>)) (+ a b))
997
998 (define-method (new-+ (a <real>) (b <my-complex>))
999 (make-rectangular (+ a (real-part b)) (imag-part b)))
1000
1001 (define-method (new-+ (a <my-complex>) (b <real>))
1002 (make-rectangular (+ (real-part a) b) (imag-part a)))
a0e07ba4 1003
f60a8353
NJ
1004 (define-method (new-+ (a <my-complex>) (b <my-complex>))
1005 (make-rectangular (+ (real-part a) (real-part b))
1006 (+ (imag-part a) (imag-part b))))
a0e07ba4 1007
f60a8353
NJ
1008 (define-method (new-+ (a <number>)) a)
1009
1010 (define-method (new-+) 0)
a0e07ba4 1011
f60a8353
NJ
1012 (define-method (new-+ . args)
1013 (new-+ (car args)
1014 (apply new-+ (cdr args)))))
1015
1016(set! + new-+)
1017@end lisp
1018
4431a337
NJ
1019@caption{Extending @code{+} to handle complex numbers}
1020@end float
a0e07ba4 1021
68f4fee1
NJ
1022We take advantage here of the fact that generic function are not obliged
1023to have a fixed number of parameters. The four first methods implement
1024dyadic addition. The fifth method says that the addition of a single
1025element is this element itself. The sixth method says that using the
1026addition with no parameter always return 0 (as is also true for the
1027primitive @code{+}). The last method takes an arbitrary number of
1028parameters@footnote{The parameter list for a @code{define-method}
1029follows the conventions used for Scheme procedures. In particular it can
1030use the dot notation or a symbol to denote an arbitrary number of
1031parameters}. This method acts as a kind of @code{reduce}: it calls the
1032dyadic addition on the @emph{car} of the list and on the result of
1033applying it on its rest. To finish, the @code{set!} permits to redefine
1034the @code{+} symbol to our extended addition.
1035
1036To conclude our implementation (integration?) of complex numbers, we
1037could redefine standard Scheme predicates in the following manner:
f60a8353
NJ
1038
1039@lisp
1040(define-method (complex? c <my-complex>) #t)
1041(define-method (complex? c) #f)
1042
1043(define-method (number? n <number>) #t)
1044(define-method (number? n) #f)
1045@dots{}
f60a8353
NJ
1046@end lisp
1047
1048Standard primitives in which complex numbers are involved could also be
1049redefined in the same manner.
1050
1051
68f4fee1
NJ
1052@node Handling Invocation Errors
1053@subsection Handling Invocation Errors
1054
1055If a generic function is invoked with a combination of parameters for
1056which there is no applicable method, GOOPS raises an error.
1057
1058@deffn generic no-method
1059@deffnx method no-method (gf <generic>) args
1060When an application invokes a generic function, and no methods at all
1061have been defined for that generic function, GOOPS calls the
1062@code{no-method} generic function. The default method calls
1063@code{goops-error} with an appropriate message.
1064@end deffn
1065
1066@deffn generic no-applicable-method
1067@deffnx method no-applicable-method (gf <generic>) args
1068When an application applies a generic function to a set of arguments,
1069and no methods have been defined for those argument types, GOOPS calls
1070the @code{no-applicable-method} generic function. The default method
1071calls @code{goops-error} with an appropriate message.
1072@end deffn
1073
1074@deffn generic no-next-method
1075@deffnx method no-next-method (gf <generic>) args
1076When a generic function method calls @code{(next-method)} to invoke the
1077next less specialized method for that generic function, and no less
1078specialized methods have been defined for the current generic function
1079arguments, GOOPS calls the @code{no-next-method} generic function. The
1080default method calls @code{goops-error} with an appropriate message.
1081@end deffn
1082
1083
f60a8353
NJ
1084@node Inheritance
1085@section Inheritance
1086
1087Here are some class definitions to help illustrate inheritance:
1088
1089@lisp
1090(define-class A () a)
1091(define-class B () b)
1092(define-class C () c)
1093(define-class D (A B) d a)
1094(define-class E (A C) e c)
1095(define-class F (D E) f)
1096@end lisp
1097
1098@code{A}, @code{B}, @code{C} have a null list of superclasses. In this
1099case, the system will replace the null list by a list which only
1100contains @code{<object>}, the root of all the classes defined by
1101@code{define-class}. @code{D}, @code{E}, @code{F} use multiple
1102inheritance: each class inherits from two previously defined classes.
4431a337
NJ
1103Those class definitions define a hierarchy which is shown in
1104@ref{fig:hier}. In this figure, the class @code{<top>} is also shown;
1105this class is the superclass of all Scheme objects. In particular,
1106@code{<top>} is the superclass of all standard Scheme
1107types.@footnote{@code{<complex>}, which is the direct subclass of
1108@code{<number>} and the direct superclass of @code{<real>}, has been
1109omitted in this figure.}
1110
1111@float Figure,fig:hier
f60a8353
NJ
1112@iftex
1113@center @image{hierarchy,5in}
1114@end iftex
1115@ifnottex
1116@verbatiminclude hierarchy.txt
1117@end ifnottex
1118
4431a337
NJ
1119@caption{A class hierarchy.}
1120@end float
f60a8353
NJ
1121
1122When a class has superclasses, its set of slots is calculated by taking
1123the union of its own slots and those of all its superclasses. Thus each
1124instance of D will have three slots, @code{a}, @code{b} and
1125@code{d}). The slots of a class can be discovered using the
1126@code{class-slots} primitive. For instance,
1127
1128@lisp
1129(class-slots A) @result{} ((a))
1130(class-slots E) @result{} ((a) (e) (c))
1131(class-slots F) @result{} ((e) (c) (b) (d) (a) (f))
1132@end lisp
1133
1134@noindent
1135The ordering of the returned slots is not significant.
1136
1137@menu
68f4fee1
NJ
1138* Class Precedence List::
1139* Sorting Methods::
f60a8353
NJ
1140@end menu
1141
1142
68f4fee1
NJ
1143@node Class Precedence List
1144@subsection Class Precedence List
1145
1146What happens when a class inherits from two or more superclasses that
1147have a slot with the same name but incompatible definitions --- for
1148example, different init values or slot allocations? We need a rule for
1149deciding which slot definition the derived class ends up with, and this
1150rule is provided by the class's @dfn{Class Precedence
1151List}.@footnote{This section is an adaptation of material from Jeff
1152Dalton's (J.Dalton@@ed.ac.uk) @cite{Brief introduction to CLOS}}
a0e07ba4 1153
68f4fee1
NJ
1154Another problem arises when invoking a generic function, and there is
1155more than one method that could apply to the call arguments. Here we
1156need a way of ordering the applicable methods, so that Guile knows which
1157method to use first, which to use next if that method calls
1158@code{next-method}, and so on. One of the ingredients for this ordering
1159is determining, for each given call argument, which of the specializing
1160classes, from each applicable method's definition, is the most specific
1161for that argument; and here again the class precedence list helps.
a0e07ba4 1162
68f4fee1
NJ
1163If inheritance was restricted such that each class could only have one
1164superclass --- which is known as @dfn{single} inheritance --- class
1165ordering would be easy. The rule would be simply that a subclass is
1166considered more specific than its superclass.
a0e07ba4 1167
68f4fee1
NJ
1168With multiple inheritance, ordering is less obvious, and we have to
1169impose an arbitrary rule to determine precedence. Suppose we have
a0e07ba4 1170
f60a8353
NJ
1171@lisp
1172(define-class X ()
1173 (x #:init-value 1))
1174
1175(define-class Y ()
1176 (x #:init-value 2))
1177
1178(define-class Z (X Y)
1179 (@dots{}))
1180@end lisp
1181
68f4fee1
NJ
1182@noindent
1183Clearly the @code{Z} class is more specific than @code{X} or @code{Y},
1184for instances of @code{Z}. But which is more specific out of @code{X}
1185and @code{Y} --- and hence, for the definitions above, which
1186@code{#:init-value} will take effect when creating an instance of
1187@code{Z}? The rule in @goops{} is that the superclasses listed earlier
1188are more specific than those listed later. Hence @code{X} is more
1189specific than @code{Y}, and the @code{#:init-value} for slot @code{x} in
1190instances of @code{Z} will be 1.
1191
1192Hence there is a linear ordering for a class and all its
1193superclasses, from most specific to least specific, and this ordering is
1194called the Class Precedence List of the class.
1195
1196In fact the rules above are not quite enough to always determine a
1197unique order, but they give an idea of how things work. For example,
1198for the @code{F} class shown in @ref{fig:hier}, the class precedence
1199list is
f60a8353
NJ
1200
1201@example
1202(f d e a c b <object> <top>)
a0e07ba4
NJ
1203@end example
1204
68f4fee1
NJ
1205@noindent
1206In cases where there is any ambiguity (like this one), it is a bad idea
1207for programmers to rely on exactly what the order is. If the order for
1208some superclasses is important, it can be expressed directly in the
1209class definition.
f60a8353 1210
68f4fee1
NJ
1211The precedence list of a class can be obtained by calling
1212@code{class-precedence-list}. This function returns a ordered list
1213whose first element is the most specific class. For instance:
f60a8353
NJ
1214
1215@lisp
1216(class-precedence-list B) @result{} (#<<class> B 401b97c8>
1217 #<<class> <object> 401e4a10>
1218 #<<class> <top> 4026a9d8>)
1219@end lisp
1220
68f4fee1
NJ
1221@noindent
1222Or for a more immediately readable result:
f60a8353
NJ
1223
1224@lisp
1225(map class-name (class-precedence-list B)) @result{} (B <object> <top>)
1226@end lisp
1227
1228
68f4fee1
NJ
1229@node Sorting Methods
1230@subsection Sorting Methods
1231
1232Now, with the idea of the class precedence list, we can state precisely
1233how the possible methods are sorted when more than one of the methods of
1234a generic function are applicable to the call arguments.
1235
1236The rules are that
1237@itemize
1238@item
1239the applicable methods are sorted in order of specificity, and the most
1240specific method is used first, then the next if that method calls
1241@code{next-method}, and so on
1242
1243@item
1244a method M1 is more specific than another method M2 if the first
1245specializing class that differs, between the definitions of M1 and M2,
1246is more specific, in M1's definition, for the corresponding actual call
1247argument, than the specializing class in M2's definition
1248
1249@item
1250a class C1 is more specific than another class C2, for an object of
1251actual class C, if C1 comes before C2 in C's class precedence list.
1252@end itemize
1253
1254
62d7cba3
NJ
1255@node Introspection
1256@section Introspection
f60a8353 1257
dc08a490
NJ
1258@dfn{Introspection}, or @dfn{reflection}, means being able to obtain
1259information dynamically about GOOPS objects. It is perhaps best
1260illustrated by considering an object oriented language that does not
1261provide any introspection, namely C++.
f60a8353 1262
62d7cba3
NJ
1263Nothing in C++ allows a running program to obtain answers to the following
1264types of question:
f60a8353 1265
62d7cba3
NJ
1266@itemize @bullet
1267@item
1268What are the data members of this object or class?
f60a8353 1269
62d7cba3
NJ
1270@item
1271What classes does this class inherit from?
f60a8353 1272
62d7cba3
NJ
1273@item
1274Is this method call virtual or non-virtual?
1275
1276@item
1277If I invoke @code{Employee::adjustHoliday()}, what class contains the
1278@code{adjustHoliday()} method that will be applied?
1279@end itemize
1280
1281In C++, answers to such questions can only be determined by looking at
1282the source code, if you have access to it. GOOPS, on the other hand,
1283includes procedures that allow answers to these questions --- or their
1284GOOPS equivalents --- to be obtained dynamically, at run time.
a0e07ba4
NJ
1285
1286@menu
62d7cba3 1287* Classes::
62d7cba3 1288* Instances::
c7b15458 1289* Slots::
62d7cba3 1290* Generic Functions::
3617da95 1291* Accessing Slots::
a0e07ba4
NJ
1292@end menu
1293
62d7cba3
NJ
1294@node Classes
1295@subsection Classes
a0e07ba4 1296
dc08a490
NJ
1297A GOOPS class is itself an instance of the @code{<class>} class, or of a
1298subclass of @code{<class>}. The definition of the @code{<class>} class
1299has slots that are used to describe the properties of a class, including
1300the following.
1301
62d7cba3 1302@deffn {primitive procedure} class-name class
dc08a490
NJ
1303Return the name of class @var{class}. This is the value of
1304@var{class}'s @code{name} slot.
62d7cba3 1305@end deffn
a0e07ba4 1306
62d7cba3 1307@deffn {primitive procedure} class-direct-supers class
dc08a490
NJ
1308Return a list containing the direct superclasses of @var{class}. This
1309is the value of @var{class}'s @code{direct-supers} slot.
a0e07ba4
NJ
1310@end deffn
1311
62d7cba3
NJ
1312@deffn {primitive procedure} class-direct-slots class
1313Return a list containing the slot definitions of the direct slots of
dc08a490 1314@var{class}. This is the value of @var{class}'s @code{direct-slots}
62d7cba3
NJ
1315slot.
1316@end deffn
a0e07ba4 1317
62d7cba3 1318@deffn {primitive procedure} class-direct-subclasses class
dc08a490
NJ
1319Return a list containing the direct subclasses of @var{class}. This is
1320the value of @var{class}'s @code{direct-subclasses} slot.
a0e07ba4
NJ
1321@end deffn
1322
62d7cba3
NJ
1323@deffn {primitive procedure} class-direct-methods class
1324Return a list of all the generic function methods that use @var{class}
dc08a490
NJ
1325as a formal parameter specializer. This is the value of @var{class}'s
1326@code{direct-methods} slot.
62d7cba3 1327@end deffn
a0e07ba4 1328
62d7cba3
NJ
1329@deffn {primitive procedure} class-precedence-list class
1330Return the class precedence list for class @var{class} (@pxref{Class
dc08a490 1331Precedence List}). This is the value of @var{class}'s @code{cpl} slot.
62d7cba3 1332@end deffn
a0e07ba4 1333
62d7cba3 1334@deffn {primitive procedure} class-slots class
dc08a490
NJ
1335Return a list containing the slot definitions for all @var{class}'s
1336slots, including any slots that are inherited from superclasses. This
1337is the value of @var{class}'s @code{slots} slot.
62d7cba3 1338@end deffn
a0e07ba4 1339
62d7cba3
NJ
1340@deffn procedure class-subclasses class
1341Return a list of all subclasses of @var{class}.
a0e07ba4
NJ
1342@end deffn
1343
62d7cba3
NJ
1344@deffn procedure class-methods class
1345Return a list of all methods that use @var{class} or a subclass of
1346@var{class} as one of its formal parameter specializers.
1347@end deffn
a0e07ba4 1348
dc08a490 1349
c7b15458
NJ
1350@node Instances
1351@subsection Instances
1352
1353@deffn {primitive procedure} class-of value
1354Return the GOOPS class of any Scheme @var{value}.
1355@end deffn
1356
1357@deffn {primitive procedure} instance? object
1358Return @code{#t} if @var{object} is any GOOPS instance, otherwise
1359@code{#f}.
1360@end deffn
1361
1362@deffn procedure is-a? object class
1363Return @code{#t} if @var{object} is an instance of @var{class} or one of
1364its subclasses.
1365@end deffn
1366
1367You can use the @code{is-a?} predicate to ask whether any given value
1368belongs to a given class, or @code{class-of} to discover the class of a
1369given value. Note that when GOOPS is loaded (by code using the
1370@code{(oop goops)} module) built-in classes like @code{<string>},
1371@code{<list>} and @code{<number>} are automatically set up,
1372corresponding to all Guile Scheme types.
1373
1374@lisp
1375(is-a? 2.3 <number>) @result{} #t
1376(is-a? 2.3 <real>) @result{} #t
1377(is-a? 2.3 <string>) @result{} #f
1378(is-a? '("a" "b") <string>) @result{} #f
1379(is-a? '("a" "b") <list>) @result{} #t
1380(is-a? (car '("a" "b")) <string>) @result{} #t
1381(is-a? <string> <class>) @result{} #t
1382(is-a? <class> <string>) @result{} #f
1383
1384(class-of 2.3) @result{} #<<class> <real> 908c708>
1385(class-of #(1 2 3)) @result{} #<<class> <vector> 908cd20>
1386(class-of <string>) @result{} #<<class> <class> 8bd3e10>
1387(class-of <class>) @result{} #<<class> <class> 8bd3e10>
1388@end lisp
1389
1390
62d7cba3
NJ
1391@node Slots
1392@subsection Slots
a0e07ba4 1393
62d7cba3
NJ
1394@deffn procedure class-slot-definition class slot-name
1395Return the slot definition for the slot named @var{slot-name} in class
1396@var{class}. @var{slot-name} should be a symbol.
a0e07ba4
NJ
1397@end deffn
1398
62d7cba3
NJ
1399@deffn procedure slot-definition-name slot-def
1400Extract and return the slot name from @var{slot-def}.
a0e07ba4
NJ
1401@end deffn
1402
62d7cba3
NJ
1403@deffn procedure slot-definition-options slot-def
1404Extract and return the slot options from @var{slot-def}.
1405@end deffn
a0e07ba4 1406
62d7cba3
NJ
1407@deffn procedure slot-definition-allocation slot-def
1408Extract and return the slot allocation option from @var{slot-def}. This
1409is the value of the @code{#:allocation} keyword (@pxref{Slot Options,,
1410allocation}), or @code{#:instance} if the @code{#:allocation} keyword is
1411absent.
1412@end deffn
a0e07ba4 1413
62d7cba3
NJ
1414@deffn procedure slot-definition-getter slot-def
1415Extract and return the slot getter option from @var{slot-def}. This is
1416the value of the @code{#:getter} keyword (@pxref{Slot Options,,
1417getter}), or @code{#f} if the @code{#:getter} keyword is absent.
a0e07ba4
NJ
1418@end deffn
1419
62d7cba3
NJ
1420@deffn procedure slot-definition-setter slot-def
1421Extract and return the slot setter option from @var{slot-def}. This is
1422the value of the @code{#:setter} keyword (@pxref{Slot Options,,
1423setter}), or @code{#f} if the @code{#:setter} keyword is absent.
1424@end deffn
a0e07ba4 1425
62d7cba3
NJ
1426@deffn procedure slot-definition-accessor slot-def
1427Extract and return the slot accessor option from @var{slot-def}. This
1428is the value of the @code{#:accessor} keyword (@pxref{Slot Options,,
1429accessor}), or @code{#f} if the @code{#:accessor} keyword is absent.
a0e07ba4
NJ
1430@end deffn
1431
62d7cba3
NJ
1432@deffn procedure slot-definition-init-value slot-def
1433Extract and return the slot init-value option from @var{slot-def}. This
1434is the value of the @code{#:init-value} keyword (@pxref{Slot Options,,
1435init-value}), or the unbound value if the @code{#:init-value} keyword is
1436absent.
1437@end deffn
a0e07ba4 1438
62d7cba3
NJ
1439@deffn procedure slot-definition-init-form slot-def
1440Extract and return the slot init-form option from @var{slot-def}. This
1441is the value of the @code{#:init-form} keyword (@pxref{Slot Options,,
1442init-form}), or the unbound value if the @code{#:init-form} keyword is
1443absent.
1444@end deffn
a0e07ba4 1445
62d7cba3
NJ
1446@deffn procedure slot-definition-init-thunk slot-def
1447Extract and return the slot init-thunk option from @var{slot-def}. This
1448is the value of the @code{#:init-thunk} keyword (@pxref{Slot Options,,
1449init-thunk}), or @code{#f} if the @code{#:init-thunk} keyword is absent.
1450@end deffn
a0e07ba4 1451
62d7cba3
NJ
1452@deffn procedure slot-definition-init-keyword slot-def
1453Extract and return the slot init-keyword option from @var{slot-def}.
1454This is the value of the @code{#:init-keyword} keyword (@pxref{Slot
1455Options,, init-keyword}), or @code{#f} if the @code{#:init-keyword}
1456keyword is absent.
a0e07ba4
NJ
1457@end deffn
1458
62d7cba3
NJ
1459@deffn procedure slot-init-function class slot-name
1460Return the initialization function for the slot named @var{slot-name} in
1461class @var{class}. @var{slot-name} should be a symbol.
a0e07ba4 1462
62d7cba3
NJ
1463The returned initialization function incorporates the effects of the
1464standard @code{#:init-thunk}, @code{#:init-form} and @code{#:init-value}
1465slot options. These initializations can be overridden by the
1466@code{#:init-keyword} slot option or by a specialized @code{initialize}
1467method, so, in general, the function returned by
1468@code{slot-init-function} may be irrelevant. For a fuller discussion,
1469see @ref{Slot Options,, init-value}.
a0e07ba4
NJ
1470@end deffn
1471
62d7cba3
NJ
1472
1473@node Generic Functions
1474@subsection Generic Functions
1475
dc08a490
NJ
1476A generic function is an instance of the @code{<generic>} class, or of a
1477subclass of @code{<generic>}. The definition of the @code{<generic>}
1478class has slots that are used to describe the properties of a generic
1479function.
1480
62d7cba3
NJ
1481@deffn {primitive procedure} generic-function-name gf
1482Return the name of generic function @var{gf}.
1483@end deffn
1484
1485@deffn {primitive procedure} generic-function-methods gf
dc08a490
NJ
1486Return a list of the methods of generic function @var{gf}. This is the
1487value of @var{gf}'s @code{methods} slot.
62d7cba3
NJ
1488@end deffn
1489
dc08a490
NJ
1490Similarly, a method is an instance of the @code{<method>} class, or of a
1491subclass of @code{<method>}; and the definition of the @code{<method>}
1492class has slots that are used to describe the properties of a method.
62d7cba3
NJ
1493
1494@deffn {primitive procedure} method-generic-function method
dc08a490
NJ
1495Return the generic function that @var{method} belongs to. This is the
1496value of @var{method}'s @code{generic-function} slot.
62d7cba3
NJ
1497@end deffn
1498
1499@deffn {primitive procedure} method-specializers method
dc08a490
NJ
1500Return a list of @var{method}'s formal parameter specializers . This is
1501the value of @var{method}'s @code{specializers} slot.
62d7cba3
NJ
1502@end deffn
1503
1504@deffn {primitive procedure} method-procedure method
dc08a490
NJ
1505Return the procedure that implements @var{method}. This is the value of
1506@var{method}'s @code{procedure} slot.
62d7cba3
NJ
1507@end deffn
1508
1509@deffn generic method-source
1510@deffnx method method-source (m <method>)
1511Return an expression that prints to show the definition of method
1512@var{m}.
1513
1514@example
1515(define-generic cube)
1516
1517(define-method (cube (n <number>))
1518 (* n n n))
1519
1520(map method-source (generic-function-methods cube))
1521@result{}
1522((method ((n <number>)) (* n n n)))
1523@end example
1524@end deffn
1525
1526
62d7cba3 1527@node Accessing Slots
3617da95 1528@subsection Accessing Slots
62d7cba3
NJ
1529
1530Any slot, regardless of its allocation, can be queried, referenced and
1531set using the following four primitive procedures.
1532
1533@deffn {primitive procedure} slot-exists? obj slot-name
1534Return @code{#t} if @var{obj} has a slot with name @var{slot-name},
1535otherwise @code{#f}.
1536@end deffn
1537
1538@deffn {primitive procedure} slot-bound? obj slot-name
1539Return @code{#t} if the slot named @var{slot-name} in @var{obj} has a
1540value, otherwise @code{#f}.
1541
1542@code{slot-bound?} calls the generic function @code{slot-missing} if
9320479a
NJ
1543@var{obj} does not have a slot called @var{slot-name} (@pxref{Accessing
1544Slots, slot-missing}).
62d7cba3
NJ
1545@end deffn
1546
1547@deffn {primitive procedure} slot-ref obj slot-name
1548Return the value of the slot named @var{slot-name} in @var{obj}.
1549
1550@code{slot-ref} calls the generic function @code{slot-missing} if
9320479a
NJ
1551@var{obj} does not have a slot called @var{slot-name} (@pxref{Accessing
1552Slots, slot-missing}).
62d7cba3
NJ
1553
1554@code{slot-ref} calls the generic function @code{slot-unbound} if the
9320479a
NJ
1555named slot in @var{obj} does not have a value (@pxref{Accessing Slots,
1556slot-unbound}).
62d7cba3
NJ
1557@end deffn
1558
1559@deffn {primitive procedure} slot-set! obj slot-name value
1560Set the value of the slot named @var{slot-name} in @var{obj} to @var{value}.
1561
1562@code{slot-set!} calls the generic function @code{slot-missing} if
9320479a
NJ
1563@var{obj} does not have a slot called @var{slot-name} (@pxref{Accessing
1564Slots, slot-missing}).
62d7cba3
NJ
1565@end deffn
1566
1567GOOPS stores information about slots in classes. Internally,
1568all of these procedures work by looking up the slot definition for the
1569slot named @var{slot-name} in the class @code{(class-of
1570@var{obj})}, and then using the slot definition's ``getter'' and
1571``setter'' closures to get and set the slot value.
1572
1573The next four procedures differ from the previous ones in that they take
1574the class as an explicit argument, rather than assuming
1575@code{(class-of @var{obj})}. Therefore they allow you to apply the
1576``getter'' and ``setter'' closures of a slot definition in one class to
1577an instance of a different class.
1578
1579@deffn {primitive procedure} slot-exists-using-class? class obj slot-name
1580Return @code{#t} if @var{class} has a slot definition for a slot with
1581name @var{slot-name}, otherwise @code{#f}.
1582@end deffn
1583
1584@deffn {primitive procedure} slot-bound-using-class? class obj slot-name
1585Return @code{#t} if applying @code{slot-ref-using-class} to the same
1586arguments would call the generic function @code{slot-unbound}, otherwise
1587@code{#f}.
1588
1589@code{slot-bound-using-class?} calls the generic function
1590@code{slot-missing} if @var{class} does not have a slot definition for a
9320479a 1591slot called @var{slot-name} (@pxref{Accessing Slots,
62d7cba3
NJ
1592slot-missing}).
1593@end deffn
1594
1595@deffn {primitive procedure} slot-ref-using-class class obj slot-name
1596Apply the ``getter'' closure for the slot named @var{slot-name} in
1597@var{class} to @var{obj}, and return its result.
1598
1599@code{slot-ref-using-class} calls the generic function
1600@code{slot-missing} if @var{class} does not have a slot definition for a
9320479a 1601slot called @var{slot-name} (@pxref{Accessing Slots,
62d7cba3
NJ
1602slot-missing}).
1603
1604@code{slot-ref-using-class} calls the generic function
1605@code{slot-unbound} if the application of the ``getter'' closure to
9320479a 1606@var{obj} returns an unbound value (@pxref{Accessing Slots,
62d7cba3
NJ
1607slot-unbound}).
1608@end deffn
1609
1610@deffn {primitive procedure} slot-set-using-class! class obj slot-name value
1611Apply the ``setter'' closure for the slot named @var{slot-name} in
1612@var{class} to @var{obj} and @var{value}.
1613
1614@code{slot-set-using-class!} calls the generic function
1615@code{slot-missing} if @var{class} does not have a slot definition for a
9320479a 1616slot called @var{slot-name} (@pxref{Accessing Slots, slot-missing}).
62d7cba3
NJ
1617@end deffn
1618
62d7cba3
NJ
1619Slots whose allocation is per-class rather than per-instance can be
1620referenced and set without needing to specify any particular instance.
1621
1622@deffn procedure class-slot-ref class slot-name
1623Return the value of the slot named @var{slot-name} in class @var{class}.
1624The named slot must have @code{#:class} or @code{#:each-subclass}
1625allocation (@pxref{Slot Options,, allocation}).
1626
1627If there is no such slot with @code{#:class} or @code{#:each-subclass}
1628allocation, @code{class-slot-ref} calls the @code{slot-missing} generic
1629function with arguments @var{class} and @var{slot-name}. Otherwise, if
1630the slot value is unbound, @code{class-slot-ref} calls the
1631@code{slot-unbound} generic function, with the same arguments.
1632@end deffn
1633
1634@deffn procedure class-slot-set! class slot-name value
1635Set the value of the slot named @var{slot-name} in class @var{class} to
1636@var{value}. The named slot must have @code{#:class} or
1637@code{#:each-subclass} allocation (@pxref{Slot Options,, allocation}).
1638
1639If there is no such slot with @code{#:class} or @code{#:each-subclass}
1640allocation, @code{class-slot-ref} calls the @code{slot-missing} generic
1641function with arguments @var{class} and @var{slot-name}.
1642@end deffn
1643
9320479a
NJ
1644When a @code{slot-ref} or @code{slot-set!} call specifies a non-existent
1645slot name, or tries to reference a slot whose value is unbound, GOOPS
1646calls one of the following generic functions.
1647
1648@deffn generic slot-missing
1649@deffnx method slot-missing (class <class>) slot-name
1650@deffnx method slot-missing (class <class>) (object <object>) slot-name
1651@deffnx method slot-missing (class <class>) (object <object>) slot-name value
1652When an application attempts to reference or set a class or instance
1653slot by name, and the slot name is invalid for the specified @var{class}
1654or @var{object}, GOOPS calls the @code{slot-missing} generic function.
1655
1656The default methods all call @code{goops-error} with an appropriate
1657message.
1658@end deffn
1659
1660@deffn generic slot-unbound
1661@deffnx method slot-unbound (object <object>)
1662@deffnx method slot-unbound (class <class>) slot-name
1663@deffnx method slot-unbound (class <class>) (object <object>) slot-name
1664When an application attempts to reference a class or instance slot, and
1665the slot's value is unbound, GOOPS calls the @code{slot-unbound} generic
1666function.
1667
1668The default methods all call @code{goops-error} with an appropriate
1669message.
1670@end deffn
1671
62d7cba3 1672
12fe9fcf
NJ
1673@node GOOPS Error Handling
1674@section Error Handling
1675
1676The procedure @code{goops-error} is called to raise an appropriate error
1677by the default methods of the following generic functions:
1678
1679@itemize @bullet
1680@item
1681@code{slot-missing} (@pxref{Accessing Slots,, slot-missing})
1682
1683@item
1684@code{slot-unbound} (@pxref{Accessing Slots,, slot-unbound})
1685
1686@item
1687@code{no-method} (@pxref{Handling Invocation Errors,, no-method})
1688
1689@item
1690@code{no-applicable-method} (@pxref{Handling Invocation Errors,,
1691no-applicable-method})
1692
1693@item
1694@code{no-next-method} (@pxref{Handling Invocation Errors,,
1695no-next-method})
1696@end itemize
1697
1698If you customize these functions for particular classes or metaclasses,
1699you may still want to use @code{goops-error} to signal any error
1700conditions that you detect.
1701
1702@deffn procedure goops-error format-string . args
1703Raise an error with key @code{goops-error} and error message constructed
1704from @var{format-string} and @var{args}. Error message formatting is
1705as done by @code{scm-error}.
1706@end deffn
1707
1708
2cb8cf04
NJ
1709@node GOOPS Object Miscellany
1710@section GOOPS Object Miscellany
1711
1712Here we cover some points about GOOPS objects that aren't substantial
1713enough to merit sections on their own.
1714
1715@subheading Object Equality
1716
1717When GOOPS is loaded, @code{eqv?}, @code{equal?} and @code{=} become
1718generic functions, and you can define methods for them, specialized for
1719your own classes, so as to control what the various kinds of equality
1720mean for your classes.
1721
1722For example, the @code{assoc} procedure, for looking up an entry in an
1723alist, is specified as using @code{equal?} to determine when the car of
1724an entry in the alist is the same as the key parameter that @code{assoc}
1725is called with. Hence, if you had defined a new class, and wanted to
1726use instances of that class as the keys in an alist, you could define a
1727method for @code{equal?}, for your class, to control @code{assoc}'s
1728lookup precisely.
1729
1730@subheading Cloning Objects
1731
1732@deffn generic shallow-clone
1733@deffnx method shallow-clone (self <object>)
1734Return a ``shallow'' clone of @var{self}. The default method makes a
1735shallow clone by allocating a new instance and copying slot values from
1736self to the new instance. Each slot value is copied either as an
1737immediate value or by reference.
1738@end deffn
1739
1740@deffn generic deep-clone
1741@deffnx method deep-clone (self <object>)
1742Return a ``deep'' clone of @var{self}. The default method makes a deep
1743clone by allocating a new instance and copying or cloning slot values
1744from self to the new instance. If a slot value is an instance
1745(satisfies @code{instance?}), it is cloned by calling @code{deep-clone}
1746on that value. Other slot values are copied either as immediate values
1747or by reference.
1748@end deffn
1749
1750@subheading Write and Display
1751
1752@deffn {primitive generic} write object port
1753@deffnx {primitive generic} display object port
1754When GOOPS is loaded, @code{write} and @code{display} become generic
1755functions with special methods for printing
1756
1757@itemize @bullet
1758@item
1759objects - instances of the class @code{<object>}
1760
1761@item
1762foreign objects - instances of the class @code{<foreign-object>}
1763
1764@item
1765classes - instances of the class @code{<class>}
1766
1767@item
1768generic functions - instances of the class @code{<generic>}
1769
1770@item
1771methods - instances of the class @code{<method>}.
1772@end itemize
1773
1774@code{write} and @code{display} print non-GOOPS values in the same way
1775as the Guile primitive @code{write} and @code{display} functions.
1776@end deffn
1777
1778In addition to the cases mentioned, you can of course define
1779@code{write} and @code{display} methods for your own classes, to
1780customize how they are printed.
1781
1782
a9bf12c2
NJ
1783@node The Metaobject Protocol
1784@section The Metaobject Protocol
a0e07ba4 1785
0b452f2c
NJ
1786At this point, we've said about as much as can be said about GOOPS
1787without having to confront the idea of the metaobject protocol. There
1788are a couple more topics that could be discussed in isolation first ---
1789class redefinition, and changing the class of existing instances --- but
1790in practice developers using them will be advanced enough to want to
1791understand the metaobject protocol too, and will probably be using the
1792protocol to customize exactly what happens during these events.
1793
1794So let's plunge in. GOOPS is based on a ``metaobject protocol'' (aka
1795``MOP'') derived from the ones used in CLOS (the Common Lisp Object
1796System), tiny-clos (a small Scheme implementation of a subset of CLOS
1797functionality) and STKlos.
a0e07ba4 1798
a46f77f9
NJ
1799The MOP underlies many possible GOOPS customizations --- such as
1800defining an @code{initialize} method to customize the initialization of
1801instances of an application-defined class --- and an understanding of
1802the MOP makes it much easier to explain such customizations in a precise
1803way. And at a deeper level, understanding the MOP is a key part of
1804understanding GOOPS, and of taking full advantage of GOOPS' power, by
1805customizing the behaviour of GOOPS itself.
a0e07ba4 1806
a9bf12c2
NJ
1807@menu
1808* Metaobjects and the Metaobject Protocol::
a46f77f9 1809* Metaclasses::
a9bf12c2 1810* MOP Specification::
d9ff8506 1811* Instance Creation Protocol::
a46f77f9 1812* Class Definition Protocol::
58ad1de7 1813* Customizing Class Definition::
a9bf12c2 1814* Method Definition::
de6b3a5c 1815* Method Definition Internals::
eed4cc7b 1816* Generic Function Internals::
a9bf12c2
NJ
1817* Generic Function Invocation::
1818@end menu
1819
1820@node Metaobjects and the Metaobject Protocol
1821@subsection Metaobjects and the Metaobject Protocol
1822
5aaf0709
NJ
1823The building blocks of GOOPS are classes, slot definitions, instances,
1824generic functions and methods. A class is a grouping of inheritance
1825relations and slot definitions. An instance is an object with slots
1826that are allocated following the rules implied by its class's
a9bf12c2
NJ
1827superclasses and slot definitions. A generic function is a collection
1828of methods and rules for determining which of those methods to apply
1829when the generic function is invoked. A method is a procedure and a set
1830of specializers that specify the type of arguments to which the
1831procedure is applicable.
1832
1833Of these entities, GOOPS represents classes, generic functions and
1834methods as ``metaobjects''. In other words, the values in a GOOPS
1835program that describe classes, generic functions and methods, are
1836themselves instances (or ``objects'') of special GOOPS classes that
1837encapsulate the behaviour, respectively, of classes, generic functions,
1838and methods.
1839
1840(The other two entities are slot definitions and instances. Slot
1841definitions are not strictly instances, but every slot definition is
1842associated with a GOOPS class that specifies the behaviour of the slot
1843as regards accessibility and protection from garbage collection.
1844Instances are of course objects in the usual sense, and there is no
1845benefit from thinking of them as metaobjects.)
1846
a46f77f9 1847The ``metaobject protocol'' (or ``MOP'') is the specification of the
a9bf12c2
NJ
1848generic functions which determine the behaviour of these metaobjects and
1849the circumstances in which these generic functions are invoked.
1850
1851For a concrete example of what this means, consider how GOOPS calculates
1852the set of slots for a class that is being defined using
1853@code{define-class}. The desired set of slots is the union of the new
1854class's direct slots and the slots of all its superclasses. But
1855@code{define-class} itself does not perform this calculation. Instead,
1856there is a method of the @code{initialize} generic function that is
1857specialized for instances of type @code{<class>}, and it is this method
1858that performs the slot calculation.
1859
1860@code{initialize} is a generic function which GOOPS calls whenever a new
1861instance is created, immediately after allocating memory for a new
1862instance, in order to initialize the new instance's slots. The sequence
1863of steps is as follows.
1864
1865@itemize @bullet
1866@item
1867@code{define-class} uses @code{make} to make a new instance of the
5aaf0709
NJ
1868@code{<class>} class, passing as initialization arguments the
1869superclasses, slot definitions and class options that were specified in
1870the @code{define-class} form.
a9bf12c2
NJ
1871
1872@item
a46f77f9 1873@code{make} allocates memory for the new instance, and invokes the
a9bf12c2
NJ
1874@code{initialize} generic function to initialize the new instance's
1875slots.
1876
1877@item
1878The @code{initialize} generic function applies the method that is
1879specialized for instances of type @code{<class>}, and this method
1880performs the slot calculation.
1881@end itemize
1882
1883In other words, rather than being hardcoded in @code{define-class}, the
a46f77f9
NJ
1884default behaviour of class definition is encapsulated by generic
1885function methods that are specialized for the class @code{<class>}.
a9bf12c2
NJ
1886
1887It is possible to create a new class that inherits from @code{<class>},
1888which is called a ``metaclass'', and to write a new @code{initialize}
1889method that is specialized for instances of the new metaclass. Then, if
1890the @code{define-class} form includes a @code{#:metaclass} class option
1891whose value is the new metaclass, the class that is defined by the
1892@code{define-class} form will be an instance of the new metaclass rather
1893than of the default @code{<class>}, and will be defined in accordance
1894with the new @code{initialize} method. Thus the default slot
1895calculation, as well as any other aspect of the new class's relationship
1896with its superclasses, can be modified or overridden.
1897
1898In a similar way, the behaviour of generic functions can be modified or
1899overridden by creating a new class that inherits from the standard
1900generic function class @code{<generic>}, writing appropriate methods
1901that are specialized to the new class, and creating new generic
1902functions that are instances of the new class.
1903
1904The same is true for method metaobjects. And the same basic mechanism
1905allows the application class author to write an @code{initialize} method
1906that is specialized to their application class, to initialize instances
1907of that class.
1908
1909Such is the power of the MOP. Note that @code{initialize} is just one
1910of a large number of generic functions that can be customized to modify
1911the behaviour of application objects and classes and of GOOPS itself.
5aaf0709
NJ
1912Each following section covers a particular area of GOOPS functionality,
1913and describes the generic functions that are relevant for customization
1914of that area.
1915
a46f77f9
NJ
1916@node Metaclasses
1917@subsection Metaclasses
a9bf12c2
NJ
1918
1919A @dfn{metaclass} is the class of an object which represents a GOOPS
1920class. Put more succinctly, a metaclass is a class's class.
1921
1922Most GOOPS classes have the metaclass @code{<class>} and, by default,
1923any new class that is created using @code{define-class} has the
1924metaclass @code{<class>}.
1925
1926But what does this really mean? To find out, let's look in more detail
1927at what happens when a new class is created using @code{define-class}:
1928
1929@example
1930(define-class <my-class> (<object>) . slots)
1931@end example
1932
a46f77f9
NJ
1933@noindent
1934Guile expands this to something like:
a9bf12c2
NJ
1935
1936@example
1937(define <my-class> (class (<object>) . slots))
1938@end example
1939
a46f77f9
NJ
1940@noindent
1941which in turn expands to:
a9bf12c2
NJ
1942
1943@example
1944(define <my-class>
1945 (make <class> #:supers (list <object>) #:slots slots))
1946@end example
1947
a46f77f9
NJ
1948As this expansion makes clear, the resulting value of @code{<my-class>}
1949is an instance of the class @code{<class>} with slot values specifying
1950the superclasses and slot definitions for the class @code{<my-class>}.
1951(@code{#:supers} and @code{#:slots} are initialization keywords for the
1952@code{dsupers} and @code{dslots} slots of the @code{<class>} class.)
a9bf12c2 1953
a46f77f9
NJ
1954Now suppose that you want to define a new class with a metaclass other
1955than the default @code{<class>}. This is done by writing:
a9bf12c2
NJ
1956
1957@example
1958(define-class <my-class2> (<object>)
1959 slot @dots{}
1960 #:metaclass <my-metaclass>)
1961@end example
1962
a46f77f9
NJ
1963@noindent
1964and Guile expands @emph{this} to something like:
a9bf12c2
NJ
1965
1966@example
1967(define <my-class2>
1968 (make <my-metaclass> #:supers (list <object>) #:slots slots))
1969@end example
1970
1971In this case, the value of @code{<my-class2>} is an instance of the more
1972specialized class @code{<my-metaclass>}. Note that
1973@code{<my-metaclass>} itself must previously have been defined as a
1974subclass of @code{<class>}. For a full discussion of when and how it is
1975useful to define new metaclasses, see @ref{MOP Specification}.
1976
1977Now let's make an instance of @code{<my-class2>}:
1978
1979@example
1980(define my-object (make <my-class2> ...))
1981@end example
1982
1983All of the following statements are correct expressions of the
1984relationships between @code{my-object}, @code{<my-class2>},
1985@code{<my-metaclass>} and @code{<class>}.
1986
1987@itemize @bullet
1988@item
1989@code{my-object} is an instance of the class @code{<my-class2>}.
1990
1991@item
1992@code{<my-class2>} is an instance of the class @code{<my-metaclass>}.
1993
1994@item
1995@code{<my-metaclass>} is an instance of the class @code{<class>}.
1996
1997@item
1998The class of @code{my-object} is @code{<my-class2>}.
1999
a9bf12c2
NJ
2000@item
2001The class of @code{<my-class2>} is @code{<my-metaclass>}.
2002
a9bf12c2
NJ
2003@item
2004The class of @code{<my-metaclass>} is @code{<class>}.
a9bf12c2
NJ
2005@end itemize
2006
a9bf12c2
NJ
2007
2008@node MOP Specification
2009@subsection MOP Specification
2010
2011The aim of the MOP specification in this chapter is to specify all the
2012customizable generic function invocations that can be made by the standard
2013GOOPS syntax, procedures and methods, and to explain the protocol for
2014customizing such invocations.
2015
a46f77f9
NJ
2016A generic function invocation is customizable if the types of the
2017arguments to which it is applied are not completely determined by the
2018lexical context in which the invocation appears. For example, the
2019@code{(initialize @var{instance} @var{initargs})} invocation in the
2020default @code{make-instance} method is customizable, because the type of
2021the @code{@var{instance}} argument is determined by the class that was
2022passed to @code{make-instance}.
a0e07ba4 2023
a46f77f9
NJ
2024(Whereas --- to give a counter-example --- the @code{(make <generic>
2025#:name ',name)} invocation in @code{define-generic} is not customizable,
2026because all of its arguments have lexically determined types.)
a0e07ba4
NJ
2027
2028When using this rule to decide whether a given generic function invocation
2029is customizable, we ignore arguments that are expected to be handled in
2030method definitions as a single ``rest'' list argument.
2031
2032For each customizable generic function invocation, the @dfn{invocation
2033protocol} is explained by specifying
2034
2035@itemize @bullet
2036@item
2037what, conceptually, the applied method is intended to do
2038
2039@item
2040what assumptions, if any, the caller makes about the applied method's side
2041effects
2042
2043@item
2044what the caller expects to get as the applied method's return value.
2045@end itemize
2046
d9ff8506
NJ
2047
2048@node Instance Creation Protocol
2049@subsection Instance Creation Protocol
2050
2051@code{make <class> . @var{initargs}} (method)
2052
2053@itemize @bullet
2054@item
2055@code{allocate-instance @var{class} @var{initargs}} (generic)
2056
2057The applied @code{allocate-instance} method should allocate storage for
2058a new instance of class @var{class} and return the uninitialized instance.
2059
2060@item
2061@code{initialize @var{instance} @var{initargs}} (generic)
2062
2063@var{instance} is the uninitialized instance returned by
2064@code{allocate-instance}. The applied method should initialize the new
2065instance in whatever sense is appropriate for its class. The method's
2066return value is ignored.
2067@end itemize
2068
2069@code{make} itself is a generic function. Hence the @code{make}
2070invocation itself can be customized in the case where the new instance's
2071metaclass is more specialized than the default @code{<class>}, by
2072defining a @code{make} method that is specialized to that metaclass.
2073
2074Normally, however, the method for classes with metaclass @code{<class>}
2075will be applied. This method calls two generic functions:
2076
2077@itemize @bullet
2078@item
2079(allocate-instance @var{class} . @var{initargs})
2080
2081@item
2082(initialize @var{instance} . @var{initargs})
2083@end itemize
2084
2085@code{allocate-instance} allocates storage for and returns the new
2086instance, uninitialized. You might customize @code{allocate-instance},
2087for example, if you wanted to provide a GOOPS wrapper around some other
2088object programming system.
2089
2090To do this, you would create a specialized metaclass, which would act as
2091the metaclass for all classes and instances from the other system. Then
2092define an @code{allocate-instance} method, specialized to that
2093metaclass, which calls a Guile primitive C function (or FFI code), which
2094in turn allocates the new instance using the interface of the other
2095object system.
2096
2097In this case, for a complete system, you would also need to customize a
2098number of other generic functions like @code{make} and
2099@code{initialize}, so that GOOPS knows how to make classes from the
2100other system, access instance slots, and so on.
2101
2102@code{initialize} initializes the instance that is returned by
2103@code{allocate-instance}. The standard GOOPS methods perform
2104initializations appropriate to the instance class.
2105
2106@itemize @bullet
2107@item
2108At the least specialized level, the method for instances of type
2109@code{<object>} performs internal GOOPS instance initialization, and
2110initializes the instance's slots according to the slot definitions and
2111any slot initialization keywords that appear in @var{initargs}.
2112
2113@item
2114The method for instances of type @code{<class>} calls
2115@code{(next-method)}, then performs the class initializations described
2116in @ref{Class Definition Protocol}.
2117
2118@item
2119and so on for generic functions, methods, operator classes @dots{}
2120@end itemize
2121
2122Similarly, you can customize the initialization of instances of any
2123application-defined class by defining an @code{initialize} method
2124specialized to that class.
2125
2126Imagine a class whose instances' slots need to be initialized at
2127instance creation time by querying a database. Although it might be
2128possible to achieve this a combination of @code{#:init-thunk} keywords
2129and closures in the slot definitions, it may be neater to write an
2130@code{initialize} method for the class that queries the database once
2131and initializes all the dependent slot values according to the results.
2132
2133
a46f77f9
NJ
2134@node Class Definition Protocol
2135@subsection Class Definition Protocol
a0e07ba4 2136
476a51eb
NJ
2137Here is a summary diagram of the syntax, procedures and generic
2138functions that may be involved in class definition.
2139
2140@noindent
2141@code{define-class} (syntax)
2142
2143@itemize @bullet
2144@item
2145@code{class} (syntax)
2146
2147@itemize @bullet
2148@item
2149@code{make-class} (procedure)
2150
2151@itemize @bullet
2152@item
2153@code{ensure-metaclass} (procedure)
2154
476a51eb
NJ
2155@item
2156@code{make @var{metaclass} @dots{}} (generic)
2157
2158@itemize @bullet
2159@item
2160@code{allocate-instance} (generic)
2161
2162@item
2163@code{initialize} (generic)
2164
2165@itemize @bullet
2166@item
2167@code{compute-cpl} (generic)
2168
2169@itemize @bullet
2170@item
2171@code{compute-std-cpl} (procedure)
2172@end itemize
2173
2174@item
2175@code{compute-slots} (generic)
2176
2177@item
2178@code{compute-get-n-set} (generic)
2179
2180@item
2181@code{compute-getter-method} (generic)
2182
2183@item
2184@code{compute-setter-method} (generic)
2185@end itemize
2186@end itemize
2187@end itemize
2188@end itemize
2189
2190@item
2191@code{class-redefinition} (generic)
2192
2193@itemize @bullet
2194@item
2195@code{remove-class-accessors} (generic)
2196
2197@item
2198@code{update-direct-method!} (generic)
2199
2200@item
2201@code{update-direct-subclass!} (generic)
2202@end itemize
2203@end itemize
2204
2205Wherever a step above is marked as ``generic'', it can be customized,
2206and the detail shown below it is only ``correct'' insofar as it
2207describes what the default method of that generic function does. For
2208example, if you write an @code{initialize} method, for some metaclass,
2209that does not call @code{next-method} and does not call
2210@code{compute-cpl}, then @code{compute-cpl} will not be called when a
2211class is defined with that metaclass.
2212
d9ff8506
NJ
2213A @code{(define-class ...)} form (@pxref{Class Definition}) expands to
2214an expression which
58ad1de7
NJ
2215
2216@itemize @bullet
2217@item
2218checks that it is being evaluated only at top level
2219
2220@item
2221defines any accessors that are implied by the @var{slot-definition}s
2222
2223@item
d9ff8506 2224uses @code{class} to create the new class
58ad1de7
NJ
2225
2226@item
2227checks for a previous class definition for @var{name} and, if found,
2228handles the redefinition by invoking @code{class-redefinition}
2229(@pxref{Redefining a Class}).
2230@end itemize
2231
2232@deffn syntax class name (super @dots{}) slot-definition @dots{} . options
2233Return a newly created class that inherits from @var{super}s, with
2234direct slots defined by @var{slot-definition}s and class options
2235@var{options}. For the format of @var{slot-definition}s and
f60a8353 2236@var{options}, see @ref{Class Definition,, define-class}.
58ad1de7
NJ
2237@end deffn
2238
2239@noindent @code{class} expands to an expression which
2240
2241@itemize @bullet
2242@item
2243processes the class and slot definition options to check that they are
2244well-formed, to convert the @code{#:init-form} option to an
2245@code{#:init-thunk} option, to supply a default environment parameter
2246(the current top-level environment) and to evaluate all the bits that
2247need to be evaluated
2248
2249@item
2250calls @code{make-class} to create the class with the processed and
2251evaluated parameters.
2252@end itemize
2253
2254@deffn procedure make-class supers slots . options
2255Return a newly created class that inherits from @var{supers}, with
2256direct slots defined by @var{slots} and class options @var{options}.
f60a8353
NJ
2257For the format of @var{slots} and @var{options}, see @ref{Class
2258Definition,, define-class}, except note that for @code{make-class},
58ad1de7
NJ
2259@var{slots} and @var{options} are separate list parameters: @var{slots}
2260here is a list of slot definitions.
2261@end deffn
2262
2263@noindent @code{make-class}
2264
2265@itemize @bullet
2266@item
2267adds @code{<object>} to the @var{supers} list if @var{supers} is empty
2268or if none of the classes in @var{supers} have @code{<object>} in their
2269class precedence list
2270
2271@item
2272defaults the @code{#:environment}, @code{#:name} and @code{#:metaclass}
2273options, if they are not specified by @var{options}, to the current
2274top-level environment, the unbound value, and @code{(ensure-metaclass
d9ff8506 2275@var{supers})} respectively
58ad1de7
NJ
2276
2277@item
2278checks for duplicate classes in @var{supers} and duplicate slot names in
2279@var{slots}, and signals an error if there are any duplicates
2280
2281@item
2282calls @code{make}, passing the metaclass as the first parameter and all
2283other parameters as option keywords with values.
2284@end itemize
2285
2286@deffn procedure ensure-metaclass supers env
2287Return a metaclass suitable for a class that inherits from the list of
2288classes in @var{supers}. The returned metaclass is the union by
2289inheritance of the metaclasses of the classes in @var{supers}.
2290
2291In the simplest case, where all the @var{supers} are straightforward
2292classes with metaclass @code{<class>}, the returned metaclass is just
2293@code{<class>}.
2294
2295For a more complex example, suppose that @var{supers} contained one
2296class with metaclass @code{<operator-class>} and one with metaclass
2297@code{<foreign-object-class>}. Then the returned metaclass would be a
2298class that inherits from both @code{<operator-class>} and
2299@code{<foreign-object-class>}.
2300
2301If @var{supers} is the empty list, @code{ensure-metaclass} returns the
2302default GOOPS metaclass @code{<class>}.
2303
2304GOOPS keeps a list of the metaclasses created by
2305@code{ensure-metaclass}, so that each required type of metaclass only
2306has to be created once.
2307
2308The @code{env} parameter is ignored.
2309@end deffn
2310
d9ff8506
NJ
2311@deffn generic make metaclass @dots{}
2312@var{metaclass} is the metaclass of the class being defined, either
2313taken from the @code{#:metaclass} class option or computed by
2314@code{ensure-metaclass}. The applied method must create and return the
2315fully initialized class metaobject for the new class definition.
58ad1de7
NJ
2316@end deffn
2317
d9ff8506
NJ
2318The @code{(make @var{metaclass} @dots{})} invocation is a particular
2319case of the instance creation protocol covered in the previous section.
2320It will create an class metaobject with metaclass @var{metaclass}. By
2321default, this metaobject will be initialized by the @code{initialize}
2322method that is specialized for instances of type @code{<class>}.
58ad1de7 2323
d9ff8506
NJ
2324The @code{initialize} method for classes (signature @code{(initialize
2325<class> initargs)}) calls the following generic functions.
58ad1de7
NJ
2326
2327@itemize @bullet
2328@item
d9ff8506 2329@code{compute-cpl @var{class}} (generic)
58ad1de7 2330
d9ff8506
NJ
2331The applied method should compute and return the class precedence list
2332for @var{class} as a list of class metaobjects. When @code{compute-cpl}
2333is called, the following @var{class} metaobject slots have all been
2334initialized: @code{name}, @code{direct-supers}, @code{direct-slots},
2335@code{direct-subclasses} (empty), @code{direct-methods}. The value
2336returned by @code{compute-cpl} will be stored in the @code{cpl} slot.
58ad1de7 2337
58ad1de7 2338@item
d9ff8506 2339@code{compute-slots @var{class}} (generic)
58ad1de7 2340
d9ff8506
NJ
2341The applied method should compute and return the slots (union of direct
2342and inherited) for @var{class} as a list of slot definitions. When
2343@code{compute-slots} is called, all the @var{class} metaobject slots
2344mentioned for @code{compute-cpl} have been initialized, plus the
2345following: @code{cpl}, @code{redefined} (@code{#f}), @code{environment}.
2346The value returned by @code{compute-slots} will be stored in the
2347@code{slots} slot.
58ad1de7
NJ
2348
2349@item
d9ff8506
NJ
2350@code{compute-get-n-set @var{class} @var{slot-def}} (generic)
2351
2352@code{initialize} calls @code{compute-get-n-set} for each slot computed
2353by @code{compute-slots}. The applied method should compute and return a
2354pair of closures that, respectively, get and set the value of the specified
2355slot. The get closure should have arity 1 and expect a single argument
2356that is the instance whose slot value is to be retrieved. The set closure
2357should have arity 2 and expect two arguments, where the first argument is
2358the instance whose slot value is to be set and the second argument is the
2359new value for that slot. The closures should be returned in a two element
2360list: @code{(list @var{get} @var{set})}.
2361
2362The closures returned by @code{compute-get-n-set} are stored as part of
2363the value of the @var{class} metaobject's @code{getters-n-setters} slot.
2364Specifically, the value of this slot is a list with the same number of
2365elements as there are slots in the class, and each element looks either like
2366
2367@example
2368@code{(@var{slot-name-symbol} @var{init-function} . @var{index})}
2369@end example
2370
2371or like
2372
2373@example
2374@code{(@var{slot-name-symbol} @var{init-function} @var{get} @var{set})}
2375@end example
2376
2377Where the get and set closures are replaced by @var{index}, the slot is
2378an instance slot and @var{index} is the slot's index in the underlying
2379structure: GOOPS knows how to get and set the value of such slots and so
2380does not need specially constructed get and set closures. Otherwise,
2381@var{get} and @var{set} are the closures returned by @code{compute-get-n-set}.
2382
2383The structure of the @code{getters-n-setters} slot value is important when
2384understanding the next customizable generic functions that @code{initialize}
2385calls@dots{}
58ad1de7
NJ
2386
2387@item
d9ff8506
NJ
2388@code{compute-getter-method @var{class} @var{gns}} (generic)
2389
2390@code{initialize} calls @code{compute-getter-method} for each of the class's
2391slots (as determined by @code{compute-slots}) that includes a
2392@code{#:getter} or @code{#:accessor} slot option. @var{gns} is the
2393element of the @var{class} metaobject's @code{getters-n-setters} slot that
2394specifies how the slot in question is referenced and set, as described
2395above under @code{compute-get-n-set}. The applied method should create
2396and return a method that is specialized for instances of type @var{class}
2397and uses the get closure to retrieve the slot's value. [ *fixme Need
2398to insert something here about checking that the value is not unbound. ]
2399@code{initialize} uses @code{add-method!} to add the returned method to
2400the generic function named by the slot definition's @code{#:getter} or
2401@code{#:accessor} option.
58ad1de7
NJ
2402
2403@item
d9ff8506
NJ
2404@code{compute-setter-method @var{class} @var{gns}} (generic)
2405
2406@code{compute-setter-method} is invoked with the same arguments as
2407@code{compute-getter-method}, for each of the class's slots that includes
2408a @code{#:setter} or @code{#:accessor} slot option. The applied method
2409should create and return a method that is specialized for instances of
2410type @var{class} and uses the set closure to set the slot's value.
2411@code{initialize} then uses @code{add-method!} to add the returned method
2412to the generic function named by the slot definition's @code{#:setter}
2413or @code{#:accessor} option.
58ad1de7
NJ
2414@end itemize
2415
d9ff8506
NJ
2416@node Customizing Class Definition
2417@subsection Customizing Class Definition
2418
58ad1de7
NJ
2419If the metaclass of the new class is something more specialized than the
2420default @code{<class>}, then the type of @var{class} in the calls above
2421is more specialized than @code{<class>}, and hence it becomes possible
2422to define generic function methods, specialized for the new class's
2423metaclass, that can modify or override the default behaviour of
2424@code{initialize}, @code{compute-cpl} or @code{compute-get-n-set}.
2425
2426@code{compute-cpl} computes the class precedence list (``CPL'') for the
68f4fee1 2427new class (@pxref{Class Precedence List}), and returns it as a list of
58ad1de7
NJ
2428class objects. The CPL is important because it defines a superclass
2429ordering that is used, when a generic function is invoked upon an
2430instance of the class, to decide which of the available generic function
2431methods is the most specific. Hence @code{compute-cpl} could be
2432customized in order to modify the CPL ordering algorithm for all classes
2433with a special metaclass.
2434
2435The default CPL algorithm is encapsulated by the @code{compute-std-cpl}
d9ff8506 2436procedure, which is called by the default @code{compute-cpl} method.
58ad1de7
NJ
2437
2438@deffn procedure compute-std-cpl class
2439Compute and return the class precedence list for @var{class} according
68f4fee1 2440to the algorithm described in @ref{Class Precedence List}.
58ad1de7
NJ
2441@end deffn
2442
2443@code{compute-slots} computes and returns a list of all slot definitions
2444for the new class. By default, this list includes the direct slot
2445definitions from the @code{define-class} form, plus the slot definitions
2446that are inherited from the new class's superclasses. The default
2447@code{compute-slots} method uses the CPL computed by @code{compute-cpl}
2448to calculate this union of slot definitions, with the rule that slots
2449inherited from superclasses are shadowed by direct slots with the same
2450name. One possible reason for customizing @code{compute-slots} would be
2451to implement an alternative resolution strategy for slot name conflicts.
2452
2453@code{compute-get-n-set} computes the low-level closures that will be
2454used to get and set the value of a particular slot, and returns them in
2455a list with two elements.
2456
2457The closures returned depend on how storage for that slot is allocated.
2458The standard @code{compute-get-n-set} method, specialized for classes of
2459type @code{<class>}, handles the standard GOOPS values for the
2460@code{#:allocation} slot option (@pxref{Slot Options,, allocation}). By
2461defining a new @code{compute-get-n-set} method for a more specialized
2462metaclass, it is possible to support new types of slot allocation.
2463
2464Suppose you wanted to create a large number of instances of some class
2465with a slot that should be shared between some but not all instances of
2466that class - say every 10 instances should share the same slot storage.
2467The following example shows how to implement and use a new type of slot
2468allocation to do this.
2469
2470@example
2471(define-class <batched-allocation-metaclass> (<class>))
2472
2473(let ((batch-allocation-count 0)
2474 (batch-get-n-set #f))
2475 (define-method (compute-get-n-set
2476 (class <batched-allocation-metaclass>) s)
2477 (case (slot-definition-allocation s)
2478 ((#:batched)
2479 ;; If we've already used the same slot storage for 10 instances,
2480 ;; reset variables.
2481 (if (= batch-allocation-count 10)
2482 (begin
2483 (set! batch-allocation-count 0)
2484 (set! batch-get-n-set #f)))
2485 ;; If we don't have a current pair of get and set closures,
2486 ;; create one. make-closure-variable returns a pair of closures
2487 ;; around a single Scheme variable - see goops.scm for details.
2488 (or batch-get-n-set
2489 (set! batch-get-n-set (make-closure-variable)))
2490 ;; Increment the batch allocation count.
2491 (set! batch-allocation-count (+ batch-allocation-count 1))
2492 batch-get-n-set)
2493
2494 ;; Call next-method to handle standard allocation types.
2495 (else (next-method)))))
2496
2497(define-class <class-using-batched-slot> ()
2498 ...
2499 (c #:allocation #:batched)
2500 ...
2501 #:metaclass <batched-allocation-metaclass>)
2502@end example
2503
2504The usage of @code{compute-getter-method} and @code{compute-setter-method}
d9ff8506 2505is described in @ref{Class Definition Protocol}.
58ad1de7
NJ
2506
2507@code{compute-cpl} and @code{compute-get-n-set} are called by the
2508standard @code{initialize} method for classes whose metaclass is
2509@code{<class>}. But @code{initialize} itself can also be modified, by
2510defining an @code{initialize} method specialized to the new class's
2511metaclass. Such a method could complete override the standard
2512behaviour, by not calling @code{(next-method)} at all, but more
2513typically it would perform additional class initialization steps before
2514and/or after calling @code{(next-method)} for the standard behaviour.
2515
9e57815d 2516
a0e07ba4 2517@node Method Definition
eb12b401 2518@subsection Method Definition
a0e07ba4
NJ
2519
2520@code{define-method} (syntax)
2521
2522@itemize @bullet
2523@item
2524@code{add-method! @var{target} @var{method}} (generic)
2525
2526@code{define-method} invokes the @code{add-method!} generic function to
2527handle adding the new method to a variety of possible targets. GOOPS
2528includes methods to handle @var{target} as
2529
2530@itemize @bullet
2531@item
2532a generic function (the most common case)
2533
2534@item
2535a procedure
2536
2537@item
eed4cc7b 2538a primitive generic (@pxref{Extending Primitives})
a0e07ba4
NJ
2539@end itemize
2540
2541By defining further methods for @code{add-method!}, you can
2542theoretically handle adding methods to further types of target.
2543@end itemize
2544
de6b3a5c
NJ
2545@node Method Definition Internals
2546@subsection Method Definition Internals
2547
2548@code{define-method}
2549
2550@itemize @bullet
2551@item
2552checks the form of the first parameter, and applies the following steps
2553to the accessor's setter if it has the @code{(setter @dots{})} form
2554
2555@item
2556interpolates a call to @code{define-generic} or @code{define-accessor}
2557if a generic function is not already defined with the supplied name
2558
2559@item
2560calls @code{method} with the @var{parameter}s and @var{body}, to make a
2561new method instance
2562
2563@item
2564calls @code{add-method!} to add this method to the relevant generic
2565function.
2566@end itemize
2567
2568@deffn syntax method (parameter @dots{}) . body
2569Make a method whose specializers are defined by the classes in
2570@var{parameter}s and whose procedure definition is constructed from the
2571@var{parameter} symbols and @var{body} forms.
2572
2573The @var{parameter} and @var{body} parameters should be as for
68f4fee1 2574@code{define-method} (@pxref{Methods and Generic Functions,,
de6b3a5c
NJ
2575define-method}).
2576@end deffn
2577
2578@code{method}
2579
2580@itemize @bullet
2581@item
2582extracts formals and specializing classes from the @var{parameter}s,
2583defaulting the class for unspecialized parameters to @code{<top>}
2584
2585@item
2586creates a closure using the formals and the @var{body} forms
2587
2588@item
2589calls @code{make} with metaclass @code{<method>} and the specializers
2590and closure using the @code{#:specializers} and @code{#:procedure}
2591keywords.
2592@end itemize
2593
2594@deffn procedure make-method specializers procedure
2595Make a method using @var{specializers} and @var{procedure}.
2596
2597@var{specializers} should be a list of classes that specifies the
2598parameter combinations to which this method will be applicable.
2599
2600@var{procedure} should be the closure that will applied to the generic
2601function parameters when this method is invoked.
2602@end deffn
2603
2604@code{make-method} is a simple wrapper around @code{make} with metaclass
2605@code{<method>}.
2606
2607@deffn generic add-method! target method
2608Generic function for adding method @var{method} to @var{target}.
2609@end deffn
2610
2611@deffn method add-method! (generic <generic>) (method <method>)
2612Add method @var{method} to the generic function @var{generic}.
2613@end deffn
2614
2615@deffn method add-method! (proc <procedure>) (method <method>)
2616If @var{proc} is a procedure with generic capability (@pxref{Extending
2617Primitives,, generic-capability?}), upgrade it to a primitive generic
2618and add @var{method} to its generic function definition.
2619@end deffn
2620
2621@deffn method add-method! (pg <primitive-generic>) (method <method>)
2622Add method @var{method} to the generic function definition of @var{pg}.
2623
2624Implementation: @code{(add-method! (primitive-generic-generic pg) method)}.
2625@end deffn
2626
2627@deffn method add-method! (whatever <top>) (method <method>)
2628Raise an error indicating that @var{whatever} is not a valid generic
2629function.
2630@end deffn
2631
eed4cc7b
NJ
2632@node Generic Function Internals
2633@subsection Generic Function Internals
2634
2635@code{define-generic} calls @code{ensure-generic} to upgrade a
2636pre-existing procedure value, or @code{make} with metaclass
2637@code{<generic>} to create a new generic function.
2638
2639@code{define-accessor} calls @code{ensure-accessor} to upgrade a
2640pre-existing procedure value, or @code{make-accessor} to create a new
2641accessor.
2642
2643@deffn procedure ensure-generic old-definition [name]
2644Return a generic function with name @var{name}, if possible by using or
2645upgrading @var{old-definition}. If unspecified, @var{name} defaults to
2646@code{#f}.
2647
2648If @var{old-definition} is already a generic function, it is returned
2649unchanged.
2650
2651If @var{old-definition} is a Scheme procedure or procedure-with-setter,
2652@code{ensure-generic} returns a new generic function that uses
2653@var{old-definition} for its default procedure and setter.
2654
2655Otherwise @code{ensure-generic} returns a new generic function with no
2656defaults and no methods.
2657@end deffn
2658
2659@deffn procedure make-generic [name]
2660Return a new generic function with name @code{(car @var{name})}. If
2661unspecified, @var{name} defaults to @code{#f}.
2662@end deffn
2663
2664@code{ensure-generic} calls @code{make} with metaclasses
2665@code{<generic>} and @code{<generic-with-setter>}, depending on the
2666previous value of the variable that it is trying to upgrade.
2667
2668@code{make-generic} is a simple wrapper for @code{make} with metaclass
2669@code{<generic>}.
2670
2671@deffn procedure ensure-accessor proc [name]
2672Return an accessor with name @var{name}, if possible by using or
2673upgrading @var{proc}. If unspecified, @var{name} defaults to @code{#f}.
2674
2675If @var{proc} is already an accessor, it is returned unchanged.
2676
2677If @var{proc} is a Scheme procedure, procedure-with-setter or generic
2678function, @code{ensure-accessor} returns an accessor that reuses the
2679reusable elements of @var{proc}.
2680
2681Otherwise @code{ensure-accessor} returns a new accessor with no defaults
2682and no methods.
2683@end deffn
2684
2685@deffn procedure make-accessor [name]
2686Return a new accessor with name @code{(car @var{name})}. If
2687unspecified, @var{name} defaults to @code{#f}.
2688@end deffn
2689
2690@code{ensure-accessor} calls @code{make} with
2691metaclass @code{<generic-with-setter>}, as well as calls to
2692@code{ensure-generic}, @code{make-accessor} and (tail recursively)
2693@code{ensure-accessor}.
2694
2695@code{make-accessor} calls @code{make} twice, first
2696with metaclass @code{<generic>} to create a generic function for the
2697setter, then with metaclass @code{<generic-with-setter>} to create the
2698accessor, passing the setter generic function as the value of the
2699@code{#:setter} keyword.
2700
a0e07ba4 2701@node Generic Function Invocation
eb12b401 2702@subsection Generic Function Invocation
a0e07ba4
NJ
2703
2704[ *fixme* Description required here. ]
2705
2706@code{apply-generic}
2707
2708@itemize @bullet
2709@item
2710@code{no-method}
2711
2712@item
2713@code{compute-applicable-methods}
2714
2715@item
2716@code{sort-applicable-methods}
2717
2718@item
2719@code{apply-methods}
2720
2721@item
2722@code{no-applicable-method}
2723@end itemize
2724
2725@code{sort-applicable-methods}
2726
2727@itemize @bullet
2728@item
2729@code{method-more-specific?}
2730@end itemize
2731
2732@code{apply-methods}
2733
2734@itemize @bullet
2735@item
2736@code{apply-method}
2737@end itemize
2738
2739@code{next-method}
2740
2741@itemize @bullet
2742@item
2743@code{no-next-method}
2744@end itemize
0b452f2c
NJ
2745
2746
0b452f2c
NJ
2747@node Redefining a Class
2748@section Redefining a Class
2749
2750Suppose that a class @code{<my-class>} is defined using @code{define-class}
2751(@pxref{Class Definition,, define-class}), with slots that have
2752accessor functions, and that an application has created several instances
2753of @code{<my-class>} using @code{make} (@pxref{Instance Creation,,
2754make}). What then happens if @code{<my-class>} is redefined by calling
2755@code{define-class} again?
2756
2757@menu
2758* Default Class Redefinition Behaviour::
2759* Customizing Class Redefinition::
2760@end menu
2761
2762@node Default Class Redefinition Behaviour
2763@subsection Default Class Redefinition Behaviour
2764
2765GOOPS' default answer to this question is as follows.
2766
2767@itemize @bullet
2768@item
2769All existing direct instances of @code{<my-class>} are converted to be
2770instances of the new class. This is achieved by preserving the values
2771of slots that exist in both the old and new definitions, and
2772initializing the values of new slots in the usual way (@pxref{Instance
2773Creation,, make}).
2774
2775@item
2776All existing subclasses of @code{<my-class>} are redefined, as though
2777the @code{define-class} expressions that defined them were re-evaluated
2778following the redefinition of @code{<my-class>}, and the class
2779redefinition process described here is applied recursively to the
2780redefined subclasses.
2781
2782@item
2783Once all of its instances and subclasses have been updated, the class
2784metaobject previously bound to the variable @code{<my-class>} is no
2785longer needed and so can be allowed to be garbage collected.
2786@end itemize
2787
2788To keep things tidy, GOOPS also needs to do a little housekeeping on
2789methods that are associated with the redefined class.
2790
2791@itemize @bullet
2792@item
2793Slot accessor methods for slots in the old definition should be removed
2794from their generic functions. They will be replaced by accessor methods
2795for the slots of the new class definition.
2796
2797@item
2798Any generic function method that uses the old @code{<my-class>} metaobject
2799as one of its formal parameter specializers must be updated to refer to
2800the new @code{<my-class>} metaobject. (Whenever a new generic function
2801method is defined, @code{define-method} adds the method to a list stored
2802in the class metaobject for each class used as a formal parameter
2803specializer, so it is easy to identify all the methods that must be
2804updated when a class is redefined.)
2805@end itemize
2806
2807If this class redefinition strategy strikes you as rather counter-intuitive,
2808bear in mind that it is derived from similar behaviour in other object
2809systems such as CLOS, and that experience in those systems has shown it to be
2810very useful in practice.
2811
2812Also bear in mind that, like most of GOOPS' default behaviour, it can
2813be customized@dots{}
2814
2815@node Customizing Class Redefinition
2816@subsection Customizing Class Redefinition
2817
ed478161
NJ
2818When @code{define-class} notices that a class is being redefined, it
2819constructs the new class metaobject as usual, then invokes the
0b452f2c
NJ
2820@code{class-redefinition} generic function with the old and new classes
2821as arguments. Therefore, if the old or new classes have metaclasses
2822other than the default @code{<class>}, class redefinition behaviour can
2823be customized by defining a @code{class-redefinition} method that is
2824specialized for the relevant metaclasses.
2825
2826@deffn generic class-redefinition
2827Handle the class redefinition from @var{old-class} to @var{new-class},
2828and return the new class metaobject that should be bound to the
2829variable specified by @code{define-class}'s first argument.
2830@end deffn
2831
2832@deffn method class-redefinition (old-class <class>) (new-class <class>)
2833Implements GOOPS' default class redefinition behaviour, as described in
2834@ref{Default Class Redefinition Behaviour}. Returns the metaobject
2835for the new class definition.
2836@end deffn
2837
ed478161
NJ
2838The default @code{class-redefinition} method, for classes with the
2839default metaclass @code{<class>}, calls the following generic functions,
2840which could of course be individually customized.
2841
2842@deffn generic remove-class-accessors! old
2843The default @code{remove-class-accessors!} method removes the accessor
2844methods of the old class from all classes which they specialize.
2845@end deffn
2846
2847@deffn generic update-direct-method! method old new
2848The default @code{update-direct-method!} method substitutes the new
2849class for the old in all methods specialized to the old class.
2850@end deffn
2851
2852@deffn generic update-direct-subclass! subclass old new
2853The default @code{update-direct-subclass!} method invokes
2854@code{class-redefinition} recursively to handle the redefinition of
2855subclasses.
2856@end deffn
2857
0b452f2c
NJ
2858An alternative class redefinition strategy could be to leave all
2859existing instances as instances of the old class, but accepting that the
2860old class is now ``nameless'', since its name has been taken over by the
2861new definition. In this strategy, any existing subclasses could also
2862be left as they are, on the understanding that they inherit from a nameless
2863superclass.
2864
2865This strategy is easily implemented in GOOPS, by defining a new metaclass,
2866that will be used as the metaclass for all classes to which the strategy
2867should apply, and then defining a @code{class-redefinition} method that
2868is specialized for this metaclass:
2869
2870@example
2871(define-class <can-be-nameless> (<class>))
2872
2873(define-method (class-redefinition (old <can-be-nameless>)
2874 (new <class>))
2875 new)
2876@end example
2877
2878When customization can be as easy as this, aren't you glad that GOOPS
2879implements the far more difficult strategy as its default!
2880
0b452f2c
NJ
2881
2882@node Changing the Class of an Instance
2883@section Changing the Class of an Instance
2884
ed478161
NJ
2885When a class is redefined, any existing instance of the redefined class
2886will be modified for the new class definition before the next time that
2887any of the instance's slots is referenced or set. GOOPS modifies each
2888instance by calling the generic function @code{change-class}.
0b452f2c 2889
ed478161
NJ
2890More generally, you can change the class of an existing instance at any
2891time by invoking the generic function @code{change-class} with two
2892arguments: the instance and the new class.
0b452f2c
NJ
2893
2894The default method for @code{change-class} decides how to implement the
2895change of class by looking at the slot definitions for the instance's
2896existing class and for the new class. If the new class has slots with
2897the same name as slots in the existing class, the values for those slots
2898are preserved. Slots that are present only in the existing class are
2899discarded. Slots that are present only in the new class are initialized
2900using the corresponding slot definition's init function (@pxref{Classes,,
2901slot-init-function}).
2902
ed478161
NJ
2903@deffn generic change-class instance new-class
2904@end deffn
2905
0b452f2c
NJ
2906@deffn {method} change-class (obj <object>) (new <class>)
2907Modify instance @var{obj} to make it an instance of class @var{new}.
2908
2909The value of each of @var{obj}'s slots is preserved only if a similarly named
2910slot exists in @var{new}; any other slot values are discarded.
2911
2912The slots in @var{new} that do not correspond to any of @var{obj}'s
2913pre-existing slots are initialized according to @var{new}'s slot definitions'
2914init functions.
2915@end deffn
2916
ed478161
NJ
2917The default @code{change-class} method also invokes another generic
2918function, @code{update-instance-for-different-class}, as the last thing
2919that it does before returning. The applied
2920@code{update-instance-for-different-class} method can make any further
2921adjustments to @var{new-instance} that are required to complete or
2922modify the change of class. The return value from the applied method is
2923ignored.
2924
2925@deffn generic update-instance-for-different-class old-instance new-instance
2926A generic function that can be customized to put finishing touches to an
2927instance whose class has just been changed. The default
2928@code{update-instance-for-different-class} method does nothing.
2929@end deffn
2930
0b452f2c
NJ
2931Customized change of class behaviour can be implemented by defining
2932@code{change-class} methods that are specialized either by the class
2933of the instances to be modified or by the metaclass of the new class.