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