0.9.11.45:
[sbcl.git] / src / pcl / std-class.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3
4 ;;;; This software is derived from software originally released by Xerox
5 ;;;; Corporation. Copyright and release statements follow. Later modifications
6 ;;;; to the software are in the public domain and are provided with
7 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
8 ;;;; information.
9
10 ;;;; copyright information from original PCL sources:
11 ;;;;
12 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
13 ;;;; All rights reserved.
14 ;;;;
15 ;;;; Use and copying of this software and preparation of derivative works based
16 ;;;; upon this software are permitted. Any distribution of this software or
17 ;;;; derivative works must comply with all applicable United States export
18 ;;;; control laws.
19 ;;;;
20 ;;;; This software is made available AS IS, and Xerox Corporation makes no
21 ;;;; warranty about the software, its performance or its conformity to any
22 ;;;; specification.
23
24 (in-package "SB-PCL")
25 \f
26 (defmethod slot-accessor-function ((slotd effective-slot-definition) type)
27   (ecase type
28     (reader (slot-definition-reader-function slotd))
29     (writer (slot-definition-writer-function slotd))
30     (boundp (slot-definition-boundp-function slotd))))
31
32 (defmethod (setf slot-accessor-function) (function
33                                           (slotd effective-slot-definition)
34                                           type)
35   (ecase type
36     (reader (setf (slot-definition-reader-function slotd) function))
37     (writer (setf (slot-definition-writer-function slotd) function))
38     (boundp (setf (slot-definition-boundp-function slotd) function))))
39
40 (defconstant +slotd-reader-function-std-p+ 1)
41 (defconstant +slotd-writer-function-std-p+ 2)
42 (defconstant +slotd-boundp-function-std-p+ 4)
43 (defconstant +slotd-all-function-std-p+ 7)
44
45 (defmethod slot-accessor-std-p ((slotd effective-slot-definition) type)
46   (let ((flags (slot-value slotd 'accessor-flags)))
47     (declare (type fixnum flags))
48     (if (eq type 'all)
49         (eql +slotd-all-function-std-p+ flags)
50         (let ((mask (ecase type
51                       (reader +slotd-reader-function-std-p+)
52                       (writer +slotd-writer-function-std-p+)
53                       (boundp +slotd-boundp-function-std-p+))))
54           (declare (type fixnum mask))
55           (not (zerop (the fixnum (logand mask flags))))))))
56
57 (defmethod (setf slot-accessor-std-p) (value
58                                        (slotd effective-slot-definition)
59                                        type)
60   (let ((mask (ecase type
61                 (reader +slotd-reader-function-std-p+)
62                 (writer +slotd-writer-function-std-p+)
63                 (boundp +slotd-boundp-function-std-p+)))
64         (flags (slot-value slotd 'accessor-flags)))
65     (declare (type fixnum mask flags))
66     (setf (slot-value slotd 'accessor-flags)
67           (if value
68               (the fixnum (logior mask flags))
69               (the fixnum (logand (the fixnum (lognot mask)) flags)))))
70   value)
71
72 (defmethod initialize-internal-slot-functions ((slotd
73                                                 effective-slot-definition))
74   (let* ((name (slot-value slotd 'name))
75          (class (slot-value slotd '%class)))
76     (dolist (type '(reader writer boundp))
77       (let* ((gf-name (ecase type
78                               (reader 'slot-value-using-class)
79                               (writer '(setf slot-value-using-class))
80                               (boundp 'slot-boundp-using-class)))
81              (gf (gdefinition gf-name)))
82         (compute-slot-accessor-info slotd type gf)))))
83
84 ;;; CMUCL (Gerd PCL 2003-04-25) comment:
85 ;;;
86 ;;; Compute an effective method for SLOT-VALUE-USING-CLASS, (SETF
87 ;;; SLOT-VALUE-USING-CLASS) or SLOT-BOUNDP-USING-CLASS for reading/
88 ;;; writing/testing effective slot SLOTD.
89 ;;;
90 ;;; TYPE is one of the symbols READER, WRITER or BOUNDP, depending on
91 ;;; GF.  Store the effective method in the effective slot definition
92 ;;; object itself; these GFs have special dispatch functions calling
93 ;;; effective methods directly retrieved from effective slot
94 ;;; definition objects, as an optimization.
95 ;;;
96 ;;; FIXME: Change the function name to COMPUTE-SVUC-SLOTD-FUNCTION,
97 ;;; or some such.
98 (defmethod compute-slot-accessor-info ((slotd effective-slot-definition)
99                                        type gf)
100   (let* ((name (slot-value slotd 'name))
101          (class (slot-value slotd '%class))
102          (old-slotd (find-slot-definition class name))
103          (old-std-p (and old-slotd (slot-accessor-std-p old-slotd 'all))))
104     (multiple-value-bind (function std-p)
105         (if (eq *boot-state* 'complete)
106             (get-accessor-method-function gf type class slotd)
107             (get-optimized-std-accessor-method-function class slotd type))
108       (setf (slot-accessor-std-p slotd type) std-p)
109       (setf (slot-accessor-function slotd type) function))
110     (when (and old-slotd (not (eq old-std-p (slot-accessor-std-p slotd 'all))))
111       (push (cons class name) *pv-table-cache-update-info*))))
112
113 (defmethod slot-definition-allocation ((slotd structure-slot-definition))
114   :instance)
115 \f
116 ;;;; various class accessors that are a little more complicated than can be
117 ;;;; done with automatically generated reader methods
118
119 (defmethod class-prototype :before (class)
120   (unless (class-finalized-p class)
121     (error "~@<~S is not finalized.~:@>" class)))
122
123 ;;; KLUDGE: For some reason factoring the common body into a function
124 ;;; breaks PCL bootstrapping, so just generate it with a macrolet for
125 ;;; all.
126 (macrolet ((def (class)
127              `(defmethod class-prototype ((class ,class))
128                 (with-slots (prototype) class
129                   (or prototype
130                       (setf prototype (allocate-instance class)))))))
131   (def std-class)
132   (def condition-class)
133   (def structure-class))
134
135 (defmethod class-direct-default-initargs ((class slot-class))
136   (plist-value class 'direct-default-initargs))
137
138 (defmethod class-default-initargs ((class slot-class))
139   (plist-value class 'default-initargs))
140
141 (defmethod class-slot-cells ((class std-class))
142   (plist-value class 'class-slot-cells))
143 (defmethod (setf class-slot-cells) (new-value (class std-class))
144   (setf (plist-value class 'class-slot-cells) new-value))
145 \f
146 ;;;; class accessors that are even a little bit more complicated than those
147 ;;;; above. These have a protocol for updating them, we must implement that
148 ;;;; protocol.
149
150 ;;; Maintaining the direct subclasses backpointers. The update methods are
151 ;;; here, the values are read by an automatically generated reader method.
152 (defmethod add-direct-subclass ((class class) (subclass class))
153   (with-slots (direct-subclasses) class
154     (pushnew subclass direct-subclasses)
155     subclass))
156 (defmethod remove-direct-subclass ((class class) (subclass class))
157   (with-slots (direct-subclasses) class
158     (setq direct-subclasses (remove subclass direct-subclasses))
159     subclass))
160
161 ;;; Maintaining the direct-methods and direct-generic-functions backpointers.
162 ;;;
163 ;;; There are four generic functions involved, each has one method for the
164 ;;; class case and another method for the damned EQL specializers. All of
165 ;;; these are specified methods and appear in their specified place in the
166 ;;; class graph.
167 ;;;
168 ;;;   ADD-DIRECT-METHOD
169 ;;;   REMOVE-DIRECT-METHOD
170 ;;;   SPECIALIZER-DIRECT-METHODS
171 ;;;   SPECIALIZER-DIRECT-GENERIC-FUNCTIONS
172 ;;;
173 ;;; In each case, we maintain one value which is a cons. The car is the list
174 ;;; methods. The cdr is a list of the generic functions. The cdr is always
175 ;;; computed lazily.
176 (defmethod add-direct-method ((specializer class) (method method))
177   (with-slots (direct-methods) specializer
178     (setf (car direct-methods) (adjoin method (car direct-methods))     ;PUSH
179           (cdr direct-methods) ()))
180   method)
181 (defmethod remove-direct-method ((specializer class) (method method))
182   (with-slots (direct-methods) specializer
183     (setf (car direct-methods) (remove method (car direct-methods))
184           (cdr direct-methods) ()))
185   method)
186
187 (defmethod specializer-direct-methods ((specializer class))
188   (with-slots (direct-methods) specializer
189     (car direct-methods)))
190
191 (defmethod specializer-direct-generic-functions ((specializer class))
192   (with-slots (direct-methods) specializer
193     (or (cdr direct-methods)
194         (setf (cdr direct-methods)
195               (let (collect)
196                 (dolist (m (car direct-methods))
197                   ;; the old PCL code used COLLECTING-ONCE which used
198                   ;; #'EQ to check for newness
199                   (pushnew (method-generic-function m) collect :test #'eq))
200                 (nreverse collect))))))
201 \f
202 ;;; This hash table is used to store the direct methods and direct generic
203 ;;; functions of EQL specializers. Each value in the table is the cons.
204 (defvar *eql-specializer-methods* (make-hash-table :test 'eql))
205 (defvar *class-eq-specializer-methods* (make-hash-table :test 'eq))
206
207 (defmethod specializer-method-table ((specializer eql-specializer))
208   *eql-specializer-methods*)
209
210 (defmethod specializer-method-table ((specializer class-eq-specializer))
211   *class-eq-specializer-methods*)
212
213 (defmethod add-direct-method ((specializer specializer-with-object)
214                               (method method))
215   (let* ((object (specializer-object specializer))
216          (table (specializer-method-table specializer))
217          (entry (gethash object table)))
218     (unless entry
219       (setq entry
220             (setf (gethash object table)
221                   (cons nil nil))))
222     (setf (car entry) (adjoin method (car entry))
223           (cdr entry) ())
224     method))
225
226 (defmethod remove-direct-method ((specializer specializer-with-object)
227                                  (method method))
228   (let* ((object (specializer-object specializer))
229          (entry (gethash object (specializer-method-table specializer))))
230     (when entry
231       (setf (car entry) (remove method (car entry))
232             (cdr entry) ()))
233     method))
234
235 (defmethod specializer-direct-methods ((specializer specializer-with-object))
236   (car (gethash (specializer-object specializer)
237                 (specializer-method-table specializer))))
238
239 (defmethod specializer-direct-generic-functions ((specializer
240                                                   specializer-with-object))
241   (let* ((object (specializer-object specializer))
242          (entry (gethash object (specializer-method-table specializer))))
243     (when entry
244       (or (cdr entry)
245           (setf (cdr entry)
246                 (let (collect)
247                   (dolist (m (car entry))
248                     (pushnew (method-generic-function m) collect :test #'eq))
249                   (nreverse collect)))))))
250
251 (defun map-specializers (function)
252   (map-all-classes (lambda (class)
253                      (funcall function (class-eq-specializer class))
254                      (funcall function class)))
255   (maphash (lambda (object methods)
256              (declare (ignore methods))
257              (intern-eql-specializer object))
258            *eql-specializer-methods*)
259   (maphash (lambda (object specl)
260              (declare (ignore object))
261              (funcall function specl))
262            *eql-specializer-table*)
263   nil)
264
265 (defun map-all-generic-functions (function)
266   (let ((all-generic-functions (make-hash-table :test 'eq)))
267     (map-specializers (lambda (specl)
268                         (dolist (gf (specializer-direct-generic-functions
269                                      specl))
270                           (unless (gethash gf all-generic-functions)
271                             (setf (gethash gf all-generic-functions) t)
272                             (funcall function gf))))))
273   nil)
274
275 (defmethod shared-initialize :after ((specl class-eq-specializer)
276                                      slot-names
277                                      &key)
278   (declare (ignore slot-names))
279   (setf (slot-value specl '%type) `(class-eq ,(specializer-class specl))))
280
281 (defmethod shared-initialize :after ((specl eql-specializer) slot-names &key)
282   (declare (ignore slot-names))
283   (setf (slot-value specl '%type)
284         `(eql ,(specializer-object specl)))
285   (setf (info :type :translator specl)
286         (constantly (make-member-type :members (list (specializer-object specl))))))
287
288 (defun real-load-defclass (name metaclass-name supers slots other
289                            readers writers slot-names source-location)
290   (with-single-package-locked-error (:symbol name "defining ~S as a class")
291     (%compiler-defclass name readers writers slot-names)
292     (let ((res (apply #'ensure-class name :metaclass metaclass-name
293                       :direct-superclasses supers
294                       :direct-slots slots
295                       :definition-source source-location
296                       other)))
297       res)))
298
299 (setf (gdefinition 'load-defclass) #'real-load-defclass)
300
301 (defun ensure-class (name &rest args)
302   (apply #'ensure-class-using-class
303          (let ((class (find-class name nil)))
304            (when (and class (eq name (class-name class)))
305              ;; NAME is the proper name of CLASS, so redefine it
306              class))
307          name
308          args))
309
310 (defmethod ensure-class-using-class ((class null) name &rest args &key)
311   (multiple-value-bind (meta initargs)
312       (ensure-class-values class args)
313     (set-class-type-translation (class-prototype meta) name)
314     (setf class (apply #'make-instance meta :name name initargs))
315     (without-package-locks
316       (setf (find-class name) class))
317     (set-class-type-translation class name)
318     class))
319
320 (defmethod ensure-class-using-class ((class pcl-class) name &rest args &key)
321   (multiple-value-bind (meta initargs)
322       (ensure-class-values class args)
323     (unless (eq (class-of class) meta)
324       (apply #'change-class class meta initargs))
325     (apply #'reinitialize-instance class initargs)
326     (without-package-locks
327       (setf (find-class name) class))
328     (set-class-type-translation class name)
329     class))
330
331 (defun fix-super (s)
332   (cond ((classp s) s)
333         ((not (legal-class-name-p s))
334          (error "~S is not a class or a legal class name." s))
335         (t
336          (or (find-class s nil)
337              (make-instance 'forward-referenced-class
338                             :name s)))))
339
340 (defun ensure-class-values (class initargs)
341   (let (metaclass metaclassp reversed-plist)
342     (doplist (key val) initargs
343       (cond ((eq key :metaclass)
344              (setf metaclass val
345                    metaclassp key))
346             (t
347              (when (eq key :direct-superclasses)
348                (setf val (mapcar #'fix-super val)))
349              (setf reversed-plist (list* val key reversed-plist)))))
350     (values (cond (metaclassp
351                    (if (classp metaclass)
352                        metaclass
353                        (find-class metaclass)))
354                   ((or (null class) (forward-referenced-class-p class))
355                    *the-class-standard-class*)
356                   (t
357                    (class-of class)))
358             (nreverse reversed-plist))))
359
360 \f
361 (defmethod shared-initialize :after
362     ((class std-class) slot-names &key
363      (direct-superclasses nil direct-superclasses-p)
364      (direct-slots nil direct-slots-p)
365      (direct-default-initargs nil direct-default-initargs-p))
366   (cond (direct-superclasses-p
367          (setq direct-superclasses
368                (or direct-superclasses
369                    (list (if (funcallable-standard-class-p class)
370                              *the-class-funcallable-standard-object*
371                              *the-class-standard-object*))))
372          (dolist (superclass direct-superclasses)
373            (unless (validate-superclass class superclass)
374              (error "~@<The class ~S was specified as a ~
375                      super-class of the class ~S, ~
376                      but the meta-classes ~S and ~S are incompatible.  ~
377                      Define a method for ~S to avoid this error.~@:>"
378                      superclass class (class-of superclass) (class-of class)
379                      'validate-superclass)))
380          (setf (slot-value class 'direct-superclasses) direct-superclasses))
381         (t
382          (setq direct-superclasses (slot-value class 'direct-superclasses))))
383   (setq direct-slots
384         (if direct-slots-p
385             (setf (slot-value class 'direct-slots)
386                   (mapcar (lambda (pl) (make-direct-slotd class pl))
387                           direct-slots))
388             (slot-value class 'direct-slots)))
389   (if direct-default-initargs-p
390       (setf (plist-value class 'direct-default-initargs)
391             direct-default-initargs)
392       (setq direct-default-initargs
393             (plist-value class 'direct-default-initargs)))
394   (setf (plist-value class 'class-slot-cells)
395         (let ((old-class-slot-cells (plist-value class 'class-slot-cells))
396               (collect '()))
397           (dolist (dslotd direct-slots)
398             (when (eq :class (slot-definition-allocation dslotd))
399               ;; see CLHS 4.3.6
400               (let* ((name (slot-definition-name dslotd))
401                      (old (assoc name old-class-slot-cells)))
402                 (if (or (not old)
403                         (eq t slot-names)
404                         (member name slot-names))
405                     (let* ((initfunction (slot-definition-initfunction dslotd))
406                            (value (if initfunction
407                                       (funcall initfunction)
408                                       +slot-unbound+)))
409                       (push (cons name value) collect))
410                     (push old collect)))))
411           (nreverse collect)))
412   (add-direct-subclasses class direct-superclasses)
413   (update-class class nil)
414   (do* ((slots (slot-value class 'slots) (cdr slots))
415         (dupes nil))
416        ((null slots) (when dupes
417                        (style-warn
418                         ;; FIXME: the indentation request ("~4I")
419                         ;; below appears not to do anything.  Finding
420                         ;; out why would be nice.  -- CSR, 2003-04-24
421                         "~@<slot names with the same SYMBOL-NAME but ~
422                          different SYMBOL-PACKAGE (possible package problem) ~
423                          for class ~S:~@:_~4I~<~@{~S~^~:@_~}~:>~@:>"
424                         class
425                         dupes)))
426     (let* ((slot (car slots))
427            (oslots (remove (slot-definition-name slot) (cdr slots)
428                            :test #'string/= :key #'slot-definition-name)))
429       (when oslots
430         (pushnew (cons (slot-definition-name slot)
431                        (mapcar #'slot-definition-name oslots))
432                  dupes
433                  :test #'string= :key #'car))))
434   (add-slot-accessors class direct-slots)
435   (make-preliminary-layout class))
436
437 (defmethod shared-initialize :after ((class forward-referenced-class)
438                                      slot-names &key &allow-other-keys)
439   (declare (ignore slot-names))
440   (make-preliminary-layout class))
441
442 (defvar *allow-forward-referenced-classes-in-cpl-p* nil)
443
444 ;;; Give CLASS a preliminary layout if it doesn't have one already, to
445 ;;; make it known to the type system.
446 (defun make-preliminary-layout (class)
447   (flet ((compute-preliminary-cpl (root)
448            (let ((*allow-forward-referenced-classes-in-cpl-p* t))
449              (compute-class-precedence-list root))))
450     (without-package-locks
451      (unless (class-finalized-p class)
452        (let ((name (class-name class)))
453          (setf (find-class name) class)
454          ;; KLUDGE: This is fairly horrible.  We need to make a
455          ;; full-fledged CLASSOID here, not just tell the compiler that
456          ;; some class is forthcoming, because there are legitimate
457          ;; questions one can ask of the type system, implemented in
458          ;; terms of CLASSOIDs, involving forward-referenced classes. So.
459          (when (and (eq *boot-state* 'complete)
460                     (null (find-classoid name nil)))
461            (setf (find-classoid name)
462                  (make-standard-classoid :name name)))
463          (set-class-type-translation class name)
464          (let ((layout (make-wrapper 0 class))
465                (classoid (find-classoid name)))
466            (setf (layout-classoid layout) classoid)
467            (setf (classoid-pcl-class classoid) class)
468            (setf (slot-value class 'wrapper) layout)
469            (let ((cpl (compute-preliminary-cpl class)))
470              (setf (layout-inherits layout)
471                    (order-layout-inherits
472                     (map 'simple-vector #'class-wrapper
473                          (reverse (rest cpl))))))
474            (register-layout layout :invalidate t)
475            (setf (classoid-layout classoid) layout)
476            (mapc #'make-preliminary-layout (class-direct-subclasses class))))))))
477
478
479 (defmethod shared-initialize :before ((class class) slot-names &key name)
480   (declare (ignore slot-names name))
481   ;; FIXME: Could this just be CLASS instead of `(CLASS ,CLASS)? If not,
482   ;; why not? (See also similar expression in !BOOTSTRAP-INITIALIZE-CLASS.)
483   (setf (slot-value class '%type) `(class ,class))
484   (setf (slot-value class 'class-eq-specializer)
485         (make-instance 'class-eq-specializer :class class)))
486
487 (defmethod reinitialize-instance :before ((class slot-class) &key direct-superclasses)
488   (dolist (old-super (set-difference (class-direct-superclasses class) direct-superclasses))
489     (remove-direct-subclass old-super class))
490   (remove-slot-accessors    class (class-direct-slots class)))
491
492 (defmethod reinitialize-instance :after ((class slot-class)
493                                          &rest initargs
494                                          &key)
495   (map-dependents class
496                   (lambda (dependent)
497                     (apply #'update-dependent class dependent initargs))))
498
499 (defmethod reinitialize-instance :after ((class condition-class) &key)
500   (let* ((name (class-name class))
501          (classoid (find-classoid name))
502          (slots (condition-classoid-slots classoid)))
503     ;; to balance the REMOVE-SLOT-ACCESSORS call in
504     ;; REINITIALIZE-INSTANCE :BEFORE (SLOT-CLASS).
505     (dolist (slot slots)
506       (let ((slot-name (condition-slot-name slot)))
507         (dolist (reader (condition-slot-readers slot))
508           ;; FIXME: see comment in SHARED-INITIALIZE :AFTER
509           ;; (CONDITION-CLASS T), below.  -- CSR, 2005-11-18
510           (sb-kernel::install-condition-slot-reader reader name slot-name))
511         (dolist (writer (condition-slot-writers slot))
512           (sb-kernel::install-condition-slot-writer writer name slot-name))))))
513
514 (defmethod shared-initialize :after ((class condition-class) slot-names
515                                      &key direct-slots direct-superclasses)
516   (declare (ignore slot-names))
517   (let ((classoid (find-classoid (class-name class))))
518     (with-slots (wrapper %class-precedence-list cpl-available-p
519                          prototype (direct-supers direct-superclasses))
520         class
521       (setf (slot-value class 'direct-slots)
522             (mapcar (lambda (pl) (make-direct-slotd class pl))
523                     direct-slots))
524       (setf (slot-value class 'finalized-p) t)
525       (setf (classoid-pcl-class classoid) class)
526       (setq direct-supers direct-superclasses)
527       (setq wrapper (classoid-layout classoid))
528       (setq %class-precedence-list (compute-class-precedence-list class))
529       (setq cpl-available-p t)
530       (add-direct-subclasses class direct-superclasses)
531       (setf (slot-value class 'slots) (compute-slots class))))
532   ;; Comment from Gerd's PCL, 2003-05-15:
533   ;;
534   ;; We don't ADD-SLOT-ACCESSORS here because we don't want to
535   ;; override condition accessors with generic functions.  We do this
536   ;; differently.
537   ;;
538   ;; ??? What does the above comment mean and why is it a good idea?
539   ;; CMUCL (which still as of 2005-11-18 uses this code and has this
540   ;; comment) loses slot information in its condition classes:
541   ;; DIRECT-SLOTS is always NIL.  We have the right information, so we
542   ;; remove slot accessors but never put them back.  I've added a
543   ;; REINITIALIZE-INSTANCE :AFTER (CONDITION-CLASS) method, but what
544   ;; was meant to happen?  -- CSR, 2005-11-18
545   (update-pv-table-cache-info class))
546
547 (defmethod direct-slot-definition-class ((class condition-class)
548                                          &rest initargs)
549   (declare (ignore initargs))
550   (find-class 'condition-direct-slot-definition))
551
552 (defmethod effective-slot-definition-class ((class condition-class)
553                                             &rest initargs)
554   (declare (ignore initargs))
555   (find-class 'condition-effective-slot-definition))
556
557 (defmethod finalize-inheritance ((class condition-class))
558   (aver (slot-value class 'finalized-p))
559   nil)
560
561 (defmethod compute-effective-slot-definition
562     ((class condition-class) slot-name dslotds)
563   (let ((slotd (call-next-method)))
564     (setf (slot-definition-reader-function slotd)
565           (lambda (x)
566             (handler-case (condition-reader-function x slot-name)
567               ;; FIXME: FIND-SLOT-DEFAULT throws an error if the slot
568               ;; is unbound; maybe it should be a CELL-ERROR of some
569               ;; sort?
570               (error () (values (slot-unbound class x slot-name))))))
571     (setf (slot-definition-writer-function slotd)
572           (lambda (v x)
573             (condition-writer-function x v slot-name)))
574     (setf (slot-definition-boundp-function slotd)
575           (lambda (x)
576             (multiple-value-bind (v c)
577                 (ignore-errors (condition-reader-function x slot-name))
578               (declare (ignore v))
579               (null c))))
580     slotd))
581
582 (defmethod compute-slots ((class condition-class))
583   (mapcan (lambda (superclass)
584             (mapcar (lambda (dslotd)
585                       (compute-effective-slot-definition
586                        class (slot-definition-name dslotd) (list dslotd)))
587                     (class-direct-slots superclass)))
588           (reverse (slot-value class '%class-precedence-list))))
589
590 (defmethod compute-slots :around ((class condition-class))
591   (let ((eslotds (call-next-method)))
592     (mapc #'initialize-internal-slot-functions eslotds)
593     eslotds))
594
595 (defmethod shared-initialize :after
596     ((slotd structure-slot-definition) slot-names &key
597      (allocation :instance) allocation-class)
598   (declare (ignore slot-names allocation-class))
599   (unless (eq allocation :instance)
600     (error "Structure slots must have :INSTANCE allocation.")))
601
602 (defun make-structure-class-defstruct-form (name direct-slots include)
603   (let* ((conc-name (format-symbol *package* "~S structure class " name))
604          (constructor (format-symbol *package* "~Aconstructor" conc-name))
605          (defstruct `(defstruct (,name
606                                  ,@(when include
607                                          `((:include ,(class-name include))))
608                                  (:predicate nil)
609                                  (:conc-name ,conc-name)
610                                  (:constructor ,constructor ())
611                                  (:copier nil))
612                       ,@(mapcar (lambda (slot)
613                                   `(,(slot-definition-name slot)
614                                     +slot-unbound+))
615                                 direct-slots)))
616          (reader-names (mapcar (lambda (slotd)
617                                  (list 'slot-accessor name
618                                        (slot-definition-name slotd)
619                                        'reader))
620                                direct-slots))
621          (writer-names (mapcar (lambda (slotd)
622                                  (list 'slot-accessor name
623                                        (slot-definition-name slotd)
624                                        'writer))
625                                direct-slots))
626          (readers-init
627            (mapcar (lambda (slotd reader-name)
628                      (let ((accessor
629                              (slot-definition-defstruct-accessor-symbol
630                               slotd)))
631                        `(defun ,reader-name (obj)
632                          (declare (type ,name obj))
633                          (,accessor obj))))
634                    direct-slots reader-names))
635          (writers-init
636            (mapcar (lambda (slotd writer-name)
637                      (let ((accessor
638                              (slot-definition-defstruct-accessor-symbol
639                               slotd)))
640                        `(defun ,writer-name (nv obj)
641                          (declare (type ,name obj))
642                          (setf (,accessor obj) nv))))
643                    direct-slots writer-names))
644          (defstruct-form
645              `(progn
646                ,defstruct
647                ,@readers-init ,@writers-init
648                (cons nil nil))))
649     (values defstruct-form constructor reader-names writer-names)))
650
651 (defun make-defstruct-allocation-function (class)
652   (let ((dd (get-structure-dd (class-name class))))
653     (lambda ()
654       (sb-kernel::%make-instance-with-layout
655        (sb-kernel::compiler-layout-or-lose (dd-name dd))))))
656
657 (defmethod shared-initialize :after
658     ((class structure-class) slot-names &key
659      (direct-superclasses nil direct-superclasses-p)
660      (direct-slots nil direct-slots-p)
661      direct-default-initargs)
662   (declare (ignore slot-names direct-default-initargs))
663   (if direct-superclasses-p
664       (setf (slot-value class 'direct-superclasses)
665             (or direct-superclasses
666                 (setq direct-superclasses
667                       (and (not (eq (class-name class) 'structure-object))
668                            (list *the-class-structure-object*)))))
669       (setq direct-superclasses (slot-value class 'direct-superclasses)))
670   (let* ((name (class-name class))
671          (from-defclass-p (slot-value class 'from-defclass-p))
672          (defstruct-p (or from-defclass-p (not (structure-type-p name)))))
673     (if direct-slots-p
674         (setf (slot-value class 'direct-slots)
675               (setq direct-slots
676                     (mapcar (lambda (pl)
677                               (when defstruct-p
678                                 (let* ((slot-name (getf pl :name))
679                                        (accessor
680                                         (format-symbol *package*
681                                                        "~S structure class ~A"
682                                                        name slot-name)))
683                                   (setq pl (list* :defstruct-accessor-symbol
684                                                   accessor pl))))
685                               (make-direct-slotd class pl))
686                             direct-slots)))
687         (setq direct-slots (slot-value class 'direct-slots)))
688     (if defstruct-p
689         (let ((include (car (slot-value class 'direct-superclasses))))
690           (multiple-value-bind (defstruct-form constructor reader-names writer-names)
691               (make-structure-class-defstruct-form name direct-slots include)
692             (unless (structure-type-p name) (eval defstruct-form))
693             (mapc (lambda (dslotd reader-name writer-name)
694                     (let* ((reader (gdefinition reader-name))
695                            (writer (when (fboundp writer-name)
696                                      (gdefinition writer-name))))
697                       (setf (slot-value dslotd 'internal-reader-function)
698                             reader)
699                       (setf (slot-value dslotd 'internal-writer-function)
700                             writer)))
701                   direct-slots reader-names writer-names)
702             (setf (slot-value class 'defstruct-form) defstruct-form)
703             (setf (slot-value class 'defstruct-constructor) constructor)))
704         (setf (slot-value class 'defstruct-constructor)
705               (make-defstruct-allocation-function class)))
706     (add-direct-subclasses class direct-superclasses)
707     (setf (slot-value class '%class-precedence-list)
708           (compute-class-precedence-list class))
709     (setf (slot-value class 'cpl-available-p) t)
710     (setf (slot-value class 'slots) (compute-slots class))
711     (let ((lclass (find-classoid (class-name class))))
712       (setf (classoid-pcl-class lclass) class)
713       (setf (slot-value class 'wrapper) (classoid-layout lclass)))
714     (setf (slot-value class 'finalized-p) t)
715     (update-pv-table-cache-info class)
716     (add-slot-accessors class direct-slots)))
717
718 (defmethod direct-slot-definition-class ((class structure-class) &rest initargs)
719   (declare (ignore initargs))
720   (find-class 'structure-direct-slot-definition))
721
722 (defmethod finalize-inheritance ((class structure-class))
723   nil) ; always finalized
724 \f
725 (defun add-slot-accessors (class dslotds)
726   (fix-slot-accessors class dslotds 'add))
727
728 (defun remove-slot-accessors (class dslotds)
729   (fix-slot-accessors class dslotds 'remove))
730
731 (defun fix-slot-accessors (class dslotds add/remove)
732   (flet ((fix (gfspec name r/w)
733            (let ((gf (cond ((eq add/remove 'add)
734                             (if (fboundp gfspec)
735                                 (without-package-locks
736                                   (ensure-generic-function gfspec))
737                                 (ensure-generic-function
738                                  gfspec :lambda-list (case r/w
739                                                        (r '(object))
740                                                        (w '(new-value object))))))
741                            ((generic-function-p (and (fboundp gfspec)
742                                                      (fdefinition gfspec)))
743                             (without-package-locks
744                               (ensure-generic-function gfspec))))))
745              (when gf
746                (case r/w
747                  (r (if (eq add/remove 'add)
748                         (add-reader-method class gf name)
749                         (remove-reader-method class gf)))
750                  (w (if (eq add/remove 'add)
751                         (add-writer-method class gf name)
752                         (remove-writer-method class gf))))))))
753     (dolist (dslotd dslotds)
754       (let ((slot-name (slot-definition-name dslotd)))
755         (dolist (r (slot-definition-readers dslotd))
756           (fix r slot-name 'r))
757         (dolist (w (slot-definition-writers dslotd))
758           (fix w slot-name 'w))))))
759 \f
760 (defun add-direct-subclasses (class supers)
761   (dolist (super supers)
762     (unless (memq class (class-direct-subclasses class))
763       (add-direct-subclass super class))))
764
765 (defmethod finalize-inheritance ((class std-class))
766   (update-class class t))
767
768 (defmethod finalize-inheritance ((class forward-referenced-class))
769   ;; FIXME: should we not be thinking a bit about what kinds of error
770   ;; we're throwing?  Maybe we need a clos-error type to mix in?  Or
771   ;; possibly a forward-referenced-class-error, though that's
772   ;; difficult given e.g. class precedence list calculations...
773   (error
774    "~@<FINALIZE-INHERITANCE was called on a forward referenced class:~
775        ~2I~_~S~:>"
776    class))
777
778 \f
779 (defun class-has-a-forward-referenced-superclass-p (class)
780   (or (forward-referenced-class-p class)
781       (some #'class-has-a-forward-referenced-superclass-p
782             (class-direct-superclasses class))))
783
784 ;;; This is called by :after shared-initialize whenever a class is initialized
785 ;;; or reinitialized. The class may or may not be finalized.
786 (defun update-class (class finalizep)
787   ;; Comment from Gerd Moellmann:
788   ;;
789   ;; Note that we can't simply delay the finalization when CLASS has
790   ;; no forward referenced superclasses because that causes bootstrap
791   ;; problems.
792   (without-package-locks
793    (when (and (not finalizep)
794               (not (class-finalized-p class))
795               (not (class-has-a-forward-referenced-superclass-p class)))
796      (finalize-inheritance class)
797      (dolist (sub (class-direct-subclasses class))
798        (update-class sub nil))
799      (return-from update-class))
800    (when (or finalizep (class-finalized-p class)
801              (not (class-has-a-forward-referenced-superclass-p class)))
802      (setf (find-class (class-name class)) class)
803      (update-cpl class (compute-class-precedence-list class))
804      ;; This invocation of UPDATE-SLOTS, in practice, finalizes the
805      ;; class.  The hoops above are to ensure that FINALIZE-INHERITANCE
806      ;; is called at finalization, so that MOP programmers can hook
807      ;; into the system as described in "Class Finalization Protocol"
808      ;; (section 5.5.2 of AMOP).
809      (update-slots class (compute-slots class))
810      (update-gfs-of-class class)
811      (update-initargs class (compute-default-initargs class))
812      (update-ctors 'finalize-inheritance :class class))
813    (unless finalizep
814      (dolist (sub (class-direct-subclasses class))
815        (update-class sub nil)))))
816
817 (define-condition cpl-protocol-violation (reference-condition error)
818   ((class :initarg :class :reader cpl-protocol-violation-class)
819    (cpl :initarg :cpl :reader cpl-protocol-violation-cpl))
820   (:default-initargs :references (list '(:sbcl :node "Metaobject Protocol")))
821   (:report
822    (lambda (c s)
823      (format s "~@<Protocol violation: the ~S class ~S ~
824                 ~:[has~;does not have~] the class ~S in its ~
825                 class precedence list: ~S.~@:>"
826              (class-name (class-of (cpl-protocol-violation-class c)))
827              (cpl-protocol-violation-class c)
828              (eq (class-of (cpl-protocol-violation-class c))
829                  *the-class-funcallable-standard-class*)
830              (find-class 'function)
831              (cpl-protocol-violation-cpl c)))))
832
833 (defun update-cpl (class cpl)
834   (when (eq (class-of class) *the-class-standard-class*)
835     (when (find (find-class 'function) cpl)
836       (error 'cpl-protocol-violation :class class :cpl cpl)))
837   (when (eq (class-of class) *the-class-funcallable-standard-class*)
838     (unless (find (find-class 'function) cpl)
839       (error 'cpl-protocol-violation :class class :cpl cpl)))
840   (if (class-finalized-p class)
841       (unless (and (equal (class-precedence-list class) cpl)
842                    (dolist (c cpl t)
843                      (when (position :class (class-direct-slots c)
844                                      :key #'slot-definition-allocation)
845                        (return nil))))
846         ;; comment from the old CMU CL sources:
847         ;;   Need to have the cpl setup before update-lisp-class-layout
848         ;;   is called on CMU CL.
849         (setf (slot-value class '%class-precedence-list) cpl)
850         (setf (slot-value class 'cpl-available-p) t)
851         (force-cache-flushes class))
852       (progn
853         (setf (slot-value class '%class-precedence-list) cpl)
854         (setf (slot-value class 'cpl-available-p) t)))
855   (update-class-can-precede-p cpl))
856
857 (defun update-class-can-precede-p (cpl)
858   (when cpl
859     (let ((first (car cpl)))
860       (dolist (c (cdr cpl))
861         (pushnew c (slot-value first 'can-precede-list))))
862     (update-class-can-precede-p (cdr cpl))))
863
864 (defun class-can-precede-p (class1 class2)
865   (member class2 (class-can-precede-list class1)))
866
867 (defun update-slots (class eslotds)
868   (let ((instance-slots ())
869         (class-slots    ()))
870     (dolist (eslotd eslotds)
871       (let ((alloc (slot-definition-allocation eslotd)))
872         (case alloc
873           (:instance (push eslotd instance-slots))
874           (:class (push eslotd class-slots)))))
875
876     ;; If there is a change in the shape of the instances then the
877     ;; old class is now obsolete.
878     (let* ((nlayout (mapcar #'slot-definition-name
879                             (sort instance-slots #'<
880                                   :key #'slot-definition-location)))
881            (nslots (length nlayout))
882            (nwrapper-class-slots (compute-class-slots class-slots))
883            (owrapper (when (class-finalized-p class)
884                        (class-wrapper class)))
885            (olayout (when owrapper
886                       (wrapper-instance-slots-layout owrapper)))
887            (owrapper-class-slots (and owrapper (wrapper-class-slots owrapper)))
888            (nwrapper
889             (cond ((null owrapper)
890                    (make-wrapper nslots class))
891                   ((and (equal nlayout olayout)
892                         (not
893                          (loop for o in owrapper-class-slots
894                                for n in nwrapper-class-slots
895                                do (unless (eq (car o) (car n)) (return t)))))
896                    owrapper)
897                   (t
898                    ;; This will initialize the new wrapper to have the
899                    ;; same state as the old wrapper. We will then have
900                    ;; to change that. This may seem like wasted work
901                    ;; (and it is), but the spec requires that we call
902                    ;; MAKE-INSTANCES-OBSOLETE.
903                    (make-instances-obsolete class)
904                    (class-wrapper class)))))
905
906       (with-slots (wrapper slots) class
907         (update-lisp-class-layout class nwrapper)
908         (setf slots eslotds
909               (wrapper-instance-slots-layout nwrapper) nlayout
910               (wrapper-class-slots nwrapper) nwrapper-class-slots
911               (wrapper-no-of-instance-slots nwrapper) nslots
912               wrapper nwrapper))
913       (setf (slot-value class 'finalized-p) t)
914       (unless (eq owrapper nwrapper)
915         (update-pv-table-cache-info class)
916         (maybe-update-standard-class-locations class)))))
917
918 (defun compute-class-slots (eslotds)
919   (let (collect)
920     (dolist (eslotd eslotds)
921       (push (assoc (slot-definition-name eslotd)
922                    (class-slot-cells (slot-definition-class eslotd)))
923             collect))
924     (nreverse collect)))
925
926 (defun update-gfs-of-class (class)
927   (when (and (class-finalized-p class)
928              (let ((cpl (class-precedence-list class)))
929                (or (member *the-class-slot-class* cpl)
930                    (member *the-class-standard-effective-slot-definition*
931                            cpl))))
932     (let ((gf-table (make-hash-table :test 'eq)))
933       (labels ((collect-gfs (class)
934                  (dolist (gf (specializer-direct-generic-functions class))
935                    (setf (gethash gf gf-table) t))
936                  (mapc #'collect-gfs (class-direct-superclasses class))))
937         (collect-gfs class)
938         (maphash (lambda (gf ignore)
939                    (declare (ignore ignore))
940                    (update-gf-dfun class gf))
941                  gf-table)))))
942
943 (defun update-initargs (class inits)
944   (setf (plist-value class 'default-initargs) inits))
945 \f
946 (defmethod compute-default-initargs ((class slot-class))
947   (let ((initargs (loop for c in (class-precedence-list class)
948                         append (class-direct-default-initargs c))))
949     (delete-duplicates initargs :test #'eq :key #'car :from-end t)))
950 \f
951 ;;;; protocols for constructing direct and effective slot definitions
952
953 (defmethod direct-slot-definition-class ((class std-class) &rest initargs)
954   (declare (ignore initargs))
955   (find-class 'standard-direct-slot-definition))
956
957 (defun make-direct-slotd (class initargs)
958   (apply #'make-instance
959          (apply #'direct-slot-definition-class class initargs)
960          :class class
961          initargs))
962
963 ;;; I (CSR) am not sure, but I believe that the particular order of
964 ;;; slots is quite important: it is ideal to attempt to have a
965 ;;; constant slot location for the same notional slots as much as
966 ;;; possible, so that clever discriminating functions (ONE-INDEX et
967 ;;; al.) have a chance of working.  The below at least walks through
968 ;;; the slots predictably, but maybe it would be good to compute some
969 ;;; kind of optimal slot layout by looking at locations of slots in
970 ;;; superclasses?
971 (defun std-compute-slots (class)
972   ;; As specified, we must call COMPUTE-EFFECTIVE-SLOT-DEFINITION once
973   ;; for each different slot name we find in our superclasses. Each
974   ;; call receives the class and a list of the dslotds with that name.
975   ;; The list is in most-specific-first order.
976   (let ((name-dslotds-alist ()))
977     (dolist (c (reverse (class-precedence-list class)))
978       (dolist (slot (class-direct-slots c))
979         (let* ((name (slot-definition-name slot))
980                (entry (assq name name-dslotds-alist)))
981           (if entry
982               (push slot (cdr entry))
983               (push (list name slot) name-dslotds-alist)))))
984     (mapcar (lambda (direct)
985               (compute-effective-slot-definition class
986                                                  (car direct)
987                                                  (cdr direct)))
988             (nreverse name-dslotds-alist))))
989
990 (defmethod compute-slots ((class standard-class))
991   (std-compute-slots class))
992 (defmethod compute-slots ((class funcallable-standard-class))
993   (std-compute-slots class))
994
995 (defun std-compute-slots-around (class eslotds)
996   (let ((location -1))
997     (dolist (eslotd eslotds eslotds)
998       (setf (slot-definition-location eslotd)
999             (case (slot-definition-allocation eslotd)
1000               (:instance
1001                (incf location))
1002               (:class
1003                (let* ((name (slot-definition-name eslotd))
1004                       (from-class
1005                        (or
1006                         (slot-definition-allocation-class eslotd)
1007                         ;; we get here if the user adds an extra slot
1008                         ;; himself...
1009                         (setf (slot-definition-allocation-class eslotd)
1010                               class)))
1011                       ;; which raises the question of what we should
1012                       ;; do if we find that said user has added a slot
1013                       ;; with the same name as another slot...
1014                       (cell (or (assq name (class-slot-cells from-class))
1015                                 (let ((c (cons name +slot-unbound+)))
1016                                   (push c (class-slot-cells from-class))
1017                                   c))))
1018                  (aver (consp cell))
1019                  (if (eq +slot-unbound+ (cdr cell))
1020                      ;; We may have inherited an initfunction
1021                      (let ((initfun (slot-definition-initfunction eslotd)))
1022                        (if initfun
1023                            (rplacd cell (funcall initfun))
1024                            cell))
1025                      cell)))))
1026       (unless (slot-definition-class eslotd)
1027         (setf (slot-definition-class eslotd) class))
1028       (initialize-internal-slot-functions eslotd))))
1029
1030 (defmethod compute-slots :around ((class standard-class))
1031   (let ((eslotds (call-next-method)))
1032     (std-compute-slots-around class eslotds)))
1033 (defmethod compute-slots :around ((class funcallable-standard-class))
1034   (let ((eslotds (call-next-method)))
1035     (std-compute-slots-around class eslotds)))
1036
1037 (defmethod compute-slots ((class structure-class))
1038   (mapcan (lambda (superclass)
1039             (mapcar (lambda (dslotd)
1040                       (compute-effective-slot-definition
1041                        class
1042                        (slot-definition-name dslotd)
1043                        (list dslotd)))
1044                     (class-direct-slots superclass)))
1045           (reverse (slot-value class '%class-precedence-list))))
1046
1047 (defmethod compute-slots :around ((class structure-class))
1048   (let ((eslotds (call-next-method)))
1049     (mapc #'initialize-internal-slot-functions eslotds)
1050     eslotds))
1051
1052 (defmethod compute-effective-slot-definition ((class slot-class) name dslotds)
1053   (declare (ignore name))
1054   (let* ((initargs (compute-effective-slot-definition-initargs class dslotds))
1055          (class (apply #'effective-slot-definition-class class initargs)))
1056     (apply #'make-instance class initargs)))
1057
1058 (defmethod effective-slot-definition-class ((class std-class) &rest initargs)
1059   (declare (ignore initargs))
1060   (find-class 'standard-effective-slot-definition))
1061
1062 (defmethod effective-slot-definition-class ((class structure-class) &rest initargs)
1063   (declare (ignore initargs))
1064   (find-class 'structure-effective-slot-definition))
1065
1066 (defmethod compute-effective-slot-definition-initargs
1067     ((class slot-class) direct-slotds)
1068   (let* ((name nil)
1069          (initfunction nil)
1070          (initform nil)
1071          (initargs nil)
1072          (allocation nil)
1073          (allocation-class nil)
1074          (type t)
1075          (documentation nil)
1076          (documentationp nil)
1077          (namep  nil)
1078          (initp  nil)
1079          (allocp nil))
1080
1081     (dolist (slotd direct-slotds)
1082       (when slotd
1083         (unless namep
1084           (setq name (slot-definition-name slotd)
1085                 namep t))
1086         (unless initp
1087           (when (slot-definition-initfunction slotd)
1088             (setq initform (slot-definition-initform slotd)
1089                   initfunction (slot-definition-initfunction slotd)
1090                   initp t)))
1091         (unless documentationp
1092           (when (%slot-definition-documentation slotd)
1093             (setq documentation (%slot-definition-documentation slotd)
1094                   documentationp t)))
1095         (unless allocp
1096           (setq allocation (slot-definition-allocation slotd)
1097                 allocation-class (slot-definition-class slotd)
1098                 allocp t))
1099         (setq initargs (append (slot-definition-initargs slotd) initargs))
1100         (let ((slotd-type (slot-definition-type slotd)))
1101           (setq type (cond
1102                        ((eq type t) slotd-type)
1103                        ;; This pairwise type intersection is perhaps a
1104                        ;; little inefficient and inelegant, but it's
1105                        ;; unlikely to lie on the critical path.  Shout
1106                        ;; if I'm wrong.  -- CSR, 2005-11-24
1107                        (t (type-specifier
1108                            (specifier-type `(and ,type ,slotd-type)))))))))
1109     (list :name name
1110           :initform initform
1111           :initfunction initfunction
1112           :initargs initargs
1113           :allocation allocation
1114           :allocation-class allocation-class
1115           :type type
1116           :class class
1117           :documentation documentation)))
1118
1119 (defmethod compute-effective-slot-definition-initargs :around
1120     ((class structure-class) direct-slotds)
1121   (let ((slotd (car direct-slotds)))
1122     (list* :defstruct-accessor-symbol
1123            (slot-definition-defstruct-accessor-symbol slotd)
1124            :internal-reader-function
1125            (slot-definition-internal-reader-function slotd)
1126            :internal-writer-function
1127            (slot-definition-internal-writer-function slotd)
1128            (call-next-method))))
1129 \f
1130 ;;; NOTE: For bootstrapping considerations, these can't use MAKE-INSTANCE
1131 ;;;       to make the method object. They have to use make-a-method which
1132 ;;;       is a specially bootstrapped mechanism for making standard methods.
1133 (defmethod reader-method-class ((class slot-class) direct-slot &rest initargs)
1134   (declare (ignore direct-slot initargs))
1135   (find-class 'standard-reader-method))
1136
1137 (defmethod add-reader-method ((class slot-class) generic-function slot-name)
1138   (add-method generic-function
1139               (make-a-method 'standard-reader-method
1140                              ()
1141                              (list (or (class-name class) 'object))
1142                              (list class)
1143                              (make-reader-method-function class slot-name)
1144                              "automatically generated reader method"
1145                              slot-name)))
1146
1147 (defmethod writer-method-class ((class slot-class) direct-slot &rest initargs)
1148   (declare (ignore direct-slot initargs))
1149   (find-class 'standard-writer-method))
1150
1151 (defmethod add-writer-method ((class slot-class) generic-function slot-name)
1152   (add-method generic-function
1153               (make-a-method 'standard-writer-method
1154                              ()
1155                              (list 'new-value (or (class-name class) 'object))
1156                              (list *the-class-t* class)
1157                              (make-writer-method-function class slot-name)
1158                              "automatically generated writer method"
1159                              slot-name)))
1160
1161 (defmethod add-boundp-method ((class slot-class) generic-function slot-name)
1162   (add-method generic-function
1163               (make-a-method 'standard-boundp-method
1164                              ()
1165                              (list (or (class-name class) 'object))
1166                              (list class)
1167                              (make-boundp-method-function class slot-name)
1168                              "automatically generated boundp method"
1169                              slot-name)))
1170
1171 (defmethod remove-reader-method ((class slot-class) generic-function)
1172   (let ((method (get-method generic-function () (list class) nil)))
1173     (when method (remove-method generic-function method))))
1174
1175 (defmethod remove-writer-method ((class slot-class) generic-function)
1176   (let ((method
1177           (get-method generic-function () (list *the-class-t* class) nil)))
1178     (when method (remove-method generic-function method))))
1179
1180 (defmethod remove-boundp-method ((class slot-class) generic-function)
1181   (let ((method (get-method generic-function () (list class) nil)))
1182     (when method (remove-method generic-function method))))
1183 \f
1184 ;;; MAKE-READER-METHOD-FUNCTION and MAKE-WRITE-METHOD function are NOT
1185 ;;; part of the standard protocol. They are however useful, PCL makes
1186 ;;; use of them internally and documents them for PCL users.
1187 ;;;
1188 ;;; *** This needs work to make type testing by the writer functions which
1189 ;;; *** do type testing faster. The idea would be to have one constructor
1190 ;;; *** for each possible type test.
1191 ;;;
1192 ;;; *** There is a subtle bug here which is going to have to be fixed.
1193 ;;; *** Namely, the simplistic use of the template has to be fixed. We
1194 ;;; *** have to give the OPTIMIZE-SLOT-VALUE method the user might have
1195 ;;; *** defined for this metaclass a chance to run.
1196
1197 (defmethod make-reader-method-function ((class slot-class) slot-name)
1198   (make-std-reader-method-function (class-name class) slot-name))
1199
1200 (defmethod make-writer-method-function ((class slot-class) slot-name)
1201   (make-std-writer-method-function (class-name class) slot-name))
1202
1203 (defmethod make-boundp-method-function ((class slot-class) slot-name)
1204   (make-std-boundp-method-function (class-name class) slot-name))
1205 \f
1206 (defmethod compatible-meta-class-change-p (class proto-new-class)
1207   (eq (class-of class) (class-of proto-new-class)))
1208
1209 (defmethod validate-superclass ((class class) (superclass class))
1210   (or (eq superclass *the-class-t*)
1211       (eq (class-of class) (class-of superclass))
1212       (and (eq (class-of superclass) *the-class-standard-class*)
1213            (eq (class-of class) *the-class-funcallable-standard-class*))
1214       (and (eq (class-of superclass) *the-class-funcallable-standard-class*)
1215            (eq (class-of class) *the-class-standard-class*))))
1216 \f
1217 ;;; What this does depends on which of the four possible values of
1218 ;;; LAYOUT-INVALID the PCL wrapper has; the simplest case is when it
1219 ;;; is (:FLUSH <wrapper>) or (:OBSOLETE <wrapper>), when there is
1220 ;;; nothing to do, as the new wrapper has already been created.  If
1221 ;;; LAYOUT-INVALID returns NIL, then we invalidate it (setting it to
1222 ;;; (:FLUSH <wrapper>); UPDATE-SLOTS later gets to choose whether or
1223 ;;; not to "upgrade" this to (:OBSOLETE <wrapper>).
1224 ;;;
1225 ;;; This leaves the case where LAYOUT-INVALID returns T, which happens
1226 ;;; when REGISTER-LAYOUT has invalidated a superclass of CLASS (which
1227 ;;; invalidated all the subclasses in SB-KERNEL land).  Again, here we
1228 ;;; must flush the caches and allow UPDATE-SLOTS to decide whether to
1229 ;;; obsolete the wrapper.
1230 ;;;
1231 ;;; FIXME: either here or in INVALID-WRAPPER-P looks like a good place
1232 ;;; for (AVER (NOT (EQ (LAYOUT-INVALID OWRAPPER)
1233 ;;;                    :UNINITIALIZED)))
1234 ;;;
1235 ;;; Thanks to Gerd Moellmann for the explanation.  -- CSR, 2002-10-29
1236 (defun force-cache-flushes (class)
1237   (let* ((owrapper (class-wrapper class)))
1238     ;; We only need to do something if the wrapper is still valid. If
1239     ;; the wrapper isn't valid, state will be FLUSH or OBSOLETE, and
1240     ;; both of those will already be doing what we want. In
1241     ;; particular, we must be sure we never change an OBSOLETE into a
1242     ;; FLUSH since OBSOLETE means do what FLUSH does and then some.
1243     (when (or (not (invalid-wrapper-p owrapper))
1244               ;; KLUDGE: despite the observations above, this remains
1245               ;; a violation of locality or what might be considered
1246               ;; good style.  There has to be a better way!  -- CSR,
1247               ;; 2002-10-29
1248               (eq (layout-invalid owrapper) t))
1249       (let ((nwrapper (make-wrapper (wrapper-no-of-instance-slots owrapper)
1250                                     class)))
1251         (setf (wrapper-instance-slots-layout nwrapper)
1252               (wrapper-instance-slots-layout owrapper))
1253         (setf (wrapper-class-slots nwrapper)
1254               (wrapper-class-slots owrapper))
1255         (with-pcl-lock
1256           (update-lisp-class-layout class nwrapper)
1257           (setf (slot-value class 'wrapper) nwrapper)
1258           ;; Use :OBSOLETE instead of :FLUSH if any superclass has
1259           ;; been obsoleted.
1260           (if (find-if (lambda (x)
1261                          (and (consp x) (eq :obsolete (car x))))
1262                        (layout-inherits owrapper)
1263                        :key #'layout-invalid)
1264               (invalidate-wrapper owrapper :obsolete nwrapper)
1265               (invalidate-wrapper owrapper :flush nwrapper)))))))
1266
1267 (defun flush-cache-trap (owrapper nwrapper instance)
1268   (declare (ignore owrapper))
1269   (set-wrapper instance nwrapper))
1270 \f
1271 ;;; MAKE-INSTANCES-OBSOLETE can be called by user code. It will cause
1272 ;;; the next access to the instance (as defined in 88-002R) to trap
1273 ;;; through the UPDATE-INSTANCE-FOR-REDEFINED-CLASS mechanism.
1274 (defmethod make-instances-obsolete ((class std-class))
1275   (let* ((owrapper (class-wrapper class))
1276          (nwrapper (make-wrapper (wrapper-no-of-instance-slots owrapper)
1277                                  class)))
1278       (setf (wrapper-instance-slots-layout nwrapper)
1279             (wrapper-instance-slots-layout owrapper))
1280       (setf (wrapper-class-slots nwrapper)
1281             (wrapper-class-slots owrapper))
1282       (with-pcl-lock
1283         (update-lisp-class-layout class nwrapper)
1284         (setf (slot-value class 'wrapper) nwrapper)
1285         (invalidate-wrapper owrapper :obsolete nwrapper)
1286         class)))
1287
1288 (defmethod make-instances-obsolete ((class symbol))
1289   (make-instances-obsolete (find-class class))
1290   ;; ANSI wants the class name when called with a symbol.
1291   class)
1292
1293 ;;; OBSOLETE-INSTANCE-TRAP is the internal trap that is called when we
1294 ;;; see an obsolete instance. The times when it is called are:
1295 ;;;   - when the instance is involved in method lookup
1296 ;;;   - when attempting to access a slot of an instance
1297 ;;;
1298 ;;; It is not called by class-of, wrapper-of, or any of the low-level
1299 ;;; instance access macros.
1300 ;;;
1301 ;;; Of course these times when it is called are an internal
1302 ;;; implementation detail of PCL and are not part of the documented
1303 ;;; description of when the obsolete instance update happens. The
1304 ;;; documented description is as it appears in 88-002R.
1305 ;;;
1306 ;;; This has to return the new wrapper, so it counts on all the
1307 ;;; methods on obsolete-instance-trap-internal to return the new
1308 ;;; wrapper. It also does a little internal error checking to make
1309 ;;; sure that the traps are only happening when they should, and that
1310 ;;; the trap methods are computing appropriate new wrappers.
1311
1312 ;;; OBSOLETE-INSTANCE-TRAP might be called on structure instances
1313 ;;; after a structure is redefined. In most cases,
1314 ;;; OBSOLETE-INSTANCE-TRAP will not be able to fix the old instance,
1315 ;;; so it must signal an error. The hard part of this is that the
1316 ;;; error system and debugger might cause OBSOLETE-INSTANCE-TRAP to be
1317 ;;; called again, so in that case, we have to return some reasonable
1318 ;;; wrapper, instead.
1319
1320 (defvar *in-obsolete-instance-trap* nil)
1321 (defvar *the-wrapper-of-structure-object*
1322   (class-wrapper (find-class 'structure-object)))
1323
1324 (define-condition obsolete-structure (error)
1325   ((datum :reader obsolete-structure-datum :initarg :datum))
1326   (:report
1327    (lambda (condition stream)
1328      ;; Don't try to print the structure, since it probably won't work.
1329      (format stream
1330              "~@<obsolete structure error for a structure of type ~2I~_~S~:>"
1331              (type-of (obsolete-structure-datum condition))))))
1332
1333 (defun obsolete-instance-trap (owrapper nwrapper instance)
1334   (if (not (pcl-instance-p instance))
1335       (if *in-obsolete-instance-trap*
1336           *the-wrapper-of-structure-object*
1337            (let ((*in-obsolete-instance-trap* t))
1338              (error 'obsolete-structure :datum instance)))
1339       (let* ((class (wrapper-class* nwrapper))
1340              (copy (allocate-instance class)) ;??? allocate-instance ???
1341              (olayout (wrapper-instance-slots-layout owrapper))
1342              (nlayout (wrapper-instance-slots-layout nwrapper))
1343              (oslots (get-slots instance))
1344              (nslots (get-slots copy))
1345              (oclass-slots (wrapper-class-slots owrapper))
1346              (added ())
1347              (discarded ())
1348              (plist ()))
1349
1350         ;; local  --> local     transfer value
1351         ;; local  --> shared    discard value, discard slot
1352         ;; local  -->  --       discard slot
1353         ;; shared --> local     transfer value
1354         ;; shared --> shared    -- (cf SHARED-INITIALIZE :AFTER STD-CLASS)
1355         ;; shared -->  --       discard value
1356         ;;  --    --> local     add slot
1357         ;;  --    --> shared    --
1358
1359         ;; Collect class slots from inherited wrappers. Needed for
1360         ;; shared -> local transfers of inherited slots.
1361         (let ((inherited (layout-inherits owrapper)))
1362           (loop for i from (1- (length inherited)) downto 0
1363                 for layout = (aref inherited i)
1364                 when (typep layout 'wrapper)
1365                 do (dolist (slot (wrapper-class-slots layout))
1366                      (pushnew slot oclass-slots :key #'car))))
1367
1368         ;; Go through all the old local slots.
1369         (let ((opos 0))
1370           (dolist (name olayout)
1371             (let ((npos (posq name nlayout)))
1372               (if npos
1373                   (setf (clos-slots-ref nslots npos)
1374                         (clos-slots-ref oslots opos))
1375                   (progn
1376                     (push name discarded)
1377                     (unless (eq (clos-slots-ref oslots opos) +slot-unbound+)
1378                       (setf (getf plist name) (clos-slots-ref oslots opos))))))
1379             (incf opos)))
1380
1381         ;; Go through all the old shared slots.
1382         (dolist (oclass-slot-and-val oclass-slots)
1383           (let ((name (car oclass-slot-and-val))
1384                 (val (cdr oclass-slot-and-val)))
1385             (let ((npos (posq name nlayout)))
1386               (when npos
1387                 (setf (clos-slots-ref nslots npos) val)))))
1388
1389         ;; Go through all the new local slots to compute the added slots.
1390         (dolist (nlocal nlayout)
1391           (unless (or (memq nlocal olayout)
1392                       (assq nlocal oclass-slots))
1393             (push nlocal added)))
1394
1395         (swap-wrappers-and-slots instance copy)
1396
1397         (update-instance-for-redefined-class instance
1398                                              added
1399                                              discarded
1400                                              plist)
1401         nwrapper)))
1402 \f
1403 (defun change-class-internal (instance new-class initargs)
1404   (let* ((old-class (class-of instance))
1405          (copy (allocate-instance new-class))
1406          (new-wrapper (get-wrapper copy))
1407          (old-wrapper (class-wrapper old-class))
1408          (old-layout (wrapper-instance-slots-layout old-wrapper))
1409          (new-layout (wrapper-instance-slots-layout new-wrapper))
1410          (old-slots (get-slots instance))
1411          (new-slots (get-slots copy))
1412          (old-class-slots (wrapper-class-slots old-wrapper)))
1413
1414     ;; "The values of local slots specified by both the class CTO and
1415     ;; CFROM are retained. If such a local slot was unbound, it
1416     ;; remains unbound."
1417     (let ((new-position 0))
1418       (dolist (new-slot new-layout)
1419         (let ((old-position (posq new-slot old-layout)))
1420           (when old-position
1421             (setf (clos-slots-ref new-slots new-position)
1422                   (clos-slots-ref old-slots old-position))))
1423         (incf new-position)))
1424
1425     ;; "The values of slots specified as shared in the class CFROM and
1426     ;; as local in the class CTO are retained."
1427     (dolist (slot-and-val old-class-slots)
1428       (let ((position (posq (car slot-and-val) new-layout)))
1429         (when position
1430           (setf (clos-slots-ref new-slots position) (cdr slot-and-val)))))
1431
1432     ;; Make the copy point to the old instance's storage, and make the
1433     ;; old instance point to the new storage.
1434     (swap-wrappers-and-slots instance copy)
1435
1436     (apply #'update-instance-for-different-class copy instance initargs)
1437     instance))
1438
1439 (defmethod change-class ((instance standard-object) (new-class standard-class)
1440                          &rest initargs)
1441   (let ((cpl (class-precedence-list new-class)))
1442     (dolist (class cpl)
1443       (macrolet
1444           ((frob (class-name)
1445              `(when (eq class (find-class ',class-name))
1446                (error 'metaobject-initialization-violation
1447                 :format-control "~@<Cannot ~S objects into ~S metaobjects.~@:>"
1448                 :format-arguments (list 'change-class ',class-name)
1449                 :references (list '(:amop :initialization ,class-name))))))
1450         (frob class)
1451         (frob generic-function)
1452         (frob method)
1453         (frob slot-definition))))
1454   (change-class-internal instance new-class initargs))
1455
1456 (defmethod change-class ((instance forward-referenced-class)
1457                          (new-class standard-class) &rest initargs)
1458   (let ((cpl (class-precedence-list new-class)))
1459     (dolist (class cpl
1460              (error 'metaobject-initialization-violation
1461                     :format-control
1462                     "~@<Cannot ~S ~S objects into non-~S objects.~@:>"
1463                     :format-arguments
1464                     (list 'change-class 'forward-referenced-class 'class)
1465                     :references
1466                     (list '(:amop :generic-function ensure-class-using-class)
1467                           '(:amop :initialization class))))
1468       (when (eq class (find-class 'class))
1469         (return nil))))
1470   (change-class-internal instance new-class initargs))
1471
1472 (defmethod change-class ((instance funcallable-standard-object)
1473                          (new-class funcallable-standard-class)
1474                          &rest initargs)
1475   (let ((cpl (class-precedence-list new-class)))
1476     (dolist (class cpl)
1477       (macrolet
1478           ((frob (class-name)
1479              `(when (eq class (find-class ',class-name))
1480                (error 'metaobject-initialization-violation
1481                 :format-control "~@<Cannot ~S objects into ~S metaobjects.~@:>"
1482                 :format-arguments (list 'change-class ',class-name)
1483                 :references (list '(:amop :initialization ,class-name))))))
1484         (frob class)
1485         (frob generic-function)
1486         (frob method)
1487         (frob slot-definition))))
1488   (change-class-internal instance new-class initargs))
1489
1490 (defmethod change-class ((instance standard-object)
1491                          (new-class funcallable-standard-class)
1492                          &rest initargs)
1493   (declare (ignore initargs))
1494   (error "You can't change the class of ~S to ~S~@
1495           because it isn't already an instance with metaclass ~S."
1496          instance new-class 'standard-class))
1497
1498 (defmethod change-class ((instance funcallable-standard-object)
1499                          (new-class standard-class)
1500                          &rest initargs)
1501   (declare (ignore initargs))
1502   (error "You can't change the class of ~S to ~S~@
1503           because it isn't already an instance with metaclass ~S."
1504          instance new-class 'funcallable-standard-class))
1505
1506 (defmethod change-class ((instance t) (new-class-name symbol) &rest initargs)
1507   (apply #'change-class instance (find-class new-class-name) initargs))
1508 \f
1509 ;;;; The metaclass BUILT-IN-CLASS
1510 ;;;;
1511 ;;;; This metaclass is something of a weird creature. By this point, all
1512 ;;;; instances of it which will exist have been created, and no instance
1513 ;;;; is ever created by calling MAKE-INSTANCE.
1514 ;;;;
1515 ;;;; But, there are other parts of the protocol we must follow and those
1516 ;;;; definitions appear here.
1517
1518 (macrolet ((def (name args control)
1519                `(defmethod ,name ,args
1520                  (declare (ignore initargs))
1521                  (error 'metaobject-initialization-violation
1522                   :format-control ,(format nil "~@<~A~@:>" control)
1523                   :format-arguments (list ',name)
1524                   :references (list '(:amop :initialization "Class"))))))
1525   (def initialize-instance ((class built-in-class) &rest initargs)
1526     "Cannot ~S an instance of BUILT-IN-CLASS.")
1527   (def reinitialize-instance ((class built-in-class) &rest initargs)
1528     "Cannot ~S an instance of BUILT-IN-CLASS."))
1529
1530 (macrolet ((def (name)
1531                `(defmethod ,name ((class built-in-class)) nil)))
1532   (def class-direct-slots)
1533   (def class-slots)
1534   (def class-direct-default-initargs)
1535   (def class-default-initargs))
1536
1537 (defmethod validate-superclass ((c class) (s built-in-class))
1538   (or (eq s *the-class-t*) (eq s *the-class-stream*)
1539       ;; FIXME: bad things happen if someone tries to mix in both
1540       ;; FILE-STREAM and STRING-STREAM (as they have the same
1541       ;; layout-depthoid).  Is there any way we can provide a useful
1542       ;; error message?  -- CSR, 2005-05-03
1543       (eq s *the-class-file-stream*) (eq s *the-class-string-stream*)))
1544 \f
1545 ;;; Some necessary methods for FORWARD-REFERENCED-CLASS
1546 (defmethod class-direct-slots ((class forward-referenced-class)) ())
1547 (defmethod class-direct-default-initargs ((class forward-referenced-class)) ())
1548 (macrolet ((def (method)
1549              `(defmethod ,method ((class forward-referenced-class))
1550                 (error "~@<~I~S was called on a forward referenced class:~2I~_~S~:>"
1551                        ',method class))))
1552   (def class-default-initargs)
1553   (def class-precedence-list)
1554   (def class-slots))
1555
1556 (defmethod validate-superclass ((c slot-class)
1557                                 (f forward-referenced-class))
1558   t)
1559 \f
1560 (defmethod add-dependent ((metaobject dependent-update-mixin) dependent)
1561   (pushnew dependent (plist-value metaobject 'dependents)))
1562
1563 (defmethod remove-dependent ((metaobject dependent-update-mixin) dependent)
1564   (setf (plist-value metaobject 'dependents)
1565         (delete dependent (plist-value metaobject 'dependents))))
1566
1567 (defmethod map-dependents ((metaobject dependent-update-mixin) function)
1568   (dolist (dependent (plist-value metaobject 'dependents))
1569     (funcall function dependent)))
1570