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

Last change on this file since 13778 was 13778, checked in by rschlatte, 11 years ago

Define make-instance for standard-class and funcallable-standard-class

... Don't define a method for class (which would cover built-in-class

etc. as well)

... refactor out some common parts

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