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