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