source: branches/0.15.x/abcl/src/org/armedbear/lisp/clos.lisp

Last change on this file was 12000, checked in by ehuelsmann, 15 years ago

Backport r11992, 11993 and 11999: Cells support in MOP package.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 99.3 KB
Line 
1;;; clos.lisp
2;;;
3;;; Copyright (C) 2003-2007 Peter Graves
4;;; $Id: clos.lisp 12000 2009-06-06 19:40:42Z ehuelsmann $
5;;;
6;;; This program is free software; you can redistribute it and/or
7;;; modify it under the terms of the GNU General Public License
8;;; as published by the Free Software Foundation; either version 2
9;;; of the License, or (at your option) any later version.
10;;;
11;;; This program is distributed in the hope that it will be useful,
12;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14;;; GNU General Public License for more details.
15;;;
16;;; You should have received a copy of the GNU General Public License
17;;; along with this program; if not, write to the Free Software
18;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19;;;
20;;; As a special exception, the copyright holders of this library give you
21;;; permission to link this library with independent modules to produce an
22;;; executable, regardless of the license terms of these independent
23;;; modules, and to copy and distribute the resulting executable under
24;;; terms of your choice, provided that you also meet, for each linked
25;;; independent module, the terms and conditions of the license of that
26;;; module.  An independent module is a module which is not derived from
27;;; or based on this library.  If you modify this library, you may extend
28;;; this exception to your version of the library, but you are not
29;;; obligated to do so.  If you do not wish to do so, delete this
30;;; exception statement from your version.
31
32;;; Originally based on Closette.
33
34;;; Closette Version 1.0 (February 10, 1991)
35;;;
36;;; Copyright (c) 1990, 1991 Xerox Corporation.
37;;; All rights reserved.
38;;;
39;;; Use and copying of this software and preparation of derivative works
40;;; based upon this software are permitted.  Any distribution of this
41;;; software or derivative works must comply with all applicable United
42;;; States export control laws.
43;;;
44;;; This software is made available AS IS, and Xerox Corporation makes no
45;;; warranty about the software, its performance or its conformity to any
46;;; specification.
47;;;
48;;; Closette is an implementation of a subset of CLOS with a metaobject
49;;; protocol as described in "The Art of The Metaobject Protocol",
50;;; MIT Press, 1991.
51
52(in-package #:mop)
53
54(export '(class-precedence-list class-slots slot-definition-name))
55
56(defun class-slots (class)
57  (%class-slots class))
58
59(defun slot-definition-name (slot-definition)
60  (%slot-definition-name slot-definition))
61
62(defmacro push-on-end (value location)
63  `(setf ,location (nconc ,location (list ,value))))
64
65;;; (SETF GETF*) is like (SETF GETF) except that it always changes the list,
66;;; which must be non-nil.
67
68(defun (setf getf*) (new-value plist key)
69  (block body
70    (do ((x plist (cddr x)))
71        ((null x))
72      (when (eq (car x) key)
73        (setf (car (cdr x)) new-value)
74        (return-from body new-value)))
75    (push-on-end key plist)
76    (push-on-end new-value plist)
77    new-value))
78
79(defun mapappend (fun &rest args)
80  (if (some #'null args)
81      ()
82      (append (apply fun (mapcar #'car args))
83              (apply #'mapappend fun (mapcar #'cdr args)))))
84
85(defun mapplist (fun x)
86  (if (null x)
87      ()
88      (cons (funcall fun (car x) (cadr x))
89            (mapplist fun (cddr x)))))
90
91(defsetf class-layout %set-class-layout)
92(defsetf class-direct-superclasses %set-class-direct-superclasses)
93(defsetf class-direct-subclasses %set-class-direct-subclasses)
94(defsetf class-direct-methods %set-class-direct-methods)
95(defsetf class-direct-slots %set-class-direct-slots)
96;; (defsetf class-slots %set-class-slots)
97(defsetf class-direct-default-initargs %set-class-direct-default-initargs)
98(defsetf class-default-initargs %set-class-default-initargs)
99(defsetf class-finalized-p %set-class-finalized-p)
100(defsetf std-instance-layout %set-std-instance-layout)
101(defsetf standard-instance-access %set-standard-instance-access)
102
103(defun (setf find-class) (new-value symbol &optional errorp environment)
104  (declare (ignore errorp environment))
105  (%set-find-class symbol new-value))
106
107(defun canonicalize-direct-slots (direct-slots)
108  `(list ,@(mapcar #'canonicalize-direct-slot direct-slots)))
109
110(defun canonicalize-direct-slot (spec)
111  (if (symbolp spec)
112      `(list :name ',spec)
113      (let ((name (car spec))
114            (initfunction nil)
115            (initform nil)
116            (initargs ())
117            (type nil)
118            (allocation nil)
119            (documentation nil)
120            (readers ())
121            (writers ())
122            (other-options ()))
123        (do ((olist (cdr spec) (cddr olist)))
124            ((null olist))
125          (case (car olist)
126            (:initform
127             (when initform
128               (error 'program-error
129                      "duplicate slot option :INITFORM for slot named ~S"
130                      name))
131             (setq initfunction
132                   `(function (lambda () ,(cadr olist))))
133             (setq initform `',(cadr olist)))
134            (:initarg
135             (push-on-end (cadr olist) initargs))
136            (:allocation
137             (when allocation
138               (error 'program-error
139                      "duplicate slot option :ALLOCATION for slot named ~S"
140                      name))
141             (setf allocation (cadr olist))
142             (push-on-end (car olist) other-options)
143             (push-on-end (cadr olist) other-options))
144            (:type
145             (when type
146               (error 'program-error
147                      "duplicate slot option :TYPE for slot named ~S"
148                      name))
149             (setf type (cadr olist))) ;; FIXME type is ignored
150            (:documentation
151             (when documentation
152               (error 'program-error
153                      "duplicate slot option :DOCUMENTATION for slot named ~S"
154                      name))
155             (setf documentation (cadr olist))) ;; FIXME documentation is ignored
156            (:reader
157             (maybe-note-name-defined (cadr olist))
158             (push-on-end (cadr olist) readers))
159            (:writer
160             (maybe-note-name-defined (cadr olist))
161             (push-on-end (cadr olist) writers))
162            (:accessor
163             (maybe-note-name-defined (cadr olist))
164             (push-on-end (cadr olist) readers)
165             (push-on-end `(setf ,(cadr olist)) writers))
166            (t
167             (error 'program-error
168                    "invalid initialization argument ~S for slot named ~S"
169                    (car olist) name))))
170        `(list
171          :name ',name
172          ,@(when initfunction
173              `(:initform ,initform
174                          :initfunction ,initfunction))
175          ,@(when initargs `(:initargs ',initargs))
176          ,@(when readers `(:readers ',readers))
177          ,@(when writers `(:writers ',writers))
178          ,@other-options))))
179
180(defun maybe-note-name-defined (name)
181  (when (fboundp 'note-name-defined)
182    (note-name-defined name)))
183
184(defun canonicalize-direct-superclasses (direct-superclasses)
185  (let ((classes '()))
186    (dolist (class-specifier direct-superclasses)
187      (if (classp class-specifier)
188          (push class-specifier classes)
189          (let ((class (find-class class-specifier nil)))
190            (unless class
191              (setf class (make-forward-referenced-class class-specifier)))
192            (push class classes))))
193    (nreverse classes)))
194
195(defun canonicalize-defclass-options (options)
196  (mapappend #'canonicalize-defclass-option options))
197
198(defun canonicalize-defclass-option (option)
199  (case (car option)
200    (:metaclass
201     (list ':metaclass
202           `(find-class ',(cadr option))))
203    (:default-initargs
204     (list
205      ':direct-default-initargs
206      `(list ,@(mapappend
207                #'(lambda (x) x)
208                (mapplist
209                 #'(lambda (key value)
210                    `(',key ,(make-initfunction value)))
211                 (cdr option))))))
212    ((:documentation :report)
213     (list (car option) `',(cadr option)))
214    (t
215     (error 'program-error
216            :format-control "invalid DEFCLASS option ~S"
217            :format-arguments (list (car option))))))
218
219(defun make-initfunction (initform)
220  `(function (lambda () ,initform)))
221
222(defun make-direct-slot-definition (class &key name
223                                          (initargs ())
224                                          (initform nil)
225                                          (initfunction nil)
226                                          (readers ())
227                                          (writers ())
228                                          (allocation :instance)
229                                          &allow-other-keys)
230  (let ((slot (make-slot-definition)))
231    (set-slot-definition-name slot name)
232    (set-slot-definition-initargs slot initargs)
233    (set-slot-definition-initform slot initform)
234    (set-slot-definition-initfunction slot initfunction)
235    (set-slot-definition-readers slot readers)
236    (set-slot-definition-writers slot writers)
237    (set-slot-definition-allocation slot allocation)
238    (set-slot-definition-allocation-class slot class)
239    slot))
240
241(defun make-effective-slot-definition (&key name
242                                            (initargs ())
243                                            (initform nil)
244                                            (initfunction nil)
245                                            (allocation :instance)
246                                            (allocation-class nil)
247                                            &allow-other-keys)
248  (let ((slot (make-slot-definition)))
249    (set-slot-definition-name slot name)
250    (set-slot-definition-initargs slot initargs)
251    (set-slot-definition-initform slot initform)
252    (set-slot-definition-initfunction slot initfunction)
253    (set-slot-definition-allocation slot allocation)
254    (set-slot-definition-allocation-class slot allocation-class)
255    slot))
256
257;;; finalize-inheritance
258
259(defun std-finalize-inheritance (class)
260  (set-class-precedence-list
261   class
262   (funcall (if (eq (class-of class) (find-class 'standard-class))
263                #'std-compute-class-precedence-list
264                #'compute-class-precedence-list)
265            class))
266  (dolist (class (%class-precedence-list class))
267    (when (typep class 'forward-referenced-class)
268      (return-from std-finalize-inheritance)))
269  (set-class-slots class
270                   (funcall (if (eq (class-of class) (find-class 'standard-class))
271                                #'std-compute-slots
272                                #'compute-slots)
273                            class))
274  (let ((old-layout (class-layout class))
275        (length 0)
276        (instance-slots '())
277        (shared-slots '()))
278    (dolist (slot (%class-slots class))
279      (case (%slot-definition-allocation slot)
280        (:instance
281         (set-slot-definition-location slot length)
282         (incf length)
283         (push (%slot-definition-name slot) instance-slots))
284        (:class
285         (unless (%slot-definition-location slot)
286           (let ((allocation-class (%slot-definition-allocation-class slot)))
287             (set-slot-definition-location slot
288                                           (if (eq allocation-class class)
289                                               (cons (%slot-definition-name slot) +slot-unbound+)
290                                               (slot-location allocation-class (%slot-definition-name slot))))))
291         (push (%slot-definition-location slot) shared-slots))))
292    (when old-layout
293      ;; Redefined class: initialize added shared slots.
294      (dolist (location shared-slots)
295        (let* ((slot-name (car location))
296               (old-location (layout-slot-location old-layout slot-name)))
297          (unless old-location
298            (let* ((slot-definition (find slot-name (%class-slots class) :key #'%slot-definition-name))
299                   (initfunction (%slot-definition-initfunction slot-definition)))
300              (when initfunction
301                (setf (cdr location) (funcall initfunction))))))))
302    (setf (class-layout class)
303          (make-layout class (nreverse instance-slots) (nreverse shared-slots))))
304  (setf (class-default-initargs class) (compute-class-default-initargs class))
305  (setf (class-finalized-p class) t))
306
307;;; Class precedence lists
308
309(defun std-compute-class-precedence-list (class)
310  (let ((classes-to-order (collect-superclasses* class)))
311    (topological-sort classes-to-order
312                      (remove-duplicates
313                       (mapappend #'local-precedence-ordering
314                                  classes-to-order))
315                      #'std-tie-breaker-rule)))
316
317;;; topological-sort implements the standard algorithm for topologically
318;;; sorting an arbitrary set of elements while honoring the precedence
319;;; constraints given by a set of (X,Y) pairs that indicate that element
320;;; X must precede element Y.  The tie-breaker procedure is called when it
321;;; is necessary to choose from multiple minimal elements; both a list of
322;;; candidates and the ordering so far are provided as arguments.
323
324(defun topological-sort (elements constraints tie-breaker)
325  (let ((remaining-constraints constraints)
326        (remaining-elements elements)
327        (result ()))
328    (loop
329      (let ((minimal-elements
330             (remove-if
331              #'(lambda (class)
332                 (member class remaining-constraints
333                         :key #'cadr))
334              remaining-elements)))
335        (when (null minimal-elements)
336          (if (null remaining-elements)
337              (return-from topological-sort result)
338              (error "Inconsistent precedence graph.")))
339        (let ((choice (if (null (cdr minimal-elements))
340                          (car minimal-elements)
341                          (funcall tie-breaker
342                                   minimal-elements
343                                   result))))
344          (setq result (append result (list choice)))
345          (setq remaining-elements
346                (remove choice remaining-elements))
347          (setq remaining-constraints
348                (remove choice
349                        remaining-constraints
350                        :test #'member)))))))
351
352;;; In the event of a tie while topologically sorting class precedence lists,
353;;; the CLOS Specification says to "select the one that has a direct subclass
354;;; rightmost in the class precedence list computed so far."  The same result
355;;; is obtained by inspecting the partially constructed class precedence list
356;;; from right to left, looking for the first minimal element to show up among
357;;; the direct superclasses of the class precedence list constituent.
358;;; (There's a lemma that shows that this rule yields a unique result.)
359
360(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
361  (dolist (cpl-constituent (reverse cpl-so-far))
362    (let* ((supers (class-direct-superclasses cpl-constituent))
363           (common (intersection minimal-elements supers)))
364      (when (not (null common))
365        (return-from std-tie-breaker-rule (car common))))))
366
367;;; This version of collect-superclasses* isn't bothered by cycles in the class
368;;; hierarchy, which sometimes happen by accident.
369
370(defun collect-superclasses* (class)
371  (labels ((all-superclasses-loop (seen superclasses)
372                                  (let ((to-be-processed
373                                         (set-difference superclasses seen)))
374                                    (if (null to-be-processed)
375                                        superclasses
376                                        (let ((class-to-process
377                                               (car to-be-processed)))
378                                          (all-superclasses-loop
379                                           (cons class-to-process seen)
380                                           (union (class-direct-superclasses
381                                                   class-to-process)
382                                                  superclasses)))))))
383          (all-superclasses-loop () (list class))))
384
385;;; The local precedence ordering of a class C with direct superclasses C_1,
386;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
387
388(defun local-precedence-ordering (class)
389  (mapcar #'list
390          (cons class
391                (butlast (class-direct-superclasses class)))
392          (class-direct-superclasses class)))
393
394;;; Slot inheritance
395
396(defun std-compute-slots (class)
397  (let* ((all-slots (mapappend #'class-direct-slots
398                               (%class-precedence-list class)))
399         (all-names (remove-duplicates
400                     (mapcar #'%slot-definition-name all-slots))))
401    (mapcar #'(lambda (name)
402               (funcall
403                (if (eq (class-of class) (find-class 'standard-class))
404                    #'std-compute-effective-slot-definition
405                    #'compute-effective-slot-definition)
406                class
407                (remove name all-slots
408                        :key #'%slot-definition-name
409                        :test-not #'eq)))
410            all-names)))
411
412(defun std-compute-effective-slot-definition (class direct-slots)
413  (declare (ignore class))
414  (let ((initer (find-if-not #'null direct-slots
415                             :key #'%slot-definition-initfunction)))
416    (make-effective-slot-definition
417     :name (%slot-definition-name (car direct-slots))
418     :initform (if initer
419                   (%slot-definition-initform initer)
420                   nil)
421     :initfunction (if initer
422                       (%slot-definition-initfunction initer)
423                       nil)
424     :initargs (remove-duplicates
425                (mapappend #'%slot-definition-initargs
426                           direct-slots))
427     :allocation (%slot-definition-allocation (car direct-slots))
428     :allocation-class (%slot-definition-allocation-class (car direct-slots)))))
429
430;;; Standard instance slot access
431
432;;; N.B. The location of the effective-slots slots in the class metaobject for
433;;; standard-class must be determined without making any further slot
434;;; references.
435
436(defun find-slot-definition (class slot-name)
437  (dolist (slot (%class-slots class) nil)
438    (when (eq slot-name (%slot-definition-name slot))
439      (return slot))))
440
441(defun slot-location (class slot-name)
442  (let ((slot (find-slot-definition class slot-name)))
443    (if slot
444        (%slot-definition-location slot)
445        nil)))
446
447(defun instance-slot-location (instance slot-name)
448  (let ((layout (std-instance-layout instance)))
449    (and layout (layout-slot-location layout slot-name))))
450
451(defun slot-value (object slot-name)
452  (if (eq (class-of (class-of object)) (find-class 'standard-class))
453      (std-slot-value object slot-name)
454      (slot-value-using-class (class-of object) object slot-name)))
455
456(defsetf std-slot-value set-std-slot-value)
457
458(defun %set-slot-value (object slot-name new-value)
459  (if (eq (class-of (class-of object)) (find-class 'standard-class))
460      (setf (std-slot-value object slot-name) new-value)
461      (set-slot-value-using-class new-value (class-of object)
462                                  object slot-name)))
463
464(defsetf slot-value %set-slot-value)
465
466(defun slot-boundp (object slot-name)
467  (if (eq (class-of (class-of object)) (find-class 'standard-class))
468      (std-slot-boundp object slot-name)
469      (slot-boundp-using-class (class-of object) object slot-name)))
470
471(defun std-slot-makunbound (instance slot-name)
472  (let ((location (instance-slot-location instance slot-name)))
473    (cond ((fixnump location)
474           (setf (standard-instance-access instance location) +slot-unbound+))
475          ((consp location)
476           (setf (cdr location) +slot-unbound+))
477          (t
478           (slot-missing (class-of instance) instance slot-name 'slot-makunbound))))
479  instance)
480
481(defun slot-makunbound (object slot-name)
482  (if (eq (class-of (class-of object)) (find-class 'standard-class))
483      (std-slot-makunbound object slot-name)
484      (slot-makunbound-using-class (class-of object) object slot-name)))
485
486(defun std-slot-exists-p (instance slot-name)
487  (not (null (find slot-name (%class-slots (class-of instance))
488                   :key #'%slot-definition-name))))
489
490(defun slot-exists-p (object slot-name)
491  (if (eq (class-of (class-of object)) (find-class 'standard-class))
492      (std-slot-exists-p object slot-name)
493      (slot-exists-p-using-class (class-of object) object slot-name)))
494
495(defun instance-slot-p (slot)
496  (eq (%slot-definition-allocation slot) :instance))
497
498(defun make-instance-standard-class (metaclass
499                                     &key name direct-superclasses direct-slots
500                                     direct-default-initargs
501                                     documentation
502                                     &allow-other-keys)
503  (declare (ignore metaclass))
504  (let ((class (std-allocate-instance (find-class 'standard-class))))
505    (%set-class-name class name)
506    (setf (class-direct-subclasses class) ())
507    (setf (class-direct-methods class) ())
508    (%set-class-documentation class documentation)
509    (std-after-initialization-for-classes class
510                                          :direct-superclasses direct-superclasses
511                                          :direct-slots direct-slots
512                                          :direct-default-initargs direct-default-initargs)
513    class))
514
515(defun std-after-initialization-for-classes (class
516                                             &key direct-superclasses direct-slots
517                                             direct-default-initargs
518                                             &allow-other-keys)
519  (let ((supers (or direct-superclasses
520                    (list (find-class 'standard-object)))))
521    (setf (class-direct-superclasses class) supers)
522    (dolist (superclass supers)
523      (push class (class-direct-subclasses superclass))))
524  (let ((slots (mapcar #'(lambda (slot-properties)
525                          (apply #'make-direct-slot-definition class slot-properties))
526                       direct-slots)))
527    (setf (class-direct-slots class) slots)
528    (dolist (direct-slot slots)
529      (dolist (reader (%slot-definition-readers direct-slot))
530        (add-reader-method class reader (%slot-definition-name direct-slot)))
531      (dolist (writer (%slot-definition-writers direct-slot))
532        (add-writer-method class writer (%slot-definition-name direct-slot)))))
533  (setf (class-direct-default-initargs class) direct-default-initargs)
534  (funcall (if (eq (class-of class) (find-class 'standard-class))
535               #'std-finalize-inheritance
536               #'finalize-inheritance)
537           class)
538  (values))
539
540(defun canonical-slot-name (canonical-slot)
541  (getf canonical-slot :name))
542
543(defun ensure-class (name &rest all-keys &allow-other-keys)
544  ;; Check for duplicate slots.
545  (let ((slots (getf all-keys :direct-slots)))
546    (dolist (s1 slots)
547      (let ((name1 (canonical-slot-name s1)))
548        (dolist (s2 (cdr (memq s1 slots)))
549          (when (eq name1 (canonical-slot-name s2))
550            (error 'program-error "Duplicate slot ~S" name1))))))
551  ;; Check for duplicate argument names in :DEFAULT-INITARGS.
552  (let ((names ()))
553    (do* ((initargs (getf all-keys :direct-default-initargs) (cddr initargs))
554          (name (car initargs) (car initargs)))
555         ((null initargs))
556      (push name names))
557    (do* ((names names (cdr names))
558          (name (car names) (car names)))
559         ((null names))
560      (when (memq name (cdr names))
561        (error 'program-error
562               :format-control "Duplicate initialization argument name ~S in :DEFAULT-INITARGS."
563               :format-arguments (list name)))))
564  (let ((direct-superclasses (getf all-keys :direct-superclasses)))
565    (dolist (class direct-superclasses)
566      (when (typep class 'built-in-class)
567        (error "Attempt to define a subclass of a built-in-class: ~S" class))))
568  (let ((old-class (find-class name nil)))
569    (cond ((and old-class (eq name (%class-name old-class)))
570           (cond ((typep old-class 'built-in-class)
571                  (error "The symbol ~S names a built-in class." name))
572                 ((typep old-class 'forward-referenced-class)
573                  (let ((new-class (apply #'make-instance-standard-class
574                                          (find-class 'standard-class)
575                                          :name name all-keys)))
576                    (%set-find-class name new-class)
577                    (dolist (subclass (class-direct-subclasses old-class))
578                      (setf (class-direct-superclasses subclass)
579                            (substitute new-class old-class
580                                        (class-direct-superclasses subclass))))
581                    new-class))
582                 (t
583                  ;; We're redefining the class.
584                  (%make-instances-obsolete old-class)
585                  (apply #'std-after-initialization-for-classes old-class all-keys)
586                  old-class)))
587          (t
588           (let ((class (apply #'make-instance-standard-class
589                               (find-class 'standard-class)
590                               :name name all-keys)))
591             (%set-find-class name class)
592             class)))))
593
594(defmacro defclass (&whole form name direct-superclasses direct-slots &rest options)
595  (unless (>= (length form) 3)
596    (error 'program-error "Wrong number of arguments for DEFCLASS."))
597  (check-declaration-type name)
598  `(ensure-class ',name
599                 :direct-superclasses
600                 (canonicalize-direct-superclasses ',direct-superclasses)
601                 :direct-slots
602                 ,(canonicalize-direct-slots direct-slots)
603                 ,@(canonicalize-defclass-options options)))
604
605(eval-when (:compile-toplevel :load-toplevel :execute)
606  (defstruct method-combination
607    name
608    operator
609    identity-with-one-argument
610    documentation)
611
612  (defun expand-short-defcombin (whole)
613    (let* ((name (cadr whole))
614           (documentation
615            (getf (cddr whole) :documentation ""))
616           (identity-with-one-arg
617            (getf (cddr whole) :identity-with-one-argument nil))
618           (operator
619            (getf (cddr whole) :operator name)))
620      `(progn
621         (setf (get ',name 'method-combination-object)
622               (make-method-combination :name ',name
623                                        :operator ',operator
624                                        :identity-with-one-argument ',identity-with-one-arg
625                                        :documentation ',documentation))
626         ',name)))
627
628  (defun expand-long-defcombin (whole)
629    (declare (ignore whole))
630    (error "The long form of DEFINE-METHOD-COMBINATION is not implemented.")))
631
632(defmacro define-method-combination (&whole form &rest args)
633  (declare (ignore args))
634  (if (and (cddr form)
635           (listp (caddr form)))
636      (expand-long-defcombin form)
637      (expand-short-defcombin form)))
638
639(define-method-combination +      :identity-with-one-argument t)
640(define-method-combination and    :identity-with-one-argument t)
641(define-method-combination append :identity-with-one-argument nil)
642(define-method-combination list   :identity-with-one-argument nil)
643(define-method-combination max    :identity-with-one-argument t)
644(define-method-combination min    :identity-with-one-argument t)
645(define-method-combination nconc  :identity-with-one-argument t)
646(define-method-combination or     :identity-with-one-argument t)
647(define-method-combination progn  :identity-with-one-argument t)
648
649(defstruct eql-specializer
650  object)
651
652(defparameter *eql-specializer-table* (make-hash-table :test 'eql))
653
654(defun intern-eql-specializer (object)
655  (or (gethash object *eql-specializer-table*)
656      (setf (gethash object *eql-specializer-table*)
657            (make-eql-specializer :object object))))
658
659;; MOP (p. 216) specifies the following reader generic functions:
660;;   generic-function-argument-precedence-order
661;;   generic-function-declarations
662;;   generic-function-lambda-list
663;;   generic-function-method-class
664;;   generic-function-method-combination
665;;   generic-function-methods
666;;   generic-function-name
667
668(defun generic-function-lambda-list (gf)
669  (%generic-function-lambda-list gf))
670(defsetf generic-function-lambda-list %set-generic-function-lambda-list)
671
672(defun (setf generic-function-documentation) (new-value gf)
673  (set-generic-function-documentation gf new-value))
674
675(defun (setf generic-function-initial-methods) (new-value gf)
676  (set-generic-function-initial-methods gf new-value))
677
678(defun (setf generic-function-methods) (new-value gf)
679  (set-generic-function-methods gf new-value))
680
681(defun (setf generic-function-method-class) (new-value gf)
682  (set-generic-function-method-class gf new-value))
683
684(defun (setf generic-function-method-combination) (new-value gf)
685  (set-generic-function-method-combination gf new-value))
686
687(defun (setf generic-function-argument-precedence-order) (new-value gf)
688  (set-generic-function-argument-precedence-order gf new-value))
689
690(declaim (ftype (function * t) classes-to-emf-table))
691(defun classes-to-emf-table (gf)
692  (generic-function-classes-to-emf-table gf))
693
694(defun (setf classes-to-emf-table) (new-value gf)
695  (set-generic-function-classes-to-emf-table gf new-value))
696
697(defvar the-class-standard-method (find-class 'standard-method))
698
699(defun (setf method-lambda-list) (new-value method)
700  (set-method-lambda-list method new-value))
701
702(defun (setf method-qualifiers) (new-value method)
703  (set-method-qualifiers method new-value))
704
705(defun (setf method-documentation) (new-value method)
706  (set-method-documentation method new-value))
707
708;;; defgeneric
709
710(defmacro defgeneric (function-name lambda-list
711                                    &rest options-and-method-descriptions)
712  (let ((options ())
713        (methods ())
714        (documentation nil))
715    (dolist (item options-and-method-descriptions)
716      (case (car item)
717        (declare) ; FIXME
718        (:documentation
719         (when documentation
720           (error 'program-error
721                  :format-control "Documentation option was specified twice for generic function ~S."
722                  :format-arguments (list function-name)))
723         (setf documentation t)
724         (push item options))
725        (:method
726         (push
727          `(push (defmethod ,function-name ,@(cdr item))
728                 (generic-function-initial-methods (fdefinition ',function-name)))
729          methods))
730        (t
731         (push item options))))
732    (setf options (nreverse options)
733          methods (nreverse methods))
734    `(prog1
735       (%defgeneric
736        ',function-name
737        :lambda-list ',lambda-list
738        ,@(canonicalize-defgeneric-options options))
739       ,@methods)))
740
741(defun canonicalize-defgeneric-options (options)
742  (mapappend #'canonicalize-defgeneric-option options))
743
744(defun canonicalize-defgeneric-option (option)
745  (case (car option)
746    (:generic-function-class
747     (list :generic-function-class `(find-class ',(cadr option))))
748    (:method-class
749     (list :method-class `(find-class ',(cadr option))))
750    (:method-combination
751     (list :method-combination `',(cdr option)))
752    (:argument-precedence-order
753     (list :argument-precedence-order `',(cdr option)))
754    (t
755     (list `',(car option) `',(cadr option)))))
756
757;; From OpenMCL.
758(defun canonicalize-argument-precedence-order (apo req)
759  (cond ((equal apo req) nil)
760        ((not (eql (length apo) (length req)))
761         (error 'program-error
762                :format-control "Specified argument precedence order ~S does not match lambda list."
763                :format-arguments (list apo)))
764        (t (let ((res nil))
765             (dolist (arg apo (nreverse res))
766               (let ((index (position arg req)))
767                 (if (or (null index) (memq index res))
768                     (error 'program-error
769                            :format-control "Specified argument precedence order ~S does not match lambda list."
770                            :format-arguments (list apo)))
771                 (push index res)))))))
772
773(defun find-generic-function (name &optional (errorp t))
774  (let ((function (and (fboundp name) (fdefinition name))))
775    (when function
776      (when (typep function 'generic-function)
777        (return-from find-generic-function function))
778      (when (and *traced-names* (find name *traced-names* :test #'equal))
779        (setf function (untraced-function name))
780        (when (typep function 'generic-function)
781          (return-from find-generic-function function)))))
782  (if errorp
783      (error "There is no generic function named ~S." name)
784      nil))
785
786(defun lambda-lists-congruent-p (lambda-list1 lambda-list2)
787  (let* ((plist1 (analyze-lambda-list lambda-list1))
788         (args1 (getf plist1 :required-args))
789         (plist2 (analyze-lambda-list lambda-list2))
790         (args2 (getf plist2 :required-args)))
791    (= (length args1) (length args2))))
792
793(defun %defgeneric (function-name &rest all-keys)
794  (when (fboundp function-name)
795    (let ((gf (fdefinition function-name)))
796      (when (typep gf 'generic-function)
797        ;; Remove methods defined by previous DEFGENERIC forms.
798        (dolist (method (generic-function-initial-methods gf))
799          (%remove-method gf method))
800        (setf (generic-function-initial-methods gf) '()))))
801  (apply 'ensure-generic-function function-name all-keys))
802
803(defun ensure-generic-function (function-name
804                                &rest all-keys
805                                &key
806                                lambda-list
807                                (generic-function-class (find-class 'standard-generic-function))
808                                (method-class the-class-standard-method)
809                                (method-combination 'standard)
810                                (argument-precedence-order nil apo-p)
811                                documentation
812                                &allow-other-keys)
813  (when (autoloadp function-name)
814    (resolve function-name))
815  (let ((gf (find-generic-function function-name nil)))
816    (if gf
817        (progn
818          (unless (or (null (generic-function-methods gf))
819                      (lambda-lists-congruent-p lambda-list (generic-function-lambda-list gf)))
820            (error 'simple-error
821                   :format-control "The lambda list ~S is incompatible with the existing methods of ~S."
822                   :format-arguments (list lambda-list gf)))
823          (setf (generic-function-lambda-list gf) lambda-list)
824          (setf (generic-function-documentation gf) documentation)
825          (let* ((plist (analyze-lambda-list lambda-list))
826                 (required-args (getf plist ':required-args)))
827            (%set-gf-required-args gf required-args)
828            (when apo-p
829              (setf (generic-function-argument-precedence-order gf)
830                    (if argument-precedence-order
831                        (canonicalize-argument-precedence-order argument-precedence-order
832                                                                required-args)
833                        nil)))
834            (finalize-generic-function gf))
835          gf)
836        (progn
837          (when (fboundp function-name)
838            (error 'program-error
839                   :format-control "~A already names an ordinary function, macro, or special operator."
840                   :format-arguments (list function-name)))
841          (setf gf (apply (if (eq generic-function-class (find-class 'standard-generic-function))
842                              #'make-instance-standard-generic-function
843                              #'make-instance)
844                          generic-function-class
845                          :name function-name
846                          :method-class method-class
847                          :method-combination method-combination
848                          all-keys))
849          gf))))
850
851(defun initial-discriminating-function (gf args)
852  (set-funcallable-instance-function
853   gf
854   (funcall (if (eq (class-of gf) (find-class 'standard-generic-function))
855                #'std-compute-discriminating-function
856                #'compute-discriminating-function)
857            gf))
858  (apply gf args))
859
860(defun finalize-generic-function (gf)
861  (%finalize-generic-function gf)
862  (setf (classes-to-emf-table gf) (make-hash-table :test #'equal))
863  (set-funcallable-instance-function
864   gf
865   (make-closure `(lambda (&rest args)
866                    (initial-discriminating-function ,gf args))
867                 nil))
868  ;; FIXME Do we need to warn on redefinition somewhere else?
869  (let ((*warn-on-redefinition* nil))
870    (setf (fdefinition (%generic-function-name gf)) gf))
871  (values))
872
873(defun make-instance-standard-generic-function (generic-function-class
874                                                &key name lambda-list
875                                                method-class
876                                                method-combination
877                                                argument-precedence-order
878                                                documentation)
879  (declare (ignore generic-function-class))
880  (let ((gf (std-allocate-instance (find-class 'standard-generic-function))))
881    (%set-generic-function-name gf name)
882    (setf (generic-function-lambda-list gf) lambda-list)
883    (setf (generic-function-initial-methods gf) ())
884    (setf (generic-function-methods gf) ())
885    (setf (generic-function-method-class gf) method-class)
886    (setf (generic-function-method-combination gf) method-combination)
887    (setf (generic-function-documentation gf) documentation)
888    (setf (classes-to-emf-table gf) nil)
889    (let* ((plist (analyze-lambda-list (generic-function-lambda-list gf)))
890           (required-args (getf plist ':required-args)))
891      (%set-gf-required-args gf required-args)
892      (setf (generic-function-argument-precedence-order gf)
893            (if argument-precedence-order
894                (canonicalize-argument-precedence-order argument-precedence-order
895                                                        required-args)
896                nil)))
897    (finalize-generic-function gf)
898    gf))
899
900(defun canonicalize-specializers (specializers)
901  (mapcar #'canonicalize-specializer specializers))
902
903(defun canonicalize-specializer (specializer)
904  (cond ((classp specializer)
905         specializer)
906        ((eql-specializer-p specializer)
907         specializer)
908        ((symbolp specializer)
909         (find-class specializer))
910        ((and (consp specializer)
911              (eq (car specializer) 'eql))
912         (let ((object (cadr specializer)))
913           (when (and (consp object)
914                      (eq (car object) 'quote))
915             (setf object (cadr object)))
916           (intern-eql-specializer object)))
917  ((and (consp specializer)
918              (eq (car specializer) 'java:jclass))
919         (let ((class-name (cadr specializer)))
920           (when (and (consp class-name)
921                      (eq (car class-name) 'quote))
922             (setf class-name (cadr class-name)))
923           (java::%find-java-class class-name)))
924        (t
925         (error "Unknown specializer: ~S" specializer))))
926
927(defun parse-defmethod (args)
928  (let ((function-name (car args))
929        (qualifiers ())
930        (specialized-lambda-list ())
931        (body ())
932        (parse-state :qualifiers))
933    (dolist (arg (cdr args))
934      (ecase parse-state
935        (:qualifiers
936         (if (and (atom arg) (not (null arg)))
937             (push arg qualifiers)
938             (progn
939               (setf specialized-lambda-list arg)
940               (setf parse-state :body))))
941        (:body (push arg body))))
942    (setf qualifiers (nreverse qualifiers)
943          body (nreverse body))
944    (multiple-value-bind (real-body declarations documentation)
945        (parse-body body)
946      (values function-name
947              qualifiers
948              (extract-lambda-list specialized-lambda-list)
949              (extract-specializers specialized-lambda-list)
950              documentation
951              declarations
952              (list* 'block
953                     (fdefinition-block-name function-name)
954                     real-body)))))
955
956(defun required-portion (gf args)
957  (let ((number-required (length (gf-required-args gf))))
958    (when (< (length args) number-required)
959      (error 'program-error
960             :format-control "Not enough arguments for generic function ~S."
961             :format-arguments (list (%generic-function-name gf))))
962    (subseq args 0 number-required)))
963
964(defun extract-lambda-list (specialized-lambda-list)
965  (let* ((plist (analyze-lambda-list specialized-lambda-list))
966         (requireds (getf plist :required-names))
967         (rv (getf plist :rest-var))
968         (ks (getf plist :key-args))
969         (keysp (getf plist :keysp))
970         (aok (getf plist :allow-other-keys))
971         (opts (getf plist :optional-args))
972         (auxs (getf plist :auxiliary-args)))
973    `(,@requireds
974      ,@(if rv `(&rest ,rv) ())
975      ,@(if (or ks keysp aok) `(&key ,@ks) ())
976      ,@(if aok '(&allow-other-keys) ())
977      ,@(if opts `(&optional ,@opts) ())
978      ,@(if auxs `(&aux ,@auxs) ()))))
979
980(defun extract-specializers (specialized-lambda-list)
981  (let ((plist (analyze-lambda-list specialized-lambda-list)))
982    (getf plist ':specializers)))
983
984(defun get-keyword-from-arg (arg)
985  (if (listp arg)
986      (if (listp (car arg))
987          (caar arg)
988          (make-keyword (car arg)))
989      (make-keyword arg)))
990
991(defun analyze-lambda-list (lambda-list)
992  (let ((keys ())           ; Just the keywords
993        (key-args ())       ; Keywords argument specs
994        (keysp nil)         ;
995        (required-names ()) ; Just the variable names
996        (required-args ())  ; Variable names & specializers
997        (specializers ())   ; Just the specializers
998        (rest-var nil)
999        (optionals ())
1000        (auxs ())
1001        (allow-other-keys nil)
1002        (state :parsing-required))
1003    (dolist (arg lambda-list)
1004      (if (member arg lambda-list-keywords)
1005          (ecase arg
1006            (&optional
1007             (setq state :parsing-optional))
1008            (&rest
1009             (setq state :parsing-rest))
1010            (&key
1011             (setq keysp t)
1012             (setq state :parsing-key))
1013            (&allow-other-keys
1014             (setq allow-other-keys 't))
1015            (&aux
1016             (setq state :parsing-aux)))
1017          (case state
1018            (:parsing-required
1019             (push-on-end arg required-args)
1020             (if (listp arg)
1021                 (progn (push-on-end (car arg) required-names)
1022                   (push-on-end (cadr arg) specializers))
1023                 (progn (push-on-end arg required-names)
1024                   (push-on-end 't specializers))))
1025            (:parsing-optional (push-on-end arg optionals))
1026            (:parsing-rest (setq rest-var arg))
1027            (:parsing-key
1028             (push-on-end (get-keyword-from-arg arg) keys)
1029             (push-on-end arg key-args))
1030            (:parsing-aux (push-on-end arg auxs)))))
1031    (list  :required-names required-names
1032           :required-args required-args
1033           :specializers specializers
1034           :rest-var rest-var
1035           :keywords keys
1036           :key-args key-args
1037           :keysp keysp
1038           :auxiliary-args auxs
1039           :optional-args optionals
1040           :allow-other-keys allow-other-keys)))
1041
1042#+nil
1043(defun check-method-arg-info (gf arg-info method)
1044  (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
1045      (analyze-lambda-list (if (consp method)
1046                               (early-method-lambda-list method)
1047                               (method-lambda-list method)))
1048    (flet ((lose (string &rest args)
1049                 (error 'simple-program-error
1050                        :format-control "~@<attempt to add the method~2I~_~S~I~_~
1051                        to the generic function~2I~_~S;~I~_~
1052                        but ~?~:>"
1053                        :format-arguments (list method gf string args)))
1054           (comparison-description (x y)
1055                                   (if (> x y) "more" "fewer")))
1056      (let ((gf-nreq (arg-info-number-required arg-info))
1057            (gf-nopt (arg-info-number-optional arg-info))
1058            (gf-key/rest-p (arg-info-key/rest-p arg-info))
1059            (gf-keywords (arg-info-keys arg-info)))
1060        (unless (= nreq gf-nreq)
1061          (lose
1062           "the method has ~A required arguments than the generic function."
1063           (comparison-description nreq gf-nreq)))
1064        (unless (= nopt gf-nopt)
1065          (lose
1066           "the method has ~A optional arguments than the generic function."
1067           (comparison-description nopt gf-nopt)))
1068        (unless (eq (or keysp restp) gf-key/rest-p)
1069          (lose
1070           "the method and generic function differ in whether they accept~_~
1071            &REST or &KEY arguments."))
1072        (when (consp gf-keywords)
1073          (unless (or (and restp (not keysp))
1074                      allow-other-keys-p
1075                      (every (lambda (k) (memq k keywords)) gf-keywords))
1076            (lose "the method does not accept each of the &KEY arguments~2I~_~
1077            ~S."
1078                  gf-keywords)))))))
1079
1080(defun check-method-lambda-list (method-lambda-list gf-lambda-list)
1081  (let* ((gf-restp (not (null (memq '&rest gf-lambda-list))))
1082         (gf-plist (analyze-lambda-list gf-lambda-list))
1083         (gf-keysp (getf gf-plist :keysp))
1084         (gf-keywords (getf gf-plist :keywords))
1085         (method-plist (analyze-lambda-list method-lambda-list))
1086         (method-restp (not (null (memq '&rest method-lambda-list))))
1087         (method-keysp (getf method-plist :keysp))
1088         (method-keywords (getf method-plist :keywords))
1089         (method-allow-other-keys-p (getf method-plist :allow-other-keys)))
1090    (unless (= (length (getf gf-plist :required-args))
1091               (length (getf method-plist :required-args)))
1092      (error "The method has the wrong number of required arguments for the generic function."))
1093    (unless (= (length (getf gf-plist :optional-args))
1094               (length (getf method-plist :optional-args)))
1095      (error "The method has the wrong number of optional arguments for the generic function."))
1096    (unless (eq (or gf-restp gf-keysp) (or method-restp method-keysp))
1097      (error "The method and the generic function differ in whether they accept &REST or &KEY arguments."))
1098    (when (consp gf-keywords)
1099      (unless (or (and method-restp (not method-keysp))
1100                  method-allow-other-keys-p
1101                  (every (lambda (k) (memq k method-keywords)) gf-keywords))
1102        (error "The method does not accept all of the keyword arguments defined for the generic function.")))))
1103
1104(declaim (ftype (function * method) ensure-method))
1105(defun ensure-method (name &rest all-keys)
1106  (let ((method-lambda-list (getf all-keys :lambda-list))
1107        (gf (find-generic-function name nil)))
1108    (if gf
1109        (check-method-lambda-list method-lambda-list (generic-function-lambda-list gf))
1110        (setf gf (ensure-generic-function name :lambda-list method-lambda-list)))
1111    (let ((method
1112           (if (eq (generic-function-method-class gf) the-class-standard-method)
1113               (apply #'make-instance-standard-method gf all-keys)
1114               (apply #'make-instance (generic-function-method-class gf) all-keys))))
1115      (%add-method gf method)
1116      method)))
1117
1118(defun make-instance-standard-method (gf
1119                                      &key
1120                                      lambda-list
1121                                      qualifiers
1122                                      specializers
1123                                      documentation
1124                                      function
1125                                      fast-function)
1126  (declare (ignore gf))
1127  (let ((method (std-allocate-instance the-class-standard-method)))
1128    (setf (method-lambda-list method) lambda-list)
1129    (setf (method-qualifiers method) qualifiers)
1130    (%set-method-specializers method (canonicalize-specializers specializers))
1131    (setf (method-documentation method) documentation)
1132    (%set-method-generic-function method nil)
1133    (%set-method-function method function)
1134    (%set-method-fast-function method fast-function)
1135    method))
1136
1137(defun %add-method (gf method)
1138  (when (%method-generic-function method)
1139    (error 'simple-error
1140           :format-control "ADD-METHOD: ~S is a method of ~S."
1141           :format-arguments (list method (%method-generic-function method))))
1142  ;; Remove existing method with same qualifiers and specializers (if any).
1143  (let ((old-method (%find-method gf (method-qualifiers method)
1144                                 (%method-specializers method) nil)))
1145    (when old-method
1146      (%remove-method gf old-method)))
1147  (%set-method-generic-function method gf)
1148  (push method (generic-function-methods gf))
1149  (dolist (specializer (%method-specializers method))
1150    (when (typep specializer 'class) ;; FIXME What about EQL specializer objects?
1151      (pushnew method (class-direct-methods specializer))))
1152  (finalize-generic-function gf)
1153  gf)
1154
1155(defun %remove-method (gf method)
1156  (setf (generic-function-methods gf)
1157        (remove method (generic-function-methods gf)))
1158  (%set-method-generic-function method nil)
1159  (dolist (specializer (%method-specializers method))
1160    (when (typep specializer 'class) ;; FIXME What about EQL specializer objects?
1161      (setf (class-direct-methods specializer)
1162            (remove method (class-direct-methods specializer)))))
1163  (finalize-generic-function gf)
1164  gf)
1165
1166(defun %find-method (gf qualifiers specializers &optional (errorp t))
1167  ;; "If the specializers argument does not correspond in length to the number
1168  ;; of required arguments of the generic-function, an an error of type ERROR
1169  ;; is signaled."
1170  (unless (= (length specializers) (length (gf-required-args gf)))
1171    (error "The specializers argument has length ~S, but ~S has ~S required parameters."
1172           (length specializers)
1173           gf
1174           (length (gf-required-args gf))))
1175  (let* ((canonical-specializers (canonicalize-specializers specializers))
1176         (method
1177          (find-if #'(lambda (method)
1178                      (and (equal qualifiers
1179                                  (method-qualifiers method))
1180                           (equal canonical-specializers
1181                                  (%method-specializers method))))
1182                   (generic-function-methods gf))))
1183    (if (and (null method) errorp)
1184        (error "No such method for ~S." (%generic-function-name gf))
1185        method)))
1186
1187(defun methods-contain-eql-specializer-p (methods)
1188  (dolist (method methods nil)
1189    (when (dolist (spec (%method-specializers method) nil)
1190            (when (eql-specializer-p spec) (return t)))
1191      (return t))))
1192
1193(defun fast-callable-p (gf)
1194  (and (eq (generic-function-method-combination gf) 'standard)
1195       (null (intersection (%generic-function-lambda-list gf)
1196                           '(&rest &optional &key &allow-other-keys &aux)))))
1197
1198(declaim (ftype (function * t) slow-method-lookup-1))
1199
1200(declaim (ftype (function (t t t) t) slow-reader-lookup))
1201(defun slow-reader-lookup (gf layout slot-name)
1202  (let ((location (layout-slot-location layout slot-name)))
1203    (cache-slot-location gf layout location)
1204    location))
1205
1206(defun std-compute-discriminating-function (gf)
1207  (let ((code
1208         (cond ((methods-contain-eql-specializer-p (generic-function-methods gf))
1209                (make-closure `(lambda (&rest args)
1210                                 (slow-method-lookup ,gf args))
1211                              nil))
1212               ((and (= (length (generic-function-methods gf)) 1)
1213                     (typep (car (generic-function-methods gf)) 'standard-reader-method))
1214;;                 (sys::%format t "standard reader function ~S~%" (generic-function-name gf))
1215                (make-closure
1216                 (let* ((method (%car (generic-function-methods gf)))
1217                        (class (car (%method-specializers method)))
1218                        (slot-name (reader-method-slot-name method)))
1219                   `(lambda (arg)
1220                      (declare (optimize speed))
1221                      (let* ((layout (std-instance-layout arg))
1222                             (location (get-cached-slot-location ,gf layout)))
1223                        (unless location
1224                          (unless (simple-typep arg ,class)
1225                            ;; FIXME no applicable method
1226                            (error 'simple-type-error
1227                                   :datum arg
1228                                   :expected-type ,class))
1229                          (setf location (slow-reader-lookup ,gf layout ',slot-name)))
1230                        (if (consp location)
1231                            ;; Shared slot.
1232                            (cdr location)
1233                            (standard-instance-access arg location)))))
1234                 nil))
1235               (t
1236                (let* ((emf-table (classes-to-emf-table gf))
1237                       (number-required (length (gf-required-args gf)))
1238                       (lambda-list (%generic-function-lambda-list gf))
1239                       (exact (null (intersection lambda-list
1240                                                  '(&rest &optional &key
1241                                                    &allow-other-keys &aux)))))
1242                  (make-closure
1243                   (cond ((= number-required 1)
1244                          (if exact
1245                              (cond ((and (eq (generic-function-method-combination gf) 'standard)
1246                                          (= (length (generic-function-methods gf)) 1))
1247                                     (let* ((method (%car (generic-function-methods gf)))
1248                                            (class (car (%method-specializers method)))
1249                                            (function (or (%method-fast-function method)
1250                                                          (%method-function method))))
1251                                       `(lambda (arg)
1252                                          (declare (optimize speed))
1253                                          (unless (simple-typep arg ,class)
1254                                            ;; FIXME no applicable method
1255                                            (error 'simple-type-error
1256                                                   :datum arg
1257                                                   :expected-type ,class))
1258                                          (funcall ,function arg))))
1259                                    (t
1260                                     `(lambda (arg)
1261                                        (declare (optimize speed))
1262                                        (let* ((class (class-of arg))
1263                                               (emfun (or (gethash1 class ,emf-table)
1264                                                          (slow-method-lookup-1 ,gf class))))
1265                                          (if emfun
1266                                              (funcall emfun (list arg))
1267                                              (apply #'no-applicable-method ,gf (list arg)))))
1268                                     ))
1269                              `(lambda (&rest args)
1270                                 (declare (optimize speed))
1271                                 (unless (>= (length args) 1)
1272                                   (error 'program-error
1273                                          :format-control "Not enough arguments for generic function ~S."
1274                                          :format-arguments (list (%generic-function-name ,gf))))
1275                                 (let ((emfun (get-cached-emf ,gf args)))
1276                                   (if emfun
1277                                       (funcall emfun args)
1278                                       (slow-method-lookup ,gf args))))))
1279                         ((= number-required 2)
1280                          (if exact
1281                              `(lambda (arg1 arg2)
1282                                 (declare (optimize speed))
1283                                 (let* ((args (list arg1 arg2))
1284                                        (emfun (get-cached-emf ,gf args)))
1285                                   (if emfun
1286                                       (funcall emfun args)
1287                                       (slow-method-lookup ,gf args))))
1288                              `(lambda (&rest args)
1289                                 (declare (optimize speed))
1290                                 (unless (>= (length args) 2)
1291                                   (error 'program-error
1292                                          :format-control "Not enough arguments for generic function ~S."
1293                                          :format-arguments (list (%generic-function-name ,gf))))
1294                                 (let ((emfun (get-cached-emf ,gf args)))
1295                                   (if emfun
1296                                       (funcall emfun args)
1297                                       (slow-method-lookup ,gf args))))))
1298                         ((= number-required 3)
1299                          (if exact
1300                              `(lambda (arg1 arg2 arg3)
1301                                 (declare (optimize speed))
1302                                 (let* ((args (list arg1 arg2 arg3))
1303                                        (emfun (get-cached-emf ,gf args)))
1304                                   (if emfun
1305                                       (funcall emfun args)
1306                                       (slow-method-lookup ,gf args))))
1307                              `(lambda (&rest args)
1308                                 (declare (optimize speed))
1309                                 (unless (>= (length args) 3)
1310                                   (error 'program-error
1311                                          :format-control "Not enough arguments for generic function ~S."
1312                                          :format-arguments (list (%generic-function-name ,gf))))
1313                                 (let ((emfun (get-cached-emf ,gf args)))
1314                                   (if emfun
1315                                       (funcall emfun args)
1316                                       (slow-method-lookup ,gf args))))))
1317                         (t
1318                          `(lambda (&rest args)
1319                             (declare (optimize speed))
1320                             (unless (,(if exact '= '>=) (length args) ,number-required)
1321                               (error 'program-error
1322                                      :format-control "Not enough arguments for generic function ~S."
1323                                      :format-arguments (list (%generic-function-name ,gf))))
1324                             (let ((emfun (get-cached-emf ,gf args)))
1325                               (if emfun
1326                                   (funcall emfun args)
1327                                   (slow-method-lookup ,gf args))))))
1328                   nil))))))
1329
1330    (when (and (fboundp 'compile)
1331               (not (autoloadp 'compile)))
1332      (setf code (or (compile nil code) code)))
1333
1334    code))
1335
1336(defun method-applicable-p (method args)
1337  (do* ((specializers (%method-specializers method) (cdr specializers))
1338        (args args (cdr args)))
1339       ((null specializers) t)
1340    (let ((specializer (car specializers)))
1341      (if (typep specializer 'eql-specializer)
1342          (unless (eql (car args) (eql-specializer-object specializer))
1343            (return nil))
1344          (unless (subclassp (class-of (car args)) specializer)
1345            (return nil))))))
1346
1347(defun %compute-applicable-methods (gf args)
1348  (let ((required-classes (mapcar #'class-of (required-portion gf args)))
1349        (methods '()))
1350    (dolist (method (generic-function-methods gf))
1351      (when (method-applicable-p method args)
1352        (push method methods)))
1353    (if (or (null methods) (null (%cdr methods)))
1354        methods
1355        (sort methods
1356              (if (eq (class-of gf) (find-class 'standard-generic-function))
1357                  #'(lambda (m1 m2)
1358                     (std-method-more-specific-p m1 m2 required-classes
1359                                                 (generic-function-argument-precedence-order gf)))
1360                  #'(lambda (m1 m2)
1361                     (method-more-specific-p gf m1 m2 required-classes)))))))
1362
1363(defun method-applicable-p-using-classes (method classes)
1364  (do* ((specializers (%method-specializers method) (cdr specializers))
1365        (classes classes (cdr classes)))
1366       ((null specializers) t)
1367    (let ((specializer (car specializers)))
1368      (unless (subclassp (car classes) specializer)
1369        (return nil)))))
1370
1371(defun %compute-applicable-methods-using-classes (gf required-classes)
1372  (let ((methods '()))
1373    (dolist (method (generic-function-methods gf))
1374      (when (method-applicable-p-using-classes method required-classes)
1375        (push method methods)))
1376    (if (or (null methods) (null (%cdr methods)))
1377        methods
1378        (sort methods
1379              (if (eq (class-of gf) (find-class 'standard-generic-function))
1380                  #'(lambda (m1 m2)
1381                     (std-method-more-specific-p m1 m2 required-classes
1382                                                 (generic-function-argument-precedence-order gf)))
1383                  #'(lambda (m1 m2)
1384                     (method-more-specific-p gf m1 m2 required-classes)))))))
1385
1386(defun slow-method-lookup (gf args)
1387  (let ((applicable-methods (%compute-applicable-methods gf args)))
1388    (if applicable-methods
1389        (let ((emfun (funcall (if (eq (class-of gf) (find-class 'standard-generic-function))
1390                                  #'std-compute-effective-method-function
1391                                  #'compute-effective-method-function)
1392                              gf applicable-methods)))
1393          (cache-emf gf args emfun)
1394          (funcall emfun args))
1395        (apply #'no-applicable-method gf args))))
1396
1397(defun slow-method-lookup-1 (gf class)
1398  (let ((applicable-methods (%compute-applicable-methods-using-classes gf (list class))))
1399    (if applicable-methods
1400        (let ((emfun (funcall (if (eq (class-of gf) (find-class 'standard-generic-function))
1401                                  #'std-compute-effective-method-function
1402                                  #'compute-effective-method-function)
1403                              gf applicable-methods)))
1404          (when emfun
1405            (setf (gethash class (classes-to-emf-table gf)) emfun))
1406          emfun))))
1407
1408(defun sub-specializer-p (c1 c2 c-arg)
1409  (find c2 (cdr (memq c1 (%class-precedence-list c-arg)))))
1410
1411(defun std-method-more-specific-p (method1 method2 required-classes argument-precedence-order)
1412  (if argument-precedence-order
1413      (let ((specializers-1 (%method-specializers method1))
1414            (specializers-2 (%method-specializers method2)))
1415        (dolist (index argument-precedence-order)
1416          (let ((spec1 (nth index specializers-1))
1417                (spec2 (nth index specializers-2)))
1418            (unless (eq spec1 spec2)
1419              (cond ((eql-specializer-p spec1)
1420                     (return t))
1421                    ((eql-specializer-p spec2)
1422                     (return nil))
1423                    (t
1424                     (return (sub-specializer-p spec1 spec2
1425                                                (nth index required-classes)))))))))
1426      (do ((specializers-1 (%method-specializers method1) (cdr specializers-1))
1427           (specializers-2 (%method-specializers method2) (cdr specializers-2))
1428           (classes required-classes (cdr classes)))
1429          ((null specializers-1) nil)
1430        (let ((spec1 (car specializers-1))
1431              (spec2 (car specializers-2)))
1432          (unless (eq spec1 spec2)
1433            (cond ((eql-specializer-p spec1)
1434                   (return t))
1435                  ((eql-specializer-p spec2)
1436                   (return nil))
1437                  (t
1438                   (return (sub-specializer-p spec1 spec2 (car classes))))))))))
1439
1440(defun primary-method-p (method)
1441  (null (intersection '(:before :after :around) (method-qualifiers method))))
1442
1443(defun before-method-p (method)
1444  (equal '(:before) (method-qualifiers method)))
1445
1446(defun after-method-p (method)
1447  (equal '(:after) (method-qualifiers method)))
1448
1449(defun around-method-p (method)
1450  (equal '(:around) (method-qualifiers method)))
1451
1452(defun std-compute-effective-method-function (gf methods)
1453  (let* ((mc (generic-function-method-combination gf))
1454         (mc-name (if (atom mc) mc (%car mc)))
1455         (options (if (atom mc) '() (%cdr mc)))
1456         (order (car options))
1457         (primaries '())
1458         (arounds '())
1459         around
1460         emf-form)
1461    (dolist (m methods)
1462      (let ((qualifiers (method-qualifiers m)))
1463        (cond ((null qualifiers)
1464               (if (eq mc-name 'standard)
1465                   (push m primaries)
1466                   (error "Method combination type mismatch.")))
1467              ((cdr qualifiers)
1468               (error "Invalid method qualifiers."))
1469              ((eq (car qualifiers) :around)
1470               (push m arounds))
1471              ((eq (car qualifiers) mc-name)
1472               (push m primaries))
1473              ((memq (car qualifiers) '(:before :after)))
1474              (t
1475               (error "Invalid method qualifiers.")))))
1476    (unless (eq order :most-specific-last)
1477      (setf primaries (nreverse primaries)))
1478    (setf arounds (nreverse arounds))
1479    (setf around (car arounds))
1480    (when (null primaries)
1481      (error "No primary methods for the generic function ~S." gf))
1482    (cond (around
1483           (let ((next-emfun
1484                  (funcall
1485                   (if (eq (class-of gf) (find-class 'standard-generic-function))
1486                       #'std-compute-effective-method-function
1487                       #'compute-effective-method-function)
1488                   gf (remove around methods))))
1489             (setf emf-form
1490;;                    `(lambda (args)
1491;;                       (funcall ,(%method-function around) args ,next-emfun))
1492                   (generate-emf-lambda (%method-function around) next-emfun)
1493                   )))
1494          ((eq mc-name 'standard)
1495           (let* ((next-emfun (compute-primary-emfun (cdr primaries)))
1496                  (befores (remove-if-not #'before-method-p methods))
1497                  (reverse-afters
1498                   (reverse (remove-if-not #'after-method-p methods))))
1499             (setf emf-form
1500                   (cond ((and (null befores) (null reverse-afters))
1501                          (if (%method-fast-function (car primaries))
1502                              (ecase (length (gf-required-args gf))
1503                                (1
1504                                 `(lambda (args)
1505                                    (declare (optimize speed))
1506                                    (funcall ,(%method-fast-function (car primaries)) (car args))))
1507                                (2
1508                                 `(lambda (args)
1509                                    (declare (optimize speed))
1510                                    (funcall ,(%method-fast-function (car primaries))
1511                                             (car args)
1512                                             (cadr args)))))
1513;;                               `(lambda (args)
1514;;                                  (declare (optimize speed))
1515;;                                  (funcall ,(%method-function (car primaries)) args ,next-emfun))
1516                              (generate-emf-lambda (%method-function (car primaries))
1517                                                   next-emfun)
1518                              ))
1519                         (t
1520                          `(lambda (args)
1521                             (declare (optimize speed))
1522                             (dolist (before ',befores)
1523                               (funcall (%method-function before) args nil))
1524                             (multiple-value-prog1
1525                              (funcall (%method-function ,(car primaries)) args ,next-emfun)
1526                              (dolist (after ',reverse-afters)
1527                                (funcall (%method-function after) args nil)))))))))
1528          (t
1529           (let ((mc-obj (get mc-name 'method-combination-object)))
1530             (unless mc-obj
1531               (error "Unsupported method combination type ~A." mc-name))
1532             (let* ((operator (method-combination-operator mc-obj))
1533                    (ioa (method-combination-identity-with-one-argument mc-obj)))
1534               (setf emf-form
1535                     (if (and (null (cdr primaries))
1536                              (not (null ioa)))
1537;;                          `(lambda (args)
1538;;                             (funcall ,(%method-function (car primaries)) args nil))
1539                         (generate-emf-lambda (%method-function (car primaries)) nil)
1540                         `(lambda (args)
1541                            (,operator ,@(mapcar
1542                                          (lambda (primary)
1543                                            `(funcall ,(%method-function primary) args nil))
1544                                          primaries)))))))))
1545    (or (ignore-errors (compile nil emf-form))
1546        (coerce-to-function emf-form))))
1547
1548(defun generate-emf-lambda (method-function next-emfun)
1549  `(lambda (args)
1550     (declare (optimize speed))
1551     (funcall ,method-function args ,next-emfun)))
1552
1553;;; compute an effective method function from a list of primary methods:
1554
1555(defun compute-primary-emfun (methods)
1556  (if (null methods)
1557      nil
1558      (let ((next-emfun (compute-primary-emfun (cdr methods))))
1559        #'(lambda (args)
1560           (funcall (%method-function (car methods)) args next-emfun)))))
1561
1562(defvar *call-next-method-p*)
1563(defvar *next-method-p-p*)
1564
1565(defun walk-form (form)
1566  (cond ((atom form)
1567         (cond ((eq form 'call-next-method)
1568                (setf *call-next-method-p* t))
1569               ((eq form 'next-method-p)
1570                (setf *next-method-p-p* t))))
1571        (t
1572         (walk-form (%car form))
1573         (walk-form (%cdr form)))))
1574
1575(defun compute-method-function (lambda-expression)
1576  (let ((lambda-list (allow-other-keys (cadr lambda-expression)))
1577        (body (cddr lambda-expression))
1578        (*call-next-method-p* nil)
1579        (*next-method-p-p* nil))
1580    (multiple-value-bind (body declarations) (parse-body body)
1581      (let ((ignorable-vars '()))
1582        (dolist (var lambda-list)
1583          (if (memq var lambda-list-keywords)
1584              (return)
1585              (push var ignorable-vars)))
1586        (push `(declare (ignorable ,@ignorable-vars)) declarations))
1587      (walk-form body)
1588      (cond ((or *call-next-method-p* *next-method-p-p*)
1589             `(lambda (args next-emfun)
1590                (flet ((call-next-method (&rest cnm-args)
1591                         (if (null next-emfun)
1592                             (error "No next method for generic function.")
1593                             (funcall next-emfun (or cnm-args args))))
1594                       (next-method-p ()
1595                         (not (null next-emfun))))
1596                  (declare (ignorable call-next-method next-method-p))
1597                  (apply #'(lambda ,lambda-list ,@declarations ,@body) args))))
1598            ((null (intersection lambda-list '(&rest &optional &key &allow-other-keys &aux)))
1599             ;; Required parameters only.
1600             (case (length lambda-list)
1601               (1
1602                `(lambda (args next-emfun)
1603                   (declare (ignore next-emfun))
1604                   (let ((,(%car lambda-list) (%car args)))
1605                     (declare (ignorable ,(%car lambda-list)))
1606                     ,@declarations ,@body)))
1607               (2
1608                `(lambda (args next-emfun)
1609                   (declare (ignore next-emfun))
1610                   (let ((,(%car lambda-list) (%car args))
1611                         (,(%cadr lambda-list) (%cadr args)))
1612                     (declare (ignorable ,(%car lambda-list)
1613                                         ,(%cadr lambda-list)))
1614                     ,@declarations ,@body)))
1615               (3
1616                `(lambda (args next-emfun)
1617                   (declare (ignore next-emfun))
1618                   (let ((,(%car lambda-list) (%car args))
1619                         (,(%cadr lambda-list) (%cadr args))
1620                         (,(%caddr lambda-list) (%caddr args)))
1621                     (declare (ignorable ,(%car lambda-list)
1622                                         ,(%cadr lambda-list)
1623                                         ,(%caddr lambda-list)))
1624                     ,@declarations ,@body)))
1625               (t
1626                `(lambda (args next-emfun)
1627                   (declare (ignore next-emfun))
1628                   (apply #'(lambda ,lambda-list ,@declarations ,@body) args)))))
1629            (t
1630             `(lambda (args next-emfun)
1631                (declare (ignore next-emfun))
1632                (apply #'(lambda ,lambda-list ,@declarations ,@body) args)))))))
1633
1634(defun compute-method-fast-function (lambda-expression)
1635  (let ((lambda-list (allow-other-keys (cadr lambda-expression))))
1636    (when (intersection lambda-list '(&rest &optional &key &allow-other-keys &aux))
1637      (return-from compute-method-fast-function nil))
1638    ;; Only required args.
1639    (let ((body (cddr lambda-expression))
1640          (*call-next-method-p* nil)
1641          (*next-method-p-p* nil))
1642      (multiple-value-bind (body declarations) (parse-body body)
1643        (walk-form body)
1644        (when (or *call-next-method-p* *next-method-p-p*)
1645          (return-from compute-method-fast-function nil))
1646        (let ((decls `(declare (ignorable ,@lambda-list))))
1647          (setf lambda-expression
1648                (list* (car lambda-expression)
1649                       (cadr lambda-expression)
1650                       decls
1651                       (cddr lambda-expression))))
1652        (case (length lambda-list)
1653          (1
1654;;            `(lambda (args next-emfun)
1655;;               (let ((,(%car lambda-list) (%car args)))
1656;;                 (declare (ignorable ,(%car lambda-list)))
1657;;                 ,@declarations ,@body)))
1658           lambda-expression)
1659          (2
1660;;            `(lambda (args next-emfun)
1661;;               (let ((,(%car lambda-list) (%car args))
1662;;                     (,(%cadr lambda-list) (%cadr args)))
1663;;                 (declare (ignorable ,(%car lambda-list)
1664;;                                     ,(%cadr lambda-list)))
1665;;                 ,@declarations ,@body)))
1666           lambda-expression)
1667;;           (3
1668;;            `(lambda (args next-emfun)
1669;;               (let ((,(%car lambda-list) (%car args))
1670;;                     (,(%cadr lambda-list) (%cadr args))
1671;;                     (,(%caddr lambda-list) (%caddr args)))
1672;;                 (declare (ignorable ,(%car lambda-list)
1673;;                                     ,(%cadr lambda-list)
1674;;                                     ,(%caddr lambda-list)))
1675;;                 ,@declarations ,@body)))
1676          (t
1677           nil))))))
1678
1679;; From CLHS section 7.6.5:
1680;; "When a generic function or any of its methods mentions &key in a lambda
1681;; list, the specific set of keyword arguments accepted by the generic function
1682;; varies according to the applicable methods. The set of keyword arguments
1683;; accepted by the generic function for a particular call is the union of the
1684;; keyword arguments accepted by all applicable methods and the keyword
1685;; arguments mentioned after &key in the generic function definition, if any."
1686;; Adapted from Sacla.
1687(defun allow-other-keys (lambda-list)
1688  (if (and (member '&key lambda-list)
1689           (not (member '&allow-other-keys lambda-list)))
1690      (let* ((key-end (or (position '&aux lambda-list) (length lambda-list)))
1691             (aux-part (subseq lambda-list key-end)))
1692        `(,@(subseq lambda-list 0 key-end) &allow-other-keys ,@aux-part))
1693      lambda-list))
1694
1695(defmacro defmethod (&rest args)
1696  (multiple-value-bind
1697      (function-name qualifiers lambda-list specializers documentation declarations body)
1698      (parse-defmethod args)
1699    (let* ((specializers-form '())
1700           (lambda-expression `(lambda ,lambda-list ,@declarations ,body))
1701           (method-function (compute-method-function lambda-expression))
1702           (fast-function (compute-method-fast-function lambda-expression))
1703           )
1704      (dolist (specializer specializers)
1705        (cond ((and (consp specializer) (eq (car specializer) 'eql))
1706               (push `(list 'eql ,(cadr specializer)) specializers-form))
1707              (t
1708               (push `',specializer specializers-form))))
1709      (setf specializers-form `(list ,@(nreverse specializers-form)))
1710      `(progn
1711         (ensure-method ',function-name
1712                        :lambda-list ',lambda-list
1713                        :qualifiers ',qualifiers
1714                        :specializers ,specializers-form
1715                        ,@(if documentation `(:documentation ,documentation))
1716                        :function (function ,method-function)
1717                        ,@(if fast-function `(:fast-function (function ,fast-function)))
1718                        )))))
1719
1720;;; Reader and writer methods
1721
1722(defun make-instance-standard-reader-method (gf
1723                                             &key
1724                                             lambda-list
1725                                             qualifiers
1726                                             specializers
1727                                             documentation
1728                                             function
1729                                             fast-function
1730                                             slot-name)
1731  (declare (ignore gf))
1732  (let ((method (std-allocate-instance (find-class 'standard-reader-method))))
1733    (setf (method-lambda-list method) lambda-list)
1734    (setf (method-qualifiers method) qualifiers)
1735    (%set-method-specializers method (canonicalize-specializers specializers))
1736    (setf (method-documentation method) documentation)
1737    (%set-method-generic-function method nil)
1738    (%set-method-function method function)
1739    (%set-method-fast-function method fast-function)
1740    (set-reader-method-slot-name method slot-name)
1741    method))
1742
1743(defun add-reader-method (class function-name slot-name)
1744  (let* ((lambda-expression
1745          (if (eq (class-of class) (find-class 'standard-class))
1746              `(lambda (object) (std-slot-value object ',slot-name))
1747              `(lambda (object) (slot-value object ',slot-name))))
1748         (method-function (compute-method-function lambda-expression))
1749         (fast-function (compute-method-fast-function lambda-expression)))
1750    (let ((method-lambda-list '(object))
1751          (gf (find-generic-function function-name nil)))
1752      (if gf
1753          (check-method-lambda-list method-lambda-list (generic-function-lambda-list gf))
1754          (setf gf (ensure-generic-function function-name :lambda-list method-lambda-list)))
1755      (let ((method
1756             (make-instance-standard-reader-method gf
1757                                                   :lambda-list '(object)
1758                                                   :qualifiers ()
1759                                                   :specializers (list class)
1760                                                   :function (if (autoloadp 'compile)
1761                                                                 method-function
1762                                                                 (compile nil method-function))
1763                                                   :fast-function (if (autoloadp 'compile)
1764                                                                      fast-function
1765                                                                      (compile nil fast-function))
1766                                                   :slot-name slot-name)))
1767        (%add-method gf method)
1768        method))))
1769
1770(defun add-writer-method (class function-name slot-name)
1771  (let* ((lambda-expression
1772          (if (eq (class-of class) (find-class 'standard-class))
1773              `(lambda (new-value object)
1774                 (setf (std-slot-value object ',slot-name) new-value))
1775              `(lambda (new-value object)
1776                 (setf (slot-value object ',slot-name) new-value))))
1777         (method-function (compute-method-function lambda-expression))
1778         (fast-function (compute-method-fast-function lambda-expression))
1779         )
1780    (ensure-method function-name
1781                   :lambda-list '(new-value object)
1782                   :qualifiers ()
1783                   :specializers (list (find-class 't) class)
1784;;                    :function `(function ,method-function)
1785                   :function (if (autoloadp 'compile)
1786                                 method-function
1787                                 (compile nil method-function))
1788                   :fast-function (if (autoloadp 'compile)
1789                                      fast-function
1790                                      (compile nil fast-function))
1791                   )))
1792
1793(fmakunbound 'class-name)
1794
1795(defgeneric class-name (class))
1796
1797(defmethod class-name ((class class))
1798  (%class-name class))
1799
1800(defgeneric (setf class-name) (new-value class))
1801
1802(defmethod (setf class-name) (new-value (class class))
1803  (%set-class-name class new-value))
1804
1805(when (autoloadp 'class-precedence-list)
1806  (fmakunbound 'class-precedence-list))
1807
1808(defgeneric class-precedence-list (class))
1809
1810(defmethod class-precedence-list ((class class))
1811  (%class-precedence-list class))
1812
1813(defgeneric documentation (x doc-type))
1814
1815(defgeneric (setf documentation) (new-value x doc-type))
1816
1817(defmethod documentation ((x symbol) doc-type)
1818  (%documentation x doc-type))
1819
1820(defmethod (setf documentation) (new-value (x symbol) doc-type)
1821  (%set-documentation x doc-type new-value))
1822
1823(defmethod documentation ((x function) doc-type)
1824  (%documentation x doc-type))
1825
1826(defmethod (setf documentation) (new-value (x function) doc-type)
1827  (%set-documentation x doc-type new-value))
1828
1829;; FIXME This should be a weak hashtable!
1830(defvar *list-documentation-hashtable* (make-hash-table :test #'equal))
1831
1832(defmethod documentation ((x list) (doc-type (eql 'function)))
1833  (let ((alist (gethash x *list-documentation-hashtable*)))
1834    (and alist (cdr (assoc doc-type alist)))))
1835
1836(defmethod documentation ((x list) (doc-type (eql 'compiler-macro)))
1837  (let ((alist (gethash x *list-documentation-hashtable*)))
1838    (and alist (cdr (assoc doc-type alist)))))
1839
1840(defmethod (setf documentation) (new-value (x list) (doc-type (eql 'function)))
1841  (let* ((alist (gethash x *list-documentation-hashtable*))
1842         (entry (and alist (assoc doc-type alist))))
1843    (cond (entry
1844           (setf (cdr entry) new-value))
1845          (t
1846           (setf (gethash x *list-documentation-hashtable*)
1847                 (push (cons doc-type new-value) alist)))))
1848  new-value)
1849
1850(defmethod (setf documentation) (new-value (x list) (doc-type (eql 'compiler-macro)))
1851  (let* ((alist (gethash x *list-documentation-hashtable*))
1852         (entry (and alist (assoc doc-type alist))))
1853    (cond (entry
1854           (setf (cdr entry) new-value))
1855          (t
1856           (setf (gethash x *list-documentation-hashtable*)
1857                 (push (cons doc-type new-value) alist)))))
1858  new-value)
1859
1860(defmethod documentation ((x standard-class) (doc-type (eql 't)))
1861  (class-documentation x))
1862
1863(defmethod documentation ((x standard-class) (doc-type (eql 'type)))
1864  (class-documentation x))
1865
1866(defmethod (setf documentation) (new-value (x standard-class) (doc-type (eql 't)))
1867  (%set-class-documentation x new-value))
1868
1869(defmethod (setf documentation) (new-value (x standard-class) (doc-type (eql 'type)))
1870  (%set-class-documentation x new-value))
1871
1872(defmethod documentation ((x structure-class) (doc-type (eql 't)))
1873  (%documentation x doc-type))
1874
1875(defmethod documentation ((x structure-class) (doc-type (eql 'type)))
1876  (%documentation x doc-type))
1877
1878(defmethod (setf documentation) (new-value (x structure-class) (doc-type (eql 't)))
1879  (%set-documentation x doc-type new-value))
1880
1881(defmethod (setf documentation) (new-value (x structure-class) (doc-type (eql 'type)))
1882  (%set-documentation x doc-type new-value))
1883
1884(defmethod documentation ((x standard-generic-function) (doc-type (eql 't)))
1885  (generic-function-documentation x))
1886
1887(defmethod (setf documentation) (new-value (x standard-generic-function) (doc-type (eql 't)))
1888  (setf (generic-function-documentation x) new-value))
1889
1890(defmethod documentation ((x standard-generic-function) (doc-type (eql 'function)))
1891  (generic-function-documentation x))
1892
1893(defmethod (setf documentation) (new-value (x standard-generic-function) (doc-type (eql 'function)))
1894  (setf (generic-function-documentation x) new-value))
1895
1896(defmethod documentation ((x standard-method) (doc-type (eql 't)))
1897  (method-documentation x))
1898
1899(defmethod (setf documentation) (new-value (x standard-method) (doc-type (eql 't)))
1900  (setf (method-documentation x) new-value))
1901
1902(defmethod documentation ((x package) (doc-type (eql 't)))
1903  (%documentation x doc-type))
1904
1905(defmethod (setf documentation) (new-value (x package) (doc-type (eql 't)))
1906  (%set-documentation x doc-type new-value))
1907
1908;;; Slot access
1909
1910(defun set-slot-value-using-class (new-value class instance slot-name)
1911  (declare (ignore class)) ; FIXME
1912  (setf (std-slot-value instance slot-name) new-value))
1913
1914(defgeneric slot-value-using-class (class instance slot-name))
1915
1916(defmethod slot-value-using-class ((class standard-class) instance slot-name)
1917  (std-slot-value instance slot-name))
1918
1919(defgeneric (setf slot-value-using-class) (new-value class instance slot-name))
1920(defmethod (setf slot-value-using-class) (new-value
1921                                          (class standard-class)
1922                                          instance
1923                                          slot-name)
1924  (setf (std-slot-value instance slot-name) new-value))
1925
1926(defgeneric slot-exists-p-using-class (class instance slot-name))
1927
1928(defmethod slot-exists-p-using-class (class instance slot-name)
1929  nil)
1930
1931(defmethod slot-exists-p-using-class ((class standard-class) instance slot-name)
1932  (std-slot-exists-p instance slot-name))
1933
1934(defmethod slot-exists-p-using-class ((class structure-class) instance slot-name)
1935  (dolist (dsd (%class-slots class))
1936    (when (eq (sys::dsd-name dsd) slot-name)
1937      (return-from slot-exists-p-using-class t)))
1938  nil)
1939
1940(defgeneric slot-boundp-using-class (class instance slot-name))
1941(defmethod slot-boundp-using-class ((class standard-class) instance slot-name)
1942  (std-slot-boundp instance slot-name))
1943
1944(defgeneric slot-makunbound-using-class (class instance slot-name))
1945(defmethod slot-makunbound-using-class ((class standard-class)
1946                                        instance
1947                                        slot-name)
1948  (std-slot-makunbound instance slot-name))
1949
1950(defgeneric slot-missing (class instance slot-name operation &optional new-value))
1951
1952(defmethod slot-missing ((class t) instance slot-name operation &optional new-value)
1953  (declare (ignore new-value))
1954  (error "The slot ~S is missing from the class ~S." slot-name class))
1955
1956(defgeneric slot-unbound (class instance slot-name))
1957
1958(defmethod slot-unbound ((class t) instance slot-name)
1959  (error 'unbound-slot :instance instance :name slot-name))
1960
1961;;; Instance creation and initialization
1962
1963(defgeneric allocate-instance (class &rest initargs &key &allow-other-keys))
1964
1965(defmethod allocate-instance ((class standard-class) &rest initargs)
1966  (declare (ignore initargs))
1967  (std-allocate-instance class))
1968
1969(defmethod allocate-instance ((class structure-class) &rest initargs)
1970  (declare (ignore initargs))
1971  (%make-structure (%class-name class)
1972                   (make-list (length (%class-slots class))
1973                              :initial-element +slot-unbound+)))
1974
1975;; "The set of valid initialization arguments for a class is the set of valid
1976;; initialization arguments that either fill slots or supply arguments to
1977;; methods, along with the predefined initialization argument :ALLOW-OTHER-KEYS."
1978;; 7.1.2
1979#+nil
1980(defun check-initargs (class initargs)
1981  (when (oddp (length initargs))
1982    (error 'program-error
1983           :format-control "Odd number of keyword arguments."))
1984  (unless (getf initargs :allow-other-keys)
1985    (let ((slots (%class-slots class)))
1986      (do* ((tail initargs (cddr tail))
1987            (initarg (car tail) (car tail)))
1988           ((null tail))
1989        (unless (or (valid-initarg-p initarg slots)
1990                    (eq initarg :allow-other-keys))
1991          (error 'program-error
1992                 :format-control "Invalid initarg ~S."
1993                 :format-arguments (list initarg)))))))
1994
1995;; FIXME
1996(defun check-initargs (class initargs)
1997  (declare (ignore class initargs)))
1998
1999(defun valid-initarg-p (initarg slots)
2000  (dolist (slot slots nil)
2001    (let ((valid-initargs (%slot-definition-initargs slot)))
2002      (when (memq initarg valid-initargs)
2003        (return t)))))
2004
2005(defgeneric make-instance (class &rest initargs &key &allow-other-keys))
2006
2007(defmethod make-instance ((class standard-class) &rest initargs)
2008  (when (oddp (length initargs))
2009    (error 'program-error :format-control "Odd number of keyword arguments."))
2010  (unless (class-finalized-p class)
2011    (std-finalize-inheritance class))
2012  (let ((class-default-initargs (class-default-initargs class)))
2013    (when class-default-initargs
2014      (let ((default-initargs '()))
2015        (do* ((list class-default-initargs (cddr list))
2016              (key (car list) (car list))
2017              (fn (cadr list) (cadr list)))
2018             ((null list))
2019          (when (eq (getf initargs key 'not-found) 'not-found)
2020            (setf default-initargs (append default-initargs (list key (funcall fn))))))
2021        (setf initargs (append initargs default-initargs)))))
2022  (check-initargs class initargs)
2023  (let ((instance (std-allocate-instance class)))
2024    (apply #'initialize-instance instance initargs)
2025    instance))
2026
2027(defmethod make-instance ((class symbol) &rest initargs)
2028  (apply #'make-instance (find-class class) initargs))
2029
2030(defgeneric initialize-instance (instance &key))
2031
2032(defmethod initialize-instance ((instance standard-object) &rest initargs)
2033  (apply #'shared-initialize instance t initargs))
2034
2035(defgeneric reinitialize-instance (instance &key))
2036
2037;; "The system-supplied primary method for REINITIALIZE-INSTANCE checks the
2038;; validity of initargs and signals an error if an initarg is supplied that is
2039;; not declared as valid. The method then calls the generic function SHARED-
2040;; INITIALIZE with the following arguments: the instance, nil (which means no
2041;; slots should be initialized according to their initforms), and the initargs
2042;; it received."
2043(defmethod reinitialize-instance ((instance standard-object) &rest initargs)
2044  (apply #'shared-initialize instance () initargs))
2045
2046(defun std-shared-initialize (instance slot-names all-keys)
2047  (when (oddp (length all-keys))
2048    (error 'program-error :format-control "Odd number of keyword arguments."))
2049  (dolist (slot (%class-slots (class-of instance)))
2050    (let ((slot-name (%slot-definition-name slot)))
2051      (multiple-value-bind (init-key init-value foundp)
2052          (get-properties all-keys (%slot-definition-initargs slot))
2053        (if foundp
2054            (setf (std-slot-value instance slot-name) init-value)
2055            (unless (std-slot-boundp instance slot-name)
2056              (let ((initfunction (%slot-definition-initfunction slot)))
2057                (when (and initfunction (or (eq slot-names t)
2058                                            (memq slot-name slot-names)))
2059                  (setf (std-slot-value instance slot-name)
2060                        (funcall initfunction)))))))))
2061  instance)
2062
2063(defgeneric shared-initialize (instance slot-names &key))
2064
2065(defmethod shared-initialize ((instance standard-object) slot-names &rest initargs)
2066  (std-shared-initialize instance slot-names initargs))
2067
2068;;; change-class
2069
2070(defgeneric change-class (instance new-class &key))
2071
2072(defmethod change-class ((old-instance standard-object) (new-class standard-class)
2073                         &rest initargs)
2074  (let ((old-slots (%class-slots (class-of old-instance)))
2075        (new-slots (%class-slots new-class))
2076        (new-instance (allocate-instance new-class)))
2077    ;; "The values of local slots specified by both the class CTO and the class
2078    ;; CFROM are retained. If such a local slot was unbound, it remains
2079    ;; unbound."
2080    (dolist (new-slot new-slots)
2081      (when (instance-slot-p new-slot)
2082        (let* ((slot-name (%slot-definition-name new-slot))
2083               (old-slot (find slot-name old-slots :key #'%slot-definition-name)))
2084          ;; "The values of slots specified as shared in the class CFROM and as
2085          ;; local in the class CTO are retained."
2086          (when (and old-slot (slot-boundp old-instance slot-name))
2087            (setf (slot-value new-instance slot-name)
2088                  (slot-value old-instance slot-name))))))
2089    (swap-slots old-instance new-instance)
2090    (rotatef (std-instance-layout new-instance)
2091             (std-instance-layout old-instance))
2092    (apply #'update-instance-for-different-class
2093           new-instance old-instance initargs)
2094    old-instance))
2095
2096(defmethod change-class ((instance standard-object) (new-class symbol) &rest initargs)
2097  (apply #'change-class instance (find-class new-class) initargs))
2098
2099(defgeneric update-instance-for-different-class (old new &key))
2100
2101(defmethod update-instance-for-different-class
2102  ((old standard-object) (new standard-object) &rest initargs)
2103  (let ((added-slots
2104         (remove-if #'(lambda (slot-name)
2105                       (slot-exists-p old slot-name))
2106                    (mapcar #'%slot-definition-name
2107                            (%class-slots (class-of new))))))
2108    (check-initargs (class-of new) initargs)
2109    (apply #'shared-initialize new added-slots initargs)))
2110
2111;;; make-instances-obsolete
2112
2113(defgeneric make-instances-obsolete (class))
2114
2115(defmethod make-instances-obsolete ((class standard-class))
2116  (%make-instances-obsolete class))
2117
2118(defmethod make-instances-obsolete ((class symbol))
2119  (make-instances-obsolete (find-class class))
2120  class)
2121
2122;;; update-instance-for-redefined-class
2123
2124(defgeneric update-instance-for-redefined-class (instance
2125                                                 added-slots
2126                                                 discarded-slots
2127                                                 property-list
2128                                                 &rest initargs
2129                                                 &key
2130                                                 &allow-other-keys))
2131
2132(defmethod update-instance-for-redefined-class ((instance standard-object)
2133            added-slots
2134            discarded-slots
2135            property-list
2136            &rest initargs)
2137  (check-initargs (class-of instance) initargs)
2138  (apply #'shared-initialize instance added-slots initargs))
2139
2140;;;  Methods having to do with class metaobjects.
2141
2142(defmethod initialize-instance :after ((class standard-class) &rest args)
2143  (apply #'std-after-initialization-for-classes class args))
2144
2145;;; Finalize inheritance
2146
2147(defgeneric finalize-inheritance (class))
2148
2149(defmethod finalize-inheritance ((class standard-class))
2150  (std-finalize-inheritance class))
2151
2152;;; Class precedence lists
2153
2154(defgeneric compute-class-precedence-list (class))
2155(defmethod compute-class-precedence-list ((class standard-class))
2156  (std-compute-class-precedence-list class))
2157
2158;;; Slot inheritance
2159
2160(defgeneric compute-slots (class))
2161(defmethod compute-slots ((class standard-class))
2162  (std-compute-slots class))
2163
2164(defgeneric compute-effective-slot-definition (class direct-slots))
2165(defmethod compute-effective-slot-definition
2166  ((class standard-class) direct-slots)
2167  (std-compute-effective-slot-definition class direct-slots))
2168
2169;;; Methods having to do with generic function metaobjects.
2170
2171(defmethod initialize-instance :after ((gf standard-generic-function) &key)
2172  (finalize-generic-function gf))
2173
2174;;; Methods having to do with generic function invocation.
2175
2176(defgeneric compute-discriminating-function (gf))
2177(defmethod compute-discriminating-function ((gf standard-generic-function))
2178  (std-compute-discriminating-function gf))
2179
2180(defgeneric method-more-specific-p (gf method1 method2 required-classes))
2181
2182(defmethod method-more-specific-p ((gf standard-generic-function)
2183                                   method1 method2 required-classes)
2184  (std-method-more-specific-p method1 method2 required-classes
2185                              (generic-function-argument-precedence-order gf)))
2186
2187(defgeneric compute-effective-method-function (gf methods))
2188(defmethod compute-effective-method-function ((gf standard-generic-function) methods)
2189  (std-compute-effective-method-function gf methods))
2190
2191(defgeneric compute-applicable-methods (gf args))
2192(defmethod compute-applicable-methods ((gf standard-generic-function) args)
2193  (%compute-applicable-methods gf args))
2194
2195;;; Conditions.
2196
2197(defmacro define-condition (name (&rest parent-types) (&rest slot-specs) &body options)
2198  (let ((parent-types (or parent-types '(condition)))
2199        (report nil))
2200    (dolist (option options)
2201      (when (eq (car option) :report)
2202        (setf report (cadr option))
2203        (return)))
2204    (typecase report
2205      (null
2206       `(progn
2207          (defclass ,name ,parent-types ,slot-specs ,@options)
2208          ',name))
2209      (string
2210       `(progn
2211          (defclass ,name ,parent-types ,slot-specs ,@options)
2212          (defmethod print-object ((condition ,name) stream)
2213            (if *print-escape*
2214                (call-next-method)
2215                (progn (write-string ,report stream) condition)))
2216          ',name))
2217      (t
2218       `(progn
2219          (defclass ,name ,parent-types ,slot-specs ,@options)
2220          (defmethod print-object ((condition ,name) stream)
2221            (if *print-escape*
2222                (call-next-method)
2223                (funcall #',report condition stream)))
2224          ',name)))))
2225
2226(defun make-condition (type &rest initargs)
2227  (or (%make-condition type initargs)
2228      (let ((class (if (symbolp type) (find-class type) type)))
2229        (apply #'make-instance class initargs))))
2230
2231;; Adapted from SBCL.
2232;; Originally defined in signal.lisp. Redefined here now that we have MAKE-CONDITION.
2233(defun coerce-to-condition (datum arguments default-type fun-name)
2234  (cond ((typep datum 'condition)
2235         (when arguments
2236           (error 'simple-type-error
2237                  :datum arguments
2238                  :expected-type 'null
2239                  :format-control "You may not supply additional arguments when giving ~S to ~S."
2240                  :format-arguments (list datum fun-name)))
2241         datum)
2242        ((symbolp datum)
2243         (apply #'make-condition datum arguments))
2244        ((or (stringp datum) (functionp datum))
2245         (make-condition default-type
2246                         :format-control datum
2247                         :format-arguments arguments))
2248        (t
2249         (error 'simple-type-error
2250                :datum datum
2251                :expected-type '(or symbol string)
2252                :format-control "Bad argument to ~S: ~S."
2253                :format-arguments (list fun-name datum)))))
2254
2255(defgeneric make-load-form (object &optional environment))
2256
2257(defmethod make-load-form ((object t) &optional environment)
2258  (declare (ignore environment))
2259  (apply #'no-applicable-method #'make-load-form (list object)))
2260
2261(defmethod make-load-form ((class class) &optional environment)
2262  (declare (ignore environment))
2263  (let ((name (%class-name class)))
2264    (unless (and name (eq (find-class name nil) class))
2265      (error 'simple-type-error
2266             :format-control "Can't use anonymous or undefined class as a constant: ~S."
2267             :format-arguments (list class)))
2268    `(find-class ',name)))
2269
2270(defun invalid-method-error (method format-control &rest args)
2271  (let ((message (apply #'format nil format-control args)))
2272    (error "Invalid method error for ~S:~%    ~A" method message)))
2273
2274(defun method-combination-error (format-control &rest args)
2275  (let ((message (apply #'format nil format-control args)))
2276    (error "Method combination error in CLOS dispatch:~%    ~A" message)))
2277
2278(defgeneric no-applicable-method (generic-function &rest args))
2279
2280(defmethod no-applicable-method (generic-function &rest args)
2281  (error "There is no applicable method for the generic function ~S when called with arguments ~S."
2282         generic-function
2283         args))
2284
2285(defgeneric find-method (generic-function
2286                         qualifiers
2287                         specializers
2288                         &optional errorp))
2289
2290(defmethod find-method ((generic-function standard-generic-function)
2291      qualifiers specializers &optional (errorp t))
2292  (%find-method generic-function qualifiers specializers errorp))
2293
2294(defgeneric add-method (generic-function method))
2295
2296(defmethod add-method ((generic-function standard-generic-function) (method method))
2297  (let ((method-lambda-list (method-lambda-list method))
2298        (gf-lambda-list (generic-function-lambda-list generic-function)))
2299    (check-method-lambda-list method-lambda-list gf-lambda-list))
2300  (%add-method generic-function method))
2301
2302(defgeneric remove-method (generic-function method))
2303
2304(defmethod remove-method ((generic-function standard-generic-function) method)
2305  (%remove-method generic-function method))
2306
2307;; See describe.lisp.
2308(defgeneric describe-object (object stream))
2309
2310;; FIXME
2311(defgeneric no-next-method (generic-function method &rest args))
2312
2313;; FIXME
2314(defgeneric function-keywords (method))
2315
2316(provide 'clos)
Note: See TracBrowser for help on using the repository browser.