source: trunk/abcl/src/org/armedbear/lisp/clos.lisp @ 13207

Last change on this file since 13207 was 13207, checked in by ehuelsmann, 13 years ago

Fix CHECK-INITARGS checking the wrong generic functions by
making it general purpose and ask for more parameters.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 130.6 KB
Line 
1;;; clos.lisp
2;;;
3;;; Copyright (C) 2003-2007 Peter Graves
4;;; Copyright (C) 2010 Mark Evenson
5;;; $Id: clos.lisp 13207 2011-02-08 17:59:09Z ehuelsmann $
6;;;
7;;; This program is free software; you can redistribute it and/or
8;;; modify it under the terms of the GNU General Public License
9;;; as published by the Free Software Foundation; either version 2
10;;; of the License, or (at your option) any later version.
11;;;
12;;; This program is distributed in the hope that it will be useful,
13;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15;;; GNU General Public License for more details.
16;;;
17;;; You should have received a copy of the GNU General Public License
18;;; along with this program; if not, write to the Free Software
19;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20;;;
21;;; As a special exception, the copyright holders of this library give you
22;;; permission to link this library with independent modules to produce an
23;;; executable, regardless of the license terms of these independent
24;;; modules, and to copy and distribute the resulting executable under
25;;; terms of your choice, provided that you also meet, for each linked
26;;; independent module, the terms and conditions of the license of that
27;;; module.  An independent module is a module which is not derived from
28;;; or based on this library.  If you modify this library, you may extend
29;;; this exception to your version of the library, but you are not
30;;; obligated to do so.  If you do not wish to do so, delete this
31;;; exception statement from your version.
32
33;;; Originally based on Closette.
34     
35;;; Closette Version 1.0 (February 10, 1991)
36;;;
37;;; Copyright (c) 1990, 1991 Xerox Corporation.
38;;; All rights reserved.
39;;;
40;;; Use and copying of this software and preparation of derivative works
41;;; based upon this software are permitted.  Any distribution of this
42;;; software or derivative works must comply with all applicable United
43;;; States export control laws.
44;;;
45;;; This software is made available AS IS, and Xerox Corporation makes no
46;;; warranty about the software, its performance or its conformity to any
47;;; specification.
48;;;
49;;; Closette is an implementation of a subset of CLOS with a metaobject
50;;; protocol as described in "The Art of The Metaobject Protocol",
51;;; MIT Press, 1991.
52
53(in-package #:mop)
54
55;;
56;;
57;;
58;; In order to bootstrap CLOS, first implement the required API as
59;; normal functions which only apply to the "root" metaclass
60;; STANDARD-CLASS.
61;;
62;; After putting the normal functions in place, the building blocks
63;; are in place to gradually swap the normal functions with
64;; generic functions and methods.
65;;
66;; Some functionality implemented in the temporary regular functions
67;; needs to be available later as a method definition to be dispatched
68;; to for the STANDARD-CLASS case.  To prevent repeated code, the
69;; functions are implemented in functions by the same name as the
70;; API functions, but with the STD- prefix.
71;;
72;; When hacking this file, note that some important parts are implemented
73;; in the Java world. These Java bits can be found in the files
74;;
75;; * LispClass.java
76;; * SlotClass.java
77;; * StandardClass.java
78;; * BuiltInClass.java
79;; * StandardObject.java
80;; * StandardObjectFunctions.java
81;; * Layout.java
82;;
83;; In case of function names, those defined on the Java side can be
84;; recognized by their prefixed percent sign.
85;;
86;; The API functions need to be declaimed NOTINLINE explicitly, because
87;; that prevents inlining in the current FASL (which is allowed by the
88;; CLHS without the declaration); this is a hard requirement to in order
89;; to be able to swap the symbol's function slot with a generic function
90;; later on - with it actually being used.
91;;
92;;
93;;
94;; ### Note that the "declares all API functions as regular functions"
95;; isn't true when I write the above, but it's definitely the target.
96;;
97;;
98
99(export '(class-precedence-list class-slots))
100(defconstant +the-standard-class+ (find-class 'standard-class))
101(defconstant +the-structure-class+ (find-class 'structure-class))
102(defconstant +the-standard-object-class+ (find-class 'standard-object))
103(defconstant +the-standard-method-class+ (find-class 'standard-method))
104(defconstant +the-standard-reader-method-class+
105  (find-class 'standard-reader-method))
106(defconstant +the-standard-generic-function-class+
107  (find-class 'standard-generic-function))
108(defconstant +the-T-class+ (find-class 'T))
109(defconstant +the-slot-definition-class+ (find-class 'slot-definition))
110(defconstant +the-direct-slot-definition-class+ (find-class 'direct-slot-definition))
111(defconstant +the-effective-slot-definition-class+ (find-class 'effective-slot-definition))
112
113;; Don't use DEFVAR, because that disallows loading clos.lisp
114;; after compiling it: the binding won't get assigned to T anymore
115(defparameter *clos-booting* t)
116
117(defmacro define-class->%class-forwarder (name)
118  (let* (($name (if (consp name) (cadr name) name))
119         (%name (intern (concatenate 'string
120                                     "%"
121                                     (if (consp name)
122                                         (symbol-name 'set-) "")
123                                     (symbol-name $name))
124                        (symbol-package $name))))
125    `(progn
126       (declaim (notinline ,name))
127       (defun ,name (&rest args)
128         (apply #',%name args)))))
129
130(define-class->%class-forwarder class-name)
131(define-class->%class-forwarder (setf class-name))
132(define-class->%class-forwarder class-slots)
133(define-class->%class-forwarder (setf class-slots))
134(define-class->%class-forwarder class-direct-slots)
135(define-class->%class-forwarder (setf class-direct-slots))
136(define-class->%class-forwarder class-layout)
137(define-class->%class-forwarder (setf class-layout))
138(define-class->%class-forwarder class-direct-superclasses)
139(define-class->%class-forwarder (setf class-direct-superclasses))
140(define-class->%class-forwarder class-direct-subclasses)
141(define-class->%class-forwarder (setf class-direct-subclasses))
142(define-class->%class-forwarder class-direct-methods)
143(define-class->%class-forwarder (setf class-direct-methods))
144(define-class->%class-forwarder class-precedence-list)
145(define-class->%class-forwarder (setf class-precedence-list))
146(define-class->%class-forwarder class-finalized-p)
147(define-class->%class-forwarder (setf class-finalized-p))
148(define-class->%class-forwarder class-default-initargs)
149(define-class->%class-forwarder (setf class-default-initargs))
150(define-class->%class-forwarder class-direct-default-initargs)
151(define-class->%class-forwarder (setf class-direct-default-initargs))
152
153(defun no-applicable-method (generic-function &rest args)
154  (error "There is no applicable method for the generic function ~S when called with arguments ~S."
155         generic-function
156         args))
157
158
159
160(defmacro push-on-end (value location)
161  `(setf ,location (nconc ,location (list ,value))))
162
163;;; (SETF GETF*) is like (SETF GETF) except that it always changes the list,
164;;; which must be non-nil.
165
166(defun (setf getf*) (new-value plist key)
167  (block body
168    (do ((x plist (cddr x)))
169        ((null x))
170      (when (eq (car x) key)
171        (setf (car (cdr x)) new-value)
172        (return-from body new-value)))
173    (push-on-end key plist)
174    (push-on-end new-value plist)
175    new-value))
176
177(defun mapappend (fun &rest args)
178  (if (some #'null args)
179      ()
180      (append (apply fun (mapcar #'car args))
181              (apply #'mapappend fun (mapcar #'cdr args)))))
182
183(defun mapplist (fun x)
184  (if (null x)
185      ()
186      (cons (funcall fun (car x) (cadr x))
187            (mapplist fun (cddr x)))))
188
189(defsetf std-instance-layout %set-std-instance-layout)
190(defsetf standard-instance-access %set-standard-instance-access)
191
192(defun (setf find-class) (new-value symbol &optional errorp environment)
193  (declare (ignore errorp environment))
194  (%set-find-class symbol new-value))
195
196(defun canonicalize-direct-slots (direct-slots)
197  `(list ,@(mapcar #'canonicalize-direct-slot direct-slots)))
198
199(defun canonicalize-direct-slot (spec)
200  (if (symbolp spec)
201      `(list :name ',spec)
202      (let ((name (car spec))
203            (initfunction nil)
204            (initform nil)
205            (initargs ())
206            (type nil)
207            (allocation nil)
208            (documentation nil)
209            (readers ())
210            (writers ())
211            (other-options ())
212            (non-std-options ()))
213        (do ((olist (cdr spec) (cddr olist)))
214            ((null olist))
215          (case (car olist)
216            (:initform
217             (when initform
218               (error 'program-error
219                      "duplicate slot option :INITFORM for slot named ~S"
220                      name))
221             (setq initfunction t)
222             (setq initform (cadr olist)))
223            (:initarg
224             (push-on-end (cadr olist) initargs))
225            (:allocation
226             (when allocation
227               (error 'program-error
228                      "duplicate slot option :ALLOCATION for slot named ~S"
229                      name))
230             (setf allocation (cadr olist))
231             (push-on-end (car olist) other-options)
232             (push-on-end (cadr olist) other-options))
233            (:type
234             (when type
235               (error 'program-error
236                      "duplicate slot option :TYPE for slot named ~S"
237                      name))
238             (setf type (cadr olist))) ;; FIXME type is ignored
239            (:documentation
240             (when documentation
241               (error 'program-error
242                      "duplicate slot option :DOCUMENTATION for slot named ~S"
243                      name))
244             (setf documentation (cadr olist))) ;; FIXME documentation is ignored
245            (:reader
246             (maybe-note-name-defined (cadr olist))
247             (push-on-end (cadr olist) readers))
248            (:writer
249             (maybe-note-name-defined (cadr olist))
250             (push-on-end (cadr olist) writers))
251            (:accessor
252             (maybe-note-name-defined (cadr olist))
253             (push-on-end (cadr olist) readers)
254             (push-on-end `(setf ,(cadr olist)) writers))
255            (t
256             (push-on-end `(quote ,(car olist)) non-std-options)
257             (push-on-end (cadr olist) non-std-options))))
258        `(list
259          :name ',name
260          ,@(when initfunction
261              `(:initform ',initform
262                :initfunction ,(if (eq allocation :class)
263                                   ;; CLHS specifies the initform for a
264                                   ;; class allocation level slot needs
265                                   ;; to be evaluated in the dynamic
266                                   ;; extent of the DEFCLASS form
267                                   (let ((var (gensym)))
268                                     `(let ((,var ,initform))
269                                        (lambda () ,var)))
270                                 `(lambda () ,initform))))
271          ,@(when initargs `(:initargs ',initargs))
272          ,@(when readers `(:readers ',readers))
273          ,@(when writers `(:writers ',writers))
274          ,@other-options
275    ,@non-std-options))))
276
277(defun maybe-note-name-defined (name)
278  (when (fboundp 'note-name-defined)
279    (note-name-defined name)))
280
281(defun canonicalize-direct-superclasses (direct-superclasses)
282  (let ((classes '()))
283    (dolist (class-specifier direct-superclasses)
284      (if (classp class-specifier)
285          (push class-specifier classes)
286          (let ((class (find-class class-specifier nil)))
287            (unless class
288              (setf class (make-forward-referenced-class class-specifier)))
289            (push class classes))))
290    (nreverse classes)))
291
292(defun canonicalize-defclass-options (options)
293  (mapappend #'canonicalize-defclass-option options))
294
295(defun canonicalize-defclass-option (option)
296  (case (car option)
297    (:metaclass
298     (list ':metaclass
299           `(find-class ',(cadr option))))
300    (:default-initargs
301     (list
302      ':direct-default-initargs
303      `(list ,@(mapappend
304                #'(lambda (x) x)
305                (mapplist
306                 #'(lambda (key value)
307                    `(',key ,(make-initfunction value)))
308                 (cdr option))))))
309    ((:documentation :report)
310     (list (car option) `',(cadr option)))
311    (t (list `(quote ,(car option)) `(quote ,(cdr option))))))
312
313(defun make-initfunction (initform)
314  `(function (lambda () ,initform)))
315
316(defun slot-definition-allocation (slot-definition)
317  (%slot-definition-allocation slot-definition))
318
319(declaim (notinline (setf slot-definition-allocation)))
320(defun (setf slot-definition-allocation) (value slot-definition)
321  (set-slot-definition-allocation slot-definition value))
322
323(defun slot-definition-initargs (slot-definition)
324  (%slot-definition-initargs slot-definition))
325
326(declaim (notinline (setf slot-definition-initargs)))
327(defun (setf slot-definition-initargs) (value slot-definition)
328  (set-slot-definition-initargs slot-definition value))
329
330(defun slot-definition-initform (slot-definition)
331  (%slot-definition-initform slot-definition))
332
333(declaim (notinline (setf slot-definition-initform)))
334(defun (setf slot-definition-initform) (value slot-definition)
335  (set-slot-definition-initform slot-definition value))
336
337(defun slot-definition-initfunction (slot-definition)
338  (%slot-definition-initfunction slot-definition))
339
340(declaim (notinline (setf slot-definition-initfunction)))
341(defun (setf slot-definition-initfunction) (value slot-definition)
342  (set-slot-definition-initfunction slot-definition value))
343
344(defun slot-definition-name (slot-definition)
345  (%slot-definition-name slot-definition))
346
347(declaim (notinline (setf slot-definition-name)))
348(defun (setf slot-definition-name) (value slot-definition)
349  (set-slot-definition-name slot-definition value))
350
351(defun slot-definition-readers (slot-definition)
352  (%slot-definition-readers slot-definition))
353
354(declaim (notinline (setf slot-definition-readers)))
355(defun (setf slot-definition-readers) (value slot-definition)
356  (set-slot-definition-readers slot-definition value))
357
358(defun slot-definition-writers (slot-definition)
359  (%slot-definition-writers slot-definition))
360
361(declaim (notinline (setf slot-definition-writers)))
362(defun (setf slot-definition-writers) (value slot-definition)
363  (set-slot-definition-writers slot-definition value))
364
365(defun slot-definition-allocation-class (slot-definition)
366  (%slot-definition-allocation-class slot-definition))
367
368(declaim (notinline (setf slot-definition-allocation-class)))
369(defun (setf slot-definition-allocation-class) (value slot-definition)
370  (set-slot-definition-allocation-class slot-definition value))
371
372(defun slot-definition-location (slot-definition)
373  (%slot-definition-location slot-definition))
374
375(declaim (notinline (setf slot-definition-location-class)))
376(defun (setf slot-definition-location) (value slot-definition)
377  (set-slot-definition-location slot-definition value))
378
379(defun init-slot-definition (slot &key name
380           (initargs ())
381           (initform nil)
382           (initfunction nil)
383           (readers ())
384           (writers ())
385           (allocation :instance)
386           (allocation-class nil))
387  (setf (slot-definition-name slot) name)
388  (setf (slot-definition-initargs slot) initargs)
389  (setf (slot-definition-initform slot) initform)
390  (setf (slot-definition-initfunction slot) initfunction)
391  (setf (slot-definition-readers slot) readers)
392  (setf (slot-definition-writers slot) writers)
393  (setf (slot-definition-allocation slot) allocation)
394  (setf (slot-definition-allocation-class slot) allocation-class)
395  slot)
396
397(defun make-direct-slot-definition (class &rest args)
398  (let ((slot-class (direct-slot-definition-class class)))
399    (if (eq slot-class +the-direct-slot-definition-class+)
400  (let ((slot (make-slot-definition +the-direct-slot-definition-class+)))
401    (apply #'init-slot-definition slot :allocation-class class args)
402    slot)
403  (progn
404    (let ((slot (apply #'make-instance slot-class :allocation-class class
405           args)))
406      slot)))))
407
408(defun make-effective-slot-definition (class &rest args)
409  (let ((slot-class (effective-slot-definition-class class)))
410    (if (eq slot-class +the-effective-slot-definition-class+)
411  (let ((slot (make-slot-definition +the-effective-slot-definition-class+)))
412    (apply #'init-slot-definition slot args)
413    slot)
414  (progn
415    (let ((slot (apply #'make-instance slot-class args)))
416      slot)))))
417
418;;; finalize-inheritance
419
420(defun std-compute-class-default-initargs (class)
421  (mapcan #'(lambda (c)
422              (copy-list
423               (class-direct-default-initargs c)))
424          (class-precedence-list class)))
425
426(defun std-finalize-inheritance (class)
427  ;; In case the class is already finalized, return
428  ;; immediately, as per AMOP.
429  (when (class-finalized-p class)
430    (return-from std-finalize-inheritance))
431  (setf (class-precedence-list class)
432   (funcall (if (eq (class-of class) +the-standard-class+)
433                #'std-compute-class-precedence-list
434                #'compute-class-precedence-list)
435            class))
436  (dolist (class (class-precedence-list class))
437    (when (typep class 'forward-referenced-class)
438      (return-from std-finalize-inheritance)))
439  (setf (class-slots class)
440                   (funcall (if (eq (class-of class) +the-standard-class+)
441                                #'std-compute-slots
442                     #'compute-slots) class))
443  (let ((old-layout (class-layout class))
444        (length 0)
445        (instance-slots '())
446        (shared-slots '()))
447    (dolist (slot (class-slots class))
448      (case (slot-definition-allocation slot)
449        (:instance
450         (setf (slot-definition-location slot) length)
451         (incf length)
452         (push (slot-definition-name slot) instance-slots))
453        (:class
454         (unless (slot-definition-location slot)
455           (let ((allocation-class (slot-definition-allocation-class slot)))
456             (setf (slot-definition-location slot)
457       (if (eq allocation-class class)
458           (cons (slot-definition-name slot) +slot-unbound+)
459           (slot-location allocation-class (slot-definition-name slot))))))
460         (push (slot-definition-location slot) shared-slots))))
461    (when old-layout
462      ;; Redefined class: initialize added shared slots.
463      (dolist (location shared-slots)
464        (let* ((slot-name (car location))
465               (old-location (layout-slot-location old-layout slot-name)))
466          (unless old-location
467            (let* ((slot-definition (find slot-name (class-slots class) :key 'slot-definition-name))
468                   (initfunction (slot-definition-initfunction slot-definition)))
469              (when initfunction
470                (setf (cdr location) (funcall initfunction))))))))
471    (setf (class-layout class)
472          (make-layout class (nreverse instance-slots) (nreverse shared-slots))))
473  (setf (class-default-initargs class)
474        (std-compute-class-default-initargs class))
475  (setf (class-finalized-p class) t))
476
477(declaim (notinline finalize-inheritance))
478(defun finalize-inheritance (class)
479  (std-finalize-inheritance class))
480
481
482;;; Class precedence lists
483
484(defun std-compute-class-precedence-list (class)
485  (let ((classes-to-order (collect-superclasses* class)))
486    (topological-sort classes-to-order
487                      (remove-duplicates
488                       (mapappend #'local-precedence-ordering
489                                  classes-to-order))
490                      #'std-tie-breaker-rule)))
491
492;;; topological-sort implements the standard algorithm for topologically
493;;; sorting an arbitrary set of elements while honoring the precedence
494;;; constraints given by a set of (X,Y) pairs that indicate that element
495;;; X must precede element Y.  The tie-breaker procedure is called when it
496;;; is necessary to choose from multiple minimal elements; both a list of
497;;; candidates and the ordering so far are provided as arguments.
498
499(defun topological-sort (elements constraints tie-breaker)
500  (let ((remaining-constraints constraints)
501        (remaining-elements elements)
502        (result ()))
503    (loop
504      (let ((minimal-elements
505             (remove-if
506              #'(lambda (class)
507                 (member class remaining-constraints
508                         :key #'cadr))
509              remaining-elements)))
510        (when (null minimal-elements)
511          (if (null remaining-elements)
512              (return-from topological-sort result)
513              (error "Inconsistent precedence graph.")))
514        (let ((choice (if (null (cdr minimal-elements))
515                          (car minimal-elements)
516                          (funcall tie-breaker
517                                   minimal-elements
518                                   result))))
519          (setq result (append result (list choice)))
520          (setq remaining-elements
521                (remove choice remaining-elements))
522          (setq remaining-constraints
523                (remove choice
524                        remaining-constraints
525                        :test #'member)))))))
526
527;;; In the event of a tie while topologically sorting class precedence lists,
528;;; the CLOS Specification says to "select the one that has a direct subclass
529;;; rightmost in the class precedence list computed so far."  The same result
530;;; is obtained by inspecting the partially constructed class precedence list
531;;; from right to left, looking for the first minimal element to show up among
532;;; the direct superclasses of the class precedence list constituent.
533;;; (There's a lemma that shows that this rule yields a unique result.)
534
535(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
536  (dolist (cpl-constituent (reverse cpl-so-far))
537    (let* ((supers (class-direct-superclasses cpl-constituent))
538           (common (intersection minimal-elements supers)))
539      (when (not (null common))
540        (return-from std-tie-breaker-rule (car common))))))
541
542;;; This version of collect-superclasses* isn't bothered by cycles in the class
543;;; hierarchy, which sometimes happen by accident.
544
545(defun collect-superclasses* (class)
546  (labels ((all-superclasses-loop (seen superclasses)
547                                  (let ((to-be-processed
548                                         (set-difference superclasses seen)))
549                                    (if (null to-be-processed)
550                                        superclasses
551                                        (let ((class-to-process
552                                               (car to-be-processed)))
553                                          (all-superclasses-loop
554                                           (cons class-to-process seen)
555                                           (union (class-direct-superclasses
556                                                   class-to-process)
557                                                  superclasses)))))))
558          (all-superclasses-loop () (list class))))
559
560;;; The local precedence ordering of a class C with direct superclasses C_1,
561;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
562
563(defun local-precedence-ordering (class)
564  (mapcar #'list
565          (cons class
566                (butlast (class-direct-superclasses class)))
567          (class-direct-superclasses class)))
568
569;;; Slot inheritance
570
571(defun std-compute-slots (class)
572  (let* ((all-slots (mapappend #'class-direct-slots
573                               (class-precedence-list class)))
574         (all-names (remove-duplicates
575                     (mapcar 'slot-definition-name all-slots))))
576    (mapcar #'(lambda (name)
577               (funcall
578                (if (eq (class-of class) +the-standard-class+)
579                    #'std-compute-effective-slot-definition
580                    #'compute-effective-slot-definition)
581                class
582                (remove name all-slots
583                        :key 'slot-definition-name
584                        :test-not #'eq)))
585            all-names)))
586
587(defun std-compute-effective-slot-definition (class direct-slots)
588  (let ((initer (find-if-not #'null direct-slots
589                             :key 'slot-definition-initfunction)))
590    (make-effective-slot-definition
591     class
592     :name (slot-definition-name (car direct-slots))
593     :initform (if initer
594                   (slot-definition-initform initer)
595                   nil)
596     :initfunction (if initer
597                       (slot-definition-initfunction initer)
598                       nil)
599     :initargs (remove-duplicates
600                (mapappend 'slot-definition-initargs
601                           direct-slots))
602     :allocation (slot-definition-allocation (car direct-slots))
603     :allocation-class (when (slot-boundp (car direct-slots)
604            'sys::allocation-class)
605       ;;for some classes created in Java
606       ;;(e.g. SimpleCondition) this slot is unbound
607       (slot-definition-allocation-class (car direct-slots))))))
608
609;;; Standard instance slot access
610
611;;; N.B. The location of the effective-slots slots in the class metaobject for
612;;; standard-class must be determined without making any further slot
613;;; references.
614
615(defun find-slot-definition (class slot-name)
616  (dolist (slot (class-slots class) nil)
617    (when (eq slot-name (slot-definition-name slot))
618      (return slot))))
619
620(defun slot-location (class slot-name)
621  (let ((slot (find-slot-definition class slot-name)))
622    (if slot
623        (slot-definition-location slot)
624        nil)))
625
626(defun instance-slot-location (instance slot-name)
627  (let ((layout (std-instance-layout instance)))
628    (and layout (layout-slot-location layout slot-name))))
629
630(defun slot-value (object slot-name)
631  (if (or (eq (class-of (class-of object)) +the-standard-class+)
632    (eq (class-of (class-of object)) +the-structure-class+))
633      (std-slot-value object slot-name)
634      (slot-value-using-class (class-of object) object slot-name)))
635
636(defsetf std-slot-value set-std-slot-value)
637
638(defun %set-slot-value (object slot-name new-value)
639  (if (or (eq (class-of (class-of object)) +the-standard-class+)
640    (eq (class-of (class-of object)) +the-structure-class+))
641      (setf (std-slot-value object slot-name) new-value)
642      (set-slot-value-using-class new-value (class-of object)
643                                  object slot-name)))
644
645(defsetf slot-value %set-slot-value)
646
647(defun slot-boundp (object slot-name)
648  (if (eq (class-of (class-of object)) +the-standard-class+)
649      (std-slot-boundp object slot-name)
650      (slot-boundp-using-class (class-of object) object slot-name)))
651
652(defun std-slot-makunbound (instance slot-name)
653  (let ((location (instance-slot-location instance slot-name)))
654    (cond ((fixnump location)
655           (setf (standard-instance-access instance location) +slot-unbound+))
656          ((consp location)
657           (setf (cdr location) +slot-unbound+))
658          (t
659           (slot-missing (class-of instance) instance slot-name 'slot-makunbound))))
660  instance)
661
662(defun slot-makunbound (object slot-name)
663  (if (eq (class-of (class-of object)) +the-standard-class+)
664      (std-slot-makunbound object slot-name)
665      (slot-makunbound-using-class (class-of object) object slot-name)))
666
667(defun std-slot-exists-p (instance slot-name)
668  (not (null (find slot-name (class-slots (class-of instance))
669                   :key 'slot-definition-name))))
670
671(defun slot-exists-p (object slot-name)
672  (if (eq (class-of (class-of object)) +the-standard-class+)
673      (std-slot-exists-p object slot-name)
674      (slot-exists-p-using-class (class-of object) object slot-name)))
675
676(defun instance-slot-p (slot)
677  (eq (slot-definition-allocation slot) :instance))
678
679(defun std-allocate-instance (class)
680  ;; AMOP says ALLOCATE-INSTANCE checks if the class is finalized
681  ;; and if not, tries to finalize it.
682  (unless (class-finalized-p class)
683    (std-finalize-inheritance class))
684  (sys::%std-allocate-instance class))
685
686(defun make-instance-standard-class (metaclass
687             &rest initargs
688                                     &key name direct-superclasses direct-slots
689                                     direct-default-initargs
690                                     documentation)
691  (declare (ignore metaclass))
692  (let ((class (std-allocate-instance +the-standard-class+)))
693    (check-initargs (list #'allocate-instance #'initialize-instance)
694                    (list* class initargs)
695                    class t initargs)
696    (%set-class-name name class)
697    (%set-class-layout nil class)
698    (%set-class-direct-subclasses ()  class)
699    (%set-class-direct-methods ()  class)
700    (%set-class-documentation class documentation)
701    (std-after-initialization-for-classes class
702                                          :direct-superclasses direct-superclasses
703                                          :direct-slots direct-slots
704                                          :direct-default-initargs direct-default-initargs)
705    class))
706
707;(defun convert-to-direct-slot-definition (class canonicalized-slot)
708;  (apply #'make-instance
709;         (apply #'direct-slot-definition-class
710;                class canonicalized-slot)
711;         canonicalized-slot))
712
713(defun std-after-initialization-for-classes (class
714                                             &key direct-superclasses direct-slots
715                                             direct-default-initargs
716                                             &allow-other-keys)
717  (let ((supers (or direct-superclasses
718                    (list +the-standard-object-class+))))
719    (setf (class-direct-superclasses class) supers)
720    (dolist (superclass supers)
721      (pushnew class (class-direct-subclasses superclass))))
722  (let ((slots (mapcar #'(lambda (slot-properties)
723                          (apply #'make-direct-slot-definition class slot-properties))
724                       direct-slots)))
725    (setf (class-direct-slots class) slots)
726    (dolist (direct-slot slots)
727      (dolist (reader (slot-definition-readers direct-slot))
728        (add-reader-method class reader (slot-definition-name direct-slot)))
729      (dolist (writer (slot-definition-writers direct-slot))
730        (add-writer-method class writer (slot-definition-name direct-slot)))))
731  (setf (class-direct-default-initargs class) direct-default-initargs)
732  (funcall (if (eq (class-of class) +the-standard-class+)
733               #'std-finalize-inheritance
734               #'finalize-inheritance)
735           class)
736  (values))
737
738(defun canonical-slot-name (canonical-slot)
739  (getf canonical-slot :name))
740
741(defvar *extensible-built-in-classes*
742  (list (find-class 'sequence)
743        (find-class 'java:java-object)))
744
745(defun ensure-class (name &rest all-keys &key metaclass &allow-other-keys)
746  ;; Check for duplicate slots.
747  (remf all-keys :metaclass)
748  (let ((slots (getf all-keys :direct-slots)))
749    (dolist (s1 slots)
750      (let ((name1 (canonical-slot-name s1)))
751        (dolist (s2 (cdr (memq s1 slots)))
752          (when (eq name1 (canonical-slot-name s2))
753            (error 'program-error "Duplicate slot ~S" name1))))))
754  ;; Check for duplicate argument names in :DEFAULT-INITARGS.
755  (let ((names ()))
756    (do* ((initargs (getf all-keys :direct-default-initargs) (cddr initargs))
757          (name (car initargs) (car initargs)))
758         ((null initargs))
759      (push name names))
760    (do* ((names names (cdr names))
761          (name (car names) (car names)))
762         ((null names))
763      (when (memq name (cdr names))
764        (error 'program-error
765               :format-control "Duplicate initialization argument name ~S in :DEFAULT-INITARGS."
766               :format-arguments (list name)))))
767  (let ((direct-superclasses (getf all-keys :direct-superclasses)))
768    (dolist (class direct-superclasses)
769      (when (and (typep class 'built-in-class)
770     (not (member class *extensible-built-in-classes*)))
771        (error "Attempt to define a subclass of a built-in-class: ~S" class))))
772  (let ((old-class (find-class name nil)))
773    (cond ((and old-class (eq name (class-name old-class)))
774           (cond ((typep old-class 'built-in-class)
775                  (error "The symbol ~S names a built-in class." name))
776                 ((typep old-class 'forward-referenced-class)
777                  (let ((new-class (apply #'make-instance-standard-class
778                                          +the-standard-class+
779                                          :name name all-keys)))
780                    (%set-find-class name new-class)
781                    (setf (class-direct-subclasses new-class)
782                          (class-direct-subclasses old-class))
783                    (dolist (subclass (class-direct-subclasses old-class))
784                      (setf (class-direct-superclasses subclass)
785                            (substitute new-class old-class
786                                        (class-direct-superclasses subclass))))
787                    new-class))
788                 (t
789                  ;; We're redefining the class.
790                  (%make-instances-obsolete old-class)
791                  (setf (class-finalized-p old-class) nil)
792                  (check-initargs (list #'allocate-instance #'initialize-instance)
793                                  (list* old-class all-keys)
794                                  old-class t all-keys)
795                  (apply #'std-after-initialization-for-classes old-class all-keys)
796                  old-class)))
797          (t
798           (let ((class (apply (if metaclass
799                                   #'make-instance
800                                   #'make-instance-standard-class)
801                               (or metaclass
802                                   +the-standard-class+)
803                               :name name all-keys)))
804             (%set-find-class name class)
805             class)))))
806
807(defmacro defclass (&whole form name direct-superclasses direct-slots &rest options)
808  (unless (>= (length form) 3)
809    (error 'program-error "Wrong number of arguments for DEFCLASS."))
810  (check-declaration-type name)
811  `(ensure-class ',name
812                 :direct-superclasses
813                 (canonicalize-direct-superclasses ',direct-superclasses)
814                 :direct-slots
815                 ,(canonicalize-direct-slots direct-slots)
816                 ,@(canonicalize-defclass-options options)))
817
818(defstruct method-combination
819  name
820  documentation)
821
822(defstruct (short-method-combination 
823             (:include method-combination))
824  operator
825  identity-with-one-argument)
826
827(defstruct (long-method-combination
828             (:include method-combination))
829  lambda-list
830  method-group-specs
831  args-lambda-list
832  generic-function-symbol
833  function
834  arguments
835  declarations
836  forms)
837
838(defun expand-long-defcombin (name args)
839  (destructuring-bind (lambda-list method-groups &rest body) args
840    `(apply #'define-long-form-method-combination
841            ',name
842            ',lambda-list
843            (list ,@(mapcar #'canonicalize-method-group-spec method-groups))
844            ',body)))
845
846(defun expand-short-defcombin (whole)
847  (let* ((name (cadr whole))
848         (documentation
849          (getf (cddr whole) :documentation ""))
850         (identity-with-one-arg
851          (getf (cddr whole) :identity-with-one-argument nil))
852         (operator
853          (getf (cddr whole) :operator name)))
854    `(progn
855       (setf (get ',name 'method-combination-object)
856             (make-short-method-combination
857              :name ',name
858              :operator ',operator
859              :identity-with-one-argument ',identity-with-one-arg
860              :documentation ',documentation))
861       ',name)))
862
863(defmacro define-method-combination (&whole form name &rest args)
864  (if (and (cddr form)
865           (listp (caddr form)))
866      (expand-long-defcombin name args)
867      (expand-short-defcombin form)))
868
869(define-method-combination +      :identity-with-one-argument t)
870(define-method-combination and    :identity-with-one-argument t)
871(define-method-combination append :identity-with-one-argument nil)
872(define-method-combination list   :identity-with-one-argument nil)
873(define-method-combination max    :identity-with-one-argument t)
874(define-method-combination min    :identity-with-one-argument t)
875(define-method-combination nconc  :identity-with-one-argument t)
876(define-method-combination or     :identity-with-one-argument t)
877(define-method-combination progn  :identity-with-one-argument t)
878
879;;;
880;;; long form of define-method-combination (from Sacla and XCL)
881;;;
882(defun define-method-combination-type (name &rest initargs)
883    (setf (get name 'method-combination-object)
884          (apply 'make-long-method-combination initargs)))
885
886(defun method-group-p (selecter qualifiers)
887  ;; selecter::= qualifier-pattern | predicate
888  (etypecase selecter
889    (list (or (equal selecter qualifiers)
890              (let ((last (last selecter)))
891                (when (eq '* (cdr last))
892                  (let* ((prefix `(,@(butlast selecter) ,(car last)))
893                         (pos (mismatch prefix qualifiers)))
894                    (or (null pos) (= pos (length prefix))))))))
895    ((eql *) t)
896    (symbol (funcall (symbol-function selecter) qualifiers))))
897
898(defun check-variable-name (name)
899  (flet ((valid-variable-name-p (name)
900                                (and (symbolp name) (not (constantp name)))))
901    (assert (valid-variable-name-p name))))
902
903(defun canonicalize-method-group-spec (spec)
904  ;; spec ::= (name {qualifier-pattern+ | predicate} [[long-form-option]])
905  ;; long-form-option::= :description description | :order order |
906  ;;                     :required required-p
907  ;; a canonicalized-spec is a simple plist.
908  (let* ((rest spec)
909         (name (prog2 (check-variable-name (car rest))
910                 (car rest)
911                 (setq rest (cdr rest))))
912         (option-names '(:description :order :required))
913         (selecters (let ((end (or (position-if #'(lambda (it)
914                                                   (member it option-names))
915                                                rest)
916                                   (length rest))))
917                      (prog1 (subseq rest 0 end)
918                        (setq rest (subseq rest end)))))
919         (description (getf rest :description ""))
920         (order (getf rest :order :most-specific-first))
921         (required-p (getf rest :required)))
922    `(list :name ',name
923           :predicate (lambda (qualifiers)
924                        (loop for item in ',selecters
925                          thereis (method-group-p item qualifiers)))
926           :description ',description
927           :order ',order
928           :required ',required-p)))
929
930(defun extract-required-part (lambda-list)
931  (flet ((skip (key lambda-list)
932               (if (eq (first lambda-list) key)
933                   (cddr lambda-list)
934                   lambda-list)))
935    (ldiff (skip '&environment (skip '&whole lambda-list))
936           (member-if #'(lambda (it) (member it lambda-list-keywords))
937                      lambda-list))))
938
939(defun extract-specified-part (key lambda-list)
940  (case key
941    ((&eval &whole)
942     (list (second (member key lambda-list))))
943    (t
944     (let ((here (cdr (member key lambda-list))))
945       (ldiff here
946              (member-if #'(lambda (it) (member it lambda-list-keywords))
947                         here))))))
948
949(defun extract-optional-part (lambda-list)
950  (extract-specified-part '&optional lambda-list))
951
952(defun parse-define-method-combination-arguments-lambda-list (lambda-list)
953  ;; Define-method-combination Arguments Lambda Lists
954  ;; http://www.lispworks.com/reference/HyperSpec/Body/03_dj.htm
955  (let ((required (extract-required-part lambda-list))
956        (whole    (extract-specified-part '&whole    lambda-list))
957        (optional (extract-specified-part '&optional lambda-list))
958        (rest     (extract-specified-part '&rest     lambda-list))
959        (keys     (extract-specified-part '&key      lambda-list))
960        (aux      (extract-specified-part '&aux      lambda-list)))
961    (values (first whole)
962            required
963            (mapcar #'(lambda (spec)
964                       (if (consp spec)
965                           `(,(first spec) ,(second spec) ,@(cddr spec))
966                           `(,spec nil)))
967                    optional)
968            (first rest)
969            (mapcar #'(lambda (spec)
970                       (let ((key (if (consp spec) (car spec) spec))
971                             (rest (when (consp spec) (rest spec))))
972                         `(,(if (consp key) key `(,(make-keyword key) ,key))
973                           ,(car rest)
974                           ,@(cdr rest))))
975                    keys)
976            (mapcar #'(lambda (spec)
977                       (if (consp spec)
978                           `(,(first spec) ,(second spec))
979                           `(,spec nil)))
980                    aux))))
981
982(defmacro getk (plist key init-form)
983  "Similar to getf except eval and return INIT-FORM if KEY has no value in PLIST."
984  (let ((not-exist (gensym))
985        (value (gensym)))
986    `(let ((,value (getf ,plist ,key ,not-exist)))
987       (if (eq ,not-exist ,value) ,init-form ,value))))
988
989(defconstant +gf-args-var+ (make-symbol "GF-ARGS-VAR"))
990
991(defmacro with-args-lambda-list (args-lambda-list generic-function-symbol
992                                                  &body forms)
993  (let ((gf-lambda-list (gensym))
994        (nrequired (gensym))
995        (noptional (gensym))
996        (rest-args (gensym)))
997    (multiple-value-bind (whole required optional rest keys aux)
998        (parse-define-method-combination-arguments-lambda-list args-lambda-list)
999      `(let* ((,gf-lambda-list (slot-value ,generic-function-symbol 'lambda-list))
1000              (,nrequired (length (extract-required-part ,gf-lambda-list)))
1001              (,noptional (length (extract-optional-part ,gf-lambda-list)))
1002              (,rest-args (subseq ,+gf-args-var+ (+ ,nrequired ,noptional)))
1003              ,@(when whole `((,whole ,+gf-args-var+)))
1004              ,@(loop for var in required and i upfrom 0
1005                  collect `(,var (when (< ,i ,nrequired)
1006                                   (nth ,i ,+gf-args-var+))))
1007              ,@(loop for (var init-form) in optional and i upfrom 0
1008                  collect
1009                  `(,var (if (< ,i ,noptional)
1010                             (nth (+ ,nrequired ,i) ,+gf-args-var+)
1011                             ,init-form)))
1012              ,@(when rest `((,rest ,rest-args)))
1013              ,@(loop for ((key var) init-form) in keys and i upfrom 0
1014                  collect `(,var (getk ,rest-args ',key ,init-form)))
1015              ,@(loop for (var init-form) in aux and i upfrom 0
1016                  collect `(,var ,init-form)))
1017         ,@forms))))
1018
1019(defmacro with-method-groups (method-group-specs methods-form &body forms)
1020  (flet ((grouping-form (spec methods-var)
1021                        (let ((predicate (coerce-to-function (getf spec :predicate)))
1022                              (group (gensym))
1023                              (leftovers (gensym))
1024                              (method (gensym)))
1025                          `(let ((,group '())
1026                                 (,leftovers '()))
1027                             (dolist (,method ,methods-var)
1028                               (if (funcall ,predicate (method-qualifiers ,method))
1029                                   (push ,method ,group)
1030                                   (push ,method ,leftovers)))
1031                             (ecase ,(getf spec :order)
1032                               (:most-specific-last )
1033                               (:most-specific-first (setq ,group (nreverse ,group))))
1034                             ,@(when (getf spec :required)
1035                                 `((when (null ,group)
1036                                     (error "Method group ~S must not be empty."
1037                                            ',(getf spec :name)))))
1038                             (setq ,methods-var (nreverse ,leftovers))
1039                             ,group))))
1040    (let ((rest (gensym))
1041          (method (gensym)))
1042      `(let* ((,rest ,methods-form)
1043              ,@(mapcar #'(lambda (spec)
1044                           `(,(getf spec :name) ,(grouping-form spec rest)))
1045                        method-group-specs))
1046         (dolist (,method ,rest)
1047           (invalid-method-error ,method
1048                                 "Method ~S with qualifiers ~S does not belong to any method group."
1049                                 ,method (method-qualifiers ,method)))
1050         ,@forms))))
1051
1052(defun method-combination-type-lambda
1053  (&key name lambda-list args-lambda-list generic-function-symbol
1054        method-group-specs declarations forms &allow-other-keys)
1055  (let ((methods (gensym)))
1056    `(lambda (,generic-function-symbol ,methods ,@lambda-list)
1057       ,@declarations
1058       (let ((*message-prefix* ,(format nil "METHOD COMBINATION TYPE ~S: " name)))
1059         (with-method-groups ,method-group-specs
1060           ,methods
1061           ,@(if (null args-lambda-list)
1062                 forms
1063                 `((with-args-lambda-list ,args-lambda-list
1064                     ,generic-function-symbol
1065                     ,@forms))))))))
1066
1067(defun declarationp (expr)
1068  (and (consp expr) (eq (car expr) 'DECLARE)))
1069
1070(defun long-form-method-combination-args (args)
1071  ;; define-method-combination name lambda-list (method-group-specifier*) args
1072  ;; args ::= [(:arguments . args-lambda-list)]
1073  ;;          [(:generic-function generic-function-symbol)]
1074  ;;          [[declaration* | documentation]] form*
1075  (let ((rest args))
1076    (labels ((nextp (key) (and (consp (car rest)) (eq key (caar rest))))
1077             (args-lambda-list ()
1078               (when (nextp :arguments)
1079                 (prog1 (cdr (car rest)) (setq rest (cdr rest)))))
1080             (generic-function-symbol ()
1081                (if (nextp :generic-function)
1082                    (prog1 (second (car rest)) (setq rest (cdr rest)))
1083                    (gensym)))
1084             (declaration* ()
1085               (let ((end (position-if-not #'declarationp rest)))
1086                 (when end
1087                   (prog1 (subseq rest 0 end) (setq rest (nthcdr end rest))))))
1088             (documentation? ()
1089               (when (stringp (car rest))
1090                 (prog1 (car rest) (setq rest (cdr rest)))))
1091             (form* () rest))
1092      (let ((declarations '()))
1093        `(:args-lambda-list ,(args-lambda-list)
1094                            :generic-function-symbol ,(generic-function-symbol)
1095                            :documentation ,(prog2 (setq declarations (declaration*))
1096                                              (documentation?))
1097                            :declarations (,@declarations ,@(declaration*))
1098                            :forms ,(form*))))))
1099
1100(defun define-long-form-method-combination (name lambda-list method-group-specs
1101                                                 &rest args)
1102  (let* ((initargs `(:name ,name
1103                     :lambda-list ,lambda-list
1104                     :method-group-specs ,method-group-specs
1105                     ,@(long-form-method-combination-args args)))
1106         (lambda-expression (apply #'method-combination-type-lambda initargs)))
1107    (apply #'define-method-combination-type name
1108           `(,@initargs
1109;;              :function ,(compile nil lambda-expression)
1110             :function ,(coerce-to-function lambda-expression)))
1111    name))
1112
1113(defstruct eql-specializer
1114  object)
1115
1116(defparameter *eql-specializer-table* (make-hash-table :test 'eql))
1117
1118(defun intern-eql-specializer (object)
1119  (or (gethash object *eql-specializer-table*)
1120      (setf (gethash object *eql-specializer-table*)
1121            (make-eql-specializer :object object))))
1122
1123;; MOP (p. 216) specifies the following reader generic functions:
1124;;   generic-function-argument-precedence-order
1125;;   generic-function-declarations
1126;;   generic-function-lambda-list
1127;;   generic-function-method-class
1128;;   generic-function-method-combination
1129;;   generic-function-methods
1130;;   generic-function-name
1131
1132(defun generic-function-lambda-list (gf)
1133  (%generic-function-lambda-list gf))
1134(defsetf generic-function-lambda-list %set-generic-function-lambda-list)
1135
1136(defun (setf generic-function-documentation) (new-value gf)
1137  (set-generic-function-documentation gf new-value))
1138
1139(defun (setf generic-function-initial-methods) (new-value gf)
1140  (set-generic-function-initial-methods gf new-value))
1141
1142(defun (setf generic-function-methods) (new-value gf)
1143  (set-generic-function-methods gf new-value))
1144
1145(defun (setf generic-function-method-class) (new-value gf)
1146  (set-generic-function-method-class gf new-value))
1147
1148(defun (setf generic-function-method-combination) (new-value gf)
1149  (set-generic-function-method-combination gf new-value))
1150
1151(defun (setf generic-function-argument-precedence-order) (new-value gf)
1152  (set-generic-function-argument-precedence-order gf new-value))
1153
1154(declaim (ftype (function * t) classes-to-emf-table))
1155(defun classes-to-emf-table (gf)
1156  (generic-function-classes-to-emf-table gf))
1157
1158(defun (setf classes-to-emf-table) (new-value gf)
1159  (set-generic-function-classes-to-emf-table gf new-value))
1160
1161(defun (setf method-lambda-list) (new-value method)
1162  (set-method-lambda-list method new-value))
1163
1164(defun (setf method-qualifiers) (new-value method)
1165  (set-method-qualifiers method new-value))
1166
1167(defun (setf method-documentation) (new-value method)
1168  (set-method-documentation method new-value))
1169
1170;;; defgeneric
1171
1172(defmacro defgeneric (function-name lambda-list
1173                                    &rest options-and-method-descriptions)
1174  (let ((options ())
1175        (methods ())
1176        (documentation nil))
1177    (dolist (item options-and-method-descriptions)
1178      (case (car item)
1179        (declare) ; FIXME
1180        (:documentation
1181         (when documentation
1182           (error 'program-error
1183                  :format-control "Documentation option was specified twice for generic function ~S."
1184                  :format-arguments (list function-name)))
1185         (setf documentation t)
1186         (push item options))
1187        (:method
1188         (push
1189          `(push (defmethod ,function-name ,@(cdr item))
1190                 (generic-function-initial-methods (fdefinition ',function-name)))
1191          methods))
1192        (t
1193         (push item options))))
1194    (setf options (nreverse options)
1195          methods (nreverse methods))
1196    `(prog1
1197       (%defgeneric
1198        ',function-name
1199        :lambda-list ',lambda-list
1200        ,@(canonicalize-defgeneric-options options))
1201       ,@methods)))
1202
1203(defun canonicalize-defgeneric-options (options)
1204  (mapappend #'canonicalize-defgeneric-option options))
1205
1206(defun canonicalize-defgeneric-option (option)
1207  (case (car option)
1208    (:generic-function-class
1209     (list :generic-function-class `(find-class ',(cadr option))))
1210    (:method-class
1211     (list :method-class `(find-class ',(cadr option))))
1212    (:method-combination
1213     (list :method-combination `',(cdr option)))
1214    (:argument-precedence-order
1215     (list :argument-precedence-order `',(cdr option)))
1216    (t
1217     (list `',(car option) `',(cadr option)))))
1218
1219;; From OpenMCL.
1220(defun canonicalize-argument-precedence-order (apo req)
1221  (cond ((equal apo req) nil)
1222        ((not (eql (length apo) (length req)))
1223         (error 'program-error
1224                :format-control "Specified argument precedence order ~S does not match lambda list."
1225                :format-arguments (list apo)))
1226        (t (let ((res nil))
1227             (dolist (arg apo (nreverse res))
1228               (let ((index (position arg req)))
1229                 (if (or (null index) (memq index res))
1230                     (error 'program-error
1231                            :format-control "Specified argument precedence order ~S does not match lambda list."
1232                            :format-arguments (list apo)))
1233                 (push index res)))))))
1234
1235(defun find-generic-function (name &optional (errorp t))
1236  (let ((function (and (fboundp name) (fdefinition name))))
1237    (when function
1238      (when (typep function 'generic-function)
1239        (return-from find-generic-function function))
1240      (when (and *traced-names* (find name *traced-names* :test #'equal))
1241        (setf function (untraced-function name))
1242        (when (typep function 'generic-function)
1243          (return-from find-generic-function function)))))
1244  (if errorp
1245      (error "There is no generic function named ~S." name)
1246      nil))
1247
1248(defun lambda-lists-congruent-p (lambda-list1 lambda-list2)
1249  (let* ((plist1 (analyze-lambda-list lambda-list1))
1250         (args1 (getf plist1 :required-args))
1251         (plist2 (analyze-lambda-list lambda-list2))
1252         (args2 (getf plist2 :required-args)))
1253    (= (length args1) (length args2))))
1254
1255(defun %defgeneric (function-name &rest all-keys)
1256  (when (fboundp function-name)
1257    (let ((gf (fdefinition function-name)))
1258      (when (typep gf 'generic-function)
1259        ;; Remove methods defined by previous DEFGENERIC forms.
1260        (dolist (method (generic-function-initial-methods gf))
1261          (%remove-method gf method))
1262        (setf (generic-function-initial-methods gf) '()))))
1263  (apply 'ensure-generic-function function-name all-keys))
1264
1265(defun ensure-generic-function (function-name
1266                                &rest all-keys
1267                                &key
1268                                lambda-list
1269                                (generic-function-class +the-standard-generic-function-class+)
1270                                (method-class +the-standard-method-class+)
1271                                (method-combination 'standard)
1272                                (argument-precedence-order nil apo-p)
1273                                documentation
1274                                &allow-other-keys)
1275  (when (autoloadp function-name)
1276    (resolve function-name))
1277  (let ((gf (find-generic-function function-name nil)))
1278    (if gf
1279        (progn
1280          (unless (or (null (generic-function-methods gf))
1281                      (lambda-lists-congruent-p lambda-list (generic-function-lambda-list gf)))
1282            (error 'simple-error
1283                   :format-control "The lambda list ~S is incompatible with the existing methods of ~S."
1284                   :format-arguments (list lambda-list gf)))
1285          (setf (generic-function-lambda-list gf) lambda-list)
1286          (setf (generic-function-documentation gf) documentation)
1287          (let* ((plist (analyze-lambda-list lambda-list))
1288                 (required-args (getf plist ':required-args)))
1289            (%set-gf-required-args gf required-args)
1290            (when apo-p
1291              (setf (generic-function-argument-precedence-order gf)
1292                    (if argument-precedence-order
1293                        (canonicalize-argument-precedence-order argument-precedence-order
1294                                                                required-args)
1295                        nil)))
1296            (finalize-generic-function gf))
1297          gf)
1298        (progn
1299          (when (and (null *clos-booting*)
1300                     (fboundp function-name))
1301            (error 'program-error
1302                   :format-control "~A already names an ordinary function, macro, or special operator."
1303                   :format-arguments (list function-name)))
1304          (setf gf (apply (if (eq generic-function-class +the-standard-generic-function-class+)
1305                              #'make-instance-standard-generic-function
1306                              #'make-instance)
1307                          generic-function-class
1308                          :name function-name
1309                          :method-class method-class
1310                          :method-combination method-combination
1311                          all-keys))
1312          gf))))
1313
1314(defun initial-discriminating-function (gf args)
1315  (set-funcallable-instance-function
1316   gf
1317   (funcall (if (eq (class-of gf) +the-standard-generic-function-class+)
1318                #'std-compute-discriminating-function
1319                #'compute-discriminating-function)
1320            gf))
1321  (apply gf args))
1322
1323(defun collect-eql-specializer-objects (generic-function)
1324  (let ((result nil))
1325    (dolist (method (generic-function-methods generic-function))
1326      (dolist (specializer (%method-specializers method))
1327        (when (typep specializer 'eql-specializer)
1328          (pushnew (eql-specializer-object specializer)
1329                   result
1330                   :test 'eql))))
1331    result))
1332
1333(defun finalize-generic-function (gf)
1334  (%finalize-generic-function gf)
1335  (setf (classes-to-emf-table gf) (make-hash-table :test #'equal))
1336  (%init-eql-specializations gf (collect-eql-specializer-objects gf))
1337  (set-funcallable-instance-function
1338   gf #'(lambda (&rest args)
1339          (initial-discriminating-function gf args)))
1340  ;; FIXME Do we need to warn on redefinition somewhere else?
1341  (let ((*warn-on-redefinition* nil))
1342    (setf (fdefinition (%generic-function-name gf)) gf))
1343  (values))
1344
1345(defun make-instance-standard-generic-function (generic-function-class
1346                                                &key name lambda-list
1347                                                method-class
1348                                                method-combination
1349                                                argument-precedence-order
1350                                                documentation)
1351  (declare (ignore generic-function-class))
1352  (let ((gf (std-allocate-instance +the-standard-generic-function-class+)))
1353    (%set-generic-function-name gf name)
1354    (setf (generic-function-lambda-list gf) lambda-list)
1355    (setf (generic-function-initial-methods gf) ())
1356    (setf (generic-function-methods gf) ())
1357    (setf (generic-function-method-class gf) method-class)
1358    (setf (generic-function-method-combination gf) method-combination)
1359    (setf (generic-function-documentation gf) documentation)
1360    (setf (classes-to-emf-table gf) nil)
1361    (let* ((plist (analyze-lambda-list (generic-function-lambda-list gf)))
1362           (required-args (getf plist ':required-args)))
1363      (%set-gf-required-args gf required-args)
1364      (setf (generic-function-argument-precedence-order gf)
1365            (if argument-precedence-order
1366                (canonicalize-argument-precedence-order argument-precedence-order
1367                                                        required-args)
1368                nil)))
1369    (finalize-generic-function gf)
1370    gf))
1371
1372(defun canonicalize-specializers (specializers)
1373  (mapcar #'canonicalize-specializer specializers))
1374
1375(defun canonicalize-specializer (specializer)
1376  (cond ((classp specializer)
1377         specializer)
1378        ((eql-specializer-p specializer)
1379         specializer)
1380        ((symbolp specializer)
1381         (find-class specializer))
1382        ((and (consp specializer)
1383              (eq (car specializer) 'eql))
1384         (let ((object (cadr specializer)))
1385           (when (and (consp object)
1386                      (eq (car object) 'quote))
1387             (setf object (cadr object)))
1388           (intern-eql-specializer object)))
1389        ((and (consp specializer)
1390              (eq (car specializer) 'java:jclass))
1391         (let ((jclass (eval specializer)))
1392           (java::ensure-java-class jclass)))
1393        (t
1394         (error "Unknown specializer: ~S" specializer))))
1395
1396(defun parse-defmethod (args)
1397  (let ((function-name (car args))
1398        (qualifiers ())
1399        (specialized-lambda-list ())
1400        (body ())
1401        (parse-state :qualifiers))
1402    (dolist (arg (cdr args))
1403      (ecase parse-state
1404        (:qualifiers
1405         (if (and (atom arg) (not (null arg)))
1406             (push arg qualifiers)
1407             (progn
1408               (setf specialized-lambda-list arg)
1409               (setf parse-state :body))))
1410        (:body (push arg body))))
1411    (setf qualifiers (nreverse qualifiers)
1412          body (nreverse body))
1413    (multiple-value-bind (real-body declarations documentation)
1414        (parse-body body)
1415      (values function-name
1416              qualifiers
1417              (extract-lambda-list specialized-lambda-list)
1418              (extract-specializers specialized-lambda-list)
1419              documentation
1420              declarations
1421              (list* 'block
1422                     (fdefinition-block-name function-name)
1423                     real-body)))))
1424
1425(defun required-portion (gf args)
1426  (let ((number-required (length (gf-required-args gf))))
1427    (when (< (length args) number-required)
1428      (error 'program-error
1429             :format-control "Not enough arguments for generic function ~S."
1430             :format-arguments (list (%generic-function-name gf))))
1431    (subseq args 0 number-required)))
1432
1433(defun extract-lambda-list (specialized-lambda-list)
1434  (let* ((plist (analyze-lambda-list specialized-lambda-list))
1435         (requireds (getf plist :required-names))
1436         (rv (getf plist :rest-var))
1437         (ks (getf plist :key-args))
1438         (keysp (getf plist :keysp))
1439         (aok (getf plist :allow-other-keys))
1440         (opts (getf plist :optional-args))
1441         (auxs (getf plist :auxiliary-args)))
1442    `(,@requireds
1443      ,@(if rv `(&rest ,rv) ())
1444      ,@(if (or ks keysp aok) `(&key ,@ks) ())
1445      ,@(if aok '(&allow-other-keys) ())
1446      ,@(if opts `(&optional ,@opts) ())
1447      ,@(if auxs `(&aux ,@auxs) ()))))
1448
1449(defun extract-specializers (specialized-lambda-list)
1450  (let ((plist (analyze-lambda-list specialized-lambda-list)))
1451    (getf plist ':specializers)))
1452
1453(defun get-keyword-from-arg (arg)
1454  (if (listp arg)
1455      (if (listp (car arg))
1456          (caar arg)
1457          (make-keyword (car arg)))
1458      (make-keyword arg)))
1459
1460(defun analyze-lambda-list (lambda-list)
1461  (let ((keys ())           ; Just the keywords
1462        (key-args ())       ; Keywords argument specs
1463        (keysp nil)         ;
1464        (required-names ()) ; Just the variable names
1465        (required-args ())  ; Variable names & specializers
1466        (specializers ())   ; Just the specializers
1467        (rest-var nil)
1468        (optionals ())
1469        (auxs ())
1470        (allow-other-keys nil)
1471        (state :parsing-required))
1472    (dolist (arg lambda-list)
1473      (if (member arg lambda-list-keywords)
1474          (ecase arg
1475            (&optional
1476             (setq state :parsing-optional))
1477            (&rest
1478             (setq state :parsing-rest))
1479            (&key
1480             (setq keysp t)
1481             (setq state :parsing-key))
1482            (&allow-other-keys
1483             (setq allow-other-keys 't))
1484            (&aux
1485             (setq state :parsing-aux)))
1486          (case state
1487            (:parsing-required
1488             (push-on-end arg required-args)
1489             (if (listp arg)
1490                 (progn (push-on-end (car arg) required-names)
1491                   (push-on-end (cadr arg) specializers))
1492                 (progn (push-on-end arg required-names)
1493                   (push-on-end 't specializers))))
1494            (:parsing-optional (push-on-end arg optionals))
1495            (:parsing-rest (setq rest-var arg))
1496            (:parsing-key
1497             (push-on-end (get-keyword-from-arg arg) keys)
1498             (push-on-end arg key-args))
1499            (:parsing-aux (push-on-end arg auxs)))))
1500    (list  :required-names required-names
1501           :required-args required-args
1502           :specializers specializers
1503           :rest-var rest-var
1504           :keywords keys
1505           :key-args key-args
1506           :keysp keysp
1507           :auxiliary-args auxs
1508           :optional-args optionals
1509           :allow-other-keys allow-other-keys)))
1510
1511#+nil
1512(defun check-method-arg-info (gf arg-info method)
1513  (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
1514      (analyze-lambda-list (if (consp method)
1515                               (early-method-lambda-list method)
1516                               (method-lambda-list method)))
1517    (flet ((lose (string &rest args)
1518                 (error 'simple-program-error
1519                        :format-control "~@<attempt to add the method~2I~_~S~I~_~
1520                        to the generic function~2I~_~S;~I~_~
1521                        but ~?~:>"
1522                        :format-arguments (list method gf string args)))
1523           (comparison-description (x y)
1524                                   (if (> x y) "more" "fewer")))
1525      (let ((gf-nreq (arg-info-number-required arg-info))
1526            (gf-nopt (arg-info-number-optional arg-info))
1527            (gf-key/rest-p (arg-info-key/rest-p arg-info))
1528            (gf-keywords (arg-info-keys arg-info)))
1529        (unless (= nreq gf-nreq)
1530          (lose
1531           "the method has ~A required arguments than the generic function."
1532           (comparison-description nreq gf-nreq)))
1533        (unless (= nopt gf-nopt)
1534          (lose
1535           "the method has ~A optional arguments than the generic function."
1536           (comparison-description nopt gf-nopt)))
1537        (unless (eq (or keysp restp) gf-key/rest-p)
1538          (lose
1539           "the method and generic function differ in whether they accept~_~
1540            &REST or &KEY arguments."))
1541        (when (consp gf-keywords)
1542          (unless (or (and restp (not keysp))
1543                      allow-other-keys-p
1544                      (every (lambda (k) (memq k keywords)) gf-keywords))
1545            (lose "the method does not accept each of the &KEY arguments~2I~_~
1546            ~S."
1547                  gf-keywords)))))))
1548
1549(defun check-method-lambda-list (name method-lambda-list gf-lambda-list)
1550  (let* ((gf-restp (not (null (memq '&rest gf-lambda-list))))
1551         (gf-plist (analyze-lambda-list gf-lambda-list))
1552         (gf-keysp (getf gf-plist :keysp))
1553         (gf-keywords (getf gf-plist :keywords))
1554         (method-plist (analyze-lambda-list method-lambda-list))
1555         (method-restp (not (null (memq '&rest method-lambda-list))))
1556         (method-keysp (getf method-plist :keysp))
1557         (method-keywords (getf method-plist :keywords))
1558         (method-allow-other-keys-p (getf method-plist :allow-other-keys)))
1559    (unless (= (length (getf gf-plist :required-args))
1560               (length (getf method-plist :required-args)))
1561      (error "The method-lambda-list ~S ~
1562              has the wrong number of required arguments ~
1563              for the generic function ~S." method-lambda-list name))
1564    (unless (= (length (getf gf-plist :optional-args))
1565               (length (getf method-plist :optional-args)))
1566      (error "The method-lambda-list ~S ~
1567              has the wrong number of optional arguments ~
1568              for the generic function ~S." method-lambda-list name))
1569    (unless (eq (or gf-restp gf-keysp) (or method-restp method-keysp))
1570      (error "The method-lambda-list ~S ~
1571              and the generic function ~S ~
1572              differ in whether they accept &REST or &KEY arguments."
1573             method-lambda-list name))
1574    (when (consp gf-keywords)
1575      (unless (or (and method-restp (not method-keysp))
1576                  method-allow-other-keys-p
1577                  (every (lambda (k) (memq k method-keywords)) gf-keywords))
1578        (error "The method-lambda-list ~S does not accept ~
1579                all of the keyword arguments defined for the ~
1580                generic function." method-lambda-list name)))))
1581
1582(declaim (ftype (function * method) ensure-method))
1583(defun ensure-method (name &rest all-keys)
1584  (let ((method-lambda-list (getf all-keys :lambda-list))
1585        (gf (find-generic-function name nil)))
1586    (if gf
1587        (check-method-lambda-list name method-lambda-list
1588                                  (generic-function-lambda-list gf))
1589        (setf gf (ensure-generic-function name :lambda-list method-lambda-list)))
1590    (let ((method
1591           (if (eq (generic-function-method-class gf) +the-standard-method-class+)
1592               (apply #'make-instance-standard-method gf all-keys)
1593               (apply #'make-instance (generic-function-method-class gf) all-keys))))
1594      (%add-method gf method)
1595      method)))
1596
1597(defun make-instance-standard-method (gf
1598                                      &key
1599                                      lambda-list
1600                                      qualifiers
1601                                      specializers
1602                                      documentation
1603                                      function
1604                                      fast-function)
1605  (declare (ignore gf))
1606  (let ((method (std-allocate-instance +the-standard-method-class+)))
1607    (setf (method-lambda-list method) lambda-list)
1608    (setf (method-qualifiers method) qualifiers)
1609    (%set-method-specializers method (canonicalize-specializers specializers))
1610    (setf (method-documentation method) documentation)
1611    (%set-method-generic-function method nil)
1612    (%set-method-function method function)
1613    (%set-method-fast-function method fast-function)
1614    method))
1615
1616(defun %add-method (gf method)
1617  (when (%method-generic-function method)
1618    (error 'simple-error
1619           :format-control "ADD-METHOD: ~S is a method of ~S."
1620           :format-arguments (list method (%method-generic-function method))))
1621  ;; Remove existing method with same qualifiers and specializers (if any).
1622  (let ((old-method (%find-method gf (method-qualifiers method)
1623                                 (%method-specializers method) nil)))
1624    (when old-method
1625      (%remove-method gf old-method)))
1626  (%set-method-generic-function method gf)
1627  (push method (generic-function-methods gf))
1628  (dolist (specializer (%method-specializers method))
1629    (when (typep specializer 'class) ;; FIXME What about EQL specializer objects?
1630      (pushnew method (class-direct-methods specializer))))
1631  (finalize-generic-function gf)
1632  gf)
1633
1634(defun %remove-method (gf method)
1635  (setf (generic-function-methods gf)
1636        (remove method (generic-function-methods gf)))
1637  (%set-method-generic-function method nil)
1638  (dolist (specializer (%method-specializers method))
1639    (when (typep specializer 'class) ;; FIXME What about EQL specializer objects?
1640      (setf (class-direct-methods specializer)
1641            (remove method (class-direct-methods specializer)))))
1642  (finalize-generic-function gf)
1643  gf)
1644
1645(defun %find-method (gf qualifiers specializers &optional (errorp t))
1646  ;; "If the specializers argument does not correspond in length to the number
1647  ;; of required arguments of the generic-function, an an error of type ERROR
1648  ;; is signaled."
1649  (unless (= (length specializers) (length (gf-required-args gf)))
1650    (error "The specializers argument has length ~S, but ~S has ~S required parameters."
1651           (length specializers)
1652           gf
1653           (length (gf-required-args gf))))
1654  (let* ((canonical-specializers (canonicalize-specializers specializers))
1655         (method
1656          (find-if #'(lambda (method)
1657                      (and (equal qualifiers
1658                                  (method-qualifiers method))
1659                           (equal canonical-specializers
1660                                  (%method-specializers method))))
1661                   (generic-function-methods gf))))
1662    (if (and (null method) errorp)
1663        (error "No such method for ~S." (%generic-function-name gf))
1664        method)))
1665
1666(defun fast-callable-p (gf)
1667  (and (eq (generic-function-method-combination gf) 'standard)
1668       (null (intersection (%generic-function-lambda-list gf)
1669                           '(&rest &optional &key &allow-other-keys &aux)))))
1670
1671(declaim (ftype (function * t) slow-method-lookup-1))
1672
1673(declaim (ftype (function (t t t) t) slow-reader-lookup))
1674(defun slow-reader-lookup (gf layout slot-name)
1675  (let ((location (layout-slot-location layout slot-name)))
1676    (cache-slot-location gf layout location)
1677    location))
1678
1679(defun std-compute-discriminating-function (gf)
1680  (let ((code
1681         (cond
1682           ((and (= (length (generic-function-methods gf)) 1)
1683                 (typep (car (generic-function-methods gf)) 'standard-reader-method))
1684            ;;                 (sys::%format t "standard reader function ~S~%" (generic-function-name gf))
1685
1686            (let* ((method (%car (generic-function-methods gf)))
1687                   (class (car (%method-specializers method)))
1688                   (slot-name (reader-method-slot-name method)))
1689              #'(lambda (arg)
1690                  (declare (optimize speed))
1691                  (let* ((layout (std-instance-layout arg))
1692                         (location (get-cached-slot-location gf layout)))
1693                    (unless location
1694                      (unless (simple-typep arg class)
1695                        ;; FIXME no applicable method
1696                        (error 'simple-type-error
1697                               :datum arg
1698                               :expected-type class))
1699                      (setf location (slow-reader-lookup gf layout slot-name)))
1700                    (if (consp location)
1701                        ;; Shared slot.
1702                        (cdr location)
1703                        (standard-instance-access arg location))))))
1704
1705           (t
1706            (let* ((emf-table (classes-to-emf-table gf))
1707                   (number-required (length (gf-required-args gf)))
1708                   (lambda-list (%generic-function-lambda-list gf))
1709                   (exact (null (intersection lambda-list
1710                                              '(&rest &optional &key
1711                                                &allow-other-keys &aux)))))
1712              (if exact
1713                  (cond
1714                    ((= number-required 1)
1715                     (cond
1716                       ((and (eq (generic-function-method-combination gf) 'standard)
1717                             (= (length (generic-function-methods gf)) 1))
1718                        (let* ((method (%car (generic-function-methods gf)))
1719                               (specializer (car (%method-specializers method)))
1720                               (function (or (%method-fast-function method)
1721                                             (%method-function method))))
1722                          (if (eql-specializer-p specializer)
1723                              (let ((specializer-object (eql-specializer-object specializer)))
1724                                #'(lambda (arg)
1725                                    (declare (optimize speed))
1726                                    (if (eql arg specializer-object)
1727                                        (funcall function arg)
1728                                        (no-applicable-method gf (list arg)))))
1729                              #'(lambda (arg)
1730                                  (declare (optimize speed))
1731                                  (unless (simple-typep arg specializer)
1732                                    ;; FIXME no applicable method
1733                                    (error 'simple-type-error
1734                                           :datum arg
1735                                           :expected-type specializer))
1736                                  (funcall function arg)))))
1737                       (t
1738                        #'(lambda (arg)
1739                            (declare (optimize speed))
1740                            (let* ((specialization
1741                                    (%get-arg-specialization gf arg))
1742                                   (emfun (or (gethash1 specialization
1743                                                        emf-table)
1744                                              (slow-method-lookup-1
1745                                               gf arg specialization))))
1746                              (if emfun
1747                                  (funcall emfun (list arg))
1748                                  (apply #'no-applicable-method gf (list arg))))))))
1749                    ((= number-required 2)
1750                     #'(lambda (arg1 arg2)
1751                         (declare (optimize speed))
1752                         (let* ((args (list arg1 arg2))
1753                                (emfun (get-cached-emf gf args)))
1754                           (if emfun
1755                               (funcall emfun args)
1756                               (slow-method-lookup gf args)))))
1757                    ((= number-required 3)
1758                     #'(lambda (arg1 arg2 arg3)
1759                         (declare (optimize speed))
1760                         (let* ((args (list arg1 arg2 arg3))
1761                                (emfun (get-cached-emf gf args)))
1762                           (if emfun
1763                               (funcall emfun args)
1764                               (slow-method-lookup gf args)))))
1765                    (t
1766                     #'(lambda (&rest args)
1767                         (declare (optimize speed))
1768                         (let ((len (length args)))
1769                           (unless (= len number-required)
1770                             (error 'program-error
1771                                    :format-control "Not enough arguments for generic function ~S."
1772                                    :format-arguments (list (%generic-function-name gf)))))
1773                         (let ((emfun (get-cached-emf gf args)))
1774                           (if emfun
1775                               (funcall emfun args)
1776                               (slow-method-lookup gf args))))))
1777                  #'(lambda (&rest args)
1778                      (declare (optimize speed))
1779                      (let ((len (length args)))
1780                        (unless (>= len number-required)
1781                          (error 'program-error
1782                                 :format-control "Not enough arguments for generic function ~S."
1783                                 :format-arguments (list (%generic-function-name gf)))))
1784                      (let ((emfun (get-cached-emf gf args)))
1785                        (if emfun
1786                            (funcall emfun args)
1787                            (slow-method-lookup gf args))))))))))
1788
1789    code))
1790
1791(defun sort-methods (methods gf required-classes)
1792  (if (or (null methods) (null (%cdr methods)))
1793      methods
1794      (sort methods
1795      (if (eq (class-of gf) +the-standard-generic-function-class+)
1796    #'(lambda (m1 m2)
1797        (std-method-more-specific-p m1 m2 required-classes
1798            (generic-function-argument-precedence-order gf)))
1799    #'(lambda (m1 m2)
1800        (method-more-specific-p gf m1 m2 required-classes))))))
1801
1802(defun method-applicable-p (method args)
1803  (do* ((specializers (%method-specializers method) (cdr specializers))
1804        (args args (cdr args)))
1805       ((null specializers) t)
1806    (let ((specializer (car specializers)))
1807      (if (typep specializer 'eql-specializer)
1808          (unless (eql (car args) (eql-specializer-object specializer))
1809            (return nil))
1810          (unless (subclassp (class-of (car args)) specializer)
1811            (return nil))))))
1812
1813(defun %compute-applicable-methods (gf args)
1814  (let ((required-classes (mapcar #'class-of (required-portion gf args)))
1815        (methods '()))
1816    (dolist (method (generic-function-methods gf))
1817      (when (method-applicable-p method args)
1818        (push method methods)))
1819    (sort-methods methods gf required-classes)))
1820
1821;;; METHOD-APPLICABLE-USING-CLASSES-P
1822;;;
1823;;; If the first return value is T, METHOD is definitely applicable to
1824;;; arguments that are instances of CLASSES.  If the first value is
1825;;; NIL and the second value is T, METHOD is definitely not applicable
1826;;; to arguments that are instances of CLASSES; if the second value is
1827;;; NIL the applicability of METHOD cannot be determined by inspecting
1828;;; the classes of its arguments only.
1829;;;
1830(defun method-applicable-using-classes-p (method classes)
1831  (do* ((specializers (%method-specializers method) (cdr specializers))
1832  (classes classes (cdr classes))
1833  (knownp t))
1834       ((null specializers)
1835  (if knownp (values t t) (values nil nil)))
1836    (let ((specializer (car specializers)))
1837      (if (typep specializer 'eql-specializer)
1838    (if (eql (class-of (eql-specializer-object specializer)) 
1839       (car classes))
1840        (setf knownp nil)
1841        (return (values nil t)))
1842    (unless (subclassp (car classes) specializer)
1843      (return (values nil t)))))))
1844
1845(defun slow-method-lookup (gf args)
1846  (let ((applicable-methods (%compute-applicable-methods gf args)))
1847    (if applicable-methods
1848        (let ((emfun (funcall (if (eq (class-of gf) +the-standard-generic-function-class+)
1849                                  #'std-compute-effective-method-function
1850                                  #'compute-effective-method-function)
1851                              gf applicable-methods)))
1852          (cache-emf gf args emfun)
1853          (funcall emfun args))
1854        (apply #'no-applicable-method gf args))))
1855
1856(defun slow-method-lookup-1 (gf arg arg-specialization)
1857  (let ((applicable-methods (%compute-applicable-methods gf (list arg))))
1858    (if applicable-methods
1859        (let ((emfun (funcall (if (eq (class-of gf) +the-standard-generic-function-class+)
1860                                  #'std-compute-effective-method-function
1861                                  #'compute-effective-method-function)
1862                              gf applicable-methods)))
1863          (when emfun
1864            (setf (gethash arg-specialization (classes-to-emf-table gf)) emfun))
1865          emfun))))
1866
1867(defun sub-specializer-p (c1 c2 c-arg)
1868  (find c2 (cdr (memq c1 (%class-precedence-list c-arg)))))
1869
1870(defun std-method-more-specific-p (method1 method2 required-classes argument-precedence-order)
1871  (if argument-precedence-order
1872      (let ((specializers-1 (%method-specializers method1))
1873            (specializers-2 (%method-specializers method2)))
1874        (dolist (index argument-precedence-order)
1875          (let ((spec1 (nth index specializers-1))
1876                (spec2 (nth index specializers-2)))
1877            (unless (eq spec1 spec2)
1878              (cond ((eql-specializer-p spec1)
1879                     (return t))
1880                    ((eql-specializer-p spec2)
1881                     (return nil))
1882                    (t
1883                     (return (sub-specializer-p spec1 spec2
1884                                                (nth index required-classes)))))))))
1885      (do ((specializers-1 (%method-specializers method1) (cdr specializers-1))
1886           (specializers-2 (%method-specializers method2) (cdr specializers-2))
1887           (classes required-classes (cdr classes)))
1888          ((null specializers-1) nil)
1889        (let ((spec1 (car specializers-1))
1890              (spec2 (car specializers-2)))
1891          (unless (eq spec1 spec2)
1892            (cond ((eql-specializer-p spec1)
1893                   (return t))
1894                  ((eql-specializer-p spec2)
1895                   (return nil))
1896                  (t
1897                   (return (sub-specializer-p spec1 spec2 (car classes))))))))))
1898
1899(defun primary-method-p (method)
1900  (null (intersection '(:before :after :around) (method-qualifiers method))))
1901
1902(defun before-method-p (method)
1903  (equal '(:before) (method-qualifiers method)))
1904
1905(defun after-method-p (method)
1906  (equal '(:after) (method-qualifiers method)))
1907
1908(defun around-method-p (method)
1909  (equal '(:around) (method-qualifiers method)))
1910
1911(defun std-compute-effective-method-function (gf methods)
1912  (let* ((mc (generic-function-method-combination gf))
1913         (mc-name (if (atom mc) mc (%car mc)))
1914         (options (if (atom mc) '() (%cdr mc)))
1915         (order (car options))
1916         (primaries '())
1917         (arounds '())
1918         around
1919         emf-form
1920         (long-method-combination-p 
1921          (typep (get mc-name 'method-combination-object) 'long-method-combination)))
1922    (unless long-method-combination-p
1923      (dolist (m methods)
1924        (let ((qualifiers (method-qualifiers m)))
1925          (cond ((null qualifiers)
1926                 (if (eq mc-name 'standard)
1927                     (push m primaries)
1928                     (error "Method combination type mismatch.")))
1929                ((cdr qualifiers)
1930                 (error "Invalid method qualifiers."))
1931                ((eq (car qualifiers) :around)
1932                 (push m arounds))
1933                ((eq (car qualifiers) mc-name)
1934                 (push m primaries))
1935                ((memq (car qualifiers) '(:before :after)))
1936                (t
1937                 (error "Invalid method qualifiers."))))))
1938    (unless (eq order :most-specific-last)
1939      (setf primaries (nreverse primaries)))
1940    (setf arounds (nreverse arounds))
1941    (setf around (car arounds))
1942    (when (and (null primaries) (not long-method-combination-p))
1943      (error "No primary methods for the generic function ~S." gf))
1944    (cond
1945      (around
1946       (let ((next-emfun
1947              (funcall
1948               (if (eq (class-of gf) +the-standard-generic-function-class+)
1949                   #'std-compute-effective-method-function
1950                   #'compute-effective-method-function)
1951               gf (remove around methods))))
1952         (setf emf-form
1953               (generate-emf-lambda (%method-function around) next-emfun))))
1954      ((eq mc-name 'standard)
1955       (let* ((next-emfun (compute-primary-emfun (cdr primaries)))
1956              (befores (remove-if-not #'before-method-p methods))
1957              (reverse-afters
1958               (reverse (remove-if-not #'after-method-p methods))))
1959         (setf emf-form
1960               (cond
1961                 ((and (null befores) (null reverse-afters))
1962                  (let ((fast-function (%method-fast-function (car primaries))))
1963                    (if fast-function
1964                        (ecase (length (gf-required-args gf))
1965                          (1
1966                           #'(lambda (args)
1967                               (declare (optimize speed))
1968                               (funcall fast-function (car args))))
1969                          (2
1970                           #'(lambda (args)
1971                               (declare (optimize speed))
1972                               (funcall fast-function (car args) (cadr args)))))
1973                        (generate-emf-lambda (%method-function (car primaries))
1974                                             next-emfun))))
1975                 (t
1976                  (let ((method-function (%method-function (car primaries))))
1977                    #'(lambda (args)
1978                        (declare (optimize speed))
1979                        (dolist (before befores)
1980                          (funcall (%method-function before) args nil))
1981                        (multiple-value-prog1
1982                            (funcall method-function args next-emfun)
1983                          (dolist (after reverse-afters)
1984                            (funcall (%method-function after) args nil))))))))))
1985      (long-method-combination-p
1986       (let* ((mc-obj (get mc-name 'method-combination-object))
1987              (function (long-method-combination-function mc-obj))
1988              (arguments (rest (slot-value gf 'method-combination))))
1989         (assert (typep mc-obj 'long-method-combination))
1990         (assert function)
1991         (setf emf-form 
1992               (let ((result (if arguments
1993                                 (apply function gf methods arguments)
1994                                 (funcall function gf methods))))
1995                 `(lambda (args)
1996                    (let ((gf-args-var args))
1997                      (macrolet ((call-method (method &optional next-method-list)
1998                                   `(funcall ,(%method-function method) args nil)))
1999                        ,result)))))))
2000      (t
2001       (let ((mc-obj (get mc-name 'method-combination-object)))
2002         (unless (typep mc-obj 'short-method-combination)
2003           (error "Unsupported method combination type ~A."
2004                  mc-name))
2005         (let* ((operator (short-method-combination-operator mc-obj))
2006                (ioa (short-method-combination-identity-with-one-argument mc-obj)))
2007           (setf emf-form
2008                 (if (and (null (cdr primaries))
2009                          (not (null ioa)))
2010                     (generate-emf-lambda (%method-function (car primaries)) nil)
2011                     `(lambda (args)
2012                        (,operator ,@(mapcar
2013                                      (lambda (primary)
2014                                        `(funcall ,(%method-function primary) args nil))
2015                                      primaries)))))))))
2016    (assert (not (null emf-form)))
2017    (or #+nil (ignore-errors (autocompile emf-form))
2018        (coerce-to-function emf-form))))
2019
2020(defun generate-emf-lambda (method-function next-emfun)
2021  #'(lambda (args)
2022      (declare (optimize speed))
2023      (funcall method-function args next-emfun)))
2024
2025;;; compute an effective method function from a list of primary methods:
2026
2027(defun compute-primary-emfun (methods)
2028  (if (null methods)
2029      nil
2030      (let ((next-emfun (compute-primary-emfun (cdr methods))))
2031        #'(lambda (args)
2032           (funcall (%method-function (car methods)) args next-emfun)))))
2033
2034(defvar *call-next-method-p*)
2035(defvar *next-method-p-p*)
2036
2037(defun walk-form (form)
2038  (cond ((atom form)
2039         (cond ((eq form 'call-next-method)
2040                (setf *call-next-method-p* t))
2041               ((eq form 'next-method-p)
2042                (setf *next-method-p-p* t))))
2043        (t
2044         (walk-form (%car form))
2045         (walk-form (%cdr form)))))
2046
2047(defun compute-method-function (lambda-expression)
2048  (let ((lambda-list (allow-other-keys (cadr lambda-expression)))
2049        (body (cddr lambda-expression))
2050        (*call-next-method-p* nil)
2051        (*next-method-p-p* nil))
2052    (multiple-value-bind (body declarations) (parse-body body)
2053      (let ((ignorable-vars '()))
2054        (dolist (var lambda-list)
2055          (if (memq var lambda-list-keywords)
2056              (return)
2057              (push var ignorable-vars)))
2058        (push `(declare (ignorable ,@ignorable-vars)) declarations))
2059      (walk-form body)
2060      (cond ((or *call-next-method-p* *next-method-p-p*)
2061             `(lambda (args next-emfun)
2062                (flet ((call-next-method (&rest cnm-args)
2063                         (if (null next-emfun)
2064                             (error "No next method for generic function.")
2065                             (funcall next-emfun (or cnm-args args))))
2066                       (next-method-p ()
2067                         (not (null next-emfun))))
2068                  (declare (ignorable (function call-next-method)
2069                                      (function next-method-p)))
2070                  (apply #'(lambda ,lambda-list ,@declarations ,@body) args))))
2071            ((null (intersection lambda-list '(&rest &optional &key &allow-other-keys &aux)))
2072             ;; Required parameters only.
2073             (case (length lambda-list)
2074               (1
2075                `(lambda (args next-emfun)
2076                   (declare (ignore next-emfun))
2077                   (let ((,(%car lambda-list) (%car args)))
2078                     (declare (ignorable ,(%car lambda-list)))
2079                     ,@declarations ,@body)))
2080               (2
2081                `(lambda (args next-emfun)
2082                   (declare (ignore next-emfun))
2083                   (let ((,(%car lambda-list) (%car args))
2084                         (,(%cadr lambda-list) (%cadr args)))
2085                     (declare (ignorable ,(%car lambda-list)
2086                                         ,(%cadr lambda-list)))
2087                     ,@declarations ,@body)))
2088               (3
2089                `(lambda (args next-emfun)
2090                   (declare (ignore next-emfun))
2091                   (let ((,(%car lambda-list) (%car args))
2092                         (,(%cadr lambda-list) (%cadr args))
2093                         (,(%caddr lambda-list) (%caddr args)))
2094                     (declare (ignorable ,(%car lambda-list)
2095                                         ,(%cadr lambda-list)
2096                                         ,(%caddr lambda-list)))
2097                     ,@declarations ,@body)))
2098               (t
2099                `(lambda (args next-emfun)
2100                   (declare (ignore next-emfun))
2101                   (apply #'(lambda ,lambda-list ,@declarations ,@body) args)))))
2102            (t
2103             `(lambda (args next-emfun)
2104                (declare (ignore next-emfun))
2105                (apply #'(lambda ,lambda-list ,@declarations ,@body) args)))))))
2106
2107(defun compute-method-fast-function (lambda-expression)
2108  (let ((lambda-list (allow-other-keys (cadr lambda-expression))))
2109    (when (intersection lambda-list '(&rest &optional &key &allow-other-keys &aux))
2110      (return-from compute-method-fast-function nil))
2111    ;; Only required args.
2112    (let ((body (cddr lambda-expression))
2113          (*call-next-method-p* nil)
2114          (*next-method-p-p* nil))
2115      (multiple-value-bind (body declarations) (parse-body body)
2116        (walk-form body)
2117        (when (or *call-next-method-p* *next-method-p-p*)
2118          (return-from compute-method-fast-function nil))
2119        (let ((decls `(declare (ignorable ,@lambda-list))))
2120          (setf lambda-expression
2121                (list* (car lambda-expression)
2122                       (cadr lambda-expression)
2123                       decls
2124                       (cddr lambda-expression))))
2125        (case (length lambda-list)
2126          (1
2127;;            `(lambda (args next-emfun)
2128;;               (let ((,(%car lambda-list) (%car args)))
2129;;                 (declare (ignorable ,(%car lambda-list)))
2130;;                 ,@declarations ,@body)))
2131           lambda-expression)
2132          (2
2133;;            `(lambda (args next-emfun)
2134;;               (let ((,(%car lambda-list) (%car args))
2135;;                     (,(%cadr lambda-list) (%cadr args)))
2136;;                 (declare (ignorable ,(%car lambda-list)
2137;;                                     ,(%cadr lambda-list)))
2138;;                 ,@declarations ,@body)))
2139           lambda-expression)
2140;;           (3
2141;;            `(lambda (args next-emfun)
2142;;               (let ((,(%car lambda-list) (%car args))
2143;;                     (,(%cadr lambda-list) (%cadr args))
2144;;                     (,(%caddr lambda-list) (%caddr args)))
2145;;                 (declare (ignorable ,(%car lambda-list)
2146;;                                     ,(%cadr lambda-list)
2147;;                                     ,(%caddr lambda-list)))
2148;;                 ,@declarations ,@body)))
2149          (t
2150           nil))))))
2151
2152;; From CLHS section 7.6.5:
2153;; "When a generic function or any of its methods mentions &key in a lambda
2154;; list, the specific set of keyword arguments accepted by the generic function
2155;; varies according to the applicable methods. The set of keyword arguments
2156;; accepted by the generic function for a particular call is the union of the
2157;; keyword arguments accepted by all applicable methods and the keyword
2158;; arguments mentioned after &key in the generic function definition, if any."
2159;; Adapted from Sacla.
2160(defun allow-other-keys (lambda-list)
2161  (if (and (member '&key lambda-list)
2162           (not (member '&allow-other-keys lambda-list)))
2163      (let* ((key-end (or (position '&aux lambda-list) (length lambda-list)))
2164             (aux-part (subseq lambda-list key-end)))
2165        `(,@(subseq lambda-list 0 key-end) &allow-other-keys ,@aux-part))
2166      lambda-list))
2167
2168(defmacro defmethod (&rest args)
2169  (multiple-value-bind
2170      (function-name qualifiers lambda-list specializers documentation declarations body)
2171      (parse-defmethod args)
2172    (let* ((specializers-form '())
2173           (lambda-expression `(lambda ,lambda-list ,@declarations ,body))
2174           (method-function (compute-method-function lambda-expression))
2175           (fast-function (compute-method-fast-function lambda-expression))
2176           )
2177      (dolist (specializer specializers)
2178        (cond ((and (consp specializer) (eq (car specializer) 'eql))
2179               (push `(list 'eql ,(cadr specializer)) specializers-form))
2180              (t
2181               (push `',specializer specializers-form))))
2182      (setf specializers-form `(list ,@(nreverse specializers-form)))
2183      `(progn
2184         (ensure-method ',function-name
2185                        :lambda-list ',lambda-list
2186                        :qualifiers ',qualifiers
2187                        :specializers ,specializers-form
2188                        ,@(if documentation `(:documentation ,documentation))
2189                        :function (function ,method-function)
2190                        ,@(if fast-function `(:fast-function (function ,fast-function)))
2191                        )))))
2192
2193;;; Reader and writer methods
2194
2195(defun make-instance-standard-reader-method (gf
2196                                             &key
2197                                             lambda-list
2198                                             qualifiers
2199                                             specializers
2200                                             documentation
2201                                             function
2202                                             fast-function
2203                                             slot-name)
2204  (declare (ignore gf))
2205  (let ((method (std-allocate-instance +the-standard-reader-method-class+)))
2206    (setf (method-lambda-list method) lambda-list)
2207    (setf (method-qualifiers method) qualifiers)
2208    (%set-method-specializers method (canonicalize-specializers specializers))
2209    (setf (method-documentation method) documentation)
2210    (%set-method-generic-function method nil)
2211    (%set-method-function method function)
2212    (%set-method-fast-function method fast-function)
2213    (set-reader-method-slot-name method slot-name)
2214    method))
2215
2216(defun add-reader-method (class function-name slot-name)
2217  (let* ((lambda-expression
2218          (if (eq (class-of class) +the-standard-class+)
2219              `(lambda (object) (std-slot-value object ',slot-name))
2220              `(lambda (object) (slot-value object ',slot-name))))
2221         (method-function (compute-method-function lambda-expression))
2222         (fast-function (compute-method-fast-function lambda-expression)))
2223    (let ((method-lambda-list '(object))
2224          (gf (find-generic-function function-name nil)))
2225      (if gf
2226          (check-method-lambda-list function-name
2227                                    method-lambda-list
2228                                    (generic-function-lambda-list gf))
2229        (setf gf (ensure-generic-function function-name :lambda-list method-lambda-list)))
2230      (let ((method
2231             (make-instance-standard-reader-method gf
2232                                                   :lambda-list '(object)
2233                                                   :qualifiers ()
2234                                                   :specializers (list class)
2235                                                   :function (if (autoloadp 'compile)
2236                                                                 method-function
2237                                                                 (autocompile method-function))
2238                                                   :fast-function (if (autoloadp 'compile)
2239                                                                      fast-function
2240                                                                      (autocompile fast-function))
2241                                                   :slot-name slot-name)))
2242        (%add-method gf method)
2243        method))))
2244
2245(defun add-writer-method (class function-name slot-name)
2246  (let* ((lambda-expression
2247          (if (eq (class-of class) +the-standard-class+)
2248              `(lambda (new-value object)
2249                 (setf (std-slot-value object ',slot-name) new-value))
2250              `(lambda (new-value object)
2251                 (setf (slot-value object ',slot-name) new-value))))
2252         (method-function (compute-method-function lambda-expression))
2253         (fast-function (compute-method-fast-function lambda-expression))
2254         )
2255    (ensure-method function-name
2256                   :lambda-list '(new-value object)
2257                   :qualifiers ()
2258                   :specializers (list +the-T-class+ class)
2259;;                    :function `(function ,method-function)
2260                   :function (if (autoloadp 'compile)
2261                                 method-function
2262                                 (autocompile method-function))
2263                   :fast-function (if (autoloadp 'compile)
2264                                      fast-function
2265                                      (autocompile fast-function))
2266                   )))
2267
2268(defmacro atomic-defgeneric (function-name &rest rest)
2269  "Macro to define a generic function and 'swap it into place' after
2270it's been fully defined with all its methods.
2271
2272Note: the user should really use the (:method ..) method description
2273way of defining methods; there's not much use in atomically defining
2274generic functions without providing sensible behaviour..."
2275  (let ((temp-sym (gensym)))
2276    `(progn
2277       (defgeneric ,temp-sym ,@rest)
2278       (let ((gf (symbol-function ',temp-sym)))
2279         (setf ,(if (and (consp function-name)
2280                         (eq (car function-name) 'setf))
2281                    `(get ',(second function-name) 'setf-function)
2282                  `(symbol-function ',function-name)) gf)
2283         (%set-generic-function-name gf ',function-name)
2284         gf))))
2285
2286(defmacro redefine-class-forwarder (name slot)
2287  "Define a generic function on a temporary symbol as an accessor
2288for the slot `slot'. Then, when definition is complete (including
2289allocation of methods), swap the definition in place.
2290
2291Without this approach, we can't depend the old forwarders to be
2292in place, while we still need them to "
2293  (let* (($name (if (consp name) (cadr name) name))
2294         (%name (intern (concatenate 'string
2295                                     "%"
2296                                     (if (consp name)
2297                                         (symbol-name 'set-) "")
2298                                     (symbol-name $name))
2299                        (find-package "SYS"))))
2300    `(atomic-defgeneric ,name (;; splice a new-value parameter for setters
2301                               ,@(when (consp name) (list 'new-value))
2302                               class)
2303         ,@(mapcar (if (consp name)
2304                       #'(lambda (class-name)
2305                           `(:method (new-value (class ,class-name))
2306                                     (,%name new-value class)))
2307                     #'(lambda (class-name)
2308                         `(:method ((class ,class-name))
2309                                   (,%name class))))
2310                   '(built-in-class
2311                     forward-referenced-class
2312                     structure-class))
2313         (:method (,@(when (consp name) (list 'new-value))
2314                   (class standard-class))
2315             ,(if (consp name)
2316                  `(setf (slot-value class ',slot) new-value)
2317                `(slot-value class ',slot))))))
2318
2319
2320(redefine-class-forwarder class-name name)
2321(redefine-class-forwarder (setf class-name) name)
2322(redefine-class-forwarder class-slots slots)
2323(redefine-class-forwarder (setf class-slots) slots)
2324(redefine-class-forwarder class-direct-slots direct-slots)
2325(redefine-class-forwarder (setf class-direct-slots) direct-slots)
2326(redefine-class-forwarder class-layout layout)
2327(redefine-class-forwarder (setf class-layout) layout)
2328(redefine-class-forwarder class-direct-superclasses direct-superclasses)
2329(redefine-class-forwarder (setf class-direct-superclasses) direct-superclasses)
2330(redefine-class-forwarder class-direct-subclasses direct-subclasses)
2331(redefine-class-forwarder (setf class-direct-subclasses) direct-subclasses)
2332(redefine-class-forwarder class-direct-methods direct-methods)
2333(redefine-class-forwarder (setf class-direct-methods) direct-methods)
2334(redefine-class-forwarder class-precedence-list precedence-list)
2335(redefine-class-forwarder (setf class-precedence-list) precedence-list)
2336(redefine-class-forwarder class-finalized-p finalized-p)
2337(redefine-class-forwarder (setf class-finalized-p) finalized-p)
2338(redefine-class-forwarder class-default-initargs default-initargs)
2339(redefine-class-forwarder (setf class-default-initargs) default-initargs)
2340(redefine-class-forwarder class-direct-default-initargs direct-default-initargs)
2341(redefine-class-forwarder (setf class-direct-default-initargs) direct-default-initargs)
2342
2343(defgeneric direct-slot-definition-class (class &rest initargs))
2344
2345(defmethod direct-slot-definition-class ((class class) &rest initargs)
2346  (declare (ignore initargs))
2347  +the-direct-slot-definition-class+)
2348
2349(defgeneric effective-slot-definition-class (class &rest initargs))
2350
2351(defmethod effective-slot-definition-class ((class class) &rest initargs)
2352  (declare (ignore initargs))
2353  +the-effective-slot-definition-class+)
2354
2355(atomic-defgeneric documentation (x doc-type)
2356    (:method ((x symbol) doc-type)
2357        (%documentation x doc-type))
2358    (:method ((x function) doc-type)
2359        (%documentation x doc-type)))
2360
2361(atomic-defgeneric (setf documentation) (new-value x doc-type)
2362    (:method (new-value (x symbol) doc-type)
2363        (%set-documentation x doc-type new-value))
2364    (:method (new-value (x function) doc-type)
2365        (%set-documentation x doc-type new-value)))
2366
2367
2368;; FIXME This should be a weak hashtable!
2369(defvar *list-documentation-hashtable* (make-hash-table :test #'equal))
2370
2371(defmethod documentation ((x list) (doc-type (eql 'function)))
2372  (let ((alist (gethash x *list-documentation-hashtable*)))
2373    (and alist (cdr (assoc doc-type alist)))))
2374
2375(defmethod documentation ((x list) (doc-type (eql 'compiler-macro)))
2376  (let ((alist (gethash x *list-documentation-hashtable*)))
2377    (and alist (cdr (assoc doc-type alist)))))
2378
2379(defmethod (setf documentation) (new-value (x list) (doc-type (eql 'function)))
2380  (let* ((alist (gethash x *list-documentation-hashtable*))
2381         (entry (and alist (assoc doc-type alist))))
2382    (cond (entry
2383           (setf (cdr entry) new-value))
2384          (t
2385           (setf (gethash x *list-documentation-hashtable*)
2386                 (push (cons doc-type new-value) alist)))))
2387  new-value)
2388
2389(defmethod (setf documentation) (new-value (x list) (doc-type (eql 'compiler-macro)))
2390  (let* ((alist (gethash x *list-documentation-hashtable*))
2391         (entry (and alist (assoc doc-type alist))))
2392    (cond (entry
2393           (setf (cdr entry) new-value))
2394          (t
2395           (setf (gethash x *list-documentation-hashtable*)
2396                 (push (cons doc-type new-value) alist)))))
2397  new-value)
2398
2399(defmethod documentation ((x standard-class) (doc-type (eql 't)))
2400  (class-documentation x))
2401
2402(defmethod documentation ((x standard-class) (doc-type (eql 'type)))
2403  (class-documentation x))
2404
2405(defmethod (setf documentation) (new-value (x standard-class) (doc-type (eql 't)))
2406  (%set-class-documentation x new-value))
2407
2408(defmethod (setf documentation) (new-value (x standard-class) (doc-type (eql 'type)))
2409  (%set-class-documentation x new-value))
2410
2411(defmethod documentation ((x structure-class) (doc-type (eql 't)))
2412  (%documentation x doc-type))
2413
2414(defmethod documentation ((x structure-class) (doc-type (eql 'type)))
2415  (%documentation x doc-type))
2416
2417(defmethod (setf documentation) (new-value (x structure-class) (doc-type (eql 't)))
2418  (%set-documentation x doc-type new-value))
2419
2420(defmethod (setf documentation) (new-value (x structure-class) (doc-type (eql 'type)))
2421  (%set-documentation x doc-type new-value))
2422
2423(defmethod documentation ((x standard-generic-function) (doc-type (eql 't)))
2424  (generic-function-documentation x))
2425
2426(defmethod (setf documentation) (new-value (x standard-generic-function) (doc-type (eql 't)))
2427  (setf (generic-function-documentation x) new-value))
2428
2429(defmethod documentation ((x standard-generic-function) (doc-type (eql 'function)))
2430  (generic-function-documentation x))
2431
2432(defmethod (setf documentation) (new-value (x standard-generic-function) (doc-type (eql 'function)))
2433  (setf (generic-function-documentation x) new-value))
2434
2435(defmethod documentation ((x standard-method) (doc-type (eql 't)))
2436  (method-documentation x))
2437
2438(defmethod (setf documentation) (new-value (x standard-method) (doc-type (eql 't)))
2439  (setf (method-documentation x) new-value))
2440
2441(defmethod documentation ((x package) (doc-type (eql 't)))
2442  (%documentation x doc-type))
2443
2444(defmethod (setf documentation) (new-value (x package) (doc-type (eql 't)))
2445  (%set-documentation x doc-type new-value))
2446
2447;;; Applicable methods
2448
2449(defgeneric compute-applicable-methods (gf args)
2450  (:method ((gf standard-generic-function) args)
2451    (%compute-applicable-methods gf args)))
2452
2453(defgeneric compute-applicable-methods-using-classes (gf classes)
2454  (:method ((gf standard-generic-function) classes)
2455    (let ((methods '()))
2456      (dolist (method (generic-function-methods gf))
2457  (multiple-value-bind (applicable knownp)
2458      (method-applicable-using-classes-p method classes)
2459    (cond (applicable
2460     (push method methods))
2461    ((not knownp)
2462     (return-from compute-applicable-methods-using-classes
2463       (values nil nil))))))
2464      (values (sort-methods methods gf classes)
2465        t))))
2466
2467(export '(compute-applicable-methods
2468    compute-applicable-methods-using-classes))
2469
2470
2471;;; Slot access
2472
2473(defun set-slot-value-using-class (new-value class instance slot-name)
2474  (declare (ignore class)) ; FIXME
2475  (setf (std-slot-value instance slot-name) new-value))
2476
2477(defgeneric slot-value-using-class (class instance slot-name))
2478
2479(defmethod slot-value-using-class ((class standard-class) instance slot-name)
2480  (std-slot-value instance slot-name))
2481
2482(defmethod slot-value-using-class ((class structure-class) instance slot-name)
2483  (std-slot-value instance slot-name))
2484
2485(defgeneric (setf slot-value-using-class) (new-value class instance slot-name))
2486
2487(defmethod (setf slot-value-using-class) (new-value
2488                                          (class standard-class)
2489                                          instance
2490                                          slot-name)
2491  (setf (std-slot-value instance slot-name) new-value))
2492
2493(defmethod (setf slot-value-using-class) (new-value
2494                                          (class structure-class)
2495                                          instance
2496                                          slot-name)
2497  (setf (std-slot-value instance slot-name) new-value))
2498
2499(defgeneric slot-exists-p-using-class (class instance slot-name))
2500
2501(defmethod slot-exists-p-using-class (class instance slot-name)
2502  nil)
2503
2504(defmethod slot-exists-p-using-class ((class standard-class) instance slot-name)
2505  (std-slot-exists-p instance slot-name))
2506
2507(defmethod slot-exists-p-using-class ((class structure-class) instance slot-name)
2508  (dolist (dsd (class-slots class))
2509    (when (eq (sys::dsd-name dsd) slot-name)
2510      (return-from slot-exists-p-using-class t)))
2511  nil)
2512
2513(defgeneric slot-boundp-using-class (class instance slot-name))
2514(defmethod slot-boundp-using-class ((class standard-class) instance slot-name)
2515  (std-slot-boundp instance slot-name))
2516(defmethod slot-boundp-using-class ((class structure-class) instance slot-name)
2517  "Structure slots can't be unbound, so this method always returns T."
2518  (declare (ignore class instance slot-name))
2519  t)
2520
2521(defgeneric slot-makunbound-using-class (class instance slot-name))
2522(defmethod slot-makunbound-using-class ((class standard-class)
2523                                        instance
2524                                        slot-name)
2525  (std-slot-makunbound instance slot-name))
2526(defmethod slot-makunbound-using-class ((class structure-class)
2527                                        instance
2528                                        slot-name)
2529  (declare (ignore class instance slot-name))
2530  (error "Structure slots can't be unbound"))
2531
2532(defgeneric slot-missing (class instance slot-name operation &optional new-value))
2533
2534(defmethod slot-missing ((class t) instance slot-name operation &optional new-value)
2535  (declare (ignore new-value))
2536  (error "The slot ~S is missing from the class ~S." slot-name class))
2537
2538(defgeneric slot-unbound (class instance slot-name))
2539
2540(defmethod slot-unbound ((class t) instance slot-name)
2541  (error 'unbound-slot :instance instance :name slot-name))
2542
2543;;; Instance creation and initialization
2544
2545(defgeneric allocate-instance (class &rest initargs &key &allow-other-keys))
2546
2547(defmethod allocate-instance ((class standard-class) &rest initargs)
2548  (declare (ignore initargs))
2549  (std-allocate-instance class))
2550
2551(defmethod allocate-instance ((class structure-class) &rest initargs)
2552  (declare (ignore initargs))
2553  (%make-structure (class-name class)
2554                   (make-list (length (class-slots class))
2555                              :initial-element +slot-unbound+)))
2556
2557;; "The set of valid initialization arguments for a class is the set of valid
2558;; initialization arguments that either fill slots or supply arguments to
2559;; methods, along with the predefined initialization argument :ALLOW-OTHER-KEYS."
2560;; 7.1.2
2561
2562(defun check-initargs (gf-list args instance shared-initialize-param initargs)
2563  (when (oddp (length initargs))
2564    (error 'program-error
2565           :format-control "Odd number of keyword arguments."))
2566  (unless (getf initargs :allow-other-keys)
2567    (let ((methods
2568           (nconc
2569            (compute-applicable-methods #'shared-initialize
2570                                        (list* instance shared-initialize-param
2571                                               initargs))
2572            (mapcan #'(lambda (gf)
2573                        (compute-applicable-methods gf args))
2574                    gf-list)))
2575          (slots (class-slots (class-of instance))))
2576      (do* ((tail initargs (cddr tail))
2577            (initarg (car tail) (car tail)))
2578           ((null tail))
2579        (unless (or (valid-initarg-p initarg slots)
2580                    (valid-methodarg-p initarg methods)
2581                    (eq initarg :allow-other-keys))
2582          (error 'program-error
2583                 :format-control "Invalid initarg ~S."
2584                 :format-arguments (list initarg)))))))
2585
2586(defun valid-methodarg-p (initarg methods)
2587  (when (symbolp initarg)
2588    (dolist (method methods nil)
2589      (let ((valid-initargs (method-lambda-list method)))
2590  (when (find (symbol-value initarg) valid-initargs 
2591         :test #'(lambda (a b)
2592             (if (listp b)
2593           (string= a (car b))
2594         (or
2595          (string= a b)
2596          (string= b "&ALLOW-OTHER-KEYS")))))
2597
2598    (return t))))))
2599
2600(defun valid-initarg-p (initarg slots)
2601  (dolist (slot slots nil)
2602    (let ((valid-initargs (slot-definition-initargs slot)))
2603      (when (memq initarg valid-initargs)
2604        (return t)))))
2605
2606(defgeneric make-instance (class &rest initargs &key &allow-other-keys))
2607
2608(defmethod make-instance ((class standard-class) &rest initargs)
2609  (when (oddp (length initargs))
2610    (error 'program-error :format-control "Odd number of keyword arguments."))
2611  (unless (class-finalized-p class)
2612    (std-finalize-inheritance class))
2613  (let ((class-default-initargs (class-default-initargs class)))
2614    (when class-default-initargs
2615      (let ((default-initargs '()))
2616        (do* ((list class-default-initargs (cddr list))
2617              (key (car list) (car list))
2618              (fn (cadr list) (cadr list)))
2619             ((null list))
2620          (when (eq (getf initargs key 'not-found) 'not-found)
2621            (setf default-initargs (append default-initargs (list key (funcall fn))))))
2622        (setf initargs (append initargs default-initargs)))))
2623
2624  (let ((instance (std-allocate-instance class)))
2625    (check-initargs (list #'allocate-instance #'initialize-instance)
2626                    (list* instance initargs)
2627                    instance t initargs)
2628    (apply #'initialize-instance instance initargs)
2629    instance))
2630
2631(defmethod make-instance ((class symbol) &rest initargs)
2632  (apply #'make-instance (find-class class) initargs))
2633
2634(defgeneric initialize-instance (instance &key))
2635
2636(defmethod initialize-instance ((instance standard-object) &rest initargs)
2637  (apply #'shared-initialize instance t initargs))
2638
2639(defgeneric reinitialize-instance (instance &key))
2640
2641;; "The system-supplied primary method for REINITIALIZE-INSTANCE checks the
2642;; validity of initargs and signals an error if an initarg is supplied that is
2643;; not declared as valid. The method then calls the generic function SHARED-
2644;; INITIALIZE with the following arguments: the instance, nil (which means no
2645;; slots should be initialized according to their initforms), and the initargs
2646;; it received."
2647(defmethod reinitialize-instance ((instance standard-object) &rest initargs)
2648  (apply #'shared-initialize instance () initargs))
2649
2650(defun std-shared-initialize (instance slot-names all-keys)
2651  (when (oddp (length all-keys))
2652    (error 'program-error :format-control "Odd number of keyword arguments."))
2653  (do* ((tail all-keys (cddr tail))
2654  (initarg (car tail) (car tail)))
2655      ((null tail))
2656    (when (and initarg (not (symbolp initarg)))
2657      (error 'program-error
2658       :format-control "Invalid initarg ~S."
2659       :format-arguments (list initarg))))
2660  (dolist (slot (class-slots (class-of instance)))
2661    (let ((slot-name (slot-definition-name slot)))
2662      (multiple-value-bind (init-key init-value foundp)
2663          (get-properties all-keys (slot-definition-initargs slot))
2664        (if foundp
2665            (setf (std-slot-value instance slot-name) init-value)
2666            (unless (std-slot-boundp instance slot-name)
2667              (let ((initfunction (slot-definition-initfunction slot)))
2668                (when (and initfunction (or (eq slot-names t)
2669                                            (memq slot-name slot-names)))
2670                  (setf (std-slot-value instance slot-name)
2671                        (funcall initfunction)))))))))
2672  instance)
2673
2674(defgeneric shared-initialize (instance slot-names &key))
2675
2676(defmethod shared-initialize ((instance standard-object) slot-names &rest initargs)
2677  (std-shared-initialize instance slot-names initargs))
2678
2679(defmethod shared-initialize ((slot slot-definition) slot-names
2680            &rest args
2681            &key name initargs initform initfunction
2682            readers writers allocation
2683            &allow-other-keys)
2684  ;;Keyword args are duplicated from init-slot-definition only to have
2685  ;;them checked.
2686  (declare (ignore slot-names)) ;;TODO?
2687  (declare (ignore name initargs initform initfunction readers writers allocation))
2688  ;;For built-in slots
2689  (apply #'init-slot-definition slot :allow-other-keys t args)
2690  ;;For user-defined slots
2691  (call-next-method))
2692
2693;;; change-class
2694
2695(defgeneric change-class (instance new-class &key))
2696
2697(defmethod change-class ((old-instance standard-object) (new-class standard-class)
2698                         &rest initargs)
2699  (let ((old-slots (class-slots (class-of old-instance)))
2700        (new-slots (class-slots new-class))
2701        (new-instance (allocate-instance new-class)))
2702    ;; "The values of local slots specified by both the class CTO and the class
2703    ;; CFROM are retained. If such a local slot was unbound, it remains
2704    ;; unbound."
2705    (dolist (new-slot new-slots)
2706      (when (instance-slot-p new-slot)
2707        (let* ((slot-name (slot-definition-name new-slot))
2708               (old-slot (find slot-name old-slots :key 'slot-definition-name)))
2709          ;; "The values of slots specified as shared in the class CFROM and as
2710          ;; local in the class CTO are retained."
2711          (when (and old-slot (slot-boundp old-instance slot-name))
2712            (setf (slot-value new-instance slot-name)
2713                  (slot-value old-instance slot-name))))))
2714    (swap-slots old-instance new-instance)
2715    (rotatef (std-instance-layout new-instance)
2716             (std-instance-layout old-instance))
2717    (apply #'update-instance-for-different-class
2718           new-instance old-instance initargs)
2719    old-instance))
2720
2721(defmethod change-class ((instance standard-object) (new-class symbol) &rest initargs)
2722  (apply #'change-class instance (find-class new-class) initargs))
2723
2724(defgeneric update-instance-for-different-class (old new &key))
2725
2726(defmethod update-instance-for-different-class
2727  ((old standard-object) (new standard-object) &rest initargs)
2728  (let ((added-slots
2729         (remove-if #'(lambda (slot-name)
2730                       (slot-exists-p old slot-name))
2731                    (mapcar 'slot-definition-name
2732                            (class-slots (class-of new))))))
2733    (check-initargs (list #'update-instance-for-different-class)
2734                    (list old new initargs)
2735                    new added-slots initargs)
2736    (apply #'shared-initialize new added-slots initargs)))
2737
2738;;; make-instances-obsolete
2739
2740(defgeneric make-instances-obsolete (class))
2741
2742(defmethod make-instances-obsolete ((class standard-class))
2743  (%make-instances-obsolete class))
2744
2745(defmethod make-instances-obsolete ((class symbol))
2746  (make-instances-obsolete (find-class class))
2747  class)
2748
2749;;; update-instance-for-redefined-class
2750
2751(defgeneric update-instance-for-redefined-class (instance
2752                                                 added-slots
2753                                                 discarded-slots
2754                                                 property-list
2755                                                 &rest initargs
2756                                                 &key
2757                                                 &allow-other-keys))
2758
2759(defmethod update-instance-for-redefined-class ((instance standard-object)
2760            added-slots
2761            discarded-slots
2762            property-list
2763            &rest initargs)
2764  (check-initargs (list #'update-instance-for-redefined-class)
2765                  (list* instance added-slots discarded-slots
2766                         property-list initargs)
2767                  instance added-slots initargs)
2768  (apply #'shared-initialize instance added-slots initargs))
2769
2770;;;  Methods having to do with class metaobjects.
2771
2772(defmethod initialize-instance :after ((class standard-class) &rest args)
2773  (apply #'std-after-initialization-for-classes class args))
2774
2775;;; Finalize inheritance
2776
2777(atomic-defgeneric finalize-inheritance (class)
2778    (:method ((class standard-class))
2779       (std-finalize-inheritance class)))
2780
2781;;; Class precedence lists
2782
2783(defgeneric compute-class-precedence-list (class))
2784(defmethod compute-class-precedence-list ((class standard-class))
2785  (std-compute-class-precedence-list class))
2786
2787;;; Slot inheritance
2788
2789(defgeneric compute-slots (class))
2790(defmethod compute-slots ((class standard-class))
2791  (std-compute-slots class))
2792
2793(defgeneric compute-effective-slot-definition (class direct-slots))
2794(defmethod compute-effective-slot-definition
2795  ((class standard-class) direct-slots)
2796  (std-compute-effective-slot-definition class direct-slots))
2797
2798;;; Methods having to do with generic function metaobjects.
2799
2800(defmethod initialize-instance :after ((gf standard-generic-function) &key)
2801  (finalize-generic-function gf))
2802
2803;;; Methods having to do with generic function invocation.
2804
2805(defgeneric compute-discriminating-function (gf))
2806(defmethod compute-discriminating-function ((gf standard-generic-function))
2807  (std-compute-discriminating-function gf))
2808
2809(defgeneric method-more-specific-p (gf method1 method2 required-classes))
2810
2811(defmethod method-more-specific-p ((gf standard-generic-function)
2812                                   method1 method2 required-classes)
2813  (std-method-more-specific-p method1 method2 required-classes
2814                              (generic-function-argument-precedence-order gf)))
2815
2816;;; XXX AMOP has COMPUTE-EFFECTIVE-METHOD
2817(defgeneric compute-effective-method-function (gf methods))
2818(defmethod compute-effective-method-function ((gf standard-generic-function) methods)
2819  (std-compute-effective-method-function gf methods))
2820
2821(defgeneric compute-applicable-methods (gf args))
2822(defmethod compute-applicable-methods ((gf standard-generic-function) args)
2823  (%compute-applicable-methods gf args))
2824
2825;;; Slot definition accessors
2826
2827(defmacro slot-definition-dispatch (slot-definition std-form generic-form)
2828  `(let (($cl (class-of ,slot-definition)))
2829     (case $cl
2830       ((+the-slot-definition-class+
2831   +the-direct-slot-definition-class+
2832   +the-effective-slot-definition-class+)
2833  ,std-form)
2834       (t ,generic-form))))
2835
2836(atomic-defgeneric slot-definition-allocation (slot-definition)
2837  (:method ((slot-definition slot-definition))
2838    (slot-definition-dispatch slot-definition
2839      (%slot-definition-allocation slot-definition)
2840      (slot-value slot-definition 'sys::allocation))))
2841
2842(atomic-defgeneric (setf slot-definition-allocation) (value slot-definition)
2843  (:method (value (slot-definition slot-definition))
2844    (slot-definition-dispatch slot-definition
2845      (set-slot-definition-allocation slot-definition value)
2846      (setf (slot-value slot-definition 'sys::allocation) value))))
2847
2848(atomic-defgeneric slot-definition-initargs (slot-definition)
2849  (:method ((slot-definition slot-definition))
2850    (slot-definition-dispatch slot-definition
2851      (%slot-definition-initargs slot-definition)
2852      (slot-value slot-definition 'sys::initargs))))
2853
2854(atomic-defgeneric (setf slot-definition-initargs) (value slot-definition)
2855  (:method (value (slot-definition slot-definition))
2856    (slot-definition-dispatch slot-definition
2857      (set-slot-definition-initargs slot-definition value)
2858      (setf (slot-value slot-definition 'sys::initargs) value))))
2859
2860(atomic-defgeneric slot-definition-initform (slot-definition)
2861  (:method ((slot-definition slot-definition))
2862    (slot-definition-dispatch slot-definition
2863      (%slot-definition-initform slot-definition)
2864      (slot-value slot-definition 'sys::initform))))
2865
2866(atomic-defgeneric (setf slot-definition-initform) (value slot-definition)
2867  (:method (value (slot-definition slot-definition))
2868    (slot-definition-dispatch slot-definition
2869      (set-slot-definition-initform slot-definition value)
2870      (setf (slot-value slot-definition 'sys::initform) value))))
2871
2872(atomic-defgeneric slot-definition-initfunction (slot-definition)
2873  (:method ((slot-definition slot-definition))
2874    (slot-definition-dispatch slot-definition
2875      (%slot-definition-initfunction slot-definition)
2876      (slot-value slot-definition 'sys::initfunction))))
2877
2878(atomic-defgeneric (setf slot-definition-initfunction) (value slot-definition)
2879  (:method (value (slot-definition slot-definition))
2880    (slot-definition-dispatch slot-definition
2881      (set-slot-definition-initfunction slot-definition value)
2882      (setf (slot-value slot-definition 'sys::initfunction) value))))
2883
2884(atomic-defgeneric slot-definition-name (slot-definition)
2885  (:method ((slot-definition slot-definition))
2886    (slot-definition-dispatch slot-definition
2887      (%slot-definition-name slot-definition)
2888      (slot-value slot-definition 'sys::name))))
2889
2890(atomic-defgeneric (setf slot-definition-name) (value slot-definition)
2891  (:method (value (slot-definition slot-definition))
2892    (slot-definition-dispatch slot-definition
2893      (set-slot-definition-name slot-definition value)
2894      (setf (slot-value slot-definition 'sys::name) value))))
2895
2896(atomic-defgeneric slot-definition-readers (slot-definition)
2897  (:method ((slot-definition slot-definition))
2898    (slot-definition-dispatch slot-definition
2899      (%slot-definition-readers slot-definition)
2900      (slot-value slot-definition 'sys::readers))))
2901
2902(atomic-defgeneric (setf slot-definition-readers) (value slot-definition)
2903  (:method (value (slot-definition slot-definition))
2904    (slot-definition-dispatch slot-definition
2905      (set-slot-definition-readers slot-definition value)
2906      (setf (slot-value slot-definition 'sys::readers) value))))
2907
2908(atomic-defgeneric slot-definition-writers (slot-definition)
2909  (:method ((slot-definition slot-definition))
2910    (slot-definition-dispatch slot-definition
2911      (%slot-definition-writers slot-definition)
2912      (slot-value slot-definition 'sys::writers))))
2913
2914(atomic-defgeneric (setf slot-definition-writers) (value slot-definition)
2915  (:method (value (slot-definition slot-definition))
2916    (slot-definition-dispatch slot-definition
2917      (set-slot-definition-writers slot-definition value)
2918      (setf (slot-value slot-definition 'sys::writers) value))))
2919
2920(atomic-defgeneric slot-definition-allocation-class (slot-definition)
2921  (:method ((slot-definition slot-definition))
2922    (slot-definition-dispatch slot-definition
2923      (%slot-definition-allocation-class slot-definition)
2924      (slot-value slot-definition 'sys::allocation-class))))
2925
2926(atomic-defgeneric (setf slot-definition-allocation-class)
2927                       (value slot-definition)
2928  (:method (value (slot-definition slot-definition))
2929    (slot-definition-dispatch slot-definition
2930      (set-slot-definition-allocation-class slot-definition value)
2931      (setf (slot-value slot-definition 'sys::allocation-class) value))))
2932
2933(atomic-defgeneric slot-definition-location (slot-definition)
2934  (:method ((slot-definition slot-definition))
2935    (slot-definition-dispatch slot-definition
2936      (%slot-definition-location slot-definition)
2937      (slot-value slot-definition 'sys::location))))
2938
2939(atomic-defgeneric (setf slot-definition-location) (value slot-definition)
2940  (:method (value (slot-definition slot-definition))
2941    (slot-definition-dispatch slot-definition
2942      (set-slot-definition-location slot-definition value)
2943      (setf (slot-value slot-definition 'sys::location) value))))
2944
2945;;; No %slot-definition-type.
2946
2947
2948;;; Conditions.
2949
2950(defmacro define-condition (name (&rest parent-types) (&rest slot-specs) &body options)
2951  (let ((parent-types (or parent-types '(condition)))
2952        (report nil))
2953    (dolist (option options)
2954      (when (eq (car option) :report)
2955        (setf report (cadr option))
2956  (setf options (delete option options :test #'equal))
2957        (return)))
2958    (typecase report
2959      (null
2960       `(progn
2961          (defclass ,name ,parent-types ,slot-specs ,@options)
2962          ',name))
2963      (string
2964       `(progn
2965          (defclass ,name ,parent-types ,slot-specs ,@options)
2966          (defmethod print-object ((condition ,name) stream)
2967            (if *print-escape*
2968                (call-next-method)
2969                (progn (write-string ,report stream) condition)))
2970          ',name))
2971      (t
2972       `(progn
2973          (defclass ,name ,parent-types ,slot-specs ,@options)
2974          (defmethod print-object ((condition ,name) stream)
2975            (if *print-escape*
2976                (call-next-method)
2977                (funcall #',report condition stream)))
2978          ',name)))))
2979
2980(defun make-condition (type &rest initargs)
2981  (or (%make-condition type initargs)
2982      (let ((class (if (symbolp type) (find-class type) type)))
2983        (apply #'make-instance class initargs))))
2984
2985;; Adapted from SBCL.
2986;; Originally defined in signal.lisp. Redefined here now that we have MAKE-CONDITION.
2987(defun coerce-to-condition (datum arguments default-type fun-name)
2988  (cond ((typep datum 'condition)
2989         (when arguments
2990           (error 'simple-type-error
2991                  :datum arguments
2992                  :expected-type 'null
2993                  :format-control "You may not supply additional arguments when giving ~S to ~S."
2994                  :format-arguments (list datum fun-name)))
2995         datum)
2996        ((symbolp datum)
2997         (apply #'make-condition datum arguments))
2998        ((or (stringp datum) (functionp datum))
2999         (make-condition default-type
3000                         :format-control datum
3001                         :format-arguments arguments))
3002        (t
3003         (error 'simple-type-error
3004                :datum datum
3005                :expected-type '(or symbol string)
3006                :format-control "Bad argument to ~S: ~S."
3007                :format-arguments (list fun-name datum)))))
3008
3009(defgeneric make-load-form (object &optional environment))
3010
3011(defmethod make-load-form ((object t) &optional environment)
3012  (declare (ignore environment))
3013  (apply #'no-applicable-method #'make-load-form (list object)))
3014
3015(defmethod make-load-form ((class class) &optional environment)
3016  (declare (ignore environment))
3017  (let ((name (class-name class)))
3018    (unless (and name (eq (find-class name nil) class))
3019      (error 'simple-type-error
3020             :format-control "Can't use anonymous or undefined class as a constant: ~S."
3021             :format-arguments (list class)))
3022    `(find-class ',name)))
3023
3024(defun invalid-method-error (method format-control &rest args)
3025  (let ((message (apply #'format nil format-control args)))
3026    (error "Invalid method error for ~S:~%    ~A" method message)))
3027
3028(defun method-combination-error (format-control &rest args)
3029  (let ((message (apply #'format nil format-control args)))
3030    (error "Method combination error in CLOS dispatch:~%    ~A" message)))
3031
3032
3033(atomic-defgeneric no-applicable-method (generic-function &rest args)
3034  (:method (generic-function &rest args)
3035      (error "There is no applicable method for the generic function ~S ~
3036              when called with arguments ~S."
3037             generic-function
3038             args)))
3039
3040
3041
3042(defgeneric find-method (generic-function
3043                         qualifiers
3044                         specializers
3045                         &optional errorp))
3046
3047(defmethod find-method ((generic-function standard-generic-function)
3048                        qualifiers specializers &optional (errorp t))
3049  (%find-method generic-function qualifiers specializers errorp))
3050
3051(defgeneric add-method (generic-function method))
3052
3053(defmethod add-method ((generic-function standard-generic-function)
3054                       (method method))
3055  (let ((method-lambda-list (method-lambda-list method))
3056        (gf-lambda-list (generic-function-lambda-list generic-function)))
3057    (check-method-lambda-list (%generic-function-name generic-function)
3058                              method-lambda-list gf-lambda-list))
3059  (%add-method generic-function method))
3060
3061(defgeneric remove-method (generic-function method))
3062
3063(defmethod remove-method ((generic-function standard-generic-function) method)
3064  (%remove-method generic-function method))
3065
3066;; See describe.lisp.
3067(defgeneric describe-object (object stream))
3068
3069;; FIXME
3070(defgeneric no-next-method (generic-function method &rest args))
3071
3072;; FIXME
3073(defgeneric function-keywords (method))
3074
3075(setf *clos-booting* nil)
3076
3077(defgeneric class-prototype (class))
3078
3079(defmethod class-prototype :before (class)
3080  (unless (class-finalized-p class)
3081    (error "~@<~S is not finalized.~:@>" class)))
3082
3083(defmethod class-prototype ((class standard-class))
3084  (allocate-instance class))
3085
3086(defmethod class-prototype ((class structure-class))
3087  (allocate-instance class))
3088
3089(provide 'clos)
Note: See TracBrowser for help on using the repository browser.