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