source: branches/1.1.x/src/org/armedbear/lisp/clos.lisp

Last change on this file was 14378, checked in by Mark Evenson, 11 years ago

Backport r14369 | mevenson | 2013-02-13 20:01:20 +0100 (Wed, 13 Feb 2013) | 7 lines

Implementation of autoloader for SETF generalized references.

Fixes #296. Fixes #266. Fixes #228.

For forms which set the symbol properties of SETF-EXPANDER or
SETF-FUNCTION to function definitions, places stub of type
AutoloadGeneralizedReference? to be resolved when first invoked.

Does NOT include changes to asdf.

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