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

Last change on this file since 14493 was 14493, checked in by rschlatte, 10 years ago

downsize StandardGenericFunction?.java

  • move all caching into new class EMFCache.java
  • eliminate or inline all other methods, rely on superclasses' implementations instead.
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 201.1 KB
Line 
1;;; clos.lisp
2;;;
3;;; Copyright (C) 2003-2007 Peter Graves
4;;; Copyright (C) 2010-2013 Mark Evenson
5;;; $Id: clos.lisp 14493 2013-05-05 15:02:32Z rschlatte $
6;;;
7;;; This program is free software; you can redistribute it and/or
8;;; modify it under the terms of the GNU General Public License
9;;; as published by the Free Software Foundation; either version 2
10;;; of the License, or (at your option) any later version.
11;;;
12;;; This program is distributed in the hope that it will be useful,
13;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15;;; GNU General Public License for more details.
16;;;
17;;; You should have received a copy of the GNU General Public License
18;;; along with this program; if not, write to the Free Software
19;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20;;;
21;;; As a special exception, the copyright holders of this library give you
22;;; permission to link this library with independent modules to produce an
23;;; executable, regardless of the license terms of these independent
24;;; modules, and to copy and distribute the resulting executable under
25;;; terms of your choice, provided that you also meet, for each linked
26;;; independent module, the terms and conditions of the license of that
27;;; module.  An independent module is a module which is not derived from
28;;; or based on this library.  If you modify this library, you may extend
29;;; this exception to your version of the library, but you are not
30;;; obligated to do so.  If you do not wish to do so, delete this
31;;; exception statement from your version.
32
33;;; Originally based on Closette.
34
35;;; Closette Version 1.0 (February 10, 1991)
36;;;
37;;; Copyright (c) 1990, 1991 Xerox Corporation.
38;;; All rights reserved.
39;;;
40;;; Use and copying of this software and preparation of derivative works
41;;; based upon this software are permitted.  Any distribution of this
42;;; software or derivative works must comply with all applicable United
43;;; States export control laws.
44;;;
45;;; This software is made available AS IS, and Xerox Corporation makes no
46;;; warranty about the software, its performance or its conformity to any
47;;; specification.
48;;;
49;;; Closette is an implementation of a subset of CLOS with a metaobject
50;;; protocol as described in "The Art of The Metaobject Protocol",
51;;; MIT Press, 1991.
52
53(in-package #:mop)
54
55(export '(%defgeneric canonicalize-direct-superclasses))
56
57
58;;
59;;
60;;
61;; In order to bootstrap CLOS, first implement the required API as
62;; normal functions which only apply to the "root" metaclass
63;; STANDARD-CLASS.
64;;
65;; After putting the normal functions in place, the building blocks
66;; are in place to gradually swap the normal functions with
67;; generic functions and methods.
68;;
69;; Some functionality implemented in the temporary regular functions
70;; needs to be available later as a method definition to be dispatched
71;; to for the standard case, e.g. with arguments of type STANDARD-CLASS
72;; or STANDARD-GENERIC-FUNCTION.  To prevent repeated code, the
73;; functions are implemented in functions by the same name as the API
74;; functions, but with the STD- prefix.  These functions are sometimes
75;; used in regular code as well, either in a "fast path" or to break a
76;; circularity (e.g., within compute-discriminating-function when the
77;; user adds a method to compute-discriminating-function).
78;;
79;; When hacking this file, note that some important parts are implemented
80;; in the Java world. These Java bits can be found in the files
81;;
82;; * LispClass.java
83;; * SlotClass.java
84;; * StandardClass.java
85;; * BuiltInClass.java
86;; * StandardObject.java
87;; * StandardObjectFunctions.java
88;; * FuncallableStandardObject.java
89;; * Layout.java
90;;
91;; In case of function names, those defined on the Java side can be
92;; recognized by their prefixed percent (%) sign.
93;;
94;; The API functions need to be declaimed NOTINLINE explicitly, because
95;; that prevents inlining in the current FASL (which is allowed by the
96;; CLHS without the declaration); this is a hard requirement to in order
97;; to be able to swap the symbol's function slot with a generic function
98;; later on - with it actually being used.
99;;
100;;
101;;
102;; ### Note that the "declares all API functions as regular functions"
103;; isn't true when I write the above, but it's definitely the target.
104;;
105;; A note about AMOP: the first chapters (and the sample Closette
106;; implementation) of the book sometimes deviate from the specification.
107;; For example, in the examples slot-value-using-class has the slot name
108;; as third argument where in the specification it is the effective slot
109;; definition.  When in doubt, we aim to follow the specification, the
110;; MOP test suite at http://common-lisp.net/project/closer/features.html
111;; and the behavior of other CL implementations in preference to
112;; chapters 1-4 and appendix D.
113
114(defconstant +the-standard-class+ (find-class 'standard-class))
115(defconstant +the-funcallable-standard-class+
116  (find-class 'funcallable-standard-class))
117(defconstant +the-standard-object-class+ (find-class 'standard-object))
118(defconstant +the-funcallable-standard-object-class+
119  (find-class 'funcallable-standard-object))
120(defconstant +the-standard-method-class+ (find-class 'standard-method))
121(defconstant +the-standard-generic-function-class+
122  (find-class 'standard-generic-function))
123(defconstant +the-T-class+ (find-class 'T))
124(defconstant +the-standard-slot-definition-class+ (find-class 'standard-slot-definition))
125(defconstant +the-standard-direct-slot-definition-class+ (find-class 'standard-direct-slot-definition))
126(defconstant +the-standard-effective-slot-definition-class+ (find-class 'standard-effective-slot-definition))
127
128;; Don't use DEFVAR, because that disallows loading clos.lisp
129;; after compiling it: the binding won't get assigned to T anymore
130(defparameter *clos-booting* t)
131
132(defmacro define-class->%class-forwarder (name)
133  (let* (($name (if (consp name) (cadr name) name))
134         (%name (intern (concatenate 'string
135                                     "%"
136                                     (if (consp name)
137                                         (symbol-name 'set-) "")
138                                     (symbol-name $name))
139                        (symbol-package $name))))
140    `(progn
141       (declaim (notinline ,name))
142       (defun ,name (&rest args)
143         (apply #',%name args)))))
144
145;;
146;;  DEFINE PLACE HOLDER FUNCTIONS
147;;
148
149(define-class->%class-forwarder class-name)
150(define-class->%class-forwarder (setf class-name))
151(define-class->%class-forwarder class-slots)
152(define-class->%class-forwarder (setf class-slots))
153(define-class->%class-forwarder class-direct-slots)
154(define-class->%class-forwarder (setf class-direct-slots))
155(define-class->%class-forwarder class-layout)
156(define-class->%class-forwarder (setf class-layout))
157(define-class->%class-forwarder class-direct-superclasses)
158(define-class->%class-forwarder (setf class-direct-superclasses))
159(define-class->%class-forwarder class-direct-subclasses)
160(define-class->%class-forwarder (setf class-direct-subclasses))
161(define-class->%class-forwarder class-direct-methods)
162(define-class->%class-forwarder (setf class-direct-methods))
163(define-class->%class-forwarder class-precedence-list)
164(define-class->%class-forwarder (setf class-precedence-list))
165(define-class->%class-forwarder class-finalized-p)
166(define-class->%class-forwarder (setf class-finalized-p))
167(define-class->%class-forwarder class-default-initargs)
168(define-class->%class-forwarder (setf class-default-initargs))
169(define-class->%class-forwarder class-direct-default-initargs)
170(define-class->%class-forwarder (setf class-direct-default-initargs))
171
172(declaim (notinline add-direct-subclass remove-direct-subclass))
173(defun add-direct-subclass (superclass subclass)
174  (setf (class-direct-subclasses superclass)
175        (adjoin subclass (class-direct-subclasses superclass))))
176(defun remove-direct-subclass (superclass subclass)
177  (setf (class-direct-subclasses superclass)
178        (remove subclass (class-direct-subclasses superclass))))
179
180(defun fixup-standard-class-hierarchy ()
181  ;; Make the result of class-direct-subclasses for the pre-built
182  ;; classes agree with AMOP Table 5.1 (pg. 141).  This could be done in
183  ;; StandardClass.java where these classes are defined, but it's less
184  ;; painful to do it Lisp-side.
185  (flet ((add-subclasses (class subclasses)
186           (when (atom subclasses) (setf subclasses (list subclasses)))
187           (setf (class-direct-subclasses (find-class class))
188                 (union (class-direct-subclasses (find-class class))
189                        (mapcar #'find-class subclasses)))))
190    (add-subclasses t 'standard-object)
191    (add-subclasses 'function 'funcallable-standard-object)
192    (add-subclasses 'standard-object '(funcallable-standard-object metaobject))
193    (add-subclasses 'metaobject
194                    '(generic-function method slot-definition specializer))
195    (add-subclasses 'specializer '(class))
196    (add-subclasses 'funcallable-standard-object 'generic-function)
197    (add-subclasses 'generic-function 'standard-generic-function)
198    (add-subclasses 'method 'standard-method)
199    (add-subclasses 'slot-definition
200                    '(direct-slot-definition effective-slot-definition
201                      standard-slot-definition))
202    (add-subclasses 'standard-slot-definition
203                    '(standard-direct-slot-definition
204                      standard-effective-slot-definition))
205    (add-subclasses 'direct-slot-definition 'standard-direct-slot-definition)
206    (add-subclasses 'effective-slot-definition
207                    'standard-effective-slot-definition)
208    (add-subclasses 'class
209                    '(built-in-class standard-class funcallable-standard-class))))
210(fixup-standard-class-hierarchy)
211
212(defun no-applicable-method (generic-function &rest args)
213  (error "There is no applicable method for the generic function ~S when called with arguments ~S."
214         generic-function
215         args))
216
217(defun function-keywords (method)
218  (std-function-keywords method))
219
220(declaim (notinline map-dependents))
221(defun map-dependents (metaobject function)
222  ;; stub, will be redefined later
223  (declare (ignore metaobject function))
224  nil)
225
226(defmacro push-on-end (value location)
227  `(setf ,location (nconc ,location (list ,value))))
228
229;;; (SETF GETF*) is like (SETF GETF) except that it always changes the list,
230;;; which must be non-nil.
231
232(defun (setf getf*) (new-value plist key)
233  (block body
234    (do ((x plist (cddr x)))
235        ((null x))
236      (when (eq (car x) key)
237        (setf (car (cdr x)) new-value)
238        (return-from body new-value)))
239    (push-on-end key plist)
240    (push-on-end new-value plist)
241    new-value))
242
243(defun mapappend (fun &rest args)
244  (if (some #'null args)
245      ()
246      (append (apply fun (mapcar #'car args))
247              (apply #'mapappend fun (mapcar #'cdr args)))))
248
249(defun mapplist (fun x)
250  (if (null x)
251      ()
252      (cons (funcall fun (car x) (cadr x))
253            (mapplist fun (cddr x)))))
254
255(defsetf std-slot-value set-std-slot-value)
256
257(defsetf std-instance-layout %set-std-instance-layout)
258(defsetf standard-instance-access %set-standard-instance-access)
259(defun funcallable-standard-instance-access (instance location)
260  (standard-instance-access instance location))
261(defsetf funcallable-standard-instance-access %set-standard-instance-access)
262
263(defun (setf find-class) (new-value symbol &optional errorp environment)
264  (declare (ignore errorp environment))
265  (%set-find-class symbol new-value))
266
267(defun canonicalize-direct-slots (direct-slots)
268  `(list ,@(mapcar #'canonicalize-direct-slot direct-slots)))
269
270(defun canonicalize-direct-slot (spec)
271  (if (symbolp spec)
272      `(list :name ',spec)
273      (let ((name (car spec))
274            (initfunction nil)
275            (initform nil)
276            (initargs ())
277            (type nil)
278            (allocation nil)
279            (documentation nil)
280            (readers ())
281            (writers ())
282            (other-options ())
283            (non-std-options ()))
284        (do ((olist (cdr spec) (cddr olist)))
285            ((null olist))
286          (case (car olist)
287            (:initform
288             (when initform
289               (error 'program-error
290                      "duplicate slot option :INITFORM for slot named ~S"
291                      name))
292             (setq initfunction t)
293             (setq initform (cadr olist)))
294            (:initarg
295             (push-on-end (cadr olist) initargs))
296            (:allocation
297             (when allocation
298               (error 'program-error
299                      "duplicate slot option :ALLOCATION for slot named ~S"
300                      name))
301             (setf allocation (cadr olist))
302             (push-on-end (car olist) other-options)
303             (push-on-end (cadr olist) other-options))
304            (:type
305             (when type
306               (error 'program-error
307                      "duplicate slot option :TYPE for slot named ~S"
308                      name))
309             (setf type (cadr olist)))
310            (:documentation
311             (when documentation
312               (error 'program-error
313                      "duplicate slot option :DOCUMENTATION for slot named ~S"
314                      name))
315             (setf documentation (cadr olist)))
316            (:reader
317             (maybe-note-name-defined (cadr olist))
318             (push-on-end (cadr olist) readers))
319            (:writer
320             (maybe-note-name-defined (cadr olist))
321             (push-on-end (cadr olist) writers))
322            (:accessor
323             (maybe-note-name-defined (cadr olist))
324             (push-on-end (cadr olist) readers)
325             (push-on-end `(setf ,(cadr olist)) writers))
326            (t
327             (push-on-end (cadr olist) (getf non-std-options (car olist))))))
328        `(list
329          :name ',name
330          ,@(when initfunction
331              `(:initform ',initform
332                :initfunction ,(if (eq allocation :class)
333                                   ;; CLHS specifies the initform for a
334                                   ;; class allocation level slot needs
335                                   ;; to be evaluated in the dynamic
336                                   ;; extent of the DEFCLASS form
337                                   (let ((var (gensym)))
338                                     `(let ((,var ,initform))
339                                        (lambda () ,var)))
340                                 `(lambda () ,initform))))
341          ,@(when initargs `(:initargs ',initargs))
342          ,@(when readers `(:readers ',readers))
343          ,@(when writers `(:writers ',writers))
344          ,@(when type `(:type ',type))
345          ,@(when documentation `(:documentation ',documentation))
346          ,@other-options
347          ,@(mapcar #'(lambda (opt) (if (or (atom opt) (/= 1 (length opt)))
348                                        `',opt
349                                        `',(car opt)))
350                    non-std-options)))))
351
352(defun maybe-note-name-defined (name)
353  (when (fboundp 'note-name-defined)
354    (note-name-defined name)))
355
356(defun canonicalize-defclass-options (options)
357  (mapappend #'canonicalize-defclass-option options))
358
359(defun canonicalize-defclass-option (option)
360  (case (car option)
361    (:metaclass
362     (list ':metaclass
363           `(find-class ',(cadr option))))
364    (:default-initargs
365     (list
366      ':direct-default-initargs
367      `(list ,@(mapplist
368                #'(lambda (key value)
369                    `(list ',key ',value ,(make-initfunction value)))
370                (cdr option)))))
371    ((:documentation :report)
372     (list (car option) `',(cadr option)))
373    (t (list `(quote ,(car option)) `(quote ,(cdr option))))))
374
375(defun make-initfunction (initform)
376  `(function (lambda () ,initform)))
377
378(defun slot-definition-allocation (slot-definition)
379  (std-slot-value slot-definition 'sys::allocation))
380
381(declaim (notinline (setf slot-definition-allocation)))
382(defun (setf slot-definition-allocation) (value slot-definition)
383  (setf (std-slot-value slot-definition 'sys::allocation) value))
384
385(defun slot-definition-initargs (slot-definition)
386  (std-slot-value slot-definition 'sys::initargs))
387
388(declaim (notinline (setf slot-definition-initargs)))
389(defun (setf slot-definition-initargs) (value slot-definition)
390  (setf (std-slot-value slot-definition 'sys::initargs) value))
391
392(defun slot-definition-initform (slot-definition)
393  (std-slot-value slot-definition 'sys::initform))
394
395(declaim (notinline (setf slot-definition-initform)))
396(defun (setf slot-definition-initform) (value slot-definition)
397  (setf (std-slot-value slot-definition 'sys::initform) value))
398
399(defun slot-definition-initfunction (slot-definition)
400  (std-slot-value slot-definition 'sys::initfunction))
401
402(declaim (notinline (setf slot-definition-initfunction)))
403(defun (setf slot-definition-initfunction) (value slot-definition)
404  (setf (std-slot-value slot-definition 'sys::initfunction) value))
405
406(defun slot-definition-name (slot-definition)
407  (std-slot-value slot-definition 'sys:name))
408
409(declaim (notinline (setf slot-definition-name)))
410(defun (setf slot-definition-name) (value slot-definition)
411  (setf (std-slot-value slot-definition 'sys:name) value))
412
413(defun slot-definition-readers (slot-definition)
414  (std-slot-value slot-definition 'sys::readers))
415
416(declaim (notinline (setf slot-definition-readers)))
417(defun (setf slot-definition-readers) (value slot-definition)
418  (setf (std-slot-value slot-definition 'sys::readers) value))
419
420(defun slot-definition-writers (slot-definition)
421  (std-slot-value slot-definition 'sys::writers))
422
423(declaim (notinline (setf slot-definition-writers)))
424(defun (setf slot-definition-writers) (value slot-definition)
425  (setf (std-slot-value slot-definition 'sys::writers) value))
426
427(defun slot-definition-allocation-class (slot-definition)
428  (std-slot-value slot-definition 'sys::allocation-class))
429
430(declaim (notinline (setf slot-definition-allocation-class)))
431(defun (setf slot-definition-allocation-class) (value slot-definition)
432  (setf (std-slot-value slot-definition 'sys::allocation-class) value))
433
434(defun slot-definition-location (slot-definition)
435  (std-slot-value slot-definition 'sys::location))
436
437(declaim (notinline (setf slot-definition-location-class)))
438(defun (setf slot-definition-location) (value slot-definition)
439  (setf (std-slot-value slot-definition 'sys::location) value))
440
441(defun slot-definition-type (slot-definition)
442  (std-slot-value slot-definition 'sys::%type))
443
444(declaim (notinline (setf slot-definition-type)))
445(defun (setf slot-definition-type) (value slot-definition)
446  (setf (std-slot-value slot-definition 'sys::%type) value))
447
448(defun slot-definition-documentation (slot-definition)
449  (std-slot-value slot-definition 'sys:%documentation))
450
451(declaim (notinline (setf slot-definition-documentation)))
452(defun (setf slot-definition-documentation) (value slot-definition)
453  (setf (std-slot-value slot-definition 'sys:%documentation) value))
454
455(defun init-slot-definition (slot &key name
456                                    (initargs ())
457                                    (initform nil)
458                                    (initfunction nil)
459                                    (readers ())
460                                    (writers ())
461                                    (allocation :instance)
462                                    (allocation-class nil)
463                                    (type t)
464                                    (documentation nil))
465  (setf (slot-definition-name slot) name)
466  (setf (slot-definition-initargs slot) initargs)
467  (setf (slot-definition-initform slot) initform)
468  (setf (slot-definition-initfunction slot) initfunction)
469  (setf (slot-definition-readers slot) readers)
470  (setf (slot-definition-writers slot) writers)
471  (setf (slot-definition-allocation slot) allocation)
472  (setf (slot-definition-allocation-class slot) allocation-class)
473  (setf (slot-definition-type slot) type)
474  (setf (slot-definition-documentation slot) documentation)
475  slot)
476
477(declaim (notinline direct-slot-definition-class))
478(defun direct-slot-definition-class (class &rest args)
479  (declare (ignore class args))
480  +the-standard-direct-slot-definition-class+)
481
482(defun make-direct-slot-definition (class &rest args)
483  (let ((slot-class (apply #'direct-slot-definition-class class args)))
484    (if (eq slot-class +the-standard-direct-slot-definition-class+)
485        (let ((slot (%make-slot-definition +the-standard-direct-slot-definition-class+)))
486          (apply #'init-slot-definition slot :allocation-class class args)
487          slot)
488        (progn
489          (let ((slot (apply #'make-instance slot-class :allocation-class class
490                             args)))
491            slot)))))
492
493(declaim (notinline effective-slot-definition-class))
494(defun effective-slot-definition-class (class &rest args)
495  (declare (ignore class args))
496  +the-standard-effective-slot-definition-class+)
497
498(defun make-effective-slot-definition (class &rest args)
499  (let ((slot-class (apply #'effective-slot-definition-class class args)))
500    (if (eq slot-class +the-standard-effective-slot-definition-class+)
501        (let ((slot (%make-slot-definition +the-standard-effective-slot-definition-class+)))
502          (apply #'init-slot-definition slot args)
503          slot)
504        (progn
505          (let ((slot (apply #'make-instance slot-class args)))
506            slot)))))
507
508;;; finalize-inheritance
509
510(declaim (notinline compute-default-initargs))
511(defun compute-default-initargs (class)
512  (std-compute-default-initargs class))
513
514(defun std-compute-default-initargs (class)
515  (delete-duplicates
516   (mapcan #'(lambda (c)
517               (copy-list
518                (class-direct-default-initargs c)))
519           (class-precedence-list class))
520   :key #'car :from-end t))
521
522(defun std-finalize-inheritance (class)
523  ;; In case the class is already finalized, return
524  ;; immediately, as per AMOP.
525  (when (class-finalized-p class)
526    (return-from std-finalize-inheritance))
527  (setf (class-precedence-list class)
528   (funcall (if (eq (class-of class) +the-standard-class+)
529                #'std-compute-class-precedence-list
530                #'compute-class-precedence-list)
531            class))
532  (setf (class-slots class)
533        (funcall (if (eq (class-of class) +the-standard-class+)
534                     #'std-compute-slots
535                     #'compute-slots) class))
536  (let ((old-layout (class-layout class))
537        (length 0)
538        (instance-slots '())
539        (shared-slots '()))
540    (dolist (slot (class-slots class))
541      (case (slot-definition-allocation slot)
542        (:instance
543         (setf (slot-definition-location slot) length)
544         (incf length)
545         (push (slot-definition-name slot) instance-slots))
546        (:class
547         (unless (slot-definition-location slot)
548           (let ((allocation-class (slot-definition-allocation-class slot)))
549             (if (eq allocation-class class)
550                 ;; We initialize class slots here so they can be
551                 ;; accessed without creating a dummy instance.
552                 (let ((initfunction (slot-definition-initfunction slot)))
553                   (setf (slot-definition-location slot)
554                         (cons (slot-definition-name slot)
555                               (if initfunction
556                                   (funcall initfunction)
557                                   +slot-unbound+))))
558                 (setf (slot-definition-location slot)
559                       (slot-location allocation-class (slot-definition-name slot))))))
560         (push (slot-definition-location slot) shared-slots))))
561    (when old-layout
562      ;; Redefined class: initialize added shared slots.
563      (dolist (location shared-slots)
564        (let* ((slot-name (car location))
565               (old-location (layout-slot-location old-layout slot-name)))
566          (unless old-location
567            (let* ((slot-definition (find slot-name (class-slots class) :key 'slot-definition-name))
568                   (initfunction (slot-definition-initfunction slot-definition)))
569              (when initfunction
570                (setf (cdr location) (funcall initfunction))))))))
571    (setf (class-layout class)
572          (make-layout class (nreverse instance-slots) (nreverse shared-slots))))
573  (setf (class-default-initargs class)
574        (compute-default-initargs class))
575  (setf (class-finalized-p class) t))
576
577(declaim (notinline finalize-inheritance))
578(defun finalize-inheritance (class)
579  (std-finalize-inheritance class))
580
581
582;;; Class precedence lists
583
584(defun std-compute-class-precedence-list (class)
585  (let ((classes-to-order (collect-superclasses* class)))
586    (dolist (super classes-to-order)
587      (when (typep super 'forward-referenced-class)
588        (error "Can't compute class precedence list for class ~A ~
589                which depends on forward referenced class ~A." class super)))
590    (topological-sort classes-to-order
591                      (remove-duplicates
592                       (mapappend #'local-precedence-ordering
593                                  classes-to-order))
594                      #'std-tie-breaker-rule)))
595
596;;; topological-sort implements the standard algorithm for topologically
597;;; sorting an arbitrary set of elements while honoring the precedence
598;;; constraints given by a set of (X,Y) pairs that indicate that element
599;;; X must precede element Y.  The tie-breaker procedure is called when it
600;;; is necessary to choose from multiple minimal elements; both a list of
601;;; candidates and the ordering so far are provided as arguments.
602
603(defun topological-sort (elements constraints tie-breaker)
604  (let ((remaining-constraints constraints)
605        (remaining-elements elements)
606        (result ()))
607    (loop
608      (let ((minimal-elements
609             (remove-if
610              #'(lambda (class)
611                 (member class remaining-constraints
612                         :key #'cadr))
613              remaining-elements)))
614        (when (null minimal-elements)
615          (if (null remaining-elements)
616              (return-from topological-sort result)
617              (error "Inconsistent precedence graph.")))
618        (let ((choice (if (null (cdr minimal-elements))
619                          (car minimal-elements)
620                          (funcall tie-breaker
621                                   minimal-elements
622                                   result))))
623          (setq result (append result (list choice)))
624          (setq remaining-elements
625                (remove choice remaining-elements))
626          (setq remaining-constraints
627                (remove choice
628                        remaining-constraints
629                        :test #'member)))))))
630
631;;; In the event of a tie while topologically sorting class precedence lists,
632;;; the CLOS Specification says to "select the one that has a direct subclass
633;;; rightmost in the class precedence list computed so far."  The same result
634;;; is obtained by inspecting the partially constructed class precedence list
635;;; from right to left, looking for the first minimal element to show up among
636;;; the direct superclasses of the class precedence list constituent.
637;;; (There's a lemma that shows that this rule yields a unique result.)
638
639(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
640  (dolist (cpl-constituent (reverse cpl-so-far))
641    (let* ((supers (class-direct-superclasses cpl-constituent))
642           (common (intersection minimal-elements supers)))
643      (when (not (null common))
644        (return-from std-tie-breaker-rule (car common))))))
645
646;;; This version of collect-superclasses* isn't bothered by cycles in the class
647;;; hierarchy, which sometimes happen by accident.
648
649(defun collect-superclasses* (class)
650  (labels ((all-superclasses-loop (seen superclasses)
651                                  (let ((to-be-processed
652                                         (set-difference superclasses seen)))
653                                    (if (null to-be-processed)
654                                        superclasses
655                                        (let ((class-to-process
656                                               (car to-be-processed)))
657                                          (all-superclasses-loop
658                                           (cons class-to-process seen)
659                                           (union (class-direct-superclasses
660                                                   class-to-process)
661                                                  superclasses)))))))
662          (all-superclasses-loop () (list class))))
663
664;;; The local precedence ordering of a class C with direct superclasses C_1,
665;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
666
667(defun local-precedence-ordering (class)
668  (mapcar #'list
669          (cons class
670                (butlast (class-direct-superclasses class)))
671          (class-direct-superclasses class)))
672
673;;; Slot inheritance
674
675(defun std-compute-slots (class)
676  (let* ((all-slots (mapappend #'(lambda (c) (class-direct-slots c))
677                               ;; Slots of base class must come first
678                               (reverse (class-precedence-list class))))
679         (all-names (delete-duplicates
680                     (mapcar 'slot-definition-name all-slots)
681                     :from-end t)))
682    (mapcar #'(lambda (name)
683               (funcall
684                (if (eq (class-of class) +the-standard-class+)
685                    #'std-compute-effective-slot-definition
686                    #'compute-effective-slot-definition)
687                class
688                name
689                ;; Slot of inherited class must override initfunction,
690                ;; documentation of base class
691                (nreverse
692                 (remove name all-slots
693                         :key 'slot-definition-name
694                         :test-not #'eq))))
695            all-names)))
696
697(defun std-compute-effective-slot-definition (class name direct-slots)
698  (let ((initer (find-if-not #'null direct-slots
699                             :key 'slot-definition-initfunction))
700        (documentation-slot (find-if-not #'null direct-slots
701                                         :key 'slot-definition-documentation))
702        (types (delete-duplicates
703                (delete t (mapcar #'slot-definition-type direct-slots))
704                :test #'equal)))
705    (make-effective-slot-definition
706     class
707     :name name
708     :initform (if initer
709                   (slot-definition-initform initer)
710                   nil)
711     :initfunction (if initer
712                       (slot-definition-initfunction initer)
713                       nil)
714     :initargs (remove-duplicates
715                (mapappend 'slot-definition-initargs
716                           direct-slots))
717     :allocation (slot-definition-allocation (car direct-slots))
718     :allocation-class (when (slot-boundp (car direct-slots)
719                                          'sys::allocation-class)
720                         ;;for some classes created in Java
721                         ;;(e.g. SimpleCondition) this slot is unbound
722                         (slot-definition-allocation-class (car direct-slots)))
723     :type (cond ((null types) t)
724                 ((= 1 (length types)) types)
725                 (t (list* 'and types)))
726     :documentation (if documentation-slot
727                        (documentation documentation-slot t)
728                        nil))))
729
730;;; Standard instance slot access
731
732;;; N.B. The location of the effective-slots slots in the class metaobject for
733;;; standard-class must be determined without making any further slot
734;;; references.
735
736(defun find-slot-definition (class slot-name)
737  (dolist (slot (class-slots class) nil)
738    (when (eq slot-name (slot-definition-name slot))
739      (return slot))))
740
741(defun slot-location (class slot-name)
742  (let ((slot (find-slot-definition class slot-name)))
743    (if slot
744        (slot-definition-location slot)
745        nil)))
746
747(defun instance-slot-location (instance slot-name)
748  (let ((layout (std-instance-layout instance)))
749    (and layout (layout-slot-location layout slot-name))))
750
751(defun slot-value (object slot-name)
752  (let* ((class (class-of object))
753         (metaclass (class-of class)))
754    (if (or (eq metaclass +the-standard-class+)
755            (eq metaclass +the-structure-class+)
756            (eq metaclass +the-funcallable-standard-class+))
757        (std-slot-value object slot-name)
758        (slot-value-using-class class object
759                                (find-slot-definition class slot-name)))))
760
761(defun %set-slot-value (object slot-name new-value)
762  (let* ((class (class-of object))
763         (metaclass (class-of class)))
764    (if (or (eq metaclass +the-standard-class+)
765            (eq metaclass +the-structure-class+)
766            (eq metaclass +the-funcallable-standard-class+))
767        (setf (std-slot-value object slot-name) new-value)
768        (setf (slot-value-using-class class object
769                                      (find-slot-definition class slot-name))
770              new-value))))
771
772(defsetf slot-value %set-slot-value)
773
774(defun slot-boundp (object slot-name)
775  (let* ((class (class-of object))
776         (metaclass (class-of class)))
777    (if (or (eq metaclass +the-standard-class+) 
778            (eq metaclass +the-funcallable-standard-class+))
779        (std-slot-boundp object slot-name)
780        (slot-boundp-using-class class object
781                                 (find-slot-definition class slot-name)))))
782
783(defun std-slot-makunbound (instance slot-name)
784  (let ((location (instance-slot-location instance slot-name)))
785    (cond ((fixnump location)
786           (setf (standard-instance-access instance location) +slot-unbound+))
787          ((consp location)
788           (setf (cdr location) +slot-unbound+))
789          (t
790           (slot-missing (class-of instance) instance slot-name 'slot-makunbound))))
791  instance)
792
793(defun slot-makunbound (object slot-name)
794  (let* ((class (class-of object))
795         (metaclass (class-of class)))
796    (if (or (eq metaclass +the-standard-class+)
797            (eq metaclass +the-funcallable-standard-class+))
798        (std-slot-makunbound object slot-name)
799        (slot-makunbound-using-class class object
800                                     (find-slot-definition class slot-name)))))
801
802(defun std-slot-exists-p (instance slot-name)
803  (not (null (find slot-name (class-slots (class-of instance))
804                   :key 'slot-definition-name))))
805
806(defun slot-exists-p (object slot-name)
807  (if (eq (class-of (class-of object)) +the-standard-class+)
808      (std-slot-exists-p object slot-name)
809      (slot-exists-p-using-class (class-of object) object slot-name)))
810
811(defun instance-slot-p (slot)
812  (eq (slot-definition-allocation slot) :instance))
813
814(defun std-allocate-instance (class)
815  (sys::%std-allocate-instance class))
816
817(defun allocate-funcallable-instance (class)
818  (let ((instance (sys::%allocate-funcallable-instance class)))
819    (set-funcallable-instance-function
820     instance
821     #'(lambda (&rest args)
822         (declare (ignore args))
823         (error 'program-error "Called a funcallable-instance with unset function.")))
824    instance))
825
826(declaim (notinline class-prototype))
827(defun class-prototype (class)
828  (unless (class-finalized-p class) (error "Class ~A not finalized" (class-name class)))
829  (std-allocate-instance class))
830
831(defun maybe-finalize-class-subtree (class)
832  (when (every #'class-finalized-p (class-direct-superclasses class))
833    (finalize-inheritance class)
834    (dolist (subclass (class-direct-subclasses class))
835      (maybe-finalize-class-subtree subclass))))
836
837(defun make-instance-standard-class (metaclass
838                                     &rest initargs
839                                     &key name direct-superclasses direct-slots
840                                       direct-default-initargs
841                                       documentation)
842  (declare (ignore metaclass))
843  (let ((class (std-allocate-instance +the-standard-class+)))
844    (unless *clos-booting*
845      (check-initargs (list #'allocate-instance #'initialize-instance)
846                      (list* class initargs)
847                      class t initargs
848                      *make-instance-initargs-cache* 'make-instance))
849    (%set-class-name name class)
850    ;; KLUDGE: necessary in define-primordial-class, otherwise
851    ;; StandardClass.getClassLayout() throws an error
852    (unless *clos-booting* (%set-class-layout nil class))
853    (%set-class-direct-subclasses ()  class)
854    (%set-class-direct-methods ()  class)
855    (%set-class-documentation class documentation)
856    (std-after-initialization-for-classes class
857                                          :direct-superclasses direct-superclasses
858                                          :direct-slots direct-slots
859                                          :direct-default-initargs direct-default-initargs)
860    class))
861
862;(defun convert-to-direct-slot-definition (class canonicalized-slot)
863;  (apply #'make-instance
864;         (apply #'direct-slot-definition-class
865;                class canonicalized-slot)
866;         canonicalized-slot))
867
868(defun canonicalize-direct-superclass-list (class direct-superclasses)
869  (cond (direct-superclasses)
870        ((subtypep (class-of class) +the-funcallable-standard-class+)
871         (list +the-funcallable-standard-object-class+))
872        ((subtypep (class-of class) +the-standard-class+)
873         (list +the-standard-object-class+))))
874
875(defun std-after-initialization-for-classes (class
876                                             &key direct-superclasses direct-slots
877                                             direct-default-initargs
878                                             &allow-other-keys)
879  (let ((supers (canonicalize-direct-superclass-list class direct-superclasses)))
880    (setf (class-direct-superclasses class) supers)
881    (dolist (superclass supers)
882      (add-direct-subclass superclass class)))
883  (let ((slots (mapcar #'(lambda (slot-properties)
884                          (apply #'make-direct-slot-definition class slot-properties))
885                       direct-slots)))
886    (setf (class-direct-slots class) slots)
887    (dolist (direct-slot slots)
888      (dolist (reader (slot-definition-readers direct-slot))
889        (add-reader-method class reader direct-slot))
890      (dolist (writer (slot-definition-writers direct-slot))
891        (add-writer-method class writer direct-slot))))
892  (setf (class-direct-default-initargs class) direct-default-initargs)
893  (maybe-finalize-class-subtree class)
894  (values))
895
896;;; Bootstrap the lower parts of the metaclass hierarchy.
897
898(defmacro define-primordial-class (name superclasses direct-slots)
899  "Primitive class definition tool.
900No non-standard metaclasses, accessor methods, duplicate slots,
901non-existent superclasses, default initargs, or other complicated stuff.
902Handle with care."
903  (let ((class (gensym)))
904    `(let ((,class (make-instance-standard-class
905                    nil
906                    :name ',name
907                    :direct-superclasses ',(mapcar #'find-class superclasses)
908                    :direct-slots ,(canonicalize-direct-slots direct-slots))))
909       (%set-find-class ',name ,class)
910       ,class)))
911
912(define-primordial-class eql-specializer (specializer)
913  ((object :initform nil)
914   (direct-methods :initform nil)))
915
916(define-primordial-class method-combination (metaobject)
917  ((sys::name :initarg :name :initform nil)
918   (sys::%documentation :initarg :documentation :initform nil)
919   (options :initarg :options :initform nil)))
920
921(define-primordial-class short-method-combination (method-combination)
922  ((operator :initarg :operator)
923   (identity-with-one-argument :initarg :identity-with-one-argument)))
924
925(define-primordial-class long-method-combination (method-combination)
926  ((sys::lambda-list :initarg :lambda-list)
927   (method-group-specs :initarg :method-group-specs)
928   (args-lambda-list :initarg :args-lambda-list)
929   (generic-function-symbol :initarg :generic-function-symbol)
930   (function :initarg :function)
931   (arguments :initarg :arguments)
932   (declarations :initarg :declarations)
933   (forms :initarg :forms)))
934
935(define-primordial-class standard-accessor-method (standard-method)
936  ((sys::%slot-definition :initarg :slot-definition :initform nil)))
937
938(define-primordial-class standard-reader-method (standard-accessor-method)
939  ())
940(defconstant +the-standard-reader-method-class+
941  (find-class 'standard-reader-method))
942
943(define-primordial-class standard-writer-method (standard-accessor-method)
944  ())
945(defconstant +the-standard-writer-method-class+
946  (find-class 'standard-writer-method))
947
948(define-primordial-class structure-class (class)
949  ())
950(defconstant +the-structure-class+ (find-class 'structure-class))
951
952(define-primordial-class forward-referenced-class (class)
953  ;; The standard-class layout.  Not all of these slots are necessary,
954  ;; but at least NAME and DIRECT-SUBCLASSES are.
955  ((sys::name :initarg :name :initform nil)
956   (sys::layout :initform nil)
957   (sys::direct-superclasses :initform nil)
958   (sys::direct-subclasses :initform nil)
959   (sys::precedence-list :initform nil)
960   (sys::direct-methods :initform nil)
961   (sys::direct-slots :initform nil)
962   (sys::slots :initform nil)
963   (sys::direct-default-initargs :initform nil)
964   (sys::default-initargs :initform nil)
965   (sys::finalized-p :initform nil)
966   (sys::%documentation :initform nil)))
967(defconstant +the-forward-referenced-class+
968  (find-class 'forward-referenced-class))
969
970(defvar *extensible-built-in-classes*
971  (list (find-class 'sequence)
972        (find-class 'java:java-object)))
973
974(defvar *make-instance-initargs-cache*
975  (make-hash-table :test #'eq)
976  "Cached sets of allowable initargs, keyed on the class they belong to.")
977(defvar *reinitialize-instance-initargs-cache*
978  (make-hash-table :test #'eq)
979  "Cached sets of allowable initargs, keyed on the class they belong to.")
980
981(defun expand-long-defcombin (name args)
982  (destructuring-bind (lambda-list method-groups &rest body) args
983    `(apply #'define-long-form-method-combination
984            ',name
985            ',lambda-list
986            (list ,@(mapcar #'canonicalize-method-group-spec method-groups))
987            ',body)))
988
989;;; The class method-combination and its subclasses are defined in
990;;; StandardClass.java, but we cannot use make-instance and slot-value
991;;; yet.
992
993(defun %make-long-method-combination (&key name documentation lambda-list
994                                       method-group-specs args-lambda-list
995                                       generic-function-symbol function
996                                       arguments declarations forms)
997  (let ((instance (std-allocate-instance (find-class 'long-method-combination))))
998    (setf (std-slot-value instance 'sys::name) name)
999    (setf (std-slot-value instance 'sys:%documentation) documentation)
1000    (setf (std-slot-value instance 'sys::lambda-list) lambda-list)
1001    (setf (std-slot-value instance 'method-group-specs) method-group-specs)
1002    (setf (std-slot-value instance 'args-lambda-list) args-lambda-list)
1003    (setf (std-slot-value instance 'generic-function-symbol)
1004          generic-function-symbol)
1005    (setf (std-slot-value instance 'function) function)
1006    (setf (std-slot-value instance 'arguments) arguments)
1007    (setf (std-slot-value instance 'declarations) declarations)
1008    (setf (std-slot-value instance 'forms) forms)
1009    (setf (std-slot-value instance 'options) nil)
1010    instance))
1011
1012(defun method-combination-name (method-combination)
1013  (check-type method-combination method-combination)
1014  (std-slot-value method-combination 'sys::name))
1015
1016(defun method-combination-documentation (method-combination)
1017  (check-type method-combination method-combination)
1018  (std-slot-value method-combination 'sys:%documentation))
1019
1020(defun short-method-combination-operator (method-combination)
1021  (check-type method-combination short-method-combination)
1022  (std-slot-value method-combination 'operator))
1023
1024(defun short-method-combination-identity-with-one-argument (method-combination)
1025  (check-type method-combination short-method-combination)
1026  (std-slot-value method-combination 'identity-with-one-argument))
1027
1028(defun long-method-combination-lambda-list (method-combination)
1029  (check-type method-combination long-method-combination)
1030  (std-slot-value method-combination 'sys::lambda-list))
1031
1032(defun long-method-combination-method-group-specs (method-combination)
1033  (check-type method-combination long-method-combination)
1034  (std-slot-value method-combination 'method-group-specs))
1035
1036(defun long-method-combination-args-lambda-list (method-combination)
1037  (check-type method-combination long-method-combination)
1038  (std-slot-value method-combination 'args-lambda-list))
1039
1040(defun long-method-combination-generic-function-symbol (method-combination)
1041  (check-type method-combination long-method-combination)
1042  (std-slot-value method-combination 'generic-function-symbol))
1043
1044(defun long-method-combination-function (method-combination)
1045  (check-type method-combination long-method-combination)
1046  (std-slot-value method-combination 'function))
1047
1048(defun long-method-combination-arguments (method-combination)
1049  (check-type method-combination long-method-combination)
1050  (std-slot-value method-combination 'arguments))
1051
1052(defun long-method-combination-declarations (method-combination)
1053  (check-type method-combination long-method-combination)
1054  (std-slot-value method-combination 'declarations))
1055
1056(defun long-method-combination-forms (method-combination)
1057  (check-type method-combination long-method-combination)
1058  (std-slot-value method-combination 'forms))
1059
1060
1061(defun expand-short-defcombin (whole)
1062  (let* ((name (cadr whole))
1063         (documentation
1064          (getf (cddr whole) :documentation ""))
1065         (identity-with-one-arg
1066          (getf (cddr whole) :identity-with-one-argument nil))
1067         (operator
1068          (getf (cddr whole) :operator name)))
1069    `(progn
1070       (let ((instance (std-allocate-instance
1071                        (find-class 'short-method-combination))))
1072         (setf (std-slot-value instance 'sys::name) ',name)
1073         (setf (std-slot-value instance 'sys:%documentation) ',documentation)
1074         (setf (std-slot-value instance 'operator) ',operator)
1075         (setf (std-slot-value instance 'identity-with-one-argument)
1076               ',identity-with-one-arg)
1077         (setf (std-slot-value instance 'options) nil)
1078         (setf (get ',name 'method-combination-object) instance)
1079         ',name))))
1080
1081(defmacro define-method-combination (&whole form name &rest args)
1082  (if (and (cddr form)
1083           (listp (caddr form)))
1084      (expand-long-defcombin name args)
1085      (expand-short-defcombin form)))
1086
1087(define-method-combination +      :identity-with-one-argument t)
1088(define-method-combination and    :identity-with-one-argument t)
1089(define-method-combination append :identity-with-one-argument nil)
1090(define-method-combination list   :identity-with-one-argument nil)
1091(define-method-combination max    :identity-with-one-argument t)
1092(define-method-combination min    :identity-with-one-argument t)
1093(define-method-combination nconc  :identity-with-one-argument t)
1094(define-method-combination or     :identity-with-one-argument t)
1095(define-method-combination progn  :identity-with-one-argument t)
1096
1097;;;
1098;;; long form of define-method-combination (from Sacla and XCL)
1099;;;
1100(defun method-group-p (selecter qualifiers)
1101  ;; selecter::= qualifier-pattern | predicate
1102  (etypecase selecter
1103    (list (or (equal selecter qualifiers)
1104              (let ((last (last selecter)))
1105                (when (eq '* (cdr last))
1106                  (let* ((prefix `(,@(butlast selecter) ,(car last)))
1107                         (pos (mismatch prefix qualifiers)))
1108                    (or (null pos) (= pos (length prefix))))))))
1109    ((eql *) t)
1110    (symbol (funcall (symbol-function selecter) qualifiers))))
1111
1112(defun check-variable-name (name)
1113  (flet ((valid-variable-name-p (name)
1114                                (and (symbolp name) (not (constantp name)))))
1115    (assert (valid-variable-name-p name))))
1116
1117(defun canonicalize-method-group-spec (spec)
1118  ;; spec ::= (name {qualifier-pattern+ | predicate} [[long-form-option]])
1119  ;; long-form-option::= :description description | :order order |
1120  ;;                     :required required-p
1121  ;; a canonicalized-spec is a simple plist.
1122  (let* ((rest spec)
1123         (name (prog2 (check-variable-name (car rest))
1124                 (car rest)
1125                 (setq rest (cdr rest))))
1126         (option-names '(:description :order :required))
1127         (selecters (let ((end (or (position-if #'(lambda (it)
1128                                                   (member it option-names))
1129                                                rest)
1130                                   (length rest))))
1131                      (prog1 (subseq rest 0 end)
1132                        (setq rest (subseq rest end)))))
1133         (description (getf rest :description ""))
1134         (order (getf rest :order :most-specific-first))
1135         (required-p (getf rest :required)))
1136    `(list :name ',name
1137           :predicate (lambda (qualifiers)
1138                        (loop for item in ',selecters
1139                          thereis (method-group-p item qualifiers)))
1140           :description ',description
1141           :order ',order
1142           :required ',required-p
1143           :*-selecter ,(equal selecters '(*)))))
1144
1145(defun extract-required-part (lambda-list)
1146  (flet ((skip (key lambda-list)
1147               (if (eq (first lambda-list) key)
1148                   (cddr lambda-list)
1149                   lambda-list)))
1150    (let* ((trimmed-lambda-list
1151            (skip '&environment (skip '&whole lambda-list)))
1152           (after-required-lambda-list
1153            (member-if #'(lambda (it) (member it lambda-list-keywords))
1154                       trimmed-lambda-list)))
1155      (if after-required-lambda-list
1156        (ldiff trimmed-lambda-list after-required-lambda-list)
1157        trimmed-lambda-list))))
1158
1159(defun extract-specified-part (key lambda-list)
1160  (case key
1161    ((&eval &whole)
1162     (list (second (member key lambda-list))))
1163    (t
1164     (let ((here (cdr (member key lambda-list))))
1165       (ldiff here
1166              (member-if #'(lambda (it) (member it lambda-list-keywords))
1167                         here))))))
1168
1169(defun extract-optional-part (lambda-list)
1170  (extract-specified-part '&optional lambda-list))
1171
1172(defun parse-define-method-combination-args-lambda-list (lambda-list)
1173  ;; Define-method-combination Arguments Lambda Lists
1174  ;; http://www.lispworks.com/reference/HyperSpec/Body/03_dj.htm
1175  (let ((required (extract-required-part lambda-list))
1176        (whole    (extract-specified-part '&whole    lambda-list))
1177        (optional (extract-specified-part '&optional lambda-list))
1178        (rest     (extract-specified-part '&rest     lambda-list))
1179        (keys     (extract-specified-part '&key      lambda-list))
1180        (aux      (extract-specified-part '&aux      lambda-list)))
1181    (values (first whole)
1182            required
1183            (mapcar #'(lambda (spec)
1184                       (if (consp spec)
1185                           `(,(first spec) ,(second spec) ,@(cddr spec))
1186                           `(,spec nil)))
1187                    optional)
1188            (first rest)
1189            (mapcar #'(lambda (spec)
1190                       (let ((key (if (consp spec) (car spec) spec))
1191                             (rest (when (consp spec) (rest spec))))
1192                         `(,(if (consp key) key `(,(make-keyword key) ,key))
1193                           ,(car rest)
1194                           ,@(cdr rest))))
1195                    keys)
1196            (mapcar #'(lambda (spec)
1197                       (if (consp spec)
1198                           `(,(first spec) ,(second spec))
1199                           `(,spec nil)))
1200                    aux))))
1201
1202(defun wrap-with-call-method-macro (gf args-var emf-form)
1203  `(macrolet
1204       ((call-method (method &optional next-method-list)
1205          `(funcall
1206            ,(cond
1207              ((listp method)
1208               (assert (eq (first method) 'make-method))
1209               ;; by generating an inline expansion we prevent allocation
1210               ;; of a method instance which will be discarded immediately
1211               ;; after reading the METHOD-FUNCTION slot
1212               (compute-method-function
1213                    `(lambda (&rest ,(gensym))
1214                       ;; the MAKE-METHOD body form gets evaluated in
1215                       ;; the null lexical environment augmented
1216                       ;; with a binding for CALL-METHOD
1217                       ,(wrap-with-call-method-macro ,gf
1218                                                     ',args-var
1219                                                     (second method)))))
1220              (t (method-function method)))
1221            ,',args-var
1222            ,(unless (null next-method-list)
1223                     ;; by not generating an emf when there are no next methods,
1224                     ;; we ensure next-method-p returns NIL
1225                     (compute-effective-method
1226                      ,gf (generic-function-method-combination ,gf)
1227                      (process-next-method-list next-method-list))))))
1228     ,emf-form))
1229
1230(defun assert-unambiguous-method-sorting (group-name methods)
1231  (let ((specializers (make-hash-table :test 'equal)))
1232    (dolist (method methods)
1233      (push method (gethash (method-specializers method) specializers)))
1234    (loop for specializer-methods being each hash-value of specializers
1235       using (hash-key method-specializers)
1236       unless (= 1 (length specializer-methods))
1237       do (error "Ambiguous method sorting in method group ~A due to multiple ~
1238                  methods with specializers ~S: ~S"
1239                 group-name method-specializers specializer-methods))))
1240
1241(defmacro with-method-groups (method-group-specs methods-form &body forms)
1242  (flet ((grouping-form (spec methods-var)
1243           (let ((predicate (coerce-to-function (getf spec :predicate)))
1244                 (group (gensym))
1245                 (leftovers (gensym))
1246                 (method (gensym)))
1247             `(let ((,group '())
1248                    (,leftovers '()))
1249                (dolist (,method ,methods-var)
1250                  (if (funcall ,predicate (method-qualifiers ,method))
1251                      (push ,method ,group)
1252                      (push ,method ,leftovers)))
1253                (ecase ,(getf spec :order)
1254                  (:most-specific-last )
1255                  (:most-specific-first (setq ,group (nreverse ,group))))
1256                ,@(when (getf spec :required)
1257                        `((when (null ,group)
1258                            (error "Method group ~S must not be empty."
1259                                   ',(getf spec :name)))))
1260                (setq ,methods-var (nreverse ,leftovers))
1261                ,group))))
1262    (let ((rest (gensym))
1263          (method (gensym)))
1264      `(let* ((,rest ,methods-form)
1265              ,@(mapcar #'(lambda (spec)
1266                           `(,(getf spec :name) ,(grouping-form spec rest)))
1267                        method-group-specs))
1268         (dolist (,method ,rest)
1269           (invalid-method-error ,method
1270                                 "Method ~S with qualifiers ~S does not belong to any method group."
1271                                 ,method (method-qualifiers ,method)))
1272         ,@(unless (and (= 1 (length method-group-specs))
1273                        (getf (car method-group-specs) :*-selecter))
1274             (mapcar #'(lambda (spec)
1275                         `(assert-unambiguous-method-sorting ',(getf spec :name) ,(getf spec :name)))
1276                     method-group-specs))
1277         ,@forms))))
1278
1279(defun method-combination-type-lambda-with-args-emf
1280    (&key args-lambda-list generic-function-symbol forms &allow-other-keys)
1281  (multiple-value-bind
1282        (whole required optional rest keys aux)
1283      (parse-define-method-combination-args-lambda-list args-lambda-list)
1284    (unless rest
1285      (when keys
1286        (setf rest (gensym))))
1287    (let* ((gf-lambda-list (gensym))
1288           (args-var (gensym))
1289           (args-len-var (gensym))
1290           (binding-forms (gensym))
1291           (needs-args-len-var (gensym))
1292           (emf-form (gensym)))
1293      `(let* ((,gf-lambda-list (slot-value ,generic-function-symbol
1294                                           'sys::lambda-list))
1295              (nreq (length (extract-required-part ,gf-lambda-list)))
1296              (nopt (length (extract-optional-part ,gf-lambda-list)))
1297              (,binding-forms)
1298              (,needs-args-len-var)
1299              (,emf-form
1300               (let* (,@(when whole
1301                              `((,whole (progn
1302                                          (push `(,',whole ,',args-var)
1303                                                ,binding-forms)
1304                                          ',args-var))))
1305                      ,@(when rest
1306                              ;; ### TODO: use a fresh symbol for the rest
1307                              ;;   binding being generated and pushed into binding-forms
1308                              `((,rest (progn
1309                                         (push `(,',rest
1310                                                 (subseq ,',args-var
1311                                                          ,(+ nreq nopt)))
1312                                               ,binding-forms)
1313                                         ',rest))))
1314                        ,@(loop for var in required and i upfrom 0
1315                               for var-binding = (gensym)
1316                             collect `(,var (when (< ,i nreq)
1317                                              (push `(,',var-binding
1318                                                      (nth ,,i ,',args-var))
1319                                                    ,binding-forms)
1320                                              ',var-binding)))
1321                        ,@(loop for (var initform supplied-var) in optional
1322                             and i upfrom 0
1323                             for supplied-binding = (or supplied-var (gensym))
1324                             for var-binding = (gensym)
1325                             ;; check for excess parameters
1326                             ;; only assign initform if the parameter
1327                             ;; isn't in excess: the spec says explicitly
1328                             ;; to bind parameters in excess to forms evaluating
1329                             ;; to nil.
1330                             ;; This leaves initforms to be used with
1331                             ;; parameters not supplied in excess, but
1332                             ;; not available in the arguments list
1333                             ;;
1334                             ;; Also, if specified, bind "supplied-p"
1335                             collect `(,supplied-binding
1336                                       (when (< ,i nopt)
1337                                         (setq ,needs-args-len-var t)
1338                              ;; ### TODO: use a fresh symbol for the supplied binding
1339                              ;;   binding being generated and pushed into binding-forms
1340                                         (push `(,',supplied-binding
1341                                                 (< ,(+ ,i nreq) ,',args-len-var))
1342                                               ,binding-forms)
1343                                         ',supplied-binding))
1344                             collect `(,var (when (< ,i nopt)
1345                                              (push `(,',var-binding
1346                                                      (if ,',supplied-binding
1347                                                          (nth ,(+ ,i nreq)
1348                                                               ,',args-var)
1349                                                          ,',initform))
1350                                                    ,binding-forms)
1351                                              ',var-binding)))
1352                        ,@(loop for ((key var) initform supplied-var) in keys
1353                             for supplied-binding = (or supplied-var (gensym))
1354                             for var-binding = (gensym)
1355                             ;; Same as optional parameters:
1356                             ;; even though keywords can't be supplied in
1357                             ;; excess, we should bind "supplied-p" in case
1358                             ;; the key isn't supplied in the arguments list
1359                             collect `(,supplied-binding
1360                                       (progn
1361                              ;; ### TODO: use a fresh symbol for the rest
1362                              ;;   binding being generated and pushed into binding-forms
1363                                         (push `(,',supplied-binding
1364                                                 (member ,',key ,',rest))
1365                                               ,binding-forms)
1366                                         ',supplied-binding))
1367                             collect `(,var (progn
1368                                              (push `(,',var-binding
1369                                                      (if ,',supplied-binding
1370                                                          (cadr ,',supplied-binding)
1371                                                          ,',initform))
1372                                                    ,binding-forms)
1373                                              ',var-binding)))
1374                        ,@(loop for (var initform) in aux
1375                             for var-binding = (gensym)
1376                             collect `(,var (progn
1377                                              (push '(,var-binding ,initform)
1378                                                    ,binding-forms)
1379                                              ',var-binding))))
1380                 ,@forms)))
1381         `(lambda (,',args-var)
1382            ;; set up bindings to ensure the expressions to which the
1383            ;; variables of the arguments option have been bound are
1384            ;; evaluated exactly once.
1385            (let* (,@(when ,needs-args-len-var
1386                           `((,',args-len-var (length ,',args-var))))
1387                   ,@(reverse ,binding-forms))
1388              ;; This is the lambda which *is* the effective method
1389              ;; hence gets called on every method invocation
1390              ;; be as efficient in this method as we can be
1391              ,(wrap-with-call-method-macro ,generic-function-symbol
1392                                            ',args-var ,emf-form)))))))
1393
1394(defun method-combination-type-lambda
1395  (&rest all-args
1396   &key name lambda-list args-lambda-list generic-function-symbol
1397        method-group-specs declarations forms &allow-other-keys)
1398  (declare (ignore name))
1399  (let ((methods (gensym))
1400        (args-var (gensym))
1401        (emf-form (gensym)))
1402    `(lambda (,generic-function-symbol ,methods ,@lambda-list)
1403       ;; This is the lambda which computes the effective method
1404       ,@declarations
1405       (with-method-groups ,method-group-specs
1406           ,methods
1407         ,(if (null args-lambda-list)
1408              `(let ((,emf-form (progn ,@forms)))
1409                 `(lambda (,',args-var)
1410                    ;; This is the lambda which *is* the effective method
1411                    ;; hence gets called on every method invocation
1412                    ;; be as efficient in this method as we can be
1413                    ,(wrap-with-call-method-macro ,generic-function-symbol
1414                                                  ',args-var ,emf-form)))
1415              (apply #'method-combination-type-lambda-with-args-emf all-args))))))
1416
1417(defun declarationp (expr)
1418  (and (consp expr) (eq (car expr) 'DECLARE)))
1419
1420(defun long-form-method-combination-args (args)
1421  ;; define-method-combination name lambda-list (method-group-specifier*) args
1422  ;; args ::= [(:arguments . args-lambda-list)]
1423  ;;          [(:generic-function generic-function-symbol)]
1424  ;;          [[declaration* | documentation]] form*
1425  (let ((rest args))
1426    (labels ((nextp (key) (and (consp (car rest)) (eq key (caar rest))))
1427             (args-lambda-list ()
1428               (when (nextp :arguments)
1429                 (prog1 (cdr (car rest)) (setq rest (cdr rest)))))
1430             (generic-function-symbol ()
1431                (if (nextp :generic-function)
1432                    (prog1 (second (car rest)) (setq rest (cdr rest)))
1433                    (gensym)))
1434             (declaration* ()
1435               (let ((end (position-if-not #'declarationp rest)))
1436                 (when end
1437                   (prog1 (subseq rest 0 end) (setq rest (nthcdr end rest))))))
1438             (documentation? ()
1439               (when (stringp (car rest))
1440                 (prog1 (car rest) (setq rest (cdr rest)))))
1441             (form* () rest))
1442      (let ((declarations '()))
1443        `(:args-lambda-list ,(args-lambda-list)
1444                            :generic-function-symbol ,(generic-function-symbol)
1445                            :documentation ,(prog2 (setq declarations (declaration*))
1446                                              (documentation?))
1447                            :declarations (,@declarations ,@(declaration*))
1448                            :forms ,(form*))))))
1449
1450(defun define-long-form-method-combination (name lambda-list method-group-specs
1451                                                 &rest args)
1452  (let* ((initargs `(:name ,name
1453                     :lambda-list ,lambda-list
1454                     :method-group-specs ,method-group-specs
1455                     ,@(long-form-method-combination-args args)))
1456         (lambda-expression (apply #'method-combination-type-lambda initargs)))
1457    (setf (get name 'method-combination-object)
1458          (apply '%make-long-method-combination
1459                 :function (coerce-to-function lambda-expression) initargs))
1460    name))
1461
1462(defun std-find-method-combination (gf name options)
1463  (declare (ignore gf))
1464  (when (and (eql name 'standard) options)
1465    ;; CLHS DEFGENERIC
1466    (error "The standard method combination does not accept any arguments."))
1467  (let ((mc (get name 'method-combination-object)))
1468    (cond
1469      ((null mc) (error "Method combination ~S not found" name))
1470      ((null options) mc)
1471      ((typep mc 'short-method-combination)
1472       (make-instance
1473        'short-method-combination
1474        :name name
1475        :documentation (method-combination-documentation mc)
1476        :operator (short-method-combination-operator mc)
1477        :identity-with-one-argument
1478        (short-method-combination-identity-with-one-argument mc)
1479        :options options))
1480      ((typep mc 'long-method-combination)
1481       (make-instance
1482        'long-method-combination
1483        :name name
1484        :documentation (method-combination-documentation mc)
1485        :lambda-list (long-method-combination-lambda-list mc)
1486        :method-group-specs (long-method-combination-method-group-specs mc)
1487        :args-lambda-list (long-method-combination-args-lambda-list mc)
1488        :generic-function-symbol (long-method-combination-generic-function-symbol mc)
1489        :function (long-method-combination-function mc)
1490        :arguments (long-method-combination-arguments mc)
1491        :declarations (long-method-combination-declarations mc)
1492        :forms (long-method-combination-forms mc)
1493        :options options)))))
1494
1495(declaim (notinline find-method-combination))
1496(defun find-method-combination (gf name options)
1497  (std-find-method-combination gf name options))
1498
1499(defconstant +the-standard-method-combination+
1500  (let ((instance (std-allocate-instance (find-class 'method-combination))))
1501    (setf (std-slot-value instance 'sys::name) 'standard)
1502    (setf (std-slot-value instance 'sys:%documentation)
1503          "The standard method combination.")
1504    (setf (std-slot-value instance 'options) nil)
1505    instance)
1506  "The standard method combination.
1507Do not use this object for identity since it changes between
1508compile-time and run-time.  To detect the standard method combination,
1509compare the method combination name to the symbol 'standard.")
1510(setf (get 'standard 'method-combination-object) +the-standard-method-combination+)
1511
1512(defparameter *eql-specializer-table* (make-hash-table :test 'eql))
1513
1514(defun intern-eql-specializer (object)
1515  (or (gethash object *eql-specializer-table*)
1516      (setf (gethash object *eql-specializer-table*)
1517            ;; we will be called during generic function invocation
1518            ;; setup, so have to rely on plain functions here.
1519            (let ((instance (std-allocate-instance (find-class 'eql-specializer))))
1520              (setf (std-slot-value instance 'object) object)
1521              (setf (std-slot-value instance 'direct-methods) nil)
1522              instance))))
1523
1524(defun eql-specializer-object (eql-specializer)
1525  (check-type eql-specializer eql-specializer)
1526  (std-slot-value eql-specializer 'object))
1527
1528;;; Initial versions of some method metaobject readers.  Defined on
1529;;; AMOP pg. 218ff, will be redefined when generic functions are set up.
1530
1531(defun std-method-function (method)
1532  (std-slot-value method 'sys::%function))
1533
1534(defun std-method-generic-function (method)
1535  (std-slot-value method 'sys::%generic-function))
1536
1537(defun std-method-specializers (method)
1538  (std-slot-value method 'sys::specializers))
1539
1540(defun std-method-qualifiers (method)
1541  (std-slot-value method 'sys::qualifiers))
1542
1543(defun std-accessor-method-slot-definition (accessor-method)
1544  (std-slot-value accessor-method 'sys::%slot-definition))
1545
1546;;; Additional method readers
1547(defun std-method-fast-function (method)
1548  (std-slot-value method 'sys::fast-function))
1549
1550(defun std-function-keywords (method)
1551  (values (std-slot-value method 'sys::keywords)
1552          (std-slot-value method 'sys::other-keywords-p)))
1553
1554;;; Preliminary accessor definitions, will be redefined as generic
1555;;; functions later in this file
1556
1557(declaim (notinline method-generic-function))
1558(defun method-generic-function (method)
1559  (std-method-generic-function method))
1560
1561(declaim (notinline method-function))
1562(defun method-function (method)
1563  (std-method-function method))
1564
1565(declaim (notinline method-specializers))
1566(defun method-specializers (method)
1567  (std-method-specializers method))
1568
1569(declaim (notinline method-qualifiers))
1570(defun method-qualifiers (method)
1571  (std-method-qualifiers method))
1572
1573
1574
1575;;; MOP (p. 216) specifies the following reader generic functions:
1576;;;   generic-function-argument-precedence-order
1577;;;   generic-function-declarations
1578;;;   generic-function-lambda-list
1579;;;   generic-function-method-class
1580;;;   generic-function-method-combination
1581;;;   generic-function-methods
1582;;;   generic-function-name
1583
1584;;; Additionally, we define the following reader functions:
1585;;;   generic-function-required-arguments
1586;;;   generic-function-optional-arguments
1587
1588;;; These are defined as functions here and redefined as generic
1589;;; functions via atomic-defgeneric once we're all set up.
1590
1591(defun generic-function-name (gf)
1592  (std-slot-value gf 'sys::name))
1593
1594(defun generic-function-lambda-list (gf)
1595  (std-slot-value gf 'sys::lambda-list))
1596
1597(defun generic-function-methods (gf)
1598  (std-slot-value gf 'sys::methods))
1599
1600(defun generic-function-method-class (gf)
1601  (std-slot-value gf 'sys::method-class))
1602
1603(defun generic-function-method-combination (gf)
1604  (std-slot-value gf 'sys::%method-combination))
1605
1606(defun generic-function-argument-precedence-order (gf)
1607  (std-slot-value gf 'sys::argument-precedence-order))
1608
1609(defun generic-function-required-arguments (gf)
1610  (std-slot-value gf 'sys::required-args))
1611
1612(defun generic-function-optional-arguments (gf)
1613  (std-slot-value gf 'sys::optional-args))
1614
1615(defun (setf method-lambda-list) (new-value method)
1616  (setf (std-slot-value method 'sys::lambda-list) new-value))
1617
1618(defun (setf method-qualifiers) (new-value method)
1619  (setf (std-slot-value method 'sys::qualifiers) new-value))
1620
1621(defun method-documentation (method)
1622  (std-slot-value method 'sys:%documentation))
1623
1624(defun (setf method-documentation) (new-value method)
1625  (setf (std-slot-value method 'sys:%documentation) new-value))
1626
1627;;; defgeneric
1628
1629(defmacro defgeneric (function-name lambda-list
1630                                    &rest options-and-method-descriptions)
1631  (let ((options ())
1632        (methods ())
1633        (declarations ())
1634        (documentation nil))
1635    (dolist (item options-and-method-descriptions)
1636      (case (car item)
1637        (declare
1638         (setf declarations (append declarations (cdr item))))
1639        (:documentation
1640         (when documentation
1641           (error 'program-error
1642                  :format-control "Documentation option was specified twice for generic function ~S."
1643                  :format-arguments (list function-name)))
1644         (setf documentation t)
1645         (push item options))
1646        (:method
1647            ;; KLUDGE (rudi 2013-04-02): this only works with subclasses
1648            ;; of standard-generic-function, since the initial-methods
1649            ;; slot is not mandated by AMOP
1650            (push
1651             `(push (defmethod ,function-name ,@(cdr item))
1652               (std-slot-value (fdefinition ',function-name) 'sys::initial-methods))
1653             methods))
1654        (t
1655         (push item options))))
1656    (when declarations (push (list :declarations declarations) options))
1657    (setf options (nreverse options)
1658          methods (nreverse methods))
1659    ;; Since DEFGENERIC currently shares its argument parsing with
1660    ;; DEFMETHOD, we perform this check here.
1661    (when (find '&aux lambda-list)
1662      (error 'program-error
1663             :format-control "&AUX is not allowed in a generic function lambda list: ~S"
1664             :format-arguments (list lambda-list)))
1665    `(prog1
1666       (%defgeneric
1667        ',function-name
1668        :lambda-list ',lambda-list
1669        ,@(canonicalize-defgeneric-options options))
1670       ,@methods)))
1671
1672(defun canonicalize-defgeneric-options (options)
1673  (mapappend #'canonicalize-defgeneric-option options))
1674
1675(defun canonicalize-defgeneric-option (option)
1676  (case (car option)
1677    (:generic-function-class
1678     (list :generic-function-class `(find-class ',(cadr option))))
1679    (:method-class
1680     (list :method-class `(find-class ',(cadr option))))
1681    (:method-combination
1682     (list :method-combination `',(cdr option)))
1683    (:argument-precedence-order
1684     (list :argument-precedence-order `',(cdr option)))
1685    (t
1686     (list `',(car option) `',(cadr option)))))
1687
1688;; From OpenMCL (called canonicalize-argument-precedence-order there,
1689;; but AMOP specifies argument-precedence-order to return a permutation
1690;; of the required arguments, not a list of indices, so we calculate
1691;; them on demand).
1692(defun argument-precedence-order-indices (apo req)
1693  (cond ((equal apo req) nil)
1694        ((not (eql (length apo) (length req)))
1695         (error 'program-error
1696                :format-control "Specified argument precedence order ~S does not match lambda list."
1697                :format-arguments (list apo)))
1698        (t (let ((res nil))
1699             (dolist (arg apo (nreverse res))
1700               (let ((index (position arg req)))
1701                 (if (or (null index) (memq index res))
1702                     (error 'program-error
1703                            :format-control "Specified argument precedence order ~S does not match lambda list."
1704                            :format-arguments (list apo)))
1705                 (push index res)))))))
1706
1707(defun find-generic-function (name &optional (errorp t))
1708  (let ((function (and (fboundp name) (fdefinition name))))
1709    (when function
1710      (when (typep function 'generic-function)
1711        (return-from find-generic-function function))
1712      (when (and *traced-names* (find name *traced-names* :test #'equal))
1713        (setf function (untraced-function name))
1714        (when (typep function 'generic-function)
1715          (return-from find-generic-function function)))))
1716  (if errorp
1717      (error "There is no generic function named ~S." name)
1718      nil))
1719
1720(defun lambda-lists-congruent-p (lambda-list1 lambda-list2)
1721  (let* ((plist1 (analyze-lambda-list lambda-list1))
1722         (args1 (getf plist1 :required-args))
1723         (plist2 (analyze-lambda-list lambda-list2))
1724         (args2 (getf plist2 :required-args)))
1725    (= (length args1) (length args2))))
1726
1727(defun %defgeneric (function-name &rest all-keys)
1728  (when (fboundp function-name)
1729    (let ((gf (fdefinition function-name)))
1730      (when (typep gf 'standard-generic-function)
1731        ;; Remove methods defined by previous DEFGENERIC forms, as
1732        ;; specified by CLHS, 7.7 (Macro DEFGENERIC).  KLUDGE: only
1733        ;; works for subclasses of standard-generic-function.  Since
1734        ;; AMOP doesn't specify a reader for initial methods, we have to
1735        ;; skip this step otherwise.
1736        (dolist (method (std-slot-value gf 'sys::initial-methods))
1737          (std-remove-method gf method)
1738          (map-dependents gf
1739                          #'(lambda (dep)
1740                              (update-dependent gf dep
1741                                                'remove-method method))))
1742        (setf (std-slot-value gf 'sys::initial-methods) '()))))
1743  (apply 'ensure-generic-function function-name all-keys))
1744
1745;;; Bootstrap version of ensure-generic-function, handling only
1746;;; standard-generic-function.  This function is replaced later.
1747(declaim (notinline ensure-generic-function))
1748(defun ensure-generic-function (function-name
1749                                &rest all-keys
1750                                &key
1751                                (lambda-list nil lambda-list-supplied-p)
1752                                (generic-function-class +the-standard-generic-function-class+)
1753                                (method-class +the-standard-method-class+)
1754                                (method-combination +the-standard-method-combination+ mc-p)
1755                                argument-precedence-order
1756                                (documentation nil documentation-supplied-p)
1757                                &allow-other-keys)
1758  (setf all-keys (copy-list all-keys))  ; since we modify it
1759  (remf all-keys :generic-function-class)
1760  (let ((gf (find-generic-function function-name nil)))
1761    (if gf
1762        (progn
1763          (when lambda-list-supplied-p
1764            (unless (or (null (generic-function-methods gf))
1765                        (lambda-lists-congruent-p lambda-list
1766                                                  (generic-function-lambda-list gf)))
1767              (error 'simple-error
1768                     :format-control "The lambda list ~S is incompatible with the existing methods of ~S."
1769                     :format-arguments (list lambda-list gf)))
1770            (setf (std-slot-value gf 'sys::lambda-list) lambda-list)
1771            (let* ((plist (analyze-lambda-list lambda-list))
1772                   (required-args (getf plist ':required-args)))
1773              (setf (std-slot-value gf 'sys::required-args) required-args)
1774              (setf (std-slot-value gf 'sys::optional-args)
1775                    (getf plist :optional-args))))
1776          (setf (std-slot-value gf 'sys::argument-precedence-order)
1777                (or argument-precedence-order (generic-function-required-arguments gf)))
1778          (when documentation-supplied-p
1779            (setf (std-slot-value gf 'sys::%documentation) documentation))
1780          (finalize-standard-generic-function gf)
1781          gf)
1782        (progn
1783          (when (and (null *clos-booting*)
1784                     (and (fboundp function-name)
1785                          ;; since we're overwriting an autoloader,
1786                          ;; we're probably meant to redefine it,
1787                          ;; so throwing an error here might be a bad idea.
1788                          ;; also, resolving the symbol isn't
1789                          ;; a good option either: we've seen that lead to
1790                          ;; recursive loading of the same file
1791                          (and (not (autoloadp function-name))
1792                               (and (consp function-name)
1793                                    (eq 'setf (first function-name))
1794                                    (not (autoload-ref-p (second function-name)))))))
1795            (error 'program-error
1796                   :format-control "~A already names an ordinary function, macro, or special operator."
1797                   :format-arguments (list function-name)))
1798          (when mc-p
1799            (error "Preliminary ensure-method does not support :method-combination argument."))
1800          (setf gf (apply (if (eq generic-function-class
1801                                  +the-standard-generic-function-class+)
1802                              #'make-instance-standard-generic-function
1803                              #'make-instance)
1804                          generic-function-class
1805                          :name function-name
1806                          :method-class method-class
1807                          :method-combination method-combination
1808                          all-keys))
1809          gf))))
1810
1811(defun collect-eql-specializer-objects (generic-function)
1812  (let ((result nil))
1813    (dolist (method (generic-function-methods generic-function))
1814      (dolist (specializer (method-specializers method))
1815        (when (typep specializer 'eql-specializer)
1816          (pushnew (eql-specializer-object specializer)
1817                   result
1818                   :test 'eql))))
1819    result))
1820
1821(defun finalize-standard-generic-function (gf)
1822  (%reinit-emf-cache gf (collect-eql-specializer-objects gf))
1823  (set-funcallable-instance-function
1824   gf
1825   (if (eq (class-of gf) +the-standard-generic-function-class+)
1826       (std-compute-discriminating-function gf)
1827       (compute-discriminating-function gf)))
1828  ;; FIXME Do we need to warn on redefinition somewhere else?
1829  (let ((*warn-on-redefinition* nil))
1830    (setf (fdefinition (generic-function-name gf)) gf))
1831  (values))
1832
1833(defun make-instance-standard-generic-function (generic-function-class
1834                                                &key name lambda-list
1835                                                (method-class +the-standard-method-class+)
1836                                                (method-combination +the-standard-method-combination+)
1837                                                argument-precedence-order
1838                                                declarations
1839                                                documentation)
1840  ;; to avoid circularities, we do not call generic functions in here.
1841  (declare (ignore generic-function-class))
1842  (check-argument-precedence-order lambda-list argument-precedence-order)
1843  (let ((gf (allocate-funcallable-instance +the-standard-generic-function-class+)))
1844    (unless (classp method-class) (setf method-class (find-class method-class)))
1845    (unless (typep method-combination 'method-combination)
1846      (setf method-combination
1847            (find-method-combination
1848             gf (car method-combination) (cdr method-combination))))
1849    (setf (std-slot-value gf 'sys::name) name)
1850    (setf (std-slot-value gf 'sys::lambda-list) lambda-list)
1851    (setf (std-slot-value gf 'sys::initial-methods) ())
1852    (setf (std-slot-value gf 'sys::methods) ())
1853    (setf (std-slot-value gf 'sys::method-class) method-class)
1854    (setf (std-slot-value gf 'sys::%method-combination) method-combination)
1855    (setf (std-slot-value gf 'sys::declarations) declarations)
1856    (setf (std-slot-value gf 'sys::%documentation) documentation)
1857    (let* ((plist (analyze-lambda-list (generic-function-lambda-list gf)))
1858           (required-args (getf plist ':required-args)))
1859      (setf (std-slot-value gf 'sys::required-args) required-args)
1860      (setf (std-slot-value gf 'sys::optional-args) (getf plist :optional-args))
1861      (setf (std-slot-value gf 'sys::argument-precedence-order)
1862            (or argument-precedence-order required-args)))
1863    (finalize-standard-generic-function gf)
1864    gf))
1865
1866(defun canonicalize-specializers (specializers)
1867  (mapcar #'canonicalize-specializer specializers))
1868
1869(defun canonicalize-specializer (specializer)
1870  (cond ((classp specializer)
1871         specializer)
1872        ((typep specializer 'eql-specializer)
1873         specializer)
1874        ((symbolp specializer)
1875         (find-class specializer))
1876        ((and (consp specializer)
1877              (eq (car specializer) 'eql))
1878         (let ((object (cadr specializer)))
1879           (when (and (consp object)
1880                      (eq (car object) 'quote))
1881             (setf object (cadr object)))
1882           (intern-eql-specializer object)))
1883        ((and (consp specializer)
1884              (eq (car specializer) 'java:jclass))
1885         (let ((jclass (eval specializer)))
1886           (java::ensure-java-class jclass)))
1887        (t
1888         (error "Unknown specializer: ~S" specializer))))
1889
1890(defun parse-defmethod (args)
1891  (let ((function-name (car args))
1892        (qualifiers ())
1893        (specialized-lambda-list ())
1894        (body ())
1895        (parse-state :qualifiers))
1896    (dolist (arg (cdr args))
1897      (ecase parse-state
1898        (:qualifiers
1899         (if (and (atom arg) (not (null arg)))
1900             (push arg qualifiers)
1901             (progn
1902               (setf specialized-lambda-list arg)
1903               (setf parse-state :body))))
1904        (:body (push arg body))))
1905    (setf qualifiers (nreverse qualifiers)
1906          body (nreverse body))
1907    (multiple-value-bind (real-body declarations documentation)
1908        (parse-body body)
1909      (values function-name
1910              qualifiers
1911              (extract-lambda-list specialized-lambda-list)
1912              (extract-specializer-names specialized-lambda-list)
1913              documentation
1914              declarations
1915              (list* 'block
1916                     (fdefinition-block-name function-name)
1917                     real-body)))))
1918
1919(defun required-portion (gf args)
1920  (let ((number-required (length (generic-function-required-arguments gf))))
1921    (when (< (length args) number-required)
1922      (error 'program-error
1923             :format-control "Not enough arguments for generic function ~S."
1924             :format-arguments (list (generic-function-name gf))))
1925    (subseq args 0 number-required)))
1926
1927(defun extract-lambda-list (specialized-lambda-list)
1928  (let* ((plist (analyze-lambda-list specialized-lambda-list))
1929         (requireds (getf plist :required-names))
1930         (rv (getf plist :rest-var))
1931         (ks (getf plist :key-args))
1932         (keysp (getf plist :keysp))
1933         (aok (getf plist :allow-other-keys))
1934         (opts (getf plist :optional-args))
1935         (auxs (getf plist :auxiliary-args)))
1936    `(,@requireds
1937      ,@(if opts `(&optional ,@opts) ())
1938      ,@(if rv `(&rest ,rv) ())
1939      ,@(if (or ks keysp aok) `(&key ,@ks) ())
1940      ,@(if aok '(&allow-other-keys) ())
1941      ,@(if auxs `(&aux ,@auxs) ()))))
1942
1943(defun extract-specializer-names (specialized-lambda-list)
1944  (let ((plist (analyze-lambda-list specialized-lambda-list)))
1945    (getf plist ':specializers)))
1946
1947(defun get-keyword-from-arg (arg)
1948  (if (listp arg)
1949      (if (listp (car arg))
1950          (caar arg)
1951          (make-keyword (car arg)))
1952      (make-keyword arg)))
1953
1954(defun analyze-lambda-list (lambda-list)
1955  (let ((keys ())           ; Just the keywords
1956        (key-args ())       ; Keywords argument specs
1957        (keysp nil)         ;
1958        (required-names ()) ; Just the variable names
1959        (required-args ())  ; Variable names & specializers
1960        (specializers ())   ; Just the specializers
1961        (rest-var nil)
1962        (optionals ())
1963        (auxs ())
1964        (allow-other-keys nil)
1965        (state :required))
1966    (dolist (arg lambda-list)
1967      (if (member arg lambda-list-keywords)
1968          (ecase arg
1969            (&optional
1970             (unless (eq state :required)
1971               (error 'program-error
1972                      :format-control "~A followed by &OPTIONAL not allowed ~
1973                                       in lambda list ~S"
1974                      :format-arguments (list state lambda-list)))
1975             (setq state '&optional))
1976            (&rest
1977             (unless (or (eq state :required)
1978                         (eq state '&optional))
1979               (error 'program-error
1980                      :format-control "~A followed by &REST not allowed ~
1981                                       in lambda list ~S"
1982                      :format-arguments (list state lambda-list)))
1983             (setq state '&rest))
1984            (&key
1985             (unless (or (eq state :required)
1986                         (eq state '&optional)
1987                         (eq state '&rest))
1988               (error 'program-error
1989                      :format-control "~A followed by &KEY not allowed
1990                                       in lambda list ~S"
1991                      :format-arguments (list state lambda-list)))
1992             (setq keysp t)
1993             (setq state '&key))
1994            (&allow-other-keys
1995             (unless (eq state '&key)
1996               (error 'program-error
1997                      :format-control "&ALLOW-OTHER-KEYS not allowed while
1998                                       parsing ~A in lambda list ~S"
1999                      :format-arguments (list state lambda-list)))
2000             (setq allow-other-keys 't))
2001            (&aux
2002             ;; &aux comes last; any other previous state is fine
2003             (setq state '&aux)))
2004          (case state
2005            (:required
2006             (push-on-end arg required-args)
2007             (if (listp arg)
2008                 (progn (push-on-end (car arg) required-names)
2009                   (push-on-end (cadr arg) specializers))
2010                 (progn (push-on-end arg required-names)
2011                   (push-on-end 't specializers))))
2012            (&optional (push-on-end arg optionals))
2013            (&rest (setq rest-var arg))
2014            (&key
2015             (push-on-end (get-keyword-from-arg arg) keys)
2016             (push-on-end arg key-args))
2017            (&aux (push-on-end arg auxs)))))
2018    (list  :required-names required-names
2019           :required-args required-args
2020           :specializers specializers
2021           :rest-var rest-var
2022           :keywords keys
2023           :key-args key-args
2024           :keysp keysp
2025           :auxiliary-args auxs
2026           :optional-args optionals
2027           :allow-other-keys allow-other-keys)))
2028
2029#+nil
2030(defun check-method-arg-info (gf arg-info method)
2031  (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
2032      (analyze-lambda-list (if (consp method)
2033                               (early-method-lambda-list method)
2034                               (method-lambda-list method)))
2035    (flet ((lose (string &rest args)
2036                 (error 'simple-program-error
2037                        :format-control "~@<attempt to add the method~2I~_~S~I~_~
2038                        to the generic function~2I~_~S;~I~_~
2039                        but ~?~:>"
2040                        :format-arguments (list method gf string args)))
2041           (comparison-description (x y)
2042                                   (if (> x y) "more" "fewer")))
2043      (let ((gf-nreq (arg-info-number-required arg-info))
2044            (gf-nopt (arg-info-number-optional arg-info))
2045            (gf-key/rest-p (arg-info-key/rest-p arg-info))
2046            (gf-keywords (arg-info-keys arg-info)))
2047        (unless (= nreq gf-nreq)
2048          (lose
2049           "the method has ~A required arguments than the generic function."
2050           (comparison-description nreq gf-nreq)))
2051        (unless (= nopt gf-nopt)
2052          (lose
2053           "the method has ~A optional arguments than the generic function."
2054           (comparison-description nopt gf-nopt)))
2055        (unless (eq (or keysp restp) gf-key/rest-p)
2056          (lose
2057           "the method and generic function differ in whether they accept~_~
2058            &REST or &KEY arguments."))
2059        (when (consp gf-keywords)
2060          (unless (or (and restp (not keysp))
2061                      allow-other-keys-p
2062                      (every (lambda (k) (memq k keywords)) gf-keywords))
2063            (lose "the method does not accept each of the &KEY arguments~2I~_~
2064            ~S."
2065                  gf-keywords)))))))
2066
2067(defun check-method-lambda-list (name method-lambda-list gf-lambda-list)
2068  (let* ((gf-restp (not (null (memq '&rest gf-lambda-list))))
2069         (gf-plist (analyze-lambda-list gf-lambda-list))
2070         (gf-keysp (getf gf-plist :keysp))
2071         (gf-keywords (getf gf-plist :keywords))
2072         (method-plist (analyze-lambda-list method-lambda-list))
2073         (method-restp (not (null (memq '&rest method-lambda-list))))
2074         (method-keysp (getf method-plist :keysp))
2075         (method-keywords (getf method-plist :keywords))
2076         (method-allow-other-keys-p (getf method-plist :allow-other-keys)))
2077    (unless (= (length (getf gf-plist :required-args))
2078               (length (getf method-plist :required-args)))
2079      (error "The method-lambda-list ~S ~
2080              has the wrong number of required arguments ~
2081              for the generic function ~S." method-lambda-list name))
2082    (unless (= (length (getf gf-plist :optional-args))
2083               (length (getf method-plist :optional-args)))
2084      (error "The method-lambda-list ~S ~
2085              has the wrong number of optional arguments ~
2086              for the generic function ~S." method-lambda-list name))
2087    (unless (eq (or gf-restp gf-keysp) (or method-restp method-keysp))
2088      (error "The method-lambda-list ~S ~
2089              and the generic function ~S ~
2090              differ in whether they accept &REST or &KEY arguments."
2091             method-lambda-list name))
2092    (when (consp gf-keywords)
2093      (unless (or (and method-restp (not method-keysp))
2094                  method-allow-other-keys-p
2095                  (every (lambda (k) (memq k method-keywords)) gf-keywords))
2096        (error "The method-lambda-list ~S does not accept ~
2097                all of the keyword arguments defined for the ~
2098                generic function." method-lambda-list name)))))
2099
2100(defun check-argument-precedence-order (lambda-list argument-precedence-order)
2101  (when argument-precedence-order
2102    (if lambda-list
2103        ;; raising the required program-errors is a side-effect of
2104        ;; calculating the given permutation of apo vs req
2105        (argument-precedence-order-indices
2106         argument-precedence-order
2107         (getf (analyze-lambda-list lambda-list) :required-args))
2108        ;; AMOP pg. 198
2109        (error 'program-error "argument precedence order specified without lambda list"))))
2110
2111(defvar *gf-initialize-instance* nil
2112  "Cached value of the INITIALIZE-INSTANCE generic function.
2113Initialized with the true value near the end of the file.")
2114(defvar *gf-allocate-instance* nil
2115  "Cached value of the ALLOCATE-INSTANCE generic function.
2116Initialized with the true value near the end of the file.")
2117(defvar *gf-shared-initialize* nil
2118  "Cached value of the SHARED-INITIALIZE generic function.
2119Initialized with the true value near the end of the file.")
2120(defvar *gf-reinitialize-instance* nil
2121  "Cached value of the REINITIALIZE-INSTANCE generic function.
2122Initialized with the true value near the end of the file.")
2123
2124(declaim (ftype (function * method) ensure-method))
2125(defun ensure-method (name &rest all-keys)
2126  (let ((method-lambda-list (getf all-keys :lambda-list))
2127        (gf (find-generic-function name nil)))
2128    (when (or (eq gf *gf-initialize-instance*)
2129              (eq gf *gf-allocate-instance*)
2130              (eq gf *gf-shared-initialize*)
2131              (eq gf *gf-reinitialize-instance*))
2132      ;; ### Clearly, this can be targeted much more exact
2133      ;; as we only need to remove the specializing class and all
2134      ;; its subclasses from the hash.
2135      (clrhash *make-instance-initargs-cache*)
2136      (clrhash *reinitialize-instance-initargs-cache*))
2137    (if gf
2138        (check-method-lambda-list name method-lambda-list
2139                                  (generic-function-lambda-list gf))
2140        (setf gf (ensure-generic-function name :lambda-list method-lambda-list)))
2141    (let ((method
2142           (if (eq (generic-function-method-class gf) +the-standard-method-class+)
2143               (apply #'make-instance-standard-method gf all-keys)
2144               (apply #'make-instance (generic-function-method-class gf) all-keys))))
2145      (if (and
2146           (eq (generic-function-method-class gf) +the-standard-method-class+)
2147           (eq (class-of gf) +the-standard-generic-function-class+))
2148          (progn
2149            (std-add-method gf method)
2150            (map-dependents gf
2151                            #'(lambda (dep)
2152                                (update-dependent gf dep 'add-method method))))
2153          (add-method gf method))
2154      method)))
2155
2156(defun make-instance-standard-method (gf
2157                                      &key
2158                                      lambda-list
2159                                      qualifiers
2160                                      specializers
2161                                      documentation
2162                                      function
2163                                      fast-function)
2164  (declare (ignore gf))
2165  (let ((method (std-allocate-instance +the-standard-method-class+))
2166        (analyzed-args (analyze-lambda-list lambda-list)))
2167    (setf (method-lambda-list method) lambda-list)
2168    (setf (method-qualifiers method) qualifiers)
2169    (setf (std-slot-value method 'sys::specializers)
2170          (canonicalize-specializers specializers))
2171    (setf (method-documentation method) documentation)
2172    (setf (std-slot-value method 'sys::%generic-function) nil) ; set by add-method
2173    (setf (std-slot-value method 'sys::%function) function)
2174    (setf (std-slot-value method 'sys::fast-function) fast-function)
2175    (setf (std-slot-value method 'sys::keywords) (getf analyzed-args :keywords))
2176    (setf (std-slot-value method 'sys::other-keywords-p)
2177          (getf analyzed-args :allow-other-keys))
2178    method))
2179
2180;;; To be redefined as generic functions later
2181(declaim (notinline add-direct-method))
2182(defun add-direct-method (specializer method)
2183  (if (typep specializer 'eql-specializer)
2184      (pushnew method (std-slot-value specializer 'direct-methods))
2185      (pushnew method (class-direct-methods specializer))))
2186
2187(declaim (notinline remove-direct-method))
2188(defun remove-direct-method (specializer method)
2189  (if (typep specializer 'eql-specializer)
2190      (setf (std-slot-value specializer 'direct-methods)
2191            (remove method (std-slot-value specializer 'direct-methods)))
2192      (setf (class-direct-methods specializer)
2193            (remove method (class-direct-methods specializer)))))
2194
2195(defun std-add-method (gf method)
2196  ;; calls sites need to make sure that method is either a method of the
2197  ;; given gf or does not have a gf.
2198  (let ((old-method (%find-method gf (std-method-qualifiers method)
2199                                 (method-specializers method) nil)))
2200    (when old-method
2201      (if (and (eq (class-of gf) +the-standard-generic-function-class+)
2202               (eq (class-of old-method) +the-standard-method-class+))
2203          (std-remove-method gf old-method)
2204          (remove-method gf old-method))))
2205  (setf (std-slot-value method 'sys::%generic-function) gf)
2206  (push method (std-slot-value gf 'sys::methods))
2207  (dolist (specializer (method-specializers method))
2208    (add-direct-method specializer method))
2209  (finalize-standard-generic-function gf)
2210  gf)
2211
2212(defun std-remove-method (gf method)
2213  (setf (std-slot-value gf 'sys::methods)
2214        (remove method (generic-function-methods gf)))
2215  (setf (std-slot-value method 'sys::%generic-function) nil)
2216  (dolist (specializer (method-specializers method))
2217    (remove-direct-method specializer method))
2218  (finalize-standard-generic-function gf)
2219  gf)
2220
2221(defun %find-method (gf qualifiers specializers &optional (errorp t))
2222  ;; "If the specializers argument does not correspond in length to the number
2223  ;; of required arguments of the generic-function, an an error of type ERROR
2224  ;; is signaled."
2225  (unless (= (length specializers) (length (generic-function-required-arguments gf)))
2226    (error "The specializers argument has length ~S, but ~S has ~S required parameters."
2227           (length specializers)
2228           gf
2229           (length (generic-function-required-arguments gf))))
2230  (let* ((canonical-specializers (canonicalize-specializers specializers))
2231         (method
2232          (find-if #'(lambda (method)
2233                      (and (equal qualifiers
2234                                  (method-qualifiers method))
2235                           (equal canonical-specializers
2236                                  (method-specializers method))))
2237                   (generic-function-methods gf))))
2238    (if (and (null method) errorp)
2239        (error "No such method for ~S." (generic-function-name gf))
2240        method)))
2241
2242(defun fast-callable-p (gf)
2243  (and (eq (method-combination-name (generic-function-method-combination gf))
2244           'standard)
2245       (null (intersection (generic-function-lambda-list gf)
2246                           '(&rest &optional &key &allow-other-keys &aux)))))
2247
2248(defun std-compute-discriminating-function (gf)
2249  ;; In this function, we know that gf is of class
2250  ;; standard-generic-function, so we can access the instance's slots
2251  ;; via std-slot-value.  This breaks circularities when redefining
2252  ;; generic function accessors.
2253  (let ((methods (std-slot-value gf 'sys::methods)))
2254    (cond
2255      ((and (= (length methods) 1)
2256            (eq (type-of (car methods)) 'standard-reader-method)
2257            (eq (type-of (car (std-method-specializers (car methods))))
2258                'standard-class))
2259       (let* ((method (first methods))
2260              (slot-definition (std-slot-value method 'sys::%slot-definition))
2261              (slot-name (std-slot-value slot-definition 'sys:name))
2262              (class (car (std-method-specializers method))))
2263         #'(lambda (instance)
2264             ;; TODO: elide this test for low values of SAFETY
2265             (unless (typep instance class)
2266               (no-applicable-method gf (list instance)))
2267             ;; hash table lookup for slot position in Layout object via
2268             ;; StandardObject.SLOT_VALUE, so should be reasonably fast
2269             (std-slot-value instance slot-name))))
2270      ((and (= (length methods) 1)
2271            (eq (type-of (car methods)) 'standard-writer-method)
2272            (eq (type-of (second (std-method-specializers (car methods))))
2273                'standard-class))
2274       (let* ((method (first methods))
2275              (slot-definition (std-slot-value method 'sys::%slot-definition))
2276              (slot-name (std-slot-value slot-definition 'sys:name))
2277              (class (car (std-method-specializers method))))
2278         #'(lambda (new-value instance)
2279             ;; TODO: elide this test for low values of SAFETY
2280             (unless (typep instance class)
2281               (no-applicable-method gf (list new-value instance)))
2282             ;; hash table lookup for slot position in Layout object via
2283             ;; StandardObject.SET_SLOT_VALUE, so should be reasonably fast
2284             (setf (std-slot-value instance slot-name) new-value))))
2285      (t
2286       (let* ((number-required (length (generic-function-required-arguments gf)))
2287              (lambda-list (generic-function-lambda-list gf))
2288              (exact (null (intersection lambda-list
2289                                         '(&rest &optional &key
2290                                           &allow-other-keys))))
2291              (no-aux (null (some 
2292                             (lambda (method) 
2293                               (find '&aux (std-slot-value method 'sys::lambda-list)))
2294                             methods))))
2295         (if (and exact
2296                  no-aux)
2297             (cond
2298               ((= number-required 1)
2299                (cond
2300                  ((and (eq (method-combination-name
2301                             (std-slot-value gf 'sys::%method-combination))
2302                            'standard)
2303                        (= (length methods) 1)
2304                        (std-method-fast-function (%car methods)))
2305                   (let* ((method (%car methods))
2306                          (specializer (car (std-method-specializers method)))
2307                          (function (std-method-fast-function method)))
2308                     (if (typep specializer 'eql-specializer)
2309                         (let ((specializer-object (eql-specializer-object specializer)))
2310                           #'(lambda (arg)
2311                               (declare (optimize speed))
2312                               (if (eql arg specializer-object)
2313                                   (funcall function arg)
2314                                   (no-applicable-method gf (list arg)))))
2315                         #'(lambda (arg)
2316                             (declare (optimize speed))
2317                             (unless (simple-typep arg specializer)
2318                               ;; FIXME no applicable method
2319                               (error 'simple-type-error
2320                                      :datum arg
2321                                      :expected-type specializer))
2322                             (funcall function arg)))))
2323                  (t
2324                   #'(lambda (arg)
2325                       (declare (optimize speed))
2326                       (let* ((args (list arg))
2327                              (emfun (get-cached-emf gf args)))
2328                         (if emfun
2329                             (funcall emfun args)
2330                             (slow-method-lookup gf args)))))))
2331               ((= number-required 2)
2332                #'(lambda (arg1 arg2)
2333                    (declare (optimize speed))
2334                    (let* ((args (list arg1 arg2))
2335                           (emfun (get-cached-emf gf args)))
2336                      (if emfun
2337                          (funcall emfun args)
2338                          (slow-method-lookup gf args)))))
2339               ((= number-required 3)
2340                #'(lambda (arg1 arg2 arg3)
2341                    (declare (optimize speed))
2342                    (let* ((args (list arg1 arg2 arg3))
2343                           (emfun (get-cached-emf gf args)))
2344                      (if emfun
2345                          (funcall emfun args)
2346                          (slow-method-lookup gf args)))))
2347               (t
2348                #'(lambda (&rest args)
2349                    (declare (optimize speed))
2350                    (let ((len (length args)))
2351                      (unless (= len number-required)
2352                        (error 'program-error
2353                               :format-control "Not enough arguments for generic function ~S."
2354                               :format-arguments (list (generic-function-name gf)))))
2355                    (let ((emfun (get-cached-emf gf args)))
2356                      (if emfun
2357                          (funcall emfun args)
2358                          (slow-method-lookup gf args))))))
2359             #'(lambda (&rest args)
2360                 (declare (optimize speed))
2361                 (let ((len (length args)))
2362                   (unless (>= len number-required)
2363                     (error 'program-error
2364                            :format-control "Not enough arguments for generic function ~S."
2365                            :format-arguments (list (generic-function-name gf)))))
2366                 (let ((emfun (get-cached-emf gf args)))
2367                   (if emfun
2368                       (funcall emfun args)
2369                       (slow-method-lookup gf args))))))))))
2370
2371(defun sort-methods (methods gf required-classes)
2372  (if (or (null methods) (null (%cdr methods)))
2373      methods
2374      (sort methods
2375            (if (eq (class-of gf) +the-standard-generic-function-class+)
2376                (let ((method-indices
2377                       (argument-precedence-order-indices
2378                        (generic-function-argument-precedence-order gf)
2379                        (getf (analyze-lambda-list (generic-function-lambda-list gf))
2380                              ':required-args))))
2381                  #'(lambda (m1 m2)
2382                      (std-method-more-specific-p
2383                       m1 m2 required-classes method-indices)))
2384                #'(lambda (m1 m2)
2385                    (method-more-specific-p gf m1 m2 required-classes))))))
2386
2387(defun method-applicable-p (method args)
2388  (do* ((specializers (method-specializers method) (cdr specializers))
2389        (args args (cdr args)))
2390       ((null specializers) t)
2391    (let ((specializer (car specializers)))
2392      (if (typep specializer 'eql-specializer)
2393          (unless (eql (car args) (eql-specializer-object specializer))
2394            (return nil))
2395          (unless (subclassp (class-of (car args)) specializer)
2396            (return nil))))))
2397
2398(defun std-compute-applicable-methods (gf args)
2399  (let ((required-classes (mapcar #'class-of (required-portion gf args)))
2400        (methods '()))
2401    (dolist (method (generic-function-methods gf))
2402      (when (method-applicable-p method args)
2403        (push method methods)))
2404    (sort-methods methods gf required-classes)))
2405
2406(declaim (notinline compute-applicable-methods))
2407(defun compute-applicable-methods (gf args)
2408  (std-compute-applicable-methods gf args))
2409
2410;;; METHOD-APPLICABLE-USING-CLASSES-P
2411;;;
2412;;; If the first return value is T, METHOD is definitely applicable to
2413;;; arguments that are instances of CLASSES.  If the first value is
2414;;; NIL and the second value is T, METHOD is definitely not applicable
2415;;; to arguments that are instances of CLASSES; if the second value is
2416;;; NIL the applicability of METHOD cannot be determined by inspecting
2417;;; the classes of its arguments only.
2418;;;
2419(defun method-applicable-using-classes-p (method classes)
2420  (do* ((specializers (method-specializers method) (cdr specializers))
2421        (classes classes (cdr classes))
2422        (knownp t))
2423       ((null specializers)
2424        (if knownp (values t t) (values nil nil)))
2425    (let ((specializer (car specializers)))
2426      (if (typep specializer 'eql-specializer)
2427          (if (eql (class-of (eql-specializer-object specializer)) 
2428                   (car classes))
2429              (setf knownp nil)
2430              (return (values nil t)))
2431          (unless (subclassp (car classes) specializer)
2432            (return (values nil t)))))))
2433
2434(defun check-applicable-method-keyword-args (gf args
2435                                             keyword-args
2436                                             applicable-keywords)
2437  (when (oddp (length keyword-args))
2438    (error 'program-error
2439           :format-control "Odd number of keyword arguments in call to ~S ~
2440with arguments list ~S"
2441           :format-arguments (list gf args)))
2442  (unless (getf keyword-args :allow-other-keys)
2443    (loop for key in keyword-args by #'cddr
2444       unless (or (member key applicable-keywords)
2445                  (eq key :allow-other-keys))
2446       do (error 'program-error
2447                 :format-control "Invalid keyword argument ~S in call ~
2448to ~S with argument list ~S."
2449                 :format-arguments (list key gf args)))))
2450
2451(defun compute-applicable-keywords (gf applicable-methods)
2452  (let ((applicable-keywords
2453         (getf (analyze-lambda-list (generic-function-lambda-list gf))
2454               :keywords)))
2455    (loop for method in applicable-methods
2456       do (multiple-value-bind
2457                (keywords allow-other-keys)
2458              (function-keywords method)
2459            (when allow-other-keys
2460              (setf applicable-keywords :any)
2461              (return))
2462            (setf applicable-keywords
2463                  (union applicable-keywords keywords))))
2464    applicable-keywords))
2465
2466(defun wrap-emfun-for-keyword-args-check (gf emfun non-keyword-args
2467                                          applicable-keywords)
2468  #'(lambda (args)
2469      (check-applicable-method-keyword-args
2470         gf args
2471         (nthcdr non-keyword-args args) applicable-keywords)
2472      (funcall emfun args)))
2473
2474(defun slow-method-lookup (gf args)
2475  (let ((applicable-methods
2476          (if (eq (class-of gf) +the-standard-generic-function-class+)
2477              (std-compute-applicable-methods gf args)
2478              (or (compute-applicable-methods-using-classes gf (mapcar #'class-of args))
2479                  (compute-applicable-methods gf args)))))
2480    (if applicable-methods
2481        (let* ((emfun (funcall (if (eq (class-of gf)
2482                                       +the-standard-generic-function-class+)
2483                                   #'std-compute-effective-method
2484                                   #'compute-effective-method)
2485                               gf (generic-function-method-combination gf)
2486                               applicable-methods))
2487               (non-keyword-args (+ (length (generic-function-required-arguments gf))
2488                                    (length (generic-function-optional-arguments gf))))
2489               (gf-lambda-list (generic-function-lambda-list gf))
2490               (checks-required (and (member '&key gf-lambda-list)
2491                                     (not (member '&allow-other-keys
2492                                                  gf-lambda-list))))
2493              (applicable-keywords
2494               (when checks-required
2495                 ;; Don't do applicable keyword checks when this is
2496                 ;; one of the 'exceptional four' or when the gf allows
2497                 ;; other keywords.
2498                 (compute-applicable-keywords gf applicable-methods))))
2499          (when (and checks-required
2500                     (not (eq applicable-keywords :any)))
2501            (setf emfun
2502                  (wrap-emfun-for-keyword-args-check gf emfun non-keyword-args
2503                                                     applicable-keywords)))
2504          (cache-emf gf args emfun)
2505          (funcall emfun args))
2506        (apply #'no-applicable-method gf args))))
2507
2508(defun sub-specializer-p (c1 c2 c-arg)
2509  (find c2 (cdr (memq c1 (%class-precedence-list c-arg)))))
2510
2511(defun std-method-more-specific-p (method1 method2 required-classes argument-precedence-order)
2512  (if argument-precedence-order
2513      (let ((specializers-1 (std-method-specializers method1))
2514            (specializers-2 (std-method-specializers method2)))
2515        (dolist (index argument-precedence-order)
2516          (let ((spec1 (nth index specializers-1))
2517                (spec2 (nth index specializers-2)))
2518            (unless (eq spec1 spec2)
2519              (cond ((typep spec1 'eql-specializer)
2520                     (return t))
2521                    ((typep spec2 'eql-specializer)
2522                     (return nil))
2523                    (t
2524                     (return (sub-specializer-p spec1 spec2
2525                                                (nth index required-classes)))))))))
2526      (do ((specializers-1 (std-method-specializers method1) (cdr specializers-1))
2527           (specializers-2 (std-method-specializers method2) (cdr specializers-2))
2528           (classes required-classes (cdr classes)))
2529          ((null specializers-1) nil)
2530        (let ((spec1 (car specializers-1))
2531              (spec2 (car specializers-2)))
2532          (unless (eq spec1 spec2)
2533            (cond ((typep spec1 'eql-specializer)
2534                   (return t))
2535                  ((typep spec2 'eql-specializer)
2536                   (return nil))
2537                  (t
2538                   (return (sub-specializer-p spec1 spec2 (car classes))))))))))
2539
2540(defun primary-method-p (method)
2541  (null (intersection '(:before :after :around) (method-qualifiers method))))
2542
2543(defun before-method-p (method)
2544  (equal '(:before) (method-qualifiers method)))
2545
2546(defun after-method-p (method)
2547  (equal '(:after) (method-qualifiers method)))
2548
2549(defun around-method-p (method)
2550  (equal '(:around) (method-qualifiers method)))
2551
2552(defun process-next-method-list (next-method-list)
2553  (mapcar #'(lambda (next-method-form)
2554              (cond
2555                ((listp next-method-form)
2556                 (assert (eq (first next-method-form) 'make-method))
2557                 (let* ((rest-sym (gensym)))
2558                   (make-instance-standard-method
2559                    nil ;; ignored
2560                    :lambda-list (list '&rest rest-sym)
2561                    :function (compute-method-function `(lambda (&rest ,rest-sym)
2562                                                          ,(second next-method-form))))))
2563                (t
2564                 (assert (typep next-method-form 'method))
2565                 next-method-form)))
2566          next-method-list))
2567
2568(defun std-compute-effective-method (gf method-combination methods)
2569  (assert (typep method-combination 'method-combination))
2570  (let* ((mc-name (method-combination-name method-combination))
2571         (options (slot-value method-combination 'options))
2572         (order (car options))
2573         (primaries '())
2574         (arounds '())
2575         around
2576         emf-form
2577         (long-method-combination-p
2578          (typep method-combination 'long-method-combination)))
2579    (unless long-method-combination-p
2580      (dolist (m methods)
2581        (let ((qualifiers (method-qualifiers m)))
2582          (cond ((null qualifiers)
2583                 (if (eq mc-name 'standard)
2584                     (push m primaries)
2585                     (error "Method combination type mismatch: missing qualifier for method combination ~S." method-combination)))
2586                ((cdr qualifiers)
2587                 (error "Invalid method qualifiers."))
2588                ((eq (car qualifiers) :around)
2589                 (push m arounds))
2590                ((eq (car qualifiers) mc-name)
2591                 (push m primaries))
2592                ((memq (car qualifiers) '(:before :after)))
2593                (t
2594                 (error "Invalid method qualifiers."))))))
2595    (unless (eq order :most-specific-last)
2596      (setf primaries (nreverse primaries)))
2597    (setf arounds (nreverse arounds))
2598    (setf around (car arounds))
2599    (when (and (null primaries) (not long-method-combination-p))
2600      (error "No primary methods for the generic function ~S." gf))
2601    (cond
2602      (around
2603       (let ((next-emfun
2604              (funcall
2605               (if (eq (class-of gf) +the-standard-generic-function-class+)
2606                   #'std-compute-effective-method
2607                   #'compute-effective-method)
2608               gf method-combination (remove around methods))))
2609         (setf emf-form
2610               (generate-emf-lambda (method-function around) next-emfun))))
2611      ((eq mc-name 'standard)
2612       (let* ((next-emfun (compute-primary-emfun (cdr primaries)))
2613              (befores (remove-if-not #'before-method-p methods))
2614              (reverse-afters
2615               (reverse (remove-if-not #'after-method-p methods))))
2616         (setf emf-form
2617               (cond
2618                 ((and (null befores) (null reverse-afters))
2619                  (let ((fast-function (std-method-fast-function (car primaries))))
2620                    (if fast-function
2621                        (ecase (length (generic-function-required-arguments gf))
2622                          (1
2623                           #'(lambda (args)
2624                               (declare (optimize speed))
2625                               (funcall fast-function (car args))))
2626                          (2
2627                           #'(lambda (args)
2628                               (declare (optimize speed))
2629                               (funcall fast-function (car args) (cadr args)))))
2630                        (generate-emf-lambda (std-method-function (car primaries))
2631                                             next-emfun))))
2632                 (t
2633                  (let ((method-function (method-function (car primaries))))
2634                    #'(lambda (args)
2635                        (declare (optimize speed))
2636                        (dolist (before befores)
2637                          (funcall (method-function before) args nil))
2638                        (multiple-value-prog1
2639                            (funcall method-function args next-emfun)
2640                          (dolist (after reverse-afters)
2641                            (funcall (method-function after) args nil))))))))))
2642      (long-method-combination-p
2643       (let ((function (long-method-combination-function method-combination))
2644             (arguments (slot-value method-combination 'options)))
2645         (assert function)
2646         (setf emf-form
2647               (if arguments
2648                   (apply function gf methods arguments)
2649                   (funcall function gf methods)))))
2650      (t
2651       (unless (typep method-combination 'short-method-combination)
2652         (error "Unsupported method combination type ~A." mc-name))
2653       (let ((operator (short-method-combination-operator method-combination))
2654             (ioa (short-method-combination-identity-with-one-argument method-combination)))
2655         (setf emf-form
2656               (if (and ioa (null (cdr primaries)))
2657                   (generate-emf-lambda (method-function (car primaries)) nil)
2658                   `(lambda (args)
2659                      (,operator ,@(mapcar
2660                                    (lambda (primary)
2661                                      `(funcall ,(method-function primary) args nil))
2662                                    primaries))))))))
2663    (assert (not (null emf-form)))
2664    (or #+nil (ignore-errors (autocompile emf-form))
2665        (coerce-to-function emf-form))))
2666
2667(defun generate-emf-lambda (method-function next-emfun)
2668  #'(lambda (args)
2669      (declare (optimize speed))
2670      (funcall method-function args next-emfun)))
2671
2672;;; compute an effective method function from a list of primary methods:
2673
2674(defun compute-primary-emfun (methods)
2675  (if (null methods)
2676      nil
2677      (let ((next-emfun (compute-primary-emfun (cdr methods))))
2678        #'(lambda (args)
2679           (funcall (std-method-function (car methods)) args next-emfun)))))
2680
2681(defvar *call-next-method-p*)
2682(defvar *next-method-p-p*)
2683
2684(defun walk-form (form)
2685  (cond ((atom form)
2686         (cond ((eq form 'call-next-method)
2687                (setf *call-next-method-p* t))
2688               ((eq form 'next-method-p)
2689                (setf *next-method-p-p* t))))
2690        (t
2691         (walk-form (%car form))
2692         (walk-form (%cdr form)))))
2693
2694(defun compute-method-function (lambda-expression)
2695  (let ((lambda-list (allow-other-keys (cadr lambda-expression)))
2696        (body (cddr lambda-expression))
2697        (*call-next-method-p* nil)
2698        (*next-method-p-p* nil))
2699    (multiple-value-bind (body declarations) (parse-body body)
2700      (let ((ignorable-vars '()))
2701        (dolist (var lambda-list)
2702          (if (memq var lambda-list-keywords)
2703              (return)
2704              (push var ignorable-vars)))
2705        (push `(declare (ignorable ,@ignorable-vars)) declarations))
2706      (walk-form body)
2707      (cond ((or *call-next-method-p* *next-method-p-p*)
2708             `(lambda (args next-emfun)
2709                (flet ((call-next-method (&rest cnm-args)
2710                         (if (null next-emfun)
2711                             (error "No next method for generic function.")
2712                             (funcall next-emfun (or cnm-args args))))
2713                       (next-method-p ()
2714                         (not (null next-emfun))))
2715                  (declare (ignorable (function call-next-method)
2716                                      (function next-method-p)))
2717                  (apply #'(lambda ,lambda-list ,@declarations ,@body) args))))
2718            ((null (intersection lambda-list '(&rest &optional &key &allow-other-keys &aux)))
2719             ;; Required parameters only.
2720             (case (length lambda-list)
2721               (1
2722                `(lambda (args next-emfun)
2723                   (declare (ignore next-emfun))
2724                   (let ((,(%car lambda-list) (%car args)))
2725                     (declare (ignorable ,(%car lambda-list)))
2726                     ,@declarations ,@body)))
2727               (2
2728                `(lambda (args next-emfun)
2729                   (declare (ignore next-emfun))
2730                   (let ((,(%car lambda-list) (%car args))
2731                         (,(%cadr lambda-list) (%cadr args)))
2732                     (declare (ignorable ,(%car lambda-list)
2733                                         ,(%cadr lambda-list)))
2734                     ,@declarations ,@body)))
2735               (3
2736                `(lambda (args next-emfun)
2737                   (declare (ignore next-emfun))
2738                   (let ((,(%car lambda-list) (%car args))
2739                         (,(%cadr lambda-list) (%cadr args))
2740                         (,(%caddr lambda-list) (%caddr args)))
2741                     (declare (ignorable ,(%car lambda-list)
2742                                         ,(%cadr lambda-list)
2743                                         ,(%caddr lambda-list)))
2744                     ,@declarations ,@body)))
2745               (t
2746                `(lambda (args next-emfun)
2747                   (declare (ignore next-emfun))
2748                   (apply #'(lambda ,lambda-list ,@declarations ,@body) args)))))
2749            (t
2750             `(lambda (args next-emfun)
2751                (declare (ignore next-emfun))
2752                (apply #'(lambda ,lambda-list ,@declarations ,@body) args)))))))
2753
2754(defun compute-method-fast-function (lambda-expression)
2755  (let ((lambda-list (allow-other-keys (cadr lambda-expression))))
2756    (when (intersection lambda-list '(&rest &optional &key &allow-other-keys &aux))
2757      (return-from compute-method-fast-function nil))
2758    ;; Only required args.
2759    (let ((body (cddr lambda-expression))
2760          (*call-next-method-p* nil)
2761          (*next-method-p-p* nil))
2762      (multiple-value-bind (body declarations) (parse-body body)
2763        (walk-form body)
2764        (when (or *call-next-method-p* *next-method-p-p*)
2765          (return-from compute-method-fast-function nil))
2766        (let ((decls `(declare (ignorable ,@lambda-list))))
2767          (setf lambda-expression
2768                (list* (car lambda-expression)
2769                       (cadr lambda-expression)
2770                       decls
2771                       (cddr lambda-expression))))
2772        (case (length lambda-list)
2773          (1
2774;;            `(lambda (args next-emfun)
2775;;               (let ((,(%car lambda-list) (%car args)))
2776;;                 (declare (ignorable ,(%car lambda-list)))
2777;;                 ,@declarations ,@body)))
2778           lambda-expression)
2779          (2
2780;;            `(lambda (args next-emfun)
2781;;               (let ((,(%car lambda-list) (%car args))
2782;;                     (,(%cadr lambda-list) (%cadr args)))
2783;;                 (declare (ignorable ,(%car lambda-list)
2784;;                                     ,(%cadr lambda-list)))
2785;;                 ,@declarations ,@body)))
2786           lambda-expression)
2787;;           (3
2788;;            `(lambda (args next-emfun)
2789;;               (let ((,(%car lambda-list) (%car args))
2790;;                     (,(%cadr lambda-list) (%cadr args))
2791;;                     (,(%caddr lambda-list) (%caddr args)))
2792;;                 (declare (ignorable ,(%car lambda-list)
2793;;                                     ,(%cadr lambda-list)
2794;;                                     ,(%caddr lambda-list)))
2795;;                 ,@declarations ,@body)))
2796          (t
2797           nil))))))
2798
2799(declaim (notinline make-method-lambda))
2800(defun make-method-lambda (generic-function method lambda-expression env)
2801  (declare (ignore generic-function method env))
2802  (values (compute-method-function lambda-expression) nil))
2803
2804
2805;; From CLHS section 7.6.5:
2806;; "When a generic function or any of its methods mentions &key in a lambda
2807;; list, the specific set of keyword arguments accepted by the generic function
2808;; varies according to the applicable methods. The set of keyword arguments
2809;; accepted by the generic function for a particular call is the union of the
2810;; keyword arguments accepted by all applicable methods and the keyword
2811;; arguments mentioned after &key in the generic function definition, if any."
2812;; Adapted from Sacla.
2813(defun allow-other-keys (lambda-list)
2814  (if (and (member '&key lambda-list)
2815           (not (member '&allow-other-keys lambda-list)))
2816      (let* ((key-end (or (position '&aux lambda-list) (length lambda-list)))
2817             (aux-part (subseq lambda-list key-end)))
2818        `(,@(subseq lambda-list 0 key-end) &allow-other-keys ,@aux-part))
2819      lambda-list))
2820
2821(defmacro defmethod (&rest args &environment env)
2822  (multiple-value-bind
2823      (function-name qualifiers lambda-list specializers documentation declarations body)
2824      (parse-defmethod args)
2825    (let* ((specializers-form '())
2826           (lambda-expression `(lambda ,lambda-list ,@declarations ,body))
2827           (gf (or (find-generic-function function-name nil)
2828                   (class-prototype (find-class 'standard-generic-function))))
2829           (method-function
2830             (make-method-lambda gf (class-prototype (generic-function-method-class gf))
2831                                 lambda-expression env))
2832           (fast-function (compute-method-fast-function lambda-expression))
2833           )
2834      (dolist (specializer specializers)
2835        (cond ((and (consp specializer) (eq (car specializer) 'eql))
2836               (push `(list 'eql ,(cadr specializer)) specializers-form))
2837              (t
2838               (push `',specializer specializers-form))))
2839      (setf specializers-form `(list ,@(nreverse specializers-form)))
2840      `(progn
2841         (ensure-method ',function-name
2842                        :lambda-list ',lambda-list
2843                        :qualifiers ',qualifiers
2844                        :specializers (canonicalize-specializers ,specializers-form)
2845                        ,@(if documentation `(:documentation ,documentation))
2846                        :function (function ,method-function)
2847                        ,@(if fast-function `(:fast-function (function ,fast-function)))
2848                        )))))
2849
2850;;; Reader and writer methods
2851
2852(defun make-instance-standard-accessor-method (method-class
2853                                               &key
2854                                               lambda-list
2855                                               qualifiers
2856                                               specializers
2857                                               documentation
2858                                               function
2859                                               fast-function
2860                                               slot-definition)
2861  (let ((method (std-allocate-instance method-class)))
2862    (setf (method-lambda-list method) lambda-list)
2863    (setf (method-qualifiers method) qualifiers)
2864    (setf (std-slot-value method 'sys::specializers)
2865          (canonicalize-specializers specializers))
2866    (setf (method-documentation method) documentation)
2867    (setf (std-slot-value method 'sys::%generic-function) nil)
2868    (setf (std-slot-value method 'sys::%function) function)
2869    (setf (std-slot-value method 'sys::fast-function) fast-function)
2870    (setf (std-slot-value method 'sys::%slot-definition) slot-definition)
2871    (setf (std-slot-value method 'sys::keywords) nil)
2872    (setf (std-slot-value method 'sys::other-keywords-p) nil)
2873    method))
2874
2875(defun add-reader-method (class function-name slot-definition)
2876  (let* ((slot-name (slot-definition-name slot-definition))
2877         (lambda-expression
2878          (if (eq (class-of class) +the-standard-class+)
2879              `(lambda (object) (std-slot-value object ',slot-name))
2880              `(lambda (object) (slot-value object ',slot-name))))
2881         (method-function (compute-method-function lambda-expression))
2882         (fast-function (compute-method-fast-function lambda-expression))
2883         (method-lambda-list '(object))
2884         (gf (find-generic-function function-name nil))
2885         (initargs `(:lambda-list ,method-lambda-list
2886                     :qualifiers ()
2887                     :specializers (,class)
2888                     :function ,(if (autoloadp 'compile)
2889                                    method-function
2890                                    (autocompile method-function))
2891                     :fast-function ,(if (autoloadp 'compile)
2892                                         fast-function
2893                                         (autocompile fast-function))
2894                     :slot-definition ,slot-definition))
2895         (method-class (if (eq class +the-standard-class+)
2896                           +the-standard-reader-method-class+
2897                           (apply #'reader-method-class class slot-definition
2898                                  initargs))))
2899    ;; required by AMOP pg. 225
2900    (assert (subtypep method-class +the-standard-reader-method-class+))
2901    (if gf
2902        (check-method-lambda-list function-name
2903                                  method-lambda-list
2904                                  (generic-function-lambda-list gf))
2905        (setf gf (ensure-generic-function function-name
2906                                          :lambda-list method-lambda-list)))
2907    (let ((method
2908           (if (eq method-class +the-standard-reader-method-class+)
2909               (apply #'make-instance-standard-accessor-method method-class
2910                      initargs)
2911               (apply #'make-instance method-class
2912                      :generic-function nil ; handled by add-method
2913                      initargs))))
2914      (if (eq (class-of gf) +the-standard-generic-function-class+)
2915          (progn
2916            (std-add-method gf method)
2917            (map-dependents gf
2918                            #'(lambda (dep)
2919                                (update-dependent gf dep 'add-method method))))
2920          (add-method gf method))
2921      method)))
2922
2923(defun add-writer-method (class function-name slot-definition)
2924  (let* ((slot-name (slot-definition-name slot-definition))
2925         (lambda-expression
2926          (if (eq (class-of class) +the-standard-class+)
2927              `(lambda (new-value object)
2928                 (setf (std-slot-value object ',slot-name) new-value))
2929              `(lambda (new-value object)
2930                 (setf (slot-value object ',slot-name) new-value))))
2931         (method-function (compute-method-function lambda-expression))
2932         (fast-function (compute-method-fast-function lambda-expression))
2933         (method-lambda-list '(new-value object))
2934         (gf (find-generic-function function-name nil))
2935         (initargs `(:lambda-list ,method-lambda-list
2936                     :qualifiers ()
2937                     :specializers (,+the-T-class+ ,class)
2938                     :function ,(if (autoloadp 'compile)
2939                                    method-function
2940                                    (autocompile method-function))
2941                     :fast-function ,(if (autoloadp 'compile)
2942                                         fast-function
2943                                         (autocompile fast-function))
2944                     :slot-definition ,slot-definition))
2945         (method-class (if (eq class +the-standard-class+)
2946                           +the-standard-writer-method-class+
2947                           (apply #'writer-method-class class slot-definition
2948                                  initargs))))
2949    ;; required by AMOP pg. 242
2950    (assert (subtypep method-class +the-standard-writer-method-class+))
2951    (if gf
2952        (check-method-lambda-list function-name
2953                                  method-lambda-list
2954                                  (generic-function-lambda-list gf))
2955        (setf gf (ensure-generic-function function-name
2956                                          :lambda-list method-lambda-list)))
2957    (let ((method
2958           (if (eq method-class +the-standard-writer-method-class+)
2959               (apply #'make-instance-standard-accessor-method method-class
2960                      initargs)
2961               (apply #'make-instance method-class
2962                      :generic-function nil ; handled by add-method
2963                      initargs))))
2964      (if (eq (class-of gf) +the-standard-generic-function-class+)
2965          (progn
2966            (std-add-method gf method)
2967            (map-dependents gf
2968                            #'(lambda (dep)
2969                                (update-dependent gf dep 'add-method method))))
2970          (add-method gf method))
2971      method)))
2972
2973(defmacro atomic-defgeneric (function-name &rest rest)
2974  "Macro to define a generic function and 'swap it into place' after
2975it's been fully defined with all its methods.
2976
2977Note: the user should really use the (:method ..) method description
2978way of defining methods; there's not much use in atomically defining
2979generic functions without providing sensible behaviour."
2980  (let ((temp-sym (gensym)))
2981    `(progn
2982       (defgeneric ,temp-sym ,@rest)
2983       (let ((gf (symbol-function ',temp-sym)))
2984         ;; FIXME (rudi 2012-07-08): fset gets the source location info
2985         ;; to charpos 23 always (but (setf fdefinition) leaves the
2986         ;; outdated source position in place, which is even worse).
2987         (fset ',function-name gf)
2988         (setf (std-slot-value gf 'sys::name) ',function-name)
2989         (fmakunbound ',temp-sym)
2990         gf))))
2991
2992(defmacro redefine-class-forwarder (name slot &optional body-alist)
2993  "Define a generic function on a temporary symbol as an accessor
2994for the slot `slot'. Then, when definition is complete (including
2995allocation of methods), swap the definition in place.
2996
2997`body-alist' can be used to override the default method bodies for given
2998metaclasses.  In substitute method bodies, `class' names the class
2999instance and, for setters, `new-value' the new value."
3000  (let* ((setterp (consp name))
3001         (%name
3002          (intern (concatenate 'string
3003                               "%"
3004                               (if setterp (symbol-name 'set-) "")
3005                               (symbol-name (if setterp (cadr name) name)))
3006                  (find-package "SYS")))
3007         (bodies
3008          (append body-alist
3009                  (if setterp
3010                      `((built-in-class . (,%name new-value class))
3011                        (forward-referenced-class . (,%name new-value class))
3012                        (structure-class . (,%name new-value class))
3013                        (standard-class . (setf (slot-value class ',slot)
3014                                                new-value))
3015                        (funcallable-standard-class . (setf (slot-value class ',slot)
3016                                                            new-value)))
3017                      `((built-in-class . (,%name class))
3018                        (forward-referenced-class . (,%name class))
3019                        (structure-class . (,%name class))
3020                        (standard-class . (slot-value class ',slot))
3021                        (funcallable-standard-class . (slot-value class ',slot)))))))
3022    `(atomic-defgeneric ,name (,@(when setterp (list 'new-value)) class)
3023        ,@(mapcar #'(lambda (class-name)
3024                      `(:method (,@(when setterp (list 'new-value))
3025                                 (class ,class-name))
3026                         ,(cdr (assoc class-name bodies))))
3027                  '(built-in-class forward-referenced-class structure-class
3028                    standard-class funcallable-standard-class)))))
3029
3030;;; The slot names here must agree with the ones defined in
3031;;; StandardClass.java:layoutStandardClass.
3032(redefine-class-forwarder class-name sys:name)
3033;;; AMOP pg. 230
3034(redefine-class-forwarder (setf class-name) sys:name
3035   ((standard-class . (progn (reinitialize-instance class :name new-value) new-value))
3036    (funcallable-standard-class . (progn (reinitialize-instance class :name new-value) new-value))))
3037(redefine-class-forwarder class-slots sys:slots)
3038(redefine-class-forwarder (setf class-slots) sys:slots)
3039(redefine-class-forwarder class-direct-slots sys:direct-slots)
3040(redefine-class-forwarder (setf class-direct-slots) sys:direct-slots)
3041(redefine-class-forwarder class-layout sys:layout)
3042(redefine-class-forwarder (setf class-layout) sys:layout)
3043(redefine-class-forwarder class-direct-superclasses sys:direct-superclasses)
3044(redefine-class-forwarder (setf class-direct-superclasses) sys:direct-superclasses)
3045(redefine-class-forwarder class-direct-subclasses sys:direct-subclasses)
3046(redefine-class-forwarder (setf class-direct-subclasses) sys:direct-subclasses)
3047(redefine-class-forwarder class-direct-methods sys:direct-methods)
3048(redefine-class-forwarder (setf class-direct-methods) sys:direct-methods)
3049(redefine-class-forwarder class-precedence-list sys:precedence-list)
3050(redefine-class-forwarder (setf class-precedence-list) sys:precedence-list)
3051(redefine-class-forwarder class-finalized-p sys:finalized-p)
3052(redefine-class-forwarder (setf class-finalized-p) sys:finalized-p)
3053(redefine-class-forwarder class-default-initargs sys:default-initargs)
3054(redefine-class-forwarder (setf class-default-initargs) sys:default-initargs)
3055(redefine-class-forwarder class-direct-default-initargs sys:direct-default-initargs)
3056(redefine-class-forwarder (setf class-direct-default-initargs) sys:direct-default-initargs)
3057
3058;;; Class definition
3059
3060(defun check-duplicate-slots (slots)
3061  (flet ((canonical-slot-name (canonical-slot)
3062           (getf canonical-slot :name)))
3063    (dolist (s1 slots)
3064      (let ((name1 (canonical-slot-name s1)))
3065        (dolist (s2 (cdr (memq s1 slots)))
3066          (when (eq name1 (canonical-slot-name s2))
3067            (error 'program-error "Duplicate slot ~S" name1)))))))
3068
3069(defun check-duplicate-default-initargs (initargs)
3070  (let ((names ()))
3071    (dolist (initarg initargs)
3072      (push (car initarg) names))
3073    (do* ((names names (cdr names))
3074          (name (car names) (car names)))
3075         ((null names))
3076      (when (memq name (cdr names))
3077        (error 'program-error
3078               :format-control "Duplicate initialization argument name ~S in :DEFAULT-INITARGS."
3079               :format-arguments (list name))))))
3080
3081(defun canonicalize-direct-superclasses (direct-superclasses)
3082  (let ((classes '()))
3083    (dolist (class-specifier direct-superclasses)
3084      (let ((class (if (classp class-specifier)
3085                       class-specifier
3086                       (find-class class-specifier nil))))
3087        (unless class
3088          (setf class (make-instance +the-forward-referenced-class+
3089                                     :name class-specifier))
3090          (setf (find-class class-specifier) class))
3091        (when (and (typep class 'built-in-class)
3092                   (not (member class *extensible-built-in-classes*)))
3093          (error "Attempt to define a subclass of built-in-class ~S."
3094                 class-specifier))
3095        (push class classes)))
3096    (nreverse classes)))
3097
3098(atomic-defgeneric add-direct-subclass (superclass subclass)
3099  (:method ((superclass class) (subclass class))
3100    (setf (class-direct-subclasses superclass)
3101          (adjoin subclass (class-direct-subclasses superclass)))))
3102
3103(atomic-defgeneric remove-direct-subclass (superclass subclass)
3104  (:method ((superclass class) (subclass class))
3105    (setf (class-direct-subclasses superclass)
3106          (remove subclass (class-direct-subclasses superclass)))))
3107
3108 ;;; AMOP pg. 182
3109(defun ensure-class (name &rest all-keys &key &allow-other-keys)
3110  (let ((class (find-class name nil)))
3111    ;; CLHS DEFCLASS: "If a class with the same proper name already
3112    ;; exists [...] the existing class is redefined."  Ansi-tests
3113    ;; CLASS-0309 and CLASS-0310.1 demand this behavior.
3114    (if (and class (eql (class-name class) name))
3115        (apply #'ensure-class-using-class class name all-keys)
3116        (apply #'ensure-class-using-class nil name all-keys))))
3117
3118;;; AMOP pg. 183ff.
3119(defgeneric ensure-class-using-class (class name &key direct-default-initargs
3120                                      direct-slots direct-superclasses
3121                                      metaclass &allow-other-keys))
3122
3123(defmethod ensure-class-using-class :before (class name  &key direct-slots
3124                                             direct-default-initargs 
3125                                             &allow-other-keys)
3126  (check-duplicate-slots direct-slots)
3127  (check-duplicate-default-initargs direct-default-initargs))
3128
3129(defmethod ensure-class-using-class ((class null) name &rest all-keys
3130                                     &key (metaclass +the-standard-class+)
3131                                     direct-superclasses
3132                                     &allow-other-keys)
3133  (setf all-keys (copy-list all-keys))  ; since we modify it
3134  (remf all-keys :metaclass)
3135  (unless (classp metaclass) (setf metaclass (find-class metaclass)))
3136  (let ((class (apply (if (eq metaclass +the-standard-class+)
3137                          #'make-instance-standard-class
3138                          #'make-instance)
3139                      metaclass :name name
3140                      :direct-superclasses (canonicalize-direct-superclasses
3141                                            direct-superclasses)
3142                      all-keys)))
3143    (%set-find-class name class)
3144    class))
3145
3146(defmethod ensure-class-using-class ((class built-in-class) name &rest all-keys
3147                                     &key &allow-other-keys)
3148  (declare (ignore all-keys))
3149  (error "The symbol ~S names a built-in class." name))
3150
3151(defmethod ensure-class-using-class ((class forward-referenced-class) name
3152                                     &rest all-keys
3153                                     &key (metaclass +the-standard-class+)
3154                                     direct-superclasses &allow-other-keys)
3155  (setf all-keys (copy-list all-keys))  ; since we modify it
3156  (remf all-keys :metaclass)
3157  (unless (classp metaclass) (setf metaclass (find-class metaclass)))
3158  (apply #'change-class class metaclass all-keys)
3159  (apply #'reinitialize-instance class
3160         :name name
3161         :direct-superclasses (canonicalize-direct-superclasses
3162                               direct-superclasses)
3163         all-keys)
3164  class)
3165
3166(defmethod ensure-class-using-class ((class class) name
3167                                     &rest all-keys
3168                                     &key (metaclass +the-standard-class+ metaclassp)
3169                                     direct-superclasses
3170                                     &allow-other-keys)
3171  (declare (ignore name))
3172  (setf all-keys (copy-list all-keys))  ; since we modify it
3173  (remf all-keys :metaclass)
3174  (unless (classp metaclass) (setf metaclass (find-class metaclass)))
3175  (when (and metaclassp (not (eq (class-of class) metaclass)))
3176    (error 'program-error
3177           "Trying to redefine class ~S with different metaclass."
3178           (class-name class)))
3179  (apply #'reinitialize-instance class
3180         :direct-superclasses (canonicalize-direct-superclasses direct-superclasses)
3181         all-keys)
3182  class)
3183
3184(defmacro defclass (&whole form name direct-superclasses direct-slots &rest options)
3185  (unless (>= (length form) 3)
3186    (error 'program-error "Wrong number of arguments for DEFCLASS."))
3187  (check-declaration-type name)
3188  `(ensure-class ',name
3189                 :direct-superclasses
3190                 (canonicalize-direct-superclasses ',direct-superclasses)
3191                 :direct-slots
3192                 ,(canonicalize-direct-slots direct-slots)
3193                 ,@(canonicalize-defclass-options options)))
3194
3195
3196;;; AMOP pg. 180
3197(defgeneric direct-slot-definition-class (class &rest initargs))
3198
3199(defmethod direct-slot-definition-class ((class class) &rest initargs)
3200  (declare (ignore initargs))
3201  +the-standard-direct-slot-definition-class+)
3202
3203;;; AMOP pg. 181
3204(defgeneric effective-slot-definition-class (class &rest initargs))
3205
3206(defmethod effective-slot-definition-class ((class class) &rest initargs)
3207  (declare (ignore initargs))
3208  +the-standard-effective-slot-definition-class+)
3209
3210;;; AMOP pg. 224
3211(defgeneric reader-method-class (class direct-slot &rest initargs))
3212
3213(defmethod reader-method-class ((class standard-class)
3214                                (direct-slot standard-direct-slot-definition)
3215                                &rest initargs)
3216  (declare (ignore initargs))
3217  +the-standard-reader-method-class+)
3218
3219(defmethod reader-method-class ((class funcallable-standard-class)
3220                                (direct-slot standard-direct-slot-definition)
3221                                &rest initargs)
3222  (declare (ignore initargs))
3223  +the-standard-reader-method-class+)
3224
3225;;; AMOP pg. 242
3226(defgeneric writer-method-class (class direct-slot &rest initargs))
3227
3228(defmethod writer-method-class ((class standard-class)
3229                                (direct-slot standard-direct-slot-definition)
3230                                &rest initargs)
3231  (declare (ignore initargs))
3232  +the-standard-writer-method-class+)
3233
3234(defmethod writer-method-class ((class funcallable-standard-class)
3235                                (direct-slot standard-direct-slot-definition)
3236                                &rest initargs)
3237  (declare (ignore initargs))
3238  +the-standard-writer-method-class+)
3239
3240;;; Applicable methods
3241
3242(atomic-defgeneric compute-applicable-methods (gf args)
3243  (:method ((gf standard-generic-function) args)
3244    (std-compute-applicable-methods gf args)))
3245
3246(defgeneric compute-applicable-methods-using-classes (gf classes)
3247  (:method ((gf standard-generic-function) classes)
3248    (let ((methods '()))
3249      (dolist (method (generic-function-methods gf))
3250  (multiple-value-bind (applicable knownp)
3251      (method-applicable-using-classes-p method classes)
3252    (cond (applicable
3253     (push method methods))
3254    ((not knownp)
3255     (return-from compute-applicable-methods-using-classes
3256       (values nil nil))))))
3257      (values (sort-methods methods gf classes)
3258        t))))
3259
3260
3261;;; Slot access
3262;;;
3263;;; See AMOP pg. 156ff. for an overview.
3264;;;
3265;;; AMOP specifies these generic functions to dispatch on slot objects
3266;;; (with the exception of slot-exists-p-using-class), although its
3267;;; sample implementation Closette dispatches on slot names.  We let
3268;;; slot-value and friends call their gf counterparts with the effective
3269;;; slot definition, but leave the definitions dispatching on slot name
3270;;; in place for user convenience.
3271
3272;;; AMOP pg. 235
3273(defgeneric slot-value-using-class (class instance slot))
3274
3275(defmethod slot-value-using-class ((class standard-class) instance (slot symbol))
3276  (std-slot-value instance slot))
3277(defmethod slot-value-using-class ((class standard-class) instance
3278                                   (slot standard-effective-slot-definition))
3279  (let* ((location (slot-definition-location slot))
3280         (value (if (consp location)
3281                    (cdr location)      ; :allocation :class
3282                    (standard-instance-access instance location))))
3283    (if (eq value +slot-unbound+)
3284        ;; fix SLOT-UNBOUND.5 from ansi test suite
3285        (nth-value 0 (slot-unbound class instance (slot-definition-name slot)))
3286        value)))
3287
3288(defmethod slot-value-using-class ((class funcallable-standard-class)
3289                                   instance (slot symbol))
3290  (std-slot-value instance slot))
3291(defmethod slot-value-using-class ((class funcallable-standard-class) instance
3292                                   (slot standard-effective-slot-definition))
3293  (let* ((location (slot-definition-location slot))
3294         (value (if (consp location)
3295                    (cdr location)      ; :allocation :class
3296                    (funcallable-standard-instance-access instance location))))
3297    (if (eq value +slot-unbound+)
3298        ;; fix SLOT-UNBOUND.5 from ansi test suite
3299        (nth-value 0 (slot-unbound class instance (slot-definition-name slot)))
3300        value)))
3301
3302(defmethod slot-value-using-class ((class structure-class) instance
3303                                   (slot symbol))
3304  (std-slot-value instance slot))
3305(defmethod slot-value-using-class ((class structure-class) instance
3306                                   (slot standard-effective-slot-definition))
3307  (std-slot-value instance (slot-definition-name slot)))
3308
3309;;; AMOP pg. 231
3310(defgeneric (setf slot-value-using-class) (new-value class instance slot))
3311
3312(defmethod (setf slot-value-using-class) (new-value
3313                                          (class standard-class)
3314                                          instance
3315                                          (slot symbol))
3316  (setf (std-slot-value instance slot) new-value))
3317(defmethod (setf slot-value-using-class) (new-value
3318                                          (class standard-class)
3319                                          instance
3320                                          (slot standard-effective-slot-definition))
3321  (let ((location (slot-definition-location slot)))
3322    (if (consp location)                ; :allocation :class
3323        (setf (cdr location) new-value)
3324        (setf (standard-instance-access instance location) new-value))))
3325
3326(defmethod (setf slot-value-using-class) (new-value
3327                                          (class funcallable-standard-class)
3328                                          instance
3329                                          (slot symbol))
3330  (setf (std-slot-value instance slot) new-value))
3331(defmethod (setf slot-value-using-class) (new-value
3332                                          (class funcallable-standard-class)
3333                                          instance
3334                                          (slot standard-effective-slot-definition))
3335  (let ((location (slot-definition-location slot)))
3336    (if (consp location)                ; :allocation :class
3337        (setf (cdr location) new-value)
3338        (setf (funcallable-standard-instance-access instance location)
3339              new-value))))
3340
3341(defmethod (setf slot-value-using-class) (new-value
3342                                          (class structure-class)
3343                                          instance
3344                                          (slot symbol))
3345  (setf (std-slot-value instance slot) new-value))
3346(defmethod (setf slot-value-using-class) (new-value
3347                                          (class structure-class)
3348                                          instance
3349                                          (slot standard-effective-slot-definition))
3350  (setf (std-slot-value instance (slot-definition-name slot)) new-value))
3351
3352;;; slot-exists-p-using-class is not specified by AMOP, and obviously
3353;;; cannot be specialized on the slot type.  Hence, its implementation
3354;;; differs from slot-(boundp|makunbound|value)-using-class
3355(defgeneric slot-exists-p-using-class (class instance slot-name))
3356
3357(defmethod slot-exists-p-using-class (class instance slot-name)
3358  nil)
3359
3360(defmethod slot-exists-p-using-class ((class standard-class) instance slot-name)
3361  (std-slot-exists-p instance slot-name))
3362(defmethod slot-exists-p-using-class ((class funcallable-standard-class) instance slot-name)
3363  (std-slot-exists-p instance slot-name))
3364
3365(defmethod slot-exists-p-using-class ((class structure-class) instance slot-name)
3366  (dolist (dsd (class-slots class))
3367    (when (eq (sys::dsd-name dsd) slot-name)
3368      (return-from slot-exists-p-using-class t)))
3369  nil)
3370
3371
3372(defgeneric slot-boundp-using-class (class instance slot))
3373(defmethod slot-boundp-using-class ((class standard-class) instance (slot symbol))
3374  (std-slot-boundp instance slot))
3375(defmethod slot-boundp-using-class ((class standard-class) instance
3376                                    (slot standard-effective-slot-definition))
3377  (let ((location (slot-definition-location slot)))
3378    (if (consp location)
3379        (not (eq (cdr location) +slot-unbound+)) ; :allocation :class
3380        (not (eq (standard-instance-access instance location) +slot-unbound+)))))
3381
3382(defmethod slot-boundp-using-class ((class funcallable-standard-class) instance
3383                                    (slot symbol))
3384  (std-slot-boundp instance slot))
3385(defmethod slot-boundp-using-class ((class funcallable-standard-class) instance
3386                                    (slot standard-effective-slot-definition))
3387  (let ((location (slot-definition-location slot)))
3388    (if (consp location)
3389        (not (eq (cdr location) +slot-unbound+)) ; :allocation :class
3390        (not (eq (funcallable-standard-instance-access instance location)
3391                 +slot-unbound+)))))
3392
3393(defmethod slot-boundp-using-class ((class structure-class) instance slot)
3394  "Structure slots can't be unbound, so this method always returns T."
3395  (declare (ignore class instance slot))
3396  t)
3397
3398(defgeneric slot-makunbound-using-class (class instance slot))
3399(defmethod slot-makunbound-using-class ((class standard-class)
3400                                        instance
3401                                        (slot symbol))
3402  (std-slot-makunbound instance slot))
3403(defmethod slot-makunbound-using-class ((class standard-class)
3404                                        instance
3405                                        (slot standard-effective-slot-definition))
3406  (let ((location (slot-definition-location slot)))
3407    (if (consp location)
3408        (setf (cdr location) +slot-unbound+)
3409        (setf (standard-instance-access instance location) +slot-unbound+))))
3410
3411(defmethod slot-makunbound-using-class ((class funcallable-standard-class)
3412                                        instance
3413                                        (slot symbol))
3414  (std-slot-makunbound instance slot))
3415(defmethod slot-makunbound-using-class ((class funcallable-standard-class)
3416                                        instance
3417                                        (slot symbol))
3418  (let ((location (slot-definition-location slot)))
3419    (if (consp location)
3420        (setf (cdr location) +slot-unbound+)
3421        (setf (funcallable-standard-instance-access instance location)
3422              +slot-unbound+))))
3423
3424(defmethod slot-makunbound-using-class ((class structure-class)
3425                                        instance
3426                                        slot)
3427  (declare (ignore class instance slot))
3428  (error "Structure slots can't be unbound"))
3429
3430(defgeneric slot-missing (class instance slot-name operation &optional new-value))
3431
3432(defmethod slot-missing ((class t) instance slot-name operation &optional new-value)
3433  (declare (ignore new-value))
3434  (error "The slot ~S is missing from the class ~S." slot-name class))
3435
3436(defgeneric slot-unbound (class instance slot-name))
3437
3438(defmethod slot-unbound ((class t) instance slot-name)
3439  (error 'unbound-slot :instance instance :name slot-name))
3440
3441;;; Instance creation and initialization
3442
3443;;; AMOP pg. 168ff.
3444(defgeneric allocate-instance (class &rest initargs &key &allow-other-keys))
3445
3446(defmethod allocate-instance ((class standard-class) &rest initargs)
3447  (declare (ignore initargs))
3448  (std-allocate-instance class))
3449
3450(defmethod allocate-instance ((class funcallable-standard-class) &rest initargs)
3451  (declare (ignore initargs))
3452  (allocate-funcallable-instance class))
3453
3454(defmethod allocate-instance ((class structure-class) &rest initargs)
3455  (declare (ignore initargs))
3456  (%make-structure (class-name class)
3457                   (make-list (length (class-slots class))
3458                              :initial-element +slot-unbound+)))
3459
3460(defmethod allocate-instance ((class built-in-class) &rest initargs)
3461  (declare (ignore initargs))
3462  (error "Cannot allocate instances of a built-in class: ~S" class))
3463
3464(defmethod allocate-instance :before ((class class) &rest initargs)
3465  (declare (ignore initargs))
3466  (unless (class-finalized-p class)
3467    (finalize-inheritance class)))
3468
3469;; "The set of valid initialization arguments for a class is the set of valid
3470;; initialization arguments that either fill slots or supply arguments to
3471;; methods, along with the predefined initialization argument :ALLOW-OTHER-KEYS."
3472;; 7.1.2
3473
3474(defun calculate-allowable-initargs (gf-list args instance
3475                                             shared-initialize-param
3476                                             initargs)
3477  (let* ((methods
3478          (nconc
3479             (std-compute-applicable-methods #'shared-initialize
3480                                             (list* instance
3481                                                    shared-initialize-param
3482                                                    initargs))
3483             (mapcan #'(lambda (gf)
3484                         (if (eq (class-of gf)
3485                                 +the-standard-generic-function-class+)
3486                             (std-compute-applicable-methods gf args)
3487                             (compute-applicable-methods gf args)))
3488                     gf-list)))
3489         (method-keyword-args
3490          (reduce #'merge-initargs-sets
3491                  (mapcar #'method-lambda-list methods)
3492                  :key #'extract-lambda-list-keywords
3493                  :initial-value nil))
3494         (slots-initargs
3495          (mapappend #'slot-definition-initargs
3496                     (class-slots (class-of instance)))))
3497    (merge-initargs-sets
3498     (merge-initargs-sets slots-initargs method-keyword-args)
3499     '(:allow-other-keys))))  ;; allow-other-keys is always allowed
3500
3501(defun check-initargs (gf-list args instance
3502                       shared-initialize-param initargs
3503                       cache call-site)
3504  "Checks the validity of `initargs' for the generic functions in `gf-list'
3505when called with `args' by calculating the applicable methods for each gf.
3506The applicable methods for SHARED-INITIALIZE based on `instance',
3507`shared-initialize-param' and `initargs' are added to the list of
3508applicable methods."
3509  (when (oddp (length initargs))
3510    (error 'program-error
3511           :format-control "Odd number of keyword arguments."))
3512  (unless (getf initargs :allow-other-keys)
3513    (multiple-value-bind (allowable-initargs present-p)
3514                         (when cache
3515                           (gethash (class-of instance) cache))
3516       (unless present-p
3517         (setf allowable-initargs
3518               (calculate-allowable-initargs gf-list args instance
3519                                             shared-initialize-param initargs))
3520         (when cache
3521           (setf (gethash (class-of instance) cache)
3522                 allowable-initargs)))
3523       (unless (eq t allowable-initargs)
3524         (do* ((tail initargs (cddr tail))
3525               (initarg (car tail) (car tail)))
3526              ((null tail))
3527              (unless (memq initarg allowable-initargs)
3528                (error 'program-error
3529                       :format-control "Invalid initarg ~S in call to ~S with arglist ~S."
3530                       :format-arguments (list initarg call-site args))))))))
3531
3532(defun merge-initargs-sets (list1 list2)
3533  (cond
3534   ((eq list1 t)  t)
3535   ((eq list2 t)  t)
3536   (t             (union list1 list2))))
3537
3538(defun extract-lambda-list-keywords (lambda-list)
3539  "Returns a list of keywords acceptable as keyword arguments,
3540or T when any keyword is acceptable due to presence of
3541&allow-other-keys."
3542  (when (member '&allow-other-keys lambda-list)
3543    (return-from extract-lambda-list-keywords t))
3544  (loop with keyword-args = (cdr (memq '&key lambda-list))
3545        for key in keyword-args
3546        when (eq key '&aux) do (loop-finish)
3547        when (eq key '&allow-other-keys) do (return t)
3548        when (listp key) do (setq key (car key))
3549        collect (if (symbolp key)
3550                    (make-keyword key)
3551                  (car key))))
3552
3553
3554(defgeneric make-instance (class &rest initargs &key &allow-other-keys))
3555
3556(defmethod make-instance :before ((class class) &rest initargs)
3557  (when (oddp (length initargs))
3558    (error 'program-error :format-control "Odd number of keyword arguments."))
3559  (unless (class-finalized-p class)
3560    (finalize-inheritance class)))
3561
3562(defun augment-initargs-with-defaults (class initargs)
3563  (let ((default-initargs '()))
3564    (dolist (initarg (class-default-initargs class))
3565      (let ((key (first initarg))
3566            (fn (third initarg)))
3567        (when (eq (getf initargs key +slot-unbound+) +slot-unbound+)
3568          (push key default-initargs)
3569          (push (funcall fn) default-initargs))))
3570    (append initargs (nreverse default-initargs))))
3571
3572(defmethod make-instance ((class standard-class) &rest initargs)
3573  (setf initargs (augment-initargs-with-defaults class initargs))
3574  (let ((instance (std-allocate-instance class)))
3575    (check-initargs (list #'allocate-instance #'initialize-instance)
3576                    (list* instance initargs)
3577                    instance t initargs
3578                    *make-instance-initargs-cache* 'make-instance)
3579    (apply #'initialize-instance instance initargs)
3580    instance))
3581
3582(defmethod make-instance ((class funcallable-standard-class) &rest initargs)
3583  (setf initargs (augment-initargs-with-defaults class initargs))
3584  (let ((instance (allocate-funcallable-instance class)))
3585    (check-initargs (list #'allocate-instance #'initialize-instance)
3586                    (list* instance initargs)
3587                    instance t initargs
3588                    *make-instance-initargs-cache* 'make-instance)
3589    (apply #'initialize-instance instance initargs)
3590    instance))
3591
3592(defmethod make-instance ((class symbol) &rest initargs)
3593  (apply #'make-instance (find-class class) initargs))
3594
3595(defgeneric initialize-instance (instance &rest initargs
3596                                          &key &allow-other-keys))
3597
3598(defmethod initialize-instance ((instance standard-object) &rest initargs)
3599  (apply #'shared-initialize instance t initargs))
3600
3601(defgeneric reinitialize-instance (instance &rest initargs
3602                                            &key &allow-other-keys))
3603
3604;; "The system-supplied primary method for REINITIALIZE-INSTANCE checks the
3605;; validity of initargs and signals an error if an initarg is supplied that is
3606;; not declared as valid. The method then calls the generic function SHARED-
3607;; INITIALIZE with the following arguments: the instance, nil (which means no
3608;; slots should be initialized according to their initforms), and the initargs
3609;; it received."
3610(defmethod reinitialize-instance ((instance standard-object) &rest initargs)
3611  (check-initargs (list #'reinitialize-instance) (list* instance initargs)
3612                  instance () initargs
3613                  *reinitialize-instance-initargs-cache* 'reinitialize-instance)
3614  (apply #'shared-initialize instance () initargs))
3615
3616(defun std-shared-initialize (instance slot-names all-keys)
3617  (when (oddp (length all-keys))
3618    (error 'program-error :format-control "Odd number of keyword arguments."))
3619  ;; do a quick scan of the arguments list to see if it's a real
3620  ;; 'initialization argument list' (which is not the same as
3621  ;; checking initarg validity
3622  (do* ((tail all-keys (cddr tail))
3623        (initarg (car tail) (car tail)))
3624      ((null tail))
3625    (unless (symbolp initarg)
3626      (error 'program-error
3627             :format-control "Initarg ~S not a symbol."
3628             :format-arguments (list initarg))))
3629  (dolist (slot (class-slots (class-of instance)))
3630    (let ((slot-name (slot-definition-name slot)))
3631      (multiple-value-bind (init-key init-value foundp)
3632          (get-properties all-keys (slot-definition-initargs slot))
3633        (if foundp
3634            (setf (std-slot-value instance slot-name) init-value)
3635            (unless (std-slot-boundp instance slot-name)
3636              (let ((initfunction (slot-definition-initfunction slot)))
3637                (when (and initfunction (or (eq slot-names t)
3638                                            (memq slot-name slot-names)))
3639                  (setf (std-slot-value instance slot-name)
3640                        (funcall initfunction)))))))))
3641  instance)
3642
3643(defgeneric shared-initialize (instance slot-names
3644                                        &rest initargs
3645                                        &key &allow-other-keys))
3646
3647(defmethod shared-initialize ((instance standard-object) slot-names
3648                              &rest initargs)
3649  (std-shared-initialize instance slot-names initargs))
3650
3651(defmethod shared-initialize ((slot slot-definition) slot-names
3652                              &rest args
3653                              &key name initargs initform initfunction
3654                              readers writers allocation
3655                              &allow-other-keys)
3656  ;;Keyword args are duplicated from init-slot-definition only to have
3657  ;;them checked.
3658  (declare (ignore slot-names)) ;;TODO?
3659  (declare (ignore name initargs initform initfunction readers writers allocation))
3660  ;;For built-in slots
3661  (apply #'init-slot-definition slot :allow-other-keys t args)
3662  ;;For user-defined slots
3663  (call-next-method))
3664
3665;;; change-class
3666
3667(defgeneric change-class (instance new-class &key &allow-other-keys))
3668
3669(defmethod change-class ((old-instance standard-object) (new-class standard-class)
3670                         &rest initargs)
3671  (let ((old-slots (class-slots (class-of old-instance)))
3672        (new-slots (class-slots new-class))
3673        (new-instance (allocate-instance new-class)))
3674    ;; "The values of local slots specified by both the class CTO and the class
3675    ;; CFROM are retained. If such a local slot was unbound, it remains
3676    ;; unbound."
3677    (dolist (new-slot new-slots)
3678      (when (instance-slot-p new-slot)
3679        (let* ((slot-name (slot-definition-name new-slot))
3680               (old-slot (find slot-name old-slots :key 'slot-definition-name)))
3681          ;; "The values of slots specified as shared in the class CFROM and as
3682          ;; local in the class CTO are retained."
3683          (when (and old-slot (slot-boundp old-instance slot-name))
3684            (setf (slot-value new-instance slot-name)
3685                  (slot-value old-instance slot-name))))))
3686    (swap-slots old-instance new-instance)
3687    (rotatef (std-instance-layout new-instance)
3688             (std-instance-layout old-instance))
3689    (apply #'update-instance-for-different-class
3690           new-instance old-instance initargs)
3691    old-instance))
3692
3693(defmethod change-class ((instance standard-object) (new-class symbol) &rest initargs)
3694  (apply #'change-class instance (find-class new-class) initargs))
3695
3696(defgeneric update-instance-for-different-class (old new
3697                                                     &rest initargs
3698                                                     &key &allow-other-keys))
3699
3700(defmethod update-instance-for-different-class
3701  ((old standard-object) (new standard-object) &rest initargs)
3702  (let ((added-slots
3703         (remove-if #'(lambda (slot-name)
3704                       (slot-exists-p old slot-name))
3705                    (mapcar 'slot-definition-name
3706                            (class-slots (class-of new))))))
3707    (check-initargs (list #'update-instance-for-different-class)
3708                    (list old new initargs)
3709                    new added-slots initargs
3710                    nil 'update-instance-for-different-class)
3711    (apply #'shared-initialize new added-slots initargs)))
3712
3713;;; make-instances-obsolete
3714
3715(defgeneric make-instances-obsolete (class))
3716
3717(defmethod make-instances-obsolete ((class standard-class))
3718  (%make-instances-obsolete class))
3719(defmethod make-instances-obsolete ((class funcallable-standard-class))
3720  (%make-instances-obsolete class))
3721(defmethod make-instances-obsolete ((class symbol))
3722  (make-instances-obsolete (find-class class))
3723  class)
3724
3725;;; update-instance-for-redefined-class
3726
3727(defgeneric update-instance-for-redefined-class (instance
3728                                                 added-slots
3729                                                 discarded-slots
3730                                                 property-list
3731                                                 &rest initargs
3732                                                 &key
3733                                                 &allow-other-keys))
3734
3735(defmethod update-instance-for-redefined-class ((instance standard-object)
3736            added-slots
3737            discarded-slots
3738            property-list
3739            &rest initargs)
3740  (check-initargs (list #'update-instance-for-redefined-class)
3741                  (list* instance added-slots discarded-slots
3742                         property-list initargs)
3743                  instance added-slots initargs
3744                  nil 'update-instance-for-redefined-class)
3745  (apply #'shared-initialize instance added-slots initargs))
3746
3747;;;  Methods having to do with class metaobjects.
3748
3749(defmethod initialize-instance :after ((class standard-class) &rest args)
3750  (apply #'std-after-initialization-for-classes class args))
3751
3752(defmethod initialize-instance :after ((class funcallable-standard-class)
3753                                       &rest args)
3754  (apply #'std-after-initialization-for-classes class args))
3755
3756(defmethod reinitialize-instance :before ((class standard-class)
3757                                          &rest all-keys
3758                                          &key direct-superclasses)
3759  (check-initargs (list #'allocate-instance
3760                        #'initialize-instance)
3761                  (list* class all-keys)
3762                  class t all-keys
3763                  nil 'reinitialize-instance)
3764  (dolist (superclass (set-difference (class-direct-superclasses class)
3765                                      direct-superclasses))
3766    (remove-direct-subclass superclass class))
3767  (dolist (superclass (set-difference direct-superclasses
3768                                      (class-direct-superclasses class)))
3769    (add-direct-subclass superclass class)))
3770
3771(defmethod reinitialize-instance :before ((class funcallable-standard-class)
3772                                          &rest all-keys
3773                                          &key direct-superclasses)
3774  (check-initargs (list #'allocate-instance
3775                        #'initialize-instance)
3776                  (list* class all-keys)
3777                  class t all-keys
3778                  nil 'reinitialize-instance)
3779  (dolist (superclass (set-difference (class-direct-superclasses class)
3780                                      direct-superclasses))
3781    (remove-direct-subclass superclass class))
3782  (dolist (superclass (set-difference direct-superclasses
3783                                      (class-direct-superclasses class)))
3784    (add-direct-subclass superclass class)))
3785
3786(defun std-after-reinitialization-for-classes (class
3787                                               &rest all-keys
3788                                               &key (direct-superclasses nil direct-superclasses-p)
3789                                               (direct-slots nil direct-slots-p)
3790                                               (direct-default-initargs nil direct-default-initargs-p)
3791                                               &allow-other-keys)
3792  (remhash class *make-instance-initargs-cache*)
3793  (remhash class *reinitialize-instance-initargs-cache*)
3794  (%make-instances-obsolete class)
3795  (setf (class-finalized-p class) nil)
3796  (when direct-superclasses-p
3797    (let* ((old-supers (class-direct-superclasses class))
3798           (new-supers (canonicalize-direct-superclass-list
3799                        class direct-superclasses)))
3800      (setf (class-direct-superclasses class) new-supers)
3801      (dolist (old-superclass (set-difference old-supers new-supers))
3802        (remove-direct-subclass old-superclass class))
3803      (dolist (new-superclass (set-difference new-supers old-supers))
3804        (add-direct-subclass new-superclass class))))
3805  (when direct-slots-p
3806    ;; FIXME: maybe remove old reader and writer methods?
3807    (let ((slots (mapcar #'(lambda (slot-properties)
3808                             (apply #'make-direct-slot-definition class slot-properties))
3809                         direct-slots)))
3810      (setf (class-direct-slots class) slots)
3811      (dolist (direct-slot slots)
3812        (dolist (reader (slot-definition-readers direct-slot))
3813          (add-reader-method class reader direct-slot))
3814        (dolist (writer (slot-definition-writers direct-slot))
3815          (add-writer-method class writer direct-slot)))))
3816  (when direct-default-initargs-p
3817    (setf (class-direct-default-initargs class) direct-default-initargs))
3818  (maybe-finalize-class-subtree class)
3819  (map-dependents class #'(lambda (dep) (update-dependent class dep all-keys))))
3820
3821(defmethod reinitialize-instance :after ((class standard-class)
3822                                         &rest all-keys)
3823  (apply #'std-after-reinitialization-for-classes class all-keys))
3824
3825(defmethod reinitialize-instance :after ((class funcallable-standard-class)
3826                                         &rest all-keys)
3827  (apply #'std-after-reinitialization-for-classes class all-keys))
3828
3829(defmethod reinitialize-instance :before ((gf standard-generic-function)
3830                                          &key
3831                                            (lambda-list nil lambda-list-supplied-p)
3832                                          &allow-other-keys)
3833  (when lambda-list-supplied-p
3834    (unless (or (null (generic-function-methods gf))
3835                (lambda-lists-congruent-p lambda-list
3836                                          (generic-function-lambda-list gf)))
3837      (error "The lambda list ~S is incompatible with the existing methods of ~S."
3838             lambda-list gf))))
3839
3840(defmethod reinitialize-instance :after ((gf standard-generic-function)
3841                                         &rest all-keys)
3842  (map-dependents gf #'(lambda (dep) (update-dependent gf dep all-keys))))
3843
3844;;; Finalize inheritance
3845
3846(atomic-defgeneric finalize-inheritance (class)
3847    (:method ((class standard-class))
3848       (std-finalize-inheritance class))
3849    (:method ((class funcallable-standard-class))
3850       (std-finalize-inheritance class)))
3851
3852;;; Default initargs
3853
3854;;; AMOP pg. 174
3855(atomic-defgeneric compute-default-initargs (class)
3856  (:method ((class standard-class))
3857    (std-compute-default-initargs class))
3858  (:method ((class funcallable-standard-class))
3859    (std-compute-default-initargs class)))
3860
3861;;; Class precedence lists
3862
3863(defgeneric compute-class-precedence-list (class))
3864(defmethod compute-class-precedence-list ((class standard-class))
3865  (std-compute-class-precedence-list class))
3866(defmethod compute-class-precedence-list ((class funcallable-standard-class))
3867  (std-compute-class-precedence-list class))
3868
3869;;; Slot inheritance
3870
3871(defgeneric compute-slots (class))
3872(defmethod compute-slots ((class standard-class))
3873  (std-compute-slots class))
3874(defmethod compute-slots ((class funcallable-standard-class))
3875  (std-compute-slots class))
3876
3877(defgeneric compute-effective-slot-definition (class name direct-slots))
3878(defmethod compute-effective-slot-definition
3879  ((class standard-class) name direct-slots)
3880  (std-compute-effective-slot-definition class name direct-slots))
3881(defmethod compute-effective-slot-definition
3882  ((class funcallable-standard-class) name direct-slots)
3883  (std-compute-effective-slot-definition class name direct-slots))
3884
3885;;; Methods having to do with generic function invocation.
3886
3887(defgeneric compute-discriminating-function (gf))
3888(defmethod compute-discriminating-function ((gf standard-generic-function))
3889  (std-compute-discriminating-function gf))
3890
3891(defgeneric method-more-specific-p (gf method1 method2 required-classes))
3892
3893(defmethod method-more-specific-p ((gf standard-generic-function)
3894                                   method1 method2 required-classes)
3895  (let ((method-indices
3896         (argument-precedence-order-indices
3897          (generic-function-argument-precedence-order gf)
3898          (getf (analyze-lambda-list (generic-function-lambda-list gf))
3899                ':required-args))))
3900    (std-method-more-specific-p method1 method2 required-classes method-indices)))
3901
3902;;; AMOP pg. 176
3903(defgeneric compute-effective-method (gf method-combination methods))
3904(defmethod compute-effective-method ((gf standard-generic-function) method-combination methods)
3905  (std-compute-effective-method gf method-combination methods))
3906
3907(defgeneric compute-applicable-methods (gf args))
3908(defmethod compute-applicable-methods ((gf standard-generic-function) args)
3909  (std-compute-applicable-methods gf args))
3910
3911;;; AMOP pg. 207
3912(atomic-defgeneric make-method-lambda (generic-function method lambda-expression environment)
3913  (:method ((generic-function standard-generic-function)
3914            (method standard-method)
3915            lambda-expression environment)
3916    (declare (ignore environment))
3917    (values (compute-method-function lambda-expression) nil)))
3918
3919
3920;;; Slot definition accessors
3921
3922(defmacro slot-definition-dispatch (slot-definition std-form generic-form)
3923  `(let (($cl (class-of ,slot-definition)))
3924     (case $cl
3925       ((+the-standard-slot-definition-class+
3926         +the-standard-direct-slot-definition-class+
3927         +the-standard-effective-slot-definition-class+)
3928        ,std-form)
3929       (t ,generic-form))))
3930
3931(atomic-defgeneric slot-definition-allocation (slot-definition)
3932  (:method ((slot-definition slot-definition))
3933    (slot-definition-dispatch slot-definition
3934      (std-slot-value slot-definition 'sys::allocation)
3935      (slot-value slot-definition 'sys::allocation))))
3936
3937(atomic-defgeneric (setf slot-definition-allocation) (value slot-definition)
3938  (:method (value (slot-definition slot-definition))
3939    (slot-definition-dispatch slot-definition
3940      (setf (std-slot-value slot-definition 'sys::allocation) value)
3941      (setf (slot-value slot-definition 'sys::allocation) value))))
3942
3943(atomic-defgeneric slot-definition-initargs (slot-definition)
3944  (:method ((slot-definition slot-definition))
3945    (slot-definition-dispatch slot-definition
3946      (std-slot-value slot-definition 'sys::initargs)
3947      (slot-value slot-definition 'sys::initargs))))
3948
3949(atomic-defgeneric (setf slot-definition-initargs) (value slot-definition)
3950  (:method (value (slot-definition slot-definition))
3951    (slot-definition-dispatch slot-definition
3952      (setf (std-slot-value slot-definition 'sys::initargs) value)
3953      (setf (slot-value slot-definition 'sys::initargs) value))))
3954
3955(atomic-defgeneric slot-definition-initform (slot-definition)
3956  (:method ((slot-definition slot-definition))
3957    (slot-definition-dispatch slot-definition
3958      (std-slot-value slot-definition 'sys::initform)
3959      (slot-value slot-definition 'sys::initform))))
3960
3961(atomic-defgeneric (setf slot-definition-initform) (value slot-definition)
3962  (:method (value (slot-definition slot-definition))
3963    (slot-definition-dispatch slot-definition
3964      (setf (std-slot-value slot-definition 'sys::initform) value)
3965      (setf (slot-value slot-definition 'sys::initform) value))))
3966
3967(atomic-defgeneric slot-definition-initfunction (slot-definition)
3968  (:method ((slot-definition slot-definition))
3969    (slot-definition-dispatch slot-definition
3970      (std-slot-value slot-definition 'sys::initfunction)
3971      (slot-value slot-definition 'sys::initfunction))))
3972
3973(atomic-defgeneric (setf slot-definition-initfunction) (value slot-definition)
3974  (:method (value (slot-definition slot-definition))
3975    (slot-definition-dispatch slot-definition
3976      (setf (std-slot-value slot-definition 'sys::initfunction) value)
3977      (setf (slot-value slot-definition 'sys::initfunction) value))))
3978
3979(atomic-defgeneric slot-definition-name (slot-definition)
3980  (:method ((slot-definition slot-definition))
3981    (slot-definition-dispatch slot-definition
3982      (std-slot-value slot-definition 'sys:name)
3983      (slot-value slot-definition 'sys:name))))
3984
3985(atomic-defgeneric (setf slot-definition-name) (value slot-definition)
3986  (:method (value (slot-definition slot-definition))
3987    (slot-definition-dispatch slot-definition
3988      (setf (std-slot-value slot-definition 'sys:name) value)
3989      (setf (slot-value slot-definition 'sys:name) value))))
3990
3991(atomic-defgeneric slot-definition-readers (slot-definition)
3992  (:method ((slot-definition slot-definition))
3993    (slot-definition-dispatch slot-definition
3994      (std-slot-value slot-definition 'sys::readers)
3995      (slot-value slot-definition 'sys::readers))))
3996
3997(atomic-defgeneric (setf slot-definition-readers) (value slot-definition)
3998  (:method (value (slot-definition slot-definition))
3999    (slot-definition-dispatch slot-definition
4000      (setf (std-slot-value slot-definition 'sys::readers) value)
4001      (setf (slot-value slot-definition 'sys::readers) value))))
4002
4003(atomic-defgeneric slot-definition-writers (slot-definition)
4004  (:method ((slot-definition slot-definition))
4005    (slot-definition-dispatch slot-definition
4006      (std-slot-value slot-definition 'sys::writers)
4007      (slot-value slot-definition 'sys::writers))))
4008
4009(atomic-defgeneric (setf slot-definition-writers) (value slot-definition)
4010  (:method (value (slot-definition slot-definition))
4011    (slot-definition-dispatch slot-definition
4012      (setf (std-slot-value slot-definition 'sys::writers) value)
4013      (setf (slot-value slot-definition 'sys::writers) value))))
4014
4015(atomic-defgeneric slot-definition-allocation-class (slot-definition)
4016  (:method ((slot-definition slot-definition))
4017    (slot-definition-dispatch slot-definition
4018      (std-slot-value slot-definition 'sys::allocation-class)
4019      (slot-value slot-definition 'sys::allocation-class))))
4020
4021(atomic-defgeneric (setf slot-definition-allocation-class)
4022                       (value slot-definition)
4023  (:method (value (slot-definition slot-definition))
4024    (slot-definition-dispatch slot-definition
4025      (setf (std-slot-value slot-definition 'sys::allocation-class) value)
4026      (setf (slot-value slot-definition 'sys::allocation-class) value))))
4027
4028(atomic-defgeneric slot-definition-location (slot-definition)
4029  (:method ((slot-definition slot-definition))
4030    (slot-definition-dispatch slot-definition
4031      (std-slot-value slot-definition 'sys::location)
4032      (slot-value slot-definition 'sys::location))))
4033
4034(atomic-defgeneric (setf slot-definition-location) (value slot-definition)
4035  (:method (value (slot-definition slot-definition))
4036    (slot-definition-dispatch slot-definition
4037      (setf (std-slot-value slot-definition 'sys::location) value)
4038      (setf (slot-value slot-definition 'sys::location) value))))
4039
4040(atomic-defgeneric slot-definition-type (slot-definition)
4041  (:method ((slot-definition slot-definition))
4042    (slot-definition-dispatch slot-definition
4043      (std-slot-value slot-definition 'sys::%type)
4044      (slot-value slot-definition 'sys::%type))))
4045
4046(atomic-defgeneric (setf slot-definition-type) (value slot-definition)
4047  (:method (value (slot-definition slot-definition))
4048    (slot-definition-dispatch slot-definition
4049      (setf (std-slot-value slot-definition 'sys::%type) value)
4050      (setf (slot-value slot-definition 'sys::%type) value))))
4051
4052(atomic-defgeneric slot-definition-documentation (slot-definition)
4053  (:method ((slot-definition slot-definition))
4054    (slot-definition-dispatch slot-definition
4055      (std-slot-value slot-definition 'sys:%documentation)
4056      (slot-value slot-definition 'sys:%documentation))))
4057
4058(atomic-defgeneric (setf slot-definition-documentation) (value slot-definition)
4059  (:method (value (slot-definition slot-definition))
4060    (slot-definition-dispatch slot-definition
4061      (setf (std-slot-value slot-definition 'sys:%documentation) value)
4062      (setf (slot-value slot-definition 'sys:%documentation) value))))
4063
4064
4065;;; Conditions.
4066
4067(defmacro define-condition (name (&rest parent-types) (&rest slot-specs) &body options)
4068  (let ((parent-types (or parent-types '(condition)))
4069        (report nil))
4070    (dolist (option options)
4071      (when (eq (car option) :report)
4072        (setf report (cadr option))
4073  (setf options (delete option options :test #'equal))
4074        (return)))
4075    (typecase report
4076      (null
4077       `(progn
4078          (defclass ,name ,parent-types ,slot-specs ,@options)
4079          ',name))
4080      (string
4081       `(progn
4082          (defclass ,name ,parent-types ,slot-specs ,@options)
4083          (defmethod print-object ((condition ,name) stream)
4084            (if *print-escape*
4085                (call-next-method)
4086                (progn (write-string ,report stream) condition)))
4087          ',name))
4088      (t
4089       `(progn
4090          (defclass ,name ,parent-types ,slot-specs ,@options)
4091          (defmethod print-object ((condition ,name) stream)
4092            (if *print-escape*
4093                (call-next-method)
4094                (funcall #',report condition stream)))
4095          ',name)))))
4096
4097(defun make-condition (type &rest initargs)
4098  (or (%make-condition type initargs)
4099      (let ((class (if (symbolp type) (find-class type) type)))
4100        (apply #'make-instance class initargs))))
4101
4102;; Adapted from SBCL.
4103;; Originally defined in signal.lisp. Redefined here now that we have MAKE-CONDITION.
4104(defun coerce-to-condition (datum arguments default-type fun-name)
4105  (cond ((typep datum 'condition)
4106         (when arguments
4107           (error 'simple-type-error
4108                  :datum arguments
4109                  :expected-type 'null
4110                  :format-control "You may not supply additional arguments when giving ~S to ~S."
4111                  :format-arguments (list datum fun-name)))
4112         datum)
4113        ((symbolp datum)
4114         (apply #'make-condition datum arguments))
4115        ((or (stringp datum) (functionp datum))
4116         (make-condition default-type
4117                         :format-control datum
4118                         :format-arguments arguments))
4119        (t
4120         (error 'simple-type-error
4121                :datum datum
4122                :expected-type '(or symbol string)
4123                :format-control "Bad argument to ~S: ~S."
4124                :format-arguments (list fun-name datum)))))
4125
4126(defgeneric make-load-form (object &optional environment))
4127
4128(defmethod make-load-form ((object t) &optional environment)
4129  (declare (ignore environment))
4130  (apply #'no-applicable-method #'make-load-form (list object)))
4131
4132(defmethod make-load-form ((class class) &optional environment)
4133  (declare (ignore environment))
4134  (let ((name (class-name class)))
4135    (unless (and name (eq (find-class name nil) class))
4136      (error 'simple-type-error
4137             :format-control "Can't use anonymous or undefined class as a constant: ~S."
4138             :format-arguments (list class)))
4139    `(find-class ',name)))
4140
4141(defun invalid-method-error (method format-control &rest args)
4142  (let ((message (apply #'format nil format-control args)))
4143    (error "Invalid method error for ~S:~%    ~A" method message)))
4144
4145(defun method-combination-error (format-control &rest args)
4146  (let ((message (apply #'format nil format-control args)))
4147    (error "Method combination error in CLOS dispatch:~%    ~A" message)))
4148
4149
4150(atomic-defgeneric no-applicable-method (generic-function &rest args)
4151  (:method (generic-function &rest args)
4152      (error "There is no applicable method for the generic function ~S ~
4153              when called with arguments ~S."
4154             generic-function
4155             args)))
4156
4157
4158;;; FIXME (rudi 2012-01-28): this can be a function, it only needs to
4159;;; use standard accessor functions
4160(defgeneric find-method (generic-function
4161                         qualifiers
4162                         specializers
4163                         &optional errorp))
4164
4165(defmethod find-method ((generic-function standard-generic-function)
4166                        qualifiers specializers &optional (errorp t))
4167  (%find-method generic-function qualifiers specializers errorp))
4168
4169(defgeneric find-method ((generic-function symbol)
4170                         qualifiers specializers &optional (errorp t))
4171  (find-method (find-generic-function generic-function errorp)
4172               qualifiers specializers errorp))
4173
4174;;; AMOP pg. 167
4175(defgeneric add-method (generic-function method))
4176
4177(defmethod add-method :before ((generic-function generic-function)
4178                               (method method))
4179  (when (and (method-generic-function method)
4180             (not (eql generic-function (method-generic-function method))))
4181    (error 'simple-error
4182           :format-control "~S is already a method of ~S, cannot add to ~S."
4183           :format-arguments (list method (method-generic-function method)
4184                                   generic-function)))
4185  (check-method-lambda-list (generic-function-name generic-function)
4186                            (method-lambda-list method)
4187                            (generic-function-lambda-list generic-function)))
4188
4189(defmethod add-method ((generic-function standard-generic-function)
4190                       (method standard-method))
4191  (std-add-method generic-function method))
4192
4193(defmethod add-method :after ((generic-function generic-function)
4194                              (method method))
4195  (map-dependents generic-function
4196                  #'(lambda (dep) (update-dependent generic-function dep
4197                                                    'add-method method))))
4198
4199(defgeneric remove-method (generic-function method))
4200
4201(defmethod remove-method ((generic-function standard-generic-function)
4202                          (method standard-method))
4203  (std-remove-method generic-function method))
4204
4205(defmethod remove-method :after ((generic-function generic-function)
4206                                 (method method))
4207  (map-dependents generic-function
4208                  #'(lambda (dep) (update-dependent generic-function dep
4209                                                    'remove-method method))))
4210
4211;; See describe.lisp.
4212(defgeneric describe-object (object stream))
4213
4214;; FIXME
4215(defgeneric no-next-method (generic-function method &rest args))
4216
4217(atomic-defgeneric function-keywords (method)
4218  (:method ((method standard-method))
4219    (std-function-keywords method)))
4220
4221(setf *gf-initialize-instance* (symbol-function 'initialize-instance))
4222(setf *gf-allocate-instance* (symbol-function 'allocate-instance))
4223(setf *gf-shared-initialize* (symbol-function 'shared-initialize))
4224(setf *gf-reinitialize-instance* (symbol-function 'reinitialize-instance))
4225(setf *clos-booting* nil)
4226
4227(atomic-defgeneric class-prototype (class)
4228  (:method ((class standard-class))
4229    (allocate-instance class))
4230  (:method ((class funcallable-standard-class))
4231    (allocate-instance class))
4232  (:method ((class structure-class))
4233    (allocate-instance class))
4234  (:method :before (class)
4235    (unless (class-finalized-p class)
4236      (error "~@<~S is not finalized.~:@>" class))))
4237
4238
4239
4240
4241
4242(defmethod shared-initialize :before ((instance generic-function)
4243                                      slot-names
4244                                      &key lambda-list argument-precedence-order
4245                                      &allow-other-keys)
4246  (check-argument-precedence-order lambda-list argument-precedence-order))
4247
4248(defmethod shared-initialize :after ((instance standard-generic-function)
4249                                     slot-names
4250                                     &key lambda-list argument-precedence-order
4251                                       (method-combination '(standard))
4252                                     &allow-other-keys)
4253  (let* ((plist (analyze-lambda-list lambda-list))
4254         (required-args (getf plist ':required-args)))
4255    (setf (std-slot-value instance 'sys::required-args) required-args)
4256    (setf (std-slot-value instance 'sys::optional-args)
4257          (getf plist :optional-args)) 
4258    (setf (std-slot-value instance 'sys::argument-precedence-order)
4259          (or argument-precedence-order required-args)))
4260  (unless (typep (generic-function-method-combination instance)
4261                 'method-combination)
4262    ;; this fixes (make-instance 'standard-generic-function) -- the
4263    ;; constructor of StandardGenericFunction sets this slot to '(standard)
4264    (setf (std-slot-value instance 'sys::%method-combination)
4265          (find-method-combination
4266           instance (car method-combination) (cdr method-combination))))
4267  (finalize-standard-generic-function instance))
4268
4269;;; Readers for generic function metaobjects
4270;;; AMOP pg. 216ff.
4271(atomic-defgeneric generic-function-argument-precedence-order (generic-function)
4272  (:method ((generic-function standard-generic-function))
4273    (std-slot-value generic-function 'sys::argument-precedence-order)))
4274
4275(atomic-defgeneric generic-function-declarations (generic-function)
4276  (:method ((generic-function standard-generic-function))
4277    (std-slot-value generic-function 'sys::declarations)))
4278
4279(atomic-defgeneric generic-function-lambda-list (generic-function)
4280  (:method ((generic-function standard-generic-function))
4281    (std-slot-value generic-function 'sys::lambda-list)))
4282
4283(atomic-defgeneric generic-function-method-class (generic-function)
4284  (:method ((generic-function standard-generic-function))
4285    (std-slot-value generic-function 'sys::method-class)))
4286
4287(atomic-defgeneric generic-function-method-combination (generic-function)
4288  (:method ((generic-function standard-generic-function))
4289    (std-slot-value generic-function 'sys::%method-combination)))
4290
4291(atomic-defgeneric generic-function-methods (generic-function)
4292  (:method ((generic-function standard-generic-function))
4293    (std-slot-value generic-function 'sys::methods)))
4294
4295(atomic-defgeneric generic-function-name (generic-function)
4296  (:method ((generic-function standard-generic-function))
4297    (slot-value generic-function 'sys::name)))
4298
4299(atomic-defgeneric generic-function-required-arguments (generic-function)
4300  (:method ((generic-function standard-generic-function))
4301    (std-slot-value generic-function 'sys::required-args)))
4302
4303(atomic-defgeneric generic-function-optional-arguments (generic-function)
4304  (:method ((generic-function standard-generic-function))
4305    (std-slot-value generic-function 'sys::optional-args)))
4306
4307;;; AMOP pg. 231
4308(defgeneric (setf generic-function-name) (new-value gf)
4309  (:method (new-value (gf generic-function))
4310    (reinitialize-instance gf :name new-value)))
4311
4312;;; Readers for Method Metaobjects
4313;;; AMOP pg. 218ff.
4314
4315(atomic-defgeneric method-function (method)
4316  (:method ((method standard-method))
4317    (std-method-function method)))
4318
4319(atomic-defgeneric method-generic-function (method)
4320  (:method ((method standard-method))
4321    (std-method-generic-function method)))
4322
4323(atomic-defgeneric method-lambda-list (method)
4324  (:method ((method standard-method))
4325    (std-slot-value method 'sys::lambda-list)))
4326
4327(atomic-defgeneric method-specializers (method)
4328  (:method ((method standard-method))
4329    (std-method-specializers method)))
4330
4331(atomic-defgeneric method-qualifiers (method)
4332  (:method ((method standard-method))
4333    (std-method-qualifiers method)))
4334
4335(atomic-defgeneric accessor-method-slot-definition (method)
4336  (:method ((method standard-accessor-method))
4337    (std-accessor-method-slot-definition method)))
4338
4339
4340;;; find-method-combination
4341
4342;;; AMOP pg. 191
4343(atomic-defgeneric find-method-combination (gf name options)
4344  (:method (gf (name symbol) options)
4345    (std-find-method-combination gf name options)))
4346
4347;;; specializer-direct-method and friends.
4348
4349;;; AMOP pg. 237
4350(defgeneric specializer-direct-generic-functions (specializer))
4351
4352(defmethod specializer-direct-generic-functions ((specializer class))
4353  (delete-duplicates (mapcar #'method-generic-function
4354                             (class-direct-methods specializer))))
4355
4356(defmethod specializer-direct-generic-functions ((specializer eql-specializer))
4357  (delete-duplicates (mapcar #'method-generic-function
4358                             (slot-value specializer 'direct-methods))))
4359
4360;;; AMOP pg. 238
4361(defgeneric specializer-direct-methods (specializer))
4362
4363(defmethod specializer-direct-methods ((specializer class))
4364  (class-direct-methods specializer))
4365
4366(defmethod specializer-direct-methods ((specializer eql-specializer))
4367  (slot-value specializer 'direct-methods))
4368
4369;;; AMOP pg. 165
4370(atomic-defgeneric add-direct-method (specializer method)
4371  (:method ((specializer class) (method method))
4372    (pushnew method (class-direct-methods specializer)))
4373  (:method ((specializer eql-specializer) (method method))
4374    (pushnew method (slot-value specializer 'direct-methods))))
4375
4376
4377;;; AMOP pg. 227
4378(atomic-defgeneric remove-direct-method (specializer method)
4379  (:method ((specializer class) (method method))
4380    (setf (class-direct-methods specializer)
4381          (remove method (class-direct-methods specializer))))
4382  (:method ((specializer eql-specializer) (method method))
4383    (setf (slot-value specializer 'direct-methods)
4384          (remove method (slot-value specializer 'direct-methods)))))
4385
4386;;; The Dependent Maintenance Protocol (AMOP pg. 160ff.)
4387
4388(defvar *dependents* (make-hash-table :test 'eq :weakness :key))
4389
4390;;; AMOP pg. 164
4391(defgeneric add-dependent (metaobject dependent))
4392(defmethod add-dependent ((metaobject standard-class) dependent)
4393  (pushnew dependent (gethash metaobject *dependents* nil)))
4394(defmethod add-dependent ((metaobject funcallable-standard-class) dependent)
4395  (pushnew dependent (gethash metaobject *dependents* nil)))
4396(defmethod add-dependent ((metaobject standard-generic-function) dependent)
4397  (pushnew dependent (gethash metaobject *dependents* nil)))
4398
4399;;; AMOP pg. 225
4400(defgeneric remove-dependent (metaobject dependent))
4401(defmethod remove-dependent ((metaobject standard-class) dependent)
4402  (setf (gethash metaobject *dependents*)
4403        (delete dependent (gethash metaobject *dependents* nil) :test #'eq)))
4404(defmethod remove-dependent ((metaobject funcallable-standard-class) dependent)
4405  (setf (gethash metaobject *dependents*)
4406        (delete dependent (gethash metaobject *dependents* nil) :test #'eq)))
4407(defmethod remove-dependent ((metaobject standard-generic-function) dependent)
4408  (setf (gethash metaobject *dependents*)
4409        (delete dependent (gethash metaobject *dependents* nil) :test #'eq)))
4410
4411;;; AMOP pg. 210
4412(atomic-defgeneric map-dependents (metaobject function)
4413  (:method ((metaobject standard-class) function)
4414    (dolist (dependent (gethash metaobject *dependents* nil))
4415      (funcall function dependent)))
4416  (:method ((metaobject funcallable-standard-class) function)
4417    (dolist (dependent (gethash metaobject *dependents* nil))
4418      (funcall function dependent)))
4419  (:method ((metaobject standard-generic-function) function)
4420    (dolist (dependent (gethash metaobject *dependents* nil))
4421      (funcall function dependent))))
4422
4423;;; AMOP pg. 239
4424(defgeneric update-dependent (metaobject dependent &rest initargs))
4425
4426
4427;;; ensure-generic-function(-using-class), AMOP pg. 185ff.
4428(defgeneric ensure-generic-function-using-class (generic-function function-name
4429                                                 &key
4430                                                   argument-precedence-order
4431                                                   declarations documentation
4432                                                   generic-function-class
4433                                                   lambda-list method-class
4434                                                   method-combination
4435                                                   name
4436                                                 &allow-other-keys))
4437
4438(defmethod ensure-generic-function-using-class
4439    ((generic-function generic-function)
4440     function-name
4441     &rest all-keys
4442     &key (generic-function-class (class-of generic-function))
4443     (method-class (generic-function-method-class generic-function))
4444     (method-combination (generic-function-method-combination generic-function))
4445     &allow-other-keys)
4446  (setf all-keys (copy-list all-keys))  ; since we modify it
4447  (remf all-keys :generic-function-class)
4448  (unless (classp generic-function-class)
4449    (setf generic-function-class (find-class generic-function-class)))
4450  (unless (classp method-class) (setf method-class (find-class method-class)))
4451  (unless (eq generic-function-class (class-of generic-function))
4452    (error "The class ~S is incompatible with the existing class (~S) of ~S."
4453           generic-function-class (class-of generic-function) generic-function))
4454  ;; We used to check for changes in method class here, but CLHS says:
4455  ;; "If function-name specifies a generic function that has a different
4456  ;; value for the :method-class argument, the value is changed, but any
4457  ;; existing methods are not changed."
4458  (unless (typep method-combination 'method-combination)
4459    (setf method-combination
4460          (find-method-combination generic-function
4461                                   (car method-combination)
4462                                   (cdr method-combination))))
4463  (apply #'reinitialize-instance generic-function
4464         :method-combination method-combination
4465         :method-class method-class
4466         all-keys)
4467  generic-function)
4468
4469(defmethod ensure-generic-function-using-class ((generic-function null)
4470                                                function-name
4471                                                &rest all-keys
4472                                                &key (generic-function-class +the-standard-generic-function-class+)
4473                                                &allow-other-keys)
4474  (setf all-keys (copy-list all-keys))  ; since we modify it
4475  (remf all-keys :generic-function-class)
4476  (unless (classp generic-function-class)
4477    (setf generic-function-class (find-class generic-function-class)))
4478  (when (and (null *clos-booting*) (fboundp function-name))
4479    (if (or (autoloadp function-name)
4480            (and (consp function-name)
4481                 (eq 'setf (first function-name))
4482                 (autoload-ref-p (second function-name))))
4483        (fmakunbound function-name)
4484        (error 'program-error
4485               :format-control "~A already names an ordinary function, macro, or special operator."
4486               :format-arguments (list function-name))))
4487  (apply (if (eq generic-function-class +the-standard-generic-function-class+)
4488             #'make-instance-standard-generic-function
4489             #'make-instance)
4490         generic-function-class :name function-name all-keys))
4491
4492(defun ensure-generic-function (function-name &rest all-keys
4493                                &key
4494                                  lambda-list generic-function-class
4495                                  method-class
4496                                  method-combination
4497                                  argument-precedence-order
4498                                  declarations
4499                                  documentation
4500                                &allow-other-keys)
4501  (declare (ignore lambda-list generic-function-class method-class
4502                   method-combination argument-precedence-order declarations
4503                   documentation))
4504  (apply #'ensure-generic-function-using-class
4505         (find-generic-function function-name nil)
4506         function-name all-keys))
4507
4508;;; SLIME compatibility functions.
4509
4510(defun %method-generic-function (method)
4511  (method-generic-function method))
4512
4513(defun %method-function (method)
4514  (method-function method))
4515
4516(eval-when (:compile-toplevel :load-toplevel :execute)
4517  (require "MOP"))
4518
4519(provide "CLOS")
4520
Note: See TracBrowser for help on using the repository browser.