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

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

Robustify funcallable-instances with respect to unspecified behavior.

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