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

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

Convert EQL-SPECIALIZER from a structure into a CLOS class.

From rudi at constantly.

Backout creation of Specializer.java and Equalizer.java (do it all in
Lisp).

From: Rudi Schlatte <rudi@…>
Date: Wed, 4 Jan 2012 17:22:59 +0100
Subject: [PATCH] Convert EQL-SPECIALIZER from a structure into a CLOS class.

... open-code make-instance machinery in intern-eql-specializer to break

circular dependency between it and generic functions working

... also remove unused Java classes for metaobject and

specializer introduced in previous patches (Java-side, they
are just instances of StandardClass?).

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