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

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

Initialize the OPTIONAL-ARGUMENTS slot in one more place.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 147.2 KB
Line 
1;;; clos.lisp
2;;;
3;;; Copyright (C) 2003-2007 Peter Graves
4;;; Copyright (C) 2010 Mark Evenson
5;;; $Id: clos.lisp 13786 2012-01-17 19:38:01Z ehuelsmann $
6;;;
7;;; This program is free software; you can redistribute it and/or
8;;; modify it under the terms of the GNU General Public License
9;;; as published by the Free Software Foundation; either version 2
10;;; of the License, or (at your option) any later version.
11;;;
12;;; This program is distributed in the hope that it will be useful,
13;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15;;; GNU General Public License for more details.
16;;;
17;;; You should have received a copy of the GNU General Public License
18;;; along with this program; if not, write to the Free Software
19;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20;;;
21;;; As a special exception, the copyright holders of this library give you
22;;; permission to link this library with independent modules to produce an
23;;; executable, regardless of the license terms of these independent
24;;; modules, and to copy and distribute the resulting executable under
25;;; terms of your choice, provided that you also meet, for each linked
26;;; independent module, the terms and conditions of the license of that
27;;; module.  An independent module is a module which is not derived from
28;;; or based on this library.  If you modify this library, you may extend
29;;; this exception to your version of the library, but you are not
30;;; obligated to do so.  If you do not wish to do so, delete this
31;;; exception statement from your version.
32
33;;; Originally based on Closette.
34
35;;; Closette Version 1.0 (February 10, 1991)
36;;;
37;;; Copyright (c) 1990, 1991 Xerox Corporation.
38;;; All rights reserved.
39;;;
40;;; Use and copying of this software and preparation of derivative works
41;;; based upon this software are permitted.  Any distribution of this
42;;; software or derivative works must comply with all applicable United
43;;; States export control laws.
44;;;
45;;; This software is made available AS IS, and Xerox Corporation makes no
46;;; warranty about the software, its performance or its conformity to any
47;;; specification.
48;;;
49;;; Closette is an implementation of a subset of CLOS with a metaobject
50;;; protocol as described in "The Art of The Metaobject Protocol",
51;;; MIT Press, 1991.
52
53(in-package #:mop)
54
55;;
56;;
57;;
58;; In order to bootstrap CLOS, first implement the required API as
59;; normal functions which only apply to the "root" metaclass
60;; STANDARD-CLASS.
61;;
62;; After putting the normal functions in place, the building blocks
63;; are in place to gradually swap the normal functions with
64;; generic functions and methods.
65;;
66;; Some functionality implemented in the temporary regular functions
67;; needs to be available later as a method definition to be dispatched
68;; to for the STANDARD-CLASS case.  To prevent repeated code, the
69;; functions are implemented in functions by the same name as the
70;; API functions, but with the STD- prefix.
71;;
72;; When hacking this file, note that some important parts are implemented
73;; in the Java world. These Java bits can be found in the files
74;;
75;; * LispClass.java
76;; * SlotClass.java
77;; * StandardClass.java
78;; * BuiltInClass.java
79;; * StandardObject.java
80;; * StandardObjectFunctions.java
81;; * Layout.java
82;;
83;; In case of function names, those defined on the Java side can be
84;; recognized by their prefixed percent sign.
85;;
86;; The API functions need to be declaimed NOTINLINE explicitly, because
87;; that prevents inlining in the current FASL (which is allowed by the
88;; CLHS without the declaration); this is a hard requirement to in order
89;; to be able to swap the symbol's function slot with a generic function
90;; later on - with it actually being used.
91;;
92;;
93;;
94;; ### Note that the "declares all API functions as regular functions"
95;; isn't true when I write the above, but it's definitely the target.
96;;
97;;
98
99(export '(class-precedence-list class-slots
100          slot-definition-name))
101(defconstant +the-standard-class+ (find-class 'standard-class))
102(defconstant +the-structure-class+ (find-class 'structure-class))
103(defconstant +the-standard-object-class+ (find-class 'standard-object))
104(defconstant +the-standard-method-class+ (find-class 'standard-method))
105(defconstant +the-standard-reader-method-class+
106  (find-class 'standard-reader-method))
107(defconstant +the-standard-generic-function-class+
108  (find-class 'standard-generic-function))
109(defconstant +the-T-class+ (find-class 'T))
110(defconstant +the-standard-slot-definition-class+ (find-class 'standard-slot-definition))
111(defconstant +the-standard-direct-slot-definition-class+ (find-class 'standard-direct-slot-definition))
112(defconstant +the-standard-effective-slot-definition-class+ (find-class 'standard-effective-slot-definition))
113
114;; Don't use DEFVAR, because that disallows loading clos.lisp
115;; after compiling it: the binding won't get assigned to T anymore
116(defparameter *clos-booting* t)
117
118(defmacro define-class->%class-forwarder (name)
119  (let* (($name (if (consp name) (cadr name) name))
120         (%name (intern (concatenate 'string
121                                     "%"
122                                     (if (consp name)
123                                         (symbol-name 'set-) "")
124                                     (symbol-name $name))
125                        (symbol-package $name))))
126    `(progn
127       (declaim (notinline ,name))
128       (defun ,name (&rest args)
129         (apply #',%name args)))))
130
131;;
132;;  DEFINE PLACE HOLDER FUNCTIONS
133;;
134
135(define-class->%class-forwarder class-name)
136(define-class->%class-forwarder (setf class-name))
137(define-class->%class-forwarder class-slots)
138(define-class->%class-forwarder (setf class-slots))
139(define-class->%class-forwarder class-direct-slots)
140(define-class->%class-forwarder (setf class-direct-slots))
141(define-class->%class-forwarder class-layout)
142(define-class->%class-forwarder (setf class-layout))
143(define-class->%class-forwarder class-direct-superclasses)
144(define-class->%class-forwarder (setf class-direct-superclasses))
145(define-class->%class-forwarder class-direct-subclasses)
146(define-class->%class-forwarder (setf class-direct-subclasses))
147(define-class->%class-forwarder class-direct-methods)
148(define-class->%class-forwarder (setf class-direct-methods))
149(define-class->%class-forwarder class-precedence-list)
150(define-class->%class-forwarder (setf class-precedence-list))
151(define-class->%class-forwarder class-finalized-p)
152(define-class->%class-forwarder (setf class-finalized-p))
153(define-class->%class-forwarder class-default-initargs)
154(define-class->%class-forwarder (setf class-default-initargs))
155(define-class->%class-forwarder class-direct-default-initargs)
156(define-class->%class-forwarder (setf class-direct-default-initargs))
157
158(defun no-applicable-method (generic-function &rest args)
159  (error "There is no applicable method for the generic function ~S when called with arguments ~S."
160         generic-function
161         args))
162
163(defun function-keywords (method)
164  (%function-keywords method))
165
166
167
168(defmacro push-on-end (value location)
169  `(setf ,location (nconc ,location (list ,value))))
170
171;;; (SETF GETF*) is like (SETF GETF) except that it always changes the list,
172;;; which must be non-nil.
173
174(defun (setf getf*) (new-value plist key)
175  (block body
176    (do ((x plist (cddr x)))
177        ((null x))
178      (when (eq (car x) key)
179        (setf (car (cdr x)) new-value)
180        (return-from body new-value)))
181    (push-on-end key plist)
182    (push-on-end new-value plist)
183    new-value))
184
185(defun mapappend (fun &rest args)
186  (if (some #'null args)
187      ()
188      (append (apply fun (mapcar #'car args))
189              (apply #'mapappend fun (mapcar #'cdr args)))))
190
191(defun mapplist (fun x)
192  (if (null x)
193      ()
194      (cons (funcall fun (car x) (cadr x))
195            (mapplist fun (cddr x)))))
196
197(defsetf std-instance-layout %set-std-instance-layout)
198(defsetf standard-instance-access %set-standard-instance-access)
199
200(defun (setf find-class) (new-value symbol &optional errorp environment)
201  (declare (ignore errorp environment))
202  (%set-find-class symbol new-value))
203
204(defun canonicalize-direct-slots (direct-slots)
205  `(list ,@(mapcar #'canonicalize-direct-slot direct-slots)))
206
207(defun canonicalize-direct-slot (spec)
208  (if (symbolp spec)
209      `(list :name ',spec)
210      (let ((name (car spec))
211            (initfunction nil)
212            (initform nil)
213            (initargs ())
214            (type nil)
215            (allocation nil)
216            (documentation nil)
217            (readers ())
218            (writers ())
219            (other-options ())
220            (non-std-options ()))
221        (do ((olist (cdr spec) (cddr olist)))
222            ((null olist))
223          (case (car olist)
224            (:initform
225             (when initform
226               (error 'program-error
227                      "duplicate slot option :INITFORM for slot named ~S"
228                      name))
229             (setq initfunction t)
230             (setq initform (cadr olist)))
231            (:initarg
232             (push-on-end (cadr olist) initargs))
233            (:allocation
234             (when allocation
235               (error 'program-error
236                      "duplicate slot option :ALLOCATION for slot named ~S"
237                      name))
238             (setf allocation (cadr olist))
239             (push-on-end (car olist) other-options)
240             (push-on-end (cadr olist) other-options))
241            (:type
242             (when type
243               (error 'program-error
244                      "duplicate slot option :TYPE for slot named ~S"
245                      name))
246             (setf type (cadr olist))) ;; FIXME type is ignored
247            (:documentation
248             (when documentation
249               (error 'program-error
250                      "duplicate slot option :DOCUMENTATION for slot named ~S"
251                      name))
252             (setf documentation (cadr olist))) ;; FIXME documentation is ignored
253            (:reader
254             (maybe-note-name-defined (cadr olist))
255             (push-on-end (cadr olist) readers))
256            (:writer
257             (maybe-note-name-defined (cadr olist))
258             (push-on-end (cadr olist) writers))
259            (:accessor
260             (maybe-note-name-defined (cadr olist))
261             (push-on-end (cadr olist) readers)
262             (push-on-end `(setf ,(cadr olist)) writers))
263            (t
264             (push-on-end `(quote ,(car olist)) non-std-options)
265             (push-on-end `(quote ,(cadr olist)) non-std-options))))
266        `(list
267          :name ',name
268          ,@(when initfunction
269              `(:initform ',initform
270                :initfunction ,(if (eq allocation :class)
271                                   ;; CLHS specifies the initform for a
272                                   ;; class allocation level slot needs
273                                   ;; to be evaluated in the dynamic
274                                   ;; extent of the DEFCLASS form
275                                   (let ((var (gensym)))
276                                     `(let ((,var ,initform))
277                                        (lambda () ,var)))
278                                 `(lambda () ,initform))))
279          ,@(when initargs `(:initargs ',initargs))
280          ,@(when readers `(:readers ',readers))
281          ,@(when writers `(:writers ',writers))
282          ,@other-options
283    ,@non-std-options))))
284
285(defun maybe-note-name-defined (name)
286  (when (fboundp 'note-name-defined)
287    (note-name-defined name)))
288
289(defun canonicalize-direct-superclasses (direct-superclasses)
290  (let ((classes '()))
291    (dolist (class-specifier direct-superclasses)
292      (if (classp class-specifier)
293          (push class-specifier classes)
294          (let ((class (find-class class-specifier nil)))
295            (unless class
296              (setf class (make-forward-referenced-class class-specifier)))
297            (push class classes))))
298    (nreverse classes)))
299
300(defun canonicalize-defclass-options (options)
301  (mapappend #'canonicalize-defclass-option options))
302
303(defun canonicalize-defclass-option (option)
304  (case (car option)
305    (:metaclass
306     (list ':metaclass
307           `(find-class ',(cadr option))))
308    (:default-initargs
309     (list
310      ':direct-default-initargs
311      `(list ,@(mapappend
312                #'(lambda (x) x)
313                (mapplist
314                 #'(lambda (key value)
315                    `(',key ,(make-initfunction value)))
316                 (cdr option))))))
317    ((:documentation :report)
318     (list (car option) `',(cadr option)))
319    (t (list `(quote ,(car option)) `(quote ,(cdr option))))))
320
321(defun make-initfunction (initform)
322  `(function (lambda () ,initform)))
323
324(defun slot-definition-allocation (slot-definition)
325  (%slot-definition-allocation slot-definition))
326
327(declaim (notinline (setf slot-definition-allocation)))
328(defun (setf slot-definition-allocation) (value slot-definition)
329  (set-slot-definition-allocation slot-definition value))
330
331(defun slot-definition-initargs (slot-definition)
332  (%slot-definition-initargs slot-definition))
333
334(declaim (notinline (setf slot-definition-initargs)))
335(defun (setf slot-definition-initargs) (value slot-definition)
336  (set-slot-definition-initargs slot-definition value))
337
338(defun slot-definition-initform (slot-definition)
339  (%slot-definition-initform slot-definition))
340
341(declaim (notinline (setf slot-definition-initform)))
342(defun (setf slot-definition-initform) (value slot-definition)
343  (set-slot-definition-initform slot-definition value))
344
345(defun slot-definition-initfunction (slot-definition)
346  (%slot-definition-initfunction slot-definition))
347
348(declaim (notinline (setf slot-definition-initfunction)))
349(defun (setf slot-definition-initfunction) (value slot-definition)
350  (set-slot-definition-initfunction slot-definition value))
351
352(defun slot-definition-name (slot-definition)
353  (%slot-definition-name slot-definition))
354
355(declaim (notinline (setf slot-definition-name)))
356(defun (setf slot-definition-name) (value slot-definition)
357  (set-slot-definition-name slot-definition value))
358
359(defun slot-definition-readers (slot-definition)
360  (%slot-definition-readers slot-definition))
361
362(declaim (notinline (setf slot-definition-readers)))
363(defun (setf slot-definition-readers) (value slot-definition)
364  (set-slot-definition-readers slot-definition value))
365
366(defun slot-definition-writers (slot-definition)
367  (%slot-definition-writers slot-definition))
368
369(declaim (notinline (setf slot-definition-writers)))
370(defun (setf slot-definition-writers) (value slot-definition)
371  (set-slot-definition-writers slot-definition value))
372
373(defun slot-definition-allocation-class (slot-definition)
374  (%slot-definition-allocation-class slot-definition))
375
376(declaim (notinline (setf slot-definition-allocation-class)))
377(defun (setf slot-definition-allocation-class) (value slot-definition)
378  (set-slot-definition-allocation-class slot-definition value))
379
380(defun slot-definition-location (slot-definition)
381  (%slot-definition-location slot-definition))
382
383(declaim (notinline (setf slot-definition-location-class)))
384(defun (setf slot-definition-location) (value slot-definition)
385  (set-slot-definition-location slot-definition value))
386
387(defun init-slot-definition (slot &key name
388                             (initargs ())
389                             (initform nil)
390                             (initfunction nil)
391                             (readers ())
392                             (writers ())
393                             (allocation :instance)
394                             (allocation-class nil))
395  (setf (slot-definition-name slot) name)
396  (setf (slot-definition-initargs slot) initargs)
397  (setf (slot-definition-initform slot) initform)
398  (setf (slot-definition-initfunction slot) initfunction)
399  (setf (slot-definition-readers slot) readers)
400  (setf (slot-definition-writers slot) writers)
401  (setf (slot-definition-allocation slot) allocation)
402  (setf (slot-definition-allocation-class slot) allocation-class)
403  slot)
404
405(defun make-direct-slot-definition (class &rest args)
406  (let ((slot-class (direct-slot-definition-class class)))
407    (if (eq slot-class +the-standard-direct-slot-definition-class+)
408  (let ((slot (make-slot-definition +the-standard-direct-slot-definition-class+)))
409    (apply #'init-slot-definition slot :allocation-class class args)
410    slot)
411  (progn
412    (let ((slot (apply #'make-instance slot-class :allocation-class class
413           args)))
414      slot)))))
415
416(defun make-effective-slot-definition (class &rest args)
417  (let ((slot-class (effective-slot-definition-class class)))
418    (if (eq slot-class +the-standard-effective-slot-definition-class+)
419  (let ((slot (make-slot-definition +the-standard-effective-slot-definition-class+)))
420    (apply #'init-slot-definition slot args)
421    slot)
422  (progn
423    (let ((slot (apply #'make-instance slot-class args)))
424      slot)))))
425
426;;; finalize-inheritance
427
428(defun std-compute-class-default-initargs (class)
429  (mapcan #'(lambda (c)
430              (copy-list
431               (class-direct-default-initargs c)))
432          (class-precedence-list class)))
433
434(defun std-finalize-inheritance (class)
435  ;; In case the class is already finalized, return
436  ;; immediately, as per AMOP.
437  (when (class-finalized-p class)
438    (return-from std-finalize-inheritance))
439  (setf (class-precedence-list class)
440   (funcall (if (eq (class-of class) +the-standard-class+)
441                #'std-compute-class-precedence-list
442                #'compute-class-precedence-list)
443            class))
444  (setf (class-slots class)
445                   (funcall (if (eq (class-of class) +the-standard-class+)
446                                #'std-compute-slots
447                     #'compute-slots) class))
448  (let ((old-layout (class-layout class))
449        (length 0)
450        (instance-slots '())
451        (shared-slots '()))
452    (dolist (slot (class-slots class))
453      (case (slot-definition-allocation slot)
454        (:instance
455         (setf (slot-definition-location slot) length)
456         (incf length)
457         (push (slot-definition-name slot) instance-slots))
458        (:class
459         (unless (slot-definition-location slot)
460           (let ((allocation-class (slot-definition-allocation-class slot)))
461             (setf (slot-definition-location slot)
462       (if (eq allocation-class class)
463           (cons (slot-definition-name slot) +slot-unbound+)
464           (slot-location allocation-class (slot-definition-name slot))))))
465         (push (slot-definition-location slot) shared-slots))))
466    (when old-layout
467      ;; Redefined class: initialize added shared slots.
468      (dolist (location shared-slots)
469        (let* ((slot-name (car location))
470               (old-location (layout-slot-location old-layout slot-name)))
471          (unless old-location
472            (let* ((slot-definition (find slot-name (class-slots class) :key 'slot-definition-name))
473                   (initfunction (slot-definition-initfunction slot-definition)))
474              (when initfunction
475                (setf (cdr location) (funcall initfunction))))))))
476    (setf (class-layout class)
477          (make-layout class (nreverse instance-slots) (nreverse shared-slots))))
478  (setf (class-default-initargs class)
479        (std-compute-class-default-initargs class))
480  (setf (class-finalized-p class) t))
481
482(declaim (notinline finalize-inheritance))
483(defun finalize-inheritance (class)
484  (std-finalize-inheritance class))
485
486
487;;; Class precedence lists
488
489(defun std-compute-class-precedence-list (class)
490  (let ((classes-to-order (collect-superclasses* class)))
491    (dolist (super classes-to-order)
492      (when (typep super 'forward-referenced-class)
493        (error "Can't compute class precedence list for class ~A ~
494                which depends on forward referenced class ~A." class super)))
495    (topological-sort classes-to-order
496                      (remove-duplicates
497                       (mapappend #'local-precedence-ordering
498                                  classes-to-order))
499                      #'std-tie-breaker-rule)))
500
501;;; topological-sort implements the standard algorithm for topologically
502;;; sorting an arbitrary set of elements while honoring the precedence
503;;; constraints given by a set of (X,Y) pairs that indicate that element
504;;; X must precede element Y.  The tie-breaker procedure is called when it
505;;; is necessary to choose from multiple minimal elements; both a list of
506;;; candidates and the ordering so far are provided as arguments.
507
508(defun topological-sort (elements constraints tie-breaker)
509  (let ((remaining-constraints constraints)
510        (remaining-elements elements)
511        (result ()))
512    (loop
513      (let ((minimal-elements
514             (remove-if
515              #'(lambda (class)
516                 (member class remaining-constraints
517                         :key #'cadr))
518              remaining-elements)))
519        (when (null minimal-elements)
520          (if (null remaining-elements)
521              (return-from topological-sort result)
522              (error "Inconsistent precedence graph.")))
523        (let ((choice (if (null (cdr minimal-elements))
524                          (car minimal-elements)
525                          (funcall tie-breaker
526                                   minimal-elements
527                                   result))))
528          (setq result (append result (list choice)))
529          (setq remaining-elements
530                (remove choice remaining-elements))
531          (setq remaining-constraints
532                (remove choice
533                        remaining-constraints
534                        :test #'member)))))))
535
536;;; In the event of a tie while topologically sorting class precedence lists,
537;;; the CLOS Specification says to "select the one that has a direct subclass
538;;; rightmost in the class precedence list computed so far."  The same result
539;;; is obtained by inspecting the partially constructed class precedence list
540;;; from right to left, looking for the first minimal element to show up among
541;;; the direct superclasses of the class precedence list constituent.
542;;; (There's a lemma that shows that this rule yields a unique result.)
543
544(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
545  (dolist (cpl-constituent (reverse cpl-so-far))
546    (let* ((supers (class-direct-superclasses cpl-constituent))
547           (common (intersection minimal-elements supers)))
548      (when (not (null common))
549        (return-from std-tie-breaker-rule (car common))))))
550
551;;; This version of collect-superclasses* isn't bothered by cycles in the class
552;;; hierarchy, which sometimes happen by accident.
553
554(defun collect-superclasses* (class)
555  (labels ((all-superclasses-loop (seen superclasses)
556                                  (let ((to-be-processed
557                                         (set-difference superclasses seen)))
558                                    (if (null to-be-processed)
559                                        superclasses
560                                        (let ((class-to-process
561                                               (car to-be-processed)))
562                                          (all-superclasses-loop
563                                           (cons class-to-process seen)
564                                           (union (class-direct-superclasses
565                                                   class-to-process)
566                                                  superclasses)))))))
567          (all-superclasses-loop () (list class))))
568
569;;; The local precedence ordering of a class C with direct superclasses C_1,
570;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
571
572(defun local-precedence-ordering (class)
573  (mapcar #'list
574          (cons class
575                (butlast (class-direct-superclasses class)))
576          (class-direct-superclasses class)))
577
578;;; Slot inheritance
579
580(defun std-compute-slots (class)
581  (let* ((all-slots (mapappend #'class-direct-slots
582                               (class-precedence-list class)))
583         (all-names (remove-duplicates
584                     (mapcar 'slot-definition-name all-slots))))
585    (mapcar #'(lambda (name)
586               (funcall
587                (if (eq (class-of class) +the-standard-class+)
588                    #'std-compute-effective-slot-definition
589                    #'compute-effective-slot-definition)
590                class
591                name
592                (remove name all-slots
593                        :key 'slot-definition-name
594                        :test-not #'eq)))
595            all-names)))
596
597(defun std-compute-effective-slot-definition (class name direct-slots)
598  (let ((initer (find-if-not #'null direct-slots
599                             :key 'slot-definition-initfunction)))
600    (make-effective-slot-definition
601     class
602     :name name
603     :initform (if initer
604                   (slot-definition-initform initer)
605                   nil)
606     :initfunction (if initer
607                       (slot-definition-initfunction initer)
608                       nil)
609     :initargs (remove-duplicates
610                (mapappend 'slot-definition-initargs
611                           direct-slots))
612     :allocation (slot-definition-allocation (car direct-slots))
613     :allocation-class (when (slot-boundp (car direct-slots)
614            'sys::allocation-class)
615       ;;for some classes created in Java
616       ;;(e.g. SimpleCondition) this slot is unbound
617       (slot-definition-allocation-class (car direct-slots))))))
618
619;;; Standard instance slot access
620
621;;; N.B. The location of the effective-slots slots in the class metaobject for
622;;; standard-class must be determined without making any further slot
623;;; references.
624
625(defun find-slot-definition (class slot-name)
626  (dolist (slot (class-slots class) nil)
627    (when (eq slot-name (slot-definition-name slot))
628      (return slot))))
629
630(defun slot-location (class slot-name)
631  (let ((slot (find-slot-definition class slot-name)))
632    (if slot
633        (slot-definition-location slot)
634        nil)))
635
636(defun instance-slot-location (instance slot-name)
637  (let ((layout (std-instance-layout instance)))
638    (and layout (layout-slot-location layout slot-name))))
639
640(defun slot-value (object slot-name)
641  (if (or (eq (class-of (class-of object)) +the-standard-class+)
642    (eq (class-of (class-of object)) +the-structure-class+))
643      (std-slot-value object slot-name)
644      (slot-value-using-class (class-of object) object slot-name)))
645
646(defsetf std-slot-value set-std-slot-value)
647
648(defun %set-slot-value (object slot-name new-value)
649  (if (or (eq (class-of (class-of object)) +the-standard-class+)
650    (eq (class-of (class-of object)) +the-structure-class+))
651      (setf (std-slot-value object slot-name) new-value)
652      (set-slot-value-using-class new-value (class-of object)
653                                  object slot-name)))
654
655(defsetf slot-value %set-slot-value)
656
657(defun slot-boundp (object slot-name)
658  (if (eq (class-of (class-of object)) +the-standard-class+)
659      (std-slot-boundp object slot-name)
660      (slot-boundp-using-class (class-of object) object slot-name)))
661
662(defun std-slot-makunbound (instance slot-name)
663  (let ((location (instance-slot-location instance slot-name)))
664    (cond ((fixnump location)
665           (setf (standard-instance-access instance location) +slot-unbound+))
666          ((consp location)
667           (setf (cdr location) +slot-unbound+))
668          (t
669           (slot-missing (class-of instance) instance slot-name 'slot-makunbound))))
670  instance)
671
672(defun slot-makunbound (object slot-name)
673  (if (eq (class-of (class-of object)) +the-standard-class+)
674      (std-slot-makunbound object slot-name)
675      (slot-makunbound-using-class (class-of object) object slot-name)))
676
677(defun std-slot-exists-p (instance slot-name)
678  (not (null (find slot-name (class-slots (class-of instance))
679                   :key 'slot-definition-name))))
680
681(defun slot-exists-p (object slot-name)
682  (if (eq (class-of (class-of object)) +the-standard-class+)
683      (std-slot-exists-p object slot-name)
684      (slot-exists-p-using-class (class-of object) object slot-name)))
685
686(defun instance-slot-p (slot)
687  (eq (slot-definition-allocation slot) :instance))
688
689(defun std-allocate-instance (class)
690  ;; AMOP says ALLOCATE-INSTANCE checks if the class is finalized
691  ;; and if not, tries to finalize it.
692  (unless (class-finalized-p class)
693    (std-finalize-inheritance class))
694  (sys::%std-allocate-instance class))
695
696(defun allocate-funcallable-instance (class)
697  (unless (class-finalized-p class)
698    (std-finalize-inheritance class))
699  (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      (%set-gf-optional-args gf (getf plist :optional-args))
1522      (setf (generic-function-argument-precedence-order gf)
1523            (if argument-precedence-order
1524                (canonicalize-argument-precedence-order argument-precedence-order
1525                                                        required-args)
1526                nil)))
1527    (finalize-generic-function gf)
1528    gf))
1529
1530(defun canonicalize-specializers (specializers)
1531  (mapcar #'canonicalize-specializer specializers))
1532
1533(defun canonicalize-specializer (specializer)
1534  (cond ((classp specializer)
1535         specializer)
1536        ((typep specializer 'eql-specializer)
1537         specializer)
1538        ((symbolp specializer)
1539         (find-class specializer))
1540        ((and (consp specializer)
1541              (eq (car specializer) 'eql))
1542         (let ((object (cadr specializer)))
1543           (when (and (consp object)
1544                      (eq (car object) 'quote))
1545             (setf object (cadr object)))
1546           (intern-eql-specializer object)))
1547        ((and (consp specializer)
1548              (eq (car specializer) 'java:jclass))
1549         (let ((jclass (eval specializer)))
1550           (java::ensure-java-class jclass)))
1551        (t
1552         (error "Unknown specializer: ~S" specializer))))
1553
1554(defun parse-defmethod (args)
1555  (let ((function-name (car args))
1556        (qualifiers ())
1557        (specialized-lambda-list ())
1558        (body ())
1559        (parse-state :qualifiers))
1560    (dolist (arg (cdr args))
1561      (ecase parse-state
1562        (:qualifiers
1563         (if (and (atom arg) (not (null arg)))
1564             (push arg qualifiers)
1565             (progn
1566               (setf specialized-lambda-list arg)
1567               (setf parse-state :body))))
1568        (:body (push arg body))))
1569    (setf qualifiers (nreverse qualifiers)
1570          body (nreverse body))
1571    (multiple-value-bind (real-body declarations documentation)
1572        (parse-body body)
1573      (values function-name
1574              qualifiers
1575              (extract-lambda-list specialized-lambda-list)
1576              (extract-specializer-names specialized-lambda-list)
1577              documentation
1578              declarations
1579              (list* 'block
1580                     (fdefinition-block-name function-name)
1581                     real-body)))))
1582
1583(defun required-portion (gf args)
1584  (let ((number-required (length (gf-required-args gf))))
1585    (when (< (length args) number-required)
1586      (error 'program-error
1587             :format-control "Not enough arguments for generic function ~S."
1588             :format-arguments (list (%generic-function-name gf))))
1589    (subseq args 0 number-required)))
1590
1591(defun extract-lambda-list (specialized-lambda-list)
1592  (let* ((plist (analyze-lambda-list specialized-lambda-list))
1593         (requireds (getf plist :required-names))
1594         (rv (getf plist :rest-var))
1595         (ks (getf plist :key-args))
1596         (keysp (getf plist :keysp))
1597         (aok (getf plist :allow-other-keys))
1598         (opts (getf plist :optional-args))
1599         (auxs (getf plist :auxiliary-args)))
1600    `(,@requireds
1601      ,@(if rv `(&rest ,rv) ())
1602      ,@(if (or ks keysp aok) `(&key ,@ks) ())
1603      ,@(if aok '(&allow-other-keys) ())
1604      ,@(if opts `(&optional ,@opts) ())
1605      ,@(if auxs `(&aux ,@auxs) ()))))
1606
1607(defun extract-specializer-names (specialized-lambda-list)
1608  (let ((plist (analyze-lambda-list specialized-lambda-list)))
1609    (getf plist ':specializers)))
1610
1611(defun get-keyword-from-arg (arg)
1612  (if (listp arg)
1613      (if (listp (car arg))
1614          (caar arg)
1615          (make-keyword (car arg)))
1616      (make-keyword arg)))
1617
1618(defun analyze-lambda-list (lambda-list)
1619  (let ((keys ())           ; Just the keywords
1620        (key-args ())       ; Keywords argument specs
1621        (keysp nil)         ;
1622        (required-names ()) ; Just the variable names
1623        (required-args ())  ; Variable names & specializers
1624        (specializers ())   ; Just the specializers
1625        (rest-var nil)
1626        (optionals ())
1627        (auxs ())
1628        (allow-other-keys nil)
1629        (state :parsing-required))
1630    (dolist (arg lambda-list)
1631      (if (member arg lambda-list-keywords)
1632          (ecase arg
1633            (&optional
1634             (setq state :parsing-optional))
1635            (&rest
1636             (setq state :parsing-rest))
1637            (&key
1638             (setq keysp t)
1639             (setq state :parsing-key))
1640            (&allow-other-keys
1641             (setq allow-other-keys 't))
1642            (&aux
1643             (setq state :parsing-aux)))
1644          (case state
1645            (:parsing-required
1646             (push-on-end arg required-args)
1647             (if (listp arg)
1648                 (progn (push-on-end (car arg) required-names)
1649                   (push-on-end (cadr arg) specializers))
1650                 (progn (push-on-end arg required-names)
1651                   (push-on-end 't specializers))))
1652            (:parsing-optional (push-on-end arg optionals))
1653            (:parsing-rest (setq rest-var arg))
1654            (:parsing-key
1655             (push-on-end (get-keyword-from-arg arg) keys)
1656             (push-on-end arg key-args))
1657            (:parsing-aux (push-on-end arg auxs)))))
1658    (list  :required-names required-names
1659           :required-args required-args
1660           :specializers specializers
1661           :rest-var rest-var
1662           :keywords keys
1663           :key-args key-args
1664           :keysp keysp
1665           :auxiliary-args auxs
1666           :optional-args optionals
1667           :allow-other-keys allow-other-keys)))
1668
1669#+nil
1670(defun check-method-arg-info (gf arg-info method)
1671  (multiple-value-bind (nreq nopt keysp restp allow-other-keys-p keywords)
1672      (analyze-lambda-list (if (consp method)
1673                               (early-method-lambda-list method)
1674                               (method-lambda-list method)))
1675    (flet ((lose (string &rest args)
1676                 (error 'simple-program-error
1677                        :format-control "~@<attempt to add the method~2I~_~S~I~_~
1678                        to the generic function~2I~_~S;~I~_~
1679                        but ~?~:>"
1680                        :format-arguments (list method gf string args)))
1681           (comparison-description (x y)
1682                                   (if (> x y) "more" "fewer")))
1683      (let ((gf-nreq (arg-info-number-required arg-info))
1684            (gf-nopt (arg-info-number-optional arg-info))
1685            (gf-key/rest-p (arg-info-key/rest-p arg-info))
1686            (gf-keywords (arg-info-keys arg-info)))
1687        (unless (= nreq gf-nreq)
1688          (lose
1689           "the method has ~A required arguments than the generic function."
1690           (comparison-description nreq gf-nreq)))
1691        (unless (= nopt gf-nopt)
1692          (lose
1693           "the method has ~A optional arguments than the generic function."
1694           (comparison-description nopt gf-nopt)))
1695        (unless (eq (or keysp restp) gf-key/rest-p)
1696          (lose
1697           "the method and generic function differ in whether they accept~_~
1698            &REST or &KEY arguments."))
1699        (when (consp gf-keywords)
1700          (unless (or (and restp (not keysp))
1701                      allow-other-keys-p
1702                      (every (lambda (k) (memq k keywords)) gf-keywords))
1703            (lose "the method does not accept each of the &KEY arguments~2I~_~
1704            ~S."
1705                  gf-keywords)))))))
1706
1707(defun check-method-lambda-list (name method-lambda-list gf-lambda-list)
1708  (let* ((gf-restp (not (null (memq '&rest gf-lambda-list))))
1709         (gf-plist (analyze-lambda-list gf-lambda-list))
1710         (gf-keysp (getf gf-plist :keysp))
1711         (gf-keywords (getf gf-plist :keywords))
1712         (method-plist (analyze-lambda-list method-lambda-list))
1713         (method-restp (not (null (memq '&rest method-lambda-list))))
1714         (method-keysp (getf method-plist :keysp))
1715         (method-keywords (getf method-plist :keywords))
1716         (method-allow-other-keys-p (getf method-plist :allow-other-keys)))
1717    (unless (= (length (getf gf-plist :required-args))
1718               (length (getf method-plist :required-args)))
1719      (error "The method-lambda-list ~S ~
1720              has the wrong number of required arguments ~
1721              for the generic function ~S." method-lambda-list name))
1722    (unless (= (length (getf gf-plist :optional-args))
1723               (length (getf method-plist :optional-args)))
1724      (error "The method-lambda-list ~S ~
1725              has the wrong number of optional arguments ~
1726              for the generic function ~S." method-lambda-list name))
1727    (unless (eq (or gf-restp gf-keysp) (or method-restp method-keysp))
1728      (error "The method-lambda-list ~S ~
1729              and the generic function ~S ~
1730              differ in whether they accept &REST or &KEY arguments."
1731             method-lambda-list name))
1732    (when (consp gf-keywords)
1733      (unless (or (and method-restp (not method-keysp))
1734                  method-allow-other-keys-p
1735                  (every (lambda (k) (memq k method-keywords)) gf-keywords))
1736        (error "The method-lambda-list ~S does not accept ~
1737                all of the keyword arguments defined for the ~
1738                generic function." method-lambda-list name)))))
1739
1740(defvar *gf-initialize-instance* nil
1741  "Cached value of the INITIALIZE-INSTANCE generic function.
1742Initialized with the true value near the end of the file.")
1743(defvar *gf-allocate-instance* nil
1744  "Cached value of the ALLOCATE-INSTANCE generic function.
1745Initialized with the true value near the end of the file.")
1746(defvar *gf-shared-initialize* nil
1747  "Cached value of the SHARED-INITIALIZE generic function.
1748Initialized with the true value near the end of the file.")
1749(defvar *gf-reinitialize-instance* nil
1750  "Cached value of the REINITIALIZE-INSTANCE generic function.
1751Initialized with the true value near the end of the file.")
1752
1753(declaim (ftype (function * method) ensure-method))
1754(defun ensure-method (name &rest all-keys)
1755  (let ((method-lambda-list (getf all-keys :lambda-list))
1756        (gf (find-generic-function name nil)))
1757    (when (or (eq gf *gf-initialize-instance*)
1758              (eq gf *gf-allocate-instance*)
1759              (eq gf *gf-shared-initialize*)
1760              (eq gf *gf-reinitialize-instance*))
1761      ;; ### Clearly, this can be targeted much more exact
1762      ;; as we only need to remove the specializing class and all
1763      ;; its subclasses from the hash.
1764      (clrhash *make-instance-initargs-cache*)
1765      (clrhash *reinitialize-instance-initargs-cache*))
1766    (if gf
1767        (check-method-lambda-list name method-lambda-list
1768                                  (generic-function-lambda-list gf))
1769        (setf gf (ensure-generic-function name :lambda-list method-lambda-list)))
1770    (let ((method
1771           (if (eq (generic-function-method-class gf) +the-standard-method-class+)
1772               (apply #'make-instance-standard-method gf all-keys)
1773               (apply #'make-instance (generic-function-method-class gf) all-keys))))
1774      (%add-method gf method)
1775      method)))
1776
1777(defun make-instance-standard-method (gf
1778                                      &key
1779                                      lambda-list
1780                                      qualifiers
1781                                      specializers
1782                                      documentation
1783                                      function
1784                                      fast-function)
1785  (declare (ignore gf))
1786  (let ((method (std-allocate-instance +the-standard-method-class+))
1787        (analyzed-args (analyze-lambda-list lambda-list))
1788        )
1789    (setf (method-lambda-list method) lambda-list)
1790    (setf (method-qualifiers method) qualifiers)
1791    (%set-method-specializers method (canonicalize-specializers specializers))
1792    (setf (method-documentation method) documentation)
1793    (%set-method-generic-function method nil)
1794    (%set-method-function method function)
1795    (%set-method-fast-function method fast-function)
1796    (%set-function-keywords method
1797                            (getf analyzed-args :keywords)
1798                            (getf analyzed-args :allow-other-keys))
1799    method))
1800
1801(defun %add-method (gf method)
1802  (when (%method-generic-function method)
1803    (error 'simple-error
1804           :format-control "ADD-METHOD: ~S is a method of ~S."
1805           :format-arguments (list method (%method-generic-function method))))
1806  ;; Remove existing method with same qualifiers and specializers (if any).
1807  (let ((old-method (%find-method gf (method-qualifiers method)
1808                                 (%method-specializers method) nil)))
1809    (when old-method
1810      (%remove-method gf old-method)))
1811  (%set-method-generic-function method gf)
1812  (push method (generic-function-methods gf))
1813  (dolist (specializer (%method-specializers method))
1814    (when (typep specializer 'class) ;; FIXME What about EQL specializer objects?
1815      (pushnew method (class-direct-methods specializer))))
1816  (finalize-generic-function gf)
1817  gf)
1818
1819(defun %remove-method (gf method)
1820  (setf (generic-function-methods gf)
1821        (remove method (generic-function-methods gf)))
1822  (%set-method-generic-function method nil)
1823  (dolist (specializer (%method-specializers method))
1824    (when (typep specializer 'class) ;; FIXME What about EQL specializer objects?
1825      (setf (class-direct-methods specializer)
1826            (remove method (class-direct-methods specializer)))))
1827  (finalize-generic-function gf)
1828  gf)
1829
1830(defun %find-method (gf qualifiers specializers &optional (errorp t))
1831  ;; "If the specializers argument does not correspond in length to the number
1832  ;; of required arguments of the generic-function, an an error of type ERROR
1833  ;; is signaled."
1834  (unless (= (length specializers) (length (gf-required-args gf)))
1835    (error "The specializers argument has length ~S, but ~S has ~S required parameters."
1836           (length specializers)
1837           gf
1838           (length (gf-required-args gf))))
1839  (let* ((canonical-specializers (canonicalize-specializers specializers))
1840         (method
1841          (find-if #'(lambda (method)
1842                      (and (equal qualifiers
1843                                  (method-qualifiers method))
1844                           (equal canonical-specializers
1845                                  (%method-specializers method))))
1846                   (generic-function-methods gf))))
1847    (if (and (null method) errorp)
1848        (error "No such method for ~S." (%generic-function-name gf))
1849        method)))
1850
1851(defun fast-callable-p (gf)
1852  (and (eq (generic-function-method-combination gf) 'standard)
1853       (null (intersection (%generic-function-lambda-list gf)
1854                           '(&rest &optional &key &allow-other-keys &aux)))))
1855
1856(declaim (ftype (function * t) slow-method-lookup-1))
1857
1858(declaim (ftype (function (t t t) t) slow-reader-lookup))
1859(defun slow-reader-lookup (gf layout slot-name)
1860  (let ((location (layout-slot-location layout slot-name)))
1861    (cache-slot-location gf layout location)
1862    location))
1863
1864(defun std-compute-discriminating-function (gf)
1865  ;; In this function, we know that gf is of class
1866  ;; standard-generic-function, so we call various
1867  ;; sys:%generic-function-foo readers to break circularities.
1868  (cond
1869    ((and (= (length (sys:%generic-function-methods gf)) 1)
1870          (typep (car (sys:%generic-function-methods gf)) 'standard-reader-method))
1871     (let* ((method (%car (sys:%generic-function-methods gf)))
1872            (class (car (%method-specializers method)))
1873            (slot-name (reader-method-slot-name method)))
1874       #'(lambda (arg)
1875           (declare (optimize speed))
1876           (let* ((layout (std-instance-layout arg))
1877                  (location (get-cached-slot-location gf layout)))
1878             (unless location
1879               (unless (simple-typep arg class)
1880                 ;; FIXME no applicable method
1881                 (error 'simple-type-error
1882                        :datum arg
1883                        :expected-type class))
1884               (setf location (slow-reader-lookup gf layout slot-name)))
1885             (if (consp location)
1886                 ;; Shared slot.
1887                 (cdr location)
1888                 (standard-instance-access arg location))))))
1889
1890    (t
1891     (let* ((emf-table (classes-to-emf-table gf))
1892            (number-required (length (gf-required-args gf)))
1893            (lambda-list (%generic-function-lambda-list gf))
1894            (exact (null (intersection lambda-list
1895                                       '(&rest &optional &key
1896                                         &allow-other-keys &aux)))))
1897       (if exact
1898           (cond
1899             ((= number-required 1)
1900              (cond
1901                ((and (eq (sys:%generic-function-method-combination gf) 'standard)
1902                      (= (length (sys:%generic-function-methods gf)) 1))
1903                 (let* ((method (%car (sys:%generic-function-methods gf)))
1904                        (specializer (car (%method-specializers method)))
1905                        (function (or (%method-fast-function method)
1906                                      (%method-function method))))
1907                   (if (typep specializer 'eql-specializer)
1908                       (let ((specializer-object (eql-specializer-object specializer)))
1909                         #'(lambda (arg)
1910                             (declare (optimize speed))
1911                             (if (eql arg specializer-object)
1912                                 (funcall function arg)
1913                                 (no-applicable-method gf (list arg)))))
1914                       #'(lambda (arg)
1915                           (declare (optimize speed))
1916                           (unless (simple-typep arg specializer)
1917                             ;; FIXME no applicable method
1918                             (error 'simple-type-error
1919                                    :datum arg
1920                                    :expected-type specializer))
1921                           (funcall function arg)))))
1922                (t
1923                 #'(lambda (arg)
1924                     (declare (optimize speed))
1925                     (let* ((specialization
1926                             (%get-arg-specialization gf arg))
1927                            (emfun (or (gethash1 specialization
1928                                                 emf-table)
1929                                       (slow-method-lookup-1
1930                                        gf arg specialization))))
1931                       (if emfun
1932                           (funcall emfun (list arg))
1933                           (apply #'no-applicable-method gf (list arg))))))))
1934             ((= number-required 2)
1935              #'(lambda (arg1 arg2)
1936                  (declare (optimize speed))
1937                  (let* ((args (list arg1 arg2))
1938                         (emfun (get-cached-emf gf args)))
1939                    (if emfun
1940                        (funcall emfun args)
1941                        (slow-method-lookup gf args)))))
1942             ((= number-required 3)
1943              #'(lambda (arg1 arg2 arg3)
1944                  (declare (optimize speed))
1945                  (let* ((args (list arg1 arg2 arg3))
1946                         (emfun (get-cached-emf gf args)))
1947                    (if emfun
1948                        (funcall emfun args)
1949                        (slow-method-lookup gf args)))))
1950             (t
1951              #'(lambda (&rest args)
1952                  (declare (optimize speed))
1953                  (let ((len (length args)))
1954                    (unless (= len number-required)
1955                      (error 'program-error
1956                             :format-control "Not enough arguments for generic function ~S."
1957                             :format-arguments (list (%generic-function-name gf)))))
1958                  (let ((emfun (get-cached-emf gf args)))
1959                    (if emfun
1960                        (funcall emfun args)
1961                        (slow-method-lookup gf args))))))
1962;;           (let ((non-key-args (+ number-required
1963;;                                  (length (gf-optional-args gf))))))
1964           #'(lambda (&rest args)
1965               (declare (optimize speed))
1966               (let ((len (length args)))
1967                 (unless (>= len number-required)
1968                   (error 'program-error
1969                          :format-control "Not enough arguments for generic function ~S."
1970                          :format-arguments (list (%generic-function-name gf)))))
1971               (let ((emfun (get-cached-emf gf args)))
1972                 (if emfun
1973                     (funcall emfun args)
1974                     (slow-method-lookup gf args)))))))))
1975
1976(defun sort-methods (methods gf required-classes)
1977  (if (or (null methods) (null (%cdr methods)))
1978      methods
1979      (sort methods
1980      (if (eq (class-of gf) +the-standard-generic-function-class+)
1981    #'(lambda (m1 m2)
1982        (std-method-more-specific-p m1 m2 required-classes
1983            (generic-function-argument-precedence-order gf)))
1984    #'(lambda (m1 m2)
1985        (method-more-specific-p gf m1 m2 required-classes))))))
1986
1987(defun method-applicable-p (method args)
1988  (do* ((specializers (%method-specializers method) (cdr specializers))
1989        (args args (cdr args)))
1990       ((null specializers) t)
1991    (let ((specializer (car specializers)))
1992      (if (typep specializer 'eql-specializer)
1993          (unless (eql (car args) (eql-specializer-object specializer))
1994            (return nil))
1995          (unless (subclassp (class-of (car args)) specializer)
1996            (return nil))))))
1997
1998(defun %compute-applicable-methods (gf args)
1999  (let ((required-classes (mapcar #'class-of (required-portion gf args)))
2000        (methods '()))
2001    (dolist (method (generic-function-methods gf))
2002      (when (method-applicable-p method args)
2003        (push method methods)))
2004    (sort-methods methods gf required-classes)))
2005
2006;;; METHOD-APPLICABLE-USING-CLASSES-P
2007;;;
2008;;; If the first return value is T, METHOD is definitely applicable to
2009;;; arguments that are instances of CLASSES.  If the first value is
2010;;; NIL and the second value is T, METHOD is definitely not applicable
2011;;; to arguments that are instances of CLASSES; if the second value is
2012;;; NIL the applicability of METHOD cannot be determined by inspecting
2013;;; the classes of its arguments only.
2014;;;
2015(defun method-applicable-using-classes-p (method classes)
2016  (do* ((specializers (%method-specializers method) (cdr specializers))
2017  (classes classes (cdr classes))
2018  (knownp t))
2019       ((null specializers)
2020  (if knownp (values t t) (values nil nil)))
2021    (let ((specializer (car specializers)))
2022      (if (typep specializer 'eql-specializer)
2023    (if (eql (class-of (eql-specializer-object specializer)) 
2024       (car classes))
2025        (setf knownp nil)
2026        (return (values nil t)))
2027    (unless (subclassp (car classes) specializer)
2028      (return (values nil t)))))))
2029
2030(defun slow-method-lookup (gf args)
2031  (let ((applicable-methods (%compute-applicable-methods gf args)))
2032    (if applicable-methods
2033        (let ((emfun (funcall (if (eq (class-of gf) +the-standard-generic-function-class+)
2034                                  #'std-compute-effective-method-function
2035                                  #'compute-effective-method-function)
2036                              gf applicable-methods)))
2037          (cache-emf gf args emfun)
2038          (funcall emfun args))
2039        (apply #'no-applicable-method gf args))))
2040
2041(defun slow-method-lookup-1 (gf arg arg-specialization)
2042  (let ((applicable-methods (%compute-applicable-methods gf (list arg))))
2043    (if applicable-methods
2044        (let ((emfun (funcall (if (eq (class-of gf) +the-standard-generic-function-class+)
2045                                  #'std-compute-effective-method-function
2046                                  #'compute-effective-method-function)
2047                              gf applicable-methods)))
2048          (when emfun
2049            (setf (gethash arg-specialization (classes-to-emf-table gf)) emfun))
2050          emfun))))
2051
2052(defun sub-specializer-p (c1 c2 c-arg)
2053  (find c2 (cdr (memq c1 (%class-precedence-list c-arg)))))
2054
2055(defun std-method-more-specific-p (method1 method2 required-classes argument-precedence-order)
2056  (if argument-precedence-order
2057      (let ((specializers-1 (%method-specializers method1))
2058            (specializers-2 (%method-specializers method2)))
2059        (dolist (index argument-precedence-order)
2060          (let ((spec1 (nth index specializers-1))
2061                (spec2 (nth index specializers-2)))
2062            (unless (eq spec1 spec2)
2063              (cond ((typep spec1 'eql-specializer)
2064                     (return t))
2065                    ((typep spec2 'eql-specializer)
2066                     (return nil))
2067                    (t
2068                     (return (sub-specializer-p spec1 spec2
2069                                                (nth index required-classes)))))))))
2070      (do ((specializers-1 (%method-specializers method1) (cdr specializers-1))
2071           (specializers-2 (%method-specializers method2) (cdr specializers-2))
2072           (classes required-classes (cdr classes)))
2073          ((null specializers-1) nil)
2074        (let ((spec1 (car specializers-1))
2075              (spec2 (car specializers-2)))
2076          (unless (eq spec1 spec2)
2077            (cond ((typep spec1 'eql-specializer)
2078                   (return t))
2079                  ((typep spec2 'eql-specializer)
2080                   (return nil))
2081                  (t
2082                   (return (sub-specializer-p spec1 spec2 (car classes))))))))))
2083
2084(defun primary-method-p (method)
2085  (null (intersection '(:before :after :around) (method-qualifiers method))))
2086
2087(defun before-method-p (method)
2088  (equal '(:before) (method-qualifiers method)))
2089
2090(defun after-method-p (method)
2091  (equal '(:after) (method-qualifiers method)))
2092
2093(defun around-method-p (method)
2094  (equal '(:around) (method-qualifiers method)))
2095
2096(defun process-next-method-list (next-method-list)
2097  (mapcar #'(lambda (next-method-form)
2098              (cond
2099                ((listp next-method-form)
2100                 (assert (eq (first next-method-form) 'make-method))
2101                 (let* ((rest-sym (gensym)))
2102                   (make-instance-standard-method
2103                    nil ;; ignored
2104                    :lambda-list (list '&rest rest-sym)
2105                    :function (compute-method-function `(lambda (&rest ,rest-sym)
2106                                                          ,(second next-method-form))))))
2107                (t
2108                 (assert (typep next-method-form 'method))
2109                 next-method-form)))
2110          next-method-list))
2111
2112(defun std-compute-effective-method-function (gf methods)
2113  (let* ((mc (generic-function-method-combination gf))
2114         (mc-name (if (atom mc) mc (%car mc)))
2115         (options (if (atom mc) '() (%cdr mc)))
2116         (order (car options))
2117         (primaries '())
2118         (arounds '())
2119         around
2120         emf-form
2121         (long-method-combination-p
2122          (typep (get mc-name 'method-combination-object) 'long-method-combination)))
2123    (unless long-method-combination-p
2124      (dolist (m methods)
2125        (let ((qualifiers (method-qualifiers m)))
2126          (cond ((null qualifiers)
2127                 (if (eq mc-name 'standard)
2128                     (push m primaries)
2129                     (error "Method combination type mismatch.")))
2130                ((cdr qualifiers)
2131                 (error "Invalid method qualifiers."))
2132                ((eq (car qualifiers) :around)
2133                 (push m arounds))
2134                ((eq (car qualifiers) mc-name)
2135                 (push m primaries))
2136                ((memq (car qualifiers) '(:before :after)))
2137                (t
2138                 (error "Invalid method qualifiers."))))))
2139    (unless (eq order :most-specific-last)
2140      (setf primaries (nreverse primaries)))
2141    (setf arounds (nreverse arounds))
2142    (setf around (car arounds))
2143    (when (and (null primaries) (not long-method-combination-p))
2144      (error "No primary methods for the generic function ~S." gf))
2145    (cond
2146      (around
2147       (let ((next-emfun
2148              (funcall
2149               (if (eq (class-of gf) +the-standard-generic-function-class+)
2150                   #'std-compute-effective-method-function
2151                   #'compute-effective-method-function)
2152               gf (remove around methods))))
2153         (setf emf-form
2154               (generate-emf-lambda (%method-function around) next-emfun))))
2155      ((eq mc-name 'standard)
2156       (let* ((next-emfun (compute-primary-emfun (cdr primaries)))
2157              (befores (remove-if-not #'before-method-p methods))
2158              (reverse-afters
2159               (reverse (remove-if-not #'after-method-p methods))))
2160         (setf emf-form
2161               (cond
2162                 ((and (null befores) (null reverse-afters))
2163                  (let ((fast-function (%method-fast-function (car primaries))))
2164                    (if fast-function
2165                        (ecase (length (gf-required-args gf))
2166                          (1
2167                           #'(lambda (args)
2168                               (declare (optimize speed))
2169                               (funcall fast-function (car args))))
2170                          (2
2171                           #'(lambda (args)
2172                               (declare (optimize speed))
2173                               (funcall fast-function (car args) (cadr args)))))
2174                        (generate-emf-lambda (%method-function (car primaries))
2175                                             next-emfun))))
2176                 (t
2177                  (let ((method-function (%method-function (car primaries))))
2178                    #'(lambda (args)
2179                        (declare (optimize speed))
2180                        (dolist (before befores)
2181                          (funcall (%method-function before) args nil))
2182                        (multiple-value-prog1
2183                            (funcall method-function args next-emfun)
2184                          (dolist (after reverse-afters)
2185                            (funcall (%method-function after) args nil))))))))))
2186      (long-method-combination-p
2187       (let* ((mc-obj (get mc-name 'method-combination-object))
2188              (function (long-method-combination-function mc-obj))
2189              (arguments (rest (slot-value gf 'method-combination))))
2190         (assert (typep mc-obj 'long-method-combination))
2191         (assert function)
2192         (setf emf-form
2193               (if arguments
2194                   (apply function gf methods arguments)
2195                   (funcall function gf methods)))))
2196      (t
2197       (let ((mc-obj (get mc-name 'method-combination-object)))
2198         (unless (typep mc-obj 'short-method-combination)
2199           (error "Unsupported method combination type ~A."
2200                  mc-name))
2201         (let* ((operator (short-method-combination-operator mc-obj))
2202                (ioa (short-method-combination-identity-with-one-argument mc-obj)))
2203           (setf emf-form
2204                 (if (and (null (cdr primaries))
2205                          (not (null ioa)))
2206                     (generate-emf-lambda (%method-function (car primaries)) nil)
2207                     `(lambda (args)
2208                        (,operator ,@(mapcar
2209                                      (lambda (primary)
2210                                        `(funcall ,(%method-function primary) args nil))
2211                                      primaries)))))))))
2212    (assert (not (null emf-form)))
2213    (or #+nil (ignore-errors (autocompile emf-form))
2214        (coerce-to-function emf-form))))
2215
2216(defun generate-emf-lambda (method-function next-emfun)
2217  #'(lambda (args)
2218      (declare (optimize speed))
2219      (funcall method-function args next-emfun)))
2220
2221;;; compute an effective method function from a list of primary methods:
2222
2223(defun compute-primary-emfun (methods)
2224  (if (null methods)
2225      nil
2226      (let ((next-emfun (compute-primary-emfun (cdr methods))))
2227        #'(lambda (args)
2228           (funcall (%method-function (car methods)) args next-emfun)))))
2229
2230(defvar *call-next-method-p*)
2231(defvar *next-method-p-p*)
2232
2233(defun walk-form (form)
2234  (cond ((atom form)
2235         (cond ((eq form 'call-next-method)
2236                (setf *call-next-method-p* t))
2237               ((eq form 'next-method-p)
2238                (setf *next-method-p-p* t))))
2239        (t
2240         (walk-form (%car form))
2241         (walk-form (%cdr form)))))
2242
2243(defun compute-method-function (lambda-expression)
2244  (let ((lambda-list (allow-other-keys (cadr lambda-expression)))
2245        (body (cddr lambda-expression))
2246        (*call-next-method-p* nil)
2247        (*next-method-p-p* nil))
2248    (multiple-value-bind (body declarations) (parse-body body)
2249      (let ((ignorable-vars '()))
2250        (dolist (var lambda-list)
2251          (if (memq var lambda-list-keywords)
2252              (return)
2253              (push var ignorable-vars)))
2254        (push `(declare (ignorable ,@ignorable-vars)) declarations))
2255      (walk-form body)
2256      (cond ((or *call-next-method-p* *next-method-p-p*)
2257             `(lambda (args next-emfun)
2258                (flet ((call-next-method (&rest cnm-args)
2259                         (if (null next-emfun)
2260                             (error "No next method for generic function.")
2261                             (funcall next-emfun (or cnm-args args))))
2262                       (next-method-p ()
2263                         (not (null next-emfun))))
2264                  (declare (ignorable (function call-next-method)
2265                                      (function next-method-p)))
2266                  (apply #'(lambda ,lambda-list ,@declarations ,@body) args))))
2267            ((null (intersection lambda-list '(&rest &optional &key &allow-other-keys &aux)))
2268             ;; Required parameters only.
2269             (case (length lambda-list)
2270               (1
2271                `(lambda (args next-emfun)
2272                   (declare (ignore next-emfun))
2273                   (let ((,(%car lambda-list) (%car args)))
2274                     (declare (ignorable ,(%car lambda-list)))
2275                     ,@declarations ,@body)))
2276               (2
2277                `(lambda (args next-emfun)
2278                   (declare (ignore next-emfun))
2279                   (let ((,(%car lambda-list) (%car args))
2280                         (,(%cadr lambda-list) (%cadr args)))
2281                     (declare (ignorable ,(%car lambda-list)
2282                                         ,(%cadr lambda-list)))
2283                     ,@declarations ,@body)))
2284               (3
2285                `(lambda (args next-emfun)
2286                   (declare (ignore next-emfun))
2287                   (let ((,(%car lambda-list) (%car args))
2288                         (,(%cadr lambda-list) (%cadr args))
2289                         (,(%caddr lambda-list) (%caddr args)))
2290                     (declare (ignorable ,(%car lambda-list)
2291                                         ,(%cadr lambda-list)
2292                                         ,(%caddr lambda-list)))
2293                     ,@declarations ,@body)))
2294               (t
2295                `(lambda (args next-emfun)
2296                   (declare (ignore next-emfun))
2297                   (apply #'(lambda ,lambda-list ,@declarations ,@body) args)))))
2298            (t
2299             `(lambda (args next-emfun)
2300                (declare (ignore next-emfun))
2301                (apply #'(lambda ,lambda-list ,@declarations ,@body) args)))))))
2302
2303(defun compute-method-fast-function (lambda-expression)
2304  (let ((lambda-list (allow-other-keys (cadr lambda-expression))))
2305    (when (intersection lambda-list '(&rest &optional &key &allow-other-keys &aux))
2306      (return-from compute-method-fast-function nil))
2307    ;; Only required args.
2308    (let ((body (cddr lambda-expression))
2309          (*call-next-method-p* nil)
2310          (*next-method-p-p* nil))
2311      (multiple-value-bind (body declarations) (parse-body body)
2312        (walk-form body)
2313        (when (or *call-next-method-p* *next-method-p-p*)
2314          (return-from compute-method-fast-function nil))
2315        (let ((decls `(declare (ignorable ,@lambda-list))))
2316          (setf lambda-expression
2317                (list* (car lambda-expression)
2318                       (cadr lambda-expression)
2319                       decls
2320                       (cddr lambda-expression))))
2321        (case (length lambda-list)
2322          (1
2323;;            `(lambda (args next-emfun)
2324;;               (let ((,(%car lambda-list) (%car args)))
2325;;                 (declare (ignorable ,(%car lambda-list)))
2326;;                 ,@declarations ,@body)))
2327           lambda-expression)
2328          (2
2329;;            `(lambda (args next-emfun)
2330;;               (let ((,(%car lambda-list) (%car args))
2331;;                     (,(%cadr lambda-list) (%cadr args)))
2332;;                 (declare (ignorable ,(%car lambda-list)
2333;;                                     ,(%cadr lambda-list)))
2334;;                 ,@declarations ,@body)))
2335           lambda-expression)
2336;;           (3
2337;;            `(lambda (args next-emfun)
2338;;               (let ((,(%car lambda-list) (%car args))
2339;;                     (,(%cadr lambda-list) (%cadr args))
2340;;                     (,(%caddr lambda-list) (%caddr args)))
2341;;                 (declare (ignorable ,(%car lambda-list)
2342;;                                     ,(%cadr lambda-list)
2343;;                                     ,(%caddr lambda-list)))
2344;;                 ,@declarations ,@body)))
2345          (t
2346           nil))))))
2347
2348;; From CLHS section 7.6.5:
2349;; "When a generic function or any of its methods mentions &key in a lambda
2350;; list, the specific set of keyword arguments accepted by the generic function
2351;; varies according to the applicable methods. The set of keyword arguments
2352;; accepted by the generic function for a particular call is the union of the
2353;; keyword arguments accepted by all applicable methods and the keyword
2354;; arguments mentioned after &key in the generic function definition, if any."
2355;; Adapted from Sacla.
2356(defun allow-other-keys (lambda-list)
2357  (if (and (member '&key lambda-list)
2358           (not (member '&allow-other-keys lambda-list)))
2359      (let* ((key-end (or (position '&aux lambda-list) (length lambda-list)))
2360             (aux-part (subseq lambda-list key-end)))
2361        `(,@(subseq lambda-list 0 key-end) &allow-other-keys ,@aux-part))
2362      lambda-list))
2363
2364(defmacro defmethod (&rest args)
2365  (multiple-value-bind
2366      (function-name qualifiers lambda-list specializers documentation declarations body)
2367      (parse-defmethod args)
2368    (let* ((specializers-form '())
2369           (lambda-expression `(lambda ,lambda-list ,@declarations ,body))
2370           (method-function (compute-method-function lambda-expression))
2371           (fast-function (compute-method-fast-function lambda-expression))
2372           )
2373      (dolist (specializer specializers)
2374        (cond ((and (consp specializer) (eq (car specializer) 'eql))
2375               (push `(list 'eql ,(cadr specializer)) specializers-form))
2376              (t
2377               (push `',specializer specializers-form))))
2378      (setf specializers-form `(list ,@(nreverse specializers-form)))
2379      `(progn
2380         (ensure-method ',function-name
2381                        :lambda-list ',lambda-list
2382                        :qualifiers ',qualifiers
2383                        :specializers ,specializers-form
2384                        ,@(if documentation `(:documentation ,documentation))
2385                        :function (function ,method-function)
2386                        ,@(if fast-function `(:fast-function (function ,fast-function)))
2387                        )))))
2388
2389;;; Reader and writer methods
2390
2391(defun make-instance-standard-reader-method (gf
2392                                             &key
2393                                             lambda-list
2394                                             qualifiers
2395                                             specializers
2396                                             documentation
2397                                             function
2398                                             fast-function
2399                                             slot-name)
2400  (declare (ignore gf))
2401  (let ((method (std-allocate-instance +the-standard-reader-method-class+)))
2402    (setf (method-lambda-list method) lambda-list)
2403    (setf (method-qualifiers method) qualifiers)
2404    (%set-method-specializers method (canonicalize-specializers specializers))
2405    (setf (method-documentation method) documentation)
2406    (%set-method-generic-function method nil)
2407    (%set-method-function method function)
2408    (%set-method-fast-function method fast-function)
2409    (set-reader-method-slot-name method slot-name)
2410    method))
2411
2412(defun add-reader-method (class function-name slot-name)
2413  (let* ((lambda-expression
2414          (if (eq (class-of class) +the-standard-class+)
2415              `(lambda (object) (std-slot-value object ',slot-name))
2416              `(lambda (object) (slot-value object ',slot-name))))
2417         (method-function (compute-method-function lambda-expression))
2418         (fast-function (compute-method-fast-function lambda-expression)))
2419    (let ((method-lambda-list '(object))
2420          (gf (find-generic-function function-name nil)))
2421      (if gf
2422          (check-method-lambda-list function-name
2423                                    method-lambda-list
2424                                    (generic-function-lambda-list gf))
2425        (setf gf (ensure-generic-function function-name :lambda-list method-lambda-list)))
2426      (let ((method
2427             (make-instance-standard-reader-method gf
2428                                                   :lambda-list '(object)
2429                                                   :qualifiers ()
2430                                                   :specializers (list class)
2431                                                   :function (if (autoloadp 'compile)
2432                                                                 method-function
2433                                                                 (autocompile method-function))
2434                                                   :fast-function (if (autoloadp 'compile)
2435                                                                      fast-function
2436                                                                      (autocompile fast-function))
2437                                                   :slot-name slot-name)))
2438        (%add-method gf method)
2439        method))))
2440
2441(defun add-writer-method (class function-name slot-name)
2442  (let* ((lambda-expression
2443          (if (eq (class-of class) +the-standard-class+)
2444              `(lambda (new-value object)
2445                 (setf (std-slot-value object ',slot-name) new-value))
2446              `(lambda (new-value object)
2447                 (setf (slot-value object ',slot-name) new-value))))
2448         (method-function (compute-method-function lambda-expression))
2449         (fast-function (compute-method-fast-function lambda-expression))
2450         )
2451    (ensure-method function-name
2452                   :lambda-list '(new-value object)
2453                   :qualifiers ()
2454                   :specializers (list +the-T-class+ class)
2455;;                    :function `(function ,method-function)
2456                   :function (if (autoloadp 'compile)
2457                                 method-function
2458                                 (autocompile method-function))
2459                   :fast-function (if (autoloadp 'compile)
2460                                      fast-function
2461                                      (autocompile fast-function))
2462                   )))
2463
2464(defmacro atomic-defgeneric (function-name &rest rest)
2465  "Macro to define a generic function and 'swap it into place' after
2466it's been fully defined with all its methods.
2467
2468Note: the user should really use the (:method ..) method description
2469way of defining methods; there's not much use in atomically defining
2470generic functions without providing sensible behaviour..."
2471  (let ((temp-sym (gensym)))
2472    `(progn
2473       (defgeneric ,temp-sym ,@rest)
2474       (let ((gf (symbol-function ',temp-sym)))
2475         (setf ,(if (and (consp function-name)
2476                         (eq (car function-name) 'setf))
2477                    `(get ',(second function-name) 'setf-function)
2478                  `(symbol-function ',function-name)) gf)
2479         (%set-generic-function-name gf ',function-name)
2480         gf))))
2481
2482(defmacro redefine-class-forwarder (name slot)
2483  "Define a generic function on a temporary symbol as an accessor
2484for the slot `slot'. Then, when definition is complete (including
2485allocation of methods), swap the definition in place.
2486
2487Without this approach, we can't depend the old forwarders to be
2488in place, while we still need them to "
2489  (let* (($name (if (consp name) (cadr name) name))
2490         (%name (intern (concatenate 'string
2491                                     "%"
2492                                     (if (consp name)
2493                                         (symbol-name 'set-) "")
2494                                     (symbol-name $name))
2495                        (find-package "SYS"))))
2496    `(atomic-defgeneric ,name (;; splice a new-value parameter for setters
2497                               ,@(when (consp name) (list 'new-value))
2498                               class)
2499         ,@(mapcar (if (consp name)
2500                       #'(lambda (class-name)
2501                           `(:method (new-value (class ,class-name))
2502                              (,%name new-value class)))
2503                       #'(lambda (class-name)
2504                           `(:method ((class ,class-name))
2505                              (,%name class))))
2506                   '(built-in-class forward-referenced-class structure-class))
2507         ,@(mapcar #'(lambda (class-name)
2508                       `(:method (,@(when (consp name) (list 'new-value))
2509                                  (class ,class-name))
2510                          ,(if (consp name)
2511                               `(setf (slot-value class ',slot) new-value)
2512                               `(slot-value class ',slot))))
2513                   '(standard-class funcallable-standard-class)))))
2514
2515
2516(redefine-class-forwarder class-name name)
2517(redefine-class-forwarder (setf class-name) name)
2518(redefine-class-forwarder class-slots slots)
2519(redefine-class-forwarder (setf class-slots) slots)
2520(redefine-class-forwarder class-direct-slots direct-slots)
2521(redefine-class-forwarder (setf class-direct-slots) direct-slots)
2522(redefine-class-forwarder class-layout layout)
2523(redefine-class-forwarder (setf class-layout) layout)
2524(redefine-class-forwarder class-direct-superclasses direct-superclasses)
2525(redefine-class-forwarder (setf class-direct-superclasses) direct-superclasses)
2526(redefine-class-forwarder class-direct-subclasses direct-subclasses)
2527(redefine-class-forwarder (setf class-direct-subclasses) direct-subclasses)
2528(redefine-class-forwarder class-direct-methods direct-methods)
2529(redefine-class-forwarder (setf class-direct-methods) direct-methods)
2530(redefine-class-forwarder class-precedence-list precedence-list)
2531(redefine-class-forwarder (setf class-precedence-list) precedence-list)
2532(redefine-class-forwarder class-finalized-p finalized-p)
2533(redefine-class-forwarder (setf class-finalized-p) finalized-p)
2534(redefine-class-forwarder class-default-initargs default-initargs)
2535(redefine-class-forwarder (setf class-default-initargs) default-initargs)
2536(redefine-class-forwarder class-direct-default-initargs direct-default-initargs)
2537(redefine-class-forwarder (setf class-direct-default-initargs) direct-default-initargs)
2538
2539(defgeneric direct-slot-definition-class (class &rest initargs))
2540
2541(defmethod direct-slot-definition-class ((class class) &rest initargs)
2542  (declare (ignore initargs))
2543  +the-standard-direct-slot-definition-class+)
2544
2545(defgeneric effective-slot-definition-class (class &rest initargs))
2546
2547(defmethod effective-slot-definition-class ((class class) &rest initargs)
2548  (declare (ignore initargs))
2549  +the-standard-effective-slot-definition-class+)
2550
2551(atomic-defgeneric documentation (x doc-type)
2552    (:method ((x symbol) doc-type)
2553        (%documentation x doc-type))
2554    (:method ((x function) doc-type)
2555        (%documentation x doc-type)))
2556
2557(atomic-defgeneric (setf documentation) (new-value x doc-type)
2558    (:method (new-value (x symbol) doc-type)
2559        (%set-documentation x doc-type new-value))
2560    (:method (new-value (x function) doc-type)
2561        (%set-documentation x doc-type new-value)))
2562
2563
2564;; FIXME This should be a weak hashtable!
2565(defvar *list-documentation-hashtable* (make-hash-table :test #'equal))
2566
2567(defmethod documentation ((x list) (doc-type (eql 'function)))
2568  (let ((alist (gethash x *list-documentation-hashtable*)))
2569    (and alist (cdr (assoc doc-type alist)))))
2570
2571(defmethod documentation ((x list) (doc-type (eql 'compiler-macro)))
2572  (let ((alist (gethash x *list-documentation-hashtable*)))
2573    (and alist (cdr (assoc doc-type alist)))))
2574
2575(defmethod (setf documentation) (new-value (x list) (doc-type (eql 'function)))
2576  (let* ((alist (gethash x *list-documentation-hashtable*))
2577         (entry (and alist (assoc doc-type alist))))
2578    (cond (entry
2579           (setf (cdr entry) new-value))
2580          (t
2581           (setf (gethash x *list-documentation-hashtable*)
2582                 (push (cons doc-type new-value) alist)))))
2583  new-value)
2584
2585(defmethod (setf documentation) (new-value (x list) (doc-type (eql 'compiler-macro)))
2586  (let* ((alist (gethash x *list-documentation-hashtable*))
2587         (entry (and alist (assoc doc-type alist))))
2588    (cond (entry
2589           (setf (cdr entry) new-value))
2590          (t
2591           (setf (gethash x *list-documentation-hashtable*)
2592                 (push (cons doc-type new-value) alist)))))
2593  new-value)
2594
2595(defmethod documentation ((x class) (doc-type (eql 't)))
2596  (class-documentation x))
2597
2598(defmethod documentation ((x class) (doc-type (eql 'type)))
2599  (class-documentation x))
2600
2601(defmethod (setf documentation) (new-value (x class) (doc-type (eql 't)))
2602  (%set-class-documentation x new-value))
2603
2604(defmethod (setf documentation) (new-value (x class) (doc-type (eql 'type)))
2605  (%set-class-documentation x new-value))
2606
2607(defmethod documentation ((x structure-class) (doc-type (eql 't)))
2608  (%documentation x doc-type))
2609
2610(defmethod documentation ((x structure-class) (doc-type (eql 'type)))
2611  (%documentation x doc-type))
2612
2613(defmethod (setf documentation) (new-value (x structure-class) (doc-type (eql 't)))
2614  (%set-documentation x doc-type new-value))
2615
2616(defmethod (setf documentation) (new-value (x structure-class) (doc-type (eql 'type)))
2617  (%set-documentation x doc-type new-value))
2618
2619(defmethod documentation ((x standard-generic-function) (doc-type (eql 't)))
2620  (generic-function-documentation x))
2621
2622(defmethod (setf documentation) (new-value (x standard-generic-function) (doc-type (eql 't)))
2623  (setf (generic-function-documentation x) new-value))
2624
2625(defmethod documentation ((x standard-generic-function) (doc-type (eql 'function)))
2626  (generic-function-documentation x))
2627
2628(defmethod (setf documentation) (new-value (x standard-generic-function) (doc-type (eql 'function)))
2629  (setf (generic-function-documentation x) new-value))
2630
2631(defmethod documentation ((x standard-method) (doc-type (eql 't)))
2632  (method-documentation x))
2633
2634(defmethod (setf documentation) (new-value (x standard-method) (doc-type (eql 't)))
2635  (setf (method-documentation x) new-value))
2636
2637(defmethod documentation ((x package) (doc-type (eql 't)))
2638  (%documentation x doc-type))
2639
2640(defmethod (setf documentation) (new-value (x package) (doc-type (eql 't)))
2641  (%set-documentation x doc-type new-value))
2642
2643(defmethod documentation ((x symbol) (doc-type (eql 'function)))
2644  (%documentation x doc-type))
2645
2646;;; Applicable methods
2647
2648(defgeneric compute-applicable-methods (gf args)
2649  (:method ((gf standard-generic-function) args)
2650    (%compute-applicable-methods gf args)))
2651
2652(defgeneric compute-applicable-methods-using-classes (gf classes)
2653  (:method ((gf standard-generic-function) classes)
2654    (let ((methods '()))
2655      (dolist (method (generic-function-methods gf))
2656  (multiple-value-bind (applicable knownp)
2657      (method-applicable-using-classes-p method classes)
2658    (cond (applicable
2659     (push method methods))
2660    ((not knownp)
2661     (return-from compute-applicable-methods-using-classes
2662       (values nil nil))))))
2663      (values (sort-methods methods gf classes)
2664        t))))
2665
2666(export '(compute-applicable-methods
2667    compute-applicable-methods-using-classes))
2668
2669
2670;;; Slot access
2671
2672(defun set-slot-value-using-class (new-value class instance slot-name)
2673  (declare (ignore class)) ; FIXME
2674  (setf (std-slot-value instance slot-name) new-value))
2675
2676(defgeneric slot-value-using-class (class instance slot-name))
2677
2678(defmethod slot-value-using-class ((class standard-class) instance slot-name)
2679  (std-slot-value instance slot-name))
2680(defmethod slot-value-using-class ((class funcallable-standard-class)
2681                                   instance slot-name)
2682  (std-slot-value instance slot-name))
2683(defmethod slot-value-using-class ((class structure-class) instance slot-name)
2684  (std-slot-value instance slot-name))
2685
2686(defgeneric (setf slot-value-using-class) (new-value class instance slot-name))
2687
2688(defmethod (setf slot-value-using-class) (new-value
2689                                          (class standard-class)
2690                                          instance
2691                                          slot-name)
2692  (setf (std-slot-value instance slot-name) new-value))
2693
2694(defmethod (setf slot-value-using-class) (new-value
2695                                          (class funcallable-standard-class)
2696                                          instance
2697                                          slot-name)
2698  (setf (std-slot-value instance slot-name) new-value))
2699
2700(defmethod (setf slot-value-using-class) (new-value
2701                                          (class structure-class)
2702                                          instance
2703                                          slot-name)
2704  (setf (std-slot-value instance slot-name) new-value))
2705
2706(defgeneric slot-exists-p-using-class (class instance slot-name))
2707
2708(defmethod slot-exists-p-using-class (class instance slot-name)
2709  nil)
2710
2711(defmethod slot-exists-p-using-class ((class standard-class) instance slot-name)
2712  (std-slot-exists-p instance slot-name))
2713(defmethod slot-exists-p-using-class ((class funcallable-standard-class) instance slot-name)
2714  (std-slot-exists-p instance slot-name))
2715
2716(defmethod slot-exists-p-using-class ((class structure-class) instance slot-name)
2717  (dolist (dsd (class-slots class))
2718    (when (eq (sys::dsd-name dsd) slot-name)
2719      (return-from slot-exists-p-using-class t)))
2720  nil)
2721
2722(defgeneric slot-boundp-using-class (class instance slot-name))
2723(defmethod slot-boundp-using-class ((class standard-class) instance slot-name)
2724  (std-slot-boundp instance slot-name))
2725(defmethod slot-boundp-using-class ((class funcallable-standard-class) instance slot-name)
2726  (std-slot-boundp instance slot-name))
2727(defmethod slot-boundp-using-class ((class structure-class) instance slot-name)
2728  "Structure slots can't be unbound, so this method always returns T."
2729  (declare (ignore class instance slot-name))
2730  t)
2731
2732(defgeneric slot-makunbound-using-class (class instance slot-name))
2733(defmethod slot-makunbound-using-class ((class standard-class)
2734                                        instance
2735                                        slot-name)
2736  (std-slot-makunbound instance slot-name))
2737(defmethod slot-makunbound-using-class ((class funcallable-standard-class)
2738                                        instance
2739                                        slot-name)
2740  (std-slot-makunbound instance slot-name))
2741(defmethod slot-makunbound-using-class ((class structure-class)
2742                                        instance
2743                                        slot-name)
2744  (declare (ignore class instance slot-name))
2745  (error "Structure slots can't be unbound"))
2746
2747(defgeneric slot-missing (class instance slot-name operation &optional new-value))
2748
2749(defmethod slot-missing ((class t) instance slot-name operation &optional new-value)
2750  (declare (ignore new-value))
2751  (error "The slot ~S is missing from the class ~S." slot-name class))
2752
2753(defgeneric slot-unbound (class instance slot-name))
2754
2755(defmethod slot-unbound ((class t) instance slot-name)
2756  (error 'unbound-slot :instance instance :name slot-name))
2757
2758;;; Instance creation and initialization
2759
2760(defgeneric allocate-instance (class &rest initargs &key &allow-other-keys))
2761
2762(defmethod allocate-instance ((class standard-class) &rest initargs)
2763  (declare (ignore initargs))
2764  (std-allocate-instance class))
2765
2766(defmethod allocate-instance ((class funcallable-standard-class) &rest initargs)
2767  (declare (ignore initargs))
2768  (allocate-funcallable-instance class))
2769
2770(defmethod allocate-instance ((class structure-class) &rest initargs)
2771  (declare (ignore initargs))
2772  (%make-structure (class-name class)
2773                   (make-list (length (class-slots class))
2774                              :initial-element +slot-unbound+)))
2775
2776;; "The set of valid initialization arguments for a class is the set of valid
2777;; initialization arguments that either fill slots or supply arguments to
2778;; methods, along with the predefined initialization argument :ALLOW-OTHER-KEYS."
2779;; 7.1.2
2780
2781(defun calculate-allowable-initargs (gf-list args instance
2782                                             shared-initialize-param
2783                                             initargs)
2784  (let* ((methods
2785          (nconc
2786             (compute-applicable-methods #'shared-initialize
2787                                         (list* instance
2788                                                shared-initialize-param
2789                                                initargs))
2790             (mapcan #'(lambda (gf)
2791                         (compute-applicable-methods gf args))
2792                     gf-list)))
2793         (method-keyword-args
2794          (reduce #'merge-initargs-sets
2795                  (mapcar #'method-lambda-list methods)
2796                  :key #'extract-lambda-list-keywords
2797                  :initial-value nil))
2798         (slots-initargs
2799          (mapappend #'slot-definition-initargs
2800                     (class-slots (class-of instance)))))
2801    (merge-initargs-sets
2802     (merge-initargs-sets slots-initargs method-keyword-args)
2803     '(:allow-other-keys))))  ;; allow-other-keys is always allowed
2804
2805(defun check-initargs (gf-list args instance
2806                       shared-initialize-param initargs
2807                       cache call-site)
2808  "Checks the validity of `initargs' for the generic functions in `gf-list'
2809when called with `args' by calculating the applicable methods for each gf.
2810The applicable methods for SHARED-INITIALIZE based on `instance',
2811`shared-initialize-param' and `initargs' are added to the list of
2812applicable methods."
2813  (when (oddp (length initargs))
2814    (error 'program-error
2815           :format-control "Odd number of keyword arguments."))
2816  (unless (getf initargs :allow-other-keys)
2817    (multiple-value-bind (allowable-initargs present-p)
2818                         (when cache
2819                           (gethash (class-of instance) cache))
2820       (unless present-p
2821         (setf allowable-initargs
2822               (calculate-allowable-initargs gf-list args instance
2823                                             shared-initialize-param initargs))
2824         (when cache
2825           (setf (gethash (class-of instance) cache)
2826                 allowable-initargs)))
2827       (unless (eq t allowable-initargs)
2828         (do* ((tail initargs (cddr tail))
2829               (initarg (car tail) (car tail)))
2830              ((null tail))
2831              (unless (memq initarg allowable-initargs)
2832                (error 'program-error
2833                       :format-control "Invalid initarg ~S in call to ~S ~
2834with arglist ~S."
2835                       :format-arguments (list initarg call-site args))))))))
2836
2837(defun merge-initargs-sets (list1 list2)
2838  (cond
2839   ((eq list1 t)  t)
2840   ((eq list2 t)  t)
2841   (t             (union list1 list2))))
2842
2843(defun extract-lambda-list-keywords (lambda-list)
2844  "Returns a list of keywords acceptable as keyword arguments,
2845or T when any keyword is acceptable due to presence of
2846&allow-other-keys."
2847  (when (member '&allow-other-keys lambda-list)
2848    (return-from extract-lambda-list-keywords t))
2849  (loop with keyword-args = (cdr (memq '&key lambda-list))
2850        for key in keyword-args
2851        when (eq key '&aux) do (loop-finish)
2852        when (eq key '&allow-other-keys) do (return t)
2853        when (listp key) do (setq key (car key))
2854        collect (if (symbolp key)
2855                    (make-keyword key)
2856                  (car key))))
2857
2858
2859(defgeneric make-instance (class &rest initargs &key &allow-other-keys))
2860
2861(defmethod make-instance :before ((class class) &rest initargs)
2862  (when (oddp (length initargs))
2863    (error 'program-error :format-control "Odd number of keyword arguments."))
2864  (unless (class-finalized-p class)
2865    (finalize-inheritance class)))
2866
2867(defun augment-initargs-with-defaults (class initargs)
2868  (let ((default-initargs '()))
2869    (do* ((list (class-default-initargs class) (cddr list))
2870          (key (car list) (car list))
2871          (fn (cadr list) (cadr list)))
2872         ((null list))
2873      (when (eq (getf initargs key 'not-found) 'not-found)
2874        (setf default-initargs (append default-initargs (list key (funcall fn))))))
2875    (append initargs default-initargs)))
2876
2877(defmethod make-instance ((class standard-class) &rest initargs)
2878  (setf initargs (augment-initargs-with-defaults class initargs))
2879  (let ((instance (std-allocate-instance class)))
2880    (check-initargs (list #'allocate-instance #'initialize-instance)
2881                    (list* instance initargs)
2882                    instance t initargs
2883                    *make-instance-initargs-cache* 'make-instance)
2884    (apply #'initialize-instance instance initargs)
2885    instance))
2886
2887(defmethod make-instance ((class funcallable-standard-class) &rest initargs)
2888  (setf initargs (augment-initargs-with-defaults class initargs))
2889  (let ((instance (allocate-funcallable-instance class)))
2890    (check-initargs (list #'allocate-instance #'initialize-instance)
2891                    (list* instance initargs)
2892                    instance t initargs
2893                    *make-instance-initargs-cache* 'make-instance)
2894    (apply #'initialize-instance instance initargs)
2895    instance))
2896
2897(defmethod make-instance ((class symbol) &rest initargs)
2898  (apply #'make-instance (find-class class) initargs))
2899
2900(defgeneric initialize-instance (instance &rest initargs
2901                                          &key &allow-other-keys))
2902
2903(defmethod initialize-instance ((instance standard-object) &rest initargs)
2904  (apply #'shared-initialize instance t initargs))
2905
2906(defgeneric reinitialize-instance (instance &rest initargs
2907                                            &key &allow-other-keys))
2908
2909;; "The system-supplied primary method for REINITIALIZE-INSTANCE checks the
2910;; validity of initargs and signals an error if an initarg is supplied that is
2911;; not declared as valid. The method then calls the generic function SHARED-
2912;; INITIALIZE with the following arguments: the instance, nil (which means no
2913;; slots should be initialized according to their initforms), and the initargs
2914;; it received."
2915(defmethod reinitialize-instance ((instance standard-object) &rest initargs)
2916  (check-initargs (list #'reinitialize-instance) (list* instance initargs)
2917                  instance () initargs
2918                  *reinitialize-instance-initargs-cache* 'reinitialize-instance)
2919  (apply #'shared-initialize instance () initargs))
2920
2921(defun std-shared-initialize (instance slot-names all-keys)
2922  (when (oddp (length all-keys))
2923    (error 'program-error :format-control "Odd number of keyword arguments."))
2924  ;; do a quick scan of the arguments list to see if it's a real
2925  ;; 'initialization argument list' (which is not the same as
2926  ;; checking initarg validity
2927  (do* ((tail all-keys (cddr tail))
2928        (initarg (car tail) (car tail)))
2929      ((null tail))
2930    (unless (symbolp initarg)
2931      (error 'program-error
2932             :format-control "Initarg ~S not a symbol."
2933             :format-arguments (list initarg))))
2934  (dolist (slot (class-slots (class-of instance)))
2935    (let ((slot-name (slot-definition-name slot)))
2936      (multiple-value-bind (init-key init-value foundp)
2937          (get-properties all-keys (slot-definition-initargs slot))
2938        (if foundp
2939            (setf (std-slot-value instance slot-name) init-value)
2940            (unless (std-slot-boundp instance slot-name)
2941              (let ((initfunction (slot-definition-initfunction slot)))
2942                (when (and initfunction (or (eq slot-names t)
2943                                            (memq slot-name slot-names)))
2944                  (setf (std-slot-value instance slot-name)
2945                        (funcall initfunction)))))))))
2946  instance)
2947
2948(defgeneric shared-initialize (instance slot-names
2949                                        &rest initargs
2950                                        &key &allow-other-keys))
2951
2952(defmethod shared-initialize ((instance standard-object) slot-names &rest initargs)
2953  (std-shared-initialize instance slot-names initargs))
2954
2955(defmethod shared-initialize ((slot slot-definition) slot-names
2956                              &rest args
2957                              &key name initargs initform initfunction
2958                              readers writers allocation
2959                              &allow-other-keys)
2960  ;;Keyword args are duplicated from init-slot-definition only to have
2961  ;;them checked.
2962  (declare (ignore slot-names)) ;;TODO?
2963  (declare (ignore name initargs initform initfunction readers writers allocation))
2964  ;;For built-in slots
2965  (apply #'init-slot-definition slot :allow-other-keys t args)
2966  ;;For user-defined slots
2967  (call-next-method))
2968
2969;;; change-class
2970
2971(defgeneric change-class (instance new-class &key &allow-other-keys))
2972
2973(defmethod change-class ((old-instance standard-object) (new-class standard-class)
2974                         &rest initargs)
2975  (let ((old-slots (class-slots (class-of old-instance)))
2976        (new-slots (class-slots new-class))
2977        (new-instance (allocate-instance new-class)))
2978    ;; "The values of local slots specified by both the class CTO and the class
2979    ;; CFROM are retained. If such a local slot was unbound, it remains
2980    ;; unbound."
2981    (dolist (new-slot new-slots)
2982      (when (instance-slot-p new-slot)
2983        (let* ((slot-name (slot-definition-name new-slot))
2984               (old-slot (find slot-name old-slots :key 'slot-definition-name)))
2985          ;; "The values of slots specified as shared in the class CFROM and as
2986          ;; local in the class CTO are retained."
2987          (when (and old-slot (slot-boundp old-instance slot-name))
2988            (setf (slot-value new-instance slot-name)
2989                  (slot-value old-instance slot-name))))))
2990    (swap-slots old-instance new-instance)
2991    (rotatef (std-instance-layout new-instance)
2992             (std-instance-layout old-instance))
2993    (apply #'update-instance-for-different-class
2994           new-instance old-instance initargs)
2995    old-instance))
2996
2997(defmethod change-class ((instance standard-object) (new-class symbol) &rest initargs)
2998  (apply #'change-class instance (find-class new-class) initargs))
2999
3000(defgeneric update-instance-for-different-class (old new
3001                                                     &rest initargs
3002                                                     &key &allow-other-keys))
3003
3004(defmethod update-instance-for-different-class
3005  ((old standard-object) (new standard-object) &rest initargs)
3006  (let ((added-slots
3007         (remove-if #'(lambda (slot-name)
3008                       (slot-exists-p old slot-name))
3009                    (mapcar 'slot-definition-name
3010                            (class-slots (class-of new))))))
3011    (check-initargs (list #'update-instance-for-different-class)
3012                    (list old new initargs)
3013                    new added-slots initargs
3014                    nil 'update-instance-for-different-class)
3015    (apply #'shared-initialize new added-slots initargs)))
3016
3017;;; make-instances-obsolete
3018
3019(defgeneric make-instances-obsolete (class))
3020
3021(defmethod make-instances-obsolete ((class standard-class))
3022  (%make-instances-obsolete class))
3023(defmethod make-instances-obsolete ((class funcallable-standard-class))
3024  (%make-instances-obsolete class))
3025(defmethod make-instances-obsolete ((class symbol))
3026  (make-instances-obsolete (find-class class))
3027  class)
3028
3029;;; update-instance-for-redefined-class
3030
3031(defgeneric update-instance-for-redefined-class (instance
3032                                                 added-slots
3033                                                 discarded-slots
3034                                                 property-list
3035                                                 &rest initargs
3036                                                 &key
3037                                                 &allow-other-keys))
3038
3039(defmethod update-instance-for-redefined-class ((instance standard-object)
3040            added-slots
3041            discarded-slots
3042            property-list
3043            &rest initargs)
3044  (check-initargs (list #'update-instance-for-redefined-class)
3045                  (list* instance added-slots discarded-slots
3046                         property-list initargs)
3047                  instance added-slots initargs
3048                  nil 'update-instance-for-redefined-class)
3049  (apply #'shared-initialize instance added-slots initargs))
3050
3051;;;  Methods having to do with class metaobjects.
3052
3053(defmethod initialize-instance :after ((class standard-class) &rest args)
3054  (apply #'std-after-initialization-for-classes class args))
3055
3056(defmethod initialize-instance :after ((class funcallable-standard-class)
3057                                       &rest args)
3058  (apply #'std-after-initialization-for-classes class args))
3059
3060(defmethod reinitialize-instance :after ((class standard-class) &rest all-keys)
3061  (remhash class *make-instance-initargs-cache*)
3062  (remhash class *reinitialize-instance-initargs-cache*)
3063  (%make-instances-obsolete class)
3064  (setf (class-finalized-p class) nil)
3065  (check-initargs (list #'allocate-instance
3066                        #'initialize-instance)
3067                  (list* class all-keys)
3068                  class t all-keys
3069                  nil 'reinitialize-instance)
3070  (apply #'std-after-initialization-for-classes class all-keys))
3071
3072;;; Finalize inheritance
3073
3074(atomic-defgeneric finalize-inheritance (class)
3075    (:method ((class standard-class))
3076       (std-finalize-inheritance class))
3077    (:method ((class funcallable-standard-class))
3078       (std-finalize-inheritance class)))
3079
3080;;; Class precedence lists
3081
3082(defgeneric compute-class-precedence-list (class))
3083(defmethod compute-class-precedence-list ((class standard-class))
3084  (std-compute-class-precedence-list class))
3085(defmethod compute-class-precedence-list ((class funcallable-standard-class))
3086  (std-compute-class-precedence-list class))
3087
3088;;; Slot inheritance
3089
3090(defgeneric compute-slots (class))
3091(defmethod compute-slots ((class standard-class))
3092  (std-compute-slots class))
3093(defmethod compute-slots ((class funcallable-standard-class))
3094  (std-compute-slots class))
3095
3096(defgeneric compute-effective-slot-definition (class name direct-slots))
3097(defmethod compute-effective-slot-definition
3098  ((class standard-class) name direct-slots)
3099  (std-compute-effective-slot-definition class name direct-slots))
3100(defmethod compute-effective-slot-definition
3101  ((class funcallable-standard-class) name direct-slots)
3102  (std-compute-effective-slot-definition class name direct-slots))
3103;;; Methods having to do with generic function metaobjects.
3104
3105(defmethod initialize-instance :after ((gf standard-generic-function) &key)
3106  (finalize-generic-function gf))
3107
3108;;; Methods having to do with generic function invocation.
3109
3110(defgeneric compute-discriminating-function (gf))
3111(defmethod compute-discriminating-function ((gf standard-generic-function))
3112  (std-compute-discriminating-function gf))
3113
3114(defgeneric method-more-specific-p (gf method1 method2 required-classes))
3115
3116(defmethod method-more-specific-p ((gf standard-generic-function)
3117                                   method1 method2 required-classes)
3118  (std-method-more-specific-p method1 method2 required-classes
3119                              (generic-function-argument-precedence-order gf)))
3120
3121;;; XXX AMOP has COMPUTE-EFFECTIVE-METHOD
3122(defgeneric compute-effective-method-function (gf methods))
3123(defmethod compute-effective-method-function ((gf standard-generic-function) methods)
3124  (std-compute-effective-method-function gf methods))
3125
3126(defgeneric compute-applicable-methods (gf args))
3127(defmethod compute-applicable-methods ((gf standard-generic-function) args)
3128  (%compute-applicable-methods gf args))
3129
3130;;; Slot definition accessors
3131
3132(defmacro slot-definition-dispatch (slot-definition std-form generic-form)
3133  `(let (($cl (class-of ,slot-definition)))
3134     (case $cl
3135       ((+the-standard-slot-definition-class+
3136         +the-standard-direct-slot-definition-class+
3137         +the-standard-effective-slot-definition-class+)
3138        ,std-form)
3139       (t ,generic-form))))
3140
3141(atomic-defgeneric slot-definition-allocation (slot-definition)
3142  (:method ((slot-definition slot-definition))
3143    (slot-definition-dispatch slot-definition
3144      (%slot-definition-allocation slot-definition)
3145      (slot-value slot-definition 'sys::allocation))))
3146
3147(atomic-defgeneric (setf slot-definition-allocation) (value slot-definition)
3148  (:method (value (slot-definition slot-definition))
3149    (slot-definition-dispatch slot-definition
3150      (set-slot-definition-allocation slot-definition value)
3151      (setf (slot-value slot-definition 'sys::allocation) value))))
3152
3153(atomic-defgeneric slot-definition-initargs (slot-definition)
3154  (:method ((slot-definition slot-definition))
3155    (slot-definition-dispatch slot-definition
3156      (%slot-definition-initargs slot-definition)
3157      (slot-value slot-definition 'sys::initargs))))
3158
3159(atomic-defgeneric slot-definition-initform (slot-definition)
3160  (:method ((slot-definition slot-definition))
3161    (slot-definition-dispatch slot-definition
3162      (%slot-definition-initform slot-definition)
3163      (slot-value slot-definition 'sys::initform))))
3164
3165(atomic-defgeneric (setf slot-definition-initform) (value slot-definition)
3166  (:method (value (slot-definition slot-definition))
3167    (slot-definition-dispatch slot-definition
3168      (set-slot-definition-initform slot-definition value)
3169      (setf (slot-value slot-definition 'sys::initform) value))))
3170
3171(atomic-defgeneric slot-definition-initfunction (slot-definition)
3172  (:method ((slot-definition slot-definition))
3173    (slot-definition-dispatch slot-definition
3174      (%slot-definition-initfunction slot-definition)
3175      (slot-value slot-definition 'sys::initfunction))))
3176
3177(atomic-defgeneric (setf slot-definition-initfunction) (value slot-definition)
3178  (:method (value (slot-definition slot-definition))
3179    (slot-definition-dispatch slot-definition
3180      (set-slot-definition-initfunction slot-definition value)
3181      (setf (slot-value slot-definition 'sys::initfunction) value))))
3182
3183(atomic-defgeneric slot-definition-name (slot-definition)
3184  (:method ((slot-definition slot-definition))
3185    (slot-definition-dispatch slot-definition
3186      (%slot-definition-name slot-definition)
3187      (slot-value slot-definition 'sys::name))))
3188
3189(atomic-defgeneric (setf slot-definition-name) (value slot-definition)
3190  (:method (value (slot-definition slot-definition))
3191    (slot-definition-dispatch slot-definition
3192      (set-slot-definition-name slot-definition value)
3193      (setf (slot-value slot-definition 'sys::name) value))))
3194
3195(atomic-defgeneric slot-definition-readers (slot-definition)
3196  (:method ((slot-definition slot-definition))
3197    (slot-definition-dispatch slot-definition
3198      (%slot-definition-readers slot-definition)
3199      (slot-value slot-definition 'sys::readers))))
3200
3201(atomic-defgeneric (setf slot-definition-readers) (value slot-definition)
3202  (:method (value (slot-definition slot-definition))
3203    (slot-definition-dispatch slot-definition
3204      (set-slot-definition-readers slot-definition value)
3205      (setf (slot-value slot-definition 'sys::readers) value))))
3206
3207(atomic-defgeneric slot-definition-writers (slot-definition)
3208  (:method ((slot-definition slot-definition))
3209    (slot-definition-dispatch slot-definition
3210      (%slot-definition-writers slot-definition)
3211      (slot-value slot-definition 'sys::writers))))
3212
3213(atomic-defgeneric (setf slot-definition-writers) (value slot-definition)
3214  (:method (value (slot-definition slot-definition))
3215    (slot-definition-dispatch slot-definition
3216      (set-slot-definition-writers slot-definition value)
3217      (setf (slot-value slot-definition 'sys::writers) value))))
3218
3219(atomic-defgeneric slot-definition-allocation-class (slot-definition)
3220  (:method ((slot-definition slot-definition))
3221    (slot-definition-dispatch slot-definition
3222      (%slot-definition-allocation-class slot-definition)
3223      (slot-value slot-definition 'sys::allocation-class))))
3224
3225(atomic-defgeneric (setf slot-definition-allocation-class)
3226                       (value slot-definition)
3227  (:method (value (slot-definition slot-definition))
3228    (slot-definition-dispatch slot-definition
3229      (set-slot-definition-allocation-class slot-definition value)
3230      (setf (slot-value slot-definition 'sys::allocation-class) value))))
3231
3232(atomic-defgeneric slot-definition-location (slot-definition)
3233  (:method ((slot-definition slot-definition))
3234    (slot-definition-dispatch slot-definition
3235      (%slot-definition-location slot-definition)
3236      (slot-value slot-definition 'sys::location))))
3237
3238(atomic-defgeneric (setf slot-definition-location) (value slot-definition)
3239  (:method (value (slot-definition slot-definition))
3240    (slot-definition-dispatch slot-definition
3241      (set-slot-definition-location slot-definition value)
3242      (setf (slot-value slot-definition 'sys::location) value))))
3243
3244;;; No %slot-definition-type.
3245
3246
3247;;; Conditions.
3248
3249(defmacro define-condition (name (&rest parent-types) (&rest slot-specs) &body options)
3250  (let ((parent-types (or parent-types '(condition)))
3251        (report nil))
3252    (dolist (option options)
3253      (when (eq (car option) :report)
3254        (setf report (cadr option))
3255  (setf options (delete option options :test #'equal))
3256        (return)))
3257    (typecase report
3258      (null
3259       `(progn
3260          (defclass ,name ,parent-types ,slot-specs ,@options)
3261          ',name))
3262      (string
3263       `(progn
3264          (defclass ,name ,parent-types ,slot-specs ,@options)
3265          (defmethod print-object ((condition ,name) stream)
3266            (if *print-escape*
3267                (call-next-method)
3268                (progn (write-string ,report stream) condition)))
3269          ',name))
3270      (t
3271       `(progn
3272          (defclass ,name ,parent-types ,slot-specs ,@options)
3273          (defmethod print-object ((condition ,name) stream)
3274            (if *print-escape*
3275                (call-next-method)
3276                (funcall #',report condition stream)))
3277          ',name)))))
3278
3279(defun make-condition (type &rest initargs)
3280  (or (%make-condition type initargs)
3281      (let ((class (if (symbolp type) (find-class type) type)))
3282        (apply #'make-instance class initargs))))
3283
3284;; Adapted from SBCL.
3285;; Originally defined in signal.lisp. Redefined here now that we have MAKE-CONDITION.
3286(defun coerce-to-condition (datum arguments default-type fun-name)
3287  (cond ((typep datum 'condition)
3288         (when arguments
3289           (error 'simple-type-error
3290                  :datum arguments
3291                  :expected-type 'null
3292                  :format-control "You may not supply additional arguments when giving ~S to ~S."
3293                  :format-arguments (list datum fun-name)))
3294         datum)
3295        ((symbolp datum)
3296         (apply #'make-condition datum arguments))
3297        ((or (stringp datum) (functionp datum))
3298         (make-condition default-type
3299                         :format-control datum
3300                         :format-arguments arguments))
3301        (t
3302         (error 'simple-type-error
3303                :datum datum
3304                :expected-type '(or symbol string)
3305                :format-control "Bad argument to ~S: ~S."
3306                :format-arguments (list fun-name datum)))))
3307
3308(defgeneric make-load-form (object &optional environment))
3309
3310(defmethod make-load-form ((object t) &optional environment)
3311  (declare (ignore environment))
3312  (apply #'no-applicable-method #'make-load-form (list object)))
3313
3314(defmethod make-load-form ((class class) &optional environment)
3315  (declare (ignore environment))
3316  (let ((name (class-name class)))
3317    (unless (and name (eq (find-class name nil) class))
3318      (error 'simple-type-error
3319             :format-control "Can't use anonymous or undefined class as a constant: ~S."
3320             :format-arguments (list class)))
3321    `(find-class ',name)))
3322
3323(defun invalid-method-error (method format-control &rest args)
3324  (let ((message (apply #'format nil format-control args)))
3325    (error "Invalid method error for ~S:~%    ~A" method message)))
3326
3327(defun method-combination-error (format-control &rest args)
3328  (let ((message (apply #'format nil format-control args)))
3329    (error "Method combination error in CLOS dispatch:~%    ~A" message)))
3330
3331
3332(atomic-defgeneric no-applicable-method (generic-function &rest args)
3333  (:method (generic-function &rest args)
3334      (error "There is no applicable method for the generic function ~S ~
3335              when called with arguments ~S."
3336             generic-function
3337             args)))
3338
3339
3340
3341(defgeneric find-method (generic-function
3342                         qualifiers
3343                         specializers
3344                         &optional errorp))
3345
3346(defmethod find-method ((generic-function standard-generic-function)
3347                        qualifiers specializers &optional (errorp t))
3348  (%find-method generic-function qualifiers specializers errorp))
3349
3350(defgeneric add-method (generic-function method))
3351
3352(defmethod add-method ((generic-function standard-generic-function)
3353                       (method method))
3354  (let ((method-lambda-list (method-lambda-list method))
3355        (gf-lambda-list (generic-function-lambda-list generic-function)))
3356    (check-method-lambda-list (%generic-function-name generic-function)
3357                              method-lambda-list gf-lambda-list))
3358  (%add-method generic-function method))
3359
3360(defgeneric remove-method (generic-function method))
3361
3362(defmethod remove-method ((generic-function standard-generic-function) method)
3363  (%remove-method generic-function method))
3364
3365;; See describe.lisp.
3366(defgeneric describe-object (object stream))
3367
3368;; FIXME
3369(defgeneric no-next-method (generic-function method &rest args))
3370
3371(atomic-defgeneric function-keywords (method)
3372  (:method ((method standard-method))
3373    (%function-keywords method)))
3374
3375
3376(setf *gf-initialize-instance* (symbol-function 'initialize-instance))
3377(setf *gf-allocate-instance* (symbol-function 'allocate-instance))
3378(setf *gf-shared-initialize* (symbol-function 'shared-initialize))
3379(setf *gf-reinitialize-instance* (symbol-function 'reinitialize-instance))
3380(setf *clos-booting* nil)
3381
3382(defgeneric class-prototype (class))
3383
3384(defmethod class-prototype :before (class)
3385  (unless (class-finalized-p class)
3386    (error "~@<~S is not finalized.~:@>" class)))
3387
3388(defmethod class-prototype ((class standard-class))
3389  (allocate-instance class))
3390
3391(defmethod class-prototype ((class funcallable-standard-class))
3392  (allocate-instance class))
3393
3394(defmethod class-prototype ((class structure-class))
3395  (allocate-instance class))
3396
3397;;; Readers for generic function metaobjects
3398;;; See AMOP pg. 216ff.
3399(atomic-defgeneric generic-function-argument-precedence-order (generic-function)
3400  (:method ((generic-function standard-generic-function))
3401    (sys:%generic-function-argument-precedence-order generic-function)))
3402
3403(atomic-defgeneric generic-function-declarations (generic-function)
3404  (:method ((generic-function standard-generic-function))
3405    ;; TODO: add slot to StandardGenericFunctionClass.java, use it
3406    nil))
3407
3408(atomic-defgeneric generic-function-lambda-list (generic-function)
3409  (:method ((generic-function standard-generic-function))
3410    (sys:%generic-function-lambda-list generic-function)))
3411
3412(atomic-defgeneric generic-function-method-class (generic-function)
3413  (:method ((generic-function standard-generic-function))
3414    (sys:%generic-function-method-class generic-function)))
3415
3416(atomic-defgeneric generic-function-method-combination (generic-function)
3417  (:method ((generic-function standard-generic-function))
3418    (sys:%generic-function-method-combination generic-function)))
3419
3420(atomic-defgeneric generic-function-methods (generic-function)
3421  (:method ((generic-function standard-generic-function))
3422    (sys:%generic-function-methods generic-function)))
3423
3424(atomic-defgeneric generic-function-name (generic-function)
3425  (:method ((generic-function standard-generic-function))
3426    (sys:%generic-function-name generic-function)))
3427
3428(eval-when (:compile-toplevel :load-toplevel :execute)
3429  (require "MOP"))
3430
3431(provide 'clos)
3432
Note: See TracBrowser for help on using the repository browser.