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

Last change on this file since 13781 was 13781, checked in by ehuelsmann, 11 years ago

Support for the FUNCTION-KEYWORDS protocol, required to implement
keyword argument verification for effective methods.

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